inode.c 290 KB

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