inode.c 173 KB

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