inode.c 178 KB

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