inode.c 132 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647
  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. * Goal-directed block allocation by Stephen Tweedie
  16. * (sct@redhat.com), 1993, 1998
  17. * Big-endian to little-endian byte-swapping/bitmaps by
  18. * David S. Miller (davem@caip.rutgers.edu), 1995
  19. * 64-bit file support on 64-bit platforms by Jakub Jelinek
  20. * (jj@sunsite.ms.mff.cuni.cz)
  21. *
  22. * Assorted race fixes, rewrite of ext4_get_block() by Al Viro, 2000
  23. */
  24. #include <linux/module.h>
  25. #include <linux/fs.h>
  26. #include <linux/time.h>
  27. #include <linux/jbd2.h>
  28. #include <linux/highuid.h>
  29. #include <linux/pagemap.h>
  30. #include <linux/quotaops.h>
  31. #include <linux/string.h>
  32. #include <linux/buffer_head.h>
  33. #include <linux/writeback.h>
  34. #include <linux/pagevec.h>
  35. #include <linux/mpage.h>
  36. #include <linux/uio.h>
  37. #include <linux/bio.h>
  38. #include "ext4_jbd2.h"
  39. #include "xattr.h"
  40. #include "acl.h"
  41. #include "ext4_extents.h"
  42. static inline int ext4_begin_ordered_truncate(struct inode *inode,
  43. loff_t new_size)
  44. {
  45. return jbd2_journal_begin_ordered_truncate(&EXT4_I(inode)->jinode,
  46. new_size);
  47. }
  48. static void ext4_invalidatepage(struct page *page, unsigned long offset);
  49. /*
  50. * Test whether an inode is a fast symlink.
  51. */
  52. static int ext4_inode_is_fast_symlink(struct inode *inode)
  53. {
  54. int ea_blocks = EXT4_I(inode)->i_file_acl ?
  55. (inode->i_sb->s_blocksize >> 9) : 0;
  56. return (S_ISLNK(inode->i_mode) && inode->i_blocks - ea_blocks == 0);
  57. }
  58. /*
  59. * The ext4 forget function must perform a revoke if we are freeing data
  60. * which has been journaled. Metadata (eg. indirect blocks) must be
  61. * revoked in all cases.
  62. *
  63. * "bh" may be NULL: a metadata block may have been freed from memory
  64. * but there may still be a record of it in the journal, and that record
  65. * still needs to be revoked.
  66. */
  67. int ext4_forget(handle_t *handle, int is_metadata, struct inode *inode,
  68. struct buffer_head *bh, ext4_fsblk_t blocknr)
  69. {
  70. int err;
  71. might_sleep();
  72. BUFFER_TRACE(bh, "enter");
  73. jbd_debug(4, "forgetting bh %p: is_metadata = %d, mode %o, "
  74. "data mode %lx\n",
  75. bh, is_metadata, inode->i_mode,
  76. test_opt(inode->i_sb, DATA_FLAGS));
  77. /* Never use the revoke function if we are doing full data
  78. * journaling: there is no need to, and a V1 superblock won't
  79. * support it. Otherwise, only skip the revoke on un-journaled
  80. * data blocks. */
  81. if (test_opt(inode->i_sb, DATA_FLAGS) == EXT4_MOUNT_JOURNAL_DATA ||
  82. (!is_metadata && !ext4_should_journal_data(inode))) {
  83. if (bh) {
  84. BUFFER_TRACE(bh, "call jbd2_journal_forget");
  85. return ext4_journal_forget(handle, bh);
  86. }
  87. return 0;
  88. }
  89. /*
  90. * data!=journal && (is_metadata || should_journal_data(inode))
  91. */
  92. BUFFER_TRACE(bh, "call ext4_journal_revoke");
  93. err = ext4_journal_revoke(handle, blocknr, bh);
  94. if (err)
  95. ext4_abort(inode->i_sb, __func__,
  96. "error %d when attempting revoke", err);
  97. BUFFER_TRACE(bh, "exit");
  98. return err;
  99. }
  100. /*
  101. * Work out how many blocks we need to proceed with the next chunk of a
  102. * truncate transaction.
  103. */
  104. static unsigned long blocks_for_truncate(struct inode *inode)
  105. {
  106. ext4_lblk_t needed;
  107. needed = inode->i_blocks >> (inode->i_sb->s_blocksize_bits - 9);
  108. /* Give ourselves just enough room to cope with inodes in which
  109. * i_blocks is corrupt: we've seen disk corruptions in the past
  110. * which resulted in random data in an inode which looked enough
  111. * like a regular file for ext4 to try to delete it. Things
  112. * will go a bit crazy if that happens, but at least we should
  113. * try not to panic the whole kernel. */
  114. if (needed < 2)
  115. needed = 2;
  116. /* But we need to bound the transaction so we don't overflow the
  117. * journal. */
  118. if (needed > EXT4_MAX_TRANS_DATA)
  119. needed = EXT4_MAX_TRANS_DATA;
  120. return EXT4_DATA_TRANS_BLOCKS(inode->i_sb) + needed;
  121. }
  122. /*
  123. * Truncate transactions can be complex and absolutely huge. So we need to
  124. * be able to restart the transaction at a conventient checkpoint to make
  125. * sure we don't overflow the journal.
  126. *
  127. * start_transaction gets us a new handle for a truncate transaction,
  128. * and extend_transaction tries to extend the existing one a bit. If
  129. * extend fails, we need to propagate the failure up and restart the
  130. * transaction in the top-level truncate loop. --sct
  131. */
  132. static handle_t *start_transaction(struct inode *inode)
  133. {
  134. handle_t *result;
  135. result = ext4_journal_start(inode, blocks_for_truncate(inode));
  136. if (!IS_ERR(result))
  137. return result;
  138. ext4_std_error(inode->i_sb, PTR_ERR(result));
  139. return result;
  140. }
  141. /*
  142. * Try to extend this transaction for the purposes of truncation.
  143. *
  144. * Returns 0 if we managed to create more room. If we can't create more
  145. * room, and the transaction must be restarted we return 1.
  146. */
  147. static int try_to_extend_transaction(handle_t *handle, struct inode *inode)
  148. {
  149. if (handle->h_buffer_credits > EXT4_RESERVE_TRANS_BLOCKS)
  150. return 0;
  151. if (!ext4_journal_extend(handle, blocks_for_truncate(inode)))
  152. return 0;
  153. return 1;
  154. }
  155. /*
  156. * Restart the transaction associated with *handle. This does a commit,
  157. * so before we call here everything must be consistently dirtied against
  158. * this transaction.
  159. */
  160. static int ext4_journal_test_restart(handle_t *handle, struct inode *inode)
  161. {
  162. jbd_debug(2, "restarting handle %p\n", handle);
  163. return ext4_journal_restart(handle, blocks_for_truncate(inode));
  164. }
  165. /*
  166. * Called at the last iput() if i_nlink is zero.
  167. */
  168. void ext4_delete_inode (struct inode * inode)
  169. {
  170. handle_t *handle;
  171. if (ext4_should_order_data(inode))
  172. ext4_begin_ordered_truncate(inode, 0);
  173. truncate_inode_pages(&inode->i_data, 0);
  174. if (is_bad_inode(inode))
  175. goto no_delete;
  176. handle = start_transaction(inode);
  177. if (IS_ERR(handle)) {
  178. /*
  179. * If we're going to skip the normal cleanup, we still need to
  180. * make sure that the in-core orphan linked list is properly
  181. * cleaned up.
  182. */
  183. ext4_orphan_del(NULL, inode);
  184. goto no_delete;
  185. }
  186. if (IS_SYNC(inode))
  187. handle->h_sync = 1;
  188. inode->i_size = 0;
  189. if (inode->i_blocks)
  190. ext4_truncate(inode);
  191. /*
  192. * Kill off the orphan record which ext4_truncate created.
  193. * AKPM: I think this can be inside the above `if'.
  194. * Note that ext4_orphan_del() has to be able to cope with the
  195. * deletion of a non-existent orphan - this is because we don't
  196. * know if ext4_truncate() actually created an orphan record.
  197. * (Well, we could do this if we need to, but heck - it works)
  198. */
  199. ext4_orphan_del(handle, inode);
  200. EXT4_I(inode)->i_dtime = get_seconds();
  201. /*
  202. * One subtle ordering requirement: if anything has gone wrong
  203. * (transaction abort, IO errors, whatever), then we can still
  204. * do these next steps (the fs will already have been marked as
  205. * having errors), but we can't free the inode if the mark_dirty
  206. * fails.
  207. */
  208. if (ext4_mark_inode_dirty(handle, inode))
  209. /* If that failed, just do the required in-core inode clear. */
  210. clear_inode(inode);
  211. else
  212. ext4_free_inode(handle, inode);
  213. ext4_journal_stop(handle);
  214. return;
  215. no_delete:
  216. clear_inode(inode); /* We must guarantee clearing of inode... */
  217. }
  218. typedef struct {
  219. __le32 *p;
  220. __le32 key;
  221. struct buffer_head *bh;
  222. } Indirect;
  223. static inline void add_chain(Indirect *p, struct buffer_head *bh, __le32 *v)
  224. {
  225. p->key = *(p->p = v);
  226. p->bh = bh;
  227. }
  228. /**
  229. * ext4_block_to_path - parse the block number into array of offsets
  230. * @inode: inode in question (we are only interested in its superblock)
  231. * @i_block: block number to be parsed
  232. * @offsets: array to store the offsets in
  233. * @boundary: set this non-zero if the referred-to block is likely to be
  234. * followed (on disk) by an indirect block.
  235. *
  236. * To store the locations of file's data ext4 uses a data structure common
  237. * for UNIX filesystems - tree of pointers anchored in the inode, with
  238. * data blocks at leaves and indirect blocks in intermediate nodes.
  239. * This function translates the block number into path in that tree -
  240. * return value is the path length and @offsets[n] is the offset of
  241. * pointer to (n+1)th node in the nth one. If @block is out of range
  242. * (negative or too large) warning is printed and zero returned.
  243. *
  244. * Note: function doesn't find node addresses, so no IO is needed. All
  245. * we need to know is the capacity of indirect blocks (taken from the
  246. * inode->i_sb).
  247. */
  248. /*
  249. * Portability note: the last comparison (check that we fit into triple
  250. * indirect block) is spelled differently, because otherwise on an
  251. * architecture with 32-bit longs and 8Kb pages we might get into trouble
  252. * if our filesystem had 8Kb blocks. We might use long long, but that would
  253. * kill us on x86. Oh, well, at least the sign propagation does not matter -
  254. * i_block would have to be negative in the very beginning, so we would not
  255. * get there at all.
  256. */
  257. static int ext4_block_to_path(struct inode *inode,
  258. ext4_lblk_t i_block,
  259. ext4_lblk_t offsets[4], int *boundary)
  260. {
  261. int ptrs = EXT4_ADDR_PER_BLOCK(inode->i_sb);
  262. int ptrs_bits = EXT4_ADDR_PER_BLOCK_BITS(inode->i_sb);
  263. const long direct_blocks = EXT4_NDIR_BLOCKS,
  264. indirect_blocks = ptrs,
  265. double_blocks = (1 << (ptrs_bits * 2));
  266. int n = 0;
  267. int final = 0;
  268. if (i_block < 0) {
  269. ext4_warning (inode->i_sb, "ext4_block_to_path", "block < 0");
  270. } else if (i_block < direct_blocks) {
  271. offsets[n++] = i_block;
  272. final = direct_blocks;
  273. } else if ( (i_block -= direct_blocks) < indirect_blocks) {
  274. offsets[n++] = EXT4_IND_BLOCK;
  275. offsets[n++] = i_block;
  276. final = ptrs;
  277. } else if ((i_block -= indirect_blocks) < double_blocks) {
  278. offsets[n++] = EXT4_DIND_BLOCK;
  279. offsets[n++] = i_block >> ptrs_bits;
  280. offsets[n++] = i_block & (ptrs - 1);
  281. final = ptrs;
  282. } else if (((i_block -= double_blocks) >> (ptrs_bits * 2)) < ptrs) {
  283. offsets[n++] = EXT4_TIND_BLOCK;
  284. offsets[n++] = i_block >> (ptrs_bits * 2);
  285. offsets[n++] = (i_block >> ptrs_bits) & (ptrs - 1);
  286. offsets[n++] = i_block & (ptrs - 1);
  287. final = ptrs;
  288. } else {
  289. ext4_warning(inode->i_sb, "ext4_block_to_path",
  290. "block %lu > max",
  291. i_block + direct_blocks +
  292. indirect_blocks + double_blocks);
  293. }
  294. if (boundary)
  295. *boundary = final - 1 - (i_block & (ptrs - 1));
  296. return n;
  297. }
  298. /**
  299. * ext4_get_branch - read the chain of indirect blocks leading to data
  300. * @inode: inode in question
  301. * @depth: depth of the chain (1 - direct pointer, etc.)
  302. * @offsets: offsets of pointers in inode/indirect blocks
  303. * @chain: place to store the result
  304. * @err: here we store the error value
  305. *
  306. * Function fills the array of triples <key, p, bh> and returns %NULL
  307. * if everything went OK or the pointer to the last filled triple
  308. * (incomplete one) otherwise. Upon the return chain[i].key contains
  309. * the number of (i+1)-th block in the chain (as it is stored in memory,
  310. * i.e. little-endian 32-bit), chain[i].p contains the address of that
  311. * number (it points into struct inode for i==0 and into the bh->b_data
  312. * for i>0) and chain[i].bh points to the buffer_head of i-th indirect
  313. * block for i>0 and NULL for i==0. In other words, it holds the block
  314. * numbers of the chain, addresses they were taken from (and where we can
  315. * verify that chain did not change) and buffer_heads hosting these
  316. * numbers.
  317. *
  318. * Function stops when it stumbles upon zero pointer (absent block)
  319. * (pointer to last triple returned, *@err == 0)
  320. * or when it gets an IO error reading an indirect block
  321. * (ditto, *@err == -EIO)
  322. * or when it reads all @depth-1 indirect blocks successfully and finds
  323. * the whole chain, all way to the data (returns %NULL, *err == 0).
  324. *
  325. * Need to be called with
  326. * down_read(&EXT4_I(inode)->i_data_sem)
  327. */
  328. static Indirect *ext4_get_branch(struct inode *inode, int depth,
  329. ext4_lblk_t *offsets,
  330. Indirect chain[4], int *err)
  331. {
  332. struct super_block *sb = inode->i_sb;
  333. Indirect *p = chain;
  334. struct buffer_head *bh;
  335. *err = 0;
  336. /* i_data is not going away, no lock needed */
  337. add_chain (chain, NULL, EXT4_I(inode)->i_data + *offsets);
  338. if (!p->key)
  339. goto no_block;
  340. while (--depth) {
  341. bh = sb_bread(sb, le32_to_cpu(p->key));
  342. if (!bh)
  343. goto failure;
  344. add_chain(++p, bh, (__le32*)bh->b_data + *++offsets);
  345. /* Reader: end */
  346. if (!p->key)
  347. goto no_block;
  348. }
  349. return NULL;
  350. failure:
  351. *err = -EIO;
  352. no_block:
  353. return p;
  354. }
  355. /**
  356. * ext4_find_near - find a place for allocation with sufficient locality
  357. * @inode: owner
  358. * @ind: descriptor of indirect block.
  359. *
  360. * This function returns the preferred place for block allocation.
  361. * It is used when heuristic for sequential allocation fails.
  362. * Rules are:
  363. * + if there is a block to the left of our position - allocate near it.
  364. * + if pointer will live in indirect block - allocate near that block.
  365. * + if pointer will live in inode - allocate in the same
  366. * cylinder group.
  367. *
  368. * In the latter case we colour the starting block by the callers PID to
  369. * prevent it from clashing with concurrent allocations for a different inode
  370. * in the same block group. The PID is used here so that functionally related
  371. * files will be close-by on-disk.
  372. *
  373. * Caller must make sure that @ind is valid and will stay that way.
  374. */
  375. static ext4_fsblk_t ext4_find_near(struct inode *inode, Indirect *ind)
  376. {
  377. struct ext4_inode_info *ei = EXT4_I(inode);
  378. __le32 *start = ind->bh ? (__le32*) ind->bh->b_data : ei->i_data;
  379. __le32 *p;
  380. ext4_fsblk_t bg_start;
  381. ext4_fsblk_t last_block;
  382. ext4_grpblk_t colour;
  383. /* Try to find previous block */
  384. for (p = ind->p - 1; p >= start; p--) {
  385. if (*p)
  386. return le32_to_cpu(*p);
  387. }
  388. /* No such thing, so let's try location of indirect block */
  389. if (ind->bh)
  390. return ind->bh->b_blocknr;
  391. /*
  392. * It is going to be referred to from the inode itself? OK, just put it
  393. * into the same cylinder group then.
  394. */
  395. bg_start = ext4_group_first_block_no(inode->i_sb, ei->i_block_group);
  396. last_block = ext4_blocks_count(EXT4_SB(inode->i_sb)->s_es) - 1;
  397. if (bg_start + EXT4_BLOCKS_PER_GROUP(inode->i_sb) <= last_block)
  398. colour = (current->pid % 16) *
  399. (EXT4_BLOCKS_PER_GROUP(inode->i_sb) / 16);
  400. else
  401. colour = (current->pid % 16) * ((last_block - bg_start) / 16);
  402. return bg_start + colour;
  403. }
  404. /**
  405. * ext4_find_goal - find a preferred place for allocation.
  406. * @inode: owner
  407. * @block: block we want
  408. * @partial: pointer to the last triple within a chain
  409. *
  410. * Normally this function find the preferred place for block allocation,
  411. * returns it.
  412. */
  413. static ext4_fsblk_t ext4_find_goal(struct inode *inode, ext4_lblk_t block,
  414. Indirect *partial)
  415. {
  416. struct ext4_block_alloc_info *block_i;
  417. block_i = EXT4_I(inode)->i_block_alloc_info;
  418. /*
  419. * try the heuristic for sequential allocation,
  420. * failing that at least try to get decent locality.
  421. */
  422. if (block_i && (block == block_i->last_alloc_logical_block + 1)
  423. && (block_i->last_alloc_physical_block != 0)) {
  424. return block_i->last_alloc_physical_block + 1;
  425. }
  426. return ext4_find_near(inode, partial);
  427. }
  428. /**
  429. * ext4_blks_to_allocate: Look up the block map and count the number
  430. * of direct blocks need to be allocated for the given branch.
  431. *
  432. * @branch: chain of indirect blocks
  433. * @k: number of blocks need for indirect blocks
  434. * @blks: number of data blocks to be mapped.
  435. * @blocks_to_boundary: the offset in the indirect block
  436. *
  437. * return the total number of blocks to be allocate, including the
  438. * direct and indirect blocks.
  439. */
  440. static int ext4_blks_to_allocate(Indirect *branch, int k, unsigned long blks,
  441. int blocks_to_boundary)
  442. {
  443. unsigned long count = 0;
  444. /*
  445. * Simple case, [t,d]Indirect block(s) has not allocated yet
  446. * then it's clear blocks on that path have not allocated
  447. */
  448. if (k > 0) {
  449. /* right now we don't handle cross boundary allocation */
  450. if (blks < blocks_to_boundary + 1)
  451. count += blks;
  452. else
  453. count += blocks_to_boundary + 1;
  454. return count;
  455. }
  456. count++;
  457. while (count < blks && count <= blocks_to_boundary &&
  458. le32_to_cpu(*(branch[0].p + count)) == 0) {
  459. count++;
  460. }
  461. return count;
  462. }
  463. /**
  464. * ext4_alloc_blocks: multiple allocate blocks needed for a branch
  465. * @indirect_blks: the number of blocks need to allocate for indirect
  466. * blocks
  467. *
  468. * @new_blocks: on return it will store the new block numbers for
  469. * the indirect blocks(if needed) and the first direct block,
  470. * @blks: on return it will store the total number of allocated
  471. * direct blocks
  472. */
  473. static int ext4_alloc_blocks(handle_t *handle, struct inode *inode,
  474. ext4_lblk_t iblock, ext4_fsblk_t goal,
  475. int indirect_blks, int blks,
  476. ext4_fsblk_t new_blocks[4], int *err)
  477. {
  478. int target, i;
  479. unsigned long count = 0, blk_allocated = 0;
  480. int index = 0;
  481. ext4_fsblk_t current_block = 0;
  482. int ret = 0;
  483. /*
  484. * Here we try to allocate the requested multiple blocks at once,
  485. * on a best-effort basis.
  486. * To build a branch, we should allocate blocks for
  487. * the indirect blocks(if not allocated yet), and at least
  488. * the first direct block of this branch. That's the
  489. * minimum number of blocks need to allocate(required)
  490. */
  491. /* first we try to allocate the indirect blocks */
  492. target = indirect_blks;
  493. while (target > 0) {
  494. count = target;
  495. /* allocating blocks for indirect blocks and direct blocks */
  496. current_block = ext4_new_meta_blocks(handle, inode,
  497. goal, &count, err);
  498. if (*err)
  499. goto failed_out;
  500. target -= count;
  501. /* allocate blocks for indirect blocks */
  502. while (index < indirect_blks && count) {
  503. new_blocks[index++] = current_block++;
  504. count--;
  505. }
  506. if (count > 0) {
  507. /*
  508. * save the new block number
  509. * for the first direct block
  510. */
  511. new_blocks[index] = current_block;
  512. printk(KERN_INFO "%s returned more blocks than "
  513. "requested\n", __func__);
  514. WARN_ON(1);
  515. break;
  516. }
  517. }
  518. target = blks - count ;
  519. blk_allocated = count;
  520. if (!target)
  521. goto allocated;
  522. /* Now allocate data blocks */
  523. count = target;
  524. /* allocating blocks for data blocks */
  525. current_block = ext4_new_blocks(handle, inode, iblock,
  526. goal, &count, err);
  527. if (*err && (target == blks)) {
  528. /*
  529. * if the allocation failed and we didn't allocate
  530. * any blocks before
  531. */
  532. goto failed_out;
  533. }
  534. if (!*err) {
  535. if (target == blks) {
  536. /*
  537. * save the new block number
  538. * for the first direct block
  539. */
  540. new_blocks[index] = current_block;
  541. }
  542. blk_allocated += count;
  543. }
  544. allocated:
  545. /* total number of blocks allocated for direct blocks */
  546. ret = blk_allocated;
  547. *err = 0;
  548. return ret;
  549. failed_out:
  550. for (i = 0; i <index; i++)
  551. ext4_free_blocks(handle, inode, new_blocks[i], 1, 0);
  552. return ret;
  553. }
  554. /**
  555. * ext4_alloc_branch - allocate and set up a chain of blocks.
  556. * @inode: owner
  557. * @indirect_blks: number of allocated indirect blocks
  558. * @blks: number of allocated direct blocks
  559. * @offsets: offsets (in the blocks) to store the pointers to next.
  560. * @branch: place to store the chain in.
  561. *
  562. * This function allocates blocks, zeroes out all but the last one,
  563. * links them into chain and (if we are synchronous) writes them to disk.
  564. * In other words, it prepares a branch that can be spliced onto the
  565. * inode. It stores the information about that chain in the branch[], in
  566. * the same format as ext4_get_branch() would do. We are calling it after
  567. * we had read the existing part of chain and partial points to the last
  568. * triple of that (one with zero ->key). Upon the exit we have the same
  569. * picture as after the successful ext4_get_block(), except that in one
  570. * place chain is disconnected - *branch->p is still zero (we did not
  571. * set the last link), but branch->key contains the number that should
  572. * be placed into *branch->p to fill that gap.
  573. *
  574. * If allocation fails we free all blocks we've allocated (and forget
  575. * their buffer_heads) and return the error value the from failed
  576. * ext4_alloc_block() (normally -ENOSPC). Otherwise we set the chain
  577. * as described above and return 0.
  578. */
  579. static int ext4_alloc_branch(handle_t *handle, struct inode *inode,
  580. ext4_lblk_t iblock, int indirect_blks,
  581. int *blks, ext4_fsblk_t goal,
  582. ext4_lblk_t *offsets, Indirect *branch)
  583. {
  584. int blocksize = inode->i_sb->s_blocksize;
  585. int i, n = 0;
  586. int err = 0;
  587. struct buffer_head *bh;
  588. int num;
  589. ext4_fsblk_t new_blocks[4];
  590. ext4_fsblk_t current_block;
  591. num = ext4_alloc_blocks(handle, inode, iblock, goal, indirect_blks,
  592. *blks, new_blocks, &err);
  593. if (err)
  594. return err;
  595. branch[0].key = cpu_to_le32(new_blocks[0]);
  596. /*
  597. * metadata blocks and data blocks are allocated.
  598. */
  599. for (n = 1; n <= indirect_blks; n++) {
  600. /*
  601. * Get buffer_head for parent block, zero it out
  602. * and set the pointer to new one, then send
  603. * parent to disk.
  604. */
  605. bh = sb_getblk(inode->i_sb, new_blocks[n-1]);
  606. branch[n].bh = bh;
  607. lock_buffer(bh);
  608. BUFFER_TRACE(bh, "call get_create_access");
  609. err = ext4_journal_get_create_access(handle, bh);
  610. if (err) {
  611. unlock_buffer(bh);
  612. brelse(bh);
  613. goto failed;
  614. }
  615. memset(bh->b_data, 0, blocksize);
  616. branch[n].p = (__le32 *) bh->b_data + offsets[n];
  617. branch[n].key = cpu_to_le32(new_blocks[n]);
  618. *branch[n].p = branch[n].key;
  619. if ( n == indirect_blks) {
  620. current_block = new_blocks[n];
  621. /*
  622. * End of chain, update the last new metablock of
  623. * the chain to point to the new allocated
  624. * data blocks numbers
  625. */
  626. for (i=1; i < num; i++)
  627. *(branch[n].p + i) = cpu_to_le32(++current_block);
  628. }
  629. BUFFER_TRACE(bh, "marking uptodate");
  630. set_buffer_uptodate(bh);
  631. unlock_buffer(bh);
  632. BUFFER_TRACE(bh, "call ext4_journal_dirty_metadata");
  633. err = ext4_journal_dirty_metadata(handle, bh);
  634. if (err)
  635. goto failed;
  636. }
  637. *blks = num;
  638. return err;
  639. failed:
  640. /* Allocation failed, free what we already allocated */
  641. for (i = 1; i <= n ; i++) {
  642. BUFFER_TRACE(branch[i].bh, "call jbd2_journal_forget");
  643. ext4_journal_forget(handle, branch[i].bh);
  644. }
  645. for (i = 0; i <indirect_blks; i++)
  646. ext4_free_blocks(handle, inode, new_blocks[i], 1, 0);
  647. ext4_free_blocks(handle, inode, new_blocks[i], num, 0);
  648. return err;
  649. }
  650. /**
  651. * ext4_splice_branch - splice the allocated branch onto inode.
  652. * @inode: owner
  653. * @block: (logical) number of block we are adding
  654. * @chain: chain of indirect blocks (with a missing link - see
  655. * ext4_alloc_branch)
  656. * @where: location of missing link
  657. * @num: number of indirect blocks we are adding
  658. * @blks: number of direct blocks we are adding
  659. *
  660. * This function fills the missing link and does all housekeeping needed in
  661. * inode (->i_blocks, etc.). In case of success we end up with the full
  662. * chain to new block and return 0.
  663. */
  664. static int ext4_splice_branch(handle_t *handle, struct inode *inode,
  665. ext4_lblk_t block, Indirect *where, int num, int blks)
  666. {
  667. int i;
  668. int err = 0;
  669. struct ext4_block_alloc_info *block_i;
  670. ext4_fsblk_t current_block;
  671. block_i = EXT4_I(inode)->i_block_alloc_info;
  672. /*
  673. * If we're splicing into a [td]indirect block (as opposed to the
  674. * inode) then we need to get write access to the [td]indirect block
  675. * before the splice.
  676. */
  677. if (where->bh) {
  678. BUFFER_TRACE(where->bh, "get_write_access");
  679. err = ext4_journal_get_write_access(handle, where->bh);
  680. if (err)
  681. goto err_out;
  682. }
  683. /* That's it */
  684. *where->p = where->key;
  685. /*
  686. * Update the host buffer_head or inode to point to more just allocated
  687. * direct blocks blocks
  688. */
  689. if (num == 0 && blks > 1) {
  690. current_block = le32_to_cpu(where->key) + 1;
  691. for (i = 1; i < blks; i++)
  692. *(where->p + i ) = cpu_to_le32(current_block++);
  693. }
  694. /*
  695. * update the most recently allocated logical & physical block
  696. * in i_block_alloc_info, to assist find the proper goal block for next
  697. * allocation
  698. */
  699. if (block_i) {
  700. block_i->last_alloc_logical_block = block + blks - 1;
  701. block_i->last_alloc_physical_block =
  702. le32_to_cpu(where[num].key) + blks - 1;
  703. }
  704. /* We are done with atomic stuff, now do the rest of housekeeping */
  705. inode->i_ctime = ext4_current_time(inode);
  706. ext4_mark_inode_dirty(handle, inode);
  707. /* had we spliced it onto indirect block? */
  708. if (where->bh) {
  709. /*
  710. * If we spliced it onto an indirect block, we haven't
  711. * altered the inode. Note however that if it is being spliced
  712. * onto an indirect block at the very end of the file (the
  713. * file is growing) then we *will* alter the inode to reflect
  714. * the new i_size. But that is not done here - it is done in
  715. * generic_commit_write->__mark_inode_dirty->ext4_dirty_inode.
  716. */
  717. jbd_debug(5, "splicing indirect only\n");
  718. BUFFER_TRACE(where->bh, "call ext4_journal_dirty_metadata");
  719. err = ext4_journal_dirty_metadata(handle, where->bh);
  720. if (err)
  721. goto err_out;
  722. } else {
  723. /*
  724. * OK, we spliced it into the inode itself on a direct block.
  725. * Inode was dirtied above.
  726. */
  727. jbd_debug(5, "splicing direct\n");
  728. }
  729. return err;
  730. err_out:
  731. for (i = 1; i <= num; i++) {
  732. BUFFER_TRACE(where[i].bh, "call jbd2_journal_forget");
  733. ext4_journal_forget(handle, where[i].bh);
  734. ext4_free_blocks(handle, inode,
  735. le32_to_cpu(where[i-1].key), 1, 0);
  736. }
  737. ext4_free_blocks(handle, inode, le32_to_cpu(where[num].key), blks, 0);
  738. return err;
  739. }
  740. /*
  741. * Allocation strategy is simple: if we have to allocate something, we will
  742. * have to go the whole way to leaf. So let's do it before attaching anything
  743. * to tree, set linkage between the newborn blocks, write them if sync is
  744. * required, recheck the path, free and repeat if check fails, otherwise
  745. * set the last missing link (that will protect us from any truncate-generated
  746. * removals - all blocks on the path are immune now) and possibly force the
  747. * write on the parent block.
  748. * That has a nice additional property: no special recovery from the failed
  749. * allocations is needed - we simply release blocks and do not touch anything
  750. * reachable from inode.
  751. *
  752. * `handle' can be NULL if create == 0.
  753. *
  754. * return > 0, # of blocks mapped or allocated.
  755. * return = 0, if plain lookup failed.
  756. * return < 0, error case.
  757. *
  758. *
  759. * Need to be called with
  760. * down_read(&EXT4_I(inode)->i_data_sem) if not allocating file system block
  761. * (ie, create is zero). Otherwise down_write(&EXT4_I(inode)->i_data_sem)
  762. */
  763. int ext4_get_blocks_handle(handle_t *handle, struct inode *inode,
  764. ext4_lblk_t iblock, unsigned long maxblocks,
  765. struct buffer_head *bh_result,
  766. int create, int extend_disksize)
  767. {
  768. int err = -EIO;
  769. ext4_lblk_t offsets[4];
  770. Indirect chain[4];
  771. Indirect *partial;
  772. ext4_fsblk_t goal;
  773. int indirect_blks;
  774. int blocks_to_boundary = 0;
  775. int depth;
  776. struct ext4_inode_info *ei = EXT4_I(inode);
  777. int count = 0;
  778. ext4_fsblk_t first_block = 0;
  779. loff_t disksize;
  780. J_ASSERT(!(EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL));
  781. J_ASSERT(handle != NULL || create == 0);
  782. depth = ext4_block_to_path(inode, iblock, offsets,
  783. &blocks_to_boundary);
  784. if (depth == 0)
  785. goto out;
  786. partial = ext4_get_branch(inode, depth, offsets, chain, &err);
  787. /* Simplest case - block found, no allocation needed */
  788. if (!partial) {
  789. first_block = le32_to_cpu(chain[depth - 1].key);
  790. clear_buffer_new(bh_result);
  791. count++;
  792. /*map more blocks*/
  793. while (count < maxblocks && count <= blocks_to_boundary) {
  794. ext4_fsblk_t blk;
  795. blk = le32_to_cpu(*(chain[depth-1].p + count));
  796. if (blk == first_block + count)
  797. count++;
  798. else
  799. break;
  800. }
  801. goto got_it;
  802. }
  803. /* Next simple case - plain lookup or failed read of indirect block */
  804. if (!create || err == -EIO)
  805. goto cleanup;
  806. /*
  807. * Okay, we need to do block allocation. Lazily initialize the block
  808. * allocation info here if necessary
  809. */
  810. if (S_ISREG(inode->i_mode) && (!ei->i_block_alloc_info))
  811. ext4_init_block_alloc_info(inode);
  812. goal = ext4_find_goal(inode, iblock, partial);
  813. /* the number of blocks need to allocate for [d,t]indirect blocks */
  814. indirect_blks = (chain + depth) - partial - 1;
  815. /*
  816. * Next look up the indirect map to count the totoal number of
  817. * direct blocks to allocate for this branch.
  818. */
  819. count = ext4_blks_to_allocate(partial, indirect_blks,
  820. maxblocks, blocks_to_boundary);
  821. /*
  822. * Block out ext4_truncate while we alter the tree
  823. */
  824. err = ext4_alloc_branch(handle, inode, iblock, indirect_blks,
  825. &count, goal,
  826. offsets + (partial - chain), partial);
  827. /*
  828. * The ext4_splice_branch call will free and forget any buffers
  829. * on the new chain if there is a failure, but that risks using
  830. * up transaction credits, especially for bitmaps where the
  831. * credits cannot be returned. Can we handle this somehow? We
  832. * may need to return -EAGAIN upwards in the worst case. --sct
  833. */
  834. if (!err)
  835. err = ext4_splice_branch(handle, inode, iblock,
  836. partial, indirect_blks, count);
  837. /*
  838. * i_disksize growing is protected by i_data_sem. Don't forget to
  839. * protect it if you're about to implement concurrent
  840. * ext4_get_block() -bzzz
  841. */
  842. if (!err && extend_disksize) {
  843. disksize = ((loff_t) iblock + count) << inode->i_blkbits;
  844. if (disksize > i_size_read(inode))
  845. disksize = i_size_read(inode);
  846. if (disksize > ei->i_disksize)
  847. ei->i_disksize = disksize;
  848. }
  849. if (err)
  850. goto cleanup;
  851. set_buffer_new(bh_result);
  852. got_it:
  853. map_bh(bh_result, inode->i_sb, le32_to_cpu(chain[depth-1].key));
  854. if (count > blocks_to_boundary)
  855. set_buffer_boundary(bh_result);
  856. err = count;
  857. /* Clean up and exit */
  858. partial = chain + depth - 1; /* the whole chain */
  859. cleanup:
  860. while (partial > chain) {
  861. BUFFER_TRACE(partial->bh, "call brelse");
  862. brelse(partial->bh);
  863. partial--;
  864. }
  865. BUFFER_TRACE(bh_result, "returned");
  866. out:
  867. return err;
  868. }
  869. /* Maximum number of blocks we map for direct IO at once. */
  870. #define DIO_MAX_BLOCKS 4096
  871. /*
  872. * Number of credits we need for writing DIO_MAX_BLOCKS:
  873. * We need sb + group descriptor + bitmap + inode -> 4
  874. * For B blocks with A block pointers per block we need:
  875. * 1 (triple ind.) + (B/A/A + 2) (doubly ind.) + (B/A + 2) (indirect).
  876. * If we plug in 4096 for B and 256 for A (for 1KB block size), we get 25.
  877. */
  878. #define DIO_CREDITS 25
  879. /*
  880. *
  881. *
  882. * ext4_ext4 get_block() wrapper function
  883. * It will do a look up first, and returns if the blocks already mapped.
  884. * Otherwise it takes the write lock of the i_data_sem and allocate blocks
  885. * and store the allocated blocks in the result buffer head and mark it
  886. * mapped.
  887. *
  888. * If file type is extents based, it will call ext4_ext_get_blocks(),
  889. * Otherwise, call with ext4_get_blocks_handle() to handle indirect mapping
  890. * based files
  891. *
  892. * On success, it returns the number of blocks being mapped or allocate.
  893. * if create==0 and the blocks are pre-allocated and uninitialized block,
  894. * the result buffer head is unmapped. If the create ==1, it will make sure
  895. * the buffer head is mapped.
  896. *
  897. * It returns 0 if plain look up failed (blocks have not been allocated), in
  898. * that casem, buffer head is unmapped
  899. *
  900. * It returns the error in case of allocation failure.
  901. */
  902. int ext4_get_blocks_wrap(handle_t *handle, struct inode *inode, sector_t block,
  903. unsigned long max_blocks, struct buffer_head *bh,
  904. int create, int extend_disksize, int flag)
  905. {
  906. int retval;
  907. clear_buffer_mapped(bh);
  908. /*
  909. * Try to see if we can get the block without requesting
  910. * for new file system block.
  911. */
  912. down_read((&EXT4_I(inode)->i_data_sem));
  913. if (EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL) {
  914. retval = ext4_ext_get_blocks(handle, inode, block, max_blocks,
  915. bh, 0, 0);
  916. } else {
  917. retval = ext4_get_blocks_handle(handle,
  918. inode, block, max_blocks, bh, 0, 0);
  919. }
  920. up_read((&EXT4_I(inode)->i_data_sem));
  921. /* If it is only a block(s) look up */
  922. if (!create)
  923. return retval;
  924. /*
  925. * Returns if the blocks have already allocated
  926. *
  927. * Note that if blocks have been preallocated
  928. * ext4_ext_get_block() returns th create = 0
  929. * with buffer head unmapped.
  930. */
  931. if (retval > 0 && buffer_mapped(bh))
  932. return retval;
  933. /*
  934. * New blocks allocate and/or writing to uninitialized extent
  935. * will possibly result in updating i_data, so we take
  936. * the write lock of i_data_sem, and call get_blocks()
  937. * with create == 1 flag.
  938. */
  939. down_write((&EXT4_I(inode)->i_data_sem));
  940. /*
  941. * if the caller is from delayed allocation writeout path
  942. * we have already reserved fs blocks for allocation
  943. * let the underlying get_block() function know to
  944. * avoid double accounting
  945. */
  946. if (flag)
  947. EXT4_I(inode)->i_delalloc_reserved_flag = 1;
  948. /*
  949. * We need to check for EXT4 here because migrate
  950. * could have changed the inode type in between
  951. */
  952. if (EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL) {
  953. retval = ext4_ext_get_blocks(handle, inode, block, max_blocks,
  954. bh, create, extend_disksize);
  955. } else {
  956. retval = ext4_get_blocks_handle(handle, inode, block,
  957. max_blocks, bh, create, extend_disksize);
  958. if (retval > 0 && buffer_new(bh)) {
  959. /*
  960. * We allocated new blocks which will result in
  961. * i_data's format changing. Force the migrate
  962. * to fail by clearing migrate flags
  963. */
  964. EXT4_I(inode)->i_flags = EXT4_I(inode)->i_flags &
  965. ~EXT4_EXT_MIGRATE;
  966. }
  967. }
  968. if (flag) {
  969. EXT4_I(inode)->i_delalloc_reserved_flag = 0;
  970. /*
  971. * Update reserved blocks/metadata blocks
  972. * after successful block allocation
  973. * which were deferred till now
  974. */
  975. if ((retval > 0) && buffer_delay(bh))
  976. ext4_da_release_space(inode, retval, 0);
  977. }
  978. up_write((&EXT4_I(inode)->i_data_sem));
  979. return retval;
  980. }
  981. static int ext4_get_block(struct inode *inode, sector_t iblock,
  982. struct buffer_head *bh_result, int create)
  983. {
  984. handle_t *handle = ext4_journal_current_handle();
  985. int ret = 0, started = 0;
  986. unsigned max_blocks = bh_result->b_size >> inode->i_blkbits;
  987. if (create && !handle) {
  988. /* Direct IO write... */
  989. if (max_blocks > DIO_MAX_BLOCKS)
  990. max_blocks = DIO_MAX_BLOCKS;
  991. handle = ext4_journal_start(inode, DIO_CREDITS +
  992. 2 * EXT4_QUOTA_TRANS_BLOCKS(inode->i_sb));
  993. if (IS_ERR(handle)) {
  994. ret = PTR_ERR(handle);
  995. goto out;
  996. }
  997. started = 1;
  998. }
  999. ret = ext4_get_blocks_wrap(handle, inode, iblock,
  1000. max_blocks, bh_result, create, 0, 0);
  1001. if (ret > 0) {
  1002. bh_result->b_size = (ret << inode->i_blkbits);
  1003. ret = 0;
  1004. }
  1005. if (started)
  1006. ext4_journal_stop(handle);
  1007. out:
  1008. return ret;
  1009. }
  1010. /*
  1011. * `handle' can be NULL if create is zero
  1012. */
  1013. struct buffer_head *ext4_getblk(handle_t *handle, struct inode *inode,
  1014. ext4_lblk_t block, int create, int *errp)
  1015. {
  1016. struct buffer_head dummy;
  1017. int fatal = 0, err;
  1018. J_ASSERT(handle != NULL || create == 0);
  1019. dummy.b_state = 0;
  1020. dummy.b_blocknr = -1000;
  1021. buffer_trace_init(&dummy.b_history);
  1022. err = ext4_get_blocks_wrap(handle, inode, block, 1,
  1023. &dummy, create, 1, 0);
  1024. /*
  1025. * ext4_get_blocks_handle() returns number of blocks
  1026. * mapped. 0 in case of a HOLE.
  1027. */
  1028. if (err > 0) {
  1029. if (err > 1)
  1030. WARN_ON(1);
  1031. err = 0;
  1032. }
  1033. *errp = err;
  1034. if (!err && buffer_mapped(&dummy)) {
  1035. struct buffer_head *bh;
  1036. bh = sb_getblk(inode->i_sb, dummy.b_blocknr);
  1037. if (!bh) {
  1038. *errp = -EIO;
  1039. goto err;
  1040. }
  1041. if (buffer_new(&dummy)) {
  1042. J_ASSERT(create != 0);
  1043. J_ASSERT(handle != NULL);
  1044. /*
  1045. * Now that we do not always journal data, we should
  1046. * keep in mind whether this should always journal the
  1047. * new buffer as metadata. For now, regular file
  1048. * writes use ext4_get_block instead, so it's not a
  1049. * problem.
  1050. */
  1051. lock_buffer(bh);
  1052. BUFFER_TRACE(bh, "call get_create_access");
  1053. fatal = ext4_journal_get_create_access(handle, bh);
  1054. if (!fatal && !buffer_uptodate(bh)) {
  1055. memset(bh->b_data,0,inode->i_sb->s_blocksize);
  1056. set_buffer_uptodate(bh);
  1057. }
  1058. unlock_buffer(bh);
  1059. BUFFER_TRACE(bh, "call ext4_journal_dirty_metadata");
  1060. err = ext4_journal_dirty_metadata(handle, bh);
  1061. if (!fatal)
  1062. fatal = err;
  1063. } else {
  1064. BUFFER_TRACE(bh, "not a new buffer");
  1065. }
  1066. if (fatal) {
  1067. *errp = fatal;
  1068. brelse(bh);
  1069. bh = NULL;
  1070. }
  1071. return bh;
  1072. }
  1073. err:
  1074. return NULL;
  1075. }
  1076. struct buffer_head *ext4_bread(handle_t *handle, struct inode *inode,
  1077. ext4_lblk_t block, int create, int *err)
  1078. {
  1079. struct buffer_head * bh;
  1080. bh = ext4_getblk(handle, inode, block, create, err);
  1081. if (!bh)
  1082. return bh;
  1083. if (buffer_uptodate(bh))
  1084. return bh;
  1085. ll_rw_block(READ_META, 1, &bh);
  1086. wait_on_buffer(bh);
  1087. if (buffer_uptodate(bh))
  1088. return bh;
  1089. put_bh(bh);
  1090. *err = -EIO;
  1091. return NULL;
  1092. }
  1093. static int walk_page_buffers( handle_t *handle,
  1094. struct buffer_head *head,
  1095. unsigned from,
  1096. unsigned to,
  1097. int *partial,
  1098. int (*fn)( handle_t *handle,
  1099. struct buffer_head *bh))
  1100. {
  1101. struct buffer_head *bh;
  1102. unsigned block_start, block_end;
  1103. unsigned blocksize = head->b_size;
  1104. int err, ret = 0;
  1105. struct buffer_head *next;
  1106. for ( bh = head, block_start = 0;
  1107. ret == 0 && (bh != head || !block_start);
  1108. block_start = block_end, bh = next)
  1109. {
  1110. next = bh->b_this_page;
  1111. block_end = block_start + blocksize;
  1112. if (block_end <= from || block_start >= to) {
  1113. if (partial && !buffer_uptodate(bh))
  1114. *partial = 1;
  1115. continue;
  1116. }
  1117. err = (*fn)(handle, bh);
  1118. if (!ret)
  1119. ret = err;
  1120. }
  1121. return ret;
  1122. }
  1123. /*
  1124. * To preserve ordering, it is essential that the hole instantiation and
  1125. * the data write be encapsulated in a single transaction. We cannot
  1126. * close off a transaction and start a new one between the ext4_get_block()
  1127. * and the commit_write(). So doing the jbd2_journal_start at the start of
  1128. * prepare_write() is the right place.
  1129. *
  1130. * Also, this function can nest inside ext4_writepage() ->
  1131. * block_write_full_page(). In that case, we *know* that ext4_writepage()
  1132. * has generated enough buffer credits to do the whole page. So we won't
  1133. * block on the journal in that case, which is good, because the caller may
  1134. * be PF_MEMALLOC.
  1135. *
  1136. * By accident, ext4 can be reentered when a transaction is open via
  1137. * quota file writes. If we were to commit the transaction while thus
  1138. * reentered, there can be a deadlock - we would be holding a quota
  1139. * lock, and the commit would never complete if another thread had a
  1140. * transaction open and was blocking on the quota lock - a ranking
  1141. * violation.
  1142. *
  1143. * So what we do is to rely on the fact that jbd2_journal_stop/journal_start
  1144. * will _not_ run commit under these circumstances because handle->h_ref
  1145. * is elevated. We'll still have enough credits for the tiny quotafile
  1146. * write.
  1147. */
  1148. static int do_journal_get_write_access(handle_t *handle,
  1149. struct buffer_head *bh)
  1150. {
  1151. if (!buffer_mapped(bh) || buffer_freed(bh))
  1152. return 0;
  1153. return ext4_journal_get_write_access(handle, bh);
  1154. }
  1155. static int ext4_write_begin(struct file *file, struct address_space *mapping,
  1156. loff_t pos, unsigned len, unsigned flags,
  1157. struct page **pagep, void **fsdata)
  1158. {
  1159. struct inode *inode = mapping->host;
  1160. int ret, needed_blocks = ext4_writepage_trans_blocks(inode);
  1161. handle_t *handle;
  1162. int retries = 0;
  1163. struct page *page;
  1164. pgoff_t index;
  1165. unsigned from, to;
  1166. index = pos >> PAGE_CACHE_SHIFT;
  1167. from = pos & (PAGE_CACHE_SIZE - 1);
  1168. to = from + len;
  1169. retry:
  1170. handle = ext4_journal_start(inode, needed_blocks);
  1171. if (IS_ERR(handle)) {
  1172. ret = PTR_ERR(handle);
  1173. goto out;
  1174. }
  1175. page = __grab_cache_page(mapping, index);
  1176. if (!page) {
  1177. ext4_journal_stop(handle);
  1178. ret = -ENOMEM;
  1179. goto out;
  1180. }
  1181. *pagep = page;
  1182. ret = block_write_begin(file, mapping, pos, len, flags, pagep, fsdata,
  1183. ext4_get_block);
  1184. if (!ret && ext4_should_journal_data(inode)) {
  1185. ret = walk_page_buffers(handle, page_buffers(page),
  1186. from, to, NULL, do_journal_get_write_access);
  1187. }
  1188. if (ret) {
  1189. unlock_page(page);
  1190. ext4_journal_stop(handle);
  1191. page_cache_release(page);
  1192. }
  1193. if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
  1194. goto retry;
  1195. out:
  1196. return ret;
  1197. }
  1198. /* For write_end() in data=journal mode */
  1199. static int write_end_fn(handle_t *handle, struct buffer_head *bh)
  1200. {
  1201. if (!buffer_mapped(bh) || buffer_freed(bh))
  1202. return 0;
  1203. set_buffer_uptodate(bh);
  1204. return ext4_journal_dirty_metadata(handle, bh);
  1205. }
  1206. /*
  1207. * We need to pick up the new inode size which generic_commit_write gave us
  1208. * `file' can be NULL - eg, when called from page_symlink().
  1209. *
  1210. * ext4 never places buffers on inode->i_mapping->private_list. metadata
  1211. * buffers are managed internally.
  1212. */
  1213. static int ext4_ordered_write_end(struct file *file,
  1214. struct address_space *mapping,
  1215. loff_t pos, unsigned len, unsigned copied,
  1216. struct page *page, void *fsdata)
  1217. {
  1218. handle_t *handle = ext4_journal_current_handle();
  1219. struct inode *inode = mapping->host;
  1220. unsigned from, to;
  1221. int ret = 0, ret2;
  1222. from = pos & (PAGE_CACHE_SIZE - 1);
  1223. to = from + len;
  1224. ret = ext4_jbd2_file_inode(handle, inode);
  1225. if (ret == 0) {
  1226. /*
  1227. * generic_write_end() will run mark_inode_dirty() if i_size
  1228. * changes. So let's piggyback the i_disksize mark_inode_dirty
  1229. * into that.
  1230. */
  1231. loff_t new_i_size;
  1232. new_i_size = pos + copied;
  1233. if (new_i_size > EXT4_I(inode)->i_disksize)
  1234. EXT4_I(inode)->i_disksize = new_i_size;
  1235. ret2 = generic_write_end(file, mapping, pos, len, copied,
  1236. page, fsdata);
  1237. copied = ret2;
  1238. if (ret2 < 0)
  1239. ret = ret2;
  1240. }
  1241. ret2 = ext4_journal_stop(handle);
  1242. if (!ret)
  1243. ret = ret2;
  1244. return ret ? ret : copied;
  1245. }
  1246. static int ext4_writeback_write_end(struct file *file,
  1247. struct address_space *mapping,
  1248. loff_t pos, unsigned len, unsigned copied,
  1249. struct page *page, void *fsdata)
  1250. {
  1251. handle_t *handle = ext4_journal_current_handle();
  1252. struct inode *inode = mapping->host;
  1253. int ret = 0, ret2;
  1254. loff_t new_i_size;
  1255. new_i_size = pos + copied;
  1256. if (new_i_size > EXT4_I(inode)->i_disksize)
  1257. EXT4_I(inode)->i_disksize = new_i_size;
  1258. ret2 = generic_write_end(file, mapping, pos, len, copied,
  1259. page, fsdata);
  1260. copied = ret2;
  1261. if (ret2 < 0)
  1262. ret = ret2;
  1263. ret2 = ext4_journal_stop(handle);
  1264. if (!ret)
  1265. ret = ret2;
  1266. return ret ? ret : copied;
  1267. }
  1268. static int ext4_journalled_write_end(struct file *file,
  1269. struct address_space *mapping,
  1270. loff_t pos, unsigned len, unsigned copied,
  1271. struct page *page, void *fsdata)
  1272. {
  1273. handle_t *handle = ext4_journal_current_handle();
  1274. struct inode *inode = mapping->host;
  1275. int ret = 0, ret2;
  1276. int partial = 0;
  1277. unsigned from, to;
  1278. from = pos & (PAGE_CACHE_SIZE - 1);
  1279. to = from + len;
  1280. if (copied < len) {
  1281. if (!PageUptodate(page))
  1282. copied = 0;
  1283. page_zero_new_buffers(page, from+copied, to);
  1284. }
  1285. ret = walk_page_buffers(handle, page_buffers(page), from,
  1286. to, &partial, write_end_fn);
  1287. if (!partial)
  1288. SetPageUptodate(page);
  1289. if (pos+copied > inode->i_size)
  1290. i_size_write(inode, pos+copied);
  1291. EXT4_I(inode)->i_state |= EXT4_STATE_JDATA;
  1292. if (inode->i_size > EXT4_I(inode)->i_disksize) {
  1293. EXT4_I(inode)->i_disksize = inode->i_size;
  1294. ret2 = ext4_mark_inode_dirty(handle, inode);
  1295. if (!ret)
  1296. ret = ret2;
  1297. }
  1298. unlock_page(page);
  1299. ret2 = ext4_journal_stop(handle);
  1300. if (!ret)
  1301. ret = ret2;
  1302. page_cache_release(page);
  1303. return ret ? ret : copied;
  1304. }
  1305. /*
  1306. * Calculate the number of metadata blocks need to reserve
  1307. * to allocate @blocks for non extent file based file
  1308. */
  1309. static int ext4_indirect_calc_metadata_amount(struct inode *inode, int blocks)
  1310. {
  1311. int icap = EXT4_ADDR_PER_BLOCK(inode->i_sb);
  1312. int ind_blks, dind_blks, tind_blks;
  1313. /* number of new indirect blocks needed */
  1314. ind_blks = (blocks + icap - 1) / icap;
  1315. dind_blks = (ind_blks + icap - 1) / icap;
  1316. tind_blks = 1;
  1317. return ind_blks + dind_blks + tind_blks;
  1318. }
  1319. /*
  1320. * Calculate the number of metadata blocks need to reserve
  1321. * to allocate given number of blocks
  1322. */
  1323. static int ext4_calc_metadata_amount(struct inode *inode, int blocks)
  1324. {
  1325. if (EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL)
  1326. return ext4_ext_calc_metadata_amount(inode, blocks);
  1327. return ext4_indirect_calc_metadata_amount(inode, blocks);
  1328. }
  1329. static int ext4_da_reserve_space(struct inode *inode, int nrblocks)
  1330. {
  1331. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  1332. unsigned long md_needed, mdblocks, total = 0;
  1333. /*
  1334. * recalculate the amount of metadata blocks to reserve
  1335. * in order to allocate nrblocks
  1336. * worse case is one extent per block
  1337. */
  1338. spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
  1339. total = EXT4_I(inode)->i_reserved_data_blocks + nrblocks;
  1340. mdblocks = ext4_calc_metadata_amount(inode, total);
  1341. BUG_ON(mdblocks < EXT4_I(inode)->i_reserved_meta_blocks);
  1342. md_needed = mdblocks - EXT4_I(inode)->i_reserved_meta_blocks;
  1343. total = md_needed + nrblocks;
  1344. if (ext4_has_free_blocks(sbi, total) < total) {
  1345. spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
  1346. return -ENOSPC;
  1347. }
  1348. /* reduce fs free blocks counter */
  1349. percpu_counter_sub(&sbi->s_freeblocks_counter, total);
  1350. EXT4_I(inode)->i_reserved_data_blocks += nrblocks;
  1351. EXT4_I(inode)->i_reserved_meta_blocks = mdblocks;
  1352. spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
  1353. return 0; /* success */
  1354. }
  1355. void ext4_da_release_space(struct inode *inode, int used, int to_free)
  1356. {
  1357. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  1358. int total, mdb, mdb_free, release;
  1359. spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
  1360. /* recalculate the number of metablocks still need to be reserved */
  1361. total = EXT4_I(inode)->i_reserved_data_blocks - used - to_free;
  1362. mdb = ext4_calc_metadata_amount(inode, total);
  1363. /* figure out how many metablocks to release */
  1364. BUG_ON(mdb > EXT4_I(inode)->i_reserved_meta_blocks);
  1365. mdb_free = EXT4_I(inode)->i_reserved_meta_blocks - mdb;
  1366. /* Account for allocated meta_blocks */
  1367. mdb_free -= EXT4_I(inode)->i_allocated_meta_blocks;
  1368. release = to_free + mdb_free;
  1369. /* update fs free blocks counter for truncate case */
  1370. percpu_counter_add(&sbi->s_freeblocks_counter, release);
  1371. /* update per-inode reservations */
  1372. BUG_ON(used + to_free > EXT4_I(inode)->i_reserved_data_blocks);
  1373. EXT4_I(inode)->i_reserved_data_blocks -= (used + to_free);
  1374. BUG_ON(mdb > EXT4_I(inode)->i_reserved_meta_blocks);
  1375. EXT4_I(inode)->i_reserved_meta_blocks = mdb;
  1376. EXT4_I(inode)->i_allocated_meta_blocks = 0;
  1377. spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
  1378. }
  1379. static void ext4_da_page_release_reservation(struct page *page,
  1380. unsigned long offset)
  1381. {
  1382. int to_release = 0;
  1383. struct buffer_head *head, *bh;
  1384. unsigned int curr_off = 0;
  1385. head = page_buffers(page);
  1386. bh = head;
  1387. do {
  1388. unsigned int next_off = curr_off + bh->b_size;
  1389. if ((offset <= curr_off) && (buffer_delay(bh))) {
  1390. to_release++;
  1391. clear_buffer_delay(bh);
  1392. }
  1393. curr_off = next_off;
  1394. } while ((bh = bh->b_this_page) != head);
  1395. ext4_da_release_space(page->mapping->host, 0, to_release);
  1396. }
  1397. /*
  1398. * Delayed allocation stuff
  1399. */
  1400. struct mpage_da_data {
  1401. struct inode *inode;
  1402. struct buffer_head lbh; /* extent of blocks */
  1403. unsigned long first_page, next_page; /* extent of pages */
  1404. get_block_t *get_block;
  1405. struct writeback_control *wbc;
  1406. };
  1407. /*
  1408. * mpage_da_submit_io - walks through extent of pages and try to write
  1409. * them with __mpage_writepage()
  1410. *
  1411. * @mpd->inode: inode
  1412. * @mpd->first_page: first page of the extent
  1413. * @mpd->next_page: page after the last page of the extent
  1414. * @mpd->get_block: the filesystem's block mapper function
  1415. *
  1416. * By the time mpage_da_submit_io() is called we expect all blocks
  1417. * to be allocated. this may be wrong if allocation failed.
  1418. *
  1419. * As pages are already locked by write_cache_pages(), we can't use it
  1420. */
  1421. static int mpage_da_submit_io(struct mpage_da_data *mpd)
  1422. {
  1423. struct address_space *mapping = mpd->inode->i_mapping;
  1424. struct mpage_data mpd_pp = {
  1425. .bio = NULL,
  1426. .last_block_in_bio = 0,
  1427. .get_block = mpd->get_block,
  1428. .use_writepage = 1,
  1429. };
  1430. int ret = 0, err, nr_pages, i;
  1431. unsigned long index, end;
  1432. struct pagevec pvec;
  1433. BUG_ON(mpd->next_page <= mpd->first_page);
  1434. pagevec_init(&pvec, 0);
  1435. index = mpd->first_page;
  1436. end = mpd->next_page - 1;
  1437. while (index <= end) {
  1438. /* XXX: optimize tail */
  1439. nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
  1440. if (nr_pages == 0)
  1441. break;
  1442. for (i = 0; i < nr_pages; i++) {
  1443. struct page *page = pvec.pages[i];
  1444. index = page->index;
  1445. if (index > end)
  1446. break;
  1447. index++;
  1448. err = __mpage_writepage(page, mpd->wbc, &mpd_pp);
  1449. /*
  1450. * In error case, we have to continue because
  1451. * remaining pages are still locked
  1452. * XXX: unlock and re-dirty them?
  1453. */
  1454. if (ret == 0)
  1455. ret = err;
  1456. }
  1457. pagevec_release(&pvec);
  1458. }
  1459. if (mpd_pp.bio)
  1460. mpage_bio_submit(WRITE, mpd_pp.bio);
  1461. return ret;
  1462. }
  1463. /*
  1464. * mpage_put_bnr_to_bhs - walk blocks and assign them actual numbers
  1465. *
  1466. * @mpd->inode - inode to walk through
  1467. * @exbh->b_blocknr - first block on a disk
  1468. * @exbh->b_size - amount of space in bytes
  1469. * @logical - first logical block to start assignment with
  1470. *
  1471. * the function goes through all passed space and put actual disk
  1472. * block numbers into buffer heads, dropping BH_Delay
  1473. */
  1474. static void mpage_put_bnr_to_bhs(struct mpage_da_data *mpd, sector_t logical,
  1475. struct buffer_head *exbh)
  1476. {
  1477. struct inode *inode = mpd->inode;
  1478. struct address_space *mapping = inode->i_mapping;
  1479. int blocks = exbh->b_size >> inode->i_blkbits;
  1480. sector_t pblock = exbh->b_blocknr, cur_logical;
  1481. struct buffer_head *head, *bh;
  1482. unsigned long index, end;
  1483. struct pagevec pvec;
  1484. int nr_pages, i;
  1485. index = logical >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
  1486. end = (logical + blocks - 1) >> (PAGE_CACHE_SHIFT - inode->i_blkbits);
  1487. cur_logical = index << (PAGE_CACHE_SHIFT - inode->i_blkbits);
  1488. pagevec_init(&pvec, 0);
  1489. while (index <= end) {
  1490. /* XXX: optimize tail */
  1491. nr_pages = pagevec_lookup(&pvec, mapping, index, PAGEVEC_SIZE);
  1492. if (nr_pages == 0)
  1493. break;
  1494. for (i = 0; i < nr_pages; i++) {
  1495. struct page *page = pvec.pages[i];
  1496. index = page->index;
  1497. if (index > end)
  1498. break;
  1499. index++;
  1500. BUG_ON(!PageLocked(page));
  1501. BUG_ON(PageWriteback(page));
  1502. BUG_ON(!page_has_buffers(page));
  1503. bh = page_buffers(page);
  1504. head = bh;
  1505. /* skip blocks out of the range */
  1506. do {
  1507. if (cur_logical >= logical)
  1508. break;
  1509. cur_logical++;
  1510. } while ((bh = bh->b_this_page) != head);
  1511. do {
  1512. if (cur_logical >= logical + blocks)
  1513. break;
  1514. if (buffer_delay(bh)) {
  1515. bh->b_blocknr = pblock;
  1516. clear_buffer_delay(bh);
  1517. } else if (buffer_mapped(bh))
  1518. BUG_ON(bh->b_blocknr != pblock);
  1519. cur_logical++;
  1520. pblock++;
  1521. } while ((bh = bh->b_this_page) != head);
  1522. }
  1523. pagevec_release(&pvec);
  1524. }
  1525. }
  1526. /*
  1527. * __unmap_underlying_blocks - just a helper function to unmap
  1528. * set of blocks described by @bh
  1529. */
  1530. static inline void __unmap_underlying_blocks(struct inode *inode,
  1531. struct buffer_head *bh)
  1532. {
  1533. struct block_device *bdev = inode->i_sb->s_bdev;
  1534. int blocks, i;
  1535. blocks = bh->b_size >> inode->i_blkbits;
  1536. for (i = 0; i < blocks; i++)
  1537. unmap_underlying_metadata(bdev, bh->b_blocknr + i);
  1538. }
  1539. /*
  1540. * mpage_da_map_blocks - go through given space
  1541. *
  1542. * @mpd->lbh - bh describing space
  1543. * @mpd->get_block - the filesystem's block mapper function
  1544. *
  1545. * The function skips space we know is already mapped to disk blocks.
  1546. *
  1547. * The function ignores errors ->get_block() returns, thus real
  1548. * error handling is postponed to __mpage_writepage()
  1549. */
  1550. static void mpage_da_map_blocks(struct mpage_da_data *mpd)
  1551. {
  1552. struct buffer_head *lbh = &mpd->lbh;
  1553. int err = 0, remain = lbh->b_size;
  1554. sector_t next = lbh->b_blocknr;
  1555. struct buffer_head new;
  1556. /*
  1557. * We consider only non-mapped and non-allocated blocks
  1558. */
  1559. if (buffer_mapped(lbh) && !buffer_delay(lbh))
  1560. return;
  1561. while (remain) {
  1562. new.b_state = lbh->b_state;
  1563. new.b_blocknr = 0;
  1564. new.b_size = remain;
  1565. err = mpd->get_block(mpd->inode, next, &new, 1);
  1566. if (err) {
  1567. /*
  1568. * Rather than implement own error handling
  1569. * here, we just leave remaining blocks
  1570. * unallocated and try again with ->writepage()
  1571. */
  1572. break;
  1573. }
  1574. BUG_ON(new.b_size == 0);
  1575. if (buffer_new(&new))
  1576. __unmap_underlying_blocks(mpd->inode, &new);
  1577. /*
  1578. * If blocks are delayed marked, we need to
  1579. * put actual blocknr and drop delayed bit
  1580. */
  1581. if (buffer_delay(lbh))
  1582. mpage_put_bnr_to_bhs(mpd, next, &new);
  1583. /* go for the remaining blocks */
  1584. next += new.b_size >> mpd->inode->i_blkbits;
  1585. remain -= new.b_size;
  1586. }
  1587. }
  1588. #define BH_FLAGS ((1 << BH_Uptodate) | (1 << BH_Mapped) | (1 << BH_Delay))
  1589. /*
  1590. * mpage_add_bh_to_extent - try to add one more block to extent of blocks
  1591. *
  1592. * @mpd->lbh - extent of blocks
  1593. * @logical - logical number of the block in the file
  1594. * @bh - bh of the block (used to access block's state)
  1595. *
  1596. * the function is used to collect contig. blocks in same state
  1597. */
  1598. static void mpage_add_bh_to_extent(struct mpage_da_data *mpd,
  1599. sector_t logical, struct buffer_head *bh)
  1600. {
  1601. struct buffer_head *lbh = &mpd->lbh;
  1602. sector_t next;
  1603. next = lbh->b_blocknr + (lbh->b_size >> mpd->inode->i_blkbits);
  1604. /*
  1605. * First block in the extent
  1606. */
  1607. if (lbh->b_size == 0) {
  1608. lbh->b_blocknr = logical;
  1609. lbh->b_size = bh->b_size;
  1610. lbh->b_state = bh->b_state & BH_FLAGS;
  1611. return;
  1612. }
  1613. /*
  1614. * Can we merge the block to our big extent?
  1615. */
  1616. if (logical == next && (bh->b_state & BH_FLAGS) == lbh->b_state) {
  1617. lbh->b_size += bh->b_size;
  1618. return;
  1619. }
  1620. /*
  1621. * We couldn't merge the block to our extent, so we
  1622. * need to flush current extent and start new one
  1623. */
  1624. mpage_da_map_blocks(mpd);
  1625. /*
  1626. * Now start a new extent
  1627. */
  1628. lbh->b_size = bh->b_size;
  1629. lbh->b_state = bh->b_state & BH_FLAGS;
  1630. lbh->b_blocknr = logical;
  1631. }
  1632. /*
  1633. * __mpage_da_writepage - finds extent of pages and blocks
  1634. *
  1635. * @page: page to consider
  1636. * @wbc: not used, we just follow rules
  1637. * @data: context
  1638. *
  1639. * The function finds extents of pages and scan them for all blocks.
  1640. */
  1641. static int __mpage_da_writepage(struct page *page,
  1642. struct writeback_control *wbc, void *data)
  1643. {
  1644. struct mpage_da_data *mpd = data;
  1645. struct inode *inode = mpd->inode;
  1646. struct buffer_head *bh, *head, fake;
  1647. sector_t logical;
  1648. /*
  1649. * Can we merge this page to current extent?
  1650. */
  1651. if (mpd->next_page != page->index) {
  1652. /*
  1653. * Nope, we can't. So, we map non-allocated blocks
  1654. * and start IO on them using __mpage_writepage()
  1655. */
  1656. if (mpd->next_page != mpd->first_page) {
  1657. mpage_da_map_blocks(mpd);
  1658. mpage_da_submit_io(mpd);
  1659. }
  1660. /*
  1661. * Start next extent of pages ...
  1662. */
  1663. mpd->first_page = page->index;
  1664. /*
  1665. * ... and blocks
  1666. */
  1667. mpd->lbh.b_size = 0;
  1668. mpd->lbh.b_state = 0;
  1669. mpd->lbh.b_blocknr = 0;
  1670. }
  1671. mpd->next_page = page->index + 1;
  1672. logical = (sector_t) page->index <<
  1673. (PAGE_CACHE_SHIFT - inode->i_blkbits);
  1674. if (!page_has_buffers(page)) {
  1675. /*
  1676. * There is no attached buffer heads yet (mmap?)
  1677. * we treat the page asfull of dirty blocks
  1678. */
  1679. bh = &fake;
  1680. bh->b_size = PAGE_CACHE_SIZE;
  1681. bh->b_state = 0;
  1682. set_buffer_dirty(bh);
  1683. set_buffer_uptodate(bh);
  1684. mpage_add_bh_to_extent(mpd, logical, bh);
  1685. } else {
  1686. /*
  1687. * Page with regular buffer heads, just add all dirty ones
  1688. */
  1689. head = page_buffers(page);
  1690. bh = head;
  1691. do {
  1692. BUG_ON(buffer_locked(bh));
  1693. if (buffer_dirty(bh))
  1694. mpage_add_bh_to_extent(mpd, logical, bh);
  1695. logical++;
  1696. } while ((bh = bh->b_this_page) != head);
  1697. }
  1698. return 0;
  1699. }
  1700. /*
  1701. * mpage_da_writepages - walk the list of dirty pages of the given
  1702. * address space, allocates non-allocated blocks, maps newly-allocated
  1703. * blocks to existing bhs and issue IO them
  1704. *
  1705. * @mapping: address space structure to write
  1706. * @wbc: subtract the number of written pages from *@wbc->nr_to_write
  1707. * @get_block: the filesystem's block mapper function.
  1708. *
  1709. * This is a library function, which implements the writepages()
  1710. * address_space_operation.
  1711. *
  1712. * In order to avoid duplication of logic that deals with partial pages,
  1713. * multiple bio per page, etc, we find non-allocated blocks, allocate
  1714. * them with minimal calls to ->get_block() and re-use __mpage_writepage()
  1715. *
  1716. * It's important that we call __mpage_writepage() only once for each
  1717. * involved page, otherwise we'd have to implement more complicated logic
  1718. * to deal with pages w/o PG_lock or w/ PG_writeback and so on.
  1719. *
  1720. * See comments to mpage_writepages()
  1721. */
  1722. static int mpage_da_writepages(struct address_space *mapping,
  1723. struct writeback_control *wbc,
  1724. get_block_t get_block)
  1725. {
  1726. struct mpage_da_data mpd;
  1727. int ret;
  1728. if (!get_block)
  1729. return generic_writepages(mapping, wbc);
  1730. mpd.wbc = wbc;
  1731. mpd.inode = mapping->host;
  1732. mpd.lbh.b_size = 0;
  1733. mpd.lbh.b_state = 0;
  1734. mpd.lbh.b_blocknr = 0;
  1735. mpd.first_page = 0;
  1736. mpd.next_page = 0;
  1737. mpd.get_block = get_block;
  1738. ret = write_cache_pages(mapping, wbc, __mpage_da_writepage, &mpd);
  1739. /*
  1740. * Handle last extent of pages
  1741. */
  1742. if (mpd.next_page != mpd.first_page) {
  1743. mpage_da_map_blocks(&mpd);
  1744. mpage_da_submit_io(&mpd);
  1745. }
  1746. return ret;
  1747. }
  1748. /*
  1749. * this is a special callback for ->write_begin() only
  1750. * it's intention is to return mapped block or reserve space
  1751. */
  1752. static int ext4_da_get_block_prep(struct inode *inode, sector_t iblock,
  1753. struct buffer_head *bh_result, int create)
  1754. {
  1755. int ret = 0;
  1756. BUG_ON(create == 0);
  1757. BUG_ON(bh_result->b_size != inode->i_sb->s_blocksize);
  1758. /*
  1759. * first, we need to know whether the block is allocated already
  1760. * preallocated blocks are unmapped but should treated
  1761. * the same as allocated blocks.
  1762. */
  1763. ret = ext4_get_blocks_wrap(NULL, inode, iblock, 1, bh_result, 0, 0, 0);
  1764. if ((ret == 0) && !buffer_delay(bh_result)) {
  1765. /* the block isn't (pre)allocated yet, let's reserve space */
  1766. /*
  1767. * XXX: __block_prepare_write() unmaps passed block,
  1768. * is it OK?
  1769. */
  1770. ret = ext4_da_reserve_space(inode, 1);
  1771. if (ret)
  1772. /* not enough space to reserve */
  1773. return ret;
  1774. map_bh(bh_result, inode->i_sb, 0);
  1775. set_buffer_new(bh_result);
  1776. set_buffer_delay(bh_result);
  1777. } else if (ret > 0) {
  1778. bh_result->b_size = (ret << inode->i_blkbits);
  1779. ret = 0;
  1780. }
  1781. return ret;
  1782. }
  1783. #define EXT4_DELALLOC_RSVED 1
  1784. static int ext4_da_get_block_write(struct inode *inode, sector_t iblock,
  1785. struct buffer_head *bh_result, int create)
  1786. {
  1787. int ret;
  1788. unsigned max_blocks = bh_result->b_size >> inode->i_blkbits;
  1789. loff_t disksize = EXT4_I(inode)->i_disksize;
  1790. handle_t *handle = NULL;
  1791. handle = ext4_journal_current_handle();
  1792. if (!handle) {
  1793. ret = ext4_get_blocks_wrap(handle, inode, iblock, max_blocks,
  1794. bh_result, 0, 0, 0);
  1795. BUG_ON(!ret);
  1796. } else {
  1797. ret = ext4_get_blocks_wrap(handle, inode, iblock, max_blocks,
  1798. bh_result, create, 0, EXT4_DELALLOC_RSVED);
  1799. }
  1800. if (ret > 0) {
  1801. bh_result->b_size = (ret << inode->i_blkbits);
  1802. /*
  1803. * Update on-disk size along with block allocation
  1804. * we don't use 'extend_disksize' as size may change
  1805. * within already allocated block -bzzz
  1806. */
  1807. disksize = ((loff_t) iblock + ret) << inode->i_blkbits;
  1808. if (disksize > i_size_read(inode))
  1809. disksize = i_size_read(inode);
  1810. if (disksize > EXT4_I(inode)->i_disksize) {
  1811. /*
  1812. * XXX: replace with spinlock if seen contended -bzzz
  1813. */
  1814. down_write(&EXT4_I(inode)->i_data_sem);
  1815. if (disksize > EXT4_I(inode)->i_disksize)
  1816. EXT4_I(inode)->i_disksize = disksize;
  1817. up_write(&EXT4_I(inode)->i_data_sem);
  1818. if (EXT4_I(inode)->i_disksize == disksize) {
  1819. ret = ext4_mark_inode_dirty(handle, inode);
  1820. return ret;
  1821. }
  1822. }
  1823. ret = 0;
  1824. }
  1825. return ret;
  1826. }
  1827. static int ext4_bh_unmapped_or_delay(handle_t *handle, struct buffer_head *bh)
  1828. {
  1829. /*
  1830. * unmapped buffer is possible for holes.
  1831. * delay buffer is possible with delayed allocation
  1832. */
  1833. return ((!buffer_mapped(bh) || buffer_delay(bh)) && buffer_dirty(bh));
  1834. }
  1835. static int ext4_normal_get_block_write(struct inode *inode, sector_t iblock,
  1836. struct buffer_head *bh_result, int create)
  1837. {
  1838. int ret = 0;
  1839. unsigned max_blocks = bh_result->b_size >> inode->i_blkbits;
  1840. /*
  1841. * we don't want to do block allocation in writepage
  1842. * so call get_block_wrap with create = 0
  1843. */
  1844. ret = ext4_get_blocks_wrap(NULL, inode, iblock, max_blocks,
  1845. bh_result, 0, 0, 0);
  1846. if (ret > 0) {
  1847. bh_result->b_size = (ret << inode->i_blkbits);
  1848. ret = 0;
  1849. }
  1850. return ret;
  1851. }
  1852. /*
  1853. * get called vi ext4_da_writepages after taking page lock (have journal handle)
  1854. * get called via journal_submit_inode_data_buffers (no journal handle)
  1855. * get called via shrink_page_list via pdflush (no journal handle)
  1856. * or grab_page_cache when doing write_begin (have journal handle)
  1857. */
  1858. static int ext4_da_writepage(struct page *page,
  1859. struct writeback_control *wbc)
  1860. {
  1861. int ret = 0;
  1862. loff_t size;
  1863. unsigned long len;
  1864. struct buffer_head *page_bufs;
  1865. struct inode *inode = page->mapping->host;
  1866. size = i_size_read(inode);
  1867. if (page->index == size >> PAGE_CACHE_SHIFT)
  1868. len = size & ~PAGE_CACHE_MASK;
  1869. else
  1870. len = PAGE_CACHE_SIZE;
  1871. if (page_has_buffers(page)) {
  1872. page_bufs = page_buffers(page);
  1873. if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
  1874. ext4_bh_unmapped_or_delay)) {
  1875. /*
  1876. * We don't want to do block allocation
  1877. * So redirty the page and return
  1878. * We may reach here when we do a journal commit
  1879. * via journal_submit_inode_data_buffers.
  1880. * If we don't have mapping block we just ignore
  1881. * them. We can also reach here via shrink_page_list
  1882. */
  1883. redirty_page_for_writepage(wbc, page);
  1884. unlock_page(page);
  1885. return 0;
  1886. }
  1887. } else {
  1888. /*
  1889. * The test for page_has_buffers() is subtle:
  1890. * We know the page is dirty but it lost buffers. That means
  1891. * that at some moment in time after write_begin()/write_end()
  1892. * has been called all buffers have been clean and thus they
  1893. * must have been written at least once. So they are all
  1894. * mapped and we can happily proceed with mapping them
  1895. * and writing the page.
  1896. *
  1897. * Try to initialize the buffer_heads and check whether
  1898. * all are mapped and non delay. We don't want to
  1899. * do block allocation here.
  1900. */
  1901. ret = block_prepare_write(page, 0, PAGE_CACHE_SIZE,
  1902. ext4_normal_get_block_write);
  1903. if (!ret) {
  1904. page_bufs = page_buffers(page);
  1905. /* check whether all are mapped and non delay */
  1906. if (walk_page_buffers(NULL, page_bufs, 0, len, NULL,
  1907. ext4_bh_unmapped_or_delay)) {
  1908. redirty_page_for_writepage(wbc, page);
  1909. unlock_page(page);
  1910. return 0;
  1911. }
  1912. } else {
  1913. /*
  1914. * We can't do block allocation here
  1915. * so just redity the page and unlock
  1916. * and return
  1917. */
  1918. redirty_page_for_writepage(wbc, page);
  1919. unlock_page(page);
  1920. return 0;
  1921. }
  1922. }
  1923. if (test_opt(inode->i_sb, NOBH) && ext4_should_writeback_data(inode))
  1924. ret = nobh_writepage(page, ext4_normal_get_block_write, wbc);
  1925. else
  1926. ret = block_write_full_page(page,
  1927. ext4_normal_get_block_write,
  1928. wbc);
  1929. return ret;
  1930. }
  1931. /*
  1932. * For now just follow the DIO way to estimate the max credits
  1933. * needed to write out EXT4_MAX_WRITEBACK_PAGES.
  1934. * todo: need to calculate the max credits need for
  1935. * extent based files, currently the DIO credits is based on
  1936. * indirect-blocks mapping way.
  1937. *
  1938. * Probably should have a generic way to calculate credits
  1939. * for DIO, writepages, and truncate
  1940. */
  1941. #define EXT4_MAX_WRITEBACK_PAGES DIO_MAX_BLOCKS
  1942. #define EXT4_MAX_WRITEBACK_CREDITS DIO_CREDITS
  1943. static int ext4_da_writepages(struct address_space *mapping,
  1944. struct writeback_control *wbc)
  1945. {
  1946. struct inode *inode = mapping->host;
  1947. handle_t *handle = NULL;
  1948. int needed_blocks;
  1949. int ret = 0;
  1950. long to_write;
  1951. loff_t range_start = 0;
  1952. /*
  1953. * No pages to write? This is mainly a kludge to avoid starting
  1954. * a transaction for special inodes like journal inode on last iput()
  1955. * because that could violate lock ordering on umount
  1956. */
  1957. if (!mapping->nrpages)
  1958. return 0;
  1959. /*
  1960. * Estimate the worse case needed credits to write out
  1961. * EXT4_MAX_BUF_BLOCKS pages
  1962. */
  1963. needed_blocks = EXT4_MAX_WRITEBACK_CREDITS;
  1964. to_write = wbc->nr_to_write;
  1965. if (!wbc->range_cyclic) {
  1966. /*
  1967. * If range_cyclic is not set force range_cont
  1968. * and save the old writeback_index
  1969. */
  1970. wbc->range_cont = 1;
  1971. range_start = wbc->range_start;
  1972. }
  1973. while (!ret && to_write) {
  1974. /* start a new transaction*/
  1975. handle = ext4_journal_start(inode, needed_blocks);
  1976. if (IS_ERR(handle)) {
  1977. ret = PTR_ERR(handle);
  1978. goto out_writepages;
  1979. }
  1980. if (ext4_should_order_data(inode)) {
  1981. /*
  1982. * With ordered mode we need to add
  1983. * the inode to the journal handle
  1984. * when we do block allocation.
  1985. */
  1986. ret = ext4_jbd2_file_inode(handle, inode);
  1987. if (ret) {
  1988. ext4_journal_stop(handle);
  1989. goto out_writepages;
  1990. }
  1991. }
  1992. /*
  1993. * set the max dirty pages could be write at a time
  1994. * to fit into the reserved transaction credits
  1995. */
  1996. if (wbc->nr_to_write > EXT4_MAX_WRITEBACK_PAGES)
  1997. wbc->nr_to_write = EXT4_MAX_WRITEBACK_PAGES;
  1998. to_write -= wbc->nr_to_write;
  1999. ret = mpage_da_writepages(mapping, wbc,
  2000. ext4_da_get_block_write);
  2001. ext4_journal_stop(handle);
  2002. if (wbc->nr_to_write) {
  2003. /*
  2004. * There is no more writeout needed
  2005. * or we requested for a noblocking writeout
  2006. * and we found the device congested
  2007. */
  2008. to_write += wbc->nr_to_write;
  2009. break;
  2010. }
  2011. wbc->nr_to_write = to_write;
  2012. }
  2013. out_writepages:
  2014. wbc->nr_to_write = to_write;
  2015. if (range_start)
  2016. wbc->range_start = range_start;
  2017. return ret;
  2018. }
  2019. static int ext4_da_write_begin(struct file *file, struct address_space *mapping,
  2020. loff_t pos, unsigned len, unsigned flags,
  2021. struct page **pagep, void **fsdata)
  2022. {
  2023. int ret, retries = 0;
  2024. struct page *page;
  2025. pgoff_t index;
  2026. unsigned from, to;
  2027. struct inode *inode = mapping->host;
  2028. handle_t *handle;
  2029. index = pos >> PAGE_CACHE_SHIFT;
  2030. from = pos & (PAGE_CACHE_SIZE - 1);
  2031. to = from + len;
  2032. retry:
  2033. /*
  2034. * With delayed allocation, we don't log the i_disksize update
  2035. * if there is delayed block allocation. But we still need
  2036. * to journalling the i_disksize update if writes to the end
  2037. * of file which has an already mapped buffer.
  2038. */
  2039. handle = ext4_journal_start(inode, 1);
  2040. if (IS_ERR(handle)) {
  2041. ret = PTR_ERR(handle);
  2042. goto out;
  2043. }
  2044. page = __grab_cache_page(mapping, index);
  2045. if (!page)
  2046. return -ENOMEM;
  2047. *pagep = page;
  2048. ret = block_write_begin(file, mapping, pos, len, flags, pagep, fsdata,
  2049. ext4_da_get_block_prep);
  2050. if (ret < 0) {
  2051. unlock_page(page);
  2052. ext4_journal_stop(handle);
  2053. page_cache_release(page);
  2054. }
  2055. if (ret == -ENOSPC && ext4_should_retry_alloc(inode->i_sb, &retries))
  2056. goto retry;
  2057. out:
  2058. return ret;
  2059. }
  2060. /*
  2061. * Check if we should update i_disksize
  2062. * when write to the end of file but not require block allocation
  2063. */
  2064. static int ext4_da_should_update_i_disksize(struct page *page,
  2065. unsigned long offset)
  2066. {
  2067. struct buffer_head *bh;
  2068. struct inode *inode = page->mapping->host;
  2069. unsigned int idx;
  2070. int i;
  2071. bh = page_buffers(page);
  2072. idx = offset >> inode->i_blkbits;
  2073. for (i=0; i < idx; i++)
  2074. bh = bh->b_this_page;
  2075. if (!buffer_mapped(bh) || (buffer_delay(bh)))
  2076. return 0;
  2077. return 1;
  2078. }
  2079. static int ext4_da_write_end(struct file *file,
  2080. struct address_space *mapping,
  2081. loff_t pos, unsigned len, unsigned copied,
  2082. struct page *page, void *fsdata)
  2083. {
  2084. struct inode *inode = mapping->host;
  2085. int ret = 0, ret2;
  2086. handle_t *handle = ext4_journal_current_handle();
  2087. loff_t new_i_size;
  2088. unsigned long start, end;
  2089. start = pos & (PAGE_CACHE_SIZE - 1);
  2090. end = start + copied -1;
  2091. /*
  2092. * generic_write_end() will run mark_inode_dirty() if i_size
  2093. * changes. So let's piggyback the i_disksize mark_inode_dirty
  2094. * into that.
  2095. */
  2096. new_i_size = pos + copied;
  2097. if (new_i_size > EXT4_I(inode)->i_disksize) {
  2098. if (ext4_da_should_update_i_disksize(page, end)) {
  2099. down_write(&EXT4_I(inode)->i_data_sem);
  2100. if (new_i_size > EXT4_I(inode)->i_disksize) {
  2101. /*
  2102. * Updating i_disksize when extending file
  2103. * without needing block allocation
  2104. */
  2105. if (ext4_should_order_data(inode))
  2106. ret = ext4_jbd2_file_inode(handle,
  2107. inode);
  2108. EXT4_I(inode)->i_disksize = new_i_size;
  2109. }
  2110. up_write(&EXT4_I(inode)->i_data_sem);
  2111. }
  2112. }
  2113. ret2 = generic_write_end(file, mapping, pos, len, copied,
  2114. page, fsdata);
  2115. copied = ret2;
  2116. if (ret2 < 0)
  2117. ret = ret2;
  2118. ret2 = ext4_journal_stop(handle);
  2119. if (!ret)
  2120. ret = ret2;
  2121. return ret ? ret : copied;
  2122. }
  2123. static void ext4_da_invalidatepage(struct page *page, unsigned long offset)
  2124. {
  2125. /*
  2126. * Drop reserved blocks
  2127. */
  2128. BUG_ON(!PageLocked(page));
  2129. if (!page_has_buffers(page))
  2130. goto out;
  2131. ext4_da_page_release_reservation(page, offset);
  2132. out:
  2133. ext4_invalidatepage(page, offset);
  2134. return;
  2135. }
  2136. /*
  2137. * bmap() is special. It gets used by applications such as lilo and by
  2138. * the swapper to find the on-disk block of a specific piece of data.
  2139. *
  2140. * Naturally, this is dangerous if the block concerned is still in the
  2141. * journal. If somebody makes a swapfile on an ext4 data-journaling
  2142. * filesystem and enables swap, then they may get a nasty shock when the
  2143. * data getting swapped to that swapfile suddenly gets overwritten by
  2144. * the original zero's written out previously to the journal and
  2145. * awaiting writeback in the kernel's buffer cache.
  2146. *
  2147. * So, if we see any bmap calls here on a modified, data-journaled file,
  2148. * take extra steps to flush any blocks which might be in the cache.
  2149. */
  2150. static sector_t ext4_bmap(struct address_space *mapping, sector_t block)
  2151. {
  2152. struct inode *inode = mapping->host;
  2153. journal_t *journal;
  2154. int err;
  2155. if (mapping_tagged(mapping, PAGECACHE_TAG_DIRTY) &&
  2156. test_opt(inode->i_sb, DELALLOC)) {
  2157. /*
  2158. * With delalloc we want to sync the file
  2159. * so that we can make sure we allocate
  2160. * blocks for file
  2161. */
  2162. filemap_write_and_wait(mapping);
  2163. }
  2164. if (EXT4_I(inode)->i_state & EXT4_STATE_JDATA) {
  2165. /*
  2166. * This is a REALLY heavyweight approach, but the use of
  2167. * bmap on dirty files is expected to be extremely rare:
  2168. * only if we run lilo or swapon on a freshly made file
  2169. * do we expect this to happen.
  2170. *
  2171. * (bmap requires CAP_SYS_RAWIO so this does not
  2172. * represent an unprivileged user DOS attack --- we'd be
  2173. * in trouble if mortal users could trigger this path at
  2174. * will.)
  2175. *
  2176. * NB. EXT4_STATE_JDATA is not set on files other than
  2177. * regular files. If somebody wants to bmap a directory
  2178. * or symlink and gets confused because the buffer
  2179. * hasn't yet been flushed to disk, they deserve
  2180. * everything they get.
  2181. */
  2182. EXT4_I(inode)->i_state &= ~EXT4_STATE_JDATA;
  2183. journal = EXT4_JOURNAL(inode);
  2184. jbd2_journal_lock_updates(journal);
  2185. err = jbd2_journal_flush(journal);
  2186. jbd2_journal_unlock_updates(journal);
  2187. if (err)
  2188. return 0;
  2189. }
  2190. return generic_block_bmap(mapping,block,ext4_get_block);
  2191. }
  2192. static int bget_one(handle_t *handle, struct buffer_head *bh)
  2193. {
  2194. get_bh(bh);
  2195. return 0;
  2196. }
  2197. static int bput_one(handle_t *handle, struct buffer_head *bh)
  2198. {
  2199. put_bh(bh);
  2200. return 0;
  2201. }
  2202. /*
  2203. * Note that we don't need to start a transaction unless we're journaling data
  2204. * because we should have holes filled from ext4_page_mkwrite(). We even don't
  2205. * need to file the inode to the transaction's list in ordered mode because if
  2206. * we are writing back data added by write(), the inode is already there and if
  2207. * we are writing back data modified via mmap(), noone guarantees in which
  2208. * transaction the data will hit the disk. In case we are journaling data, we
  2209. * cannot start transaction directly because transaction start ranks above page
  2210. * lock so we have to do some magic.
  2211. *
  2212. * In all journaling modes block_write_full_page() will start the I/O.
  2213. *
  2214. * Problem:
  2215. *
  2216. * ext4_writepage() -> kmalloc() -> __alloc_pages() -> page_launder() ->
  2217. * ext4_writepage()
  2218. *
  2219. * Similar for:
  2220. *
  2221. * ext4_file_write() -> generic_file_write() -> __alloc_pages() -> ...
  2222. *
  2223. * Same applies to ext4_get_block(). We will deadlock on various things like
  2224. * lock_journal and i_data_sem
  2225. *
  2226. * Setting PF_MEMALLOC here doesn't work - too many internal memory
  2227. * allocations fail.
  2228. *
  2229. * 16May01: If we're reentered then journal_current_handle() will be
  2230. * non-zero. We simply *return*.
  2231. *
  2232. * 1 July 2001: @@@ FIXME:
  2233. * In journalled data mode, a data buffer may be metadata against the
  2234. * current transaction. But the same file is part of a shared mapping
  2235. * and someone does a writepage() on it.
  2236. *
  2237. * We will move the buffer onto the async_data list, but *after* it has
  2238. * been dirtied. So there's a small window where we have dirty data on
  2239. * BJ_Metadata.
  2240. *
  2241. * Note that this only applies to the last partial page in the file. The
  2242. * bit which block_write_full_page() uses prepare/commit for. (That's
  2243. * broken code anyway: it's wrong for msync()).
  2244. *
  2245. * It's a rare case: affects the final partial page, for journalled data
  2246. * where the file is subject to bith write() and writepage() in the same
  2247. * transction. To fix it we'll need a custom block_write_full_page().
  2248. * We'll probably need that anyway for journalling writepage() output.
  2249. *
  2250. * We don't honour synchronous mounts for writepage(). That would be
  2251. * disastrous. Any write() or metadata operation will sync the fs for
  2252. * us.
  2253. *
  2254. */
  2255. static int __ext4_normal_writepage(struct page *page,
  2256. struct writeback_control *wbc)
  2257. {
  2258. struct inode *inode = page->mapping->host;
  2259. if (test_opt(inode->i_sb, NOBH))
  2260. return nobh_writepage(page,
  2261. ext4_normal_get_block_write, wbc);
  2262. else
  2263. return block_write_full_page(page,
  2264. ext4_normal_get_block_write,
  2265. wbc);
  2266. }
  2267. static int ext4_normal_writepage(struct page *page,
  2268. struct writeback_control *wbc)
  2269. {
  2270. struct inode *inode = page->mapping->host;
  2271. loff_t size = i_size_read(inode);
  2272. loff_t len;
  2273. J_ASSERT(PageLocked(page));
  2274. if (page->index == size >> PAGE_CACHE_SHIFT)
  2275. len = size & ~PAGE_CACHE_MASK;
  2276. else
  2277. len = PAGE_CACHE_SIZE;
  2278. if (page_has_buffers(page)) {
  2279. /* if page has buffers it should all be mapped
  2280. * and allocated. If there are not buffers attached
  2281. * to the page we know the page is dirty but it lost
  2282. * buffers. That means that at some moment in time
  2283. * after write_begin() / write_end() has been called
  2284. * all buffers have been clean and thus they must have been
  2285. * written at least once. So they are all mapped and we can
  2286. * happily proceed with mapping them and writing the page.
  2287. */
  2288. BUG_ON(walk_page_buffers(NULL, page_buffers(page), 0, len, NULL,
  2289. ext4_bh_unmapped_or_delay));
  2290. }
  2291. if (!ext4_journal_current_handle())
  2292. return __ext4_normal_writepage(page, wbc);
  2293. redirty_page_for_writepage(wbc, page);
  2294. unlock_page(page);
  2295. return 0;
  2296. }
  2297. static int __ext4_journalled_writepage(struct page *page,
  2298. struct writeback_control *wbc)
  2299. {
  2300. struct address_space *mapping = page->mapping;
  2301. struct inode *inode = mapping->host;
  2302. struct buffer_head *page_bufs;
  2303. handle_t *handle = NULL;
  2304. int ret = 0;
  2305. int err;
  2306. ret = block_prepare_write(page, 0, PAGE_CACHE_SIZE,
  2307. ext4_normal_get_block_write);
  2308. if (ret != 0)
  2309. goto out_unlock;
  2310. page_bufs = page_buffers(page);
  2311. walk_page_buffers(handle, page_bufs, 0, PAGE_CACHE_SIZE, NULL,
  2312. bget_one);
  2313. /* As soon as we unlock the page, it can go away, but we have
  2314. * references to buffers so we are safe */
  2315. unlock_page(page);
  2316. handle = ext4_journal_start(inode, ext4_writepage_trans_blocks(inode));
  2317. if (IS_ERR(handle)) {
  2318. ret = PTR_ERR(handle);
  2319. goto out;
  2320. }
  2321. ret = walk_page_buffers(handle, page_bufs, 0,
  2322. PAGE_CACHE_SIZE, NULL, do_journal_get_write_access);
  2323. err = walk_page_buffers(handle, page_bufs, 0,
  2324. PAGE_CACHE_SIZE, NULL, write_end_fn);
  2325. if (ret == 0)
  2326. ret = err;
  2327. err = ext4_journal_stop(handle);
  2328. if (!ret)
  2329. ret = err;
  2330. walk_page_buffers(handle, page_bufs, 0,
  2331. PAGE_CACHE_SIZE, NULL, bput_one);
  2332. EXT4_I(inode)->i_state |= EXT4_STATE_JDATA;
  2333. goto out;
  2334. out_unlock:
  2335. unlock_page(page);
  2336. out:
  2337. return ret;
  2338. }
  2339. static int ext4_journalled_writepage(struct page *page,
  2340. struct writeback_control *wbc)
  2341. {
  2342. struct inode *inode = page->mapping->host;
  2343. loff_t size = i_size_read(inode);
  2344. loff_t len;
  2345. J_ASSERT(PageLocked(page));
  2346. if (page->index == size >> PAGE_CACHE_SHIFT)
  2347. len = size & ~PAGE_CACHE_MASK;
  2348. else
  2349. len = PAGE_CACHE_SIZE;
  2350. if (page_has_buffers(page)) {
  2351. /* if page has buffers it should all be mapped
  2352. * and allocated. If there are not buffers attached
  2353. * to the page we know the page is dirty but it lost
  2354. * buffers. That means that at some moment in time
  2355. * after write_begin() / write_end() has been called
  2356. * all buffers have been clean and thus they must have been
  2357. * written at least once. So they are all mapped and we can
  2358. * happily proceed with mapping them and writing the page.
  2359. */
  2360. BUG_ON(walk_page_buffers(NULL, page_buffers(page), 0, len, NULL,
  2361. ext4_bh_unmapped_or_delay));
  2362. }
  2363. if (ext4_journal_current_handle())
  2364. goto no_write;
  2365. if (PageChecked(page)) {
  2366. /*
  2367. * It's mmapped pagecache. Add buffers and journal it. There
  2368. * doesn't seem much point in redirtying the page here.
  2369. */
  2370. ClearPageChecked(page);
  2371. return __ext4_journalled_writepage(page, wbc);
  2372. } else {
  2373. /*
  2374. * It may be a page full of checkpoint-mode buffers. We don't
  2375. * really know unless we go poke around in the buffer_heads.
  2376. * But block_write_full_page will do the right thing.
  2377. */
  2378. return block_write_full_page(page,
  2379. ext4_normal_get_block_write,
  2380. wbc);
  2381. }
  2382. no_write:
  2383. redirty_page_for_writepage(wbc, page);
  2384. unlock_page(page);
  2385. return 0;
  2386. }
  2387. static int ext4_readpage(struct file *file, struct page *page)
  2388. {
  2389. return mpage_readpage(page, ext4_get_block);
  2390. }
  2391. static int
  2392. ext4_readpages(struct file *file, struct address_space *mapping,
  2393. struct list_head *pages, unsigned nr_pages)
  2394. {
  2395. return mpage_readpages(mapping, pages, nr_pages, ext4_get_block);
  2396. }
  2397. static void ext4_invalidatepage(struct page *page, unsigned long offset)
  2398. {
  2399. journal_t *journal = EXT4_JOURNAL(page->mapping->host);
  2400. /*
  2401. * If it's a full truncate we just forget about the pending dirtying
  2402. */
  2403. if (offset == 0)
  2404. ClearPageChecked(page);
  2405. jbd2_journal_invalidatepage(journal, page, offset);
  2406. }
  2407. static int ext4_releasepage(struct page *page, gfp_t wait)
  2408. {
  2409. journal_t *journal = EXT4_JOURNAL(page->mapping->host);
  2410. WARN_ON(PageChecked(page));
  2411. if (!page_has_buffers(page))
  2412. return 0;
  2413. return jbd2_journal_try_to_free_buffers(journal, page, wait);
  2414. }
  2415. /*
  2416. * If the O_DIRECT write will extend the file then add this inode to the
  2417. * orphan list. So recovery will truncate it back to the original size
  2418. * if the machine crashes during the write.
  2419. *
  2420. * If the O_DIRECT write is intantiating holes inside i_size and the machine
  2421. * crashes then stale disk data _may_ be exposed inside the file. But current
  2422. * VFS code falls back into buffered path in that case so we are safe.
  2423. */
  2424. static ssize_t ext4_direct_IO(int rw, struct kiocb *iocb,
  2425. const struct iovec *iov, loff_t offset,
  2426. unsigned long nr_segs)
  2427. {
  2428. struct file *file = iocb->ki_filp;
  2429. struct inode *inode = file->f_mapping->host;
  2430. struct ext4_inode_info *ei = EXT4_I(inode);
  2431. handle_t *handle;
  2432. ssize_t ret;
  2433. int orphan = 0;
  2434. size_t count = iov_length(iov, nr_segs);
  2435. if (rw == WRITE) {
  2436. loff_t final_size = offset + count;
  2437. if (final_size > inode->i_size) {
  2438. /* Credits for sb + inode write */
  2439. handle = ext4_journal_start(inode, 2);
  2440. if (IS_ERR(handle)) {
  2441. ret = PTR_ERR(handle);
  2442. goto out;
  2443. }
  2444. ret = ext4_orphan_add(handle, inode);
  2445. if (ret) {
  2446. ext4_journal_stop(handle);
  2447. goto out;
  2448. }
  2449. orphan = 1;
  2450. ei->i_disksize = inode->i_size;
  2451. ext4_journal_stop(handle);
  2452. }
  2453. }
  2454. ret = blockdev_direct_IO(rw, iocb, inode, inode->i_sb->s_bdev, iov,
  2455. offset, nr_segs,
  2456. ext4_get_block, NULL);
  2457. if (orphan) {
  2458. int err;
  2459. /* Credits for sb + inode write */
  2460. handle = ext4_journal_start(inode, 2);
  2461. if (IS_ERR(handle)) {
  2462. /* This is really bad luck. We've written the data
  2463. * but cannot extend i_size. Bail out and pretend
  2464. * the write failed... */
  2465. ret = PTR_ERR(handle);
  2466. goto out;
  2467. }
  2468. if (inode->i_nlink)
  2469. ext4_orphan_del(handle, inode);
  2470. if (ret > 0) {
  2471. loff_t end = offset + ret;
  2472. if (end > inode->i_size) {
  2473. ei->i_disksize = end;
  2474. i_size_write(inode, end);
  2475. /*
  2476. * We're going to return a positive `ret'
  2477. * here due to non-zero-length I/O, so there's
  2478. * no way of reporting error returns from
  2479. * ext4_mark_inode_dirty() to userspace. So
  2480. * ignore it.
  2481. */
  2482. ext4_mark_inode_dirty(handle, inode);
  2483. }
  2484. }
  2485. err = ext4_journal_stop(handle);
  2486. if (ret == 0)
  2487. ret = err;
  2488. }
  2489. out:
  2490. return ret;
  2491. }
  2492. /*
  2493. * Pages can be marked dirty completely asynchronously from ext4's journalling
  2494. * activity. By filemap_sync_pte(), try_to_unmap_one(), etc. We cannot do
  2495. * much here because ->set_page_dirty is called under VFS locks. The page is
  2496. * not necessarily locked.
  2497. *
  2498. * We cannot just dirty the page and leave attached buffers clean, because the
  2499. * buffers' dirty state is "definitive". We cannot just set the buffers dirty
  2500. * or jbddirty because all the journalling code will explode.
  2501. *
  2502. * So what we do is to mark the page "pending dirty" and next time writepage
  2503. * is called, propagate that into the buffers appropriately.
  2504. */
  2505. static int ext4_journalled_set_page_dirty(struct page *page)
  2506. {
  2507. SetPageChecked(page);
  2508. return __set_page_dirty_nobuffers(page);
  2509. }
  2510. static const struct address_space_operations ext4_ordered_aops = {
  2511. .readpage = ext4_readpage,
  2512. .readpages = ext4_readpages,
  2513. .writepage = ext4_normal_writepage,
  2514. .sync_page = block_sync_page,
  2515. .write_begin = ext4_write_begin,
  2516. .write_end = ext4_ordered_write_end,
  2517. .bmap = ext4_bmap,
  2518. .invalidatepage = ext4_invalidatepage,
  2519. .releasepage = ext4_releasepage,
  2520. .direct_IO = ext4_direct_IO,
  2521. .migratepage = buffer_migrate_page,
  2522. .is_partially_uptodate = block_is_partially_uptodate,
  2523. };
  2524. static const struct address_space_operations ext4_writeback_aops = {
  2525. .readpage = ext4_readpage,
  2526. .readpages = ext4_readpages,
  2527. .writepage = ext4_normal_writepage,
  2528. .sync_page = block_sync_page,
  2529. .write_begin = ext4_write_begin,
  2530. .write_end = ext4_writeback_write_end,
  2531. .bmap = ext4_bmap,
  2532. .invalidatepage = ext4_invalidatepage,
  2533. .releasepage = ext4_releasepage,
  2534. .direct_IO = ext4_direct_IO,
  2535. .migratepage = buffer_migrate_page,
  2536. .is_partially_uptodate = block_is_partially_uptodate,
  2537. };
  2538. static const struct address_space_operations ext4_journalled_aops = {
  2539. .readpage = ext4_readpage,
  2540. .readpages = ext4_readpages,
  2541. .writepage = ext4_journalled_writepage,
  2542. .sync_page = block_sync_page,
  2543. .write_begin = ext4_write_begin,
  2544. .write_end = ext4_journalled_write_end,
  2545. .set_page_dirty = ext4_journalled_set_page_dirty,
  2546. .bmap = ext4_bmap,
  2547. .invalidatepage = ext4_invalidatepage,
  2548. .releasepage = ext4_releasepage,
  2549. .is_partially_uptodate = block_is_partially_uptodate,
  2550. };
  2551. static const struct address_space_operations ext4_da_aops = {
  2552. .readpage = ext4_readpage,
  2553. .readpages = ext4_readpages,
  2554. .writepage = ext4_da_writepage,
  2555. .writepages = ext4_da_writepages,
  2556. .sync_page = block_sync_page,
  2557. .write_begin = ext4_da_write_begin,
  2558. .write_end = ext4_da_write_end,
  2559. .bmap = ext4_bmap,
  2560. .invalidatepage = ext4_da_invalidatepage,
  2561. .releasepage = ext4_releasepage,
  2562. .direct_IO = ext4_direct_IO,
  2563. .migratepage = buffer_migrate_page,
  2564. .is_partially_uptodate = block_is_partially_uptodate,
  2565. };
  2566. void ext4_set_aops(struct inode *inode)
  2567. {
  2568. if (ext4_should_order_data(inode) &&
  2569. test_opt(inode->i_sb, DELALLOC))
  2570. inode->i_mapping->a_ops = &ext4_da_aops;
  2571. else if (ext4_should_order_data(inode))
  2572. inode->i_mapping->a_ops = &ext4_ordered_aops;
  2573. else if (ext4_should_writeback_data(inode) &&
  2574. test_opt(inode->i_sb, DELALLOC))
  2575. inode->i_mapping->a_ops = &ext4_da_aops;
  2576. else if (ext4_should_writeback_data(inode))
  2577. inode->i_mapping->a_ops = &ext4_writeback_aops;
  2578. else
  2579. inode->i_mapping->a_ops = &ext4_journalled_aops;
  2580. }
  2581. /*
  2582. * ext4_block_truncate_page() zeroes out a mapping from file offset `from'
  2583. * up to the end of the block which corresponds to `from'.
  2584. * This required during truncate. We need to physically zero the tail end
  2585. * of that block so it doesn't yield old data if the file is later grown.
  2586. */
  2587. int ext4_block_truncate_page(handle_t *handle,
  2588. struct address_space *mapping, loff_t from)
  2589. {
  2590. ext4_fsblk_t index = from >> PAGE_CACHE_SHIFT;
  2591. unsigned offset = from & (PAGE_CACHE_SIZE-1);
  2592. unsigned blocksize, length, pos;
  2593. ext4_lblk_t iblock;
  2594. struct inode *inode = mapping->host;
  2595. struct buffer_head *bh;
  2596. struct page *page;
  2597. int err = 0;
  2598. page = grab_cache_page(mapping, from >> PAGE_CACHE_SHIFT);
  2599. if (!page)
  2600. return -EINVAL;
  2601. blocksize = inode->i_sb->s_blocksize;
  2602. length = blocksize - (offset & (blocksize - 1));
  2603. iblock = index << (PAGE_CACHE_SHIFT - inode->i_sb->s_blocksize_bits);
  2604. /*
  2605. * For "nobh" option, we can only work if we don't need to
  2606. * read-in the page - otherwise we create buffers to do the IO.
  2607. */
  2608. if (!page_has_buffers(page) && test_opt(inode->i_sb, NOBH) &&
  2609. ext4_should_writeback_data(inode) && PageUptodate(page)) {
  2610. zero_user(page, offset, length);
  2611. set_page_dirty(page);
  2612. goto unlock;
  2613. }
  2614. if (!page_has_buffers(page))
  2615. create_empty_buffers(page, blocksize, 0);
  2616. /* Find the buffer that contains "offset" */
  2617. bh = page_buffers(page);
  2618. pos = blocksize;
  2619. while (offset >= pos) {
  2620. bh = bh->b_this_page;
  2621. iblock++;
  2622. pos += blocksize;
  2623. }
  2624. err = 0;
  2625. if (buffer_freed(bh)) {
  2626. BUFFER_TRACE(bh, "freed: skip");
  2627. goto unlock;
  2628. }
  2629. if (!buffer_mapped(bh)) {
  2630. BUFFER_TRACE(bh, "unmapped");
  2631. ext4_get_block(inode, iblock, bh, 0);
  2632. /* unmapped? It's a hole - nothing to do */
  2633. if (!buffer_mapped(bh)) {
  2634. BUFFER_TRACE(bh, "still unmapped");
  2635. goto unlock;
  2636. }
  2637. }
  2638. /* Ok, it's mapped. Make sure it's up-to-date */
  2639. if (PageUptodate(page))
  2640. set_buffer_uptodate(bh);
  2641. if (!buffer_uptodate(bh)) {
  2642. err = -EIO;
  2643. ll_rw_block(READ, 1, &bh);
  2644. wait_on_buffer(bh);
  2645. /* Uhhuh. Read error. Complain and punt. */
  2646. if (!buffer_uptodate(bh))
  2647. goto unlock;
  2648. }
  2649. if (ext4_should_journal_data(inode)) {
  2650. BUFFER_TRACE(bh, "get write access");
  2651. err = ext4_journal_get_write_access(handle, bh);
  2652. if (err)
  2653. goto unlock;
  2654. }
  2655. zero_user(page, offset, length);
  2656. BUFFER_TRACE(bh, "zeroed end of block");
  2657. err = 0;
  2658. if (ext4_should_journal_data(inode)) {
  2659. err = ext4_journal_dirty_metadata(handle, bh);
  2660. } else {
  2661. if (ext4_should_order_data(inode))
  2662. err = ext4_jbd2_file_inode(handle, inode);
  2663. mark_buffer_dirty(bh);
  2664. }
  2665. unlock:
  2666. unlock_page(page);
  2667. page_cache_release(page);
  2668. return err;
  2669. }
  2670. /*
  2671. * Probably it should be a library function... search for first non-zero word
  2672. * or memcmp with zero_page, whatever is better for particular architecture.
  2673. * Linus?
  2674. */
  2675. static inline int all_zeroes(__le32 *p, __le32 *q)
  2676. {
  2677. while (p < q)
  2678. if (*p++)
  2679. return 0;
  2680. return 1;
  2681. }
  2682. /**
  2683. * ext4_find_shared - find the indirect blocks for partial truncation.
  2684. * @inode: inode in question
  2685. * @depth: depth of the affected branch
  2686. * @offsets: offsets of pointers in that branch (see ext4_block_to_path)
  2687. * @chain: place to store the pointers to partial indirect blocks
  2688. * @top: place to the (detached) top of branch
  2689. *
  2690. * This is a helper function used by ext4_truncate().
  2691. *
  2692. * When we do truncate() we may have to clean the ends of several
  2693. * indirect blocks but leave the blocks themselves alive. Block is
  2694. * partially truncated if some data below the new i_size is refered
  2695. * from it (and it is on the path to the first completely truncated
  2696. * data block, indeed). We have to free the top of that path along
  2697. * with everything to the right of the path. Since no allocation
  2698. * past the truncation point is possible until ext4_truncate()
  2699. * finishes, we may safely do the latter, but top of branch may
  2700. * require special attention - pageout below the truncation point
  2701. * might try to populate it.
  2702. *
  2703. * We atomically detach the top of branch from the tree, store the
  2704. * block number of its root in *@top, pointers to buffer_heads of
  2705. * partially truncated blocks - in @chain[].bh and pointers to
  2706. * their last elements that should not be removed - in
  2707. * @chain[].p. Return value is the pointer to last filled element
  2708. * of @chain.
  2709. *
  2710. * The work left to caller to do the actual freeing of subtrees:
  2711. * a) free the subtree starting from *@top
  2712. * b) free the subtrees whose roots are stored in
  2713. * (@chain[i].p+1 .. end of @chain[i].bh->b_data)
  2714. * c) free the subtrees growing from the inode past the @chain[0].
  2715. * (no partially truncated stuff there). */
  2716. static Indirect *ext4_find_shared(struct inode *inode, int depth,
  2717. ext4_lblk_t offsets[4], Indirect chain[4], __le32 *top)
  2718. {
  2719. Indirect *partial, *p;
  2720. int k, err;
  2721. *top = 0;
  2722. /* Make k index the deepest non-null offest + 1 */
  2723. for (k = depth; k > 1 && !offsets[k-1]; k--)
  2724. ;
  2725. partial = ext4_get_branch(inode, k, offsets, chain, &err);
  2726. /* Writer: pointers */
  2727. if (!partial)
  2728. partial = chain + k-1;
  2729. /*
  2730. * If the branch acquired continuation since we've looked at it -
  2731. * fine, it should all survive and (new) top doesn't belong to us.
  2732. */
  2733. if (!partial->key && *partial->p)
  2734. /* Writer: end */
  2735. goto no_top;
  2736. for (p=partial; p>chain && all_zeroes((__le32*)p->bh->b_data,p->p); p--)
  2737. ;
  2738. /*
  2739. * OK, we've found the last block that must survive. The rest of our
  2740. * branch should be detached before unlocking. However, if that rest
  2741. * of branch is all ours and does not grow immediately from the inode
  2742. * it's easier to cheat and just decrement partial->p.
  2743. */
  2744. if (p == chain + k - 1 && p > chain) {
  2745. p->p--;
  2746. } else {
  2747. *top = *p->p;
  2748. /* Nope, don't do this in ext4. Must leave the tree intact */
  2749. #if 0
  2750. *p->p = 0;
  2751. #endif
  2752. }
  2753. /* Writer: end */
  2754. while(partial > p) {
  2755. brelse(partial->bh);
  2756. partial--;
  2757. }
  2758. no_top:
  2759. return partial;
  2760. }
  2761. /*
  2762. * Zero a number of block pointers in either an inode or an indirect block.
  2763. * If we restart the transaction we must again get write access to the
  2764. * indirect block for further modification.
  2765. *
  2766. * We release `count' blocks on disk, but (last - first) may be greater
  2767. * than `count' because there can be holes in there.
  2768. */
  2769. static void ext4_clear_blocks(handle_t *handle, struct inode *inode,
  2770. struct buffer_head *bh, ext4_fsblk_t block_to_free,
  2771. unsigned long count, __le32 *first, __le32 *last)
  2772. {
  2773. __le32 *p;
  2774. if (try_to_extend_transaction(handle, inode)) {
  2775. if (bh) {
  2776. BUFFER_TRACE(bh, "call ext4_journal_dirty_metadata");
  2777. ext4_journal_dirty_metadata(handle, bh);
  2778. }
  2779. ext4_mark_inode_dirty(handle, inode);
  2780. ext4_journal_test_restart(handle, inode);
  2781. if (bh) {
  2782. BUFFER_TRACE(bh, "retaking write access");
  2783. ext4_journal_get_write_access(handle, bh);
  2784. }
  2785. }
  2786. /*
  2787. * Any buffers which are on the journal will be in memory. We find
  2788. * them on the hash table so jbd2_journal_revoke() will run jbd2_journal_forget()
  2789. * on them. We've already detached each block from the file, so
  2790. * bforget() in jbd2_journal_forget() should be safe.
  2791. *
  2792. * AKPM: turn on bforget in jbd2_journal_forget()!!!
  2793. */
  2794. for (p = first; p < last; p++) {
  2795. u32 nr = le32_to_cpu(*p);
  2796. if (nr) {
  2797. struct buffer_head *tbh;
  2798. *p = 0;
  2799. tbh = sb_find_get_block(inode->i_sb, nr);
  2800. ext4_forget(handle, 0, inode, tbh, nr);
  2801. }
  2802. }
  2803. ext4_free_blocks(handle, inode, block_to_free, count, 0);
  2804. }
  2805. /**
  2806. * ext4_free_data - free a list of data blocks
  2807. * @handle: handle for this transaction
  2808. * @inode: inode we are dealing with
  2809. * @this_bh: indirect buffer_head which contains *@first and *@last
  2810. * @first: array of block numbers
  2811. * @last: points immediately past the end of array
  2812. *
  2813. * We are freeing all blocks refered from that array (numbers are stored as
  2814. * little-endian 32-bit) and updating @inode->i_blocks appropriately.
  2815. *
  2816. * We accumulate contiguous runs of blocks to free. Conveniently, if these
  2817. * blocks are contiguous then releasing them at one time will only affect one
  2818. * or two bitmap blocks (+ group descriptor(s) and superblock) and we won't
  2819. * actually use a lot of journal space.
  2820. *
  2821. * @this_bh will be %NULL if @first and @last point into the inode's direct
  2822. * block pointers.
  2823. */
  2824. static void ext4_free_data(handle_t *handle, struct inode *inode,
  2825. struct buffer_head *this_bh,
  2826. __le32 *first, __le32 *last)
  2827. {
  2828. ext4_fsblk_t block_to_free = 0; /* Starting block # of a run */
  2829. unsigned long count = 0; /* Number of blocks in the run */
  2830. __le32 *block_to_free_p = NULL; /* Pointer into inode/ind
  2831. corresponding to
  2832. block_to_free */
  2833. ext4_fsblk_t nr; /* Current block # */
  2834. __le32 *p; /* Pointer into inode/ind
  2835. for current block */
  2836. int err;
  2837. if (this_bh) { /* For indirect block */
  2838. BUFFER_TRACE(this_bh, "get_write_access");
  2839. err = ext4_journal_get_write_access(handle, this_bh);
  2840. /* Important: if we can't update the indirect pointers
  2841. * to the blocks, we can't free them. */
  2842. if (err)
  2843. return;
  2844. }
  2845. for (p = first; p < last; p++) {
  2846. nr = le32_to_cpu(*p);
  2847. if (nr) {
  2848. /* accumulate blocks to free if they're contiguous */
  2849. if (count == 0) {
  2850. block_to_free = nr;
  2851. block_to_free_p = p;
  2852. count = 1;
  2853. } else if (nr == block_to_free + count) {
  2854. count++;
  2855. } else {
  2856. ext4_clear_blocks(handle, inode, this_bh,
  2857. block_to_free,
  2858. count, block_to_free_p, p);
  2859. block_to_free = nr;
  2860. block_to_free_p = p;
  2861. count = 1;
  2862. }
  2863. }
  2864. }
  2865. if (count > 0)
  2866. ext4_clear_blocks(handle, inode, this_bh, block_to_free,
  2867. count, block_to_free_p, p);
  2868. if (this_bh) {
  2869. BUFFER_TRACE(this_bh, "call ext4_journal_dirty_metadata");
  2870. /*
  2871. * The buffer head should have an attached journal head at this
  2872. * point. However, if the data is corrupted and an indirect
  2873. * block pointed to itself, it would have been detached when
  2874. * the block was cleared. Check for this instead of OOPSing.
  2875. */
  2876. if (bh2jh(this_bh))
  2877. ext4_journal_dirty_metadata(handle, this_bh);
  2878. else
  2879. ext4_error(inode->i_sb, __func__,
  2880. "circular indirect block detected, "
  2881. "inode=%lu, block=%llu",
  2882. inode->i_ino,
  2883. (unsigned long long) this_bh->b_blocknr);
  2884. }
  2885. }
  2886. /**
  2887. * ext4_free_branches - free an array of branches
  2888. * @handle: JBD handle for this transaction
  2889. * @inode: inode we are dealing with
  2890. * @parent_bh: the buffer_head which contains *@first and *@last
  2891. * @first: array of block numbers
  2892. * @last: pointer immediately past the end of array
  2893. * @depth: depth of the branches to free
  2894. *
  2895. * We are freeing all blocks refered from these branches (numbers are
  2896. * stored as little-endian 32-bit) and updating @inode->i_blocks
  2897. * appropriately.
  2898. */
  2899. static void ext4_free_branches(handle_t *handle, struct inode *inode,
  2900. struct buffer_head *parent_bh,
  2901. __le32 *first, __le32 *last, int depth)
  2902. {
  2903. ext4_fsblk_t nr;
  2904. __le32 *p;
  2905. if (is_handle_aborted(handle))
  2906. return;
  2907. if (depth--) {
  2908. struct buffer_head *bh;
  2909. int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
  2910. p = last;
  2911. while (--p >= first) {
  2912. nr = le32_to_cpu(*p);
  2913. if (!nr)
  2914. continue; /* A hole */
  2915. /* Go read the buffer for the next level down */
  2916. bh = sb_bread(inode->i_sb, nr);
  2917. /*
  2918. * A read failure? Report error and clear slot
  2919. * (should be rare).
  2920. */
  2921. if (!bh) {
  2922. ext4_error(inode->i_sb, "ext4_free_branches",
  2923. "Read failure, inode=%lu, block=%llu",
  2924. inode->i_ino, nr);
  2925. continue;
  2926. }
  2927. /* This zaps the entire block. Bottom up. */
  2928. BUFFER_TRACE(bh, "free child branches");
  2929. ext4_free_branches(handle, inode, bh,
  2930. (__le32*)bh->b_data,
  2931. (__le32*)bh->b_data + addr_per_block,
  2932. depth);
  2933. /*
  2934. * We've probably journalled the indirect block several
  2935. * times during the truncate. But it's no longer
  2936. * needed and we now drop it from the transaction via
  2937. * jbd2_journal_revoke().
  2938. *
  2939. * That's easy if it's exclusively part of this
  2940. * transaction. But if it's part of the committing
  2941. * transaction then jbd2_journal_forget() will simply
  2942. * brelse() it. That means that if the underlying
  2943. * block is reallocated in ext4_get_block(),
  2944. * unmap_underlying_metadata() will find this block
  2945. * and will try to get rid of it. damn, damn.
  2946. *
  2947. * If this block has already been committed to the
  2948. * journal, a revoke record will be written. And
  2949. * revoke records must be emitted *before* clearing
  2950. * this block's bit in the bitmaps.
  2951. */
  2952. ext4_forget(handle, 1, inode, bh, bh->b_blocknr);
  2953. /*
  2954. * Everything below this this pointer has been
  2955. * released. Now let this top-of-subtree go.
  2956. *
  2957. * We want the freeing of this indirect block to be
  2958. * atomic in the journal with the updating of the
  2959. * bitmap block which owns it. So make some room in
  2960. * the journal.
  2961. *
  2962. * We zero the parent pointer *after* freeing its
  2963. * pointee in the bitmaps, so if extend_transaction()
  2964. * for some reason fails to put the bitmap changes and
  2965. * the release into the same transaction, recovery
  2966. * will merely complain about releasing a free block,
  2967. * rather than leaking blocks.
  2968. */
  2969. if (is_handle_aborted(handle))
  2970. return;
  2971. if (try_to_extend_transaction(handle, inode)) {
  2972. ext4_mark_inode_dirty(handle, inode);
  2973. ext4_journal_test_restart(handle, inode);
  2974. }
  2975. ext4_free_blocks(handle, inode, nr, 1, 1);
  2976. if (parent_bh) {
  2977. /*
  2978. * The block which we have just freed is
  2979. * pointed to by an indirect block: journal it
  2980. */
  2981. BUFFER_TRACE(parent_bh, "get_write_access");
  2982. if (!ext4_journal_get_write_access(handle,
  2983. parent_bh)){
  2984. *p = 0;
  2985. BUFFER_TRACE(parent_bh,
  2986. "call ext4_journal_dirty_metadata");
  2987. ext4_journal_dirty_metadata(handle,
  2988. parent_bh);
  2989. }
  2990. }
  2991. }
  2992. } else {
  2993. /* We have reached the bottom of the tree. */
  2994. BUFFER_TRACE(parent_bh, "free data blocks");
  2995. ext4_free_data(handle, inode, parent_bh, first, last);
  2996. }
  2997. }
  2998. int ext4_can_truncate(struct inode *inode)
  2999. {
  3000. if (IS_APPEND(inode) || IS_IMMUTABLE(inode))
  3001. return 0;
  3002. if (S_ISREG(inode->i_mode))
  3003. return 1;
  3004. if (S_ISDIR(inode->i_mode))
  3005. return 1;
  3006. if (S_ISLNK(inode->i_mode))
  3007. return !ext4_inode_is_fast_symlink(inode);
  3008. return 0;
  3009. }
  3010. /*
  3011. * ext4_truncate()
  3012. *
  3013. * We block out ext4_get_block() block instantiations across the entire
  3014. * transaction, and VFS/VM ensures that ext4_truncate() cannot run
  3015. * simultaneously on behalf of the same inode.
  3016. *
  3017. * As we work through the truncate and commmit bits of it to the journal there
  3018. * is one core, guiding principle: the file's tree must always be consistent on
  3019. * disk. We must be able to restart the truncate after a crash.
  3020. *
  3021. * The file's tree may be transiently inconsistent in memory (although it
  3022. * probably isn't), but whenever we close off and commit a journal transaction,
  3023. * the contents of (the filesystem + the journal) must be consistent and
  3024. * restartable. It's pretty simple, really: bottom up, right to left (although
  3025. * left-to-right works OK too).
  3026. *
  3027. * Note that at recovery time, journal replay occurs *before* the restart of
  3028. * truncate against the orphan inode list.
  3029. *
  3030. * The committed inode has the new, desired i_size (which is the same as
  3031. * i_disksize in this case). After a crash, ext4_orphan_cleanup() will see
  3032. * that this inode's truncate did not complete and it will again call
  3033. * ext4_truncate() to have another go. So there will be instantiated blocks
  3034. * to the right of the truncation point in a crashed ext4 filesystem. But
  3035. * that's fine - as long as they are linked from the inode, the post-crash
  3036. * ext4_truncate() run will find them and release them.
  3037. */
  3038. void ext4_truncate(struct inode *inode)
  3039. {
  3040. handle_t *handle;
  3041. struct ext4_inode_info *ei = EXT4_I(inode);
  3042. __le32 *i_data = ei->i_data;
  3043. int addr_per_block = EXT4_ADDR_PER_BLOCK(inode->i_sb);
  3044. struct address_space *mapping = inode->i_mapping;
  3045. ext4_lblk_t offsets[4];
  3046. Indirect chain[4];
  3047. Indirect *partial;
  3048. __le32 nr = 0;
  3049. int n;
  3050. ext4_lblk_t last_block;
  3051. unsigned blocksize = inode->i_sb->s_blocksize;
  3052. if (!ext4_can_truncate(inode))
  3053. return;
  3054. if (EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL) {
  3055. ext4_ext_truncate(inode);
  3056. return;
  3057. }
  3058. handle = start_transaction(inode);
  3059. if (IS_ERR(handle))
  3060. return; /* AKPM: return what? */
  3061. last_block = (inode->i_size + blocksize-1)
  3062. >> EXT4_BLOCK_SIZE_BITS(inode->i_sb);
  3063. if (inode->i_size & (blocksize - 1))
  3064. if (ext4_block_truncate_page(handle, mapping, inode->i_size))
  3065. goto out_stop;
  3066. n = ext4_block_to_path(inode, last_block, offsets, NULL);
  3067. if (n == 0)
  3068. goto out_stop; /* error */
  3069. /*
  3070. * OK. This truncate is going to happen. We add the inode to the
  3071. * orphan list, so that if this truncate spans multiple transactions,
  3072. * and we crash, we will resume the truncate when the filesystem
  3073. * recovers. It also marks the inode dirty, to catch the new size.
  3074. *
  3075. * Implication: the file must always be in a sane, consistent
  3076. * truncatable state while each transaction commits.
  3077. */
  3078. if (ext4_orphan_add(handle, inode))
  3079. goto out_stop;
  3080. /*
  3081. * From here we block out all ext4_get_block() callers who want to
  3082. * modify the block allocation tree.
  3083. */
  3084. down_write(&ei->i_data_sem);
  3085. /*
  3086. * The orphan list entry will now protect us from any crash which
  3087. * occurs before the truncate completes, so it is now safe to propagate
  3088. * the new, shorter inode size (held for now in i_size) into the
  3089. * on-disk inode. We do this via i_disksize, which is the value which
  3090. * ext4 *really* writes onto the disk inode.
  3091. */
  3092. ei->i_disksize = inode->i_size;
  3093. if (n == 1) { /* direct blocks */
  3094. ext4_free_data(handle, inode, NULL, i_data+offsets[0],
  3095. i_data + EXT4_NDIR_BLOCKS);
  3096. goto do_indirects;
  3097. }
  3098. partial = ext4_find_shared(inode, n, offsets, chain, &nr);
  3099. /* Kill the top of shared branch (not detached) */
  3100. if (nr) {
  3101. if (partial == chain) {
  3102. /* Shared branch grows from the inode */
  3103. ext4_free_branches(handle, inode, NULL,
  3104. &nr, &nr+1, (chain+n-1) - partial);
  3105. *partial->p = 0;
  3106. /*
  3107. * We mark the inode dirty prior to restart,
  3108. * and prior to stop. No need for it here.
  3109. */
  3110. } else {
  3111. /* Shared branch grows from an indirect block */
  3112. BUFFER_TRACE(partial->bh, "get_write_access");
  3113. ext4_free_branches(handle, inode, partial->bh,
  3114. partial->p,
  3115. partial->p+1, (chain+n-1) - partial);
  3116. }
  3117. }
  3118. /* Clear the ends of indirect blocks on the shared branch */
  3119. while (partial > chain) {
  3120. ext4_free_branches(handle, inode, partial->bh, partial->p + 1,
  3121. (__le32*)partial->bh->b_data+addr_per_block,
  3122. (chain+n-1) - partial);
  3123. BUFFER_TRACE(partial->bh, "call brelse");
  3124. brelse (partial->bh);
  3125. partial--;
  3126. }
  3127. do_indirects:
  3128. /* Kill the remaining (whole) subtrees */
  3129. switch (offsets[0]) {
  3130. default:
  3131. nr = i_data[EXT4_IND_BLOCK];
  3132. if (nr) {
  3133. ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 1);
  3134. i_data[EXT4_IND_BLOCK] = 0;
  3135. }
  3136. case EXT4_IND_BLOCK:
  3137. nr = i_data[EXT4_DIND_BLOCK];
  3138. if (nr) {
  3139. ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 2);
  3140. i_data[EXT4_DIND_BLOCK] = 0;
  3141. }
  3142. case EXT4_DIND_BLOCK:
  3143. nr = i_data[EXT4_TIND_BLOCK];
  3144. if (nr) {
  3145. ext4_free_branches(handle, inode, NULL, &nr, &nr+1, 3);
  3146. i_data[EXT4_TIND_BLOCK] = 0;
  3147. }
  3148. case EXT4_TIND_BLOCK:
  3149. ;
  3150. }
  3151. ext4_discard_reservation(inode);
  3152. up_write(&ei->i_data_sem);
  3153. inode->i_mtime = inode->i_ctime = ext4_current_time(inode);
  3154. ext4_mark_inode_dirty(handle, inode);
  3155. /*
  3156. * In a multi-transaction truncate, we only make the final transaction
  3157. * synchronous
  3158. */
  3159. if (IS_SYNC(inode))
  3160. handle->h_sync = 1;
  3161. out_stop:
  3162. /*
  3163. * If this was a simple ftruncate(), and the file will remain alive
  3164. * then we need to clear up the orphan record which we created above.
  3165. * However, if this was a real unlink then we were called by
  3166. * ext4_delete_inode(), and we allow that function to clean up the
  3167. * orphan info for us.
  3168. */
  3169. if (inode->i_nlink)
  3170. ext4_orphan_del(handle, inode);
  3171. ext4_journal_stop(handle);
  3172. }
  3173. static ext4_fsblk_t ext4_get_inode_block(struct super_block *sb,
  3174. unsigned long ino, struct ext4_iloc *iloc)
  3175. {
  3176. ext4_group_t block_group;
  3177. unsigned long offset;
  3178. ext4_fsblk_t block;
  3179. struct ext4_group_desc *gdp;
  3180. if (!ext4_valid_inum(sb, ino)) {
  3181. /*
  3182. * This error is already checked for in namei.c unless we are
  3183. * looking at an NFS filehandle, in which case no error
  3184. * report is needed
  3185. */
  3186. return 0;
  3187. }
  3188. block_group = (ino - 1) / EXT4_INODES_PER_GROUP(sb);
  3189. gdp = ext4_get_group_desc(sb, block_group, NULL);
  3190. if (!gdp)
  3191. return 0;
  3192. /*
  3193. * Figure out the offset within the block group inode table
  3194. */
  3195. offset = ((ino - 1) % EXT4_INODES_PER_GROUP(sb)) *
  3196. EXT4_INODE_SIZE(sb);
  3197. block = ext4_inode_table(sb, gdp) +
  3198. (offset >> EXT4_BLOCK_SIZE_BITS(sb));
  3199. iloc->block_group = block_group;
  3200. iloc->offset = offset & (EXT4_BLOCK_SIZE(sb) - 1);
  3201. return block;
  3202. }
  3203. /*
  3204. * ext4_get_inode_loc returns with an extra refcount against the inode's
  3205. * underlying buffer_head on success. If 'in_mem' is true, we have all
  3206. * data in memory that is needed to recreate the on-disk version of this
  3207. * inode.
  3208. */
  3209. static int __ext4_get_inode_loc(struct inode *inode,
  3210. struct ext4_iloc *iloc, int in_mem)
  3211. {
  3212. ext4_fsblk_t block;
  3213. struct buffer_head *bh;
  3214. block = ext4_get_inode_block(inode->i_sb, inode->i_ino, iloc);
  3215. if (!block)
  3216. return -EIO;
  3217. bh = sb_getblk(inode->i_sb, block);
  3218. if (!bh) {
  3219. ext4_error (inode->i_sb, "ext4_get_inode_loc",
  3220. "unable to read inode block - "
  3221. "inode=%lu, block=%llu",
  3222. inode->i_ino, block);
  3223. return -EIO;
  3224. }
  3225. if (!buffer_uptodate(bh)) {
  3226. lock_buffer(bh);
  3227. /*
  3228. * If the buffer has the write error flag, we have failed
  3229. * to write out another inode in the same block. In this
  3230. * case, we don't have to read the block because we may
  3231. * read the old inode data successfully.
  3232. */
  3233. if (buffer_write_io_error(bh) && !buffer_uptodate(bh))
  3234. set_buffer_uptodate(bh);
  3235. if (buffer_uptodate(bh)) {
  3236. /* someone brought it uptodate while we waited */
  3237. unlock_buffer(bh);
  3238. goto has_buffer;
  3239. }
  3240. /*
  3241. * If we have all information of the inode in memory and this
  3242. * is the only valid inode in the block, we need not read the
  3243. * block.
  3244. */
  3245. if (in_mem) {
  3246. struct buffer_head *bitmap_bh;
  3247. struct ext4_group_desc *desc;
  3248. int inodes_per_buffer;
  3249. int inode_offset, i;
  3250. ext4_group_t block_group;
  3251. int start;
  3252. block_group = (inode->i_ino - 1) /
  3253. EXT4_INODES_PER_GROUP(inode->i_sb);
  3254. inodes_per_buffer = bh->b_size /
  3255. EXT4_INODE_SIZE(inode->i_sb);
  3256. inode_offset = ((inode->i_ino - 1) %
  3257. EXT4_INODES_PER_GROUP(inode->i_sb));
  3258. start = inode_offset & ~(inodes_per_buffer - 1);
  3259. /* Is the inode bitmap in cache? */
  3260. desc = ext4_get_group_desc(inode->i_sb,
  3261. block_group, NULL);
  3262. if (!desc)
  3263. goto make_io;
  3264. bitmap_bh = sb_getblk(inode->i_sb,
  3265. ext4_inode_bitmap(inode->i_sb, desc));
  3266. if (!bitmap_bh)
  3267. goto make_io;
  3268. /*
  3269. * If the inode bitmap isn't in cache then the
  3270. * optimisation may end up performing two reads instead
  3271. * of one, so skip it.
  3272. */
  3273. if (!buffer_uptodate(bitmap_bh)) {
  3274. brelse(bitmap_bh);
  3275. goto make_io;
  3276. }
  3277. for (i = start; i < start + inodes_per_buffer; i++) {
  3278. if (i == inode_offset)
  3279. continue;
  3280. if (ext4_test_bit(i, bitmap_bh->b_data))
  3281. break;
  3282. }
  3283. brelse(bitmap_bh);
  3284. if (i == start + inodes_per_buffer) {
  3285. /* all other inodes are free, so skip I/O */
  3286. memset(bh->b_data, 0, bh->b_size);
  3287. set_buffer_uptodate(bh);
  3288. unlock_buffer(bh);
  3289. goto has_buffer;
  3290. }
  3291. }
  3292. make_io:
  3293. /*
  3294. * There are other valid inodes in the buffer, this inode
  3295. * has in-inode xattrs, or we don't have this inode in memory.
  3296. * Read the block from disk.
  3297. */
  3298. get_bh(bh);
  3299. bh->b_end_io = end_buffer_read_sync;
  3300. submit_bh(READ_META, bh);
  3301. wait_on_buffer(bh);
  3302. if (!buffer_uptodate(bh)) {
  3303. ext4_error(inode->i_sb, "ext4_get_inode_loc",
  3304. "unable to read inode block - "
  3305. "inode=%lu, block=%llu",
  3306. inode->i_ino, block);
  3307. brelse(bh);
  3308. return -EIO;
  3309. }
  3310. }
  3311. has_buffer:
  3312. iloc->bh = bh;
  3313. return 0;
  3314. }
  3315. int ext4_get_inode_loc(struct inode *inode, struct ext4_iloc *iloc)
  3316. {
  3317. /* We have all inode data except xattrs in memory here. */
  3318. return __ext4_get_inode_loc(inode, iloc,
  3319. !(EXT4_I(inode)->i_state & EXT4_STATE_XATTR));
  3320. }
  3321. void ext4_set_inode_flags(struct inode *inode)
  3322. {
  3323. unsigned int flags = EXT4_I(inode)->i_flags;
  3324. inode->i_flags &= ~(S_SYNC|S_APPEND|S_IMMUTABLE|S_NOATIME|S_DIRSYNC);
  3325. if (flags & EXT4_SYNC_FL)
  3326. inode->i_flags |= S_SYNC;
  3327. if (flags & EXT4_APPEND_FL)
  3328. inode->i_flags |= S_APPEND;
  3329. if (flags & EXT4_IMMUTABLE_FL)
  3330. inode->i_flags |= S_IMMUTABLE;
  3331. if (flags & EXT4_NOATIME_FL)
  3332. inode->i_flags |= S_NOATIME;
  3333. if (flags & EXT4_DIRSYNC_FL)
  3334. inode->i_flags |= S_DIRSYNC;
  3335. }
  3336. /* Propagate flags from i_flags to EXT4_I(inode)->i_flags */
  3337. void ext4_get_inode_flags(struct ext4_inode_info *ei)
  3338. {
  3339. unsigned int flags = ei->vfs_inode.i_flags;
  3340. ei->i_flags &= ~(EXT4_SYNC_FL|EXT4_APPEND_FL|
  3341. EXT4_IMMUTABLE_FL|EXT4_NOATIME_FL|EXT4_DIRSYNC_FL);
  3342. if (flags & S_SYNC)
  3343. ei->i_flags |= EXT4_SYNC_FL;
  3344. if (flags & S_APPEND)
  3345. ei->i_flags |= EXT4_APPEND_FL;
  3346. if (flags & S_IMMUTABLE)
  3347. ei->i_flags |= EXT4_IMMUTABLE_FL;
  3348. if (flags & S_NOATIME)
  3349. ei->i_flags |= EXT4_NOATIME_FL;
  3350. if (flags & S_DIRSYNC)
  3351. ei->i_flags |= EXT4_DIRSYNC_FL;
  3352. }
  3353. static blkcnt_t ext4_inode_blocks(struct ext4_inode *raw_inode,
  3354. struct ext4_inode_info *ei)
  3355. {
  3356. blkcnt_t i_blocks ;
  3357. struct inode *inode = &(ei->vfs_inode);
  3358. struct super_block *sb = inode->i_sb;
  3359. if (EXT4_HAS_RO_COMPAT_FEATURE(sb,
  3360. EXT4_FEATURE_RO_COMPAT_HUGE_FILE)) {
  3361. /* we are using combined 48 bit field */
  3362. i_blocks = ((u64)le16_to_cpu(raw_inode->i_blocks_high)) << 32 |
  3363. le32_to_cpu(raw_inode->i_blocks_lo);
  3364. if (ei->i_flags & EXT4_HUGE_FILE_FL) {
  3365. /* i_blocks represent file system block size */
  3366. return i_blocks << (inode->i_blkbits - 9);
  3367. } else {
  3368. return i_blocks;
  3369. }
  3370. } else {
  3371. return le32_to_cpu(raw_inode->i_blocks_lo);
  3372. }
  3373. }
  3374. struct inode *ext4_iget(struct super_block *sb, unsigned long ino)
  3375. {
  3376. struct ext4_iloc iloc;
  3377. struct ext4_inode *raw_inode;
  3378. struct ext4_inode_info *ei;
  3379. struct buffer_head *bh;
  3380. struct inode *inode;
  3381. long ret;
  3382. int block;
  3383. inode = iget_locked(sb, ino);
  3384. if (!inode)
  3385. return ERR_PTR(-ENOMEM);
  3386. if (!(inode->i_state & I_NEW))
  3387. return inode;
  3388. ei = EXT4_I(inode);
  3389. #ifdef CONFIG_EXT4DEV_FS_POSIX_ACL
  3390. ei->i_acl = EXT4_ACL_NOT_CACHED;
  3391. ei->i_default_acl = EXT4_ACL_NOT_CACHED;
  3392. #endif
  3393. ei->i_block_alloc_info = NULL;
  3394. ret = __ext4_get_inode_loc(inode, &iloc, 0);
  3395. if (ret < 0)
  3396. goto bad_inode;
  3397. bh = iloc.bh;
  3398. raw_inode = ext4_raw_inode(&iloc);
  3399. inode->i_mode = le16_to_cpu(raw_inode->i_mode);
  3400. inode->i_uid = (uid_t)le16_to_cpu(raw_inode->i_uid_low);
  3401. inode->i_gid = (gid_t)le16_to_cpu(raw_inode->i_gid_low);
  3402. if(!(test_opt (inode->i_sb, NO_UID32))) {
  3403. inode->i_uid |= le16_to_cpu(raw_inode->i_uid_high) << 16;
  3404. inode->i_gid |= le16_to_cpu(raw_inode->i_gid_high) << 16;
  3405. }
  3406. inode->i_nlink = le16_to_cpu(raw_inode->i_links_count);
  3407. ei->i_state = 0;
  3408. ei->i_dir_start_lookup = 0;
  3409. ei->i_dtime = le32_to_cpu(raw_inode->i_dtime);
  3410. /* We now have enough fields to check if the inode was active or not.
  3411. * This is needed because nfsd might try to access dead inodes
  3412. * the test is that same one that e2fsck uses
  3413. * NeilBrown 1999oct15
  3414. */
  3415. if (inode->i_nlink == 0) {
  3416. if (inode->i_mode == 0 ||
  3417. !(EXT4_SB(inode->i_sb)->s_mount_state & EXT4_ORPHAN_FS)) {
  3418. /* this inode is deleted */
  3419. brelse (bh);
  3420. ret = -ESTALE;
  3421. goto bad_inode;
  3422. }
  3423. /* The only unlinked inodes we let through here have
  3424. * valid i_mode and are being read by the orphan
  3425. * recovery code: that's fine, we're about to complete
  3426. * the process of deleting those. */
  3427. }
  3428. ei->i_flags = le32_to_cpu(raw_inode->i_flags);
  3429. inode->i_blocks = ext4_inode_blocks(raw_inode, ei);
  3430. ei->i_file_acl = le32_to_cpu(raw_inode->i_file_acl_lo);
  3431. if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
  3432. cpu_to_le32(EXT4_OS_HURD)) {
  3433. ei->i_file_acl |=
  3434. ((__u64)le16_to_cpu(raw_inode->i_file_acl_high)) << 32;
  3435. }
  3436. inode->i_size = ext4_isize(raw_inode);
  3437. ei->i_disksize = inode->i_size;
  3438. inode->i_generation = le32_to_cpu(raw_inode->i_generation);
  3439. ei->i_block_group = iloc.block_group;
  3440. /*
  3441. * NOTE! The in-memory inode i_data array is in little-endian order
  3442. * even on big-endian machines: we do NOT byteswap the block numbers!
  3443. */
  3444. for (block = 0; block < EXT4_N_BLOCKS; block++)
  3445. ei->i_data[block] = raw_inode->i_block[block];
  3446. INIT_LIST_HEAD(&ei->i_orphan);
  3447. if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
  3448. ei->i_extra_isize = le16_to_cpu(raw_inode->i_extra_isize);
  3449. if (EXT4_GOOD_OLD_INODE_SIZE + ei->i_extra_isize >
  3450. EXT4_INODE_SIZE(inode->i_sb)) {
  3451. brelse (bh);
  3452. ret = -EIO;
  3453. goto bad_inode;
  3454. }
  3455. if (ei->i_extra_isize == 0) {
  3456. /* The extra space is currently unused. Use it. */
  3457. ei->i_extra_isize = sizeof(struct ext4_inode) -
  3458. EXT4_GOOD_OLD_INODE_SIZE;
  3459. } else {
  3460. __le32 *magic = (void *)raw_inode +
  3461. EXT4_GOOD_OLD_INODE_SIZE +
  3462. ei->i_extra_isize;
  3463. if (*magic == cpu_to_le32(EXT4_XATTR_MAGIC))
  3464. ei->i_state |= EXT4_STATE_XATTR;
  3465. }
  3466. } else
  3467. ei->i_extra_isize = 0;
  3468. EXT4_INODE_GET_XTIME(i_ctime, inode, raw_inode);
  3469. EXT4_INODE_GET_XTIME(i_mtime, inode, raw_inode);
  3470. EXT4_INODE_GET_XTIME(i_atime, inode, raw_inode);
  3471. EXT4_EINODE_GET_XTIME(i_crtime, ei, raw_inode);
  3472. inode->i_version = le32_to_cpu(raw_inode->i_disk_version);
  3473. if (EXT4_INODE_SIZE(inode->i_sb) > EXT4_GOOD_OLD_INODE_SIZE) {
  3474. if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
  3475. inode->i_version |=
  3476. (__u64)(le32_to_cpu(raw_inode->i_version_hi)) << 32;
  3477. }
  3478. if (S_ISREG(inode->i_mode)) {
  3479. inode->i_op = &ext4_file_inode_operations;
  3480. inode->i_fop = &ext4_file_operations;
  3481. ext4_set_aops(inode);
  3482. } else if (S_ISDIR(inode->i_mode)) {
  3483. inode->i_op = &ext4_dir_inode_operations;
  3484. inode->i_fop = &ext4_dir_operations;
  3485. } else if (S_ISLNK(inode->i_mode)) {
  3486. if (ext4_inode_is_fast_symlink(inode))
  3487. inode->i_op = &ext4_fast_symlink_inode_operations;
  3488. else {
  3489. inode->i_op = &ext4_symlink_inode_operations;
  3490. ext4_set_aops(inode);
  3491. }
  3492. } else {
  3493. inode->i_op = &ext4_special_inode_operations;
  3494. if (raw_inode->i_block[0])
  3495. init_special_inode(inode, inode->i_mode,
  3496. old_decode_dev(le32_to_cpu(raw_inode->i_block[0])));
  3497. else
  3498. init_special_inode(inode, inode->i_mode,
  3499. new_decode_dev(le32_to_cpu(raw_inode->i_block[1])));
  3500. }
  3501. brelse (iloc.bh);
  3502. ext4_set_inode_flags(inode);
  3503. unlock_new_inode(inode);
  3504. return inode;
  3505. bad_inode:
  3506. iget_failed(inode);
  3507. return ERR_PTR(ret);
  3508. }
  3509. static int ext4_inode_blocks_set(handle_t *handle,
  3510. struct ext4_inode *raw_inode,
  3511. struct ext4_inode_info *ei)
  3512. {
  3513. struct inode *inode = &(ei->vfs_inode);
  3514. u64 i_blocks = inode->i_blocks;
  3515. struct super_block *sb = inode->i_sb;
  3516. int err = 0;
  3517. if (i_blocks <= ~0U) {
  3518. /*
  3519. * i_blocks can be represnted in a 32 bit variable
  3520. * as multiple of 512 bytes
  3521. */
  3522. raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
  3523. raw_inode->i_blocks_high = 0;
  3524. ei->i_flags &= ~EXT4_HUGE_FILE_FL;
  3525. } else if (i_blocks <= 0xffffffffffffULL) {
  3526. /*
  3527. * i_blocks can be represented in a 48 bit variable
  3528. * as multiple of 512 bytes
  3529. */
  3530. err = ext4_update_rocompat_feature(handle, sb,
  3531. EXT4_FEATURE_RO_COMPAT_HUGE_FILE);
  3532. if (err)
  3533. goto err_out;
  3534. /* i_block is stored in the split 48 bit fields */
  3535. raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
  3536. raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
  3537. ei->i_flags &= ~EXT4_HUGE_FILE_FL;
  3538. } else {
  3539. /*
  3540. * i_blocks should be represented in a 48 bit variable
  3541. * as multiple of file system block size
  3542. */
  3543. err = ext4_update_rocompat_feature(handle, sb,
  3544. EXT4_FEATURE_RO_COMPAT_HUGE_FILE);
  3545. if (err)
  3546. goto err_out;
  3547. ei->i_flags |= EXT4_HUGE_FILE_FL;
  3548. /* i_block is stored in file system block size */
  3549. i_blocks = i_blocks >> (inode->i_blkbits - 9);
  3550. raw_inode->i_blocks_lo = cpu_to_le32(i_blocks);
  3551. raw_inode->i_blocks_high = cpu_to_le16(i_blocks >> 32);
  3552. }
  3553. err_out:
  3554. return err;
  3555. }
  3556. /*
  3557. * Post the struct inode info into an on-disk inode location in the
  3558. * buffer-cache. This gobbles the caller's reference to the
  3559. * buffer_head in the inode location struct.
  3560. *
  3561. * The caller must have write access to iloc->bh.
  3562. */
  3563. static int ext4_do_update_inode(handle_t *handle,
  3564. struct inode *inode,
  3565. struct ext4_iloc *iloc)
  3566. {
  3567. struct ext4_inode *raw_inode = ext4_raw_inode(iloc);
  3568. struct ext4_inode_info *ei = EXT4_I(inode);
  3569. struct buffer_head *bh = iloc->bh;
  3570. int err = 0, rc, block;
  3571. /* For fields not not tracking in the in-memory inode,
  3572. * initialise them to zero for new inodes. */
  3573. if (ei->i_state & EXT4_STATE_NEW)
  3574. memset(raw_inode, 0, EXT4_SB(inode->i_sb)->s_inode_size);
  3575. ext4_get_inode_flags(ei);
  3576. raw_inode->i_mode = cpu_to_le16(inode->i_mode);
  3577. if(!(test_opt(inode->i_sb, NO_UID32))) {
  3578. raw_inode->i_uid_low = cpu_to_le16(low_16_bits(inode->i_uid));
  3579. raw_inode->i_gid_low = cpu_to_le16(low_16_bits(inode->i_gid));
  3580. /*
  3581. * Fix up interoperability with old kernels. Otherwise, old inodes get
  3582. * re-used with the upper 16 bits of the uid/gid intact
  3583. */
  3584. if(!ei->i_dtime) {
  3585. raw_inode->i_uid_high =
  3586. cpu_to_le16(high_16_bits(inode->i_uid));
  3587. raw_inode->i_gid_high =
  3588. cpu_to_le16(high_16_bits(inode->i_gid));
  3589. } else {
  3590. raw_inode->i_uid_high = 0;
  3591. raw_inode->i_gid_high = 0;
  3592. }
  3593. } else {
  3594. raw_inode->i_uid_low =
  3595. cpu_to_le16(fs_high2lowuid(inode->i_uid));
  3596. raw_inode->i_gid_low =
  3597. cpu_to_le16(fs_high2lowgid(inode->i_gid));
  3598. raw_inode->i_uid_high = 0;
  3599. raw_inode->i_gid_high = 0;
  3600. }
  3601. raw_inode->i_links_count = cpu_to_le16(inode->i_nlink);
  3602. EXT4_INODE_SET_XTIME(i_ctime, inode, raw_inode);
  3603. EXT4_INODE_SET_XTIME(i_mtime, inode, raw_inode);
  3604. EXT4_INODE_SET_XTIME(i_atime, inode, raw_inode);
  3605. EXT4_EINODE_SET_XTIME(i_crtime, ei, raw_inode);
  3606. if (ext4_inode_blocks_set(handle, raw_inode, ei))
  3607. goto out_brelse;
  3608. raw_inode->i_dtime = cpu_to_le32(ei->i_dtime);
  3609. /* clear the migrate flag in the raw_inode */
  3610. raw_inode->i_flags = cpu_to_le32(ei->i_flags & ~EXT4_EXT_MIGRATE);
  3611. if (EXT4_SB(inode->i_sb)->s_es->s_creator_os !=
  3612. cpu_to_le32(EXT4_OS_HURD))
  3613. raw_inode->i_file_acl_high =
  3614. cpu_to_le16(ei->i_file_acl >> 32);
  3615. raw_inode->i_file_acl_lo = cpu_to_le32(ei->i_file_acl);
  3616. ext4_isize_set(raw_inode, ei->i_disksize);
  3617. if (ei->i_disksize > 0x7fffffffULL) {
  3618. struct super_block *sb = inode->i_sb;
  3619. if (!EXT4_HAS_RO_COMPAT_FEATURE(sb,
  3620. EXT4_FEATURE_RO_COMPAT_LARGE_FILE) ||
  3621. EXT4_SB(sb)->s_es->s_rev_level ==
  3622. cpu_to_le32(EXT4_GOOD_OLD_REV)) {
  3623. /* If this is the first large file
  3624. * created, add a flag to the superblock.
  3625. */
  3626. err = ext4_journal_get_write_access(handle,
  3627. EXT4_SB(sb)->s_sbh);
  3628. if (err)
  3629. goto out_brelse;
  3630. ext4_update_dynamic_rev(sb);
  3631. EXT4_SET_RO_COMPAT_FEATURE(sb,
  3632. EXT4_FEATURE_RO_COMPAT_LARGE_FILE);
  3633. sb->s_dirt = 1;
  3634. handle->h_sync = 1;
  3635. err = ext4_journal_dirty_metadata(handle,
  3636. EXT4_SB(sb)->s_sbh);
  3637. }
  3638. }
  3639. raw_inode->i_generation = cpu_to_le32(inode->i_generation);
  3640. if (S_ISCHR(inode->i_mode) || S_ISBLK(inode->i_mode)) {
  3641. if (old_valid_dev(inode->i_rdev)) {
  3642. raw_inode->i_block[0] =
  3643. cpu_to_le32(old_encode_dev(inode->i_rdev));
  3644. raw_inode->i_block[1] = 0;
  3645. } else {
  3646. raw_inode->i_block[0] = 0;
  3647. raw_inode->i_block[1] =
  3648. cpu_to_le32(new_encode_dev(inode->i_rdev));
  3649. raw_inode->i_block[2] = 0;
  3650. }
  3651. } else for (block = 0; block < EXT4_N_BLOCKS; block++)
  3652. raw_inode->i_block[block] = ei->i_data[block];
  3653. raw_inode->i_disk_version = cpu_to_le32(inode->i_version);
  3654. if (ei->i_extra_isize) {
  3655. if (EXT4_FITS_IN_INODE(raw_inode, ei, i_version_hi))
  3656. raw_inode->i_version_hi =
  3657. cpu_to_le32(inode->i_version >> 32);
  3658. raw_inode->i_extra_isize = cpu_to_le16(ei->i_extra_isize);
  3659. }
  3660. BUFFER_TRACE(bh, "call ext4_journal_dirty_metadata");
  3661. rc = ext4_journal_dirty_metadata(handle, bh);
  3662. if (!err)
  3663. err = rc;
  3664. ei->i_state &= ~EXT4_STATE_NEW;
  3665. out_brelse:
  3666. brelse (bh);
  3667. ext4_std_error(inode->i_sb, err);
  3668. return err;
  3669. }
  3670. /*
  3671. * ext4_write_inode()
  3672. *
  3673. * We are called from a few places:
  3674. *
  3675. * - Within generic_file_write() for O_SYNC files.
  3676. * Here, there will be no transaction running. We wait for any running
  3677. * trasnaction to commit.
  3678. *
  3679. * - Within sys_sync(), kupdate and such.
  3680. * We wait on commit, if tol to.
  3681. *
  3682. * - Within prune_icache() (PF_MEMALLOC == true)
  3683. * Here we simply return. We can't afford to block kswapd on the
  3684. * journal commit.
  3685. *
  3686. * In all cases it is actually safe for us to return without doing anything,
  3687. * because the inode has been copied into a raw inode buffer in
  3688. * ext4_mark_inode_dirty(). This is a correctness thing for O_SYNC and for
  3689. * knfsd.
  3690. *
  3691. * Note that we are absolutely dependent upon all inode dirtiers doing the
  3692. * right thing: they *must* call mark_inode_dirty() after dirtying info in
  3693. * which we are interested.
  3694. *
  3695. * It would be a bug for them to not do this. The code:
  3696. *
  3697. * mark_inode_dirty(inode)
  3698. * stuff();
  3699. * inode->i_size = expr;
  3700. *
  3701. * is in error because a kswapd-driven write_inode() could occur while
  3702. * `stuff()' is running, and the new i_size will be lost. Plus the inode
  3703. * will no longer be on the superblock's dirty inode list.
  3704. */
  3705. int ext4_write_inode(struct inode *inode, int wait)
  3706. {
  3707. if (current->flags & PF_MEMALLOC)
  3708. return 0;
  3709. if (ext4_journal_current_handle()) {
  3710. jbd_debug(1, "called recursively, non-PF_MEMALLOC!\n");
  3711. dump_stack();
  3712. return -EIO;
  3713. }
  3714. if (!wait)
  3715. return 0;
  3716. return ext4_force_commit(inode->i_sb);
  3717. }
  3718. /*
  3719. * ext4_setattr()
  3720. *
  3721. * Called from notify_change.
  3722. *
  3723. * We want to trap VFS attempts to truncate the file as soon as
  3724. * possible. In particular, we want to make sure that when the VFS
  3725. * shrinks i_size, we put the inode on the orphan list and modify
  3726. * i_disksize immediately, so that during the subsequent flushing of
  3727. * dirty pages and freeing of disk blocks, we can guarantee that any
  3728. * commit will leave the blocks being flushed in an unused state on
  3729. * disk. (On recovery, the inode will get truncated and the blocks will
  3730. * be freed, so we have a strong guarantee that no future commit will
  3731. * leave these blocks visible to the user.)
  3732. *
  3733. * Another thing we have to assure is that if we are in ordered mode
  3734. * and inode is still attached to the committing transaction, we must
  3735. * we start writeout of all the dirty pages which are being truncated.
  3736. * This way we are sure that all the data written in the previous
  3737. * transaction are already on disk (truncate waits for pages under
  3738. * writeback).
  3739. *
  3740. * Called with inode->i_mutex down.
  3741. */
  3742. int ext4_setattr(struct dentry *dentry, struct iattr *attr)
  3743. {
  3744. struct inode *inode = dentry->d_inode;
  3745. int error, rc = 0;
  3746. const unsigned int ia_valid = attr->ia_valid;
  3747. error = inode_change_ok(inode, attr);
  3748. if (error)
  3749. return error;
  3750. if ((ia_valid & ATTR_UID && attr->ia_uid != inode->i_uid) ||
  3751. (ia_valid & ATTR_GID && attr->ia_gid != inode->i_gid)) {
  3752. handle_t *handle;
  3753. /* (user+group)*(old+new) structure, inode write (sb,
  3754. * inode block, ? - but truncate inode update has it) */
  3755. handle = ext4_journal_start(inode, 2*(EXT4_QUOTA_INIT_BLOCKS(inode->i_sb)+
  3756. EXT4_QUOTA_DEL_BLOCKS(inode->i_sb))+3);
  3757. if (IS_ERR(handle)) {
  3758. error = PTR_ERR(handle);
  3759. goto err_out;
  3760. }
  3761. error = DQUOT_TRANSFER(inode, attr) ? -EDQUOT : 0;
  3762. if (error) {
  3763. ext4_journal_stop(handle);
  3764. return error;
  3765. }
  3766. /* Update corresponding info in inode so that everything is in
  3767. * one transaction */
  3768. if (attr->ia_valid & ATTR_UID)
  3769. inode->i_uid = attr->ia_uid;
  3770. if (attr->ia_valid & ATTR_GID)
  3771. inode->i_gid = attr->ia_gid;
  3772. error = ext4_mark_inode_dirty(handle, inode);
  3773. ext4_journal_stop(handle);
  3774. }
  3775. if (attr->ia_valid & ATTR_SIZE) {
  3776. if (!(EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL)) {
  3777. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  3778. if (attr->ia_size > sbi->s_bitmap_maxbytes) {
  3779. error = -EFBIG;
  3780. goto err_out;
  3781. }
  3782. }
  3783. }
  3784. if (S_ISREG(inode->i_mode) &&
  3785. attr->ia_valid & ATTR_SIZE && attr->ia_size < inode->i_size) {
  3786. handle_t *handle;
  3787. handle = ext4_journal_start(inode, 3);
  3788. if (IS_ERR(handle)) {
  3789. error = PTR_ERR(handle);
  3790. goto err_out;
  3791. }
  3792. error = ext4_orphan_add(handle, inode);
  3793. EXT4_I(inode)->i_disksize = attr->ia_size;
  3794. rc = ext4_mark_inode_dirty(handle, inode);
  3795. if (!error)
  3796. error = rc;
  3797. ext4_journal_stop(handle);
  3798. if (ext4_should_order_data(inode)) {
  3799. error = ext4_begin_ordered_truncate(inode,
  3800. attr->ia_size);
  3801. if (error) {
  3802. /* Do as much error cleanup as possible */
  3803. handle = ext4_journal_start(inode, 3);
  3804. if (IS_ERR(handle)) {
  3805. ext4_orphan_del(NULL, inode);
  3806. goto err_out;
  3807. }
  3808. ext4_orphan_del(handle, inode);
  3809. ext4_journal_stop(handle);
  3810. goto err_out;
  3811. }
  3812. }
  3813. }
  3814. rc = inode_setattr(inode, attr);
  3815. /* If inode_setattr's call to ext4_truncate failed to get a
  3816. * transaction handle at all, we need to clean up the in-core
  3817. * orphan list manually. */
  3818. if (inode->i_nlink)
  3819. ext4_orphan_del(NULL, inode);
  3820. if (!rc && (ia_valid & ATTR_MODE))
  3821. rc = ext4_acl_chmod(inode);
  3822. err_out:
  3823. ext4_std_error(inode->i_sb, error);
  3824. if (!error)
  3825. error = rc;
  3826. return error;
  3827. }
  3828. int ext4_getattr(struct vfsmount *mnt, struct dentry *dentry,
  3829. struct kstat *stat)
  3830. {
  3831. struct inode *inode;
  3832. unsigned long delalloc_blocks;
  3833. inode = dentry->d_inode;
  3834. generic_fillattr(inode, stat);
  3835. /*
  3836. * We can't update i_blocks if the block allocation is delayed
  3837. * otherwise in the case of system crash before the real block
  3838. * allocation is done, we will have i_blocks inconsistent with
  3839. * on-disk file blocks.
  3840. * We always keep i_blocks updated together with real
  3841. * allocation. But to not confuse with user, stat
  3842. * will return the blocks that include the delayed allocation
  3843. * blocks for this file.
  3844. */
  3845. spin_lock(&EXT4_I(inode)->i_block_reservation_lock);
  3846. delalloc_blocks = EXT4_I(inode)->i_reserved_data_blocks;
  3847. spin_unlock(&EXT4_I(inode)->i_block_reservation_lock);
  3848. stat->blocks += (delalloc_blocks << inode->i_sb->s_blocksize_bits)>>9;
  3849. return 0;
  3850. }
  3851. /*
  3852. * How many blocks doth make a writepage()?
  3853. *
  3854. * With N blocks per page, it may be:
  3855. * N data blocks
  3856. * 2 indirect block
  3857. * 2 dindirect
  3858. * 1 tindirect
  3859. * N+5 bitmap blocks (from the above)
  3860. * N+5 group descriptor summary blocks
  3861. * 1 inode block
  3862. * 1 superblock.
  3863. * 2 * EXT4_SINGLEDATA_TRANS_BLOCKS for the quote files
  3864. *
  3865. * 3 * (N + 5) + 2 + 2 * EXT4_SINGLEDATA_TRANS_BLOCKS
  3866. *
  3867. * With ordered or writeback data it's the same, less the N data blocks.
  3868. *
  3869. * If the inode's direct blocks can hold an integral number of pages then a
  3870. * page cannot straddle two indirect blocks, and we can only touch one indirect
  3871. * and dindirect block, and the "5" above becomes "3".
  3872. *
  3873. * This still overestimates under most circumstances. If we were to pass the
  3874. * start and end offsets in here as well we could do block_to_path() on each
  3875. * block and work out the exact number of indirects which are touched. Pah.
  3876. */
  3877. int ext4_writepage_trans_blocks(struct inode *inode)
  3878. {
  3879. int bpp = ext4_journal_blocks_per_page(inode);
  3880. int indirects = (EXT4_NDIR_BLOCKS % bpp) ? 5 : 3;
  3881. int ret;
  3882. if (EXT4_I(inode)->i_flags & EXT4_EXTENTS_FL)
  3883. return ext4_ext_writepage_trans_blocks(inode, bpp);
  3884. if (ext4_should_journal_data(inode))
  3885. ret = 3 * (bpp + indirects) + 2;
  3886. else
  3887. ret = 2 * (bpp + indirects) + 2;
  3888. #ifdef CONFIG_QUOTA
  3889. /* We know that structure was already allocated during DQUOT_INIT so
  3890. * we will be updating only the data blocks + inodes */
  3891. ret += 2*EXT4_QUOTA_TRANS_BLOCKS(inode->i_sb);
  3892. #endif
  3893. return ret;
  3894. }
  3895. /*
  3896. * The caller must have previously called ext4_reserve_inode_write().
  3897. * Give this, we know that the caller already has write access to iloc->bh.
  3898. */
  3899. int ext4_mark_iloc_dirty(handle_t *handle,
  3900. struct inode *inode, struct ext4_iloc *iloc)
  3901. {
  3902. int err = 0;
  3903. if (test_opt(inode->i_sb, I_VERSION))
  3904. inode_inc_iversion(inode);
  3905. /* the do_update_inode consumes one bh->b_count */
  3906. get_bh(iloc->bh);
  3907. /* ext4_do_update_inode() does jbd2_journal_dirty_metadata */
  3908. err = ext4_do_update_inode(handle, inode, iloc);
  3909. put_bh(iloc->bh);
  3910. return err;
  3911. }
  3912. /*
  3913. * On success, We end up with an outstanding reference count against
  3914. * iloc->bh. This _must_ be cleaned up later.
  3915. */
  3916. int
  3917. ext4_reserve_inode_write(handle_t *handle, struct inode *inode,
  3918. struct ext4_iloc *iloc)
  3919. {
  3920. int err = 0;
  3921. if (handle) {
  3922. err = ext4_get_inode_loc(inode, iloc);
  3923. if (!err) {
  3924. BUFFER_TRACE(iloc->bh, "get_write_access");
  3925. err = ext4_journal_get_write_access(handle, iloc->bh);
  3926. if (err) {
  3927. brelse(iloc->bh);
  3928. iloc->bh = NULL;
  3929. }
  3930. }
  3931. }
  3932. ext4_std_error(inode->i_sb, err);
  3933. return err;
  3934. }
  3935. /*
  3936. * Expand an inode by new_extra_isize bytes.
  3937. * Returns 0 on success or negative error number on failure.
  3938. */
  3939. static int ext4_expand_extra_isize(struct inode *inode,
  3940. unsigned int new_extra_isize,
  3941. struct ext4_iloc iloc,
  3942. handle_t *handle)
  3943. {
  3944. struct ext4_inode *raw_inode;
  3945. struct ext4_xattr_ibody_header *header;
  3946. struct ext4_xattr_entry *entry;
  3947. if (EXT4_I(inode)->i_extra_isize >= new_extra_isize)
  3948. return 0;
  3949. raw_inode = ext4_raw_inode(&iloc);
  3950. header = IHDR(inode, raw_inode);
  3951. entry = IFIRST(header);
  3952. /* No extended attributes present */
  3953. if (!(EXT4_I(inode)->i_state & EXT4_STATE_XATTR) ||
  3954. header->h_magic != cpu_to_le32(EXT4_XATTR_MAGIC)) {
  3955. memset((void *)raw_inode + EXT4_GOOD_OLD_INODE_SIZE, 0,
  3956. new_extra_isize);
  3957. EXT4_I(inode)->i_extra_isize = new_extra_isize;
  3958. return 0;
  3959. }
  3960. /* try to expand with EAs present */
  3961. return ext4_expand_extra_isize_ea(inode, new_extra_isize,
  3962. raw_inode, handle);
  3963. }
  3964. /*
  3965. * What we do here is to mark the in-core inode as clean with respect to inode
  3966. * dirtiness (it may still be data-dirty).
  3967. * This means that the in-core inode may be reaped by prune_icache
  3968. * without having to perform any I/O. This is a very good thing,
  3969. * because *any* task may call prune_icache - even ones which
  3970. * have a transaction open against a different journal.
  3971. *
  3972. * Is this cheating? Not really. Sure, we haven't written the
  3973. * inode out, but prune_icache isn't a user-visible syncing function.
  3974. * Whenever the user wants stuff synced (sys_sync, sys_msync, sys_fsync)
  3975. * we start and wait on commits.
  3976. *
  3977. * Is this efficient/effective? Well, we're being nice to the system
  3978. * by cleaning up our inodes proactively so they can be reaped
  3979. * without I/O. But we are potentially leaving up to five seconds'
  3980. * worth of inodes floating about which prune_icache wants us to
  3981. * write out. One way to fix that would be to get prune_icache()
  3982. * to do a write_super() to free up some memory. It has the desired
  3983. * effect.
  3984. */
  3985. int ext4_mark_inode_dirty(handle_t *handle, struct inode *inode)
  3986. {
  3987. struct ext4_iloc iloc;
  3988. struct ext4_sb_info *sbi = EXT4_SB(inode->i_sb);
  3989. static unsigned int mnt_count;
  3990. int err, ret;
  3991. might_sleep();
  3992. err = ext4_reserve_inode_write(handle, inode, &iloc);
  3993. if (EXT4_I(inode)->i_extra_isize < sbi->s_want_extra_isize &&
  3994. !(EXT4_I(inode)->i_state & EXT4_STATE_NO_EXPAND)) {
  3995. /*
  3996. * We need extra buffer credits since we may write into EA block
  3997. * with this same handle. If journal_extend fails, then it will
  3998. * only result in a minor loss of functionality for that inode.
  3999. * If this is felt to be critical, then e2fsck should be run to
  4000. * force a large enough s_min_extra_isize.
  4001. */
  4002. if ((jbd2_journal_extend(handle,
  4003. EXT4_DATA_TRANS_BLOCKS(inode->i_sb))) == 0) {
  4004. ret = ext4_expand_extra_isize(inode,
  4005. sbi->s_want_extra_isize,
  4006. iloc, handle);
  4007. if (ret) {
  4008. EXT4_I(inode)->i_state |= EXT4_STATE_NO_EXPAND;
  4009. if (mnt_count !=
  4010. le16_to_cpu(sbi->s_es->s_mnt_count)) {
  4011. ext4_warning(inode->i_sb, __func__,
  4012. "Unable to expand inode %lu. Delete"
  4013. " some EAs or run e2fsck.",
  4014. inode->i_ino);
  4015. mnt_count =
  4016. le16_to_cpu(sbi->s_es->s_mnt_count);
  4017. }
  4018. }
  4019. }
  4020. }
  4021. if (!err)
  4022. err = ext4_mark_iloc_dirty(handle, inode, &iloc);
  4023. return err;
  4024. }
  4025. /*
  4026. * ext4_dirty_inode() is called from __mark_inode_dirty()
  4027. *
  4028. * We're really interested in the case where a file is being extended.
  4029. * i_size has been changed by generic_commit_write() and we thus need
  4030. * to include the updated inode in the current transaction.
  4031. *
  4032. * Also, DQUOT_ALLOC_SPACE() will always dirty the inode when blocks
  4033. * are allocated to the file.
  4034. *
  4035. * If the inode is marked synchronous, we don't honour that here - doing
  4036. * so would cause a commit on atime updates, which we don't bother doing.
  4037. * We handle synchronous inodes at the highest possible level.
  4038. */
  4039. void ext4_dirty_inode(struct inode *inode)
  4040. {
  4041. handle_t *current_handle = ext4_journal_current_handle();
  4042. handle_t *handle;
  4043. handle = ext4_journal_start(inode, 2);
  4044. if (IS_ERR(handle))
  4045. goto out;
  4046. if (current_handle &&
  4047. current_handle->h_transaction != handle->h_transaction) {
  4048. /* This task has a transaction open against a different fs */
  4049. printk(KERN_EMERG "%s: transactions do not match!\n",
  4050. __func__);
  4051. } else {
  4052. jbd_debug(5, "marking dirty. outer handle=%p\n",
  4053. current_handle);
  4054. ext4_mark_inode_dirty(handle, inode);
  4055. }
  4056. ext4_journal_stop(handle);
  4057. out:
  4058. return;
  4059. }
  4060. #if 0
  4061. /*
  4062. * Bind an inode's backing buffer_head into this transaction, to prevent
  4063. * it from being flushed to disk early. Unlike
  4064. * ext4_reserve_inode_write, this leaves behind no bh reference and
  4065. * returns no iloc structure, so the caller needs to repeat the iloc
  4066. * lookup to mark the inode dirty later.
  4067. */
  4068. static int ext4_pin_inode(handle_t *handle, struct inode *inode)
  4069. {
  4070. struct ext4_iloc iloc;
  4071. int err = 0;
  4072. if (handle) {
  4073. err = ext4_get_inode_loc(inode, &iloc);
  4074. if (!err) {
  4075. BUFFER_TRACE(iloc.bh, "get_write_access");
  4076. err = jbd2_journal_get_write_access(handle, iloc.bh);
  4077. if (!err)
  4078. err = ext4_journal_dirty_metadata(handle,
  4079. iloc.bh);
  4080. brelse(iloc.bh);
  4081. }
  4082. }
  4083. ext4_std_error(inode->i_sb, err);
  4084. return err;
  4085. }
  4086. #endif
  4087. int ext4_change_inode_journal_flag(struct inode *inode, int val)
  4088. {
  4089. journal_t *journal;
  4090. handle_t *handle;
  4091. int err;
  4092. /*
  4093. * We have to be very careful here: changing a data block's
  4094. * journaling status dynamically is dangerous. If we write a
  4095. * data block to the journal, change the status and then delete
  4096. * that block, we risk forgetting to revoke the old log record
  4097. * from the journal and so a subsequent replay can corrupt data.
  4098. * So, first we make sure that the journal is empty and that
  4099. * nobody is changing anything.
  4100. */
  4101. journal = EXT4_JOURNAL(inode);
  4102. if (is_journal_aborted(journal))
  4103. return -EROFS;
  4104. jbd2_journal_lock_updates(journal);
  4105. jbd2_journal_flush(journal);
  4106. /*
  4107. * OK, there are no updates running now, and all cached data is
  4108. * synced to disk. We are now in a completely consistent state
  4109. * which doesn't have anything in the journal, and we know that
  4110. * no filesystem updates are running, so it is safe to modify
  4111. * the inode's in-core data-journaling state flag now.
  4112. */
  4113. if (val)
  4114. EXT4_I(inode)->i_flags |= EXT4_JOURNAL_DATA_FL;
  4115. else
  4116. EXT4_I(inode)->i_flags &= ~EXT4_JOURNAL_DATA_FL;
  4117. ext4_set_aops(inode);
  4118. jbd2_journal_unlock_updates(journal);
  4119. /* Finally we can mark the inode as dirty. */
  4120. handle = ext4_journal_start(inode, 1);
  4121. if (IS_ERR(handle))
  4122. return PTR_ERR(handle);
  4123. err = ext4_mark_inode_dirty(handle, inode);
  4124. handle->h_sync = 1;
  4125. ext4_journal_stop(handle);
  4126. ext4_std_error(inode->i_sb, err);
  4127. return err;
  4128. }
  4129. static int ext4_bh_unmapped(handle_t *handle, struct buffer_head *bh)
  4130. {
  4131. return !buffer_mapped(bh);
  4132. }
  4133. int ext4_page_mkwrite(struct vm_area_struct *vma, struct page *page)
  4134. {
  4135. loff_t size;
  4136. unsigned long len;
  4137. int ret = -EINVAL;
  4138. struct file *file = vma->vm_file;
  4139. struct inode *inode = file->f_path.dentry->d_inode;
  4140. struct address_space *mapping = inode->i_mapping;
  4141. /*
  4142. * Get i_alloc_sem to stop truncates messing with the inode. We cannot
  4143. * get i_mutex because we are already holding mmap_sem.
  4144. */
  4145. down_read(&inode->i_alloc_sem);
  4146. size = i_size_read(inode);
  4147. if (page->mapping != mapping || size <= page_offset(page)
  4148. || !PageUptodate(page)) {
  4149. /* page got truncated from under us? */
  4150. goto out_unlock;
  4151. }
  4152. ret = 0;
  4153. if (PageMappedToDisk(page))
  4154. goto out_unlock;
  4155. if (page->index == size >> PAGE_CACHE_SHIFT)
  4156. len = size & ~PAGE_CACHE_MASK;
  4157. else
  4158. len = PAGE_CACHE_SIZE;
  4159. if (page_has_buffers(page)) {
  4160. /* return if we have all the buffers mapped */
  4161. if (!walk_page_buffers(NULL, page_buffers(page), 0, len, NULL,
  4162. ext4_bh_unmapped))
  4163. goto out_unlock;
  4164. }
  4165. /*
  4166. * OK, we need to fill the hole... Do write_begin write_end
  4167. * to do block allocation/reservation.We are not holding
  4168. * inode.i__mutex here. That allow * parallel write_begin,
  4169. * write_end call. lock_page prevent this from happening
  4170. * on the same page though
  4171. */
  4172. ret = mapping->a_ops->write_begin(file, mapping, page_offset(page),
  4173. len, AOP_FLAG_UNINTERRUPTIBLE, &page, NULL);
  4174. if (ret < 0)
  4175. goto out_unlock;
  4176. ret = mapping->a_ops->write_end(file, mapping, page_offset(page),
  4177. len, len, page, NULL);
  4178. if (ret < 0)
  4179. goto out_unlock;
  4180. ret = 0;
  4181. out_unlock:
  4182. up_read(&inode->i_alloc_sem);
  4183. return ret;
  4184. }