inode.c 173 KB

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