inode.c 169 KB

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