inode.c 293 KB

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