inode.c 282 KB

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