inode.c 291 KB

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