inode.c 172 KB

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