inode.c 176 KB

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