inode.c 128 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428
  1. /*
  2. * linux/fs/ext4/inode.c
  3. *
  4. * Copyright (C) 1992, 1993, 1994, 1995
  5. * Remy Card (card@masi.ibp.fr)
  6. * Laboratoire MASI - Institut Blaise Pascal
  7. * Universite Pierre et Marie Curie (Paris VI)
  8. *
  9. * from
  10. *
  11. * linux/fs/minix/inode.c
  12. *
  13. * Copyright (C) 1991, 1992 Linus Torvalds
  14. *
  15. * 64-bit file support on 64-bit platforms by Jakub Jelinek
  16. * (jj@sunsite.ms.mff.cuni.cz)
  17. *
  18. * Assorted race fixes, rewrite of ext4_get_block() by Al Viro, 2000
  19. */
  20. #include <linux/module.h>
  21. #include <linux/fs.h>
  22. #include <linux/time.h>
  23. #include <linux/jbd2.h>
  24. #include <linux/highuid.h>
  25. #include <linux/pagemap.h>
  26. #include <linux/quotaops.h>
  27. #include <linux/string.h>
  28. #include <linux/buffer_head.h>
  29. #include <linux/writeback.h>
  30. #include <linux/pagevec.h>
  31. #include <linux/mpage.h>
  32. #include <linux/namei.h>
  33. #include <linux/uio.h>
  34. #include <linux/bio.h>
  35. #include <linux/workqueue.h>
  36. #include <linux/kernel.h>
  37. #include <linux/printk.h>
  38. #include <linux/slab.h>
  39. #include <linux/ratelimit.h>
  40. #include "ext4_jbd2.h"
  41. #include "xattr.h"
  42. #include "acl.h"
  43. #include "ext4_extents.h"
  44. #include "truncate.h"
  45. #include <trace/events/ext4.h>
  46. #define MPAGE_DA_EXTENT_TAIL 0x01
  47. static inline int ext4_begin_ordered_truncate(struct inode *inode,
  48. loff_t new_size)
  49. {
  50. trace_ext4_begin_ordered_truncate(inode, new_size);
  51. /*
  52. * If jinode is zero, then we never opened the file for
  53. * writing, so there's no need to call
  54. * jbd2_journal_begin_ordered_truncate() since there's no
  55. * outstanding writes we need to flush.
  56. */
  57. if (!EXT4_I(inode)->jinode)
  58. return 0;
  59. return jbd2_journal_begin_ordered_truncate(EXT4_JOURNAL(inode),
  60. EXT4_I(inode)->jinode,
  61. new_size);
  62. }
  63. static void ext4_invalidatepage(struct page *page, unsigned long offset);
  64. static int noalloc_get_block_write(struct inode *inode, sector_t iblock,
  65. struct buffer_head *bh_result, int create);
  66. static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode);
  67. static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate);
  68. static int __ext4_journalled_writepage(struct page *page, unsigned int len);
  69. static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh);
  70. /*
  71. * Test whether an inode is a fast symlink.
  72. */
  73. static int ext4_inode_is_fast_symlink(struct inode *inode)
  74. {
  75. int ea_blocks = EXT4_I(inode)->i_file_acl ?
  76. (inode->i_sb->s_blocksize >> 9) : 0;
  77. return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
  78. }
  79. /*
  80. * Restart the transaction associated with *handle. This does a commit,
  81. * so before we call here everything must be consistently dirtied against
  82. * this transaction.
  83. */
  84. int ext4_truncate_restart_trans(handle_t *handle, struct inode *inode,
  85. int nblocks)
  86. {
  87. int ret;
  88. /*
  89. * Drop i_data_sem to avoid deadlock with ext4_map_blocks. At this
  90. * moment, get_block can be called only for blocks inside i_size since
  91. * page cache has been already dropped and writes are blocked by
  92. * i_mutex. So we can safely drop the i_data_sem here.
  93. */
  94. BUG_ON(EXT4_JOURNAL(inode) == NULL);
  95. jbd_debug(2, "restarting handle %p\n", handle);
  96. up_write(&EXT4_I(inode)->i_data_sem);
  97. ret = ext4_journal_restart(handle, nblocks);
  98. down_write(&EXT4_I(inode)->i_data_sem);
  99. ext4_discard_preallocations(inode);
  100. return ret;
  101. }
  102. /*
  103. * Called at the last iput() if i_nlink is zero.
  104. */
  105. void ext4_evict_inode(struct inode *inode)
  106. {
  107. handle_t *handle;
  108. int err;
  109. trace_ext4_evict_inode(inode);
  110. mutex_lock(&inode->i_mutex);
  111. ext4_flush_completed_IO(inode);
  112. mutex_unlock(&inode->i_mutex);
  113. ext4_ioend_wait(inode);
  114. if (inode->i_nlink) {
  115. /*
  116. * When journalling data dirty buffers are tracked only in the
  117. * journal. So although mm thinks everything is clean and
  118. * ready for reaping the inode might still have some pages to
  119. * write in the running transaction or waiting to be
  120. * checkpointed. Thus calling jbd2_journal_invalidatepage()
  121. * (via truncate_inode_pages()) to discard these buffers can
  122. * cause data loss. Also even if we did not discard these
  123. * buffers, we would have no way to find them after the inode
  124. * is reaped and thus user could see stale data if he tries to
  125. * read them before the transaction is checkpointed. So be
  126. * careful and force everything to disk here... We use
  127. * ei->i_datasync_tid to store the newest transaction
  128. * containing inode's data.
  129. *
  130. * Note that directories do not have this problem because they
  131. * don't use page cache.
  132. */
  133. if (ext4_should_journal_data(inode) &&
  134. (S_ISLNK(inode->i_mode) || S_ISREG(inode->i_mode))) {
  135. journal_t *journal = EXT4_SB(inode->i_sb)->s_journal;
  136. tid_t commit_tid = EXT4_I(inode)->i_datasync_tid;
  137. jbd2_log_start_commit(journal, commit_tid);
  138. jbd2_log_wait_commit(journal, commit_tid);
  139. filemap_write_and_wait(&inode->i_data);
  140. }
  141. truncate_inode_pages(&inode->i_data, 0);
  142. goto no_delete;
  143. }
  144. if (!is_bad_inode(inode))
  145. dquot_initialize(inode);
  146. if (ext4_should_order_data(inode))
  147. ext4_begin_ordered_truncate(inode, 0);
  148. truncate_inode_pages(&inode->i_data, 0);
  149. if (is_bad_inode(inode))
  150. goto no_delete;
  151. handle = ext4_journal_start(inode, ext4_blocks_for_truncate(inode)+3);
  152. if (IS_ERR(handle)) {
  153. ext4_std_error(inode->i_sb, PTR_ERR(handle));
  154. /*
  155. * If we're going to skip the normal cleanup, we still need to
  156. * make sure that the in-core orphan linked list is properly
  157. * cleaned up.
  158. */
  159. ext4_orphan_del(NULL, inode);
  160. goto no_delete;
  161. }
  162. if (IS_SYNC(inode))
  163. ext4_handle_sync(handle);
  164. inode->i_size = 0;
  165. err = ext4_mark_inode_dirty(handle, inode);
  166. if (err) {
  167. ext4_warning(inode->i_sb,
  168. "couldn't mark inode dirty (err %d)", err);
  169. goto stop_handle;
  170. }
  171. if (inode->i_blocks)
  172. ext4_truncate(inode);
  173. /*
  174. * ext4_ext_truncate() doesn't reserve any slop when it
  175. * restarts journal transactions; therefore there may not be
  176. * enough credits left in the handle to remove the inode from
  177. * the orphan list and set the dtime field.
  178. */
  179. if (!ext4_handle_has_enough_credits(handle, 3)) {
  180. err = ext4_journal_extend(handle, 3);
  181. if (err > 0)
  182. err = ext4_journal_restart(handle, 3);
  183. if (err != 0) {
  184. ext4_warning(inode->i_sb,
  185. "couldn't extend journal (err %d)", err);
  186. stop_handle:
  187. ext4_journal_stop(handle);
  188. ext4_orphan_del(NULL, inode);
  189. goto no_delete;
  190. }
  191. }
  192. /*
  193. * Kill off the orphan record which ext4_truncate created.
  194. * AKPM: I think this can be inside the above `if'.
  195. * Note that ext4_orphan_del() has to be able to cope with the
  196. * deletion of a non-existent orphan - this is because we don't
  197. * know if ext4_truncate() actually created an orphan record.
  198. * (Well, we could do this if we need to, but heck - it works)
  199. */
  200. ext4_orphan_del(handle, inode);
  201. EXT4_I(inode)->i_dtime = get_seconds();
  202. /*
  203. * One subtle ordering requirement: if anything has gone wrong
  204. * (transaction abort, IO errors, whatever), then we can still
  205. * do these next steps (the fs will already have been marked as
  206. * having errors), but we can't free the inode if the mark_dirty
  207. * fails.
  208. */
  209. if (ext4_mark_inode_dirty(handle, inode))
  210. /* If that failed, just do the required in-core inode clear. */
  211. ext4_clear_inode(inode);
  212. else
  213. ext4_free_inode(handle, inode);
  214. ext4_journal_stop(handle);
  215. return;
  216. no_delete:
  217. ext4_clear_inode(inode); /* We must guarantee clearing of inode... */
  218. }
  219. #ifdef CONFIG_QUOTA
  220. qsize_t *ext4_get_reserved_space(struct inode *inode)
  221. {
  222. return &EXT4_I(inode)->i_reserved_quota;
  223. }
  224. #endif
  225. /*
  226. * Calculate the number of metadata blocks need to reserve
  227. * to allocate a block located at @lblock
  228. */
  229. static int ext4_calc_metadata_amount(struct inode *inode, ext4_lblk_t lblock)
  230. {
  231. if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
  232. return ext4_ext_calc_metadata_amount(inode, lblock);
  233. return ext4_ind_calc_metadata_amount(inode, lblock);
  234. }
  235. /*
  236. * Called with i_data_sem down, which is important since we can call
  237. * ext4_discard_preallocations() from here.
  238. */
  239. void ext4_da_update_reserve_space(struct inode *inode,
  240. int used, int quota_claim)
  241. {
  242. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  243. struct ext4_inode_info *ei = EXT4_I(inode);
  244. spin_lock(&ei->i_block_reservation_lock);
  245. trace_ext4_da_update_reserve_space(inode, used);
  246. if (unlikely(used > ei->i_reserved_data_blocks)) {
  247. ext4_msg(inode->i_sb, KERN_NOTICE, "%s: ino %lu, used %d "
  248. "with only %d reserved data blocks\n",
  249. __func__, inode->i_ino, used,
  250. ei->i_reserved_data_blocks);
  251. WARN_ON(1);
  252. used = ei->i_reserved_data_blocks;
  253. }
  254. /* Update per-inode reservations */
  255. ei->i_reserved_data_blocks -= used;
  256. ei->i_reserved_meta_blocks -= ei->i_allocated_meta_blocks;
  257. percpu_counter_sub(&sbi->s_dirtyblocks_counter,
  258. used + ei->i_allocated_meta_blocks);
  259. ei->i_allocated_meta_blocks = 0;
  260. if (ei->i_reserved_data_blocks == 0) {
  261. /*
  262. * We can release all of the reserved metadata blocks
  263. * only when we have written all of the delayed
  264. * allocation blocks.
  265. */
  266. percpu_counter_sub(&sbi->s_dirtyblocks_counter,
  267. ei->i_reserved_meta_blocks);
  268. ei->i_reserved_meta_blocks = 0;
  269. ei->i_da_metadata_calc_len = 0;
  270. }
  271. spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
  272. /* Update quota subsystem for data blocks */
  273. if (quota_claim)
  274. dquot_claim_block(inode, used);
  275. else {
  276. /*
  277. * We did fallocate with an offset that is already delayed
  278. * allocated. So on delayed allocated writeback we should
  279. * not re-claim the quota for fallocated blocks.
  280. */
  281. dquot_release_reservation_block(inode, used);
  282. }
  283. /*
  284. * If we have done all the pending block allocations and if
  285. * there aren't any writers on the inode, we can discard the
  286. * inode's preallocations.
  287. */
  288. if ((ei->i_reserved_data_blocks == 0) &&
  289. (atomic_read(&inode->i_writecount) == 0))
  290. ext4_discard_preallocations(inode);
  291. }
  292. static int __check_block_validity(struct inode *inode, const char *func,
  293. unsigned int line,
  294. struct ext4_map_blocks *map)
  295. {
  296. if (!ext4_data_block_valid(EXT4_SB(inode->i_sb), map->m_pblk,
  297. map->m_len)) {
  298. ext4_error_inode(inode, func, line, map->m_pblk,
  299. "lblock %lu mapped to illegal pblock "
  300. "(length %d)", (unsigned long) map->m_lblk,
  301. map->m_len);
  302. return -EIO;
  303. }
  304. return 0;
  305. }
  306. #define check_block_validity(inode, map) \
  307. __check_block_validity((inode), __func__, __LINE__, (map))
  308. /*
  309. * Return the number of contiguous dirty pages in a given inode
  310. * starting at page frame idx.
  311. */
  312. static pgoff_t ext4_num_dirty_pages(struct inode *inode, pgoff_t idx,
  313. unsigned int max_pages)
  314. {
  315. struct address_space *mapping = inode->i_mapping;
  316. pgoff_t index;
  317. struct pagevec pvec;
  318. pgoff_t num = 0;
  319. int i, nr_pages, done = 0;
  320. if (max_pages == 0)
  321. return 0;
  322. pagevec_init(&pvec, 0);
  323. while (!done) {
  324. index = idx;
  325. nr_pages = pagevec_lookup_tag(&pvec, mapping, &index,
  326. PAGECACHE_TAG_DIRTY,
  327. (pgoff_t)PAGEVEC_SIZE);
  328. if (nr_pages == 0)
  329. break;
  330. for (i = 0; i < nr_pages; i++) {
  331. struct page *page = pvec.pages[i];
  332. struct buffer_head *bh, *head;
  333. lock_page(page);
  334. if (unlikely(page->mapping != mapping) ||
  335. !PageDirty(page) ||
  336. PageWriteback(page) ||
  337. page->index != idx) {
  338. done = 1;
  339. unlock_page(page);
  340. break;
  341. }
  342. if (page_has_buffers(page)) {
  343. bh = head = page_buffers(page);
  344. do {
  345. if (!buffer_delay(bh) &&
  346. !buffer_unwritten(bh))
  347. done = 1;
  348. bh = bh->b_this_page;
  349. } while (!done && (bh != head));
  350. }
  351. unlock_page(page);
  352. if (done)
  353. break;
  354. idx++;
  355. num++;
  356. if (num >= max_pages) {
  357. done = 1;
  358. break;
  359. }
  360. }
  361. pagevec_release(&pvec);
  362. }
  363. return num;
  364. }
  365. /*
  366. * The ext4_map_blocks() function tries to look up the requested blocks,
  367. * and returns if the blocks are already mapped.
  368. *
  369. * Otherwise it takes the write lock of the i_data_sem and allocate blocks
  370. * and store the allocated blocks in the result buffer head and mark it
  371. * mapped.
  372. *
  373. * If file type is extents based, it will call ext4_ext_map_blocks(),
  374. * Otherwise, call with ext4_ind_map_blocks() to handle indirect mapping
  375. * based files
  376. *
  377. * On success, it returns the number of blocks being mapped or allocate.
  378. * if create==0 and the blocks are pre-allocated and uninitialized block,
  379. * the result buffer head is unmapped. If the create ==1, it will make sure
  380. * the buffer head is mapped.
  381. *
  382. * It returns 0 if plain look up failed (blocks have not been allocated), in
  383. * that casem, buffer head is unmapped
  384. *
  385. * It returns the error in case of allocation failure.
  386. */
  387. int ext4_map_blocks(handle_t *handle, struct inode *inode,
  388. struct ext4_map_blocks *map, int flags)
  389. {
  390. int retval;
  391. map->m_flags = 0;
  392. ext_debug("ext4_map_blocks(): inode %lu, flag %d, max_blocks %u,"
  393. "logical block %lu\n", inode->i_ino, flags, map->m_len,
  394. (unsigned long) map->m_lblk);
  395. /*
  396. * Try to see if we can get the block without requesting a new
  397. * file system block.
  398. */
  399. down_read((&EXT4_I(inode)->i_data_sem));
  400. if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
  401. retval = ext4_ext_map_blocks(handle, inode, map, 0);
  402. } else {
  403. retval = ext4_ind_map_blocks(handle, inode, map, 0);
  404. }
  405. up_read((&EXT4_I(inode)->i_data_sem));
  406. if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
  407. int ret = check_block_validity(inode, map);
  408. if (ret != 0)
  409. return ret;
  410. }
  411. /* If it is only a block(s) look up */
  412. if ((flags & EXT4_GET_BLOCKS_CREATE) == 0)
  413. return retval;
  414. /*
  415. * Returns if the blocks have already allocated
  416. *
  417. * Note that if blocks have been preallocated
  418. * ext4_ext_get_block() returns th create = 0
  419. * with buffer head unmapped.
  420. */
  421. if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED)
  422. return retval;
  423. /*
  424. * When we call get_blocks without the create flag, the
  425. * BH_Unwritten flag could have gotten set if the blocks
  426. * requested were part of a uninitialized extent. We need to
  427. * clear this flag now that we are committed to convert all or
  428. * part of the uninitialized extent to be an initialized
  429. * extent. This is because we need to avoid the combination
  430. * of BH_Unwritten and BH_Mapped flags being simultaneously
  431. * set on the buffer_head.
  432. */
  433. map->m_flags &= ~EXT4_MAP_UNWRITTEN;
  434. /*
  435. * New blocks allocate and/or writing to uninitialized extent
  436. * will possibly result in updating i_data, so we take
  437. * the write lock of i_data_sem, and call get_blocks()
  438. * with create == 1 flag.
  439. */
  440. down_write((&EXT4_I(inode)->i_data_sem));
  441. /*
  442. * if the caller is from delayed allocation writeout path
  443. * we have already reserved fs blocks for allocation
  444. * let the underlying get_block() function know to
  445. * avoid double accounting
  446. */
  447. if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
  448. ext4_set_inode_state(inode, EXT4_STATE_DELALLOC_RESERVED);
  449. /*
  450. * We need to check for EXT4 here because migrate
  451. * could have changed the inode type in between
  452. */
  453. if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
  454. retval = ext4_ext_map_blocks(handle, inode, map, flags);
  455. } else {
  456. retval = ext4_ind_map_blocks(handle, inode, map, flags);
  457. if (retval > 0 && map->m_flags & EXT4_MAP_NEW) {
  458. /*
  459. * We allocated new blocks which will result in
  460. * i_data's format changing. Force the migrate
  461. * to fail by clearing migrate flags
  462. */
  463. ext4_clear_inode_state(inode, EXT4_STATE_EXT_MIGRATE);
  464. }
  465. /*
  466. * Update reserved blocks/metadata blocks after successful
  467. * block allocation which had been deferred till now. We don't
  468. * support fallocate for non extent files. So we can update
  469. * reserve space here.
  470. */
  471. if ((retval > 0) &&
  472. (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE))
  473. ext4_da_update_reserve_space(inode, retval, 1);
  474. }
  475. if (flags & EXT4_GET_BLOCKS_DELALLOC_RESERVE)
  476. ext4_clear_inode_state(inode, EXT4_STATE_DELALLOC_RESERVED);
  477. up_write((&EXT4_I(inode)->i_data_sem));
  478. if (retval > 0 && map->m_flags & EXT4_MAP_MAPPED) {
  479. int ret = check_block_validity(inode, map);
  480. if (ret != 0)
  481. return ret;
  482. }
  483. return retval;
  484. }
  485. /* Maximum number of blocks we map for direct IO at once. */
  486. #define DIO_MAX_BLOCKS 4096
  487. static int _ext4_get_block(struct inode *inode, sector_t iblock,
  488. struct buffer_head *bh, int flags)
  489. {
  490. handle_t *handle = ext4_journal_current_handle();
  491. struct ext4_map_blocks map;
  492. int ret = 0, started = 0;
  493. int dio_credits;
  494. map.m_lblk = iblock;
  495. map.m_len = bh->b_size >> inode->i_blkbits;
  496. if (flags && !handle) {
  497. /* Direct IO write... */
  498. if (map.m_len > DIO_MAX_BLOCKS)
  499. map.m_len = DIO_MAX_BLOCKS;
  500. dio_credits = ext4_chunk_trans_blocks(inode, map.m_len);
  501. handle = ext4_journal_start(inode, dio_credits);
  502. if (IS_ERR(handle)) {
  503. ret = PTR_ERR(handle);
  504. return ret;
  505. }
  506. started = 1;
  507. }
  508. ret = ext4_map_blocks(handle, inode, &map, flags);
  509. if (ret > 0) {
  510. map_bh(bh, inode->i_sb, map.m_pblk);
  511. bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
  512. bh->b_size = inode->i_sb->s_blocksize * map.m_len;
  513. ret = 0;
  514. }
  515. if (started)
  516. ext4_journal_stop(handle);
  517. return ret;
  518. }
  519. int ext4_get_block(struct inode *inode, sector_t iblock,
  520. struct buffer_head *bh, int create)
  521. {
  522. return _ext4_get_block(inode, iblock, bh,
  523. create ? EXT4_GET_BLOCKS_CREATE : 0);
  524. }
  525. /*
  526. * `handle' can be NULL if create is zero
  527. */
  528. struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
  529. ext4_lblk_t block, int create, int *errp)
  530. {
  531. struct ext4_map_blocks map;
  532. struct buffer_head *bh;
  533. int fatal = 0, err;
  534. J_ASSERT(handle != NULL || create == 0);
  535. map.m_lblk = block;
  536. map.m_len = 1;
  537. err = ext4_map_blocks(handle, inode, &map,
  538. create ? EXT4_GET_BLOCKS_CREATE : 0);
  539. if (err < 0)
  540. *errp = err;
  541. if (err <= 0)
  542. return NULL;
  543. *errp = 0;
  544. bh = sb_getblk(inode->i_sb, map.m_pblk);
  545. if (!bh) {
  546. *errp = -EIO;
  547. return NULL;
  548. }
  549. if (map.m_flags & EXT4_MAP_NEW) {
  550. J_ASSERT(create != 0);
  551. J_ASSERT(handle != NULL);
  552. /*
  553. * Now that we do not always journal data, we should
  554. * keep in mind whether this should always journal the
  555. * new buffer as metadata. For now, regular file
  556. * writes use ext4_get_block instead, so it's not a
  557. * problem.
  558. */
  559. lock_buffer(bh);
  560. BUFFER_TRACE(bh, "call get_create_access");
  561. fatal = ext4_journal_get_create_access(handle, bh);
  562. if (!fatal && !buffer_uptodate(bh)) {
  563. memset(bh->b_data, 0, inode->i_sb->s_blocksize);
  564. set_buffer_uptodate(bh);
  565. }
  566. unlock_buffer(bh);
  567. BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
  568. err = ext4_handle_dirty_metadata(handle, inode, bh);
  569. if (!fatal)
  570. fatal = err;
  571. } else {
  572. BUFFER_TRACE(bh, "not a new buffer");
  573. }
  574. if (fatal) {
  575. *errp = fatal;
  576. brelse(bh);
  577. bh = NULL;
  578. }
  579. return bh;
  580. }
  581. struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
  582. ext4_lblk_t block, int create, int *err)
  583. {
  584. struct buffer_head *bh;
  585. bh = ext4_getblk(handle, inode, block, create, err);
  586. if (!bh)
  587. return bh;
  588. if (buffer_uptodate(bh))
  589. return bh;
  590. ll_rw_block(READ_META, 1, &bh);
  591. wait_on_buffer(bh);
  592. if (buffer_uptodate(bh))
  593. return bh;
  594. put_bh(bh);
  595. *err = -EIO;
  596. return NULL;
  597. }
  598. static int walk_page_buffers(handle_t *handle,
  599. struct buffer_head *head,
  600. unsigned from,
  601. unsigned to,
  602. int *partial,
  603. int (*fn)(handle_t *handle,
  604. struct buffer_head *bh))
  605. {
  606. struct buffer_head *bh;
  607. unsigned block_start, block_end;
  608. unsigned blocksize = head->b_size;
  609. int err, ret = 0;
  610. struct buffer_head *next;
  611. for (bh = head, block_start = 0;
  612. ret == 0 && (bh != head || !block_start);
  613. block_start = block_end, bh = next) {
  614. next = bh->b_this_page;
  615. block_end = block_start + blocksize;
  616. if (block_end <= from || block_start >= to) {
  617. if (partial && !buffer_uptodate(bh))
  618. *partial = 1;
  619. continue;
  620. }
  621. err = (*fn)(handle, bh);
  622. if (!ret)
  623. ret = err;
  624. }
  625. return ret;
  626. }
  627. /*
  628. * To preserve ordering, it is essential that the hole instantiation and
  629. * the data write be encapsulated in a single transaction. We cannot
  630. * close off a transaction and start a new one between the ext4_get_block()
  631. * and the commit_write(). So doing the jbd2_journal_start at the start of
  632. * prepare_write() is the right place.
  633. *
  634. * Also, this function can nest inside ext4_writepage() ->
  635. * block_write_full_page(). In that case, we *know* that ext4_writepage()
  636. * has generated enough buffer credits to do the whole page. So we won't
  637. * block on the journal in that case, which is good, because the caller may
  638. * be PF_MEMALLOC.
  639. *
  640. * By accident, ext4 can be reentered when a transaction is open via
  641. * quota file writes. If we were to commit the transaction while thus
  642. * reentered, there can be a deadlock - we would be holding a quota
  643. * lock, and the commit would never complete if another thread had a
  644. * transaction open and was blocking on the quota lock - a ranking
  645. * violation.
  646. *
  647. * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
  648. * will _not_ run commit under these circumstances because handle->h_ref
  649. * is elevated. We'll still have enough credits for the tiny quotafile
  650. * write.
  651. */
  652. static int do_journal_get_write_access(handle_t *handle,
  653. struct buffer_head *bh)
  654. {
  655. int dirty = buffer_dirty(bh);
  656. int ret;
  657. if (!buffer_mapped(bh) || buffer_freed(bh))
  658. return 0;
  659. /*
  660. * __block_write_begin() could have dirtied some buffers. Clean
  661. * the dirty bit as jbd2_journal_get_write_access() could complain
  662. * otherwise about fs integrity issues. Setting of the dirty bit
  663. * by __block_write_begin() isn't a real problem here as we clear
  664. * the bit before releasing a page lock and thus writeback cannot
  665. * ever write the buffer.
  666. */
  667. if (dirty)
  668. clear_buffer_dirty(bh);
  669. ret = ext4_journal_get_write_access(handle, bh);
  670. if (!ret && dirty)
  671. ret = ext4_handle_dirty_metadata(handle, NULL, bh);
  672. return ret;
  673. }
  674. static int ext4_get_block_write(struct inode *inode, sector_t iblock,
  675. struct buffer_head *bh_result, int create);
  676. static int ext4_write_begin(struct file *file, struct address_space *mapping,
  677. loff_t pos, unsigned len, unsigned flags,
  678. struct page **pagep, void **fsdata)
  679. {
  680. struct inode *inode = mapping->host;
  681. int ret, needed_blocks;
  682. handle_t *handle;
  683. int retries = 0;
  684. struct page *page;
  685. pgoff_t index;
  686. unsigned from, to;
  687. trace_ext4_write_begin(inode, pos, len, flags);
  688. /*
  689. * Reserve one block more for addition to orphan list in case
  690. * we allocate blocks but write fails for some reason
  691. */
  692. needed_blocks = ext4_writepage_trans_blocks(inode) + 1;
  693. index = pos >> PAGE_CACHE_SHIFT;
  694. from = pos & (PAGE_CACHE_SIZE - 1);
  695. to = from + len;
  696. retry:
  697. handle = ext4_journal_start(inode, needed_blocks);
  698. if (IS_ERR(handle)) {
  699. ret = PTR_ERR(handle);
  700. goto out;
  701. }
  702. /* We cannot recurse into the filesystem as the transaction is already
  703. * started */
  704. flags |= AOP_FLAG_NOFS;
  705. page = grab_cache_page_write_begin(mapping, index, flags);
  706. if (!page) {
  707. ext4_journal_stop(handle);
  708. ret = -ENOMEM;
  709. goto out;
  710. }
  711. *pagep = page;
  712. if (ext4_should_dioread_nolock(inode))
  713. ret = __block_write_begin(page, pos, len, ext4_get_block_write);
  714. else
  715. ret = __block_write_begin(page, pos, len, ext4_get_block);
  716. if (!ret && ext4_should_journal_data(inode)) {
  717. ret = walk_page_buffers(handle, page_buffers(page),
  718. from, to, NULL, do_journal_get_write_access);
  719. }
  720. if (ret) {
  721. unlock_page(page);
  722. page_cache_release(page);
  723. /*
  724. * __block_write_begin may have instantiated a few blocks
  725. * outside i_size. Trim these off again. Don't need
  726. * i_size_read because we hold i_mutex.
  727. *
  728. * Add inode to orphan list in case we crash before
  729. * truncate finishes
  730. */
  731. if (pos + len > inode->i_size && ext4_can_truncate(inode))
  732. ext4_orphan_add(handle, inode);
  733. ext4_journal_stop(handle);
  734. if (pos + len > inode->i_size) {
  735. ext4_truncate_failed_write(inode);
  736. /*
  737. * If truncate failed early the inode might
  738. * still be on the orphan list; we need to
  739. * make sure the inode is removed from the
  740. * orphan list in that case.
  741. */
  742. if (inode->i_nlink)
  743. ext4_orphan_del(NULL, inode);
  744. }
  745. }
  746. if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
  747. goto retry;
  748. out:
  749. return ret;
  750. }
  751. /* For write_end() in data=journal mode */
  752. static int write_end_fn(handle_t *handle, struct buffer_head *bh)
  753. {
  754. if (!buffer_mapped(bh) || buffer_freed(bh))
  755. return 0;
  756. set_buffer_uptodate(bh);
  757. return ext4_handle_dirty_metadata(handle, NULL, bh);
  758. }
  759. static int ext4_generic_write_end(struct file *file,
  760. struct address_space *mapping,
  761. loff_t pos, unsigned len, unsigned copied,
  762. struct page *page, void *fsdata)
  763. {
  764. int i_size_changed = 0;
  765. struct inode *inode = mapping->host;
  766. handle_t *handle = ext4_journal_current_handle();
  767. copied = block_write_end(file, mapping, pos, len, copied, page, fsdata);
  768. /*
  769. * No need to use i_size_read() here, the i_size
  770. * cannot change under us because we hold i_mutex.
  771. *
  772. * But it's important to update i_size while still holding page lock:
  773. * page writeout could otherwise come in and zero beyond i_size.
  774. */
  775. if (pos + copied > inode->i_size) {
  776. i_size_write(inode, pos + copied);
  777. i_size_changed = 1;
  778. }
  779. if (pos + copied > EXT4_I(inode)->i_disksize) {
  780. /* We need to mark inode dirty even if
  781. * new_i_size is less that inode->i_size
  782. * bu greater than i_disksize.(hint delalloc)
  783. */
  784. ext4_update_i_disksize(inode, (pos + copied));
  785. i_size_changed = 1;
  786. }
  787. unlock_page(page);
  788. page_cache_release(page);
  789. /*
  790. * Don't mark the inode dirty under page lock. First, it unnecessarily
  791. * makes the holding time of page lock longer. Second, it forces lock
  792. * ordering of page lock and transaction start for journaling
  793. * filesystems.
  794. */
  795. if (i_size_changed)
  796. ext4_mark_inode_dirty(handle, inode);
  797. return copied;
  798. }
  799. /*
  800. * We need to pick up the new inode size which generic_commit_write gave us
  801. * `file' can be NULL - eg, when called from page_symlink().
  802. *
  803. * ext4 never places buffers on inode->i_mapping->private_list. metadata
  804. * buffers are managed internally.
  805. */
  806. static int ext4_ordered_write_end(struct file *file,
  807. struct address_space *mapping,
  808. loff_t pos, unsigned len, unsigned copied,
  809. struct page *page, void *fsdata)
  810. {
  811. handle_t *handle = ext4_journal_current_handle();
  812. struct inode *inode = mapping->host;
  813. int ret = 0, ret2;
  814. trace_ext4_ordered_write_end(inode, pos, len, copied);
  815. ret = ext4_jbd2_file_inode(handle, inode);
  816. if (ret == 0) {
  817. ret2 = ext4_generic_write_end(file, mapping, pos, len, copied,
  818. page, fsdata);
  819. copied = ret2;
  820. if (pos + len > inode->i_size && ext4_can_truncate(inode))
  821. /* if we have allocated more blocks and copied
  822. * less. We will have blocks allocated outside
  823. * inode->i_size. So truncate them
  824. */
  825. ext4_orphan_add(handle, inode);
  826. if (ret2 < 0)
  827. ret = ret2;
  828. }
  829. ret2 = ext4_journal_stop(handle);
  830. if (!ret)
  831. ret = ret2;
  832. if (pos + len > inode->i_size) {
  833. ext4_truncate_failed_write(inode);
  834. /*
  835. * If truncate failed early the inode might still be
  836. * on the orphan list; we need to make sure the inode
  837. * is removed from the orphan list in that case.
  838. */
  839. if (inode->i_nlink)
  840. ext4_orphan_del(NULL, inode);
  841. }
  842. return ret ? ret : copied;
  843. }
  844. static int ext4_writeback_write_end(struct file *file,
  845. struct address_space *mapping,
  846. loff_t pos, unsigned len, unsigned copied,
  847. struct page *page, void *fsdata)
  848. {
  849. handle_t *handle = ext4_journal_current_handle();
  850. struct inode *inode = mapping->host;
  851. int ret = 0, ret2;
  852. trace_ext4_writeback_write_end(inode, pos, len, copied);
  853. ret2 = ext4_generic_write_end(file, mapping, pos, len, copied,
  854. page, fsdata);
  855. copied = ret2;
  856. if (pos + len > inode->i_size && ext4_can_truncate(inode))
  857. /* if we have allocated more blocks and copied
  858. * less. We will have blocks allocated outside
  859. * inode->i_size. So truncate them
  860. */
  861. ext4_orphan_add(handle, inode);
  862. if (ret2 < 0)
  863. ret = ret2;
  864. ret2 = ext4_journal_stop(handle);
  865. if (!ret)
  866. ret = ret2;
  867. if (pos + len > inode->i_size) {
  868. ext4_truncate_failed_write(inode);
  869. /*
  870. * If truncate failed early the inode might still be
  871. * on the orphan list; we need to make sure the inode
  872. * is removed from the orphan list in that case.
  873. */
  874. if (inode->i_nlink)
  875. ext4_orphan_del(NULL, inode);
  876. }
  877. return ret ? ret : copied;
  878. }
  879. static int ext4_journalled_write_end(struct file *file,
  880. struct address_space *mapping,
  881. loff_t pos, unsigned len, unsigned copied,
  882. struct page *page, void *fsdata)
  883. {
  884. handle_t *handle = ext4_journal_current_handle();
  885. struct inode *inode = mapping->host;
  886. int ret = 0, ret2;
  887. int partial = 0;
  888. unsigned from, to;
  889. loff_t new_i_size;
  890. trace_ext4_journalled_write_end(inode, pos, len, copied);
  891. from = pos & (PAGE_CACHE_SIZE - 1);
  892. to = from + len;
  893. BUG_ON(!ext4_handle_valid(handle));
  894. if (copied < len) {
  895. if (!PageUptodate(page))
  896. copied = 0;
  897. page_zero_new_buffers(page, from+copied, to);
  898. }
  899. ret = walk_page_buffers(handle, page_buffers(page), from,
  900. to, &partial, write_end_fn);
  901. if (!partial)
  902. SetPageUptodate(page);
  903. new_i_size = pos + copied;
  904. if (new_i_size > inode->i_size)
  905. i_size_write(inode, pos+copied);
  906. ext4_set_inode_state(inode, EXT4_STATE_JDATA);
  907. EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
  908. if (new_i_size > EXT4_I(inode)->i_disksize) {
  909. ext4_update_i_disksize(inode, new_i_size);
  910. ret2 = ext4_mark_inode_dirty(handle, inode);
  911. if (!ret)
  912. ret = ret2;
  913. }
  914. unlock_page(page);
  915. page_cache_release(page);
  916. if (pos + len > inode->i_size && ext4_can_truncate(inode))
  917. /* if we have allocated more blocks and copied
  918. * less. We will have blocks allocated outside
  919. * inode->i_size. So truncate them
  920. */
  921. ext4_orphan_add(handle, inode);
  922. ret2 = ext4_journal_stop(handle);
  923. if (!ret)
  924. ret = ret2;
  925. if (pos + len > inode->i_size) {
  926. ext4_truncate_failed_write(inode);
  927. /*
  928. * If truncate failed early the inode might still be
  929. * on the orphan list; we need to make sure the inode
  930. * is removed from the orphan list in that case.
  931. */
  932. if (inode->i_nlink)
  933. ext4_orphan_del(NULL, inode);
  934. }
  935. return ret ? ret : copied;
  936. }
  937. /*
  938. * Reserve a single block located at lblock
  939. */
  940. static int ext4_da_reserve_space(struct inode *inode, ext4_lblk_t lblock)
  941. {
  942. int retries = 0;
  943. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  944. struct ext4_inode_info *ei = EXT4_I(inode);
  945. unsigned long md_needed;
  946. int ret;
  947. /*
  948. * recalculate the amount of metadata blocks to reserve
  949. * in order to allocate nrblocks
  950. * worse case is one extent per block
  951. */
  952. repeat:
  953. spin_lock(&ei->i_block_reservation_lock);
  954. md_needed = ext4_calc_metadata_amount(inode, lblock);
  955. trace_ext4_da_reserve_space(inode, md_needed);
  956. spin_unlock(&ei->i_block_reservation_lock);
  957. /*
  958. * We will charge metadata quota at writeout time; this saves
  959. * us from metadata over-estimation, though we may go over by
  960. * a small amount in the end. Here we just reserve for data.
  961. */
  962. ret = dquot_reserve_block(inode, 1);
  963. if (ret)
  964. return ret;
  965. /*
  966. * We do still charge estimated metadata to the sb though;
  967. * we cannot afford to run out of free blocks.
  968. */
  969. if (ext4_claim_free_blocks(sbi, md_needed + 1, 0)) {
  970. dquot_release_reservation_block(inode, 1);
  971. if (ext4_should_retry_alloc(inode->i_sb, &retries)) {
  972. yield();
  973. goto repeat;
  974. }
  975. return -ENOSPC;
  976. }
  977. spin_lock(&ei->i_block_reservation_lock);
  978. ei->i_reserved_data_blocks++;
  979. ei->i_reserved_meta_blocks += md_needed;
  980. spin_unlock(&ei->i_block_reservation_lock);
  981. return 0; /* success */
  982. }
  983. static void ext4_da_release_space(struct inode *inode, int to_free)
  984. {
  985. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  986. struct ext4_inode_info *ei = EXT4_I(inode);
  987. if (!to_free)
  988. return; /* Nothing to release, exit */
  989. spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
  990. trace_ext4_da_release_space(inode, to_free);
  991. if (unlikely(to_free > ei->i_reserved_data_blocks)) {
  992. /*
  993. * if there aren't enough reserved blocks, then the
  994. * counter is messed up somewhere. Since this
  995. * function is called from invalidate page, it's
  996. * harmless to return without any action.
  997. */
  998. ext4_msg(inode->i_sb, KERN_NOTICE, "ext4_da_release_space: "
  999. "ino %lu, to_free %d with only %d reserved "
  1000. "data blocks\n", inode->i_ino, to_free,
  1001. ei->i_reserved_data_blocks);
  1002. WARN_ON(1);
  1003. to_free = ei->i_reserved_data_blocks;
  1004. }
  1005. ei->i_reserved_data_blocks -= to_free;
  1006. if (ei->i_reserved_data_blocks == 0) {
  1007. /*
  1008. * We can release all of the reserved metadata blocks
  1009. * only when we have written all of the delayed
  1010. * allocation blocks.
  1011. */
  1012. percpu_counter_sub(&sbi->s_dirtyblocks_counter,
  1013. ei->i_reserved_meta_blocks);
  1014. ei->i_reserved_meta_blocks = 0;
  1015. ei->i_da_metadata_calc_len = 0;
  1016. }
  1017. /* update fs dirty data blocks counter */
  1018. percpu_counter_sub(&sbi->s_dirtyblocks_counter, to_free);
  1019. spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
  1020. dquot_release_reservation_block(inode, to_free);
  1021. }
  1022. static void ext4_da_page_release_reservation(struct page *page,
  1023. unsigned long offset)
  1024. {
  1025. int to_release = 0;
  1026. struct buffer_head *head, *bh;
  1027. unsigned int curr_off = 0;
  1028. head = page_buffers(page);
  1029. bh = head;
  1030. do {
  1031. unsigned int next_off = curr_off + bh->b_size;
  1032. if ((offset <= curr_off) && (buffer_delay(bh))) {
  1033. to_release++;
  1034. clear_buffer_delay(bh);
  1035. }
  1036. curr_off = next_off;
  1037. } while ((bh = bh->b_this_page) != head);
  1038. ext4_da_release_space(page->mapping->host, to_release);
  1039. }
  1040. /*
  1041. * Delayed allocation stuff
  1042. */
  1043. /*
  1044. * mpage_da_submit_io - walks through extent of pages and try to write
  1045. * them with writepage() call back
  1046. *
  1047. * @mpd->inode: inode
  1048. * @mpd->first_page: first page of the extent
  1049. * @mpd->next_page: page after the last page of the extent
  1050. *
  1051. * By the time mpage_da_submit_io() is called we expect all blocks
  1052. * to be allocated. this may be wrong if allocation failed.
  1053. *
  1054. * As pages are already locked by write_cache_pages(), we can't use it
  1055. */
  1056. static int mpage_da_submit_io(struct mpage_da_data *mpd,
  1057. struct ext4_map_blocks *map)
  1058. {
  1059. struct pagevec pvec;
  1060. unsigned long index, end;
  1061. int ret = 0, err, nr_pages, i;
  1062. struct inode *inode = mpd->inode;
  1063. struct address_space *mapping = inode->i_mapping;
  1064. loff_t size = i_size_read(inode);
  1065. unsigned int len, block_start;
  1066. struct buffer_head *bh, *page_bufs = NULL;
  1067. int journal_data = ext4_should_journal_data(inode);
  1068. sector_t pblock = 0, cur_logical = 0;
  1069. struct ext4_io_submit io_submit;
  1070. BUG_ON(mpd->next_page <= mpd->first_page);
  1071. memset(&io_submit, 0, sizeof(io_submit));
  1072. /*
  1073. * We need to start from the first_page to the next_page - 1
  1074. * to make sure we also write the mapped dirty buffer_heads.
  1075. * If we look at mpd->b_blocknr we would only be looking
  1076. * at the currently mapped buffer_heads.
  1077. */
  1078. index = mpd->first_page;
  1079. end = mpd->next_page - 1;
  1080. pagevec_init(&pvec, 0);
  1081. while (index <= end) {
  1082. nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
  1083. if (nr_pages == 0)
  1084. break;
  1085. for (i = 0; i < nr_pages; i++) {
  1086. int commit_write = 0, skip_page = 0;
  1087. struct page *page = pvec.pages[i];
  1088. index = page->index;
  1089. if (index > end)
  1090. break;
  1091. if (index == size >> PAGE_CACHE_SHIFT)
  1092. len = size & ~PAGE_CACHE_MASK;
  1093. else
  1094. len = PAGE_CACHE_SIZE;
  1095. if (map) {
  1096. cur_logical = index << (PAGE_CACHE_SHIFT -
  1097. inode->i_blkbits);
  1098. pblock = map->m_pblk + (cur_logical -
  1099. map->m_lblk);
  1100. }
  1101. index++;
  1102. BUG_ON(!PageLocked(page));
  1103. BUG_ON(PageWriteback(page));
  1104. /*
  1105. * If the page does not have buffers (for
  1106. * whatever reason), try to create them using
  1107. * __block_write_begin. If this fails,
  1108. * skip the page and move on.
  1109. */
  1110. if (!page_has_buffers(page)) {
  1111. if (__block_write_begin(page, 0, len,
  1112. noalloc_get_block_write)) {
  1113. skip_page:
  1114. unlock_page(page);
  1115. continue;
  1116. }
  1117. commit_write = 1;
  1118. }
  1119. bh = page_bufs = page_buffers(page);
  1120. block_start = 0;
  1121. do {
  1122. if (!bh)
  1123. goto skip_page;
  1124. if (map && (cur_logical >= map->m_lblk) &&
  1125. (cur_logical <= (map->m_lblk +
  1126. (map->m_len - 1)))) {
  1127. if (buffer_delay(bh)) {
  1128. clear_buffer_delay(bh);
  1129. bh->b_blocknr = pblock;
  1130. }
  1131. if (buffer_unwritten(bh) ||
  1132. buffer_mapped(bh))
  1133. BUG_ON(bh->b_blocknr != pblock);
  1134. if (map->m_flags & EXT4_MAP_UNINIT)
  1135. set_buffer_uninit(bh);
  1136. clear_buffer_unwritten(bh);
  1137. }
  1138. /* skip page if block allocation undone */
  1139. if (buffer_delay(bh) || buffer_unwritten(bh))
  1140. skip_page = 1;
  1141. bh = bh->b_this_page;
  1142. block_start += bh->b_size;
  1143. cur_logical++;
  1144. pblock++;
  1145. } while (bh != page_bufs);
  1146. if (skip_page)
  1147. goto skip_page;
  1148. if (commit_write)
  1149. /* mark the buffer_heads as dirty & uptodate */
  1150. block_commit_write(page, 0, len);
  1151. clear_page_dirty_for_io(page);
  1152. /*
  1153. * Delalloc doesn't support data journalling,
  1154. * but eventually maybe we'll lift this
  1155. * restriction.
  1156. */
  1157. if (unlikely(journal_data && PageChecked(page)))
  1158. err = __ext4_journalled_writepage(page, len);
  1159. else if (test_opt(inode->i_sb, MBLK_IO_SUBMIT))
  1160. err = ext4_bio_write_page(&io_submit, page,
  1161. len, mpd->wbc);
  1162. else
  1163. err = block_write_full_page(page,
  1164. noalloc_get_block_write, mpd->wbc);
  1165. if (!err)
  1166. mpd->pages_written++;
  1167. /*
  1168. * In error case, we have to continue because
  1169. * remaining pages are still locked
  1170. */
  1171. if (ret == 0)
  1172. ret = err;
  1173. }
  1174. pagevec_release(&pvec);
  1175. }
  1176. ext4_io_submit(&io_submit);
  1177. return ret;
  1178. }
  1179. static void ext4_da_block_invalidatepages(struct mpage_da_data *mpd)
  1180. {
  1181. int nr_pages, i;
  1182. pgoff_t index, end;
  1183. struct pagevec pvec;
  1184. struct inode *inode = mpd->inode;
  1185. struct address_space *mapping = inode->i_mapping;
  1186. index = mpd->first_page;
  1187. end = mpd->next_page - 1;
  1188. while (index <= end) {
  1189. nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
  1190. if (nr_pages == 0)
  1191. break;
  1192. for (i = 0; i < nr_pages; i++) {
  1193. struct page *page = pvec.pages[i];
  1194. if (page->index > end)
  1195. break;
  1196. BUG_ON(!PageLocked(page));
  1197. BUG_ON(PageWriteback(page));
  1198. block_invalidatepage(page, 0);
  1199. ClearPageUptodate(page);
  1200. unlock_page(page);
  1201. }
  1202. index = pvec.pages[nr_pages - 1]->index + 1;
  1203. pagevec_release(&pvec);
  1204. }
  1205. return;
  1206. }
  1207. static void ext4_print_free_blocks(struct inode *inode)
  1208. {
  1209. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  1210. printk(KERN_CRIT "Total free blocks count %lld\n",
  1211. ext4_count_free_blocks(inode->i_sb));
  1212. printk(KERN_CRIT "Free/Dirty block details\n");
  1213. printk(KERN_CRIT "free_blocks=%lld\n",
  1214. (long long) percpu_counter_sum(&sbi->s_freeblocks_counter));
  1215. printk(KERN_CRIT "dirty_blocks=%lld\n",
  1216. (long long) percpu_counter_sum(&sbi->s_dirtyblocks_counter));
  1217. printk(KERN_CRIT "Block reservation details\n");
  1218. printk(KERN_CRIT "i_reserved_data_blocks=%u\n",
  1219. EXT4_I(inode)->i_reserved_data_blocks);
  1220. printk(KERN_CRIT "i_reserved_meta_blocks=%u\n",
  1221. EXT4_I(inode)->i_reserved_meta_blocks);
  1222. return;
  1223. }
  1224. /*
  1225. * mpage_da_map_and_submit - go through given space, map them
  1226. * if necessary, and then submit them for I/O
  1227. *
  1228. * @mpd - bh describing space
  1229. *
  1230. * The function skips space we know is already mapped to disk blocks.
  1231. *
  1232. */
  1233. static void mpage_da_map_and_submit(struct mpage_da_data *mpd)
  1234. {
  1235. int err, blks, get_blocks_flags;
  1236. struct ext4_map_blocks map, *mapp = NULL;
  1237. sector_t next = mpd->b_blocknr;
  1238. unsigned max_blocks = mpd->b_size >> mpd->inode->i_blkbits;
  1239. loff_t disksize = EXT4_I(mpd->inode)->i_disksize;
  1240. handle_t *handle = NULL;
  1241. /*
  1242. * If the blocks are mapped already, or we couldn't accumulate
  1243. * any blocks, then proceed immediately to the submission stage.
  1244. */
  1245. if ((mpd->b_size == 0) ||
  1246. ((mpd->b_state & (1 << BH_Mapped)) &&
  1247. !(mpd->b_state & (1 << BH_Delay)) &&
  1248. !(mpd->b_state & (1 << BH_Unwritten))))
  1249. goto submit_io;
  1250. handle = ext4_journal_current_handle();
  1251. BUG_ON(!handle);
  1252. /*
  1253. * Call ext4_map_blocks() to allocate any delayed allocation
  1254. * blocks, or to convert an uninitialized extent to be
  1255. * initialized (in the case where we have written into
  1256. * one or more preallocated blocks).
  1257. *
  1258. * We pass in the magic EXT4_GET_BLOCKS_DELALLOC_RESERVE to
  1259. * indicate that we are on the delayed allocation path. This
  1260. * affects functions in many different parts of the allocation
  1261. * call path. This flag exists primarily because we don't
  1262. * want to change *many* call functions, so ext4_map_blocks()
  1263. * will set the EXT4_STATE_DELALLOC_RESERVED flag once the
  1264. * inode's allocation semaphore is taken.
  1265. *
  1266. * If the blocks in questions were delalloc blocks, set
  1267. * EXT4_GET_BLOCKS_DELALLOC_RESERVE so the delalloc accounting
  1268. * variables are updated after the blocks have been allocated.
  1269. */
  1270. map.m_lblk = next;
  1271. map.m_len = max_blocks;
  1272. get_blocks_flags = EXT4_GET_BLOCKS_CREATE;
  1273. if (ext4_should_dioread_nolock(mpd->inode))
  1274. get_blocks_flags |= EXT4_GET_BLOCKS_IO_CREATE_EXT;
  1275. if (mpd->b_state & (1 << BH_Delay))
  1276. get_blocks_flags |= EXT4_GET_BLOCKS_DELALLOC_RESERVE;
  1277. blks = ext4_map_blocks(handle, mpd->inode, &map, get_blocks_flags);
  1278. if (blks < 0) {
  1279. struct super_block *sb = mpd->inode->i_sb;
  1280. err = blks;
  1281. /*
  1282. * If get block returns EAGAIN or ENOSPC and there
  1283. * appears to be free blocks we will just let
  1284. * mpage_da_submit_io() unlock all of the pages.
  1285. */
  1286. if (err == -EAGAIN)
  1287. goto submit_io;
  1288. if (err == -ENOSPC &&
  1289. ext4_count_free_blocks(sb)) {
  1290. mpd->retval = err;
  1291. goto submit_io;
  1292. }
  1293. /*
  1294. * get block failure will cause us to loop in
  1295. * writepages, because a_ops->writepage won't be able
  1296. * to make progress. The page will be redirtied by
  1297. * writepage and writepages will again try to write
  1298. * the same.
  1299. */
  1300. if (!(EXT4_SB(sb)->s_mount_flags & EXT4_MF_FS_ABORTED)) {
  1301. ext4_msg(sb, KERN_CRIT,
  1302. "delayed block allocation failed for inode %lu "
  1303. "at logical offset %llu with max blocks %zd "
  1304. "with error %d", mpd->inode->i_ino,
  1305. (unsigned long long) next,
  1306. mpd->b_size >> mpd->inode->i_blkbits, err);
  1307. ext4_msg(sb, KERN_CRIT,
  1308. "This should not happen!! Data will be lost\n");
  1309. if (err == -ENOSPC)
  1310. ext4_print_free_blocks(mpd->inode);
  1311. }
  1312. /* invalidate all the pages */
  1313. ext4_da_block_invalidatepages(mpd);
  1314. /* Mark this page range as having been completed */
  1315. mpd->io_done = 1;
  1316. return;
  1317. }
  1318. BUG_ON(blks == 0);
  1319. mapp = &map;
  1320. if (map.m_flags & EXT4_MAP_NEW) {
  1321. struct block_device *bdev = mpd->inode->i_sb->s_bdev;
  1322. int i;
  1323. for (i = 0; i < map.m_len; i++)
  1324. unmap_underlying_metadata(bdev, map.m_pblk + i);
  1325. }
  1326. if (ext4_should_order_data(mpd->inode)) {
  1327. err = ext4_jbd2_file_inode(handle, mpd->inode);
  1328. if (err)
  1329. /* This only happens if the journal is aborted */
  1330. return;
  1331. }
  1332. /*
  1333. * Update on-disk size along with block allocation.
  1334. */
  1335. disksize = ((loff_t) next + blks) << mpd->inode->i_blkbits;
  1336. if (disksize > i_size_read(mpd->inode))
  1337. disksize = i_size_read(mpd->inode);
  1338. if (disksize > EXT4_I(mpd->inode)->i_disksize) {
  1339. ext4_update_i_disksize(mpd->inode, disksize);
  1340. err = ext4_mark_inode_dirty(handle, mpd->inode);
  1341. if (err)
  1342. ext4_error(mpd->inode->i_sb,
  1343. "Failed to mark inode %lu dirty",
  1344. mpd->inode->i_ino);
  1345. }
  1346. submit_io:
  1347. mpage_da_submit_io(mpd, mapp);
  1348. mpd->io_done = 1;
  1349. }
  1350. #define BH_FLAGS ((1 << BH_Uptodate) | (1 << BH_Mapped) | \
  1351. (1 << BH_Delay) | (1 << BH_Unwritten))
  1352. /*
  1353. * mpage_add_bh_to_extent - try to add one more block to extent of blocks
  1354. *
  1355. * @mpd->lbh - extent of blocks
  1356. * @logical - logical number of the block in the file
  1357. * @bh - bh of the block (used to access block's state)
  1358. *
  1359. * the function is used to collect contig. blocks in same state
  1360. */
  1361. static void mpage_add_bh_to_extent(struct mpage_da_data *mpd,
  1362. sector_t logical, size_t b_size,
  1363. unsigned long b_state)
  1364. {
  1365. sector_t next;
  1366. int nrblocks = mpd->b_size >> mpd->inode->i_blkbits;
  1367. /*
  1368. * XXX Don't go larger than mballoc is willing to allocate
  1369. * This is a stopgap solution. We eventually need to fold
  1370. * mpage_da_submit_io() into this function and then call
  1371. * ext4_map_blocks() multiple times in a loop
  1372. */
  1373. if (nrblocks >= 8*1024*1024/mpd->inode->i_sb->s_blocksize)
  1374. goto flush_it;
  1375. /* check if thereserved journal credits might overflow */
  1376. if (!(ext4_test_inode_flag(mpd->inode, EXT4_INODE_EXTENTS))) {
  1377. if (nrblocks >= EXT4_MAX_TRANS_DATA) {
  1378. /*
  1379. * With non-extent format we are limited by the journal
  1380. * credit available. Total credit needed to insert
  1381. * nrblocks contiguous blocks is dependent on the
  1382. * nrblocks. So limit nrblocks.
  1383. */
  1384. goto flush_it;
  1385. } else if ((nrblocks + (b_size >> mpd->inode->i_blkbits)) >
  1386. EXT4_MAX_TRANS_DATA) {
  1387. /*
  1388. * Adding the new buffer_head would make it cross the
  1389. * allowed limit for which we have journal credit
  1390. * reserved. So limit the new bh->b_size
  1391. */
  1392. b_size = (EXT4_MAX_TRANS_DATA - nrblocks) <<
  1393. mpd->inode->i_blkbits;
  1394. /* we will do mpage_da_submit_io in the next loop */
  1395. }
  1396. }
  1397. /*
  1398. * First block in the extent
  1399. */
  1400. if (mpd->b_size == 0) {
  1401. mpd->b_blocknr = logical;
  1402. mpd->b_size = b_size;
  1403. mpd->b_state = b_state & BH_FLAGS;
  1404. return;
  1405. }
  1406. next = mpd->b_blocknr + nrblocks;
  1407. /*
  1408. * Can we merge the block to our big extent?
  1409. */
  1410. if (logical == next && (b_state & BH_FLAGS) == mpd->b_state) {
  1411. mpd->b_size += b_size;
  1412. return;
  1413. }
  1414. flush_it:
  1415. /*
  1416. * We couldn't merge the block to our extent, so we
  1417. * need to flush current extent and start new one
  1418. */
  1419. mpage_da_map_and_submit(mpd);
  1420. return;
  1421. }
  1422. static int ext4_bh_delay_or_unwritten(handle_t *handle, struct buffer_head *bh)
  1423. {
  1424. return (buffer_delay(bh) || buffer_unwritten(bh)) && buffer_dirty(bh);
  1425. }
  1426. /*
  1427. * This is a special get_blocks_t callback which is used by
  1428. * ext4_da_write_begin(). It will either return mapped block or
  1429. * reserve space for a single block.
  1430. *
  1431. * For delayed buffer_head we have BH_Mapped, BH_New, BH_Delay set.
  1432. * We also have b_blocknr = -1 and b_bdev initialized properly
  1433. *
  1434. * For unwritten buffer_head we have BH_Mapped, BH_New, BH_Unwritten set.
  1435. * We also have b_blocknr = physicalblock mapping unwritten extent and b_bdev
  1436. * initialized properly.
  1437. */
  1438. static int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
  1439. struct buffer_head *bh, int create)
  1440. {
  1441. struct ext4_map_blocks map;
  1442. int ret = 0;
  1443. sector_t invalid_block = ~((sector_t) 0xffff);
  1444. if (invalid_block < ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es))
  1445. invalid_block = ~0;
  1446. BUG_ON(create == 0);
  1447. BUG_ON(bh->b_size != inode->i_sb->s_blocksize);
  1448. map.m_lblk = iblock;
  1449. map.m_len = 1;
  1450. /*
  1451. * first, we need to know whether the block is allocated already
  1452. * preallocated blocks are unmapped but should treated
  1453. * the same as allocated blocks.
  1454. */
  1455. ret = ext4_map_blocks(NULL, inode, &map, 0);
  1456. if (ret < 0)
  1457. return ret;
  1458. if (ret == 0) {
  1459. if (buffer_delay(bh))
  1460. return 0; /* Not sure this could or should happen */
  1461. /*
  1462. * XXX: __block_write_begin() unmaps passed block, is it OK?
  1463. */
  1464. ret = ext4_da_reserve_space(inode, iblock);
  1465. if (ret)
  1466. /* not enough space to reserve */
  1467. return ret;
  1468. map_bh(bh, inode->i_sb, invalid_block);
  1469. set_buffer_new(bh);
  1470. set_buffer_delay(bh);
  1471. return 0;
  1472. }
  1473. map_bh(bh, inode->i_sb, map.m_pblk);
  1474. bh->b_state = (bh->b_state & ~EXT4_MAP_FLAGS) | map.m_flags;
  1475. if (buffer_unwritten(bh)) {
  1476. /* A delayed write to unwritten bh should be marked
  1477. * new and mapped. Mapped ensures that we don't do
  1478. * get_block multiple times when we write to the same
  1479. * offset and new ensures that we do proper zero out
  1480. * for partial write.
  1481. */
  1482. set_buffer_new(bh);
  1483. set_buffer_mapped(bh);
  1484. }
  1485. return 0;
  1486. }
  1487. /*
  1488. * This function is used as a standard get_block_t calback function
  1489. * when there is no desire to allocate any blocks. It is used as a
  1490. * callback function for block_write_begin() and block_write_full_page().
  1491. * These functions should only try to map a single block at a time.
  1492. *
  1493. * Since this function doesn't do block allocations even if the caller
  1494. * requests it by passing in create=1, it is critically important that
  1495. * any caller checks to make sure that any buffer heads are returned
  1496. * by this function are either all already mapped or marked for
  1497. * delayed allocation before calling block_write_full_page(). Otherwise,
  1498. * b_blocknr could be left unitialized, and the page write functions will
  1499. * be taken by surprise.
  1500. */
  1501. static int noalloc_get_block_write(struct inode *inode, sector_t iblock,
  1502. struct buffer_head *bh_result, int create)
  1503. {
  1504. BUG_ON(bh_result->b_size != inode->i_sb->s_blocksize);
  1505. return _ext4_get_block(inode, iblock, bh_result, 0);
  1506. }
  1507. static int bget_one(handle_t *handle, struct buffer_head *bh)
  1508. {
  1509. get_bh(bh);
  1510. return 0;
  1511. }
  1512. static int bput_one(handle_t *handle, struct buffer_head *bh)
  1513. {
  1514. put_bh(bh);
  1515. return 0;
  1516. }
  1517. static int __ext4_journalled_writepage(struct page *page,
  1518. unsigned int len)
  1519. {
  1520. struct address_space *mapping = page->mapping;
  1521. struct inode *inode = mapping->host;
  1522. struct buffer_head *page_bufs;
  1523. handle_t *handle = NULL;
  1524. int ret = 0;
  1525. int err;
  1526. ClearPageChecked(page);
  1527. page_bufs = page_buffers(page);
  1528. BUG_ON(!page_bufs);
  1529. walk_page_buffers(handle, page_bufs, 0, len, NULL, bget_one);
  1530. /* As soon as we unlock the page, it can go away, but we have
  1531. * references to buffers so we are safe */
  1532. unlock_page(page);
  1533. handle = ext4_journal_start(inode, ext4_writepage_trans_blocks(inode));
  1534. if (IS_ERR(handle)) {
  1535. ret = PTR_ERR(handle);
  1536. goto out;
  1537. }
  1538. BUG_ON(!ext4_handle_valid(handle));
  1539. ret = walk_page_buffers(handle, page_bufs, 0, len, NULL,
  1540. do_journal_get_write_access);
  1541. err = walk_page_buffers(handle, page_bufs, 0, len, NULL,
  1542. write_end_fn);
  1543. if (ret == 0)
  1544. ret = err;
  1545. EXT4_I(inode)->i_datasync_tid = handle->h_transaction->t_tid;
  1546. err = ext4_journal_stop(handle);
  1547. if (!ret)
  1548. ret = err;
  1549. walk_page_buffers(handle, page_bufs, 0, len, NULL, bput_one);
  1550. ext4_set_inode_state(inode, EXT4_STATE_JDATA);
  1551. out:
  1552. return ret;
  1553. }
  1554. static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode);
  1555. static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate);
  1556. /*
  1557. * Note that we don't need to start a transaction unless we're journaling data
  1558. * because we should have holes filled from ext4_page_mkwrite(). We even don't
  1559. * need to file the inode to the transaction's list in ordered mode because if
  1560. * we are writing back data added by write(), the inode is already there and if
  1561. * we are writing back data modified via mmap(), no one guarantees in which
  1562. * transaction the data will hit the disk. In case we are journaling data, we
  1563. * cannot start transaction directly because transaction start ranks above page
  1564. * lock so we have to do some magic.
  1565. *
  1566. * This function can get called via...
  1567. * - ext4_da_writepages after taking page lock (have journal handle)
  1568. * - journal_submit_inode_data_buffers (no journal handle)
  1569. * - shrink_page_list via pdflush (no journal handle)
  1570. * - grab_page_cache when doing write_begin (have journal handle)
  1571. *
  1572. * We don't do any block allocation in this function. If we have page with
  1573. * multiple blocks we need to write those buffer_heads that are mapped. This
  1574. * is important for mmaped based write. So if we do with blocksize 1K
  1575. * truncate(f, 1024);
  1576. * a = mmap(f, 0, 4096);
  1577. * a[0] = 'a';
  1578. * truncate(f, 4096);
  1579. * we have in the page first buffer_head mapped via page_mkwrite call back
  1580. * but other bufer_heads would be unmapped but dirty(dirty done via the
  1581. * do_wp_page). So writepage should write the first block. If we modify
  1582. * the mmap area beyond 1024 we will again get a page_fault and the
  1583. * page_mkwrite callback will do the block allocation and mark the
  1584. * buffer_heads mapped.
  1585. *
  1586. * We redirty the page if we have any buffer_heads that is either delay or
  1587. * unwritten in the page.
  1588. *
  1589. * We can get recursively called as show below.
  1590. *
  1591. * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
  1592. * ext4_writepage()
  1593. *
  1594. * But since we don't do any block allocation we should not deadlock.
  1595. * Page also have the dirty flag cleared so we don't get recurive page_lock.
  1596. */
  1597. static int ext4_writepage(struct page *page,
  1598. struct writeback_control *wbc)
  1599. {
  1600. int ret = 0, commit_write = 0;
  1601. loff_t size;
  1602. unsigned int len;
  1603. struct buffer_head *page_bufs = NULL;
  1604. struct inode *inode = page->mapping->host;
  1605. trace_ext4_writepage(page);
  1606. size = i_size_read(inode);
  1607. if (page->index == size >> PAGE_CACHE_SHIFT)
  1608. len = size & ~PAGE_CACHE_MASK;
  1609. else
  1610. len = PAGE_CACHE_SIZE;
  1611. /*
  1612. * If the page does not have buffers (for whatever reason),
  1613. * try to create them using __block_write_begin. If this
  1614. * fails, redirty the page and move on.
  1615. */
  1616. if (!page_has_buffers(page)) {
  1617. if (__block_write_begin(page, 0, len,
  1618. noalloc_get_block_write)) {
  1619. redirty_page:
  1620. redirty_page_for_writepage(wbc, page);
  1621. unlock_page(page);
  1622. return 0;
  1623. }
  1624. commit_write = 1;
  1625. }
  1626. page_bufs = page_buffers(page);
  1627. if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
  1628. ext4_bh_delay_or_unwritten)) {
  1629. /*
  1630. * We don't want to do block allocation, so redirty
  1631. * the page and return. We may reach here when we do
  1632. * a journal commit via journal_submit_inode_data_buffers.
  1633. * We can also reach here via shrink_page_list
  1634. */
  1635. goto redirty_page;
  1636. }
  1637. if (commit_write)
  1638. /* now mark the buffer_heads as dirty and uptodate */
  1639. block_commit_write(page, 0, len);
  1640. if (PageChecked(page) && ext4_should_journal_data(inode))
  1641. /*
  1642. * It's mmapped pagecache. Add buffers and journal it. There
  1643. * doesn't seem much point in redirtying the page here.
  1644. */
  1645. return __ext4_journalled_writepage(page, len);
  1646. if (buffer_uninit(page_bufs)) {
  1647. ext4_set_bh_endio(page_bufs, inode);
  1648. ret = block_write_full_page_endio(page, noalloc_get_block_write,
  1649. wbc, ext4_end_io_buffer_write);
  1650. } else
  1651. ret = block_write_full_page(page, noalloc_get_block_write,
  1652. wbc);
  1653. return ret;
  1654. }
  1655. /*
  1656. * This is called via ext4_da_writepages() to
  1657. * calculate the total number of credits to reserve to fit
  1658. * a single extent allocation into a single transaction,
  1659. * ext4_da_writpeages() will loop calling this before
  1660. * the block allocation.
  1661. */
  1662. static int ext4_da_writepages_trans_blocks(struct inode *inode)
  1663. {
  1664. int max_blocks = EXT4_I(inode)->i_reserved_data_blocks;
  1665. /*
  1666. * With non-extent format the journal credit needed to
  1667. * insert nrblocks contiguous block is dependent on
  1668. * number of contiguous block. So we will limit
  1669. * number of contiguous block to a sane value
  1670. */
  1671. if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) &&
  1672. (max_blocks > EXT4_MAX_TRANS_DATA))
  1673. max_blocks = EXT4_MAX_TRANS_DATA;
  1674. return ext4_chunk_trans_blocks(inode, max_blocks);
  1675. }
  1676. /*
  1677. * write_cache_pages_da - walk the list of dirty pages of the given
  1678. * address space and accumulate pages that need writing, and call
  1679. * mpage_da_map_and_submit to map a single contiguous memory region
  1680. * and then write them.
  1681. */
  1682. static int write_cache_pages_da(struct address_space *mapping,
  1683. struct writeback_control *wbc,
  1684. struct mpage_da_data *mpd,
  1685. pgoff_t *done_index)
  1686. {
  1687. struct buffer_head *bh, *head;
  1688. struct inode *inode = mapping->host;
  1689. struct pagevec pvec;
  1690. unsigned int nr_pages;
  1691. sector_t logical;
  1692. pgoff_t index, end;
  1693. long nr_to_write = wbc->nr_to_write;
  1694. int i, tag, ret = 0;
  1695. memset(mpd, 0, sizeof(struct mpage_da_data));
  1696. mpd->wbc = wbc;
  1697. mpd->inode = inode;
  1698. pagevec_init(&pvec, 0);
  1699. index = wbc->range_start >> PAGE_CACHE_SHIFT;
  1700. end = wbc->range_end >> PAGE_CACHE_SHIFT;
  1701. if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
  1702. tag = PAGECACHE_TAG_TOWRITE;
  1703. else
  1704. tag = PAGECACHE_TAG_DIRTY;
  1705. *done_index = index;
  1706. while (index <= end) {
  1707. nr_pages = pagevec_lookup_tag(&pvec, mapping, &index, tag,
  1708. min(end - index, (pgoff_t)PAGEVEC_SIZE-1) + 1);
  1709. if (nr_pages == 0)
  1710. return 0;
  1711. for (i = 0; i < nr_pages; i++) {
  1712. struct page *page = pvec.pages[i];
  1713. /*
  1714. * At this point, the page may be truncated or
  1715. * invalidated (changing page->mapping to NULL), or
  1716. * even swizzled back from swapper_space to tmpfs file
  1717. * mapping. However, page->index will not change
  1718. * because we have a reference on the page.
  1719. */
  1720. if (page->index > end)
  1721. goto out;
  1722. *done_index = page->index + 1;
  1723. /*
  1724. * If we can't merge this page, and we have
  1725. * accumulated an contiguous region, write it
  1726. */
  1727. if ((mpd->next_page != page->index) &&
  1728. (mpd->next_page != mpd->first_page)) {
  1729. mpage_da_map_and_submit(mpd);
  1730. goto ret_extent_tail;
  1731. }
  1732. lock_page(page);
  1733. /*
  1734. * If the page is no longer dirty, or its
  1735. * mapping no longer corresponds to inode we
  1736. * are writing (which means it has been
  1737. * truncated or invalidated), or the page is
  1738. * already under writeback and we are not
  1739. * doing a data integrity writeback, skip the page
  1740. */
  1741. if (!PageDirty(page) ||
  1742. (PageWriteback(page) &&
  1743. (wbc->sync_mode == WB_SYNC_NONE)) ||
  1744. unlikely(page->mapping != mapping)) {
  1745. unlock_page(page);
  1746. continue;
  1747. }
  1748. wait_on_page_writeback(page);
  1749. BUG_ON(PageWriteback(page));
  1750. if (mpd->next_page != page->index)
  1751. mpd->first_page = page->index;
  1752. mpd->next_page = page->index + 1;
  1753. logical = (sector_t) page->index <<
  1754. (PAGE_CACHE_SHIFT - inode->i_blkbits);
  1755. if (!page_has_buffers(page)) {
  1756. mpage_add_bh_to_extent(mpd, logical,
  1757. PAGE_CACHE_SIZE,
  1758. (1 << BH_Dirty) | (1 << BH_Uptodate));
  1759. if (mpd->io_done)
  1760. goto ret_extent_tail;
  1761. } else {
  1762. /*
  1763. * Page with regular buffer heads,
  1764. * just add all dirty ones
  1765. */
  1766. head = page_buffers(page);
  1767. bh = head;
  1768. do {
  1769. BUG_ON(buffer_locked(bh));
  1770. /*
  1771. * We need to try to allocate
  1772. * unmapped blocks in the same page.
  1773. * Otherwise we won't make progress
  1774. * with the page in ext4_writepage
  1775. */
  1776. if (ext4_bh_delay_or_unwritten(NULL, bh)) {
  1777. mpage_add_bh_to_extent(mpd, logical,
  1778. bh->b_size,
  1779. bh->b_state);
  1780. if (mpd->io_done)
  1781. goto ret_extent_tail;
  1782. } else if (buffer_dirty(bh) && (buffer_mapped(bh))) {
  1783. /*
  1784. * mapped dirty buffer. We need
  1785. * to update the b_state
  1786. * because we look at b_state
  1787. * in mpage_da_map_blocks. We
  1788. * don't update b_size because
  1789. * if we find an unmapped
  1790. * buffer_head later we need to
  1791. * use the b_state flag of that
  1792. * buffer_head.
  1793. */
  1794. if (mpd->b_size == 0)
  1795. mpd->b_state = bh->b_state & BH_FLAGS;
  1796. }
  1797. logical++;
  1798. } while ((bh = bh->b_this_page) != head);
  1799. }
  1800. if (nr_to_write > 0) {
  1801. nr_to_write--;
  1802. if (nr_to_write == 0 &&
  1803. wbc->sync_mode == WB_SYNC_NONE)
  1804. /*
  1805. * We stop writing back only if we are
  1806. * not doing integrity sync. In case of
  1807. * integrity sync we have to keep going
  1808. * because someone may be concurrently
  1809. * dirtying pages, and we might have
  1810. * synced a lot of newly appeared dirty
  1811. * pages, but have not synced all of the
  1812. * old dirty pages.
  1813. */
  1814. goto out;
  1815. }
  1816. }
  1817. pagevec_release(&pvec);
  1818. cond_resched();
  1819. }
  1820. return 0;
  1821. ret_extent_tail:
  1822. ret = MPAGE_DA_EXTENT_TAIL;
  1823. out:
  1824. pagevec_release(&pvec);
  1825. cond_resched();
  1826. return ret;
  1827. }
  1828. static int ext4_da_writepages(struct address_space *mapping,
  1829. struct writeback_control *wbc)
  1830. {
  1831. pgoff_t index;
  1832. int range_whole = 0;
  1833. handle_t *handle = NULL;
  1834. struct mpage_da_data mpd;
  1835. struct inode *inode = mapping->host;
  1836. int pages_written = 0;
  1837. unsigned int max_pages;
  1838. int range_cyclic, cycled = 1, io_done = 0;
  1839. int needed_blocks, ret = 0;
  1840. long desired_nr_to_write, nr_to_writebump = 0;
  1841. loff_t range_start = wbc->range_start;
  1842. struct ext4_sb_info *sbi = EXT4_SB(mapping->host->i_sb);
  1843. pgoff_t done_index = 0;
  1844. pgoff_t end;
  1845. trace_ext4_da_writepages(inode, wbc);
  1846. /*
  1847. * No pages to write? This is mainly a kludge to avoid starting
  1848. * a transaction for special inodes like journal inode on last iput()
  1849. * because that could violate lock ordering on umount
  1850. */
  1851. if (!mapping->nrpages || !mapping_tagged(mapping, PAGECACHE_TAG_DIRTY))
  1852. return 0;
  1853. /*
  1854. * If the filesystem has aborted, it is read-only, so return
  1855. * right away instead of dumping stack traces later on that
  1856. * will obscure the real source of the problem. We test
  1857. * EXT4_MF_FS_ABORTED instead of sb->s_flag's MS_RDONLY because
  1858. * the latter could be true if the filesystem is mounted
  1859. * read-only, and in that case, ext4_da_writepages should
  1860. * *never* be called, so if that ever happens, we would want
  1861. * the stack trace.
  1862. */
  1863. if (unlikely(sbi->s_mount_flags & EXT4_MF_FS_ABORTED))
  1864. return -EROFS;
  1865. if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
  1866. range_whole = 1;
  1867. range_cyclic = wbc->range_cyclic;
  1868. if (wbc->range_cyclic) {
  1869. index = mapping->writeback_index;
  1870. if (index)
  1871. cycled = 0;
  1872. wbc->range_start = index << PAGE_CACHE_SHIFT;
  1873. wbc->range_end = LLONG_MAX;
  1874. wbc->range_cyclic = 0;
  1875. end = -1;
  1876. } else {
  1877. index = wbc->range_start >> PAGE_CACHE_SHIFT;
  1878. end = wbc->range_end >> PAGE_CACHE_SHIFT;
  1879. }
  1880. /*
  1881. * This works around two forms of stupidity. The first is in
  1882. * the writeback code, which caps the maximum number of pages
  1883. * written to be 1024 pages. This is wrong on multiple
  1884. * levels; different architectues have a different page size,
  1885. * which changes the maximum amount of data which gets
  1886. * written. Secondly, 4 megabytes is way too small. XFS
  1887. * forces this value to be 16 megabytes by multiplying
  1888. * nr_to_write parameter by four, and then relies on its
  1889. * allocator to allocate larger extents to make them
  1890. * contiguous. Unfortunately this brings us to the second
  1891. * stupidity, which is that ext4's mballoc code only allocates
  1892. * at most 2048 blocks. So we force contiguous writes up to
  1893. * the number of dirty blocks in the inode, or
  1894. * sbi->max_writeback_mb_bump whichever is smaller.
  1895. */
  1896. max_pages = sbi->s_max_writeback_mb_bump << (20 - PAGE_CACHE_SHIFT);
  1897. if (!range_cyclic && range_whole) {
  1898. if (wbc->nr_to_write == LONG_MAX)
  1899. desired_nr_to_write = wbc->nr_to_write;
  1900. else
  1901. desired_nr_to_write = wbc->nr_to_write * 8;
  1902. } else
  1903. desired_nr_to_write = ext4_num_dirty_pages(inode, index,
  1904. max_pages);
  1905. if (desired_nr_to_write > max_pages)
  1906. desired_nr_to_write = max_pages;
  1907. if (wbc->nr_to_write < desired_nr_to_write) {
  1908. nr_to_writebump = desired_nr_to_write - wbc->nr_to_write;
  1909. wbc->nr_to_write = desired_nr_to_write;
  1910. }
  1911. retry:
  1912. if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
  1913. tag_pages_for_writeback(mapping, index, end);
  1914. while (!ret && wbc->nr_to_write > 0) {
  1915. /*
  1916. * we insert one extent at a time. So we need
  1917. * credit needed for single extent allocation.
  1918. * journalled mode is currently not supported
  1919. * by delalloc
  1920. */
  1921. BUG_ON(ext4_should_journal_data(inode));
  1922. needed_blocks = ext4_da_writepages_trans_blocks(inode);
  1923. /* start a new transaction*/
  1924. handle = ext4_journal_start(inode, needed_blocks);
  1925. if (IS_ERR(handle)) {
  1926. ret = PTR_ERR(handle);
  1927. ext4_msg(inode->i_sb, KERN_CRIT, "%s: jbd2_start: "
  1928. "%ld pages, ino %lu; err %d", __func__,
  1929. wbc->nr_to_write, inode->i_ino, ret);
  1930. goto out_writepages;
  1931. }
  1932. /*
  1933. * Now call write_cache_pages_da() to find the next
  1934. * contiguous region of logical blocks that need
  1935. * blocks to be allocated by ext4 and submit them.
  1936. */
  1937. ret = write_cache_pages_da(mapping, wbc, &mpd, &done_index);
  1938. /*
  1939. * If we have a contiguous extent of pages and we
  1940. * haven't done the I/O yet, map the blocks and submit
  1941. * them for I/O.
  1942. */
  1943. if (!mpd.io_done && mpd.next_page != mpd.first_page) {
  1944. mpage_da_map_and_submit(&mpd);
  1945. ret = MPAGE_DA_EXTENT_TAIL;
  1946. }
  1947. trace_ext4_da_write_pages(inode, &mpd);
  1948. wbc->nr_to_write -= mpd.pages_written;
  1949. ext4_journal_stop(handle);
  1950. if ((mpd.retval == -ENOSPC) && sbi->s_journal) {
  1951. /* commit the transaction which would
  1952. * free blocks released in the transaction
  1953. * and try again
  1954. */
  1955. jbd2_journal_force_commit_nested(sbi->s_journal);
  1956. ret = 0;
  1957. } else if (ret == MPAGE_DA_EXTENT_TAIL) {
  1958. /*
  1959. * got one extent now try with
  1960. * rest of the pages
  1961. */
  1962. pages_written += mpd.pages_written;
  1963. ret = 0;
  1964. io_done = 1;
  1965. } else if (wbc->nr_to_write)
  1966. /*
  1967. * There is no more writeout needed
  1968. * or we requested for a noblocking writeout
  1969. * and we found the device congested
  1970. */
  1971. break;
  1972. }
  1973. if (!io_done && !cycled) {
  1974. cycled = 1;
  1975. index = 0;
  1976. wbc->range_start = index << PAGE_CACHE_SHIFT;
  1977. wbc->range_end = mapping->writeback_index - 1;
  1978. goto retry;
  1979. }
  1980. /* Update index */
  1981. wbc->range_cyclic = range_cyclic;
  1982. if (wbc->range_cyclic || (range_whole && wbc->nr_to_write > 0))
  1983. /*
  1984. * set the writeback_index so that range_cyclic
  1985. * mode will write it back later
  1986. */
  1987. mapping->writeback_index = done_index;
  1988. out_writepages:
  1989. wbc->nr_to_write -= nr_to_writebump;
  1990. wbc->range_start = range_start;
  1991. trace_ext4_da_writepages_result(inode, wbc, ret, pages_written);
  1992. return ret;
  1993. }
  1994. #define FALL_BACK_TO_NONDELALLOC 1
  1995. static int ext4_nonda_switch(struct super_block *sb)
  1996. {
  1997. s64 free_blocks, dirty_blocks;
  1998. struct ext4_sb_info *sbi = EXT4_SB(sb);
  1999. /*
  2000. * switch to non delalloc mode if we are running low
  2001. * on free block. The free block accounting via percpu
  2002. * counters can get slightly wrong with percpu_counter_batch getting
  2003. * accumulated on each CPU without updating global counters
  2004. * Delalloc need an accurate free block accounting. So switch
  2005. * to non delalloc when we are near to error range.
  2006. */
  2007. free_blocks = percpu_counter_read_positive(&sbi->s_freeblocks_counter);
  2008. dirty_blocks = percpu_counter_read_positive(&sbi->s_dirtyblocks_counter);
  2009. if (2 * free_blocks < 3 * dirty_blocks ||
  2010. free_blocks < (dirty_blocks + EXT4_FREEBLOCKS_WATERMARK)) {
  2011. /*
  2012. * free block count is less than 150% of dirty blocks
  2013. * or free blocks is less than watermark
  2014. */
  2015. return 1;
  2016. }
  2017. /*
  2018. * Even if we don't switch but are nearing capacity,
  2019. * start pushing delalloc when 1/2 of free blocks are dirty.
  2020. */
  2021. if (free_blocks < 2 * dirty_blocks)
  2022. writeback_inodes_sb_if_idle(sb);
  2023. return 0;
  2024. }
  2025. static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
  2026. loff_t pos, unsigned len, unsigned flags,
  2027. struct page **pagep, void **fsdata)
  2028. {
  2029. int ret, retries = 0;
  2030. struct page *page;
  2031. pgoff_t index;
  2032. struct inode *inode = mapping->host;
  2033. handle_t *handle;
  2034. index = pos >> PAGE_CACHE_SHIFT;
  2035. if (ext4_nonda_switch(inode->i_sb)) {
  2036. *fsdata = (void *)FALL_BACK_TO_NONDELALLOC;
  2037. return ext4_write_begin(file, mapping, pos,
  2038. len, flags, pagep, fsdata);
  2039. }
  2040. *fsdata = (void *)0;
  2041. trace_ext4_da_write_begin(inode, pos, len, flags);
  2042. retry:
  2043. /*
  2044. * With delayed allocation, we don't log the i_disksize update
  2045. * if there is delayed block allocation. But we still need
  2046. * to journalling the i_disksize update if writes to the end
  2047. * of file which has an already mapped buffer.
  2048. */
  2049. handle = ext4_journal_start(inode, 1);
  2050. if (IS_ERR(handle)) {
  2051. ret = PTR_ERR(handle);
  2052. goto out;
  2053. }
  2054. /* We cannot recurse into the filesystem as the transaction is already
  2055. * started */
  2056. flags |= AOP_FLAG_NOFS;
  2057. page = grab_cache_page_write_begin(mapping, index, flags);
  2058. if (!page) {
  2059. ext4_journal_stop(handle);
  2060. ret = -ENOMEM;
  2061. goto out;
  2062. }
  2063. *pagep = page;
  2064. ret = __block_write_begin(page, pos, len, ext4_da_get_block_prep);
  2065. if (ret < 0) {
  2066. unlock_page(page);
  2067. ext4_journal_stop(handle);
  2068. page_cache_release(page);
  2069. /*
  2070. * block_write_begin may have instantiated a few blocks
  2071. * outside i_size. Trim these off again. Don't need
  2072. * i_size_read because we hold i_mutex.
  2073. */
  2074. if (pos + len > inode->i_size)
  2075. ext4_truncate_failed_write(inode);
  2076. }
  2077. if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
  2078. goto retry;
  2079. out:
  2080. return ret;
  2081. }
  2082. /*
  2083. * Check if we should update i_disksize
  2084. * when write to the end of file but not require block allocation
  2085. */
  2086. static int ext4_da_should_update_i_disksize(struct page *page,
  2087. unsigned long offset)
  2088. {
  2089. struct buffer_head *bh;
  2090. struct inode *inode = page->mapping->host;
  2091. unsigned int idx;
  2092. int i;
  2093. bh = page_buffers(page);
  2094. idx = offset >> inode->i_blkbits;
  2095. for (i = 0; i < idx; i++)
  2096. bh = bh->b_this_page;
  2097. if (!buffer_mapped(bh) || (buffer_delay(bh)) || buffer_unwritten(bh))
  2098. return 0;
  2099. return 1;
  2100. }
  2101. static int ext4_da_write_end(struct file *file,
  2102. struct address_space *mapping,
  2103. loff_t pos, unsigned len, unsigned copied,
  2104. struct page *page, void *fsdata)
  2105. {
  2106. struct inode *inode = mapping->host;
  2107. int ret = 0, ret2;
  2108. handle_t *handle = ext4_journal_current_handle();
  2109. loff_t new_i_size;
  2110. unsigned long start, end;
  2111. int write_mode = (int)(unsigned long)fsdata;
  2112. if (write_mode == FALL_BACK_TO_NONDELALLOC) {
  2113. if (ext4_should_order_data(inode)) {
  2114. return ext4_ordered_write_end(file, mapping, pos,
  2115. len, copied, page, fsdata);
  2116. } else if (ext4_should_writeback_data(inode)) {
  2117. return ext4_writeback_write_end(file, mapping, pos,
  2118. len, copied, page, fsdata);
  2119. } else {
  2120. BUG();
  2121. }
  2122. }
  2123. trace_ext4_da_write_end(inode, pos, len, copied);
  2124. start = pos & (PAGE_CACHE_SIZE - 1);
  2125. end = start + copied - 1;
  2126. /*
  2127. * generic_write_end() will run mark_inode_dirty() if i_size
  2128. * changes. So let's piggyback the i_disksize mark_inode_dirty
  2129. * into that.
  2130. */
  2131. new_i_size = pos + copied;
  2132. if (new_i_size > EXT4_I(inode)->i_disksize) {
  2133. if (ext4_da_should_update_i_disksize(page, end)) {
  2134. down_write(&EXT4_I(inode)->i_data_sem);
  2135. if (new_i_size > EXT4_I(inode)->i_disksize) {
  2136. /*
  2137. * Updating i_disksize when extending file
  2138. * without needing block allocation
  2139. */
  2140. if (ext4_should_order_data(inode))
  2141. ret = ext4_jbd2_file_inode(handle,
  2142. inode);
  2143. EXT4_I(inode)->i_disksize = new_i_size;
  2144. }
  2145. up_write(&EXT4_I(inode)->i_data_sem);
  2146. /* We need to mark inode dirty even if
  2147. * new_i_size is less that inode->i_size
  2148. * bu greater than i_disksize.(hint delalloc)
  2149. */
  2150. ext4_mark_inode_dirty(handle, inode);
  2151. }
  2152. }
  2153. ret2 = generic_write_end(file, mapping, pos, len, copied,
  2154. page, fsdata);
  2155. copied = ret2;
  2156. if (ret2 < 0)
  2157. ret = ret2;
  2158. ret2 = ext4_journal_stop(handle);
  2159. if (!ret)
  2160. ret = ret2;
  2161. return ret ? ret : copied;
  2162. }
  2163. static void ext4_da_invalidatepage(struct page *page, unsigned long offset)
  2164. {
  2165. /*
  2166. * Drop reserved blocks
  2167. */
  2168. BUG_ON(!PageLocked(page));
  2169. if (!page_has_buffers(page))
  2170. goto out;
  2171. ext4_da_page_release_reservation(page, offset);
  2172. out:
  2173. ext4_invalidatepage(page, offset);
  2174. return;
  2175. }
  2176. /*
  2177. * Force all delayed allocation blocks to be allocated for a given inode.
  2178. */
  2179. int ext4_alloc_da_blocks(struct inode *inode)
  2180. {
  2181. trace_ext4_alloc_da_blocks(inode);
  2182. if (!EXT4_I(inode)->i_reserved_data_blocks &&
  2183. !EXT4_I(inode)->i_reserved_meta_blocks)
  2184. return 0;
  2185. /*
  2186. * We do something simple for now. The filemap_flush() will
  2187. * also start triggering a write of the data blocks, which is
  2188. * not strictly speaking necessary (and for users of
  2189. * laptop_mode, not even desirable). However, to do otherwise
  2190. * would require replicating code paths in:
  2191. *
  2192. * ext4_da_writepages() ->
  2193. * write_cache_pages() ---> (via passed in callback function)
  2194. * __mpage_da_writepage() -->
  2195. * mpage_add_bh_to_extent()
  2196. * mpage_da_map_blocks()
  2197. *
  2198. * The problem is that write_cache_pages(), located in
  2199. * mm/page-writeback.c, marks pages clean in preparation for
  2200. * doing I/O, which is not desirable if we're not planning on
  2201. * doing I/O at all.
  2202. *
  2203. * We could call write_cache_pages(), and then redirty all of
  2204. * the pages by calling redirty_page_for_writepage() but that
  2205. * would be ugly in the extreme. So instead we would need to
  2206. * replicate parts of the code in the above functions,
  2207. * simplifying them because we wouldn't actually intend to
  2208. * write out the pages, but rather only collect contiguous
  2209. * logical block extents, call the multi-block allocator, and
  2210. * then update the buffer heads with the block allocations.
  2211. *
  2212. * For now, though, we'll cheat by calling filemap_flush(),
  2213. * which will map the blocks, and start the I/O, but not
  2214. * actually wait for the I/O to complete.
  2215. */
  2216. return filemap_flush(inode->i_mapping);
  2217. }
  2218. /*
  2219. * bmap() is special. It gets used by applications such as lilo and by
  2220. * the swapper to find the on-disk block of a specific piece of data.
  2221. *
  2222. * Naturally, this is dangerous if the block concerned is still in the
  2223. * journal. If somebody makes a swapfile on an ext4 data-journaling
  2224. * filesystem and enables swap, then they may get a nasty shock when the
  2225. * data getting swapped to that swapfile suddenly gets overwritten by
  2226. * the original zero's written out previously to the journal and
  2227. * awaiting writeback in the kernel's buffer cache.
  2228. *
  2229. * So, if we see any bmap calls here on a modified, data-journaled file,
  2230. * take extra steps to flush any blocks which might be in the cache.
  2231. */
  2232. static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
  2233. {
  2234. struct inode *inode = mapping->host;
  2235. journal_t *journal;
  2236. int err;
  2237. if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
  2238. test_opt(inode->i_sb, DELALLOC)) {
  2239. /*
  2240. * With delalloc we want to sync the file
  2241. * so that we can make sure we allocate
  2242. * blocks for file
  2243. */
  2244. filemap_write_and_wait(mapping);
  2245. }
  2246. if (EXT4_JOURNAL(inode) &&
  2247. ext4_test_inode_state(inode, EXT4_STATE_JDATA)) {
  2248. /*
  2249. * This is a REALLY heavyweight approach, but the use of
  2250. * bmap on dirty files is expected to be extremely rare:
  2251. * only if we run lilo or swapon on a freshly made file
  2252. * do we expect this to happen.
  2253. *
  2254. * (bmap requires CAP_SYS_RAWIO so this does not
  2255. * represent an unprivileged user DOS attack --- we'd be
  2256. * in trouble if mortal users could trigger this path at
  2257. * will.)
  2258. *
  2259. * NB. EXT4_STATE_JDATA is not set on files other than
  2260. * regular files. If somebody wants to bmap a directory
  2261. * or symlink and gets confused because the buffer
  2262. * hasn't yet been flushed to disk, they deserve
  2263. * everything they get.
  2264. */
  2265. ext4_clear_inode_state(inode, EXT4_STATE_JDATA);
  2266. journal = EXT4_JOURNAL(inode);
  2267. jbd2_journal_lock_updates(journal);
  2268. err = jbd2_journal_flush(journal);
  2269. jbd2_journal_unlock_updates(journal);
  2270. if (err)
  2271. return 0;
  2272. }
  2273. return generic_block_bmap(mapping, block, ext4_get_block);
  2274. }
  2275. static int ext4_readpage(struct file *file, struct page *page)
  2276. {
  2277. trace_ext4_readpage(page);
  2278. return mpage_readpage(page, ext4_get_block);
  2279. }
  2280. static int
  2281. ext4_readpages(struct file *file, struct address_space *mapping,
  2282. struct list_head *pages, unsigned nr_pages)
  2283. {
  2284. return mpage_readpages(mapping, pages, nr_pages, ext4_get_block);
  2285. }
  2286. static void ext4_invalidatepage_free_endio(struct page *page, unsigned long offset)
  2287. {
  2288. struct buffer_head *head, *bh;
  2289. unsigned int curr_off = 0;
  2290. if (!page_has_buffers(page))
  2291. return;
  2292. head = bh = page_buffers(page);
  2293. do {
  2294. if (offset <= curr_off && test_clear_buffer_uninit(bh)
  2295. && bh->b_private) {
  2296. ext4_free_io_end(bh->b_private);
  2297. bh->b_private = NULL;
  2298. bh->b_end_io = NULL;
  2299. }
  2300. curr_off = curr_off + bh->b_size;
  2301. bh = bh->b_this_page;
  2302. } while (bh != head);
  2303. }
  2304. static void ext4_invalidatepage(struct page *page, unsigned long offset)
  2305. {
  2306. journal_t *journal = EXT4_JOURNAL(page->mapping->host);
  2307. trace_ext4_invalidatepage(page, offset);
  2308. /*
  2309. * free any io_end structure allocated for buffers to be discarded
  2310. */
  2311. if (ext4_should_dioread_nolock(page->mapping->host))
  2312. ext4_invalidatepage_free_endio(page, offset);
  2313. /*
  2314. * If it's a full truncate we just forget about the pending dirtying
  2315. */
  2316. if (offset == 0)
  2317. ClearPageChecked(page);
  2318. if (journal)
  2319. jbd2_journal_invalidatepage(journal, page, offset);
  2320. else
  2321. block_invalidatepage(page, offset);
  2322. }
  2323. static int ext4_releasepage(struct page *page, gfp_t wait)
  2324. {
  2325. journal_t *journal = EXT4_JOURNAL(page->mapping->host);
  2326. trace_ext4_releasepage(page);
  2327. WARN_ON(PageChecked(page));
  2328. if (!page_has_buffers(page))
  2329. return 0;
  2330. if (journal)
  2331. return jbd2_journal_try_to_free_buffers(journal, page, wait);
  2332. else
  2333. return try_to_free_buffers(page);
  2334. }
  2335. /*
  2336. * ext4_get_block used when preparing for a DIO write or buffer write.
  2337. * We allocate an uinitialized extent if blocks haven't been allocated.
  2338. * The extent will be converted to initialized after the IO is complete.
  2339. */
  2340. static int ext4_get_block_write(struct inode *inode, sector_t iblock,
  2341. struct buffer_head *bh_result, int create)
  2342. {
  2343. ext4_debug("ext4_get_block_write: inode %lu, create flag %d\n",
  2344. inode->i_ino, create);
  2345. return _ext4_get_block(inode, iblock, bh_result,
  2346. EXT4_GET_BLOCKS_IO_CREATE_EXT);
  2347. }
  2348. static void ext4_end_io_dio(struct kiocb *iocb, loff_t offset,
  2349. ssize_t size, void *private, int ret,
  2350. bool is_async)
  2351. {
  2352. struct inode *inode = iocb->ki_filp->f_path.dentry->d_inode;
  2353. ext4_io_end_t *io_end = iocb->private;
  2354. struct workqueue_struct *wq;
  2355. unsigned long flags;
  2356. struct ext4_inode_info *ei;
  2357. /* if not async direct IO or dio with 0 bytes write, just return */
  2358. if (!io_end || !size)
  2359. goto out;
  2360. ext_debug("ext4_end_io_dio(): io_end 0x%p"
  2361. "for inode %lu, iocb 0x%p, offset %llu, size %llu\n",
  2362. iocb->private, io_end->inode->i_ino, iocb, offset,
  2363. size);
  2364. /* if not aio dio with unwritten extents, just free io and return */
  2365. if (!(io_end->flag & EXT4_IO_END_UNWRITTEN)) {
  2366. ext4_free_io_end(io_end);
  2367. iocb->private = NULL;
  2368. out:
  2369. if (is_async)
  2370. aio_complete(iocb, ret, 0);
  2371. inode_dio_done(inode);
  2372. return;
  2373. }
  2374. io_end->offset = offset;
  2375. io_end->size = size;
  2376. if (is_async) {
  2377. io_end->iocb = iocb;
  2378. io_end->result = ret;
  2379. }
  2380. wq = EXT4_SB(io_end->inode->i_sb)->dio_unwritten_wq;
  2381. /* Add the io_end to per-inode completed aio dio list*/
  2382. ei = EXT4_I(io_end->inode);
  2383. spin_lock_irqsave(&ei->i_completed_io_lock, flags);
  2384. list_add_tail(&io_end->list, &ei->i_completed_io_list);
  2385. spin_unlock_irqrestore(&ei->i_completed_io_lock, flags);
  2386. /* queue the work to convert unwritten extents to written */
  2387. queue_work(wq, &io_end->work);
  2388. iocb->private = NULL;
  2389. /* XXX: probably should move into the real I/O completion handler */
  2390. inode_dio_done(inode);
  2391. }
  2392. static void ext4_end_io_buffer_write(struct buffer_head *bh, int uptodate)
  2393. {
  2394. ext4_io_end_t *io_end = bh->b_private;
  2395. struct workqueue_struct *wq;
  2396. struct inode *inode;
  2397. unsigned long flags;
  2398. if (!test_clear_buffer_uninit(bh) || !io_end)
  2399. goto out;
  2400. if (!(io_end->inode->i_sb->s_flags & MS_ACTIVE)) {
  2401. printk("sb umounted, discard end_io request for inode %lu\n",
  2402. io_end->inode->i_ino);
  2403. ext4_free_io_end(io_end);
  2404. goto out;
  2405. }
  2406. /*
  2407. * It may be over-defensive here to check EXT4_IO_END_UNWRITTEN now,
  2408. * but being more careful is always safe for the future change.
  2409. */
  2410. inode = io_end->inode;
  2411. if (!(io_end->flag & EXT4_IO_END_UNWRITTEN)) {
  2412. io_end->flag |= EXT4_IO_END_UNWRITTEN;
  2413. atomic_inc(&EXT4_I(inode)->i_aiodio_unwritten);
  2414. }
  2415. /* Add the io_end to per-inode completed io list*/
  2416. spin_lock_irqsave(&EXT4_I(inode)->i_completed_io_lock, flags);
  2417. list_add_tail(&io_end->list, &EXT4_I(inode)->i_completed_io_list);
  2418. spin_unlock_irqrestore(&EXT4_I(inode)->i_completed_io_lock, flags);
  2419. wq = EXT4_SB(inode->i_sb)->dio_unwritten_wq;
  2420. /* queue the work to convert unwritten extents to written */
  2421. queue_work(wq, &io_end->work);
  2422. out:
  2423. bh->b_private = NULL;
  2424. bh->b_end_io = NULL;
  2425. clear_buffer_uninit(bh);
  2426. end_buffer_async_write(bh, uptodate);
  2427. }
  2428. static int ext4_set_bh_endio(struct buffer_head *bh, struct inode *inode)
  2429. {
  2430. ext4_io_end_t *io_end;
  2431. struct page *page = bh->b_page;
  2432. loff_t offset = (sector_t)page->index << PAGE_CACHE_SHIFT;
  2433. size_t size = bh->b_size;
  2434. retry:
  2435. io_end = ext4_init_io_end(inode, GFP_ATOMIC);
  2436. if (!io_end) {
  2437. pr_warn_ratelimited("%s: allocation fail\n", __func__);
  2438. schedule();
  2439. goto retry;
  2440. }
  2441. io_end->offset = offset;
  2442. io_end->size = size;
  2443. /*
  2444. * We need to hold a reference to the page to make sure it
  2445. * doesn't get evicted before ext4_end_io_work() has a chance
  2446. * to convert the extent from written to unwritten.
  2447. */
  2448. io_end->page = page;
  2449. get_page(io_end->page);
  2450. bh->b_private = io_end;
  2451. bh->b_end_io = ext4_end_io_buffer_write;
  2452. return 0;
  2453. }
  2454. /*
  2455. * For ext4 extent files, ext4 will do direct-io write to holes,
  2456. * preallocated extents, and those write extend the file, no need to
  2457. * fall back to buffered IO.
  2458. *
  2459. * For holes, we fallocate those blocks, mark them as uninitialized
  2460. * If those blocks were preallocated, we mark sure they are splited, but
  2461. * still keep the range to write as uninitialized.
  2462. *
  2463. * The unwrritten extents will be converted to written when DIO is completed.
  2464. * For async direct IO, since the IO may still pending when return, we
  2465. * set up an end_io call back function, which will do the conversion
  2466. * when async direct IO completed.
  2467. *
  2468. * If the O_DIRECT write will extend the file then add this inode to the
  2469. * orphan list. So recovery will truncate it back to the original size
  2470. * if the machine crashes during the write.
  2471. *
  2472. */
  2473. static ssize_t ext4_ext_direct_IO(int rw, struct kiocb *iocb,
  2474. const struct iovec *iov, loff_t offset,
  2475. unsigned long nr_segs)
  2476. {
  2477. struct file *file = iocb->ki_filp;
  2478. struct inode *inode = file->f_mapping->host;
  2479. ssize_t ret;
  2480. size_t count = iov_length(iov, nr_segs);
  2481. loff_t final_size = offset + count;
  2482. if (rw == WRITE && final_size <= inode->i_size) {
  2483. /*
  2484. * We could direct write to holes and fallocate.
  2485. *
  2486. * Allocated blocks to fill the hole are marked as uninitialized
  2487. * to prevent parallel buffered read to expose the stale data
  2488. * before DIO complete the data IO.
  2489. *
  2490. * As to previously fallocated extents, ext4 get_block
  2491. * will just simply mark the buffer mapped but still
  2492. * keep the extents uninitialized.
  2493. *
  2494. * for non AIO case, we will convert those unwritten extents
  2495. * to written after return back from blockdev_direct_IO.
  2496. *
  2497. * for async DIO, the conversion needs to be defered when
  2498. * the IO is completed. The ext4 end_io callback function
  2499. * will be called to take care of the conversion work.
  2500. * Here for async case, we allocate an io_end structure to
  2501. * hook to the iocb.
  2502. */
  2503. iocb->private = NULL;
  2504. EXT4_I(inode)->cur_aio_dio = NULL;
  2505. if (!is_sync_kiocb(iocb)) {
  2506. iocb->private = ext4_init_io_end(inode, GFP_NOFS);
  2507. if (!iocb->private)
  2508. return -ENOMEM;
  2509. /*
  2510. * we save the io structure for current async
  2511. * direct IO, so that later ext4_map_blocks()
  2512. * could flag the io structure whether there
  2513. * is a unwritten extents needs to be converted
  2514. * when IO is completed.
  2515. */
  2516. EXT4_I(inode)->cur_aio_dio = iocb->private;
  2517. }
  2518. ret = __blockdev_direct_IO(rw, iocb, inode,
  2519. inode->i_sb->s_bdev, iov,
  2520. offset, nr_segs,
  2521. ext4_get_block_write,
  2522. ext4_end_io_dio,
  2523. NULL,
  2524. DIO_LOCKING | DIO_SKIP_HOLES);
  2525. if (iocb->private)
  2526. EXT4_I(inode)->cur_aio_dio = NULL;
  2527. /*
  2528. * The io_end structure takes a reference to the inode,
  2529. * that structure needs to be destroyed and the
  2530. * reference to the inode need to be dropped, when IO is
  2531. * complete, even with 0 byte write, or failed.
  2532. *
  2533. * In the successful AIO DIO case, the io_end structure will be
  2534. * desctroyed and the reference to the inode will be dropped
  2535. * after the end_io call back function is called.
  2536. *
  2537. * In the case there is 0 byte write, or error case, since
  2538. * VFS direct IO won't invoke the end_io call back function,
  2539. * we need to free the end_io structure here.
  2540. */
  2541. if (ret != -EIOCBQUEUED && ret <= 0 && iocb->private) {
  2542. ext4_free_io_end(iocb->private);
  2543. iocb->private = NULL;
  2544. } else if (ret > 0 && ext4_test_inode_state(inode,
  2545. EXT4_STATE_DIO_UNWRITTEN)) {
  2546. int err;
  2547. /*
  2548. * for non AIO case, since the IO is already
  2549. * completed, we could do the conversion right here
  2550. */
  2551. err = ext4_convert_unwritten_extents(inode,
  2552. offset, ret);
  2553. if (err < 0)
  2554. ret = err;
  2555. ext4_clear_inode_state(inode, EXT4_STATE_DIO_UNWRITTEN);
  2556. }
  2557. return ret;
  2558. }
  2559. /* for write the the end of file case, we fall back to old way */
  2560. return ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
  2561. }
  2562. static ssize_t ext4_direct_IO(int rw, struct kiocb *iocb,
  2563. const struct iovec *iov, loff_t offset,
  2564. unsigned long nr_segs)
  2565. {
  2566. struct file *file = iocb->ki_filp;
  2567. struct inode *inode = file->f_mapping->host;
  2568. ssize_t ret;
  2569. trace_ext4_direct_IO_enter(inode, offset, iov_length(iov, nr_segs), rw);
  2570. if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
  2571. ret = ext4_ext_direct_IO(rw, iocb, iov, offset, nr_segs);
  2572. else
  2573. ret = ext4_ind_direct_IO(rw, iocb, iov, offset, nr_segs);
  2574. trace_ext4_direct_IO_exit(inode, offset,
  2575. iov_length(iov, nr_segs), rw, ret);
  2576. return ret;
  2577. }
  2578. /*
  2579. * Pages can be marked dirty completely asynchronously from ext4's journalling
  2580. * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
  2581. * much here because ->set_page_dirty is called under VFS locks. The page is
  2582. * not necessarily locked.
  2583. *
  2584. * We cannot just dirty the page and leave attached buffers clean, because the
  2585. * buffers' dirty state is "definitive". We cannot just set the buffers dirty
  2586. * or jbddirty because all the journalling code will explode.
  2587. *
  2588. * So what we do is to mark the page "pending dirty" and next time writepage
  2589. * is called, propagate that into the buffers appropriately.
  2590. */
  2591. static int ext4_journalled_set_page_dirty(struct page *page)
  2592. {
  2593. SetPageChecked(page);
  2594. return __set_page_dirty_nobuffers(page);
  2595. }
  2596. static const struct address_space_operations ext4_ordered_aops = {
  2597. .readpage = ext4_readpage,
  2598. .readpages = ext4_readpages,
  2599. .writepage = ext4_writepage,
  2600. .write_begin = ext4_write_begin,
  2601. .write_end = ext4_ordered_write_end,
  2602. .bmap = ext4_bmap,
  2603. .invalidatepage = ext4_invalidatepage,
  2604. .releasepage = ext4_releasepage,
  2605. .direct_IO = ext4_direct_IO,
  2606. .migratepage = buffer_migrate_page,
  2607. .is_partially_uptodate = block_is_partially_uptodate,
  2608. .error_remove_page = generic_error_remove_page,
  2609. };
  2610. static const struct address_space_operations ext4_writeback_aops = {
  2611. .readpage = ext4_readpage,
  2612. .readpages = ext4_readpages,
  2613. .writepage = ext4_writepage,
  2614. .write_begin = ext4_write_begin,
  2615. .write_end = ext4_writeback_write_end,
  2616. .bmap = ext4_bmap,
  2617. .invalidatepage = ext4_invalidatepage,
  2618. .releasepage = ext4_releasepage,
  2619. .direct_IO = ext4_direct_IO,
  2620. .migratepage = buffer_migrate_page,
  2621. .is_partially_uptodate = block_is_partially_uptodate,
  2622. .error_remove_page = generic_error_remove_page,
  2623. };
  2624. static const struct address_space_operations ext4_journalled_aops = {
  2625. .readpage = ext4_readpage,
  2626. .readpages = ext4_readpages,
  2627. .writepage = ext4_writepage,
  2628. .write_begin = ext4_write_begin,
  2629. .write_end = ext4_journalled_write_end,
  2630. .set_page_dirty = ext4_journalled_set_page_dirty,
  2631. .bmap = ext4_bmap,
  2632. .invalidatepage = ext4_invalidatepage,
  2633. .releasepage = ext4_releasepage,
  2634. .is_partially_uptodate = block_is_partially_uptodate,
  2635. .error_remove_page = generic_error_remove_page,
  2636. };
  2637. static const struct address_space_operations ext4_da_aops = {
  2638. .readpage = ext4_readpage,
  2639. .readpages = ext4_readpages,
  2640. .writepage = ext4_writepage,
  2641. .writepages = ext4_da_writepages,
  2642. .write_begin = ext4_da_write_begin,
  2643. .write_end = ext4_da_write_end,
  2644. .bmap = ext4_bmap,
  2645. .invalidatepage = ext4_da_invalidatepage,
  2646. .releasepage = ext4_releasepage,
  2647. .direct_IO = ext4_direct_IO,
  2648. .migratepage = buffer_migrate_page,
  2649. .is_partially_uptodate = block_is_partially_uptodate,
  2650. .error_remove_page = generic_error_remove_page,
  2651. };
  2652. void ext4_set_aops(struct inode *inode)
  2653. {
  2654. if (ext4_should_order_data(inode) &&
  2655. test_opt(inode->i_sb, DELALLOC))
  2656. inode->i_mapping->a_ops = &ext4_da_aops;
  2657. else if (ext4_should_order_data(inode))
  2658. inode->i_mapping->a_ops = &ext4_ordered_aops;
  2659. else if (ext4_should_writeback_data(inode) &&
  2660. test_opt(inode->i_sb, DELALLOC))
  2661. inode->i_mapping->a_ops = &ext4_da_aops;
  2662. else if (ext4_should_writeback_data(inode))
  2663. inode->i_mapping->a_ops = &ext4_writeback_aops;
  2664. else
  2665. inode->i_mapping->a_ops = &ext4_journalled_aops;
  2666. }
  2667. /*
  2668. * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
  2669. * up to the end of the block which corresponds to `from'.
  2670. * This required during truncate. We need to physically zero the tail end
  2671. * of that block so it doesn't yield old data if the file is later grown.
  2672. */
  2673. int ext4_block_truncate_page(handle_t *handle,
  2674. struct address_space *mapping, loff_t from)
  2675. {
  2676. unsigned offset = from & (PAGE_CACHE_SIZE-1);
  2677. unsigned length;
  2678. unsigned blocksize;
  2679. struct inode *inode = mapping->host;
  2680. blocksize = inode->i_sb->s_blocksize;
  2681. length = blocksize - (offset & (blocksize - 1));
  2682. return ext4_block_zero_page_range(handle, mapping, from, length);
  2683. }
  2684. /*
  2685. * ext4_block_zero_page_range() zeros out a mapping of length 'length'
  2686. * starting from file offset 'from'. The range to be zero'd must
  2687. * be contained with in one block. If the specified range exceeds
  2688. * the end of the block it will be shortened to end of the block
  2689. * that cooresponds to 'from'
  2690. */
  2691. int ext4_block_zero_page_range(handle_t *handle,
  2692. struct address_space *mapping, loff_t from, loff_t length)
  2693. {
  2694. ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
  2695. unsigned offset = from & (PAGE_CACHE_SIZE-1);
  2696. unsigned blocksize, max, pos;
  2697. ext4_lblk_t iblock;
  2698. struct inode *inode = mapping->host;
  2699. struct buffer_head *bh;
  2700. struct page *page;
  2701. int err = 0;
  2702. page = find_or_create_page(mapping, from >> PAGE_CACHE_SHIFT,
  2703. mapping_gfp_mask(mapping) & ~__GFP_FS);
  2704. if (!page)
  2705. return -EINVAL;
  2706. blocksize = inode->i_sb->s_blocksize;
  2707. max = blocksize - (offset & (blocksize - 1));
  2708. /*
  2709. * correct length if it does not fall between
  2710. * 'from' and the end of the block
  2711. */
  2712. if (length > max || length < 0)
  2713. length = max;
  2714. iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
  2715. if (!page_has_buffers(page))
  2716. create_empty_buffers(page, blocksize, 0);
  2717. /* Find the buffer that contains "offset" */
  2718. bh = page_buffers(page);
  2719. pos = blocksize;
  2720. while (offset >= pos) {
  2721. bh = bh->b_this_page;
  2722. iblock++;
  2723. pos += blocksize;
  2724. }
  2725. err = 0;
  2726. if (buffer_freed(bh)) {
  2727. BUFFER_TRACE(bh, "freed: skip");
  2728. goto unlock;
  2729. }
  2730. if (!buffer_mapped(bh)) {
  2731. BUFFER_TRACE(bh, "unmapped");
  2732. ext4_get_block(inode, iblock, bh, 0);
  2733. /* unmapped? It's a hole - nothing to do */
  2734. if (!buffer_mapped(bh)) {
  2735. BUFFER_TRACE(bh, "still unmapped");
  2736. goto unlock;
  2737. }
  2738. }
  2739. /* Ok, it's mapped. Make sure it's up-to-date */
  2740. if (PageUptodate(page))
  2741. set_buffer_uptodate(bh);
  2742. if (!buffer_uptodate(bh)) {
  2743. err = -EIO;
  2744. ll_rw_block(READ, 1, &bh);
  2745. wait_on_buffer(bh);
  2746. /* Uhhuh. Read error. Complain and punt. */
  2747. if (!buffer_uptodate(bh))
  2748. goto unlock;
  2749. }
  2750. if (ext4_should_journal_data(inode)) {
  2751. BUFFER_TRACE(bh, "get write access");
  2752. err = ext4_journal_get_write_access(handle, bh);
  2753. if (err)
  2754. goto unlock;
  2755. }
  2756. zero_user(page, offset, length);
  2757. BUFFER_TRACE(bh, "zeroed end of block");
  2758. err = 0;
  2759. if (ext4_should_journal_data(inode)) {
  2760. err = ext4_handle_dirty_metadata(handle, inode, bh);
  2761. } else {
  2762. if (ext4_should_order_data(inode) && EXT4_I(inode)->jinode)
  2763. err = ext4_jbd2_file_inode(handle, inode);
  2764. mark_buffer_dirty(bh);
  2765. }
  2766. unlock:
  2767. unlock_page(page);
  2768. page_cache_release(page);
  2769. return err;
  2770. }
  2771. int ext4_can_truncate(struct inode *inode)
  2772. {
  2773. if (S_ISREG(inode->i_mode))
  2774. return 1;
  2775. if (S_ISDIR(inode->i_mode))
  2776. return 1;
  2777. if (S_ISLNK(inode->i_mode))
  2778. return !ext4_inode_is_fast_symlink(inode);
  2779. return 0;
  2780. }
  2781. /*
  2782. * ext4_punch_hole: punches a hole in a file by releaseing the blocks
  2783. * associated with the given offset and length
  2784. *
  2785. * @inode: File inode
  2786. * @offset: The offset where the hole will begin
  2787. * @len: The length of the hole
  2788. *
  2789. * Returns: 0 on sucess or negative on failure
  2790. */
  2791. int ext4_punch_hole(struct file *file, loff_t offset, loff_t length)
  2792. {
  2793. struct inode *inode = file->f_path.dentry->d_inode;
  2794. if (!S_ISREG(inode->i_mode))
  2795. return -ENOTSUPP;
  2796. if (!ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
  2797. /* TODO: Add support for non extent hole punching */
  2798. return -ENOTSUPP;
  2799. }
  2800. return ext4_ext_punch_hole(file, offset, length);
  2801. }
  2802. /*
  2803. * ext4_truncate()
  2804. *
  2805. * We block out ext4_get_block() block instantiations across the entire
  2806. * transaction, and VFS/VM ensures that ext4_truncate() cannot run
  2807. * simultaneously on behalf of the same inode.
  2808. *
  2809. * As we work through the truncate and commmit bits of it to the journal there
  2810. * is one core, guiding principle: the file's tree must always be consistent on
  2811. * disk. We must be able to restart the truncate after a crash.
  2812. *
  2813. * The file's tree may be transiently inconsistent in memory (although it
  2814. * probably isn't), but whenever we close off and commit a journal transaction,
  2815. * the contents of (the filesystem + the journal) must be consistent and
  2816. * restartable. It's pretty simple, really: bottom up, right to left (although
  2817. * left-to-right works OK too).
  2818. *
  2819. * Note that at recovery time, journal replay occurs *before* the restart of
  2820. * truncate against the orphan inode list.
  2821. *
  2822. * The committed inode has the new, desired i_size (which is the same as
  2823. * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
  2824. * that this inode's truncate did not complete and it will again call
  2825. * ext4_truncate() to have another go. So there will be instantiated blocks
  2826. * to the right of the truncation point in a crashed ext4 filesystem. But
  2827. * that's fine - as long as they are linked from the inode, the post-crash
  2828. * ext4_truncate() run will find them and release them.
  2829. */
  2830. void ext4_truncate(struct inode *inode)
  2831. {
  2832. trace_ext4_truncate_enter(inode);
  2833. if (!ext4_can_truncate(inode))
  2834. return;
  2835. ext4_clear_inode_flag(inode, EXT4_INODE_EOFBLOCKS);
  2836. if (inode->i_size == 0 && !test_opt(inode->i_sb, NO_AUTO_DA_ALLOC))
  2837. ext4_set_inode_state(inode, EXT4_STATE_DA_ALLOC_CLOSE);
  2838. if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))
  2839. ext4_ext_truncate(inode);
  2840. else
  2841. ext4_ind_truncate(inode);
  2842. trace_ext4_truncate_exit(inode);
  2843. }
  2844. /*
  2845. * ext4_get_inode_loc returns with an extra refcount against the inode's
  2846. * underlying buffer_head on success. If 'in_mem' is true, we have all
  2847. * data in memory that is needed to recreate the on-disk version of this
  2848. * inode.
  2849. */
  2850. static int __ext4_get_inode_loc(struct inode *inode,
  2851. struct ext4_iloc *iloc, int in_mem)
  2852. {
  2853. struct ext4_group_desc *gdp;
  2854. struct buffer_head *bh;
  2855. struct super_block *sb = inode->i_sb;
  2856. ext4_fsblk_t block;
  2857. int inodes_per_block, inode_offset;
  2858. iloc->bh = NULL;
  2859. if (!ext4_valid_inum(sb, inode->i_ino))
  2860. return -EIO;
  2861. iloc->block_group = (inode->i_ino - 1) / EXT4_INODES_PER_GROUP(sb);
  2862. gdp = ext4_get_group_desc(sb, iloc->block_group, NULL);
  2863. if (!gdp)
  2864. return -EIO;
  2865. /*
  2866. * Figure out the offset within the block group inode table
  2867. */
  2868. inodes_per_block = EXT4_SB(sb)->s_inodes_per_block;
  2869. inode_offset = ((inode->i_ino - 1) %
  2870. EXT4_INODES_PER_GROUP(sb));
  2871. block = ext4_inode_table(sb, gdp) + (inode_offset / inodes_per_block);
  2872. iloc->offset = (inode_offset % inodes_per_block) * EXT4_INODE_SIZE(sb);
  2873. bh = sb_getblk(sb, block);
  2874. if (!bh) {
  2875. EXT4_ERROR_INODE_BLOCK(inode, block,
  2876. "unable to read itable block");
  2877. return -EIO;
  2878. }
  2879. if (!buffer_uptodate(bh)) {
  2880. lock_buffer(bh);
  2881. /*
  2882. * If the buffer has the write error flag, we have failed
  2883. * to write out another inode in the same block. In this
  2884. * case, we don't have to read the block because we may
  2885. * read the old inode data successfully.
  2886. */
  2887. if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
  2888. set_buffer_uptodate(bh);
  2889. if (buffer_uptodate(bh)) {
  2890. /* someone brought it uptodate while we waited */
  2891. unlock_buffer(bh);
  2892. goto has_buffer;
  2893. }
  2894. /*
  2895. * If we have all information of the inode in memory and this
  2896. * is the only valid inode in the block, we need not read the
  2897. * block.
  2898. */
  2899. if (in_mem) {
  2900. struct buffer_head *bitmap_bh;
  2901. int i, start;
  2902. start = inode_offset & ~(inodes_per_block - 1);
  2903. /* Is the inode bitmap in cache? */
  2904. bitmap_bh = sb_getblk(sb, ext4_inode_bitmap(sb, gdp));
  2905. if (!bitmap_bh)
  2906. goto make_io;
  2907. /*
  2908. * If the inode bitmap isn't in cache then the
  2909. * optimisation may end up performing two reads instead
  2910. * of one, so skip it.
  2911. */
  2912. if (!buffer_uptodate(bitmap_bh)) {
  2913. brelse(bitmap_bh);
  2914. goto make_io;
  2915. }
  2916. for (i = start; i < start + inodes_per_block; i++) {
  2917. if (i == inode_offset)
  2918. continue;
  2919. if (ext4_test_bit(i, bitmap_bh->b_data))
  2920. break;
  2921. }
  2922. brelse(bitmap_bh);
  2923. if (i == start + inodes_per_block) {
  2924. /* all other inodes are free, so skip I/O */
  2925. memset(bh->b_data, 0, bh->b_size);
  2926. set_buffer_uptodate(bh);
  2927. unlock_buffer(bh);
  2928. goto has_buffer;
  2929. }
  2930. }
  2931. make_io:
  2932. /*
  2933. * If we need to do any I/O, try to pre-readahead extra
  2934. * blocks from the inode table.
  2935. */
  2936. if (EXT4_SB(sb)->s_inode_readahead_blks) {
  2937. ext4_fsblk_t b, end, table;
  2938. unsigned num;
  2939. table = ext4_inode_table(sb, gdp);
  2940. /* s_inode_readahead_blks is always a power of 2 */
  2941. b = block & ~(EXT4_SB(sb)->s_inode_readahead_blks-1);
  2942. if (table > b)
  2943. b = table;
  2944. end = b + EXT4_SB(sb)->s_inode_readahead_blks;
  2945. num = EXT4_INODES_PER_GROUP(sb);
  2946. if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
  2947. EXT4_FEATURE_RO_COMPAT_GDT_CSUM))
  2948. num -= ext4_itable_unused_count(sb, gdp);
  2949. table += num / inodes_per_block;
  2950. if (end > table)
  2951. end = table;
  2952. while (b <= end)
  2953. sb_breadahead(sb, b++);
  2954. }
  2955. /*
  2956. * There are other valid inodes in the buffer, this inode
  2957. * has in-inode xattrs, or we don't have this inode in memory.
  2958. * Read the block from disk.
  2959. */
  2960. trace_ext4_load_inode(inode);
  2961. get_bh(bh);
  2962. bh->b_end_io = end_buffer_read_sync;
  2963. submit_bh(READ_META, bh);
  2964. wait_on_buffer(bh);
  2965. if (!buffer_uptodate(bh)) {
  2966. EXT4_ERROR_INODE_BLOCK(inode, block,
  2967. "unable to read itable block");
  2968. brelse(bh);
  2969. return -EIO;
  2970. }
  2971. }
  2972. has_buffer:
  2973. iloc->bh = bh;
  2974. return 0;
  2975. }
  2976. int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
  2977. {
  2978. /* We have all inode data except xattrs in memory here. */
  2979. return __ext4_get_inode_loc(inode, iloc,
  2980. !ext4_test_inode_state(inode, EXT4_STATE_XATTR));
  2981. }
  2982. void ext4_set_inode_flags(struct inode *inode)
  2983. {
  2984. unsigned int flags = EXT4_I(inode)->i_flags;
  2985. inode->i_flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC);
  2986. if (flags & EXT4_SYNC_FL)
  2987. inode->i_flags |= S_SYNC;
  2988. if (flags & EXT4_APPEND_FL)
  2989. inode->i_flags |= S_APPEND;
  2990. if (flags & EXT4_IMMUTABLE_FL)
  2991. inode->i_flags |= S_IMMUTABLE;
  2992. if (flags & EXT4_NOATIME_FL)
  2993. inode->i_flags |= S_NOATIME;
  2994. if (flags & EXT4_DIRSYNC_FL)
  2995. inode->i_flags |= S_DIRSYNC;
  2996. }
  2997. /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
  2998. void ext4_get_inode_flags(struct ext4_inode_info *ei)
  2999. {
  3000. unsigned int vfs_fl;
  3001. unsigned long old_fl, new_fl;
  3002. do {
  3003. vfs_fl = ei->vfs_inode.i_flags;
  3004. old_fl = ei->i_flags;
  3005. new_fl = old_fl & ~(EXT4_SYNC_FL|EXT4_APPEND_FL|
  3006. EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL|
  3007. EXT4_DIRSYNC_FL);
  3008. if (vfs_fl & S_SYNC)
  3009. new_fl |= EXT4_SYNC_FL;
  3010. if (vfs_fl & S_APPEND)
  3011. new_fl |= EXT4_APPEND_FL;
  3012. if (vfs_fl & S_IMMUTABLE)
  3013. new_fl |= EXT4_IMMUTABLE_FL;
  3014. if (vfs_fl & S_NOATIME)
  3015. new_fl |= EXT4_NOATIME_FL;
  3016. if (vfs_fl & S_DIRSYNC)
  3017. new_fl |= EXT4_DIRSYNC_FL;
  3018. } while (cmpxchg(&ei->i_flags, old_fl, new_fl) != old_fl);
  3019. }
  3020. static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
  3021. struct ext4_inode_info *ei)
  3022. {
  3023. blkcnt_t i_blocks ;
  3024. struct inode *inode = &(ei->vfs_inode);
  3025. struct super_block *sb = inode->i_sb;
  3026. if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
  3027. EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
  3028. /* we are using combined 48 bit field */
  3029. i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
  3030. le32_to_cpu(raw_inode->i_blocks_lo);
  3031. if (ext4_test_inode_flag(inode, EXT4_INODE_HUGE_FILE)) {
  3032. /* i_blocks represent file system block size */
  3033. return i_blocks << (inode->i_blkbits - 9);
  3034. } else {
  3035. return i_blocks;
  3036. }
  3037. } else {
  3038. return le32_to_cpu(raw_inode->i_blocks_lo);
  3039. }
  3040. }
  3041. struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
  3042. {
  3043. struct ext4_iloc iloc;
  3044. struct ext4_inode *raw_inode;
  3045. struct ext4_inode_info *ei;
  3046. struct inode *inode;
  3047. journal_t *journal = EXT4_SB(sb)->s_journal;
  3048. long ret;
  3049. int block;
  3050. inode = iget_locked(sb, ino);
  3051. if (!inode)
  3052. return ERR_PTR(-ENOMEM);
  3053. if (!(inode->i_state & I_NEW))
  3054. return inode;
  3055. ei = EXT4_I(inode);
  3056. iloc.bh = NULL;
  3057. ret = __ext4_get_inode_loc(inode, &iloc, 0);
  3058. if (ret < 0)
  3059. goto bad_inode;
  3060. raw_inode = ext4_raw_inode(&iloc);
  3061. inode->i_mode = le16_to_cpu(raw_inode->i_mode);
  3062. inode->i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
  3063. inode->i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
  3064. if (!(test_opt(inode->i_sb, NO_UID32))) {
  3065. inode->i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
  3066. inode->i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
  3067. }
  3068. inode->i_nlink = le16_to_cpu(raw_inode->i_links_count);
  3069. ext4_clear_state_flags(ei); /* Only relevant on 32-bit archs */
  3070. ei->i_dir_start_lookup = 0;
  3071. ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
  3072. /* We now have enough fields to check if the inode was active or not.
  3073. * This is needed because nfsd might try to access dead inodes
  3074. * the test is that same one that e2fsck uses
  3075. * NeilBrown 1999oct15
  3076. */
  3077. if (inode->i_nlink == 0) {
  3078. if (inode->i_mode == 0 ||
  3079. !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) {
  3080. /* this inode is deleted */
  3081. ret = -ESTALE;
  3082. goto bad_inode;
  3083. }
  3084. /* The only unlinked inodes we let through here have
  3085. * valid i_mode and are being read by the orphan
  3086. * recovery code: that's fine, we're about to complete
  3087. * the process of deleting those. */
  3088. }
  3089. ei->i_flags = le32_to_cpu(raw_inode->i_flags);
  3090. inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
  3091. ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
  3092. if (EXT4_HAS_INCOMPAT_FEATURE(sb, EXT4_FEATURE_INCOMPAT_64BIT))
  3093. ei->i_file_acl |=
  3094. ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
  3095. inode->i_size = ext4_isize(raw_inode);
  3096. ei->i_disksize = inode->i_size;
  3097. #ifdef CONFIG_QUOTA
  3098. ei->i_reserved_quota = 0;
  3099. #endif
  3100. inode->i_generation = le32_to_cpu(raw_inode->i_generation);
  3101. ei->i_block_group = iloc.block_group;
  3102. ei->i_last_alloc_group = ~0;
  3103. /*
  3104. * NOTE! The in-memory inode i_data array is in little-endian order
  3105. * even on big-endian machines: we do NOT byteswap the block numbers!
  3106. */
  3107. for (block = 0; block < EXT4_N_BLOCKS; block++)
  3108. ei->i_data[block] = raw_inode->i_block[block];
  3109. INIT_LIST_HEAD(&ei->i_orphan);
  3110. /*
  3111. * Set transaction id's of transactions that have to be committed
  3112. * to finish f[data]sync. We set them to currently running transaction
  3113. * as we cannot be sure that the inode or some of its metadata isn't
  3114. * part of the transaction - the inode could have been reclaimed and
  3115. * now it is reread from disk.
  3116. */
  3117. if (journal) {
  3118. transaction_t *transaction;
  3119. tid_t tid;
  3120. read_lock(&journal->j_state_lock);
  3121. if (journal->j_running_transaction)
  3122. transaction = journal->j_running_transaction;
  3123. else
  3124. transaction = journal->j_committing_transaction;
  3125. if (transaction)
  3126. tid = transaction->t_tid;
  3127. else
  3128. tid = journal->j_commit_sequence;
  3129. read_unlock(&journal->j_state_lock);
  3130. ei->i_sync_tid = tid;
  3131. ei->i_datasync_tid = tid;
  3132. }
  3133. if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
  3134. ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
  3135. if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
  3136. EXT4_INODE_SIZE(inode->i_sb)) {
  3137. ret = -EIO;
  3138. goto bad_inode;
  3139. }
  3140. if (ei->i_extra_isize == 0) {
  3141. /* The extra space is currently unused. Use it. */
  3142. ei->i_extra_isize = sizeof(struct ext4_inode) -
  3143. EXT4_GOOD_OLD_INODE_SIZE;
  3144. } else {
  3145. __le32 *magic = (void *)raw_inode +
  3146. EXT4_GOOD_OLD_INODE_SIZE +
  3147. ei->i_extra_isize;
  3148. if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC))
  3149. ext4_set_inode_state(inode, EXT4_STATE_XATTR);
  3150. }
  3151. } else
  3152. ei->i_extra_isize = 0;
  3153. EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
  3154. EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
  3155. EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
  3156. EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
  3157. inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
  3158. if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
  3159. if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
  3160. inode->i_version |=
  3161. (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
  3162. }
  3163. ret = 0;
  3164. if (ei->i_file_acl &&
  3165. !ext4_data_block_valid(EXT4_SB(sb), ei->i_file_acl, 1)) {
  3166. EXT4_ERROR_INODE(inode, "bad extended attribute block %llu",
  3167. ei->i_file_acl);
  3168. ret = -EIO;
  3169. goto bad_inode;
  3170. } else if (ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)) {
  3171. if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
  3172. (S_ISLNK(inode->i_mode) &&
  3173. !ext4_inode_is_fast_symlink(inode)))
  3174. /* Validate extent which is part of inode */
  3175. ret = ext4_ext_check_inode(inode);
  3176. } else if (S_ISREG(inode->i_mode) || S_ISDIR(inode->i_mode) ||
  3177. (S_ISLNK(inode->i_mode) &&
  3178. !ext4_inode_is_fast_symlink(inode))) {
  3179. /* Validate block references which are part of inode */
  3180. ret = ext4_ind_check_inode(inode);
  3181. }
  3182. if (ret)
  3183. goto bad_inode;
  3184. if (S_ISREG(inode->i_mode)) {
  3185. inode->i_op = &ext4_file_inode_operations;
  3186. inode->i_fop = &ext4_file_operations;
  3187. ext4_set_aops(inode);
  3188. } else if (S_ISDIR(inode->i_mode)) {
  3189. inode->i_op = &ext4_dir_inode_operations;
  3190. inode->i_fop = &ext4_dir_operations;
  3191. } else if (S_ISLNK(inode->i_mode)) {
  3192. if (ext4_inode_is_fast_symlink(inode)) {
  3193. inode->i_op = &ext4_fast_symlink_inode_operations;
  3194. nd_terminate_link(ei->i_data, inode->i_size,
  3195. sizeof(ei->i_data) - 1);
  3196. } else {
  3197. inode->i_op = &ext4_symlink_inode_operations;
  3198. ext4_set_aops(inode);
  3199. }
  3200. } else if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode) ||
  3201. S_ISFIFO(inode->i_mode) || S_ISSOCK(inode->i_mode)) {
  3202. inode->i_op = &ext4_special_inode_operations;
  3203. if (raw_inode->i_block[0])
  3204. init_special_inode(inode, inode->i_mode,
  3205. old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
  3206. else
  3207. init_special_inode(inode, inode->i_mode,
  3208. new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
  3209. } else {
  3210. ret = -EIO;
  3211. EXT4_ERROR_INODE(inode, "bogus i_mode (%o)", inode->i_mode);
  3212. goto bad_inode;
  3213. }
  3214. brelse(iloc.bh);
  3215. ext4_set_inode_flags(inode);
  3216. unlock_new_inode(inode);
  3217. return inode;
  3218. bad_inode:
  3219. brelse(iloc.bh);
  3220. iget_failed(inode);
  3221. return ERR_PTR(ret);
  3222. }
  3223. static int ext4_inode_blocks_set(handle_t *handle,
  3224. struct ext4_inode *raw_inode,
  3225. struct ext4_inode_info *ei)
  3226. {
  3227. struct inode *inode = &(ei->vfs_inode);
  3228. u64 i_blocks = inode->i_blocks;
  3229. struct super_block *sb = inode->i_sb;
  3230. if (i_blocks <= ~0U) {
  3231. /*
  3232. * i_blocks can be represnted in a 32 bit variable
  3233. * as multiple of 512 bytes
  3234. */
  3235. raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
  3236. raw_inode->i_blocks_high = 0;
  3237. ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
  3238. return 0;
  3239. }
  3240. if (!EXT4_HAS_RO_COMPAT_FEATURE(sb, EXT4_FEATURE_RO_COMPAT_HUGE_FILE))
  3241. return -EFBIG;
  3242. if (i_blocks <= 0xffffffffffffULL) {
  3243. /*
  3244. * i_blocks can be represented in a 48 bit variable
  3245. * as multiple of 512 bytes
  3246. */
  3247. raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
  3248. raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
  3249. ext4_clear_inode_flag(inode, EXT4_INODE_HUGE_FILE);
  3250. } else {
  3251. ext4_set_inode_flag(inode, EXT4_INODE_HUGE_FILE);
  3252. /* i_block is stored in file system block size */
  3253. i_blocks = i_blocks >> (inode->i_blkbits - 9);
  3254. raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
  3255. raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
  3256. }
  3257. return 0;
  3258. }
  3259. /*
  3260. * Post the struct inode info into an on-disk inode location in the
  3261. * buffer-cache. This gobbles the caller's reference to the
  3262. * buffer_head in the inode location struct.
  3263. *
  3264. * The caller must have write access to iloc->bh.
  3265. */
  3266. static int ext4_do_update_inode(handle_t *handle,
  3267. struct inode *inode,
  3268. struct ext4_iloc *iloc)
  3269. {
  3270. struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
  3271. struct ext4_inode_info *ei = EXT4_I(inode);
  3272. struct buffer_head *bh = iloc->bh;
  3273. int err = 0, rc, block;
  3274. /* For fields not not tracking in the in-memory inode,
  3275. * initialise them to zero for new inodes. */
  3276. if (ext4_test_inode_state(inode, EXT4_STATE_NEW))
  3277. memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
  3278. ext4_get_inode_flags(ei);
  3279. raw_inode->i_mode = cpu_to_le16(inode->i_mode);
  3280. if (!(test_opt(inode->i_sb, NO_UID32))) {
  3281. raw_inode->i_uid_low = cpu_to_le16(low_16_bits(inode->i_uid));
  3282. raw_inode->i_gid_low = cpu_to_le16(low_16_bits(inode->i_gid));
  3283. /*
  3284. * Fix up interoperability with old kernels. Otherwise, old inodes get
  3285. * re-used with the upper 16 bits of the uid/gid intact
  3286. */
  3287. if (!ei->i_dtime) {
  3288. raw_inode->i_uid_high =
  3289. cpu_to_le16(high_16_bits(inode->i_uid));
  3290. raw_inode->i_gid_high =
  3291. cpu_to_le16(high_16_bits(inode->i_gid));
  3292. } else {
  3293. raw_inode->i_uid_high = 0;
  3294. raw_inode->i_gid_high = 0;
  3295. }
  3296. } else {
  3297. raw_inode->i_uid_low =
  3298. cpu_to_le16(fs_high2lowuid(inode->i_uid));
  3299. raw_inode->i_gid_low =
  3300. cpu_to_le16(fs_high2lowgid(inode->i_gid));
  3301. raw_inode->i_uid_high = 0;
  3302. raw_inode->i_gid_high = 0;
  3303. }
  3304. raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
  3305. EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
  3306. EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
  3307. EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
  3308. EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
  3309. if (ext4_inode_blocks_set(handle, raw_inode, ei))
  3310. goto out_brelse;
  3311. raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
  3312. raw_inode->i_flags = cpu_to_le32(ei->i_flags & 0xFFFFFFFF);
  3313. if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
  3314. cpu_to_le32(EXT4_OS_HURD))
  3315. raw_inode->i_file_acl_high =
  3316. cpu_to_le16(ei->i_file_acl >> 32);
  3317. raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
  3318. ext4_isize_set(raw_inode, ei->i_disksize);
  3319. if (ei->i_disksize > 0x7fffffffULL) {
  3320. struct super_block *sb = inode->i_sb;
  3321. if (!EXT4_HAS_RO_COMPAT_FEATURE(sb,
  3322. EXT4_FEATURE_RO_COMPAT_LARGE_FILE) ||
  3323. EXT4_SB(sb)->s_es->s_rev_level ==
  3324. cpu_to_le32(EXT4_GOOD_OLD_REV)) {
  3325. /* If this is the first large file
  3326. * created, add a flag to the superblock.
  3327. */
  3328. err = ext4_journal_get_write_access(handle,
  3329. EXT4_SB(sb)->s_sbh);
  3330. if (err)
  3331. goto out_brelse;
  3332. ext4_update_dynamic_rev(sb);
  3333. EXT4_SET_RO_COMPAT_FEATURE(sb,
  3334. EXT4_FEATURE_RO_COMPAT_LARGE_FILE);
  3335. sb->s_dirt = 1;
  3336. ext4_handle_sync(handle);
  3337. err = ext4_handle_dirty_metadata(handle, NULL,
  3338. EXT4_SB(sb)->s_sbh);
  3339. }
  3340. }
  3341. raw_inode->i_generation = cpu_to_le32(inode->i_generation);
  3342. if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
  3343. if (old_valid_dev(inode->i_rdev)) {
  3344. raw_inode->i_block[0] =
  3345. cpu_to_le32(old_encode_dev(inode->i_rdev));
  3346. raw_inode->i_block[1] = 0;
  3347. } else {
  3348. raw_inode->i_block[0] = 0;
  3349. raw_inode->i_block[1] =
  3350. cpu_to_le32(new_encode_dev(inode->i_rdev));
  3351. raw_inode->i_block[2] = 0;
  3352. }
  3353. } else
  3354. for (block = 0; block < EXT4_N_BLOCKS; block++)
  3355. raw_inode->i_block[block] = ei->i_data[block];
  3356. raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
  3357. if (ei->i_extra_isize) {
  3358. if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
  3359. raw_inode->i_version_hi =
  3360. cpu_to_le32(inode->i_version >> 32);
  3361. raw_inode->i_extra_isize = cpu_to_le16(ei->i_extra_isize);
  3362. }
  3363. BUFFER_TRACE(bh, "call ext4_handle_dirty_metadata");
  3364. rc = ext4_handle_dirty_metadata(handle, NULL, bh);
  3365. if (!err)
  3366. err = rc;
  3367. ext4_clear_inode_state(inode, EXT4_STATE_NEW);
  3368. ext4_update_inode_fsync_trans(handle, inode, 0);
  3369. out_brelse:
  3370. brelse(bh);
  3371. ext4_std_error(inode->i_sb, err);
  3372. return err;
  3373. }
  3374. /*
  3375. * ext4_write_inode()
  3376. *
  3377. * We are called from a few places:
  3378. *
  3379. * - Within generic_file_write() for O_SYNC files.
  3380. * Here, there will be no transaction running. We wait for any running
  3381. * trasnaction to commit.
  3382. *
  3383. * - Within sys_sync(), kupdate and such.
  3384. * We wait on commit, if tol to.
  3385. *
  3386. * - Within prune_icache() (PF_MEMALLOC == true)
  3387. * Here we simply return. We can't afford to block kswapd on the
  3388. * journal commit.
  3389. *
  3390. * In all cases it is actually safe for us to return without doing anything,
  3391. * because the inode has been copied into a raw inode buffer in
  3392. * ext4_mark_inode_dirty(). This is a correctness thing for O_SYNC and for
  3393. * knfsd.
  3394. *
  3395. * Note that we are absolutely dependent upon all inode dirtiers doing the
  3396. * right thing: they *must* call mark_inode_dirty() after dirtying info in
  3397. * which we are interested.
  3398. *
  3399. * It would be a bug for them to not do this. The code:
  3400. *
  3401. * mark_inode_dirty(inode)
  3402. * stuff();
  3403. * inode->i_size = expr;
  3404. *
  3405. * is in error because a kswapd-driven write_inode() could occur while
  3406. * `stuff()' is running, and the new i_size will be lost. Plus the inode
  3407. * will no longer be on the superblock's dirty inode list.
  3408. */
  3409. int ext4_write_inode(struct inode *inode, struct writeback_control *wbc)
  3410. {
  3411. int err;
  3412. if (current->flags & PF_MEMALLOC)
  3413. return 0;
  3414. if (EXT4_SB(inode->i_sb)->s_journal) {
  3415. if (ext4_journal_current_handle()) {
  3416. jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
  3417. dump_stack();
  3418. return -EIO;
  3419. }
  3420. if (wbc->sync_mode != WB_SYNC_ALL)
  3421. return 0;
  3422. err = ext4_force_commit(inode->i_sb);
  3423. } else {
  3424. struct ext4_iloc iloc;
  3425. err = __ext4_get_inode_loc(inode, &iloc, 0);
  3426. if (err)
  3427. return err;
  3428. if (wbc->sync_mode == WB_SYNC_ALL)
  3429. sync_dirty_buffer(iloc.bh);
  3430. if (buffer_req(iloc.bh) && !buffer_uptodate(iloc.bh)) {
  3431. EXT4_ERROR_INODE_BLOCK(inode, iloc.bh->b_blocknr,
  3432. "IO error syncing inode");
  3433. err = -EIO;
  3434. }
  3435. brelse(iloc.bh);
  3436. }
  3437. return err;
  3438. }
  3439. /*
  3440. * ext4_setattr()
  3441. *
  3442. * Called from notify_change.
  3443. *
  3444. * We want to trap VFS attempts to truncate the file as soon as
  3445. * possible. In particular, we want to make sure that when the VFS
  3446. * shrinks i_size, we put the inode on the orphan list and modify
  3447. * i_disksize immediately, so that during the subsequent flushing of
  3448. * dirty pages and freeing of disk blocks, we can guarantee that any
  3449. * commit will leave the blocks being flushed in an unused state on
  3450. * disk. (On recovery, the inode will get truncated and the blocks will
  3451. * be freed, so we have a strong guarantee that no future commit will
  3452. * leave these blocks visible to the user.)
  3453. *
  3454. * Another thing we have to assure is that if we are in ordered mode
  3455. * and inode is still attached to the committing transaction, we must
  3456. * we start writeout of all the dirty pages which are being truncated.
  3457. * This way we are sure that all the data written in the previous
  3458. * transaction are already on disk (truncate waits for pages under
  3459. * writeback).
  3460. *
  3461. * Called with inode->i_mutex down.
  3462. */
  3463. int ext4_setattr(struct dentry *dentry, struct iattr *attr)
  3464. {
  3465. struct inode *inode = dentry->d_inode;
  3466. int error, rc = 0;
  3467. int orphan = 0;
  3468. const unsigned int ia_valid = attr->ia_valid;
  3469. error = inode_change_ok(inode, attr);
  3470. if (error)
  3471. return error;
  3472. if (is_quota_modification(inode, attr))
  3473. dquot_initialize(inode);
  3474. if ((ia_valid & ATTR_UID && attr->ia_uid != inode->i_uid) ||
  3475. (ia_valid & ATTR_GID && attr->ia_gid != inode->i_gid)) {
  3476. handle_t *handle;
  3477. /* (user+group)*(old+new) structure, inode write (sb,
  3478. * inode block, ? - but truncate inode update has it) */
  3479. handle = ext4_journal_start(inode, (EXT4_MAXQUOTAS_INIT_BLOCKS(inode->i_sb)+
  3480. EXT4_MAXQUOTAS_DEL_BLOCKS(inode->i_sb))+3);
  3481. if (IS_ERR(handle)) {
  3482. error = PTR_ERR(handle);
  3483. goto err_out;
  3484. }
  3485. error = dquot_transfer(inode, attr);
  3486. if (error) {
  3487. ext4_journal_stop(handle);
  3488. return error;
  3489. }
  3490. /* Update corresponding info in inode so that everything is in
  3491. * one transaction */
  3492. if (attr->ia_valid & ATTR_UID)
  3493. inode->i_uid = attr->ia_uid;
  3494. if (attr->ia_valid & ATTR_GID)
  3495. inode->i_gid = attr->ia_gid;
  3496. error = ext4_mark_inode_dirty(handle, inode);
  3497. ext4_journal_stop(handle);
  3498. }
  3499. if (attr->ia_valid & ATTR_SIZE) {
  3500. inode_dio_wait(inode);
  3501. if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS))) {
  3502. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  3503. if (attr->ia_size > sbi->s_bitmap_maxbytes)
  3504. return -EFBIG;
  3505. }
  3506. }
  3507. if (S_ISREG(inode->i_mode) &&
  3508. attr->ia_valid & ATTR_SIZE &&
  3509. (attr->ia_size < inode->i_size)) {
  3510. handle_t *handle;
  3511. handle = ext4_journal_start(inode, 3);
  3512. if (IS_ERR(handle)) {
  3513. error = PTR_ERR(handle);
  3514. goto err_out;
  3515. }
  3516. if (ext4_handle_valid(handle)) {
  3517. error = ext4_orphan_add(handle, inode);
  3518. orphan = 1;
  3519. }
  3520. EXT4_I(inode)->i_disksize = attr->ia_size;
  3521. rc = ext4_mark_inode_dirty(handle, inode);
  3522. if (!error)
  3523. error = rc;
  3524. ext4_journal_stop(handle);
  3525. if (ext4_should_order_data(inode)) {
  3526. error = ext4_begin_ordered_truncate(inode,
  3527. attr->ia_size);
  3528. if (error) {
  3529. /* Do as much error cleanup as possible */
  3530. handle = ext4_journal_start(inode, 3);
  3531. if (IS_ERR(handle)) {
  3532. ext4_orphan_del(NULL, inode);
  3533. goto err_out;
  3534. }
  3535. ext4_orphan_del(handle, inode);
  3536. orphan = 0;
  3537. ext4_journal_stop(handle);
  3538. goto err_out;
  3539. }
  3540. }
  3541. }
  3542. if (attr->ia_valid & ATTR_SIZE) {
  3543. if (attr->ia_size != i_size_read(inode)) {
  3544. truncate_setsize(inode, attr->ia_size);
  3545. ext4_truncate(inode);
  3546. } else if (ext4_test_inode_flag(inode, EXT4_INODE_EOFBLOCKS))
  3547. ext4_truncate(inode);
  3548. }
  3549. if (!rc) {
  3550. setattr_copy(inode, attr);
  3551. mark_inode_dirty(inode);
  3552. }
  3553. /*
  3554. * If the call to ext4_truncate failed to get a transaction handle at
  3555. * all, we need to clean up the in-core orphan list manually.
  3556. */
  3557. if (orphan && inode->i_nlink)
  3558. ext4_orphan_del(NULL, inode);
  3559. if (!rc && (ia_valid & ATTR_MODE))
  3560. rc = ext4_acl_chmod(inode);
  3561. err_out:
  3562. ext4_std_error(inode->i_sb, error);
  3563. if (!error)
  3564. error = rc;
  3565. return error;
  3566. }
  3567. int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
  3568. struct kstat *stat)
  3569. {
  3570. struct inode *inode;
  3571. unsigned long delalloc_blocks;
  3572. inode = dentry->d_inode;
  3573. generic_fillattr(inode, stat);
  3574. /*
  3575. * We can't update i_blocks if the block allocation is delayed
  3576. * otherwise in the case of system crash before the real block
  3577. * allocation is done, we will have i_blocks inconsistent with
  3578. * on-disk file blocks.
  3579. * We always keep i_blocks updated together with real
  3580. * allocation. But to not confuse with user, stat
  3581. * will return the blocks that include the delayed allocation
  3582. * blocks for this file.
  3583. */
  3584. delalloc_blocks = EXT4_I(inode)->i_reserved_data_blocks;
  3585. stat->blocks += (delalloc_blocks << inode->i_sb->s_blocksize_bits)>>9;
  3586. return 0;
  3587. }
  3588. static int ext4_index_trans_blocks(struct inode *inode, int nrblocks, int chunk)
  3589. {
  3590. if (!(ext4_test_inode_flag(inode, EXT4_INODE_EXTENTS)))
  3591. return ext4_ind_trans_blocks(inode, nrblocks, chunk);
  3592. return ext4_ext_index_trans_blocks(inode, nrblocks, chunk);
  3593. }
  3594. /*
  3595. * Account for index blocks, block groups bitmaps and block group
  3596. * descriptor blocks if modify datablocks and index blocks
  3597. * worse case, the indexs blocks spread over different block groups
  3598. *
  3599. * If datablocks are discontiguous, they are possible to spread over
  3600. * different block groups too. If they are contiuguous, with flexbg,
  3601. * they could still across block group boundary.
  3602. *
  3603. * Also account for superblock, inode, quota and xattr blocks
  3604. */
  3605. static int ext4_meta_trans_blocks(struct inode *inode, int nrblocks, int chunk)
  3606. {
  3607. ext4_group_t groups, ngroups = ext4_get_groups_count(inode->i_sb);
  3608. int gdpblocks;
  3609. int idxblocks;
  3610. int ret = 0;
  3611. /*
  3612. * How many index blocks need to touch to modify nrblocks?
  3613. * The "Chunk" flag indicating whether the nrblocks is
  3614. * physically contiguous on disk
  3615. *
  3616. * For Direct IO and fallocate, they calls get_block to allocate
  3617. * one single extent at a time, so they could set the "Chunk" flag
  3618. */
  3619. idxblocks = ext4_index_trans_blocks(inode, nrblocks, chunk);
  3620. ret = idxblocks;
  3621. /*
  3622. * Now let's see how many group bitmaps and group descriptors need
  3623. * to account
  3624. */
  3625. groups = idxblocks;
  3626. if (chunk)
  3627. groups += 1;
  3628. else
  3629. groups += nrblocks;
  3630. gdpblocks = groups;
  3631. if (groups > ngroups)
  3632. groups = ngroups;
  3633. if (groups > EXT4_SB(inode->i_sb)->s_gdb_count)
  3634. gdpblocks = EXT4_SB(inode->i_sb)->s_gdb_count;
  3635. /* bitmaps and block group descriptor blocks */
  3636. ret += groups + gdpblocks;
  3637. /* Blocks for super block, inode, quota and xattr blocks */
  3638. ret += EXT4_META_TRANS_BLOCKS(inode->i_sb);
  3639. return ret;
  3640. }
  3641. /*
  3642. * Calculate the total number of credits to reserve to fit
  3643. * the modification of a single pages into a single transaction,
  3644. * which may include multiple chunks of block allocations.
  3645. *
  3646. * This could be called via ext4_write_begin()
  3647. *
  3648. * We need to consider the worse case, when
  3649. * one new block per extent.
  3650. */
  3651. int ext4_writepage_trans_blocks(struct inode *inode)
  3652. {
  3653. int bpp = ext4_journal_blocks_per_page(inode);
  3654. int ret;
  3655. ret = ext4_meta_trans_blocks(inode, bpp, 0);
  3656. /* Account for data blocks for journalled mode */
  3657. if (ext4_should_journal_data(inode))
  3658. ret += bpp;
  3659. return ret;
  3660. }
  3661. /*
  3662. * Calculate the journal credits for a chunk of data modification.
  3663. *
  3664. * This is called from DIO, fallocate or whoever calling
  3665. * ext4_map_blocks() to map/allocate a chunk of contiguous disk blocks.
  3666. *
  3667. * journal buffers for data blocks are not included here, as DIO
  3668. * and fallocate do no need to journal data buffers.
  3669. */
  3670. int ext4_chunk_trans_blocks(struct inode *inode, int nrblocks)
  3671. {
  3672. return ext4_meta_trans_blocks(inode, nrblocks, 1);
  3673. }
  3674. /*
  3675. * The caller must have previously called ext4_reserve_inode_write().
  3676. * Give this, we know that the caller already has write access to iloc->bh.
  3677. */
  3678. int ext4_mark_iloc_dirty(handle_t *handle,
  3679. struct inode *inode, struct ext4_iloc *iloc)
  3680. {
  3681. int err = 0;
  3682. if (test_opt(inode->i_sb, I_VERSION))
  3683. inode_inc_iversion(inode);
  3684. /* the do_update_inode consumes one bh->b_count */
  3685. get_bh(iloc->bh);
  3686. /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
  3687. err = ext4_do_update_inode(handle, inode, iloc);
  3688. put_bh(iloc->bh);
  3689. return err;
  3690. }
  3691. /*
  3692. * On success, We end up with an outstanding reference count against
  3693. * iloc->bh. This _must_ be cleaned up later.
  3694. */
  3695. int
  3696. ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
  3697. struct ext4_iloc *iloc)
  3698. {
  3699. int err;
  3700. err = ext4_get_inode_loc(inode, iloc);
  3701. if (!err) {
  3702. BUFFER_TRACE(iloc->bh, "get_write_access");
  3703. err = ext4_journal_get_write_access(handle, iloc->bh);
  3704. if (err) {
  3705. brelse(iloc->bh);
  3706. iloc->bh = NULL;
  3707. }
  3708. }
  3709. ext4_std_error(inode->i_sb, err);
  3710. return err;
  3711. }
  3712. /*
  3713. * Expand an inode by new_extra_isize bytes.
  3714. * Returns 0 on success or negative error number on failure.
  3715. */
  3716. static int ext4_expand_extra_isize(struct inode *inode,
  3717. unsigned int new_extra_isize,
  3718. struct ext4_iloc iloc,
  3719. handle_t *handle)
  3720. {
  3721. struct ext4_inode *raw_inode;
  3722. struct ext4_xattr_ibody_header *header;
  3723. if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
  3724. return 0;
  3725. raw_inode = ext4_raw_inode(&iloc);
  3726. header = IHDR(inode, raw_inode);
  3727. /* No extended attributes present */
  3728. if (!ext4_test_inode_state(inode, EXT4_STATE_XATTR) ||
  3729. header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
  3730. memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE, 0,
  3731. new_extra_isize);
  3732. EXT4_I(inode)->i_extra_isize = new_extra_isize;
  3733. return 0;
  3734. }
  3735. /* try to expand with EAs present */
  3736. return ext4_expand_extra_isize_ea(inode, new_extra_isize,
  3737. raw_inode, handle);
  3738. }
  3739. /*
  3740. * What we do here is to mark the in-core inode as clean with respect to inode
  3741. * dirtiness (it may still be data-dirty).
  3742. * This means that the in-core inode may be reaped by prune_icache
  3743. * without having to perform any I/O. This is a very good thing,
  3744. * because *any* task may call prune_icache - even ones which
  3745. * have a transaction open against a different journal.
  3746. *
  3747. * Is this cheating? Not really. Sure, we haven't written the
  3748. * inode out, but prune_icache isn't a user-visible syncing function.
  3749. * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
  3750. * we start and wait on commits.
  3751. *
  3752. * Is this efficient/effective? Well, we're being nice to the system
  3753. * by cleaning up our inodes proactively so they can be reaped
  3754. * without I/O. But we are potentially leaving up to five seconds'
  3755. * worth of inodes floating about which prune_icache wants us to
  3756. * write out. One way to fix that would be to get prune_icache()
  3757. * to do a write_super() to free up some memory. It has the desired
  3758. * effect.
  3759. */
  3760. int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
  3761. {
  3762. struct ext4_iloc iloc;
  3763. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  3764. static unsigned int mnt_count;
  3765. int err, ret;
  3766. might_sleep();
  3767. trace_ext4_mark_inode_dirty(inode, _RET_IP_);
  3768. err = ext4_reserve_inode_write(handle, inode, &iloc);
  3769. if (ext4_handle_valid(handle) &&
  3770. EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
  3771. !ext4_test_inode_state(inode, EXT4_STATE_NO_EXPAND)) {
  3772. /*
  3773. * We need extra buffer credits since we may write into EA block
  3774. * with this same handle. If journal_extend fails, then it will
  3775. * only result in a minor loss of functionality for that inode.
  3776. * If this is felt to be critical, then e2fsck should be run to
  3777. * force a large enough s_min_extra_isize.
  3778. */
  3779. if ((jbd2_journal_extend(handle,
  3780. EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) {
  3781. ret = ext4_expand_extra_isize(inode,
  3782. sbi->s_want_extra_isize,
  3783. iloc, handle);
  3784. if (ret) {
  3785. ext4_set_inode_state(inode,
  3786. EXT4_STATE_NO_EXPAND);
  3787. if (mnt_count !=
  3788. le16_to_cpu(sbi->s_es->s_mnt_count)) {
  3789. ext4_warning(inode->i_sb,
  3790. "Unable to expand inode %lu. Delete"
  3791. " some EAs or run e2fsck.",
  3792. inode->i_ino);
  3793. mnt_count =
  3794. le16_to_cpu(sbi->s_es->s_mnt_count);
  3795. }
  3796. }
  3797. }
  3798. }
  3799. if (!err)
  3800. err = ext4_mark_iloc_dirty(handle, inode, &iloc);
  3801. return err;
  3802. }
  3803. /*
  3804. * ext4_dirty_inode() is called from __mark_inode_dirty()
  3805. *
  3806. * We're really interested in the case where a file is being extended.
  3807. * i_size has been changed by generic_commit_write() and we thus need
  3808. * to include the updated inode in the current transaction.
  3809. *
  3810. * Also, dquot_alloc_block() will always dirty the inode when blocks
  3811. * are allocated to the file.
  3812. *
  3813. * If the inode is marked synchronous, we don't honour that here - doing
  3814. * so would cause a commit on atime updates, which we don't bother doing.
  3815. * We handle synchronous inodes at the highest possible level.
  3816. */
  3817. void ext4_dirty_inode(struct inode *inode, int flags)
  3818. {
  3819. handle_t *handle;
  3820. handle = ext4_journal_start(inode, 2);
  3821. if (IS_ERR(handle))
  3822. goto out;
  3823. ext4_mark_inode_dirty(handle, inode);
  3824. ext4_journal_stop(handle);
  3825. out:
  3826. return;
  3827. }
  3828. #if 0
  3829. /*
  3830. * Bind an inode's backing buffer_head into this transaction, to prevent
  3831. * it from being flushed to disk early. Unlike
  3832. * ext4_reserve_inode_write, this leaves behind no bh reference and
  3833. * returns no iloc structure, so the caller needs to repeat the iloc
  3834. * lookup to mark the inode dirty later.
  3835. */
  3836. static int ext4_pin_inode(handle_t *handle, struct inode *inode)
  3837. {
  3838. struct ext4_iloc iloc;
  3839. int err = 0;
  3840. if (handle) {
  3841. err = ext4_get_inode_loc(inode, &iloc);
  3842. if (!err) {
  3843. BUFFER_TRACE(iloc.bh, "get_write_access");
  3844. err = jbd2_journal_get_write_access(handle, iloc.bh);
  3845. if (!err)
  3846. err = ext4_handle_dirty_metadata(handle,
  3847. NULL,
  3848. iloc.bh);
  3849. brelse(iloc.bh);
  3850. }
  3851. }
  3852. ext4_std_error(inode->i_sb, err);
  3853. return err;
  3854. }
  3855. #endif
  3856. int ext4_change_inode_journal_flag(struct inode *inode, int val)
  3857. {
  3858. journal_t *journal;
  3859. handle_t *handle;
  3860. int err;
  3861. /*
  3862. * We have to be very careful here: changing a data block's
  3863. * journaling status dynamically is dangerous. If we write a
  3864. * data block to the journal, change the status and then delete
  3865. * that block, we risk forgetting to revoke the old log record
  3866. * from the journal and so a subsequent replay can corrupt data.
  3867. * So, first we make sure that the journal is empty and that
  3868. * nobody is changing anything.
  3869. */
  3870. journal = EXT4_JOURNAL(inode);
  3871. if (!journal)
  3872. return 0;
  3873. if (is_journal_aborted(journal))
  3874. return -EROFS;
  3875. jbd2_journal_lock_updates(journal);
  3876. jbd2_journal_flush(journal);
  3877. /*
  3878. * OK, there are no updates running now, and all cached data is
  3879. * synced to disk. We are now in a completely consistent state
  3880. * which doesn't have anything in the journal, and we know that
  3881. * no filesystem updates are running, so it is safe to modify
  3882. * the inode's in-core data-journaling state flag now.
  3883. */
  3884. if (val)
  3885. ext4_set_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
  3886. else
  3887. ext4_clear_inode_flag(inode, EXT4_INODE_JOURNAL_DATA);
  3888. ext4_set_aops(inode);
  3889. jbd2_journal_unlock_updates(journal);
  3890. /* Finally we can mark the inode as dirty. */
  3891. handle = ext4_journal_start(inode, 1);
  3892. if (IS_ERR(handle))
  3893. return PTR_ERR(handle);
  3894. err = ext4_mark_inode_dirty(handle, inode);
  3895. ext4_handle_sync(handle);
  3896. ext4_journal_stop(handle);
  3897. ext4_std_error(inode->i_sb, err);
  3898. return err;
  3899. }
  3900. static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
  3901. {
  3902. return !buffer_mapped(bh);
  3903. }
  3904. int ext4_page_mkwrite(struct vm_area_struct *vma, struct vm_fault *vmf)
  3905. {
  3906. struct page *page = vmf->page;
  3907. loff_t size;
  3908. unsigned long len;
  3909. int ret;
  3910. struct file *file = vma->vm_file;
  3911. struct inode *inode = file->f_path.dentry->d_inode;
  3912. struct address_space *mapping = inode->i_mapping;
  3913. handle_t *handle;
  3914. get_block_t *get_block;
  3915. int retries = 0;
  3916. /*
  3917. * This check is racy but catches the common case. We rely on
  3918. * __block_page_mkwrite() to do a reliable check.
  3919. */
  3920. vfs_check_frozen(inode->i_sb, SB_FREEZE_WRITE);
  3921. /* Delalloc case is easy... */
  3922. if (test_opt(inode->i_sb, DELALLOC) &&
  3923. !ext4_should_journal_data(inode) &&
  3924. !ext4_nonda_switch(inode->i_sb)) {
  3925. do {
  3926. ret = __block_page_mkwrite(vma, vmf,
  3927. ext4_da_get_block_prep);
  3928. } while (ret == -ENOSPC &&
  3929. ext4_should_retry_alloc(inode->i_sb, &retries));
  3930. goto out_ret;
  3931. }
  3932. lock_page(page);
  3933. size = i_size_read(inode);
  3934. /* Page got truncated from under us? */
  3935. if (page->mapping != mapping || page_offset(page) > size) {
  3936. unlock_page(page);
  3937. ret = VM_FAULT_NOPAGE;
  3938. goto out;
  3939. }
  3940. if (page->index == size >> PAGE_CACHE_SHIFT)
  3941. len = size & ~PAGE_CACHE_MASK;
  3942. else
  3943. len = PAGE_CACHE_SIZE;
  3944. /*
  3945. * Return if we have all the buffers mapped. This avoids the need to do
  3946. * journal_start/journal_stop which can block and take a long time
  3947. */
  3948. if (page_has_buffers(page)) {
  3949. if (!walk_page_buffers(NULL, page_buffers(page), 0, len, NULL,
  3950. ext4_bh_unmapped)) {
  3951. /* Wait so that we don't change page under IO */
  3952. wait_on_page_writeback(page);
  3953. ret = VM_FAULT_LOCKED;
  3954. goto out;
  3955. }
  3956. }
  3957. unlock_page(page);
  3958. /* OK, we need to fill the hole... */
  3959. if (ext4_should_dioread_nolock(inode))
  3960. get_block = ext4_get_block_write;
  3961. else
  3962. get_block = ext4_get_block;
  3963. retry_alloc:
  3964. handle = ext4_journal_start(inode, ext4_writepage_trans_blocks(inode));
  3965. if (IS_ERR(handle)) {
  3966. ret = VM_FAULT_SIGBUS;
  3967. goto out;
  3968. }
  3969. ret = __block_page_mkwrite(vma, vmf, get_block);
  3970. if (!ret && ext4_should_journal_data(inode)) {
  3971. if (walk_page_buffers(handle, page_buffers(page), 0,
  3972. PAGE_CACHE_SIZE, NULL, do_journal_get_write_access)) {
  3973. unlock_page(page);
  3974. ret = VM_FAULT_SIGBUS;
  3975. goto out;
  3976. }
  3977. ext4_set_inode_state(inode, EXT4_STATE_JDATA);
  3978. }
  3979. ext4_journal_stop(handle);
  3980. if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
  3981. goto retry_alloc;
  3982. out_ret:
  3983. ret = block_page_mkwrite_return(ret);
  3984. out:
  3985. return ret;
  3986. }