inode.c 148 KB

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