inode.c 291 KB

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