inode.c 174 KB

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