inode.c 297 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Copyright (C) 2007 Oracle. All rights reserved.
  4. */
  5. #include <crypto/hash.h>
  6. #include <linux/kernel.h>
  7. #include <linux/bio.h>
  8. #include <linux/blk-cgroup.h>
  9. #include <linux/file.h>
  10. #include <linux/fs.h>
  11. #include <linux/pagemap.h>
  12. #include <linux/highmem.h>
  13. #include <linux/time.h>
  14. #include <linux/init.h>
  15. #include <linux/string.h>
  16. #include <linux/backing-dev.h>
  17. #include <linux/writeback.h>
  18. #include <linux/compat.h>
  19. #include <linux/xattr.h>
  20. #include <linux/posix_acl.h>
  21. #include <linux/falloc.h>
  22. #include <linux/slab.h>
  23. #include <linux/ratelimit.h>
  24. #include <linux/btrfs.h>
  25. #include <linux/blkdev.h>
  26. #include <linux/posix_acl_xattr.h>
  27. #include <linux/uio.h>
  28. #include <linux/magic.h>
  29. #include <linux/iversion.h>
  30. #include <linux/swap.h>
  31. #include <linux/migrate.h>
  32. #include <linux/sched/mm.h>
  33. #include <linux/iomap.h>
  34. #include <linux/unaligned.h>
  35. #include <linux/fsverity.h>
  36. #include "misc.h"
  37. #include "ctree.h"
  38. #include "disk-io.h"
  39. #include "transaction.h"
  40. #include "btrfs_inode.h"
  41. #include "ordered-data.h"
  42. #include "xattr.h"
  43. #include "tree-log.h"
  44. #include "bio.h"
  45. #include "compression.h"
  46. #include "locking.h"
  47. #include "props.h"
  48. #include "qgroup.h"
  49. #include "delalloc-space.h"
  50. #include "block-group.h"
  51. #include "space-info.h"
  52. #include "zoned.h"
  53. #include "subpage.h"
  54. #include "inode-item.h"
  55. #include "fs.h"
  56. #include "accessors.h"
  57. #include "extent-tree.h"
  58. #include "root-tree.h"
  59. #include "defrag.h"
  60. #include "dir-item.h"
  61. #include "file-item.h"
  62. #include "uuid-tree.h"
  63. #include "ioctl.h"
  64. #include "file.h"
  65. #include "acl.h"
  66. #include "relocation.h"
  67. #include "verity.h"
  68. #include "super.h"
  69. #include "orphan.h"
  70. #include "backref.h"
  71. #include "raid-stripe-tree.h"
  72. #include "fiemap.h"
  73. struct btrfs_iget_args {
  74. u64 ino;
  75. struct btrfs_root *root;
  76. };
  77. struct btrfs_rename_ctx {
  78. /* Output field. Stores the index number of the old directory entry. */
  79. u64 index;
  80. };
  81. /*
  82. * Used by data_reloc_print_warning_inode() to pass needed info for filename
  83. * resolution and output of error message.
  84. */
  85. struct data_reloc_warn {
  86. struct btrfs_path path;
  87. struct btrfs_fs_info *fs_info;
  88. u64 extent_item_size;
  89. u64 logical;
  90. int mirror_num;
  91. };
  92. /*
  93. * For the file_extent_tree, we want to hold the inode lock when we lookup and
  94. * update the disk_i_size, but lockdep will complain because our io_tree we hold
  95. * the tree lock and get the inode lock when setting delalloc. These two things
  96. * are unrelated, so make a class for the file_extent_tree so we don't get the
  97. * two locking patterns mixed up.
  98. */
  99. static struct lock_class_key file_extent_tree_class;
  100. static const struct inode_operations btrfs_dir_inode_operations;
  101. static const struct inode_operations btrfs_symlink_inode_operations;
  102. static const struct inode_operations btrfs_special_inode_operations;
  103. static const struct inode_operations btrfs_file_inode_operations;
  104. static const struct address_space_operations btrfs_aops;
  105. static const struct file_operations btrfs_dir_file_operations;
  106. static struct kmem_cache *btrfs_inode_cachep;
  107. static int btrfs_setsize(struct inode *inode, struct iattr *attr);
  108. static int btrfs_truncate(struct btrfs_inode *inode, bool skip_writeback);
  109. static noinline int run_delalloc_cow(struct btrfs_inode *inode,
  110. struct folio *locked_folio, u64 start,
  111. u64 end, struct writeback_control *wbc,
  112. bool pages_dirty);
  113. static int data_reloc_print_warning_inode(u64 inum, u64 offset, u64 num_bytes,
  114. u64 root, void *warn_ctx)
  115. {
  116. struct data_reloc_warn *warn = warn_ctx;
  117. struct btrfs_fs_info *fs_info = warn->fs_info;
  118. struct extent_buffer *eb;
  119. struct btrfs_inode_item *inode_item;
  120. struct inode_fs_paths *ipath = NULL;
  121. struct btrfs_root *local_root;
  122. struct btrfs_key key;
  123. unsigned int nofs_flag;
  124. u32 nlink;
  125. int ret;
  126. local_root = btrfs_get_fs_root(fs_info, root, true);
  127. if (IS_ERR(local_root)) {
  128. ret = PTR_ERR(local_root);
  129. goto err;
  130. }
  131. /* This makes the path point to (inum INODE_ITEM ioff). */
  132. key.objectid = inum;
  133. key.type = BTRFS_INODE_ITEM_KEY;
  134. key.offset = 0;
  135. ret = btrfs_search_slot(NULL, local_root, &key, &warn->path, 0, 0);
  136. if (ret) {
  137. btrfs_put_root(local_root);
  138. btrfs_release_path(&warn->path);
  139. goto err;
  140. }
  141. eb = warn->path.nodes[0];
  142. inode_item = btrfs_item_ptr(eb, warn->path.slots[0], struct btrfs_inode_item);
  143. nlink = btrfs_inode_nlink(eb, inode_item);
  144. btrfs_release_path(&warn->path);
  145. nofs_flag = memalloc_nofs_save();
  146. ipath = init_ipath(4096, local_root, &warn->path);
  147. memalloc_nofs_restore(nofs_flag);
  148. if (IS_ERR(ipath)) {
  149. btrfs_put_root(local_root);
  150. ret = PTR_ERR(ipath);
  151. ipath = NULL;
  152. /*
  153. * -ENOMEM, not a critical error, just output an generic error
  154. * without filename.
  155. */
  156. btrfs_warn(fs_info,
  157. "checksum error at logical %llu mirror %u root %llu, inode %llu offset %llu",
  158. warn->logical, warn->mirror_num, root, inum, offset);
  159. return ret;
  160. }
  161. ret = paths_from_inode(inum, ipath);
  162. if (ret < 0)
  163. goto err;
  164. /*
  165. * We deliberately ignore the bit ipath might have been too small to
  166. * hold all of the paths here
  167. */
  168. for (int i = 0; i < ipath->fspath->elem_cnt; i++) {
  169. btrfs_warn(fs_info,
  170. "checksum error at logical %llu mirror %u root %llu inode %llu offset %llu length %u links %u (path: %s)",
  171. warn->logical, warn->mirror_num, root, inum, offset,
  172. fs_info->sectorsize, nlink,
  173. (char *)(unsigned long)ipath->fspath->val[i]);
  174. }
  175. btrfs_put_root(local_root);
  176. free_ipath(ipath);
  177. return 0;
  178. err:
  179. btrfs_warn(fs_info,
  180. "checksum error at logical %llu mirror %u root %llu inode %llu offset %llu, path resolving failed with ret=%d",
  181. warn->logical, warn->mirror_num, root, inum, offset, ret);
  182. free_ipath(ipath);
  183. return ret;
  184. }
  185. /*
  186. * Do extra user-friendly error output (e.g. lookup all the affected files).
  187. *
  188. * Return true if we succeeded doing the backref lookup.
  189. * Return false if such lookup failed, and has to fallback to the old error message.
  190. */
  191. static void print_data_reloc_error(const struct btrfs_inode *inode, u64 file_off,
  192. const u8 *csum, const u8 *csum_expected,
  193. int mirror_num)
  194. {
  195. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  196. struct btrfs_path path = { 0 };
  197. struct btrfs_key found_key = { 0 };
  198. struct extent_buffer *eb;
  199. struct btrfs_extent_item *ei;
  200. const u32 csum_size = fs_info->csum_size;
  201. u64 logical;
  202. u64 flags;
  203. u32 item_size;
  204. int ret;
  205. mutex_lock(&fs_info->reloc_mutex);
  206. logical = btrfs_get_reloc_bg_bytenr(fs_info);
  207. mutex_unlock(&fs_info->reloc_mutex);
  208. if (logical == U64_MAX) {
  209. btrfs_warn_rl(fs_info, "has data reloc tree but no running relocation");
  210. btrfs_warn_rl(fs_info,
  211. "csum failed root %lld ino %llu off %llu csum " CSUM_FMT " expected csum " CSUM_FMT " mirror %d",
  212. btrfs_root_id(inode->root), btrfs_ino(inode), file_off,
  213. CSUM_FMT_VALUE(csum_size, csum),
  214. CSUM_FMT_VALUE(csum_size, csum_expected),
  215. mirror_num);
  216. return;
  217. }
  218. logical += file_off;
  219. btrfs_warn_rl(fs_info,
  220. "csum failed root %lld ino %llu off %llu logical %llu csum " CSUM_FMT " expected csum " CSUM_FMT " mirror %d",
  221. btrfs_root_id(inode->root),
  222. btrfs_ino(inode), file_off, logical,
  223. CSUM_FMT_VALUE(csum_size, csum),
  224. CSUM_FMT_VALUE(csum_size, csum_expected),
  225. mirror_num);
  226. ret = extent_from_logical(fs_info, logical, &path, &found_key, &flags);
  227. if (ret < 0) {
  228. btrfs_err_rl(fs_info, "failed to lookup extent item for logical %llu: %d",
  229. logical, ret);
  230. return;
  231. }
  232. eb = path.nodes[0];
  233. ei = btrfs_item_ptr(eb, path.slots[0], struct btrfs_extent_item);
  234. item_size = btrfs_item_size(eb, path.slots[0]);
  235. if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
  236. unsigned long ptr = 0;
  237. u64 ref_root;
  238. u8 ref_level;
  239. while (true) {
  240. ret = tree_backref_for_extent(&ptr, eb, &found_key, ei,
  241. item_size, &ref_root,
  242. &ref_level);
  243. if (ret < 0) {
  244. btrfs_warn_rl(fs_info,
  245. "failed to resolve tree backref for logical %llu: %d",
  246. logical, ret);
  247. break;
  248. }
  249. if (ret > 0)
  250. break;
  251. btrfs_warn_rl(fs_info,
  252. "csum error at logical %llu mirror %u: metadata %s (level %d) in tree %llu",
  253. logical, mirror_num,
  254. (ref_level ? "node" : "leaf"),
  255. ref_level, ref_root);
  256. }
  257. btrfs_release_path(&path);
  258. } else {
  259. struct btrfs_backref_walk_ctx ctx = { 0 };
  260. struct data_reloc_warn reloc_warn = { 0 };
  261. btrfs_release_path(&path);
  262. ctx.bytenr = found_key.objectid;
  263. ctx.extent_item_pos = logical - found_key.objectid;
  264. ctx.fs_info = fs_info;
  265. reloc_warn.logical = logical;
  266. reloc_warn.extent_item_size = found_key.offset;
  267. reloc_warn.mirror_num = mirror_num;
  268. reloc_warn.fs_info = fs_info;
  269. iterate_extent_inodes(&ctx, true,
  270. data_reloc_print_warning_inode, &reloc_warn);
  271. }
  272. }
  273. static void __cold btrfs_print_data_csum_error(struct btrfs_inode *inode,
  274. u64 logical_start, u8 *csum, u8 *csum_expected, int mirror_num)
  275. {
  276. struct btrfs_root *root = inode->root;
  277. const u32 csum_size = root->fs_info->csum_size;
  278. /* For data reloc tree, it's better to do a backref lookup instead. */
  279. if (btrfs_root_id(root) == BTRFS_DATA_RELOC_TREE_OBJECTID)
  280. return print_data_reloc_error(inode, logical_start, csum,
  281. csum_expected, mirror_num);
  282. /* Output without objectid, which is more meaningful */
  283. if (btrfs_root_id(root) >= BTRFS_LAST_FREE_OBJECTID) {
  284. btrfs_warn_rl(root->fs_info,
  285. "csum failed root %lld ino %lld off %llu csum " CSUM_FMT " expected csum " CSUM_FMT " mirror %d",
  286. btrfs_root_id(root), btrfs_ino(inode),
  287. logical_start,
  288. CSUM_FMT_VALUE(csum_size, csum),
  289. CSUM_FMT_VALUE(csum_size, csum_expected),
  290. mirror_num);
  291. } else {
  292. btrfs_warn_rl(root->fs_info,
  293. "csum failed root %llu ino %llu off %llu csum " CSUM_FMT " expected csum " CSUM_FMT " mirror %d",
  294. btrfs_root_id(root), btrfs_ino(inode),
  295. logical_start,
  296. CSUM_FMT_VALUE(csum_size, csum),
  297. CSUM_FMT_VALUE(csum_size, csum_expected),
  298. mirror_num);
  299. }
  300. }
  301. /*
  302. * Lock inode i_rwsem based on arguments passed.
  303. *
  304. * ilock_flags can have the following bit set:
  305. *
  306. * BTRFS_ILOCK_SHARED - acquire a shared lock on the inode
  307. * BTRFS_ILOCK_TRY - try to acquire the lock, if fails on first attempt
  308. * return -EAGAIN
  309. * BTRFS_ILOCK_MMAP - acquire a write lock on the i_mmap_lock
  310. */
  311. int btrfs_inode_lock(struct btrfs_inode *inode, unsigned int ilock_flags)
  312. {
  313. if (ilock_flags & BTRFS_ILOCK_SHARED) {
  314. if (ilock_flags & BTRFS_ILOCK_TRY) {
  315. if (!inode_trylock_shared(&inode->vfs_inode))
  316. return -EAGAIN;
  317. else
  318. return 0;
  319. }
  320. inode_lock_shared(&inode->vfs_inode);
  321. } else {
  322. if (ilock_flags & BTRFS_ILOCK_TRY) {
  323. if (!inode_trylock(&inode->vfs_inode))
  324. return -EAGAIN;
  325. else
  326. return 0;
  327. }
  328. inode_lock(&inode->vfs_inode);
  329. }
  330. if (ilock_flags & BTRFS_ILOCK_MMAP)
  331. down_write(&inode->i_mmap_lock);
  332. return 0;
  333. }
  334. /*
  335. * Unock inode i_rwsem.
  336. *
  337. * ilock_flags should contain the same bits set as passed to btrfs_inode_lock()
  338. * to decide whether the lock acquired is shared or exclusive.
  339. */
  340. void btrfs_inode_unlock(struct btrfs_inode *inode, unsigned int ilock_flags)
  341. {
  342. if (ilock_flags & BTRFS_ILOCK_MMAP)
  343. up_write(&inode->i_mmap_lock);
  344. if (ilock_flags & BTRFS_ILOCK_SHARED)
  345. inode_unlock_shared(&inode->vfs_inode);
  346. else
  347. inode_unlock(&inode->vfs_inode);
  348. }
  349. /*
  350. * Cleanup all submitted ordered extents in specified range to handle errors
  351. * from the btrfs_run_delalloc_range() callback.
  352. *
  353. * NOTE: caller must ensure that when an error happens, it can not call
  354. * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
  355. * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
  356. * to be released, which we want to happen only when finishing the ordered
  357. * extent (btrfs_finish_ordered_io()).
  358. */
  359. static inline void btrfs_cleanup_ordered_extents(struct btrfs_inode *inode,
  360. struct folio *locked_folio,
  361. u64 offset, u64 bytes)
  362. {
  363. unsigned long index = offset >> PAGE_SHIFT;
  364. unsigned long end_index = (offset + bytes - 1) >> PAGE_SHIFT;
  365. u64 page_start = 0, page_end = 0;
  366. struct folio *folio;
  367. if (locked_folio) {
  368. page_start = folio_pos(locked_folio);
  369. page_end = page_start + folio_size(locked_folio) - 1;
  370. }
  371. while (index <= end_index) {
  372. /*
  373. * For locked page, we will call btrfs_mark_ordered_io_finished
  374. * through btrfs_mark_ordered_io_finished() on it
  375. * in run_delalloc_range() for the error handling, which will
  376. * clear page Ordered and run the ordered extent accounting.
  377. *
  378. * Here we can't just clear the Ordered bit, or
  379. * btrfs_mark_ordered_io_finished() would skip the accounting
  380. * for the page range, and the ordered extent will never finish.
  381. */
  382. if (locked_folio && index == (page_start >> PAGE_SHIFT)) {
  383. index++;
  384. continue;
  385. }
  386. folio = __filemap_get_folio(inode->vfs_inode.i_mapping, index, 0, 0);
  387. index++;
  388. if (IS_ERR(folio))
  389. continue;
  390. /*
  391. * Here we just clear all Ordered bits for every page in the
  392. * range, then btrfs_mark_ordered_io_finished() will handle
  393. * the ordered extent accounting for the range.
  394. */
  395. btrfs_folio_clamp_clear_ordered(inode->root->fs_info, folio,
  396. offset, bytes);
  397. folio_put(folio);
  398. }
  399. if (locked_folio) {
  400. /* The locked page covers the full range, nothing needs to be done */
  401. if (bytes + offset <= page_start + folio_size(locked_folio))
  402. return;
  403. /*
  404. * In case this page belongs to the delalloc range being
  405. * instantiated then skip it, since the first page of a range is
  406. * going to be properly cleaned up by the caller of
  407. * run_delalloc_range
  408. */
  409. if (page_start >= offset && page_end <= (offset + bytes - 1)) {
  410. bytes = offset + bytes - folio_pos(locked_folio) -
  411. folio_size(locked_folio);
  412. offset = folio_pos(locked_folio) + folio_size(locked_folio);
  413. }
  414. }
  415. return btrfs_mark_ordered_io_finished(inode, NULL, offset, bytes, false);
  416. }
  417. static int btrfs_dirty_inode(struct btrfs_inode *inode);
  418. static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
  419. struct btrfs_new_inode_args *args)
  420. {
  421. int err;
  422. if (args->default_acl) {
  423. err = __btrfs_set_acl(trans, args->inode, args->default_acl,
  424. ACL_TYPE_DEFAULT);
  425. if (err)
  426. return err;
  427. }
  428. if (args->acl) {
  429. err = __btrfs_set_acl(trans, args->inode, args->acl, ACL_TYPE_ACCESS);
  430. if (err)
  431. return err;
  432. }
  433. if (!args->default_acl && !args->acl)
  434. cache_no_acl(args->inode);
  435. return btrfs_xattr_security_init(trans, args->inode, args->dir,
  436. &args->dentry->d_name);
  437. }
  438. /*
  439. * this does all the hard work for inserting an inline extent into
  440. * the btree. The caller should have done a btrfs_drop_extents so that
  441. * no overlapping inline items exist in the btree
  442. */
  443. static int insert_inline_extent(struct btrfs_trans_handle *trans,
  444. struct btrfs_path *path,
  445. struct btrfs_inode *inode, bool extent_inserted,
  446. size_t size, size_t compressed_size,
  447. int compress_type,
  448. struct folio *compressed_folio,
  449. bool update_i_size)
  450. {
  451. struct btrfs_root *root = inode->root;
  452. struct extent_buffer *leaf;
  453. const u32 sectorsize = trans->fs_info->sectorsize;
  454. char *kaddr;
  455. unsigned long ptr;
  456. struct btrfs_file_extent_item *ei;
  457. int ret;
  458. size_t cur_size = size;
  459. u64 i_size;
  460. /*
  461. * The decompressed size must still be no larger than a sector. Under
  462. * heavy race, we can have size == 0 passed in, but that shouldn't be a
  463. * big deal and we can continue the insertion.
  464. */
  465. ASSERT(size <= sectorsize);
  466. /*
  467. * The compressed size also needs to be no larger than a sector.
  468. * That's also why we only need one page as the parameter.
  469. */
  470. if (compressed_folio)
  471. ASSERT(compressed_size <= sectorsize);
  472. else
  473. ASSERT(compressed_size == 0);
  474. if (compressed_size && compressed_folio)
  475. cur_size = compressed_size;
  476. if (!extent_inserted) {
  477. struct btrfs_key key;
  478. size_t datasize;
  479. key.objectid = btrfs_ino(inode);
  480. key.offset = 0;
  481. key.type = BTRFS_EXTENT_DATA_KEY;
  482. datasize = btrfs_file_extent_calc_inline_size(cur_size);
  483. ret = btrfs_insert_empty_item(trans, root, path, &key,
  484. datasize);
  485. if (ret)
  486. goto fail;
  487. }
  488. leaf = path->nodes[0];
  489. ei = btrfs_item_ptr(leaf, path->slots[0],
  490. struct btrfs_file_extent_item);
  491. btrfs_set_file_extent_generation(leaf, ei, trans->transid);
  492. btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
  493. btrfs_set_file_extent_encryption(leaf, ei, 0);
  494. btrfs_set_file_extent_other_encoding(leaf, ei, 0);
  495. btrfs_set_file_extent_ram_bytes(leaf, ei, size);
  496. ptr = btrfs_file_extent_inline_start(ei);
  497. if (compress_type != BTRFS_COMPRESS_NONE) {
  498. kaddr = kmap_local_folio(compressed_folio, 0);
  499. write_extent_buffer(leaf, kaddr, ptr, compressed_size);
  500. kunmap_local(kaddr);
  501. btrfs_set_file_extent_compression(leaf, ei,
  502. compress_type);
  503. } else {
  504. struct folio *folio;
  505. folio = __filemap_get_folio(inode->vfs_inode.i_mapping,
  506. 0, 0, 0);
  507. ASSERT(!IS_ERR(folio));
  508. btrfs_set_file_extent_compression(leaf, ei, 0);
  509. kaddr = kmap_local_folio(folio, 0);
  510. write_extent_buffer(leaf, kaddr, ptr, size);
  511. kunmap_local(kaddr);
  512. folio_put(folio);
  513. }
  514. btrfs_mark_buffer_dirty(trans, leaf);
  515. btrfs_release_path(path);
  516. /*
  517. * We align size to sectorsize for inline extents just for simplicity
  518. * sake.
  519. */
  520. ret = btrfs_inode_set_file_extent_range(inode, 0,
  521. ALIGN(size, root->fs_info->sectorsize));
  522. if (ret)
  523. goto fail;
  524. /*
  525. * We're an inline extent, so nobody can extend the file past i_size
  526. * without locking a page we already have locked.
  527. *
  528. * We must do any i_size and inode updates before we unlock the pages.
  529. * Otherwise we could end up racing with unlink.
  530. */
  531. i_size = i_size_read(&inode->vfs_inode);
  532. if (update_i_size && size > i_size) {
  533. i_size_write(&inode->vfs_inode, size);
  534. i_size = size;
  535. }
  536. inode->disk_i_size = i_size;
  537. fail:
  538. return ret;
  539. }
  540. static bool can_cow_file_range_inline(struct btrfs_inode *inode,
  541. u64 offset, u64 size,
  542. size_t compressed_size)
  543. {
  544. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  545. u64 data_len = (compressed_size ?: size);
  546. /* Inline extents must start at offset 0. */
  547. if (offset != 0)
  548. return false;
  549. /*
  550. * Due to the page size limit, for subpage we can only trigger the
  551. * writeback for the dirty sectors of page, that means data writeback
  552. * is doing more writeback than what we want.
  553. *
  554. * This is especially unexpected for some call sites like fallocate,
  555. * where we only increase i_size after everything is done.
  556. * This means we can trigger inline extent even if we didn't want to.
  557. * So here we skip inline extent creation completely.
  558. */
  559. if (fs_info->sectorsize != PAGE_SIZE)
  560. return false;
  561. /* Inline extents are limited to sectorsize. */
  562. if (size > fs_info->sectorsize)
  563. return false;
  564. /* We cannot exceed the maximum inline data size. */
  565. if (data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
  566. return false;
  567. /* We cannot exceed the user specified max_inline size. */
  568. if (data_len > fs_info->max_inline)
  569. return false;
  570. /* Inline extents must be the entirety of the file. */
  571. if (size < i_size_read(&inode->vfs_inode))
  572. return false;
  573. return true;
  574. }
  575. /*
  576. * conditionally insert an inline extent into the file. This
  577. * does the checks required to make sure the data is small enough
  578. * to fit as an inline extent.
  579. *
  580. * If being used directly, you must have already checked we're allowed to cow
  581. * the range by getting true from can_cow_file_range_inline().
  582. */
  583. static noinline int __cow_file_range_inline(struct btrfs_inode *inode, u64 offset,
  584. u64 size, size_t compressed_size,
  585. int compress_type,
  586. struct folio *compressed_folio,
  587. bool update_i_size)
  588. {
  589. struct btrfs_drop_extents_args drop_args = { 0 };
  590. struct btrfs_root *root = inode->root;
  591. struct btrfs_fs_info *fs_info = root->fs_info;
  592. struct btrfs_trans_handle *trans;
  593. u64 data_len = (compressed_size ?: size);
  594. int ret;
  595. struct btrfs_path *path;
  596. path = btrfs_alloc_path();
  597. if (!path)
  598. return -ENOMEM;
  599. trans = btrfs_join_transaction(root);
  600. if (IS_ERR(trans)) {
  601. btrfs_free_path(path);
  602. return PTR_ERR(trans);
  603. }
  604. trans->block_rsv = &inode->block_rsv;
  605. drop_args.path = path;
  606. drop_args.start = 0;
  607. drop_args.end = fs_info->sectorsize;
  608. drop_args.drop_cache = true;
  609. drop_args.replace_extent = true;
  610. drop_args.extent_item_size = btrfs_file_extent_calc_inline_size(data_len);
  611. ret = btrfs_drop_extents(trans, root, inode, &drop_args);
  612. if (ret) {
  613. btrfs_abort_transaction(trans, ret);
  614. goto out;
  615. }
  616. ret = insert_inline_extent(trans, path, inode, drop_args.extent_inserted,
  617. size, compressed_size, compress_type,
  618. compressed_folio, update_i_size);
  619. if (ret && ret != -ENOSPC) {
  620. btrfs_abort_transaction(trans, ret);
  621. goto out;
  622. } else if (ret == -ENOSPC) {
  623. ret = 1;
  624. goto out;
  625. }
  626. btrfs_update_inode_bytes(inode, size, drop_args.bytes_found);
  627. ret = btrfs_update_inode(trans, inode);
  628. if (ret && ret != -ENOSPC) {
  629. btrfs_abort_transaction(trans, ret);
  630. goto out;
  631. } else if (ret == -ENOSPC) {
  632. ret = 1;
  633. goto out;
  634. }
  635. btrfs_set_inode_full_sync(inode);
  636. out:
  637. /*
  638. * Don't forget to free the reserved space, as for inlined extent
  639. * it won't count as data extent, free them directly here.
  640. * And at reserve time, it's always aligned to page size, so
  641. * just free one page here.
  642. */
  643. btrfs_qgroup_free_data(inode, NULL, 0, PAGE_SIZE, NULL);
  644. btrfs_free_path(path);
  645. btrfs_end_transaction(trans);
  646. return ret;
  647. }
  648. static noinline int cow_file_range_inline(struct btrfs_inode *inode,
  649. struct folio *locked_folio,
  650. u64 offset, u64 end,
  651. size_t compressed_size,
  652. int compress_type,
  653. struct folio *compressed_folio,
  654. bool update_i_size)
  655. {
  656. struct extent_state *cached = NULL;
  657. unsigned long clear_flags = EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
  658. EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING | EXTENT_LOCKED;
  659. u64 size = min_t(u64, i_size_read(&inode->vfs_inode), end + 1);
  660. int ret;
  661. if (!can_cow_file_range_inline(inode, offset, size, compressed_size))
  662. return 1;
  663. lock_extent(&inode->io_tree, offset, end, &cached);
  664. ret = __cow_file_range_inline(inode, offset, size, compressed_size,
  665. compress_type, compressed_folio,
  666. update_i_size);
  667. if (ret > 0) {
  668. unlock_extent(&inode->io_tree, offset, end, &cached);
  669. return ret;
  670. }
  671. /*
  672. * In the successful case (ret == 0 here), cow_file_range will return 1.
  673. *
  674. * Quite a bit further up the callstack in extent_writepage(), ret == 1
  675. * is treated as a short circuited success and does not unlock the folio,
  676. * so we must do it here.
  677. *
  678. * In the failure case, the locked_folio does get unlocked by
  679. * btrfs_folio_end_all_writers, which asserts that it is still locked
  680. * at that point, so we must *not* unlock it here.
  681. *
  682. * The other two callsites in compress_file_range do not have a
  683. * locked_folio, so they are not relevant to this logic.
  684. */
  685. if (ret == 0)
  686. locked_folio = NULL;
  687. extent_clear_unlock_delalloc(inode, offset, end, locked_folio, &cached,
  688. clear_flags, PAGE_UNLOCK |
  689. PAGE_START_WRITEBACK | PAGE_END_WRITEBACK);
  690. return ret;
  691. }
  692. struct async_extent {
  693. u64 start;
  694. u64 ram_size;
  695. u64 compressed_size;
  696. struct folio **folios;
  697. unsigned long nr_folios;
  698. int compress_type;
  699. struct list_head list;
  700. };
  701. struct async_chunk {
  702. struct btrfs_inode *inode;
  703. struct folio *locked_folio;
  704. u64 start;
  705. u64 end;
  706. blk_opf_t write_flags;
  707. struct list_head extents;
  708. struct cgroup_subsys_state *blkcg_css;
  709. struct btrfs_work work;
  710. struct async_cow *async_cow;
  711. };
  712. struct async_cow {
  713. atomic_t num_chunks;
  714. struct async_chunk chunks[];
  715. };
  716. static noinline int add_async_extent(struct async_chunk *cow,
  717. u64 start, u64 ram_size,
  718. u64 compressed_size,
  719. struct folio **folios,
  720. unsigned long nr_folios,
  721. int compress_type)
  722. {
  723. struct async_extent *async_extent;
  724. async_extent = kmalloc(sizeof(*async_extent), GFP_NOFS);
  725. if (!async_extent)
  726. return -ENOMEM;
  727. async_extent->start = start;
  728. async_extent->ram_size = ram_size;
  729. async_extent->compressed_size = compressed_size;
  730. async_extent->folios = folios;
  731. async_extent->nr_folios = nr_folios;
  732. async_extent->compress_type = compress_type;
  733. list_add_tail(&async_extent->list, &cow->extents);
  734. return 0;
  735. }
  736. /*
  737. * Check if the inode needs to be submitted to compression, based on mount
  738. * options, defragmentation, properties or heuristics.
  739. */
  740. static inline int inode_need_compress(struct btrfs_inode *inode, u64 start,
  741. u64 end)
  742. {
  743. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  744. if (!btrfs_inode_can_compress(inode)) {
  745. WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
  746. KERN_ERR "BTRFS: unexpected compression for ino %llu\n",
  747. btrfs_ino(inode));
  748. return 0;
  749. }
  750. /*
  751. * Special check for subpage.
  752. *
  753. * We lock the full page then run each delalloc range in the page, thus
  754. * for the following case, we will hit some subpage specific corner case:
  755. *
  756. * 0 32K 64K
  757. * | |///////| |///////|
  758. * \- A \- B
  759. *
  760. * In above case, both range A and range B will try to unlock the full
  761. * page [0, 64K), causing the one finished later will have page
  762. * unlocked already, triggering various page lock requirement BUG_ON()s.
  763. *
  764. * So here we add an artificial limit that subpage compression can only
  765. * if the range is fully page aligned.
  766. *
  767. * In theory we only need to ensure the first page is fully covered, but
  768. * the tailing partial page will be locked until the full compression
  769. * finishes, delaying the write of other range.
  770. *
  771. * TODO: Make btrfs_run_delalloc_range() to lock all delalloc range
  772. * first to prevent any submitted async extent to unlock the full page.
  773. * By this, we can ensure for subpage case that only the last async_cow
  774. * will unlock the full page.
  775. */
  776. if (fs_info->sectorsize < PAGE_SIZE) {
  777. if (!PAGE_ALIGNED(start) ||
  778. !PAGE_ALIGNED(end + 1))
  779. return 0;
  780. }
  781. /* force compress */
  782. if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
  783. return 1;
  784. /* defrag ioctl */
  785. if (inode->defrag_compress)
  786. return 1;
  787. /* bad compression ratios */
  788. if (inode->flags & BTRFS_INODE_NOCOMPRESS)
  789. return 0;
  790. if (btrfs_test_opt(fs_info, COMPRESS) ||
  791. inode->flags & BTRFS_INODE_COMPRESS ||
  792. inode->prop_compress)
  793. return btrfs_compress_heuristic(inode, start, end);
  794. return 0;
  795. }
  796. static inline void inode_should_defrag(struct btrfs_inode *inode,
  797. u64 start, u64 end, u64 num_bytes, u32 small_write)
  798. {
  799. /* If this is a small write inside eof, kick off a defrag */
  800. if (num_bytes < small_write &&
  801. (start > 0 || end + 1 < inode->disk_i_size))
  802. btrfs_add_inode_defrag(inode, small_write);
  803. }
  804. static int extent_range_clear_dirty_for_io(struct inode *inode, u64 start, u64 end)
  805. {
  806. unsigned long end_index = end >> PAGE_SHIFT;
  807. struct folio *folio;
  808. int ret = 0;
  809. for (unsigned long index = start >> PAGE_SHIFT;
  810. index <= end_index; index++) {
  811. folio = __filemap_get_folio(inode->i_mapping, index, 0, 0);
  812. if (IS_ERR(folio)) {
  813. if (!ret)
  814. ret = PTR_ERR(folio);
  815. continue;
  816. }
  817. folio_clear_dirty_for_io(folio);
  818. folio_put(folio);
  819. }
  820. return ret;
  821. }
  822. /*
  823. * Work queue call back to started compression on a file and pages.
  824. *
  825. * This is done inside an ordered work queue, and the compression is spread
  826. * across many cpus. The actual IO submission is step two, and the ordered work
  827. * queue takes care of making sure that happens in the same order things were
  828. * put onto the queue by writepages and friends.
  829. *
  830. * If this code finds it can't get good compression, it puts an entry onto the
  831. * work queue to write the uncompressed bytes. This makes sure that both
  832. * compressed inodes and uncompressed inodes are written in the same order that
  833. * the flusher thread sent them down.
  834. */
  835. static void compress_file_range(struct btrfs_work *work)
  836. {
  837. struct async_chunk *async_chunk =
  838. container_of(work, struct async_chunk, work);
  839. struct btrfs_inode *inode = async_chunk->inode;
  840. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  841. struct address_space *mapping = inode->vfs_inode.i_mapping;
  842. u64 blocksize = fs_info->sectorsize;
  843. u64 start = async_chunk->start;
  844. u64 end = async_chunk->end;
  845. u64 actual_end;
  846. u64 i_size;
  847. int ret = 0;
  848. struct folio **folios;
  849. unsigned long nr_folios;
  850. unsigned long total_compressed = 0;
  851. unsigned long total_in = 0;
  852. unsigned int poff;
  853. int i;
  854. int compress_type = fs_info->compress_type;
  855. inode_should_defrag(inode, start, end, end - start + 1, SZ_16K);
  856. /*
  857. * We need to call clear_page_dirty_for_io on each page in the range.
  858. * Otherwise applications with the file mmap'd can wander in and change
  859. * the page contents while we are compressing them.
  860. */
  861. ret = extent_range_clear_dirty_for_io(&inode->vfs_inode, start, end);
  862. /*
  863. * All the folios should have been locked thus no failure.
  864. *
  865. * And even if some folios are missing, btrfs_compress_folios()
  866. * would handle them correctly, so here just do an ASSERT() check for
  867. * early logic errors.
  868. */
  869. ASSERT(ret == 0);
  870. /*
  871. * We need to save i_size before now because it could change in between
  872. * us evaluating the size and assigning it. This is because we lock and
  873. * unlock the page in truncate and fallocate, and then modify the i_size
  874. * later on.
  875. *
  876. * The barriers are to emulate READ_ONCE, remove that once i_size_read
  877. * does that for us.
  878. */
  879. barrier();
  880. i_size = i_size_read(&inode->vfs_inode);
  881. barrier();
  882. actual_end = min_t(u64, i_size, end + 1);
  883. again:
  884. folios = NULL;
  885. nr_folios = (end >> PAGE_SHIFT) - (start >> PAGE_SHIFT) + 1;
  886. nr_folios = min_t(unsigned long, nr_folios, BTRFS_MAX_COMPRESSED_PAGES);
  887. /*
  888. * we don't want to send crud past the end of i_size through
  889. * compression, that's just a waste of CPU time. So, if the
  890. * end of the file is before the start of our current
  891. * requested range of bytes, we bail out to the uncompressed
  892. * cleanup code that can deal with all of this.
  893. *
  894. * It isn't really the fastest way to fix things, but this is a
  895. * very uncommon corner.
  896. */
  897. if (actual_end <= start)
  898. goto cleanup_and_bail_uncompressed;
  899. total_compressed = actual_end - start;
  900. /*
  901. * Skip compression for a small file range(<=blocksize) that
  902. * isn't an inline extent, since it doesn't save disk space at all.
  903. */
  904. if (total_compressed <= blocksize &&
  905. (start > 0 || end + 1 < inode->disk_i_size))
  906. goto cleanup_and_bail_uncompressed;
  907. /*
  908. * For subpage case, we require full page alignment for the sector
  909. * aligned range.
  910. * Thus we must also check against @actual_end, not just @end.
  911. */
  912. if (blocksize < PAGE_SIZE) {
  913. if (!PAGE_ALIGNED(start) ||
  914. !PAGE_ALIGNED(round_up(actual_end, blocksize)))
  915. goto cleanup_and_bail_uncompressed;
  916. }
  917. total_compressed = min_t(unsigned long, total_compressed,
  918. BTRFS_MAX_UNCOMPRESSED);
  919. total_in = 0;
  920. ret = 0;
  921. /*
  922. * We do compression for mount -o compress and when the inode has not
  923. * been flagged as NOCOMPRESS. This flag can change at any time if we
  924. * discover bad compression ratios.
  925. */
  926. if (!inode_need_compress(inode, start, end))
  927. goto cleanup_and_bail_uncompressed;
  928. folios = kcalloc(nr_folios, sizeof(struct folio *), GFP_NOFS);
  929. if (!folios) {
  930. /*
  931. * Memory allocation failure is not a fatal error, we can fall
  932. * back to uncompressed code.
  933. */
  934. goto cleanup_and_bail_uncompressed;
  935. }
  936. if (inode->defrag_compress)
  937. compress_type = inode->defrag_compress;
  938. else if (inode->prop_compress)
  939. compress_type = inode->prop_compress;
  940. /* Compression level is applied here. */
  941. ret = btrfs_compress_folios(compress_type | (fs_info->compress_level << 4),
  942. mapping, start, folios, &nr_folios, &total_in,
  943. &total_compressed);
  944. if (ret)
  945. goto mark_incompressible;
  946. /*
  947. * Zero the tail end of the last page, as we might be sending it down
  948. * to disk.
  949. */
  950. poff = offset_in_page(total_compressed);
  951. if (poff)
  952. folio_zero_range(folios[nr_folios - 1], poff, PAGE_SIZE - poff);
  953. /*
  954. * Try to create an inline extent.
  955. *
  956. * If we didn't compress the entire range, try to create an uncompressed
  957. * inline extent, else a compressed one.
  958. *
  959. * Check cow_file_range() for why we don't even try to create inline
  960. * extent for the subpage case.
  961. */
  962. if (total_in < actual_end)
  963. ret = cow_file_range_inline(inode, NULL, start, end, 0,
  964. BTRFS_COMPRESS_NONE, NULL, false);
  965. else
  966. ret = cow_file_range_inline(inode, NULL, start, end, total_compressed,
  967. compress_type, folios[0], false);
  968. if (ret <= 0) {
  969. if (ret < 0)
  970. mapping_set_error(mapping, -EIO);
  971. goto free_pages;
  972. }
  973. /*
  974. * We aren't doing an inline extent. Round the compressed size up to a
  975. * block size boundary so the allocator does sane things.
  976. */
  977. total_compressed = ALIGN(total_compressed, blocksize);
  978. /*
  979. * One last check to make sure the compression is really a win, compare
  980. * the page count read with the blocks on disk, compression must free at
  981. * least one sector.
  982. */
  983. total_in = round_up(total_in, fs_info->sectorsize);
  984. if (total_compressed + blocksize > total_in)
  985. goto mark_incompressible;
  986. /*
  987. * The async work queues will take care of doing actual allocation on
  988. * disk for these compressed pages, and will submit the bios.
  989. */
  990. ret = add_async_extent(async_chunk, start, total_in, total_compressed, folios,
  991. nr_folios, compress_type);
  992. BUG_ON(ret);
  993. if (start + total_in < end) {
  994. start += total_in;
  995. cond_resched();
  996. goto again;
  997. }
  998. return;
  999. mark_incompressible:
  1000. if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) && !inode->prop_compress)
  1001. inode->flags |= BTRFS_INODE_NOCOMPRESS;
  1002. cleanup_and_bail_uncompressed:
  1003. ret = add_async_extent(async_chunk, start, end - start + 1, 0, NULL, 0,
  1004. BTRFS_COMPRESS_NONE);
  1005. BUG_ON(ret);
  1006. free_pages:
  1007. if (folios) {
  1008. for (i = 0; i < nr_folios; i++) {
  1009. WARN_ON(folios[i]->mapping);
  1010. btrfs_free_compr_folio(folios[i]);
  1011. }
  1012. kfree(folios);
  1013. }
  1014. }
  1015. static void free_async_extent_pages(struct async_extent *async_extent)
  1016. {
  1017. int i;
  1018. if (!async_extent->folios)
  1019. return;
  1020. for (i = 0; i < async_extent->nr_folios; i++) {
  1021. WARN_ON(async_extent->folios[i]->mapping);
  1022. btrfs_free_compr_folio(async_extent->folios[i]);
  1023. }
  1024. kfree(async_extent->folios);
  1025. async_extent->nr_folios = 0;
  1026. async_extent->folios = NULL;
  1027. }
  1028. static void submit_uncompressed_range(struct btrfs_inode *inode,
  1029. struct async_extent *async_extent,
  1030. struct folio *locked_folio)
  1031. {
  1032. u64 start = async_extent->start;
  1033. u64 end = async_extent->start + async_extent->ram_size - 1;
  1034. int ret;
  1035. struct writeback_control wbc = {
  1036. .sync_mode = WB_SYNC_ALL,
  1037. .range_start = start,
  1038. .range_end = end,
  1039. .no_cgroup_owner = 1,
  1040. };
  1041. wbc_attach_fdatawrite_inode(&wbc, &inode->vfs_inode);
  1042. ret = run_delalloc_cow(inode, locked_folio, start, end,
  1043. &wbc, false);
  1044. wbc_detach_inode(&wbc);
  1045. if (ret < 0) {
  1046. btrfs_cleanup_ordered_extents(inode, locked_folio,
  1047. start, end - start + 1);
  1048. if (locked_folio) {
  1049. const u64 page_start = folio_pos(locked_folio);
  1050. folio_start_writeback(locked_folio);
  1051. folio_end_writeback(locked_folio);
  1052. btrfs_mark_ordered_io_finished(inode, locked_folio,
  1053. page_start, PAGE_SIZE,
  1054. !ret);
  1055. mapping_set_error(locked_folio->mapping, ret);
  1056. folio_unlock(locked_folio);
  1057. }
  1058. }
  1059. }
  1060. static void submit_one_async_extent(struct async_chunk *async_chunk,
  1061. struct async_extent *async_extent,
  1062. u64 *alloc_hint)
  1063. {
  1064. struct btrfs_inode *inode = async_chunk->inode;
  1065. struct extent_io_tree *io_tree = &inode->io_tree;
  1066. struct btrfs_root *root = inode->root;
  1067. struct btrfs_fs_info *fs_info = root->fs_info;
  1068. struct btrfs_ordered_extent *ordered;
  1069. struct btrfs_file_extent file_extent;
  1070. struct btrfs_key ins;
  1071. struct folio *locked_folio = NULL;
  1072. struct extent_state *cached = NULL;
  1073. struct extent_map *em;
  1074. int ret = 0;
  1075. bool free_pages = false;
  1076. u64 start = async_extent->start;
  1077. u64 end = async_extent->start + async_extent->ram_size - 1;
  1078. if (async_chunk->blkcg_css)
  1079. kthread_associate_blkcg(async_chunk->blkcg_css);
  1080. /*
  1081. * If async_chunk->locked_folio is in the async_extent range, we need to
  1082. * handle it.
  1083. */
  1084. if (async_chunk->locked_folio) {
  1085. u64 locked_folio_start = folio_pos(async_chunk->locked_folio);
  1086. u64 locked_folio_end = locked_folio_start +
  1087. folio_size(async_chunk->locked_folio) - 1;
  1088. if (!(start >= locked_folio_end || end <= locked_folio_start))
  1089. locked_folio = async_chunk->locked_folio;
  1090. }
  1091. if (async_extent->compress_type == BTRFS_COMPRESS_NONE) {
  1092. ASSERT(!async_extent->folios);
  1093. ASSERT(async_extent->nr_folios == 0);
  1094. submit_uncompressed_range(inode, async_extent, locked_folio);
  1095. free_pages = true;
  1096. goto done;
  1097. }
  1098. ret = btrfs_reserve_extent(root, async_extent->ram_size,
  1099. async_extent->compressed_size,
  1100. async_extent->compressed_size,
  1101. 0, *alloc_hint, &ins, 1, 1);
  1102. if (ret) {
  1103. /*
  1104. * We can't reserve contiguous space for the compressed size.
  1105. * Unlikely, but it's possible that we could have enough
  1106. * non-contiguous space for the uncompressed size instead. So
  1107. * fall back to uncompressed.
  1108. */
  1109. submit_uncompressed_range(inode, async_extent, locked_folio);
  1110. free_pages = true;
  1111. goto done;
  1112. }
  1113. lock_extent(io_tree, start, end, &cached);
  1114. /* Here we're doing allocation and writeback of the compressed pages */
  1115. file_extent.disk_bytenr = ins.objectid;
  1116. file_extent.disk_num_bytes = ins.offset;
  1117. file_extent.ram_bytes = async_extent->ram_size;
  1118. file_extent.num_bytes = async_extent->ram_size;
  1119. file_extent.offset = 0;
  1120. file_extent.compression = async_extent->compress_type;
  1121. em = btrfs_create_io_em(inode, start, &file_extent, BTRFS_ORDERED_COMPRESSED);
  1122. if (IS_ERR(em)) {
  1123. ret = PTR_ERR(em);
  1124. goto out_free_reserve;
  1125. }
  1126. free_extent_map(em);
  1127. ordered = btrfs_alloc_ordered_extent(inode, start, &file_extent,
  1128. 1U << BTRFS_ORDERED_COMPRESSED);
  1129. if (IS_ERR(ordered)) {
  1130. btrfs_drop_extent_map_range(inode, start, end, false);
  1131. ret = PTR_ERR(ordered);
  1132. goto out_free_reserve;
  1133. }
  1134. btrfs_dec_block_group_reservations(fs_info, ins.objectid);
  1135. /* Clear dirty, set writeback and unlock the pages. */
  1136. extent_clear_unlock_delalloc(inode, start, end,
  1137. NULL, &cached, EXTENT_LOCKED | EXTENT_DELALLOC,
  1138. PAGE_UNLOCK | PAGE_START_WRITEBACK);
  1139. btrfs_submit_compressed_write(ordered,
  1140. async_extent->folios, /* compressed_folios */
  1141. async_extent->nr_folios,
  1142. async_chunk->write_flags, true);
  1143. *alloc_hint = ins.objectid + ins.offset;
  1144. done:
  1145. if (async_chunk->blkcg_css)
  1146. kthread_associate_blkcg(NULL);
  1147. if (free_pages)
  1148. free_async_extent_pages(async_extent);
  1149. kfree(async_extent);
  1150. return;
  1151. out_free_reserve:
  1152. btrfs_dec_block_group_reservations(fs_info, ins.objectid);
  1153. btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
  1154. mapping_set_error(inode->vfs_inode.i_mapping, -EIO);
  1155. extent_clear_unlock_delalloc(inode, start, end,
  1156. NULL, &cached,
  1157. EXTENT_LOCKED | EXTENT_DELALLOC |
  1158. EXTENT_DELALLOC_NEW |
  1159. EXTENT_DEFRAG | EXTENT_DO_ACCOUNTING,
  1160. PAGE_UNLOCK | PAGE_START_WRITEBACK |
  1161. PAGE_END_WRITEBACK);
  1162. free_async_extent_pages(async_extent);
  1163. if (async_chunk->blkcg_css)
  1164. kthread_associate_blkcg(NULL);
  1165. btrfs_debug(fs_info,
  1166. "async extent submission failed root=%lld inode=%llu start=%llu len=%llu ret=%d",
  1167. btrfs_root_id(root), btrfs_ino(inode), start,
  1168. async_extent->ram_size, ret);
  1169. kfree(async_extent);
  1170. }
  1171. u64 btrfs_get_extent_allocation_hint(struct btrfs_inode *inode, u64 start,
  1172. u64 num_bytes)
  1173. {
  1174. struct extent_map_tree *em_tree = &inode->extent_tree;
  1175. struct extent_map *em;
  1176. u64 alloc_hint = 0;
  1177. read_lock(&em_tree->lock);
  1178. em = search_extent_mapping(em_tree, start, num_bytes);
  1179. if (em) {
  1180. /*
  1181. * if block start isn't an actual block number then find the
  1182. * first block in this inode and use that as a hint. If that
  1183. * block is also bogus then just don't worry about it.
  1184. */
  1185. if (em->disk_bytenr >= EXTENT_MAP_LAST_BYTE) {
  1186. free_extent_map(em);
  1187. em = search_extent_mapping(em_tree, 0, 0);
  1188. if (em && em->disk_bytenr < EXTENT_MAP_LAST_BYTE)
  1189. alloc_hint = extent_map_block_start(em);
  1190. if (em)
  1191. free_extent_map(em);
  1192. } else {
  1193. alloc_hint = extent_map_block_start(em);
  1194. free_extent_map(em);
  1195. }
  1196. }
  1197. read_unlock(&em_tree->lock);
  1198. return alloc_hint;
  1199. }
  1200. /*
  1201. * when extent_io.c finds a delayed allocation range in the file,
  1202. * the call backs end up in this code. The basic idea is to
  1203. * allocate extents on disk for the range, and create ordered data structs
  1204. * in ram to track those extents.
  1205. *
  1206. * locked_folio is the folio that writepage had locked already. We use
  1207. * it to make sure we don't do extra locks or unlocks.
  1208. *
  1209. * When this function fails, it unlocks all pages except @locked_folio.
  1210. *
  1211. * When this function successfully creates an inline extent, it returns 1 and
  1212. * unlocks all pages including locked_folio and starts I/O on them.
  1213. * (In reality inline extents are limited to a single page, so locked_folio is
  1214. * the only page handled anyway).
  1215. *
  1216. * When this function succeed and creates a normal extent, the page locking
  1217. * status depends on the passed in flags:
  1218. *
  1219. * - If @keep_locked is set, all pages are kept locked.
  1220. * - Else all pages except for @locked_folio are unlocked.
  1221. *
  1222. * When a failure happens in the second or later iteration of the
  1223. * while-loop, the ordered extents created in previous iterations are kept
  1224. * intact. So, the caller must clean them up by calling
  1225. * btrfs_cleanup_ordered_extents(). See btrfs_run_delalloc_range() for
  1226. * example.
  1227. */
  1228. static noinline int cow_file_range(struct btrfs_inode *inode,
  1229. struct folio *locked_folio, u64 start,
  1230. u64 end, u64 *done_offset,
  1231. bool keep_locked, bool no_inline)
  1232. {
  1233. struct btrfs_root *root = inode->root;
  1234. struct btrfs_fs_info *fs_info = root->fs_info;
  1235. struct extent_state *cached = NULL;
  1236. u64 alloc_hint = 0;
  1237. u64 orig_start = start;
  1238. u64 num_bytes;
  1239. unsigned long ram_size;
  1240. u64 cur_alloc_size = 0;
  1241. u64 min_alloc_size;
  1242. u64 blocksize = fs_info->sectorsize;
  1243. struct btrfs_key ins;
  1244. struct extent_map *em;
  1245. unsigned clear_bits;
  1246. unsigned long page_ops;
  1247. bool extent_reserved = false;
  1248. int ret = 0;
  1249. if (btrfs_is_free_space_inode(inode)) {
  1250. ret = -EINVAL;
  1251. goto out_unlock;
  1252. }
  1253. num_bytes = ALIGN(end - start + 1, blocksize);
  1254. num_bytes = max(blocksize, num_bytes);
  1255. ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
  1256. inode_should_defrag(inode, start, end, num_bytes, SZ_64K);
  1257. if (!no_inline) {
  1258. /* lets try to make an inline extent */
  1259. ret = cow_file_range_inline(inode, locked_folio, start, end, 0,
  1260. BTRFS_COMPRESS_NONE, NULL, false);
  1261. if (ret <= 0) {
  1262. /*
  1263. * We succeeded, return 1 so the caller knows we're done
  1264. * with this page and already handled the IO.
  1265. *
  1266. * If there was an error then cow_file_range_inline() has
  1267. * already done the cleanup.
  1268. */
  1269. if (ret == 0)
  1270. ret = 1;
  1271. goto done;
  1272. }
  1273. }
  1274. alloc_hint = btrfs_get_extent_allocation_hint(inode, start, num_bytes);
  1275. /*
  1276. * We're not doing compressed IO, don't unlock the first page (which
  1277. * the caller expects to stay locked), don't clear any dirty bits and
  1278. * don't set any writeback bits.
  1279. *
  1280. * Do set the Ordered (Private2) bit so we know this page was properly
  1281. * setup for writepage.
  1282. */
  1283. page_ops = (keep_locked ? 0 : PAGE_UNLOCK);
  1284. page_ops |= PAGE_SET_ORDERED;
  1285. /*
  1286. * Relocation relies on the relocated extents to have exactly the same
  1287. * size as the original extents. Normally writeback for relocation data
  1288. * extents follows a NOCOW path because relocation preallocates the
  1289. * extents. However, due to an operation such as scrub turning a block
  1290. * group to RO mode, it may fallback to COW mode, so we must make sure
  1291. * an extent allocated during COW has exactly the requested size and can
  1292. * not be split into smaller extents, otherwise relocation breaks and
  1293. * fails during the stage where it updates the bytenr of file extent
  1294. * items.
  1295. */
  1296. if (btrfs_is_data_reloc_root(root))
  1297. min_alloc_size = num_bytes;
  1298. else
  1299. min_alloc_size = fs_info->sectorsize;
  1300. while (num_bytes > 0) {
  1301. struct btrfs_ordered_extent *ordered;
  1302. struct btrfs_file_extent file_extent;
  1303. cur_alloc_size = num_bytes;
  1304. ret = btrfs_reserve_extent(root, cur_alloc_size, cur_alloc_size,
  1305. min_alloc_size, 0, alloc_hint,
  1306. &ins, 1, 1);
  1307. if (ret == -EAGAIN) {
  1308. /*
  1309. * btrfs_reserve_extent only returns -EAGAIN for zoned
  1310. * file systems, which is an indication that there are
  1311. * no active zones to allocate from at the moment.
  1312. *
  1313. * If this is the first loop iteration, wait for at
  1314. * least one zone to finish before retrying the
  1315. * allocation. Otherwise ask the caller to write out
  1316. * the already allocated blocks before coming back to
  1317. * us, or return -ENOSPC if it can't handle retries.
  1318. */
  1319. ASSERT(btrfs_is_zoned(fs_info));
  1320. if (start == orig_start) {
  1321. wait_on_bit_io(&inode->root->fs_info->flags,
  1322. BTRFS_FS_NEED_ZONE_FINISH,
  1323. TASK_UNINTERRUPTIBLE);
  1324. continue;
  1325. }
  1326. if (done_offset) {
  1327. /*
  1328. * Move @end to the end of the processed range,
  1329. * and exit the loop to unlock the processed extents.
  1330. */
  1331. end = start - 1;
  1332. ret = 0;
  1333. break;
  1334. }
  1335. ret = -ENOSPC;
  1336. }
  1337. if (ret < 0)
  1338. goto out_unlock;
  1339. cur_alloc_size = ins.offset;
  1340. extent_reserved = true;
  1341. ram_size = ins.offset;
  1342. file_extent.disk_bytenr = ins.objectid;
  1343. file_extent.disk_num_bytes = ins.offset;
  1344. file_extent.num_bytes = ins.offset;
  1345. file_extent.ram_bytes = ins.offset;
  1346. file_extent.offset = 0;
  1347. file_extent.compression = BTRFS_COMPRESS_NONE;
  1348. /*
  1349. * Locked range will be released either during error clean up or
  1350. * after the whole range is finished.
  1351. */
  1352. lock_extent(&inode->io_tree, start, start + ram_size - 1,
  1353. &cached);
  1354. em = btrfs_create_io_em(inode, start, &file_extent,
  1355. BTRFS_ORDERED_REGULAR);
  1356. if (IS_ERR(em)) {
  1357. unlock_extent(&inode->io_tree, start,
  1358. start + ram_size - 1, &cached);
  1359. ret = PTR_ERR(em);
  1360. goto out_reserve;
  1361. }
  1362. free_extent_map(em);
  1363. ordered = btrfs_alloc_ordered_extent(inode, start, &file_extent,
  1364. 1U << BTRFS_ORDERED_REGULAR);
  1365. if (IS_ERR(ordered)) {
  1366. unlock_extent(&inode->io_tree, start,
  1367. start + ram_size - 1, &cached);
  1368. ret = PTR_ERR(ordered);
  1369. goto out_drop_extent_cache;
  1370. }
  1371. if (btrfs_is_data_reloc_root(root)) {
  1372. ret = btrfs_reloc_clone_csums(ordered);
  1373. /*
  1374. * Only drop cache here, and process as normal.
  1375. *
  1376. * We must not allow extent_clear_unlock_delalloc()
  1377. * at out_unlock label to free meta of this ordered
  1378. * extent, as its meta should be freed by
  1379. * btrfs_finish_ordered_io().
  1380. *
  1381. * So we must continue until @start is increased to
  1382. * skip current ordered extent.
  1383. */
  1384. if (ret)
  1385. btrfs_drop_extent_map_range(inode, start,
  1386. start + ram_size - 1,
  1387. false);
  1388. }
  1389. btrfs_put_ordered_extent(ordered);
  1390. btrfs_dec_block_group_reservations(fs_info, ins.objectid);
  1391. if (num_bytes < ram_size)
  1392. num_bytes = 0;
  1393. else
  1394. num_bytes -= ram_size;
  1395. alloc_hint = ins.objectid + ins.offset;
  1396. start += ram_size;
  1397. extent_reserved = false;
  1398. /*
  1399. * btrfs_reloc_clone_csums() error, since start is increased
  1400. * extent_clear_unlock_delalloc() at out_unlock label won't
  1401. * free metadata of current ordered extent, we're OK to exit.
  1402. */
  1403. if (ret)
  1404. goto out_unlock;
  1405. }
  1406. extent_clear_unlock_delalloc(inode, orig_start, end, locked_folio, &cached,
  1407. EXTENT_LOCKED | EXTENT_DELALLOC, page_ops);
  1408. done:
  1409. if (done_offset)
  1410. *done_offset = end;
  1411. return ret;
  1412. out_drop_extent_cache:
  1413. btrfs_drop_extent_map_range(inode, start, start + ram_size - 1, false);
  1414. out_reserve:
  1415. btrfs_dec_block_group_reservations(fs_info, ins.objectid);
  1416. btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
  1417. out_unlock:
  1418. /*
  1419. * Now, we have three regions to clean up:
  1420. *
  1421. * |-------(1)----|---(2)---|-------------(3)----------|
  1422. * `- orig_start `- start `- start + ram_size `- end
  1423. *
  1424. * We process each region below.
  1425. */
  1426. /*
  1427. * For the range (1). We have already instantiated the ordered extents
  1428. * for this region. They are cleaned up by
  1429. * btrfs_cleanup_ordered_extents() in e.g,
  1430. * btrfs_run_delalloc_range().
  1431. * EXTENT_DELALLOC_NEW | EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV
  1432. * are also handled by the cleanup function.
  1433. *
  1434. * So here we only clear EXTENT_LOCKED and EXTENT_DELALLOC flag, and
  1435. * finish the writeback of the involved folios, which will be never submitted.
  1436. */
  1437. if (orig_start < start) {
  1438. clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC;
  1439. page_ops = PAGE_UNLOCK | PAGE_START_WRITEBACK | PAGE_END_WRITEBACK;
  1440. if (!locked_folio)
  1441. mapping_set_error(inode->vfs_inode.i_mapping, ret);
  1442. extent_clear_unlock_delalloc(inode, orig_start, start - 1,
  1443. locked_folio, NULL, clear_bits, page_ops);
  1444. }
  1445. clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
  1446. EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
  1447. page_ops = PAGE_UNLOCK | PAGE_START_WRITEBACK | PAGE_END_WRITEBACK;
  1448. /*
  1449. * For the range (2). If we reserved an extent for our delalloc range
  1450. * (or a subrange) and failed to create the respective ordered extent,
  1451. * then it means that when we reserved the extent we decremented the
  1452. * extent's size from the data space_info's bytes_may_use counter and
  1453. * incremented the space_info's bytes_reserved counter by the same
  1454. * amount. We must make sure extent_clear_unlock_delalloc() does not try
  1455. * to decrement again the data space_info's bytes_may_use counter,
  1456. * therefore we do not pass it the flag EXTENT_CLEAR_DATA_RESV.
  1457. */
  1458. if (extent_reserved) {
  1459. extent_clear_unlock_delalloc(inode, start,
  1460. start + ram_size - 1,
  1461. locked_folio, &cached, clear_bits,
  1462. page_ops);
  1463. btrfs_qgroup_free_data(inode, NULL, start, ram_size, NULL);
  1464. start += ram_size;
  1465. }
  1466. /*
  1467. * For the range (3). We never touched the region. In addition to the
  1468. * clear_bits above, we add EXTENT_CLEAR_DATA_RESV to release the data
  1469. * space_info's bytes_may_use counter, reserved in
  1470. * btrfs_check_data_free_space().
  1471. */
  1472. if (start < end) {
  1473. clear_bits |= EXTENT_CLEAR_DATA_RESV;
  1474. extent_clear_unlock_delalloc(inode, start, end, locked_folio,
  1475. &cached, clear_bits, page_ops);
  1476. btrfs_qgroup_free_data(inode, NULL, start, end - start + 1, NULL);
  1477. }
  1478. return ret;
  1479. }
  1480. /*
  1481. * Phase two of compressed writeback. This is the ordered portion of the code,
  1482. * which only gets called in the order the work was queued. We walk all the
  1483. * async extents created by compress_file_range and send them down to the disk.
  1484. *
  1485. * If called with @do_free == true then it'll try to finish the work and free
  1486. * the work struct eventually.
  1487. */
  1488. static noinline void submit_compressed_extents(struct btrfs_work *work, bool do_free)
  1489. {
  1490. struct async_chunk *async_chunk = container_of(work, struct async_chunk,
  1491. work);
  1492. struct btrfs_fs_info *fs_info = btrfs_work_owner(work);
  1493. struct async_extent *async_extent;
  1494. unsigned long nr_pages;
  1495. u64 alloc_hint = 0;
  1496. if (do_free) {
  1497. struct async_cow *async_cow;
  1498. btrfs_add_delayed_iput(async_chunk->inode);
  1499. if (async_chunk->blkcg_css)
  1500. css_put(async_chunk->blkcg_css);
  1501. async_cow = async_chunk->async_cow;
  1502. if (atomic_dec_and_test(&async_cow->num_chunks))
  1503. kvfree(async_cow);
  1504. return;
  1505. }
  1506. nr_pages = (async_chunk->end - async_chunk->start + PAGE_SIZE) >>
  1507. PAGE_SHIFT;
  1508. while (!list_empty(&async_chunk->extents)) {
  1509. async_extent = list_entry(async_chunk->extents.next,
  1510. struct async_extent, list);
  1511. list_del(&async_extent->list);
  1512. submit_one_async_extent(async_chunk, async_extent, &alloc_hint);
  1513. }
  1514. /* atomic_sub_return implies a barrier */
  1515. if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
  1516. 5 * SZ_1M)
  1517. cond_wake_up_nomb(&fs_info->async_submit_wait);
  1518. }
  1519. static bool run_delalloc_compressed(struct btrfs_inode *inode,
  1520. struct folio *locked_folio, u64 start,
  1521. u64 end, struct writeback_control *wbc)
  1522. {
  1523. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  1524. struct cgroup_subsys_state *blkcg_css = wbc_blkcg_css(wbc);
  1525. struct async_cow *ctx;
  1526. struct async_chunk *async_chunk;
  1527. unsigned long nr_pages;
  1528. u64 num_chunks = DIV_ROUND_UP(end - start, SZ_512K);
  1529. int i;
  1530. unsigned nofs_flag;
  1531. const blk_opf_t write_flags = wbc_to_write_flags(wbc);
  1532. nofs_flag = memalloc_nofs_save();
  1533. ctx = kvmalloc(struct_size(ctx, chunks, num_chunks), GFP_KERNEL);
  1534. memalloc_nofs_restore(nofs_flag);
  1535. if (!ctx)
  1536. return false;
  1537. set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT, &inode->runtime_flags);
  1538. async_chunk = ctx->chunks;
  1539. atomic_set(&ctx->num_chunks, num_chunks);
  1540. for (i = 0; i < num_chunks; i++) {
  1541. u64 cur_end = min(end, start + SZ_512K - 1);
  1542. /*
  1543. * igrab is called higher up in the call chain, take only the
  1544. * lightweight reference for the callback lifetime
  1545. */
  1546. ihold(&inode->vfs_inode);
  1547. async_chunk[i].async_cow = ctx;
  1548. async_chunk[i].inode = inode;
  1549. async_chunk[i].start = start;
  1550. async_chunk[i].end = cur_end;
  1551. async_chunk[i].write_flags = write_flags;
  1552. INIT_LIST_HEAD(&async_chunk[i].extents);
  1553. /*
  1554. * The locked_folio comes all the way from writepage and its
  1555. * the original folio we were actually given. As we spread
  1556. * this large delalloc region across multiple async_chunk
  1557. * structs, only the first struct needs a pointer to
  1558. * locked_folio.
  1559. *
  1560. * This way we don't need racey decisions about who is supposed
  1561. * to unlock it.
  1562. */
  1563. if (locked_folio) {
  1564. /*
  1565. * Depending on the compressibility, the pages might or
  1566. * might not go through async. We want all of them to
  1567. * be accounted against wbc once. Let's do it here
  1568. * before the paths diverge. wbc accounting is used
  1569. * only for foreign writeback detection and doesn't
  1570. * need full accuracy. Just account the whole thing
  1571. * against the first page.
  1572. */
  1573. wbc_account_cgroup_owner(wbc, locked_folio,
  1574. cur_end - start);
  1575. async_chunk[i].locked_folio = locked_folio;
  1576. locked_folio = NULL;
  1577. } else {
  1578. async_chunk[i].locked_folio = NULL;
  1579. }
  1580. if (blkcg_css != blkcg_root_css) {
  1581. css_get(blkcg_css);
  1582. async_chunk[i].blkcg_css = blkcg_css;
  1583. async_chunk[i].write_flags |= REQ_BTRFS_CGROUP_PUNT;
  1584. } else {
  1585. async_chunk[i].blkcg_css = NULL;
  1586. }
  1587. btrfs_init_work(&async_chunk[i].work, compress_file_range,
  1588. submit_compressed_extents);
  1589. nr_pages = DIV_ROUND_UP(cur_end - start, PAGE_SIZE);
  1590. atomic_add(nr_pages, &fs_info->async_delalloc_pages);
  1591. btrfs_queue_work(fs_info->delalloc_workers, &async_chunk[i].work);
  1592. start = cur_end + 1;
  1593. }
  1594. return true;
  1595. }
  1596. /*
  1597. * Run the delalloc range from start to end, and write back any dirty pages
  1598. * covered by the range.
  1599. */
  1600. static noinline int run_delalloc_cow(struct btrfs_inode *inode,
  1601. struct folio *locked_folio, u64 start,
  1602. u64 end, struct writeback_control *wbc,
  1603. bool pages_dirty)
  1604. {
  1605. u64 done_offset = end;
  1606. int ret;
  1607. while (start <= end) {
  1608. ret = cow_file_range(inode, locked_folio, start, end,
  1609. &done_offset, true, false);
  1610. if (ret)
  1611. return ret;
  1612. extent_write_locked_range(&inode->vfs_inode, locked_folio,
  1613. start, done_offset, wbc, pages_dirty);
  1614. start = done_offset + 1;
  1615. }
  1616. return 1;
  1617. }
  1618. static int fallback_to_cow(struct btrfs_inode *inode,
  1619. struct folio *locked_folio, const u64 start,
  1620. const u64 end)
  1621. {
  1622. const bool is_space_ino = btrfs_is_free_space_inode(inode);
  1623. const bool is_reloc_ino = btrfs_is_data_reloc_root(inode->root);
  1624. const u64 range_bytes = end + 1 - start;
  1625. struct extent_io_tree *io_tree = &inode->io_tree;
  1626. struct extent_state *cached_state = NULL;
  1627. u64 range_start = start;
  1628. u64 count;
  1629. int ret;
  1630. /*
  1631. * If EXTENT_NORESERVE is set it means that when the buffered write was
  1632. * made we had not enough available data space and therefore we did not
  1633. * reserve data space for it, since we though we could do NOCOW for the
  1634. * respective file range (either there is prealloc extent or the inode
  1635. * has the NOCOW bit set).
  1636. *
  1637. * However when we need to fallback to COW mode (because for example the
  1638. * block group for the corresponding extent was turned to RO mode by a
  1639. * scrub or relocation) we need to do the following:
  1640. *
  1641. * 1) We increment the bytes_may_use counter of the data space info.
  1642. * If COW succeeds, it allocates a new data extent and after doing
  1643. * that it decrements the space info's bytes_may_use counter and
  1644. * increments its bytes_reserved counter by the same amount (we do
  1645. * this at btrfs_add_reserved_bytes()). So we need to increment the
  1646. * bytes_may_use counter to compensate (when space is reserved at
  1647. * buffered write time, the bytes_may_use counter is incremented);
  1648. *
  1649. * 2) We clear the EXTENT_NORESERVE bit from the range. We do this so
  1650. * that if the COW path fails for any reason, it decrements (through
  1651. * extent_clear_unlock_delalloc()) the bytes_may_use counter of the
  1652. * data space info, which we incremented in the step above.
  1653. *
  1654. * If we need to fallback to cow and the inode corresponds to a free
  1655. * space cache inode or an inode of the data relocation tree, we must
  1656. * also increment bytes_may_use of the data space_info for the same
  1657. * reason. Space caches and relocated data extents always get a prealloc
  1658. * extent for them, however scrub or balance may have set the block
  1659. * group that contains that extent to RO mode and therefore force COW
  1660. * when starting writeback.
  1661. */
  1662. lock_extent(io_tree, start, end, &cached_state);
  1663. count = count_range_bits(io_tree, &range_start, end, range_bytes,
  1664. EXTENT_NORESERVE, 0, NULL);
  1665. if (count > 0 || is_space_ino || is_reloc_ino) {
  1666. u64 bytes = count;
  1667. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  1668. struct btrfs_space_info *sinfo = fs_info->data_sinfo;
  1669. if (is_space_ino || is_reloc_ino)
  1670. bytes = range_bytes;
  1671. spin_lock(&sinfo->lock);
  1672. btrfs_space_info_update_bytes_may_use(fs_info, sinfo, bytes);
  1673. spin_unlock(&sinfo->lock);
  1674. if (count > 0)
  1675. clear_extent_bit(io_tree, start, end, EXTENT_NORESERVE,
  1676. NULL);
  1677. }
  1678. unlock_extent(io_tree, start, end, &cached_state);
  1679. /*
  1680. * Don't try to create inline extents, as a mix of inline extent that
  1681. * is written out and unlocked directly and a normal NOCOW extent
  1682. * doesn't work.
  1683. */
  1684. ret = cow_file_range(inode, locked_folio, start, end, NULL, false,
  1685. true);
  1686. ASSERT(ret != 1);
  1687. return ret;
  1688. }
  1689. struct can_nocow_file_extent_args {
  1690. /* Input fields. */
  1691. /* Start file offset of the range we want to NOCOW. */
  1692. u64 start;
  1693. /* End file offset (inclusive) of the range we want to NOCOW. */
  1694. u64 end;
  1695. bool writeback_path;
  1696. bool strict;
  1697. /*
  1698. * Free the path passed to can_nocow_file_extent() once it's not needed
  1699. * anymore.
  1700. */
  1701. bool free_path;
  1702. /*
  1703. * Output fields. Only set when can_nocow_file_extent() returns 1.
  1704. * The expected file extent for the NOCOW write.
  1705. */
  1706. struct btrfs_file_extent file_extent;
  1707. };
  1708. /*
  1709. * Check if we can NOCOW the file extent that the path points to.
  1710. * This function may return with the path released, so the caller should check
  1711. * if path->nodes[0] is NULL or not if it needs to use the path afterwards.
  1712. *
  1713. * Returns: < 0 on error
  1714. * 0 if we can not NOCOW
  1715. * 1 if we can NOCOW
  1716. */
  1717. static int can_nocow_file_extent(struct btrfs_path *path,
  1718. struct btrfs_key *key,
  1719. struct btrfs_inode *inode,
  1720. struct can_nocow_file_extent_args *args)
  1721. {
  1722. const bool is_freespace_inode = btrfs_is_free_space_inode(inode);
  1723. struct extent_buffer *leaf = path->nodes[0];
  1724. struct btrfs_root *root = inode->root;
  1725. struct btrfs_file_extent_item *fi;
  1726. struct btrfs_root *csum_root;
  1727. u64 io_start;
  1728. u64 extent_end;
  1729. u8 extent_type;
  1730. int can_nocow = 0;
  1731. int ret = 0;
  1732. bool nowait = path->nowait;
  1733. fi = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
  1734. extent_type = btrfs_file_extent_type(leaf, fi);
  1735. if (extent_type == BTRFS_FILE_EXTENT_INLINE)
  1736. goto out;
  1737. if (!(inode->flags & BTRFS_INODE_NODATACOW) &&
  1738. extent_type == BTRFS_FILE_EXTENT_REG)
  1739. goto out;
  1740. /*
  1741. * If the extent was created before the generation where the last snapshot
  1742. * for its subvolume was created, then this implies the extent is shared,
  1743. * hence we must COW.
  1744. */
  1745. if (!args->strict &&
  1746. btrfs_file_extent_generation(leaf, fi) <=
  1747. btrfs_root_last_snapshot(&root->root_item))
  1748. goto out;
  1749. /* An explicit hole, must COW. */
  1750. if (btrfs_file_extent_disk_bytenr(leaf, fi) == 0)
  1751. goto out;
  1752. /* Compressed/encrypted/encoded extents must be COWed. */
  1753. if (btrfs_file_extent_compression(leaf, fi) ||
  1754. btrfs_file_extent_encryption(leaf, fi) ||
  1755. btrfs_file_extent_other_encoding(leaf, fi))
  1756. goto out;
  1757. extent_end = btrfs_file_extent_end(path);
  1758. args->file_extent.disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
  1759. args->file_extent.disk_num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
  1760. args->file_extent.ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
  1761. args->file_extent.offset = btrfs_file_extent_offset(leaf, fi);
  1762. args->file_extent.compression = btrfs_file_extent_compression(leaf, fi);
  1763. /*
  1764. * The following checks can be expensive, as they need to take other
  1765. * locks and do btree or rbtree searches, so release the path to avoid
  1766. * blocking other tasks for too long.
  1767. */
  1768. btrfs_release_path(path);
  1769. ret = btrfs_cross_ref_exist(root, btrfs_ino(inode),
  1770. key->offset - args->file_extent.offset,
  1771. args->file_extent.disk_bytenr, args->strict, path);
  1772. WARN_ON_ONCE(ret > 0 && is_freespace_inode);
  1773. if (ret != 0)
  1774. goto out;
  1775. if (args->free_path) {
  1776. /*
  1777. * We don't need the path anymore, plus through the
  1778. * btrfs_lookup_csums_list() call below we will end up allocating
  1779. * another path. So free the path to avoid unnecessary extra
  1780. * memory usage.
  1781. */
  1782. btrfs_free_path(path);
  1783. path = NULL;
  1784. }
  1785. /* If there are pending snapshots for this root, we must COW. */
  1786. if (args->writeback_path && !is_freespace_inode &&
  1787. atomic_read(&root->snapshot_force_cow))
  1788. goto out;
  1789. args->file_extent.num_bytes = min(args->end + 1, extent_end) - args->start;
  1790. args->file_extent.offset += args->start - key->offset;
  1791. io_start = args->file_extent.disk_bytenr + args->file_extent.offset;
  1792. /*
  1793. * Force COW if csums exist in the range. This ensures that csums for a
  1794. * given extent are either valid or do not exist.
  1795. */
  1796. csum_root = btrfs_csum_root(root->fs_info, io_start);
  1797. ret = btrfs_lookup_csums_list(csum_root, io_start,
  1798. io_start + args->file_extent.num_bytes - 1,
  1799. NULL, nowait);
  1800. WARN_ON_ONCE(ret > 0 && is_freespace_inode);
  1801. if (ret != 0)
  1802. goto out;
  1803. can_nocow = 1;
  1804. out:
  1805. if (args->free_path && path)
  1806. btrfs_free_path(path);
  1807. return ret < 0 ? ret : can_nocow;
  1808. }
  1809. /*
  1810. * Cleanup the dirty folios which will never be submitted due to error.
  1811. *
  1812. * When running a delalloc range, we may need to split the ranges (due to
  1813. * fragmentation or NOCOW). If we hit an error in the later part, we will error
  1814. * out and previously successfully executed range will never be submitted, thus
  1815. * we have to cleanup those folios by clearing their dirty flag, starting and
  1816. * finishing the writeback.
  1817. */
  1818. static void cleanup_dirty_folios(struct btrfs_inode *inode,
  1819. struct folio *locked_folio,
  1820. u64 start, u64 end, int error)
  1821. {
  1822. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  1823. struct address_space *mapping = inode->vfs_inode.i_mapping;
  1824. pgoff_t start_index = start >> PAGE_SHIFT;
  1825. pgoff_t end_index = end >> PAGE_SHIFT;
  1826. u32 len;
  1827. ASSERT(end + 1 - start < U32_MAX);
  1828. ASSERT(IS_ALIGNED(start, fs_info->sectorsize) &&
  1829. IS_ALIGNED(end + 1, fs_info->sectorsize));
  1830. len = end + 1 - start;
  1831. /*
  1832. * Handle the locked folio first.
  1833. * The btrfs_folio_clamp_*() helpers can handle range out of the folio case.
  1834. */
  1835. btrfs_folio_clamp_finish_io(fs_info, locked_folio, start, len);
  1836. for (pgoff_t index = start_index; index <= end_index; index++) {
  1837. struct folio *folio;
  1838. /* Already handled at the beginning. */
  1839. if (index == locked_folio->index)
  1840. continue;
  1841. folio = __filemap_get_folio(mapping, index, FGP_LOCK, GFP_NOFS);
  1842. /* Cache already dropped, no need to do any cleanup. */
  1843. if (IS_ERR(folio))
  1844. continue;
  1845. btrfs_folio_clamp_finish_io(fs_info, locked_folio, start, len);
  1846. folio_unlock(folio);
  1847. folio_put(folio);
  1848. }
  1849. mapping_set_error(mapping, error);
  1850. }
  1851. static int nocow_one_range(struct btrfs_inode *inode, struct folio *locked_folio,
  1852. struct extent_state **cached,
  1853. struct can_nocow_file_extent_args *nocow_args,
  1854. u64 file_pos, bool is_prealloc)
  1855. {
  1856. struct btrfs_ordered_extent *ordered;
  1857. u64 len = nocow_args->file_extent.num_bytes;
  1858. u64 end = file_pos + len - 1;
  1859. int ret = 0;
  1860. lock_extent(&inode->io_tree, file_pos, end, cached);
  1861. if (is_prealloc) {
  1862. struct extent_map *em;
  1863. em = btrfs_create_io_em(inode, file_pos, &nocow_args->file_extent,
  1864. BTRFS_ORDERED_PREALLOC);
  1865. if (IS_ERR(em)) {
  1866. unlock_extent(&inode->io_tree, file_pos, end, cached);
  1867. return PTR_ERR(em);
  1868. }
  1869. free_extent_map(em);
  1870. }
  1871. ordered = btrfs_alloc_ordered_extent(inode, file_pos, &nocow_args->file_extent,
  1872. is_prealloc
  1873. ? (1U << BTRFS_ORDERED_PREALLOC)
  1874. : (1U << BTRFS_ORDERED_NOCOW));
  1875. if (IS_ERR(ordered)) {
  1876. if (is_prealloc)
  1877. btrfs_drop_extent_map_range(inode, file_pos, end, false);
  1878. unlock_extent(&inode->io_tree, file_pos, end, cached);
  1879. return PTR_ERR(ordered);
  1880. }
  1881. if (btrfs_is_data_reloc_root(inode->root))
  1882. /*
  1883. * Errors are handled later, as we must prevent
  1884. * extent_clear_unlock_delalloc() in error handler from freeing
  1885. * metadata of the created ordered extent.
  1886. */
  1887. ret = btrfs_reloc_clone_csums(ordered);
  1888. btrfs_put_ordered_extent(ordered);
  1889. extent_clear_unlock_delalloc(inode, file_pos, end, locked_folio, cached,
  1890. EXTENT_LOCKED | EXTENT_DELALLOC |
  1891. EXTENT_CLEAR_DATA_RESV,
  1892. PAGE_UNLOCK | PAGE_SET_ORDERED);
  1893. /*
  1894. * btrfs_reloc_clone_csums() error, now we're OK to call error handler,
  1895. * as metadata for created ordered extent will only be freed by
  1896. * btrfs_finish_ordered_io().
  1897. */
  1898. return ret;
  1899. }
  1900. /*
  1901. * when nowcow writeback call back. This checks for snapshots or COW copies
  1902. * of the extents that exist in the file, and COWs the file as required.
  1903. *
  1904. * If no cow copies or snapshots exist, we write directly to the existing
  1905. * blocks on disk
  1906. */
  1907. static noinline int run_delalloc_nocow(struct btrfs_inode *inode,
  1908. struct folio *locked_folio,
  1909. const u64 start, const u64 end)
  1910. {
  1911. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  1912. struct btrfs_root *root = inode->root;
  1913. struct btrfs_path *path;
  1914. u64 cow_start = (u64)-1;
  1915. /*
  1916. * If not 0, represents the inclusive end of the last fallback_to_cow()
  1917. * range. Only for error handling.
  1918. */
  1919. u64 cow_end = 0;
  1920. u64 cur_offset = start;
  1921. int ret;
  1922. bool check_prev = true;
  1923. u64 ino = btrfs_ino(inode);
  1924. struct can_nocow_file_extent_args nocow_args = { 0 };
  1925. /*
  1926. * Normally on a zoned device we're only doing COW writes, but in case
  1927. * of relocation on a zoned filesystem serializes I/O so that we're only
  1928. * writing sequentially and can end up here as well.
  1929. */
  1930. ASSERT(!btrfs_is_zoned(fs_info) || btrfs_is_data_reloc_root(root));
  1931. path = btrfs_alloc_path();
  1932. if (!path) {
  1933. ret = -ENOMEM;
  1934. goto error;
  1935. }
  1936. nocow_args.end = end;
  1937. nocow_args.writeback_path = true;
  1938. while (cur_offset <= end) {
  1939. struct btrfs_block_group *nocow_bg = NULL;
  1940. struct btrfs_key found_key;
  1941. struct btrfs_file_extent_item *fi;
  1942. struct extent_buffer *leaf;
  1943. struct extent_state *cached_state = NULL;
  1944. u64 extent_end;
  1945. int extent_type;
  1946. ret = btrfs_lookup_file_extent(NULL, root, path, ino,
  1947. cur_offset, 0);
  1948. if (ret < 0)
  1949. goto error;
  1950. /*
  1951. * If there is no extent for our range when doing the initial
  1952. * search, then go back to the previous slot as it will be the
  1953. * one containing the search offset
  1954. */
  1955. if (ret > 0 && path->slots[0] > 0 && check_prev) {
  1956. leaf = path->nodes[0];
  1957. btrfs_item_key_to_cpu(leaf, &found_key,
  1958. path->slots[0] - 1);
  1959. if (found_key.objectid == ino &&
  1960. found_key.type == BTRFS_EXTENT_DATA_KEY)
  1961. path->slots[0]--;
  1962. }
  1963. check_prev = false;
  1964. next_slot:
  1965. /* Go to next leaf if we have exhausted the current one */
  1966. leaf = path->nodes[0];
  1967. if (path->slots[0] >= btrfs_header_nritems(leaf)) {
  1968. ret = btrfs_next_leaf(root, path);
  1969. if (ret < 0)
  1970. goto error;
  1971. if (ret > 0)
  1972. break;
  1973. leaf = path->nodes[0];
  1974. }
  1975. btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
  1976. /* Didn't find anything for our INO */
  1977. if (found_key.objectid > ino)
  1978. break;
  1979. /*
  1980. * Keep searching until we find an EXTENT_ITEM or there are no
  1981. * more extents for this inode
  1982. */
  1983. if (WARN_ON_ONCE(found_key.objectid < ino) ||
  1984. found_key.type < BTRFS_EXTENT_DATA_KEY) {
  1985. path->slots[0]++;
  1986. goto next_slot;
  1987. }
  1988. /* Found key is not EXTENT_DATA_KEY or starts after req range */
  1989. if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
  1990. found_key.offset > end)
  1991. break;
  1992. /*
  1993. * If the found extent starts after requested offset, then
  1994. * adjust cur_offset to be right before this extent begins.
  1995. */
  1996. if (found_key.offset > cur_offset) {
  1997. if (cow_start == (u64)-1)
  1998. cow_start = cur_offset;
  1999. cur_offset = found_key.offset;
  2000. goto next_slot;
  2001. }
  2002. /*
  2003. * Found extent which begins before our range and potentially
  2004. * intersect it
  2005. */
  2006. fi = btrfs_item_ptr(leaf, path->slots[0],
  2007. struct btrfs_file_extent_item);
  2008. extent_type = btrfs_file_extent_type(leaf, fi);
  2009. /* If this is triggered then we have a memory corruption. */
  2010. ASSERT(extent_type < BTRFS_NR_FILE_EXTENT_TYPES);
  2011. if (WARN_ON(extent_type >= BTRFS_NR_FILE_EXTENT_TYPES)) {
  2012. ret = -EUCLEAN;
  2013. goto error;
  2014. }
  2015. extent_end = btrfs_file_extent_end(path);
  2016. /*
  2017. * If the extent we got ends before our current offset, skip to
  2018. * the next extent.
  2019. */
  2020. if (extent_end <= cur_offset) {
  2021. path->slots[0]++;
  2022. goto next_slot;
  2023. }
  2024. nocow_args.start = cur_offset;
  2025. ret = can_nocow_file_extent(path, &found_key, inode, &nocow_args);
  2026. if (ret < 0)
  2027. goto error;
  2028. if (ret == 0)
  2029. goto must_cow;
  2030. ret = 0;
  2031. nocow_bg = btrfs_inc_nocow_writers(fs_info,
  2032. nocow_args.file_extent.disk_bytenr +
  2033. nocow_args.file_extent.offset);
  2034. if (!nocow_bg) {
  2035. must_cow:
  2036. /*
  2037. * If we can't perform NOCOW writeback for the range,
  2038. * then record the beginning of the range that needs to
  2039. * be COWed. It will be written out before the next
  2040. * NOCOW range if we find one, or when exiting this
  2041. * loop.
  2042. */
  2043. if (cow_start == (u64)-1)
  2044. cow_start = cur_offset;
  2045. cur_offset = extent_end;
  2046. if (cur_offset > end)
  2047. break;
  2048. if (!path->nodes[0])
  2049. continue;
  2050. path->slots[0]++;
  2051. goto next_slot;
  2052. }
  2053. /*
  2054. * COW range from cow_start to found_key.offset - 1. As the key
  2055. * will contain the beginning of the first extent that can be
  2056. * NOCOW, following one which needs to be COW'ed
  2057. */
  2058. if (cow_start != (u64)-1) {
  2059. ret = fallback_to_cow(inode, locked_folio, cow_start,
  2060. found_key.offset - 1);
  2061. cow_start = (u64)-1;
  2062. if (ret) {
  2063. cow_end = found_key.offset - 1;
  2064. btrfs_dec_nocow_writers(nocow_bg);
  2065. goto error;
  2066. }
  2067. }
  2068. ret = nocow_one_range(inode, locked_folio, &cached_state,
  2069. &nocow_args, cur_offset,
  2070. extent_type == BTRFS_FILE_EXTENT_PREALLOC);
  2071. btrfs_dec_nocow_writers(nocow_bg);
  2072. if (ret < 0)
  2073. goto error;
  2074. cur_offset = extent_end;
  2075. }
  2076. btrfs_release_path(path);
  2077. if (cur_offset <= end && cow_start == (u64)-1)
  2078. cow_start = cur_offset;
  2079. if (cow_start != (u64)-1) {
  2080. ret = fallback_to_cow(inode, locked_folio, cow_start, end);
  2081. cow_start = (u64)-1;
  2082. if (ret) {
  2083. cow_end = end;
  2084. goto error;
  2085. }
  2086. }
  2087. btrfs_free_path(path);
  2088. return 0;
  2089. error:
  2090. /*
  2091. * There are several error cases:
  2092. *
  2093. * 1) Failed without falling back to COW
  2094. * start cur_offset end
  2095. * |/////////////| |
  2096. *
  2097. * For range [start, cur_offset) the folios are already unlocked (except
  2098. * @locked_folio), EXTENT_DELALLOC already removed.
  2099. * Only need to clear the dirty flag as they will never be submitted.
  2100. * Ordered extent and extent maps are handled by
  2101. * btrfs_mark_ordered_io_finished() inside run_delalloc_range().
  2102. *
  2103. * 2) Failed with error from fallback_to_cow()
  2104. * start cur_offset cow_end end
  2105. * |/////////////|-----------| |
  2106. *
  2107. * For range [start, cur_offset) it's the same as case 1).
  2108. * But for range [cur_offset, cow_end), the folios have dirty flag
  2109. * cleared and unlocked, EXTENT_DEALLLOC cleared by cow_file_range().
  2110. *
  2111. * Thus we should not call extent_clear_unlock_delalloc() on range
  2112. * [cur_offset, cow_end), as the folios are already unlocked.
  2113. *
  2114. * So clear the folio dirty flags for [start, cur_offset) first.
  2115. */
  2116. if (cur_offset > start)
  2117. cleanup_dirty_folios(inode, locked_folio, start, cur_offset - 1, ret);
  2118. /*
  2119. * If an error happened while a COW region is outstanding, cur_offset
  2120. * needs to be reset to @cow_end + 1 to skip the COW range, as
  2121. * cow_file_range() will do the proper cleanup at error.
  2122. */
  2123. if (cow_end)
  2124. cur_offset = cow_end + 1;
  2125. /*
  2126. * We need to lock the extent here because we're clearing DELALLOC and
  2127. * we're not locked at this point.
  2128. */
  2129. if (cur_offset < end) {
  2130. struct extent_state *cached = NULL;
  2131. lock_extent(&inode->io_tree, cur_offset, end, &cached);
  2132. extent_clear_unlock_delalloc(inode, cur_offset, end,
  2133. locked_folio, &cached,
  2134. EXTENT_LOCKED | EXTENT_DELALLOC |
  2135. EXTENT_DEFRAG |
  2136. EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
  2137. PAGE_START_WRITEBACK |
  2138. PAGE_END_WRITEBACK);
  2139. btrfs_qgroup_free_data(inode, NULL, cur_offset, end - cur_offset + 1, NULL);
  2140. }
  2141. btrfs_free_path(path);
  2142. return ret;
  2143. }
  2144. static bool should_nocow(struct btrfs_inode *inode, u64 start, u64 end)
  2145. {
  2146. if (inode->flags & (BTRFS_INODE_NODATACOW | BTRFS_INODE_PREALLOC)) {
  2147. if (inode->defrag_bytes &&
  2148. test_range_bit_exists(&inode->io_tree, start, end, EXTENT_DEFRAG))
  2149. return false;
  2150. return true;
  2151. }
  2152. return false;
  2153. }
  2154. /*
  2155. * Function to process delayed allocation (create CoW) for ranges which are
  2156. * being touched for the first time.
  2157. */
  2158. int btrfs_run_delalloc_range(struct btrfs_inode *inode, struct folio *locked_folio,
  2159. u64 start, u64 end, struct writeback_control *wbc)
  2160. {
  2161. const bool zoned = btrfs_is_zoned(inode->root->fs_info);
  2162. int ret;
  2163. /*
  2164. * The range must cover part of the @locked_folio, or a return of 1
  2165. * can confuse the caller.
  2166. */
  2167. ASSERT(!(end <= folio_pos(locked_folio) ||
  2168. start >= folio_pos(locked_folio) + folio_size(locked_folio)));
  2169. if (should_nocow(inode, start, end)) {
  2170. ret = run_delalloc_nocow(inode, locked_folio, start, end);
  2171. goto out;
  2172. }
  2173. if (btrfs_inode_can_compress(inode) &&
  2174. inode_need_compress(inode, start, end) &&
  2175. run_delalloc_compressed(inode, locked_folio, start, end, wbc))
  2176. return 1;
  2177. if (zoned)
  2178. ret = run_delalloc_cow(inode, locked_folio, start, end, wbc,
  2179. true);
  2180. else
  2181. ret = cow_file_range(inode, locked_folio, start, end, NULL,
  2182. false, false);
  2183. out:
  2184. if (ret < 0)
  2185. btrfs_cleanup_ordered_extents(inode, NULL, start, end - start + 1);
  2186. return ret;
  2187. }
  2188. void btrfs_split_delalloc_extent(struct btrfs_inode *inode,
  2189. struct extent_state *orig, u64 split)
  2190. {
  2191. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  2192. u64 size;
  2193. lockdep_assert_held(&inode->io_tree.lock);
  2194. /* not delalloc, ignore it */
  2195. if (!(orig->state & EXTENT_DELALLOC))
  2196. return;
  2197. size = orig->end - orig->start + 1;
  2198. if (size > fs_info->max_extent_size) {
  2199. u32 num_extents;
  2200. u64 new_size;
  2201. /*
  2202. * See the explanation in btrfs_merge_delalloc_extent, the same
  2203. * applies here, just in reverse.
  2204. */
  2205. new_size = orig->end - split + 1;
  2206. num_extents = count_max_extents(fs_info, new_size);
  2207. new_size = split - orig->start;
  2208. num_extents += count_max_extents(fs_info, new_size);
  2209. if (count_max_extents(fs_info, size) >= num_extents)
  2210. return;
  2211. }
  2212. spin_lock(&inode->lock);
  2213. btrfs_mod_outstanding_extents(inode, 1);
  2214. spin_unlock(&inode->lock);
  2215. }
  2216. /*
  2217. * Handle merged delayed allocation extents so we can keep track of new extents
  2218. * that are just merged onto old extents, such as when we are doing sequential
  2219. * writes, so we can properly account for the metadata space we'll need.
  2220. */
  2221. void btrfs_merge_delalloc_extent(struct btrfs_inode *inode, struct extent_state *new,
  2222. struct extent_state *other)
  2223. {
  2224. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  2225. u64 new_size, old_size;
  2226. u32 num_extents;
  2227. lockdep_assert_held(&inode->io_tree.lock);
  2228. /* not delalloc, ignore it */
  2229. if (!(other->state & EXTENT_DELALLOC))
  2230. return;
  2231. if (new->start > other->start)
  2232. new_size = new->end - other->start + 1;
  2233. else
  2234. new_size = other->end - new->start + 1;
  2235. /* we're not bigger than the max, unreserve the space and go */
  2236. if (new_size <= fs_info->max_extent_size) {
  2237. spin_lock(&inode->lock);
  2238. btrfs_mod_outstanding_extents(inode, -1);
  2239. spin_unlock(&inode->lock);
  2240. return;
  2241. }
  2242. /*
  2243. * We have to add up either side to figure out how many extents were
  2244. * accounted for before we merged into one big extent. If the number of
  2245. * extents we accounted for is <= the amount we need for the new range
  2246. * then we can return, otherwise drop. Think of it like this
  2247. *
  2248. * [ 4k][MAX_SIZE]
  2249. *
  2250. * So we've grown the extent by a MAX_SIZE extent, this would mean we
  2251. * need 2 outstanding extents, on one side we have 1 and the other side
  2252. * we have 1 so they are == and we can return. But in this case
  2253. *
  2254. * [MAX_SIZE+4k][MAX_SIZE+4k]
  2255. *
  2256. * Each range on their own accounts for 2 extents, but merged together
  2257. * they are only 3 extents worth of accounting, so we need to drop in
  2258. * this case.
  2259. */
  2260. old_size = other->end - other->start + 1;
  2261. num_extents = count_max_extents(fs_info, old_size);
  2262. old_size = new->end - new->start + 1;
  2263. num_extents += count_max_extents(fs_info, old_size);
  2264. if (count_max_extents(fs_info, new_size) >= num_extents)
  2265. return;
  2266. spin_lock(&inode->lock);
  2267. btrfs_mod_outstanding_extents(inode, -1);
  2268. spin_unlock(&inode->lock);
  2269. }
  2270. static void btrfs_add_delalloc_inode(struct btrfs_inode *inode)
  2271. {
  2272. struct btrfs_root *root = inode->root;
  2273. struct btrfs_fs_info *fs_info = root->fs_info;
  2274. spin_lock(&root->delalloc_lock);
  2275. ASSERT(list_empty(&inode->delalloc_inodes));
  2276. list_add_tail(&inode->delalloc_inodes, &root->delalloc_inodes);
  2277. root->nr_delalloc_inodes++;
  2278. if (root->nr_delalloc_inodes == 1) {
  2279. spin_lock(&fs_info->delalloc_root_lock);
  2280. ASSERT(list_empty(&root->delalloc_root));
  2281. list_add_tail(&root->delalloc_root, &fs_info->delalloc_roots);
  2282. spin_unlock(&fs_info->delalloc_root_lock);
  2283. }
  2284. spin_unlock(&root->delalloc_lock);
  2285. }
  2286. void btrfs_del_delalloc_inode(struct btrfs_inode *inode)
  2287. {
  2288. struct btrfs_root *root = inode->root;
  2289. struct btrfs_fs_info *fs_info = root->fs_info;
  2290. lockdep_assert_held(&root->delalloc_lock);
  2291. /*
  2292. * We may be called after the inode was already deleted from the list,
  2293. * namely in the transaction abort path btrfs_destroy_delalloc_inodes(),
  2294. * and then later through btrfs_clear_delalloc_extent() while the inode
  2295. * still has ->delalloc_bytes > 0.
  2296. */
  2297. if (!list_empty(&inode->delalloc_inodes)) {
  2298. list_del_init(&inode->delalloc_inodes);
  2299. root->nr_delalloc_inodes--;
  2300. if (!root->nr_delalloc_inodes) {
  2301. ASSERT(list_empty(&root->delalloc_inodes));
  2302. spin_lock(&fs_info->delalloc_root_lock);
  2303. ASSERT(!list_empty(&root->delalloc_root));
  2304. list_del_init(&root->delalloc_root);
  2305. spin_unlock(&fs_info->delalloc_root_lock);
  2306. }
  2307. }
  2308. }
  2309. /*
  2310. * Properly track delayed allocation bytes in the inode and to maintain the
  2311. * list of inodes that have pending delalloc work to be done.
  2312. */
  2313. void btrfs_set_delalloc_extent(struct btrfs_inode *inode, struct extent_state *state,
  2314. u32 bits)
  2315. {
  2316. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  2317. lockdep_assert_held(&inode->io_tree.lock);
  2318. if ((bits & EXTENT_DEFRAG) && !(bits & EXTENT_DELALLOC))
  2319. WARN_ON(1);
  2320. /*
  2321. * set_bit and clear bit hooks normally require _irqsave/restore
  2322. * but in this case, we are only testing for the DELALLOC
  2323. * bit, which is only set or cleared with irqs on
  2324. */
  2325. if (!(state->state & EXTENT_DELALLOC) && (bits & EXTENT_DELALLOC)) {
  2326. u64 len = state->end + 1 - state->start;
  2327. u64 prev_delalloc_bytes;
  2328. u32 num_extents = count_max_extents(fs_info, len);
  2329. spin_lock(&inode->lock);
  2330. btrfs_mod_outstanding_extents(inode, num_extents);
  2331. spin_unlock(&inode->lock);
  2332. /* For sanity tests */
  2333. if (btrfs_is_testing(fs_info))
  2334. return;
  2335. percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
  2336. fs_info->delalloc_batch);
  2337. spin_lock(&inode->lock);
  2338. prev_delalloc_bytes = inode->delalloc_bytes;
  2339. inode->delalloc_bytes += len;
  2340. if (bits & EXTENT_DEFRAG)
  2341. inode->defrag_bytes += len;
  2342. spin_unlock(&inode->lock);
  2343. /*
  2344. * We don't need to be under the protection of the inode's lock,
  2345. * because we are called while holding the inode's io_tree lock
  2346. * and are therefore protected against concurrent calls of this
  2347. * function and btrfs_clear_delalloc_extent().
  2348. */
  2349. if (!btrfs_is_free_space_inode(inode) && prev_delalloc_bytes == 0)
  2350. btrfs_add_delalloc_inode(inode);
  2351. }
  2352. if (!(state->state & EXTENT_DELALLOC_NEW) &&
  2353. (bits & EXTENT_DELALLOC_NEW)) {
  2354. spin_lock(&inode->lock);
  2355. inode->new_delalloc_bytes += state->end + 1 - state->start;
  2356. spin_unlock(&inode->lock);
  2357. }
  2358. }
  2359. /*
  2360. * Once a range is no longer delalloc this function ensures that proper
  2361. * accounting happens.
  2362. */
  2363. void btrfs_clear_delalloc_extent(struct btrfs_inode *inode,
  2364. struct extent_state *state, u32 bits)
  2365. {
  2366. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  2367. u64 len = state->end + 1 - state->start;
  2368. u32 num_extents = count_max_extents(fs_info, len);
  2369. lockdep_assert_held(&inode->io_tree.lock);
  2370. if ((state->state & EXTENT_DEFRAG) && (bits & EXTENT_DEFRAG)) {
  2371. spin_lock(&inode->lock);
  2372. inode->defrag_bytes -= len;
  2373. spin_unlock(&inode->lock);
  2374. }
  2375. /*
  2376. * set_bit and clear bit hooks normally require _irqsave/restore
  2377. * but in this case, we are only testing for the DELALLOC
  2378. * bit, which is only set or cleared with irqs on
  2379. */
  2380. if ((state->state & EXTENT_DELALLOC) && (bits & EXTENT_DELALLOC)) {
  2381. struct btrfs_root *root = inode->root;
  2382. u64 new_delalloc_bytes;
  2383. spin_lock(&inode->lock);
  2384. btrfs_mod_outstanding_extents(inode, -num_extents);
  2385. spin_unlock(&inode->lock);
  2386. /*
  2387. * We don't reserve metadata space for space cache inodes so we
  2388. * don't need to call delalloc_release_metadata if there is an
  2389. * error.
  2390. */
  2391. if (bits & EXTENT_CLEAR_META_RESV &&
  2392. root != fs_info->tree_root)
  2393. btrfs_delalloc_release_metadata(inode, len, true);
  2394. /* For sanity tests. */
  2395. if (btrfs_is_testing(fs_info))
  2396. return;
  2397. if (!btrfs_is_data_reloc_root(root) &&
  2398. !btrfs_is_free_space_inode(inode) &&
  2399. !(state->state & EXTENT_NORESERVE) &&
  2400. (bits & EXTENT_CLEAR_DATA_RESV))
  2401. btrfs_free_reserved_data_space_noquota(fs_info, len);
  2402. percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
  2403. fs_info->delalloc_batch);
  2404. spin_lock(&inode->lock);
  2405. inode->delalloc_bytes -= len;
  2406. new_delalloc_bytes = inode->delalloc_bytes;
  2407. spin_unlock(&inode->lock);
  2408. /*
  2409. * We don't need to be under the protection of the inode's lock,
  2410. * because we are called while holding the inode's io_tree lock
  2411. * and are therefore protected against concurrent calls of this
  2412. * function and btrfs_set_delalloc_extent().
  2413. */
  2414. if (!btrfs_is_free_space_inode(inode) && new_delalloc_bytes == 0) {
  2415. spin_lock(&root->delalloc_lock);
  2416. btrfs_del_delalloc_inode(inode);
  2417. spin_unlock(&root->delalloc_lock);
  2418. }
  2419. }
  2420. if ((state->state & EXTENT_DELALLOC_NEW) &&
  2421. (bits & EXTENT_DELALLOC_NEW)) {
  2422. spin_lock(&inode->lock);
  2423. ASSERT(inode->new_delalloc_bytes >= len);
  2424. inode->new_delalloc_bytes -= len;
  2425. if (bits & EXTENT_ADD_INODE_BYTES)
  2426. inode_add_bytes(&inode->vfs_inode, len);
  2427. spin_unlock(&inode->lock);
  2428. }
  2429. }
  2430. /*
  2431. * given a list of ordered sums record them in the inode. This happens
  2432. * at IO completion time based on sums calculated at bio submission time.
  2433. */
  2434. static int add_pending_csums(struct btrfs_trans_handle *trans,
  2435. struct list_head *list)
  2436. {
  2437. struct btrfs_ordered_sum *sum;
  2438. struct btrfs_root *csum_root = NULL;
  2439. int ret;
  2440. list_for_each_entry(sum, list, list) {
  2441. trans->adding_csums = true;
  2442. if (!csum_root)
  2443. csum_root = btrfs_csum_root(trans->fs_info,
  2444. sum->logical);
  2445. ret = btrfs_csum_file_blocks(trans, csum_root, sum);
  2446. trans->adding_csums = false;
  2447. if (ret)
  2448. return ret;
  2449. }
  2450. return 0;
  2451. }
  2452. static int btrfs_find_new_delalloc_bytes(struct btrfs_inode *inode,
  2453. const u64 start,
  2454. const u64 len,
  2455. struct extent_state **cached_state)
  2456. {
  2457. u64 search_start = start;
  2458. const u64 end = start + len - 1;
  2459. while (search_start < end) {
  2460. const u64 search_len = end - search_start + 1;
  2461. struct extent_map *em;
  2462. u64 em_len;
  2463. int ret = 0;
  2464. em = btrfs_get_extent(inode, NULL, search_start, search_len);
  2465. if (IS_ERR(em))
  2466. return PTR_ERR(em);
  2467. if (em->disk_bytenr != EXTENT_MAP_HOLE)
  2468. goto next;
  2469. em_len = em->len;
  2470. if (em->start < search_start)
  2471. em_len -= search_start - em->start;
  2472. if (em_len > search_len)
  2473. em_len = search_len;
  2474. ret = set_extent_bit(&inode->io_tree, search_start,
  2475. search_start + em_len - 1,
  2476. EXTENT_DELALLOC_NEW, cached_state);
  2477. next:
  2478. search_start = extent_map_end(em);
  2479. free_extent_map(em);
  2480. if (ret)
  2481. return ret;
  2482. }
  2483. return 0;
  2484. }
  2485. int btrfs_set_extent_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
  2486. unsigned int extra_bits,
  2487. struct extent_state **cached_state)
  2488. {
  2489. WARN_ON(PAGE_ALIGNED(end));
  2490. if (start >= i_size_read(&inode->vfs_inode) &&
  2491. !(inode->flags & BTRFS_INODE_PREALLOC)) {
  2492. /*
  2493. * There can't be any extents following eof in this case so just
  2494. * set the delalloc new bit for the range directly.
  2495. */
  2496. extra_bits |= EXTENT_DELALLOC_NEW;
  2497. } else {
  2498. int ret;
  2499. ret = btrfs_find_new_delalloc_bytes(inode, start,
  2500. end + 1 - start,
  2501. cached_state);
  2502. if (ret)
  2503. return ret;
  2504. }
  2505. return set_extent_bit(&inode->io_tree, start, end,
  2506. EXTENT_DELALLOC | extra_bits, cached_state);
  2507. }
  2508. /* see btrfs_writepage_start_hook for details on why this is required */
  2509. struct btrfs_writepage_fixup {
  2510. struct folio *folio;
  2511. struct btrfs_inode *inode;
  2512. struct btrfs_work work;
  2513. };
  2514. static void btrfs_writepage_fixup_worker(struct btrfs_work *work)
  2515. {
  2516. struct btrfs_writepage_fixup *fixup =
  2517. container_of(work, struct btrfs_writepage_fixup, work);
  2518. struct btrfs_ordered_extent *ordered;
  2519. struct extent_state *cached_state = NULL;
  2520. struct extent_changeset *data_reserved = NULL;
  2521. struct folio *folio = fixup->folio;
  2522. struct btrfs_inode *inode = fixup->inode;
  2523. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  2524. u64 page_start = folio_pos(folio);
  2525. u64 page_end = folio_pos(folio) + folio_size(folio) - 1;
  2526. int ret = 0;
  2527. bool free_delalloc_space = true;
  2528. /*
  2529. * This is similar to page_mkwrite, we need to reserve the space before
  2530. * we take the folio lock.
  2531. */
  2532. ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
  2533. folio_size(folio));
  2534. again:
  2535. folio_lock(folio);
  2536. /*
  2537. * Before we queued this fixup, we took a reference on the folio.
  2538. * folio->mapping may go NULL, but it shouldn't be moved to a different
  2539. * address space.
  2540. */
  2541. if (!folio->mapping || !folio_test_dirty(folio) ||
  2542. !folio_test_checked(folio)) {
  2543. /*
  2544. * Unfortunately this is a little tricky, either
  2545. *
  2546. * 1) We got here and our folio had already been dealt with and
  2547. * we reserved our space, thus ret == 0, so we need to just
  2548. * drop our space reservation and bail. This can happen the
  2549. * first time we come into the fixup worker, or could happen
  2550. * while waiting for the ordered extent.
  2551. * 2) Our folio was already dealt with, but we happened to get an
  2552. * ENOSPC above from the btrfs_delalloc_reserve_space. In
  2553. * this case we obviously don't have anything to release, but
  2554. * because the folio was already dealt with we don't want to
  2555. * mark the folio with an error, so make sure we're resetting
  2556. * ret to 0. This is why we have this check _before_ the ret
  2557. * check, because we do not want to have a surprise ENOSPC
  2558. * when the folio was already properly dealt with.
  2559. */
  2560. if (!ret) {
  2561. btrfs_delalloc_release_extents(inode, folio_size(folio));
  2562. btrfs_delalloc_release_space(inode, data_reserved,
  2563. page_start, folio_size(folio),
  2564. true);
  2565. }
  2566. ret = 0;
  2567. goto out_page;
  2568. }
  2569. /*
  2570. * We can't mess with the folio state unless it is locked, so now that
  2571. * it is locked bail if we failed to make our space reservation.
  2572. */
  2573. if (ret)
  2574. goto out_page;
  2575. lock_extent(&inode->io_tree, page_start, page_end, &cached_state);
  2576. /* already ordered? We're done */
  2577. if (folio_test_ordered(folio))
  2578. goto out_reserved;
  2579. ordered = btrfs_lookup_ordered_range(inode, page_start, PAGE_SIZE);
  2580. if (ordered) {
  2581. unlock_extent(&inode->io_tree, page_start, page_end,
  2582. &cached_state);
  2583. folio_unlock(folio);
  2584. btrfs_start_ordered_extent(ordered);
  2585. btrfs_put_ordered_extent(ordered);
  2586. goto again;
  2587. }
  2588. ret = btrfs_set_extent_delalloc(inode, page_start, page_end, 0,
  2589. &cached_state);
  2590. if (ret)
  2591. goto out_reserved;
  2592. /*
  2593. * Everything went as planned, we're now the owner of a dirty page with
  2594. * delayed allocation bits set and space reserved for our COW
  2595. * destination.
  2596. *
  2597. * The page was dirty when we started, nothing should have cleaned it.
  2598. */
  2599. BUG_ON(!folio_test_dirty(folio));
  2600. free_delalloc_space = false;
  2601. out_reserved:
  2602. btrfs_delalloc_release_extents(inode, PAGE_SIZE);
  2603. if (free_delalloc_space)
  2604. btrfs_delalloc_release_space(inode, data_reserved, page_start,
  2605. PAGE_SIZE, true);
  2606. unlock_extent(&inode->io_tree, page_start, page_end, &cached_state);
  2607. out_page:
  2608. if (ret) {
  2609. /*
  2610. * We hit ENOSPC or other errors. Update the mapping and page
  2611. * to reflect the errors and clean the page.
  2612. */
  2613. mapping_set_error(folio->mapping, ret);
  2614. btrfs_mark_ordered_io_finished(inode, folio, page_start,
  2615. folio_size(folio), !ret);
  2616. folio_clear_dirty_for_io(folio);
  2617. }
  2618. btrfs_folio_clear_checked(fs_info, folio, page_start, PAGE_SIZE);
  2619. folio_unlock(folio);
  2620. folio_put(folio);
  2621. kfree(fixup);
  2622. extent_changeset_free(data_reserved);
  2623. /*
  2624. * As a precaution, do a delayed iput in case it would be the last iput
  2625. * that could need flushing space. Recursing back to fixup worker would
  2626. * deadlock.
  2627. */
  2628. btrfs_add_delayed_iput(inode);
  2629. }
  2630. /*
  2631. * There are a few paths in the higher layers of the kernel that directly
  2632. * set the folio dirty bit without asking the filesystem if it is a
  2633. * good idea. This causes problems because we want to make sure COW
  2634. * properly happens and the data=ordered rules are followed.
  2635. *
  2636. * In our case any range that doesn't have the ORDERED bit set
  2637. * hasn't been properly setup for IO. We kick off an async process
  2638. * to fix it up. The async helper will wait for ordered extents, set
  2639. * the delalloc bit and make it safe to write the folio.
  2640. */
  2641. int btrfs_writepage_cow_fixup(struct folio *folio)
  2642. {
  2643. struct inode *inode = folio->mapping->host;
  2644. struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
  2645. struct btrfs_writepage_fixup *fixup;
  2646. /* This folio has ordered extent covering it already */
  2647. if (folio_test_ordered(folio))
  2648. return 0;
  2649. /*
  2650. * folio_checked is set below when we create a fixup worker for this
  2651. * folio, don't try to create another one if we're already
  2652. * folio_test_checked.
  2653. *
  2654. * The extent_io writepage code will redirty the foio if we send back
  2655. * EAGAIN.
  2656. */
  2657. if (folio_test_checked(folio))
  2658. return -EAGAIN;
  2659. fixup = kzalloc(sizeof(*fixup), GFP_NOFS);
  2660. if (!fixup)
  2661. return -EAGAIN;
  2662. /*
  2663. * We are already holding a reference to this inode from
  2664. * write_cache_pages. We need to hold it because the space reservation
  2665. * takes place outside of the folio lock, and we can't trust
  2666. * page->mapping outside of the folio lock.
  2667. */
  2668. ihold(inode);
  2669. btrfs_folio_set_checked(fs_info, folio, folio_pos(folio), folio_size(folio));
  2670. folio_get(folio);
  2671. btrfs_init_work(&fixup->work, btrfs_writepage_fixup_worker, NULL);
  2672. fixup->folio = folio;
  2673. fixup->inode = BTRFS_I(inode);
  2674. btrfs_queue_work(fs_info->fixup_workers, &fixup->work);
  2675. return -EAGAIN;
  2676. }
  2677. static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
  2678. struct btrfs_inode *inode, u64 file_pos,
  2679. struct btrfs_file_extent_item *stack_fi,
  2680. const bool update_inode_bytes,
  2681. u64 qgroup_reserved)
  2682. {
  2683. struct btrfs_root *root = inode->root;
  2684. const u64 sectorsize = root->fs_info->sectorsize;
  2685. struct btrfs_path *path;
  2686. struct extent_buffer *leaf;
  2687. struct btrfs_key ins;
  2688. u64 disk_num_bytes = btrfs_stack_file_extent_disk_num_bytes(stack_fi);
  2689. u64 disk_bytenr = btrfs_stack_file_extent_disk_bytenr(stack_fi);
  2690. u64 offset = btrfs_stack_file_extent_offset(stack_fi);
  2691. u64 num_bytes = btrfs_stack_file_extent_num_bytes(stack_fi);
  2692. u64 ram_bytes = btrfs_stack_file_extent_ram_bytes(stack_fi);
  2693. struct btrfs_drop_extents_args drop_args = { 0 };
  2694. int ret;
  2695. path = btrfs_alloc_path();
  2696. if (!path)
  2697. return -ENOMEM;
  2698. /*
  2699. * we may be replacing one extent in the tree with another.
  2700. * The new extent is pinned in the extent map, and we don't want
  2701. * to drop it from the cache until it is completely in the btree.
  2702. *
  2703. * So, tell btrfs_drop_extents to leave this extent in the cache.
  2704. * the caller is expected to unpin it and allow it to be merged
  2705. * with the others.
  2706. */
  2707. drop_args.path = path;
  2708. drop_args.start = file_pos;
  2709. drop_args.end = file_pos + num_bytes;
  2710. drop_args.replace_extent = true;
  2711. drop_args.extent_item_size = sizeof(*stack_fi);
  2712. ret = btrfs_drop_extents(trans, root, inode, &drop_args);
  2713. if (ret)
  2714. goto out;
  2715. if (!drop_args.extent_inserted) {
  2716. ins.objectid = btrfs_ino(inode);
  2717. ins.offset = file_pos;
  2718. ins.type = BTRFS_EXTENT_DATA_KEY;
  2719. ret = btrfs_insert_empty_item(trans, root, path, &ins,
  2720. sizeof(*stack_fi));
  2721. if (ret)
  2722. goto out;
  2723. }
  2724. leaf = path->nodes[0];
  2725. btrfs_set_stack_file_extent_generation(stack_fi, trans->transid);
  2726. write_extent_buffer(leaf, stack_fi,
  2727. btrfs_item_ptr_offset(leaf, path->slots[0]),
  2728. sizeof(struct btrfs_file_extent_item));
  2729. btrfs_mark_buffer_dirty(trans, leaf);
  2730. btrfs_release_path(path);
  2731. /*
  2732. * If we dropped an inline extent here, we know the range where it is
  2733. * was not marked with the EXTENT_DELALLOC_NEW bit, so we update the
  2734. * number of bytes only for that range containing the inline extent.
  2735. * The remaining of the range will be processed when clearning the
  2736. * EXTENT_DELALLOC_BIT bit through the ordered extent completion.
  2737. */
  2738. if (file_pos == 0 && !IS_ALIGNED(drop_args.bytes_found, sectorsize)) {
  2739. u64 inline_size = round_down(drop_args.bytes_found, sectorsize);
  2740. inline_size = drop_args.bytes_found - inline_size;
  2741. btrfs_update_inode_bytes(inode, sectorsize, inline_size);
  2742. drop_args.bytes_found -= inline_size;
  2743. num_bytes -= sectorsize;
  2744. }
  2745. if (update_inode_bytes)
  2746. btrfs_update_inode_bytes(inode, num_bytes, drop_args.bytes_found);
  2747. ins.objectid = disk_bytenr;
  2748. ins.offset = disk_num_bytes;
  2749. ins.type = BTRFS_EXTENT_ITEM_KEY;
  2750. ret = btrfs_inode_set_file_extent_range(inode, file_pos, ram_bytes);
  2751. if (ret)
  2752. goto out;
  2753. ret = btrfs_alloc_reserved_file_extent(trans, root, btrfs_ino(inode),
  2754. file_pos - offset,
  2755. qgroup_reserved, &ins);
  2756. out:
  2757. btrfs_free_path(path);
  2758. return ret;
  2759. }
  2760. static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
  2761. u64 start, u64 len)
  2762. {
  2763. struct btrfs_block_group *cache;
  2764. cache = btrfs_lookup_block_group(fs_info, start);
  2765. ASSERT(cache);
  2766. spin_lock(&cache->lock);
  2767. cache->delalloc_bytes -= len;
  2768. spin_unlock(&cache->lock);
  2769. btrfs_put_block_group(cache);
  2770. }
  2771. static int insert_ordered_extent_file_extent(struct btrfs_trans_handle *trans,
  2772. struct btrfs_ordered_extent *oe)
  2773. {
  2774. struct btrfs_file_extent_item stack_fi;
  2775. bool update_inode_bytes;
  2776. u64 num_bytes = oe->num_bytes;
  2777. u64 ram_bytes = oe->ram_bytes;
  2778. memset(&stack_fi, 0, sizeof(stack_fi));
  2779. btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_REG);
  2780. btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, oe->disk_bytenr);
  2781. btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi,
  2782. oe->disk_num_bytes);
  2783. btrfs_set_stack_file_extent_offset(&stack_fi, oe->offset);
  2784. if (test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags))
  2785. num_bytes = oe->truncated_len;
  2786. btrfs_set_stack_file_extent_num_bytes(&stack_fi, num_bytes);
  2787. btrfs_set_stack_file_extent_ram_bytes(&stack_fi, ram_bytes);
  2788. btrfs_set_stack_file_extent_compression(&stack_fi, oe->compress_type);
  2789. /* Encryption and other encoding is reserved and all 0 */
  2790. /*
  2791. * For delalloc, when completing an ordered extent we update the inode's
  2792. * bytes when clearing the range in the inode's io tree, so pass false
  2793. * as the argument 'update_inode_bytes' to insert_reserved_file_extent(),
  2794. * except if the ordered extent was truncated.
  2795. */
  2796. update_inode_bytes = test_bit(BTRFS_ORDERED_DIRECT, &oe->flags) ||
  2797. test_bit(BTRFS_ORDERED_ENCODED, &oe->flags) ||
  2798. test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags);
  2799. return insert_reserved_file_extent(trans, oe->inode,
  2800. oe->file_offset, &stack_fi,
  2801. update_inode_bytes, oe->qgroup_rsv);
  2802. }
  2803. /*
  2804. * As ordered data IO finishes, this gets called so we can finish
  2805. * an ordered extent if the range of bytes in the file it covers are
  2806. * fully written.
  2807. */
  2808. int btrfs_finish_one_ordered(struct btrfs_ordered_extent *ordered_extent)
  2809. {
  2810. struct btrfs_inode *inode = ordered_extent->inode;
  2811. struct btrfs_root *root = inode->root;
  2812. struct btrfs_fs_info *fs_info = root->fs_info;
  2813. struct btrfs_trans_handle *trans = NULL;
  2814. struct extent_io_tree *io_tree = &inode->io_tree;
  2815. struct extent_state *cached_state = NULL;
  2816. u64 start, end;
  2817. int compress_type = 0;
  2818. int ret = 0;
  2819. u64 logical_len = ordered_extent->num_bytes;
  2820. bool freespace_inode;
  2821. bool truncated = false;
  2822. bool clear_reserved_extent = true;
  2823. unsigned int clear_bits = EXTENT_DEFRAG;
  2824. start = ordered_extent->file_offset;
  2825. end = start + ordered_extent->num_bytes - 1;
  2826. if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
  2827. !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
  2828. !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags) &&
  2829. !test_bit(BTRFS_ORDERED_ENCODED, &ordered_extent->flags))
  2830. clear_bits |= EXTENT_DELALLOC_NEW;
  2831. freespace_inode = btrfs_is_free_space_inode(inode);
  2832. if (!freespace_inode)
  2833. btrfs_lockdep_acquire(fs_info, btrfs_ordered_extent);
  2834. if (test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags)) {
  2835. ret = -EIO;
  2836. goto out;
  2837. }
  2838. if (btrfs_is_zoned(fs_info))
  2839. btrfs_zone_finish_endio(fs_info, ordered_extent->disk_bytenr,
  2840. ordered_extent->disk_num_bytes);
  2841. if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
  2842. truncated = true;
  2843. logical_len = ordered_extent->truncated_len;
  2844. /* Truncated the entire extent, don't bother adding */
  2845. if (!logical_len)
  2846. goto out;
  2847. }
  2848. if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
  2849. BUG_ON(!list_empty(&ordered_extent->list)); /* Logic error */
  2850. btrfs_inode_safe_disk_i_size_write(inode, 0);
  2851. if (freespace_inode)
  2852. trans = btrfs_join_transaction_spacecache(root);
  2853. else
  2854. trans = btrfs_join_transaction(root);
  2855. if (IS_ERR(trans)) {
  2856. ret = PTR_ERR(trans);
  2857. trans = NULL;
  2858. goto out;
  2859. }
  2860. trans->block_rsv = &inode->block_rsv;
  2861. ret = btrfs_update_inode_fallback(trans, inode);
  2862. if (ret) /* -ENOMEM or corruption */
  2863. btrfs_abort_transaction(trans, ret);
  2864. ret = btrfs_insert_raid_extent(trans, ordered_extent);
  2865. if (ret)
  2866. btrfs_abort_transaction(trans, ret);
  2867. goto out;
  2868. }
  2869. clear_bits |= EXTENT_LOCKED;
  2870. lock_extent(io_tree, start, end, &cached_state);
  2871. if (freespace_inode)
  2872. trans = btrfs_join_transaction_spacecache(root);
  2873. else
  2874. trans = btrfs_join_transaction(root);
  2875. if (IS_ERR(trans)) {
  2876. ret = PTR_ERR(trans);
  2877. trans = NULL;
  2878. goto out;
  2879. }
  2880. trans->block_rsv = &inode->block_rsv;
  2881. ret = btrfs_insert_raid_extent(trans, ordered_extent);
  2882. if (ret)
  2883. goto out;
  2884. if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
  2885. compress_type = ordered_extent->compress_type;
  2886. if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
  2887. BUG_ON(compress_type);
  2888. ret = btrfs_mark_extent_written(trans, inode,
  2889. ordered_extent->file_offset,
  2890. ordered_extent->file_offset +
  2891. logical_len);
  2892. btrfs_zoned_release_data_reloc_bg(fs_info, ordered_extent->disk_bytenr,
  2893. ordered_extent->disk_num_bytes);
  2894. } else {
  2895. BUG_ON(root == fs_info->tree_root);
  2896. ret = insert_ordered_extent_file_extent(trans, ordered_extent);
  2897. if (!ret) {
  2898. clear_reserved_extent = false;
  2899. btrfs_release_delalloc_bytes(fs_info,
  2900. ordered_extent->disk_bytenr,
  2901. ordered_extent->disk_num_bytes);
  2902. }
  2903. }
  2904. if (ret < 0) {
  2905. btrfs_abort_transaction(trans, ret);
  2906. goto out;
  2907. }
  2908. ret = unpin_extent_cache(inode, ordered_extent->file_offset,
  2909. ordered_extent->num_bytes, trans->transid);
  2910. if (ret < 0) {
  2911. btrfs_abort_transaction(trans, ret);
  2912. goto out;
  2913. }
  2914. ret = add_pending_csums(trans, &ordered_extent->list);
  2915. if (ret) {
  2916. btrfs_abort_transaction(trans, ret);
  2917. goto out;
  2918. }
  2919. /*
  2920. * If this is a new delalloc range, clear its new delalloc flag to
  2921. * update the inode's number of bytes. This needs to be done first
  2922. * before updating the inode item.
  2923. */
  2924. if ((clear_bits & EXTENT_DELALLOC_NEW) &&
  2925. !test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags))
  2926. clear_extent_bit(&inode->io_tree, start, end,
  2927. EXTENT_DELALLOC_NEW | EXTENT_ADD_INODE_BYTES,
  2928. &cached_state);
  2929. btrfs_inode_safe_disk_i_size_write(inode, 0);
  2930. ret = btrfs_update_inode_fallback(trans, inode);
  2931. if (ret) { /* -ENOMEM or corruption */
  2932. btrfs_abort_transaction(trans, ret);
  2933. goto out;
  2934. }
  2935. out:
  2936. clear_extent_bit(&inode->io_tree, start, end, clear_bits,
  2937. &cached_state);
  2938. if (trans)
  2939. btrfs_end_transaction(trans);
  2940. if (ret || truncated) {
  2941. u64 unwritten_start = start;
  2942. /*
  2943. * If we failed to finish this ordered extent for any reason we
  2944. * need to make sure BTRFS_ORDERED_IOERR is set on the ordered
  2945. * extent, and mark the inode with the error if it wasn't
  2946. * already set. Any error during writeback would have already
  2947. * set the mapping error, so we need to set it if we're the ones
  2948. * marking this ordered extent as failed.
  2949. */
  2950. if (ret)
  2951. btrfs_mark_ordered_extent_error(ordered_extent);
  2952. if (truncated)
  2953. unwritten_start += logical_len;
  2954. clear_extent_uptodate(io_tree, unwritten_start, end, NULL);
  2955. /*
  2956. * Drop extent maps for the part of the extent we didn't write.
  2957. *
  2958. * We have an exception here for the free_space_inode, this is
  2959. * because when we do btrfs_get_extent() on the free space inode
  2960. * we will search the commit root. If this is a new block group
  2961. * we won't find anything, and we will trip over the assert in
  2962. * writepage where we do ASSERT(em->block_start !=
  2963. * EXTENT_MAP_HOLE).
  2964. *
  2965. * Theoretically we could also skip this for any NOCOW extent as
  2966. * we don't mess with the extent map tree in the NOCOW case, but
  2967. * for now simply skip this if we are the free space inode.
  2968. */
  2969. if (!btrfs_is_free_space_inode(inode))
  2970. btrfs_drop_extent_map_range(inode, unwritten_start,
  2971. end, false);
  2972. /*
  2973. * If the ordered extent had an IOERR or something else went
  2974. * wrong we need to return the space for this ordered extent
  2975. * back to the allocator. We only free the extent in the
  2976. * truncated case if we didn't write out the extent at all.
  2977. *
  2978. * If we made it past insert_reserved_file_extent before we
  2979. * errored out then we don't need to do this as the accounting
  2980. * has already been done.
  2981. */
  2982. if ((ret || !logical_len) &&
  2983. clear_reserved_extent &&
  2984. !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
  2985. !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
  2986. /*
  2987. * Discard the range before returning it back to the
  2988. * free space pool
  2989. */
  2990. if (ret && btrfs_test_opt(fs_info, DISCARD_SYNC))
  2991. btrfs_discard_extent(fs_info,
  2992. ordered_extent->disk_bytenr,
  2993. ordered_extent->disk_num_bytes,
  2994. NULL);
  2995. btrfs_free_reserved_extent(fs_info,
  2996. ordered_extent->disk_bytenr,
  2997. ordered_extent->disk_num_bytes, 1);
  2998. /*
  2999. * Actually free the qgroup rsv which was released when
  3000. * the ordered extent was created.
  3001. */
  3002. btrfs_qgroup_free_refroot(fs_info, btrfs_root_id(inode->root),
  3003. ordered_extent->qgroup_rsv,
  3004. BTRFS_QGROUP_RSV_DATA);
  3005. }
  3006. }
  3007. /*
  3008. * This needs to be done to make sure anybody waiting knows we are done
  3009. * updating everything for this ordered extent.
  3010. */
  3011. btrfs_remove_ordered_extent(inode, ordered_extent);
  3012. /* once for us */
  3013. btrfs_put_ordered_extent(ordered_extent);
  3014. /* once for the tree */
  3015. btrfs_put_ordered_extent(ordered_extent);
  3016. return ret;
  3017. }
  3018. int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered)
  3019. {
  3020. if (btrfs_is_zoned(ordered->inode->root->fs_info) &&
  3021. !test_bit(BTRFS_ORDERED_IOERR, &ordered->flags) &&
  3022. list_empty(&ordered->bioc_list))
  3023. btrfs_finish_ordered_zoned(ordered);
  3024. return btrfs_finish_one_ordered(ordered);
  3025. }
  3026. /*
  3027. * Verify the checksum for a single sector without any extra action that depend
  3028. * on the type of I/O.
  3029. */
  3030. int btrfs_check_sector_csum(struct btrfs_fs_info *fs_info, struct page *page,
  3031. u32 pgoff, u8 *csum, const u8 * const csum_expected)
  3032. {
  3033. SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
  3034. char *kaddr;
  3035. ASSERT(pgoff + fs_info->sectorsize <= PAGE_SIZE);
  3036. shash->tfm = fs_info->csum_shash;
  3037. kaddr = kmap_local_page(page) + pgoff;
  3038. crypto_shash_digest(shash, kaddr, fs_info->sectorsize, csum);
  3039. kunmap_local(kaddr);
  3040. if (memcmp(csum, csum_expected, fs_info->csum_size))
  3041. return -EIO;
  3042. return 0;
  3043. }
  3044. /*
  3045. * Verify the checksum of a single data sector.
  3046. *
  3047. * @bbio: btrfs_io_bio which contains the csum
  3048. * @dev: device the sector is on
  3049. * @bio_offset: offset to the beginning of the bio (in bytes)
  3050. * @bv: bio_vec to check
  3051. *
  3052. * Check if the checksum on a data block is valid. When a checksum mismatch is
  3053. * detected, report the error and fill the corrupted range with zero.
  3054. *
  3055. * Return %true if the sector is ok or had no checksum to start with, else %false.
  3056. */
  3057. bool btrfs_data_csum_ok(struct btrfs_bio *bbio, struct btrfs_device *dev,
  3058. u32 bio_offset, struct bio_vec *bv)
  3059. {
  3060. struct btrfs_inode *inode = bbio->inode;
  3061. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  3062. u64 file_offset = bbio->file_offset + bio_offset;
  3063. u64 end = file_offset + bv->bv_len - 1;
  3064. u8 *csum_expected;
  3065. u8 csum[BTRFS_CSUM_SIZE];
  3066. ASSERT(bv->bv_len == fs_info->sectorsize);
  3067. if (!bbio->csum)
  3068. return true;
  3069. if (btrfs_is_data_reloc_root(inode->root) &&
  3070. test_range_bit(&inode->io_tree, file_offset, end, EXTENT_NODATASUM,
  3071. NULL)) {
  3072. /* Skip the range without csum for data reloc inode */
  3073. clear_extent_bits(&inode->io_tree, file_offset, end,
  3074. EXTENT_NODATASUM);
  3075. return true;
  3076. }
  3077. csum_expected = bbio->csum + (bio_offset >> fs_info->sectorsize_bits) *
  3078. fs_info->csum_size;
  3079. if (btrfs_check_sector_csum(fs_info, bv->bv_page, bv->bv_offset, csum,
  3080. csum_expected))
  3081. goto zeroit;
  3082. return true;
  3083. zeroit:
  3084. btrfs_print_data_csum_error(inode, file_offset, csum, csum_expected,
  3085. bbio->mirror_num);
  3086. if (dev)
  3087. btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS);
  3088. memzero_bvec(bv);
  3089. return false;
  3090. }
  3091. /*
  3092. * Perform a delayed iput on @inode.
  3093. *
  3094. * @inode: The inode we want to perform iput on
  3095. *
  3096. * This function uses the generic vfs_inode::i_count to track whether we should
  3097. * just decrement it (in case it's > 1) or if this is the last iput then link
  3098. * the inode to the delayed iput machinery. Delayed iputs are processed at
  3099. * transaction commit time/superblock commit/cleaner kthread.
  3100. */
  3101. void btrfs_add_delayed_iput(struct btrfs_inode *inode)
  3102. {
  3103. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  3104. unsigned long flags;
  3105. if (atomic_add_unless(&inode->vfs_inode.i_count, -1, 1))
  3106. return;
  3107. atomic_inc(&fs_info->nr_delayed_iputs);
  3108. /*
  3109. * Need to be irq safe here because we can be called from either an irq
  3110. * context (see bio.c and btrfs_put_ordered_extent()) or a non-irq
  3111. * context.
  3112. */
  3113. spin_lock_irqsave(&fs_info->delayed_iput_lock, flags);
  3114. ASSERT(list_empty(&inode->delayed_iput));
  3115. list_add_tail(&inode->delayed_iput, &fs_info->delayed_iputs);
  3116. spin_unlock_irqrestore(&fs_info->delayed_iput_lock, flags);
  3117. if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
  3118. wake_up_process(fs_info->cleaner_kthread);
  3119. }
  3120. static void run_delayed_iput_locked(struct btrfs_fs_info *fs_info,
  3121. struct btrfs_inode *inode)
  3122. {
  3123. list_del_init(&inode->delayed_iput);
  3124. spin_unlock_irq(&fs_info->delayed_iput_lock);
  3125. iput(&inode->vfs_inode);
  3126. if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
  3127. wake_up(&fs_info->delayed_iputs_wait);
  3128. spin_lock_irq(&fs_info->delayed_iput_lock);
  3129. }
  3130. static void btrfs_run_delayed_iput(struct btrfs_fs_info *fs_info,
  3131. struct btrfs_inode *inode)
  3132. {
  3133. if (!list_empty(&inode->delayed_iput)) {
  3134. spin_lock_irq(&fs_info->delayed_iput_lock);
  3135. if (!list_empty(&inode->delayed_iput))
  3136. run_delayed_iput_locked(fs_info, inode);
  3137. spin_unlock_irq(&fs_info->delayed_iput_lock);
  3138. }
  3139. }
  3140. void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
  3141. {
  3142. /*
  3143. * btrfs_put_ordered_extent() can run in irq context (see bio.c), which
  3144. * calls btrfs_add_delayed_iput() and that needs to lock
  3145. * fs_info->delayed_iput_lock. So we need to disable irqs here to
  3146. * prevent a deadlock.
  3147. */
  3148. spin_lock_irq(&fs_info->delayed_iput_lock);
  3149. while (!list_empty(&fs_info->delayed_iputs)) {
  3150. struct btrfs_inode *inode;
  3151. inode = list_first_entry(&fs_info->delayed_iputs,
  3152. struct btrfs_inode, delayed_iput);
  3153. run_delayed_iput_locked(fs_info, inode);
  3154. if (need_resched()) {
  3155. spin_unlock_irq(&fs_info->delayed_iput_lock);
  3156. cond_resched();
  3157. spin_lock_irq(&fs_info->delayed_iput_lock);
  3158. }
  3159. }
  3160. spin_unlock_irq(&fs_info->delayed_iput_lock);
  3161. }
  3162. /*
  3163. * Wait for flushing all delayed iputs
  3164. *
  3165. * @fs_info: the filesystem
  3166. *
  3167. * This will wait on any delayed iputs that are currently running with KILLABLE
  3168. * set. Once they are all done running we will return, unless we are killed in
  3169. * which case we return EINTR. This helps in user operations like fallocate etc
  3170. * that might get blocked on the iputs.
  3171. *
  3172. * Return EINTR if we were killed, 0 if nothing's pending
  3173. */
  3174. int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
  3175. {
  3176. int ret = wait_event_killable(fs_info->delayed_iputs_wait,
  3177. atomic_read(&fs_info->nr_delayed_iputs) == 0);
  3178. if (ret)
  3179. return -EINTR;
  3180. return 0;
  3181. }
  3182. /*
  3183. * This creates an orphan entry for the given inode in case something goes wrong
  3184. * in the middle of an unlink.
  3185. */
  3186. int btrfs_orphan_add(struct btrfs_trans_handle *trans,
  3187. struct btrfs_inode *inode)
  3188. {
  3189. int ret;
  3190. ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
  3191. if (ret && ret != -EEXIST) {
  3192. btrfs_abort_transaction(trans, ret);
  3193. return ret;
  3194. }
  3195. return 0;
  3196. }
  3197. /*
  3198. * We have done the delete so we can go ahead and remove the orphan item for
  3199. * this particular inode.
  3200. */
  3201. static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
  3202. struct btrfs_inode *inode)
  3203. {
  3204. return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
  3205. }
  3206. /*
  3207. * this cleans up any orphans that may be left on the list from the last use
  3208. * of this root.
  3209. */
  3210. int btrfs_orphan_cleanup(struct btrfs_root *root)
  3211. {
  3212. struct btrfs_fs_info *fs_info = root->fs_info;
  3213. struct btrfs_path *path;
  3214. struct extent_buffer *leaf;
  3215. struct btrfs_key key, found_key;
  3216. struct btrfs_trans_handle *trans;
  3217. struct inode *inode;
  3218. u64 last_objectid = 0;
  3219. int ret = 0, nr_unlink = 0;
  3220. if (test_and_set_bit(BTRFS_ROOT_ORPHAN_CLEANUP, &root->state))
  3221. return 0;
  3222. path = btrfs_alloc_path();
  3223. if (!path) {
  3224. ret = -ENOMEM;
  3225. goto out;
  3226. }
  3227. path->reada = READA_BACK;
  3228. key.objectid = BTRFS_ORPHAN_OBJECTID;
  3229. key.type = BTRFS_ORPHAN_ITEM_KEY;
  3230. key.offset = (u64)-1;
  3231. while (1) {
  3232. ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
  3233. if (ret < 0)
  3234. goto out;
  3235. /*
  3236. * if ret == 0 means we found what we were searching for, which
  3237. * is weird, but possible, so only screw with path if we didn't
  3238. * find the key and see if we have stuff that matches
  3239. */
  3240. if (ret > 0) {
  3241. ret = 0;
  3242. if (path->slots[0] == 0)
  3243. break;
  3244. path->slots[0]--;
  3245. }
  3246. /* pull out the item */
  3247. leaf = path->nodes[0];
  3248. btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
  3249. /* make sure the item matches what we want */
  3250. if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
  3251. break;
  3252. if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
  3253. break;
  3254. /* release the path since we're done with it */
  3255. btrfs_release_path(path);
  3256. /*
  3257. * this is where we are basically btrfs_lookup, without the
  3258. * crossing root thing. we store the inode number in the
  3259. * offset of the orphan item.
  3260. */
  3261. if (found_key.offset == last_objectid) {
  3262. /*
  3263. * We found the same inode as before. This means we were
  3264. * not able to remove its items via eviction triggered
  3265. * by an iput(). A transaction abort may have happened,
  3266. * due to -ENOSPC for example, so try to grab the error
  3267. * that lead to a transaction abort, if any.
  3268. */
  3269. btrfs_err(fs_info,
  3270. "Error removing orphan entry, stopping orphan cleanup");
  3271. ret = BTRFS_FS_ERROR(fs_info) ?: -EINVAL;
  3272. goto out;
  3273. }
  3274. last_objectid = found_key.offset;
  3275. found_key.objectid = found_key.offset;
  3276. found_key.type = BTRFS_INODE_ITEM_KEY;
  3277. found_key.offset = 0;
  3278. inode = btrfs_iget(last_objectid, root);
  3279. if (IS_ERR(inode)) {
  3280. ret = PTR_ERR(inode);
  3281. inode = NULL;
  3282. if (ret != -ENOENT)
  3283. goto out;
  3284. }
  3285. if (!inode && root == fs_info->tree_root) {
  3286. struct btrfs_root *dead_root;
  3287. int is_dead_root = 0;
  3288. /*
  3289. * This is an orphan in the tree root. Currently these
  3290. * could come from 2 sources:
  3291. * a) a root (snapshot/subvolume) deletion in progress
  3292. * b) a free space cache inode
  3293. * We need to distinguish those two, as the orphan item
  3294. * for a root must not get deleted before the deletion
  3295. * of the snapshot/subvolume's tree completes.
  3296. *
  3297. * btrfs_find_orphan_roots() ran before us, which has
  3298. * found all deleted roots and loaded them into
  3299. * fs_info->fs_roots_radix. So here we can find if an
  3300. * orphan item corresponds to a deleted root by looking
  3301. * up the root from that radix tree.
  3302. */
  3303. spin_lock(&fs_info->fs_roots_radix_lock);
  3304. dead_root = radix_tree_lookup(&fs_info->fs_roots_radix,
  3305. (unsigned long)found_key.objectid);
  3306. if (dead_root && btrfs_root_refs(&dead_root->root_item) == 0)
  3307. is_dead_root = 1;
  3308. spin_unlock(&fs_info->fs_roots_radix_lock);
  3309. if (is_dead_root) {
  3310. /* prevent this orphan from being found again */
  3311. key.offset = found_key.objectid - 1;
  3312. continue;
  3313. }
  3314. }
  3315. /*
  3316. * If we have an inode with links, there are a couple of
  3317. * possibilities:
  3318. *
  3319. * 1. We were halfway through creating fsverity metadata for the
  3320. * file. In that case, the orphan item represents incomplete
  3321. * fsverity metadata which must be cleaned up with
  3322. * btrfs_drop_verity_items and deleting the orphan item.
  3323. * 2. Old kernels (before v3.12) used to create an
  3324. * orphan item for truncate indicating that there were possibly
  3325. * extent items past i_size that needed to be deleted. In v3.12,
  3326. * truncate was changed to update i_size in sync with the extent
  3327. * items, but the (useless) orphan item was still created. Since
  3328. * v4.18, we don't create the orphan item for truncate at all.
  3329. *
  3330. * So, this item could mean that we need to do a truncate, but
  3331. * only if this filesystem was last used on a pre-v3.12 kernel
  3332. * and was not cleanly unmounted. The odds of that are quite
  3333. * slim, and it's a pain to do the truncate now, so just delete
  3334. * the orphan item.
  3335. *
  3336. * It's also possible that this orphan item was supposed to be
  3337. * deleted but wasn't. The inode number may have been reused,
  3338. * but either way, we can delete the orphan item.
  3339. */
  3340. if (!inode || inode->i_nlink) {
  3341. if (inode) {
  3342. ret = btrfs_drop_verity_items(BTRFS_I(inode));
  3343. iput(inode);
  3344. inode = NULL;
  3345. if (ret)
  3346. goto out;
  3347. }
  3348. trans = btrfs_start_transaction(root, 1);
  3349. if (IS_ERR(trans)) {
  3350. ret = PTR_ERR(trans);
  3351. goto out;
  3352. }
  3353. btrfs_debug(fs_info, "auto deleting %Lu",
  3354. found_key.objectid);
  3355. ret = btrfs_del_orphan_item(trans, root,
  3356. found_key.objectid);
  3357. btrfs_end_transaction(trans);
  3358. if (ret)
  3359. goto out;
  3360. continue;
  3361. }
  3362. nr_unlink++;
  3363. /* this will do delete_inode and everything for us */
  3364. iput(inode);
  3365. }
  3366. /* release the path since we're done with it */
  3367. btrfs_release_path(path);
  3368. if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
  3369. trans = btrfs_join_transaction(root);
  3370. if (!IS_ERR(trans))
  3371. btrfs_end_transaction(trans);
  3372. }
  3373. if (nr_unlink)
  3374. btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
  3375. out:
  3376. if (ret)
  3377. btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
  3378. btrfs_free_path(path);
  3379. return ret;
  3380. }
  3381. /*
  3382. * very simple check to peek ahead in the leaf looking for xattrs. If we
  3383. * don't find any xattrs, we know there can't be any acls.
  3384. *
  3385. * slot is the slot the inode is in, objectid is the objectid of the inode
  3386. */
  3387. static noinline int acls_after_inode_item(struct extent_buffer *leaf,
  3388. int slot, u64 objectid,
  3389. int *first_xattr_slot)
  3390. {
  3391. u32 nritems = btrfs_header_nritems(leaf);
  3392. struct btrfs_key found_key;
  3393. static u64 xattr_access = 0;
  3394. static u64 xattr_default = 0;
  3395. int scanned = 0;
  3396. if (!xattr_access) {
  3397. xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
  3398. strlen(XATTR_NAME_POSIX_ACL_ACCESS));
  3399. xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
  3400. strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
  3401. }
  3402. slot++;
  3403. *first_xattr_slot = -1;
  3404. while (slot < nritems) {
  3405. btrfs_item_key_to_cpu(leaf, &found_key, slot);
  3406. /* we found a different objectid, there must not be acls */
  3407. if (found_key.objectid != objectid)
  3408. return 0;
  3409. /* we found an xattr, assume we've got an acl */
  3410. if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
  3411. if (*first_xattr_slot == -1)
  3412. *first_xattr_slot = slot;
  3413. if (found_key.offset == xattr_access ||
  3414. found_key.offset == xattr_default)
  3415. return 1;
  3416. }
  3417. /*
  3418. * we found a key greater than an xattr key, there can't
  3419. * be any acls later on
  3420. */
  3421. if (found_key.type > BTRFS_XATTR_ITEM_KEY)
  3422. return 0;
  3423. slot++;
  3424. scanned++;
  3425. /*
  3426. * it goes inode, inode backrefs, xattrs, extents,
  3427. * so if there are a ton of hard links to an inode there can
  3428. * be a lot of backrefs. Don't waste time searching too hard,
  3429. * this is just an optimization
  3430. */
  3431. if (scanned >= 8)
  3432. break;
  3433. }
  3434. /* we hit the end of the leaf before we found an xattr or
  3435. * something larger than an xattr. We have to assume the inode
  3436. * has acls
  3437. */
  3438. if (*first_xattr_slot == -1)
  3439. *first_xattr_slot = slot;
  3440. return 1;
  3441. }
  3442. static int btrfs_init_file_extent_tree(struct btrfs_inode *inode)
  3443. {
  3444. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  3445. if (WARN_ON_ONCE(inode->file_extent_tree))
  3446. return 0;
  3447. if (btrfs_fs_incompat(fs_info, NO_HOLES))
  3448. return 0;
  3449. if (!S_ISREG(inode->vfs_inode.i_mode))
  3450. return 0;
  3451. if (btrfs_is_free_space_inode(inode))
  3452. return 0;
  3453. inode->file_extent_tree = kmalloc(sizeof(struct extent_io_tree), GFP_KERNEL);
  3454. if (!inode->file_extent_tree)
  3455. return -ENOMEM;
  3456. extent_io_tree_init(fs_info, inode->file_extent_tree, IO_TREE_INODE_FILE_EXTENT);
  3457. /* Lockdep class is set only for the file extent tree. */
  3458. lockdep_set_class(&inode->file_extent_tree->lock, &file_extent_tree_class);
  3459. return 0;
  3460. }
  3461. /*
  3462. * read an inode from the btree into the in-memory inode
  3463. */
  3464. static int btrfs_read_locked_inode(struct inode *inode,
  3465. struct btrfs_path *in_path)
  3466. {
  3467. struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
  3468. struct btrfs_path *path = in_path;
  3469. struct extent_buffer *leaf;
  3470. struct btrfs_inode_item *inode_item;
  3471. struct btrfs_root *root = BTRFS_I(inode)->root;
  3472. struct btrfs_key location;
  3473. unsigned long ptr;
  3474. int maybe_acls;
  3475. u32 rdev;
  3476. int ret;
  3477. bool filled = false;
  3478. int first_xattr_slot;
  3479. ret = btrfs_init_file_extent_tree(BTRFS_I(inode));
  3480. if (ret)
  3481. return ret;
  3482. ret = btrfs_fill_inode(inode, &rdev);
  3483. if (!ret)
  3484. filled = true;
  3485. if (!path) {
  3486. path = btrfs_alloc_path();
  3487. if (!path)
  3488. return -ENOMEM;
  3489. }
  3490. btrfs_get_inode_key(BTRFS_I(inode), &location);
  3491. ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
  3492. if (ret) {
  3493. if (path != in_path)
  3494. btrfs_free_path(path);
  3495. return ret;
  3496. }
  3497. leaf = path->nodes[0];
  3498. if (filled)
  3499. goto cache_index;
  3500. inode_item = btrfs_item_ptr(leaf, path->slots[0],
  3501. struct btrfs_inode_item);
  3502. inode->i_mode = btrfs_inode_mode(leaf, inode_item);
  3503. set_nlink(inode, btrfs_inode_nlink(leaf, inode_item));
  3504. i_uid_write(inode, btrfs_inode_uid(leaf, inode_item));
  3505. i_gid_write(inode, btrfs_inode_gid(leaf, inode_item));
  3506. btrfs_i_size_write(BTRFS_I(inode), btrfs_inode_size(leaf, inode_item));
  3507. btrfs_inode_set_file_extent_range(BTRFS_I(inode), 0,
  3508. round_up(i_size_read(inode), fs_info->sectorsize));
  3509. inode_set_atime(inode, btrfs_timespec_sec(leaf, &inode_item->atime),
  3510. btrfs_timespec_nsec(leaf, &inode_item->atime));
  3511. inode_set_mtime(inode, btrfs_timespec_sec(leaf, &inode_item->mtime),
  3512. btrfs_timespec_nsec(leaf, &inode_item->mtime));
  3513. inode_set_ctime(inode, btrfs_timespec_sec(leaf, &inode_item->ctime),
  3514. btrfs_timespec_nsec(leaf, &inode_item->ctime));
  3515. BTRFS_I(inode)->i_otime_sec = btrfs_timespec_sec(leaf, &inode_item->otime);
  3516. BTRFS_I(inode)->i_otime_nsec = btrfs_timespec_nsec(leaf, &inode_item->otime);
  3517. inode_set_bytes(inode, btrfs_inode_nbytes(leaf, inode_item));
  3518. BTRFS_I(inode)->generation = btrfs_inode_generation(leaf, inode_item);
  3519. BTRFS_I(inode)->last_trans = btrfs_inode_transid(leaf, inode_item);
  3520. inode_set_iversion_queried(inode,
  3521. btrfs_inode_sequence(leaf, inode_item));
  3522. inode->i_generation = BTRFS_I(inode)->generation;
  3523. inode->i_rdev = 0;
  3524. rdev = btrfs_inode_rdev(leaf, inode_item);
  3525. if (S_ISDIR(inode->i_mode))
  3526. BTRFS_I(inode)->index_cnt = (u64)-1;
  3527. btrfs_inode_split_flags(btrfs_inode_flags(leaf, inode_item),
  3528. &BTRFS_I(inode)->flags, &BTRFS_I(inode)->ro_flags);
  3529. cache_index:
  3530. /*
  3531. * If we were modified in the current generation and evicted from memory
  3532. * and then re-read we need to do a full sync since we don't have any
  3533. * idea about which extents were modified before we were evicted from
  3534. * cache.
  3535. *
  3536. * This is required for both inode re-read from disk and delayed inode
  3537. * in the delayed_nodes xarray.
  3538. */
  3539. if (BTRFS_I(inode)->last_trans == btrfs_get_fs_generation(fs_info))
  3540. set_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
  3541. &BTRFS_I(inode)->runtime_flags);
  3542. /*
  3543. * We don't persist the id of the transaction where an unlink operation
  3544. * against the inode was last made. So here we assume the inode might
  3545. * have been evicted, and therefore the exact value of last_unlink_trans
  3546. * lost, and set it to last_trans to avoid metadata inconsistencies
  3547. * between the inode and its parent if the inode is fsync'ed and the log
  3548. * replayed. For example, in the scenario:
  3549. *
  3550. * touch mydir/foo
  3551. * ln mydir/foo mydir/bar
  3552. * sync
  3553. * unlink mydir/bar
  3554. * echo 2 > /proc/sys/vm/drop_caches # evicts inode
  3555. * xfs_io -c fsync mydir/foo
  3556. * <power failure>
  3557. * mount fs, triggers fsync log replay
  3558. *
  3559. * We must make sure that when we fsync our inode foo we also log its
  3560. * parent inode, otherwise after log replay the parent still has the
  3561. * dentry with the "bar" name but our inode foo has a link count of 1
  3562. * and doesn't have an inode ref with the name "bar" anymore.
  3563. *
  3564. * Setting last_unlink_trans to last_trans is a pessimistic approach,
  3565. * but it guarantees correctness at the expense of occasional full
  3566. * transaction commits on fsync if our inode is a directory, or if our
  3567. * inode is not a directory, logging its parent unnecessarily.
  3568. */
  3569. BTRFS_I(inode)->last_unlink_trans = BTRFS_I(inode)->last_trans;
  3570. /*
  3571. * Same logic as for last_unlink_trans. We don't persist the generation
  3572. * of the last transaction where this inode was used for a reflink
  3573. * operation, so after eviction and reloading the inode we must be
  3574. * pessimistic and assume the last transaction that modified the inode.
  3575. */
  3576. BTRFS_I(inode)->last_reflink_trans = BTRFS_I(inode)->last_trans;
  3577. path->slots[0]++;
  3578. if (inode->i_nlink != 1 ||
  3579. path->slots[0] >= btrfs_header_nritems(leaf))
  3580. goto cache_acl;
  3581. btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
  3582. if (location.objectid != btrfs_ino(BTRFS_I(inode)))
  3583. goto cache_acl;
  3584. ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
  3585. if (location.type == BTRFS_INODE_REF_KEY) {
  3586. struct btrfs_inode_ref *ref;
  3587. ref = (struct btrfs_inode_ref *)ptr;
  3588. BTRFS_I(inode)->dir_index = btrfs_inode_ref_index(leaf, ref);
  3589. } else if (location.type == BTRFS_INODE_EXTREF_KEY) {
  3590. struct btrfs_inode_extref *extref;
  3591. extref = (struct btrfs_inode_extref *)ptr;
  3592. BTRFS_I(inode)->dir_index = btrfs_inode_extref_index(leaf,
  3593. extref);
  3594. }
  3595. cache_acl:
  3596. /*
  3597. * try to precache a NULL acl entry for files that don't have
  3598. * any xattrs or acls
  3599. */
  3600. maybe_acls = acls_after_inode_item(leaf, path->slots[0],
  3601. btrfs_ino(BTRFS_I(inode)), &first_xattr_slot);
  3602. if (first_xattr_slot != -1) {
  3603. path->slots[0] = first_xattr_slot;
  3604. ret = btrfs_load_inode_props(inode, path);
  3605. if (ret)
  3606. btrfs_err(fs_info,
  3607. "error loading props for ino %llu (root %llu): %d",
  3608. btrfs_ino(BTRFS_I(inode)),
  3609. btrfs_root_id(root), ret);
  3610. }
  3611. if (path != in_path)
  3612. btrfs_free_path(path);
  3613. if (!maybe_acls)
  3614. cache_no_acl(inode);
  3615. switch (inode->i_mode & S_IFMT) {
  3616. case S_IFREG:
  3617. inode->i_mapping->a_ops = &btrfs_aops;
  3618. inode->i_fop = &btrfs_file_operations;
  3619. inode->i_op = &btrfs_file_inode_operations;
  3620. break;
  3621. case S_IFDIR:
  3622. inode->i_fop = &btrfs_dir_file_operations;
  3623. inode->i_op = &btrfs_dir_inode_operations;
  3624. break;
  3625. case S_IFLNK:
  3626. inode->i_op = &btrfs_symlink_inode_operations;
  3627. inode_nohighmem(inode);
  3628. inode->i_mapping->a_ops = &btrfs_aops;
  3629. break;
  3630. default:
  3631. inode->i_op = &btrfs_special_inode_operations;
  3632. init_special_inode(inode, inode->i_mode, rdev);
  3633. break;
  3634. }
  3635. btrfs_sync_inode_flags_to_i_flags(inode);
  3636. return 0;
  3637. }
  3638. /*
  3639. * given a leaf and an inode, copy the inode fields into the leaf
  3640. */
  3641. static void fill_inode_item(struct btrfs_trans_handle *trans,
  3642. struct extent_buffer *leaf,
  3643. struct btrfs_inode_item *item,
  3644. struct inode *inode)
  3645. {
  3646. struct btrfs_map_token token;
  3647. u64 flags;
  3648. btrfs_init_map_token(&token, leaf);
  3649. btrfs_set_token_inode_uid(&token, item, i_uid_read(inode));
  3650. btrfs_set_token_inode_gid(&token, item, i_gid_read(inode));
  3651. btrfs_set_token_inode_size(&token, item, BTRFS_I(inode)->disk_i_size);
  3652. btrfs_set_token_inode_mode(&token, item, inode->i_mode);
  3653. btrfs_set_token_inode_nlink(&token, item, inode->i_nlink);
  3654. btrfs_set_token_timespec_sec(&token, &item->atime,
  3655. inode_get_atime_sec(inode));
  3656. btrfs_set_token_timespec_nsec(&token, &item->atime,
  3657. inode_get_atime_nsec(inode));
  3658. btrfs_set_token_timespec_sec(&token, &item->mtime,
  3659. inode_get_mtime_sec(inode));
  3660. btrfs_set_token_timespec_nsec(&token, &item->mtime,
  3661. inode_get_mtime_nsec(inode));
  3662. btrfs_set_token_timespec_sec(&token, &item->ctime,
  3663. inode_get_ctime_sec(inode));
  3664. btrfs_set_token_timespec_nsec(&token, &item->ctime,
  3665. inode_get_ctime_nsec(inode));
  3666. btrfs_set_token_timespec_sec(&token, &item->otime, BTRFS_I(inode)->i_otime_sec);
  3667. btrfs_set_token_timespec_nsec(&token, &item->otime, BTRFS_I(inode)->i_otime_nsec);
  3668. btrfs_set_token_inode_nbytes(&token, item, inode_get_bytes(inode));
  3669. btrfs_set_token_inode_generation(&token, item,
  3670. BTRFS_I(inode)->generation);
  3671. btrfs_set_token_inode_sequence(&token, item, inode_peek_iversion(inode));
  3672. btrfs_set_token_inode_transid(&token, item, trans->transid);
  3673. btrfs_set_token_inode_rdev(&token, item, inode->i_rdev);
  3674. flags = btrfs_inode_combine_flags(BTRFS_I(inode)->flags,
  3675. BTRFS_I(inode)->ro_flags);
  3676. btrfs_set_token_inode_flags(&token, item, flags);
  3677. btrfs_set_token_inode_block_group(&token, item, 0);
  3678. }
  3679. /*
  3680. * copy everything in the in-memory inode into the btree.
  3681. */
  3682. static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
  3683. struct btrfs_inode *inode)
  3684. {
  3685. struct btrfs_inode_item *inode_item;
  3686. struct btrfs_path *path;
  3687. struct extent_buffer *leaf;
  3688. struct btrfs_key key;
  3689. int ret;
  3690. path = btrfs_alloc_path();
  3691. if (!path)
  3692. return -ENOMEM;
  3693. btrfs_get_inode_key(inode, &key);
  3694. ret = btrfs_lookup_inode(trans, inode->root, path, &key, 1);
  3695. if (ret) {
  3696. if (ret > 0)
  3697. ret = -ENOENT;
  3698. goto failed;
  3699. }
  3700. leaf = path->nodes[0];
  3701. inode_item = btrfs_item_ptr(leaf, path->slots[0],
  3702. struct btrfs_inode_item);
  3703. fill_inode_item(trans, leaf, inode_item, &inode->vfs_inode);
  3704. btrfs_mark_buffer_dirty(trans, leaf);
  3705. btrfs_set_inode_last_trans(trans, inode);
  3706. ret = 0;
  3707. failed:
  3708. btrfs_free_path(path);
  3709. return ret;
  3710. }
  3711. /*
  3712. * copy everything in the in-memory inode into the btree.
  3713. */
  3714. int btrfs_update_inode(struct btrfs_trans_handle *trans,
  3715. struct btrfs_inode *inode)
  3716. {
  3717. struct btrfs_root *root = inode->root;
  3718. struct btrfs_fs_info *fs_info = root->fs_info;
  3719. int ret;
  3720. /*
  3721. * If the inode is a free space inode, we can deadlock during commit
  3722. * if we put it into the delayed code.
  3723. *
  3724. * The data relocation inode should also be directly updated
  3725. * without delay
  3726. */
  3727. if (!btrfs_is_free_space_inode(inode)
  3728. && !btrfs_is_data_reloc_root(root)
  3729. && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
  3730. btrfs_update_root_times(trans, root);
  3731. ret = btrfs_delayed_update_inode(trans, inode);
  3732. if (!ret)
  3733. btrfs_set_inode_last_trans(trans, inode);
  3734. return ret;
  3735. }
  3736. return btrfs_update_inode_item(trans, inode);
  3737. }
  3738. int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
  3739. struct btrfs_inode *inode)
  3740. {
  3741. int ret;
  3742. ret = btrfs_update_inode(trans, inode);
  3743. if (ret == -ENOSPC)
  3744. return btrfs_update_inode_item(trans, inode);
  3745. return ret;
  3746. }
  3747. /*
  3748. * unlink helper that gets used here in inode.c and in the tree logging
  3749. * recovery code. It remove a link in a directory with a given name, and
  3750. * also drops the back refs in the inode to the directory
  3751. */
  3752. static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
  3753. struct btrfs_inode *dir,
  3754. struct btrfs_inode *inode,
  3755. const struct fscrypt_str *name,
  3756. struct btrfs_rename_ctx *rename_ctx)
  3757. {
  3758. struct btrfs_root *root = dir->root;
  3759. struct btrfs_fs_info *fs_info = root->fs_info;
  3760. struct btrfs_path *path;
  3761. int ret = 0;
  3762. struct btrfs_dir_item *di;
  3763. u64 index;
  3764. u64 ino = btrfs_ino(inode);
  3765. u64 dir_ino = btrfs_ino(dir);
  3766. path = btrfs_alloc_path();
  3767. if (!path) {
  3768. ret = -ENOMEM;
  3769. goto out;
  3770. }
  3771. di = btrfs_lookup_dir_item(trans, root, path, dir_ino, name, -1);
  3772. if (IS_ERR_OR_NULL(di)) {
  3773. ret = di ? PTR_ERR(di) : -ENOENT;
  3774. goto err;
  3775. }
  3776. ret = btrfs_delete_one_dir_name(trans, root, path, di);
  3777. if (ret)
  3778. goto err;
  3779. btrfs_release_path(path);
  3780. /*
  3781. * If we don't have dir index, we have to get it by looking up
  3782. * the inode ref, since we get the inode ref, remove it directly,
  3783. * it is unnecessary to do delayed deletion.
  3784. *
  3785. * But if we have dir index, needn't search inode ref to get it.
  3786. * Since the inode ref is close to the inode item, it is better
  3787. * that we delay to delete it, and just do this deletion when
  3788. * we update the inode item.
  3789. */
  3790. if (inode->dir_index) {
  3791. ret = btrfs_delayed_delete_inode_ref(inode);
  3792. if (!ret) {
  3793. index = inode->dir_index;
  3794. goto skip_backref;
  3795. }
  3796. }
  3797. ret = btrfs_del_inode_ref(trans, root, name, ino, dir_ino, &index);
  3798. if (ret) {
  3799. btrfs_info(fs_info,
  3800. "failed to delete reference to %.*s, inode %llu parent %llu",
  3801. name->len, name->name, ino, dir_ino);
  3802. btrfs_abort_transaction(trans, ret);
  3803. goto err;
  3804. }
  3805. skip_backref:
  3806. if (rename_ctx)
  3807. rename_ctx->index = index;
  3808. ret = btrfs_delete_delayed_dir_index(trans, dir, index);
  3809. if (ret) {
  3810. btrfs_abort_transaction(trans, ret);
  3811. goto err;
  3812. }
  3813. /*
  3814. * If we are in a rename context, we don't need to update anything in the
  3815. * log. That will be done later during the rename by btrfs_log_new_name().
  3816. * Besides that, doing it here would only cause extra unnecessary btree
  3817. * operations on the log tree, increasing latency for applications.
  3818. */
  3819. if (!rename_ctx) {
  3820. btrfs_del_inode_ref_in_log(trans, root, name, inode, dir_ino);
  3821. btrfs_del_dir_entries_in_log(trans, root, name, dir, index);
  3822. }
  3823. /*
  3824. * If we have a pending delayed iput we could end up with the final iput
  3825. * being run in btrfs-cleaner context. If we have enough of these built
  3826. * up we can end up burning a lot of time in btrfs-cleaner without any
  3827. * way to throttle the unlinks. Since we're currently holding a ref on
  3828. * the inode we can run the delayed iput here without any issues as the
  3829. * final iput won't be done until after we drop the ref we're currently
  3830. * holding.
  3831. */
  3832. btrfs_run_delayed_iput(fs_info, inode);
  3833. err:
  3834. btrfs_free_path(path);
  3835. if (ret)
  3836. goto out;
  3837. btrfs_i_size_write(dir, dir->vfs_inode.i_size - name->len * 2);
  3838. inode_inc_iversion(&inode->vfs_inode);
  3839. inode_set_ctime_current(&inode->vfs_inode);
  3840. inode_inc_iversion(&dir->vfs_inode);
  3841. inode_set_mtime_to_ts(&dir->vfs_inode, inode_set_ctime_current(&dir->vfs_inode));
  3842. ret = btrfs_update_inode(trans, dir);
  3843. out:
  3844. return ret;
  3845. }
  3846. int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
  3847. struct btrfs_inode *dir, struct btrfs_inode *inode,
  3848. const struct fscrypt_str *name)
  3849. {
  3850. int ret;
  3851. ret = __btrfs_unlink_inode(trans, dir, inode, name, NULL);
  3852. if (!ret) {
  3853. drop_nlink(&inode->vfs_inode);
  3854. ret = btrfs_update_inode(trans, inode);
  3855. }
  3856. return ret;
  3857. }
  3858. /*
  3859. * helper to start transaction for unlink and rmdir.
  3860. *
  3861. * unlink and rmdir are special in btrfs, they do not always free space, so
  3862. * if we cannot make our reservations the normal way try and see if there is
  3863. * plenty of slack room in the global reserve to migrate, otherwise we cannot
  3864. * allow the unlink to occur.
  3865. */
  3866. static struct btrfs_trans_handle *__unlink_start_trans(struct btrfs_inode *dir)
  3867. {
  3868. struct btrfs_root *root = dir->root;
  3869. return btrfs_start_transaction_fallback_global_rsv(root,
  3870. BTRFS_UNLINK_METADATA_UNITS);
  3871. }
  3872. static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
  3873. {
  3874. struct btrfs_trans_handle *trans;
  3875. struct inode *inode = d_inode(dentry);
  3876. int ret;
  3877. struct fscrypt_name fname;
  3878. ret = fscrypt_setup_filename(dir, &dentry->d_name, 1, &fname);
  3879. if (ret)
  3880. return ret;
  3881. /* This needs to handle no-key deletions later on */
  3882. trans = __unlink_start_trans(BTRFS_I(dir));
  3883. if (IS_ERR(trans)) {
  3884. ret = PTR_ERR(trans);
  3885. goto fscrypt_free;
  3886. }
  3887. btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
  3888. false);
  3889. ret = btrfs_unlink_inode(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
  3890. &fname.disk_name);
  3891. if (ret)
  3892. goto end_trans;
  3893. if (inode->i_nlink == 0) {
  3894. ret = btrfs_orphan_add(trans, BTRFS_I(inode));
  3895. if (ret)
  3896. goto end_trans;
  3897. }
  3898. end_trans:
  3899. btrfs_end_transaction(trans);
  3900. btrfs_btree_balance_dirty(BTRFS_I(dir)->root->fs_info);
  3901. fscrypt_free:
  3902. fscrypt_free_filename(&fname);
  3903. return ret;
  3904. }
  3905. static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
  3906. struct btrfs_inode *dir, struct dentry *dentry)
  3907. {
  3908. struct btrfs_root *root = dir->root;
  3909. struct btrfs_inode *inode = BTRFS_I(d_inode(dentry));
  3910. struct btrfs_path *path;
  3911. struct extent_buffer *leaf;
  3912. struct btrfs_dir_item *di;
  3913. struct btrfs_key key;
  3914. u64 index;
  3915. int ret;
  3916. u64 objectid;
  3917. u64 dir_ino = btrfs_ino(dir);
  3918. struct fscrypt_name fname;
  3919. ret = fscrypt_setup_filename(&dir->vfs_inode, &dentry->d_name, 1, &fname);
  3920. if (ret)
  3921. return ret;
  3922. /* This needs to handle no-key deletions later on */
  3923. if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) {
  3924. objectid = btrfs_root_id(inode->root);
  3925. } else if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
  3926. objectid = inode->ref_root_id;
  3927. } else {
  3928. WARN_ON(1);
  3929. fscrypt_free_filename(&fname);
  3930. return -EINVAL;
  3931. }
  3932. path = btrfs_alloc_path();
  3933. if (!path) {
  3934. ret = -ENOMEM;
  3935. goto out;
  3936. }
  3937. di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
  3938. &fname.disk_name, -1);
  3939. if (IS_ERR_OR_NULL(di)) {
  3940. ret = di ? PTR_ERR(di) : -ENOENT;
  3941. goto out;
  3942. }
  3943. leaf = path->nodes[0];
  3944. btrfs_dir_item_key_to_cpu(leaf, di, &key);
  3945. WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
  3946. ret = btrfs_delete_one_dir_name(trans, root, path, di);
  3947. if (ret) {
  3948. btrfs_abort_transaction(trans, ret);
  3949. goto out;
  3950. }
  3951. btrfs_release_path(path);
  3952. /*
  3953. * This is a placeholder inode for a subvolume we didn't have a
  3954. * reference to at the time of the snapshot creation. In the meantime
  3955. * we could have renamed the real subvol link into our snapshot, so
  3956. * depending on btrfs_del_root_ref to return -ENOENT here is incorrect.
  3957. * Instead simply lookup the dir_index_item for this entry so we can
  3958. * remove it. Otherwise we know we have a ref to the root and we can
  3959. * call btrfs_del_root_ref, and it _shouldn't_ fail.
  3960. */
  3961. if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
  3962. di = btrfs_search_dir_index_item(root, path, dir_ino, &fname.disk_name);
  3963. if (IS_ERR(di)) {
  3964. ret = PTR_ERR(di);
  3965. btrfs_abort_transaction(trans, ret);
  3966. goto out;
  3967. }
  3968. leaf = path->nodes[0];
  3969. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  3970. index = key.offset;
  3971. btrfs_release_path(path);
  3972. } else {
  3973. ret = btrfs_del_root_ref(trans, objectid,
  3974. btrfs_root_id(root), dir_ino,
  3975. &index, &fname.disk_name);
  3976. if (ret) {
  3977. btrfs_abort_transaction(trans, ret);
  3978. goto out;
  3979. }
  3980. }
  3981. ret = btrfs_delete_delayed_dir_index(trans, dir, index);
  3982. if (ret) {
  3983. btrfs_abort_transaction(trans, ret);
  3984. goto out;
  3985. }
  3986. btrfs_i_size_write(dir, dir->vfs_inode.i_size - fname.disk_name.len * 2);
  3987. inode_inc_iversion(&dir->vfs_inode);
  3988. inode_set_mtime_to_ts(&dir->vfs_inode, inode_set_ctime_current(&dir->vfs_inode));
  3989. ret = btrfs_update_inode_fallback(trans, dir);
  3990. if (ret)
  3991. btrfs_abort_transaction(trans, ret);
  3992. out:
  3993. btrfs_free_path(path);
  3994. fscrypt_free_filename(&fname);
  3995. return ret;
  3996. }
  3997. /*
  3998. * Helper to check if the subvolume references other subvolumes or if it's
  3999. * default.
  4000. */
  4001. static noinline int may_destroy_subvol(struct btrfs_root *root)
  4002. {
  4003. struct btrfs_fs_info *fs_info = root->fs_info;
  4004. struct btrfs_path *path;
  4005. struct btrfs_dir_item *di;
  4006. struct btrfs_key key;
  4007. struct fscrypt_str name = FSTR_INIT("default", 7);
  4008. u64 dir_id;
  4009. int ret;
  4010. path = btrfs_alloc_path();
  4011. if (!path)
  4012. return -ENOMEM;
  4013. /* Make sure this root isn't set as the default subvol */
  4014. dir_id = btrfs_super_root_dir(fs_info->super_copy);
  4015. di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
  4016. dir_id, &name, 0);
  4017. if (di && !IS_ERR(di)) {
  4018. btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
  4019. if (key.objectid == btrfs_root_id(root)) {
  4020. ret = -EPERM;
  4021. btrfs_err(fs_info,
  4022. "deleting default subvolume %llu is not allowed",
  4023. key.objectid);
  4024. goto out;
  4025. }
  4026. btrfs_release_path(path);
  4027. }
  4028. key.objectid = btrfs_root_id(root);
  4029. key.type = BTRFS_ROOT_REF_KEY;
  4030. key.offset = (u64)-1;
  4031. ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
  4032. if (ret < 0)
  4033. goto out;
  4034. if (ret == 0) {
  4035. /*
  4036. * Key with offset -1 found, there would have to exist a root
  4037. * with such id, but this is out of valid range.
  4038. */
  4039. ret = -EUCLEAN;
  4040. goto out;
  4041. }
  4042. ret = 0;
  4043. if (path->slots[0] > 0) {
  4044. path->slots[0]--;
  4045. btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
  4046. if (key.objectid == btrfs_root_id(root) && key.type == BTRFS_ROOT_REF_KEY)
  4047. ret = -ENOTEMPTY;
  4048. }
  4049. out:
  4050. btrfs_free_path(path);
  4051. return ret;
  4052. }
  4053. /* Delete all dentries for inodes belonging to the root */
  4054. static void btrfs_prune_dentries(struct btrfs_root *root)
  4055. {
  4056. struct btrfs_fs_info *fs_info = root->fs_info;
  4057. struct btrfs_inode *inode;
  4058. u64 min_ino = 0;
  4059. if (!BTRFS_FS_ERROR(fs_info))
  4060. WARN_ON(btrfs_root_refs(&root->root_item) != 0);
  4061. inode = btrfs_find_first_inode(root, min_ino);
  4062. while (inode) {
  4063. if (atomic_read(&inode->vfs_inode.i_count) > 1)
  4064. d_prune_aliases(&inode->vfs_inode);
  4065. min_ino = btrfs_ino(inode) + 1;
  4066. /*
  4067. * btrfs_drop_inode() will have it removed from the inode
  4068. * cache when its usage count hits zero.
  4069. */
  4070. iput(&inode->vfs_inode);
  4071. cond_resched();
  4072. inode = btrfs_find_first_inode(root, min_ino);
  4073. }
  4074. }
  4075. int btrfs_delete_subvolume(struct btrfs_inode *dir, struct dentry *dentry)
  4076. {
  4077. struct btrfs_root *root = dir->root;
  4078. struct btrfs_fs_info *fs_info = root->fs_info;
  4079. struct inode *inode = d_inode(dentry);
  4080. struct btrfs_root *dest = BTRFS_I(inode)->root;
  4081. struct btrfs_trans_handle *trans;
  4082. struct btrfs_block_rsv block_rsv;
  4083. u64 root_flags;
  4084. u64 qgroup_reserved = 0;
  4085. int ret;
  4086. down_write(&fs_info->subvol_sem);
  4087. /*
  4088. * Don't allow to delete a subvolume with send in progress. This is
  4089. * inside the inode lock so the error handling that has to drop the bit
  4090. * again is not run concurrently.
  4091. */
  4092. spin_lock(&dest->root_item_lock);
  4093. if (dest->send_in_progress) {
  4094. spin_unlock(&dest->root_item_lock);
  4095. btrfs_warn(fs_info,
  4096. "attempt to delete subvolume %llu during send",
  4097. btrfs_root_id(dest));
  4098. ret = -EPERM;
  4099. goto out_up_write;
  4100. }
  4101. if (atomic_read(&dest->nr_swapfiles)) {
  4102. spin_unlock(&dest->root_item_lock);
  4103. btrfs_warn(fs_info,
  4104. "attempt to delete subvolume %llu with active swapfile",
  4105. btrfs_root_id(root));
  4106. ret = -EPERM;
  4107. goto out_up_write;
  4108. }
  4109. root_flags = btrfs_root_flags(&dest->root_item);
  4110. btrfs_set_root_flags(&dest->root_item,
  4111. root_flags | BTRFS_ROOT_SUBVOL_DEAD);
  4112. spin_unlock(&dest->root_item_lock);
  4113. ret = may_destroy_subvol(dest);
  4114. if (ret)
  4115. goto out_undead;
  4116. btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
  4117. /*
  4118. * One for dir inode,
  4119. * two for dir entries,
  4120. * two for root ref/backref.
  4121. */
  4122. ret = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
  4123. if (ret)
  4124. goto out_undead;
  4125. qgroup_reserved = block_rsv.qgroup_rsv_reserved;
  4126. trans = btrfs_start_transaction(root, 0);
  4127. if (IS_ERR(trans)) {
  4128. ret = PTR_ERR(trans);
  4129. goto out_release;
  4130. }
  4131. btrfs_qgroup_convert_reserved_meta(root, qgroup_reserved);
  4132. qgroup_reserved = 0;
  4133. trans->block_rsv = &block_rsv;
  4134. trans->bytes_reserved = block_rsv.size;
  4135. btrfs_record_snapshot_destroy(trans, dir);
  4136. ret = btrfs_unlink_subvol(trans, dir, dentry);
  4137. if (ret) {
  4138. btrfs_abort_transaction(trans, ret);
  4139. goto out_end_trans;
  4140. }
  4141. ret = btrfs_record_root_in_trans(trans, dest);
  4142. if (ret) {
  4143. btrfs_abort_transaction(trans, ret);
  4144. goto out_end_trans;
  4145. }
  4146. memset(&dest->root_item.drop_progress, 0,
  4147. sizeof(dest->root_item.drop_progress));
  4148. btrfs_set_root_drop_level(&dest->root_item, 0);
  4149. btrfs_set_root_refs(&dest->root_item, 0);
  4150. if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
  4151. ret = btrfs_insert_orphan_item(trans,
  4152. fs_info->tree_root,
  4153. btrfs_root_id(dest));
  4154. if (ret) {
  4155. btrfs_abort_transaction(trans, ret);
  4156. goto out_end_trans;
  4157. }
  4158. }
  4159. ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
  4160. BTRFS_UUID_KEY_SUBVOL, btrfs_root_id(dest));
  4161. if (ret && ret != -ENOENT) {
  4162. btrfs_abort_transaction(trans, ret);
  4163. goto out_end_trans;
  4164. }
  4165. if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
  4166. ret = btrfs_uuid_tree_remove(trans,
  4167. dest->root_item.received_uuid,
  4168. BTRFS_UUID_KEY_RECEIVED_SUBVOL,
  4169. btrfs_root_id(dest));
  4170. if (ret && ret != -ENOENT) {
  4171. btrfs_abort_transaction(trans, ret);
  4172. goto out_end_trans;
  4173. }
  4174. }
  4175. free_anon_bdev(dest->anon_dev);
  4176. dest->anon_dev = 0;
  4177. out_end_trans:
  4178. trans->block_rsv = NULL;
  4179. trans->bytes_reserved = 0;
  4180. ret = btrfs_end_transaction(trans);
  4181. inode->i_flags |= S_DEAD;
  4182. out_release:
  4183. btrfs_block_rsv_release(fs_info, &block_rsv, (u64)-1, NULL);
  4184. if (qgroup_reserved)
  4185. btrfs_qgroup_free_meta_prealloc(root, qgroup_reserved);
  4186. out_undead:
  4187. if (ret) {
  4188. spin_lock(&dest->root_item_lock);
  4189. root_flags = btrfs_root_flags(&dest->root_item);
  4190. btrfs_set_root_flags(&dest->root_item,
  4191. root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
  4192. spin_unlock(&dest->root_item_lock);
  4193. }
  4194. out_up_write:
  4195. up_write(&fs_info->subvol_sem);
  4196. if (!ret) {
  4197. d_invalidate(dentry);
  4198. btrfs_prune_dentries(dest);
  4199. ASSERT(dest->send_in_progress == 0);
  4200. }
  4201. return ret;
  4202. }
  4203. static int btrfs_rmdir(struct inode *dir, struct dentry *dentry)
  4204. {
  4205. struct inode *inode = d_inode(dentry);
  4206. struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
  4207. int ret = 0;
  4208. struct btrfs_trans_handle *trans;
  4209. struct fscrypt_name fname;
  4210. if (inode->i_size > BTRFS_EMPTY_DIR_SIZE)
  4211. return -ENOTEMPTY;
  4212. if (btrfs_ino(BTRFS_I(inode)) == BTRFS_FIRST_FREE_OBJECTID) {
  4213. if (unlikely(btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))) {
  4214. btrfs_err(fs_info,
  4215. "extent tree v2 doesn't support snapshot deletion yet");
  4216. return -EOPNOTSUPP;
  4217. }
  4218. return btrfs_delete_subvolume(BTRFS_I(dir), dentry);
  4219. }
  4220. ret = fscrypt_setup_filename(dir, &dentry->d_name, 1, &fname);
  4221. if (ret)
  4222. return ret;
  4223. /* This needs to handle no-key deletions later on */
  4224. trans = __unlink_start_trans(BTRFS_I(dir));
  4225. if (IS_ERR(trans)) {
  4226. ret = PTR_ERR(trans);
  4227. goto out_notrans;
  4228. }
  4229. /*
  4230. * Propagate the last_unlink_trans value of the deleted dir to its
  4231. * parent directory. This is to prevent an unrecoverable log tree in the
  4232. * case we do something like this:
  4233. * 1) create dir foo
  4234. * 2) create snapshot under dir foo
  4235. * 3) delete the snapshot
  4236. * 4) rmdir foo
  4237. * 5) mkdir foo
  4238. * 6) fsync foo or some file inside foo
  4239. *
  4240. * This is because we can't unlink other roots when replaying the dir
  4241. * deletes for directory foo.
  4242. */
  4243. if (BTRFS_I(inode)->last_unlink_trans >= trans->transid)
  4244. btrfs_record_snapshot_destroy(trans, BTRFS_I(dir));
  4245. if (unlikely(btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
  4246. ret = btrfs_unlink_subvol(trans, BTRFS_I(dir), dentry);
  4247. goto out;
  4248. }
  4249. ret = btrfs_orphan_add(trans, BTRFS_I(inode));
  4250. if (ret)
  4251. goto out;
  4252. /* now the directory is empty */
  4253. ret = btrfs_unlink_inode(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
  4254. &fname.disk_name);
  4255. if (!ret)
  4256. btrfs_i_size_write(BTRFS_I(inode), 0);
  4257. out:
  4258. btrfs_end_transaction(trans);
  4259. out_notrans:
  4260. btrfs_btree_balance_dirty(fs_info);
  4261. fscrypt_free_filename(&fname);
  4262. return ret;
  4263. }
  4264. /*
  4265. * Read, zero a chunk and write a block.
  4266. *
  4267. * @inode - inode that we're zeroing
  4268. * @from - the offset to start zeroing
  4269. * @len - the length to zero, 0 to zero the entire range respective to the
  4270. * offset
  4271. * @front - zero up to the offset instead of from the offset on
  4272. *
  4273. * This will find the block for the "from" offset and cow the block and zero the
  4274. * part we want to zero. This is used with truncate and hole punching.
  4275. */
  4276. int btrfs_truncate_block(struct btrfs_inode *inode, loff_t from, loff_t len,
  4277. int front)
  4278. {
  4279. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  4280. struct address_space *mapping = inode->vfs_inode.i_mapping;
  4281. struct extent_io_tree *io_tree = &inode->io_tree;
  4282. struct btrfs_ordered_extent *ordered;
  4283. struct extent_state *cached_state = NULL;
  4284. struct extent_changeset *data_reserved = NULL;
  4285. bool only_release_metadata = false;
  4286. u32 blocksize = fs_info->sectorsize;
  4287. pgoff_t index = from >> PAGE_SHIFT;
  4288. unsigned offset = from & (blocksize - 1);
  4289. struct folio *folio;
  4290. gfp_t mask = btrfs_alloc_write_mask(mapping);
  4291. size_t write_bytes = blocksize;
  4292. int ret = 0;
  4293. u64 block_start;
  4294. u64 block_end;
  4295. if (IS_ALIGNED(offset, blocksize) &&
  4296. (!len || IS_ALIGNED(len, blocksize)))
  4297. goto out;
  4298. block_start = round_down(from, blocksize);
  4299. block_end = block_start + blocksize - 1;
  4300. ret = btrfs_check_data_free_space(inode, &data_reserved, block_start,
  4301. blocksize, false);
  4302. if (ret < 0) {
  4303. if (btrfs_check_nocow_lock(inode, block_start, &write_bytes, false) > 0) {
  4304. /* For nocow case, no need to reserve data space */
  4305. only_release_metadata = true;
  4306. } else {
  4307. goto out;
  4308. }
  4309. }
  4310. ret = btrfs_delalloc_reserve_metadata(inode, blocksize, blocksize, false);
  4311. if (ret < 0) {
  4312. if (!only_release_metadata)
  4313. btrfs_free_reserved_data_space(inode, data_reserved,
  4314. block_start, blocksize);
  4315. goto out;
  4316. }
  4317. again:
  4318. folio = __filemap_get_folio(mapping, index,
  4319. FGP_LOCK | FGP_ACCESSED | FGP_CREAT, mask);
  4320. if (IS_ERR(folio)) {
  4321. if (only_release_metadata)
  4322. btrfs_delalloc_release_metadata(inode, blocksize, true);
  4323. else
  4324. btrfs_delalloc_release_space(inode, data_reserved,
  4325. block_start, blocksize, true);
  4326. btrfs_delalloc_release_extents(inode, blocksize);
  4327. ret = -ENOMEM;
  4328. goto out;
  4329. }
  4330. if (!folio_test_uptodate(folio)) {
  4331. ret = btrfs_read_folio(NULL, folio);
  4332. folio_lock(folio);
  4333. if (folio->mapping != mapping) {
  4334. folio_unlock(folio);
  4335. folio_put(folio);
  4336. goto again;
  4337. }
  4338. if (!folio_test_uptodate(folio)) {
  4339. ret = -EIO;
  4340. goto out_unlock;
  4341. }
  4342. }
  4343. /*
  4344. * We unlock the page after the io is completed and then re-lock it
  4345. * above. release_folio() could have come in between that and cleared
  4346. * folio private, but left the page in the mapping. Set the page mapped
  4347. * here to make sure it's properly set for the subpage stuff.
  4348. */
  4349. ret = set_folio_extent_mapped(folio);
  4350. if (ret < 0)
  4351. goto out_unlock;
  4352. folio_wait_writeback(folio);
  4353. lock_extent(io_tree, block_start, block_end, &cached_state);
  4354. ordered = btrfs_lookup_ordered_extent(inode, block_start);
  4355. if (ordered) {
  4356. unlock_extent(io_tree, block_start, block_end, &cached_state);
  4357. folio_unlock(folio);
  4358. folio_put(folio);
  4359. btrfs_start_ordered_extent(ordered);
  4360. btrfs_put_ordered_extent(ordered);
  4361. goto again;
  4362. }
  4363. clear_extent_bit(&inode->io_tree, block_start, block_end,
  4364. EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
  4365. &cached_state);
  4366. ret = btrfs_set_extent_delalloc(inode, block_start, block_end, 0,
  4367. &cached_state);
  4368. if (ret) {
  4369. unlock_extent(io_tree, block_start, block_end, &cached_state);
  4370. goto out_unlock;
  4371. }
  4372. if (offset != blocksize) {
  4373. if (!len)
  4374. len = blocksize - offset;
  4375. if (front)
  4376. folio_zero_range(folio, block_start - folio_pos(folio),
  4377. offset);
  4378. else
  4379. folio_zero_range(folio,
  4380. (block_start - folio_pos(folio)) + offset,
  4381. len);
  4382. }
  4383. btrfs_folio_clear_checked(fs_info, folio, block_start,
  4384. block_end + 1 - block_start);
  4385. btrfs_folio_set_dirty(fs_info, folio, block_start,
  4386. block_end + 1 - block_start);
  4387. unlock_extent(io_tree, block_start, block_end, &cached_state);
  4388. if (only_release_metadata)
  4389. set_extent_bit(&inode->io_tree, block_start, block_end,
  4390. EXTENT_NORESERVE, NULL);
  4391. out_unlock:
  4392. if (ret) {
  4393. if (only_release_metadata)
  4394. btrfs_delalloc_release_metadata(inode, blocksize, true);
  4395. else
  4396. btrfs_delalloc_release_space(inode, data_reserved,
  4397. block_start, blocksize, true);
  4398. }
  4399. btrfs_delalloc_release_extents(inode, blocksize);
  4400. folio_unlock(folio);
  4401. folio_put(folio);
  4402. out:
  4403. if (only_release_metadata)
  4404. btrfs_check_nocow_unlock(inode);
  4405. extent_changeset_free(data_reserved);
  4406. return ret;
  4407. }
  4408. static int maybe_insert_hole(struct btrfs_inode *inode, u64 offset, u64 len)
  4409. {
  4410. struct btrfs_root *root = inode->root;
  4411. struct btrfs_fs_info *fs_info = root->fs_info;
  4412. struct btrfs_trans_handle *trans;
  4413. struct btrfs_drop_extents_args drop_args = { 0 };
  4414. int ret;
  4415. /*
  4416. * If NO_HOLES is enabled, we don't need to do anything.
  4417. * Later, up in the call chain, either btrfs_set_inode_last_sub_trans()
  4418. * or btrfs_update_inode() will be called, which guarantee that the next
  4419. * fsync will know this inode was changed and needs to be logged.
  4420. */
  4421. if (btrfs_fs_incompat(fs_info, NO_HOLES))
  4422. return 0;
  4423. /*
  4424. * 1 - for the one we're dropping
  4425. * 1 - for the one we're adding
  4426. * 1 - for updating the inode.
  4427. */
  4428. trans = btrfs_start_transaction(root, 3);
  4429. if (IS_ERR(trans))
  4430. return PTR_ERR(trans);
  4431. drop_args.start = offset;
  4432. drop_args.end = offset + len;
  4433. drop_args.drop_cache = true;
  4434. ret = btrfs_drop_extents(trans, root, inode, &drop_args);
  4435. if (ret) {
  4436. btrfs_abort_transaction(trans, ret);
  4437. btrfs_end_transaction(trans);
  4438. return ret;
  4439. }
  4440. ret = btrfs_insert_hole_extent(trans, root, btrfs_ino(inode), offset, len);
  4441. if (ret) {
  4442. btrfs_abort_transaction(trans, ret);
  4443. } else {
  4444. btrfs_update_inode_bytes(inode, 0, drop_args.bytes_found);
  4445. btrfs_update_inode(trans, inode);
  4446. }
  4447. btrfs_end_transaction(trans);
  4448. return ret;
  4449. }
  4450. /*
  4451. * This function puts in dummy file extents for the area we're creating a hole
  4452. * for. So if we are truncating this file to a larger size we need to insert
  4453. * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
  4454. * the range between oldsize and size
  4455. */
  4456. int btrfs_cont_expand(struct btrfs_inode *inode, loff_t oldsize, loff_t size)
  4457. {
  4458. struct btrfs_root *root = inode->root;
  4459. struct btrfs_fs_info *fs_info = root->fs_info;
  4460. struct extent_io_tree *io_tree = &inode->io_tree;
  4461. struct extent_map *em = NULL;
  4462. struct extent_state *cached_state = NULL;
  4463. u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
  4464. u64 block_end = ALIGN(size, fs_info->sectorsize);
  4465. u64 last_byte;
  4466. u64 cur_offset;
  4467. u64 hole_size;
  4468. int ret = 0;
  4469. /*
  4470. * If our size started in the middle of a block we need to zero out the
  4471. * rest of the block before we expand the i_size, otherwise we could
  4472. * expose stale data.
  4473. */
  4474. ret = btrfs_truncate_block(inode, oldsize, 0, 0);
  4475. if (ret)
  4476. return ret;
  4477. if (size <= hole_start)
  4478. return 0;
  4479. btrfs_lock_and_flush_ordered_range(inode, hole_start, block_end - 1,
  4480. &cached_state);
  4481. cur_offset = hole_start;
  4482. while (1) {
  4483. em = btrfs_get_extent(inode, NULL, cur_offset, block_end - cur_offset);
  4484. if (IS_ERR(em)) {
  4485. ret = PTR_ERR(em);
  4486. em = NULL;
  4487. break;
  4488. }
  4489. last_byte = min(extent_map_end(em), block_end);
  4490. last_byte = ALIGN(last_byte, fs_info->sectorsize);
  4491. hole_size = last_byte - cur_offset;
  4492. if (!(em->flags & EXTENT_FLAG_PREALLOC)) {
  4493. struct extent_map *hole_em;
  4494. ret = maybe_insert_hole(inode, cur_offset, hole_size);
  4495. if (ret)
  4496. break;
  4497. ret = btrfs_inode_set_file_extent_range(inode,
  4498. cur_offset, hole_size);
  4499. if (ret)
  4500. break;
  4501. hole_em = alloc_extent_map();
  4502. if (!hole_em) {
  4503. btrfs_drop_extent_map_range(inode, cur_offset,
  4504. cur_offset + hole_size - 1,
  4505. false);
  4506. btrfs_set_inode_full_sync(inode);
  4507. goto next;
  4508. }
  4509. hole_em->start = cur_offset;
  4510. hole_em->len = hole_size;
  4511. hole_em->disk_bytenr = EXTENT_MAP_HOLE;
  4512. hole_em->disk_num_bytes = 0;
  4513. hole_em->ram_bytes = hole_size;
  4514. hole_em->generation = btrfs_get_fs_generation(fs_info);
  4515. ret = btrfs_replace_extent_map_range(inode, hole_em, true);
  4516. free_extent_map(hole_em);
  4517. } else {
  4518. ret = btrfs_inode_set_file_extent_range(inode,
  4519. cur_offset, hole_size);
  4520. if (ret)
  4521. break;
  4522. }
  4523. next:
  4524. free_extent_map(em);
  4525. em = NULL;
  4526. cur_offset = last_byte;
  4527. if (cur_offset >= block_end)
  4528. break;
  4529. }
  4530. free_extent_map(em);
  4531. unlock_extent(io_tree, hole_start, block_end - 1, &cached_state);
  4532. return ret;
  4533. }
  4534. static int btrfs_setsize(struct inode *inode, struct iattr *attr)
  4535. {
  4536. struct btrfs_root *root = BTRFS_I(inode)->root;
  4537. struct btrfs_trans_handle *trans;
  4538. loff_t oldsize = i_size_read(inode);
  4539. loff_t newsize = attr->ia_size;
  4540. int mask = attr->ia_valid;
  4541. int ret;
  4542. /*
  4543. * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
  4544. * special case where we need to update the times despite not having
  4545. * these flags set. For all other operations the VFS set these flags
  4546. * explicitly if it wants a timestamp update.
  4547. */
  4548. if (newsize != oldsize) {
  4549. inode_inc_iversion(inode);
  4550. if (!(mask & (ATTR_CTIME | ATTR_MTIME))) {
  4551. inode_set_mtime_to_ts(inode,
  4552. inode_set_ctime_current(inode));
  4553. }
  4554. }
  4555. if (newsize > oldsize) {
  4556. /*
  4557. * Don't do an expanding truncate while snapshotting is ongoing.
  4558. * This is to ensure the snapshot captures a fully consistent
  4559. * state of this file - if the snapshot captures this expanding
  4560. * truncation, it must capture all writes that happened before
  4561. * this truncation.
  4562. */
  4563. btrfs_drew_write_lock(&root->snapshot_lock);
  4564. ret = btrfs_cont_expand(BTRFS_I(inode), oldsize, newsize);
  4565. if (ret) {
  4566. btrfs_drew_write_unlock(&root->snapshot_lock);
  4567. return ret;
  4568. }
  4569. trans = btrfs_start_transaction(root, 1);
  4570. if (IS_ERR(trans)) {
  4571. btrfs_drew_write_unlock(&root->snapshot_lock);
  4572. return PTR_ERR(trans);
  4573. }
  4574. i_size_write(inode, newsize);
  4575. btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
  4576. pagecache_isize_extended(inode, oldsize, newsize);
  4577. ret = btrfs_update_inode(trans, BTRFS_I(inode));
  4578. btrfs_drew_write_unlock(&root->snapshot_lock);
  4579. btrfs_end_transaction(trans);
  4580. } else {
  4581. struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
  4582. if (btrfs_is_zoned(fs_info)) {
  4583. ret = btrfs_wait_ordered_range(BTRFS_I(inode),
  4584. ALIGN(newsize, fs_info->sectorsize),
  4585. (u64)-1);
  4586. if (ret)
  4587. return ret;
  4588. }
  4589. /*
  4590. * We're truncating a file that used to have good data down to
  4591. * zero. Make sure any new writes to the file get on disk
  4592. * on close.
  4593. */
  4594. if (newsize == 0)
  4595. set_bit(BTRFS_INODE_FLUSH_ON_CLOSE,
  4596. &BTRFS_I(inode)->runtime_flags);
  4597. truncate_setsize(inode, newsize);
  4598. inode_dio_wait(inode);
  4599. ret = btrfs_truncate(BTRFS_I(inode), newsize == oldsize);
  4600. if (ret && inode->i_nlink) {
  4601. int err;
  4602. /*
  4603. * Truncate failed, so fix up the in-memory size. We
  4604. * adjusted disk_i_size down as we removed extents, so
  4605. * wait for disk_i_size to be stable and then update the
  4606. * in-memory size to match.
  4607. */
  4608. err = btrfs_wait_ordered_range(BTRFS_I(inode), 0, (u64)-1);
  4609. if (err)
  4610. return err;
  4611. i_size_write(inode, BTRFS_I(inode)->disk_i_size);
  4612. }
  4613. }
  4614. return ret;
  4615. }
  4616. static int btrfs_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
  4617. struct iattr *attr)
  4618. {
  4619. struct inode *inode = d_inode(dentry);
  4620. struct btrfs_root *root = BTRFS_I(inode)->root;
  4621. int err;
  4622. if (btrfs_root_readonly(root))
  4623. return -EROFS;
  4624. err = setattr_prepare(idmap, dentry, attr);
  4625. if (err)
  4626. return err;
  4627. if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
  4628. err = btrfs_setsize(inode, attr);
  4629. if (err)
  4630. return err;
  4631. }
  4632. if (attr->ia_valid) {
  4633. setattr_copy(idmap, inode, attr);
  4634. inode_inc_iversion(inode);
  4635. err = btrfs_dirty_inode(BTRFS_I(inode));
  4636. if (!err && attr->ia_valid & ATTR_MODE)
  4637. err = posix_acl_chmod(idmap, dentry, inode->i_mode);
  4638. }
  4639. return err;
  4640. }
  4641. /*
  4642. * While truncating the inode pages during eviction, we get the VFS
  4643. * calling btrfs_invalidate_folio() against each folio of the inode. This
  4644. * is slow because the calls to btrfs_invalidate_folio() result in a
  4645. * huge amount of calls to lock_extent() and clear_extent_bit(),
  4646. * which keep merging and splitting extent_state structures over and over,
  4647. * wasting lots of time.
  4648. *
  4649. * Therefore if the inode is being evicted, let btrfs_invalidate_folio()
  4650. * skip all those expensive operations on a per folio basis and do only
  4651. * the ordered io finishing, while we release here the extent_map and
  4652. * extent_state structures, without the excessive merging and splitting.
  4653. */
  4654. static void evict_inode_truncate_pages(struct inode *inode)
  4655. {
  4656. struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
  4657. struct rb_node *node;
  4658. ASSERT(inode->i_state & I_FREEING);
  4659. truncate_inode_pages_final(&inode->i_data);
  4660. btrfs_drop_extent_map_range(BTRFS_I(inode), 0, (u64)-1, false);
  4661. /*
  4662. * Keep looping until we have no more ranges in the io tree.
  4663. * We can have ongoing bios started by readahead that have
  4664. * their endio callback (extent_io.c:end_bio_extent_readpage)
  4665. * still in progress (unlocked the pages in the bio but did not yet
  4666. * unlocked the ranges in the io tree). Therefore this means some
  4667. * ranges can still be locked and eviction started because before
  4668. * submitting those bios, which are executed by a separate task (work
  4669. * queue kthread), inode references (inode->i_count) were not taken
  4670. * (which would be dropped in the end io callback of each bio).
  4671. * Therefore here we effectively end up waiting for those bios and
  4672. * anyone else holding locked ranges without having bumped the inode's
  4673. * reference count - if we don't do it, when they access the inode's
  4674. * io_tree to unlock a range it may be too late, leading to an
  4675. * use-after-free issue.
  4676. */
  4677. spin_lock(&io_tree->lock);
  4678. while (!RB_EMPTY_ROOT(&io_tree->state)) {
  4679. struct extent_state *state;
  4680. struct extent_state *cached_state = NULL;
  4681. u64 start;
  4682. u64 end;
  4683. unsigned state_flags;
  4684. node = rb_first(&io_tree->state);
  4685. state = rb_entry(node, struct extent_state, rb_node);
  4686. start = state->start;
  4687. end = state->end;
  4688. state_flags = state->state;
  4689. spin_unlock(&io_tree->lock);
  4690. lock_extent(io_tree, start, end, &cached_state);
  4691. /*
  4692. * If still has DELALLOC flag, the extent didn't reach disk,
  4693. * and its reserved space won't be freed by delayed_ref.
  4694. * So we need to free its reserved space here.
  4695. * (Refer to comment in btrfs_invalidate_folio, case 2)
  4696. *
  4697. * Note, end is the bytenr of last byte, so we need + 1 here.
  4698. */
  4699. if (state_flags & EXTENT_DELALLOC)
  4700. btrfs_qgroup_free_data(BTRFS_I(inode), NULL, start,
  4701. end - start + 1, NULL);
  4702. clear_extent_bit(io_tree, start, end,
  4703. EXTENT_CLEAR_ALL_BITS | EXTENT_DO_ACCOUNTING,
  4704. &cached_state);
  4705. cond_resched();
  4706. spin_lock(&io_tree->lock);
  4707. }
  4708. spin_unlock(&io_tree->lock);
  4709. }
  4710. static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
  4711. struct btrfs_block_rsv *rsv)
  4712. {
  4713. struct btrfs_fs_info *fs_info = root->fs_info;
  4714. struct btrfs_trans_handle *trans;
  4715. u64 delayed_refs_extra = btrfs_calc_delayed_ref_bytes(fs_info, 1);
  4716. int ret;
  4717. /*
  4718. * Eviction should be taking place at some place safe because of our
  4719. * delayed iputs. However the normal flushing code will run delayed
  4720. * iputs, so we cannot use FLUSH_ALL otherwise we'll deadlock.
  4721. *
  4722. * We reserve the delayed_refs_extra here again because we can't use
  4723. * btrfs_start_transaction(root, 0) for the same deadlocky reason as
  4724. * above. We reserve our extra bit here because we generate a ton of
  4725. * delayed refs activity by truncating.
  4726. *
  4727. * BTRFS_RESERVE_FLUSH_EVICT will steal from the global_rsv if it can,
  4728. * if we fail to make this reservation we can re-try without the
  4729. * delayed_refs_extra so we can make some forward progress.
  4730. */
  4731. ret = btrfs_block_rsv_refill(fs_info, rsv, rsv->size + delayed_refs_extra,
  4732. BTRFS_RESERVE_FLUSH_EVICT);
  4733. if (ret) {
  4734. ret = btrfs_block_rsv_refill(fs_info, rsv, rsv->size,
  4735. BTRFS_RESERVE_FLUSH_EVICT);
  4736. if (ret) {
  4737. btrfs_warn(fs_info,
  4738. "could not allocate space for delete; will truncate on mount");
  4739. return ERR_PTR(-ENOSPC);
  4740. }
  4741. delayed_refs_extra = 0;
  4742. }
  4743. trans = btrfs_join_transaction(root);
  4744. if (IS_ERR(trans))
  4745. return trans;
  4746. if (delayed_refs_extra) {
  4747. trans->block_rsv = &fs_info->trans_block_rsv;
  4748. trans->bytes_reserved = delayed_refs_extra;
  4749. btrfs_block_rsv_migrate(rsv, trans->block_rsv,
  4750. delayed_refs_extra, true);
  4751. }
  4752. return trans;
  4753. }
  4754. void btrfs_evict_inode(struct inode *inode)
  4755. {
  4756. struct btrfs_fs_info *fs_info;
  4757. struct btrfs_trans_handle *trans;
  4758. struct btrfs_root *root = BTRFS_I(inode)->root;
  4759. struct btrfs_block_rsv *rsv = NULL;
  4760. int ret;
  4761. trace_btrfs_inode_evict(inode);
  4762. if (!root) {
  4763. fsverity_cleanup_inode(inode);
  4764. clear_inode(inode);
  4765. return;
  4766. }
  4767. fs_info = inode_to_fs_info(inode);
  4768. evict_inode_truncate_pages(inode);
  4769. if (inode->i_nlink &&
  4770. ((btrfs_root_refs(&root->root_item) != 0 &&
  4771. btrfs_root_id(root) != BTRFS_ROOT_TREE_OBJECTID) ||
  4772. btrfs_is_free_space_inode(BTRFS_I(inode))))
  4773. goto out;
  4774. if (is_bad_inode(inode))
  4775. goto out;
  4776. if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
  4777. goto out;
  4778. if (inode->i_nlink > 0) {
  4779. BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
  4780. btrfs_root_id(root) != BTRFS_ROOT_TREE_OBJECTID);
  4781. goto out;
  4782. }
  4783. /*
  4784. * This makes sure the inode item in tree is uptodate and the space for
  4785. * the inode update is released.
  4786. */
  4787. ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
  4788. if (ret)
  4789. goto out;
  4790. /*
  4791. * This drops any pending insert or delete operations we have for this
  4792. * inode. We could have a delayed dir index deletion queued up, but
  4793. * we're removing the inode completely so that'll be taken care of in
  4794. * the truncate.
  4795. */
  4796. btrfs_kill_delayed_inode_items(BTRFS_I(inode));
  4797. rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
  4798. if (!rsv)
  4799. goto out;
  4800. rsv->size = btrfs_calc_metadata_size(fs_info, 1);
  4801. rsv->failfast = true;
  4802. btrfs_i_size_write(BTRFS_I(inode), 0);
  4803. while (1) {
  4804. struct btrfs_truncate_control control = {
  4805. .inode = BTRFS_I(inode),
  4806. .ino = btrfs_ino(BTRFS_I(inode)),
  4807. .new_size = 0,
  4808. .min_type = 0,
  4809. };
  4810. trans = evict_refill_and_join(root, rsv);
  4811. if (IS_ERR(trans))
  4812. goto out;
  4813. trans->block_rsv = rsv;
  4814. ret = btrfs_truncate_inode_items(trans, root, &control);
  4815. trans->block_rsv = &fs_info->trans_block_rsv;
  4816. btrfs_end_transaction(trans);
  4817. /*
  4818. * We have not added new delayed items for our inode after we
  4819. * have flushed its delayed items, so no need to throttle on
  4820. * delayed items. However we have modified extent buffers.
  4821. */
  4822. btrfs_btree_balance_dirty_nodelay(fs_info);
  4823. if (ret && ret != -ENOSPC && ret != -EAGAIN)
  4824. goto out;
  4825. else if (!ret)
  4826. break;
  4827. }
  4828. /*
  4829. * Errors here aren't a big deal, it just means we leave orphan items in
  4830. * the tree. They will be cleaned up on the next mount. If the inode
  4831. * number gets reused, cleanup deletes the orphan item without doing
  4832. * anything, and unlink reuses the existing orphan item.
  4833. *
  4834. * If it turns out that we are dropping too many of these, we might want
  4835. * to add a mechanism for retrying these after a commit.
  4836. */
  4837. trans = evict_refill_and_join(root, rsv);
  4838. if (!IS_ERR(trans)) {
  4839. trans->block_rsv = rsv;
  4840. btrfs_orphan_del(trans, BTRFS_I(inode));
  4841. trans->block_rsv = &fs_info->trans_block_rsv;
  4842. btrfs_end_transaction(trans);
  4843. }
  4844. out:
  4845. btrfs_free_block_rsv(fs_info, rsv);
  4846. /*
  4847. * If we didn't successfully delete, the orphan item will still be in
  4848. * the tree and we'll retry on the next mount. Again, we might also want
  4849. * to retry these periodically in the future.
  4850. */
  4851. btrfs_remove_delayed_node(BTRFS_I(inode));
  4852. fsverity_cleanup_inode(inode);
  4853. clear_inode(inode);
  4854. }
  4855. /*
  4856. * Return the key found in the dir entry in the location pointer, fill @type
  4857. * with BTRFS_FT_*, and return 0.
  4858. *
  4859. * If no dir entries were found, returns -ENOENT.
  4860. * If found a corrupted location in dir entry, returns -EUCLEAN.
  4861. */
  4862. static int btrfs_inode_by_name(struct btrfs_inode *dir, struct dentry *dentry,
  4863. struct btrfs_key *location, u8 *type)
  4864. {
  4865. struct btrfs_dir_item *di;
  4866. struct btrfs_path *path;
  4867. struct btrfs_root *root = dir->root;
  4868. int ret = 0;
  4869. struct fscrypt_name fname;
  4870. path = btrfs_alloc_path();
  4871. if (!path)
  4872. return -ENOMEM;
  4873. ret = fscrypt_setup_filename(&dir->vfs_inode, &dentry->d_name, 1, &fname);
  4874. if (ret < 0)
  4875. goto out;
  4876. /*
  4877. * fscrypt_setup_filename() should never return a positive value, but
  4878. * gcc on sparc/parisc thinks it can, so assert that doesn't happen.
  4879. */
  4880. ASSERT(ret == 0);
  4881. /* This needs to handle no-key deletions later on */
  4882. di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir),
  4883. &fname.disk_name, 0);
  4884. if (IS_ERR_OR_NULL(di)) {
  4885. ret = di ? PTR_ERR(di) : -ENOENT;
  4886. goto out;
  4887. }
  4888. btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
  4889. if (location->type != BTRFS_INODE_ITEM_KEY &&
  4890. location->type != BTRFS_ROOT_ITEM_KEY) {
  4891. ret = -EUCLEAN;
  4892. btrfs_warn(root->fs_info,
  4893. "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location(%llu %u %llu))",
  4894. __func__, fname.disk_name.name, btrfs_ino(dir),
  4895. location->objectid, location->type, location->offset);
  4896. }
  4897. if (!ret)
  4898. *type = btrfs_dir_ftype(path->nodes[0], di);
  4899. out:
  4900. fscrypt_free_filename(&fname);
  4901. btrfs_free_path(path);
  4902. return ret;
  4903. }
  4904. /*
  4905. * when we hit a tree root in a directory, the btrfs part of the inode
  4906. * needs to be changed to reflect the root directory of the tree root. This
  4907. * is kind of like crossing a mount point.
  4908. */
  4909. static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
  4910. struct btrfs_inode *dir,
  4911. struct dentry *dentry,
  4912. struct btrfs_key *location,
  4913. struct btrfs_root **sub_root)
  4914. {
  4915. struct btrfs_path *path;
  4916. struct btrfs_root *new_root;
  4917. struct btrfs_root_ref *ref;
  4918. struct extent_buffer *leaf;
  4919. struct btrfs_key key;
  4920. int ret;
  4921. int err = 0;
  4922. struct fscrypt_name fname;
  4923. ret = fscrypt_setup_filename(&dir->vfs_inode, &dentry->d_name, 0, &fname);
  4924. if (ret)
  4925. return ret;
  4926. path = btrfs_alloc_path();
  4927. if (!path) {
  4928. err = -ENOMEM;
  4929. goto out;
  4930. }
  4931. err = -ENOENT;
  4932. key.objectid = btrfs_root_id(dir->root);
  4933. key.type = BTRFS_ROOT_REF_KEY;
  4934. key.offset = location->objectid;
  4935. ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
  4936. if (ret) {
  4937. if (ret < 0)
  4938. err = ret;
  4939. goto out;
  4940. }
  4941. leaf = path->nodes[0];
  4942. ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
  4943. if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
  4944. btrfs_root_ref_name_len(leaf, ref) != fname.disk_name.len)
  4945. goto out;
  4946. ret = memcmp_extent_buffer(leaf, fname.disk_name.name,
  4947. (unsigned long)(ref + 1), fname.disk_name.len);
  4948. if (ret)
  4949. goto out;
  4950. btrfs_release_path(path);
  4951. new_root = btrfs_get_fs_root(fs_info, location->objectid, true);
  4952. if (IS_ERR(new_root)) {
  4953. err = PTR_ERR(new_root);
  4954. goto out;
  4955. }
  4956. *sub_root = new_root;
  4957. location->objectid = btrfs_root_dirid(&new_root->root_item);
  4958. location->type = BTRFS_INODE_ITEM_KEY;
  4959. location->offset = 0;
  4960. err = 0;
  4961. out:
  4962. btrfs_free_path(path);
  4963. fscrypt_free_filename(&fname);
  4964. return err;
  4965. }
  4966. static int btrfs_add_inode_to_root(struct btrfs_inode *inode, bool prealloc)
  4967. {
  4968. struct btrfs_root *root = inode->root;
  4969. struct btrfs_inode *existing;
  4970. const u64 ino = btrfs_ino(inode);
  4971. int ret;
  4972. if (inode_unhashed(&inode->vfs_inode))
  4973. return 0;
  4974. if (prealloc) {
  4975. ret = xa_reserve(&root->inodes, ino, GFP_NOFS);
  4976. if (ret)
  4977. return ret;
  4978. }
  4979. existing = xa_store(&root->inodes, ino, inode, GFP_ATOMIC);
  4980. if (xa_is_err(existing)) {
  4981. ret = xa_err(existing);
  4982. ASSERT(ret != -EINVAL);
  4983. ASSERT(ret != -ENOMEM);
  4984. return ret;
  4985. } else if (existing) {
  4986. WARN_ON(!(existing->vfs_inode.i_state & (I_WILL_FREE | I_FREEING)));
  4987. }
  4988. return 0;
  4989. }
  4990. static void btrfs_del_inode_from_root(struct btrfs_inode *inode)
  4991. {
  4992. struct btrfs_root *root = inode->root;
  4993. struct btrfs_inode *entry;
  4994. bool empty = false;
  4995. xa_lock(&root->inodes);
  4996. /*
  4997. * This btrfs_inode is being freed and has already been unhashed at this
  4998. * point. It's possible that another btrfs_inode has already been
  4999. * allocated for the same inode and inserted itself into the root, so
  5000. * don't delete it in that case.
  5001. *
  5002. * Note that this shouldn't need to allocate memory, so the gfp flags
  5003. * don't really matter.
  5004. */
  5005. entry = __xa_cmpxchg(&root->inodes, btrfs_ino(inode), inode, NULL,
  5006. GFP_ATOMIC);
  5007. if (entry == inode)
  5008. empty = xa_empty(&root->inodes);
  5009. xa_unlock(&root->inodes);
  5010. if (empty && btrfs_root_refs(&root->root_item) == 0) {
  5011. xa_lock(&root->inodes);
  5012. empty = xa_empty(&root->inodes);
  5013. xa_unlock(&root->inodes);
  5014. if (empty)
  5015. btrfs_add_dead_root(root);
  5016. }
  5017. }
  5018. static int btrfs_init_locked_inode(struct inode *inode, void *p)
  5019. {
  5020. struct btrfs_iget_args *args = p;
  5021. btrfs_set_inode_number(BTRFS_I(inode), args->ino);
  5022. BTRFS_I(inode)->root = btrfs_grab_root(args->root);
  5023. if (args->root && args->root == args->root->fs_info->tree_root &&
  5024. args->ino != BTRFS_BTREE_INODE_OBJECTID)
  5025. set_bit(BTRFS_INODE_FREE_SPACE_INODE,
  5026. &BTRFS_I(inode)->runtime_flags);
  5027. return 0;
  5028. }
  5029. static int btrfs_find_actor(struct inode *inode, void *opaque)
  5030. {
  5031. struct btrfs_iget_args *args = opaque;
  5032. return args->ino == btrfs_ino(BTRFS_I(inode)) &&
  5033. args->root == BTRFS_I(inode)->root;
  5034. }
  5035. static struct inode *btrfs_iget_locked(u64 ino, struct btrfs_root *root)
  5036. {
  5037. struct inode *inode;
  5038. struct btrfs_iget_args args;
  5039. unsigned long hashval = btrfs_inode_hash(ino, root);
  5040. args.ino = ino;
  5041. args.root = root;
  5042. inode = iget5_locked_rcu(root->fs_info->sb, hashval, btrfs_find_actor,
  5043. btrfs_init_locked_inode,
  5044. (void *)&args);
  5045. return inode;
  5046. }
  5047. /*
  5048. * Get an inode object given its inode number and corresponding root.
  5049. * Path can be preallocated to prevent recursing back to iget through
  5050. * allocator. NULL is also valid but may require an additional allocation
  5051. * later.
  5052. */
  5053. struct inode *btrfs_iget_path(u64 ino, struct btrfs_root *root,
  5054. struct btrfs_path *path)
  5055. {
  5056. struct inode *inode;
  5057. int ret;
  5058. inode = btrfs_iget_locked(ino, root);
  5059. if (!inode)
  5060. return ERR_PTR(-ENOMEM);
  5061. if (!(inode->i_state & I_NEW))
  5062. return inode;
  5063. ret = btrfs_read_locked_inode(inode, path);
  5064. /*
  5065. * ret > 0 can come from btrfs_search_slot called by
  5066. * btrfs_read_locked_inode(), this means the inode item was not found.
  5067. */
  5068. if (ret > 0)
  5069. ret = -ENOENT;
  5070. if (ret < 0)
  5071. goto error;
  5072. ret = btrfs_add_inode_to_root(BTRFS_I(inode), true);
  5073. if (ret < 0)
  5074. goto error;
  5075. unlock_new_inode(inode);
  5076. return inode;
  5077. error:
  5078. iget_failed(inode);
  5079. return ERR_PTR(ret);
  5080. }
  5081. struct inode *btrfs_iget(u64 ino, struct btrfs_root *root)
  5082. {
  5083. return btrfs_iget_path(ino, root, NULL);
  5084. }
  5085. static struct inode *new_simple_dir(struct inode *dir,
  5086. struct btrfs_key *key,
  5087. struct btrfs_root *root)
  5088. {
  5089. struct timespec64 ts;
  5090. struct inode *inode = new_inode(dir->i_sb);
  5091. if (!inode)
  5092. return ERR_PTR(-ENOMEM);
  5093. BTRFS_I(inode)->root = btrfs_grab_root(root);
  5094. BTRFS_I(inode)->ref_root_id = key->objectid;
  5095. set_bit(BTRFS_INODE_ROOT_STUB, &BTRFS_I(inode)->runtime_flags);
  5096. set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
  5097. btrfs_set_inode_number(BTRFS_I(inode), BTRFS_EMPTY_SUBVOL_DIR_OBJECTID);
  5098. /*
  5099. * We only need lookup, the rest is read-only and there's no inode
  5100. * associated with the dentry
  5101. */
  5102. inode->i_op = &simple_dir_inode_operations;
  5103. inode->i_opflags &= ~IOP_XATTR;
  5104. inode->i_fop = &simple_dir_operations;
  5105. inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
  5106. ts = inode_set_ctime_current(inode);
  5107. inode_set_mtime_to_ts(inode, ts);
  5108. inode_set_atime_to_ts(inode, inode_get_atime(dir));
  5109. BTRFS_I(inode)->i_otime_sec = ts.tv_sec;
  5110. BTRFS_I(inode)->i_otime_nsec = ts.tv_nsec;
  5111. inode->i_uid = dir->i_uid;
  5112. inode->i_gid = dir->i_gid;
  5113. return inode;
  5114. }
  5115. static_assert(BTRFS_FT_UNKNOWN == FT_UNKNOWN);
  5116. static_assert(BTRFS_FT_REG_FILE == FT_REG_FILE);
  5117. static_assert(BTRFS_FT_DIR == FT_DIR);
  5118. static_assert(BTRFS_FT_CHRDEV == FT_CHRDEV);
  5119. static_assert(BTRFS_FT_BLKDEV == FT_BLKDEV);
  5120. static_assert(BTRFS_FT_FIFO == FT_FIFO);
  5121. static_assert(BTRFS_FT_SOCK == FT_SOCK);
  5122. static_assert(BTRFS_FT_SYMLINK == FT_SYMLINK);
  5123. static inline u8 btrfs_inode_type(struct inode *inode)
  5124. {
  5125. return fs_umode_to_ftype(inode->i_mode);
  5126. }
  5127. struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
  5128. {
  5129. struct btrfs_fs_info *fs_info = inode_to_fs_info(dir);
  5130. struct inode *inode;
  5131. struct btrfs_root *root = BTRFS_I(dir)->root;
  5132. struct btrfs_root *sub_root = root;
  5133. struct btrfs_key location = { 0 };
  5134. u8 di_type = 0;
  5135. int ret = 0;
  5136. if (dentry->d_name.len > BTRFS_NAME_LEN)
  5137. return ERR_PTR(-ENAMETOOLONG);
  5138. ret = btrfs_inode_by_name(BTRFS_I(dir), dentry, &location, &di_type);
  5139. if (ret < 0)
  5140. return ERR_PTR(ret);
  5141. if (location.type == BTRFS_INODE_ITEM_KEY) {
  5142. inode = btrfs_iget(location.objectid, root);
  5143. if (IS_ERR(inode))
  5144. return inode;
  5145. /* Do extra check against inode mode with di_type */
  5146. if (btrfs_inode_type(inode) != di_type) {
  5147. btrfs_crit(fs_info,
  5148. "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
  5149. inode->i_mode, btrfs_inode_type(inode),
  5150. di_type);
  5151. iput(inode);
  5152. return ERR_PTR(-EUCLEAN);
  5153. }
  5154. return inode;
  5155. }
  5156. ret = fixup_tree_root_location(fs_info, BTRFS_I(dir), dentry,
  5157. &location, &sub_root);
  5158. if (ret < 0) {
  5159. if (ret != -ENOENT)
  5160. inode = ERR_PTR(ret);
  5161. else
  5162. inode = new_simple_dir(dir, &location, root);
  5163. } else {
  5164. inode = btrfs_iget(location.objectid, sub_root);
  5165. btrfs_put_root(sub_root);
  5166. if (IS_ERR(inode))
  5167. return inode;
  5168. down_read(&fs_info->cleanup_work_sem);
  5169. if (!sb_rdonly(inode->i_sb))
  5170. ret = btrfs_orphan_cleanup(sub_root);
  5171. up_read(&fs_info->cleanup_work_sem);
  5172. if (ret) {
  5173. iput(inode);
  5174. inode = ERR_PTR(ret);
  5175. }
  5176. }
  5177. return inode;
  5178. }
  5179. static int btrfs_dentry_delete(const struct dentry *dentry)
  5180. {
  5181. struct btrfs_root *root;
  5182. struct inode *inode = d_inode(dentry);
  5183. if (!inode && !IS_ROOT(dentry))
  5184. inode = d_inode(dentry->d_parent);
  5185. if (inode) {
  5186. root = BTRFS_I(inode)->root;
  5187. if (btrfs_root_refs(&root->root_item) == 0)
  5188. return 1;
  5189. if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
  5190. return 1;
  5191. }
  5192. return 0;
  5193. }
  5194. static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
  5195. unsigned int flags)
  5196. {
  5197. struct inode *inode = btrfs_lookup_dentry(dir, dentry);
  5198. if (inode == ERR_PTR(-ENOENT))
  5199. inode = NULL;
  5200. return d_splice_alias(inode, dentry);
  5201. }
  5202. /*
  5203. * Find the highest existing sequence number in a directory and then set the
  5204. * in-memory index_cnt variable to the first free sequence number.
  5205. */
  5206. static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
  5207. {
  5208. struct btrfs_root *root = inode->root;
  5209. struct btrfs_key key, found_key;
  5210. struct btrfs_path *path;
  5211. struct extent_buffer *leaf;
  5212. int ret;
  5213. key.objectid = btrfs_ino(inode);
  5214. key.type = BTRFS_DIR_INDEX_KEY;
  5215. key.offset = (u64)-1;
  5216. path = btrfs_alloc_path();
  5217. if (!path)
  5218. return -ENOMEM;
  5219. ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
  5220. if (ret < 0)
  5221. goto out;
  5222. /* FIXME: we should be able to handle this */
  5223. if (ret == 0)
  5224. goto out;
  5225. ret = 0;
  5226. if (path->slots[0] == 0) {
  5227. inode->index_cnt = BTRFS_DIR_START_INDEX;
  5228. goto out;
  5229. }
  5230. path->slots[0]--;
  5231. leaf = path->nodes[0];
  5232. btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
  5233. if (found_key.objectid != btrfs_ino(inode) ||
  5234. found_key.type != BTRFS_DIR_INDEX_KEY) {
  5235. inode->index_cnt = BTRFS_DIR_START_INDEX;
  5236. goto out;
  5237. }
  5238. inode->index_cnt = found_key.offset + 1;
  5239. out:
  5240. btrfs_free_path(path);
  5241. return ret;
  5242. }
  5243. static int btrfs_get_dir_last_index(struct btrfs_inode *dir, u64 *index)
  5244. {
  5245. int ret = 0;
  5246. btrfs_inode_lock(dir, 0);
  5247. if (dir->index_cnt == (u64)-1) {
  5248. ret = btrfs_inode_delayed_dir_index_count(dir);
  5249. if (ret) {
  5250. ret = btrfs_set_inode_index_count(dir);
  5251. if (ret)
  5252. goto out;
  5253. }
  5254. }
  5255. /* index_cnt is the index number of next new entry, so decrement it. */
  5256. *index = dir->index_cnt - 1;
  5257. out:
  5258. btrfs_inode_unlock(dir, 0);
  5259. return ret;
  5260. }
  5261. /*
  5262. * All this infrastructure exists because dir_emit can fault, and we are holding
  5263. * the tree lock when doing readdir. For now just allocate a buffer and copy
  5264. * our information into that, and then dir_emit from the buffer. This is
  5265. * similar to what NFS does, only we don't keep the buffer around in pagecache
  5266. * because I'm afraid I'll mess that up. Long term we need to make filldir do
  5267. * copy_to_user_inatomic so we don't have to worry about page faulting under the
  5268. * tree lock.
  5269. */
  5270. static int btrfs_opendir(struct inode *inode, struct file *file)
  5271. {
  5272. struct btrfs_file_private *private;
  5273. u64 last_index;
  5274. int ret;
  5275. ret = btrfs_get_dir_last_index(BTRFS_I(inode), &last_index);
  5276. if (ret)
  5277. return ret;
  5278. private = kzalloc(sizeof(struct btrfs_file_private), GFP_KERNEL);
  5279. if (!private)
  5280. return -ENOMEM;
  5281. private->last_index = last_index;
  5282. private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
  5283. if (!private->filldir_buf) {
  5284. kfree(private);
  5285. return -ENOMEM;
  5286. }
  5287. file->private_data = private;
  5288. return 0;
  5289. }
  5290. static loff_t btrfs_dir_llseek(struct file *file, loff_t offset, int whence)
  5291. {
  5292. struct btrfs_file_private *private = file->private_data;
  5293. int ret;
  5294. ret = btrfs_get_dir_last_index(BTRFS_I(file_inode(file)),
  5295. &private->last_index);
  5296. if (ret)
  5297. return ret;
  5298. return generic_file_llseek(file, offset, whence);
  5299. }
  5300. struct dir_entry {
  5301. u64 ino;
  5302. u64 offset;
  5303. unsigned type;
  5304. int name_len;
  5305. };
  5306. static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
  5307. {
  5308. while (entries--) {
  5309. struct dir_entry *entry = addr;
  5310. char *name = (char *)(entry + 1);
  5311. ctx->pos = get_unaligned(&entry->offset);
  5312. if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
  5313. get_unaligned(&entry->ino),
  5314. get_unaligned(&entry->type)))
  5315. return 1;
  5316. addr += sizeof(struct dir_entry) +
  5317. get_unaligned(&entry->name_len);
  5318. ctx->pos++;
  5319. }
  5320. return 0;
  5321. }
  5322. static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
  5323. {
  5324. struct inode *inode = file_inode(file);
  5325. struct btrfs_root *root = BTRFS_I(inode)->root;
  5326. struct btrfs_file_private *private = file->private_data;
  5327. struct btrfs_dir_item *di;
  5328. struct btrfs_key key;
  5329. struct btrfs_key found_key;
  5330. struct btrfs_path *path;
  5331. void *addr;
  5332. LIST_HEAD(ins_list);
  5333. LIST_HEAD(del_list);
  5334. int ret;
  5335. char *name_ptr;
  5336. int name_len;
  5337. int entries = 0;
  5338. int total_len = 0;
  5339. bool put = false;
  5340. struct btrfs_key location;
  5341. if (!dir_emit_dots(file, ctx))
  5342. return 0;
  5343. path = btrfs_alloc_path();
  5344. if (!path)
  5345. return -ENOMEM;
  5346. addr = private->filldir_buf;
  5347. path->reada = READA_FORWARD;
  5348. put = btrfs_readdir_get_delayed_items(BTRFS_I(inode), private->last_index,
  5349. &ins_list, &del_list);
  5350. again:
  5351. key.type = BTRFS_DIR_INDEX_KEY;
  5352. key.offset = ctx->pos;
  5353. key.objectid = btrfs_ino(BTRFS_I(inode));
  5354. btrfs_for_each_slot(root, &key, &found_key, path, ret) {
  5355. struct dir_entry *entry;
  5356. struct extent_buffer *leaf = path->nodes[0];
  5357. u8 ftype;
  5358. if (found_key.objectid != key.objectid)
  5359. break;
  5360. if (found_key.type != BTRFS_DIR_INDEX_KEY)
  5361. break;
  5362. if (found_key.offset < ctx->pos)
  5363. continue;
  5364. if (found_key.offset > private->last_index)
  5365. break;
  5366. if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
  5367. continue;
  5368. di = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item);
  5369. name_len = btrfs_dir_name_len(leaf, di);
  5370. if ((total_len + sizeof(struct dir_entry) + name_len) >=
  5371. PAGE_SIZE) {
  5372. btrfs_release_path(path);
  5373. ret = btrfs_filldir(private->filldir_buf, entries, ctx);
  5374. if (ret)
  5375. goto nopos;
  5376. addr = private->filldir_buf;
  5377. entries = 0;
  5378. total_len = 0;
  5379. goto again;
  5380. }
  5381. ftype = btrfs_dir_flags_to_ftype(btrfs_dir_flags(leaf, di));
  5382. entry = addr;
  5383. name_ptr = (char *)(entry + 1);
  5384. read_extent_buffer(leaf, name_ptr,
  5385. (unsigned long)(di + 1), name_len);
  5386. put_unaligned(name_len, &entry->name_len);
  5387. put_unaligned(fs_ftype_to_dtype(ftype), &entry->type);
  5388. btrfs_dir_item_key_to_cpu(leaf, di, &location);
  5389. put_unaligned(location.objectid, &entry->ino);
  5390. put_unaligned(found_key.offset, &entry->offset);
  5391. entries++;
  5392. addr += sizeof(struct dir_entry) + name_len;
  5393. total_len += sizeof(struct dir_entry) + name_len;
  5394. }
  5395. /* Catch error encountered during iteration */
  5396. if (ret < 0)
  5397. goto err;
  5398. btrfs_release_path(path);
  5399. ret = btrfs_filldir(private->filldir_buf, entries, ctx);
  5400. if (ret)
  5401. goto nopos;
  5402. ret = btrfs_readdir_delayed_dir_index(ctx, &ins_list);
  5403. if (ret)
  5404. goto nopos;
  5405. /*
  5406. * Stop new entries from being returned after we return the last
  5407. * entry.
  5408. *
  5409. * New directory entries are assigned a strictly increasing
  5410. * offset. This means that new entries created during readdir
  5411. * are *guaranteed* to be seen in the future by that readdir.
  5412. * This has broken buggy programs which operate on names as
  5413. * they're returned by readdir. Until we re-use freed offsets
  5414. * we have this hack to stop new entries from being returned
  5415. * under the assumption that they'll never reach this huge
  5416. * offset.
  5417. *
  5418. * This is being careful not to overflow 32bit loff_t unless the
  5419. * last entry requires it because doing so has broken 32bit apps
  5420. * in the past.
  5421. */
  5422. if (ctx->pos >= INT_MAX)
  5423. ctx->pos = LLONG_MAX;
  5424. else
  5425. ctx->pos = INT_MAX;
  5426. nopos:
  5427. ret = 0;
  5428. err:
  5429. if (put)
  5430. btrfs_readdir_put_delayed_items(BTRFS_I(inode), &ins_list, &del_list);
  5431. btrfs_free_path(path);
  5432. return ret;
  5433. }
  5434. /*
  5435. * This is somewhat expensive, updating the tree every time the
  5436. * inode changes. But, it is most likely to find the inode in cache.
  5437. * FIXME, needs more benchmarking...there are no reasons other than performance
  5438. * to keep or drop this code.
  5439. */
  5440. static int btrfs_dirty_inode(struct btrfs_inode *inode)
  5441. {
  5442. struct btrfs_root *root = inode->root;
  5443. struct btrfs_fs_info *fs_info = root->fs_info;
  5444. struct btrfs_trans_handle *trans;
  5445. int ret;
  5446. if (test_bit(BTRFS_INODE_DUMMY, &inode->runtime_flags))
  5447. return 0;
  5448. trans = btrfs_join_transaction(root);
  5449. if (IS_ERR(trans))
  5450. return PTR_ERR(trans);
  5451. ret = btrfs_update_inode(trans, inode);
  5452. if (ret == -ENOSPC || ret == -EDQUOT) {
  5453. /* whoops, lets try again with the full transaction */
  5454. btrfs_end_transaction(trans);
  5455. trans = btrfs_start_transaction(root, 1);
  5456. if (IS_ERR(trans))
  5457. return PTR_ERR(trans);
  5458. ret = btrfs_update_inode(trans, inode);
  5459. }
  5460. btrfs_end_transaction(trans);
  5461. if (inode->delayed_node)
  5462. btrfs_balance_delayed_items(fs_info);
  5463. return ret;
  5464. }
  5465. /*
  5466. * This is a copy of file_update_time. We need this so we can return error on
  5467. * ENOSPC for updating the inode in the case of file write and mmap writes.
  5468. */
  5469. static int btrfs_update_time(struct inode *inode, int flags)
  5470. {
  5471. struct btrfs_root *root = BTRFS_I(inode)->root;
  5472. bool dirty;
  5473. if (btrfs_root_readonly(root))
  5474. return -EROFS;
  5475. dirty = inode_update_timestamps(inode, flags);
  5476. return dirty ? btrfs_dirty_inode(BTRFS_I(inode)) : 0;
  5477. }
  5478. /*
  5479. * helper to find a free sequence number in a given directory. This current
  5480. * code is very simple, later versions will do smarter things in the btree
  5481. */
  5482. int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
  5483. {
  5484. int ret = 0;
  5485. if (dir->index_cnt == (u64)-1) {
  5486. ret = btrfs_inode_delayed_dir_index_count(dir);
  5487. if (ret) {
  5488. ret = btrfs_set_inode_index_count(dir);
  5489. if (ret)
  5490. return ret;
  5491. }
  5492. }
  5493. *index = dir->index_cnt;
  5494. dir->index_cnt++;
  5495. return ret;
  5496. }
  5497. static int btrfs_insert_inode_locked(struct inode *inode)
  5498. {
  5499. struct btrfs_iget_args args;
  5500. args.ino = btrfs_ino(BTRFS_I(inode));
  5501. args.root = BTRFS_I(inode)->root;
  5502. return insert_inode_locked4(inode,
  5503. btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
  5504. btrfs_find_actor, &args);
  5505. }
  5506. int btrfs_new_inode_prepare(struct btrfs_new_inode_args *args,
  5507. unsigned int *trans_num_items)
  5508. {
  5509. struct inode *dir = args->dir;
  5510. struct inode *inode = args->inode;
  5511. int ret;
  5512. if (!args->orphan) {
  5513. ret = fscrypt_setup_filename(dir, &args->dentry->d_name, 0,
  5514. &args->fname);
  5515. if (ret)
  5516. return ret;
  5517. }
  5518. ret = posix_acl_create(dir, &inode->i_mode, &args->default_acl, &args->acl);
  5519. if (ret) {
  5520. fscrypt_free_filename(&args->fname);
  5521. return ret;
  5522. }
  5523. /* 1 to add inode item */
  5524. *trans_num_items = 1;
  5525. /* 1 to add compression property */
  5526. if (BTRFS_I(dir)->prop_compress)
  5527. (*trans_num_items)++;
  5528. /* 1 to add default ACL xattr */
  5529. if (args->default_acl)
  5530. (*trans_num_items)++;
  5531. /* 1 to add access ACL xattr */
  5532. if (args->acl)
  5533. (*trans_num_items)++;
  5534. #ifdef CONFIG_SECURITY
  5535. /* 1 to add LSM xattr */
  5536. if (dir->i_security)
  5537. (*trans_num_items)++;
  5538. #endif
  5539. if (args->orphan) {
  5540. /* 1 to add orphan item */
  5541. (*trans_num_items)++;
  5542. } else {
  5543. /*
  5544. * 1 to add dir item
  5545. * 1 to add dir index
  5546. * 1 to update parent inode item
  5547. *
  5548. * No need for 1 unit for the inode ref item because it is
  5549. * inserted in a batch together with the inode item at
  5550. * btrfs_create_new_inode().
  5551. */
  5552. *trans_num_items += 3;
  5553. }
  5554. return 0;
  5555. }
  5556. void btrfs_new_inode_args_destroy(struct btrfs_new_inode_args *args)
  5557. {
  5558. posix_acl_release(args->acl);
  5559. posix_acl_release(args->default_acl);
  5560. fscrypt_free_filename(&args->fname);
  5561. }
  5562. /*
  5563. * Inherit flags from the parent inode.
  5564. *
  5565. * Currently only the compression flags and the cow flags are inherited.
  5566. */
  5567. static void btrfs_inherit_iflags(struct btrfs_inode *inode, struct btrfs_inode *dir)
  5568. {
  5569. unsigned int flags;
  5570. flags = dir->flags;
  5571. if (flags & BTRFS_INODE_NOCOMPRESS) {
  5572. inode->flags &= ~BTRFS_INODE_COMPRESS;
  5573. inode->flags |= BTRFS_INODE_NOCOMPRESS;
  5574. } else if (flags & BTRFS_INODE_COMPRESS) {
  5575. inode->flags &= ~BTRFS_INODE_NOCOMPRESS;
  5576. inode->flags |= BTRFS_INODE_COMPRESS;
  5577. }
  5578. if (flags & BTRFS_INODE_NODATACOW) {
  5579. inode->flags |= BTRFS_INODE_NODATACOW;
  5580. if (S_ISREG(inode->vfs_inode.i_mode))
  5581. inode->flags |= BTRFS_INODE_NODATASUM;
  5582. }
  5583. btrfs_sync_inode_flags_to_i_flags(&inode->vfs_inode);
  5584. }
  5585. int btrfs_create_new_inode(struct btrfs_trans_handle *trans,
  5586. struct btrfs_new_inode_args *args)
  5587. {
  5588. struct timespec64 ts;
  5589. struct inode *dir = args->dir;
  5590. struct inode *inode = args->inode;
  5591. const struct fscrypt_str *name = args->orphan ? NULL : &args->fname.disk_name;
  5592. struct btrfs_fs_info *fs_info = inode_to_fs_info(dir);
  5593. struct btrfs_root *root;
  5594. struct btrfs_inode_item *inode_item;
  5595. struct btrfs_path *path;
  5596. u64 objectid;
  5597. struct btrfs_inode_ref *ref;
  5598. struct btrfs_key key[2];
  5599. u32 sizes[2];
  5600. struct btrfs_item_batch batch;
  5601. unsigned long ptr;
  5602. int ret;
  5603. bool xa_reserved = false;
  5604. path = btrfs_alloc_path();
  5605. if (!path)
  5606. return -ENOMEM;
  5607. if (!args->subvol)
  5608. BTRFS_I(inode)->root = btrfs_grab_root(BTRFS_I(dir)->root);
  5609. root = BTRFS_I(inode)->root;
  5610. ret = btrfs_init_file_extent_tree(BTRFS_I(inode));
  5611. if (ret)
  5612. goto out;
  5613. ret = btrfs_get_free_objectid(root, &objectid);
  5614. if (ret)
  5615. goto out;
  5616. btrfs_set_inode_number(BTRFS_I(inode), objectid);
  5617. ret = xa_reserve(&root->inodes, objectid, GFP_NOFS);
  5618. if (ret)
  5619. goto out;
  5620. xa_reserved = true;
  5621. if (args->orphan) {
  5622. /*
  5623. * O_TMPFILE, set link count to 0, so that after this point, we
  5624. * fill in an inode item with the correct link count.
  5625. */
  5626. set_nlink(inode, 0);
  5627. } else {
  5628. trace_btrfs_inode_request(dir);
  5629. ret = btrfs_set_inode_index(BTRFS_I(dir), &BTRFS_I(inode)->dir_index);
  5630. if (ret)
  5631. goto out;
  5632. }
  5633. if (S_ISDIR(inode->i_mode))
  5634. BTRFS_I(inode)->index_cnt = BTRFS_DIR_START_INDEX;
  5635. BTRFS_I(inode)->generation = trans->transid;
  5636. inode->i_generation = BTRFS_I(inode)->generation;
  5637. /*
  5638. * We don't have any capability xattrs set here yet, shortcut any
  5639. * queries for the xattrs here. If we add them later via the inode
  5640. * security init path or any other path this flag will be cleared.
  5641. */
  5642. set_bit(BTRFS_INODE_NO_CAP_XATTR, &BTRFS_I(inode)->runtime_flags);
  5643. /*
  5644. * Subvolumes don't inherit flags from their parent directory.
  5645. * Originally this was probably by accident, but we probably can't
  5646. * change it now without compatibility issues.
  5647. */
  5648. if (!args->subvol)
  5649. btrfs_inherit_iflags(BTRFS_I(inode), BTRFS_I(dir));
  5650. if (S_ISREG(inode->i_mode)) {
  5651. if (btrfs_test_opt(fs_info, NODATASUM))
  5652. BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
  5653. if (btrfs_test_opt(fs_info, NODATACOW))
  5654. BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
  5655. BTRFS_INODE_NODATASUM;
  5656. }
  5657. ret = btrfs_insert_inode_locked(inode);
  5658. if (ret < 0) {
  5659. if (!args->orphan)
  5660. BTRFS_I(dir)->index_cnt--;
  5661. goto out;
  5662. }
  5663. /*
  5664. * We could have gotten an inode number from somebody who was fsynced
  5665. * and then removed in this same transaction, so let's just set full
  5666. * sync since it will be a full sync anyway and this will blow away the
  5667. * old info in the log.
  5668. */
  5669. btrfs_set_inode_full_sync(BTRFS_I(inode));
  5670. key[0].objectid = objectid;
  5671. key[0].type = BTRFS_INODE_ITEM_KEY;
  5672. key[0].offset = 0;
  5673. sizes[0] = sizeof(struct btrfs_inode_item);
  5674. if (!args->orphan) {
  5675. /*
  5676. * Start new inodes with an inode_ref. This is slightly more
  5677. * efficient for small numbers of hard links since they will
  5678. * be packed into one item. Extended refs will kick in if we
  5679. * add more hard links than can fit in the ref item.
  5680. */
  5681. key[1].objectid = objectid;
  5682. key[1].type = BTRFS_INODE_REF_KEY;
  5683. if (args->subvol) {
  5684. key[1].offset = objectid;
  5685. sizes[1] = 2 + sizeof(*ref);
  5686. } else {
  5687. key[1].offset = btrfs_ino(BTRFS_I(dir));
  5688. sizes[1] = name->len + sizeof(*ref);
  5689. }
  5690. }
  5691. batch.keys = &key[0];
  5692. batch.data_sizes = &sizes[0];
  5693. batch.total_data_size = sizes[0] + (args->orphan ? 0 : sizes[1]);
  5694. batch.nr = args->orphan ? 1 : 2;
  5695. ret = btrfs_insert_empty_items(trans, root, path, &batch);
  5696. if (ret != 0) {
  5697. btrfs_abort_transaction(trans, ret);
  5698. goto discard;
  5699. }
  5700. ts = simple_inode_init_ts(inode);
  5701. BTRFS_I(inode)->i_otime_sec = ts.tv_sec;
  5702. BTRFS_I(inode)->i_otime_nsec = ts.tv_nsec;
  5703. /*
  5704. * We're going to fill the inode item now, so at this point the inode
  5705. * must be fully initialized.
  5706. */
  5707. inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
  5708. struct btrfs_inode_item);
  5709. memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
  5710. sizeof(*inode_item));
  5711. fill_inode_item(trans, path->nodes[0], inode_item, inode);
  5712. if (!args->orphan) {
  5713. ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
  5714. struct btrfs_inode_ref);
  5715. ptr = (unsigned long)(ref + 1);
  5716. if (args->subvol) {
  5717. btrfs_set_inode_ref_name_len(path->nodes[0], ref, 2);
  5718. btrfs_set_inode_ref_index(path->nodes[0], ref, 0);
  5719. write_extent_buffer(path->nodes[0], "..", ptr, 2);
  5720. } else {
  5721. btrfs_set_inode_ref_name_len(path->nodes[0], ref,
  5722. name->len);
  5723. btrfs_set_inode_ref_index(path->nodes[0], ref,
  5724. BTRFS_I(inode)->dir_index);
  5725. write_extent_buffer(path->nodes[0], name->name, ptr,
  5726. name->len);
  5727. }
  5728. }
  5729. btrfs_mark_buffer_dirty(trans, path->nodes[0]);
  5730. /*
  5731. * We don't need the path anymore, plus inheriting properties, adding
  5732. * ACLs, security xattrs, orphan item or adding the link, will result in
  5733. * allocating yet another path. So just free our path.
  5734. */
  5735. btrfs_free_path(path);
  5736. path = NULL;
  5737. if (args->subvol) {
  5738. struct inode *parent;
  5739. /*
  5740. * Subvolumes inherit properties from their parent subvolume,
  5741. * not the directory they were created in.
  5742. */
  5743. parent = btrfs_iget(BTRFS_FIRST_FREE_OBJECTID, BTRFS_I(dir)->root);
  5744. if (IS_ERR(parent)) {
  5745. ret = PTR_ERR(parent);
  5746. } else {
  5747. ret = btrfs_inode_inherit_props(trans, inode, parent);
  5748. iput(parent);
  5749. }
  5750. } else {
  5751. ret = btrfs_inode_inherit_props(trans, inode, dir);
  5752. }
  5753. if (ret) {
  5754. btrfs_err(fs_info,
  5755. "error inheriting props for ino %llu (root %llu): %d",
  5756. btrfs_ino(BTRFS_I(inode)), btrfs_root_id(root), ret);
  5757. }
  5758. /*
  5759. * Subvolumes don't inherit ACLs or get passed to the LSM. This is
  5760. * probably a bug.
  5761. */
  5762. if (!args->subvol) {
  5763. ret = btrfs_init_inode_security(trans, args);
  5764. if (ret) {
  5765. btrfs_abort_transaction(trans, ret);
  5766. goto discard;
  5767. }
  5768. }
  5769. ret = btrfs_add_inode_to_root(BTRFS_I(inode), false);
  5770. if (WARN_ON(ret)) {
  5771. /* Shouldn't happen, we used xa_reserve() before. */
  5772. btrfs_abort_transaction(trans, ret);
  5773. goto discard;
  5774. }
  5775. trace_btrfs_inode_new(inode);
  5776. btrfs_set_inode_last_trans(trans, BTRFS_I(inode));
  5777. btrfs_update_root_times(trans, root);
  5778. if (args->orphan) {
  5779. ret = btrfs_orphan_add(trans, BTRFS_I(inode));
  5780. } else {
  5781. ret = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode), name,
  5782. 0, BTRFS_I(inode)->dir_index);
  5783. }
  5784. if (ret) {
  5785. btrfs_abort_transaction(trans, ret);
  5786. goto discard;
  5787. }
  5788. return 0;
  5789. discard:
  5790. /*
  5791. * discard_new_inode() calls iput(), but the caller owns the reference
  5792. * to the inode.
  5793. */
  5794. ihold(inode);
  5795. discard_new_inode(inode);
  5796. out:
  5797. if (xa_reserved)
  5798. xa_release(&root->inodes, objectid);
  5799. btrfs_free_path(path);
  5800. return ret;
  5801. }
  5802. /*
  5803. * utility function to add 'inode' into 'parent_inode' with
  5804. * a give name and a given sequence number.
  5805. * if 'add_backref' is true, also insert a backref from the
  5806. * inode to the parent directory.
  5807. */
  5808. int btrfs_add_link(struct btrfs_trans_handle *trans,
  5809. struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
  5810. const struct fscrypt_str *name, int add_backref, u64 index)
  5811. {
  5812. int ret = 0;
  5813. struct btrfs_key key;
  5814. struct btrfs_root *root = parent_inode->root;
  5815. u64 ino = btrfs_ino(inode);
  5816. u64 parent_ino = btrfs_ino(parent_inode);
  5817. if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
  5818. memcpy(&key, &inode->root->root_key, sizeof(key));
  5819. } else {
  5820. key.objectid = ino;
  5821. key.type = BTRFS_INODE_ITEM_KEY;
  5822. key.offset = 0;
  5823. }
  5824. if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
  5825. ret = btrfs_add_root_ref(trans, key.objectid,
  5826. btrfs_root_id(root), parent_ino,
  5827. index, name);
  5828. } else if (add_backref) {
  5829. ret = btrfs_insert_inode_ref(trans, root, name,
  5830. ino, parent_ino, index);
  5831. }
  5832. /* Nothing to clean up yet */
  5833. if (ret)
  5834. return ret;
  5835. ret = btrfs_insert_dir_item(trans, name, parent_inode, &key,
  5836. btrfs_inode_type(&inode->vfs_inode), index);
  5837. if (ret == -EEXIST || ret == -EOVERFLOW)
  5838. goto fail_dir_item;
  5839. else if (ret) {
  5840. btrfs_abort_transaction(trans, ret);
  5841. return ret;
  5842. }
  5843. btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
  5844. name->len * 2);
  5845. inode_inc_iversion(&parent_inode->vfs_inode);
  5846. /*
  5847. * If we are replaying a log tree, we do not want to update the mtime
  5848. * and ctime of the parent directory with the current time, since the
  5849. * log replay procedure is responsible for setting them to their correct
  5850. * values (the ones it had when the fsync was done).
  5851. */
  5852. if (!test_bit(BTRFS_FS_LOG_RECOVERING, &root->fs_info->flags))
  5853. inode_set_mtime_to_ts(&parent_inode->vfs_inode,
  5854. inode_set_ctime_current(&parent_inode->vfs_inode));
  5855. ret = btrfs_update_inode(trans, parent_inode);
  5856. if (ret)
  5857. btrfs_abort_transaction(trans, ret);
  5858. return ret;
  5859. fail_dir_item:
  5860. if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
  5861. u64 local_index;
  5862. int err;
  5863. err = btrfs_del_root_ref(trans, key.objectid,
  5864. btrfs_root_id(root), parent_ino,
  5865. &local_index, name);
  5866. if (err)
  5867. btrfs_abort_transaction(trans, err);
  5868. } else if (add_backref) {
  5869. u64 local_index;
  5870. int err;
  5871. err = btrfs_del_inode_ref(trans, root, name, ino, parent_ino,
  5872. &local_index);
  5873. if (err)
  5874. btrfs_abort_transaction(trans, err);
  5875. }
  5876. /* Return the original error code */
  5877. return ret;
  5878. }
  5879. static int btrfs_create_common(struct inode *dir, struct dentry *dentry,
  5880. struct inode *inode)
  5881. {
  5882. struct btrfs_fs_info *fs_info = inode_to_fs_info(dir);
  5883. struct btrfs_root *root = BTRFS_I(dir)->root;
  5884. struct btrfs_new_inode_args new_inode_args = {
  5885. .dir = dir,
  5886. .dentry = dentry,
  5887. .inode = inode,
  5888. };
  5889. unsigned int trans_num_items;
  5890. struct btrfs_trans_handle *trans;
  5891. int err;
  5892. err = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
  5893. if (err)
  5894. goto out_inode;
  5895. trans = btrfs_start_transaction(root, trans_num_items);
  5896. if (IS_ERR(trans)) {
  5897. err = PTR_ERR(trans);
  5898. goto out_new_inode_args;
  5899. }
  5900. err = btrfs_create_new_inode(trans, &new_inode_args);
  5901. if (!err)
  5902. d_instantiate_new(dentry, inode);
  5903. btrfs_end_transaction(trans);
  5904. btrfs_btree_balance_dirty(fs_info);
  5905. out_new_inode_args:
  5906. btrfs_new_inode_args_destroy(&new_inode_args);
  5907. out_inode:
  5908. if (err)
  5909. iput(inode);
  5910. return err;
  5911. }
  5912. static int btrfs_mknod(struct mnt_idmap *idmap, struct inode *dir,
  5913. struct dentry *dentry, umode_t mode, dev_t rdev)
  5914. {
  5915. struct inode *inode;
  5916. inode = new_inode(dir->i_sb);
  5917. if (!inode)
  5918. return -ENOMEM;
  5919. inode_init_owner(idmap, inode, dir, mode);
  5920. inode->i_op = &btrfs_special_inode_operations;
  5921. init_special_inode(inode, inode->i_mode, rdev);
  5922. return btrfs_create_common(dir, dentry, inode);
  5923. }
  5924. static int btrfs_create(struct mnt_idmap *idmap, struct inode *dir,
  5925. struct dentry *dentry, umode_t mode, bool excl)
  5926. {
  5927. struct inode *inode;
  5928. inode = new_inode(dir->i_sb);
  5929. if (!inode)
  5930. return -ENOMEM;
  5931. inode_init_owner(idmap, inode, dir, mode);
  5932. inode->i_fop = &btrfs_file_operations;
  5933. inode->i_op = &btrfs_file_inode_operations;
  5934. inode->i_mapping->a_ops = &btrfs_aops;
  5935. return btrfs_create_common(dir, dentry, inode);
  5936. }
  5937. static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
  5938. struct dentry *dentry)
  5939. {
  5940. struct btrfs_trans_handle *trans = NULL;
  5941. struct btrfs_root *root = BTRFS_I(dir)->root;
  5942. struct inode *inode = d_inode(old_dentry);
  5943. struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
  5944. struct fscrypt_name fname;
  5945. u64 index;
  5946. int err;
  5947. int drop_inode = 0;
  5948. /* do not allow sys_link's with other subvols of the same device */
  5949. if (btrfs_root_id(root) != btrfs_root_id(BTRFS_I(inode)->root))
  5950. return -EXDEV;
  5951. if (inode->i_nlink >= BTRFS_LINK_MAX)
  5952. return -EMLINK;
  5953. err = fscrypt_setup_filename(dir, &dentry->d_name, 0, &fname);
  5954. if (err)
  5955. goto fail;
  5956. err = btrfs_set_inode_index(BTRFS_I(dir), &index);
  5957. if (err)
  5958. goto fail;
  5959. /*
  5960. * 2 items for inode and inode ref
  5961. * 2 items for dir items
  5962. * 1 item for parent inode
  5963. * 1 item for orphan item deletion if O_TMPFILE
  5964. */
  5965. trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
  5966. if (IS_ERR(trans)) {
  5967. err = PTR_ERR(trans);
  5968. trans = NULL;
  5969. goto fail;
  5970. }
  5971. /* There are several dir indexes for this inode, clear the cache. */
  5972. BTRFS_I(inode)->dir_index = 0ULL;
  5973. inc_nlink(inode);
  5974. inode_inc_iversion(inode);
  5975. inode_set_ctime_current(inode);
  5976. ihold(inode);
  5977. set_bit(BTRFS_INODE_COPY_EVERYTHING, &BTRFS_I(inode)->runtime_flags);
  5978. err = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
  5979. &fname.disk_name, 1, index);
  5980. if (err) {
  5981. drop_inode = 1;
  5982. } else {
  5983. struct dentry *parent = dentry->d_parent;
  5984. err = btrfs_update_inode(trans, BTRFS_I(inode));
  5985. if (err)
  5986. goto fail;
  5987. if (inode->i_nlink == 1) {
  5988. /*
  5989. * If new hard link count is 1, it's a file created
  5990. * with open(2) O_TMPFILE flag.
  5991. */
  5992. err = btrfs_orphan_del(trans, BTRFS_I(inode));
  5993. if (err)
  5994. goto fail;
  5995. }
  5996. d_instantiate(dentry, inode);
  5997. btrfs_log_new_name(trans, old_dentry, NULL, 0, parent);
  5998. }
  5999. fail:
  6000. fscrypt_free_filename(&fname);
  6001. if (trans)
  6002. btrfs_end_transaction(trans);
  6003. if (drop_inode) {
  6004. inode_dec_link_count(inode);
  6005. iput(inode);
  6006. }
  6007. btrfs_btree_balance_dirty(fs_info);
  6008. return err;
  6009. }
  6010. static int btrfs_mkdir(struct mnt_idmap *idmap, struct inode *dir,
  6011. struct dentry *dentry, umode_t mode)
  6012. {
  6013. struct inode *inode;
  6014. inode = new_inode(dir->i_sb);
  6015. if (!inode)
  6016. return -ENOMEM;
  6017. inode_init_owner(idmap, inode, dir, S_IFDIR | mode);
  6018. inode->i_op = &btrfs_dir_inode_operations;
  6019. inode->i_fop = &btrfs_dir_file_operations;
  6020. return btrfs_create_common(dir, dentry, inode);
  6021. }
  6022. static noinline int uncompress_inline(struct btrfs_path *path,
  6023. struct folio *folio,
  6024. struct btrfs_file_extent_item *item)
  6025. {
  6026. int ret;
  6027. struct extent_buffer *leaf = path->nodes[0];
  6028. char *tmp;
  6029. size_t max_size;
  6030. unsigned long inline_size;
  6031. unsigned long ptr;
  6032. int compress_type;
  6033. compress_type = btrfs_file_extent_compression(leaf, item);
  6034. max_size = btrfs_file_extent_ram_bytes(leaf, item);
  6035. inline_size = btrfs_file_extent_inline_item_len(leaf, path->slots[0]);
  6036. tmp = kmalloc(inline_size, GFP_NOFS);
  6037. if (!tmp)
  6038. return -ENOMEM;
  6039. ptr = btrfs_file_extent_inline_start(item);
  6040. read_extent_buffer(leaf, tmp, ptr, inline_size);
  6041. max_size = min_t(unsigned long, PAGE_SIZE, max_size);
  6042. ret = btrfs_decompress(compress_type, tmp, folio, 0, inline_size,
  6043. max_size);
  6044. /*
  6045. * decompression code contains a memset to fill in any space between the end
  6046. * of the uncompressed data and the end of max_size in case the decompressed
  6047. * data ends up shorter than ram_bytes. That doesn't cover the hole between
  6048. * the end of an inline extent and the beginning of the next block, so we
  6049. * cover that region here.
  6050. */
  6051. if (max_size < PAGE_SIZE)
  6052. folio_zero_range(folio, max_size, PAGE_SIZE - max_size);
  6053. kfree(tmp);
  6054. return ret;
  6055. }
  6056. static int read_inline_extent(struct btrfs_inode *inode, struct btrfs_path *path,
  6057. struct folio *folio)
  6058. {
  6059. struct btrfs_file_extent_item *fi;
  6060. void *kaddr;
  6061. size_t copy_size;
  6062. if (!folio || folio_test_uptodate(folio))
  6063. return 0;
  6064. ASSERT(folio_pos(folio) == 0);
  6065. fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
  6066. struct btrfs_file_extent_item);
  6067. if (btrfs_file_extent_compression(path->nodes[0], fi) != BTRFS_COMPRESS_NONE)
  6068. return uncompress_inline(path, folio, fi);
  6069. copy_size = min_t(u64, PAGE_SIZE,
  6070. btrfs_file_extent_ram_bytes(path->nodes[0], fi));
  6071. kaddr = kmap_local_folio(folio, 0);
  6072. read_extent_buffer(path->nodes[0], kaddr,
  6073. btrfs_file_extent_inline_start(fi), copy_size);
  6074. kunmap_local(kaddr);
  6075. if (copy_size < PAGE_SIZE)
  6076. folio_zero_range(folio, copy_size, PAGE_SIZE - copy_size);
  6077. return 0;
  6078. }
  6079. /*
  6080. * Lookup the first extent overlapping a range in a file.
  6081. *
  6082. * @inode: file to search in
  6083. * @page: page to read extent data into if the extent is inline
  6084. * @start: file offset
  6085. * @len: length of range starting at @start
  6086. *
  6087. * Return the first &struct extent_map which overlaps the given range, reading
  6088. * it from the B-tree and caching it if necessary. Note that there may be more
  6089. * extents which overlap the given range after the returned extent_map.
  6090. *
  6091. * If @page is not NULL and the extent is inline, this also reads the extent
  6092. * data directly into the page and marks the extent up to date in the io_tree.
  6093. *
  6094. * Return: ERR_PTR on error, non-NULL extent_map on success.
  6095. */
  6096. struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
  6097. struct folio *folio, u64 start, u64 len)
  6098. {
  6099. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  6100. int ret = 0;
  6101. u64 extent_start = 0;
  6102. u64 extent_end = 0;
  6103. u64 objectid = btrfs_ino(inode);
  6104. int extent_type = -1;
  6105. struct btrfs_path *path = NULL;
  6106. struct btrfs_root *root = inode->root;
  6107. struct btrfs_file_extent_item *item;
  6108. struct extent_buffer *leaf;
  6109. struct btrfs_key found_key;
  6110. struct extent_map *em = NULL;
  6111. struct extent_map_tree *em_tree = &inode->extent_tree;
  6112. read_lock(&em_tree->lock);
  6113. em = lookup_extent_mapping(em_tree, start, len);
  6114. read_unlock(&em_tree->lock);
  6115. if (em) {
  6116. if (em->start > start || em->start + em->len <= start)
  6117. free_extent_map(em);
  6118. else if (em->disk_bytenr == EXTENT_MAP_INLINE && folio)
  6119. free_extent_map(em);
  6120. else
  6121. goto out;
  6122. }
  6123. em = alloc_extent_map();
  6124. if (!em) {
  6125. ret = -ENOMEM;
  6126. goto out;
  6127. }
  6128. em->start = EXTENT_MAP_HOLE;
  6129. em->disk_bytenr = EXTENT_MAP_HOLE;
  6130. em->len = (u64)-1;
  6131. path = btrfs_alloc_path();
  6132. if (!path) {
  6133. ret = -ENOMEM;
  6134. goto out;
  6135. }
  6136. /* Chances are we'll be called again, so go ahead and do readahead */
  6137. path->reada = READA_FORWARD;
  6138. /*
  6139. * The same explanation in load_free_space_cache applies here as well,
  6140. * we only read when we're loading the free space cache, and at that
  6141. * point the commit_root has everything we need.
  6142. */
  6143. if (btrfs_is_free_space_inode(inode)) {
  6144. path->search_commit_root = 1;
  6145. path->skip_locking = 1;
  6146. }
  6147. ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
  6148. if (ret < 0) {
  6149. goto out;
  6150. } else if (ret > 0) {
  6151. if (path->slots[0] == 0)
  6152. goto not_found;
  6153. path->slots[0]--;
  6154. ret = 0;
  6155. }
  6156. leaf = path->nodes[0];
  6157. item = btrfs_item_ptr(leaf, path->slots[0],
  6158. struct btrfs_file_extent_item);
  6159. btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
  6160. if (found_key.objectid != objectid ||
  6161. found_key.type != BTRFS_EXTENT_DATA_KEY) {
  6162. /*
  6163. * If we backup past the first extent we want to move forward
  6164. * and see if there is an extent in front of us, otherwise we'll
  6165. * say there is a hole for our whole search range which can
  6166. * cause problems.
  6167. */
  6168. extent_end = start;
  6169. goto next;
  6170. }
  6171. extent_type = btrfs_file_extent_type(leaf, item);
  6172. extent_start = found_key.offset;
  6173. extent_end = btrfs_file_extent_end(path);
  6174. if (extent_type == BTRFS_FILE_EXTENT_REG ||
  6175. extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
  6176. /* Only regular file could have regular/prealloc extent */
  6177. if (!S_ISREG(inode->vfs_inode.i_mode)) {
  6178. ret = -EUCLEAN;
  6179. btrfs_crit(fs_info,
  6180. "regular/prealloc extent found for non-regular inode %llu",
  6181. btrfs_ino(inode));
  6182. goto out;
  6183. }
  6184. trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
  6185. extent_start);
  6186. } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
  6187. trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
  6188. path->slots[0],
  6189. extent_start);
  6190. }
  6191. next:
  6192. if (start >= extent_end) {
  6193. path->slots[0]++;
  6194. if (path->slots[0] >= btrfs_header_nritems(leaf)) {
  6195. ret = btrfs_next_leaf(root, path);
  6196. if (ret < 0)
  6197. goto out;
  6198. else if (ret > 0)
  6199. goto not_found;
  6200. leaf = path->nodes[0];
  6201. }
  6202. btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
  6203. if (found_key.objectid != objectid ||
  6204. found_key.type != BTRFS_EXTENT_DATA_KEY)
  6205. goto not_found;
  6206. if (start + len <= found_key.offset)
  6207. goto not_found;
  6208. if (start > found_key.offset)
  6209. goto next;
  6210. /* New extent overlaps with existing one */
  6211. em->start = start;
  6212. em->len = found_key.offset - start;
  6213. em->disk_bytenr = EXTENT_MAP_HOLE;
  6214. goto insert;
  6215. }
  6216. btrfs_extent_item_to_extent_map(inode, path, item, em);
  6217. if (extent_type == BTRFS_FILE_EXTENT_REG ||
  6218. extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
  6219. goto insert;
  6220. } else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
  6221. /*
  6222. * Inline extent can only exist at file offset 0. This is
  6223. * ensured by tree-checker and inline extent creation path.
  6224. * Thus all members representing file offsets should be zero.
  6225. */
  6226. ASSERT(extent_start == 0);
  6227. ASSERT(em->start == 0);
  6228. /*
  6229. * btrfs_extent_item_to_extent_map() should have properly
  6230. * initialized em members already.
  6231. *
  6232. * Other members are not utilized for inline extents.
  6233. */
  6234. ASSERT(em->disk_bytenr == EXTENT_MAP_INLINE);
  6235. ASSERT(em->len == fs_info->sectorsize);
  6236. ret = read_inline_extent(inode, path, folio);
  6237. if (ret < 0)
  6238. goto out;
  6239. goto insert;
  6240. }
  6241. not_found:
  6242. em->start = start;
  6243. em->len = len;
  6244. em->disk_bytenr = EXTENT_MAP_HOLE;
  6245. insert:
  6246. ret = 0;
  6247. btrfs_release_path(path);
  6248. if (em->start > start || extent_map_end(em) <= start) {
  6249. btrfs_err(fs_info,
  6250. "bad extent! em: [%llu %llu] passed [%llu %llu]",
  6251. em->start, em->len, start, len);
  6252. ret = -EIO;
  6253. goto out;
  6254. }
  6255. write_lock(&em_tree->lock);
  6256. ret = btrfs_add_extent_mapping(inode, &em, start, len);
  6257. write_unlock(&em_tree->lock);
  6258. out:
  6259. btrfs_free_path(path);
  6260. trace_btrfs_get_extent(root, inode, em);
  6261. if (ret) {
  6262. free_extent_map(em);
  6263. return ERR_PTR(ret);
  6264. }
  6265. return em;
  6266. }
  6267. static bool btrfs_extent_readonly(struct btrfs_fs_info *fs_info, u64 bytenr)
  6268. {
  6269. struct btrfs_block_group *block_group;
  6270. bool readonly = false;
  6271. block_group = btrfs_lookup_block_group(fs_info, bytenr);
  6272. if (!block_group || block_group->ro)
  6273. readonly = true;
  6274. if (block_group)
  6275. btrfs_put_block_group(block_group);
  6276. return readonly;
  6277. }
  6278. /*
  6279. * Check if we can do nocow write into the range [@offset, @offset + @len)
  6280. *
  6281. * @offset: File offset
  6282. * @len: The length to write, will be updated to the nocow writeable
  6283. * range
  6284. * @orig_start: (optional) Return the original file offset of the file extent
  6285. * @orig_len: (optional) Return the original on-disk length of the file extent
  6286. * @ram_bytes: (optional) Return the ram_bytes of the file extent
  6287. * @strict: if true, omit optimizations that might force us into unnecessary
  6288. * cow. e.g., don't trust generation number.
  6289. *
  6290. * Return:
  6291. * >0 and update @len if we can do nocow write
  6292. * 0 if we can't do nocow write
  6293. * <0 if error happened
  6294. *
  6295. * NOTE: This only checks the file extents, caller is responsible to wait for
  6296. * any ordered extents.
  6297. */
  6298. noinline int can_nocow_extent(struct inode *inode, u64 offset, u64 *len,
  6299. struct btrfs_file_extent *file_extent,
  6300. bool nowait, bool strict)
  6301. {
  6302. struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
  6303. struct can_nocow_file_extent_args nocow_args = { 0 };
  6304. struct btrfs_path *path;
  6305. int ret;
  6306. struct extent_buffer *leaf;
  6307. struct btrfs_root *root = BTRFS_I(inode)->root;
  6308. struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
  6309. struct btrfs_file_extent_item *fi;
  6310. struct btrfs_key key;
  6311. int found_type;
  6312. path = btrfs_alloc_path();
  6313. if (!path)
  6314. return -ENOMEM;
  6315. path->nowait = nowait;
  6316. ret = btrfs_lookup_file_extent(NULL, root, path,
  6317. btrfs_ino(BTRFS_I(inode)), offset, 0);
  6318. if (ret < 0)
  6319. goto out;
  6320. if (ret == 1) {
  6321. if (path->slots[0] == 0) {
  6322. /* can't find the item, must cow */
  6323. ret = 0;
  6324. goto out;
  6325. }
  6326. path->slots[0]--;
  6327. }
  6328. ret = 0;
  6329. leaf = path->nodes[0];
  6330. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  6331. if (key.objectid != btrfs_ino(BTRFS_I(inode)) ||
  6332. key.type != BTRFS_EXTENT_DATA_KEY) {
  6333. /* not our file or wrong item type, must cow */
  6334. goto out;
  6335. }
  6336. if (key.offset > offset) {
  6337. /* Wrong offset, must cow */
  6338. goto out;
  6339. }
  6340. if (btrfs_file_extent_end(path) <= offset)
  6341. goto out;
  6342. fi = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
  6343. found_type = btrfs_file_extent_type(leaf, fi);
  6344. nocow_args.start = offset;
  6345. nocow_args.end = offset + *len - 1;
  6346. nocow_args.strict = strict;
  6347. nocow_args.free_path = true;
  6348. ret = can_nocow_file_extent(path, &key, BTRFS_I(inode), &nocow_args);
  6349. /* can_nocow_file_extent() has freed the path. */
  6350. path = NULL;
  6351. if (ret != 1) {
  6352. /* Treat errors as not being able to NOCOW. */
  6353. ret = 0;
  6354. goto out;
  6355. }
  6356. ret = 0;
  6357. if (btrfs_extent_readonly(fs_info,
  6358. nocow_args.file_extent.disk_bytenr +
  6359. nocow_args.file_extent.offset))
  6360. goto out;
  6361. if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW) &&
  6362. found_type == BTRFS_FILE_EXTENT_PREALLOC) {
  6363. u64 range_end;
  6364. range_end = round_up(offset + nocow_args.file_extent.num_bytes,
  6365. root->fs_info->sectorsize) - 1;
  6366. ret = test_range_bit_exists(io_tree, offset, range_end, EXTENT_DELALLOC);
  6367. if (ret) {
  6368. ret = -EAGAIN;
  6369. goto out;
  6370. }
  6371. }
  6372. if (file_extent)
  6373. memcpy(file_extent, &nocow_args.file_extent, sizeof(*file_extent));
  6374. *len = nocow_args.file_extent.num_bytes;
  6375. ret = 1;
  6376. out:
  6377. btrfs_free_path(path);
  6378. return ret;
  6379. }
  6380. /* The callers of this must take lock_extent() */
  6381. struct extent_map *btrfs_create_io_em(struct btrfs_inode *inode, u64 start,
  6382. const struct btrfs_file_extent *file_extent,
  6383. int type)
  6384. {
  6385. struct extent_map *em;
  6386. int ret;
  6387. /*
  6388. * Note the missing NOCOW type.
  6389. *
  6390. * For pure NOCOW writes, we should not create an io extent map, but
  6391. * just reusing the existing one.
  6392. * Only PREALLOC writes (NOCOW write into preallocated range) can
  6393. * create an io extent map.
  6394. */
  6395. ASSERT(type == BTRFS_ORDERED_PREALLOC ||
  6396. type == BTRFS_ORDERED_COMPRESSED ||
  6397. type == BTRFS_ORDERED_REGULAR);
  6398. switch (type) {
  6399. case BTRFS_ORDERED_PREALLOC:
  6400. /* We're only referring part of a larger preallocated extent. */
  6401. ASSERT(file_extent->num_bytes <= file_extent->ram_bytes);
  6402. break;
  6403. case BTRFS_ORDERED_REGULAR:
  6404. /* COW results a new extent matching our file extent size. */
  6405. ASSERT(file_extent->disk_num_bytes == file_extent->num_bytes);
  6406. ASSERT(file_extent->ram_bytes == file_extent->num_bytes);
  6407. /* Since it's a new extent, we should not have any offset. */
  6408. ASSERT(file_extent->offset == 0);
  6409. break;
  6410. case BTRFS_ORDERED_COMPRESSED:
  6411. /* Must be compressed. */
  6412. ASSERT(file_extent->compression != BTRFS_COMPRESS_NONE);
  6413. /*
  6414. * Encoded write can make us to refer to part of the
  6415. * uncompressed extent.
  6416. */
  6417. ASSERT(file_extent->num_bytes <= file_extent->ram_bytes);
  6418. break;
  6419. }
  6420. em = alloc_extent_map();
  6421. if (!em)
  6422. return ERR_PTR(-ENOMEM);
  6423. em->start = start;
  6424. em->len = file_extent->num_bytes;
  6425. em->disk_bytenr = file_extent->disk_bytenr;
  6426. em->disk_num_bytes = file_extent->disk_num_bytes;
  6427. em->ram_bytes = file_extent->ram_bytes;
  6428. em->generation = -1;
  6429. em->offset = file_extent->offset;
  6430. em->flags |= EXTENT_FLAG_PINNED;
  6431. if (type == BTRFS_ORDERED_COMPRESSED)
  6432. extent_map_set_compression(em, file_extent->compression);
  6433. ret = btrfs_replace_extent_map_range(inode, em, true);
  6434. if (ret) {
  6435. free_extent_map(em);
  6436. return ERR_PTR(ret);
  6437. }
  6438. /* em got 2 refs now, callers needs to do free_extent_map once. */
  6439. return em;
  6440. }
  6441. /*
  6442. * For release_folio() and invalidate_folio() we have a race window where
  6443. * folio_end_writeback() is called but the subpage spinlock is not yet released.
  6444. * If we continue to release/invalidate the page, we could cause use-after-free
  6445. * for subpage spinlock. So this function is to spin and wait for subpage
  6446. * spinlock.
  6447. */
  6448. static void wait_subpage_spinlock(struct folio *folio)
  6449. {
  6450. struct btrfs_fs_info *fs_info = folio_to_fs_info(folio);
  6451. struct btrfs_subpage *subpage;
  6452. if (!btrfs_is_subpage(fs_info, folio->mapping))
  6453. return;
  6454. ASSERT(folio_test_private(folio) && folio_get_private(folio));
  6455. subpage = folio_get_private(folio);
  6456. /*
  6457. * This may look insane as we just acquire the spinlock and release it,
  6458. * without doing anything. But we just want to make sure no one is
  6459. * still holding the subpage spinlock.
  6460. * And since the page is not dirty nor writeback, and we have page
  6461. * locked, the only possible way to hold a spinlock is from the endio
  6462. * function to clear page writeback.
  6463. *
  6464. * Here we just acquire the spinlock so that all existing callers
  6465. * should exit and we're safe to release/invalidate the page.
  6466. */
  6467. spin_lock_irq(&subpage->lock);
  6468. spin_unlock_irq(&subpage->lock);
  6469. }
  6470. static int btrfs_launder_folio(struct folio *folio)
  6471. {
  6472. return btrfs_qgroup_free_data(folio_to_inode(folio), NULL, folio_pos(folio),
  6473. PAGE_SIZE, NULL);
  6474. }
  6475. static bool __btrfs_release_folio(struct folio *folio, gfp_t gfp_flags)
  6476. {
  6477. if (try_release_extent_mapping(folio, gfp_flags)) {
  6478. wait_subpage_spinlock(folio);
  6479. clear_folio_extent_mapped(folio);
  6480. return true;
  6481. }
  6482. return false;
  6483. }
  6484. static bool btrfs_release_folio(struct folio *folio, gfp_t gfp_flags)
  6485. {
  6486. if (folio_test_writeback(folio) || folio_test_dirty(folio))
  6487. return false;
  6488. return __btrfs_release_folio(folio, gfp_flags);
  6489. }
  6490. #ifdef CONFIG_MIGRATION
  6491. static int btrfs_migrate_folio(struct address_space *mapping,
  6492. struct folio *dst, struct folio *src,
  6493. enum migrate_mode mode)
  6494. {
  6495. int ret = filemap_migrate_folio(mapping, dst, src, mode);
  6496. if (ret != MIGRATEPAGE_SUCCESS)
  6497. return ret;
  6498. if (folio_test_ordered(src)) {
  6499. folio_clear_ordered(src);
  6500. folio_set_ordered(dst);
  6501. }
  6502. return MIGRATEPAGE_SUCCESS;
  6503. }
  6504. #else
  6505. #define btrfs_migrate_folio NULL
  6506. #endif
  6507. static void btrfs_invalidate_folio(struct folio *folio, size_t offset,
  6508. size_t length)
  6509. {
  6510. struct btrfs_inode *inode = folio_to_inode(folio);
  6511. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  6512. struct extent_io_tree *tree = &inode->io_tree;
  6513. struct extent_state *cached_state = NULL;
  6514. u64 page_start = folio_pos(folio);
  6515. u64 page_end = page_start + folio_size(folio) - 1;
  6516. u64 cur;
  6517. int inode_evicting = inode->vfs_inode.i_state & I_FREEING;
  6518. /*
  6519. * We have folio locked so no new ordered extent can be created on this
  6520. * page, nor bio can be submitted for this folio.
  6521. *
  6522. * But already submitted bio can still be finished on this folio.
  6523. * Furthermore, endio function won't skip folio which has Ordered
  6524. * (Private2) already cleared, so it's possible for endio and
  6525. * invalidate_folio to do the same ordered extent accounting twice
  6526. * on one folio.
  6527. *
  6528. * So here we wait for any submitted bios to finish, so that we won't
  6529. * do double ordered extent accounting on the same folio.
  6530. */
  6531. folio_wait_writeback(folio);
  6532. wait_subpage_spinlock(folio);
  6533. /*
  6534. * For subpage case, we have call sites like
  6535. * btrfs_punch_hole_lock_range() which passes range not aligned to
  6536. * sectorsize.
  6537. * If the range doesn't cover the full folio, we don't need to and
  6538. * shouldn't clear page extent mapped, as folio->private can still
  6539. * record subpage dirty bits for other part of the range.
  6540. *
  6541. * For cases that invalidate the full folio even the range doesn't
  6542. * cover the full folio, like invalidating the last folio, we're
  6543. * still safe to wait for ordered extent to finish.
  6544. */
  6545. if (!(offset == 0 && length == folio_size(folio))) {
  6546. btrfs_release_folio(folio, GFP_NOFS);
  6547. return;
  6548. }
  6549. if (!inode_evicting)
  6550. lock_extent(tree, page_start, page_end, &cached_state);
  6551. cur = page_start;
  6552. while (cur < page_end) {
  6553. struct btrfs_ordered_extent *ordered;
  6554. u64 range_end;
  6555. u32 range_len;
  6556. u32 extra_flags = 0;
  6557. ordered = btrfs_lookup_first_ordered_range(inode, cur,
  6558. page_end + 1 - cur);
  6559. if (!ordered) {
  6560. range_end = page_end;
  6561. /*
  6562. * No ordered extent covering this range, we are safe
  6563. * to delete all extent states in the range.
  6564. */
  6565. extra_flags = EXTENT_CLEAR_ALL_BITS;
  6566. goto next;
  6567. }
  6568. if (ordered->file_offset > cur) {
  6569. /*
  6570. * There is a range between [cur, oe->file_offset) not
  6571. * covered by any ordered extent.
  6572. * We are safe to delete all extent states, and handle
  6573. * the ordered extent in the next iteration.
  6574. */
  6575. range_end = ordered->file_offset - 1;
  6576. extra_flags = EXTENT_CLEAR_ALL_BITS;
  6577. goto next;
  6578. }
  6579. range_end = min(ordered->file_offset + ordered->num_bytes - 1,
  6580. page_end);
  6581. ASSERT(range_end + 1 - cur < U32_MAX);
  6582. range_len = range_end + 1 - cur;
  6583. if (!btrfs_folio_test_ordered(fs_info, folio, cur, range_len)) {
  6584. /*
  6585. * If Ordered (Private2) is cleared, it means endio has
  6586. * already been executed for the range.
  6587. * We can't delete the extent states as
  6588. * btrfs_finish_ordered_io() may still use some of them.
  6589. */
  6590. goto next;
  6591. }
  6592. btrfs_folio_clear_ordered(fs_info, folio, cur, range_len);
  6593. /*
  6594. * IO on this page will never be started, so we need to account
  6595. * for any ordered extents now. Don't clear EXTENT_DELALLOC_NEW
  6596. * here, must leave that up for the ordered extent completion.
  6597. *
  6598. * This will also unlock the range for incoming
  6599. * btrfs_finish_ordered_io().
  6600. */
  6601. if (!inode_evicting)
  6602. clear_extent_bit(tree, cur, range_end,
  6603. EXTENT_DELALLOC |
  6604. EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
  6605. EXTENT_DEFRAG, &cached_state);
  6606. spin_lock_irq(&inode->ordered_tree_lock);
  6607. set_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags);
  6608. ordered->truncated_len = min(ordered->truncated_len,
  6609. cur - ordered->file_offset);
  6610. spin_unlock_irq(&inode->ordered_tree_lock);
  6611. /*
  6612. * If the ordered extent has finished, we're safe to delete all
  6613. * the extent states of the range, otherwise
  6614. * btrfs_finish_ordered_io() will get executed by endio for
  6615. * other pages, so we can't delete extent states.
  6616. */
  6617. if (btrfs_dec_test_ordered_pending(inode, &ordered,
  6618. cur, range_end + 1 - cur)) {
  6619. btrfs_finish_ordered_io(ordered);
  6620. /*
  6621. * The ordered extent has finished, now we're again
  6622. * safe to delete all extent states of the range.
  6623. */
  6624. extra_flags = EXTENT_CLEAR_ALL_BITS;
  6625. }
  6626. next:
  6627. if (ordered)
  6628. btrfs_put_ordered_extent(ordered);
  6629. /*
  6630. * Qgroup reserved space handler
  6631. * Sector(s) here will be either:
  6632. *
  6633. * 1) Already written to disk or bio already finished
  6634. * Then its QGROUP_RESERVED bit in io_tree is already cleared.
  6635. * Qgroup will be handled by its qgroup_record then.
  6636. * btrfs_qgroup_free_data() call will do nothing here.
  6637. *
  6638. * 2) Not written to disk yet
  6639. * Then btrfs_qgroup_free_data() call will clear the
  6640. * QGROUP_RESERVED bit of its io_tree, and free the qgroup
  6641. * reserved data space.
  6642. * Since the IO will never happen for this page.
  6643. */
  6644. btrfs_qgroup_free_data(inode, NULL, cur, range_end + 1 - cur, NULL);
  6645. if (!inode_evicting) {
  6646. clear_extent_bit(tree, cur, range_end, EXTENT_LOCKED |
  6647. EXTENT_DELALLOC | EXTENT_UPTODATE |
  6648. EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG |
  6649. extra_flags, &cached_state);
  6650. }
  6651. cur = range_end + 1;
  6652. }
  6653. /*
  6654. * We have iterated through all ordered extents of the page, the page
  6655. * should not have Ordered (Private2) anymore, or the above iteration
  6656. * did something wrong.
  6657. */
  6658. ASSERT(!folio_test_ordered(folio));
  6659. btrfs_folio_clear_checked(fs_info, folio, folio_pos(folio), folio_size(folio));
  6660. if (!inode_evicting)
  6661. __btrfs_release_folio(folio, GFP_NOFS);
  6662. clear_folio_extent_mapped(folio);
  6663. }
  6664. static int btrfs_truncate(struct btrfs_inode *inode, bool skip_writeback)
  6665. {
  6666. struct btrfs_truncate_control control = {
  6667. .inode = inode,
  6668. .ino = btrfs_ino(inode),
  6669. .min_type = BTRFS_EXTENT_DATA_KEY,
  6670. .clear_extent_range = true,
  6671. };
  6672. struct btrfs_root *root = inode->root;
  6673. struct btrfs_fs_info *fs_info = root->fs_info;
  6674. struct btrfs_block_rsv *rsv;
  6675. int ret;
  6676. struct btrfs_trans_handle *trans;
  6677. u64 mask = fs_info->sectorsize - 1;
  6678. const u64 min_size = btrfs_calc_metadata_size(fs_info, 1);
  6679. if (!skip_writeback) {
  6680. ret = btrfs_wait_ordered_range(inode,
  6681. inode->vfs_inode.i_size & (~mask),
  6682. (u64)-1);
  6683. if (ret)
  6684. return ret;
  6685. }
  6686. /*
  6687. * Yes ladies and gentlemen, this is indeed ugly. We have a couple of
  6688. * things going on here:
  6689. *
  6690. * 1) We need to reserve space to update our inode.
  6691. *
  6692. * 2) We need to have something to cache all the space that is going to
  6693. * be free'd up by the truncate operation, but also have some slack
  6694. * space reserved in case it uses space during the truncate (thank you
  6695. * very much snapshotting).
  6696. *
  6697. * And we need these to be separate. The fact is we can use a lot of
  6698. * space doing the truncate, and we have no earthly idea how much space
  6699. * we will use, so we need the truncate reservation to be separate so it
  6700. * doesn't end up using space reserved for updating the inode. We also
  6701. * need to be able to stop the transaction and start a new one, which
  6702. * means we need to be able to update the inode several times, and we
  6703. * have no idea of knowing how many times that will be, so we can't just
  6704. * reserve 1 item for the entirety of the operation, so that has to be
  6705. * done separately as well.
  6706. *
  6707. * So that leaves us with
  6708. *
  6709. * 1) rsv - for the truncate reservation, which we will steal from the
  6710. * transaction reservation.
  6711. * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
  6712. * updating the inode.
  6713. */
  6714. rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
  6715. if (!rsv)
  6716. return -ENOMEM;
  6717. rsv->size = min_size;
  6718. rsv->failfast = true;
  6719. /*
  6720. * 1 for the truncate slack space
  6721. * 1 for updating the inode.
  6722. */
  6723. trans = btrfs_start_transaction(root, 2);
  6724. if (IS_ERR(trans)) {
  6725. ret = PTR_ERR(trans);
  6726. goto out;
  6727. }
  6728. /* Migrate the slack space for the truncate to our reserve */
  6729. ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
  6730. min_size, false);
  6731. /*
  6732. * We have reserved 2 metadata units when we started the transaction and
  6733. * min_size matches 1 unit, so this should never fail, but if it does,
  6734. * it's not critical we just fail truncation.
  6735. */
  6736. if (WARN_ON(ret)) {
  6737. btrfs_end_transaction(trans);
  6738. goto out;
  6739. }
  6740. trans->block_rsv = rsv;
  6741. while (1) {
  6742. struct extent_state *cached_state = NULL;
  6743. const u64 new_size = inode->vfs_inode.i_size;
  6744. const u64 lock_start = ALIGN_DOWN(new_size, fs_info->sectorsize);
  6745. control.new_size = new_size;
  6746. lock_extent(&inode->io_tree, lock_start, (u64)-1, &cached_state);
  6747. /*
  6748. * We want to drop from the next block forward in case this new
  6749. * size is not block aligned since we will be keeping the last
  6750. * block of the extent just the way it is.
  6751. */
  6752. btrfs_drop_extent_map_range(inode,
  6753. ALIGN(new_size, fs_info->sectorsize),
  6754. (u64)-1, false);
  6755. ret = btrfs_truncate_inode_items(trans, root, &control);
  6756. inode_sub_bytes(&inode->vfs_inode, control.sub_bytes);
  6757. btrfs_inode_safe_disk_i_size_write(inode, control.last_size);
  6758. unlock_extent(&inode->io_tree, lock_start, (u64)-1, &cached_state);
  6759. trans->block_rsv = &fs_info->trans_block_rsv;
  6760. if (ret != -ENOSPC && ret != -EAGAIN)
  6761. break;
  6762. ret = btrfs_update_inode(trans, inode);
  6763. if (ret)
  6764. break;
  6765. btrfs_end_transaction(trans);
  6766. btrfs_btree_balance_dirty(fs_info);
  6767. trans = btrfs_start_transaction(root, 2);
  6768. if (IS_ERR(trans)) {
  6769. ret = PTR_ERR(trans);
  6770. trans = NULL;
  6771. break;
  6772. }
  6773. btrfs_block_rsv_release(fs_info, rsv, -1, NULL);
  6774. ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
  6775. rsv, min_size, false);
  6776. /*
  6777. * We have reserved 2 metadata units when we started the
  6778. * transaction and min_size matches 1 unit, so this should never
  6779. * fail, but if it does, it's not critical we just fail truncation.
  6780. */
  6781. if (WARN_ON(ret))
  6782. break;
  6783. trans->block_rsv = rsv;
  6784. }
  6785. /*
  6786. * We can't call btrfs_truncate_block inside a trans handle as we could
  6787. * deadlock with freeze, if we got BTRFS_NEED_TRUNCATE_BLOCK then we
  6788. * know we've truncated everything except the last little bit, and can
  6789. * do btrfs_truncate_block and then update the disk_i_size.
  6790. */
  6791. if (ret == BTRFS_NEED_TRUNCATE_BLOCK) {
  6792. btrfs_end_transaction(trans);
  6793. btrfs_btree_balance_dirty(fs_info);
  6794. ret = btrfs_truncate_block(inode, inode->vfs_inode.i_size, 0, 0);
  6795. if (ret)
  6796. goto out;
  6797. trans = btrfs_start_transaction(root, 1);
  6798. if (IS_ERR(trans)) {
  6799. ret = PTR_ERR(trans);
  6800. goto out;
  6801. }
  6802. btrfs_inode_safe_disk_i_size_write(inode, 0);
  6803. }
  6804. if (trans) {
  6805. int ret2;
  6806. trans->block_rsv = &fs_info->trans_block_rsv;
  6807. ret2 = btrfs_update_inode(trans, inode);
  6808. if (ret2 && !ret)
  6809. ret = ret2;
  6810. ret2 = btrfs_end_transaction(trans);
  6811. if (ret2 && !ret)
  6812. ret = ret2;
  6813. btrfs_btree_balance_dirty(fs_info);
  6814. }
  6815. out:
  6816. btrfs_free_block_rsv(fs_info, rsv);
  6817. /*
  6818. * So if we truncate and then write and fsync we normally would just
  6819. * write the extents that changed, which is a problem if we need to
  6820. * first truncate that entire inode. So set this flag so we write out
  6821. * all of the extents in the inode to the sync log so we're completely
  6822. * safe.
  6823. *
  6824. * If no extents were dropped or trimmed we don't need to force the next
  6825. * fsync to truncate all the inode's items from the log and re-log them
  6826. * all. This means the truncate operation did not change the file size,
  6827. * or changed it to a smaller size but there was only an implicit hole
  6828. * between the old i_size and the new i_size, and there were no prealloc
  6829. * extents beyond i_size to drop.
  6830. */
  6831. if (control.extents_found > 0)
  6832. btrfs_set_inode_full_sync(inode);
  6833. return ret;
  6834. }
  6835. struct inode *btrfs_new_subvol_inode(struct mnt_idmap *idmap,
  6836. struct inode *dir)
  6837. {
  6838. struct inode *inode;
  6839. inode = new_inode(dir->i_sb);
  6840. if (inode) {
  6841. /*
  6842. * Subvolumes don't inherit the sgid bit or the parent's gid if
  6843. * the parent's sgid bit is set. This is probably a bug.
  6844. */
  6845. inode_init_owner(idmap, inode, NULL,
  6846. S_IFDIR | (~current_umask() & S_IRWXUGO));
  6847. inode->i_op = &btrfs_dir_inode_operations;
  6848. inode->i_fop = &btrfs_dir_file_operations;
  6849. }
  6850. return inode;
  6851. }
  6852. struct inode *btrfs_alloc_inode(struct super_block *sb)
  6853. {
  6854. struct btrfs_fs_info *fs_info = btrfs_sb(sb);
  6855. struct btrfs_inode *ei;
  6856. struct inode *inode;
  6857. ei = alloc_inode_sb(sb, btrfs_inode_cachep, GFP_KERNEL);
  6858. if (!ei)
  6859. return NULL;
  6860. ei->root = NULL;
  6861. ei->generation = 0;
  6862. ei->last_trans = 0;
  6863. ei->last_sub_trans = 0;
  6864. ei->logged_trans = 0;
  6865. ei->delalloc_bytes = 0;
  6866. /* new_delalloc_bytes and last_dir_index_offset are in a union. */
  6867. ei->new_delalloc_bytes = 0;
  6868. ei->defrag_bytes = 0;
  6869. ei->disk_i_size = 0;
  6870. ei->flags = 0;
  6871. ei->ro_flags = 0;
  6872. /*
  6873. * ->index_cnt will be properly initialized later when creating a new
  6874. * inode (btrfs_create_new_inode()) or when reading an existing inode
  6875. * from disk (btrfs_read_locked_inode()).
  6876. */
  6877. ei->csum_bytes = 0;
  6878. ei->dir_index = 0;
  6879. ei->last_unlink_trans = 0;
  6880. ei->last_reflink_trans = 0;
  6881. ei->last_log_commit = 0;
  6882. spin_lock_init(&ei->lock);
  6883. ei->outstanding_extents = 0;
  6884. if (sb->s_magic != BTRFS_TEST_MAGIC)
  6885. btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
  6886. BTRFS_BLOCK_RSV_DELALLOC);
  6887. ei->runtime_flags = 0;
  6888. ei->prop_compress = BTRFS_COMPRESS_NONE;
  6889. ei->defrag_compress = BTRFS_COMPRESS_NONE;
  6890. ei->delayed_node = NULL;
  6891. ei->i_otime_sec = 0;
  6892. ei->i_otime_nsec = 0;
  6893. inode = &ei->vfs_inode;
  6894. extent_map_tree_init(&ei->extent_tree);
  6895. /* This io tree sets the valid inode. */
  6896. extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO);
  6897. ei->io_tree.inode = ei;
  6898. ei->file_extent_tree = NULL;
  6899. mutex_init(&ei->log_mutex);
  6900. spin_lock_init(&ei->ordered_tree_lock);
  6901. ei->ordered_tree = RB_ROOT;
  6902. ei->ordered_tree_last = NULL;
  6903. INIT_LIST_HEAD(&ei->delalloc_inodes);
  6904. INIT_LIST_HEAD(&ei->delayed_iput);
  6905. init_rwsem(&ei->i_mmap_lock);
  6906. return inode;
  6907. }
  6908. #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
  6909. void btrfs_test_destroy_inode(struct inode *inode)
  6910. {
  6911. btrfs_drop_extent_map_range(BTRFS_I(inode), 0, (u64)-1, false);
  6912. kfree(BTRFS_I(inode)->file_extent_tree);
  6913. kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
  6914. }
  6915. #endif
  6916. void btrfs_free_inode(struct inode *inode)
  6917. {
  6918. kfree(BTRFS_I(inode)->file_extent_tree);
  6919. kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
  6920. }
  6921. void btrfs_destroy_inode(struct inode *vfs_inode)
  6922. {
  6923. struct btrfs_ordered_extent *ordered;
  6924. struct btrfs_inode *inode = BTRFS_I(vfs_inode);
  6925. struct btrfs_root *root = inode->root;
  6926. bool freespace_inode;
  6927. WARN_ON(!hlist_empty(&vfs_inode->i_dentry));
  6928. WARN_ON(vfs_inode->i_data.nrpages);
  6929. WARN_ON(inode->block_rsv.reserved);
  6930. WARN_ON(inode->block_rsv.size);
  6931. WARN_ON(inode->outstanding_extents);
  6932. if (!S_ISDIR(vfs_inode->i_mode)) {
  6933. WARN_ON(inode->delalloc_bytes);
  6934. WARN_ON(inode->new_delalloc_bytes);
  6935. WARN_ON(inode->csum_bytes);
  6936. }
  6937. if (!root || !btrfs_is_data_reloc_root(root))
  6938. WARN_ON(inode->defrag_bytes);
  6939. /*
  6940. * This can happen where we create an inode, but somebody else also
  6941. * created the same inode and we need to destroy the one we already
  6942. * created.
  6943. */
  6944. if (!root)
  6945. return;
  6946. /*
  6947. * If this is a free space inode do not take the ordered extents lockdep
  6948. * map.
  6949. */
  6950. freespace_inode = btrfs_is_free_space_inode(inode);
  6951. while (1) {
  6952. ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
  6953. if (!ordered)
  6954. break;
  6955. else {
  6956. btrfs_err(root->fs_info,
  6957. "found ordered extent %llu %llu on inode cleanup",
  6958. ordered->file_offset, ordered->num_bytes);
  6959. if (!freespace_inode)
  6960. btrfs_lockdep_acquire(root->fs_info, btrfs_ordered_extent);
  6961. btrfs_remove_ordered_extent(inode, ordered);
  6962. btrfs_put_ordered_extent(ordered);
  6963. btrfs_put_ordered_extent(ordered);
  6964. }
  6965. }
  6966. btrfs_qgroup_check_reserved_leak(inode);
  6967. btrfs_del_inode_from_root(inode);
  6968. btrfs_drop_extent_map_range(inode, 0, (u64)-1, false);
  6969. btrfs_inode_clear_file_extent_range(inode, 0, (u64)-1);
  6970. btrfs_put_root(inode->root);
  6971. }
  6972. int btrfs_drop_inode(struct inode *inode)
  6973. {
  6974. struct btrfs_root *root = BTRFS_I(inode)->root;
  6975. if (root == NULL)
  6976. return 1;
  6977. /* the snap/subvol tree is on deleting */
  6978. if (btrfs_root_refs(&root->root_item) == 0)
  6979. return 1;
  6980. else
  6981. return generic_drop_inode(inode);
  6982. }
  6983. static void init_once(void *foo)
  6984. {
  6985. struct btrfs_inode *ei = foo;
  6986. inode_init_once(&ei->vfs_inode);
  6987. }
  6988. void __cold btrfs_destroy_cachep(void)
  6989. {
  6990. /*
  6991. * Make sure all delayed rcu free inodes are flushed before we
  6992. * destroy cache.
  6993. */
  6994. rcu_barrier();
  6995. kmem_cache_destroy(btrfs_inode_cachep);
  6996. }
  6997. int __init btrfs_init_cachep(void)
  6998. {
  6999. btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
  7000. sizeof(struct btrfs_inode), 0,
  7001. SLAB_RECLAIM_ACCOUNT | SLAB_ACCOUNT,
  7002. init_once);
  7003. if (!btrfs_inode_cachep)
  7004. return -ENOMEM;
  7005. return 0;
  7006. }
  7007. static int btrfs_getattr(struct mnt_idmap *idmap,
  7008. const struct path *path, struct kstat *stat,
  7009. u32 request_mask, unsigned int flags)
  7010. {
  7011. u64 delalloc_bytes;
  7012. u64 inode_bytes;
  7013. struct inode *inode = d_inode(path->dentry);
  7014. u32 blocksize = btrfs_sb(inode->i_sb)->sectorsize;
  7015. u32 bi_flags = BTRFS_I(inode)->flags;
  7016. u32 bi_ro_flags = BTRFS_I(inode)->ro_flags;
  7017. stat->result_mask |= STATX_BTIME;
  7018. stat->btime.tv_sec = BTRFS_I(inode)->i_otime_sec;
  7019. stat->btime.tv_nsec = BTRFS_I(inode)->i_otime_nsec;
  7020. if (bi_flags & BTRFS_INODE_APPEND)
  7021. stat->attributes |= STATX_ATTR_APPEND;
  7022. if (bi_flags & BTRFS_INODE_COMPRESS)
  7023. stat->attributes |= STATX_ATTR_COMPRESSED;
  7024. if (bi_flags & BTRFS_INODE_IMMUTABLE)
  7025. stat->attributes |= STATX_ATTR_IMMUTABLE;
  7026. if (bi_flags & BTRFS_INODE_NODUMP)
  7027. stat->attributes |= STATX_ATTR_NODUMP;
  7028. if (bi_ro_flags & BTRFS_INODE_RO_VERITY)
  7029. stat->attributes |= STATX_ATTR_VERITY;
  7030. stat->attributes_mask |= (STATX_ATTR_APPEND |
  7031. STATX_ATTR_COMPRESSED |
  7032. STATX_ATTR_IMMUTABLE |
  7033. STATX_ATTR_NODUMP);
  7034. generic_fillattr(idmap, request_mask, inode, stat);
  7035. stat->dev = BTRFS_I(inode)->root->anon_dev;
  7036. stat->subvol = BTRFS_I(inode)->root->root_key.objectid;
  7037. stat->result_mask |= STATX_SUBVOL;
  7038. spin_lock(&BTRFS_I(inode)->lock);
  7039. delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
  7040. inode_bytes = inode_get_bytes(inode);
  7041. spin_unlock(&BTRFS_I(inode)->lock);
  7042. stat->blocks = (ALIGN(inode_bytes, blocksize) +
  7043. ALIGN(delalloc_bytes, blocksize)) >> SECTOR_SHIFT;
  7044. return 0;
  7045. }
  7046. static int btrfs_rename_exchange(struct inode *old_dir,
  7047. struct dentry *old_dentry,
  7048. struct inode *new_dir,
  7049. struct dentry *new_dentry)
  7050. {
  7051. struct btrfs_fs_info *fs_info = inode_to_fs_info(old_dir);
  7052. struct btrfs_trans_handle *trans;
  7053. unsigned int trans_num_items;
  7054. struct btrfs_root *root = BTRFS_I(old_dir)->root;
  7055. struct btrfs_root *dest = BTRFS_I(new_dir)->root;
  7056. struct inode *new_inode = new_dentry->d_inode;
  7057. struct inode *old_inode = old_dentry->d_inode;
  7058. struct btrfs_rename_ctx old_rename_ctx;
  7059. struct btrfs_rename_ctx new_rename_ctx;
  7060. u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
  7061. u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
  7062. u64 old_idx = 0;
  7063. u64 new_idx = 0;
  7064. int ret;
  7065. int ret2;
  7066. bool need_abort = false;
  7067. bool logs_pinned = false;
  7068. struct fscrypt_name old_fname, new_fname;
  7069. struct fscrypt_str *old_name, *new_name;
  7070. /*
  7071. * For non-subvolumes allow exchange only within one subvolume, in the
  7072. * same inode namespace. Two subvolumes (represented as directory) can
  7073. * be exchanged as they're a logical link and have a fixed inode number.
  7074. */
  7075. if (root != dest &&
  7076. (old_ino != BTRFS_FIRST_FREE_OBJECTID ||
  7077. new_ino != BTRFS_FIRST_FREE_OBJECTID))
  7078. return -EXDEV;
  7079. ret = fscrypt_setup_filename(old_dir, &old_dentry->d_name, 0, &old_fname);
  7080. if (ret)
  7081. return ret;
  7082. ret = fscrypt_setup_filename(new_dir, &new_dentry->d_name, 0, &new_fname);
  7083. if (ret) {
  7084. fscrypt_free_filename(&old_fname);
  7085. return ret;
  7086. }
  7087. old_name = &old_fname.disk_name;
  7088. new_name = &new_fname.disk_name;
  7089. /* close the race window with snapshot create/destroy ioctl */
  7090. if (old_ino == BTRFS_FIRST_FREE_OBJECTID ||
  7091. new_ino == BTRFS_FIRST_FREE_OBJECTID)
  7092. down_read(&fs_info->subvol_sem);
  7093. /*
  7094. * For each inode:
  7095. * 1 to remove old dir item
  7096. * 1 to remove old dir index
  7097. * 1 to add new dir item
  7098. * 1 to add new dir index
  7099. * 1 to update parent inode
  7100. *
  7101. * If the parents are the same, we only need to account for one
  7102. */
  7103. trans_num_items = (old_dir == new_dir ? 9 : 10);
  7104. if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
  7105. /*
  7106. * 1 to remove old root ref
  7107. * 1 to remove old root backref
  7108. * 1 to add new root ref
  7109. * 1 to add new root backref
  7110. */
  7111. trans_num_items += 4;
  7112. } else {
  7113. /*
  7114. * 1 to update inode item
  7115. * 1 to remove old inode ref
  7116. * 1 to add new inode ref
  7117. */
  7118. trans_num_items += 3;
  7119. }
  7120. if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
  7121. trans_num_items += 4;
  7122. else
  7123. trans_num_items += 3;
  7124. trans = btrfs_start_transaction(root, trans_num_items);
  7125. if (IS_ERR(trans)) {
  7126. ret = PTR_ERR(trans);
  7127. goto out_notrans;
  7128. }
  7129. if (dest != root) {
  7130. ret = btrfs_record_root_in_trans(trans, dest);
  7131. if (ret)
  7132. goto out_fail;
  7133. }
  7134. /*
  7135. * We need to find a free sequence number both in the source and
  7136. * in the destination directory for the exchange.
  7137. */
  7138. ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
  7139. if (ret)
  7140. goto out_fail;
  7141. ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
  7142. if (ret)
  7143. goto out_fail;
  7144. BTRFS_I(old_inode)->dir_index = 0ULL;
  7145. BTRFS_I(new_inode)->dir_index = 0ULL;
  7146. /* Reference for the source. */
  7147. if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
  7148. /* force full log commit if subvolume involved. */
  7149. btrfs_set_log_full_commit(trans);
  7150. } else {
  7151. ret = btrfs_insert_inode_ref(trans, dest, new_name, old_ino,
  7152. btrfs_ino(BTRFS_I(new_dir)),
  7153. old_idx);
  7154. if (ret)
  7155. goto out_fail;
  7156. need_abort = true;
  7157. }
  7158. /* And now for the dest. */
  7159. if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
  7160. /* force full log commit if subvolume involved. */
  7161. btrfs_set_log_full_commit(trans);
  7162. } else {
  7163. ret = btrfs_insert_inode_ref(trans, root, old_name, new_ino,
  7164. btrfs_ino(BTRFS_I(old_dir)),
  7165. new_idx);
  7166. if (ret) {
  7167. if (need_abort)
  7168. btrfs_abort_transaction(trans, ret);
  7169. goto out_fail;
  7170. }
  7171. }
  7172. /* Update inode version and ctime/mtime. */
  7173. inode_inc_iversion(old_dir);
  7174. inode_inc_iversion(new_dir);
  7175. inode_inc_iversion(old_inode);
  7176. inode_inc_iversion(new_inode);
  7177. simple_rename_timestamp(old_dir, old_dentry, new_dir, new_dentry);
  7178. if (old_ino != BTRFS_FIRST_FREE_OBJECTID &&
  7179. new_ino != BTRFS_FIRST_FREE_OBJECTID) {
  7180. /*
  7181. * If we are renaming in the same directory (and it's not for
  7182. * root entries) pin the log early to prevent any concurrent
  7183. * task from logging the directory after we removed the old
  7184. * entries and before we add the new entries, otherwise that
  7185. * task can sync a log without any entry for the inodes we are
  7186. * renaming and therefore replaying that log, if a power failure
  7187. * happens after syncing the log, would result in deleting the
  7188. * inodes.
  7189. *
  7190. * If the rename affects two different directories, we want to
  7191. * make sure the that there's no log commit that contains
  7192. * updates for only one of the directories but not for the
  7193. * other.
  7194. *
  7195. * If we are renaming an entry for a root, we don't care about
  7196. * log updates since we called btrfs_set_log_full_commit().
  7197. */
  7198. btrfs_pin_log_trans(root);
  7199. btrfs_pin_log_trans(dest);
  7200. logs_pinned = true;
  7201. }
  7202. if (old_dentry->d_parent != new_dentry->d_parent) {
  7203. btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
  7204. BTRFS_I(old_inode), true);
  7205. btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
  7206. BTRFS_I(new_inode), true);
  7207. }
  7208. /* src is a subvolume */
  7209. if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
  7210. ret = btrfs_unlink_subvol(trans, BTRFS_I(old_dir), old_dentry);
  7211. } else { /* src is an inode */
  7212. ret = __btrfs_unlink_inode(trans, BTRFS_I(old_dir),
  7213. BTRFS_I(old_dentry->d_inode),
  7214. old_name, &old_rename_ctx);
  7215. if (!ret)
  7216. ret = btrfs_update_inode(trans, BTRFS_I(old_inode));
  7217. }
  7218. if (ret) {
  7219. btrfs_abort_transaction(trans, ret);
  7220. goto out_fail;
  7221. }
  7222. /* dest is a subvolume */
  7223. if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
  7224. ret = btrfs_unlink_subvol(trans, BTRFS_I(new_dir), new_dentry);
  7225. } else { /* dest is an inode */
  7226. ret = __btrfs_unlink_inode(trans, BTRFS_I(new_dir),
  7227. BTRFS_I(new_dentry->d_inode),
  7228. new_name, &new_rename_ctx);
  7229. if (!ret)
  7230. ret = btrfs_update_inode(trans, BTRFS_I(new_inode));
  7231. }
  7232. if (ret) {
  7233. btrfs_abort_transaction(trans, ret);
  7234. goto out_fail;
  7235. }
  7236. ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
  7237. new_name, 0, old_idx);
  7238. if (ret) {
  7239. btrfs_abort_transaction(trans, ret);
  7240. goto out_fail;
  7241. }
  7242. ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
  7243. old_name, 0, new_idx);
  7244. if (ret) {
  7245. btrfs_abort_transaction(trans, ret);
  7246. goto out_fail;
  7247. }
  7248. if (old_inode->i_nlink == 1)
  7249. BTRFS_I(old_inode)->dir_index = old_idx;
  7250. if (new_inode->i_nlink == 1)
  7251. BTRFS_I(new_inode)->dir_index = new_idx;
  7252. /*
  7253. * Do the log updates for all inodes.
  7254. *
  7255. * If either entry is for a root we don't need to update the logs since
  7256. * we've called btrfs_set_log_full_commit() before.
  7257. */
  7258. if (logs_pinned) {
  7259. btrfs_log_new_name(trans, old_dentry, BTRFS_I(old_dir),
  7260. old_rename_ctx.index, new_dentry->d_parent);
  7261. btrfs_log_new_name(trans, new_dentry, BTRFS_I(new_dir),
  7262. new_rename_ctx.index, old_dentry->d_parent);
  7263. }
  7264. out_fail:
  7265. if (logs_pinned) {
  7266. btrfs_end_log_trans(root);
  7267. btrfs_end_log_trans(dest);
  7268. }
  7269. ret2 = btrfs_end_transaction(trans);
  7270. ret = ret ? ret : ret2;
  7271. out_notrans:
  7272. if (new_ino == BTRFS_FIRST_FREE_OBJECTID ||
  7273. old_ino == BTRFS_FIRST_FREE_OBJECTID)
  7274. up_read(&fs_info->subvol_sem);
  7275. fscrypt_free_filename(&new_fname);
  7276. fscrypt_free_filename(&old_fname);
  7277. return ret;
  7278. }
  7279. static struct inode *new_whiteout_inode(struct mnt_idmap *idmap,
  7280. struct inode *dir)
  7281. {
  7282. struct inode *inode;
  7283. inode = new_inode(dir->i_sb);
  7284. if (inode) {
  7285. inode_init_owner(idmap, inode, dir,
  7286. S_IFCHR | WHITEOUT_MODE);
  7287. inode->i_op = &btrfs_special_inode_operations;
  7288. init_special_inode(inode, inode->i_mode, WHITEOUT_DEV);
  7289. }
  7290. return inode;
  7291. }
  7292. static int btrfs_rename(struct mnt_idmap *idmap,
  7293. struct inode *old_dir, struct dentry *old_dentry,
  7294. struct inode *new_dir, struct dentry *new_dentry,
  7295. unsigned int flags)
  7296. {
  7297. struct btrfs_fs_info *fs_info = inode_to_fs_info(old_dir);
  7298. struct btrfs_new_inode_args whiteout_args = {
  7299. .dir = old_dir,
  7300. .dentry = old_dentry,
  7301. };
  7302. struct btrfs_trans_handle *trans;
  7303. unsigned int trans_num_items;
  7304. struct btrfs_root *root = BTRFS_I(old_dir)->root;
  7305. struct btrfs_root *dest = BTRFS_I(new_dir)->root;
  7306. struct inode *new_inode = d_inode(new_dentry);
  7307. struct inode *old_inode = d_inode(old_dentry);
  7308. struct btrfs_rename_ctx rename_ctx;
  7309. u64 index = 0;
  7310. int ret;
  7311. int ret2;
  7312. u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
  7313. struct fscrypt_name old_fname, new_fname;
  7314. bool logs_pinned = false;
  7315. if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
  7316. return -EPERM;
  7317. /* we only allow rename subvolume link between subvolumes */
  7318. if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
  7319. return -EXDEV;
  7320. if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
  7321. (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
  7322. return -ENOTEMPTY;
  7323. if (S_ISDIR(old_inode->i_mode) && new_inode &&
  7324. new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
  7325. return -ENOTEMPTY;
  7326. ret = fscrypt_setup_filename(old_dir, &old_dentry->d_name, 0, &old_fname);
  7327. if (ret)
  7328. return ret;
  7329. ret = fscrypt_setup_filename(new_dir, &new_dentry->d_name, 0, &new_fname);
  7330. if (ret) {
  7331. fscrypt_free_filename(&old_fname);
  7332. return ret;
  7333. }
  7334. /* check for collisions, even if the name isn't there */
  7335. ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino, &new_fname.disk_name);
  7336. if (ret) {
  7337. if (ret == -EEXIST) {
  7338. /* we shouldn't get
  7339. * eexist without a new_inode */
  7340. if (WARN_ON(!new_inode)) {
  7341. goto out_fscrypt_names;
  7342. }
  7343. } else {
  7344. /* maybe -EOVERFLOW */
  7345. goto out_fscrypt_names;
  7346. }
  7347. }
  7348. ret = 0;
  7349. /*
  7350. * we're using rename to replace one file with another. Start IO on it
  7351. * now so we don't add too much work to the end of the transaction
  7352. */
  7353. if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
  7354. filemap_flush(old_inode->i_mapping);
  7355. if (flags & RENAME_WHITEOUT) {
  7356. whiteout_args.inode = new_whiteout_inode(idmap, old_dir);
  7357. if (!whiteout_args.inode) {
  7358. ret = -ENOMEM;
  7359. goto out_fscrypt_names;
  7360. }
  7361. ret = btrfs_new_inode_prepare(&whiteout_args, &trans_num_items);
  7362. if (ret)
  7363. goto out_whiteout_inode;
  7364. } else {
  7365. /* 1 to update the old parent inode. */
  7366. trans_num_items = 1;
  7367. }
  7368. if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
  7369. /* Close the race window with snapshot create/destroy ioctl */
  7370. down_read(&fs_info->subvol_sem);
  7371. /*
  7372. * 1 to remove old root ref
  7373. * 1 to remove old root backref
  7374. * 1 to add new root ref
  7375. * 1 to add new root backref
  7376. */
  7377. trans_num_items += 4;
  7378. } else {
  7379. /*
  7380. * 1 to update inode
  7381. * 1 to remove old inode ref
  7382. * 1 to add new inode ref
  7383. */
  7384. trans_num_items += 3;
  7385. }
  7386. /*
  7387. * 1 to remove old dir item
  7388. * 1 to remove old dir index
  7389. * 1 to add new dir item
  7390. * 1 to add new dir index
  7391. */
  7392. trans_num_items += 4;
  7393. /* 1 to update new parent inode if it's not the same as the old parent */
  7394. if (new_dir != old_dir)
  7395. trans_num_items++;
  7396. if (new_inode) {
  7397. /*
  7398. * 1 to update inode
  7399. * 1 to remove inode ref
  7400. * 1 to remove dir item
  7401. * 1 to remove dir index
  7402. * 1 to possibly add orphan item
  7403. */
  7404. trans_num_items += 5;
  7405. }
  7406. trans = btrfs_start_transaction(root, trans_num_items);
  7407. if (IS_ERR(trans)) {
  7408. ret = PTR_ERR(trans);
  7409. goto out_notrans;
  7410. }
  7411. if (dest != root) {
  7412. ret = btrfs_record_root_in_trans(trans, dest);
  7413. if (ret)
  7414. goto out_fail;
  7415. }
  7416. ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
  7417. if (ret)
  7418. goto out_fail;
  7419. BTRFS_I(old_inode)->dir_index = 0ULL;
  7420. if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
  7421. /* force full log commit if subvolume involved. */
  7422. btrfs_set_log_full_commit(trans);
  7423. } else {
  7424. ret = btrfs_insert_inode_ref(trans, dest, &new_fname.disk_name,
  7425. old_ino, btrfs_ino(BTRFS_I(new_dir)),
  7426. index);
  7427. if (ret)
  7428. goto out_fail;
  7429. }
  7430. inode_inc_iversion(old_dir);
  7431. inode_inc_iversion(new_dir);
  7432. inode_inc_iversion(old_inode);
  7433. simple_rename_timestamp(old_dir, old_dentry, new_dir, new_dentry);
  7434. if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
  7435. /*
  7436. * If we are renaming in the same directory (and it's not a
  7437. * root entry) pin the log to prevent any concurrent task from
  7438. * logging the directory after we removed the old entry and
  7439. * before we add the new entry, otherwise that task can sync
  7440. * a log without any entry for the inode we are renaming and
  7441. * therefore replaying that log, if a power failure happens
  7442. * after syncing the log, would result in deleting the inode.
  7443. *
  7444. * If the rename affects two different directories, we want to
  7445. * make sure the that there's no log commit that contains
  7446. * updates for only one of the directories but not for the
  7447. * other.
  7448. *
  7449. * If we are renaming an entry for a root, we don't care about
  7450. * log updates since we called btrfs_set_log_full_commit().
  7451. */
  7452. btrfs_pin_log_trans(root);
  7453. btrfs_pin_log_trans(dest);
  7454. logs_pinned = true;
  7455. }
  7456. if (old_dentry->d_parent != new_dentry->d_parent)
  7457. btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
  7458. BTRFS_I(old_inode), true);
  7459. if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
  7460. ret = btrfs_unlink_subvol(trans, BTRFS_I(old_dir), old_dentry);
  7461. } else {
  7462. ret = __btrfs_unlink_inode(trans, BTRFS_I(old_dir),
  7463. BTRFS_I(d_inode(old_dentry)),
  7464. &old_fname.disk_name, &rename_ctx);
  7465. if (!ret)
  7466. ret = btrfs_update_inode(trans, BTRFS_I(old_inode));
  7467. }
  7468. if (ret) {
  7469. btrfs_abort_transaction(trans, ret);
  7470. goto out_fail;
  7471. }
  7472. if (new_inode) {
  7473. inode_inc_iversion(new_inode);
  7474. if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
  7475. BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
  7476. ret = btrfs_unlink_subvol(trans, BTRFS_I(new_dir), new_dentry);
  7477. BUG_ON(new_inode->i_nlink == 0);
  7478. } else {
  7479. ret = btrfs_unlink_inode(trans, BTRFS_I(new_dir),
  7480. BTRFS_I(d_inode(new_dentry)),
  7481. &new_fname.disk_name);
  7482. }
  7483. if (!ret && new_inode->i_nlink == 0)
  7484. ret = btrfs_orphan_add(trans,
  7485. BTRFS_I(d_inode(new_dentry)));
  7486. if (ret) {
  7487. btrfs_abort_transaction(trans, ret);
  7488. goto out_fail;
  7489. }
  7490. }
  7491. ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
  7492. &new_fname.disk_name, 0, index);
  7493. if (ret) {
  7494. btrfs_abort_transaction(trans, ret);
  7495. goto out_fail;
  7496. }
  7497. if (old_inode->i_nlink == 1)
  7498. BTRFS_I(old_inode)->dir_index = index;
  7499. if (logs_pinned)
  7500. btrfs_log_new_name(trans, old_dentry, BTRFS_I(old_dir),
  7501. rename_ctx.index, new_dentry->d_parent);
  7502. if (flags & RENAME_WHITEOUT) {
  7503. ret = btrfs_create_new_inode(trans, &whiteout_args);
  7504. if (ret) {
  7505. btrfs_abort_transaction(trans, ret);
  7506. goto out_fail;
  7507. } else {
  7508. unlock_new_inode(whiteout_args.inode);
  7509. iput(whiteout_args.inode);
  7510. whiteout_args.inode = NULL;
  7511. }
  7512. }
  7513. out_fail:
  7514. if (logs_pinned) {
  7515. btrfs_end_log_trans(root);
  7516. btrfs_end_log_trans(dest);
  7517. }
  7518. ret2 = btrfs_end_transaction(trans);
  7519. ret = ret ? ret : ret2;
  7520. out_notrans:
  7521. if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
  7522. up_read(&fs_info->subvol_sem);
  7523. if (flags & RENAME_WHITEOUT)
  7524. btrfs_new_inode_args_destroy(&whiteout_args);
  7525. out_whiteout_inode:
  7526. if (flags & RENAME_WHITEOUT)
  7527. iput(whiteout_args.inode);
  7528. out_fscrypt_names:
  7529. fscrypt_free_filename(&old_fname);
  7530. fscrypt_free_filename(&new_fname);
  7531. return ret;
  7532. }
  7533. static int btrfs_rename2(struct mnt_idmap *idmap, struct inode *old_dir,
  7534. struct dentry *old_dentry, struct inode *new_dir,
  7535. struct dentry *new_dentry, unsigned int flags)
  7536. {
  7537. int ret;
  7538. if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
  7539. return -EINVAL;
  7540. if (flags & RENAME_EXCHANGE)
  7541. ret = btrfs_rename_exchange(old_dir, old_dentry, new_dir,
  7542. new_dentry);
  7543. else
  7544. ret = btrfs_rename(idmap, old_dir, old_dentry, new_dir,
  7545. new_dentry, flags);
  7546. btrfs_btree_balance_dirty(BTRFS_I(new_dir)->root->fs_info);
  7547. return ret;
  7548. }
  7549. struct btrfs_delalloc_work {
  7550. struct inode *inode;
  7551. struct completion completion;
  7552. struct list_head list;
  7553. struct btrfs_work work;
  7554. };
  7555. static void btrfs_run_delalloc_work(struct btrfs_work *work)
  7556. {
  7557. struct btrfs_delalloc_work *delalloc_work;
  7558. struct inode *inode;
  7559. delalloc_work = container_of(work, struct btrfs_delalloc_work,
  7560. work);
  7561. inode = delalloc_work->inode;
  7562. filemap_flush(inode->i_mapping);
  7563. if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
  7564. &BTRFS_I(inode)->runtime_flags))
  7565. filemap_flush(inode->i_mapping);
  7566. iput(inode);
  7567. complete(&delalloc_work->completion);
  7568. }
  7569. static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
  7570. {
  7571. struct btrfs_delalloc_work *work;
  7572. work = kmalloc(sizeof(*work), GFP_NOFS);
  7573. if (!work)
  7574. return NULL;
  7575. init_completion(&work->completion);
  7576. INIT_LIST_HEAD(&work->list);
  7577. work->inode = inode;
  7578. btrfs_init_work(&work->work, btrfs_run_delalloc_work, NULL);
  7579. return work;
  7580. }
  7581. /*
  7582. * some fairly slow code that needs optimization. This walks the list
  7583. * of all the inodes with pending delalloc and forces them to disk.
  7584. */
  7585. static int start_delalloc_inodes(struct btrfs_root *root,
  7586. struct writeback_control *wbc, bool snapshot,
  7587. bool in_reclaim_context)
  7588. {
  7589. struct btrfs_inode *binode;
  7590. struct inode *inode;
  7591. struct btrfs_delalloc_work *work, *next;
  7592. LIST_HEAD(works);
  7593. LIST_HEAD(splice);
  7594. int ret = 0;
  7595. bool full_flush = wbc->nr_to_write == LONG_MAX;
  7596. mutex_lock(&root->delalloc_mutex);
  7597. spin_lock(&root->delalloc_lock);
  7598. list_splice_init(&root->delalloc_inodes, &splice);
  7599. while (!list_empty(&splice)) {
  7600. binode = list_entry(splice.next, struct btrfs_inode,
  7601. delalloc_inodes);
  7602. list_move_tail(&binode->delalloc_inodes,
  7603. &root->delalloc_inodes);
  7604. if (in_reclaim_context &&
  7605. test_bit(BTRFS_INODE_NO_DELALLOC_FLUSH, &binode->runtime_flags))
  7606. continue;
  7607. inode = igrab(&binode->vfs_inode);
  7608. if (!inode) {
  7609. cond_resched_lock(&root->delalloc_lock);
  7610. continue;
  7611. }
  7612. spin_unlock(&root->delalloc_lock);
  7613. if (snapshot)
  7614. set_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
  7615. &binode->runtime_flags);
  7616. if (full_flush) {
  7617. work = btrfs_alloc_delalloc_work(inode);
  7618. if (!work) {
  7619. iput(inode);
  7620. ret = -ENOMEM;
  7621. goto out;
  7622. }
  7623. list_add_tail(&work->list, &works);
  7624. btrfs_queue_work(root->fs_info->flush_workers,
  7625. &work->work);
  7626. } else {
  7627. ret = filemap_fdatawrite_wbc(inode->i_mapping, wbc);
  7628. btrfs_add_delayed_iput(BTRFS_I(inode));
  7629. if (ret || wbc->nr_to_write <= 0)
  7630. goto out;
  7631. }
  7632. cond_resched();
  7633. spin_lock(&root->delalloc_lock);
  7634. }
  7635. spin_unlock(&root->delalloc_lock);
  7636. out:
  7637. list_for_each_entry_safe(work, next, &works, list) {
  7638. list_del_init(&work->list);
  7639. wait_for_completion(&work->completion);
  7640. kfree(work);
  7641. }
  7642. if (!list_empty(&splice)) {
  7643. spin_lock(&root->delalloc_lock);
  7644. list_splice_tail(&splice, &root->delalloc_inodes);
  7645. spin_unlock(&root->delalloc_lock);
  7646. }
  7647. mutex_unlock(&root->delalloc_mutex);
  7648. return ret;
  7649. }
  7650. int btrfs_start_delalloc_snapshot(struct btrfs_root *root, bool in_reclaim_context)
  7651. {
  7652. struct writeback_control wbc = {
  7653. .nr_to_write = LONG_MAX,
  7654. .sync_mode = WB_SYNC_NONE,
  7655. .range_start = 0,
  7656. .range_end = LLONG_MAX,
  7657. };
  7658. struct btrfs_fs_info *fs_info = root->fs_info;
  7659. if (BTRFS_FS_ERROR(fs_info))
  7660. return -EROFS;
  7661. return start_delalloc_inodes(root, &wbc, true, in_reclaim_context);
  7662. }
  7663. int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, long nr,
  7664. bool in_reclaim_context)
  7665. {
  7666. struct writeback_control wbc = {
  7667. .nr_to_write = nr,
  7668. .sync_mode = WB_SYNC_NONE,
  7669. .range_start = 0,
  7670. .range_end = LLONG_MAX,
  7671. };
  7672. struct btrfs_root *root;
  7673. LIST_HEAD(splice);
  7674. int ret;
  7675. if (BTRFS_FS_ERROR(fs_info))
  7676. return -EROFS;
  7677. mutex_lock(&fs_info->delalloc_root_mutex);
  7678. spin_lock(&fs_info->delalloc_root_lock);
  7679. list_splice_init(&fs_info->delalloc_roots, &splice);
  7680. while (!list_empty(&splice)) {
  7681. /*
  7682. * Reset nr_to_write here so we know that we're doing a full
  7683. * flush.
  7684. */
  7685. if (nr == LONG_MAX)
  7686. wbc.nr_to_write = LONG_MAX;
  7687. root = list_first_entry(&splice, struct btrfs_root,
  7688. delalloc_root);
  7689. root = btrfs_grab_root(root);
  7690. BUG_ON(!root);
  7691. list_move_tail(&root->delalloc_root,
  7692. &fs_info->delalloc_roots);
  7693. spin_unlock(&fs_info->delalloc_root_lock);
  7694. ret = start_delalloc_inodes(root, &wbc, false, in_reclaim_context);
  7695. btrfs_put_root(root);
  7696. if (ret < 0 || wbc.nr_to_write <= 0)
  7697. goto out;
  7698. spin_lock(&fs_info->delalloc_root_lock);
  7699. }
  7700. spin_unlock(&fs_info->delalloc_root_lock);
  7701. ret = 0;
  7702. out:
  7703. if (!list_empty(&splice)) {
  7704. spin_lock(&fs_info->delalloc_root_lock);
  7705. list_splice_tail(&splice, &fs_info->delalloc_roots);
  7706. spin_unlock(&fs_info->delalloc_root_lock);
  7707. }
  7708. mutex_unlock(&fs_info->delalloc_root_mutex);
  7709. return ret;
  7710. }
  7711. static int btrfs_symlink(struct mnt_idmap *idmap, struct inode *dir,
  7712. struct dentry *dentry, const char *symname)
  7713. {
  7714. struct btrfs_fs_info *fs_info = inode_to_fs_info(dir);
  7715. struct btrfs_trans_handle *trans;
  7716. struct btrfs_root *root = BTRFS_I(dir)->root;
  7717. struct btrfs_path *path;
  7718. struct btrfs_key key;
  7719. struct inode *inode;
  7720. struct btrfs_new_inode_args new_inode_args = {
  7721. .dir = dir,
  7722. .dentry = dentry,
  7723. };
  7724. unsigned int trans_num_items;
  7725. int err;
  7726. int name_len;
  7727. int datasize;
  7728. unsigned long ptr;
  7729. struct btrfs_file_extent_item *ei;
  7730. struct extent_buffer *leaf;
  7731. name_len = strlen(symname);
  7732. if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
  7733. return -ENAMETOOLONG;
  7734. inode = new_inode(dir->i_sb);
  7735. if (!inode)
  7736. return -ENOMEM;
  7737. inode_init_owner(idmap, inode, dir, S_IFLNK | S_IRWXUGO);
  7738. inode->i_op = &btrfs_symlink_inode_operations;
  7739. inode_nohighmem(inode);
  7740. inode->i_mapping->a_ops = &btrfs_aops;
  7741. btrfs_i_size_write(BTRFS_I(inode), name_len);
  7742. inode_set_bytes(inode, name_len);
  7743. new_inode_args.inode = inode;
  7744. err = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
  7745. if (err)
  7746. goto out_inode;
  7747. /* 1 additional item for the inline extent */
  7748. trans_num_items++;
  7749. trans = btrfs_start_transaction(root, trans_num_items);
  7750. if (IS_ERR(trans)) {
  7751. err = PTR_ERR(trans);
  7752. goto out_new_inode_args;
  7753. }
  7754. err = btrfs_create_new_inode(trans, &new_inode_args);
  7755. if (err)
  7756. goto out;
  7757. path = btrfs_alloc_path();
  7758. if (!path) {
  7759. err = -ENOMEM;
  7760. btrfs_abort_transaction(trans, err);
  7761. discard_new_inode(inode);
  7762. inode = NULL;
  7763. goto out;
  7764. }
  7765. key.objectid = btrfs_ino(BTRFS_I(inode));
  7766. key.offset = 0;
  7767. key.type = BTRFS_EXTENT_DATA_KEY;
  7768. datasize = btrfs_file_extent_calc_inline_size(name_len);
  7769. err = btrfs_insert_empty_item(trans, root, path, &key,
  7770. datasize);
  7771. if (err) {
  7772. btrfs_abort_transaction(trans, err);
  7773. btrfs_free_path(path);
  7774. discard_new_inode(inode);
  7775. inode = NULL;
  7776. goto out;
  7777. }
  7778. leaf = path->nodes[0];
  7779. ei = btrfs_item_ptr(leaf, path->slots[0],
  7780. struct btrfs_file_extent_item);
  7781. btrfs_set_file_extent_generation(leaf, ei, trans->transid);
  7782. btrfs_set_file_extent_type(leaf, ei,
  7783. BTRFS_FILE_EXTENT_INLINE);
  7784. btrfs_set_file_extent_encryption(leaf, ei, 0);
  7785. btrfs_set_file_extent_compression(leaf, ei, 0);
  7786. btrfs_set_file_extent_other_encoding(leaf, ei, 0);
  7787. btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
  7788. ptr = btrfs_file_extent_inline_start(ei);
  7789. write_extent_buffer(leaf, symname, ptr, name_len);
  7790. btrfs_mark_buffer_dirty(trans, leaf);
  7791. btrfs_free_path(path);
  7792. d_instantiate_new(dentry, inode);
  7793. err = 0;
  7794. out:
  7795. btrfs_end_transaction(trans);
  7796. btrfs_btree_balance_dirty(fs_info);
  7797. out_new_inode_args:
  7798. btrfs_new_inode_args_destroy(&new_inode_args);
  7799. out_inode:
  7800. if (err)
  7801. iput(inode);
  7802. return err;
  7803. }
  7804. static struct btrfs_trans_handle *insert_prealloc_file_extent(
  7805. struct btrfs_trans_handle *trans_in,
  7806. struct btrfs_inode *inode,
  7807. struct btrfs_key *ins,
  7808. u64 file_offset)
  7809. {
  7810. struct btrfs_file_extent_item stack_fi;
  7811. struct btrfs_replace_extent_info extent_info;
  7812. struct btrfs_trans_handle *trans = trans_in;
  7813. struct btrfs_path *path;
  7814. u64 start = ins->objectid;
  7815. u64 len = ins->offset;
  7816. u64 qgroup_released = 0;
  7817. int ret;
  7818. memset(&stack_fi, 0, sizeof(stack_fi));
  7819. btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_PREALLOC);
  7820. btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, start);
  7821. btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi, len);
  7822. btrfs_set_stack_file_extent_num_bytes(&stack_fi, len);
  7823. btrfs_set_stack_file_extent_ram_bytes(&stack_fi, len);
  7824. btrfs_set_stack_file_extent_compression(&stack_fi, BTRFS_COMPRESS_NONE);
  7825. /* Encryption and other encoding is reserved and all 0 */
  7826. ret = btrfs_qgroup_release_data(inode, file_offset, len, &qgroup_released);
  7827. if (ret < 0)
  7828. return ERR_PTR(ret);
  7829. if (trans) {
  7830. ret = insert_reserved_file_extent(trans, inode,
  7831. file_offset, &stack_fi,
  7832. true, qgroup_released);
  7833. if (ret)
  7834. goto free_qgroup;
  7835. return trans;
  7836. }
  7837. extent_info.disk_offset = start;
  7838. extent_info.disk_len = len;
  7839. extent_info.data_offset = 0;
  7840. extent_info.data_len = len;
  7841. extent_info.file_offset = file_offset;
  7842. extent_info.extent_buf = (char *)&stack_fi;
  7843. extent_info.is_new_extent = true;
  7844. extent_info.update_times = true;
  7845. extent_info.qgroup_reserved = qgroup_released;
  7846. extent_info.insertions = 0;
  7847. path = btrfs_alloc_path();
  7848. if (!path) {
  7849. ret = -ENOMEM;
  7850. goto free_qgroup;
  7851. }
  7852. ret = btrfs_replace_file_extents(inode, path, file_offset,
  7853. file_offset + len - 1, &extent_info,
  7854. &trans);
  7855. btrfs_free_path(path);
  7856. if (ret)
  7857. goto free_qgroup;
  7858. return trans;
  7859. free_qgroup:
  7860. /*
  7861. * We have released qgroup data range at the beginning of the function,
  7862. * and normally qgroup_released bytes will be freed when committing
  7863. * transaction.
  7864. * But if we error out early, we have to free what we have released
  7865. * or we leak qgroup data reservation.
  7866. */
  7867. btrfs_qgroup_free_refroot(inode->root->fs_info,
  7868. btrfs_root_id(inode->root), qgroup_released,
  7869. BTRFS_QGROUP_RSV_DATA);
  7870. return ERR_PTR(ret);
  7871. }
  7872. static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
  7873. u64 start, u64 num_bytes, u64 min_size,
  7874. loff_t actual_len, u64 *alloc_hint,
  7875. struct btrfs_trans_handle *trans)
  7876. {
  7877. struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
  7878. struct extent_map *em;
  7879. struct btrfs_root *root = BTRFS_I(inode)->root;
  7880. struct btrfs_key ins;
  7881. u64 cur_offset = start;
  7882. u64 clear_offset = start;
  7883. u64 i_size;
  7884. u64 cur_bytes;
  7885. u64 last_alloc = (u64)-1;
  7886. int ret = 0;
  7887. bool own_trans = true;
  7888. u64 end = start + num_bytes - 1;
  7889. if (trans)
  7890. own_trans = false;
  7891. while (num_bytes > 0) {
  7892. cur_bytes = min_t(u64, num_bytes, SZ_256M);
  7893. cur_bytes = max(cur_bytes, min_size);
  7894. /*
  7895. * If we are severely fragmented we could end up with really
  7896. * small allocations, so if the allocator is returning small
  7897. * chunks lets make its job easier by only searching for those
  7898. * sized chunks.
  7899. */
  7900. cur_bytes = min(cur_bytes, last_alloc);
  7901. ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
  7902. min_size, 0, *alloc_hint, &ins, 1, 0);
  7903. if (ret)
  7904. break;
  7905. /*
  7906. * We've reserved this space, and thus converted it from
  7907. * ->bytes_may_use to ->bytes_reserved. Any error that happens
  7908. * from here on out we will only need to clear our reservation
  7909. * for the remaining unreserved area, so advance our
  7910. * clear_offset by our extent size.
  7911. */
  7912. clear_offset += ins.offset;
  7913. last_alloc = ins.offset;
  7914. trans = insert_prealloc_file_extent(trans, BTRFS_I(inode),
  7915. &ins, cur_offset);
  7916. /*
  7917. * Now that we inserted the prealloc extent we can finally
  7918. * decrement the number of reservations in the block group.
  7919. * If we did it before, we could race with relocation and have
  7920. * relocation miss the reserved extent, making it fail later.
  7921. */
  7922. btrfs_dec_block_group_reservations(fs_info, ins.objectid);
  7923. if (IS_ERR(trans)) {
  7924. ret = PTR_ERR(trans);
  7925. btrfs_free_reserved_extent(fs_info, ins.objectid,
  7926. ins.offset, 0);
  7927. break;
  7928. }
  7929. em = alloc_extent_map();
  7930. if (!em) {
  7931. btrfs_drop_extent_map_range(BTRFS_I(inode), cur_offset,
  7932. cur_offset + ins.offset - 1, false);
  7933. btrfs_set_inode_full_sync(BTRFS_I(inode));
  7934. goto next;
  7935. }
  7936. em->start = cur_offset;
  7937. em->len = ins.offset;
  7938. em->disk_bytenr = ins.objectid;
  7939. em->offset = 0;
  7940. em->disk_num_bytes = ins.offset;
  7941. em->ram_bytes = ins.offset;
  7942. em->flags |= EXTENT_FLAG_PREALLOC;
  7943. em->generation = trans->transid;
  7944. ret = btrfs_replace_extent_map_range(BTRFS_I(inode), em, true);
  7945. free_extent_map(em);
  7946. next:
  7947. num_bytes -= ins.offset;
  7948. cur_offset += ins.offset;
  7949. *alloc_hint = ins.objectid + ins.offset;
  7950. inode_inc_iversion(inode);
  7951. inode_set_ctime_current(inode);
  7952. BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
  7953. if (!(mode & FALLOC_FL_KEEP_SIZE) &&
  7954. (actual_len > inode->i_size) &&
  7955. (cur_offset > inode->i_size)) {
  7956. if (cur_offset > actual_len)
  7957. i_size = actual_len;
  7958. else
  7959. i_size = cur_offset;
  7960. i_size_write(inode, i_size);
  7961. btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
  7962. }
  7963. ret = btrfs_update_inode(trans, BTRFS_I(inode));
  7964. if (ret) {
  7965. btrfs_abort_transaction(trans, ret);
  7966. if (own_trans)
  7967. btrfs_end_transaction(trans);
  7968. break;
  7969. }
  7970. if (own_trans) {
  7971. btrfs_end_transaction(trans);
  7972. trans = NULL;
  7973. }
  7974. }
  7975. if (clear_offset < end)
  7976. btrfs_free_reserved_data_space(BTRFS_I(inode), NULL, clear_offset,
  7977. end - clear_offset + 1);
  7978. return ret;
  7979. }
  7980. int btrfs_prealloc_file_range(struct inode *inode, int mode,
  7981. u64 start, u64 num_bytes, u64 min_size,
  7982. loff_t actual_len, u64 *alloc_hint)
  7983. {
  7984. return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
  7985. min_size, actual_len, alloc_hint,
  7986. NULL);
  7987. }
  7988. int btrfs_prealloc_file_range_trans(struct inode *inode,
  7989. struct btrfs_trans_handle *trans, int mode,
  7990. u64 start, u64 num_bytes, u64 min_size,
  7991. loff_t actual_len, u64 *alloc_hint)
  7992. {
  7993. return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
  7994. min_size, actual_len, alloc_hint, trans);
  7995. }
  7996. static int btrfs_permission(struct mnt_idmap *idmap,
  7997. struct inode *inode, int mask)
  7998. {
  7999. struct btrfs_root *root = BTRFS_I(inode)->root;
  8000. umode_t mode = inode->i_mode;
  8001. if (mask & MAY_WRITE &&
  8002. (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
  8003. if (btrfs_root_readonly(root))
  8004. return -EROFS;
  8005. if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
  8006. return -EACCES;
  8007. }
  8008. return generic_permission(idmap, inode, mask);
  8009. }
  8010. static int btrfs_tmpfile(struct mnt_idmap *idmap, struct inode *dir,
  8011. struct file *file, umode_t mode)
  8012. {
  8013. struct btrfs_fs_info *fs_info = inode_to_fs_info(dir);
  8014. struct btrfs_trans_handle *trans;
  8015. struct btrfs_root *root = BTRFS_I(dir)->root;
  8016. struct inode *inode;
  8017. struct btrfs_new_inode_args new_inode_args = {
  8018. .dir = dir,
  8019. .dentry = file->f_path.dentry,
  8020. .orphan = true,
  8021. };
  8022. unsigned int trans_num_items;
  8023. int ret;
  8024. inode = new_inode(dir->i_sb);
  8025. if (!inode)
  8026. return -ENOMEM;
  8027. inode_init_owner(idmap, inode, dir, mode);
  8028. inode->i_fop = &btrfs_file_operations;
  8029. inode->i_op = &btrfs_file_inode_operations;
  8030. inode->i_mapping->a_ops = &btrfs_aops;
  8031. new_inode_args.inode = inode;
  8032. ret = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
  8033. if (ret)
  8034. goto out_inode;
  8035. trans = btrfs_start_transaction(root, trans_num_items);
  8036. if (IS_ERR(trans)) {
  8037. ret = PTR_ERR(trans);
  8038. goto out_new_inode_args;
  8039. }
  8040. ret = btrfs_create_new_inode(trans, &new_inode_args);
  8041. /*
  8042. * We set number of links to 0 in btrfs_create_new_inode(), and here we
  8043. * set it to 1 because d_tmpfile() will issue a warning if the count is
  8044. * 0, through:
  8045. *
  8046. * d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
  8047. */
  8048. set_nlink(inode, 1);
  8049. if (!ret) {
  8050. d_tmpfile(file, inode);
  8051. unlock_new_inode(inode);
  8052. mark_inode_dirty(inode);
  8053. }
  8054. btrfs_end_transaction(trans);
  8055. btrfs_btree_balance_dirty(fs_info);
  8056. out_new_inode_args:
  8057. btrfs_new_inode_args_destroy(&new_inode_args);
  8058. out_inode:
  8059. if (ret)
  8060. iput(inode);
  8061. return finish_open_simple(file, ret);
  8062. }
  8063. void btrfs_set_range_writeback(struct btrfs_inode *inode, u64 start, u64 end)
  8064. {
  8065. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  8066. unsigned long index = start >> PAGE_SHIFT;
  8067. unsigned long end_index = end >> PAGE_SHIFT;
  8068. struct folio *folio;
  8069. u32 len;
  8070. ASSERT(end + 1 - start <= U32_MAX);
  8071. len = end + 1 - start;
  8072. while (index <= end_index) {
  8073. folio = __filemap_get_folio(inode->vfs_inode.i_mapping, index, 0, 0);
  8074. ASSERT(!IS_ERR(folio)); /* folios should be in the extent_io_tree */
  8075. /* This is for data, which doesn't yet support larger folio. */
  8076. ASSERT(folio_order(folio) == 0);
  8077. btrfs_folio_set_writeback(fs_info, folio, start, len);
  8078. folio_put(folio);
  8079. index++;
  8080. }
  8081. }
  8082. int btrfs_encoded_io_compression_from_extent(struct btrfs_fs_info *fs_info,
  8083. int compress_type)
  8084. {
  8085. switch (compress_type) {
  8086. case BTRFS_COMPRESS_NONE:
  8087. return BTRFS_ENCODED_IO_COMPRESSION_NONE;
  8088. case BTRFS_COMPRESS_ZLIB:
  8089. return BTRFS_ENCODED_IO_COMPRESSION_ZLIB;
  8090. case BTRFS_COMPRESS_LZO:
  8091. /*
  8092. * The LZO format depends on the sector size. 64K is the maximum
  8093. * sector size that we support.
  8094. */
  8095. if (fs_info->sectorsize < SZ_4K || fs_info->sectorsize > SZ_64K)
  8096. return -EINVAL;
  8097. return BTRFS_ENCODED_IO_COMPRESSION_LZO_4K +
  8098. (fs_info->sectorsize_bits - 12);
  8099. case BTRFS_COMPRESS_ZSTD:
  8100. return BTRFS_ENCODED_IO_COMPRESSION_ZSTD;
  8101. default:
  8102. return -EUCLEAN;
  8103. }
  8104. }
  8105. static ssize_t btrfs_encoded_read_inline(
  8106. struct kiocb *iocb,
  8107. struct iov_iter *iter, u64 start,
  8108. u64 lockend,
  8109. struct extent_state **cached_state,
  8110. u64 extent_start, size_t count,
  8111. struct btrfs_ioctl_encoded_io_args *encoded,
  8112. bool *unlocked)
  8113. {
  8114. struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
  8115. struct btrfs_root *root = inode->root;
  8116. struct btrfs_fs_info *fs_info = root->fs_info;
  8117. struct extent_io_tree *io_tree = &inode->io_tree;
  8118. struct btrfs_path *path;
  8119. struct extent_buffer *leaf;
  8120. struct btrfs_file_extent_item *item;
  8121. u64 ram_bytes;
  8122. unsigned long ptr;
  8123. void *tmp;
  8124. ssize_t ret;
  8125. path = btrfs_alloc_path();
  8126. if (!path) {
  8127. ret = -ENOMEM;
  8128. goto out;
  8129. }
  8130. ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
  8131. extent_start, 0);
  8132. if (ret) {
  8133. if (ret > 0) {
  8134. /* The extent item disappeared? */
  8135. ret = -EIO;
  8136. }
  8137. goto out;
  8138. }
  8139. leaf = path->nodes[0];
  8140. item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
  8141. ram_bytes = btrfs_file_extent_ram_bytes(leaf, item);
  8142. ptr = btrfs_file_extent_inline_start(item);
  8143. encoded->len = min_t(u64, extent_start + ram_bytes,
  8144. inode->vfs_inode.i_size) - iocb->ki_pos;
  8145. ret = btrfs_encoded_io_compression_from_extent(fs_info,
  8146. btrfs_file_extent_compression(leaf, item));
  8147. if (ret < 0)
  8148. goto out;
  8149. encoded->compression = ret;
  8150. if (encoded->compression) {
  8151. size_t inline_size;
  8152. inline_size = btrfs_file_extent_inline_item_len(leaf,
  8153. path->slots[0]);
  8154. if (inline_size > count) {
  8155. ret = -ENOBUFS;
  8156. goto out;
  8157. }
  8158. count = inline_size;
  8159. encoded->unencoded_len = ram_bytes;
  8160. encoded->unencoded_offset = iocb->ki_pos - extent_start;
  8161. } else {
  8162. count = min_t(u64, count, encoded->len);
  8163. encoded->len = count;
  8164. encoded->unencoded_len = count;
  8165. ptr += iocb->ki_pos - extent_start;
  8166. }
  8167. tmp = kmalloc(count, GFP_NOFS);
  8168. if (!tmp) {
  8169. ret = -ENOMEM;
  8170. goto out;
  8171. }
  8172. read_extent_buffer(leaf, tmp, ptr, count);
  8173. btrfs_release_path(path);
  8174. unlock_extent(io_tree, start, lockend, cached_state);
  8175. btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
  8176. *unlocked = true;
  8177. ret = copy_to_iter(tmp, count, iter);
  8178. if (ret != count)
  8179. ret = -EFAULT;
  8180. kfree(tmp);
  8181. out:
  8182. btrfs_free_path(path);
  8183. return ret;
  8184. }
  8185. struct btrfs_encoded_read_private {
  8186. wait_queue_head_t wait;
  8187. atomic_t pending;
  8188. blk_status_t status;
  8189. };
  8190. static void btrfs_encoded_read_endio(struct btrfs_bio *bbio)
  8191. {
  8192. struct btrfs_encoded_read_private *priv = bbio->private;
  8193. if (bbio->bio.bi_status) {
  8194. /*
  8195. * The memory barrier implied by the atomic_dec_return() here
  8196. * pairs with the memory barrier implied by the
  8197. * atomic_dec_return() or io_wait_event() in
  8198. * btrfs_encoded_read_regular_fill_pages() to ensure that this
  8199. * write is observed before the load of status in
  8200. * btrfs_encoded_read_regular_fill_pages().
  8201. */
  8202. WRITE_ONCE(priv->status, bbio->bio.bi_status);
  8203. }
  8204. if (atomic_dec_and_test(&priv->pending))
  8205. wake_up(&priv->wait);
  8206. bio_put(&bbio->bio);
  8207. }
  8208. int btrfs_encoded_read_regular_fill_pages(struct btrfs_inode *inode,
  8209. u64 disk_bytenr, u64 disk_io_size,
  8210. struct page **pages)
  8211. {
  8212. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  8213. struct btrfs_encoded_read_private *priv;
  8214. unsigned long i = 0;
  8215. struct btrfs_bio *bbio;
  8216. int ret;
  8217. priv = kmalloc(sizeof(struct btrfs_encoded_read_private), GFP_NOFS);
  8218. if (!priv)
  8219. return -ENOMEM;
  8220. init_waitqueue_head(&priv->wait);
  8221. atomic_set(&priv->pending, 1);
  8222. priv->status = 0;
  8223. bbio = btrfs_bio_alloc(BIO_MAX_VECS, REQ_OP_READ, fs_info,
  8224. btrfs_encoded_read_endio, priv);
  8225. bbio->bio.bi_iter.bi_sector = disk_bytenr >> SECTOR_SHIFT;
  8226. bbio->inode = inode;
  8227. do {
  8228. size_t bytes = min_t(u64, disk_io_size, PAGE_SIZE);
  8229. if (bio_add_page(&bbio->bio, pages[i], bytes, 0) < bytes) {
  8230. atomic_inc(&priv->pending);
  8231. btrfs_submit_bbio(bbio, 0);
  8232. bbio = btrfs_bio_alloc(BIO_MAX_VECS, REQ_OP_READ, fs_info,
  8233. btrfs_encoded_read_endio, priv);
  8234. bbio->bio.bi_iter.bi_sector = disk_bytenr >> SECTOR_SHIFT;
  8235. bbio->inode = inode;
  8236. continue;
  8237. }
  8238. i++;
  8239. disk_bytenr += bytes;
  8240. disk_io_size -= bytes;
  8241. } while (disk_io_size);
  8242. atomic_inc(&priv->pending);
  8243. btrfs_submit_bbio(bbio, 0);
  8244. if (atomic_dec_return(&priv->pending))
  8245. io_wait_event(priv->wait, !atomic_read(&priv->pending));
  8246. /* See btrfs_encoded_read_endio() for ordering. */
  8247. ret = blk_status_to_errno(READ_ONCE(priv->status));
  8248. kfree(priv);
  8249. return ret;
  8250. }
  8251. ssize_t btrfs_encoded_read_regular(struct kiocb *iocb, struct iov_iter *iter,
  8252. u64 start, u64 lockend,
  8253. struct extent_state **cached_state,
  8254. u64 disk_bytenr, u64 disk_io_size,
  8255. size_t count, bool compressed, bool *unlocked)
  8256. {
  8257. struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
  8258. struct extent_io_tree *io_tree = &inode->io_tree;
  8259. struct page **pages;
  8260. unsigned long nr_pages, i;
  8261. u64 cur;
  8262. size_t page_offset;
  8263. ssize_t ret;
  8264. nr_pages = DIV_ROUND_UP(disk_io_size, PAGE_SIZE);
  8265. pages = kcalloc(nr_pages, sizeof(struct page *), GFP_NOFS);
  8266. if (!pages)
  8267. return -ENOMEM;
  8268. ret = btrfs_alloc_page_array(nr_pages, pages, false);
  8269. if (ret) {
  8270. ret = -ENOMEM;
  8271. goto out;
  8272. }
  8273. ret = btrfs_encoded_read_regular_fill_pages(inode, disk_bytenr,
  8274. disk_io_size, pages);
  8275. if (ret)
  8276. goto out;
  8277. unlock_extent(io_tree, start, lockend, cached_state);
  8278. btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
  8279. *unlocked = true;
  8280. if (compressed) {
  8281. i = 0;
  8282. page_offset = 0;
  8283. } else {
  8284. i = (iocb->ki_pos - start) >> PAGE_SHIFT;
  8285. page_offset = (iocb->ki_pos - start) & (PAGE_SIZE - 1);
  8286. }
  8287. cur = 0;
  8288. while (cur < count) {
  8289. size_t bytes = min_t(size_t, count - cur,
  8290. PAGE_SIZE - page_offset);
  8291. if (copy_page_to_iter(pages[i], page_offset, bytes,
  8292. iter) != bytes) {
  8293. ret = -EFAULT;
  8294. goto out;
  8295. }
  8296. i++;
  8297. cur += bytes;
  8298. page_offset = 0;
  8299. }
  8300. ret = count;
  8301. out:
  8302. for (i = 0; i < nr_pages; i++) {
  8303. if (pages[i])
  8304. __free_page(pages[i]);
  8305. }
  8306. kfree(pages);
  8307. return ret;
  8308. }
  8309. ssize_t btrfs_encoded_read(struct kiocb *iocb, struct iov_iter *iter,
  8310. struct btrfs_ioctl_encoded_io_args *encoded,
  8311. struct extent_state **cached_state,
  8312. u64 *disk_bytenr, u64 *disk_io_size)
  8313. {
  8314. struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
  8315. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  8316. struct extent_io_tree *io_tree = &inode->io_tree;
  8317. ssize_t ret;
  8318. size_t count = iov_iter_count(iter);
  8319. u64 start, lockend;
  8320. struct extent_map *em;
  8321. bool unlocked = false;
  8322. file_accessed(iocb->ki_filp);
  8323. btrfs_inode_lock(inode, BTRFS_ILOCK_SHARED);
  8324. if (iocb->ki_pos >= inode->vfs_inode.i_size) {
  8325. btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
  8326. return 0;
  8327. }
  8328. start = ALIGN_DOWN(iocb->ki_pos, fs_info->sectorsize);
  8329. /*
  8330. * We don't know how long the extent containing iocb->ki_pos is, but if
  8331. * it's compressed we know that it won't be longer than this.
  8332. */
  8333. lockend = start + BTRFS_MAX_UNCOMPRESSED - 1;
  8334. for (;;) {
  8335. struct btrfs_ordered_extent *ordered;
  8336. ret = btrfs_wait_ordered_range(inode, start,
  8337. lockend - start + 1);
  8338. if (ret)
  8339. goto out_unlock_inode;
  8340. lock_extent(io_tree, start, lockend, cached_state);
  8341. ordered = btrfs_lookup_ordered_range(inode, start,
  8342. lockend - start + 1);
  8343. if (!ordered)
  8344. break;
  8345. btrfs_put_ordered_extent(ordered);
  8346. unlock_extent(io_tree, start, lockend, cached_state);
  8347. cond_resched();
  8348. }
  8349. em = btrfs_get_extent(inode, NULL, start, lockend - start + 1);
  8350. if (IS_ERR(em)) {
  8351. ret = PTR_ERR(em);
  8352. goto out_unlock_extent;
  8353. }
  8354. if (em->disk_bytenr == EXTENT_MAP_INLINE) {
  8355. u64 extent_start = em->start;
  8356. /*
  8357. * For inline extents we get everything we need out of the
  8358. * extent item.
  8359. */
  8360. free_extent_map(em);
  8361. em = NULL;
  8362. ret = btrfs_encoded_read_inline(iocb, iter, start, lockend,
  8363. cached_state, extent_start,
  8364. count, encoded, &unlocked);
  8365. goto out;
  8366. }
  8367. /*
  8368. * We only want to return up to EOF even if the extent extends beyond
  8369. * that.
  8370. */
  8371. encoded->len = min_t(u64, extent_map_end(em),
  8372. inode->vfs_inode.i_size) - iocb->ki_pos;
  8373. if (em->disk_bytenr == EXTENT_MAP_HOLE ||
  8374. (em->flags & EXTENT_FLAG_PREALLOC)) {
  8375. *disk_bytenr = EXTENT_MAP_HOLE;
  8376. count = min_t(u64, count, encoded->len);
  8377. encoded->len = count;
  8378. encoded->unencoded_len = count;
  8379. } else if (extent_map_is_compressed(em)) {
  8380. *disk_bytenr = em->disk_bytenr;
  8381. /*
  8382. * Bail if the buffer isn't large enough to return the whole
  8383. * compressed extent.
  8384. */
  8385. if (em->disk_num_bytes > count) {
  8386. ret = -ENOBUFS;
  8387. goto out_em;
  8388. }
  8389. *disk_io_size = em->disk_num_bytes;
  8390. count = em->disk_num_bytes;
  8391. encoded->unencoded_len = em->ram_bytes;
  8392. encoded->unencoded_offset = iocb->ki_pos - (em->start - em->offset);
  8393. ret = btrfs_encoded_io_compression_from_extent(fs_info,
  8394. extent_map_compression(em));
  8395. if (ret < 0)
  8396. goto out_em;
  8397. encoded->compression = ret;
  8398. } else {
  8399. *disk_bytenr = extent_map_block_start(em) + (start - em->start);
  8400. if (encoded->len > count)
  8401. encoded->len = count;
  8402. /*
  8403. * Don't read beyond what we locked. This also limits the page
  8404. * allocations that we'll do.
  8405. */
  8406. *disk_io_size = min(lockend + 1, iocb->ki_pos + encoded->len) - start;
  8407. count = start + *disk_io_size - iocb->ki_pos;
  8408. encoded->len = count;
  8409. encoded->unencoded_len = count;
  8410. *disk_io_size = ALIGN(*disk_io_size, fs_info->sectorsize);
  8411. }
  8412. free_extent_map(em);
  8413. em = NULL;
  8414. if (*disk_bytenr == EXTENT_MAP_HOLE) {
  8415. unlock_extent(io_tree, start, lockend, cached_state);
  8416. btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
  8417. unlocked = true;
  8418. ret = iov_iter_zero(count, iter);
  8419. if (ret != count)
  8420. ret = -EFAULT;
  8421. } else {
  8422. ret = -EIOCBQUEUED;
  8423. goto out_em;
  8424. }
  8425. out:
  8426. if (ret >= 0)
  8427. iocb->ki_pos += encoded->len;
  8428. out_em:
  8429. free_extent_map(em);
  8430. out_unlock_extent:
  8431. /* Leave inode and extent locked if we need to do a read. */
  8432. if (!unlocked && ret != -EIOCBQUEUED)
  8433. unlock_extent(io_tree, start, lockend, cached_state);
  8434. out_unlock_inode:
  8435. if (!unlocked && ret != -EIOCBQUEUED)
  8436. btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
  8437. return ret;
  8438. }
  8439. ssize_t btrfs_do_encoded_write(struct kiocb *iocb, struct iov_iter *from,
  8440. const struct btrfs_ioctl_encoded_io_args *encoded)
  8441. {
  8442. struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
  8443. struct btrfs_root *root = inode->root;
  8444. struct btrfs_fs_info *fs_info = root->fs_info;
  8445. struct extent_io_tree *io_tree = &inode->io_tree;
  8446. struct extent_changeset *data_reserved = NULL;
  8447. struct extent_state *cached_state = NULL;
  8448. struct btrfs_ordered_extent *ordered;
  8449. struct btrfs_file_extent file_extent;
  8450. int compression;
  8451. size_t orig_count;
  8452. u64 start, end;
  8453. u64 num_bytes, ram_bytes, disk_num_bytes;
  8454. unsigned long nr_folios, i;
  8455. struct folio **folios;
  8456. struct btrfs_key ins;
  8457. bool extent_reserved = false;
  8458. struct extent_map *em;
  8459. ssize_t ret;
  8460. switch (encoded->compression) {
  8461. case BTRFS_ENCODED_IO_COMPRESSION_ZLIB:
  8462. compression = BTRFS_COMPRESS_ZLIB;
  8463. break;
  8464. case BTRFS_ENCODED_IO_COMPRESSION_ZSTD:
  8465. compression = BTRFS_COMPRESS_ZSTD;
  8466. break;
  8467. case BTRFS_ENCODED_IO_COMPRESSION_LZO_4K:
  8468. case BTRFS_ENCODED_IO_COMPRESSION_LZO_8K:
  8469. case BTRFS_ENCODED_IO_COMPRESSION_LZO_16K:
  8470. case BTRFS_ENCODED_IO_COMPRESSION_LZO_32K:
  8471. case BTRFS_ENCODED_IO_COMPRESSION_LZO_64K:
  8472. /* The sector size must match for LZO. */
  8473. if (encoded->compression -
  8474. BTRFS_ENCODED_IO_COMPRESSION_LZO_4K + 12 !=
  8475. fs_info->sectorsize_bits)
  8476. return -EINVAL;
  8477. compression = BTRFS_COMPRESS_LZO;
  8478. break;
  8479. default:
  8480. return -EINVAL;
  8481. }
  8482. if (encoded->encryption != BTRFS_ENCODED_IO_ENCRYPTION_NONE)
  8483. return -EINVAL;
  8484. /*
  8485. * Compressed extents should always have checksums, so error out if we
  8486. * have a NOCOW file or inode was created while mounted with NODATASUM.
  8487. */
  8488. if (inode->flags & BTRFS_INODE_NODATASUM)
  8489. return -EINVAL;
  8490. orig_count = iov_iter_count(from);
  8491. /* The extent size must be sane. */
  8492. if (encoded->unencoded_len > BTRFS_MAX_UNCOMPRESSED ||
  8493. orig_count > BTRFS_MAX_COMPRESSED || orig_count == 0)
  8494. return -EINVAL;
  8495. /*
  8496. * The compressed data must be smaller than the decompressed data.
  8497. *
  8498. * It's of course possible for data to compress to larger or the same
  8499. * size, but the buffered I/O path falls back to no compression for such
  8500. * data, and we don't want to break any assumptions by creating these
  8501. * extents.
  8502. *
  8503. * Note that this is less strict than the current check we have that the
  8504. * compressed data must be at least one sector smaller than the
  8505. * decompressed data. We only want to enforce the weaker requirement
  8506. * from old kernels that it is at least one byte smaller.
  8507. */
  8508. if (orig_count >= encoded->unencoded_len)
  8509. return -EINVAL;
  8510. /* The extent must start on a sector boundary. */
  8511. start = iocb->ki_pos;
  8512. if (!IS_ALIGNED(start, fs_info->sectorsize))
  8513. return -EINVAL;
  8514. /*
  8515. * The extent must end on a sector boundary. However, we allow a write
  8516. * which ends at or extends i_size to have an unaligned length; we round
  8517. * up the extent size and set i_size to the unaligned end.
  8518. */
  8519. if (start + encoded->len < inode->vfs_inode.i_size &&
  8520. !IS_ALIGNED(start + encoded->len, fs_info->sectorsize))
  8521. return -EINVAL;
  8522. /* Finally, the offset in the unencoded data must be sector-aligned. */
  8523. if (!IS_ALIGNED(encoded->unencoded_offset, fs_info->sectorsize))
  8524. return -EINVAL;
  8525. num_bytes = ALIGN(encoded->len, fs_info->sectorsize);
  8526. ram_bytes = ALIGN(encoded->unencoded_len, fs_info->sectorsize);
  8527. end = start + num_bytes - 1;
  8528. /*
  8529. * If the extent cannot be inline, the compressed data on disk must be
  8530. * sector-aligned. For convenience, we extend it with zeroes if it
  8531. * isn't.
  8532. */
  8533. disk_num_bytes = ALIGN(orig_count, fs_info->sectorsize);
  8534. nr_folios = DIV_ROUND_UP(disk_num_bytes, PAGE_SIZE);
  8535. folios = kvcalloc(nr_folios, sizeof(struct page *), GFP_KERNEL_ACCOUNT);
  8536. if (!folios)
  8537. return -ENOMEM;
  8538. for (i = 0; i < nr_folios; i++) {
  8539. size_t bytes = min_t(size_t, PAGE_SIZE, iov_iter_count(from));
  8540. char *kaddr;
  8541. folios[i] = folio_alloc(GFP_KERNEL_ACCOUNT, 0);
  8542. if (!folios[i]) {
  8543. ret = -ENOMEM;
  8544. goto out_folios;
  8545. }
  8546. kaddr = kmap_local_folio(folios[i], 0);
  8547. if (copy_from_iter(kaddr, bytes, from) != bytes) {
  8548. kunmap_local(kaddr);
  8549. ret = -EFAULT;
  8550. goto out_folios;
  8551. }
  8552. if (bytes < PAGE_SIZE)
  8553. memset(kaddr + bytes, 0, PAGE_SIZE - bytes);
  8554. kunmap_local(kaddr);
  8555. }
  8556. for (;;) {
  8557. struct btrfs_ordered_extent *ordered;
  8558. ret = btrfs_wait_ordered_range(inode, start, num_bytes);
  8559. if (ret)
  8560. goto out_folios;
  8561. ret = invalidate_inode_pages2_range(inode->vfs_inode.i_mapping,
  8562. start >> PAGE_SHIFT,
  8563. end >> PAGE_SHIFT);
  8564. if (ret)
  8565. goto out_folios;
  8566. lock_extent(io_tree, start, end, &cached_state);
  8567. ordered = btrfs_lookup_ordered_range(inode, start, num_bytes);
  8568. if (!ordered &&
  8569. !filemap_range_has_page(inode->vfs_inode.i_mapping, start, end))
  8570. break;
  8571. if (ordered)
  8572. btrfs_put_ordered_extent(ordered);
  8573. unlock_extent(io_tree, start, end, &cached_state);
  8574. cond_resched();
  8575. }
  8576. /*
  8577. * We don't use the higher-level delalloc space functions because our
  8578. * num_bytes and disk_num_bytes are different.
  8579. */
  8580. ret = btrfs_alloc_data_chunk_ondemand(inode, disk_num_bytes);
  8581. if (ret)
  8582. goto out_unlock;
  8583. ret = btrfs_qgroup_reserve_data(inode, &data_reserved, start, num_bytes);
  8584. if (ret)
  8585. goto out_free_data_space;
  8586. ret = btrfs_delalloc_reserve_metadata(inode, num_bytes, disk_num_bytes,
  8587. false);
  8588. if (ret)
  8589. goto out_qgroup_free_data;
  8590. /* Try an inline extent first. */
  8591. if (encoded->unencoded_len == encoded->len &&
  8592. encoded->unencoded_offset == 0 &&
  8593. can_cow_file_range_inline(inode, start, encoded->len, orig_count)) {
  8594. ret = __cow_file_range_inline(inode, start, encoded->len,
  8595. orig_count, compression, folios[0],
  8596. true);
  8597. if (ret <= 0) {
  8598. if (ret == 0)
  8599. ret = orig_count;
  8600. goto out_delalloc_release;
  8601. }
  8602. }
  8603. ret = btrfs_reserve_extent(root, disk_num_bytes, disk_num_bytes,
  8604. disk_num_bytes, 0, 0, &ins, 1, 1);
  8605. if (ret)
  8606. goto out_delalloc_release;
  8607. extent_reserved = true;
  8608. file_extent.disk_bytenr = ins.objectid;
  8609. file_extent.disk_num_bytes = ins.offset;
  8610. file_extent.num_bytes = num_bytes;
  8611. file_extent.ram_bytes = ram_bytes;
  8612. file_extent.offset = encoded->unencoded_offset;
  8613. file_extent.compression = compression;
  8614. em = btrfs_create_io_em(inode, start, &file_extent, BTRFS_ORDERED_COMPRESSED);
  8615. if (IS_ERR(em)) {
  8616. ret = PTR_ERR(em);
  8617. goto out_free_reserved;
  8618. }
  8619. free_extent_map(em);
  8620. ordered = btrfs_alloc_ordered_extent(inode, start, &file_extent,
  8621. (1U << BTRFS_ORDERED_ENCODED) |
  8622. (1U << BTRFS_ORDERED_COMPRESSED));
  8623. if (IS_ERR(ordered)) {
  8624. btrfs_drop_extent_map_range(inode, start, end, false);
  8625. ret = PTR_ERR(ordered);
  8626. goto out_free_reserved;
  8627. }
  8628. btrfs_dec_block_group_reservations(fs_info, ins.objectid);
  8629. if (start + encoded->len > inode->vfs_inode.i_size)
  8630. i_size_write(&inode->vfs_inode, start + encoded->len);
  8631. unlock_extent(io_tree, start, end, &cached_state);
  8632. btrfs_delalloc_release_extents(inode, num_bytes);
  8633. btrfs_submit_compressed_write(ordered, folios, nr_folios, 0, false);
  8634. ret = orig_count;
  8635. goto out;
  8636. out_free_reserved:
  8637. btrfs_dec_block_group_reservations(fs_info, ins.objectid);
  8638. btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 1);
  8639. out_delalloc_release:
  8640. btrfs_delalloc_release_extents(inode, num_bytes);
  8641. btrfs_delalloc_release_metadata(inode, disk_num_bytes, ret < 0);
  8642. out_qgroup_free_data:
  8643. if (ret < 0)
  8644. btrfs_qgroup_free_data(inode, data_reserved, start, num_bytes, NULL);
  8645. out_free_data_space:
  8646. /*
  8647. * If btrfs_reserve_extent() succeeded, then we already decremented
  8648. * bytes_may_use.
  8649. */
  8650. if (!extent_reserved)
  8651. btrfs_free_reserved_data_space_noquota(fs_info, disk_num_bytes);
  8652. out_unlock:
  8653. unlock_extent(io_tree, start, end, &cached_state);
  8654. out_folios:
  8655. for (i = 0; i < nr_folios; i++) {
  8656. if (folios[i])
  8657. folio_put(folios[i]);
  8658. }
  8659. kvfree(folios);
  8660. out:
  8661. if (ret >= 0)
  8662. iocb->ki_pos += encoded->len;
  8663. return ret;
  8664. }
  8665. #ifdef CONFIG_SWAP
  8666. /*
  8667. * Add an entry indicating a block group or device which is pinned by a
  8668. * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
  8669. * negative errno on failure.
  8670. */
  8671. static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
  8672. bool is_block_group)
  8673. {
  8674. struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
  8675. struct btrfs_swapfile_pin *sp, *entry;
  8676. struct rb_node **p;
  8677. struct rb_node *parent = NULL;
  8678. sp = kmalloc(sizeof(*sp), GFP_NOFS);
  8679. if (!sp)
  8680. return -ENOMEM;
  8681. sp->ptr = ptr;
  8682. sp->inode = inode;
  8683. sp->is_block_group = is_block_group;
  8684. sp->bg_extent_count = 1;
  8685. spin_lock(&fs_info->swapfile_pins_lock);
  8686. p = &fs_info->swapfile_pins.rb_node;
  8687. while (*p) {
  8688. parent = *p;
  8689. entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
  8690. if (sp->ptr < entry->ptr ||
  8691. (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
  8692. p = &(*p)->rb_left;
  8693. } else if (sp->ptr > entry->ptr ||
  8694. (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
  8695. p = &(*p)->rb_right;
  8696. } else {
  8697. if (is_block_group)
  8698. entry->bg_extent_count++;
  8699. spin_unlock(&fs_info->swapfile_pins_lock);
  8700. kfree(sp);
  8701. return 1;
  8702. }
  8703. }
  8704. rb_link_node(&sp->node, parent, p);
  8705. rb_insert_color(&sp->node, &fs_info->swapfile_pins);
  8706. spin_unlock(&fs_info->swapfile_pins_lock);
  8707. return 0;
  8708. }
  8709. /* Free all of the entries pinned by this swapfile. */
  8710. static void btrfs_free_swapfile_pins(struct inode *inode)
  8711. {
  8712. struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
  8713. struct btrfs_swapfile_pin *sp;
  8714. struct rb_node *node, *next;
  8715. spin_lock(&fs_info->swapfile_pins_lock);
  8716. node = rb_first(&fs_info->swapfile_pins);
  8717. while (node) {
  8718. next = rb_next(node);
  8719. sp = rb_entry(node, struct btrfs_swapfile_pin, node);
  8720. if (sp->inode == inode) {
  8721. rb_erase(&sp->node, &fs_info->swapfile_pins);
  8722. if (sp->is_block_group) {
  8723. btrfs_dec_block_group_swap_extents(sp->ptr,
  8724. sp->bg_extent_count);
  8725. btrfs_put_block_group(sp->ptr);
  8726. }
  8727. kfree(sp);
  8728. }
  8729. node = next;
  8730. }
  8731. spin_unlock(&fs_info->swapfile_pins_lock);
  8732. }
  8733. struct btrfs_swap_info {
  8734. u64 start;
  8735. u64 block_start;
  8736. u64 block_len;
  8737. u64 lowest_ppage;
  8738. u64 highest_ppage;
  8739. unsigned long nr_pages;
  8740. int nr_extents;
  8741. };
  8742. static int btrfs_add_swap_extent(struct swap_info_struct *sis,
  8743. struct btrfs_swap_info *bsi)
  8744. {
  8745. unsigned long nr_pages;
  8746. unsigned long max_pages;
  8747. u64 first_ppage, first_ppage_reported, next_ppage;
  8748. int ret;
  8749. /*
  8750. * Our swapfile may have had its size extended after the swap header was
  8751. * written. In that case activating the swapfile should not go beyond
  8752. * the max size set in the swap header.
  8753. */
  8754. if (bsi->nr_pages >= sis->max)
  8755. return 0;
  8756. max_pages = sis->max - bsi->nr_pages;
  8757. first_ppage = PAGE_ALIGN(bsi->block_start) >> PAGE_SHIFT;
  8758. next_ppage = PAGE_ALIGN_DOWN(bsi->block_start + bsi->block_len) >> PAGE_SHIFT;
  8759. if (first_ppage >= next_ppage)
  8760. return 0;
  8761. nr_pages = next_ppage - first_ppage;
  8762. nr_pages = min(nr_pages, max_pages);
  8763. first_ppage_reported = first_ppage;
  8764. if (bsi->start == 0)
  8765. first_ppage_reported++;
  8766. if (bsi->lowest_ppage > first_ppage_reported)
  8767. bsi->lowest_ppage = first_ppage_reported;
  8768. if (bsi->highest_ppage < (next_ppage - 1))
  8769. bsi->highest_ppage = next_ppage - 1;
  8770. ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
  8771. if (ret < 0)
  8772. return ret;
  8773. bsi->nr_extents += ret;
  8774. bsi->nr_pages += nr_pages;
  8775. return 0;
  8776. }
  8777. static void btrfs_swap_deactivate(struct file *file)
  8778. {
  8779. struct inode *inode = file_inode(file);
  8780. btrfs_free_swapfile_pins(inode);
  8781. atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
  8782. }
  8783. static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
  8784. sector_t *span)
  8785. {
  8786. struct inode *inode = file_inode(file);
  8787. struct btrfs_root *root = BTRFS_I(inode)->root;
  8788. struct btrfs_fs_info *fs_info = root->fs_info;
  8789. struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
  8790. struct extent_state *cached_state = NULL;
  8791. struct btrfs_chunk_map *map = NULL;
  8792. struct btrfs_device *device = NULL;
  8793. struct btrfs_swap_info bsi = {
  8794. .lowest_ppage = (sector_t)-1ULL,
  8795. };
  8796. struct btrfs_backref_share_check_ctx *backref_ctx = NULL;
  8797. struct btrfs_path *path = NULL;
  8798. int ret = 0;
  8799. u64 isize;
  8800. u64 prev_extent_end = 0;
  8801. /*
  8802. * Acquire the inode's mmap lock to prevent races with memory mapped
  8803. * writes, as they could happen after we flush delalloc below and before
  8804. * we lock the extent range further below. The inode was already locked
  8805. * up in the call chain.
  8806. */
  8807. btrfs_assert_inode_locked(BTRFS_I(inode));
  8808. down_write(&BTRFS_I(inode)->i_mmap_lock);
  8809. /*
  8810. * If the swap file was just created, make sure delalloc is done. If the
  8811. * file changes again after this, the user is doing something stupid and
  8812. * we don't really care.
  8813. */
  8814. ret = btrfs_wait_ordered_range(BTRFS_I(inode), 0, (u64)-1);
  8815. if (ret)
  8816. goto out_unlock_mmap;
  8817. /*
  8818. * The inode is locked, so these flags won't change after we check them.
  8819. */
  8820. if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
  8821. btrfs_warn(fs_info, "swapfile must not be compressed");
  8822. ret = -EINVAL;
  8823. goto out_unlock_mmap;
  8824. }
  8825. if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
  8826. btrfs_warn(fs_info, "swapfile must not be copy-on-write");
  8827. ret = -EINVAL;
  8828. goto out_unlock_mmap;
  8829. }
  8830. if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
  8831. btrfs_warn(fs_info, "swapfile must not be checksummed");
  8832. ret = -EINVAL;
  8833. goto out_unlock_mmap;
  8834. }
  8835. path = btrfs_alloc_path();
  8836. backref_ctx = btrfs_alloc_backref_share_check_ctx();
  8837. if (!path || !backref_ctx) {
  8838. ret = -ENOMEM;
  8839. goto out_unlock_mmap;
  8840. }
  8841. /*
  8842. * Balance or device remove/replace/resize can move stuff around from
  8843. * under us. The exclop protection makes sure they aren't running/won't
  8844. * run concurrently while we are mapping the swap extents, and
  8845. * fs_info->swapfile_pins prevents them from running while the swap
  8846. * file is active and moving the extents. Note that this also prevents
  8847. * a concurrent device add which isn't actually necessary, but it's not
  8848. * really worth the trouble to allow it.
  8849. */
  8850. if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_SWAP_ACTIVATE)) {
  8851. btrfs_warn(fs_info,
  8852. "cannot activate swapfile while exclusive operation is running");
  8853. ret = -EBUSY;
  8854. goto out_unlock_mmap;
  8855. }
  8856. /*
  8857. * Prevent snapshot creation while we are activating the swap file.
  8858. * We do not want to race with snapshot creation. If snapshot creation
  8859. * already started before we bumped nr_swapfiles from 0 to 1 and
  8860. * completes before the first write into the swap file after it is
  8861. * activated, than that write would fallback to COW.
  8862. */
  8863. if (!btrfs_drew_try_write_lock(&root->snapshot_lock)) {
  8864. btrfs_exclop_finish(fs_info);
  8865. btrfs_warn(fs_info,
  8866. "cannot activate swapfile because snapshot creation is in progress");
  8867. ret = -EINVAL;
  8868. goto out_unlock_mmap;
  8869. }
  8870. /*
  8871. * Snapshots can create extents which require COW even if NODATACOW is
  8872. * set. We use this counter to prevent snapshots. We must increment it
  8873. * before walking the extents because we don't want a concurrent
  8874. * snapshot to run after we've already checked the extents.
  8875. *
  8876. * It is possible that subvolume is marked for deletion but still not
  8877. * removed yet. To prevent this race, we check the root status before
  8878. * activating the swapfile.
  8879. */
  8880. spin_lock(&root->root_item_lock);
  8881. if (btrfs_root_dead(root)) {
  8882. spin_unlock(&root->root_item_lock);
  8883. btrfs_drew_write_unlock(&root->snapshot_lock);
  8884. btrfs_exclop_finish(fs_info);
  8885. btrfs_warn(fs_info,
  8886. "cannot activate swapfile because subvolume %llu is being deleted",
  8887. btrfs_root_id(root));
  8888. ret = -EPERM;
  8889. goto out_unlock_mmap;
  8890. }
  8891. atomic_inc(&root->nr_swapfiles);
  8892. spin_unlock(&root->root_item_lock);
  8893. isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
  8894. lock_extent(io_tree, 0, isize - 1, &cached_state);
  8895. while (prev_extent_end < isize) {
  8896. struct btrfs_key key;
  8897. struct extent_buffer *leaf;
  8898. struct btrfs_file_extent_item *ei;
  8899. struct btrfs_block_group *bg;
  8900. u64 logical_block_start;
  8901. u64 physical_block_start;
  8902. u64 extent_gen;
  8903. u64 disk_bytenr;
  8904. u64 len;
  8905. key.objectid = btrfs_ino(BTRFS_I(inode));
  8906. key.type = BTRFS_EXTENT_DATA_KEY;
  8907. key.offset = prev_extent_end;
  8908. ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
  8909. if (ret < 0)
  8910. goto out;
  8911. /*
  8912. * If key not found it means we have an implicit hole (NO_HOLES
  8913. * is enabled).
  8914. */
  8915. if (ret > 0) {
  8916. btrfs_warn(fs_info, "swapfile must not have holes");
  8917. ret = -EINVAL;
  8918. goto out;
  8919. }
  8920. leaf = path->nodes[0];
  8921. ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
  8922. if (btrfs_file_extent_type(leaf, ei) == BTRFS_FILE_EXTENT_INLINE) {
  8923. /*
  8924. * It's unlikely we'll ever actually find ourselves
  8925. * here, as a file small enough to fit inline won't be
  8926. * big enough to store more than the swap header, but in
  8927. * case something changes in the future, let's catch it
  8928. * here rather than later.
  8929. */
  8930. btrfs_warn(fs_info, "swapfile must not be inline");
  8931. ret = -EINVAL;
  8932. goto out;
  8933. }
  8934. if (btrfs_file_extent_compression(leaf, ei) != BTRFS_COMPRESS_NONE) {
  8935. btrfs_warn(fs_info, "swapfile must not be compressed");
  8936. ret = -EINVAL;
  8937. goto out;
  8938. }
  8939. disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, ei);
  8940. if (disk_bytenr == 0) {
  8941. btrfs_warn(fs_info, "swapfile must not have holes");
  8942. ret = -EINVAL;
  8943. goto out;
  8944. }
  8945. logical_block_start = disk_bytenr + btrfs_file_extent_offset(leaf, ei);
  8946. extent_gen = btrfs_file_extent_generation(leaf, ei);
  8947. prev_extent_end = btrfs_file_extent_end(path);
  8948. if (prev_extent_end > isize)
  8949. len = isize - key.offset;
  8950. else
  8951. len = btrfs_file_extent_num_bytes(leaf, ei);
  8952. backref_ctx->curr_leaf_bytenr = leaf->start;
  8953. /*
  8954. * Don't need the path anymore, release to avoid deadlocks when
  8955. * calling btrfs_is_data_extent_shared() because when joining a
  8956. * transaction it can block waiting for the current one's commit
  8957. * which in turn may be trying to lock the same leaf to flush
  8958. * delayed items for example.
  8959. */
  8960. btrfs_release_path(path);
  8961. ret = btrfs_is_data_extent_shared(BTRFS_I(inode), disk_bytenr,
  8962. extent_gen, backref_ctx);
  8963. if (ret < 0) {
  8964. goto out;
  8965. } else if (ret > 0) {
  8966. btrfs_warn(fs_info,
  8967. "swapfile must not be copy-on-write");
  8968. ret = -EINVAL;
  8969. goto out;
  8970. }
  8971. map = btrfs_get_chunk_map(fs_info, logical_block_start, len);
  8972. if (IS_ERR(map)) {
  8973. ret = PTR_ERR(map);
  8974. goto out;
  8975. }
  8976. if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
  8977. btrfs_warn(fs_info,
  8978. "swapfile must have single data profile");
  8979. ret = -EINVAL;
  8980. goto out;
  8981. }
  8982. if (device == NULL) {
  8983. device = map->stripes[0].dev;
  8984. ret = btrfs_add_swapfile_pin(inode, device, false);
  8985. if (ret == 1)
  8986. ret = 0;
  8987. else if (ret)
  8988. goto out;
  8989. } else if (device != map->stripes[0].dev) {
  8990. btrfs_warn(fs_info, "swapfile must be on one device");
  8991. ret = -EINVAL;
  8992. goto out;
  8993. }
  8994. physical_block_start = (map->stripes[0].physical +
  8995. (logical_block_start - map->start));
  8996. btrfs_free_chunk_map(map);
  8997. map = NULL;
  8998. bg = btrfs_lookup_block_group(fs_info, logical_block_start);
  8999. if (!bg) {
  9000. btrfs_warn(fs_info,
  9001. "could not find block group containing swapfile");
  9002. ret = -EINVAL;
  9003. goto out;
  9004. }
  9005. if (!btrfs_inc_block_group_swap_extents(bg)) {
  9006. btrfs_warn(fs_info,
  9007. "block group for swapfile at %llu is read-only%s",
  9008. bg->start,
  9009. atomic_read(&fs_info->scrubs_running) ?
  9010. " (scrub running)" : "");
  9011. btrfs_put_block_group(bg);
  9012. ret = -EINVAL;
  9013. goto out;
  9014. }
  9015. ret = btrfs_add_swapfile_pin(inode, bg, true);
  9016. if (ret) {
  9017. btrfs_put_block_group(bg);
  9018. if (ret == 1)
  9019. ret = 0;
  9020. else
  9021. goto out;
  9022. }
  9023. if (bsi.block_len &&
  9024. bsi.block_start + bsi.block_len == physical_block_start) {
  9025. bsi.block_len += len;
  9026. } else {
  9027. if (bsi.block_len) {
  9028. ret = btrfs_add_swap_extent(sis, &bsi);
  9029. if (ret)
  9030. goto out;
  9031. }
  9032. bsi.start = key.offset;
  9033. bsi.block_start = physical_block_start;
  9034. bsi.block_len = len;
  9035. }
  9036. if (fatal_signal_pending(current)) {
  9037. ret = -EINTR;
  9038. goto out;
  9039. }
  9040. cond_resched();
  9041. }
  9042. if (bsi.block_len)
  9043. ret = btrfs_add_swap_extent(sis, &bsi);
  9044. out:
  9045. if (!IS_ERR_OR_NULL(map))
  9046. btrfs_free_chunk_map(map);
  9047. unlock_extent(io_tree, 0, isize - 1, &cached_state);
  9048. if (ret)
  9049. btrfs_swap_deactivate(file);
  9050. btrfs_drew_write_unlock(&root->snapshot_lock);
  9051. btrfs_exclop_finish(fs_info);
  9052. out_unlock_mmap:
  9053. up_write(&BTRFS_I(inode)->i_mmap_lock);
  9054. btrfs_free_backref_share_ctx(backref_ctx);
  9055. btrfs_free_path(path);
  9056. if (ret)
  9057. return ret;
  9058. if (device)
  9059. sis->bdev = device->bdev;
  9060. *span = bsi.highest_ppage - bsi.lowest_ppage + 1;
  9061. sis->max = bsi.nr_pages;
  9062. sis->pages = bsi.nr_pages - 1;
  9063. sis->highest_bit = bsi.nr_pages - 1;
  9064. return bsi.nr_extents;
  9065. }
  9066. #else
  9067. static void btrfs_swap_deactivate(struct file *file)
  9068. {
  9069. }
  9070. static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
  9071. sector_t *span)
  9072. {
  9073. return -EOPNOTSUPP;
  9074. }
  9075. #endif
  9076. /*
  9077. * Update the number of bytes used in the VFS' inode. When we replace extents in
  9078. * a range (clone, dedupe, fallocate's zero range), we must update the number of
  9079. * bytes used by the inode in an atomic manner, so that concurrent stat(2) calls
  9080. * always get a correct value.
  9081. */
  9082. void btrfs_update_inode_bytes(struct btrfs_inode *inode,
  9083. const u64 add_bytes,
  9084. const u64 del_bytes)
  9085. {
  9086. if (add_bytes == del_bytes)
  9087. return;
  9088. spin_lock(&inode->lock);
  9089. if (del_bytes > 0)
  9090. inode_sub_bytes(&inode->vfs_inode, del_bytes);
  9091. if (add_bytes > 0)
  9092. inode_add_bytes(&inode->vfs_inode, add_bytes);
  9093. spin_unlock(&inode->lock);
  9094. }
  9095. /*
  9096. * Verify that there are no ordered extents for a given file range.
  9097. *
  9098. * @inode: The target inode.
  9099. * @start: Start offset of the file range, should be sector size aligned.
  9100. * @end: End offset (inclusive) of the file range, its value +1 should be
  9101. * sector size aligned.
  9102. *
  9103. * This should typically be used for cases where we locked an inode's VFS lock in
  9104. * exclusive mode, we have also locked the inode's i_mmap_lock in exclusive mode,
  9105. * we have flushed all delalloc in the range, we have waited for all ordered
  9106. * extents in the range to complete and finally we have locked the file range in
  9107. * the inode's io_tree.
  9108. */
  9109. void btrfs_assert_inode_range_clean(struct btrfs_inode *inode, u64 start, u64 end)
  9110. {
  9111. struct btrfs_root *root = inode->root;
  9112. struct btrfs_ordered_extent *ordered;
  9113. if (!IS_ENABLED(CONFIG_BTRFS_ASSERT))
  9114. return;
  9115. ordered = btrfs_lookup_first_ordered_range(inode, start, end + 1 - start);
  9116. if (ordered) {
  9117. btrfs_err(root->fs_info,
  9118. "found unexpected ordered extent in file range [%llu, %llu] for inode %llu root %llu (ordered range [%llu, %llu])",
  9119. start, end, btrfs_ino(inode), btrfs_root_id(root),
  9120. ordered->file_offset,
  9121. ordered->file_offset + ordered->num_bytes - 1);
  9122. btrfs_put_ordered_extent(ordered);
  9123. }
  9124. ASSERT(ordered == NULL);
  9125. }
  9126. /*
  9127. * Find the first inode with a minimum number.
  9128. *
  9129. * @root: The root to search for.
  9130. * @min_ino: The minimum inode number.
  9131. *
  9132. * Find the first inode in the @root with a number >= @min_ino and return it.
  9133. * Returns NULL if no such inode found.
  9134. */
  9135. struct btrfs_inode *btrfs_find_first_inode(struct btrfs_root *root, u64 min_ino)
  9136. {
  9137. struct btrfs_inode *inode;
  9138. unsigned long from = min_ino;
  9139. xa_lock(&root->inodes);
  9140. while (true) {
  9141. inode = xa_find(&root->inodes, &from, ULONG_MAX, XA_PRESENT);
  9142. if (!inode)
  9143. break;
  9144. if (igrab(&inode->vfs_inode))
  9145. break;
  9146. from = btrfs_ino(inode) + 1;
  9147. cond_resched_lock(&root->inodes.xa_lock);
  9148. }
  9149. xa_unlock(&root->inodes);
  9150. return inode;
  9151. }
  9152. static const struct inode_operations btrfs_dir_inode_operations = {
  9153. .getattr = btrfs_getattr,
  9154. .lookup = btrfs_lookup,
  9155. .create = btrfs_create,
  9156. .unlink = btrfs_unlink,
  9157. .link = btrfs_link,
  9158. .mkdir = btrfs_mkdir,
  9159. .rmdir = btrfs_rmdir,
  9160. .rename = btrfs_rename2,
  9161. .symlink = btrfs_symlink,
  9162. .setattr = btrfs_setattr,
  9163. .mknod = btrfs_mknod,
  9164. .listxattr = btrfs_listxattr,
  9165. .permission = btrfs_permission,
  9166. .get_inode_acl = btrfs_get_acl,
  9167. .set_acl = btrfs_set_acl,
  9168. .update_time = btrfs_update_time,
  9169. .tmpfile = btrfs_tmpfile,
  9170. .fileattr_get = btrfs_fileattr_get,
  9171. .fileattr_set = btrfs_fileattr_set,
  9172. };
  9173. static const struct file_operations btrfs_dir_file_operations = {
  9174. .llseek = btrfs_dir_llseek,
  9175. .read = generic_read_dir,
  9176. .iterate_shared = btrfs_real_readdir,
  9177. .open = btrfs_opendir,
  9178. .unlocked_ioctl = btrfs_ioctl,
  9179. #ifdef CONFIG_COMPAT
  9180. .compat_ioctl = btrfs_compat_ioctl,
  9181. #endif
  9182. .release = btrfs_release_file,
  9183. .fsync = btrfs_sync_file,
  9184. };
  9185. /*
  9186. * btrfs doesn't support the bmap operation because swapfiles
  9187. * use bmap to make a mapping of extents in the file. They assume
  9188. * these extents won't change over the life of the file and they
  9189. * use the bmap result to do IO directly to the drive.
  9190. *
  9191. * the btrfs bmap call would return logical addresses that aren't
  9192. * suitable for IO and they also will change frequently as COW
  9193. * operations happen. So, swapfile + btrfs == corruption.
  9194. *
  9195. * For now we're avoiding this by dropping bmap.
  9196. */
  9197. static const struct address_space_operations btrfs_aops = {
  9198. .read_folio = btrfs_read_folio,
  9199. .writepages = btrfs_writepages,
  9200. .readahead = btrfs_readahead,
  9201. .invalidate_folio = btrfs_invalidate_folio,
  9202. .launder_folio = btrfs_launder_folio,
  9203. .release_folio = btrfs_release_folio,
  9204. .migrate_folio = btrfs_migrate_folio,
  9205. .dirty_folio = filemap_dirty_folio,
  9206. .error_remove_folio = generic_error_remove_folio,
  9207. .swap_activate = btrfs_swap_activate,
  9208. .swap_deactivate = btrfs_swap_deactivate,
  9209. };
  9210. static const struct inode_operations btrfs_file_inode_operations = {
  9211. .getattr = btrfs_getattr,
  9212. .setattr = btrfs_setattr,
  9213. .listxattr = btrfs_listxattr,
  9214. .permission = btrfs_permission,
  9215. .fiemap = btrfs_fiemap,
  9216. .get_inode_acl = btrfs_get_acl,
  9217. .set_acl = btrfs_set_acl,
  9218. .update_time = btrfs_update_time,
  9219. .fileattr_get = btrfs_fileattr_get,
  9220. .fileattr_set = btrfs_fileattr_set,
  9221. };
  9222. static const struct inode_operations btrfs_special_inode_operations = {
  9223. .getattr = btrfs_getattr,
  9224. .setattr = btrfs_setattr,
  9225. .permission = btrfs_permission,
  9226. .listxattr = btrfs_listxattr,
  9227. .get_inode_acl = btrfs_get_acl,
  9228. .set_acl = btrfs_set_acl,
  9229. .update_time = btrfs_update_time,
  9230. };
  9231. static const struct inode_operations btrfs_symlink_inode_operations = {
  9232. .get_link = page_get_link,
  9233. .getattr = btrfs_getattr,
  9234. .setattr = btrfs_setattr,
  9235. .permission = btrfs_permission,
  9236. .listxattr = btrfs_listxattr,
  9237. .update_time = btrfs_update_time,
  9238. };
  9239. const struct dentry_operations btrfs_dentry_operations = {
  9240. .d_delete = btrfs_dentry_delete,
  9241. };