inode.c 151 KB

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