inode.c 288 KB

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