inode.c 182 KB

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