inode.c 174 KB

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