inode.c 154 KB

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