inode.c 291 KB

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