extent-tree.c 300 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060
  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/sched.h>
  19. #include <linux/sched/signal.h>
  20. #include <linux/pagemap.h>
  21. #include <linux/writeback.h>
  22. #include <linux/blkdev.h>
  23. #include <linux/sort.h>
  24. #include <linux/rcupdate.h>
  25. #include <linux/kthread.h>
  26. #include <linux/slab.h>
  27. #include <linux/ratelimit.h>
  28. #include <linux/percpu_counter.h>
  29. #include <linux/lockdep.h>
  30. #include "hash.h"
  31. #include "tree-log.h"
  32. #include "disk-io.h"
  33. #include "print-tree.h"
  34. #include "volumes.h"
  35. #include "raid56.h"
  36. #include "locking.h"
  37. #include "free-space-cache.h"
  38. #include "free-space-tree.h"
  39. #include "math.h"
  40. #include "sysfs.h"
  41. #include "qgroup.h"
  42. #include "ref-verify.h"
  43. #undef SCRAMBLE_DELAYED_REFS
  44. /*
  45. * control flags for do_chunk_alloc's force field
  46. * CHUNK_ALLOC_NO_FORCE means to only allocate a chunk
  47. * if we really need one.
  48. *
  49. * CHUNK_ALLOC_LIMITED means to only try and allocate one
  50. * if we have very few chunks already allocated. This is
  51. * used as part of the clustering code to help make sure
  52. * we have a good pool of storage to cluster in, without
  53. * filling the FS with empty chunks
  54. *
  55. * CHUNK_ALLOC_FORCE means it must try to allocate one
  56. *
  57. */
  58. enum {
  59. CHUNK_ALLOC_NO_FORCE = 0,
  60. CHUNK_ALLOC_LIMITED = 1,
  61. CHUNK_ALLOC_FORCE = 2,
  62. };
  63. static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
  64. struct btrfs_fs_info *fs_info,
  65. struct btrfs_delayed_ref_node *node, u64 parent,
  66. u64 root_objectid, u64 owner_objectid,
  67. u64 owner_offset, int refs_to_drop,
  68. struct btrfs_delayed_extent_op *extra_op);
  69. static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
  70. struct extent_buffer *leaf,
  71. struct btrfs_extent_item *ei);
  72. static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
  73. struct btrfs_fs_info *fs_info,
  74. u64 parent, u64 root_objectid,
  75. u64 flags, u64 owner, u64 offset,
  76. struct btrfs_key *ins, int ref_mod);
  77. static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
  78. struct btrfs_fs_info *fs_info,
  79. u64 parent, u64 root_objectid,
  80. u64 flags, struct btrfs_disk_key *key,
  81. int level, struct btrfs_key *ins);
  82. static int do_chunk_alloc(struct btrfs_trans_handle *trans,
  83. struct btrfs_fs_info *fs_info, u64 flags,
  84. int force);
  85. static int find_next_key(struct btrfs_path *path, int level,
  86. struct btrfs_key *key);
  87. static void dump_space_info(struct btrfs_fs_info *fs_info,
  88. struct btrfs_space_info *info, u64 bytes,
  89. int dump_block_groups);
  90. static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
  91. u64 num_bytes);
  92. static void space_info_add_new_bytes(struct btrfs_fs_info *fs_info,
  93. struct btrfs_space_info *space_info,
  94. u64 num_bytes);
  95. static void space_info_add_old_bytes(struct btrfs_fs_info *fs_info,
  96. struct btrfs_space_info *space_info,
  97. u64 num_bytes);
  98. static noinline int
  99. block_group_cache_done(struct btrfs_block_group_cache *cache)
  100. {
  101. smp_mb();
  102. return cache->cached == BTRFS_CACHE_FINISHED ||
  103. cache->cached == BTRFS_CACHE_ERROR;
  104. }
  105. static int block_group_bits(struct btrfs_block_group_cache *cache, u64 bits)
  106. {
  107. return (cache->flags & bits) == bits;
  108. }
  109. void btrfs_get_block_group(struct btrfs_block_group_cache *cache)
  110. {
  111. atomic_inc(&cache->count);
  112. }
  113. void btrfs_put_block_group(struct btrfs_block_group_cache *cache)
  114. {
  115. if (atomic_dec_and_test(&cache->count)) {
  116. WARN_ON(cache->pinned > 0);
  117. WARN_ON(cache->reserved > 0);
  118. /*
  119. * If not empty, someone is still holding mutex of
  120. * full_stripe_lock, which can only be released by caller.
  121. * And it will definitely cause use-after-free when caller
  122. * tries to release full stripe lock.
  123. *
  124. * No better way to resolve, but only to warn.
  125. */
  126. WARN_ON(!RB_EMPTY_ROOT(&cache->full_stripe_locks_root.root));
  127. kfree(cache->free_space_ctl);
  128. kfree(cache);
  129. }
  130. }
  131. /*
  132. * this adds the block group to the fs_info rb tree for the block group
  133. * cache
  134. */
  135. static int btrfs_add_block_group_cache(struct btrfs_fs_info *info,
  136. struct btrfs_block_group_cache *block_group)
  137. {
  138. struct rb_node **p;
  139. struct rb_node *parent = NULL;
  140. struct btrfs_block_group_cache *cache;
  141. spin_lock(&info->block_group_cache_lock);
  142. p = &info->block_group_cache_tree.rb_node;
  143. while (*p) {
  144. parent = *p;
  145. cache = rb_entry(parent, struct btrfs_block_group_cache,
  146. cache_node);
  147. if (block_group->key.objectid < cache->key.objectid) {
  148. p = &(*p)->rb_left;
  149. } else if (block_group->key.objectid > cache->key.objectid) {
  150. p = &(*p)->rb_right;
  151. } else {
  152. spin_unlock(&info->block_group_cache_lock);
  153. return -EEXIST;
  154. }
  155. }
  156. rb_link_node(&block_group->cache_node, parent, p);
  157. rb_insert_color(&block_group->cache_node,
  158. &info->block_group_cache_tree);
  159. if (info->first_logical_byte > block_group->key.objectid)
  160. info->first_logical_byte = block_group->key.objectid;
  161. spin_unlock(&info->block_group_cache_lock);
  162. return 0;
  163. }
  164. /*
  165. * This will return the block group at or after bytenr if contains is 0, else
  166. * it will return the block group that contains the bytenr
  167. */
  168. static struct btrfs_block_group_cache *
  169. block_group_cache_tree_search(struct btrfs_fs_info *info, u64 bytenr,
  170. int contains)
  171. {
  172. struct btrfs_block_group_cache *cache, *ret = NULL;
  173. struct rb_node *n;
  174. u64 end, start;
  175. spin_lock(&info->block_group_cache_lock);
  176. n = info->block_group_cache_tree.rb_node;
  177. while (n) {
  178. cache = rb_entry(n, struct btrfs_block_group_cache,
  179. cache_node);
  180. end = cache->key.objectid + cache->key.offset - 1;
  181. start = cache->key.objectid;
  182. if (bytenr < start) {
  183. if (!contains && (!ret || start < ret->key.objectid))
  184. ret = cache;
  185. n = n->rb_left;
  186. } else if (bytenr > start) {
  187. if (contains && bytenr <= end) {
  188. ret = cache;
  189. break;
  190. }
  191. n = n->rb_right;
  192. } else {
  193. ret = cache;
  194. break;
  195. }
  196. }
  197. if (ret) {
  198. btrfs_get_block_group(ret);
  199. if (bytenr == 0 && info->first_logical_byte > ret->key.objectid)
  200. info->first_logical_byte = ret->key.objectid;
  201. }
  202. spin_unlock(&info->block_group_cache_lock);
  203. return ret;
  204. }
  205. static int add_excluded_extent(struct btrfs_fs_info *fs_info,
  206. u64 start, u64 num_bytes)
  207. {
  208. u64 end = start + num_bytes - 1;
  209. set_extent_bits(&fs_info->freed_extents[0],
  210. start, end, EXTENT_UPTODATE);
  211. set_extent_bits(&fs_info->freed_extents[1],
  212. start, end, EXTENT_UPTODATE);
  213. return 0;
  214. }
  215. static void free_excluded_extents(struct btrfs_fs_info *fs_info,
  216. struct btrfs_block_group_cache *cache)
  217. {
  218. u64 start, end;
  219. start = cache->key.objectid;
  220. end = start + cache->key.offset - 1;
  221. clear_extent_bits(&fs_info->freed_extents[0],
  222. start, end, EXTENT_UPTODATE);
  223. clear_extent_bits(&fs_info->freed_extents[1],
  224. start, end, EXTENT_UPTODATE);
  225. }
  226. static int exclude_super_stripes(struct btrfs_fs_info *fs_info,
  227. struct btrfs_block_group_cache *cache)
  228. {
  229. u64 bytenr;
  230. u64 *logical;
  231. int stripe_len;
  232. int i, nr, ret;
  233. if (cache->key.objectid < BTRFS_SUPER_INFO_OFFSET) {
  234. stripe_len = BTRFS_SUPER_INFO_OFFSET - cache->key.objectid;
  235. cache->bytes_super += stripe_len;
  236. ret = add_excluded_extent(fs_info, cache->key.objectid,
  237. stripe_len);
  238. if (ret)
  239. return ret;
  240. }
  241. for (i = 0; i < BTRFS_SUPER_MIRROR_MAX; i++) {
  242. bytenr = btrfs_sb_offset(i);
  243. ret = btrfs_rmap_block(fs_info, cache->key.objectid,
  244. bytenr, 0, &logical, &nr, &stripe_len);
  245. if (ret)
  246. return ret;
  247. while (nr--) {
  248. u64 start, len;
  249. if (logical[nr] > cache->key.objectid +
  250. cache->key.offset)
  251. continue;
  252. if (logical[nr] + stripe_len <= cache->key.objectid)
  253. continue;
  254. start = logical[nr];
  255. if (start < cache->key.objectid) {
  256. start = cache->key.objectid;
  257. len = (logical[nr] + stripe_len) - start;
  258. } else {
  259. len = min_t(u64, stripe_len,
  260. cache->key.objectid +
  261. cache->key.offset - start);
  262. }
  263. cache->bytes_super += len;
  264. ret = add_excluded_extent(fs_info, start, len);
  265. if (ret) {
  266. kfree(logical);
  267. return ret;
  268. }
  269. }
  270. kfree(logical);
  271. }
  272. return 0;
  273. }
  274. static struct btrfs_caching_control *
  275. get_caching_control(struct btrfs_block_group_cache *cache)
  276. {
  277. struct btrfs_caching_control *ctl;
  278. spin_lock(&cache->lock);
  279. if (!cache->caching_ctl) {
  280. spin_unlock(&cache->lock);
  281. return NULL;
  282. }
  283. ctl = cache->caching_ctl;
  284. refcount_inc(&ctl->count);
  285. spin_unlock(&cache->lock);
  286. return ctl;
  287. }
  288. static void put_caching_control(struct btrfs_caching_control *ctl)
  289. {
  290. if (refcount_dec_and_test(&ctl->count))
  291. kfree(ctl);
  292. }
  293. #ifdef CONFIG_BTRFS_DEBUG
  294. static void fragment_free_space(struct btrfs_block_group_cache *block_group)
  295. {
  296. struct btrfs_fs_info *fs_info = block_group->fs_info;
  297. u64 start = block_group->key.objectid;
  298. u64 len = block_group->key.offset;
  299. u64 chunk = block_group->flags & BTRFS_BLOCK_GROUP_METADATA ?
  300. fs_info->nodesize : fs_info->sectorsize;
  301. u64 step = chunk << 1;
  302. while (len > chunk) {
  303. btrfs_remove_free_space(block_group, start, chunk);
  304. start += step;
  305. if (len < step)
  306. len = 0;
  307. else
  308. len -= step;
  309. }
  310. }
  311. #endif
  312. /*
  313. * this is only called by cache_block_group, since we could have freed extents
  314. * we need to check the pinned_extents for any extents that can't be used yet
  315. * since their free space will be released as soon as the transaction commits.
  316. */
  317. u64 add_new_free_space(struct btrfs_block_group_cache *block_group,
  318. struct btrfs_fs_info *info, u64 start, u64 end)
  319. {
  320. u64 extent_start, extent_end, size, total_added = 0;
  321. int ret;
  322. while (start < end) {
  323. ret = find_first_extent_bit(info->pinned_extents, start,
  324. &extent_start, &extent_end,
  325. EXTENT_DIRTY | EXTENT_UPTODATE,
  326. NULL);
  327. if (ret)
  328. break;
  329. if (extent_start <= start) {
  330. start = extent_end + 1;
  331. } else if (extent_start > start && extent_start < end) {
  332. size = extent_start - start;
  333. total_added += size;
  334. ret = btrfs_add_free_space(block_group, start,
  335. size);
  336. BUG_ON(ret); /* -ENOMEM or logic error */
  337. start = extent_end + 1;
  338. } else {
  339. break;
  340. }
  341. }
  342. if (start < end) {
  343. size = end - start;
  344. total_added += size;
  345. ret = btrfs_add_free_space(block_group, start, size);
  346. BUG_ON(ret); /* -ENOMEM or logic error */
  347. }
  348. return total_added;
  349. }
  350. static int load_extent_tree_free(struct btrfs_caching_control *caching_ctl)
  351. {
  352. struct btrfs_block_group_cache *block_group = caching_ctl->block_group;
  353. struct btrfs_fs_info *fs_info = block_group->fs_info;
  354. struct btrfs_root *extent_root = fs_info->extent_root;
  355. struct btrfs_path *path;
  356. struct extent_buffer *leaf;
  357. struct btrfs_key key;
  358. u64 total_found = 0;
  359. u64 last = 0;
  360. u32 nritems;
  361. int ret;
  362. bool wakeup = true;
  363. path = btrfs_alloc_path();
  364. if (!path)
  365. return -ENOMEM;
  366. last = max_t(u64, block_group->key.objectid, BTRFS_SUPER_INFO_OFFSET);
  367. #ifdef CONFIG_BTRFS_DEBUG
  368. /*
  369. * If we're fragmenting we don't want to make anybody think we can
  370. * allocate from this block group until we've had a chance to fragment
  371. * the free space.
  372. */
  373. if (btrfs_should_fragment_free_space(block_group))
  374. wakeup = false;
  375. #endif
  376. /*
  377. * We don't want to deadlock with somebody trying to allocate a new
  378. * extent for the extent root while also trying to search the extent
  379. * root to add free space. So we skip locking and search the commit
  380. * root, since its read-only
  381. */
  382. path->skip_locking = 1;
  383. path->search_commit_root = 1;
  384. path->reada = READA_FORWARD;
  385. key.objectid = last;
  386. key.offset = 0;
  387. key.type = BTRFS_EXTENT_ITEM_KEY;
  388. next:
  389. ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
  390. if (ret < 0)
  391. goto out;
  392. leaf = path->nodes[0];
  393. nritems = btrfs_header_nritems(leaf);
  394. while (1) {
  395. if (btrfs_fs_closing(fs_info) > 1) {
  396. last = (u64)-1;
  397. break;
  398. }
  399. if (path->slots[0] < nritems) {
  400. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  401. } else {
  402. ret = find_next_key(path, 0, &key);
  403. if (ret)
  404. break;
  405. if (need_resched() ||
  406. rwsem_is_contended(&fs_info->commit_root_sem)) {
  407. if (wakeup)
  408. caching_ctl->progress = last;
  409. btrfs_release_path(path);
  410. up_read(&fs_info->commit_root_sem);
  411. mutex_unlock(&caching_ctl->mutex);
  412. cond_resched();
  413. mutex_lock(&caching_ctl->mutex);
  414. down_read(&fs_info->commit_root_sem);
  415. goto next;
  416. }
  417. ret = btrfs_next_leaf(extent_root, path);
  418. if (ret < 0)
  419. goto out;
  420. if (ret)
  421. break;
  422. leaf = path->nodes[0];
  423. nritems = btrfs_header_nritems(leaf);
  424. continue;
  425. }
  426. if (key.objectid < last) {
  427. key.objectid = last;
  428. key.offset = 0;
  429. key.type = BTRFS_EXTENT_ITEM_KEY;
  430. if (wakeup)
  431. caching_ctl->progress = last;
  432. btrfs_release_path(path);
  433. goto next;
  434. }
  435. if (key.objectid < block_group->key.objectid) {
  436. path->slots[0]++;
  437. continue;
  438. }
  439. if (key.objectid >= block_group->key.objectid +
  440. block_group->key.offset)
  441. break;
  442. if (key.type == BTRFS_EXTENT_ITEM_KEY ||
  443. key.type == BTRFS_METADATA_ITEM_KEY) {
  444. total_found += add_new_free_space(block_group,
  445. fs_info, last,
  446. key.objectid);
  447. if (key.type == BTRFS_METADATA_ITEM_KEY)
  448. last = key.objectid +
  449. fs_info->nodesize;
  450. else
  451. last = key.objectid + key.offset;
  452. if (total_found > CACHING_CTL_WAKE_UP) {
  453. total_found = 0;
  454. if (wakeup)
  455. wake_up(&caching_ctl->wait);
  456. }
  457. }
  458. path->slots[0]++;
  459. }
  460. ret = 0;
  461. total_found += add_new_free_space(block_group, fs_info, last,
  462. block_group->key.objectid +
  463. block_group->key.offset);
  464. caching_ctl->progress = (u64)-1;
  465. out:
  466. btrfs_free_path(path);
  467. return ret;
  468. }
  469. static noinline void caching_thread(struct btrfs_work *work)
  470. {
  471. struct btrfs_block_group_cache *block_group;
  472. struct btrfs_fs_info *fs_info;
  473. struct btrfs_caching_control *caching_ctl;
  474. struct btrfs_root *extent_root;
  475. int ret;
  476. caching_ctl = container_of(work, struct btrfs_caching_control, work);
  477. block_group = caching_ctl->block_group;
  478. fs_info = block_group->fs_info;
  479. extent_root = fs_info->extent_root;
  480. mutex_lock(&caching_ctl->mutex);
  481. down_read(&fs_info->commit_root_sem);
  482. if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE))
  483. ret = load_free_space_tree(caching_ctl);
  484. else
  485. ret = load_extent_tree_free(caching_ctl);
  486. spin_lock(&block_group->lock);
  487. block_group->caching_ctl = NULL;
  488. block_group->cached = ret ? BTRFS_CACHE_ERROR : BTRFS_CACHE_FINISHED;
  489. spin_unlock(&block_group->lock);
  490. #ifdef CONFIG_BTRFS_DEBUG
  491. if (btrfs_should_fragment_free_space(block_group)) {
  492. u64 bytes_used;
  493. spin_lock(&block_group->space_info->lock);
  494. spin_lock(&block_group->lock);
  495. bytes_used = block_group->key.offset -
  496. btrfs_block_group_used(&block_group->item);
  497. block_group->space_info->bytes_used += bytes_used >> 1;
  498. spin_unlock(&block_group->lock);
  499. spin_unlock(&block_group->space_info->lock);
  500. fragment_free_space(block_group);
  501. }
  502. #endif
  503. caching_ctl->progress = (u64)-1;
  504. up_read(&fs_info->commit_root_sem);
  505. free_excluded_extents(fs_info, block_group);
  506. mutex_unlock(&caching_ctl->mutex);
  507. wake_up(&caching_ctl->wait);
  508. put_caching_control(caching_ctl);
  509. btrfs_put_block_group(block_group);
  510. }
  511. static int cache_block_group(struct btrfs_block_group_cache *cache,
  512. int load_cache_only)
  513. {
  514. DEFINE_WAIT(wait);
  515. struct btrfs_fs_info *fs_info = cache->fs_info;
  516. struct btrfs_caching_control *caching_ctl;
  517. int ret = 0;
  518. caching_ctl = kzalloc(sizeof(*caching_ctl), GFP_NOFS);
  519. if (!caching_ctl)
  520. return -ENOMEM;
  521. INIT_LIST_HEAD(&caching_ctl->list);
  522. mutex_init(&caching_ctl->mutex);
  523. init_waitqueue_head(&caching_ctl->wait);
  524. caching_ctl->block_group = cache;
  525. caching_ctl->progress = cache->key.objectid;
  526. refcount_set(&caching_ctl->count, 1);
  527. btrfs_init_work(&caching_ctl->work, btrfs_cache_helper,
  528. caching_thread, NULL, NULL);
  529. spin_lock(&cache->lock);
  530. /*
  531. * This should be a rare occasion, but this could happen I think in the
  532. * case where one thread starts to load the space cache info, and then
  533. * some other thread starts a transaction commit which tries to do an
  534. * allocation while the other thread is still loading the space cache
  535. * info. The previous loop should have kept us from choosing this block
  536. * group, but if we've moved to the state where we will wait on caching
  537. * block groups we need to first check if we're doing a fast load here,
  538. * so we can wait for it to finish, otherwise we could end up allocating
  539. * from a block group who's cache gets evicted for one reason or
  540. * another.
  541. */
  542. while (cache->cached == BTRFS_CACHE_FAST) {
  543. struct btrfs_caching_control *ctl;
  544. ctl = cache->caching_ctl;
  545. refcount_inc(&ctl->count);
  546. prepare_to_wait(&ctl->wait, &wait, TASK_UNINTERRUPTIBLE);
  547. spin_unlock(&cache->lock);
  548. schedule();
  549. finish_wait(&ctl->wait, &wait);
  550. put_caching_control(ctl);
  551. spin_lock(&cache->lock);
  552. }
  553. if (cache->cached != BTRFS_CACHE_NO) {
  554. spin_unlock(&cache->lock);
  555. kfree(caching_ctl);
  556. return 0;
  557. }
  558. WARN_ON(cache->caching_ctl);
  559. cache->caching_ctl = caching_ctl;
  560. cache->cached = BTRFS_CACHE_FAST;
  561. spin_unlock(&cache->lock);
  562. if (btrfs_test_opt(fs_info, SPACE_CACHE)) {
  563. mutex_lock(&caching_ctl->mutex);
  564. ret = load_free_space_cache(fs_info, cache);
  565. spin_lock(&cache->lock);
  566. if (ret == 1) {
  567. cache->caching_ctl = NULL;
  568. cache->cached = BTRFS_CACHE_FINISHED;
  569. cache->last_byte_to_unpin = (u64)-1;
  570. caching_ctl->progress = (u64)-1;
  571. } else {
  572. if (load_cache_only) {
  573. cache->caching_ctl = NULL;
  574. cache->cached = BTRFS_CACHE_NO;
  575. } else {
  576. cache->cached = BTRFS_CACHE_STARTED;
  577. cache->has_caching_ctl = 1;
  578. }
  579. }
  580. spin_unlock(&cache->lock);
  581. #ifdef CONFIG_BTRFS_DEBUG
  582. if (ret == 1 &&
  583. btrfs_should_fragment_free_space(cache)) {
  584. u64 bytes_used;
  585. spin_lock(&cache->space_info->lock);
  586. spin_lock(&cache->lock);
  587. bytes_used = cache->key.offset -
  588. btrfs_block_group_used(&cache->item);
  589. cache->space_info->bytes_used += bytes_used >> 1;
  590. spin_unlock(&cache->lock);
  591. spin_unlock(&cache->space_info->lock);
  592. fragment_free_space(cache);
  593. }
  594. #endif
  595. mutex_unlock(&caching_ctl->mutex);
  596. wake_up(&caching_ctl->wait);
  597. if (ret == 1) {
  598. put_caching_control(caching_ctl);
  599. free_excluded_extents(fs_info, cache);
  600. return 0;
  601. }
  602. } else {
  603. /*
  604. * We're either using the free space tree or no caching at all.
  605. * Set cached to the appropriate value and wakeup any waiters.
  606. */
  607. spin_lock(&cache->lock);
  608. if (load_cache_only) {
  609. cache->caching_ctl = NULL;
  610. cache->cached = BTRFS_CACHE_NO;
  611. } else {
  612. cache->cached = BTRFS_CACHE_STARTED;
  613. cache->has_caching_ctl = 1;
  614. }
  615. spin_unlock(&cache->lock);
  616. wake_up(&caching_ctl->wait);
  617. }
  618. if (load_cache_only) {
  619. put_caching_control(caching_ctl);
  620. return 0;
  621. }
  622. down_write(&fs_info->commit_root_sem);
  623. refcount_inc(&caching_ctl->count);
  624. list_add_tail(&caching_ctl->list, &fs_info->caching_block_groups);
  625. up_write(&fs_info->commit_root_sem);
  626. btrfs_get_block_group(cache);
  627. btrfs_queue_work(fs_info->caching_workers, &caching_ctl->work);
  628. return ret;
  629. }
  630. /*
  631. * return the block group that starts at or after bytenr
  632. */
  633. static struct btrfs_block_group_cache *
  634. btrfs_lookup_first_block_group(struct btrfs_fs_info *info, u64 bytenr)
  635. {
  636. return block_group_cache_tree_search(info, bytenr, 0);
  637. }
  638. /*
  639. * return the block group that contains the given bytenr
  640. */
  641. struct btrfs_block_group_cache *btrfs_lookup_block_group(
  642. struct btrfs_fs_info *info,
  643. u64 bytenr)
  644. {
  645. return block_group_cache_tree_search(info, bytenr, 1);
  646. }
  647. static struct btrfs_space_info *__find_space_info(struct btrfs_fs_info *info,
  648. u64 flags)
  649. {
  650. struct list_head *head = &info->space_info;
  651. struct btrfs_space_info *found;
  652. flags &= BTRFS_BLOCK_GROUP_TYPE_MASK;
  653. rcu_read_lock();
  654. list_for_each_entry_rcu(found, head, list) {
  655. if (found->flags & flags) {
  656. rcu_read_unlock();
  657. return found;
  658. }
  659. }
  660. rcu_read_unlock();
  661. return NULL;
  662. }
  663. static void add_pinned_bytes(struct btrfs_fs_info *fs_info, s64 num_bytes,
  664. u64 owner, u64 root_objectid)
  665. {
  666. struct btrfs_space_info *space_info;
  667. u64 flags;
  668. if (owner < BTRFS_FIRST_FREE_OBJECTID) {
  669. if (root_objectid == BTRFS_CHUNK_TREE_OBJECTID)
  670. flags = BTRFS_BLOCK_GROUP_SYSTEM;
  671. else
  672. flags = BTRFS_BLOCK_GROUP_METADATA;
  673. } else {
  674. flags = BTRFS_BLOCK_GROUP_DATA;
  675. }
  676. space_info = __find_space_info(fs_info, flags);
  677. ASSERT(space_info);
  678. percpu_counter_add(&space_info->total_bytes_pinned, num_bytes);
  679. }
  680. /*
  681. * after adding space to the filesystem, we need to clear the full flags
  682. * on all the space infos.
  683. */
  684. void btrfs_clear_space_info_full(struct btrfs_fs_info *info)
  685. {
  686. struct list_head *head = &info->space_info;
  687. struct btrfs_space_info *found;
  688. rcu_read_lock();
  689. list_for_each_entry_rcu(found, head, list)
  690. found->full = 0;
  691. rcu_read_unlock();
  692. }
  693. /* simple helper to search for an existing data extent at a given offset */
  694. int btrfs_lookup_data_extent(struct btrfs_fs_info *fs_info, u64 start, u64 len)
  695. {
  696. int ret;
  697. struct btrfs_key key;
  698. struct btrfs_path *path;
  699. path = btrfs_alloc_path();
  700. if (!path)
  701. return -ENOMEM;
  702. key.objectid = start;
  703. key.offset = len;
  704. key.type = BTRFS_EXTENT_ITEM_KEY;
  705. ret = btrfs_search_slot(NULL, fs_info->extent_root, &key, path, 0, 0);
  706. btrfs_free_path(path);
  707. return ret;
  708. }
  709. /*
  710. * helper function to lookup reference count and flags of a tree block.
  711. *
  712. * the head node for delayed ref is used to store the sum of all the
  713. * reference count modifications queued up in the rbtree. the head
  714. * node may also store the extent flags to set. This way you can check
  715. * to see what the reference count and extent flags would be if all of
  716. * the delayed refs are not processed.
  717. */
  718. int btrfs_lookup_extent_info(struct btrfs_trans_handle *trans,
  719. struct btrfs_fs_info *fs_info, u64 bytenr,
  720. u64 offset, int metadata, u64 *refs, u64 *flags)
  721. {
  722. struct btrfs_delayed_ref_head *head;
  723. struct btrfs_delayed_ref_root *delayed_refs;
  724. struct btrfs_path *path;
  725. struct btrfs_extent_item *ei;
  726. struct extent_buffer *leaf;
  727. struct btrfs_key key;
  728. u32 item_size;
  729. u64 num_refs;
  730. u64 extent_flags;
  731. int ret;
  732. /*
  733. * If we don't have skinny metadata, don't bother doing anything
  734. * different
  735. */
  736. if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA)) {
  737. offset = fs_info->nodesize;
  738. metadata = 0;
  739. }
  740. path = btrfs_alloc_path();
  741. if (!path)
  742. return -ENOMEM;
  743. if (!trans) {
  744. path->skip_locking = 1;
  745. path->search_commit_root = 1;
  746. }
  747. search_again:
  748. key.objectid = bytenr;
  749. key.offset = offset;
  750. if (metadata)
  751. key.type = BTRFS_METADATA_ITEM_KEY;
  752. else
  753. key.type = BTRFS_EXTENT_ITEM_KEY;
  754. ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 0);
  755. if (ret < 0)
  756. goto out_free;
  757. if (ret > 0 && metadata && key.type == BTRFS_METADATA_ITEM_KEY) {
  758. if (path->slots[0]) {
  759. path->slots[0]--;
  760. btrfs_item_key_to_cpu(path->nodes[0], &key,
  761. path->slots[0]);
  762. if (key.objectid == bytenr &&
  763. key.type == BTRFS_EXTENT_ITEM_KEY &&
  764. key.offset == fs_info->nodesize)
  765. ret = 0;
  766. }
  767. }
  768. if (ret == 0) {
  769. leaf = path->nodes[0];
  770. item_size = btrfs_item_size_nr(leaf, path->slots[0]);
  771. if (item_size >= sizeof(*ei)) {
  772. ei = btrfs_item_ptr(leaf, path->slots[0],
  773. struct btrfs_extent_item);
  774. num_refs = btrfs_extent_refs(leaf, ei);
  775. extent_flags = btrfs_extent_flags(leaf, ei);
  776. } else {
  777. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  778. struct btrfs_extent_item_v0 *ei0;
  779. BUG_ON(item_size != sizeof(*ei0));
  780. ei0 = btrfs_item_ptr(leaf, path->slots[0],
  781. struct btrfs_extent_item_v0);
  782. num_refs = btrfs_extent_refs_v0(leaf, ei0);
  783. /* FIXME: this isn't correct for data */
  784. extent_flags = BTRFS_BLOCK_FLAG_FULL_BACKREF;
  785. #else
  786. BUG();
  787. #endif
  788. }
  789. BUG_ON(num_refs == 0);
  790. } else {
  791. num_refs = 0;
  792. extent_flags = 0;
  793. ret = 0;
  794. }
  795. if (!trans)
  796. goto out;
  797. delayed_refs = &trans->transaction->delayed_refs;
  798. spin_lock(&delayed_refs->lock);
  799. head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
  800. if (head) {
  801. if (!mutex_trylock(&head->mutex)) {
  802. refcount_inc(&head->refs);
  803. spin_unlock(&delayed_refs->lock);
  804. btrfs_release_path(path);
  805. /*
  806. * Mutex was contended, block until it's released and try
  807. * again
  808. */
  809. mutex_lock(&head->mutex);
  810. mutex_unlock(&head->mutex);
  811. btrfs_put_delayed_ref_head(head);
  812. goto search_again;
  813. }
  814. spin_lock(&head->lock);
  815. if (head->extent_op && head->extent_op->update_flags)
  816. extent_flags |= head->extent_op->flags_to_set;
  817. else
  818. BUG_ON(num_refs == 0);
  819. num_refs += head->ref_mod;
  820. spin_unlock(&head->lock);
  821. mutex_unlock(&head->mutex);
  822. }
  823. spin_unlock(&delayed_refs->lock);
  824. out:
  825. WARN_ON(num_refs == 0);
  826. if (refs)
  827. *refs = num_refs;
  828. if (flags)
  829. *flags = extent_flags;
  830. out_free:
  831. btrfs_free_path(path);
  832. return ret;
  833. }
  834. /*
  835. * Back reference rules. Back refs have three main goals:
  836. *
  837. * 1) differentiate between all holders of references to an extent so that
  838. * when a reference is dropped we can make sure it was a valid reference
  839. * before freeing the extent.
  840. *
  841. * 2) Provide enough information to quickly find the holders of an extent
  842. * if we notice a given block is corrupted or bad.
  843. *
  844. * 3) Make it easy to migrate blocks for FS shrinking or storage pool
  845. * maintenance. This is actually the same as #2, but with a slightly
  846. * different use case.
  847. *
  848. * There are two kinds of back refs. The implicit back refs is optimized
  849. * for pointers in non-shared tree blocks. For a given pointer in a block,
  850. * back refs of this kind provide information about the block's owner tree
  851. * and the pointer's key. These information allow us to find the block by
  852. * b-tree searching. The full back refs is for pointers in tree blocks not
  853. * referenced by their owner trees. The location of tree block is recorded
  854. * in the back refs. Actually the full back refs is generic, and can be
  855. * used in all cases the implicit back refs is used. The major shortcoming
  856. * of the full back refs is its overhead. Every time a tree block gets
  857. * COWed, we have to update back refs entry for all pointers in it.
  858. *
  859. * For a newly allocated tree block, we use implicit back refs for
  860. * pointers in it. This means most tree related operations only involve
  861. * implicit back refs. For a tree block created in old transaction, the
  862. * only way to drop a reference to it is COW it. So we can detect the
  863. * event that tree block loses its owner tree's reference and do the
  864. * back refs conversion.
  865. *
  866. * When a tree block is COWed through a tree, there are four cases:
  867. *
  868. * The reference count of the block is one and the tree is the block's
  869. * owner tree. Nothing to do in this case.
  870. *
  871. * The reference count of the block is one and the tree is not the
  872. * block's owner tree. In this case, full back refs is used for pointers
  873. * in the block. Remove these full back refs, add implicit back refs for
  874. * every pointers in the new block.
  875. *
  876. * The reference count of the block is greater than one and the tree is
  877. * the block's owner tree. In this case, implicit back refs is used for
  878. * pointers in the block. Add full back refs for every pointers in the
  879. * block, increase lower level extents' reference counts. The original
  880. * implicit back refs are entailed to the new block.
  881. *
  882. * The reference count of the block is greater than one and the tree is
  883. * not the block's owner tree. Add implicit back refs for every pointer in
  884. * the new block, increase lower level extents' reference count.
  885. *
  886. * Back Reference Key composing:
  887. *
  888. * The key objectid corresponds to the first byte in the extent,
  889. * The key type is used to differentiate between types of back refs.
  890. * There are different meanings of the key offset for different types
  891. * of back refs.
  892. *
  893. * File extents can be referenced by:
  894. *
  895. * - multiple snapshots, subvolumes, or different generations in one subvol
  896. * - different files inside a single subvolume
  897. * - different offsets inside a file (bookend extents in file.c)
  898. *
  899. * The extent ref structure for the implicit back refs has fields for:
  900. *
  901. * - Objectid of the subvolume root
  902. * - objectid of the file holding the reference
  903. * - original offset in the file
  904. * - how many bookend extents
  905. *
  906. * The key offset for the implicit back refs is hash of the first
  907. * three fields.
  908. *
  909. * The extent ref structure for the full back refs has field for:
  910. *
  911. * - number of pointers in the tree leaf
  912. *
  913. * The key offset for the implicit back refs is the first byte of
  914. * the tree leaf
  915. *
  916. * When a file extent is allocated, The implicit back refs is used.
  917. * the fields are filled in:
  918. *
  919. * (root_key.objectid, inode objectid, offset in file, 1)
  920. *
  921. * When a file extent is removed file truncation, we find the
  922. * corresponding implicit back refs and check the following fields:
  923. *
  924. * (btrfs_header_owner(leaf), inode objectid, offset in file)
  925. *
  926. * Btree extents can be referenced by:
  927. *
  928. * - Different subvolumes
  929. *
  930. * Both the implicit back refs and the full back refs for tree blocks
  931. * only consist of key. The key offset for the implicit back refs is
  932. * objectid of block's owner tree. The key offset for the full back refs
  933. * is the first byte of parent block.
  934. *
  935. * When implicit back refs is used, information about the lowest key and
  936. * level of the tree block are required. These information are stored in
  937. * tree block info structure.
  938. */
  939. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  940. static int convert_extent_item_v0(struct btrfs_trans_handle *trans,
  941. struct btrfs_fs_info *fs_info,
  942. struct btrfs_path *path,
  943. u64 owner, u32 extra_size)
  944. {
  945. struct btrfs_root *root = fs_info->extent_root;
  946. struct btrfs_extent_item *item;
  947. struct btrfs_extent_item_v0 *ei0;
  948. struct btrfs_extent_ref_v0 *ref0;
  949. struct btrfs_tree_block_info *bi;
  950. struct extent_buffer *leaf;
  951. struct btrfs_key key;
  952. struct btrfs_key found_key;
  953. u32 new_size = sizeof(*item);
  954. u64 refs;
  955. int ret;
  956. leaf = path->nodes[0];
  957. BUG_ON(btrfs_item_size_nr(leaf, path->slots[0]) != sizeof(*ei0));
  958. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  959. ei0 = btrfs_item_ptr(leaf, path->slots[0],
  960. struct btrfs_extent_item_v0);
  961. refs = btrfs_extent_refs_v0(leaf, ei0);
  962. if (owner == (u64)-1) {
  963. while (1) {
  964. if (path->slots[0] >= btrfs_header_nritems(leaf)) {
  965. ret = btrfs_next_leaf(root, path);
  966. if (ret < 0)
  967. return ret;
  968. BUG_ON(ret > 0); /* Corruption */
  969. leaf = path->nodes[0];
  970. }
  971. btrfs_item_key_to_cpu(leaf, &found_key,
  972. path->slots[0]);
  973. BUG_ON(key.objectid != found_key.objectid);
  974. if (found_key.type != BTRFS_EXTENT_REF_V0_KEY) {
  975. path->slots[0]++;
  976. continue;
  977. }
  978. ref0 = btrfs_item_ptr(leaf, path->slots[0],
  979. struct btrfs_extent_ref_v0);
  980. owner = btrfs_ref_objectid_v0(leaf, ref0);
  981. break;
  982. }
  983. }
  984. btrfs_release_path(path);
  985. if (owner < BTRFS_FIRST_FREE_OBJECTID)
  986. new_size += sizeof(*bi);
  987. new_size -= sizeof(*ei0);
  988. ret = btrfs_search_slot(trans, root, &key, path,
  989. new_size + extra_size, 1);
  990. if (ret < 0)
  991. return ret;
  992. BUG_ON(ret); /* Corruption */
  993. btrfs_extend_item(fs_info, path, new_size);
  994. leaf = path->nodes[0];
  995. item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  996. btrfs_set_extent_refs(leaf, item, refs);
  997. /* FIXME: get real generation */
  998. btrfs_set_extent_generation(leaf, item, 0);
  999. if (owner < BTRFS_FIRST_FREE_OBJECTID) {
  1000. btrfs_set_extent_flags(leaf, item,
  1001. BTRFS_EXTENT_FLAG_TREE_BLOCK |
  1002. BTRFS_BLOCK_FLAG_FULL_BACKREF);
  1003. bi = (struct btrfs_tree_block_info *)(item + 1);
  1004. /* FIXME: get first key of the block */
  1005. memzero_extent_buffer(leaf, (unsigned long)bi, sizeof(*bi));
  1006. btrfs_set_tree_block_level(leaf, bi, (int)owner);
  1007. } else {
  1008. btrfs_set_extent_flags(leaf, item, BTRFS_EXTENT_FLAG_DATA);
  1009. }
  1010. btrfs_mark_buffer_dirty(leaf);
  1011. return 0;
  1012. }
  1013. #endif
  1014. /*
  1015. * is_data == BTRFS_REF_TYPE_BLOCK, tree block type is required,
  1016. * is_data == BTRFS_REF_TYPE_DATA, data type is requried,
  1017. * is_data == BTRFS_REF_TYPE_ANY, either type is OK.
  1018. */
  1019. int btrfs_get_extent_inline_ref_type(const struct extent_buffer *eb,
  1020. struct btrfs_extent_inline_ref *iref,
  1021. enum btrfs_inline_ref_type is_data)
  1022. {
  1023. int type = btrfs_extent_inline_ref_type(eb, iref);
  1024. u64 offset = btrfs_extent_inline_ref_offset(eb, iref);
  1025. if (type == BTRFS_TREE_BLOCK_REF_KEY ||
  1026. type == BTRFS_SHARED_BLOCK_REF_KEY ||
  1027. type == BTRFS_SHARED_DATA_REF_KEY ||
  1028. type == BTRFS_EXTENT_DATA_REF_KEY) {
  1029. if (is_data == BTRFS_REF_TYPE_BLOCK) {
  1030. if (type == BTRFS_TREE_BLOCK_REF_KEY)
  1031. return type;
  1032. if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
  1033. ASSERT(eb->fs_info);
  1034. /*
  1035. * Every shared one has parent tree
  1036. * block, which must be aligned to
  1037. * nodesize.
  1038. */
  1039. if (offset &&
  1040. IS_ALIGNED(offset, eb->fs_info->nodesize))
  1041. return type;
  1042. }
  1043. } else if (is_data == BTRFS_REF_TYPE_DATA) {
  1044. if (type == BTRFS_EXTENT_DATA_REF_KEY)
  1045. return type;
  1046. if (type == BTRFS_SHARED_DATA_REF_KEY) {
  1047. ASSERT(eb->fs_info);
  1048. /*
  1049. * Every shared one has parent tree
  1050. * block, which must be aligned to
  1051. * nodesize.
  1052. */
  1053. if (offset &&
  1054. IS_ALIGNED(offset, eb->fs_info->nodesize))
  1055. return type;
  1056. }
  1057. } else {
  1058. ASSERT(is_data == BTRFS_REF_TYPE_ANY);
  1059. return type;
  1060. }
  1061. }
  1062. btrfs_print_leaf((struct extent_buffer *)eb);
  1063. btrfs_err(eb->fs_info, "eb %llu invalid extent inline ref type %d",
  1064. eb->start, type);
  1065. WARN_ON(1);
  1066. return BTRFS_REF_TYPE_INVALID;
  1067. }
  1068. static u64 hash_extent_data_ref(u64 root_objectid, u64 owner, u64 offset)
  1069. {
  1070. u32 high_crc = ~(u32)0;
  1071. u32 low_crc = ~(u32)0;
  1072. __le64 lenum;
  1073. lenum = cpu_to_le64(root_objectid);
  1074. high_crc = btrfs_crc32c(high_crc, &lenum, sizeof(lenum));
  1075. lenum = cpu_to_le64(owner);
  1076. low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
  1077. lenum = cpu_to_le64(offset);
  1078. low_crc = btrfs_crc32c(low_crc, &lenum, sizeof(lenum));
  1079. return ((u64)high_crc << 31) ^ (u64)low_crc;
  1080. }
  1081. static u64 hash_extent_data_ref_item(struct extent_buffer *leaf,
  1082. struct btrfs_extent_data_ref *ref)
  1083. {
  1084. return hash_extent_data_ref(btrfs_extent_data_ref_root(leaf, ref),
  1085. btrfs_extent_data_ref_objectid(leaf, ref),
  1086. btrfs_extent_data_ref_offset(leaf, ref));
  1087. }
  1088. static int match_extent_data_ref(struct extent_buffer *leaf,
  1089. struct btrfs_extent_data_ref *ref,
  1090. u64 root_objectid, u64 owner, u64 offset)
  1091. {
  1092. if (btrfs_extent_data_ref_root(leaf, ref) != root_objectid ||
  1093. btrfs_extent_data_ref_objectid(leaf, ref) != owner ||
  1094. btrfs_extent_data_ref_offset(leaf, ref) != offset)
  1095. return 0;
  1096. return 1;
  1097. }
  1098. static noinline int lookup_extent_data_ref(struct btrfs_trans_handle *trans,
  1099. struct btrfs_fs_info *fs_info,
  1100. struct btrfs_path *path,
  1101. u64 bytenr, u64 parent,
  1102. u64 root_objectid,
  1103. u64 owner, u64 offset)
  1104. {
  1105. struct btrfs_root *root = fs_info->extent_root;
  1106. struct btrfs_key key;
  1107. struct btrfs_extent_data_ref *ref;
  1108. struct extent_buffer *leaf;
  1109. u32 nritems;
  1110. int ret;
  1111. int recow;
  1112. int err = -ENOENT;
  1113. key.objectid = bytenr;
  1114. if (parent) {
  1115. key.type = BTRFS_SHARED_DATA_REF_KEY;
  1116. key.offset = parent;
  1117. } else {
  1118. key.type = BTRFS_EXTENT_DATA_REF_KEY;
  1119. key.offset = hash_extent_data_ref(root_objectid,
  1120. owner, offset);
  1121. }
  1122. again:
  1123. recow = 0;
  1124. ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
  1125. if (ret < 0) {
  1126. err = ret;
  1127. goto fail;
  1128. }
  1129. if (parent) {
  1130. if (!ret)
  1131. return 0;
  1132. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  1133. key.type = BTRFS_EXTENT_REF_V0_KEY;
  1134. btrfs_release_path(path);
  1135. ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
  1136. if (ret < 0) {
  1137. err = ret;
  1138. goto fail;
  1139. }
  1140. if (!ret)
  1141. return 0;
  1142. #endif
  1143. goto fail;
  1144. }
  1145. leaf = path->nodes[0];
  1146. nritems = btrfs_header_nritems(leaf);
  1147. while (1) {
  1148. if (path->slots[0] >= nritems) {
  1149. ret = btrfs_next_leaf(root, path);
  1150. if (ret < 0)
  1151. err = ret;
  1152. if (ret)
  1153. goto fail;
  1154. leaf = path->nodes[0];
  1155. nritems = btrfs_header_nritems(leaf);
  1156. recow = 1;
  1157. }
  1158. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  1159. if (key.objectid != bytenr ||
  1160. key.type != BTRFS_EXTENT_DATA_REF_KEY)
  1161. goto fail;
  1162. ref = btrfs_item_ptr(leaf, path->slots[0],
  1163. struct btrfs_extent_data_ref);
  1164. if (match_extent_data_ref(leaf, ref, root_objectid,
  1165. owner, offset)) {
  1166. if (recow) {
  1167. btrfs_release_path(path);
  1168. goto again;
  1169. }
  1170. err = 0;
  1171. break;
  1172. }
  1173. path->slots[0]++;
  1174. }
  1175. fail:
  1176. return err;
  1177. }
  1178. static noinline int insert_extent_data_ref(struct btrfs_trans_handle *trans,
  1179. struct btrfs_fs_info *fs_info,
  1180. struct btrfs_path *path,
  1181. u64 bytenr, u64 parent,
  1182. u64 root_objectid, u64 owner,
  1183. u64 offset, int refs_to_add)
  1184. {
  1185. struct btrfs_root *root = fs_info->extent_root;
  1186. struct btrfs_key key;
  1187. struct extent_buffer *leaf;
  1188. u32 size;
  1189. u32 num_refs;
  1190. int ret;
  1191. key.objectid = bytenr;
  1192. if (parent) {
  1193. key.type = BTRFS_SHARED_DATA_REF_KEY;
  1194. key.offset = parent;
  1195. size = sizeof(struct btrfs_shared_data_ref);
  1196. } else {
  1197. key.type = BTRFS_EXTENT_DATA_REF_KEY;
  1198. key.offset = hash_extent_data_ref(root_objectid,
  1199. owner, offset);
  1200. size = sizeof(struct btrfs_extent_data_ref);
  1201. }
  1202. ret = btrfs_insert_empty_item(trans, root, path, &key, size);
  1203. if (ret && ret != -EEXIST)
  1204. goto fail;
  1205. leaf = path->nodes[0];
  1206. if (parent) {
  1207. struct btrfs_shared_data_ref *ref;
  1208. ref = btrfs_item_ptr(leaf, path->slots[0],
  1209. struct btrfs_shared_data_ref);
  1210. if (ret == 0) {
  1211. btrfs_set_shared_data_ref_count(leaf, ref, refs_to_add);
  1212. } else {
  1213. num_refs = btrfs_shared_data_ref_count(leaf, ref);
  1214. num_refs += refs_to_add;
  1215. btrfs_set_shared_data_ref_count(leaf, ref, num_refs);
  1216. }
  1217. } else {
  1218. struct btrfs_extent_data_ref *ref;
  1219. while (ret == -EEXIST) {
  1220. ref = btrfs_item_ptr(leaf, path->slots[0],
  1221. struct btrfs_extent_data_ref);
  1222. if (match_extent_data_ref(leaf, ref, root_objectid,
  1223. owner, offset))
  1224. break;
  1225. btrfs_release_path(path);
  1226. key.offset++;
  1227. ret = btrfs_insert_empty_item(trans, root, path, &key,
  1228. size);
  1229. if (ret && ret != -EEXIST)
  1230. goto fail;
  1231. leaf = path->nodes[0];
  1232. }
  1233. ref = btrfs_item_ptr(leaf, path->slots[0],
  1234. struct btrfs_extent_data_ref);
  1235. if (ret == 0) {
  1236. btrfs_set_extent_data_ref_root(leaf, ref,
  1237. root_objectid);
  1238. btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
  1239. btrfs_set_extent_data_ref_offset(leaf, ref, offset);
  1240. btrfs_set_extent_data_ref_count(leaf, ref, refs_to_add);
  1241. } else {
  1242. num_refs = btrfs_extent_data_ref_count(leaf, ref);
  1243. num_refs += refs_to_add;
  1244. btrfs_set_extent_data_ref_count(leaf, ref, num_refs);
  1245. }
  1246. }
  1247. btrfs_mark_buffer_dirty(leaf);
  1248. ret = 0;
  1249. fail:
  1250. btrfs_release_path(path);
  1251. return ret;
  1252. }
  1253. static noinline int remove_extent_data_ref(struct btrfs_trans_handle *trans,
  1254. struct btrfs_fs_info *fs_info,
  1255. struct btrfs_path *path,
  1256. int refs_to_drop, int *last_ref)
  1257. {
  1258. struct btrfs_key key;
  1259. struct btrfs_extent_data_ref *ref1 = NULL;
  1260. struct btrfs_shared_data_ref *ref2 = NULL;
  1261. struct extent_buffer *leaf;
  1262. u32 num_refs = 0;
  1263. int ret = 0;
  1264. leaf = path->nodes[0];
  1265. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  1266. if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
  1267. ref1 = btrfs_item_ptr(leaf, path->slots[0],
  1268. struct btrfs_extent_data_ref);
  1269. num_refs = btrfs_extent_data_ref_count(leaf, ref1);
  1270. } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
  1271. ref2 = btrfs_item_ptr(leaf, path->slots[0],
  1272. struct btrfs_shared_data_ref);
  1273. num_refs = btrfs_shared_data_ref_count(leaf, ref2);
  1274. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  1275. } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
  1276. struct btrfs_extent_ref_v0 *ref0;
  1277. ref0 = btrfs_item_ptr(leaf, path->slots[0],
  1278. struct btrfs_extent_ref_v0);
  1279. num_refs = btrfs_ref_count_v0(leaf, ref0);
  1280. #endif
  1281. } else {
  1282. BUG();
  1283. }
  1284. BUG_ON(num_refs < refs_to_drop);
  1285. num_refs -= refs_to_drop;
  1286. if (num_refs == 0) {
  1287. ret = btrfs_del_item(trans, fs_info->extent_root, path);
  1288. *last_ref = 1;
  1289. } else {
  1290. if (key.type == BTRFS_EXTENT_DATA_REF_KEY)
  1291. btrfs_set_extent_data_ref_count(leaf, ref1, num_refs);
  1292. else if (key.type == BTRFS_SHARED_DATA_REF_KEY)
  1293. btrfs_set_shared_data_ref_count(leaf, ref2, num_refs);
  1294. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  1295. else {
  1296. struct btrfs_extent_ref_v0 *ref0;
  1297. ref0 = btrfs_item_ptr(leaf, path->slots[0],
  1298. struct btrfs_extent_ref_v0);
  1299. btrfs_set_ref_count_v0(leaf, ref0, num_refs);
  1300. }
  1301. #endif
  1302. btrfs_mark_buffer_dirty(leaf);
  1303. }
  1304. return ret;
  1305. }
  1306. static noinline u32 extent_data_ref_count(struct btrfs_path *path,
  1307. struct btrfs_extent_inline_ref *iref)
  1308. {
  1309. struct btrfs_key key;
  1310. struct extent_buffer *leaf;
  1311. struct btrfs_extent_data_ref *ref1;
  1312. struct btrfs_shared_data_ref *ref2;
  1313. u32 num_refs = 0;
  1314. int type;
  1315. leaf = path->nodes[0];
  1316. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  1317. if (iref) {
  1318. /*
  1319. * If type is invalid, we should have bailed out earlier than
  1320. * this call.
  1321. */
  1322. type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
  1323. ASSERT(type != BTRFS_REF_TYPE_INVALID);
  1324. if (type == BTRFS_EXTENT_DATA_REF_KEY) {
  1325. ref1 = (struct btrfs_extent_data_ref *)(&iref->offset);
  1326. num_refs = btrfs_extent_data_ref_count(leaf, ref1);
  1327. } else {
  1328. ref2 = (struct btrfs_shared_data_ref *)(iref + 1);
  1329. num_refs = btrfs_shared_data_ref_count(leaf, ref2);
  1330. }
  1331. } else if (key.type == BTRFS_EXTENT_DATA_REF_KEY) {
  1332. ref1 = btrfs_item_ptr(leaf, path->slots[0],
  1333. struct btrfs_extent_data_ref);
  1334. num_refs = btrfs_extent_data_ref_count(leaf, ref1);
  1335. } else if (key.type == BTRFS_SHARED_DATA_REF_KEY) {
  1336. ref2 = btrfs_item_ptr(leaf, path->slots[0],
  1337. struct btrfs_shared_data_ref);
  1338. num_refs = btrfs_shared_data_ref_count(leaf, ref2);
  1339. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  1340. } else if (key.type == BTRFS_EXTENT_REF_V0_KEY) {
  1341. struct btrfs_extent_ref_v0 *ref0;
  1342. ref0 = btrfs_item_ptr(leaf, path->slots[0],
  1343. struct btrfs_extent_ref_v0);
  1344. num_refs = btrfs_ref_count_v0(leaf, ref0);
  1345. #endif
  1346. } else {
  1347. WARN_ON(1);
  1348. }
  1349. return num_refs;
  1350. }
  1351. static noinline int lookup_tree_block_ref(struct btrfs_trans_handle *trans,
  1352. struct btrfs_fs_info *fs_info,
  1353. struct btrfs_path *path,
  1354. u64 bytenr, u64 parent,
  1355. u64 root_objectid)
  1356. {
  1357. struct btrfs_root *root = fs_info->extent_root;
  1358. struct btrfs_key key;
  1359. int ret;
  1360. key.objectid = bytenr;
  1361. if (parent) {
  1362. key.type = BTRFS_SHARED_BLOCK_REF_KEY;
  1363. key.offset = parent;
  1364. } else {
  1365. key.type = BTRFS_TREE_BLOCK_REF_KEY;
  1366. key.offset = root_objectid;
  1367. }
  1368. ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
  1369. if (ret > 0)
  1370. ret = -ENOENT;
  1371. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  1372. if (ret == -ENOENT && parent) {
  1373. btrfs_release_path(path);
  1374. key.type = BTRFS_EXTENT_REF_V0_KEY;
  1375. ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
  1376. if (ret > 0)
  1377. ret = -ENOENT;
  1378. }
  1379. #endif
  1380. return ret;
  1381. }
  1382. static noinline int insert_tree_block_ref(struct btrfs_trans_handle *trans,
  1383. struct btrfs_fs_info *fs_info,
  1384. struct btrfs_path *path,
  1385. u64 bytenr, u64 parent,
  1386. u64 root_objectid)
  1387. {
  1388. struct btrfs_key key;
  1389. int ret;
  1390. key.objectid = bytenr;
  1391. if (parent) {
  1392. key.type = BTRFS_SHARED_BLOCK_REF_KEY;
  1393. key.offset = parent;
  1394. } else {
  1395. key.type = BTRFS_TREE_BLOCK_REF_KEY;
  1396. key.offset = root_objectid;
  1397. }
  1398. ret = btrfs_insert_empty_item(trans, fs_info->extent_root,
  1399. path, &key, 0);
  1400. btrfs_release_path(path);
  1401. return ret;
  1402. }
  1403. static inline int extent_ref_type(u64 parent, u64 owner)
  1404. {
  1405. int type;
  1406. if (owner < BTRFS_FIRST_FREE_OBJECTID) {
  1407. if (parent > 0)
  1408. type = BTRFS_SHARED_BLOCK_REF_KEY;
  1409. else
  1410. type = BTRFS_TREE_BLOCK_REF_KEY;
  1411. } else {
  1412. if (parent > 0)
  1413. type = BTRFS_SHARED_DATA_REF_KEY;
  1414. else
  1415. type = BTRFS_EXTENT_DATA_REF_KEY;
  1416. }
  1417. return type;
  1418. }
  1419. static int find_next_key(struct btrfs_path *path, int level,
  1420. struct btrfs_key *key)
  1421. {
  1422. for (; level < BTRFS_MAX_LEVEL; level++) {
  1423. if (!path->nodes[level])
  1424. break;
  1425. if (path->slots[level] + 1 >=
  1426. btrfs_header_nritems(path->nodes[level]))
  1427. continue;
  1428. if (level == 0)
  1429. btrfs_item_key_to_cpu(path->nodes[level], key,
  1430. path->slots[level] + 1);
  1431. else
  1432. btrfs_node_key_to_cpu(path->nodes[level], key,
  1433. path->slots[level] + 1);
  1434. return 0;
  1435. }
  1436. return 1;
  1437. }
  1438. /*
  1439. * look for inline back ref. if back ref is found, *ref_ret is set
  1440. * to the address of inline back ref, and 0 is returned.
  1441. *
  1442. * if back ref isn't found, *ref_ret is set to the address where it
  1443. * should be inserted, and -ENOENT is returned.
  1444. *
  1445. * if insert is true and there are too many inline back refs, the path
  1446. * points to the extent item, and -EAGAIN is returned.
  1447. *
  1448. * NOTE: inline back refs are ordered in the same way that back ref
  1449. * items in the tree are ordered.
  1450. */
  1451. static noinline_for_stack
  1452. int lookup_inline_extent_backref(struct btrfs_trans_handle *trans,
  1453. struct btrfs_fs_info *fs_info,
  1454. struct btrfs_path *path,
  1455. struct btrfs_extent_inline_ref **ref_ret,
  1456. u64 bytenr, u64 num_bytes,
  1457. u64 parent, u64 root_objectid,
  1458. u64 owner, u64 offset, int insert)
  1459. {
  1460. struct btrfs_root *root = fs_info->extent_root;
  1461. struct btrfs_key key;
  1462. struct extent_buffer *leaf;
  1463. struct btrfs_extent_item *ei;
  1464. struct btrfs_extent_inline_ref *iref;
  1465. u64 flags;
  1466. u64 item_size;
  1467. unsigned long ptr;
  1468. unsigned long end;
  1469. int extra_size;
  1470. int type;
  1471. int want;
  1472. int ret;
  1473. int err = 0;
  1474. bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
  1475. int needed;
  1476. key.objectid = bytenr;
  1477. key.type = BTRFS_EXTENT_ITEM_KEY;
  1478. key.offset = num_bytes;
  1479. want = extent_ref_type(parent, owner);
  1480. if (insert) {
  1481. extra_size = btrfs_extent_inline_ref_size(want);
  1482. path->keep_locks = 1;
  1483. } else
  1484. extra_size = -1;
  1485. /*
  1486. * Owner is our parent level, so we can just add one to get the level
  1487. * for the block we are interested in.
  1488. */
  1489. if (skinny_metadata && owner < BTRFS_FIRST_FREE_OBJECTID) {
  1490. key.type = BTRFS_METADATA_ITEM_KEY;
  1491. key.offset = owner;
  1492. }
  1493. again:
  1494. ret = btrfs_search_slot(trans, root, &key, path, extra_size, 1);
  1495. if (ret < 0) {
  1496. err = ret;
  1497. goto out;
  1498. }
  1499. /*
  1500. * We may be a newly converted file system which still has the old fat
  1501. * extent entries for metadata, so try and see if we have one of those.
  1502. */
  1503. if (ret > 0 && skinny_metadata) {
  1504. skinny_metadata = false;
  1505. if (path->slots[0]) {
  1506. path->slots[0]--;
  1507. btrfs_item_key_to_cpu(path->nodes[0], &key,
  1508. path->slots[0]);
  1509. if (key.objectid == bytenr &&
  1510. key.type == BTRFS_EXTENT_ITEM_KEY &&
  1511. key.offset == num_bytes)
  1512. ret = 0;
  1513. }
  1514. if (ret) {
  1515. key.objectid = bytenr;
  1516. key.type = BTRFS_EXTENT_ITEM_KEY;
  1517. key.offset = num_bytes;
  1518. btrfs_release_path(path);
  1519. goto again;
  1520. }
  1521. }
  1522. if (ret && !insert) {
  1523. err = -ENOENT;
  1524. goto out;
  1525. } else if (WARN_ON(ret)) {
  1526. err = -EIO;
  1527. goto out;
  1528. }
  1529. leaf = path->nodes[0];
  1530. item_size = btrfs_item_size_nr(leaf, path->slots[0]);
  1531. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  1532. if (item_size < sizeof(*ei)) {
  1533. if (!insert) {
  1534. err = -ENOENT;
  1535. goto out;
  1536. }
  1537. ret = convert_extent_item_v0(trans, fs_info, path, owner,
  1538. extra_size);
  1539. if (ret < 0) {
  1540. err = ret;
  1541. goto out;
  1542. }
  1543. leaf = path->nodes[0];
  1544. item_size = btrfs_item_size_nr(leaf, path->slots[0]);
  1545. }
  1546. #endif
  1547. BUG_ON(item_size < sizeof(*ei));
  1548. ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  1549. flags = btrfs_extent_flags(leaf, ei);
  1550. ptr = (unsigned long)(ei + 1);
  1551. end = (unsigned long)ei + item_size;
  1552. if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK && !skinny_metadata) {
  1553. ptr += sizeof(struct btrfs_tree_block_info);
  1554. BUG_ON(ptr > end);
  1555. }
  1556. if (owner >= BTRFS_FIRST_FREE_OBJECTID)
  1557. needed = BTRFS_REF_TYPE_DATA;
  1558. else
  1559. needed = BTRFS_REF_TYPE_BLOCK;
  1560. err = -ENOENT;
  1561. while (1) {
  1562. if (ptr >= end) {
  1563. WARN_ON(ptr > end);
  1564. break;
  1565. }
  1566. iref = (struct btrfs_extent_inline_ref *)ptr;
  1567. type = btrfs_get_extent_inline_ref_type(leaf, iref, needed);
  1568. if (type == BTRFS_REF_TYPE_INVALID) {
  1569. err = -EINVAL;
  1570. goto out;
  1571. }
  1572. if (want < type)
  1573. break;
  1574. if (want > type) {
  1575. ptr += btrfs_extent_inline_ref_size(type);
  1576. continue;
  1577. }
  1578. if (type == BTRFS_EXTENT_DATA_REF_KEY) {
  1579. struct btrfs_extent_data_ref *dref;
  1580. dref = (struct btrfs_extent_data_ref *)(&iref->offset);
  1581. if (match_extent_data_ref(leaf, dref, root_objectid,
  1582. owner, offset)) {
  1583. err = 0;
  1584. break;
  1585. }
  1586. if (hash_extent_data_ref_item(leaf, dref) <
  1587. hash_extent_data_ref(root_objectid, owner, offset))
  1588. break;
  1589. } else {
  1590. u64 ref_offset;
  1591. ref_offset = btrfs_extent_inline_ref_offset(leaf, iref);
  1592. if (parent > 0) {
  1593. if (parent == ref_offset) {
  1594. err = 0;
  1595. break;
  1596. }
  1597. if (ref_offset < parent)
  1598. break;
  1599. } else {
  1600. if (root_objectid == ref_offset) {
  1601. err = 0;
  1602. break;
  1603. }
  1604. if (ref_offset < root_objectid)
  1605. break;
  1606. }
  1607. }
  1608. ptr += btrfs_extent_inline_ref_size(type);
  1609. }
  1610. if (err == -ENOENT && insert) {
  1611. if (item_size + extra_size >=
  1612. BTRFS_MAX_EXTENT_ITEM_SIZE(root)) {
  1613. err = -EAGAIN;
  1614. goto out;
  1615. }
  1616. /*
  1617. * To add new inline back ref, we have to make sure
  1618. * there is no corresponding back ref item.
  1619. * For simplicity, we just do not add new inline back
  1620. * ref if there is any kind of item for this block
  1621. */
  1622. if (find_next_key(path, 0, &key) == 0 &&
  1623. key.objectid == bytenr &&
  1624. key.type < BTRFS_BLOCK_GROUP_ITEM_KEY) {
  1625. err = -EAGAIN;
  1626. goto out;
  1627. }
  1628. }
  1629. *ref_ret = (struct btrfs_extent_inline_ref *)ptr;
  1630. out:
  1631. if (insert) {
  1632. path->keep_locks = 0;
  1633. btrfs_unlock_up_safe(path, 1);
  1634. }
  1635. return err;
  1636. }
  1637. /*
  1638. * helper to add new inline back ref
  1639. */
  1640. static noinline_for_stack
  1641. void setup_inline_extent_backref(struct btrfs_fs_info *fs_info,
  1642. struct btrfs_path *path,
  1643. struct btrfs_extent_inline_ref *iref,
  1644. u64 parent, u64 root_objectid,
  1645. u64 owner, u64 offset, int refs_to_add,
  1646. struct btrfs_delayed_extent_op *extent_op)
  1647. {
  1648. struct extent_buffer *leaf;
  1649. struct btrfs_extent_item *ei;
  1650. unsigned long ptr;
  1651. unsigned long end;
  1652. unsigned long item_offset;
  1653. u64 refs;
  1654. int size;
  1655. int type;
  1656. leaf = path->nodes[0];
  1657. ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  1658. item_offset = (unsigned long)iref - (unsigned long)ei;
  1659. type = extent_ref_type(parent, owner);
  1660. size = btrfs_extent_inline_ref_size(type);
  1661. btrfs_extend_item(fs_info, path, size);
  1662. ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  1663. refs = btrfs_extent_refs(leaf, ei);
  1664. refs += refs_to_add;
  1665. btrfs_set_extent_refs(leaf, ei, refs);
  1666. if (extent_op)
  1667. __run_delayed_extent_op(extent_op, leaf, ei);
  1668. ptr = (unsigned long)ei + item_offset;
  1669. end = (unsigned long)ei + btrfs_item_size_nr(leaf, path->slots[0]);
  1670. if (ptr < end - size)
  1671. memmove_extent_buffer(leaf, ptr + size, ptr,
  1672. end - size - ptr);
  1673. iref = (struct btrfs_extent_inline_ref *)ptr;
  1674. btrfs_set_extent_inline_ref_type(leaf, iref, type);
  1675. if (type == BTRFS_EXTENT_DATA_REF_KEY) {
  1676. struct btrfs_extent_data_ref *dref;
  1677. dref = (struct btrfs_extent_data_ref *)(&iref->offset);
  1678. btrfs_set_extent_data_ref_root(leaf, dref, root_objectid);
  1679. btrfs_set_extent_data_ref_objectid(leaf, dref, owner);
  1680. btrfs_set_extent_data_ref_offset(leaf, dref, offset);
  1681. btrfs_set_extent_data_ref_count(leaf, dref, refs_to_add);
  1682. } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
  1683. struct btrfs_shared_data_ref *sref;
  1684. sref = (struct btrfs_shared_data_ref *)(iref + 1);
  1685. btrfs_set_shared_data_ref_count(leaf, sref, refs_to_add);
  1686. btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
  1687. } else if (type == BTRFS_SHARED_BLOCK_REF_KEY) {
  1688. btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
  1689. } else {
  1690. btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
  1691. }
  1692. btrfs_mark_buffer_dirty(leaf);
  1693. }
  1694. static int lookup_extent_backref(struct btrfs_trans_handle *trans,
  1695. struct btrfs_fs_info *fs_info,
  1696. struct btrfs_path *path,
  1697. struct btrfs_extent_inline_ref **ref_ret,
  1698. u64 bytenr, u64 num_bytes, u64 parent,
  1699. u64 root_objectid, u64 owner, u64 offset)
  1700. {
  1701. int ret;
  1702. ret = lookup_inline_extent_backref(trans, fs_info, path, ref_ret,
  1703. bytenr, num_bytes, parent,
  1704. root_objectid, owner, offset, 0);
  1705. if (ret != -ENOENT)
  1706. return ret;
  1707. btrfs_release_path(path);
  1708. *ref_ret = NULL;
  1709. if (owner < BTRFS_FIRST_FREE_OBJECTID) {
  1710. ret = lookup_tree_block_ref(trans, fs_info, path, bytenr,
  1711. parent, root_objectid);
  1712. } else {
  1713. ret = lookup_extent_data_ref(trans, fs_info, path, bytenr,
  1714. parent, root_objectid, owner,
  1715. offset);
  1716. }
  1717. return ret;
  1718. }
  1719. /*
  1720. * helper to update/remove inline back ref
  1721. */
  1722. static noinline_for_stack
  1723. void update_inline_extent_backref(struct btrfs_fs_info *fs_info,
  1724. struct btrfs_path *path,
  1725. struct btrfs_extent_inline_ref *iref,
  1726. int refs_to_mod,
  1727. struct btrfs_delayed_extent_op *extent_op,
  1728. int *last_ref)
  1729. {
  1730. struct extent_buffer *leaf;
  1731. struct btrfs_extent_item *ei;
  1732. struct btrfs_extent_data_ref *dref = NULL;
  1733. struct btrfs_shared_data_ref *sref = NULL;
  1734. unsigned long ptr;
  1735. unsigned long end;
  1736. u32 item_size;
  1737. int size;
  1738. int type;
  1739. u64 refs;
  1740. leaf = path->nodes[0];
  1741. ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  1742. refs = btrfs_extent_refs(leaf, ei);
  1743. WARN_ON(refs_to_mod < 0 && refs + refs_to_mod <= 0);
  1744. refs += refs_to_mod;
  1745. btrfs_set_extent_refs(leaf, ei, refs);
  1746. if (extent_op)
  1747. __run_delayed_extent_op(extent_op, leaf, ei);
  1748. /*
  1749. * If type is invalid, we should have bailed out after
  1750. * lookup_inline_extent_backref().
  1751. */
  1752. type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_ANY);
  1753. ASSERT(type != BTRFS_REF_TYPE_INVALID);
  1754. if (type == BTRFS_EXTENT_DATA_REF_KEY) {
  1755. dref = (struct btrfs_extent_data_ref *)(&iref->offset);
  1756. refs = btrfs_extent_data_ref_count(leaf, dref);
  1757. } else if (type == BTRFS_SHARED_DATA_REF_KEY) {
  1758. sref = (struct btrfs_shared_data_ref *)(iref + 1);
  1759. refs = btrfs_shared_data_ref_count(leaf, sref);
  1760. } else {
  1761. refs = 1;
  1762. BUG_ON(refs_to_mod != -1);
  1763. }
  1764. BUG_ON(refs_to_mod < 0 && refs < -refs_to_mod);
  1765. refs += refs_to_mod;
  1766. if (refs > 0) {
  1767. if (type == BTRFS_EXTENT_DATA_REF_KEY)
  1768. btrfs_set_extent_data_ref_count(leaf, dref, refs);
  1769. else
  1770. btrfs_set_shared_data_ref_count(leaf, sref, refs);
  1771. } else {
  1772. *last_ref = 1;
  1773. size = btrfs_extent_inline_ref_size(type);
  1774. item_size = btrfs_item_size_nr(leaf, path->slots[0]);
  1775. ptr = (unsigned long)iref;
  1776. end = (unsigned long)ei + item_size;
  1777. if (ptr + size < end)
  1778. memmove_extent_buffer(leaf, ptr, ptr + size,
  1779. end - ptr - size);
  1780. item_size -= size;
  1781. btrfs_truncate_item(fs_info, path, item_size, 1);
  1782. }
  1783. btrfs_mark_buffer_dirty(leaf);
  1784. }
  1785. static noinline_for_stack
  1786. int insert_inline_extent_backref(struct btrfs_trans_handle *trans,
  1787. struct btrfs_fs_info *fs_info,
  1788. struct btrfs_path *path,
  1789. u64 bytenr, u64 num_bytes, u64 parent,
  1790. u64 root_objectid, u64 owner,
  1791. u64 offset, int refs_to_add,
  1792. struct btrfs_delayed_extent_op *extent_op)
  1793. {
  1794. struct btrfs_extent_inline_ref *iref;
  1795. int ret;
  1796. ret = lookup_inline_extent_backref(trans, fs_info, path, &iref,
  1797. bytenr, num_bytes, parent,
  1798. root_objectid, owner, offset, 1);
  1799. if (ret == 0) {
  1800. BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID);
  1801. update_inline_extent_backref(fs_info, path, iref,
  1802. refs_to_add, extent_op, NULL);
  1803. } else if (ret == -ENOENT) {
  1804. setup_inline_extent_backref(fs_info, path, iref, parent,
  1805. root_objectid, owner, offset,
  1806. refs_to_add, extent_op);
  1807. ret = 0;
  1808. }
  1809. return ret;
  1810. }
  1811. static int insert_extent_backref(struct btrfs_trans_handle *trans,
  1812. struct btrfs_fs_info *fs_info,
  1813. struct btrfs_path *path,
  1814. u64 bytenr, u64 parent, u64 root_objectid,
  1815. u64 owner, u64 offset, int refs_to_add)
  1816. {
  1817. int ret;
  1818. if (owner < BTRFS_FIRST_FREE_OBJECTID) {
  1819. BUG_ON(refs_to_add != 1);
  1820. ret = insert_tree_block_ref(trans, fs_info, path, bytenr,
  1821. parent, root_objectid);
  1822. } else {
  1823. ret = insert_extent_data_ref(trans, fs_info, path, bytenr,
  1824. parent, root_objectid,
  1825. owner, offset, refs_to_add);
  1826. }
  1827. return ret;
  1828. }
  1829. static int remove_extent_backref(struct btrfs_trans_handle *trans,
  1830. struct btrfs_fs_info *fs_info,
  1831. struct btrfs_path *path,
  1832. struct btrfs_extent_inline_ref *iref,
  1833. int refs_to_drop, int is_data, int *last_ref)
  1834. {
  1835. int ret = 0;
  1836. BUG_ON(!is_data && refs_to_drop != 1);
  1837. if (iref) {
  1838. update_inline_extent_backref(fs_info, path, iref,
  1839. -refs_to_drop, NULL, last_ref);
  1840. } else if (is_data) {
  1841. ret = remove_extent_data_ref(trans, fs_info, path, refs_to_drop,
  1842. last_ref);
  1843. } else {
  1844. *last_ref = 1;
  1845. ret = btrfs_del_item(trans, fs_info->extent_root, path);
  1846. }
  1847. return ret;
  1848. }
  1849. #define in_range(b, first, len) ((b) >= (first) && (b) < (first) + (len))
  1850. static int btrfs_issue_discard(struct block_device *bdev, u64 start, u64 len,
  1851. u64 *discarded_bytes)
  1852. {
  1853. int j, ret = 0;
  1854. u64 bytes_left, end;
  1855. u64 aligned_start = ALIGN(start, 1 << 9);
  1856. if (WARN_ON(start != aligned_start)) {
  1857. len -= aligned_start - start;
  1858. len = round_down(len, 1 << 9);
  1859. start = aligned_start;
  1860. }
  1861. *discarded_bytes = 0;
  1862. if (!len)
  1863. return 0;
  1864. end = start + len;
  1865. bytes_left = len;
  1866. /* Skip any superblocks on this device. */
  1867. for (j = 0; j < BTRFS_SUPER_MIRROR_MAX; j++) {
  1868. u64 sb_start = btrfs_sb_offset(j);
  1869. u64 sb_end = sb_start + BTRFS_SUPER_INFO_SIZE;
  1870. u64 size = sb_start - start;
  1871. if (!in_range(sb_start, start, bytes_left) &&
  1872. !in_range(sb_end, start, bytes_left) &&
  1873. !in_range(start, sb_start, BTRFS_SUPER_INFO_SIZE))
  1874. continue;
  1875. /*
  1876. * Superblock spans beginning of range. Adjust start and
  1877. * try again.
  1878. */
  1879. if (sb_start <= start) {
  1880. start += sb_end - start;
  1881. if (start > end) {
  1882. bytes_left = 0;
  1883. break;
  1884. }
  1885. bytes_left = end - start;
  1886. continue;
  1887. }
  1888. if (size) {
  1889. ret = blkdev_issue_discard(bdev, start >> 9, size >> 9,
  1890. GFP_NOFS, 0);
  1891. if (!ret)
  1892. *discarded_bytes += size;
  1893. else if (ret != -EOPNOTSUPP)
  1894. return ret;
  1895. }
  1896. start = sb_end;
  1897. if (start > end) {
  1898. bytes_left = 0;
  1899. break;
  1900. }
  1901. bytes_left = end - start;
  1902. }
  1903. if (bytes_left) {
  1904. ret = blkdev_issue_discard(bdev, start >> 9, bytes_left >> 9,
  1905. GFP_NOFS, 0);
  1906. if (!ret)
  1907. *discarded_bytes += bytes_left;
  1908. }
  1909. return ret;
  1910. }
  1911. int btrfs_discard_extent(struct btrfs_fs_info *fs_info, u64 bytenr,
  1912. u64 num_bytes, u64 *actual_bytes)
  1913. {
  1914. int ret;
  1915. u64 discarded_bytes = 0;
  1916. struct btrfs_bio *bbio = NULL;
  1917. /*
  1918. * Avoid races with device replace and make sure our bbio has devices
  1919. * associated to its stripes that don't go away while we are discarding.
  1920. */
  1921. btrfs_bio_counter_inc_blocked(fs_info);
  1922. /* Tell the block device(s) that the sectors can be discarded */
  1923. ret = btrfs_map_block(fs_info, BTRFS_MAP_DISCARD, bytenr, &num_bytes,
  1924. &bbio, 0);
  1925. /* Error condition is -ENOMEM */
  1926. if (!ret) {
  1927. struct btrfs_bio_stripe *stripe = bbio->stripes;
  1928. int i;
  1929. for (i = 0; i < bbio->num_stripes; i++, stripe++) {
  1930. u64 bytes;
  1931. if (!stripe->dev->can_discard)
  1932. continue;
  1933. ret = btrfs_issue_discard(stripe->dev->bdev,
  1934. stripe->physical,
  1935. stripe->length,
  1936. &bytes);
  1937. if (!ret)
  1938. discarded_bytes += bytes;
  1939. else if (ret != -EOPNOTSUPP)
  1940. break; /* Logic errors or -ENOMEM, or -EIO but I don't know how that could happen JDM */
  1941. /*
  1942. * Just in case we get back EOPNOTSUPP for some reason,
  1943. * just ignore the return value so we don't screw up
  1944. * people calling discard_extent.
  1945. */
  1946. ret = 0;
  1947. }
  1948. btrfs_put_bbio(bbio);
  1949. }
  1950. btrfs_bio_counter_dec(fs_info);
  1951. if (actual_bytes)
  1952. *actual_bytes = discarded_bytes;
  1953. if (ret == -EOPNOTSUPP)
  1954. ret = 0;
  1955. return ret;
  1956. }
  1957. /* Can return -ENOMEM */
  1958. int btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
  1959. struct btrfs_root *root,
  1960. u64 bytenr, u64 num_bytes, u64 parent,
  1961. u64 root_objectid, u64 owner, u64 offset)
  1962. {
  1963. struct btrfs_fs_info *fs_info = root->fs_info;
  1964. int old_ref_mod, new_ref_mod;
  1965. int ret;
  1966. BUG_ON(owner < BTRFS_FIRST_FREE_OBJECTID &&
  1967. root_objectid == BTRFS_TREE_LOG_OBJECTID);
  1968. btrfs_ref_tree_mod(root, bytenr, num_bytes, parent, root_objectid,
  1969. owner, offset, BTRFS_ADD_DELAYED_REF);
  1970. if (owner < BTRFS_FIRST_FREE_OBJECTID) {
  1971. ret = btrfs_add_delayed_tree_ref(fs_info, trans, bytenr,
  1972. num_bytes, parent,
  1973. root_objectid, (int)owner,
  1974. BTRFS_ADD_DELAYED_REF, NULL,
  1975. &old_ref_mod, &new_ref_mod);
  1976. } else {
  1977. ret = btrfs_add_delayed_data_ref(fs_info, trans, bytenr,
  1978. num_bytes, parent,
  1979. root_objectid, owner, offset,
  1980. 0, BTRFS_ADD_DELAYED_REF,
  1981. &old_ref_mod, &new_ref_mod);
  1982. }
  1983. if (ret == 0 && old_ref_mod < 0 && new_ref_mod >= 0)
  1984. add_pinned_bytes(fs_info, -num_bytes, owner, root_objectid);
  1985. return ret;
  1986. }
  1987. static int __btrfs_inc_extent_ref(struct btrfs_trans_handle *trans,
  1988. struct btrfs_fs_info *fs_info,
  1989. struct btrfs_delayed_ref_node *node,
  1990. u64 parent, u64 root_objectid,
  1991. u64 owner, u64 offset, int refs_to_add,
  1992. struct btrfs_delayed_extent_op *extent_op)
  1993. {
  1994. struct btrfs_path *path;
  1995. struct extent_buffer *leaf;
  1996. struct btrfs_extent_item *item;
  1997. struct btrfs_key key;
  1998. u64 bytenr = node->bytenr;
  1999. u64 num_bytes = node->num_bytes;
  2000. u64 refs;
  2001. int ret;
  2002. path = btrfs_alloc_path();
  2003. if (!path)
  2004. return -ENOMEM;
  2005. path->reada = READA_FORWARD;
  2006. path->leave_spinning = 1;
  2007. /* this will setup the path even if it fails to insert the back ref */
  2008. ret = insert_inline_extent_backref(trans, fs_info, path, bytenr,
  2009. num_bytes, parent, root_objectid,
  2010. owner, offset,
  2011. refs_to_add, extent_op);
  2012. if ((ret < 0 && ret != -EAGAIN) || !ret)
  2013. goto out;
  2014. /*
  2015. * Ok we had -EAGAIN which means we didn't have space to insert and
  2016. * inline extent ref, so just update the reference count and add a
  2017. * normal backref.
  2018. */
  2019. leaf = path->nodes[0];
  2020. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  2021. item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  2022. refs = btrfs_extent_refs(leaf, item);
  2023. btrfs_set_extent_refs(leaf, item, refs + refs_to_add);
  2024. if (extent_op)
  2025. __run_delayed_extent_op(extent_op, leaf, item);
  2026. btrfs_mark_buffer_dirty(leaf);
  2027. btrfs_release_path(path);
  2028. path->reada = READA_FORWARD;
  2029. path->leave_spinning = 1;
  2030. /* now insert the actual backref */
  2031. ret = insert_extent_backref(trans, fs_info, path, bytenr, parent,
  2032. root_objectid, owner, offset, refs_to_add);
  2033. if (ret)
  2034. btrfs_abort_transaction(trans, ret);
  2035. out:
  2036. btrfs_free_path(path);
  2037. return ret;
  2038. }
  2039. static int run_delayed_data_ref(struct btrfs_trans_handle *trans,
  2040. struct btrfs_fs_info *fs_info,
  2041. struct btrfs_delayed_ref_node *node,
  2042. struct btrfs_delayed_extent_op *extent_op,
  2043. int insert_reserved)
  2044. {
  2045. int ret = 0;
  2046. struct btrfs_delayed_data_ref *ref;
  2047. struct btrfs_key ins;
  2048. u64 parent = 0;
  2049. u64 ref_root = 0;
  2050. u64 flags = 0;
  2051. ins.objectid = node->bytenr;
  2052. ins.offset = node->num_bytes;
  2053. ins.type = BTRFS_EXTENT_ITEM_KEY;
  2054. ref = btrfs_delayed_node_to_data_ref(node);
  2055. trace_run_delayed_data_ref(fs_info, node, ref, node->action);
  2056. if (node->type == BTRFS_SHARED_DATA_REF_KEY)
  2057. parent = ref->parent;
  2058. ref_root = ref->root;
  2059. if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
  2060. if (extent_op)
  2061. flags |= extent_op->flags_to_set;
  2062. ret = alloc_reserved_file_extent(trans, fs_info,
  2063. parent, ref_root, flags,
  2064. ref->objectid, ref->offset,
  2065. &ins, node->ref_mod);
  2066. } else if (node->action == BTRFS_ADD_DELAYED_REF) {
  2067. ret = __btrfs_inc_extent_ref(trans, fs_info, node, parent,
  2068. ref_root, ref->objectid,
  2069. ref->offset, node->ref_mod,
  2070. extent_op);
  2071. } else if (node->action == BTRFS_DROP_DELAYED_REF) {
  2072. ret = __btrfs_free_extent(trans, fs_info, node, parent,
  2073. ref_root, ref->objectid,
  2074. ref->offset, node->ref_mod,
  2075. extent_op);
  2076. } else {
  2077. BUG();
  2078. }
  2079. return ret;
  2080. }
  2081. static void __run_delayed_extent_op(struct btrfs_delayed_extent_op *extent_op,
  2082. struct extent_buffer *leaf,
  2083. struct btrfs_extent_item *ei)
  2084. {
  2085. u64 flags = btrfs_extent_flags(leaf, ei);
  2086. if (extent_op->update_flags) {
  2087. flags |= extent_op->flags_to_set;
  2088. btrfs_set_extent_flags(leaf, ei, flags);
  2089. }
  2090. if (extent_op->update_key) {
  2091. struct btrfs_tree_block_info *bi;
  2092. BUG_ON(!(flags & BTRFS_EXTENT_FLAG_TREE_BLOCK));
  2093. bi = (struct btrfs_tree_block_info *)(ei + 1);
  2094. btrfs_set_tree_block_key(leaf, bi, &extent_op->key);
  2095. }
  2096. }
  2097. static int run_delayed_extent_op(struct btrfs_trans_handle *trans,
  2098. struct btrfs_fs_info *fs_info,
  2099. struct btrfs_delayed_ref_head *head,
  2100. struct btrfs_delayed_extent_op *extent_op)
  2101. {
  2102. struct btrfs_key key;
  2103. struct btrfs_path *path;
  2104. struct btrfs_extent_item *ei;
  2105. struct extent_buffer *leaf;
  2106. u32 item_size;
  2107. int ret;
  2108. int err = 0;
  2109. int metadata = !extent_op->is_data;
  2110. if (trans->aborted)
  2111. return 0;
  2112. if (metadata && !btrfs_fs_incompat(fs_info, SKINNY_METADATA))
  2113. metadata = 0;
  2114. path = btrfs_alloc_path();
  2115. if (!path)
  2116. return -ENOMEM;
  2117. key.objectid = head->bytenr;
  2118. if (metadata) {
  2119. key.type = BTRFS_METADATA_ITEM_KEY;
  2120. key.offset = extent_op->level;
  2121. } else {
  2122. key.type = BTRFS_EXTENT_ITEM_KEY;
  2123. key.offset = head->num_bytes;
  2124. }
  2125. again:
  2126. path->reada = READA_FORWARD;
  2127. path->leave_spinning = 1;
  2128. ret = btrfs_search_slot(trans, fs_info->extent_root, &key, path, 0, 1);
  2129. if (ret < 0) {
  2130. err = ret;
  2131. goto out;
  2132. }
  2133. if (ret > 0) {
  2134. if (metadata) {
  2135. if (path->slots[0] > 0) {
  2136. path->slots[0]--;
  2137. btrfs_item_key_to_cpu(path->nodes[0], &key,
  2138. path->slots[0]);
  2139. if (key.objectid == head->bytenr &&
  2140. key.type == BTRFS_EXTENT_ITEM_KEY &&
  2141. key.offset == head->num_bytes)
  2142. ret = 0;
  2143. }
  2144. if (ret > 0) {
  2145. btrfs_release_path(path);
  2146. metadata = 0;
  2147. key.objectid = head->bytenr;
  2148. key.offset = head->num_bytes;
  2149. key.type = BTRFS_EXTENT_ITEM_KEY;
  2150. goto again;
  2151. }
  2152. } else {
  2153. err = -EIO;
  2154. goto out;
  2155. }
  2156. }
  2157. leaf = path->nodes[0];
  2158. item_size = btrfs_item_size_nr(leaf, path->slots[0]);
  2159. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  2160. if (item_size < sizeof(*ei)) {
  2161. ret = convert_extent_item_v0(trans, fs_info, path, (u64)-1, 0);
  2162. if (ret < 0) {
  2163. err = ret;
  2164. goto out;
  2165. }
  2166. leaf = path->nodes[0];
  2167. item_size = btrfs_item_size_nr(leaf, path->slots[0]);
  2168. }
  2169. #endif
  2170. BUG_ON(item_size < sizeof(*ei));
  2171. ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  2172. __run_delayed_extent_op(extent_op, leaf, ei);
  2173. btrfs_mark_buffer_dirty(leaf);
  2174. out:
  2175. btrfs_free_path(path);
  2176. return err;
  2177. }
  2178. static int run_delayed_tree_ref(struct btrfs_trans_handle *trans,
  2179. struct btrfs_fs_info *fs_info,
  2180. struct btrfs_delayed_ref_node *node,
  2181. struct btrfs_delayed_extent_op *extent_op,
  2182. int insert_reserved)
  2183. {
  2184. int ret = 0;
  2185. struct btrfs_delayed_tree_ref *ref;
  2186. struct btrfs_key ins;
  2187. u64 parent = 0;
  2188. u64 ref_root = 0;
  2189. bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
  2190. ref = btrfs_delayed_node_to_tree_ref(node);
  2191. trace_run_delayed_tree_ref(fs_info, node, ref, node->action);
  2192. if (node->type == BTRFS_SHARED_BLOCK_REF_KEY)
  2193. parent = ref->parent;
  2194. ref_root = ref->root;
  2195. ins.objectid = node->bytenr;
  2196. if (skinny_metadata) {
  2197. ins.offset = ref->level;
  2198. ins.type = BTRFS_METADATA_ITEM_KEY;
  2199. } else {
  2200. ins.offset = node->num_bytes;
  2201. ins.type = BTRFS_EXTENT_ITEM_KEY;
  2202. }
  2203. if (node->ref_mod != 1) {
  2204. btrfs_err(fs_info,
  2205. "btree block(%llu) has %d references rather than 1: action %d ref_root %llu parent %llu",
  2206. node->bytenr, node->ref_mod, node->action, ref_root,
  2207. parent);
  2208. return -EIO;
  2209. }
  2210. if (node->action == BTRFS_ADD_DELAYED_REF && insert_reserved) {
  2211. BUG_ON(!extent_op || !extent_op->update_flags);
  2212. ret = alloc_reserved_tree_block(trans, fs_info,
  2213. parent, ref_root,
  2214. extent_op->flags_to_set,
  2215. &extent_op->key,
  2216. ref->level, &ins);
  2217. } else if (node->action == BTRFS_ADD_DELAYED_REF) {
  2218. ret = __btrfs_inc_extent_ref(trans, fs_info, node,
  2219. parent, ref_root,
  2220. ref->level, 0, 1,
  2221. extent_op);
  2222. } else if (node->action == BTRFS_DROP_DELAYED_REF) {
  2223. ret = __btrfs_free_extent(trans, fs_info, node,
  2224. parent, ref_root,
  2225. ref->level, 0, 1, extent_op);
  2226. } else {
  2227. BUG();
  2228. }
  2229. return ret;
  2230. }
  2231. /* helper function to actually process a single delayed ref entry */
  2232. static int run_one_delayed_ref(struct btrfs_trans_handle *trans,
  2233. struct btrfs_fs_info *fs_info,
  2234. struct btrfs_delayed_ref_node *node,
  2235. struct btrfs_delayed_extent_op *extent_op,
  2236. int insert_reserved)
  2237. {
  2238. int ret = 0;
  2239. if (trans->aborted) {
  2240. if (insert_reserved)
  2241. btrfs_pin_extent(fs_info, node->bytenr,
  2242. node->num_bytes, 1);
  2243. return 0;
  2244. }
  2245. if (node->type == BTRFS_TREE_BLOCK_REF_KEY ||
  2246. node->type == BTRFS_SHARED_BLOCK_REF_KEY)
  2247. ret = run_delayed_tree_ref(trans, fs_info, node, extent_op,
  2248. insert_reserved);
  2249. else if (node->type == BTRFS_EXTENT_DATA_REF_KEY ||
  2250. node->type == BTRFS_SHARED_DATA_REF_KEY)
  2251. ret = run_delayed_data_ref(trans, fs_info, node, extent_op,
  2252. insert_reserved);
  2253. else
  2254. BUG();
  2255. return ret;
  2256. }
  2257. static inline struct btrfs_delayed_ref_node *
  2258. select_delayed_ref(struct btrfs_delayed_ref_head *head)
  2259. {
  2260. struct btrfs_delayed_ref_node *ref;
  2261. if (RB_EMPTY_ROOT(&head->ref_tree))
  2262. return NULL;
  2263. /*
  2264. * Select a delayed ref of type BTRFS_ADD_DELAYED_REF first.
  2265. * This is to prevent a ref count from going down to zero, which deletes
  2266. * the extent item from the extent tree, when there still are references
  2267. * to add, which would fail because they would not find the extent item.
  2268. */
  2269. if (!list_empty(&head->ref_add_list))
  2270. return list_first_entry(&head->ref_add_list,
  2271. struct btrfs_delayed_ref_node, add_list);
  2272. ref = rb_entry(rb_first(&head->ref_tree),
  2273. struct btrfs_delayed_ref_node, ref_node);
  2274. ASSERT(list_empty(&ref->add_list));
  2275. return ref;
  2276. }
  2277. static void unselect_delayed_ref_head(struct btrfs_delayed_ref_root *delayed_refs,
  2278. struct btrfs_delayed_ref_head *head)
  2279. {
  2280. spin_lock(&delayed_refs->lock);
  2281. head->processing = 0;
  2282. delayed_refs->num_heads_ready++;
  2283. spin_unlock(&delayed_refs->lock);
  2284. btrfs_delayed_ref_unlock(head);
  2285. }
  2286. static int cleanup_extent_op(struct btrfs_trans_handle *trans,
  2287. struct btrfs_fs_info *fs_info,
  2288. struct btrfs_delayed_ref_head *head)
  2289. {
  2290. struct btrfs_delayed_extent_op *extent_op = head->extent_op;
  2291. int ret;
  2292. if (!extent_op)
  2293. return 0;
  2294. head->extent_op = NULL;
  2295. if (head->must_insert_reserved) {
  2296. btrfs_free_delayed_extent_op(extent_op);
  2297. return 0;
  2298. }
  2299. spin_unlock(&head->lock);
  2300. ret = run_delayed_extent_op(trans, fs_info, head, extent_op);
  2301. btrfs_free_delayed_extent_op(extent_op);
  2302. return ret ? ret : 1;
  2303. }
  2304. static int cleanup_ref_head(struct btrfs_trans_handle *trans,
  2305. struct btrfs_fs_info *fs_info,
  2306. struct btrfs_delayed_ref_head *head)
  2307. {
  2308. struct btrfs_delayed_ref_root *delayed_refs;
  2309. int ret;
  2310. delayed_refs = &trans->transaction->delayed_refs;
  2311. ret = cleanup_extent_op(trans, fs_info, head);
  2312. if (ret < 0) {
  2313. unselect_delayed_ref_head(delayed_refs, head);
  2314. btrfs_debug(fs_info, "run_delayed_extent_op returned %d", ret);
  2315. return ret;
  2316. } else if (ret) {
  2317. return ret;
  2318. }
  2319. /*
  2320. * Need to drop our head ref lock and re-acquire the delayed ref lock
  2321. * and then re-check to make sure nobody got added.
  2322. */
  2323. spin_unlock(&head->lock);
  2324. spin_lock(&delayed_refs->lock);
  2325. spin_lock(&head->lock);
  2326. if (!RB_EMPTY_ROOT(&head->ref_tree) || head->extent_op) {
  2327. spin_unlock(&head->lock);
  2328. spin_unlock(&delayed_refs->lock);
  2329. return 1;
  2330. }
  2331. delayed_refs->num_heads--;
  2332. rb_erase(&head->href_node, &delayed_refs->href_root);
  2333. RB_CLEAR_NODE(&head->href_node);
  2334. spin_unlock(&delayed_refs->lock);
  2335. spin_unlock(&head->lock);
  2336. atomic_dec(&delayed_refs->num_entries);
  2337. trace_run_delayed_ref_head(fs_info, head, 0);
  2338. if (head->total_ref_mod < 0) {
  2339. struct btrfs_block_group_cache *cache;
  2340. cache = btrfs_lookup_block_group(fs_info, head->bytenr);
  2341. ASSERT(cache);
  2342. percpu_counter_add(&cache->space_info->total_bytes_pinned,
  2343. -head->num_bytes);
  2344. btrfs_put_block_group(cache);
  2345. if (head->is_data) {
  2346. spin_lock(&delayed_refs->lock);
  2347. delayed_refs->pending_csums -= head->num_bytes;
  2348. spin_unlock(&delayed_refs->lock);
  2349. }
  2350. }
  2351. if (head->must_insert_reserved) {
  2352. btrfs_pin_extent(fs_info, head->bytenr,
  2353. head->num_bytes, 1);
  2354. if (head->is_data) {
  2355. ret = btrfs_del_csums(trans, fs_info, head->bytenr,
  2356. head->num_bytes);
  2357. }
  2358. }
  2359. /* Also free its reserved qgroup space */
  2360. btrfs_qgroup_free_delayed_ref(fs_info, head->qgroup_ref_root,
  2361. head->qgroup_reserved);
  2362. btrfs_delayed_ref_unlock(head);
  2363. btrfs_put_delayed_ref_head(head);
  2364. return 0;
  2365. }
  2366. /*
  2367. * Returns 0 on success or if called with an already aborted transaction.
  2368. * Returns -ENOMEM or -EIO on failure and will abort the transaction.
  2369. */
  2370. static noinline int __btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
  2371. struct btrfs_fs_info *fs_info,
  2372. unsigned long nr)
  2373. {
  2374. struct btrfs_delayed_ref_root *delayed_refs;
  2375. struct btrfs_delayed_ref_node *ref;
  2376. struct btrfs_delayed_ref_head *locked_ref = NULL;
  2377. struct btrfs_delayed_extent_op *extent_op;
  2378. ktime_t start = ktime_get();
  2379. int ret;
  2380. unsigned long count = 0;
  2381. unsigned long actual_count = 0;
  2382. int must_insert_reserved = 0;
  2383. delayed_refs = &trans->transaction->delayed_refs;
  2384. while (1) {
  2385. if (!locked_ref) {
  2386. if (count >= nr)
  2387. break;
  2388. spin_lock(&delayed_refs->lock);
  2389. locked_ref = btrfs_select_ref_head(trans);
  2390. if (!locked_ref) {
  2391. spin_unlock(&delayed_refs->lock);
  2392. break;
  2393. }
  2394. /* grab the lock that says we are going to process
  2395. * all the refs for this head */
  2396. ret = btrfs_delayed_ref_lock(trans, locked_ref);
  2397. spin_unlock(&delayed_refs->lock);
  2398. /*
  2399. * we may have dropped the spin lock to get the head
  2400. * mutex lock, and that might have given someone else
  2401. * time to free the head. If that's true, it has been
  2402. * removed from our list and we can move on.
  2403. */
  2404. if (ret == -EAGAIN) {
  2405. locked_ref = NULL;
  2406. count++;
  2407. continue;
  2408. }
  2409. }
  2410. /*
  2411. * We need to try and merge add/drops of the same ref since we
  2412. * can run into issues with relocate dropping the implicit ref
  2413. * and then it being added back again before the drop can
  2414. * finish. If we merged anything we need to re-loop so we can
  2415. * get a good ref.
  2416. * Or we can get node references of the same type that weren't
  2417. * merged when created due to bumps in the tree mod seq, and
  2418. * we need to merge them to prevent adding an inline extent
  2419. * backref before dropping it (triggering a BUG_ON at
  2420. * insert_inline_extent_backref()).
  2421. */
  2422. spin_lock(&locked_ref->lock);
  2423. btrfs_merge_delayed_refs(trans, fs_info, delayed_refs,
  2424. locked_ref);
  2425. /*
  2426. * locked_ref is the head node, so we have to go one
  2427. * node back for any delayed ref updates
  2428. */
  2429. ref = select_delayed_ref(locked_ref);
  2430. if (ref && ref->seq &&
  2431. btrfs_check_delayed_seq(fs_info, delayed_refs, ref->seq)) {
  2432. spin_unlock(&locked_ref->lock);
  2433. unselect_delayed_ref_head(delayed_refs, locked_ref);
  2434. locked_ref = NULL;
  2435. cond_resched();
  2436. count++;
  2437. continue;
  2438. }
  2439. /*
  2440. * We're done processing refs in this ref_head, clean everything
  2441. * up and move on to the next ref_head.
  2442. */
  2443. if (!ref) {
  2444. ret = cleanup_ref_head(trans, fs_info, locked_ref);
  2445. if (ret > 0 ) {
  2446. /* We dropped our lock, we need to loop. */
  2447. ret = 0;
  2448. continue;
  2449. } else if (ret) {
  2450. return ret;
  2451. }
  2452. locked_ref = NULL;
  2453. count++;
  2454. continue;
  2455. }
  2456. actual_count++;
  2457. ref->in_tree = 0;
  2458. rb_erase(&ref->ref_node, &locked_ref->ref_tree);
  2459. RB_CLEAR_NODE(&ref->ref_node);
  2460. if (!list_empty(&ref->add_list))
  2461. list_del(&ref->add_list);
  2462. /*
  2463. * When we play the delayed ref, also correct the ref_mod on
  2464. * head
  2465. */
  2466. switch (ref->action) {
  2467. case BTRFS_ADD_DELAYED_REF:
  2468. case BTRFS_ADD_DELAYED_EXTENT:
  2469. locked_ref->ref_mod -= ref->ref_mod;
  2470. break;
  2471. case BTRFS_DROP_DELAYED_REF:
  2472. locked_ref->ref_mod += ref->ref_mod;
  2473. break;
  2474. default:
  2475. WARN_ON(1);
  2476. }
  2477. atomic_dec(&delayed_refs->num_entries);
  2478. /*
  2479. * Record the must-insert_reserved flag before we drop the spin
  2480. * lock.
  2481. */
  2482. must_insert_reserved = locked_ref->must_insert_reserved;
  2483. locked_ref->must_insert_reserved = 0;
  2484. extent_op = locked_ref->extent_op;
  2485. locked_ref->extent_op = NULL;
  2486. spin_unlock(&locked_ref->lock);
  2487. ret = run_one_delayed_ref(trans, fs_info, ref, extent_op,
  2488. must_insert_reserved);
  2489. btrfs_free_delayed_extent_op(extent_op);
  2490. if (ret) {
  2491. unselect_delayed_ref_head(delayed_refs, locked_ref);
  2492. btrfs_put_delayed_ref(ref);
  2493. btrfs_debug(fs_info, "run_one_delayed_ref returned %d",
  2494. ret);
  2495. return ret;
  2496. }
  2497. btrfs_put_delayed_ref(ref);
  2498. count++;
  2499. cond_resched();
  2500. }
  2501. /*
  2502. * We don't want to include ref heads since we can have empty ref heads
  2503. * and those will drastically skew our runtime down since we just do
  2504. * accounting, no actual extent tree updates.
  2505. */
  2506. if (actual_count > 0) {
  2507. u64 runtime = ktime_to_ns(ktime_sub(ktime_get(), start));
  2508. u64 avg;
  2509. /*
  2510. * We weigh the current average higher than our current runtime
  2511. * to avoid large swings in the average.
  2512. */
  2513. spin_lock(&delayed_refs->lock);
  2514. avg = fs_info->avg_delayed_ref_runtime * 3 + runtime;
  2515. fs_info->avg_delayed_ref_runtime = avg >> 2; /* div by 4 */
  2516. spin_unlock(&delayed_refs->lock);
  2517. }
  2518. return 0;
  2519. }
  2520. #ifdef SCRAMBLE_DELAYED_REFS
  2521. /*
  2522. * Normally delayed refs get processed in ascending bytenr order. This
  2523. * correlates in most cases to the order added. To expose dependencies on this
  2524. * order, we start to process the tree in the middle instead of the beginning
  2525. */
  2526. static u64 find_middle(struct rb_root *root)
  2527. {
  2528. struct rb_node *n = root->rb_node;
  2529. struct btrfs_delayed_ref_node *entry;
  2530. int alt = 1;
  2531. u64 middle;
  2532. u64 first = 0, last = 0;
  2533. n = rb_first(root);
  2534. if (n) {
  2535. entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
  2536. first = entry->bytenr;
  2537. }
  2538. n = rb_last(root);
  2539. if (n) {
  2540. entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
  2541. last = entry->bytenr;
  2542. }
  2543. n = root->rb_node;
  2544. while (n) {
  2545. entry = rb_entry(n, struct btrfs_delayed_ref_node, rb_node);
  2546. WARN_ON(!entry->in_tree);
  2547. middle = entry->bytenr;
  2548. if (alt)
  2549. n = n->rb_left;
  2550. else
  2551. n = n->rb_right;
  2552. alt = 1 - alt;
  2553. }
  2554. return middle;
  2555. }
  2556. #endif
  2557. static inline u64 heads_to_leaves(struct btrfs_fs_info *fs_info, u64 heads)
  2558. {
  2559. u64 num_bytes;
  2560. num_bytes = heads * (sizeof(struct btrfs_extent_item) +
  2561. sizeof(struct btrfs_extent_inline_ref));
  2562. if (!btrfs_fs_incompat(fs_info, SKINNY_METADATA))
  2563. num_bytes += heads * sizeof(struct btrfs_tree_block_info);
  2564. /*
  2565. * We don't ever fill up leaves all the way so multiply by 2 just to be
  2566. * closer to what we're really going to want to use.
  2567. */
  2568. return div_u64(num_bytes, BTRFS_LEAF_DATA_SIZE(fs_info));
  2569. }
  2570. /*
  2571. * Takes the number of bytes to be csumm'ed and figures out how many leaves it
  2572. * would require to store the csums for that many bytes.
  2573. */
  2574. u64 btrfs_csum_bytes_to_leaves(struct btrfs_fs_info *fs_info, u64 csum_bytes)
  2575. {
  2576. u64 csum_size;
  2577. u64 num_csums_per_leaf;
  2578. u64 num_csums;
  2579. csum_size = BTRFS_MAX_ITEM_SIZE(fs_info);
  2580. num_csums_per_leaf = div64_u64(csum_size,
  2581. (u64)btrfs_super_csum_size(fs_info->super_copy));
  2582. num_csums = div64_u64(csum_bytes, fs_info->sectorsize);
  2583. num_csums += num_csums_per_leaf - 1;
  2584. num_csums = div64_u64(num_csums, num_csums_per_leaf);
  2585. return num_csums;
  2586. }
  2587. int btrfs_check_space_for_delayed_refs(struct btrfs_trans_handle *trans,
  2588. struct btrfs_fs_info *fs_info)
  2589. {
  2590. struct btrfs_block_rsv *global_rsv;
  2591. u64 num_heads = trans->transaction->delayed_refs.num_heads_ready;
  2592. u64 csum_bytes = trans->transaction->delayed_refs.pending_csums;
  2593. u64 num_dirty_bgs = trans->transaction->num_dirty_bgs;
  2594. u64 num_bytes, num_dirty_bgs_bytes;
  2595. int ret = 0;
  2596. num_bytes = btrfs_calc_trans_metadata_size(fs_info, 1);
  2597. num_heads = heads_to_leaves(fs_info, num_heads);
  2598. if (num_heads > 1)
  2599. num_bytes += (num_heads - 1) * fs_info->nodesize;
  2600. num_bytes <<= 1;
  2601. num_bytes += btrfs_csum_bytes_to_leaves(fs_info, csum_bytes) *
  2602. fs_info->nodesize;
  2603. num_dirty_bgs_bytes = btrfs_calc_trans_metadata_size(fs_info,
  2604. num_dirty_bgs);
  2605. global_rsv = &fs_info->global_block_rsv;
  2606. /*
  2607. * If we can't allocate any more chunks lets make sure we have _lots_ of
  2608. * wiggle room since running delayed refs can create more delayed refs.
  2609. */
  2610. if (global_rsv->space_info->full) {
  2611. num_dirty_bgs_bytes <<= 1;
  2612. num_bytes <<= 1;
  2613. }
  2614. spin_lock(&global_rsv->lock);
  2615. if (global_rsv->reserved <= num_bytes + num_dirty_bgs_bytes)
  2616. ret = 1;
  2617. spin_unlock(&global_rsv->lock);
  2618. return ret;
  2619. }
  2620. int btrfs_should_throttle_delayed_refs(struct btrfs_trans_handle *trans,
  2621. struct btrfs_fs_info *fs_info)
  2622. {
  2623. u64 num_entries =
  2624. atomic_read(&trans->transaction->delayed_refs.num_entries);
  2625. u64 avg_runtime;
  2626. u64 val;
  2627. smp_mb();
  2628. avg_runtime = fs_info->avg_delayed_ref_runtime;
  2629. val = num_entries * avg_runtime;
  2630. if (val >= NSEC_PER_SEC)
  2631. return 1;
  2632. if (val >= NSEC_PER_SEC / 2)
  2633. return 2;
  2634. return btrfs_check_space_for_delayed_refs(trans, fs_info);
  2635. }
  2636. struct async_delayed_refs {
  2637. struct btrfs_root *root;
  2638. u64 transid;
  2639. int count;
  2640. int error;
  2641. int sync;
  2642. struct completion wait;
  2643. struct btrfs_work work;
  2644. };
  2645. static inline struct async_delayed_refs *
  2646. to_async_delayed_refs(struct btrfs_work *work)
  2647. {
  2648. return container_of(work, struct async_delayed_refs, work);
  2649. }
  2650. static void delayed_ref_async_start(struct btrfs_work *work)
  2651. {
  2652. struct async_delayed_refs *async = to_async_delayed_refs(work);
  2653. struct btrfs_trans_handle *trans;
  2654. struct btrfs_fs_info *fs_info = async->root->fs_info;
  2655. int ret;
  2656. /* if the commit is already started, we don't need to wait here */
  2657. if (btrfs_transaction_blocked(fs_info))
  2658. goto done;
  2659. trans = btrfs_join_transaction(async->root);
  2660. if (IS_ERR(trans)) {
  2661. async->error = PTR_ERR(trans);
  2662. goto done;
  2663. }
  2664. /*
  2665. * trans->sync means that when we call end_transaction, we won't
  2666. * wait on delayed refs
  2667. */
  2668. trans->sync = true;
  2669. /* Don't bother flushing if we got into a different transaction */
  2670. if (trans->transid > async->transid)
  2671. goto end;
  2672. ret = btrfs_run_delayed_refs(trans, fs_info, async->count);
  2673. if (ret)
  2674. async->error = ret;
  2675. end:
  2676. ret = btrfs_end_transaction(trans);
  2677. if (ret && !async->error)
  2678. async->error = ret;
  2679. done:
  2680. if (async->sync)
  2681. complete(&async->wait);
  2682. else
  2683. kfree(async);
  2684. }
  2685. int btrfs_async_run_delayed_refs(struct btrfs_fs_info *fs_info,
  2686. unsigned long count, u64 transid, int wait)
  2687. {
  2688. struct async_delayed_refs *async;
  2689. int ret;
  2690. async = kmalloc(sizeof(*async), GFP_NOFS);
  2691. if (!async)
  2692. return -ENOMEM;
  2693. async->root = fs_info->tree_root;
  2694. async->count = count;
  2695. async->error = 0;
  2696. async->transid = transid;
  2697. if (wait)
  2698. async->sync = 1;
  2699. else
  2700. async->sync = 0;
  2701. init_completion(&async->wait);
  2702. btrfs_init_work(&async->work, btrfs_extent_refs_helper,
  2703. delayed_ref_async_start, NULL, NULL);
  2704. btrfs_queue_work(fs_info->extent_workers, &async->work);
  2705. if (wait) {
  2706. wait_for_completion(&async->wait);
  2707. ret = async->error;
  2708. kfree(async);
  2709. return ret;
  2710. }
  2711. return 0;
  2712. }
  2713. /*
  2714. * this starts processing the delayed reference count updates and
  2715. * extent insertions we have queued up so far. count can be
  2716. * 0, which means to process everything in the tree at the start
  2717. * of the run (but not newly added entries), or it can be some target
  2718. * number you'd like to process.
  2719. *
  2720. * Returns 0 on success or if called with an aborted transaction
  2721. * Returns <0 on error and aborts the transaction
  2722. */
  2723. int btrfs_run_delayed_refs(struct btrfs_trans_handle *trans,
  2724. struct btrfs_fs_info *fs_info, unsigned long count)
  2725. {
  2726. struct rb_node *node;
  2727. struct btrfs_delayed_ref_root *delayed_refs;
  2728. struct btrfs_delayed_ref_head *head;
  2729. int ret;
  2730. int run_all = count == (unsigned long)-1;
  2731. bool can_flush_pending_bgs = trans->can_flush_pending_bgs;
  2732. /* We'll clean this up in btrfs_cleanup_transaction */
  2733. if (trans->aborted)
  2734. return 0;
  2735. if (test_bit(BTRFS_FS_CREATING_FREE_SPACE_TREE, &fs_info->flags))
  2736. return 0;
  2737. delayed_refs = &trans->transaction->delayed_refs;
  2738. if (count == 0)
  2739. count = atomic_read(&delayed_refs->num_entries) * 2;
  2740. again:
  2741. #ifdef SCRAMBLE_DELAYED_REFS
  2742. delayed_refs->run_delayed_start = find_middle(&delayed_refs->root);
  2743. #endif
  2744. trans->can_flush_pending_bgs = false;
  2745. ret = __btrfs_run_delayed_refs(trans, fs_info, count);
  2746. if (ret < 0) {
  2747. btrfs_abort_transaction(trans, ret);
  2748. return ret;
  2749. }
  2750. if (run_all) {
  2751. if (!list_empty(&trans->new_bgs))
  2752. btrfs_create_pending_block_groups(trans, fs_info);
  2753. spin_lock(&delayed_refs->lock);
  2754. node = rb_first(&delayed_refs->href_root);
  2755. if (!node) {
  2756. spin_unlock(&delayed_refs->lock);
  2757. goto out;
  2758. }
  2759. head = rb_entry(node, struct btrfs_delayed_ref_head,
  2760. href_node);
  2761. refcount_inc(&head->refs);
  2762. spin_unlock(&delayed_refs->lock);
  2763. /* Mutex was contended, block until it's released and retry. */
  2764. mutex_lock(&head->mutex);
  2765. mutex_unlock(&head->mutex);
  2766. btrfs_put_delayed_ref_head(head);
  2767. cond_resched();
  2768. goto again;
  2769. }
  2770. out:
  2771. trans->can_flush_pending_bgs = can_flush_pending_bgs;
  2772. return 0;
  2773. }
  2774. int btrfs_set_disk_extent_flags(struct btrfs_trans_handle *trans,
  2775. struct btrfs_fs_info *fs_info,
  2776. u64 bytenr, u64 num_bytes, u64 flags,
  2777. int level, int is_data)
  2778. {
  2779. struct btrfs_delayed_extent_op *extent_op;
  2780. int ret;
  2781. extent_op = btrfs_alloc_delayed_extent_op();
  2782. if (!extent_op)
  2783. return -ENOMEM;
  2784. extent_op->flags_to_set = flags;
  2785. extent_op->update_flags = true;
  2786. extent_op->update_key = false;
  2787. extent_op->is_data = is_data ? true : false;
  2788. extent_op->level = level;
  2789. ret = btrfs_add_delayed_extent_op(fs_info, trans, bytenr,
  2790. num_bytes, extent_op);
  2791. if (ret)
  2792. btrfs_free_delayed_extent_op(extent_op);
  2793. return ret;
  2794. }
  2795. static noinline int check_delayed_ref(struct btrfs_root *root,
  2796. struct btrfs_path *path,
  2797. u64 objectid, u64 offset, u64 bytenr)
  2798. {
  2799. struct btrfs_delayed_ref_head *head;
  2800. struct btrfs_delayed_ref_node *ref;
  2801. struct btrfs_delayed_data_ref *data_ref;
  2802. struct btrfs_delayed_ref_root *delayed_refs;
  2803. struct btrfs_transaction *cur_trans;
  2804. struct rb_node *node;
  2805. int ret = 0;
  2806. cur_trans = root->fs_info->running_transaction;
  2807. if (!cur_trans)
  2808. return 0;
  2809. delayed_refs = &cur_trans->delayed_refs;
  2810. spin_lock(&delayed_refs->lock);
  2811. head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
  2812. if (!head) {
  2813. spin_unlock(&delayed_refs->lock);
  2814. return 0;
  2815. }
  2816. if (!mutex_trylock(&head->mutex)) {
  2817. refcount_inc(&head->refs);
  2818. spin_unlock(&delayed_refs->lock);
  2819. btrfs_release_path(path);
  2820. /*
  2821. * Mutex was contended, block until it's released and let
  2822. * caller try again
  2823. */
  2824. mutex_lock(&head->mutex);
  2825. mutex_unlock(&head->mutex);
  2826. btrfs_put_delayed_ref_head(head);
  2827. return -EAGAIN;
  2828. }
  2829. spin_unlock(&delayed_refs->lock);
  2830. spin_lock(&head->lock);
  2831. /*
  2832. * XXX: We should replace this with a proper search function in the
  2833. * future.
  2834. */
  2835. for (node = rb_first(&head->ref_tree); node; node = rb_next(node)) {
  2836. ref = rb_entry(node, struct btrfs_delayed_ref_node, ref_node);
  2837. /* If it's a shared ref we know a cross reference exists */
  2838. if (ref->type != BTRFS_EXTENT_DATA_REF_KEY) {
  2839. ret = 1;
  2840. break;
  2841. }
  2842. data_ref = btrfs_delayed_node_to_data_ref(ref);
  2843. /*
  2844. * If our ref doesn't match the one we're currently looking at
  2845. * then we have a cross reference.
  2846. */
  2847. if (data_ref->root != root->root_key.objectid ||
  2848. data_ref->objectid != objectid ||
  2849. data_ref->offset != offset) {
  2850. ret = 1;
  2851. break;
  2852. }
  2853. }
  2854. spin_unlock(&head->lock);
  2855. mutex_unlock(&head->mutex);
  2856. return ret;
  2857. }
  2858. static noinline int check_committed_ref(struct btrfs_root *root,
  2859. struct btrfs_path *path,
  2860. u64 objectid, u64 offset, u64 bytenr)
  2861. {
  2862. struct btrfs_fs_info *fs_info = root->fs_info;
  2863. struct btrfs_root *extent_root = fs_info->extent_root;
  2864. struct extent_buffer *leaf;
  2865. struct btrfs_extent_data_ref *ref;
  2866. struct btrfs_extent_inline_ref *iref;
  2867. struct btrfs_extent_item *ei;
  2868. struct btrfs_key key;
  2869. u32 item_size;
  2870. int type;
  2871. int ret;
  2872. key.objectid = bytenr;
  2873. key.offset = (u64)-1;
  2874. key.type = BTRFS_EXTENT_ITEM_KEY;
  2875. ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
  2876. if (ret < 0)
  2877. goto out;
  2878. BUG_ON(ret == 0); /* Corruption */
  2879. ret = -ENOENT;
  2880. if (path->slots[0] == 0)
  2881. goto out;
  2882. path->slots[0]--;
  2883. leaf = path->nodes[0];
  2884. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  2885. if (key.objectid != bytenr || key.type != BTRFS_EXTENT_ITEM_KEY)
  2886. goto out;
  2887. ret = 1;
  2888. item_size = btrfs_item_size_nr(leaf, path->slots[0]);
  2889. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  2890. if (item_size < sizeof(*ei)) {
  2891. WARN_ON(item_size != sizeof(struct btrfs_extent_item_v0));
  2892. goto out;
  2893. }
  2894. #endif
  2895. ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_extent_item);
  2896. if (item_size != sizeof(*ei) +
  2897. btrfs_extent_inline_ref_size(BTRFS_EXTENT_DATA_REF_KEY))
  2898. goto out;
  2899. if (btrfs_extent_generation(leaf, ei) <=
  2900. btrfs_root_last_snapshot(&root->root_item))
  2901. goto out;
  2902. iref = (struct btrfs_extent_inline_ref *)(ei + 1);
  2903. type = btrfs_get_extent_inline_ref_type(leaf, iref, BTRFS_REF_TYPE_DATA);
  2904. if (type != BTRFS_EXTENT_DATA_REF_KEY)
  2905. goto out;
  2906. ref = (struct btrfs_extent_data_ref *)(&iref->offset);
  2907. if (btrfs_extent_refs(leaf, ei) !=
  2908. btrfs_extent_data_ref_count(leaf, ref) ||
  2909. btrfs_extent_data_ref_root(leaf, ref) !=
  2910. root->root_key.objectid ||
  2911. btrfs_extent_data_ref_objectid(leaf, ref) != objectid ||
  2912. btrfs_extent_data_ref_offset(leaf, ref) != offset)
  2913. goto out;
  2914. ret = 0;
  2915. out:
  2916. return ret;
  2917. }
  2918. int btrfs_cross_ref_exist(struct btrfs_root *root, u64 objectid, u64 offset,
  2919. u64 bytenr)
  2920. {
  2921. struct btrfs_path *path;
  2922. int ret;
  2923. int ret2;
  2924. path = btrfs_alloc_path();
  2925. if (!path)
  2926. return -ENOENT;
  2927. do {
  2928. ret = check_committed_ref(root, path, objectid,
  2929. offset, bytenr);
  2930. if (ret && ret != -ENOENT)
  2931. goto out;
  2932. ret2 = check_delayed_ref(root, path, objectid,
  2933. offset, bytenr);
  2934. } while (ret2 == -EAGAIN);
  2935. if (ret2 && ret2 != -ENOENT) {
  2936. ret = ret2;
  2937. goto out;
  2938. }
  2939. if (ret != -ENOENT || ret2 != -ENOENT)
  2940. ret = 0;
  2941. out:
  2942. btrfs_free_path(path);
  2943. if (root->root_key.objectid == BTRFS_DATA_RELOC_TREE_OBJECTID)
  2944. WARN_ON(ret > 0);
  2945. return ret;
  2946. }
  2947. static int __btrfs_mod_ref(struct btrfs_trans_handle *trans,
  2948. struct btrfs_root *root,
  2949. struct extent_buffer *buf,
  2950. int full_backref, int inc)
  2951. {
  2952. struct btrfs_fs_info *fs_info = root->fs_info;
  2953. u64 bytenr;
  2954. u64 num_bytes;
  2955. u64 parent;
  2956. u64 ref_root;
  2957. u32 nritems;
  2958. struct btrfs_key key;
  2959. struct btrfs_file_extent_item *fi;
  2960. int i;
  2961. int level;
  2962. int ret = 0;
  2963. int (*process_func)(struct btrfs_trans_handle *,
  2964. struct btrfs_root *,
  2965. u64, u64, u64, u64, u64, u64);
  2966. if (btrfs_is_testing(fs_info))
  2967. return 0;
  2968. ref_root = btrfs_header_owner(buf);
  2969. nritems = btrfs_header_nritems(buf);
  2970. level = btrfs_header_level(buf);
  2971. if (!test_bit(BTRFS_ROOT_REF_COWS, &root->state) && level == 0)
  2972. return 0;
  2973. if (inc)
  2974. process_func = btrfs_inc_extent_ref;
  2975. else
  2976. process_func = btrfs_free_extent;
  2977. if (full_backref)
  2978. parent = buf->start;
  2979. else
  2980. parent = 0;
  2981. for (i = 0; i < nritems; i++) {
  2982. if (level == 0) {
  2983. btrfs_item_key_to_cpu(buf, &key, i);
  2984. if (key.type != BTRFS_EXTENT_DATA_KEY)
  2985. continue;
  2986. fi = btrfs_item_ptr(buf, i,
  2987. struct btrfs_file_extent_item);
  2988. if (btrfs_file_extent_type(buf, fi) ==
  2989. BTRFS_FILE_EXTENT_INLINE)
  2990. continue;
  2991. bytenr = btrfs_file_extent_disk_bytenr(buf, fi);
  2992. if (bytenr == 0)
  2993. continue;
  2994. num_bytes = btrfs_file_extent_disk_num_bytes(buf, fi);
  2995. key.offset -= btrfs_file_extent_offset(buf, fi);
  2996. ret = process_func(trans, root, bytenr, num_bytes,
  2997. parent, ref_root, key.objectid,
  2998. key.offset);
  2999. if (ret)
  3000. goto fail;
  3001. } else {
  3002. bytenr = btrfs_node_blockptr(buf, i);
  3003. num_bytes = fs_info->nodesize;
  3004. ret = process_func(trans, root, bytenr, num_bytes,
  3005. parent, ref_root, level - 1, 0);
  3006. if (ret)
  3007. goto fail;
  3008. }
  3009. }
  3010. return 0;
  3011. fail:
  3012. return ret;
  3013. }
  3014. int btrfs_inc_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
  3015. struct extent_buffer *buf, int full_backref)
  3016. {
  3017. return __btrfs_mod_ref(trans, root, buf, full_backref, 1);
  3018. }
  3019. int btrfs_dec_ref(struct btrfs_trans_handle *trans, struct btrfs_root *root,
  3020. struct extent_buffer *buf, int full_backref)
  3021. {
  3022. return __btrfs_mod_ref(trans, root, buf, full_backref, 0);
  3023. }
  3024. static int write_one_cache_group(struct btrfs_trans_handle *trans,
  3025. struct btrfs_fs_info *fs_info,
  3026. struct btrfs_path *path,
  3027. struct btrfs_block_group_cache *cache)
  3028. {
  3029. int ret;
  3030. struct btrfs_root *extent_root = fs_info->extent_root;
  3031. unsigned long bi;
  3032. struct extent_buffer *leaf;
  3033. ret = btrfs_search_slot(trans, extent_root, &cache->key, path, 0, 1);
  3034. if (ret) {
  3035. if (ret > 0)
  3036. ret = -ENOENT;
  3037. goto fail;
  3038. }
  3039. leaf = path->nodes[0];
  3040. bi = btrfs_item_ptr_offset(leaf, path->slots[0]);
  3041. write_extent_buffer(leaf, &cache->item, bi, sizeof(cache->item));
  3042. btrfs_mark_buffer_dirty(leaf);
  3043. fail:
  3044. btrfs_release_path(path);
  3045. return ret;
  3046. }
  3047. static struct btrfs_block_group_cache *
  3048. next_block_group(struct btrfs_fs_info *fs_info,
  3049. struct btrfs_block_group_cache *cache)
  3050. {
  3051. struct rb_node *node;
  3052. spin_lock(&fs_info->block_group_cache_lock);
  3053. /* If our block group was removed, we need a full search. */
  3054. if (RB_EMPTY_NODE(&cache->cache_node)) {
  3055. const u64 next_bytenr = cache->key.objectid + cache->key.offset;
  3056. spin_unlock(&fs_info->block_group_cache_lock);
  3057. btrfs_put_block_group(cache);
  3058. cache = btrfs_lookup_first_block_group(fs_info, next_bytenr); return cache;
  3059. }
  3060. node = rb_next(&cache->cache_node);
  3061. btrfs_put_block_group(cache);
  3062. if (node) {
  3063. cache = rb_entry(node, struct btrfs_block_group_cache,
  3064. cache_node);
  3065. btrfs_get_block_group(cache);
  3066. } else
  3067. cache = NULL;
  3068. spin_unlock(&fs_info->block_group_cache_lock);
  3069. return cache;
  3070. }
  3071. static int cache_save_setup(struct btrfs_block_group_cache *block_group,
  3072. struct btrfs_trans_handle *trans,
  3073. struct btrfs_path *path)
  3074. {
  3075. struct btrfs_fs_info *fs_info = block_group->fs_info;
  3076. struct btrfs_root *root = fs_info->tree_root;
  3077. struct inode *inode = NULL;
  3078. struct extent_changeset *data_reserved = NULL;
  3079. u64 alloc_hint = 0;
  3080. int dcs = BTRFS_DC_ERROR;
  3081. u64 num_pages = 0;
  3082. int retries = 0;
  3083. int ret = 0;
  3084. /*
  3085. * If this block group is smaller than 100 megs don't bother caching the
  3086. * block group.
  3087. */
  3088. if (block_group->key.offset < (100 * SZ_1M)) {
  3089. spin_lock(&block_group->lock);
  3090. block_group->disk_cache_state = BTRFS_DC_WRITTEN;
  3091. spin_unlock(&block_group->lock);
  3092. return 0;
  3093. }
  3094. if (trans->aborted)
  3095. return 0;
  3096. again:
  3097. inode = lookup_free_space_inode(fs_info, block_group, path);
  3098. if (IS_ERR(inode) && PTR_ERR(inode) != -ENOENT) {
  3099. ret = PTR_ERR(inode);
  3100. btrfs_release_path(path);
  3101. goto out;
  3102. }
  3103. if (IS_ERR(inode)) {
  3104. BUG_ON(retries);
  3105. retries++;
  3106. if (block_group->ro)
  3107. goto out_free;
  3108. ret = create_free_space_inode(fs_info, trans, block_group,
  3109. path);
  3110. if (ret)
  3111. goto out_free;
  3112. goto again;
  3113. }
  3114. /*
  3115. * We want to set the generation to 0, that way if anything goes wrong
  3116. * from here on out we know not to trust this cache when we load up next
  3117. * time.
  3118. */
  3119. BTRFS_I(inode)->generation = 0;
  3120. ret = btrfs_update_inode(trans, root, inode);
  3121. if (ret) {
  3122. /*
  3123. * So theoretically we could recover from this, simply set the
  3124. * super cache generation to 0 so we know to invalidate the
  3125. * cache, but then we'd have to keep track of the block groups
  3126. * that fail this way so we know we _have_ to reset this cache
  3127. * before the next commit or risk reading stale cache. So to
  3128. * limit our exposure to horrible edge cases lets just abort the
  3129. * transaction, this only happens in really bad situations
  3130. * anyway.
  3131. */
  3132. btrfs_abort_transaction(trans, ret);
  3133. goto out_put;
  3134. }
  3135. WARN_ON(ret);
  3136. /* We've already setup this transaction, go ahead and exit */
  3137. if (block_group->cache_generation == trans->transid &&
  3138. i_size_read(inode)) {
  3139. dcs = BTRFS_DC_SETUP;
  3140. goto out_put;
  3141. }
  3142. if (i_size_read(inode) > 0) {
  3143. ret = btrfs_check_trunc_cache_free_space(fs_info,
  3144. &fs_info->global_block_rsv);
  3145. if (ret)
  3146. goto out_put;
  3147. ret = btrfs_truncate_free_space_cache(trans, NULL, inode);
  3148. if (ret)
  3149. goto out_put;
  3150. }
  3151. spin_lock(&block_group->lock);
  3152. if (block_group->cached != BTRFS_CACHE_FINISHED ||
  3153. !btrfs_test_opt(fs_info, SPACE_CACHE)) {
  3154. /*
  3155. * don't bother trying to write stuff out _if_
  3156. * a) we're not cached,
  3157. * b) we're with nospace_cache mount option,
  3158. * c) we're with v2 space_cache (FREE_SPACE_TREE).
  3159. */
  3160. dcs = BTRFS_DC_WRITTEN;
  3161. spin_unlock(&block_group->lock);
  3162. goto out_put;
  3163. }
  3164. spin_unlock(&block_group->lock);
  3165. /*
  3166. * We hit an ENOSPC when setting up the cache in this transaction, just
  3167. * skip doing the setup, we've already cleared the cache so we're safe.
  3168. */
  3169. if (test_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags)) {
  3170. ret = -ENOSPC;
  3171. goto out_put;
  3172. }
  3173. /*
  3174. * Try to preallocate enough space based on how big the block group is.
  3175. * Keep in mind this has to include any pinned space which could end up
  3176. * taking up quite a bit since it's not folded into the other space
  3177. * cache.
  3178. */
  3179. num_pages = div_u64(block_group->key.offset, SZ_256M);
  3180. if (!num_pages)
  3181. num_pages = 1;
  3182. num_pages *= 16;
  3183. num_pages *= PAGE_SIZE;
  3184. ret = btrfs_check_data_free_space(inode, &data_reserved, 0, num_pages);
  3185. if (ret)
  3186. goto out_put;
  3187. ret = btrfs_prealloc_file_range_trans(inode, trans, 0, 0, num_pages,
  3188. num_pages, num_pages,
  3189. &alloc_hint);
  3190. /*
  3191. * Our cache requires contiguous chunks so that we don't modify a bunch
  3192. * of metadata or split extents when writing the cache out, which means
  3193. * we can enospc if we are heavily fragmented in addition to just normal
  3194. * out of space conditions. So if we hit this just skip setting up any
  3195. * other block groups for this transaction, maybe we'll unpin enough
  3196. * space the next time around.
  3197. */
  3198. if (!ret)
  3199. dcs = BTRFS_DC_SETUP;
  3200. else if (ret == -ENOSPC)
  3201. set_bit(BTRFS_TRANS_CACHE_ENOSPC, &trans->transaction->flags);
  3202. out_put:
  3203. iput(inode);
  3204. out_free:
  3205. btrfs_release_path(path);
  3206. out:
  3207. spin_lock(&block_group->lock);
  3208. if (!ret && dcs == BTRFS_DC_SETUP)
  3209. block_group->cache_generation = trans->transid;
  3210. block_group->disk_cache_state = dcs;
  3211. spin_unlock(&block_group->lock);
  3212. extent_changeset_free(data_reserved);
  3213. return ret;
  3214. }
  3215. int btrfs_setup_space_cache(struct btrfs_trans_handle *trans,
  3216. struct btrfs_fs_info *fs_info)
  3217. {
  3218. struct btrfs_block_group_cache *cache, *tmp;
  3219. struct btrfs_transaction *cur_trans = trans->transaction;
  3220. struct btrfs_path *path;
  3221. if (list_empty(&cur_trans->dirty_bgs) ||
  3222. !btrfs_test_opt(fs_info, SPACE_CACHE))
  3223. return 0;
  3224. path = btrfs_alloc_path();
  3225. if (!path)
  3226. return -ENOMEM;
  3227. /* Could add new block groups, use _safe just in case */
  3228. list_for_each_entry_safe(cache, tmp, &cur_trans->dirty_bgs,
  3229. dirty_list) {
  3230. if (cache->disk_cache_state == BTRFS_DC_CLEAR)
  3231. cache_save_setup(cache, trans, path);
  3232. }
  3233. btrfs_free_path(path);
  3234. return 0;
  3235. }
  3236. /*
  3237. * transaction commit does final block group cache writeback during a
  3238. * critical section where nothing is allowed to change the FS. This is
  3239. * required in order for the cache to actually match the block group,
  3240. * but can introduce a lot of latency into the commit.
  3241. *
  3242. * So, btrfs_start_dirty_block_groups is here to kick off block group
  3243. * cache IO. There's a chance we'll have to redo some of it if the
  3244. * block group changes again during the commit, but it greatly reduces
  3245. * the commit latency by getting rid of the easy block groups while
  3246. * we're still allowing others to join the commit.
  3247. */
  3248. int btrfs_start_dirty_block_groups(struct btrfs_trans_handle *trans,
  3249. struct btrfs_fs_info *fs_info)
  3250. {
  3251. struct btrfs_block_group_cache *cache;
  3252. struct btrfs_transaction *cur_trans = trans->transaction;
  3253. int ret = 0;
  3254. int should_put;
  3255. struct btrfs_path *path = NULL;
  3256. LIST_HEAD(dirty);
  3257. struct list_head *io = &cur_trans->io_bgs;
  3258. int num_started = 0;
  3259. int loops = 0;
  3260. spin_lock(&cur_trans->dirty_bgs_lock);
  3261. if (list_empty(&cur_trans->dirty_bgs)) {
  3262. spin_unlock(&cur_trans->dirty_bgs_lock);
  3263. return 0;
  3264. }
  3265. list_splice_init(&cur_trans->dirty_bgs, &dirty);
  3266. spin_unlock(&cur_trans->dirty_bgs_lock);
  3267. again:
  3268. /*
  3269. * make sure all the block groups on our dirty list actually
  3270. * exist
  3271. */
  3272. btrfs_create_pending_block_groups(trans, fs_info);
  3273. if (!path) {
  3274. path = btrfs_alloc_path();
  3275. if (!path)
  3276. return -ENOMEM;
  3277. }
  3278. /*
  3279. * cache_write_mutex is here only to save us from balance or automatic
  3280. * removal of empty block groups deleting this block group while we are
  3281. * writing out the cache
  3282. */
  3283. mutex_lock(&trans->transaction->cache_write_mutex);
  3284. while (!list_empty(&dirty)) {
  3285. cache = list_first_entry(&dirty,
  3286. struct btrfs_block_group_cache,
  3287. dirty_list);
  3288. /*
  3289. * this can happen if something re-dirties a block
  3290. * group that is already under IO. Just wait for it to
  3291. * finish and then do it all again
  3292. */
  3293. if (!list_empty(&cache->io_list)) {
  3294. list_del_init(&cache->io_list);
  3295. btrfs_wait_cache_io(trans, cache, path);
  3296. btrfs_put_block_group(cache);
  3297. }
  3298. /*
  3299. * btrfs_wait_cache_io uses the cache->dirty_list to decide
  3300. * if it should update the cache_state. Don't delete
  3301. * until after we wait.
  3302. *
  3303. * Since we're not running in the commit critical section
  3304. * we need the dirty_bgs_lock to protect from update_block_group
  3305. */
  3306. spin_lock(&cur_trans->dirty_bgs_lock);
  3307. list_del_init(&cache->dirty_list);
  3308. spin_unlock(&cur_trans->dirty_bgs_lock);
  3309. should_put = 1;
  3310. cache_save_setup(cache, trans, path);
  3311. if (cache->disk_cache_state == BTRFS_DC_SETUP) {
  3312. cache->io_ctl.inode = NULL;
  3313. ret = btrfs_write_out_cache(fs_info, trans,
  3314. cache, path);
  3315. if (ret == 0 && cache->io_ctl.inode) {
  3316. num_started++;
  3317. should_put = 0;
  3318. /*
  3319. * the cache_write_mutex is protecting
  3320. * the io_list
  3321. */
  3322. list_add_tail(&cache->io_list, io);
  3323. } else {
  3324. /*
  3325. * if we failed to write the cache, the
  3326. * generation will be bad and life goes on
  3327. */
  3328. ret = 0;
  3329. }
  3330. }
  3331. if (!ret) {
  3332. ret = write_one_cache_group(trans, fs_info,
  3333. path, cache);
  3334. /*
  3335. * Our block group might still be attached to the list
  3336. * of new block groups in the transaction handle of some
  3337. * other task (struct btrfs_trans_handle->new_bgs). This
  3338. * means its block group item isn't yet in the extent
  3339. * tree. If this happens ignore the error, as we will
  3340. * try again later in the critical section of the
  3341. * transaction commit.
  3342. */
  3343. if (ret == -ENOENT) {
  3344. ret = 0;
  3345. spin_lock(&cur_trans->dirty_bgs_lock);
  3346. if (list_empty(&cache->dirty_list)) {
  3347. list_add_tail(&cache->dirty_list,
  3348. &cur_trans->dirty_bgs);
  3349. btrfs_get_block_group(cache);
  3350. }
  3351. spin_unlock(&cur_trans->dirty_bgs_lock);
  3352. } else if (ret) {
  3353. btrfs_abort_transaction(trans, ret);
  3354. }
  3355. }
  3356. /* if its not on the io list, we need to put the block group */
  3357. if (should_put)
  3358. btrfs_put_block_group(cache);
  3359. if (ret)
  3360. break;
  3361. /*
  3362. * Avoid blocking other tasks for too long. It might even save
  3363. * us from writing caches for block groups that are going to be
  3364. * removed.
  3365. */
  3366. mutex_unlock(&trans->transaction->cache_write_mutex);
  3367. mutex_lock(&trans->transaction->cache_write_mutex);
  3368. }
  3369. mutex_unlock(&trans->transaction->cache_write_mutex);
  3370. /*
  3371. * go through delayed refs for all the stuff we've just kicked off
  3372. * and then loop back (just once)
  3373. */
  3374. ret = btrfs_run_delayed_refs(trans, fs_info, 0);
  3375. if (!ret && loops == 0) {
  3376. loops++;
  3377. spin_lock(&cur_trans->dirty_bgs_lock);
  3378. list_splice_init(&cur_trans->dirty_bgs, &dirty);
  3379. /*
  3380. * dirty_bgs_lock protects us from concurrent block group
  3381. * deletes too (not just cache_write_mutex).
  3382. */
  3383. if (!list_empty(&dirty)) {
  3384. spin_unlock(&cur_trans->dirty_bgs_lock);
  3385. goto again;
  3386. }
  3387. spin_unlock(&cur_trans->dirty_bgs_lock);
  3388. } else if (ret < 0) {
  3389. btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
  3390. }
  3391. btrfs_free_path(path);
  3392. return ret;
  3393. }
  3394. int btrfs_write_dirty_block_groups(struct btrfs_trans_handle *trans,
  3395. struct btrfs_fs_info *fs_info)
  3396. {
  3397. struct btrfs_block_group_cache *cache;
  3398. struct btrfs_transaction *cur_trans = trans->transaction;
  3399. int ret = 0;
  3400. int should_put;
  3401. struct btrfs_path *path;
  3402. struct list_head *io = &cur_trans->io_bgs;
  3403. int num_started = 0;
  3404. path = btrfs_alloc_path();
  3405. if (!path)
  3406. return -ENOMEM;
  3407. /*
  3408. * Even though we are in the critical section of the transaction commit,
  3409. * we can still have concurrent tasks adding elements to this
  3410. * transaction's list of dirty block groups. These tasks correspond to
  3411. * endio free space workers started when writeback finishes for a
  3412. * space cache, which run inode.c:btrfs_finish_ordered_io(), and can
  3413. * allocate new block groups as a result of COWing nodes of the root
  3414. * tree when updating the free space inode. The writeback for the space
  3415. * caches is triggered by an earlier call to
  3416. * btrfs_start_dirty_block_groups() and iterations of the following
  3417. * loop.
  3418. * Also we want to do the cache_save_setup first and then run the
  3419. * delayed refs to make sure we have the best chance at doing this all
  3420. * in one shot.
  3421. */
  3422. spin_lock(&cur_trans->dirty_bgs_lock);
  3423. while (!list_empty(&cur_trans->dirty_bgs)) {
  3424. cache = list_first_entry(&cur_trans->dirty_bgs,
  3425. struct btrfs_block_group_cache,
  3426. dirty_list);
  3427. /*
  3428. * this can happen if cache_save_setup re-dirties a block
  3429. * group that is already under IO. Just wait for it to
  3430. * finish and then do it all again
  3431. */
  3432. if (!list_empty(&cache->io_list)) {
  3433. spin_unlock(&cur_trans->dirty_bgs_lock);
  3434. list_del_init(&cache->io_list);
  3435. btrfs_wait_cache_io(trans, cache, path);
  3436. btrfs_put_block_group(cache);
  3437. spin_lock(&cur_trans->dirty_bgs_lock);
  3438. }
  3439. /*
  3440. * don't remove from the dirty list until after we've waited
  3441. * on any pending IO
  3442. */
  3443. list_del_init(&cache->dirty_list);
  3444. spin_unlock(&cur_trans->dirty_bgs_lock);
  3445. should_put = 1;
  3446. cache_save_setup(cache, trans, path);
  3447. if (!ret)
  3448. ret = btrfs_run_delayed_refs(trans, fs_info,
  3449. (unsigned long) -1);
  3450. if (!ret && cache->disk_cache_state == BTRFS_DC_SETUP) {
  3451. cache->io_ctl.inode = NULL;
  3452. ret = btrfs_write_out_cache(fs_info, trans,
  3453. cache, path);
  3454. if (ret == 0 && cache->io_ctl.inode) {
  3455. num_started++;
  3456. should_put = 0;
  3457. list_add_tail(&cache->io_list, io);
  3458. } else {
  3459. /*
  3460. * if we failed to write the cache, the
  3461. * generation will be bad and life goes on
  3462. */
  3463. ret = 0;
  3464. }
  3465. }
  3466. if (!ret) {
  3467. ret = write_one_cache_group(trans, fs_info,
  3468. path, cache);
  3469. /*
  3470. * One of the free space endio workers might have
  3471. * created a new block group while updating a free space
  3472. * cache's inode (at inode.c:btrfs_finish_ordered_io())
  3473. * and hasn't released its transaction handle yet, in
  3474. * which case the new block group is still attached to
  3475. * its transaction handle and its creation has not
  3476. * finished yet (no block group item in the extent tree
  3477. * yet, etc). If this is the case, wait for all free
  3478. * space endio workers to finish and retry. This is a
  3479. * a very rare case so no need for a more efficient and
  3480. * complex approach.
  3481. */
  3482. if (ret == -ENOENT) {
  3483. wait_event(cur_trans->writer_wait,
  3484. atomic_read(&cur_trans->num_writers) == 1);
  3485. ret = write_one_cache_group(trans, fs_info,
  3486. path, cache);
  3487. }
  3488. if (ret)
  3489. btrfs_abort_transaction(trans, ret);
  3490. }
  3491. /* if its not on the io list, we need to put the block group */
  3492. if (should_put)
  3493. btrfs_put_block_group(cache);
  3494. spin_lock(&cur_trans->dirty_bgs_lock);
  3495. }
  3496. spin_unlock(&cur_trans->dirty_bgs_lock);
  3497. while (!list_empty(io)) {
  3498. cache = list_first_entry(io, struct btrfs_block_group_cache,
  3499. io_list);
  3500. list_del_init(&cache->io_list);
  3501. btrfs_wait_cache_io(trans, cache, path);
  3502. btrfs_put_block_group(cache);
  3503. }
  3504. btrfs_free_path(path);
  3505. return ret;
  3506. }
  3507. int btrfs_extent_readonly(struct btrfs_fs_info *fs_info, u64 bytenr)
  3508. {
  3509. struct btrfs_block_group_cache *block_group;
  3510. int readonly = 0;
  3511. block_group = btrfs_lookup_block_group(fs_info, bytenr);
  3512. if (!block_group || block_group->ro)
  3513. readonly = 1;
  3514. if (block_group)
  3515. btrfs_put_block_group(block_group);
  3516. return readonly;
  3517. }
  3518. bool btrfs_inc_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
  3519. {
  3520. struct btrfs_block_group_cache *bg;
  3521. bool ret = true;
  3522. bg = btrfs_lookup_block_group(fs_info, bytenr);
  3523. if (!bg)
  3524. return false;
  3525. spin_lock(&bg->lock);
  3526. if (bg->ro)
  3527. ret = false;
  3528. else
  3529. atomic_inc(&bg->nocow_writers);
  3530. spin_unlock(&bg->lock);
  3531. /* no put on block group, done by btrfs_dec_nocow_writers */
  3532. if (!ret)
  3533. btrfs_put_block_group(bg);
  3534. return ret;
  3535. }
  3536. void btrfs_dec_nocow_writers(struct btrfs_fs_info *fs_info, u64 bytenr)
  3537. {
  3538. struct btrfs_block_group_cache *bg;
  3539. bg = btrfs_lookup_block_group(fs_info, bytenr);
  3540. ASSERT(bg);
  3541. if (atomic_dec_and_test(&bg->nocow_writers))
  3542. wake_up_atomic_t(&bg->nocow_writers);
  3543. /*
  3544. * Once for our lookup and once for the lookup done by a previous call
  3545. * to btrfs_inc_nocow_writers()
  3546. */
  3547. btrfs_put_block_group(bg);
  3548. btrfs_put_block_group(bg);
  3549. }
  3550. void btrfs_wait_nocow_writers(struct btrfs_block_group_cache *bg)
  3551. {
  3552. wait_on_atomic_t(&bg->nocow_writers, atomic_t_wait,
  3553. TASK_UNINTERRUPTIBLE);
  3554. }
  3555. static const char *alloc_name(u64 flags)
  3556. {
  3557. switch (flags) {
  3558. case BTRFS_BLOCK_GROUP_METADATA|BTRFS_BLOCK_GROUP_DATA:
  3559. return "mixed";
  3560. case BTRFS_BLOCK_GROUP_METADATA:
  3561. return "metadata";
  3562. case BTRFS_BLOCK_GROUP_DATA:
  3563. return "data";
  3564. case BTRFS_BLOCK_GROUP_SYSTEM:
  3565. return "system";
  3566. default:
  3567. WARN_ON(1);
  3568. return "invalid-combination";
  3569. };
  3570. }
  3571. static int create_space_info(struct btrfs_fs_info *info, u64 flags,
  3572. struct btrfs_space_info **new)
  3573. {
  3574. struct btrfs_space_info *space_info;
  3575. int i;
  3576. int ret;
  3577. space_info = kzalloc(sizeof(*space_info), GFP_NOFS);
  3578. if (!space_info)
  3579. return -ENOMEM;
  3580. ret = percpu_counter_init(&space_info->total_bytes_pinned, 0,
  3581. GFP_KERNEL);
  3582. if (ret) {
  3583. kfree(space_info);
  3584. return ret;
  3585. }
  3586. for (i = 0; i < BTRFS_NR_RAID_TYPES; i++)
  3587. INIT_LIST_HEAD(&space_info->block_groups[i]);
  3588. init_rwsem(&space_info->groups_sem);
  3589. spin_lock_init(&space_info->lock);
  3590. space_info->flags = flags & BTRFS_BLOCK_GROUP_TYPE_MASK;
  3591. space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
  3592. init_waitqueue_head(&space_info->wait);
  3593. INIT_LIST_HEAD(&space_info->ro_bgs);
  3594. INIT_LIST_HEAD(&space_info->tickets);
  3595. INIT_LIST_HEAD(&space_info->priority_tickets);
  3596. ret = kobject_init_and_add(&space_info->kobj, &space_info_ktype,
  3597. info->space_info_kobj, "%s",
  3598. alloc_name(space_info->flags));
  3599. if (ret) {
  3600. percpu_counter_destroy(&space_info->total_bytes_pinned);
  3601. kfree(space_info);
  3602. return ret;
  3603. }
  3604. *new = space_info;
  3605. list_add_rcu(&space_info->list, &info->space_info);
  3606. if (flags & BTRFS_BLOCK_GROUP_DATA)
  3607. info->data_sinfo = space_info;
  3608. return ret;
  3609. }
  3610. static void update_space_info(struct btrfs_fs_info *info, u64 flags,
  3611. u64 total_bytes, u64 bytes_used,
  3612. u64 bytes_readonly,
  3613. struct btrfs_space_info **space_info)
  3614. {
  3615. struct btrfs_space_info *found;
  3616. int factor;
  3617. if (flags & (BTRFS_BLOCK_GROUP_DUP | BTRFS_BLOCK_GROUP_RAID1 |
  3618. BTRFS_BLOCK_GROUP_RAID10))
  3619. factor = 2;
  3620. else
  3621. factor = 1;
  3622. found = __find_space_info(info, flags);
  3623. ASSERT(found);
  3624. spin_lock(&found->lock);
  3625. found->total_bytes += total_bytes;
  3626. found->disk_total += total_bytes * factor;
  3627. found->bytes_used += bytes_used;
  3628. found->disk_used += bytes_used * factor;
  3629. found->bytes_readonly += bytes_readonly;
  3630. if (total_bytes > 0)
  3631. found->full = 0;
  3632. space_info_add_new_bytes(info, found, total_bytes -
  3633. bytes_used - bytes_readonly);
  3634. spin_unlock(&found->lock);
  3635. *space_info = found;
  3636. }
  3637. static void set_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
  3638. {
  3639. u64 extra_flags = chunk_to_extended(flags) &
  3640. BTRFS_EXTENDED_PROFILE_MASK;
  3641. write_seqlock(&fs_info->profiles_lock);
  3642. if (flags & BTRFS_BLOCK_GROUP_DATA)
  3643. fs_info->avail_data_alloc_bits |= extra_flags;
  3644. if (flags & BTRFS_BLOCK_GROUP_METADATA)
  3645. fs_info->avail_metadata_alloc_bits |= extra_flags;
  3646. if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
  3647. fs_info->avail_system_alloc_bits |= extra_flags;
  3648. write_sequnlock(&fs_info->profiles_lock);
  3649. }
  3650. /*
  3651. * returns target flags in extended format or 0 if restripe for this
  3652. * chunk_type is not in progress
  3653. *
  3654. * should be called with either volume_mutex or balance_lock held
  3655. */
  3656. static u64 get_restripe_target(struct btrfs_fs_info *fs_info, u64 flags)
  3657. {
  3658. struct btrfs_balance_control *bctl = fs_info->balance_ctl;
  3659. u64 target = 0;
  3660. if (!bctl)
  3661. return 0;
  3662. if (flags & BTRFS_BLOCK_GROUP_DATA &&
  3663. bctl->data.flags & BTRFS_BALANCE_ARGS_CONVERT) {
  3664. target = BTRFS_BLOCK_GROUP_DATA | bctl->data.target;
  3665. } else if (flags & BTRFS_BLOCK_GROUP_SYSTEM &&
  3666. bctl->sys.flags & BTRFS_BALANCE_ARGS_CONVERT) {
  3667. target = BTRFS_BLOCK_GROUP_SYSTEM | bctl->sys.target;
  3668. } else if (flags & BTRFS_BLOCK_GROUP_METADATA &&
  3669. bctl->meta.flags & BTRFS_BALANCE_ARGS_CONVERT) {
  3670. target = BTRFS_BLOCK_GROUP_METADATA | bctl->meta.target;
  3671. }
  3672. return target;
  3673. }
  3674. /*
  3675. * @flags: available profiles in extended format (see ctree.h)
  3676. *
  3677. * Returns reduced profile in chunk format. If profile changing is in
  3678. * progress (either running or paused) picks the target profile (if it's
  3679. * already available), otherwise falls back to plain reducing.
  3680. */
  3681. static u64 btrfs_reduce_alloc_profile(struct btrfs_fs_info *fs_info, u64 flags)
  3682. {
  3683. u64 num_devices = fs_info->fs_devices->rw_devices;
  3684. u64 target;
  3685. u64 raid_type;
  3686. u64 allowed = 0;
  3687. /*
  3688. * see if restripe for this chunk_type is in progress, if so
  3689. * try to reduce to the target profile
  3690. */
  3691. spin_lock(&fs_info->balance_lock);
  3692. target = get_restripe_target(fs_info, flags);
  3693. if (target) {
  3694. /* pick target profile only if it's already available */
  3695. if ((flags & target) & BTRFS_EXTENDED_PROFILE_MASK) {
  3696. spin_unlock(&fs_info->balance_lock);
  3697. return extended_to_chunk(target);
  3698. }
  3699. }
  3700. spin_unlock(&fs_info->balance_lock);
  3701. /* First, mask out the RAID levels which aren't possible */
  3702. for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
  3703. if (num_devices >= btrfs_raid_array[raid_type].devs_min)
  3704. allowed |= btrfs_raid_group[raid_type];
  3705. }
  3706. allowed &= flags;
  3707. if (allowed & BTRFS_BLOCK_GROUP_RAID6)
  3708. allowed = BTRFS_BLOCK_GROUP_RAID6;
  3709. else if (allowed & BTRFS_BLOCK_GROUP_RAID5)
  3710. allowed = BTRFS_BLOCK_GROUP_RAID5;
  3711. else if (allowed & BTRFS_BLOCK_GROUP_RAID10)
  3712. allowed = BTRFS_BLOCK_GROUP_RAID10;
  3713. else if (allowed & BTRFS_BLOCK_GROUP_RAID1)
  3714. allowed = BTRFS_BLOCK_GROUP_RAID1;
  3715. else if (allowed & BTRFS_BLOCK_GROUP_RAID0)
  3716. allowed = BTRFS_BLOCK_GROUP_RAID0;
  3717. flags &= ~BTRFS_BLOCK_GROUP_PROFILE_MASK;
  3718. return extended_to_chunk(flags | allowed);
  3719. }
  3720. static u64 get_alloc_profile(struct btrfs_fs_info *fs_info, u64 orig_flags)
  3721. {
  3722. unsigned seq;
  3723. u64 flags;
  3724. do {
  3725. flags = orig_flags;
  3726. seq = read_seqbegin(&fs_info->profiles_lock);
  3727. if (flags & BTRFS_BLOCK_GROUP_DATA)
  3728. flags |= fs_info->avail_data_alloc_bits;
  3729. else if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
  3730. flags |= fs_info->avail_system_alloc_bits;
  3731. else if (flags & BTRFS_BLOCK_GROUP_METADATA)
  3732. flags |= fs_info->avail_metadata_alloc_bits;
  3733. } while (read_seqretry(&fs_info->profiles_lock, seq));
  3734. return btrfs_reduce_alloc_profile(fs_info, flags);
  3735. }
  3736. static u64 get_alloc_profile_by_root(struct btrfs_root *root, int data)
  3737. {
  3738. struct btrfs_fs_info *fs_info = root->fs_info;
  3739. u64 flags;
  3740. u64 ret;
  3741. if (data)
  3742. flags = BTRFS_BLOCK_GROUP_DATA;
  3743. else if (root == fs_info->chunk_root)
  3744. flags = BTRFS_BLOCK_GROUP_SYSTEM;
  3745. else
  3746. flags = BTRFS_BLOCK_GROUP_METADATA;
  3747. ret = get_alloc_profile(fs_info, flags);
  3748. return ret;
  3749. }
  3750. u64 btrfs_data_alloc_profile(struct btrfs_fs_info *fs_info)
  3751. {
  3752. return get_alloc_profile(fs_info, BTRFS_BLOCK_GROUP_DATA);
  3753. }
  3754. u64 btrfs_metadata_alloc_profile(struct btrfs_fs_info *fs_info)
  3755. {
  3756. return get_alloc_profile(fs_info, BTRFS_BLOCK_GROUP_METADATA);
  3757. }
  3758. u64 btrfs_system_alloc_profile(struct btrfs_fs_info *fs_info)
  3759. {
  3760. return get_alloc_profile(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
  3761. }
  3762. static u64 btrfs_space_info_used(struct btrfs_space_info *s_info,
  3763. bool may_use_included)
  3764. {
  3765. ASSERT(s_info);
  3766. return s_info->bytes_used + s_info->bytes_reserved +
  3767. s_info->bytes_pinned + s_info->bytes_readonly +
  3768. (may_use_included ? s_info->bytes_may_use : 0);
  3769. }
  3770. int btrfs_alloc_data_chunk_ondemand(struct btrfs_inode *inode, u64 bytes)
  3771. {
  3772. struct btrfs_root *root = inode->root;
  3773. struct btrfs_fs_info *fs_info = root->fs_info;
  3774. struct btrfs_space_info *data_sinfo = fs_info->data_sinfo;
  3775. u64 used;
  3776. int ret = 0;
  3777. int need_commit = 2;
  3778. int have_pinned_space;
  3779. /* make sure bytes are sectorsize aligned */
  3780. bytes = ALIGN(bytes, fs_info->sectorsize);
  3781. if (btrfs_is_free_space_inode(inode)) {
  3782. need_commit = 0;
  3783. ASSERT(current->journal_info);
  3784. }
  3785. again:
  3786. /* make sure we have enough space to handle the data first */
  3787. spin_lock(&data_sinfo->lock);
  3788. used = btrfs_space_info_used(data_sinfo, true);
  3789. if (used + bytes > data_sinfo->total_bytes) {
  3790. struct btrfs_trans_handle *trans;
  3791. /*
  3792. * if we don't have enough free bytes in this space then we need
  3793. * to alloc a new chunk.
  3794. */
  3795. if (!data_sinfo->full) {
  3796. u64 alloc_target;
  3797. data_sinfo->force_alloc = CHUNK_ALLOC_FORCE;
  3798. spin_unlock(&data_sinfo->lock);
  3799. alloc_target = btrfs_data_alloc_profile(fs_info);
  3800. /*
  3801. * It is ugly that we don't call nolock join
  3802. * transaction for the free space inode case here.
  3803. * But it is safe because we only do the data space
  3804. * reservation for the free space cache in the
  3805. * transaction context, the common join transaction
  3806. * just increase the counter of the current transaction
  3807. * handler, doesn't try to acquire the trans_lock of
  3808. * the fs.
  3809. */
  3810. trans = btrfs_join_transaction(root);
  3811. if (IS_ERR(trans))
  3812. return PTR_ERR(trans);
  3813. ret = do_chunk_alloc(trans, fs_info, alloc_target,
  3814. CHUNK_ALLOC_NO_FORCE);
  3815. btrfs_end_transaction(trans);
  3816. if (ret < 0) {
  3817. if (ret != -ENOSPC)
  3818. return ret;
  3819. else {
  3820. have_pinned_space = 1;
  3821. goto commit_trans;
  3822. }
  3823. }
  3824. goto again;
  3825. }
  3826. /*
  3827. * If we don't have enough pinned space to deal with this
  3828. * allocation, and no removed chunk in current transaction,
  3829. * don't bother committing the transaction.
  3830. */
  3831. have_pinned_space = percpu_counter_compare(
  3832. &data_sinfo->total_bytes_pinned,
  3833. used + bytes - data_sinfo->total_bytes);
  3834. spin_unlock(&data_sinfo->lock);
  3835. /* commit the current transaction and try again */
  3836. commit_trans:
  3837. if (need_commit &&
  3838. !atomic_read(&fs_info->open_ioctl_trans)) {
  3839. need_commit--;
  3840. if (need_commit > 0) {
  3841. btrfs_start_delalloc_roots(fs_info, 0, -1);
  3842. btrfs_wait_ordered_roots(fs_info, U64_MAX, 0,
  3843. (u64)-1);
  3844. }
  3845. trans = btrfs_join_transaction(root);
  3846. if (IS_ERR(trans))
  3847. return PTR_ERR(trans);
  3848. if (have_pinned_space >= 0 ||
  3849. test_bit(BTRFS_TRANS_HAVE_FREE_BGS,
  3850. &trans->transaction->flags) ||
  3851. need_commit > 0) {
  3852. ret = btrfs_commit_transaction(trans);
  3853. if (ret)
  3854. return ret;
  3855. /*
  3856. * The cleaner kthread might still be doing iput
  3857. * operations. Wait for it to finish so that
  3858. * more space is released.
  3859. */
  3860. mutex_lock(&fs_info->cleaner_delayed_iput_mutex);
  3861. mutex_unlock(&fs_info->cleaner_delayed_iput_mutex);
  3862. goto again;
  3863. } else {
  3864. btrfs_end_transaction(trans);
  3865. }
  3866. }
  3867. trace_btrfs_space_reservation(fs_info,
  3868. "space_info:enospc",
  3869. data_sinfo->flags, bytes, 1);
  3870. return -ENOSPC;
  3871. }
  3872. data_sinfo->bytes_may_use += bytes;
  3873. trace_btrfs_space_reservation(fs_info, "space_info",
  3874. data_sinfo->flags, bytes, 1);
  3875. spin_unlock(&data_sinfo->lock);
  3876. return ret;
  3877. }
  3878. int btrfs_check_data_free_space(struct inode *inode,
  3879. struct extent_changeset **reserved, u64 start, u64 len)
  3880. {
  3881. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  3882. int ret;
  3883. /* align the range */
  3884. len = round_up(start + len, fs_info->sectorsize) -
  3885. round_down(start, fs_info->sectorsize);
  3886. start = round_down(start, fs_info->sectorsize);
  3887. ret = btrfs_alloc_data_chunk_ondemand(BTRFS_I(inode), len);
  3888. if (ret < 0)
  3889. return ret;
  3890. /* Use new btrfs_qgroup_reserve_data to reserve precious data space. */
  3891. ret = btrfs_qgroup_reserve_data(inode, reserved, start, len);
  3892. if (ret < 0)
  3893. btrfs_free_reserved_data_space_noquota(inode, start, len);
  3894. else
  3895. ret = 0;
  3896. return ret;
  3897. }
  3898. /*
  3899. * Called if we need to clear a data reservation for this inode
  3900. * Normally in a error case.
  3901. *
  3902. * This one will *NOT* use accurate qgroup reserved space API, just for case
  3903. * which we can't sleep and is sure it won't affect qgroup reserved space.
  3904. * Like clear_bit_hook().
  3905. */
  3906. void btrfs_free_reserved_data_space_noquota(struct inode *inode, u64 start,
  3907. u64 len)
  3908. {
  3909. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  3910. struct btrfs_space_info *data_sinfo;
  3911. /* Make sure the range is aligned to sectorsize */
  3912. len = round_up(start + len, fs_info->sectorsize) -
  3913. round_down(start, fs_info->sectorsize);
  3914. start = round_down(start, fs_info->sectorsize);
  3915. data_sinfo = fs_info->data_sinfo;
  3916. spin_lock(&data_sinfo->lock);
  3917. if (WARN_ON(data_sinfo->bytes_may_use < len))
  3918. data_sinfo->bytes_may_use = 0;
  3919. else
  3920. data_sinfo->bytes_may_use -= len;
  3921. trace_btrfs_space_reservation(fs_info, "space_info",
  3922. data_sinfo->flags, len, 0);
  3923. spin_unlock(&data_sinfo->lock);
  3924. }
  3925. /*
  3926. * Called if we need to clear a data reservation for this inode
  3927. * Normally in a error case.
  3928. *
  3929. * This one will handle the per-inode data rsv map for accurate reserved
  3930. * space framework.
  3931. */
  3932. void btrfs_free_reserved_data_space(struct inode *inode,
  3933. struct extent_changeset *reserved, u64 start, u64 len)
  3934. {
  3935. struct btrfs_root *root = BTRFS_I(inode)->root;
  3936. /* Make sure the range is aligned to sectorsize */
  3937. len = round_up(start + len, root->fs_info->sectorsize) -
  3938. round_down(start, root->fs_info->sectorsize);
  3939. start = round_down(start, root->fs_info->sectorsize);
  3940. btrfs_free_reserved_data_space_noquota(inode, start, len);
  3941. btrfs_qgroup_free_data(inode, reserved, start, len);
  3942. }
  3943. static void force_metadata_allocation(struct btrfs_fs_info *info)
  3944. {
  3945. struct list_head *head = &info->space_info;
  3946. struct btrfs_space_info *found;
  3947. rcu_read_lock();
  3948. list_for_each_entry_rcu(found, head, list) {
  3949. if (found->flags & BTRFS_BLOCK_GROUP_METADATA)
  3950. found->force_alloc = CHUNK_ALLOC_FORCE;
  3951. }
  3952. rcu_read_unlock();
  3953. }
  3954. static inline u64 calc_global_rsv_need_space(struct btrfs_block_rsv *global)
  3955. {
  3956. return (global->size << 1);
  3957. }
  3958. static int should_alloc_chunk(struct btrfs_fs_info *fs_info,
  3959. struct btrfs_space_info *sinfo, int force)
  3960. {
  3961. struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
  3962. u64 bytes_used = btrfs_space_info_used(sinfo, false);
  3963. u64 thresh;
  3964. if (force == CHUNK_ALLOC_FORCE)
  3965. return 1;
  3966. /*
  3967. * We need to take into account the global rsv because for all intents
  3968. * and purposes it's used space. Don't worry about locking the
  3969. * global_rsv, it doesn't change except when the transaction commits.
  3970. */
  3971. if (sinfo->flags & BTRFS_BLOCK_GROUP_METADATA)
  3972. bytes_used += calc_global_rsv_need_space(global_rsv);
  3973. /*
  3974. * in limited mode, we want to have some free space up to
  3975. * about 1% of the FS size.
  3976. */
  3977. if (force == CHUNK_ALLOC_LIMITED) {
  3978. thresh = btrfs_super_total_bytes(fs_info->super_copy);
  3979. thresh = max_t(u64, SZ_64M, div_factor_fine(thresh, 1));
  3980. if (sinfo->total_bytes - bytes_used < thresh)
  3981. return 1;
  3982. }
  3983. if (bytes_used + SZ_2M < div_factor(sinfo->total_bytes, 8))
  3984. return 0;
  3985. return 1;
  3986. }
  3987. static u64 get_profile_num_devs(struct btrfs_fs_info *fs_info, u64 type)
  3988. {
  3989. u64 num_dev;
  3990. if (type & (BTRFS_BLOCK_GROUP_RAID10 |
  3991. BTRFS_BLOCK_GROUP_RAID0 |
  3992. BTRFS_BLOCK_GROUP_RAID5 |
  3993. BTRFS_BLOCK_GROUP_RAID6))
  3994. num_dev = fs_info->fs_devices->rw_devices;
  3995. else if (type & BTRFS_BLOCK_GROUP_RAID1)
  3996. num_dev = 2;
  3997. else
  3998. num_dev = 1; /* DUP or single */
  3999. return num_dev;
  4000. }
  4001. /*
  4002. * If @is_allocation is true, reserve space in the system space info necessary
  4003. * for allocating a chunk, otherwise if it's false, reserve space necessary for
  4004. * removing a chunk.
  4005. */
  4006. void check_system_chunk(struct btrfs_trans_handle *trans,
  4007. struct btrfs_fs_info *fs_info, u64 type)
  4008. {
  4009. struct btrfs_space_info *info;
  4010. u64 left;
  4011. u64 thresh;
  4012. int ret = 0;
  4013. u64 num_devs;
  4014. /*
  4015. * Needed because we can end up allocating a system chunk and for an
  4016. * atomic and race free space reservation in the chunk block reserve.
  4017. */
  4018. ASSERT(mutex_is_locked(&fs_info->chunk_mutex));
  4019. info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
  4020. spin_lock(&info->lock);
  4021. left = info->total_bytes - btrfs_space_info_used(info, true);
  4022. spin_unlock(&info->lock);
  4023. num_devs = get_profile_num_devs(fs_info, type);
  4024. /* num_devs device items to update and 1 chunk item to add or remove */
  4025. thresh = btrfs_calc_trunc_metadata_size(fs_info, num_devs) +
  4026. btrfs_calc_trans_metadata_size(fs_info, 1);
  4027. if (left < thresh && btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
  4028. btrfs_info(fs_info, "left=%llu, need=%llu, flags=%llu",
  4029. left, thresh, type);
  4030. dump_space_info(fs_info, info, 0, 0);
  4031. }
  4032. if (left < thresh) {
  4033. u64 flags = btrfs_system_alloc_profile(fs_info);
  4034. /*
  4035. * Ignore failure to create system chunk. We might end up not
  4036. * needing it, as we might not need to COW all nodes/leafs from
  4037. * the paths we visit in the chunk tree (they were already COWed
  4038. * or created in the current transaction for example).
  4039. */
  4040. ret = btrfs_alloc_chunk(trans, fs_info, flags);
  4041. }
  4042. if (!ret) {
  4043. ret = btrfs_block_rsv_add(fs_info->chunk_root,
  4044. &fs_info->chunk_block_rsv,
  4045. thresh, BTRFS_RESERVE_NO_FLUSH);
  4046. if (!ret)
  4047. trans->chunk_bytes_reserved += thresh;
  4048. }
  4049. }
  4050. /*
  4051. * If force is CHUNK_ALLOC_FORCE:
  4052. * - return 1 if it successfully allocates a chunk,
  4053. * - return errors including -ENOSPC otherwise.
  4054. * If force is NOT CHUNK_ALLOC_FORCE:
  4055. * - return 0 if it doesn't need to allocate a new chunk,
  4056. * - return 1 if it successfully allocates a chunk,
  4057. * - return errors including -ENOSPC otherwise.
  4058. */
  4059. static int do_chunk_alloc(struct btrfs_trans_handle *trans,
  4060. struct btrfs_fs_info *fs_info, u64 flags, int force)
  4061. {
  4062. struct btrfs_space_info *space_info;
  4063. int wait_for_alloc = 0;
  4064. int ret = 0;
  4065. /* Don't re-enter if we're already allocating a chunk */
  4066. if (trans->allocating_chunk)
  4067. return -ENOSPC;
  4068. space_info = __find_space_info(fs_info, flags);
  4069. if (!space_info) {
  4070. ret = create_space_info(fs_info, flags, &space_info);
  4071. if (ret)
  4072. return ret;
  4073. }
  4074. again:
  4075. spin_lock(&space_info->lock);
  4076. if (force < space_info->force_alloc)
  4077. force = space_info->force_alloc;
  4078. if (space_info->full) {
  4079. if (should_alloc_chunk(fs_info, space_info, force))
  4080. ret = -ENOSPC;
  4081. else
  4082. ret = 0;
  4083. spin_unlock(&space_info->lock);
  4084. return ret;
  4085. }
  4086. if (!should_alloc_chunk(fs_info, space_info, force)) {
  4087. spin_unlock(&space_info->lock);
  4088. return 0;
  4089. } else if (space_info->chunk_alloc) {
  4090. wait_for_alloc = 1;
  4091. } else {
  4092. space_info->chunk_alloc = 1;
  4093. }
  4094. spin_unlock(&space_info->lock);
  4095. mutex_lock(&fs_info->chunk_mutex);
  4096. /*
  4097. * The chunk_mutex is held throughout the entirety of a chunk
  4098. * allocation, so once we've acquired the chunk_mutex we know that the
  4099. * other guy is done and we need to recheck and see if we should
  4100. * allocate.
  4101. */
  4102. if (wait_for_alloc) {
  4103. mutex_unlock(&fs_info->chunk_mutex);
  4104. wait_for_alloc = 0;
  4105. goto again;
  4106. }
  4107. trans->allocating_chunk = true;
  4108. /*
  4109. * If we have mixed data/metadata chunks we want to make sure we keep
  4110. * allocating mixed chunks instead of individual chunks.
  4111. */
  4112. if (btrfs_mixed_space_info(space_info))
  4113. flags |= (BTRFS_BLOCK_GROUP_DATA | BTRFS_BLOCK_GROUP_METADATA);
  4114. /*
  4115. * if we're doing a data chunk, go ahead and make sure that
  4116. * we keep a reasonable number of metadata chunks allocated in the
  4117. * FS as well.
  4118. */
  4119. if (flags & BTRFS_BLOCK_GROUP_DATA && fs_info->metadata_ratio) {
  4120. fs_info->data_chunk_allocations++;
  4121. if (!(fs_info->data_chunk_allocations %
  4122. fs_info->metadata_ratio))
  4123. force_metadata_allocation(fs_info);
  4124. }
  4125. /*
  4126. * Check if we have enough space in SYSTEM chunk because we may need
  4127. * to update devices.
  4128. */
  4129. check_system_chunk(trans, fs_info, flags);
  4130. ret = btrfs_alloc_chunk(trans, fs_info, flags);
  4131. trans->allocating_chunk = false;
  4132. spin_lock(&space_info->lock);
  4133. if (ret < 0 && ret != -ENOSPC)
  4134. goto out;
  4135. if (ret)
  4136. space_info->full = 1;
  4137. else
  4138. ret = 1;
  4139. space_info->force_alloc = CHUNK_ALLOC_NO_FORCE;
  4140. out:
  4141. space_info->chunk_alloc = 0;
  4142. spin_unlock(&space_info->lock);
  4143. mutex_unlock(&fs_info->chunk_mutex);
  4144. /*
  4145. * When we allocate a new chunk we reserve space in the chunk block
  4146. * reserve to make sure we can COW nodes/leafs in the chunk tree or
  4147. * add new nodes/leafs to it if we end up needing to do it when
  4148. * inserting the chunk item and updating device items as part of the
  4149. * second phase of chunk allocation, performed by
  4150. * btrfs_finish_chunk_alloc(). So make sure we don't accumulate a
  4151. * large number of new block groups to create in our transaction
  4152. * handle's new_bgs list to avoid exhausting the chunk block reserve
  4153. * in extreme cases - like having a single transaction create many new
  4154. * block groups when starting to write out the free space caches of all
  4155. * the block groups that were made dirty during the lifetime of the
  4156. * transaction.
  4157. */
  4158. if (trans->can_flush_pending_bgs &&
  4159. trans->chunk_bytes_reserved >= (u64)SZ_2M) {
  4160. btrfs_create_pending_block_groups(trans, fs_info);
  4161. btrfs_trans_release_chunk_metadata(trans);
  4162. }
  4163. return ret;
  4164. }
  4165. static int can_overcommit(struct btrfs_fs_info *fs_info,
  4166. struct btrfs_space_info *space_info, u64 bytes,
  4167. enum btrfs_reserve_flush_enum flush,
  4168. bool system_chunk)
  4169. {
  4170. struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
  4171. u64 profile;
  4172. u64 space_size;
  4173. u64 avail;
  4174. u64 used;
  4175. /* Don't overcommit when in mixed mode. */
  4176. if (space_info->flags & BTRFS_BLOCK_GROUP_DATA)
  4177. return 0;
  4178. if (system_chunk)
  4179. profile = btrfs_system_alloc_profile(fs_info);
  4180. else
  4181. profile = btrfs_metadata_alloc_profile(fs_info);
  4182. used = btrfs_space_info_used(space_info, false);
  4183. /*
  4184. * We only want to allow over committing if we have lots of actual space
  4185. * free, but if we don't have enough space to handle the global reserve
  4186. * space then we could end up having a real enospc problem when trying
  4187. * to allocate a chunk or some other such important allocation.
  4188. */
  4189. spin_lock(&global_rsv->lock);
  4190. space_size = calc_global_rsv_need_space(global_rsv);
  4191. spin_unlock(&global_rsv->lock);
  4192. if (used + space_size >= space_info->total_bytes)
  4193. return 0;
  4194. used += space_info->bytes_may_use;
  4195. avail = atomic64_read(&fs_info->free_chunk_space);
  4196. /*
  4197. * If we have dup, raid1 or raid10 then only half of the free
  4198. * space is actually useable. For raid56, the space info used
  4199. * doesn't include the parity drive, so we don't have to
  4200. * change the math
  4201. */
  4202. if (profile & (BTRFS_BLOCK_GROUP_DUP |
  4203. BTRFS_BLOCK_GROUP_RAID1 |
  4204. BTRFS_BLOCK_GROUP_RAID10))
  4205. avail >>= 1;
  4206. /*
  4207. * If we aren't flushing all things, let us overcommit up to
  4208. * 1/2th of the space. If we can flush, don't let us overcommit
  4209. * too much, let it overcommit up to 1/8 of the space.
  4210. */
  4211. if (flush == BTRFS_RESERVE_FLUSH_ALL)
  4212. avail >>= 3;
  4213. else
  4214. avail >>= 1;
  4215. if (used + bytes < space_info->total_bytes + avail)
  4216. return 1;
  4217. return 0;
  4218. }
  4219. static void btrfs_writeback_inodes_sb_nr(struct btrfs_fs_info *fs_info,
  4220. unsigned long nr_pages, int nr_items)
  4221. {
  4222. struct super_block *sb = fs_info->sb;
  4223. if (down_read_trylock(&sb->s_umount)) {
  4224. writeback_inodes_sb_nr(sb, nr_pages, WB_REASON_FS_FREE_SPACE);
  4225. up_read(&sb->s_umount);
  4226. } else {
  4227. /*
  4228. * We needn't worry the filesystem going from r/w to r/o though
  4229. * we don't acquire ->s_umount mutex, because the filesystem
  4230. * should guarantee the delalloc inodes list be empty after
  4231. * the filesystem is readonly(all dirty pages are written to
  4232. * the disk).
  4233. */
  4234. btrfs_start_delalloc_roots(fs_info, 0, nr_items);
  4235. if (!current->journal_info)
  4236. btrfs_wait_ordered_roots(fs_info, nr_items, 0, (u64)-1);
  4237. }
  4238. }
  4239. static inline u64 calc_reclaim_items_nr(struct btrfs_fs_info *fs_info,
  4240. u64 to_reclaim)
  4241. {
  4242. u64 bytes;
  4243. u64 nr;
  4244. bytes = btrfs_calc_trans_metadata_size(fs_info, 1);
  4245. nr = div64_u64(to_reclaim, bytes);
  4246. if (!nr)
  4247. nr = 1;
  4248. return nr;
  4249. }
  4250. #define EXTENT_SIZE_PER_ITEM SZ_256K
  4251. /*
  4252. * shrink metadata reservation for delalloc
  4253. */
  4254. static void shrink_delalloc(struct btrfs_fs_info *fs_info, u64 to_reclaim,
  4255. u64 orig, bool wait_ordered)
  4256. {
  4257. struct btrfs_space_info *space_info;
  4258. struct btrfs_trans_handle *trans;
  4259. u64 delalloc_bytes;
  4260. u64 max_reclaim;
  4261. u64 items;
  4262. long time_left;
  4263. unsigned long nr_pages;
  4264. int loops;
  4265. enum btrfs_reserve_flush_enum flush;
  4266. /* Calc the number of the pages we need flush for space reservation */
  4267. items = calc_reclaim_items_nr(fs_info, to_reclaim);
  4268. to_reclaim = items * EXTENT_SIZE_PER_ITEM;
  4269. trans = (struct btrfs_trans_handle *)current->journal_info;
  4270. space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
  4271. delalloc_bytes = percpu_counter_sum_positive(
  4272. &fs_info->delalloc_bytes);
  4273. if (delalloc_bytes == 0) {
  4274. if (trans)
  4275. return;
  4276. if (wait_ordered)
  4277. btrfs_wait_ordered_roots(fs_info, items, 0, (u64)-1);
  4278. return;
  4279. }
  4280. loops = 0;
  4281. while (delalloc_bytes && loops < 3) {
  4282. max_reclaim = min(delalloc_bytes, to_reclaim);
  4283. nr_pages = max_reclaim >> PAGE_SHIFT;
  4284. btrfs_writeback_inodes_sb_nr(fs_info, nr_pages, items);
  4285. /*
  4286. * We need to wait for the async pages to actually start before
  4287. * we do anything.
  4288. */
  4289. max_reclaim = atomic_read(&fs_info->async_delalloc_pages);
  4290. if (!max_reclaim)
  4291. goto skip_async;
  4292. if (max_reclaim <= nr_pages)
  4293. max_reclaim = 0;
  4294. else
  4295. max_reclaim -= nr_pages;
  4296. wait_event(fs_info->async_submit_wait,
  4297. atomic_read(&fs_info->async_delalloc_pages) <=
  4298. (int)max_reclaim);
  4299. skip_async:
  4300. if (!trans)
  4301. flush = BTRFS_RESERVE_FLUSH_ALL;
  4302. else
  4303. flush = BTRFS_RESERVE_NO_FLUSH;
  4304. spin_lock(&space_info->lock);
  4305. if (list_empty(&space_info->tickets) &&
  4306. list_empty(&space_info->priority_tickets)) {
  4307. spin_unlock(&space_info->lock);
  4308. break;
  4309. }
  4310. spin_unlock(&space_info->lock);
  4311. loops++;
  4312. if (wait_ordered && !trans) {
  4313. btrfs_wait_ordered_roots(fs_info, items, 0, (u64)-1);
  4314. } else {
  4315. time_left = schedule_timeout_killable(1);
  4316. if (time_left)
  4317. break;
  4318. }
  4319. delalloc_bytes = percpu_counter_sum_positive(
  4320. &fs_info->delalloc_bytes);
  4321. }
  4322. }
  4323. struct reserve_ticket {
  4324. u64 bytes;
  4325. int error;
  4326. struct list_head list;
  4327. wait_queue_head_t wait;
  4328. };
  4329. /**
  4330. * maybe_commit_transaction - possibly commit the transaction if its ok to
  4331. * @root - the root we're allocating for
  4332. * @bytes - the number of bytes we want to reserve
  4333. * @force - force the commit
  4334. *
  4335. * This will check to make sure that committing the transaction will actually
  4336. * get us somewhere and then commit the transaction if it does. Otherwise it
  4337. * will return -ENOSPC.
  4338. */
  4339. static int may_commit_transaction(struct btrfs_fs_info *fs_info,
  4340. struct btrfs_space_info *space_info)
  4341. {
  4342. struct reserve_ticket *ticket = NULL;
  4343. struct btrfs_block_rsv *delayed_rsv = &fs_info->delayed_block_rsv;
  4344. struct btrfs_trans_handle *trans;
  4345. u64 bytes;
  4346. trans = (struct btrfs_trans_handle *)current->journal_info;
  4347. if (trans)
  4348. return -EAGAIN;
  4349. spin_lock(&space_info->lock);
  4350. if (!list_empty(&space_info->priority_tickets))
  4351. ticket = list_first_entry(&space_info->priority_tickets,
  4352. struct reserve_ticket, list);
  4353. else if (!list_empty(&space_info->tickets))
  4354. ticket = list_first_entry(&space_info->tickets,
  4355. struct reserve_ticket, list);
  4356. bytes = (ticket) ? ticket->bytes : 0;
  4357. spin_unlock(&space_info->lock);
  4358. if (!bytes)
  4359. return 0;
  4360. /* See if there is enough pinned space to make this reservation */
  4361. if (percpu_counter_compare(&space_info->total_bytes_pinned,
  4362. bytes) >= 0)
  4363. goto commit;
  4364. /*
  4365. * See if there is some space in the delayed insertion reservation for
  4366. * this reservation.
  4367. */
  4368. if (space_info != delayed_rsv->space_info)
  4369. return -ENOSPC;
  4370. spin_lock(&delayed_rsv->lock);
  4371. if (delayed_rsv->size > bytes)
  4372. bytes = 0;
  4373. else
  4374. bytes -= delayed_rsv->size;
  4375. spin_unlock(&delayed_rsv->lock);
  4376. if (percpu_counter_compare(&space_info->total_bytes_pinned,
  4377. bytes) < 0) {
  4378. return -ENOSPC;
  4379. }
  4380. commit:
  4381. trans = btrfs_join_transaction(fs_info->extent_root);
  4382. if (IS_ERR(trans))
  4383. return -ENOSPC;
  4384. return btrfs_commit_transaction(trans);
  4385. }
  4386. /*
  4387. * Try to flush some data based on policy set by @state. This is only advisory
  4388. * and may fail for various reasons. The caller is supposed to examine the
  4389. * state of @space_info to detect the outcome.
  4390. */
  4391. static void flush_space(struct btrfs_fs_info *fs_info,
  4392. struct btrfs_space_info *space_info, u64 num_bytes,
  4393. int state)
  4394. {
  4395. struct btrfs_root *root = fs_info->extent_root;
  4396. struct btrfs_trans_handle *trans;
  4397. int nr;
  4398. int ret = 0;
  4399. switch (state) {
  4400. case FLUSH_DELAYED_ITEMS_NR:
  4401. case FLUSH_DELAYED_ITEMS:
  4402. if (state == FLUSH_DELAYED_ITEMS_NR)
  4403. nr = calc_reclaim_items_nr(fs_info, num_bytes) * 2;
  4404. else
  4405. nr = -1;
  4406. trans = btrfs_join_transaction(root);
  4407. if (IS_ERR(trans)) {
  4408. ret = PTR_ERR(trans);
  4409. break;
  4410. }
  4411. ret = btrfs_run_delayed_items_nr(trans, fs_info, nr);
  4412. btrfs_end_transaction(trans);
  4413. break;
  4414. case FLUSH_DELALLOC:
  4415. case FLUSH_DELALLOC_WAIT:
  4416. shrink_delalloc(fs_info, num_bytes * 2, num_bytes,
  4417. state == FLUSH_DELALLOC_WAIT);
  4418. break;
  4419. case ALLOC_CHUNK:
  4420. trans = btrfs_join_transaction(root);
  4421. if (IS_ERR(trans)) {
  4422. ret = PTR_ERR(trans);
  4423. break;
  4424. }
  4425. ret = do_chunk_alloc(trans, fs_info,
  4426. btrfs_metadata_alloc_profile(fs_info),
  4427. CHUNK_ALLOC_NO_FORCE);
  4428. btrfs_end_transaction(trans);
  4429. if (ret > 0 || ret == -ENOSPC)
  4430. ret = 0;
  4431. break;
  4432. case COMMIT_TRANS:
  4433. ret = may_commit_transaction(fs_info, space_info);
  4434. break;
  4435. default:
  4436. ret = -ENOSPC;
  4437. break;
  4438. }
  4439. trace_btrfs_flush_space(fs_info, space_info->flags, num_bytes, state,
  4440. ret);
  4441. return;
  4442. }
  4443. static inline u64
  4444. btrfs_calc_reclaim_metadata_size(struct btrfs_fs_info *fs_info,
  4445. struct btrfs_space_info *space_info,
  4446. bool system_chunk)
  4447. {
  4448. struct reserve_ticket *ticket;
  4449. u64 used;
  4450. u64 expected;
  4451. u64 to_reclaim = 0;
  4452. list_for_each_entry(ticket, &space_info->tickets, list)
  4453. to_reclaim += ticket->bytes;
  4454. list_for_each_entry(ticket, &space_info->priority_tickets, list)
  4455. to_reclaim += ticket->bytes;
  4456. if (to_reclaim)
  4457. return to_reclaim;
  4458. to_reclaim = min_t(u64, num_online_cpus() * SZ_1M, SZ_16M);
  4459. if (can_overcommit(fs_info, space_info, to_reclaim,
  4460. BTRFS_RESERVE_FLUSH_ALL, system_chunk))
  4461. return 0;
  4462. used = btrfs_space_info_used(space_info, true);
  4463. if (can_overcommit(fs_info, space_info, SZ_1M,
  4464. BTRFS_RESERVE_FLUSH_ALL, system_chunk))
  4465. expected = div_factor_fine(space_info->total_bytes, 95);
  4466. else
  4467. expected = div_factor_fine(space_info->total_bytes, 90);
  4468. if (used > expected)
  4469. to_reclaim = used - expected;
  4470. else
  4471. to_reclaim = 0;
  4472. to_reclaim = min(to_reclaim, space_info->bytes_may_use +
  4473. space_info->bytes_reserved);
  4474. return to_reclaim;
  4475. }
  4476. static inline int need_do_async_reclaim(struct btrfs_fs_info *fs_info,
  4477. struct btrfs_space_info *space_info,
  4478. u64 used, bool system_chunk)
  4479. {
  4480. u64 thresh = div_factor_fine(space_info->total_bytes, 98);
  4481. /* If we're just plain full then async reclaim just slows us down. */
  4482. if ((space_info->bytes_used + space_info->bytes_reserved) >= thresh)
  4483. return 0;
  4484. if (!btrfs_calc_reclaim_metadata_size(fs_info, space_info,
  4485. system_chunk))
  4486. return 0;
  4487. return (used >= thresh && !btrfs_fs_closing(fs_info) &&
  4488. !test_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state));
  4489. }
  4490. static void wake_all_tickets(struct list_head *head)
  4491. {
  4492. struct reserve_ticket *ticket;
  4493. while (!list_empty(head)) {
  4494. ticket = list_first_entry(head, struct reserve_ticket, list);
  4495. list_del_init(&ticket->list);
  4496. ticket->error = -ENOSPC;
  4497. wake_up(&ticket->wait);
  4498. }
  4499. }
  4500. /*
  4501. * This is for normal flushers, we can wait all goddamned day if we want to. We
  4502. * will loop and continuously try to flush as long as we are making progress.
  4503. * We count progress as clearing off tickets each time we have to loop.
  4504. */
  4505. static void btrfs_async_reclaim_metadata_space(struct work_struct *work)
  4506. {
  4507. struct btrfs_fs_info *fs_info;
  4508. struct btrfs_space_info *space_info;
  4509. u64 to_reclaim;
  4510. int flush_state;
  4511. int commit_cycles = 0;
  4512. u64 last_tickets_id;
  4513. fs_info = container_of(work, struct btrfs_fs_info, async_reclaim_work);
  4514. space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
  4515. spin_lock(&space_info->lock);
  4516. to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info, space_info,
  4517. false);
  4518. if (!to_reclaim) {
  4519. space_info->flush = 0;
  4520. spin_unlock(&space_info->lock);
  4521. return;
  4522. }
  4523. last_tickets_id = space_info->tickets_id;
  4524. spin_unlock(&space_info->lock);
  4525. flush_state = FLUSH_DELAYED_ITEMS_NR;
  4526. do {
  4527. flush_space(fs_info, space_info, to_reclaim, flush_state);
  4528. spin_lock(&space_info->lock);
  4529. if (list_empty(&space_info->tickets)) {
  4530. space_info->flush = 0;
  4531. spin_unlock(&space_info->lock);
  4532. return;
  4533. }
  4534. to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info,
  4535. space_info,
  4536. false);
  4537. if (last_tickets_id == space_info->tickets_id) {
  4538. flush_state++;
  4539. } else {
  4540. last_tickets_id = space_info->tickets_id;
  4541. flush_state = FLUSH_DELAYED_ITEMS_NR;
  4542. if (commit_cycles)
  4543. commit_cycles--;
  4544. }
  4545. if (flush_state > COMMIT_TRANS) {
  4546. commit_cycles++;
  4547. if (commit_cycles > 2) {
  4548. wake_all_tickets(&space_info->tickets);
  4549. space_info->flush = 0;
  4550. } else {
  4551. flush_state = FLUSH_DELAYED_ITEMS_NR;
  4552. }
  4553. }
  4554. spin_unlock(&space_info->lock);
  4555. } while (flush_state <= COMMIT_TRANS);
  4556. }
  4557. void btrfs_init_async_reclaim_work(struct work_struct *work)
  4558. {
  4559. INIT_WORK(work, btrfs_async_reclaim_metadata_space);
  4560. }
  4561. static void priority_reclaim_metadata_space(struct btrfs_fs_info *fs_info,
  4562. struct btrfs_space_info *space_info,
  4563. struct reserve_ticket *ticket)
  4564. {
  4565. u64 to_reclaim;
  4566. int flush_state = FLUSH_DELAYED_ITEMS_NR;
  4567. spin_lock(&space_info->lock);
  4568. to_reclaim = btrfs_calc_reclaim_metadata_size(fs_info, space_info,
  4569. false);
  4570. if (!to_reclaim) {
  4571. spin_unlock(&space_info->lock);
  4572. return;
  4573. }
  4574. spin_unlock(&space_info->lock);
  4575. do {
  4576. flush_space(fs_info, space_info, to_reclaim, flush_state);
  4577. flush_state++;
  4578. spin_lock(&space_info->lock);
  4579. if (ticket->bytes == 0) {
  4580. spin_unlock(&space_info->lock);
  4581. return;
  4582. }
  4583. spin_unlock(&space_info->lock);
  4584. /*
  4585. * Priority flushers can't wait on delalloc without
  4586. * deadlocking.
  4587. */
  4588. if (flush_state == FLUSH_DELALLOC ||
  4589. flush_state == FLUSH_DELALLOC_WAIT)
  4590. flush_state = ALLOC_CHUNK;
  4591. } while (flush_state < COMMIT_TRANS);
  4592. }
  4593. static int wait_reserve_ticket(struct btrfs_fs_info *fs_info,
  4594. struct btrfs_space_info *space_info,
  4595. struct reserve_ticket *ticket, u64 orig_bytes)
  4596. {
  4597. DEFINE_WAIT(wait);
  4598. int ret = 0;
  4599. spin_lock(&space_info->lock);
  4600. while (ticket->bytes > 0 && ticket->error == 0) {
  4601. ret = prepare_to_wait_event(&ticket->wait, &wait, TASK_KILLABLE);
  4602. if (ret) {
  4603. ret = -EINTR;
  4604. break;
  4605. }
  4606. spin_unlock(&space_info->lock);
  4607. schedule();
  4608. finish_wait(&ticket->wait, &wait);
  4609. spin_lock(&space_info->lock);
  4610. }
  4611. if (!ret)
  4612. ret = ticket->error;
  4613. if (!list_empty(&ticket->list))
  4614. list_del_init(&ticket->list);
  4615. if (ticket->bytes && ticket->bytes < orig_bytes) {
  4616. u64 num_bytes = orig_bytes - ticket->bytes;
  4617. space_info->bytes_may_use -= num_bytes;
  4618. trace_btrfs_space_reservation(fs_info, "space_info",
  4619. space_info->flags, num_bytes, 0);
  4620. }
  4621. spin_unlock(&space_info->lock);
  4622. return ret;
  4623. }
  4624. /**
  4625. * reserve_metadata_bytes - try to reserve bytes from the block_rsv's space
  4626. * @root - the root we're allocating for
  4627. * @space_info - the space info we want to allocate from
  4628. * @orig_bytes - the number of bytes we want
  4629. * @flush - whether or not we can flush to make our reservation
  4630. *
  4631. * This will reserve orig_bytes number of bytes from the space info associated
  4632. * with the block_rsv. If there is not enough space it will make an attempt to
  4633. * flush out space to make room. It will do this by flushing delalloc if
  4634. * possible or committing the transaction. If flush is 0 then no attempts to
  4635. * regain reservations will be made and this will fail if there is not enough
  4636. * space already.
  4637. */
  4638. static int __reserve_metadata_bytes(struct btrfs_fs_info *fs_info,
  4639. struct btrfs_space_info *space_info,
  4640. u64 orig_bytes,
  4641. enum btrfs_reserve_flush_enum flush,
  4642. bool system_chunk)
  4643. {
  4644. struct reserve_ticket ticket;
  4645. u64 used;
  4646. int ret = 0;
  4647. ASSERT(orig_bytes);
  4648. ASSERT(!current->journal_info || flush != BTRFS_RESERVE_FLUSH_ALL);
  4649. spin_lock(&space_info->lock);
  4650. ret = -ENOSPC;
  4651. used = btrfs_space_info_used(space_info, true);
  4652. /*
  4653. * If we have enough space then hooray, make our reservation and carry
  4654. * on. If not see if we can overcommit, and if we can, hooray carry on.
  4655. * If not things get more complicated.
  4656. */
  4657. if (used + orig_bytes <= space_info->total_bytes) {
  4658. space_info->bytes_may_use += orig_bytes;
  4659. trace_btrfs_space_reservation(fs_info, "space_info",
  4660. space_info->flags, orig_bytes, 1);
  4661. ret = 0;
  4662. } else if (can_overcommit(fs_info, space_info, orig_bytes, flush,
  4663. system_chunk)) {
  4664. space_info->bytes_may_use += orig_bytes;
  4665. trace_btrfs_space_reservation(fs_info, "space_info",
  4666. space_info->flags, orig_bytes, 1);
  4667. ret = 0;
  4668. }
  4669. /*
  4670. * If we couldn't make a reservation then setup our reservation ticket
  4671. * and kick the async worker if it's not already running.
  4672. *
  4673. * If we are a priority flusher then we just need to add our ticket to
  4674. * the list and we will do our own flushing further down.
  4675. */
  4676. if (ret && flush != BTRFS_RESERVE_NO_FLUSH) {
  4677. ticket.bytes = orig_bytes;
  4678. ticket.error = 0;
  4679. init_waitqueue_head(&ticket.wait);
  4680. if (flush == BTRFS_RESERVE_FLUSH_ALL) {
  4681. list_add_tail(&ticket.list, &space_info->tickets);
  4682. if (!space_info->flush) {
  4683. space_info->flush = 1;
  4684. trace_btrfs_trigger_flush(fs_info,
  4685. space_info->flags,
  4686. orig_bytes, flush,
  4687. "enospc");
  4688. queue_work(system_unbound_wq,
  4689. &fs_info->async_reclaim_work);
  4690. }
  4691. } else {
  4692. list_add_tail(&ticket.list,
  4693. &space_info->priority_tickets);
  4694. }
  4695. } else if (!ret && space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
  4696. used += orig_bytes;
  4697. /*
  4698. * We will do the space reservation dance during log replay,
  4699. * which means we won't have fs_info->fs_root set, so don't do
  4700. * the async reclaim as we will panic.
  4701. */
  4702. if (!test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags) &&
  4703. need_do_async_reclaim(fs_info, space_info,
  4704. used, system_chunk) &&
  4705. !work_busy(&fs_info->async_reclaim_work)) {
  4706. trace_btrfs_trigger_flush(fs_info, space_info->flags,
  4707. orig_bytes, flush, "preempt");
  4708. queue_work(system_unbound_wq,
  4709. &fs_info->async_reclaim_work);
  4710. }
  4711. }
  4712. spin_unlock(&space_info->lock);
  4713. if (!ret || flush == BTRFS_RESERVE_NO_FLUSH)
  4714. return ret;
  4715. if (flush == BTRFS_RESERVE_FLUSH_ALL)
  4716. return wait_reserve_ticket(fs_info, space_info, &ticket,
  4717. orig_bytes);
  4718. ret = 0;
  4719. priority_reclaim_metadata_space(fs_info, space_info, &ticket);
  4720. spin_lock(&space_info->lock);
  4721. if (ticket.bytes) {
  4722. if (ticket.bytes < orig_bytes) {
  4723. u64 num_bytes = orig_bytes - ticket.bytes;
  4724. space_info->bytes_may_use -= num_bytes;
  4725. trace_btrfs_space_reservation(fs_info, "space_info",
  4726. space_info->flags,
  4727. num_bytes, 0);
  4728. }
  4729. list_del_init(&ticket.list);
  4730. ret = -ENOSPC;
  4731. }
  4732. spin_unlock(&space_info->lock);
  4733. ASSERT(list_empty(&ticket.list));
  4734. return ret;
  4735. }
  4736. /**
  4737. * reserve_metadata_bytes - try to reserve bytes from the block_rsv's space
  4738. * @root - the root we're allocating for
  4739. * @block_rsv - the block_rsv we're allocating for
  4740. * @orig_bytes - the number of bytes we want
  4741. * @flush - whether or not we can flush to make our reservation
  4742. *
  4743. * This will reserve orgi_bytes number of bytes from the space info associated
  4744. * with the block_rsv. If there is not enough space it will make an attempt to
  4745. * flush out space to make room. It will do this by flushing delalloc if
  4746. * possible or committing the transaction. If flush is 0 then no attempts to
  4747. * regain reservations will be made and this will fail if there is not enough
  4748. * space already.
  4749. */
  4750. static int reserve_metadata_bytes(struct btrfs_root *root,
  4751. struct btrfs_block_rsv *block_rsv,
  4752. u64 orig_bytes,
  4753. enum btrfs_reserve_flush_enum flush)
  4754. {
  4755. struct btrfs_fs_info *fs_info = root->fs_info;
  4756. struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
  4757. int ret;
  4758. bool system_chunk = (root == fs_info->chunk_root);
  4759. ret = __reserve_metadata_bytes(fs_info, block_rsv->space_info,
  4760. orig_bytes, flush, system_chunk);
  4761. if (ret == -ENOSPC &&
  4762. unlikely(root->orphan_cleanup_state == ORPHAN_CLEANUP_STARTED)) {
  4763. if (block_rsv != global_rsv &&
  4764. !block_rsv_use_bytes(global_rsv, orig_bytes))
  4765. ret = 0;
  4766. }
  4767. if (ret == -ENOSPC)
  4768. trace_btrfs_space_reservation(fs_info, "space_info:enospc",
  4769. block_rsv->space_info->flags,
  4770. orig_bytes, 1);
  4771. return ret;
  4772. }
  4773. static struct btrfs_block_rsv *get_block_rsv(
  4774. const struct btrfs_trans_handle *trans,
  4775. const struct btrfs_root *root)
  4776. {
  4777. struct btrfs_fs_info *fs_info = root->fs_info;
  4778. struct btrfs_block_rsv *block_rsv = NULL;
  4779. if (test_bit(BTRFS_ROOT_REF_COWS, &root->state) ||
  4780. (root == fs_info->csum_root && trans->adding_csums) ||
  4781. (root == fs_info->uuid_root))
  4782. block_rsv = trans->block_rsv;
  4783. if (!block_rsv)
  4784. block_rsv = root->block_rsv;
  4785. if (!block_rsv)
  4786. block_rsv = &fs_info->empty_block_rsv;
  4787. return block_rsv;
  4788. }
  4789. static int block_rsv_use_bytes(struct btrfs_block_rsv *block_rsv,
  4790. u64 num_bytes)
  4791. {
  4792. int ret = -ENOSPC;
  4793. spin_lock(&block_rsv->lock);
  4794. if (block_rsv->reserved >= num_bytes) {
  4795. block_rsv->reserved -= num_bytes;
  4796. if (block_rsv->reserved < block_rsv->size)
  4797. block_rsv->full = 0;
  4798. ret = 0;
  4799. }
  4800. spin_unlock(&block_rsv->lock);
  4801. return ret;
  4802. }
  4803. static void block_rsv_add_bytes(struct btrfs_block_rsv *block_rsv,
  4804. u64 num_bytes, int update_size)
  4805. {
  4806. spin_lock(&block_rsv->lock);
  4807. block_rsv->reserved += num_bytes;
  4808. if (update_size)
  4809. block_rsv->size += num_bytes;
  4810. else if (block_rsv->reserved >= block_rsv->size)
  4811. block_rsv->full = 1;
  4812. spin_unlock(&block_rsv->lock);
  4813. }
  4814. int btrfs_cond_migrate_bytes(struct btrfs_fs_info *fs_info,
  4815. struct btrfs_block_rsv *dest, u64 num_bytes,
  4816. int min_factor)
  4817. {
  4818. struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
  4819. u64 min_bytes;
  4820. if (global_rsv->space_info != dest->space_info)
  4821. return -ENOSPC;
  4822. spin_lock(&global_rsv->lock);
  4823. min_bytes = div_factor(global_rsv->size, min_factor);
  4824. if (global_rsv->reserved < min_bytes + num_bytes) {
  4825. spin_unlock(&global_rsv->lock);
  4826. return -ENOSPC;
  4827. }
  4828. global_rsv->reserved -= num_bytes;
  4829. if (global_rsv->reserved < global_rsv->size)
  4830. global_rsv->full = 0;
  4831. spin_unlock(&global_rsv->lock);
  4832. block_rsv_add_bytes(dest, num_bytes, 1);
  4833. return 0;
  4834. }
  4835. /*
  4836. * This is for space we already have accounted in space_info->bytes_may_use, so
  4837. * basically when we're returning space from block_rsv's.
  4838. */
  4839. static void space_info_add_old_bytes(struct btrfs_fs_info *fs_info,
  4840. struct btrfs_space_info *space_info,
  4841. u64 num_bytes)
  4842. {
  4843. struct reserve_ticket *ticket;
  4844. struct list_head *head;
  4845. u64 used;
  4846. enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_NO_FLUSH;
  4847. bool check_overcommit = false;
  4848. spin_lock(&space_info->lock);
  4849. head = &space_info->priority_tickets;
  4850. /*
  4851. * If we are over our limit then we need to check and see if we can
  4852. * overcommit, and if we can't then we just need to free up our space
  4853. * and not satisfy any requests.
  4854. */
  4855. used = btrfs_space_info_used(space_info, true);
  4856. if (used - num_bytes >= space_info->total_bytes)
  4857. check_overcommit = true;
  4858. again:
  4859. while (!list_empty(head) && num_bytes) {
  4860. ticket = list_first_entry(head, struct reserve_ticket,
  4861. list);
  4862. /*
  4863. * We use 0 bytes because this space is already reserved, so
  4864. * adding the ticket space would be a double count.
  4865. */
  4866. if (check_overcommit &&
  4867. !can_overcommit(fs_info, space_info, 0, flush, false))
  4868. break;
  4869. if (num_bytes >= ticket->bytes) {
  4870. list_del_init(&ticket->list);
  4871. num_bytes -= ticket->bytes;
  4872. ticket->bytes = 0;
  4873. space_info->tickets_id++;
  4874. wake_up(&ticket->wait);
  4875. } else {
  4876. ticket->bytes -= num_bytes;
  4877. num_bytes = 0;
  4878. }
  4879. }
  4880. if (num_bytes && head == &space_info->priority_tickets) {
  4881. head = &space_info->tickets;
  4882. flush = BTRFS_RESERVE_FLUSH_ALL;
  4883. goto again;
  4884. }
  4885. space_info->bytes_may_use -= num_bytes;
  4886. trace_btrfs_space_reservation(fs_info, "space_info",
  4887. space_info->flags, num_bytes, 0);
  4888. spin_unlock(&space_info->lock);
  4889. }
  4890. /*
  4891. * This is for newly allocated space that isn't accounted in
  4892. * space_info->bytes_may_use yet. So if we allocate a chunk or unpin an extent
  4893. * we use this helper.
  4894. */
  4895. static void space_info_add_new_bytes(struct btrfs_fs_info *fs_info,
  4896. struct btrfs_space_info *space_info,
  4897. u64 num_bytes)
  4898. {
  4899. struct reserve_ticket *ticket;
  4900. struct list_head *head = &space_info->priority_tickets;
  4901. again:
  4902. while (!list_empty(head) && num_bytes) {
  4903. ticket = list_first_entry(head, struct reserve_ticket,
  4904. list);
  4905. if (num_bytes >= ticket->bytes) {
  4906. trace_btrfs_space_reservation(fs_info, "space_info",
  4907. space_info->flags,
  4908. ticket->bytes, 1);
  4909. list_del_init(&ticket->list);
  4910. num_bytes -= ticket->bytes;
  4911. space_info->bytes_may_use += ticket->bytes;
  4912. ticket->bytes = 0;
  4913. space_info->tickets_id++;
  4914. wake_up(&ticket->wait);
  4915. } else {
  4916. trace_btrfs_space_reservation(fs_info, "space_info",
  4917. space_info->flags,
  4918. num_bytes, 1);
  4919. space_info->bytes_may_use += num_bytes;
  4920. ticket->bytes -= num_bytes;
  4921. num_bytes = 0;
  4922. }
  4923. }
  4924. if (num_bytes && head == &space_info->priority_tickets) {
  4925. head = &space_info->tickets;
  4926. goto again;
  4927. }
  4928. }
  4929. static u64 block_rsv_release_bytes(struct btrfs_fs_info *fs_info,
  4930. struct btrfs_block_rsv *block_rsv,
  4931. struct btrfs_block_rsv *dest, u64 num_bytes)
  4932. {
  4933. struct btrfs_space_info *space_info = block_rsv->space_info;
  4934. u64 ret;
  4935. spin_lock(&block_rsv->lock);
  4936. if (num_bytes == (u64)-1)
  4937. num_bytes = block_rsv->size;
  4938. block_rsv->size -= num_bytes;
  4939. if (block_rsv->reserved >= block_rsv->size) {
  4940. num_bytes = block_rsv->reserved - block_rsv->size;
  4941. block_rsv->reserved = block_rsv->size;
  4942. block_rsv->full = 1;
  4943. } else {
  4944. num_bytes = 0;
  4945. }
  4946. spin_unlock(&block_rsv->lock);
  4947. ret = num_bytes;
  4948. if (num_bytes > 0) {
  4949. if (dest) {
  4950. spin_lock(&dest->lock);
  4951. if (!dest->full) {
  4952. u64 bytes_to_add;
  4953. bytes_to_add = dest->size - dest->reserved;
  4954. bytes_to_add = min(num_bytes, bytes_to_add);
  4955. dest->reserved += bytes_to_add;
  4956. if (dest->reserved >= dest->size)
  4957. dest->full = 1;
  4958. num_bytes -= bytes_to_add;
  4959. }
  4960. spin_unlock(&dest->lock);
  4961. }
  4962. if (num_bytes)
  4963. space_info_add_old_bytes(fs_info, space_info,
  4964. num_bytes);
  4965. }
  4966. return ret;
  4967. }
  4968. int btrfs_block_rsv_migrate(struct btrfs_block_rsv *src,
  4969. struct btrfs_block_rsv *dst, u64 num_bytes,
  4970. int update_size)
  4971. {
  4972. int ret;
  4973. ret = block_rsv_use_bytes(src, num_bytes);
  4974. if (ret)
  4975. return ret;
  4976. block_rsv_add_bytes(dst, num_bytes, update_size);
  4977. return 0;
  4978. }
  4979. void btrfs_init_block_rsv(struct btrfs_block_rsv *rsv, unsigned short type)
  4980. {
  4981. memset(rsv, 0, sizeof(*rsv));
  4982. spin_lock_init(&rsv->lock);
  4983. rsv->type = type;
  4984. }
  4985. void btrfs_init_metadata_block_rsv(struct btrfs_fs_info *fs_info,
  4986. struct btrfs_block_rsv *rsv,
  4987. unsigned short type)
  4988. {
  4989. btrfs_init_block_rsv(rsv, type);
  4990. rsv->space_info = __find_space_info(fs_info,
  4991. BTRFS_BLOCK_GROUP_METADATA);
  4992. }
  4993. struct btrfs_block_rsv *btrfs_alloc_block_rsv(struct btrfs_fs_info *fs_info,
  4994. unsigned short type)
  4995. {
  4996. struct btrfs_block_rsv *block_rsv;
  4997. block_rsv = kmalloc(sizeof(*block_rsv), GFP_NOFS);
  4998. if (!block_rsv)
  4999. return NULL;
  5000. btrfs_init_metadata_block_rsv(fs_info, block_rsv, type);
  5001. return block_rsv;
  5002. }
  5003. void btrfs_free_block_rsv(struct btrfs_fs_info *fs_info,
  5004. struct btrfs_block_rsv *rsv)
  5005. {
  5006. if (!rsv)
  5007. return;
  5008. btrfs_block_rsv_release(fs_info, rsv, (u64)-1);
  5009. kfree(rsv);
  5010. }
  5011. void __btrfs_free_block_rsv(struct btrfs_block_rsv *rsv)
  5012. {
  5013. kfree(rsv);
  5014. }
  5015. int btrfs_block_rsv_add(struct btrfs_root *root,
  5016. struct btrfs_block_rsv *block_rsv, u64 num_bytes,
  5017. enum btrfs_reserve_flush_enum flush)
  5018. {
  5019. int ret;
  5020. if (num_bytes == 0)
  5021. return 0;
  5022. ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
  5023. if (!ret) {
  5024. block_rsv_add_bytes(block_rsv, num_bytes, 1);
  5025. return 0;
  5026. }
  5027. return ret;
  5028. }
  5029. int btrfs_block_rsv_check(struct btrfs_block_rsv *block_rsv, int min_factor)
  5030. {
  5031. u64 num_bytes = 0;
  5032. int ret = -ENOSPC;
  5033. if (!block_rsv)
  5034. return 0;
  5035. spin_lock(&block_rsv->lock);
  5036. num_bytes = div_factor(block_rsv->size, min_factor);
  5037. if (block_rsv->reserved >= num_bytes)
  5038. ret = 0;
  5039. spin_unlock(&block_rsv->lock);
  5040. return ret;
  5041. }
  5042. int btrfs_block_rsv_refill(struct btrfs_root *root,
  5043. struct btrfs_block_rsv *block_rsv, u64 min_reserved,
  5044. enum btrfs_reserve_flush_enum flush)
  5045. {
  5046. u64 num_bytes = 0;
  5047. int ret = -ENOSPC;
  5048. if (!block_rsv)
  5049. return 0;
  5050. spin_lock(&block_rsv->lock);
  5051. num_bytes = min_reserved;
  5052. if (block_rsv->reserved >= num_bytes)
  5053. ret = 0;
  5054. else
  5055. num_bytes -= block_rsv->reserved;
  5056. spin_unlock(&block_rsv->lock);
  5057. if (!ret)
  5058. return 0;
  5059. ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
  5060. if (!ret) {
  5061. block_rsv_add_bytes(block_rsv, num_bytes, 0);
  5062. return 0;
  5063. }
  5064. return ret;
  5065. }
  5066. /**
  5067. * btrfs_inode_rsv_refill - refill the inode block rsv.
  5068. * @inode - the inode we are refilling.
  5069. * @flush - the flusing restriction.
  5070. *
  5071. * Essentially the same as btrfs_block_rsv_refill, except it uses the
  5072. * block_rsv->size as the minimum size. We'll either refill the missing amount
  5073. * or return if we already have enough space. This will also handle the resreve
  5074. * tracepoint for the reserved amount.
  5075. */
  5076. int btrfs_inode_rsv_refill(struct btrfs_inode *inode,
  5077. enum btrfs_reserve_flush_enum flush)
  5078. {
  5079. struct btrfs_root *root = inode->root;
  5080. struct btrfs_block_rsv *block_rsv = &inode->block_rsv;
  5081. u64 num_bytes = 0;
  5082. int ret = -ENOSPC;
  5083. spin_lock(&block_rsv->lock);
  5084. if (block_rsv->reserved < block_rsv->size)
  5085. num_bytes = block_rsv->size - block_rsv->reserved;
  5086. spin_unlock(&block_rsv->lock);
  5087. if (num_bytes == 0)
  5088. return 0;
  5089. ret = reserve_metadata_bytes(root, block_rsv, num_bytes, flush);
  5090. if (!ret) {
  5091. block_rsv_add_bytes(block_rsv, num_bytes, 0);
  5092. trace_btrfs_space_reservation(root->fs_info, "delalloc",
  5093. btrfs_ino(inode), num_bytes, 1);
  5094. }
  5095. return ret;
  5096. }
  5097. /**
  5098. * btrfs_inode_rsv_release - release any excessive reservation.
  5099. * @inode - the inode we need to release from.
  5100. *
  5101. * This is the same as btrfs_block_rsv_release, except that it handles the
  5102. * tracepoint for the reservation.
  5103. */
  5104. void btrfs_inode_rsv_release(struct btrfs_inode *inode)
  5105. {
  5106. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  5107. struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
  5108. struct btrfs_block_rsv *block_rsv = &inode->block_rsv;
  5109. u64 released = 0;
  5110. /*
  5111. * Since we statically set the block_rsv->size we just want to say we
  5112. * are releasing 0 bytes, and then we'll just get the reservation over
  5113. * the size free'd.
  5114. */
  5115. released = block_rsv_release_bytes(fs_info, block_rsv, global_rsv, 0);
  5116. if (released > 0)
  5117. trace_btrfs_space_reservation(fs_info, "delalloc",
  5118. btrfs_ino(inode), released, 0);
  5119. }
  5120. void btrfs_block_rsv_release(struct btrfs_fs_info *fs_info,
  5121. struct btrfs_block_rsv *block_rsv,
  5122. u64 num_bytes)
  5123. {
  5124. struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
  5125. if (global_rsv == block_rsv ||
  5126. block_rsv->space_info != global_rsv->space_info)
  5127. global_rsv = NULL;
  5128. block_rsv_release_bytes(fs_info, block_rsv, global_rsv, num_bytes);
  5129. }
  5130. static void update_global_block_rsv(struct btrfs_fs_info *fs_info)
  5131. {
  5132. struct btrfs_block_rsv *block_rsv = &fs_info->global_block_rsv;
  5133. struct btrfs_space_info *sinfo = block_rsv->space_info;
  5134. u64 num_bytes;
  5135. /*
  5136. * The global block rsv is based on the size of the extent tree, the
  5137. * checksum tree and the root tree. If the fs is empty we want to set
  5138. * it to a minimal amount for safety.
  5139. */
  5140. num_bytes = btrfs_root_used(&fs_info->extent_root->root_item) +
  5141. btrfs_root_used(&fs_info->csum_root->root_item) +
  5142. btrfs_root_used(&fs_info->tree_root->root_item);
  5143. num_bytes = max_t(u64, num_bytes, SZ_16M);
  5144. spin_lock(&sinfo->lock);
  5145. spin_lock(&block_rsv->lock);
  5146. block_rsv->size = min_t(u64, num_bytes, SZ_512M);
  5147. if (block_rsv->reserved < block_rsv->size) {
  5148. num_bytes = btrfs_space_info_used(sinfo, true);
  5149. if (sinfo->total_bytes > num_bytes) {
  5150. num_bytes = sinfo->total_bytes - num_bytes;
  5151. num_bytes = min(num_bytes,
  5152. block_rsv->size - block_rsv->reserved);
  5153. block_rsv->reserved += num_bytes;
  5154. sinfo->bytes_may_use += num_bytes;
  5155. trace_btrfs_space_reservation(fs_info, "space_info",
  5156. sinfo->flags, num_bytes,
  5157. 1);
  5158. }
  5159. } else if (block_rsv->reserved > block_rsv->size) {
  5160. num_bytes = block_rsv->reserved - block_rsv->size;
  5161. sinfo->bytes_may_use -= num_bytes;
  5162. trace_btrfs_space_reservation(fs_info, "space_info",
  5163. sinfo->flags, num_bytes, 0);
  5164. block_rsv->reserved = block_rsv->size;
  5165. }
  5166. if (block_rsv->reserved == block_rsv->size)
  5167. block_rsv->full = 1;
  5168. else
  5169. block_rsv->full = 0;
  5170. spin_unlock(&block_rsv->lock);
  5171. spin_unlock(&sinfo->lock);
  5172. }
  5173. static void init_global_block_rsv(struct btrfs_fs_info *fs_info)
  5174. {
  5175. struct btrfs_space_info *space_info;
  5176. space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_SYSTEM);
  5177. fs_info->chunk_block_rsv.space_info = space_info;
  5178. space_info = __find_space_info(fs_info, BTRFS_BLOCK_GROUP_METADATA);
  5179. fs_info->global_block_rsv.space_info = space_info;
  5180. fs_info->trans_block_rsv.space_info = space_info;
  5181. fs_info->empty_block_rsv.space_info = space_info;
  5182. fs_info->delayed_block_rsv.space_info = space_info;
  5183. fs_info->extent_root->block_rsv = &fs_info->global_block_rsv;
  5184. fs_info->csum_root->block_rsv = &fs_info->global_block_rsv;
  5185. fs_info->dev_root->block_rsv = &fs_info->global_block_rsv;
  5186. fs_info->tree_root->block_rsv = &fs_info->global_block_rsv;
  5187. if (fs_info->quota_root)
  5188. fs_info->quota_root->block_rsv = &fs_info->global_block_rsv;
  5189. fs_info->chunk_root->block_rsv = &fs_info->chunk_block_rsv;
  5190. update_global_block_rsv(fs_info);
  5191. }
  5192. static void release_global_block_rsv(struct btrfs_fs_info *fs_info)
  5193. {
  5194. block_rsv_release_bytes(fs_info, &fs_info->global_block_rsv, NULL,
  5195. (u64)-1);
  5196. WARN_ON(fs_info->trans_block_rsv.size > 0);
  5197. WARN_ON(fs_info->trans_block_rsv.reserved > 0);
  5198. WARN_ON(fs_info->chunk_block_rsv.size > 0);
  5199. WARN_ON(fs_info->chunk_block_rsv.reserved > 0);
  5200. WARN_ON(fs_info->delayed_block_rsv.size > 0);
  5201. WARN_ON(fs_info->delayed_block_rsv.reserved > 0);
  5202. }
  5203. void btrfs_trans_release_metadata(struct btrfs_trans_handle *trans,
  5204. struct btrfs_fs_info *fs_info)
  5205. {
  5206. if (!trans->block_rsv) {
  5207. ASSERT(!trans->bytes_reserved);
  5208. return;
  5209. }
  5210. if (!trans->bytes_reserved)
  5211. return;
  5212. ASSERT(trans->block_rsv == &fs_info->trans_block_rsv);
  5213. trace_btrfs_space_reservation(fs_info, "transaction",
  5214. trans->transid, trans->bytes_reserved, 0);
  5215. btrfs_block_rsv_release(fs_info, trans->block_rsv,
  5216. trans->bytes_reserved);
  5217. trans->bytes_reserved = 0;
  5218. }
  5219. /*
  5220. * To be called after all the new block groups attached to the transaction
  5221. * handle have been created (btrfs_create_pending_block_groups()).
  5222. */
  5223. void btrfs_trans_release_chunk_metadata(struct btrfs_trans_handle *trans)
  5224. {
  5225. struct btrfs_fs_info *fs_info = trans->fs_info;
  5226. if (!trans->chunk_bytes_reserved)
  5227. return;
  5228. WARN_ON_ONCE(!list_empty(&trans->new_bgs));
  5229. block_rsv_release_bytes(fs_info, &fs_info->chunk_block_rsv, NULL,
  5230. trans->chunk_bytes_reserved);
  5231. trans->chunk_bytes_reserved = 0;
  5232. }
  5233. /* Can only return 0 or -ENOSPC */
  5234. int btrfs_orphan_reserve_metadata(struct btrfs_trans_handle *trans,
  5235. struct btrfs_inode *inode)
  5236. {
  5237. struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
  5238. struct btrfs_root *root = inode->root;
  5239. /*
  5240. * We always use trans->block_rsv here as we will have reserved space
  5241. * for our orphan when starting the transaction, using get_block_rsv()
  5242. * here will sometimes make us choose the wrong block rsv as we could be
  5243. * doing a reloc inode for a non refcounted root.
  5244. */
  5245. struct btrfs_block_rsv *src_rsv = trans->block_rsv;
  5246. struct btrfs_block_rsv *dst_rsv = root->orphan_block_rsv;
  5247. /*
  5248. * We need to hold space in order to delete our orphan item once we've
  5249. * added it, so this takes the reservation so we can release it later
  5250. * when we are truly done with the orphan item.
  5251. */
  5252. u64 num_bytes = btrfs_calc_trans_metadata_size(fs_info, 1);
  5253. trace_btrfs_space_reservation(fs_info, "orphan", btrfs_ino(inode),
  5254. num_bytes, 1);
  5255. return btrfs_block_rsv_migrate(src_rsv, dst_rsv, num_bytes, 1);
  5256. }
  5257. void btrfs_orphan_release_metadata(struct btrfs_inode *inode)
  5258. {
  5259. struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
  5260. struct btrfs_root *root = inode->root;
  5261. u64 num_bytes = btrfs_calc_trans_metadata_size(fs_info, 1);
  5262. trace_btrfs_space_reservation(fs_info, "orphan", btrfs_ino(inode),
  5263. num_bytes, 0);
  5264. btrfs_block_rsv_release(fs_info, root->orphan_block_rsv, num_bytes);
  5265. }
  5266. /*
  5267. * btrfs_subvolume_reserve_metadata() - reserve space for subvolume operation
  5268. * root: the root of the parent directory
  5269. * rsv: block reservation
  5270. * items: the number of items that we need do reservation
  5271. * qgroup_reserved: used to return the reserved size in qgroup
  5272. *
  5273. * This function is used to reserve the space for snapshot/subvolume
  5274. * creation and deletion. Those operations are different with the
  5275. * common file/directory operations, they change two fs/file trees
  5276. * and root tree, the number of items that the qgroup reserves is
  5277. * different with the free space reservation. So we can not use
  5278. * the space reservation mechanism in start_transaction().
  5279. */
  5280. int btrfs_subvolume_reserve_metadata(struct btrfs_root *root,
  5281. struct btrfs_block_rsv *rsv,
  5282. int items,
  5283. u64 *qgroup_reserved,
  5284. bool use_global_rsv)
  5285. {
  5286. u64 num_bytes;
  5287. int ret;
  5288. struct btrfs_fs_info *fs_info = root->fs_info;
  5289. struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
  5290. if (test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags)) {
  5291. /* One for parent inode, two for dir entries */
  5292. num_bytes = 3 * fs_info->nodesize;
  5293. ret = btrfs_qgroup_reserve_meta(root, num_bytes, true);
  5294. if (ret)
  5295. return ret;
  5296. } else {
  5297. num_bytes = 0;
  5298. }
  5299. *qgroup_reserved = num_bytes;
  5300. num_bytes = btrfs_calc_trans_metadata_size(fs_info, items);
  5301. rsv->space_info = __find_space_info(fs_info,
  5302. BTRFS_BLOCK_GROUP_METADATA);
  5303. ret = btrfs_block_rsv_add(root, rsv, num_bytes,
  5304. BTRFS_RESERVE_FLUSH_ALL);
  5305. if (ret == -ENOSPC && use_global_rsv)
  5306. ret = btrfs_block_rsv_migrate(global_rsv, rsv, num_bytes, 1);
  5307. if (ret && *qgroup_reserved)
  5308. btrfs_qgroup_free_meta(root, *qgroup_reserved);
  5309. return ret;
  5310. }
  5311. void btrfs_subvolume_release_metadata(struct btrfs_fs_info *fs_info,
  5312. struct btrfs_block_rsv *rsv)
  5313. {
  5314. btrfs_block_rsv_release(fs_info, rsv, (u64)-1);
  5315. }
  5316. static void btrfs_calculate_inode_block_rsv_size(struct btrfs_fs_info *fs_info,
  5317. struct btrfs_inode *inode)
  5318. {
  5319. struct btrfs_block_rsv *block_rsv = &inode->block_rsv;
  5320. u64 reserve_size = 0;
  5321. u64 csum_leaves;
  5322. unsigned outstanding_extents;
  5323. lockdep_assert_held(&inode->lock);
  5324. outstanding_extents = inode->outstanding_extents;
  5325. if (outstanding_extents)
  5326. reserve_size = btrfs_calc_trans_metadata_size(fs_info,
  5327. outstanding_extents + 1);
  5328. csum_leaves = btrfs_csum_bytes_to_leaves(fs_info,
  5329. inode->csum_bytes);
  5330. reserve_size += btrfs_calc_trans_metadata_size(fs_info,
  5331. csum_leaves);
  5332. spin_lock(&block_rsv->lock);
  5333. block_rsv->size = reserve_size;
  5334. spin_unlock(&block_rsv->lock);
  5335. }
  5336. int btrfs_delalloc_reserve_metadata(struct btrfs_inode *inode, u64 num_bytes)
  5337. {
  5338. struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
  5339. struct btrfs_root *root = inode->root;
  5340. unsigned nr_extents;
  5341. enum btrfs_reserve_flush_enum flush = BTRFS_RESERVE_FLUSH_ALL;
  5342. int ret = 0;
  5343. bool delalloc_lock = true;
  5344. /* If we are a free space inode we need to not flush since we will be in
  5345. * the middle of a transaction commit. We also don't need the delalloc
  5346. * mutex since we won't race with anybody. We need this mostly to make
  5347. * lockdep shut its filthy mouth.
  5348. *
  5349. * If we have a transaction open (can happen if we call truncate_block
  5350. * from truncate), then we need FLUSH_LIMIT so we don't deadlock.
  5351. */
  5352. if (btrfs_is_free_space_inode(inode)) {
  5353. flush = BTRFS_RESERVE_NO_FLUSH;
  5354. delalloc_lock = false;
  5355. } else if (current->journal_info) {
  5356. flush = BTRFS_RESERVE_FLUSH_LIMIT;
  5357. }
  5358. if (flush != BTRFS_RESERVE_NO_FLUSH &&
  5359. btrfs_transaction_in_commit(fs_info))
  5360. schedule_timeout(1);
  5361. if (delalloc_lock)
  5362. mutex_lock(&inode->delalloc_mutex);
  5363. num_bytes = ALIGN(num_bytes, fs_info->sectorsize);
  5364. /* Add our new extents and calculate the new rsv size. */
  5365. spin_lock(&inode->lock);
  5366. nr_extents = count_max_extents(num_bytes);
  5367. btrfs_mod_outstanding_extents(inode, nr_extents);
  5368. inode->csum_bytes += num_bytes;
  5369. btrfs_calculate_inode_block_rsv_size(fs_info, inode);
  5370. spin_unlock(&inode->lock);
  5371. if (test_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags)) {
  5372. ret = btrfs_qgroup_reserve_meta(root,
  5373. nr_extents * fs_info->nodesize, true);
  5374. if (ret)
  5375. goto out_fail;
  5376. }
  5377. ret = btrfs_inode_rsv_refill(inode, flush);
  5378. if (unlikely(ret)) {
  5379. btrfs_qgroup_free_meta(root,
  5380. nr_extents * fs_info->nodesize);
  5381. goto out_fail;
  5382. }
  5383. if (delalloc_lock)
  5384. mutex_unlock(&inode->delalloc_mutex);
  5385. return 0;
  5386. out_fail:
  5387. spin_lock(&inode->lock);
  5388. nr_extents = count_max_extents(num_bytes);
  5389. btrfs_mod_outstanding_extents(inode, -nr_extents);
  5390. inode->csum_bytes -= num_bytes;
  5391. btrfs_calculate_inode_block_rsv_size(fs_info, inode);
  5392. spin_unlock(&inode->lock);
  5393. btrfs_inode_rsv_release(inode);
  5394. if (delalloc_lock)
  5395. mutex_unlock(&inode->delalloc_mutex);
  5396. return ret;
  5397. }
  5398. /**
  5399. * btrfs_delalloc_release_metadata - release a metadata reservation for an inode
  5400. * @inode: the inode to release the reservation for.
  5401. * @num_bytes: the number of bytes we are releasing.
  5402. *
  5403. * This will release the metadata reservation for an inode. This can be called
  5404. * once we complete IO for a given set of bytes to release their metadata
  5405. * reservations, or on error for the same reason.
  5406. */
  5407. void btrfs_delalloc_release_metadata(struct btrfs_inode *inode, u64 num_bytes)
  5408. {
  5409. struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
  5410. num_bytes = ALIGN(num_bytes, fs_info->sectorsize);
  5411. spin_lock(&inode->lock);
  5412. inode->csum_bytes -= num_bytes;
  5413. btrfs_calculate_inode_block_rsv_size(fs_info, inode);
  5414. spin_unlock(&inode->lock);
  5415. if (btrfs_is_testing(fs_info))
  5416. return;
  5417. btrfs_inode_rsv_release(inode);
  5418. }
  5419. /**
  5420. * btrfs_delalloc_release_extents - release our outstanding_extents
  5421. * @inode: the inode to balance the reservation for.
  5422. * @num_bytes: the number of bytes we originally reserved with
  5423. *
  5424. * When we reserve space we increase outstanding_extents for the extents we may
  5425. * add. Once we've set the range as delalloc or created our ordered extents we
  5426. * have outstanding_extents to track the real usage, so we use this to free our
  5427. * temporarily tracked outstanding_extents. This _must_ be used in conjunction
  5428. * with btrfs_delalloc_reserve_metadata.
  5429. */
  5430. void btrfs_delalloc_release_extents(struct btrfs_inode *inode, u64 num_bytes)
  5431. {
  5432. struct btrfs_fs_info *fs_info = btrfs_sb(inode->vfs_inode.i_sb);
  5433. unsigned num_extents;
  5434. spin_lock(&inode->lock);
  5435. num_extents = count_max_extents(num_bytes);
  5436. btrfs_mod_outstanding_extents(inode, -num_extents);
  5437. btrfs_calculate_inode_block_rsv_size(fs_info, inode);
  5438. spin_unlock(&inode->lock);
  5439. if (btrfs_is_testing(fs_info))
  5440. return;
  5441. btrfs_inode_rsv_release(inode);
  5442. }
  5443. /**
  5444. * btrfs_delalloc_reserve_space - reserve data and metadata space for
  5445. * delalloc
  5446. * @inode: inode we're writing to
  5447. * @start: start range we are writing to
  5448. * @len: how long the range we are writing to
  5449. * @reserved: mandatory parameter, record actually reserved qgroup ranges of
  5450. * current reservation.
  5451. *
  5452. * This will do the following things
  5453. *
  5454. * o reserve space in data space info for num bytes
  5455. * and reserve precious corresponding qgroup space
  5456. * (Done in check_data_free_space)
  5457. *
  5458. * o reserve space for metadata space, based on the number of outstanding
  5459. * extents and how much csums will be needed
  5460. * also reserve metadata space in a per root over-reserve method.
  5461. * o add to the inodes->delalloc_bytes
  5462. * o add it to the fs_info's delalloc inodes list.
  5463. * (Above 3 all done in delalloc_reserve_metadata)
  5464. *
  5465. * Return 0 for success
  5466. * Return <0 for error(-ENOSPC or -EQUOT)
  5467. */
  5468. int btrfs_delalloc_reserve_space(struct inode *inode,
  5469. struct extent_changeset **reserved, u64 start, u64 len)
  5470. {
  5471. int ret;
  5472. ret = btrfs_check_data_free_space(inode, reserved, start, len);
  5473. if (ret < 0)
  5474. return ret;
  5475. ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode), len);
  5476. if (ret < 0)
  5477. btrfs_free_reserved_data_space(inode, *reserved, start, len);
  5478. return ret;
  5479. }
  5480. /**
  5481. * btrfs_delalloc_release_space - release data and metadata space for delalloc
  5482. * @inode: inode we're releasing space for
  5483. * @start: start position of the space already reserved
  5484. * @len: the len of the space already reserved
  5485. * @release_bytes: the len of the space we consumed or didn't use
  5486. *
  5487. * This function will release the metadata space that was not used and will
  5488. * decrement ->delalloc_bytes and remove it from the fs_info delalloc_inodes
  5489. * list if there are no delalloc bytes left.
  5490. * Also it will handle the qgroup reserved space.
  5491. */
  5492. void btrfs_delalloc_release_space(struct inode *inode,
  5493. struct extent_changeset *reserved,
  5494. u64 start, u64 len)
  5495. {
  5496. btrfs_delalloc_release_metadata(BTRFS_I(inode), len);
  5497. btrfs_free_reserved_data_space(inode, reserved, start, len);
  5498. }
  5499. static int update_block_group(struct btrfs_trans_handle *trans,
  5500. struct btrfs_fs_info *info, u64 bytenr,
  5501. u64 num_bytes, int alloc)
  5502. {
  5503. struct btrfs_block_group_cache *cache = NULL;
  5504. u64 total = num_bytes;
  5505. u64 old_val;
  5506. u64 byte_in_group;
  5507. int factor;
  5508. /* block accounting for super block */
  5509. spin_lock(&info->delalloc_root_lock);
  5510. old_val = btrfs_super_bytes_used(info->super_copy);
  5511. if (alloc)
  5512. old_val += num_bytes;
  5513. else
  5514. old_val -= num_bytes;
  5515. btrfs_set_super_bytes_used(info->super_copy, old_val);
  5516. spin_unlock(&info->delalloc_root_lock);
  5517. while (total) {
  5518. cache = btrfs_lookup_block_group(info, bytenr);
  5519. if (!cache)
  5520. return -ENOENT;
  5521. if (cache->flags & (BTRFS_BLOCK_GROUP_DUP |
  5522. BTRFS_BLOCK_GROUP_RAID1 |
  5523. BTRFS_BLOCK_GROUP_RAID10))
  5524. factor = 2;
  5525. else
  5526. factor = 1;
  5527. /*
  5528. * If this block group has free space cache written out, we
  5529. * need to make sure to load it if we are removing space. This
  5530. * is because we need the unpinning stage to actually add the
  5531. * space back to the block group, otherwise we will leak space.
  5532. */
  5533. if (!alloc && cache->cached == BTRFS_CACHE_NO)
  5534. cache_block_group(cache, 1);
  5535. byte_in_group = bytenr - cache->key.objectid;
  5536. WARN_ON(byte_in_group > cache->key.offset);
  5537. spin_lock(&cache->space_info->lock);
  5538. spin_lock(&cache->lock);
  5539. if (btrfs_test_opt(info, SPACE_CACHE) &&
  5540. cache->disk_cache_state < BTRFS_DC_CLEAR)
  5541. cache->disk_cache_state = BTRFS_DC_CLEAR;
  5542. old_val = btrfs_block_group_used(&cache->item);
  5543. num_bytes = min(total, cache->key.offset - byte_in_group);
  5544. if (alloc) {
  5545. old_val += num_bytes;
  5546. btrfs_set_block_group_used(&cache->item, old_val);
  5547. cache->reserved -= num_bytes;
  5548. cache->space_info->bytes_reserved -= num_bytes;
  5549. cache->space_info->bytes_used += num_bytes;
  5550. cache->space_info->disk_used += num_bytes * factor;
  5551. spin_unlock(&cache->lock);
  5552. spin_unlock(&cache->space_info->lock);
  5553. } else {
  5554. old_val -= num_bytes;
  5555. btrfs_set_block_group_used(&cache->item, old_val);
  5556. cache->pinned += num_bytes;
  5557. cache->space_info->bytes_pinned += num_bytes;
  5558. cache->space_info->bytes_used -= num_bytes;
  5559. cache->space_info->disk_used -= num_bytes * factor;
  5560. spin_unlock(&cache->lock);
  5561. spin_unlock(&cache->space_info->lock);
  5562. trace_btrfs_space_reservation(info, "pinned",
  5563. cache->space_info->flags,
  5564. num_bytes, 1);
  5565. percpu_counter_add(&cache->space_info->total_bytes_pinned,
  5566. num_bytes);
  5567. set_extent_dirty(info->pinned_extents,
  5568. bytenr, bytenr + num_bytes - 1,
  5569. GFP_NOFS | __GFP_NOFAIL);
  5570. }
  5571. spin_lock(&trans->transaction->dirty_bgs_lock);
  5572. if (list_empty(&cache->dirty_list)) {
  5573. list_add_tail(&cache->dirty_list,
  5574. &trans->transaction->dirty_bgs);
  5575. trans->transaction->num_dirty_bgs++;
  5576. btrfs_get_block_group(cache);
  5577. }
  5578. spin_unlock(&trans->transaction->dirty_bgs_lock);
  5579. /*
  5580. * No longer have used bytes in this block group, queue it for
  5581. * deletion. We do this after adding the block group to the
  5582. * dirty list to avoid races between cleaner kthread and space
  5583. * cache writeout.
  5584. */
  5585. if (!alloc && old_val == 0) {
  5586. spin_lock(&info->unused_bgs_lock);
  5587. if (list_empty(&cache->bg_list)) {
  5588. btrfs_get_block_group(cache);
  5589. list_add_tail(&cache->bg_list,
  5590. &info->unused_bgs);
  5591. }
  5592. spin_unlock(&info->unused_bgs_lock);
  5593. }
  5594. btrfs_put_block_group(cache);
  5595. total -= num_bytes;
  5596. bytenr += num_bytes;
  5597. }
  5598. return 0;
  5599. }
  5600. static u64 first_logical_byte(struct btrfs_fs_info *fs_info, u64 search_start)
  5601. {
  5602. struct btrfs_block_group_cache *cache;
  5603. u64 bytenr;
  5604. spin_lock(&fs_info->block_group_cache_lock);
  5605. bytenr = fs_info->first_logical_byte;
  5606. spin_unlock(&fs_info->block_group_cache_lock);
  5607. if (bytenr < (u64)-1)
  5608. return bytenr;
  5609. cache = btrfs_lookup_first_block_group(fs_info, search_start);
  5610. if (!cache)
  5611. return 0;
  5612. bytenr = cache->key.objectid;
  5613. btrfs_put_block_group(cache);
  5614. return bytenr;
  5615. }
  5616. static int pin_down_extent(struct btrfs_fs_info *fs_info,
  5617. struct btrfs_block_group_cache *cache,
  5618. u64 bytenr, u64 num_bytes, int reserved)
  5619. {
  5620. spin_lock(&cache->space_info->lock);
  5621. spin_lock(&cache->lock);
  5622. cache->pinned += num_bytes;
  5623. cache->space_info->bytes_pinned += num_bytes;
  5624. if (reserved) {
  5625. cache->reserved -= num_bytes;
  5626. cache->space_info->bytes_reserved -= num_bytes;
  5627. }
  5628. spin_unlock(&cache->lock);
  5629. spin_unlock(&cache->space_info->lock);
  5630. trace_btrfs_space_reservation(fs_info, "pinned",
  5631. cache->space_info->flags, num_bytes, 1);
  5632. percpu_counter_add(&cache->space_info->total_bytes_pinned, num_bytes);
  5633. set_extent_dirty(fs_info->pinned_extents, bytenr,
  5634. bytenr + num_bytes - 1, GFP_NOFS | __GFP_NOFAIL);
  5635. return 0;
  5636. }
  5637. /*
  5638. * this function must be called within transaction
  5639. */
  5640. int btrfs_pin_extent(struct btrfs_fs_info *fs_info,
  5641. u64 bytenr, u64 num_bytes, int reserved)
  5642. {
  5643. struct btrfs_block_group_cache *cache;
  5644. cache = btrfs_lookup_block_group(fs_info, bytenr);
  5645. BUG_ON(!cache); /* Logic error */
  5646. pin_down_extent(fs_info, cache, bytenr, num_bytes, reserved);
  5647. btrfs_put_block_group(cache);
  5648. return 0;
  5649. }
  5650. /*
  5651. * this function must be called within transaction
  5652. */
  5653. int btrfs_pin_extent_for_log_replay(struct btrfs_fs_info *fs_info,
  5654. u64 bytenr, u64 num_bytes)
  5655. {
  5656. struct btrfs_block_group_cache *cache;
  5657. int ret;
  5658. cache = btrfs_lookup_block_group(fs_info, bytenr);
  5659. if (!cache)
  5660. return -EINVAL;
  5661. /*
  5662. * pull in the free space cache (if any) so that our pin
  5663. * removes the free space from the cache. We have load_only set
  5664. * to one because the slow code to read in the free extents does check
  5665. * the pinned extents.
  5666. */
  5667. cache_block_group(cache, 1);
  5668. pin_down_extent(fs_info, cache, bytenr, num_bytes, 0);
  5669. /* remove us from the free space cache (if we're there at all) */
  5670. ret = btrfs_remove_free_space(cache, bytenr, num_bytes);
  5671. btrfs_put_block_group(cache);
  5672. return ret;
  5673. }
  5674. static int __exclude_logged_extent(struct btrfs_fs_info *fs_info,
  5675. u64 start, u64 num_bytes)
  5676. {
  5677. int ret;
  5678. struct btrfs_block_group_cache *block_group;
  5679. struct btrfs_caching_control *caching_ctl;
  5680. block_group = btrfs_lookup_block_group(fs_info, start);
  5681. if (!block_group)
  5682. return -EINVAL;
  5683. cache_block_group(block_group, 0);
  5684. caching_ctl = get_caching_control(block_group);
  5685. if (!caching_ctl) {
  5686. /* Logic error */
  5687. BUG_ON(!block_group_cache_done(block_group));
  5688. ret = btrfs_remove_free_space(block_group, start, num_bytes);
  5689. } else {
  5690. mutex_lock(&caching_ctl->mutex);
  5691. if (start >= caching_ctl->progress) {
  5692. ret = add_excluded_extent(fs_info, start, num_bytes);
  5693. } else if (start + num_bytes <= caching_ctl->progress) {
  5694. ret = btrfs_remove_free_space(block_group,
  5695. start, num_bytes);
  5696. } else {
  5697. num_bytes = caching_ctl->progress - start;
  5698. ret = btrfs_remove_free_space(block_group,
  5699. start, num_bytes);
  5700. if (ret)
  5701. goto out_lock;
  5702. num_bytes = (start + num_bytes) -
  5703. caching_ctl->progress;
  5704. start = caching_ctl->progress;
  5705. ret = add_excluded_extent(fs_info, start, num_bytes);
  5706. }
  5707. out_lock:
  5708. mutex_unlock(&caching_ctl->mutex);
  5709. put_caching_control(caching_ctl);
  5710. }
  5711. btrfs_put_block_group(block_group);
  5712. return ret;
  5713. }
  5714. int btrfs_exclude_logged_extents(struct btrfs_fs_info *fs_info,
  5715. struct extent_buffer *eb)
  5716. {
  5717. struct btrfs_file_extent_item *item;
  5718. struct btrfs_key key;
  5719. int found_type;
  5720. int i;
  5721. if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS))
  5722. return 0;
  5723. for (i = 0; i < btrfs_header_nritems(eb); i++) {
  5724. btrfs_item_key_to_cpu(eb, &key, i);
  5725. if (key.type != BTRFS_EXTENT_DATA_KEY)
  5726. continue;
  5727. item = btrfs_item_ptr(eb, i, struct btrfs_file_extent_item);
  5728. found_type = btrfs_file_extent_type(eb, item);
  5729. if (found_type == BTRFS_FILE_EXTENT_INLINE)
  5730. continue;
  5731. if (btrfs_file_extent_disk_bytenr(eb, item) == 0)
  5732. continue;
  5733. key.objectid = btrfs_file_extent_disk_bytenr(eb, item);
  5734. key.offset = btrfs_file_extent_disk_num_bytes(eb, item);
  5735. __exclude_logged_extent(fs_info, key.objectid, key.offset);
  5736. }
  5737. return 0;
  5738. }
  5739. static void
  5740. btrfs_inc_block_group_reservations(struct btrfs_block_group_cache *bg)
  5741. {
  5742. atomic_inc(&bg->reservations);
  5743. }
  5744. void btrfs_dec_block_group_reservations(struct btrfs_fs_info *fs_info,
  5745. const u64 start)
  5746. {
  5747. struct btrfs_block_group_cache *bg;
  5748. bg = btrfs_lookup_block_group(fs_info, start);
  5749. ASSERT(bg);
  5750. if (atomic_dec_and_test(&bg->reservations))
  5751. wake_up_atomic_t(&bg->reservations);
  5752. btrfs_put_block_group(bg);
  5753. }
  5754. void btrfs_wait_block_group_reservations(struct btrfs_block_group_cache *bg)
  5755. {
  5756. struct btrfs_space_info *space_info = bg->space_info;
  5757. ASSERT(bg->ro);
  5758. if (!(bg->flags & BTRFS_BLOCK_GROUP_DATA))
  5759. return;
  5760. /*
  5761. * Our block group is read only but before we set it to read only,
  5762. * some task might have had allocated an extent from it already, but it
  5763. * has not yet created a respective ordered extent (and added it to a
  5764. * root's list of ordered extents).
  5765. * Therefore wait for any task currently allocating extents, since the
  5766. * block group's reservations counter is incremented while a read lock
  5767. * on the groups' semaphore is held and decremented after releasing
  5768. * the read access on that semaphore and creating the ordered extent.
  5769. */
  5770. down_write(&space_info->groups_sem);
  5771. up_write(&space_info->groups_sem);
  5772. wait_on_atomic_t(&bg->reservations, atomic_t_wait,
  5773. TASK_UNINTERRUPTIBLE);
  5774. }
  5775. /**
  5776. * btrfs_add_reserved_bytes - update the block_group and space info counters
  5777. * @cache: The cache we are manipulating
  5778. * @ram_bytes: The number of bytes of file content, and will be same to
  5779. * @num_bytes except for the compress path.
  5780. * @num_bytes: The number of bytes in question
  5781. * @delalloc: The blocks are allocated for the delalloc write
  5782. *
  5783. * This is called by the allocator when it reserves space. If this is a
  5784. * reservation and the block group has become read only we cannot make the
  5785. * reservation and return -EAGAIN, otherwise this function always succeeds.
  5786. */
  5787. static int btrfs_add_reserved_bytes(struct btrfs_block_group_cache *cache,
  5788. u64 ram_bytes, u64 num_bytes, int delalloc)
  5789. {
  5790. struct btrfs_space_info *space_info = cache->space_info;
  5791. int ret = 0;
  5792. spin_lock(&space_info->lock);
  5793. spin_lock(&cache->lock);
  5794. if (cache->ro) {
  5795. ret = -EAGAIN;
  5796. } else {
  5797. cache->reserved += num_bytes;
  5798. space_info->bytes_reserved += num_bytes;
  5799. trace_btrfs_space_reservation(cache->fs_info,
  5800. "space_info", space_info->flags,
  5801. ram_bytes, 0);
  5802. space_info->bytes_may_use -= ram_bytes;
  5803. if (delalloc)
  5804. cache->delalloc_bytes += num_bytes;
  5805. }
  5806. spin_unlock(&cache->lock);
  5807. spin_unlock(&space_info->lock);
  5808. return ret;
  5809. }
  5810. /**
  5811. * btrfs_free_reserved_bytes - update the block_group and space info counters
  5812. * @cache: The cache we are manipulating
  5813. * @num_bytes: The number of bytes in question
  5814. * @delalloc: The blocks are allocated for the delalloc write
  5815. *
  5816. * This is called by somebody who is freeing space that was never actually used
  5817. * on disk. For example if you reserve some space for a new leaf in transaction
  5818. * A and before transaction A commits you free that leaf, you call this with
  5819. * reserve set to 0 in order to clear the reservation.
  5820. */
  5821. static int btrfs_free_reserved_bytes(struct btrfs_block_group_cache *cache,
  5822. u64 num_bytes, int delalloc)
  5823. {
  5824. struct btrfs_space_info *space_info = cache->space_info;
  5825. int ret = 0;
  5826. spin_lock(&space_info->lock);
  5827. spin_lock(&cache->lock);
  5828. if (cache->ro)
  5829. space_info->bytes_readonly += num_bytes;
  5830. cache->reserved -= num_bytes;
  5831. space_info->bytes_reserved -= num_bytes;
  5832. if (delalloc)
  5833. cache->delalloc_bytes -= num_bytes;
  5834. spin_unlock(&cache->lock);
  5835. spin_unlock(&space_info->lock);
  5836. return ret;
  5837. }
  5838. void btrfs_prepare_extent_commit(struct btrfs_fs_info *fs_info)
  5839. {
  5840. struct btrfs_caching_control *next;
  5841. struct btrfs_caching_control *caching_ctl;
  5842. struct btrfs_block_group_cache *cache;
  5843. down_write(&fs_info->commit_root_sem);
  5844. list_for_each_entry_safe(caching_ctl, next,
  5845. &fs_info->caching_block_groups, list) {
  5846. cache = caching_ctl->block_group;
  5847. if (block_group_cache_done(cache)) {
  5848. cache->last_byte_to_unpin = (u64)-1;
  5849. list_del_init(&caching_ctl->list);
  5850. put_caching_control(caching_ctl);
  5851. } else {
  5852. cache->last_byte_to_unpin = caching_ctl->progress;
  5853. }
  5854. }
  5855. if (fs_info->pinned_extents == &fs_info->freed_extents[0])
  5856. fs_info->pinned_extents = &fs_info->freed_extents[1];
  5857. else
  5858. fs_info->pinned_extents = &fs_info->freed_extents[0];
  5859. up_write(&fs_info->commit_root_sem);
  5860. update_global_block_rsv(fs_info);
  5861. }
  5862. /*
  5863. * Returns the free cluster for the given space info and sets empty_cluster to
  5864. * what it should be based on the mount options.
  5865. */
  5866. static struct btrfs_free_cluster *
  5867. fetch_cluster_info(struct btrfs_fs_info *fs_info,
  5868. struct btrfs_space_info *space_info, u64 *empty_cluster)
  5869. {
  5870. struct btrfs_free_cluster *ret = NULL;
  5871. *empty_cluster = 0;
  5872. if (btrfs_mixed_space_info(space_info))
  5873. return ret;
  5874. if (space_info->flags & BTRFS_BLOCK_GROUP_METADATA) {
  5875. ret = &fs_info->meta_alloc_cluster;
  5876. if (btrfs_test_opt(fs_info, SSD))
  5877. *empty_cluster = SZ_2M;
  5878. else
  5879. *empty_cluster = SZ_64K;
  5880. } else if ((space_info->flags & BTRFS_BLOCK_GROUP_DATA) &&
  5881. btrfs_test_opt(fs_info, SSD_SPREAD)) {
  5882. *empty_cluster = SZ_2M;
  5883. ret = &fs_info->data_alloc_cluster;
  5884. }
  5885. return ret;
  5886. }
  5887. static int unpin_extent_range(struct btrfs_fs_info *fs_info,
  5888. u64 start, u64 end,
  5889. const bool return_free_space)
  5890. {
  5891. struct btrfs_block_group_cache *cache = NULL;
  5892. struct btrfs_space_info *space_info;
  5893. struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
  5894. struct btrfs_free_cluster *cluster = NULL;
  5895. u64 len;
  5896. u64 total_unpinned = 0;
  5897. u64 empty_cluster = 0;
  5898. bool readonly;
  5899. while (start <= end) {
  5900. readonly = false;
  5901. if (!cache ||
  5902. start >= cache->key.objectid + cache->key.offset) {
  5903. if (cache)
  5904. btrfs_put_block_group(cache);
  5905. total_unpinned = 0;
  5906. cache = btrfs_lookup_block_group(fs_info, start);
  5907. BUG_ON(!cache); /* Logic error */
  5908. cluster = fetch_cluster_info(fs_info,
  5909. cache->space_info,
  5910. &empty_cluster);
  5911. empty_cluster <<= 1;
  5912. }
  5913. len = cache->key.objectid + cache->key.offset - start;
  5914. len = min(len, end + 1 - start);
  5915. if (start < cache->last_byte_to_unpin) {
  5916. len = min(len, cache->last_byte_to_unpin - start);
  5917. if (return_free_space)
  5918. btrfs_add_free_space(cache, start, len);
  5919. }
  5920. start += len;
  5921. total_unpinned += len;
  5922. space_info = cache->space_info;
  5923. /*
  5924. * If this space cluster has been marked as fragmented and we've
  5925. * unpinned enough in this block group to potentially allow a
  5926. * cluster to be created inside of it go ahead and clear the
  5927. * fragmented check.
  5928. */
  5929. if (cluster && cluster->fragmented &&
  5930. total_unpinned > empty_cluster) {
  5931. spin_lock(&cluster->lock);
  5932. cluster->fragmented = 0;
  5933. spin_unlock(&cluster->lock);
  5934. }
  5935. spin_lock(&space_info->lock);
  5936. spin_lock(&cache->lock);
  5937. cache->pinned -= len;
  5938. space_info->bytes_pinned -= len;
  5939. trace_btrfs_space_reservation(fs_info, "pinned",
  5940. space_info->flags, len, 0);
  5941. space_info->max_extent_size = 0;
  5942. percpu_counter_add(&space_info->total_bytes_pinned, -len);
  5943. if (cache->ro) {
  5944. space_info->bytes_readonly += len;
  5945. readonly = true;
  5946. }
  5947. spin_unlock(&cache->lock);
  5948. if (!readonly && return_free_space &&
  5949. global_rsv->space_info == space_info) {
  5950. u64 to_add = len;
  5951. spin_lock(&global_rsv->lock);
  5952. if (!global_rsv->full) {
  5953. to_add = min(len, global_rsv->size -
  5954. global_rsv->reserved);
  5955. global_rsv->reserved += to_add;
  5956. space_info->bytes_may_use += to_add;
  5957. if (global_rsv->reserved >= global_rsv->size)
  5958. global_rsv->full = 1;
  5959. trace_btrfs_space_reservation(fs_info,
  5960. "space_info",
  5961. space_info->flags,
  5962. to_add, 1);
  5963. len -= to_add;
  5964. }
  5965. spin_unlock(&global_rsv->lock);
  5966. /* Add to any tickets we may have */
  5967. if (len)
  5968. space_info_add_new_bytes(fs_info, space_info,
  5969. len);
  5970. }
  5971. spin_unlock(&space_info->lock);
  5972. }
  5973. if (cache)
  5974. btrfs_put_block_group(cache);
  5975. return 0;
  5976. }
  5977. int btrfs_finish_extent_commit(struct btrfs_trans_handle *trans,
  5978. struct btrfs_fs_info *fs_info)
  5979. {
  5980. struct btrfs_block_group_cache *block_group, *tmp;
  5981. struct list_head *deleted_bgs;
  5982. struct extent_io_tree *unpin;
  5983. u64 start;
  5984. u64 end;
  5985. int ret;
  5986. if (fs_info->pinned_extents == &fs_info->freed_extents[0])
  5987. unpin = &fs_info->freed_extents[1];
  5988. else
  5989. unpin = &fs_info->freed_extents[0];
  5990. while (!trans->aborted) {
  5991. mutex_lock(&fs_info->unused_bg_unpin_mutex);
  5992. ret = find_first_extent_bit(unpin, 0, &start, &end,
  5993. EXTENT_DIRTY, NULL);
  5994. if (ret) {
  5995. mutex_unlock(&fs_info->unused_bg_unpin_mutex);
  5996. break;
  5997. }
  5998. if (btrfs_test_opt(fs_info, DISCARD))
  5999. ret = btrfs_discard_extent(fs_info, start,
  6000. end + 1 - start, NULL);
  6001. clear_extent_dirty(unpin, start, end);
  6002. unpin_extent_range(fs_info, start, end, true);
  6003. mutex_unlock(&fs_info->unused_bg_unpin_mutex);
  6004. cond_resched();
  6005. }
  6006. /*
  6007. * Transaction is finished. We don't need the lock anymore. We
  6008. * do need to clean up the block groups in case of a transaction
  6009. * abort.
  6010. */
  6011. deleted_bgs = &trans->transaction->deleted_bgs;
  6012. list_for_each_entry_safe(block_group, tmp, deleted_bgs, bg_list) {
  6013. u64 trimmed = 0;
  6014. ret = -EROFS;
  6015. if (!trans->aborted)
  6016. ret = btrfs_discard_extent(fs_info,
  6017. block_group->key.objectid,
  6018. block_group->key.offset,
  6019. &trimmed);
  6020. list_del_init(&block_group->bg_list);
  6021. btrfs_put_block_group_trimming(block_group);
  6022. btrfs_put_block_group(block_group);
  6023. if (ret) {
  6024. const char *errstr = btrfs_decode_error(ret);
  6025. btrfs_warn(fs_info,
  6026. "discard failed while removing blockgroup: errno=%d %s",
  6027. ret, errstr);
  6028. }
  6029. }
  6030. return 0;
  6031. }
  6032. static int __btrfs_free_extent(struct btrfs_trans_handle *trans,
  6033. struct btrfs_fs_info *info,
  6034. struct btrfs_delayed_ref_node *node, u64 parent,
  6035. u64 root_objectid, u64 owner_objectid,
  6036. u64 owner_offset, int refs_to_drop,
  6037. struct btrfs_delayed_extent_op *extent_op)
  6038. {
  6039. struct btrfs_key key;
  6040. struct btrfs_path *path;
  6041. struct btrfs_root *extent_root = info->extent_root;
  6042. struct extent_buffer *leaf;
  6043. struct btrfs_extent_item *ei;
  6044. struct btrfs_extent_inline_ref *iref;
  6045. int ret;
  6046. int is_data;
  6047. int extent_slot = 0;
  6048. int found_extent = 0;
  6049. int num_to_del = 1;
  6050. u32 item_size;
  6051. u64 refs;
  6052. u64 bytenr = node->bytenr;
  6053. u64 num_bytes = node->num_bytes;
  6054. int last_ref = 0;
  6055. bool skinny_metadata = btrfs_fs_incompat(info, SKINNY_METADATA);
  6056. path = btrfs_alloc_path();
  6057. if (!path)
  6058. return -ENOMEM;
  6059. path->reada = READA_FORWARD;
  6060. path->leave_spinning = 1;
  6061. is_data = owner_objectid >= BTRFS_FIRST_FREE_OBJECTID;
  6062. BUG_ON(!is_data && refs_to_drop != 1);
  6063. if (is_data)
  6064. skinny_metadata = false;
  6065. ret = lookup_extent_backref(trans, info, path, &iref,
  6066. bytenr, num_bytes, parent,
  6067. root_objectid, owner_objectid,
  6068. owner_offset);
  6069. if (ret == 0) {
  6070. extent_slot = path->slots[0];
  6071. while (extent_slot >= 0) {
  6072. btrfs_item_key_to_cpu(path->nodes[0], &key,
  6073. extent_slot);
  6074. if (key.objectid != bytenr)
  6075. break;
  6076. if (key.type == BTRFS_EXTENT_ITEM_KEY &&
  6077. key.offset == num_bytes) {
  6078. found_extent = 1;
  6079. break;
  6080. }
  6081. if (key.type == BTRFS_METADATA_ITEM_KEY &&
  6082. key.offset == owner_objectid) {
  6083. found_extent = 1;
  6084. break;
  6085. }
  6086. if (path->slots[0] - extent_slot > 5)
  6087. break;
  6088. extent_slot--;
  6089. }
  6090. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  6091. item_size = btrfs_item_size_nr(path->nodes[0], extent_slot);
  6092. if (found_extent && item_size < sizeof(*ei))
  6093. found_extent = 0;
  6094. #endif
  6095. if (!found_extent) {
  6096. BUG_ON(iref);
  6097. ret = remove_extent_backref(trans, info, path, NULL,
  6098. refs_to_drop,
  6099. is_data, &last_ref);
  6100. if (ret) {
  6101. btrfs_abort_transaction(trans, ret);
  6102. goto out;
  6103. }
  6104. btrfs_release_path(path);
  6105. path->leave_spinning = 1;
  6106. key.objectid = bytenr;
  6107. key.type = BTRFS_EXTENT_ITEM_KEY;
  6108. key.offset = num_bytes;
  6109. if (!is_data && skinny_metadata) {
  6110. key.type = BTRFS_METADATA_ITEM_KEY;
  6111. key.offset = owner_objectid;
  6112. }
  6113. ret = btrfs_search_slot(trans, extent_root,
  6114. &key, path, -1, 1);
  6115. if (ret > 0 && skinny_metadata && path->slots[0]) {
  6116. /*
  6117. * Couldn't find our skinny metadata item,
  6118. * see if we have ye olde extent item.
  6119. */
  6120. path->slots[0]--;
  6121. btrfs_item_key_to_cpu(path->nodes[0], &key,
  6122. path->slots[0]);
  6123. if (key.objectid == bytenr &&
  6124. key.type == BTRFS_EXTENT_ITEM_KEY &&
  6125. key.offset == num_bytes)
  6126. ret = 0;
  6127. }
  6128. if (ret > 0 && skinny_metadata) {
  6129. skinny_metadata = false;
  6130. key.objectid = bytenr;
  6131. key.type = BTRFS_EXTENT_ITEM_KEY;
  6132. key.offset = num_bytes;
  6133. btrfs_release_path(path);
  6134. ret = btrfs_search_slot(trans, extent_root,
  6135. &key, path, -1, 1);
  6136. }
  6137. if (ret) {
  6138. btrfs_err(info,
  6139. "umm, got %d back from search, was looking for %llu",
  6140. ret, bytenr);
  6141. if (ret > 0)
  6142. btrfs_print_leaf(path->nodes[0]);
  6143. }
  6144. if (ret < 0) {
  6145. btrfs_abort_transaction(trans, ret);
  6146. goto out;
  6147. }
  6148. extent_slot = path->slots[0];
  6149. }
  6150. } else if (WARN_ON(ret == -ENOENT)) {
  6151. btrfs_print_leaf(path->nodes[0]);
  6152. btrfs_err(info,
  6153. "unable to find ref byte nr %llu parent %llu root %llu owner %llu offset %llu",
  6154. bytenr, parent, root_objectid, owner_objectid,
  6155. owner_offset);
  6156. btrfs_abort_transaction(trans, ret);
  6157. goto out;
  6158. } else {
  6159. btrfs_abort_transaction(trans, ret);
  6160. goto out;
  6161. }
  6162. leaf = path->nodes[0];
  6163. item_size = btrfs_item_size_nr(leaf, extent_slot);
  6164. #ifdef BTRFS_COMPAT_EXTENT_TREE_V0
  6165. if (item_size < sizeof(*ei)) {
  6166. BUG_ON(found_extent || extent_slot != path->slots[0]);
  6167. ret = convert_extent_item_v0(trans, info, path, owner_objectid,
  6168. 0);
  6169. if (ret < 0) {
  6170. btrfs_abort_transaction(trans, ret);
  6171. goto out;
  6172. }
  6173. btrfs_release_path(path);
  6174. path->leave_spinning = 1;
  6175. key.objectid = bytenr;
  6176. key.type = BTRFS_EXTENT_ITEM_KEY;
  6177. key.offset = num_bytes;
  6178. ret = btrfs_search_slot(trans, extent_root, &key, path,
  6179. -1, 1);
  6180. if (ret) {
  6181. btrfs_err(info,
  6182. "umm, got %d back from search, was looking for %llu",
  6183. ret, bytenr);
  6184. btrfs_print_leaf(path->nodes[0]);
  6185. }
  6186. if (ret < 0) {
  6187. btrfs_abort_transaction(trans, ret);
  6188. goto out;
  6189. }
  6190. extent_slot = path->slots[0];
  6191. leaf = path->nodes[0];
  6192. item_size = btrfs_item_size_nr(leaf, extent_slot);
  6193. }
  6194. #endif
  6195. BUG_ON(item_size < sizeof(*ei));
  6196. ei = btrfs_item_ptr(leaf, extent_slot,
  6197. struct btrfs_extent_item);
  6198. if (owner_objectid < BTRFS_FIRST_FREE_OBJECTID &&
  6199. key.type == BTRFS_EXTENT_ITEM_KEY) {
  6200. struct btrfs_tree_block_info *bi;
  6201. BUG_ON(item_size < sizeof(*ei) + sizeof(*bi));
  6202. bi = (struct btrfs_tree_block_info *)(ei + 1);
  6203. WARN_ON(owner_objectid != btrfs_tree_block_level(leaf, bi));
  6204. }
  6205. refs = btrfs_extent_refs(leaf, ei);
  6206. if (refs < refs_to_drop) {
  6207. btrfs_err(info,
  6208. "trying to drop %d refs but we only have %Lu for bytenr %Lu",
  6209. refs_to_drop, refs, bytenr);
  6210. ret = -EINVAL;
  6211. btrfs_abort_transaction(trans, ret);
  6212. goto out;
  6213. }
  6214. refs -= refs_to_drop;
  6215. if (refs > 0) {
  6216. if (extent_op)
  6217. __run_delayed_extent_op(extent_op, leaf, ei);
  6218. /*
  6219. * In the case of inline back ref, reference count will
  6220. * be updated by remove_extent_backref
  6221. */
  6222. if (iref) {
  6223. BUG_ON(!found_extent);
  6224. } else {
  6225. btrfs_set_extent_refs(leaf, ei, refs);
  6226. btrfs_mark_buffer_dirty(leaf);
  6227. }
  6228. if (found_extent) {
  6229. ret = remove_extent_backref(trans, info, path,
  6230. iref, refs_to_drop,
  6231. is_data, &last_ref);
  6232. if (ret) {
  6233. btrfs_abort_transaction(trans, ret);
  6234. goto out;
  6235. }
  6236. }
  6237. } else {
  6238. if (found_extent) {
  6239. BUG_ON(is_data && refs_to_drop !=
  6240. extent_data_ref_count(path, iref));
  6241. if (iref) {
  6242. BUG_ON(path->slots[0] != extent_slot);
  6243. } else {
  6244. BUG_ON(path->slots[0] != extent_slot + 1);
  6245. path->slots[0] = extent_slot;
  6246. num_to_del = 2;
  6247. }
  6248. }
  6249. last_ref = 1;
  6250. ret = btrfs_del_items(trans, extent_root, path, path->slots[0],
  6251. num_to_del);
  6252. if (ret) {
  6253. btrfs_abort_transaction(trans, ret);
  6254. goto out;
  6255. }
  6256. btrfs_release_path(path);
  6257. if (is_data) {
  6258. ret = btrfs_del_csums(trans, info, bytenr, num_bytes);
  6259. if (ret) {
  6260. btrfs_abort_transaction(trans, ret);
  6261. goto out;
  6262. }
  6263. }
  6264. ret = add_to_free_space_tree(trans, info, bytenr, num_bytes);
  6265. if (ret) {
  6266. btrfs_abort_transaction(trans, ret);
  6267. goto out;
  6268. }
  6269. ret = update_block_group(trans, info, bytenr, num_bytes, 0);
  6270. if (ret) {
  6271. btrfs_abort_transaction(trans, ret);
  6272. goto out;
  6273. }
  6274. }
  6275. btrfs_release_path(path);
  6276. out:
  6277. btrfs_free_path(path);
  6278. return ret;
  6279. }
  6280. /*
  6281. * when we free an block, it is possible (and likely) that we free the last
  6282. * delayed ref for that extent as well. This searches the delayed ref tree for
  6283. * a given extent, and if there are no other delayed refs to be processed, it
  6284. * removes it from the tree.
  6285. */
  6286. static noinline int check_ref_cleanup(struct btrfs_trans_handle *trans,
  6287. u64 bytenr)
  6288. {
  6289. struct btrfs_delayed_ref_head *head;
  6290. struct btrfs_delayed_ref_root *delayed_refs;
  6291. int ret = 0;
  6292. delayed_refs = &trans->transaction->delayed_refs;
  6293. spin_lock(&delayed_refs->lock);
  6294. head = btrfs_find_delayed_ref_head(delayed_refs, bytenr);
  6295. if (!head)
  6296. goto out_delayed_unlock;
  6297. spin_lock(&head->lock);
  6298. if (!RB_EMPTY_ROOT(&head->ref_tree))
  6299. goto out;
  6300. if (head->extent_op) {
  6301. if (!head->must_insert_reserved)
  6302. goto out;
  6303. btrfs_free_delayed_extent_op(head->extent_op);
  6304. head->extent_op = NULL;
  6305. }
  6306. /*
  6307. * waiting for the lock here would deadlock. If someone else has it
  6308. * locked they are already in the process of dropping it anyway
  6309. */
  6310. if (!mutex_trylock(&head->mutex))
  6311. goto out;
  6312. /*
  6313. * at this point we have a head with no other entries. Go
  6314. * ahead and process it.
  6315. */
  6316. rb_erase(&head->href_node, &delayed_refs->href_root);
  6317. RB_CLEAR_NODE(&head->href_node);
  6318. atomic_dec(&delayed_refs->num_entries);
  6319. /*
  6320. * we don't take a ref on the node because we're removing it from the
  6321. * tree, so we just steal the ref the tree was holding.
  6322. */
  6323. delayed_refs->num_heads--;
  6324. if (head->processing == 0)
  6325. delayed_refs->num_heads_ready--;
  6326. head->processing = 0;
  6327. spin_unlock(&head->lock);
  6328. spin_unlock(&delayed_refs->lock);
  6329. BUG_ON(head->extent_op);
  6330. if (head->must_insert_reserved)
  6331. ret = 1;
  6332. mutex_unlock(&head->mutex);
  6333. btrfs_put_delayed_ref_head(head);
  6334. return ret;
  6335. out:
  6336. spin_unlock(&head->lock);
  6337. out_delayed_unlock:
  6338. spin_unlock(&delayed_refs->lock);
  6339. return 0;
  6340. }
  6341. void btrfs_free_tree_block(struct btrfs_trans_handle *trans,
  6342. struct btrfs_root *root,
  6343. struct extent_buffer *buf,
  6344. u64 parent, int last_ref)
  6345. {
  6346. struct btrfs_fs_info *fs_info = root->fs_info;
  6347. int pin = 1;
  6348. int ret;
  6349. if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
  6350. int old_ref_mod, new_ref_mod;
  6351. btrfs_ref_tree_mod(root, buf->start, buf->len, parent,
  6352. root->root_key.objectid,
  6353. btrfs_header_level(buf), 0,
  6354. BTRFS_DROP_DELAYED_REF);
  6355. ret = btrfs_add_delayed_tree_ref(fs_info, trans, buf->start,
  6356. buf->len, parent,
  6357. root->root_key.objectid,
  6358. btrfs_header_level(buf),
  6359. BTRFS_DROP_DELAYED_REF, NULL,
  6360. &old_ref_mod, &new_ref_mod);
  6361. BUG_ON(ret); /* -ENOMEM */
  6362. pin = old_ref_mod >= 0 && new_ref_mod < 0;
  6363. }
  6364. if (last_ref && btrfs_header_generation(buf) == trans->transid) {
  6365. struct btrfs_block_group_cache *cache;
  6366. if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID) {
  6367. ret = check_ref_cleanup(trans, buf->start);
  6368. if (!ret)
  6369. goto out;
  6370. }
  6371. pin = 0;
  6372. cache = btrfs_lookup_block_group(fs_info, buf->start);
  6373. if (btrfs_header_flag(buf, BTRFS_HEADER_FLAG_WRITTEN)) {
  6374. pin_down_extent(fs_info, cache, buf->start,
  6375. buf->len, 1);
  6376. btrfs_put_block_group(cache);
  6377. goto out;
  6378. }
  6379. WARN_ON(test_bit(EXTENT_BUFFER_DIRTY, &buf->bflags));
  6380. btrfs_add_free_space(cache, buf->start, buf->len);
  6381. btrfs_free_reserved_bytes(cache, buf->len, 0);
  6382. btrfs_put_block_group(cache);
  6383. trace_btrfs_reserved_extent_free(fs_info, buf->start, buf->len);
  6384. }
  6385. out:
  6386. if (pin)
  6387. add_pinned_bytes(fs_info, buf->len, btrfs_header_level(buf),
  6388. root->root_key.objectid);
  6389. if (last_ref) {
  6390. /*
  6391. * Deleting the buffer, clear the corrupt flag since it doesn't
  6392. * matter anymore.
  6393. */
  6394. clear_bit(EXTENT_BUFFER_CORRUPT, &buf->bflags);
  6395. }
  6396. }
  6397. /* Can return -ENOMEM */
  6398. int btrfs_free_extent(struct btrfs_trans_handle *trans,
  6399. struct btrfs_root *root,
  6400. u64 bytenr, u64 num_bytes, u64 parent, u64 root_objectid,
  6401. u64 owner, u64 offset)
  6402. {
  6403. struct btrfs_fs_info *fs_info = root->fs_info;
  6404. int old_ref_mod, new_ref_mod;
  6405. int ret;
  6406. if (btrfs_is_testing(fs_info))
  6407. return 0;
  6408. if (root_objectid != BTRFS_TREE_LOG_OBJECTID)
  6409. btrfs_ref_tree_mod(root, bytenr, num_bytes, parent,
  6410. root_objectid, owner, offset,
  6411. BTRFS_DROP_DELAYED_REF);
  6412. /*
  6413. * tree log blocks never actually go into the extent allocation
  6414. * tree, just update pinning info and exit early.
  6415. */
  6416. if (root_objectid == BTRFS_TREE_LOG_OBJECTID) {
  6417. WARN_ON(owner >= BTRFS_FIRST_FREE_OBJECTID);
  6418. /* unlocks the pinned mutex */
  6419. btrfs_pin_extent(fs_info, bytenr, num_bytes, 1);
  6420. old_ref_mod = new_ref_mod = 0;
  6421. ret = 0;
  6422. } else if (owner < BTRFS_FIRST_FREE_OBJECTID) {
  6423. ret = btrfs_add_delayed_tree_ref(fs_info, trans, bytenr,
  6424. num_bytes, parent,
  6425. root_objectid, (int)owner,
  6426. BTRFS_DROP_DELAYED_REF, NULL,
  6427. &old_ref_mod, &new_ref_mod);
  6428. } else {
  6429. ret = btrfs_add_delayed_data_ref(fs_info, trans, bytenr,
  6430. num_bytes, parent,
  6431. root_objectid, owner, offset,
  6432. 0, BTRFS_DROP_DELAYED_REF,
  6433. &old_ref_mod, &new_ref_mod);
  6434. }
  6435. if (ret == 0 && old_ref_mod >= 0 && new_ref_mod < 0)
  6436. add_pinned_bytes(fs_info, num_bytes, owner, root_objectid);
  6437. return ret;
  6438. }
  6439. /*
  6440. * when we wait for progress in the block group caching, its because
  6441. * our allocation attempt failed at least once. So, we must sleep
  6442. * and let some progress happen before we try again.
  6443. *
  6444. * This function will sleep at least once waiting for new free space to
  6445. * show up, and then it will check the block group free space numbers
  6446. * for our min num_bytes. Another option is to have it go ahead
  6447. * and look in the rbtree for a free extent of a given size, but this
  6448. * is a good start.
  6449. *
  6450. * Callers of this must check if cache->cached == BTRFS_CACHE_ERROR before using
  6451. * any of the information in this block group.
  6452. */
  6453. static noinline void
  6454. wait_block_group_cache_progress(struct btrfs_block_group_cache *cache,
  6455. u64 num_bytes)
  6456. {
  6457. struct btrfs_caching_control *caching_ctl;
  6458. caching_ctl = get_caching_control(cache);
  6459. if (!caching_ctl)
  6460. return;
  6461. wait_event(caching_ctl->wait, block_group_cache_done(cache) ||
  6462. (cache->free_space_ctl->free_space >= num_bytes));
  6463. put_caching_control(caching_ctl);
  6464. }
  6465. static noinline int
  6466. wait_block_group_cache_done(struct btrfs_block_group_cache *cache)
  6467. {
  6468. struct btrfs_caching_control *caching_ctl;
  6469. int ret = 0;
  6470. caching_ctl = get_caching_control(cache);
  6471. if (!caching_ctl)
  6472. return (cache->cached == BTRFS_CACHE_ERROR) ? -EIO : 0;
  6473. wait_event(caching_ctl->wait, block_group_cache_done(cache));
  6474. if (cache->cached == BTRFS_CACHE_ERROR)
  6475. ret = -EIO;
  6476. put_caching_control(caching_ctl);
  6477. return ret;
  6478. }
  6479. int __get_raid_index(u64 flags)
  6480. {
  6481. if (flags & BTRFS_BLOCK_GROUP_RAID10)
  6482. return BTRFS_RAID_RAID10;
  6483. else if (flags & BTRFS_BLOCK_GROUP_RAID1)
  6484. return BTRFS_RAID_RAID1;
  6485. else if (flags & BTRFS_BLOCK_GROUP_DUP)
  6486. return BTRFS_RAID_DUP;
  6487. else if (flags & BTRFS_BLOCK_GROUP_RAID0)
  6488. return BTRFS_RAID_RAID0;
  6489. else if (flags & BTRFS_BLOCK_GROUP_RAID5)
  6490. return BTRFS_RAID_RAID5;
  6491. else if (flags & BTRFS_BLOCK_GROUP_RAID6)
  6492. return BTRFS_RAID_RAID6;
  6493. return BTRFS_RAID_SINGLE; /* BTRFS_BLOCK_GROUP_SINGLE */
  6494. }
  6495. int get_block_group_index(struct btrfs_block_group_cache *cache)
  6496. {
  6497. return __get_raid_index(cache->flags);
  6498. }
  6499. static const char *btrfs_raid_type_names[BTRFS_NR_RAID_TYPES] = {
  6500. [BTRFS_RAID_RAID10] = "raid10",
  6501. [BTRFS_RAID_RAID1] = "raid1",
  6502. [BTRFS_RAID_DUP] = "dup",
  6503. [BTRFS_RAID_RAID0] = "raid0",
  6504. [BTRFS_RAID_SINGLE] = "single",
  6505. [BTRFS_RAID_RAID5] = "raid5",
  6506. [BTRFS_RAID_RAID6] = "raid6",
  6507. };
  6508. static const char *get_raid_name(enum btrfs_raid_types type)
  6509. {
  6510. if (type >= BTRFS_NR_RAID_TYPES)
  6511. return NULL;
  6512. return btrfs_raid_type_names[type];
  6513. }
  6514. enum btrfs_loop_type {
  6515. LOOP_CACHING_NOWAIT = 0,
  6516. LOOP_CACHING_WAIT = 1,
  6517. LOOP_ALLOC_CHUNK = 2,
  6518. LOOP_NO_EMPTY_SIZE = 3,
  6519. };
  6520. static inline void
  6521. btrfs_lock_block_group(struct btrfs_block_group_cache *cache,
  6522. int delalloc)
  6523. {
  6524. if (delalloc)
  6525. down_read(&cache->data_rwsem);
  6526. }
  6527. static inline void
  6528. btrfs_grab_block_group(struct btrfs_block_group_cache *cache,
  6529. int delalloc)
  6530. {
  6531. btrfs_get_block_group(cache);
  6532. if (delalloc)
  6533. down_read(&cache->data_rwsem);
  6534. }
  6535. static struct btrfs_block_group_cache *
  6536. btrfs_lock_cluster(struct btrfs_block_group_cache *block_group,
  6537. struct btrfs_free_cluster *cluster,
  6538. int delalloc)
  6539. {
  6540. struct btrfs_block_group_cache *used_bg = NULL;
  6541. spin_lock(&cluster->refill_lock);
  6542. while (1) {
  6543. used_bg = cluster->block_group;
  6544. if (!used_bg)
  6545. return NULL;
  6546. if (used_bg == block_group)
  6547. return used_bg;
  6548. btrfs_get_block_group(used_bg);
  6549. if (!delalloc)
  6550. return used_bg;
  6551. if (down_read_trylock(&used_bg->data_rwsem))
  6552. return used_bg;
  6553. spin_unlock(&cluster->refill_lock);
  6554. /* We should only have one-level nested. */
  6555. down_read_nested(&used_bg->data_rwsem, SINGLE_DEPTH_NESTING);
  6556. spin_lock(&cluster->refill_lock);
  6557. if (used_bg == cluster->block_group)
  6558. return used_bg;
  6559. up_read(&used_bg->data_rwsem);
  6560. btrfs_put_block_group(used_bg);
  6561. }
  6562. }
  6563. static inline void
  6564. btrfs_release_block_group(struct btrfs_block_group_cache *cache,
  6565. int delalloc)
  6566. {
  6567. if (delalloc)
  6568. up_read(&cache->data_rwsem);
  6569. btrfs_put_block_group(cache);
  6570. }
  6571. /*
  6572. * walks the btree of allocated extents and find a hole of a given size.
  6573. * The key ins is changed to record the hole:
  6574. * ins->objectid == start position
  6575. * ins->flags = BTRFS_EXTENT_ITEM_KEY
  6576. * ins->offset == the size of the hole.
  6577. * Any available blocks before search_start are skipped.
  6578. *
  6579. * If there is no suitable free space, we will record the max size of
  6580. * the free space extent currently.
  6581. */
  6582. static noinline int find_free_extent(struct btrfs_fs_info *fs_info,
  6583. u64 ram_bytes, u64 num_bytes, u64 empty_size,
  6584. u64 hint_byte, struct btrfs_key *ins,
  6585. u64 flags, int delalloc)
  6586. {
  6587. int ret = 0;
  6588. struct btrfs_root *root = fs_info->extent_root;
  6589. struct btrfs_free_cluster *last_ptr = NULL;
  6590. struct btrfs_block_group_cache *block_group = NULL;
  6591. u64 search_start = 0;
  6592. u64 max_extent_size = 0;
  6593. u64 empty_cluster = 0;
  6594. struct btrfs_space_info *space_info;
  6595. int loop = 0;
  6596. int index = __get_raid_index(flags);
  6597. bool failed_cluster_refill = false;
  6598. bool failed_alloc = false;
  6599. bool use_cluster = true;
  6600. bool have_caching_bg = false;
  6601. bool orig_have_caching_bg = false;
  6602. bool full_search = false;
  6603. WARN_ON(num_bytes < fs_info->sectorsize);
  6604. ins->type = BTRFS_EXTENT_ITEM_KEY;
  6605. ins->objectid = 0;
  6606. ins->offset = 0;
  6607. trace_find_free_extent(fs_info, num_bytes, empty_size, flags);
  6608. space_info = __find_space_info(fs_info, flags);
  6609. if (!space_info) {
  6610. btrfs_err(fs_info, "No space info for %llu", flags);
  6611. return -ENOSPC;
  6612. }
  6613. /*
  6614. * If our free space is heavily fragmented we may not be able to make
  6615. * big contiguous allocations, so instead of doing the expensive search
  6616. * for free space, simply return ENOSPC with our max_extent_size so we
  6617. * can go ahead and search for a more manageable chunk.
  6618. *
  6619. * If our max_extent_size is large enough for our allocation simply
  6620. * disable clustering since we will likely not be able to find enough
  6621. * space to create a cluster and induce latency trying.
  6622. */
  6623. if (unlikely(space_info->max_extent_size)) {
  6624. spin_lock(&space_info->lock);
  6625. if (space_info->max_extent_size &&
  6626. num_bytes > space_info->max_extent_size) {
  6627. ins->offset = space_info->max_extent_size;
  6628. spin_unlock(&space_info->lock);
  6629. return -ENOSPC;
  6630. } else if (space_info->max_extent_size) {
  6631. use_cluster = false;
  6632. }
  6633. spin_unlock(&space_info->lock);
  6634. }
  6635. last_ptr = fetch_cluster_info(fs_info, space_info, &empty_cluster);
  6636. if (last_ptr) {
  6637. spin_lock(&last_ptr->lock);
  6638. if (last_ptr->block_group)
  6639. hint_byte = last_ptr->window_start;
  6640. if (last_ptr->fragmented) {
  6641. /*
  6642. * We still set window_start so we can keep track of the
  6643. * last place we found an allocation to try and save
  6644. * some time.
  6645. */
  6646. hint_byte = last_ptr->window_start;
  6647. use_cluster = false;
  6648. }
  6649. spin_unlock(&last_ptr->lock);
  6650. }
  6651. search_start = max(search_start, first_logical_byte(fs_info, 0));
  6652. search_start = max(search_start, hint_byte);
  6653. if (search_start == hint_byte) {
  6654. block_group = btrfs_lookup_block_group(fs_info, search_start);
  6655. /*
  6656. * we don't want to use the block group if it doesn't match our
  6657. * allocation bits, or if its not cached.
  6658. *
  6659. * However if we are re-searching with an ideal block group
  6660. * picked out then we don't care that the block group is cached.
  6661. */
  6662. if (block_group && block_group_bits(block_group, flags) &&
  6663. block_group->cached != BTRFS_CACHE_NO) {
  6664. down_read(&space_info->groups_sem);
  6665. if (list_empty(&block_group->list) ||
  6666. block_group->ro) {
  6667. /*
  6668. * someone is removing this block group,
  6669. * we can't jump into the have_block_group
  6670. * target because our list pointers are not
  6671. * valid
  6672. */
  6673. btrfs_put_block_group(block_group);
  6674. up_read(&space_info->groups_sem);
  6675. } else {
  6676. index = get_block_group_index(block_group);
  6677. btrfs_lock_block_group(block_group, delalloc);
  6678. goto have_block_group;
  6679. }
  6680. } else if (block_group) {
  6681. btrfs_put_block_group(block_group);
  6682. }
  6683. }
  6684. search:
  6685. have_caching_bg = false;
  6686. if (index == 0 || index == __get_raid_index(flags))
  6687. full_search = true;
  6688. down_read(&space_info->groups_sem);
  6689. list_for_each_entry(block_group, &space_info->block_groups[index],
  6690. list) {
  6691. u64 offset;
  6692. int cached;
  6693. /* If the block group is read-only, we can skip it entirely. */
  6694. if (unlikely(block_group->ro))
  6695. continue;
  6696. btrfs_grab_block_group(block_group, delalloc);
  6697. search_start = block_group->key.objectid;
  6698. /*
  6699. * this can happen if we end up cycling through all the
  6700. * raid types, but we want to make sure we only allocate
  6701. * for the proper type.
  6702. */
  6703. if (!block_group_bits(block_group, flags)) {
  6704. u64 extra = BTRFS_BLOCK_GROUP_DUP |
  6705. BTRFS_BLOCK_GROUP_RAID1 |
  6706. BTRFS_BLOCK_GROUP_RAID5 |
  6707. BTRFS_BLOCK_GROUP_RAID6 |
  6708. BTRFS_BLOCK_GROUP_RAID10;
  6709. /*
  6710. * if they asked for extra copies and this block group
  6711. * doesn't provide them, bail. This does allow us to
  6712. * fill raid0 from raid1.
  6713. */
  6714. if ((flags & extra) && !(block_group->flags & extra))
  6715. goto loop;
  6716. }
  6717. have_block_group:
  6718. cached = block_group_cache_done(block_group);
  6719. if (unlikely(!cached)) {
  6720. have_caching_bg = true;
  6721. ret = cache_block_group(block_group, 0);
  6722. BUG_ON(ret < 0);
  6723. ret = 0;
  6724. }
  6725. if (unlikely(block_group->cached == BTRFS_CACHE_ERROR))
  6726. goto loop;
  6727. /*
  6728. * Ok we want to try and use the cluster allocator, so
  6729. * lets look there
  6730. */
  6731. if (last_ptr && use_cluster) {
  6732. struct btrfs_block_group_cache *used_block_group;
  6733. unsigned long aligned_cluster;
  6734. /*
  6735. * the refill lock keeps out other
  6736. * people trying to start a new cluster
  6737. */
  6738. used_block_group = btrfs_lock_cluster(block_group,
  6739. last_ptr,
  6740. delalloc);
  6741. if (!used_block_group)
  6742. goto refill_cluster;
  6743. if (used_block_group != block_group &&
  6744. (used_block_group->ro ||
  6745. !block_group_bits(used_block_group, flags)))
  6746. goto release_cluster;
  6747. offset = btrfs_alloc_from_cluster(used_block_group,
  6748. last_ptr,
  6749. num_bytes,
  6750. used_block_group->key.objectid,
  6751. &max_extent_size);
  6752. if (offset) {
  6753. /* we have a block, we're done */
  6754. spin_unlock(&last_ptr->refill_lock);
  6755. trace_btrfs_reserve_extent_cluster(fs_info,
  6756. used_block_group,
  6757. search_start, num_bytes);
  6758. if (used_block_group != block_group) {
  6759. btrfs_release_block_group(block_group,
  6760. delalloc);
  6761. block_group = used_block_group;
  6762. }
  6763. goto checks;
  6764. }
  6765. WARN_ON(last_ptr->block_group != used_block_group);
  6766. release_cluster:
  6767. /* If we are on LOOP_NO_EMPTY_SIZE, we can't
  6768. * set up a new clusters, so lets just skip it
  6769. * and let the allocator find whatever block
  6770. * it can find. If we reach this point, we
  6771. * will have tried the cluster allocator
  6772. * plenty of times and not have found
  6773. * anything, so we are likely way too
  6774. * fragmented for the clustering stuff to find
  6775. * anything.
  6776. *
  6777. * However, if the cluster is taken from the
  6778. * current block group, release the cluster
  6779. * first, so that we stand a better chance of
  6780. * succeeding in the unclustered
  6781. * allocation. */
  6782. if (loop >= LOOP_NO_EMPTY_SIZE &&
  6783. used_block_group != block_group) {
  6784. spin_unlock(&last_ptr->refill_lock);
  6785. btrfs_release_block_group(used_block_group,
  6786. delalloc);
  6787. goto unclustered_alloc;
  6788. }
  6789. /*
  6790. * this cluster didn't work out, free it and
  6791. * start over
  6792. */
  6793. btrfs_return_cluster_to_free_space(NULL, last_ptr);
  6794. if (used_block_group != block_group)
  6795. btrfs_release_block_group(used_block_group,
  6796. delalloc);
  6797. refill_cluster:
  6798. if (loop >= LOOP_NO_EMPTY_SIZE) {
  6799. spin_unlock(&last_ptr->refill_lock);
  6800. goto unclustered_alloc;
  6801. }
  6802. aligned_cluster = max_t(unsigned long,
  6803. empty_cluster + empty_size,
  6804. block_group->full_stripe_len);
  6805. /* allocate a cluster in this block group */
  6806. ret = btrfs_find_space_cluster(fs_info, block_group,
  6807. last_ptr, search_start,
  6808. num_bytes,
  6809. aligned_cluster);
  6810. if (ret == 0) {
  6811. /*
  6812. * now pull our allocation out of this
  6813. * cluster
  6814. */
  6815. offset = btrfs_alloc_from_cluster(block_group,
  6816. last_ptr,
  6817. num_bytes,
  6818. search_start,
  6819. &max_extent_size);
  6820. if (offset) {
  6821. /* we found one, proceed */
  6822. spin_unlock(&last_ptr->refill_lock);
  6823. trace_btrfs_reserve_extent_cluster(fs_info,
  6824. block_group, search_start,
  6825. num_bytes);
  6826. goto checks;
  6827. }
  6828. } else if (!cached && loop > LOOP_CACHING_NOWAIT
  6829. && !failed_cluster_refill) {
  6830. spin_unlock(&last_ptr->refill_lock);
  6831. failed_cluster_refill = true;
  6832. wait_block_group_cache_progress(block_group,
  6833. num_bytes + empty_cluster + empty_size);
  6834. goto have_block_group;
  6835. }
  6836. /*
  6837. * at this point we either didn't find a cluster
  6838. * or we weren't able to allocate a block from our
  6839. * cluster. Free the cluster we've been trying
  6840. * to use, and go to the next block group
  6841. */
  6842. btrfs_return_cluster_to_free_space(NULL, last_ptr);
  6843. spin_unlock(&last_ptr->refill_lock);
  6844. goto loop;
  6845. }
  6846. unclustered_alloc:
  6847. /*
  6848. * We are doing an unclustered alloc, set the fragmented flag so
  6849. * we don't bother trying to setup a cluster again until we get
  6850. * more space.
  6851. */
  6852. if (unlikely(last_ptr)) {
  6853. spin_lock(&last_ptr->lock);
  6854. last_ptr->fragmented = 1;
  6855. spin_unlock(&last_ptr->lock);
  6856. }
  6857. if (cached) {
  6858. struct btrfs_free_space_ctl *ctl =
  6859. block_group->free_space_ctl;
  6860. spin_lock(&ctl->tree_lock);
  6861. if (ctl->free_space <
  6862. num_bytes + empty_cluster + empty_size) {
  6863. if (ctl->free_space > max_extent_size)
  6864. max_extent_size = ctl->free_space;
  6865. spin_unlock(&ctl->tree_lock);
  6866. goto loop;
  6867. }
  6868. spin_unlock(&ctl->tree_lock);
  6869. }
  6870. offset = btrfs_find_space_for_alloc(block_group, search_start,
  6871. num_bytes, empty_size,
  6872. &max_extent_size);
  6873. /*
  6874. * If we didn't find a chunk, and we haven't failed on this
  6875. * block group before, and this block group is in the middle of
  6876. * caching and we are ok with waiting, then go ahead and wait
  6877. * for progress to be made, and set failed_alloc to true.
  6878. *
  6879. * If failed_alloc is true then we've already waited on this
  6880. * block group once and should move on to the next block group.
  6881. */
  6882. if (!offset && !failed_alloc && !cached &&
  6883. loop > LOOP_CACHING_NOWAIT) {
  6884. wait_block_group_cache_progress(block_group,
  6885. num_bytes + empty_size);
  6886. failed_alloc = true;
  6887. goto have_block_group;
  6888. } else if (!offset) {
  6889. goto loop;
  6890. }
  6891. checks:
  6892. search_start = ALIGN(offset, fs_info->stripesize);
  6893. /* move on to the next group */
  6894. if (search_start + num_bytes >
  6895. block_group->key.objectid + block_group->key.offset) {
  6896. btrfs_add_free_space(block_group, offset, num_bytes);
  6897. goto loop;
  6898. }
  6899. if (offset < search_start)
  6900. btrfs_add_free_space(block_group, offset,
  6901. search_start - offset);
  6902. BUG_ON(offset > search_start);
  6903. ret = btrfs_add_reserved_bytes(block_group, ram_bytes,
  6904. num_bytes, delalloc);
  6905. if (ret == -EAGAIN) {
  6906. btrfs_add_free_space(block_group, offset, num_bytes);
  6907. goto loop;
  6908. }
  6909. btrfs_inc_block_group_reservations(block_group);
  6910. /* we are all good, lets return */
  6911. ins->objectid = search_start;
  6912. ins->offset = num_bytes;
  6913. trace_btrfs_reserve_extent(fs_info, block_group,
  6914. search_start, num_bytes);
  6915. btrfs_release_block_group(block_group, delalloc);
  6916. break;
  6917. loop:
  6918. failed_cluster_refill = false;
  6919. failed_alloc = false;
  6920. BUG_ON(index != get_block_group_index(block_group));
  6921. btrfs_release_block_group(block_group, delalloc);
  6922. cond_resched();
  6923. }
  6924. up_read(&space_info->groups_sem);
  6925. if ((loop == LOOP_CACHING_NOWAIT) && have_caching_bg
  6926. && !orig_have_caching_bg)
  6927. orig_have_caching_bg = true;
  6928. if (!ins->objectid && loop >= LOOP_CACHING_WAIT && have_caching_bg)
  6929. goto search;
  6930. if (!ins->objectid && ++index < BTRFS_NR_RAID_TYPES)
  6931. goto search;
  6932. /*
  6933. * LOOP_CACHING_NOWAIT, search partially cached block groups, kicking
  6934. * caching kthreads as we move along
  6935. * LOOP_CACHING_WAIT, search everything, and wait if our bg is caching
  6936. * LOOP_ALLOC_CHUNK, force a chunk allocation and try again
  6937. * LOOP_NO_EMPTY_SIZE, set empty_size and empty_cluster to 0 and try
  6938. * again
  6939. */
  6940. if (!ins->objectid && loop < LOOP_NO_EMPTY_SIZE) {
  6941. index = 0;
  6942. if (loop == LOOP_CACHING_NOWAIT) {
  6943. /*
  6944. * We want to skip the LOOP_CACHING_WAIT step if we
  6945. * don't have any uncached bgs and we've already done a
  6946. * full search through.
  6947. */
  6948. if (orig_have_caching_bg || !full_search)
  6949. loop = LOOP_CACHING_WAIT;
  6950. else
  6951. loop = LOOP_ALLOC_CHUNK;
  6952. } else {
  6953. loop++;
  6954. }
  6955. if (loop == LOOP_ALLOC_CHUNK) {
  6956. struct btrfs_trans_handle *trans;
  6957. int exist = 0;
  6958. trans = current->journal_info;
  6959. if (trans)
  6960. exist = 1;
  6961. else
  6962. trans = btrfs_join_transaction(root);
  6963. if (IS_ERR(trans)) {
  6964. ret = PTR_ERR(trans);
  6965. goto out;
  6966. }
  6967. ret = do_chunk_alloc(trans, fs_info, flags,
  6968. CHUNK_ALLOC_FORCE);
  6969. /*
  6970. * If we can't allocate a new chunk we've already looped
  6971. * through at least once, move on to the NO_EMPTY_SIZE
  6972. * case.
  6973. */
  6974. if (ret == -ENOSPC)
  6975. loop = LOOP_NO_EMPTY_SIZE;
  6976. /*
  6977. * Do not bail out on ENOSPC since we
  6978. * can do more things.
  6979. */
  6980. if (ret < 0 && ret != -ENOSPC)
  6981. btrfs_abort_transaction(trans, ret);
  6982. else
  6983. ret = 0;
  6984. if (!exist)
  6985. btrfs_end_transaction(trans);
  6986. if (ret)
  6987. goto out;
  6988. }
  6989. if (loop == LOOP_NO_EMPTY_SIZE) {
  6990. /*
  6991. * Don't loop again if we already have no empty_size and
  6992. * no empty_cluster.
  6993. */
  6994. if (empty_size == 0 &&
  6995. empty_cluster == 0) {
  6996. ret = -ENOSPC;
  6997. goto out;
  6998. }
  6999. empty_size = 0;
  7000. empty_cluster = 0;
  7001. }
  7002. goto search;
  7003. } else if (!ins->objectid) {
  7004. ret = -ENOSPC;
  7005. } else if (ins->objectid) {
  7006. if (!use_cluster && last_ptr) {
  7007. spin_lock(&last_ptr->lock);
  7008. last_ptr->window_start = ins->objectid;
  7009. spin_unlock(&last_ptr->lock);
  7010. }
  7011. ret = 0;
  7012. }
  7013. out:
  7014. if (ret == -ENOSPC) {
  7015. spin_lock(&space_info->lock);
  7016. space_info->max_extent_size = max_extent_size;
  7017. spin_unlock(&space_info->lock);
  7018. ins->offset = max_extent_size;
  7019. }
  7020. return ret;
  7021. }
  7022. static void dump_space_info(struct btrfs_fs_info *fs_info,
  7023. struct btrfs_space_info *info, u64 bytes,
  7024. int dump_block_groups)
  7025. {
  7026. struct btrfs_block_group_cache *cache;
  7027. int index = 0;
  7028. spin_lock(&info->lock);
  7029. btrfs_info(fs_info, "space_info %llu has %llu free, is %sfull",
  7030. info->flags,
  7031. info->total_bytes - btrfs_space_info_used(info, true),
  7032. info->full ? "" : "not ");
  7033. btrfs_info(fs_info,
  7034. "space_info total=%llu, used=%llu, pinned=%llu, reserved=%llu, may_use=%llu, readonly=%llu",
  7035. info->total_bytes, info->bytes_used, info->bytes_pinned,
  7036. info->bytes_reserved, info->bytes_may_use,
  7037. info->bytes_readonly);
  7038. spin_unlock(&info->lock);
  7039. if (!dump_block_groups)
  7040. return;
  7041. down_read(&info->groups_sem);
  7042. again:
  7043. list_for_each_entry(cache, &info->block_groups[index], list) {
  7044. spin_lock(&cache->lock);
  7045. btrfs_info(fs_info,
  7046. "block group %llu has %llu bytes, %llu used %llu pinned %llu reserved %s",
  7047. cache->key.objectid, cache->key.offset,
  7048. btrfs_block_group_used(&cache->item), cache->pinned,
  7049. cache->reserved, cache->ro ? "[readonly]" : "");
  7050. btrfs_dump_free_space(cache, bytes);
  7051. spin_unlock(&cache->lock);
  7052. }
  7053. if (++index < BTRFS_NR_RAID_TYPES)
  7054. goto again;
  7055. up_read(&info->groups_sem);
  7056. }
  7057. int btrfs_reserve_extent(struct btrfs_root *root, u64 ram_bytes,
  7058. u64 num_bytes, u64 min_alloc_size,
  7059. u64 empty_size, u64 hint_byte,
  7060. struct btrfs_key *ins, int is_data, int delalloc)
  7061. {
  7062. struct btrfs_fs_info *fs_info = root->fs_info;
  7063. bool final_tried = num_bytes == min_alloc_size;
  7064. u64 flags;
  7065. int ret;
  7066. flags = get_alloc_profile_by_root(root, is_data);
  7067. again:
  7068. WARN_ON(num_bytes < fs_info->sectorsize);
  7069. ret = find_free_extent(fs_info, ram_bytes, num_bytes, empty_size,
  7070. hint_byte, ins, flags, delalloc);
  7071. if (!ret && !is_data) {
  7072. btrfs_dec_block_group_reservations(fs_info, ins->objectid);
  7073. } else if (ret == -ENOSPC) {
  7074. if (!final_tried && ins->offset) {
  7075. num_bytes = min(num_bytes >> 1, ins->offset);
  7076. num_bytes = round_down(num_bytes,
  7077. fs_info->sectorsize);
  7078. num_bytes = max(num_bytes, min_alloc_size);
  7079. ram_bytes = num_bytes;
  7080. if (num_bytes == min_alloc_size)
  7081. final_tried = true;
  7082. goto again;
  7083. } else if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
  7084. struct btrfs_space_info *sinfo;
  7085. sinfo = __find_space_info(fs_info, flags);
  7086. btrfs_err(fs_info,
  7087. "allocation failed flags %llu, wanted %llu",
  7088. flags, num_bytes);
  7089. if (sinfo)
  7090. dump_space_info(fs_info, sinfo, num_bytes, 1);
  7091. }
  7092. }
  7093. return ret;
  7094. }
  7095. static int __btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
  7096. u64 start, u64 len,
  7097. int pin, int delalloc)
  7098. {
  7099. struct btrfs_block_group_cache *cache;
  7100. int ret = 0;
  7101. cache = btrfs_lookup_block_group(fs_info, start);
  7102. if (!cache) {
  7103. btrfs_err(fs_info, "Unable to find block group for %llu",
  7104. start);
  7105. return -ENOSPC;
  7106. }
  7107. if (pin)
  7108. pin_down_extent(fs_info, cache, start, len, 1);
  7109. else {
  7110. if (btrfs_test_opt(fs_info, DISCARD))
  7111. ret = btrfs_discard_extent(fs_info, start, len, NULL);
  7112. btrfs_add_free_space(cache, start, len);
  7113. btrfs_free_reserved_bytes(cache, len, delalloc);
  7114. trace_btrfs_reserved_extent_free(fs_info, start, len);
  7115. }
  7116. btrfs_put_block_group(cache);
  7117. return ret;
  7118. }
  7119. int btrfs_free_reserved_extent(struct btrfs_fs_info *fs_info,
  7120. u64 start, u64 len, int delalloc)
  7121. {
  7122. return __btrfs_free_reserved_extent(fs_info, start, len, 0, delalloc);
  7123. }
  7124. int btrfs_free_and_pin_reserved_extent(struct btrfs_fs_info *fs_info,
  7125. u64 start, u64 len)
  7126. {
  7127. return __btrfs_free_reserved_extent(fs_info, start, len, 1, 0);
  7128. }
  7129. static int alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
  7130. struct btrfs_fs_info *fs_info,
  7131. u64 parent, u64 root_objectid,
  7132. u64 flags, u64 owner, u64 offset,
  7133. struct btrfs_key *ins, int ref_mod)
  7134. {
  7135. int ret;
  7136. struct btrfs_extent_item *extent_item;
  7137. struct btrfs_extent_inline_ref *iref;
  7138. struct btrfs_path *path;
  7139. struct extent_buffer *leaf;
  7140. int type;
  7141. u32 size;
  7142. if (parent > 0)
  7143. type = BTRFS_SHARED_DATA_REF_KEY;
  7144. else
  7145. type = BTRFS_EXTENT_DATA_REF_KEY;
  7146. size = sizeof(*extent_item) + btrfs_extent_inline_ref_size(type);
  7147. path = btrfs_alloc_path();
  7148. if (!path)
  7149. return -ENOMEM;
  7150. path->leave_spinning = 1;
  7151. ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
  7152. ins, size);
  7153. if (ret) {
  7154. btrfs_free_path(path);
  7155. return ret;
  7156. }
  7157. leaf = path->nodes[0];
  7158. extent_item = btrfs_item_ptr(leaf, path->slots[0],
  7159. struct btrfs_extent_item);
  7160. btrfs_set_extent_refs(leaf, extent_item, ref_mod);
  7161. btrfs_set_extent_generation(leaf, extent_item, trans->transid);
  7162. btrfs_set_extent_flags(leaf, extent_item,
  7163. flags | BTRFS_EXTENT_FLAG_DATA);
  7164. iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
  7165. btrfs_set_extent_inline_ref_type(leaf, iref, type);
  7166. if (parent > 0) {
  7167. struct btrfs_shared_data_ref *ref;
  7168. ref = (struct btrfs_shared_data_ref *)(iref + 1);
  7169. btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
  7170. btrfs_set_shared_data_ref_count(leaf, ref, ref_mod);
  7171. } else {
  7172. struct btrfs_extent_data_ref *ref;
  7173. ref = (struct btrfs_extent_data_ref *)(&iref->offset);
  7174. btrfs_set_extent_data_ref_root(leaf, ref, root_objectid);
  7175. btrfs_set_extent_data_ref_objectid(leaf, ref, owner);
  7176. btrfs_set_extent_data_ref_offset(leaf, ref, offset);
  7177. btrfs_set_extent_data_ref_count(leaf, ref, ref_mod);
  7178. }
  7179. btrfs_mark_buffer_dirty(path->nodes[0]);
  7180. btrfs_free_path(path);
  7181. ret = remove_from_free_space_tree(trans, fs_info, ins->objectid,
  7182. ins->offset);
  7183. if (ret)
  7184. return ret;
  7185. ret = update_block_group(trans, fs_info, ins->objectid, ins->offset, 1);
  7186. if (ret) { /* -ENOENT, logic error */
  7187. btrfs_err(fs_info, "update block group failed for %llu %llu",
  7188. ins->objectid, ins->offset);
  7189. BUG();
  7190. }
  7191. trace_btrfs_reserved_extent_alloc(fs_info, ins->objectid, ins->offset);
  7192. return ret;
  7193. }
  7194. static int alloc_reserved_tree_block(struct btrfs_trans_handle *trans,
  7195. struct btrfs_fs_info *fs_info,
  7196. u64 parent, u64 root_objectid,
  7197. u64 flags, struct btrfs_disk_key *key,
  7198. int level, struct btrfs_key *ins)
  7199. {
  7200. int ret;
  7201. struct btrfs_extent_item *extent_item;
  7202. struct btrfs_tree_block_info *block_info;
  7203. struct btrfs_extent_inline_ref *iref;
  7204. struct btrfs_path *path;
  7205. struct extent_buffer *leaf;
  7206. u32 size = sizeof(*extent_item) + sizeof(*iref);
  7207. u64 num_bytes = ins->offset;
  7208. bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
  7209. if (!skinny_metadata)
  7210. size += sizeof(*block_info);
  7211. path = btrfs_alloc_path();
  7212. if (!path) {
  7213. btrfs_free_and_pin_reserved_extent(fs_info, ins->objectid,
  7214. fs_info->nodesize);
  7215. return -ENOMEM;
  7216. }
  7217. path->leave_spinning = 1;
  7218. ret = btrfs_insert_empty_item(trans, fs_info->extent_root, path,
  7219. ins, size);
  7220. if (ret) {
  7221. btrfs_free_path(path);
  7222. btrfs_free_and_pin_reserved_extent(fs_info, ins->objectid,
  7223. fs_info->nodesize);
  7224. return ret;
  7225. }
  7226. leaf = path->nodes[0];
  7227. extent_item = btrfs_item_ptr(leaf, path->slots[0],
  7228. struct btrfs_extent_item);
  7229. btrfs_set_extent_refs(leaf, extent_item, 1);
  7230. btrfs_set_extent_generation(leaf, extent_item, trans->transid);
  7231. btrfs_set_extent_flags(leaf, extent_item,
  7232. flags | BTRFS_EXTENT_FLAG_TREE_BLOCK);
  7233. if (skinny_metadata) {
  7234. iref = (struct btrfs_extent_inline_ref *)(extent_item + 1);
  7235. num_bytes = fs_info->nodesize;
  7236. } else {
  7237. block_info = (struct btrfs_tree_block_info *)(extent_item + 1);
  7238. btrfs_set_tree_block_key(leaf, block_info, key);
  7239. btrfs_set_tree_block_level(leaf, block_info, level);
  7240. iref = (struct btrfs_extent_inline_ref *)(block_info + 1);
  7241. }
  7242. if (parent > 0) {
  7243. BUG_ON(!(flags & BTRFS_BLOCK_FLAG_FULL_BACKREF));
  7244. btrfs_set_extent_inline_ref_type(leaf, iref,
  7245. BTRFS_SHARED_BLOCK_REF_KEY);
  7246. btrfs_set_extent_inline_ref_offset(leaf, iref, parent);
  7247. } else {
  7248. btrfs_set_extent_inline_ref_type(leaf, iref,
  7249. BTRFS_TREE_BLOCK_REF_KEY);
  7250. btrfs_set_extent_inline_ref_offset(leaf, iref, root_objectid);
  7251. }
  7252. btrfs_mark_buffer_dirty(leaf);
  7253. btrfs_free_path(path);
  7254. ret = remove_from_free_space_tree(trans, fs_info, ins->objectid,
  7255. num_bytes);
  7256. if (ret)
  7257. return ret;
  7258. ret = update_block_group(trans, fs_info, ins->objectid,
  7259. fs_info->nodesize, 1);
  7260. if (ret) { /* -ENOENT, logic error */
  7261. btrfs_err(fs_info, "update block group failed for %llu %llu",
  7262. ins->objectid, ins->offset);
  7263. BUG();
  7264. }
  7265. trace_btrfs_reserved_extent_alloc(fs_info, ins->objectid,
  7266. fs_info->nodesize);
  7267. return ret;
  7268. }
  7269. int btrfs_alloc_reserved_file_extent(struct btrfs_trans_handle *trans,
  7270. struct btrfs_root *root, u64 owner,
  7271. u64 offset, u64 ram_bytes,
  7272. struct btrfs_key *ins)
  7273. {
  7274. struct btrfs_fs_info *fs_info = root->fs_info;
  7275. int ret;
  7276. BUG_ON(root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID);
  7277. btrfs_ref_tree_mod(root, ins->objectid, ins->offset, 0,
  7278. root->root_key.objectid, owner, offset,
  7279. BTRFS_ADD_DELAYED_EXTENT);
  7280. ret = btrfs_add_delayed_data_ref(fs_info, trans, ins->objectid,
  7281. ins->offset, 0,
  7282. root->root_key.objectid, owner,
  7283. offset, ram_bytes,
  7284. BTRFS_ADD_DELAYED_EXTENT, NULL, NULL);
  7285. return ret;
  7286. }
  7287. /*
  7288. * this is used by the tree logging recovery code. It records that
  7289. * an extent has been allocated and makes sure to clear the free
  7290. * space cache bits as well
  7291. */
  7292. int btrfs_alloc_logged_file_extent(struct btrfs_trans_handle *trans,
  7293. struct btrfs_fs_info *fs_info,
  7294. u64 root_objectid, u64 owner, u64 offset,
  7295. struct btrfs_key *ins)
  7296. {
  7297. int ret;
  7298. struct btrfs_block_group_cache *block_group;
  7299. struct btrfs_space_info *space_info;
  7300. /*
  7301. * Mixed block groups will exclude before processing the log so we only
  7302. * need to do the exclude dance if this fs isn't mixed.
  7303. */
  7304. if (!btrfs_fs_incompat(fs_info, MIXED_GROUPS)) {
  7305. ret = __exclude_logged_extent(fs_info, ins->objectid,
  7306. ins->offset);
  7307. if (ret)
  7308. return ret;
  7309. }
  7310. block_group = btrfs_lookup_block_group(fs_info, ins->objectid);
  7311. if (!block_group)
  7312. return -EINVAL;
  7313. space_info = block_group->space_info;
  7314. spin_lock(&space_info->lock);
  7315. spin_lock(&block_group->lock);
  7316. space_info->bytes_reserved += ins->offset;
  7317. block_group->reserved += ins->offset;
  7318. spin_unlock(&block_group->lock);
  7319. spin_unlock(&space_info->lock);
  7320. ret = alloc_reserved_file_extent(trans, fs_info, 0, root_objectid,
  7321. 0, owner, offset, ins, 1);
  7322. btrfs_put_block_group(block_group);
  7323. return ret;
  7324. }
  7325. static struct extent_buffer *
  7326. btrfs_init_new_buffer(struct btrfs_trans_handle *trans, struct btrfs_root *root,
  7327. u64 bytenr, int level)
  7328. {
  7329. struct btrfs_fs_info *fs_info = root->fs_info;
  7330. struct extent_buffer *buf;
  7331. buf = btrfs_find_create_tree_block(fs_info, bytenr);
  7332. if (IS_ERR(buf))
  7333. return buf;
  7334. btrfs_set_header_generation(buf, trans->transid);
  7335. btrfs_set_buffer_lockdep_class(root->root_key.objectid, buf, level);
  7336. btrfs_tree_lock(buf);
  7337. clean_tree_block(fs_info, buf);
  7338. clear_bit(EXTENT_BUFFER_STALE, &buf->bflags);
  7339. btrfs_set_lock_blocking(buf);
  7340. set_extent_buffer_uptodate(buf);
  7341. if (root->root_key.objectid == BTRFS_TREE_LOG_OBJECTID) {
  7342. buf->log_index = root->log_transid % 2;
  7343. /*
  7344. * we allow two log transactions at a time, use different
  7345. * EXENT bit to differentiate dirty pages.
  7346. */
  7347. if (buf->log_index == 0)
  7348. set_extent_dirty(&root->dirty_log_pages, buf->start,
  7349. buf->start + buf->len - 1, GFP_NOFS);
  7350. else
  7351. set_extent_new(&root->dirty_log_pages, buf->start,
  7352. buf->start + buf->len - 1);
  7353. } else {
  7354. buf->log_index = -1;
  7355. set_extent_dirty(&trans->transaction->dirty_pages, buf->start,
  7356. buf->start + buf->len - 1, GFP_NOFS);
  7357. }
  7358. trans->dirty = true;
  7359. /* this returns a buffer locked for blocking */
  7360. return buf;
  7361. }
  7362. static struct btrfs_block_rsv *
  7363. use_block_rsv(struct btrfs_trans_handle *trans,
  7364. struct btrfs_root *root, u32 blocksize)
  7365. {
  7366. struct btrfs_fs_info *fs_info = root->fs_info;
  7367. struct btrfs_block_rsv *block_rsv;
  7368. struct btrfs_block_rsv *global_rsv = &fs_info->global_block_rsv;
  7369. int ret;
  7370. bool global_updated = false;
  7371. block_rsv = get_block_rsv(trans, root);
  7372. if (unlikely(block_rsv->size == 0))
  7373. goto try_reserve;
  7374. again:
  7375. ret = block_rsv_use_bytes(block_rsv, blocksize);
  7376. if (!ret)
  7377. return block_rsv;
  7378. if (block_rsv->failfast)
  7379. return ERR_PTR(ret);
  7380. if (block_rsv->type == BTRFS_BLOCK_RSV_GLOBAL && !global_updated) {
  7381. global_updated = true;
  7382. update_global_block_rsv(fs_info);
  7383. goto again;
  7384. }
  7385. if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
  7386. static DEFINE_RATELIMIT_STATE(_rs,
  7387. DEFAULT_RATELIMIT_INTERVAL * 10,
  7388. /*DEFAULT_RATELIMIT_BURST*/ 1);
  7389. if (__ratelimit(&_rs))
  7390. WARN(1, KERN_DEBUG
  7391. "BTRFS: block rsv returned %d\n", ret);
  7392. }
  7393. try_reserve:
  7394. ret = reserve_metadata_bytes(root, block_rsv, blocksize,
  7395. BTRFS_RESERVE_NO_FLUSH);
  7396. if (!ret)
  7397. return block_rsv;
  7398. /*
  7399. * If we couldn't reserve metadata bytes try and use some from
  7400. * the global reserve if its space type is the same as the global
  7401. * reservation.
  7402. */
  7403. if (block_rsv->type != BTRFS_BLOCK_RSV_GLOBAL &&
  7404. block_rsv->space_info == global_rsv->space_info) {
  7405. ret = block_rsv_use_bytes(global_rsv, blocksize);
  7406. if (!ret)
  7407. return global_rsv;
  7408. }
  7409. return ERR_PTR(ret);
  7410. }
  7411. static void unuse_block_rsv(struct btrfs_fs_info *fs_info,
  7412. struct btrfs_block_rsv *block_rsv, u32 blocksize)
  7413. {
  7414. block_rsv_add_bytes(block_rsv, blocksize, 0);
  7415. block_rsv_release_bytes(fs_info, block_rsv, NULL, 0);
  7416. }
  7417. /*
  7418. * finds a free extent and does all the dirty work required for allocation
  7419. * returns the tree buffer or an ERR_PTR on error.
  7420. */
  7421. struct extent_buffer *btrfs_alloc_tree_block(struct btrfs_trans_handle *trans,
  7422. struct btrfs_root *root,
  7423. u64 parent, u64 root_objectid,
  7424. const struct btrfs_disk_key *key,
  7425. int level, u64 hint,
  7426. u64 empty_size)
  7427. {
  7428. struct btrfs_fs_info *fs_info = root->fs_info;
  7429. struct btrfs_key ins;
  7430. struct btrfs_block_rsv *block_rsv;
  7431. struct extent_buffer *buf;
  7432. struct btrfs_delayed_extent_op *extent_op;
  7433. u64 flags = 0;
  7434. int ret;
  7435. u32 blocksize = fs_info->nodesize;
  7436. bool skinny_metadata = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
  7437. #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
  7438. if (btrfs_is_testing(fs_info)) {
  7439. buf = btrfs_init_new_buffer(trans, root, root->alloc_bytenr,
  7440. level);
  7441. if (!IS_ERR(buf))
  7442. root->alloc_bytenr += blocksize;
  7443. return buf;
  7444. }
  7445. #endif
  7446. block_rsv = use_block_rsv(trans, root, blocksize);
  7447. if (IS_ERR(block_rsv))
  7448. return ERR_CAST(block_rsv);
  7449. ret = btrfs_reserve_extent(root, blocksize, blocksize, blocksize,
  7450. empty_size, hint, &ins, 0, 0);
  7451. if (ret)
  7452. goto out_unuse;
  7453. buf = btrfs_init_new_buffer(trans, root, ins.objectid, level);
  7454. if (IS_ERR(buf)) {
  7455. ret = PTR_ERR(buf);
  7456. goto out_free_reserved;
  7457. }
  7458. if (root_objectid == BTRFS_TREE_RELOC_OBJECTID) {
  7459. if (parent == 0)
  7460. parent = ins.objectid;
  7461. flags |= BTRFS_BLOCK_FLAG_FULL_BACKREF;
  7462. } else
  7463. BUG_ON(parent > 0);
  7464. if (root_objectid != BTRFS_TREE_LOG_OBJECTID) {
  7465. extent_op = btrfs_alloc_delayed_extent_op();
  7466. if (!extent_op) {
  7467. ret = -ENOMEM;
  7468. goto out_free_buf;
  7469. }
  7470. if (key)
  7471. memcpy(&extent_op->key, key, sizeof(extent_op->key));
  7472. else
  7473. memset(&extent_op->key, 0, sizeof(extent_op->key));
  7474. extent_op->flags_to_set = flags;
  7475. extent_op->update_key = skinny_metadata ? false : true;
  7476. extent_op->update_flags = true;
  7477. extent_op->is_data = false;
  7478. extent_op->level = level;
  7479. btrfs_ref_tree_mod(root, ins.objectid, ins.offset, parent,
  7480. root_objectid, level, 0,
  7481. BTRFS_ADD_DELAYED_EXTENT);
  7482. ret = btrfs_add_delayed_tree_ref(fs_info, trans, ins.objectid,
  7483. ins.offset, parent,
  7484. root_objectid, level,
  7485. BTRFS_ADD_DELAYED_EXTENT,
  7486. extent_op, NULL, NULL);
  7487. if (ret)
  7488. goto out_free_delayed;
  7489. }
  7490. return buf;
  7491. out_free_delayed:
  7492. btrfs_free_delayed_extent_op(extent_op);
  7493. out_free_buf:
  7494. free_extent_buffer(buf);
  7495. out_free_reserved:
  7496. btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, 0);
  7497. out_unuse:
  7498. unuse_block_rsv(fs_info, block_rsv, blocksize);
  7499. return ERR_PTR(ret);
  7500. }
  7501. struct walk_control {
  7502. u64 refs[BTRFS_MAX_LEVEL];
  7503. u64 flags[BTRFS_MAX_LEVEL];
  7504. struct btrfs_key update_progress;
  7505. int stage;
  7506. int level;
  7507. int shared_level;
  7508. int update_ref;
  7509. int keep_locks;
  7510. int reada_slot;
  7511. int reada_count;
  7512. int for_reloc;
  7513. };
  7514. #define DROP_REFERENCE 1
  7515. #define UPDATE_BACKREF 2
  7516. static noinline void reada_walk_down(struct btrfs_trans_handle *trans,
  7517. struct btrfs_root *root,
  7518. struct walk_control *wc,
  7519. struct btrfs_path *path)
  7520. {
  7521. struct btrfs_fs_info *fs_info = root->fs_info;
  7522. u64 bytenr;
  7523. u64 generation;
  7524. u64 refs;
  7525. u64 flags;
  7526. u32 nritems;
  7527. struct btrfs_key key;
  7528. struct extent_buffer *eb;
  7529. int ret;
  7530. int slot;
  7531. int nread = 0;
  7532. if (path->slots[wc->level] < wc->reada_slot) {
  7533. wc->reada_count = wc->reada_count * 2 / 3;
  7534. wc->reada_count = max(wc->reada_count, 2);
  7535. } else {
  7536. wc->reada_count = wc->reada_count * 3 / 2;
  7537. wc->reada_count = min_t(int, wc->reada_count,
  7538. BTRFS_NODEPTRS_PER_BLOCK(fs_info));
  7539. }
  7540. eb = path->nodes[wc->level];
  7541. nritems = btrfs_header_nritems(eb);
  7542. for (slot = path->slots[wc->level]; slot < nritems; slot++) {
  7543. if (nread >= wc->reada_count)
  7544. break;
  7545. cond_resched();
  7546. bytenr = btrfs_node_blockptr(eb, slot);
  7547. generation = btrfs_node_ptr_generation(eb, slot);
  7548. if (slot == path->slots[wc->level])
  7549. goto reada;
  7550. if (wc->stage == UPDATE_BACKREF &&
  7551. generation <= root->root_key.offset)
  7552. continue;
  7553. /* We don't lock the tree block, it's OK to be racy here */
  7554. ret = btrfs_lookup_extent_info(trans, fs_info, bytenr,
  7555. wc->level - 1, 1, &refs,
  7556. &flags);
  7557. /* We don't care about errors in readahead. */
  7558. if (ret < 0)
  7559. continue;
  7560. BUG_ON(refs == 0);
  7561. if (wc->stage == DROP_REFERENCE) {
  7562. if (refs == 1)
  7563. goto reada;
  7564. if (wc->level == 1 &&
  7565. (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
  7566. continue;
  7567. if (!wc->update_ref ||
  7568. generation <= root->root_key.offset)
  7569. continue;
  7570. btrfs_node_key_to_cpu(eb, &key, slot);
  7571. ret = btrfs_comp_cpu_keys(&key,
  7572. &wc->update_progress);
  7573. if (ret < 0)
  7574. continue;
  7575. } else {
  7576. if (wc->level == 1 &&
  7577. (flags & BTRFS_BLOCK_FLAG_FULL_BACKREF))
  7578. continue;
  7579. }
  7580. reada:
  7581. readahead_tree_block(fs_info, bytenr);
  7582. nread++;
  7583. }
  7584. wc->reada_slot = slot;
  7585. }
  7586. /*
  7587. * helper to process tree block while walking down the tree.
  7588. *
  7589. * when wc->stage == UPDATE_BACKREF, this function updates
  7590. * back refs for pointers in the block.
  7591. *
  7592. * NOTE: return value 1 means we should stop walking down.
  7593. */
  7594. static noinline int walk_down_proc(struct btrfs_trans_handle *trans,
  7595. struct btrfs_root *root,
  7596. struct btrfs_path *path,
  7597. struct walk_control *wc, int lookup_info)
  7598. {
  7599. struct btrfs_fs_info *fs_info = root->fs_info;
  7600. int level = wc->level;
  7601. struct extent_buffer *eb = path->nodes[level];
  7602. u64 flag = BTRFS_BLOCK_FLAG_FULL_BACKREF;
  7603. int ret;
  7604. if (wc->stage == UPDATE_BACKREF &&
  7605. btrfs_header_owner(eb) != root->root_key.objectid)
  7606. return 1;
  7607. /*
  7608. * when reference count of tree block is 1, it won't increase
  7609. * again. once full backref flag is set, we never clear it.
  7610. */
  7611. if (lookup_info &&
  7612. ((wc->stage == DROP_REFERENCE && wc->refs[level] != 1) ||
  7613. (wc->stage == UPDATE_BACKREF && !(wc->flags[level] & flag)))) {
  7614. BUG_ON(!path->locks[level]);
  7615. ret = btrfs_lookup_extent_info(trans, fs_info,
  7616. eb->start, level, 1,
  7617. &wc->refs[level],
  7618. &wc->flags[level]);
  7619. BUG_ON(ret == -ENOMEM);
  7620. if (ret)
  7621. return ret;
  7622. BUG_ON(wc->refs[level] == 0);
  7623. }
  7624. if (wc->stage == DROP_REFERENCE) {
  7625. if (wc->refs[level] > 1)
  7626. return 1;
  7627. if (path->locks[level] && !wc->keep_locks) {
  7628. btrfs_tree_unlock_rw(eb, path->locks[level]);
  7629. path->locks[level] = 0;
  7630. }
  7631. return 0;
  7632. }
  7633. /* wc->stage == UPDATE_BACKREF */
  7634. if (!(wc->flags[level] & flag)) {
  7635. BUG_ON(!path->locks[level]);
  7636. ret = btrfs_inc_ref(trans, root, eb, 1);
  7637. BUG_ON(ret); /* -ENOMEM */
  7638. ret = btrfs_dec_ref(trans, root, eb, 0);
  7639. BUG_ON(ret); /* -ENOMEM */
  7640. ret = btrfs_set_disk_extent_flags(trans, fs_info, eb->start,
  7641. eb->len, flag,
  7642. btrfs_header_level(eb), 0);
  7643. BUG_ON(ret); /* -ENOMEM */
  7644. wc->flags[level] |= flag;
  7645. }
  7646. /*
  7647. * the block is shared by multiple trees, so it's not good to
  7648. * keep the tree lock
  7649. */
  7650. if (path->locks[level] && level > 0) {
  7651. btrfs_tree_unlock_rw(eb, path->locks[level]);
  7652. path->locks[level] = 0;
  7653. }
  7654. return 0;
  7655. }
  7656. /*
  7657. * helper to process tree block pointer.
  7658. *
  7659. * when wc->stage == DROP_REFERENCE, this function checks
  7660. * reference count of the block pointed to. if the block
  7661. * is shared and we need update back refs for the subtree
  7662. * rooted at the block, this function changes wc->stage to
  7663. * UPDATE_BACKREF. if the block is shared and there is no
  7664. * need to update back, this function drops the reference
  7665. * to the block.
  7666. *
  7667. * NOTE: return value 1 means we should stop walking down.
  7668. */
  7669. static noinline int do_walk_down(struct btrfs_trans_handle *trans,
  7670. struct btrfs_root *root,
  7671. struct btrfs_path *path,
  7672. struct walk_control *wc, int *lookup_info)
  7673. {
  7674. struct btrfs_fs_info *fs_info = root->fs_info;
  7675. u64 bytenr;
  7676. u64 generation;
  7677. u64 parent;
  7678. u32 blocksize;
  7679. struct btrfs_key key;
  7680. struct extent_buffer *next;
  7681. int level = wc->level;
  7682. int reada = 0;
  7683. int ret = 0;
  7684. bool need_account = false;
  7685. generation = btrfs_node_ptr_generation(path->nodes[level],
  7686. path->slots[level]);
  7687. /*
  7688. * if the lower level block was created before the snapshot
  7689. * was created, we know there is no need to update back refs
  7690. * for the subtree
  7691. */
  7692. if (wc->stage == UPDATE_BACKREF &&
  7693. generation <= root->root_key.offset) {
  7694. *lookup_info = 1;
  7695. return 1;
  7696. }
  7697. bytenr = btrfs_node_blockptr(path->nodes[level], path->slots[level]);
  7698. blocksize = fs_info->nodesize;
  7699. next = find_extent_buffer(fs_info, bytenr);
  7700. if (!next) {
  7701. next = btrfs_find_create_tree_block(fs_info, bytenr);
  7702. if (IS_ERR(next))
  7703. return PTR_ERR(next);
  7704. btrfs_set_buffer_lockdep_class(root->root_key.objectid, next,
  7705. level - 1);
  7706. reada = 1;
  7707. }
  7708. btrfs_tree_lock(next);
  7709. btrfs_set_lock_blocking(next);
  7710. ret = btrfs_lookup_extent_info(trans, fs_info, bytenr, level - 1, 1,
  7711. &wc->refs[level - 1],
  7712. &wc->flags[level - 1]);
  7713. if (ret < 0)
  7714. goto out_unlock;
  7715. if (unlikely(wc->refs[level - 1] == 0)) {
  7716. btrfs_err(fs_info, "Missing references.");
  7717. ret = -EIO;
  7718. goto out_unlock;
  7719. }
  7720. *lookup_info = 0;
  7721. if (wc->stage == DROP_REFERENCE) {
  7722. if (wc->refs[level - 1] > 1) {
  7723. need_account = true;
  7724. if (level == 1 &&
  7725. (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
  7726. goto skip;
  7727. if (!wc->update_ref ||
  7728. generation <= root->root_key.offset)
  7729. goto skip;
  7730. btrfs_node_key_to_cpu(path->nodes[level], &key,
  7731. path->slots[level]);
  7732. ret = btrfs_comp_cpu_keys(&key, &wc->update_progress);
  7733. if (ret < 0)
  7734. goto skip;
  7735. wc->stage = UPDATE_BACKREF;
  7736. wc->shared_level = level - 1;
  7737. }
  7738. } else {
  7739. if (level == 1 &&
  7740. (wc->flags[0] & BTRFS_BLOCK_FLAG_FULL_BACKREF))
  7741. goto skip;
  7742. }
  7743. if (!btrfs_buffer_uptodate(next, generation, 0)) {
  7744. btrfs_tree_unlock(next);
  7745. free_extent_buffer(next);
  7746. next = NULL;
  7747. *lookup_info = 1;
  7748. }
  7749. if (!next) {
  7750. if (reada && level == 1)
  7751. reada_walk_down(trans, root, wc, path);
  7752. next = read_tree_block(fs_info, bytenr, generation);
  7753. if (IS_ERR(next)) {
  7754. return PTR_ERR(next);
  7755. } else if (!extent_buffer_uptodate(next)) {
  7756. free_extent_buffer(next);
  7757. return -EIO;
  7758. }
  7759. btrfs_tree_lock(next);
  7760. btrfs_set_lock_blocking(next);
  7761. }
  7762. level--;
  7763. ASSERT(level == btrfs_header_level(next));
  7764. if (level != btrfs_header_level(next)) {
  7765. btrfs_err(root->fs_info, "mismatched level");
  7766. ret = -EIO;
  7767. goto out_unlock;
  7768. }
  7769. path->nodes[level] = next;
  7770. path->slots[level] = 0;
  7771. path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
  7772. wc->level = level;
  7773. if (wc->level == 1)
  7774. wc->reada_slot = 0;
  7775. return 0;
  7776. skip:
  7777. wc->refs[level - 1] = 0;
  7778. wc->flags[level - 1] = 0;
  7779. if (wc->stage == DROP_REFERENCE) {
  7780. if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF) {
  7781. parent = path->nodes[level]->start;
  7782. } else {
  7783. ASSERT(root->root_key.objectid ==
  7784. btrfs_header_owner(path->nodes[level]));
  7785. if (root->root_key.objectid !=
  7786. btrfs_header_owner(path->nodes[level])) {
  7787. btrfs_err(root->fs_info,
  7788. "mismatched block owner");
  7789. ret = -EIO;
  7790. goto out_unlock;
  7791. }
  7792. parent = 0;
  7793. }
  7794. if (need_account) {
  7795. ret = btrfs_qgroup_trace_subtree(trans, root, next,
  7796. generation, level - 1);
  7797. if (ret) {
  7798. btrfs_err_rl(fs_info,
  7799. "Error %d accounting shared subtree. Quota is out of sync, rescan required.",
  7800. ret);
  7801. }
  7802. }
  7803. ret = btrfs_free_extent(trans, root, bytenr, blocksize,
  7804. parent, root->root_key.objectid,
  7805. level - 1, 0);
  7806. if (ret)
  7807. goto out_unlock;
  7808. }
  7809. *lookup_info = 1;
  7810. ret = 1;
  7811. out_unlock:
  7812. btrfs_tree_unlock(next);
  7813. free_extent_buffer(next);
  7814. return ret;
  7815. }
  7816. /*
  7817. * helper to process tree block while walking up the tree.
  7818. *
  7819. * when wc->stage == DROP_REFERENCE, this function drops
  7820. * reference count on the block.
  7821. *
  7822. * when wc->stage == UPDATE_BACKREF, this function changes
  7823. * wc->stage back to DROP_REFERENCE if we changed wc->stage
  7824. * to UPDATE_BACKREF previously while processing the block.
  7825. *
  7826. * NOTE: return value 1 means we should stop walking up.
  7827. */
  7828. static noinline int walk_up_proc(struct btrfs_trans_handle *trans,
  7829. struct btrfs_root *root,
  7830. struct btrfs_path *path,
  7831. struct walk_control *wc)
  7832. {
  7833. struct btrfs_fs_info *fs_info = root->fs_info;
  7834. int ret;
  7835. int level = wc->level;
  7836. struct extent_buffer *eb = path->nodes[level];
  7837. u64 parent = 0;
  7838. if (wc->stage == UPDATE_BACKREF) {
  7839. BUG_ON(wc->shared_level < level);
  7840. if (level < wc->shared_level)
  7841. goto out;
  7842. ret = find_next_key(path, level + 1, &wc->update_progress);
  7843. if (ret > 0)
  7844. wc->update_ref = 0;
  7845. wc->stage = DROP_REFERENCE;
  7846. wc->shared_level = -1;
  7847. path->slots[level] = 0;
  7848. /*
  7849. * check reference count again if the block isn't locked.
  7850. * we should start walking down the tree again if reference
  7851. * count is one.
  7852. */
  7853. if (!path->locks[level]) {
  7854. BUG_ON(level == 0);
  7855. btrfs_tree_lock(eb);
  7856. btrfs_set_lock_blocking(eb);
  7857. path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
  7858. ret = btrfs_lookup_extent_info(trans, fs_info,
  7859. eb->start, level, 1,
  7860. &wc->refs[level],
  7861. &wc->flags[level]);
  7862. if (ret < 0) {
  7863. btrfs_tree_unlock_rw(eb, path->locks[level]);
  7864. path->locks[level] = 0;
  7865. return ret;
  7866. }
  7867. BUG_ON(wc->refs[level] == 0);
  7868. if (wc->refs[level] == 1) {
  7869. btrfs_tree_unlock_rw(eb, path->locks[level]);
  7870. path->locks[level] = 0;
  7871. return 1;
  7872. }
  7873. }
  7874. }
  7875. /* wc->stage == DROP_REFERENCE */
  7876. BUG_ON(wc->refs[level] > 1 && !path->locks[level]);
  7877. if (wc->refs[level] == 1) {
  7878. if (level == 0) {
  7879. if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
  7880. ret = btrfs_dec_ref(trans, root, eb, 1);
  7881. else
  7882. ret = btrfs_dec_ref(trans, root, eb, 0);
  7883. BUG_ON(ret); /* -ENOMEM */
  7884. ret = btrfs_qgroup_trace_leaf_items(trans, fs_info, eb);
  7885. if (ret) {
  7886. btrfs_err_rl(fs_info,
  7887. "error %d accounting leaf items. Quota is out of sync, rescan required.",
  7888. ret);
  7889. }
  7890. }
  7891. /* make block locked assertion in clean_tree_block happy */
  7892. if (!path->locks[level] &&
  7893. btrfs_header_generation(eb) == trans->transid) {
  7894. btrfs_tree_lock(eb);
  7895. btrfs_set_lock_blocking(eb);
  7896. path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
  7897. }
  7898. clean_tree_block(fs_info, eb);
  7899. }
  7900. if (eb == root->node) {
  7901. if (wc->flags[level] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
  7902. parent = eb->start;
  7903. else
  7904. BUG_ON(root->root_key.objectid !=
  7905. btrfs_header_owner(eb));
  7906. } else {
  7907. if (wc->flags[level + 1] & BTRFS_BLOCK_FLAG_FULL_BACKREF)
  7908. parent = path->nodes[level + 1]->start;
  7909. else
  7910. BUG_ON(root->root_key.objectid !=
  7911. btrfs_header_owner(path->nodes[level + 1]));
  7912. }
  7913. btrfs_free_tree_block(trans, root, eb, parent, wc->refs[level] == 1);
  7914. out:
  7915. wc->refs[level] = 0;
  7916. wc->flags[level] = 0;
  7917. return 0;
  7918. }
  7919. static noinline int walk_down_tree(struct btrfs_trans_handle *trans,
  7920. struct btrfs_root *root,
  7921. struct btrfs_path *path,
  7922. struct walk_control *wc)
  7923. {
  7924. int level = wc->level;
  7925. int lookup_info = 1;
  7926. int ret;
  7927. while (level >= 0) {
  7928. ret = walk_down_proc(trans, root, path, wc, lookup_info);
  7929. if (ret > 0)
  7930. break;
  7931. if (level == 0)
  7932. break;
  7933. if (path->slots[level] >=
  7934. btrfs_header_nritems(path->nodes[level]))
  7935. break;
  7936. ret = do_walk_down(trans, root, path, wc, &lookup_info);
  7937. if (ret > 0) {
  7938. path->slots[level]++;
  7939. continue;
  7940. } else if (ret < 0)
  7941. return ret;
  7942. level = wc->level;
  7943. }
  7944. return 0;
  7945. }
  7946. static noinline int walk_up_tree(struct btrfs_trans_handle *trans,
  7947. struct btrfs_root *root,
  7948. struct btrfs_path *path,
  7949. struct walk_control *wc, int max_level)
  7950. {
  7951. int level = wc->level;
  7952. int ret;
  7953. path->slots[level] = btrfs_header_nritems(path->nodes[level]);
  7954. while (level < max_level && path->nodes[level]) {
  7955. wc->level = level;
  7956. if (path->slots[level] + 1 <
  7957. btrfs_header_nritems(path->nodes[level])) {
  7958. path->slots[level]++;
  7959. return 0;
  7960. } else {
  7961. ret = walk_up_proc(trans, root, path, wc);
  7962. if (ret > 0)
  7963. return 0;
  7964. if (path->locks[level]) {
  7965. btrfs_tree_unlock_rw(path->nodes[level],
  7966. path->locks[level]);
  7967. path->locks[level] = 0;
  7968. }
  7969. free_extent_buffer(path->nodes[level]);
  7970. path->nodes[level] = NULL;
  7971. level++;
  7972. }
  7973. }
  7974. return 1;
  7975. }
  7976. /*
  7977. * drop a subvolume tree.
  7978. *
  7979. * this function traverses the tree freeing any blocks that only
  7980. * referenced by the tree.
  7981. *
  7982. * when a shared tree block is found. this function decreases its
  7983. * reference count by one. if update_ref is true, this function
  7984. * also make sure backrefs for the shared block and all lower level
  7985. * blocks are properly updated.
  7986. *
  7987. * If called with for_reloc == 0, may exit early with -EAGAIN
  7988. */
  7989. int btrfs_drop_snapshot(struct btrfs_root *root,
  7990. struct btrfs_block_rsv *block_rsv, int update_ref,
  7991. int for_reloc)
  7992. {
  7993. struct btrfs_fs_info *fs_info = root->fs_info;
  7994. struct btrfs_path *path;
  7995. struct btrfs_trans_handle *trans;
  7996. struct btrfs_root *tree_root = fs_info->tree_root;
  7997. struct btrfs_root_item *root_item = &root->root_item;
  7998. struct walk_control *wc;
  7999. struct btrfs_key key;
  8000. int err = 0;
  8001. int ret;
  8002. int level;
  8003. bool root_dropped = false;
  8004. btrfs_debug(fs_info, "Drop subvolume %llu", root->objectid);
  8005. path = btrfs_alloc_path();
  8006. if (!path) {
  8007. err = -ENOMEM;
  8008. goto out;
  8009. }
  8010. wc = kzalloc(sizeof(*wc), GFP_NOFS);
  8011. if (!wc) {
  8012. btrfs_free_path(path);
  8013. err = -ENOMEM;
  8014. goto out;
  8015. }
  8016. trans = btrfs_start_transaction(tree_root, 0);
  8017. if (IS_ERR(trans)) {
  8018. err = PTR_ERR(trans);
  8019. goto out_free;
  8020. }
  8021. if (block_rsv)
  8022. trans->block_rsv = block_rsv;
  8023. if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
  8024. level = btrfs_header_level(root->node);
  8025. path->nodes[level] = btrfs_lock_root_node(root);
  8026. btrfs_set_lock_blocking(path->nodes[level]);
  8027. path->slots[level] = 0;
  8028. path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
  8029. memset(&wc->update_progress, 0,
  8030. sizeof(wc->update_progress));
  8031. } else {
  8032. btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
  8033. memcpy(&wc->update_progress, &key,
  8034. sizeof(wc->update_progress));
  8035. level = root_item->drop_level;
  8036. BUG_ON(level == 0);
  8037. path->lowest_level = level;
  8038. ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
  8039. path->lowest_level = 0;
  8040. if (ret < 0) {
  8041. err = ret;
  8042. goto out_end_trans;
  8043. }
  8044. WARN_ON(ret > 0);
  8045. /*
  8046. * unlock our path, this is safe because only this
  8047. * function is allowed to delete this snapshot
  8048. */
  8049. btrfs_unlock_up_safe(path, 0);
  8050. level = btrfs_header_level(root->node);
  8051. while (1) {
  8052. btrfs_tree_lock(path->nodes[level]);
  8053. btrfs_set_lock_blocking(path->nodes[level]);
  8054. path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
  8055. ret = btrfs_lookup_extent_info(trans, fs_info,
  8056. path->nodes[level]->start,
  8057. level, 1, &wc->refs[level],
  8058. &wc->flags[level]);
  8059. if (ret < 0) {
  8060. err = ret;
  8061. goto out_end_trans;
  8062. }
  8063. BUG_ON(wc->refs[level] == 0);
  8064. if (level == root_item->drop_level)
  8065. break;
  8066. btrfs_tree_unlock(path->nodes[level]);
  8067. path->locks[level] = 0;
  8068. WARN_ON(wc->refs[level] != 1);
  8069. level--;
  8070. }
  8071. }
  8072. wc->level = level;
  8073. wc->shared_level = -1;
  8074. wc->stage = DROP_REFERENCE;
  8075. wc->update_ref = update_ref;
  8076. wc->keep_locks = 0;
  8077. wc->for_reloc = for_reloc;
  8078. wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
  8079. while (1) {
  8080. ret = walk_down_tree(trans, root, path, wc);
  8081. if (ret < 0) {
  8082. err = ret;
  8083. break;
  8084. }
  8085. ret = walk_up_tree(trans, root, path, wc, BTRFS_MAX_LEVEL);
  8086. if (ret < 0) {
  8087. err = ret;
  8088. break;
  8089. }
  8090. if (ret > 0) {
  8091. BUG_ON(wc->stage != DROP_REFERENCE);
  8092. break;
  8093. }
  8094. if (wc->stage == DROP_REFERENCE) {
  8095. level = wc->level;
  8096. btrfs_node_key(path->nodes[level],
  8097. &root_item->drop_progress,
  8098. path->slots[level]);
  8099. root_item->drop_level = level;
  8100. }
  8101. BUG_ON(wc->level == 0);
  8102. if (btrfs_should_end_transaction(trans) ||
  8103. (!for_reloc && btrfs_need_cleaner_sleep(fs_info))) {
  8104. ret = btrfs_update_root(trans, tree_root,
  8105. &root->root_key,
  8106. root_item);
  8107. if (ret) {
  8108. btrfs_abort_transaction(trans, ret);
  8109. err = ret;
  8110. goto out_end_trans;
  8111. }
  8112. btrfs_end_transaction_throttle(trans);
  8113. if (!for_reloc && btrfs_need_cleaner_sleep(fs_info)) {
  8114. btrfs_debug(fs_info,
  8115. "drop snapshot early exit");
  8116. err = -EAGAIN;
  8117. goto out_free;
  8118. }
  8119. trans = btrfs_start_transaction(tree_root, 0);
  8120. if (IS_ERR(trans)) {
  8121. err = PTR_ERR(trans);
  8122. goto out_free;
  8123. }
  8124. if (block_rsv)
  8125. trans->block_rsv = block_rsv;
  8126. }
  8127. }
  8128. btrfs_release_path(path);
  8129. if (err)
  8130. goto out_end_trans;
  8131. ret = btrfs_del_root(trans, fs_info, &root->root_key);
  8132. if (ret) {
  8133. btrfs_abort_transaction(trans, ret);
  8134. err = ret;
  8135. goto out_end_trans;
  8136. }
  8137. if (root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID) {
  8138. ret = btrfs_find_root(tree_root, &root->root_key, path,
  8139. NULL, NULL);
  8140. if (ret < 0) {
  8141. btrfs_abort_transaction(trans, ret);
  8142. err = ret;
  8143. goto out_end_trans;
  8144. } else if (ret > 0) {
  8145. /* if we fail to delete the orphan item this time
  8146. * around, it'll get picked up the next time.
  8147. *
  8148. * The most common failure here is just -ENOENT.
  8149. */
  8150. btrfs_del_orphan_item(trans, tree_root,
  8151. root->root_key.objectid);
  8152. }
  8153. }
  8154. if (test_bit(BTRFS_ROOT_IN_RADIX, &root->state)) {
  8155. btrfs_add_dropped_root(trans, root);
  8156. } else {
  8157. free_extent_buffer(root->node);
  8158. free_extent_buffer(root->commit_root);
  8159. btrfs_put_fs_root(root);
  8160. }
  8161. root_dropped = true;
  8162. out_end_trans:
  8163. btrfs_end_transaction_throttle(trans);
  8164. out_free:
  8165. kfree(wc);
  8166. btrfs_free_path(path);
  8167. out:
  8168. /*
  8169. * So if we need to stop dropping the snapshot for whatever reason we
  8170. * need to make sure to add it back to the dead root list so that we
  8171. * keep trying to do the work later. This also cleans up roots if we
  8172. * don't have it in the radix (like when we recover after a power fail
  8173. * or unmount) so we don't leak memory.
  8174. */
  8175. if (!for_reloc && !root_dropped)
  8176. btrfs_add_dead_root(root);
  8177. if (err && err != -EAGAIN)
  8178. btrfs_handle_fs_error(fs_info, err, NULL);
  8179. return err;
  8180. }
  8181. /*
  8182. * drop subtree rooted at tree block 'node'.
  8183. *
  8184. * NOTE: this function will unlock and release tree block 'node'
  8185. * only used by relocation code
  8186. */
  8187. int btrfs_drop_subtree(struct btrfs_trans_handle *trans,
  8188. struct btrfs_root *root,
  8189. struct extent_buffer *node,
  8190. struct extent_buffer *parent)
  8191. {
  8192. struct btrfs_fs_info *fs_info = root->fs_info;
  8193. struct btrfs_path *path;
  8194. struct walk_control *wc;
  8195. int level;
  8196. int parent_level;
  8197. int ret = 0;
  8198. int wret;
  8199. BUG_ON(root->root_key.objectid != BTRFS_TREE_RELOC_OBJECTID);
  8200. path = btrfs_alloc_path();
  8201. if (!path)
  8202. return -ENOMEM;
  8203. wc = kzalloc(sizeof(*wc), GFP_NOFS);
  8204. if (!wc) {
  8205. btrfs_free_path(path);
  8206. return -ENOMEM;
  8207. }
  8208. btrfs_assert_tree_locked(parent);
  8209. parent_level = btrfs_header_level(parent);
  8210. extent_buffer_get(parent);
  8211. path->nodes[parent_level] = parent;
  8212. path->slots[parent_level] = btrfs_header_nritems(parent);
  8213. btrfs_assert_tree_locked(node);
  8214. level = btrfs_header_level(node);
  8215. path->nodes[level] = node;
  8216. path->slots[level] = 0;
  8217. path->locks[level] = BTRFS_WRITE_LOCK_BLOCKING;
  8218. wc->refs[parent_level] = 1;
  8219. wc->flags[parent_level] = BTRFS_BLOCK_FLAG_FULL_BACKREF;
  8220. wc->level = level;
  8221. wc->shared_level = -1;
  8222. wc->stage = DROP_REFERENCE;
  8223. wc->update_ref = 0;
  8224. wc->keep_locks = 1;
  8225. wc->for_reloc = 1;
  8226. wc->reada_count = BTRFS_NODEPTRS_PER_BLOCK(fs_info);
  8227. while (1) {
  8228. wret = walk_down_tree(trans, root, path, wc);
  8229. if (wret < 0) {
  8230. ret = wret;
  8231. break;
  8232. }
  8233. wret = walk_up_tree(trans, root, path, wc, parent_level);
  8234. if (wret < 0)
  8235. ret = wret;
  8236. if (wret != 0)
  8237. break;
  8238. }
  8239. kfree(wc);
  8240. btrfs_free_path(path);
  8241. return ret;
  8242. }
  8243. static u64 update_block_group_flags(struct btrfs_fs_info *fs_info, u64 flags)
  8244. {
  8245. u64 num_devices;
  8246. u64 stripped;
  8247. /*
  8248. * if restripe for this chunk_type is on pick target profile and
  8249. * return, otherwise do the usual balance
  8250. */
  8251. stripped = get_restripe_target(fs_info, flags);
  8252. if (stripped)
  8253. return extended_to_chunk(stripped);
  8254. num_devices = fs_info->fs_devices->rw_devices;
  8255. stripped = BTRFS_BLOCK_GROUP_RAID0 |
  8256. BTRFS_BLOCK_GROUP_RAID5 | BTRFS_BLOCK_GROUP_RAID6 |
  8257. BTRFS_BLOCK_GROUP_RAID1 | BTRFS_BLOCK_GROUP_RAID10;
  8258. if (num_devices == 1) {
  8259. stripped |= BTRFS_BLOCK_GROUP_DUP;
  8260. stripped = flags & ~stripped;
  8261. /* turn raid0 into single device chunks */
  8262. if (flags & BTRFS_BLOCK_GROUP_RAID0)
  8263. return stripped;
  8264. /* turn mirroring into duplication */
  8265. if (flags & (BTRFS_BLOCK_GROUP_RAID1 |
  8266. BTRFS_BLOCK_GROUP_RAID10))
  8267. return stripped | BTRFS_BLOCK_GROUP_DUP;
  8268. } else {
  8269. /* they already had raid on here, just return */
  8270. if (flags & stripped)
  8271. return flags;
  8272. stripped |= BTRFS_BLOCK_GROUP_DUP;
  8273. stripped = flags & ~stripped;
  8274. /* switch duplicated blocks with raid1 */
  8275. if (flags & BTRFS_BLOCK_GROUP_DUP)
  8276. return stripped | BTRFS_BLOCK_GROUP_RAID1;
  8277. /* this is drive concat, leave it alone */
  8278. }
  8279. return flags;
  8280. }
  8281. static int inc_block_group_ro(struct btrfs_block_group_cache *cache, int force)
  8282. {
  8283. struct btrfs_space_info *sinfo = cache->space_info;
  8284. u64 num_bytes;
  8285. u64 min_allocable_bytes;
  8286. int ret = -ENOSPC;
  8287. /*
  8288. * We need some metadata space and system metadata space for
  8289. * allocating chunks in some corner cases until we force to set
  8290. * it to be readonly.
  8291. */
  8292. if ((sinfo->flags &
  8293. (BTRFS_BLOCK_GROUP_SYSTEM | BTRFS_BLOCK_GROUP_METADATA)) &&
  8294. !force)
  8295. min_allocable_bytes = SZ_1M;
  8296. else
  8297. min_allocable_bytes = 0;
  8298. spin_lock(&sinfo->lock);
  8299. spin_lock(&cache->lock);
  8300. if (cache->ro) {
  8301. cache->ro++;
  8302. ret = 0;
  8303. goto out;
  8304. }
  8305. num_bytes = cache->key.offset - cache->reserved - cache->pinned -
  8306. cache->bytes_super - btrfs_block_group_used(&cache->item);
  8307. if (btrfs_space_info_used(sinfo, true) + num_bytes +
  8308. min_allocable_bytes <= sinfo->total_bytes) {
  8309. sinfo->bytes_readonly += num_bytes;
  8310. cache->ro++;
  8311. list_add_tail(&cache->ro_list, &sinfo->ro_bgs);
  8312. ret = 0;
  8313. }
  8314. out:
  8315. spin_unlock(&cache->lock);
  8316. spin_unlock(&sinfo->lock);
  8317. return ret;
  8318. }
  8319. int btrfs_inc_block_group_ro(struct btrfs_fs_info *fs_info,
  8320. struct btrfs_block_group_cache *cache)
  8321. {
  8322. struct btrfs_trans_handle *trans;
  8323. u64 alloc_flags;
  8324. int ret;
  8325. again:
  8326. trans = btrfs_join_transaction(fs_info->extent_root);
  8327. if (IS_ERR(trans))
  8328. return PTR_ERR(trans);
  8329. /*
  8330. * we're not allowed to set block groups readonly after the dirty
  8331. * block groups cache has started writing. If it already started,
  8332. * back off and let this transaction commit
  8333. */
  8334. mutex_lock(&fs_info->ro_block_group_mutex);
  8335. if (test_bit(BTRFS_TRANS_DIRTY_BG_RUN, &trans->transaction->flags)) {
  8336. u64 transid = trans->transid;
  8337. mutex_unlock(&fs_info->ro_block_group_mutex);
  8338. btrfs_end_transaction(trans);
  8339. ret = btrfs_wait_for_commit(fs_info, transid);
  8340. if (ret)
  8341. return ret;
  8342. goto again;
  8343. }
  8344. /*
  8345. * if we are changing raid levels, try to allocate a corresponding
  8346. * block group with the new raid level.
  8347. */
  8348. alloc_flags = update_block_group_flags(fs_info, cache->flags);
  8349. if (alloc_flags != cache->flags) {
  8350. ret = do_chunk_alloc(trans, fs_info, alloc_flags,
  8351. CHUNK_ALLOC_FORCE);
  8352. /*
  8353. * ENOSPC is allowed here, we may have enough space
  8354. * already allocated at the new raid level to
  8355. * carry on
  8356. */
  8357. if (ret == -ENOSPC)
  8358. ret = 0;
  8359. if (ret < 0)
  8360. goto out;
  8361. }
  8362. ret = inc_block_group_ro(cache, 0);
  8363. if (!ret)
  8364. goto out;
  8365. alloc_flags = get_alloc_profile(fs_info, cache->space_info->flags);
  8366. ret = do_chunk_alloc(trans, fs_info, alloc_flags,
  8367. CHUNK_ALLOC_FORCE);
  8368. if (ret < 0)
  8369. goto out;
  8370. ret = inc_block_group_ro(cache, 0);
  8371. out:
  8372. if (cache->flags & BTRFS_BLOCK_GROUP_SYSTEM) {
  8373. alloc_flags = update_block_group_flags(fs_info, cache->flags);
  8374. mutex_lock(&fs_info->chunk_mutex);
  8375. check_system_chunk(trans, fs_info, alloc_flags);
  8376. mutex_unlock(&fs_info->chunk_mutex);
  8377. }
  8378. mutex_unlock(&fs_info->ro_block_group_mutex);
  8379. btrfs_end_transaction(trans);
  8380. return ret;
  8381. }
  8382. int btrfs_force_chunk_alloc(struct btrfs_trans_handle *trans,
  8383. struct btrfs_fs_info *fs_info, u64 type)
  8384. {
  8385. u64 alloc_flags = get_alloc_profile(fs_info, type);
  8386. return do_chunk_alloc(trans, fs_info, alloc_flags, CHUNK_ALLOC_FORCE);
  8387. }
  8388. /*
  8389. * helper to account the unused space of all the readonly block group in the
  8390. * space_info. takes mirrors into account.
  8391. */
  8392. u64 btrfs_account_ro_block_groups_free_space(struct btrfs_space_info *sinfo)
  8393. {
  8394. struct btrfs_block_group_cache *block_group;
  8395. u64 free_bytes = 0;
  8396. int factor;
  8397. /* It's df, we don't care if it's racy */
  8398. if (list_empty(&sinfo->ro_bgs))
  8399. return 0;
  8400. spin_lock(&sinfo->lock);
  8401. list_for_each_entry(block_group, &sinfo->ro_bgs, ro_list) {
  8402. spin_lock(&block_group->lock);
  8403. if (!block_group->ro) {
  8404. spin_unlock(&block_group->lock);
  8405. continue;
  8406. }
  8407. if (block_group->flags & (BTRFS_BLOCK_GROUP_RAID1 |
  8408. BTRFS_BLOCK_GROUP_RAID10 |
  8409. BTRFS_BLOCK_GROUP_DUP))
  8410. factor = 2;
  8411. else
  8412. factor = 1;
  8413. free_bytes += (block_group->key.offset -
  8414. btrfs_block_group_used(&block_group->item)) *
  8415. factor;
  8416. spin_unlock(&block_group->lock);
  8417. }
  8418. spin_unlock(&sinfo->lock);
  8419. return free_bytes;
  8420. }
  8421. void btrfs_dec_block_group_ro(struct btrfs_block_group_cache *cache)
  8422. {
  8423. struct btrfs_space_info *sinfo = cache->space_info;
  8424. u64 num_bytes;
  8425. BUG_ON(!cache->ro);
  8426. spin_lock(&sinfo->lock);
  8427. spin_lock(&cache->lock);
  8428. if (!--cache->ro) {
  8429. num_bytes = cache->key.offset - cache->reserved -
  8430. cache->pinned - cache->bytes_super -
  8431. btrfs_block_group_used(&cache->item);
  8432. sinfo->bytes_readonly -= num_bytes;
  8433. list_del_init(&cache->ro_list);
  8434. }
  8435. spin_unlock(&cache->lock);
  8436. spin_unlock(&sinfo->lock);
  8437. }
  8438. /*
  8439. * checks to see if its even possible to relocate this block group.
  8440. *
  8441. * @return - -1 if it's not a good idea to relocate this block group, 0 if its
  8442. * ok to go ahead and try.
  8443. */
  8444. int btrfs_can_relocate(struct btrfs_fs_info *fs_info, u64 bytenr)
  8445. {
  8446. struct btrfs_root *root = fs_info->extent_root;
  8447. struct btrfs_block_group_cache *block_group;
  8448. struct btrfs_space_info *space_info;
  8449. struct btrfs_fs_devices *fs_devices = fs_info->fs_devices;
  8450. struct btrfs_device *device;
  8451. struct btrfs_trans_handle *trans;
  8452. u64 min_free;
  8453. u64 dev_min = 1;
  8454. u64 dev_nr = 0;
  8455. u64 target;
  8456. int debug;
  8457. int index;
  8458. int full = 0;
  8459. int ret = 0;
  8460. debug = btrfs_test_opt(fs_info, ENOSPC_DEBUG);
  8461. block_group = btrfs_lookup_block_group(fs_info, bytenr);
  8462. /* odd, couldn't find the block group, leave it alone */
  8463. if (!block_group) {
  8464. if (debug)
  8465. btrfs_warn(fs_info,
  8466. "can't find block group for bytenr %llu",
  8467. bytenr);
  8468. return -1;
  8469. }
  8470. min_free = btrfs_block_group_used(&block_group->item);
  8471. /* no bytes used, we're good */
  8472. if (!min_free)
  8473. goto out;
  8474. space_info = block_group->space_info;
  8475. spin_lock(&space_info->lock);
  8476. full = space_info->full;
  8477. /*
  8478. * if this is the last block group we have in this space, we can't
  8479. * relocate it unless we're able to allocate a new chunk below.
  8480. *
  8481. * Otherwise, we need to make sure we have room in the space to handle
  8482. * all of the extents from this block group. If we can, we're good
  8483. */
  8484. if ((space_info->total_bytes != block_group->key.offset) &&
  8485. (btrfs_space_info_used(space_info, false) + min_free <
  8486. space_info->total_bytes)) {
  8487. spin_unlock(&space_info->lock);
  8488. goto out;
  8489. }
  8490. spin_unlock(&space_info->lock);
  8491. /*
  8492. * ok we don't have enough space, but maybe we have free space on our
  8493. * devices to allocate new chunks for relocation, so loop through our
  8494. * alloc devices and guess if we have enough space. if this block
  8495. * group is going to be restriped, run checks against the target
  8496. * profile instead of the current one.
  8497. */
  8498. ret = -1;
  8499. /*
  8500. * index:
  8501. * 0: raid10
  8502. * 1: raid1
  8503. * 2: dup
  8504. * 3: raid0
  8505. * 4: single
  8506. */
  8507. target = get_restripe_target(fs_info, block_group->flags);
  8508. if (target) {
  8509. index = __get_raid_index(extended_to_chunk(target));
  8510. } else {
  8511. /*
  8512. * this is just a balance, so if we were marked as full
  8513. * we know there is no space for a new chunk
  8514. */
  8515. if (full) {
  8516. if (debug)
  8517. btrfs_warn(fs_info,
  8518. "no space to alloc new chunk for block group %llu",
  8519. block_group->key.objectid);
  8520. goto out;
  8521. }
  8522. index = get_block_group_index(block_group);
  8523. }
  8524. if (index == BTRFS_RAID_RAID10) {
  8525. dev_min = 4;
  8526. /* Divide by 2 */
  8527. min_free >>= 1;
  8528. } else if (index == BTRFS_RAID_RAID1) {
  8529. dev_min = 2;
  8530. } else if (index == BTRFS_RAID_DUP) {
  8531. /* Multiply by 2 */
  8532. min_free <<= 1;
  8533. } else if (index == BTRFS_RAID_RAID0) {
  8534. dev_min = fs_devices->rw_devices;
  8535. min_free = div64_u64(min_free, dev_min);
  8536. }
  8537. /* We need to do this so that we can look at pending chunks */
  8538. trans = btrfs_join_transaction(root);
  8539. if (IS_ERR(trans)) {
  8540. ret = PTR_ERR(trans);
  8541. goto out;
  8542. }
  8543. mutex_lock(&fs_info->chunk_mutex);
  8544. list_for_each_entry(device, &fs_devices->alloc_list, dev_alloc_list) {
  8545. u64 dev_offset;
  8546. /*
  8547. * check to make sure we can actually find a chunk with enough
  8548. * space to fit our block group in.
  8549. */
  8550. if (device->total_bytes > device->bytes_used + min_free &&
  8551. !device->is_tgtdev_for_dev_replace) {
  8552. ret = find_free_dev_extent(trans, device, min_free,
  8553. &dev_offset, NULL);
  8554. if (!ret)
  8555. dev_nr++;
  8556. if (dev_nr >= dev_min)
  8557. break;
  8558. ret = -1;
  8559. }
  8560. }
  8561. if (debug && ret == -1)
  8562. btrfs_warn(fs_info,
  8563. "no space to allocate a new chunk for block group %llu",
  8564. block_group->key.objectid);
  8565. mutex_unlock(&fs_info->chunk_mutex);
  8566. btrfs_end_transaction(trans);
  8567. out:
  8568. btrfs_put_block_group(block_group);
  8569. return ret;
  8570. }
  8571. static int find_first_block_group(struct btrfs_fs_info *fs_info,
  8572. struct btrfs_path *path,
  8573. struct btrfs_key *key)
  8574. {
  8575. struct btrfs_root *root = fs_info->extent_root;
  8576. int ret = 0;
  8577. struct btrfs_key found_key;
  8578. struct extent_buffer *leaf;
  8579. int slot;
  8580. ret = btrfs_search_slot(NULL, root, key, path, 0, 0);
  8581. if (ret < 0)
  8582. goto out;
  8583. while (1) {
  8584. slot = path->slots[0];
  8585. leaf = path->nodes[0];
  8586. if (slot >= btrfs_header_nritems(leaf)) {
  8587. ret = btrfs_next_leaf(root, path);
  8588. if (ret == 0)
  8589. continue;
  8590. if (ret < 0)
  8591. goto out;
  8592. break;
  8593. }
  8594. btrfs_item_key_to_cpu(leaf, &found_key, slot);
  8595. if (found_key.objectid >= key->objectid &&
  8596. found_key.type == BTRFS_BLOCK_GROUP_ITEM_KEY) {
  8597. struct extent_map_tree *em_tree;
  8598. struct extent_map *em;
  8599. em_tree = &root->fs_info->mapping_tree.map_tree;
  8600. read_lock(&em_tree->lock);
  8601. em = lookup_extent_mapping(em_tree, found_key.objectid,
  8602. found_key.offset);
  8603. read_unlock(&em_tree->lock);
  8604. if (!em) {
  8605. btrfs_err(fs_info,
  8606. "logical %llu len %llu found bg but no related chunk",
  8607. found_key.objectid, found_key.offset);
  8608. ret = -ENOENT;
  8609. } else {
  8610. ret = 0;
  8611. }
  8612. free_extent_map(em);
  8613. goto out;
  8614. }
  8615. path->slots[0]++;
  8616. }
  8617. out:
  8618. return ret;
  8619. }
  8620. void btrfs_put_block_group_cache(struct btrfs_fs_info *info)
  8621. {
  8622. struct btrfs_block_group_cache *block_group;
  8623. u64 last = 0;
  8624. while (1) {
  8625. struct inode *inode;
  8626. block_group = btrfs_lookup_first_block_group(info, last);
  8627. while (block_group) {
  8628. spin_lock(&block_group->lock);
  8629. if (block_group->iref)
  8630. break;
  8631. spin_unlock(&block_group->lock);
  8632. block_group = next_block_group(info, block_group);
  8633. }
  8634. if (!block_group) {
  8635. if (last == 0)
  8636. break;
  8637. last = 0;
  8638. continue;
  8639. }
  8640. inode = block_group->inode;
  8641. block_group->iref = 0;
  8642. block_group->inode = NULL;
  8643. spin_unlock(&block_group->lock);
  8644. ASSERT(block_group->io_ctl.inode == NULL);
  8645. iput(inode);
  8646. last = block_group->key.objectid + block_group->key.offset;
  8647. btrfs_put_block_group(block_group);
  8648. }
  8649. }
  8650. /*
  8651. * Must be called only after stopping all workers, since we could have block
  8652. * group caching kthreads running, and therefore they could race with us if we
  8653. * freed the block groups before stopping them.
  8654. */
  8655. int btrfs_free_block_groups(struct btrfs_fs_info *info)
  8656. {
  8657. struct btrfs_block_group_cache *block_group;
  8658. struct btrfs_space_info *space_info;
  8659. struct btrfs_caching_control *caching_ctl;
  8660. struct rb_node *n;
  8661. down_write(&info->commit_root_sem);
  8662. while (!list_empty(&info->caching_block_groups)) {
  8663. caching_ctl = list_entry(info->caching_block_groups.next,
  8664. struct btrfs_caching_control, list);
  8665. list_del(&caching_ctl->list);
  8666. put_caching_control(caching_ctl);
  8667. }
  8668. up_write(&info->commit_root_sem);
  8669. spin_lock(&info->unused_bgs_lock);
  8670. while (!list_empty(&info->unused_bgs)) {
  8671. block_group = list_first_entry(&info->unused_bgs,
  8672. struct btrfs_block_group_cache,
  8673. bg_list);
  8674. list_del_init(&block_group->bg_list);
  8675. btrfs_put_block_group(block_group);
  8676. }
  8677. spin_unlock(&info->unused_bgs_lock);
  8678. spin_lock(&info->block_group_cache_lock);
  8679. while ((n = rb_last(&info->block_group_cache_tree)) != NULL) {
  8680. block_group = rb_entry(n, struct btrfs_block_group_cache,
  8681. cache_node);
  8682. rb_erase(&block_group->cache_node,
  8683. &info->block_group_cache_tree);
  8684. RB_CLEAR_NODE(&block_group->cache_node);
  8685. spin_unlock(&info->block_group_cache_lock);
  8686. down_write(&block_group->space_info->groups_sem);
  8687. list_del(&block_group->list);
  8688. up_write(&block_group->space_info->groups_sem);
  8689. /*
  8690. * We haven't cached this block group, which means we could
  8691. * possibly have excluded extents on this block group.
  8692. */
  8693. if (block_group->cached == BTRFS_CACHE_NO ||
  8694. block_group->cached == BTRFS_CACHE_ERROR)
  8695. free_excluded_extents(info, block_group);
  8696. btrfs_remove_free_space_cache(block_group);
  8697. ASSERT(block_group->cached != BTRFS_CACHE_STARTED);
  8698. ASSERT(list_empty(&block_group->dirty_list));
  8699. ASSERT(list_empty(&block_group->io_list));
  8700. ASSERT(list_empty(&block_group->bg_list));
  8701. ASSERT(atomic_read(&block_group->count) == 1);
  8702. btrfs_put_block_group(block_group);
  8703. spin_lock(&info->block_group_cache_lock);
  8704. }
  8705. spin_unlock(&info->block_group_cache_lock);
  8706. /* now that all the block groups are freed, go through and
  8707. * free all the space_info structs. This is only called during
  8708. * the final stages of unmount, and so we know nobody is
  8709. * using them. We call synchronize_rcu() once before we start,
  8710. * just to be on the safe side.
  8711. */
  8712. synchronize_rcu();
  8713. release_global_block_rsv(info);
  8714. while (!list_empty(&info->space_info)) {
  8715. int i;
  8716. space_info = list_entry(info->space_info.next,
  8717. struct btrfs_space_info,
  8718. list);
  8719. /*
  8720. * Do not hide this behind enospc_debug, this is actually
  8721. * important and indicates a real bug if this happens.
  8722. */
  8723. if (WARN_ON(space_info->bytes_pinned > 0 ||
  8724. space_info->bytes_reserved > 0 ||
  8725. space_info->bytes_may_use > 0))
  8726. dump_space_info(info, space_info, 0, 0);
  8727. list_del(&space_info->list);
  8728. for (i = 0; i < BTRFS_NR_RAID_TYPES; i++) {
  8729. struct kobject *kobj;
  8730. kobj = space_info->block_group_kobjs[i];
  8731. space_info->block_group_kobjs[i] = NULL;
  8732. if (kobj) {
  8733. kobject_del(kobj);
  8734. kobject_put(kobj);
  8735. }
  8736. }
  8737. kobject_del(&space_info->kobj);
  8738. kobject_put(&space_info->kobj);
  8739. }
  8740. return 0;
  8741. }
  8742. static void link_block_group(struct btrfs_block_group_cache *cache)
  8743. {
  8744. struct btrfs_space_info *space_info = cache->space_info;
  8745. int index = get_block_group_index(cache);
  8746. bool first = false;
  8747. down_write(&space_info->groups_sem);
  8748. if (list_empty(&space_info->block_groups[index]))
  8749. first = true;
  8750. list_add_tail(&cache->list, &space_info->block_groups[index]);
  8751. up_write(&space_info->groups_sem);
  8752. if (first) {
  8753. struct raid_kobject *rkobj;
  8754. int ret;
  8755. rkobj = kzalloc(sizeof(*rkobj), GFP_NOFS);
  8756. if (!rkobj)
  8757. goto out_err;
  8758. rkobj->raid_type = index;
  8759. kobject_init(&rkobj->kobj, &btrfs_raid_ktype);
  8760. ret = kobject_add(&rkobj->kobj, &space_info->kobj,
  8761. "%s", get_raid_name(index));
  8762. if (ret) {
  8763. kobject_put(&rkobj->kobj);
  8764. goto out_err;
  8765. }
  8766. space_info->block_group_kobjs[index] = &rkobj->kobj;
  8767. }
  8768. return;
  8769. out_err:
  8770. btrfs_warn(cache->fs_info,
  8771. "failed to add kobject for block cache, ignoring");
  8772. }
  8773. static struct btrfs_block_group_cache *
  8774. btrfs_create_block_group_cache(struct btrfs_fs_info *fs_info,
  8775. u64 start, u64 size)
  8776. {
  8777. struct btrfs_block_group_cache *cache;
  8778. cache = kzalloc(sizeof(*cache), GFP_NOFS);
  8779. if (!cache)
  8780. return NULL;
  8781. cache->free_space_ctl = kzalloc(sizeof(*cache->free_space_ctl),
  8782. GFP_NOFS);
  8783. if (!cache->free_space_ctl) {
  8784. kfree(cache);
  8785. return NULL;
  8786. }
  8787. cache->key.objectid = start;
  8788. cache->key.offset = size;
  8789. cache->key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
  8790. cache->fs_info = fs_info;
  8791. cache->full_stripe_len = btrfs_full_stripe_len(fs_info, start);
  8792. set_free_space_tree_thresholds(cache);
  8793. atomic_set(&cache->count, 1);
  8794. spin_lock_init(&cache->lock);
  8795. init_rwsem(&cache->data_rwsem);
  8796. INIT_LIST_HEAD(&cache->list);
  8797. INIT_LIST_HEAD(&cache->cluster_list);
  8798. INIT_LIST_HEAD(&cache->bg_list);
  8799. INIT_LIST_HEAD(&cache->ro_list);
  8800. INIT_LIST_HEAD(&cache->dirty_list);
  8801. INIT_LIST_HEAD(&cache->io_list);
  8802. btrfs_init_free_space_ctl(cache);
  8803. atomic_set(&cache->trimming, 0);
  8804. mutex_init(&cache->free_space_lock);
  8805. btrfs_init_full_stripe_locks_tree(&cache->full_stripe_locks_root);
  8806. return cache;
  8807. }
  8808. int btrfs_read_block_groups(struct btrfs_fs_info *info)
  8809. {
  8810. struct btrfs_path *path;
  8811. int ret;
  8812. struct btrfs_block_group_cache *cache;
  8813. struct btrfs_space_info *space_info;
  8814. struct btrfs_key key;
  8815. struct btrfs_key found_key;
  8816. struct extent_buffer *leaf;
  8817. int need_clear = 0;
  8818. u64 cache_gen;
  8819. u64 feature;
  8820. int mixed;
  8821. feature = btrfs_super_incompat_flags(info->super_copy);
  8822. mixed = !!(feature & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS);
  8823. key.objectid = 0;
  8824. key.offset = 0;
  8825. key.type = BTRFS_BLOCK_GROUP_ITEM_KEY;
  8826. path = btrfs_alloc_path();
  8827. if (!path)
  8828. return -ENOMEM;
  8829. path->reada = READA_FORWARD;
  8830. cache_gen = btrfs_super_cache_generation(info->super_copy);
  8831. if (btrfs_test_opt(info, SPACE_CACHE) &&
  8832. btrfs_super_generation(info->super_copy) != cache_gen)
  8833. need_clear = 1;
  8834. if (btrfs_test_opt(info, CLEAR_CACHE))
  8835. need_clear = 1;
  8836. while (1) {
  8837. ret = find_first_block_group(info, path, &key);
  8838. if (ret > 0)
  8839. break;
  8840. if (ret != 0)
  8841. goto error;
  8842. leaf = path->nodes[0];
  8843. btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
  8844. cache = btrfs_create_block_group_cache(info, found_key.objectid,
  8845. found_key.offset);
  8846. if (!cache) {
  8847. ret = -ENOMEM;
  8848. goto error;
  8849. }
  8850. if (need_clear) {
  8851. /*
  8852. * When we mount with old space cache, we need to
  8853. * set BTRFS_DC_CLEAR and set dirty flag.
  8854. *
  8855. * a) Setting 'BTRFS_DC_CLEAR' makes sure that we
  8856. * truncate the old free space cache inode and
  8857. * setup a new one.
  8858. * b) Setting 'dirty flag' makes sure that we flush
  8859. * the new space cache info onto disk.
  8860. */
  8861. if (btrfs_test_opt(info, SPACE_CACHE))
  8862. cache->disk_cache_state = BTRFS_DC_CLEAR;
  8863. }
  8864. read_extent_buffer(leaf, &cache->item,
  8865. btrfs_item_ptr_offset(leaf, path->slots[0]),
  8866. sizeof(cache->item));
  8867. cache->flags = btrfs_block_group_flags(&cache->item);
  8868. if (!mixed &&
  8869. ((cache->flags & BTRFS_BLOCK_GROUP_METADATA) &&
  8870. (cache->flags & BTRFS_BLOCK_GROUP_DATA))) {
  8871. btrfs_err(info,
  8872. "bg %llu is a mixed block group but filesystem hasn't enabled mixed block groups",
  8873. cache->key.objectid);
  8874. ret = -EINVAL;
  8875. goto error;
  8876. }
  8877. key.objectid = found_key.objectid + found_key.offset;
  8878. btrfs_release_path(path);
  8879. /*
  8880. * We need to exclude the super stripes now so that the space
  8881. * info has super bytes accounted for, otherwise we'll think
  8882. * we have more space than we actually do.
  8883. */
  8884. ret = exclude_super_stripes(info, cache);
  8885. if (ret) {
  8886. /*
  8887. * We may have excluded something, so call this just in
  8888. * case.
  8889. */
  8890. free_excluded_extents(info, cache);
  8891. btrfs_put_block_group(cache);
  8892. goto error;
  8893. }
  8894. /*
  8895. * check for two cases, either we are full, and therefore
  8896. * don't need to bother with the caching work since we won't
  8897. * find any space, or we are empty, and we can just add all
  8898. * the space in and be done with it. This saves us _alot_ of
  8899. * time, particularly in the full case.
  8900. */
  8901. if (found_key.offset == btrfs_block_group_used(&cache->item)) {
  8902. cache->last_byte_to_unpin = (u64)-1;
  8903. cache->cached = BTRFS_CACHE_FINISHED;
  8904. free_excluded_extents(info, cache);
  8905. } else if (btrfs_block_group_used(&cache->item) == 0) {
  8906. cache->last_byte_to_unpin = (u64)-1;
  8907. cache->cached = BTRFS_CACHE_FINISHED;
  8908. add_new_free_space(cache, info,
  8909. found_key.objectid,
  8910. found_key.objectid +
  8911. found_key.offset);
  8912. free_excluded_extents(info, cache);
  8913. }
  8914. ret = btrfs_add_block_group_cache(info, cache);
  8915. if (ret) {
  8916. btrfs_remove_free_space_cache(cache);
  8917. btrfs_put_block_group(cache);
  8918. goto error;
  8919. }
  8920. trace_btrfs_add_block_group(info, cache, 0);
  8921. update_space_info(info, cache->flags, found_key.offset,
  8922. btrfs_block_group_used(&cache->item),
  8923. cache->bytes_super, &space_info);
  8924. cache->space_info = space_info;
  8925. link_block_group(cache);
  8926. set_avail_alloc_bits(info, cache->flags);
  8927. if (btrfs_chunk_readonly(info, cache->key.objectid)) {
  8928. inc_block_group_ro(cache, 1);
  8929. } else if (btrfs_block_group_used(&cache->item) == 0) {
  8930. spin_lock(&info->unused_bgs_lock);
  8931. /* Should always be true but just in case. */
  8932. if (list_empty(&cache->bg_list)) {
  8933. btrfs_get_block_group(cache);
  8934. list_add_tail(&cache->bg_list,
  8935. &info->unused_bgs);
  8936. }
  8937. spin_unlock(&info->unused_bgs_lock);
  8938. }
  8939. }
  8940. list_for_each_entry_rcu(space_info, &info->space_info, list) {
  8941. if (!(get_alloc_profile(info, space_info->flags) &
  8942. (BTRFS_BLOCK_GROUP_RAID10 |
  8943. BTRFS_BLOCK_GROUP_RAID1 |
  8944. BTRFS_BLOCK_GROUP_RAID5 |
  8945. BTRFS_BLOCK_GROUP_RAID6 |
  8946. BTRFS_BLOCK_GROUP_DUP)))
  8947. continue;
  8948. /*
  8949. * avoid allocating from un-mirrored block group if there are
  8950. * mirrored block groups.
  8951. */
  8952. list_for_each_entry(cache,
  8953. &space_info->block_groups[BTRFS_RAID_RAID0],
  8954. list)
  8955. inc_block_group_ro(cache, 1);
  8956. list_for_each_entry(cache,
  8957. &space_info->block_groups[BTRFS_RAID_SINGLE],
  8958. list)
  8959. inc_block_group_ro(cache, 1);
  8960. }
  8961. init_global_block_rsv(info);
  8962. ret = 0;
  8963. error:
  8964. btrfs_free_path(path);
  8965. return ret;
  8966. }
  8967. void btrfs_create_pending_block_groups(struct btrfs_trans_handle *trans,
  8968. struct btrfs_fs_info *fs_info)
  8969. {
  8970. struct btrfs_block_group_cache *block_group, *tmp;
  8971. struct btrfs_root *extent_root = fs_info->extent_root;
  8972. struct btrfs_block_group_item item;
  8973. struct btrfs_key key;
  8974. int ret = 0;
  8975. bool can_flush_pending_bgs = trans->can_flush_pending_bgs;
  8976. trans->can_flush_pending_bgs = false;
  8977. list_for_each_entry_safe(block_group, tmp, &trans->new_bgs, bg_list) {
  8978. if (ret)
  8979. goto next;
  8980. spin_lock(&block_group->lock);
  8981. memcpy(&item, &block_group->item, sizeof(item));
  8982. memcpy(&key, &block_group->key, sizeof(key));
  8983. spin_unlock(&block_group->lock);
  8984. ret = btrfs_insert_item(trans, extent_root, &key, &item,
  8985. sizeof(item));
  8986. if (ret)
  8987. btrfs_abort_transaction(trans, ret);
  8988. ret = btrfs_finish_chunk_alloc(trans, fs_info, key.objectid,
  8989. key.offset);
  8990. if (ret)
  8991. btrfs_abort_transaction(trans, ret);
  8992. add_block_group_free_space(trans, fs_info, block_group);
  8993. /* already aborted the transaction if it failed. */
  8994. next:
  8995. list_del_init(&block_group->bg_list);
  8996. }
  8997. trans->can_flush_pending_bgs = can_flush_pending_bgs;
  8998. }
  8999. int btrfs_make_block_group(struct btrfs_trans_handle *trans,
  9000. struct btrfs_fs_info *fs_info, u64 bytes_used,
  9001. u64 type, u64 chunk_offset, u64 size)
  9002. {
  9003. struct btrfs_block_group_cache *cache;
  9004. int ret;
  9005. btrfs_set_log_full_commit(fs_info, trans);
  9006. cache = btrfs_create_block_group_cache(fs_info, chunk_offset, size);
  9007. if (!cache)
  9008. return -ENOMEM;
  9009. btrfs_set_block_group_used(&cache->item, bytes_used);
  9010. btrfs_set_block_group_chunk_objectid(&cache->item,
  9011. BTRFS_FIRST_CHUNK_TREE_OBJECTID);
  9012. btrfs_set_block_group_flags(&cache->item, type);
  9013. cache->flags = type;
  9014. cache->last_byte_to_unpin = (u64)-1;
  9015. cache->cached = BTRFS_CACHE_FINISHED;
  9016. cache->needs_free_space = 1;
  9017. ret = exclude_super_stripes(fs_info, cache);
  9018. if (ret) {
  9019. /*
  9020. * We may have excluded something, so call this just in
  9021. * case.
  9022. */
  9023. free_excluded_extents(fs_info, cache);
  9024. btrfs_put_block_group(cache);
  9025. return ret;
  9026. }
  9027. add_new_free_space(cache, fs_info, chunk_offset, chunk_offset + size);
  9028. free_excluded_extents(fs_info, cache);
  9029. #ifdef CONFIG_BTRFS_DEBUG
  9030. if (btrfs_should_fragment_free_space(cache)) {
  9031. u64 new_bytes_used = size - bytes_used;
  9032. bytes_used += new_bytes_used >> 1;
  9033. fragment_free_space(cache);
  9034. }
  9035. #endif
  9036. /*
  9037. * Ensure the corresponding space_info object is created and
  9038. * assigned to our block group. We want our bg to be added to the rbtree
  9039. * with its ->space_info set.
  9040. */
  9041. cache->space_info = __find_space_info(fs_info, cache->flags);
  9042. if (!cache->space_info) {
  9043. ret = create_space_info(fs_info, cache->flags,
  9044. &cache->space_info);
  9045. if (ret) {
  9046. btrfs_remove_free_space_cache(cache);
  9047. btrfs_put_block_group(cache);
  9048. return ret;
  9049. }
  9050. }
  9051. ret = btrfs_add_block_group_cache(fs_info, cache);
  9052. if (ret) {
  9053. btrfs_remove_free_space_cache(cache);
  9054. btrfs_put_block_group(cache);
  9055. return ret;
  9056. }
  9057. /*
  9058. * Now that our block group has its ->space_info set and is inserted in
  9059. * the rbtree, update the space info's counters.
  9060. */
  9061. trace_btrfs_add_block_group(fs_info, cache, 1);
  9062. update_space_info(fs_info, cache->flags, size, bytes_used,
  9063. cache->bytes_super, &cache->space_info);
  9064. update_global_block_rsv(fs_info);
  9065. link_block_group(cache);
  9066. list_add_tail(&cache->bg_list, &trans->new_bgs);
  9067. set_avail_alloc_bits(fs_info, type);
  9068. return 0;
  9069. }
  9070. static void clear_avail_alloc_bits(struct btrfs_fs_info *fs_info, u64 flags)
  9071. {
  9072. u64 extra_flags = chunk_to_extended(flags) &
  9073. BTRFS_EXTENDED_PROFILE_MASK;
  9074. write_seqlock(&fs_info->profiles_lock);
  9075. if (flags & BTRFS_BLOCK_GROUP_DATA)
  9076. fs_info->avail_data_alloc_bits &= ~extra_flags;
  9077. if (flags & BTRFS_BLOCK_GROUP_METADATA)
  9078. fs_info->avail_metadata_alloc_bits &= ~extra_flags;
  9079. if (flags & BTRFS_BLOCK_GROUP_SYSTEM)
  9080. fs_info->avail_system_alloc_bits &= ~extra_flags;
  9081. write_sequnlock(&fs_info->profiles_lock);
  9082. }
  9083. int btrfs_remove_block_group(struct btrfs_trans_handle *trans,
  9084. struct btrfs_fs_info *fs_info, u64 group_start,
  9085. struct extent_map *em)
  9086. {
  9087. struct btrfs_root *root = fs_info->extent_root;
  9088. struct btrfs_path *path;
  9089. struct btrfs_block_group_cache *block_group;
  9090. struct btrfs_free_cluster *cluster;
  9091. struct btrfs_root *tree_root = fs_info->tree_root;
  9092. struct btrfs_key key;
  9093. struct inode *inode;
  9094. struct kobject *kobj = NULL;
  9095. int ret;
  9096. int index;
  9097. int factor;
  9098. struct btrfs_caching_control *caching_ctl = NULL;
  9099. bool remove_em;
  9100. block_group = btrfs_lookup_block_group(fs_info, group_start);
  9101. BUG_ON(!block_group);
  9102. BUG_ON(!block_group->ro);
  9103. /*
  9104. * Free the reserved super bytes from this block group before
  9105. * remove it.
  9106. */
  9107. free_excluded_extents(fs_info, block_group);
  9108. btrfs_free_ref_tree_range(fs_info, block_group->key.objectid,
  9109. block_group->key.offset);
  9110. memcpy(&key, &block_group->key, sizeof(key));
  9111. index = get_block_group_index(block_group);
  9112. if (block_group->flags & (BTRFS_BLOCK_GROUP_DUP |
  9113. BTRFS_BLOCK_GROUP_RAID1 |
  9114. BTRFS_BLOCK_GROUP_RAID10))
  9115. factor = 2;
  9116. else
  9117. factor = 1;
  9118. /* make sure this block group isn't part of an allocation cluster */
  9119. cluster = &fs_info->data_alloc_cluster;
  9120. spin_lock(&cluster->refill_lock);
  9121. btrfs_return_cluster_to_free_space(block_group, cluster);
  9122. spin_unlock(&cluster->refill_lock);
  9123. /*
  9124. * make sure this block group isn't part of a metadata
  9125. * allocation cluster
  9126. */
  9127. cluster = &fs_info->meta_alloc_cluster;
  9128. spin_lock(&cluster->refill_lock);
  9129. btrfs_return_cluster_to_free_space(block_group, cluster);
  9130. spin_unlock(&cluster->refill_lock);
  9131. path = btrfs_alloc_path();
  9132. if (!path) {
  9133. ret = -ENOMEM;
  9134. goto out;
  9135. }
  9136. /*
  9137. * get the inode first so any iput calls done for the io_list
  9138. * aren't the final iput (no unlinks allowed now)
  9139. */
  9140. inode = lookup_free_space_inode(fs_info, block_group, path);
  9141. mutex_lock(&trans->transaction->cache_write_mutex);
  9142. /*
  9143. * make sure our free spache cache IO is done before remove the
  9144. * free space inode
  9145. */
  9146. spin_lock(&trans->transaction->dirty_bgs_lock);
  9147. if (!list_empty(&block_group->io_list)) {
  9148. list_del_init(&block_group->io_list);
  9149. WARN_ON(!IS_ERR(inode) && inode != block_group->io_ctl.inode);
  9150. spin_unlock(&trans->transaction->dirty_bgs_lock);
  9151. btrfs_wait_cache_io(trans, block_group, path);
  9152. btrfs_put_block_group(block_group);
  9153. spin_lock(&trans->transaction->dirty_bgs_lock);
  9154. }
  9155. if (!list_empty(&block_group->dirty_list)) {
  9156. list_del_init(&block_group->dirty_list);
  9157. btrfs_put_block_group(block_group);
  9158. }
  9159. spin_unlock(&trans->transaction->dirty_bgs_lock);
  9160. mutex_unlock(&trans->transaction->cache_write_mutex);
  9161. if (!IS_ERR(inode)) {
  9162. ret = btrfs_orphan_add(trans, BTRFS_I(inode));
  9163. if (ret) {
  9164. btrfs_add_delayed_iput(inode);
  9165. goto out;
  9166. }
  9167. clear_nlink(inode);
  9168. /* One for the block groups ref */
  9169. spin_lock(&block_group->lock);
  9170. if (block_group->iref) {
  9171. block_group->iref = 0;
  9172. block_group->inode = NULL;
  9173. spin_unlock(&block_group->lock);
  9174. iput(inode);
  9175. } else {
  9176. spin_unlock(&block_group->lock);
  9177. }
  9178. /* One for our lookup ref */
  9179. btrfs_add_delayed_iput(inode);
  9180. }
  9181. key.objectid = BTRFS_FREE_SPACE_OBJECTID;
  9182. key.offset = block_group->key.objectid;
  9183. key.type = 0;
  9184. ret = btrfs_search_slot(trans, tree_root, &key, path, -1, 1);
  9185. if (ret < 0)
  9186. goto out;
  9187. if (ret > 0)
  9188. btrfs_release_path(path);
  9189. if (ret == 0) {
  9190. ret = btrfs_del_item(trans, tree_root, path);
  9191. if (ret)
  9192. goto out;
  9193. btrfs_release_path(path);
  9194. }
  9195. spin_lock(&fs_info->block_group_cache_lock);
  9196. rb_erase(&block_group->cache_node,
  9197. &fs_info->block_group_cache_tree);
  9198. RB_CLEAR_NODE(&block_group->cache_node);
  9199. if (fs_info->first_logical_byte == block_group->key.objectid)
  9200. fs_info->first_logical_byte = (u64)-1;
  9201. spin_unlock(&fs_info->block_group_cache_lock);
  9202. down_write(&block_group->space_info->groups_sem);
  9203. /*
  9204. * we must use list_del_init so people can check to see if they
  9205. * are still on the list after taking the semaphore
  9206. */
  9207. list_del_init(&block_group->list);
  9208. if (list_empty(&block_group->space_info->block_groups[index])) {
  9209. kobj = block_group->space_info->block_group_kobjs[index];
  9210. block_group->space_info->block_group_kobjs[index] = NULL;
  9211. clear_avail_alloc_bits(fs_info, block_group->flags);
  9212. }
  9213. up_write(&block_group->space_info->groups_sem);
  9214. if (kobj) {
  9215. kobject_del(kobj);
  9216. kobject_put(kobj);
  9217. }
  9218. if (block_group->has_caching_ctl)
  9219. caching_ctl = get_caching_control(block_group);
  9220. if (block_group->cached == BTRFS_CACHE_STARTED)
  9221. wait_block_group_cache_done(block_group);
  9222. if (block_group->has_caching_ctl) {
  9223. down_write(&fs_info->commit_root_sem);
  9224. if (!caching_ctl) {
  9225. struct btrfs_caching_control *ctl;
  9226. list_for_each_entry(ctl,
  9227. &fs_info->caching_block_groups, list)
  9228. if (ctl->block_group == block_group) {
  9229. caching_ctl = ctl;
  9230. refcount_inc(&caching_ctl->count);
  9231. break;
  9232. }
  9233. }
  9234. if (caching_ctl)
  9235. list_del_init(&caching_ctl->list);
  9236. up_write(&fs_info->commit_root_sem);
  9237. if (caching_ctl) {
  9238. /* Once for the caching bgs list and once for us. */
  9239. put_caching_control(caching_ctl);
  9240. put_caching_control(caching_ctl);
  9241. }
  9242. }
  9243. spin_lock(&trans->transaction->dirty_bgs_lock);
  9244. if (!list_empty(&block_group->dirty_list)) {
  9245. WARN_ON(1);
  9246. }
  9247. if (!list_empty(&block_group->io_list)) {
  9248. WARN_ON(1);
  9249. }
  9250. spin_unlock(&trans->transaction->dirty_bgs_lock);
  9251. btrfs_remove_free_space_cache(block_group);
  9252. spin_lock(&block_group->space_info->lock);
  9253. list_del_init(&block_group->ro_list);
  9254. if (btrfs_test_opt(fs_info, ENOSPC_DEBUG)) {
  9255. WARN_ON(block_group->space_info->total_bytes
  9256. < block_group->key.offset);
  9257. WARN_ON(block_group->space_info->bytes_readonly
  9258. < block_group->key.offset);
  9259. WARN_ON(block_group->space_info->disk_total
  9260. < block_group->key.offset * factor);
  9261. }
  9262. block_group->space_info->total_bytes -= block_group->key.offset;
  9263. block_group->space_info->bytes_readonly -= block_group->key.offset;
  9264. block_group->space_info->disk_total -= block_group->key.offset * factor;
  9265. spin_unlock(&block_group->space_info->lock);
  9266. memcpy(&key, &block_group->key, sizeof(key));
  9267. mutex_lock(&fs_info->chunk_mutex);
  9268. if (!list_empty(&em->list)) {
  9269. /* We're in the transaction->pending_chunks list. */
  9270. free_extent_map(em);
  9271. }
  9272. spin_lock(&block_group->lock);
  9273. block_group->removed = 1;
  9274. /*
  9275. * At this point trimming can't start on this block group, because we
  9276. * removed the block group from the tree fs_info->block_group_cache_tree
  9277. * so no one can't find it anymore and even if someone already got this
  9278. * block group before we removed it from the rbtree, they have already
  9279. * incremented block_group->trimming - if they didn't, they won't find
  9280. * any free space entries because we already removed them all when we
  9281. * called btrfs_remove_free_space_cache().
  9282. *
  9283. * And we must not remove the extent map from the fs_info->mapping_tree
  9284. * to prevent the same logical address range and physical device space
  9285. * ranges from being reused for a new block group. This is because our
  9286. * fs trim operation (btrfs_trim_fs() / btrfs_ioctl_fitrim()) is
  9287. * completely transactionless, so while it is trimming a range the
  9288. * currently running transaction might finish and a new one start,
  9289. * allowing for new block groups to be created that can reuse the same
  9290. * physical device locations unless we take this special care.
  9291. *
  9292. * There may also be an implicit trim operation if the file system
  9293. * is mounted with -odiscard. The same protections must remain
  9294. * in place until the extents have been discarded completely when
  9295. * the transaction commit has completed.
  9296. */
  9297. remove_em = (atomic_read(&block_group->trimming) == 0);
  9298. /*
  9299. * Make sure a trimmer task always sees the em in the pinned_chunks list
  9300. * if it sees block_group->removed == 1 (needs to lock block_group->lock
  9301. * before checking block_group->removed).
  9302. */
  9303. if (!remove_em) {
  9304. /*
  9305. * Our em might be in trans->transaction->pending_chunks which
  9306. * is protected by fs_info->chunk_mutex ([lock|unlock]_chunks),
  9307. * and so is the fs_info->pinned_chunks list.
  9308. *
  9309. * So at this point we must be holding the chunk_mutex to avoid
  9310. * any races with chunk allocation (more specifically at
  9311. * volumes.c:contains_pending_extent()), to ensure it always
  9312. * sees the em, either in the pending_chunks list or in the
  9313. * pinned_chunks list.
  9314. */
  9315. list_move_tail(&em->list, &fs_info->pinned_chunks);
  9316. }
  9317. spin_unlock(&block_group->lock);
  9318. if (remove_em) {
  9319. struct extent_map_tree *em_tree;
  9320. em_tree = &fs_info->mapping_tree.map_tree;
  9321. write_lock(&em_tree->lock);
  9322. /*
  9323. * The em might be in the pending_chunks list, so make sure the
  9324. * chunk mutex is locked, since remove_extent_mapping() will
  9325. * delete us from that list.
  9326. */
  9327. remove_extent_mapping(em_tree, em);
  9328. write_unlock(&em_tree->lock);
  9329. /* once for the tree */
  9330. free_extent_map(em);
  9331. }
  9332. mutex_unlock(&fs_info->chunk_mutex);
  9333. ret = remove_block_group_free_space(trans, fs_info, block_group);
  9334. if (ret)
  9335. goto out;
  9336. btrfs_put_block_group(block_group);
  9337. btrfs_put_block_group(block_group);
  9338. ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
  9339. if (ret > 0)
  9340. ret = -EIO;
  9341. if (ret < 0)
  9342. goto out;
  9343. ret = btrfs_del_item(trans, root, path);
  9344. out:
  9345. btrfs_free_path(path);
  9346. return ret;
  9347. }
  9348. struct btrfs_trans_handle *
  9349. btrfs_start_trans_remove_block_group(struct btrfs_fs_info *fs_info,
  9350. const u64 chunk_offset)
  9351. {
  9352. struct extent_map_tree *em_tree = &fs_info->mapping_tree.map_tree;
  9353. struct extent_map *em;
  9354. struct map_lookup *map;
  9355. unsigned int num_items;
  9356. read_lock(&em_tree->lock);
  9357. em = lookup_extent_mapping(em_tree, chunk_offset, 1);
  9358. read_unlock(&em_tree->lock);
  9359. ASSERT(em && em->start == chunk_offset);
  9360. /*
  9361. * We need to reserve 3 + N units from the metadata space info in order
  9362. * to remove a block group (done at btrfs_remove_chunk() and at
  9363. * btrfs_remove_block_group()), which are used for:
  9364. *
  9365. * 1 unit for adding the free space inode's orphan (located in the tree
  9366. * of tree roots).
  9367. * 1 unit for deleting the block group item (located in the extent
  9368. * tree).
  9369. * 1 unit for deleting the free space item (located in tree of tree
  9370. * roots).
  9371. * N units for deleting N device extent items corresponding to each
  9372. * stripe (located in the device tree).
  9373. *
  9374. * In order to remove a block group we also need to reserve units in the
  9375. * system space info in order to update the chunk tree (update one or
  9376. * more device items and remove one chunk item), but this is done at
  9377. * btrfs_remove_chunk() through a call to check_system_chunk().
  9378. */
  9379. map = em->map_lookup;
  9380. num_items = 3 + map->num_stripes;
  9381. free_extent_map(em);
  9382. return btrfs_start_transaction_fallback_global_rsv(fs_info->extent_root,
  9383. num_items, 1);
  9384. }
  9385. /*
  9386. * Process the unused_bgs list and remove any that don't have any allocated
  9387. * space inside of them.
  9388. */
  9389. void btrfs_delete_unused_bgs(struct btrfs_fs_info *fs_info)
  9390. {
  9391. struct btrfs_block_group_cache *block_group;
  9392. struct btrfs_space_info *space_info;
  9393. struct btrfs_trans_handle *trans;
  9394. int ret = 0;
  9395. if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
  9396. return;
  9397. spin_lock(&fs_info->unused_bgs_lock);
  9398. while (!list_empty(&fs_info->unused_bgs)) {
  9399. u64 start, end;
  9400. int trimming;
  9401. block_group = list_first_entry(&fs_info->unused_bgs,
  9402. struct btrfs_block_group_cache,
  9403. bg_list);
  9404. list_del_init(&block_group->bg_list);
  9405. space_info = block_group->space_info;
  9406. if (ret || btrfs_mixed_space_info(space_info)) {
  9407. btrfs_put_block_group(block_group);
  9408. continue;
  9409. }
  9410. spin_unlock(&fs_info->unused_bgs_lock);
  9411. mutex_lock(&fs_info->delete_unused_bgs_mutex);
  9412. /* Don't want to race with allocators so take the groups_sem */
  9413. down_write(&space_info->groups_sem);
  9414. spin_lock(&block_group->lock);
  9415. if (block_group->reserved ||
  9416. btrfs_block_group_used(&block_group->item) ||
  9417. block_group->ro ||
  9418. list_is_singular(&block_group->list)) {
  9419. /*
  9420. * We want to bail if we made new allocations or have
  9421. * outstanding allocations in this block group. We do
  9422. * the ro check in case balance is currently acting on
  9423. * this block group.
  9424. */
  9425. spin_unlock(&block_group->lock);
  9426. up_write(&space_info->groups_sem);
  9427. goto next;
  9428. }
  9429. spin_unlock(&block_group->lock);
  9430. /* We don't want to force the issue, only flip if it's ok. */
  9431. ret = inc_block_group_ro(block_group, 0);
  9432. up_write(&space_info->groups_sem);
  9433. if (ret < 0) {
  9434. ret = 0;
  9435. goto next;
  9436. }
  9437. /*
  9438. * Want to do this before we do anything else so we can recover
  9439. * properly if we fail to join the transaction.
  9440. */
  9441. trans = btrfs_start_trans_remove_block_group(fs_info,
  9442. block_group->key.objectid);
  9443. if (IS_ERR(trans)) {
  9444. btrfs_dec_block_group_ro(block_group);
  9445. ret = PTR_ERR(trans);
  9446. goto next;
  9447. }
  9448. /*
  9449. * We could have pending pinned extents for this block group,
  9450. * just delete them, we don't care about them anymore.
  9451. */
  9452. start = block_group->key.objectid;
  9453. end = start + block_group->key.offset - 1;
  9454. /*
  9455. * Hold the unused_bg_unpin_mutex lock to avoid racing with
  9456. * btrfs_finish_extent_commit(). If we are at transaction N,
  9457. * another task might be running finish_extent_commit() for the
  9458. * previous transaction N - 1, and have seen a range belonging
  9459. * to the block group in freed_extents[] before we were able to
  9460. * clear the whole block group range from freed_extents[]. This
  9461. * means that task can lookup for the block group after we
  9462. * unpinned it from freed_extents[] and removed it, leading to
  9463. * a BUG_ON() at btrfs_unpin_extent_range().
  9464. */
  9465. mutex_lock(&fs_info->unused_bg_unpin_mutex);
  9466. ret = clear_extent_bits(&fs_info->freed_extents[0], start, end,
  9467. EXTENT_DIRTY);
  9468. if (ret) {
  9469. mutex_unlock(&fs_info->unused_bg_unpin_mutex);
  9470. btrfs_dec_block_group_ro(block_group);
  9471. goto end_trans;
  9472. }
  9473. ret = clear_extent_bits(&fs_info->freed_extents[1], start, end,
  9474. EXTENT_DIRTY);
  9475. if (ret) {
  9476. mutex_unlock(&fs_info->unused_bg_unpin_mutex);
  9477. btrfs_dec_block_group_ro(block_group);
  9478. goto end_trans;
  9479. }
  9480. mutex_unlock(&fs_info->unused_bg_unpin_mutex);
  9481. /* Reset pinned so btrfs_put_block_group doesn't complain */
  9482. spin_lock(&space_info->lock);
  9483. spin_lock(&block_group->lock);
  9484. space_info->bytes_pinned -= block_group->pinned;
  9485. space_info->bytes_readonly += block_group->pinned;
  9486. percpu_counter_add(&space_info->total_bytes_pinned,
  9487. -block_group->pinned);
  9488. block_group->pinned = 0;
  9489. spin_unlock(&block_group->lock);
  9490. spin_unlock(&space_info->lock);
  9491. /* DISCARD can flip during remount */
  9492. trimming = btrfs_test_opt(fs_info, DISCARD);
  9493. /* Implicit trim during transaction commit. */
  9494. if (trimming)
  9495. btrfs_get_block_group_trimming(block_group);
  9496. /*
  9497. * Btrfs_remove_chunk will abort the transaction if things go
  9498. * horribly wrong.
  9499. */
  9500. ret = btrfs_remove_chunk(trans, fs_info,
  9501. block_group->key.objectid);
  9502. if (ret) {
  9503. if (trimming)
  9504. btrfs_put_block_group_trimming(block_group);
  9505. goto end_trans;
  9506. }
  9507. /*
  9508. * If we're not mounted with -odiscard, we can just forget
  9509. * about this block group. Otherwise we'll need to wait
  9510. * until transaction commit to do the actual discard.
  9511. */
  9512. if (trimming) {
  9513. spin_lock(&fs_info->unused_bgs_lock);
  9514. /*
  9515. * A concurrent scrub might have added us to the list
  9516. * fs_info->unused_bgs, so use a list_move operation
  9517. * to add the block group to the deleted_bgs list.
  9518. */
  9519. list_move(&block_group->bg_list,
  9520. &trans->transaction->deleted_bgs);
  9521. spin_unlock(&fs_info->unused_bgs_lock);
  9522. btrfs_get_block_group(block_group);
  9523. }
  9524. end_trans:
  9525. btrfs_end_transaction(trans);
  9526. next:
  9527. mutex_unlock(&fs_info->delete_unused_bgs_mutex);
  9528. btrfs_put_block_group(block_group);
  9529. spin_lock(&fs_info->unused_bgs_lock);
  9530. }
  9531. spin_unlock(&fs_info->unused_bgs_lock);
  9532. }
  9533. int btrfs_init_space_info(struct btrfs_fs_info *fs_info)
  9534. {
  9535. struct btrfs_space_info *space_info;
  9536. struct btrfs_super_block *disk_super;
  9537. u64 features;
  9538. u64 flags;
  9539. int mixed = 0;
  9540. int ret;
  9541. disk_super = fs_info->super_copy;
  9542. if (!btrfs_super_root(disk_super))
  9543. return -EINVAL;
  9544. features = btrfs_super_incompat_flags(disk_super);
  9545. if (features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS)
  9546. mixed = 1;
  9547. flags = BTRFS_BLOCK_GROUP_SYSTEM;
  9548. ret = create_space_info(fs_info, flags, &space_info);
  9549. if (ret)
  9550. goto out;
  9551. if (mixed) {
  9552. flags = BTRFS_BLOCK_GROUP_METADATA | BTRFS_BLOCK_GROUP_DATA;
  9553. ret = create_space_info(fs_info, flags, &space_info);
  9554. } else {
  9555. flags = BTRFS_BLOCK_GROUP_METADATA;
  9556. ret = create_space_info(fs_info, flags, &space_info);
  9557. if (ret)
  9558. goto out;
  9559. flags = BTRFS_BLOCK_GROUP_DATA;
  9560. ret = create_space_info(fs_info, flags, &space_info);
  9561. }
  9562. out:
  9563. return ret;
  9564. }
  9565. int btrfs_error_unpin_extent_range(struct btrfs_fs_info *fs_info,
  9566. u64 start, u64 end)
  9567. {
  9568. return unpin_extent_range(fs_info, start, end, false);
  9569. }
  9570. /*
  9571. * It used to be that old block groups would be left around forever.
  9572. * Iterating over them would be enough to trim unused space. Since we
  9573. * now automatically remove them, we also need to iterate over unallocated
  9574. * space.
  9575. *
  9576. * We don't want a transaction for this since the discard may take a
  9577. * substantial amount of time. We don't require that a transaction be
  9578. * running, but we do need to take a running transaction into account
  9579. * to ensure that we're not discarding chunks that were released in
  9580. * the current transaction.
  9581. *
  9582. * Holding the chunks lock will prevent other threads from allocating
  9583. * or releasing chunks, but it won't prevent a running transaction
  9584. * from committing and releasing the memory that the pending chunks
  9585. * list head uses. For that, we need to take a reference to the
  9586. * transaction.
  9587. */
  9588. static int btrfs_trim_free_extents(struct btrfs_device *device,
  9589. u64 minlen, u64 *trimmed)
  9590. {
  9591. u64 start = 0, len = 0;
  9592. int ret;
  9593. *trimmed = 0;
  9594. /* Not writeable = nothing to do. */
  9595. if (!device->writeable)
  9596. return 0;
  9597. /* No free space = nothing to do. */
  9598. if (device->total_bytes <= device->bytes_used)
  9599. return 0;
  9600. ret = 0;
  9601. while (1) {
  9602. struct btrfs_fs_info *fs_info = device->fs_info;
  9603. struct btrfs_transaction *trans;
  9604. u64 bytes;
  9605. ret = mutex_lock_interruptible(&fs_info->chunk_mutex);
  9606. if (ret)
  9607. return ret;
  9608. down_read(&fs_info->commit_root_sem);
  9609. spin_lock(&fs_info->trans_lock);
  9610. trans = fs_info->running_transaction;
  9611. if (trans)
  9612. refcount_inc(&trans->use_count);
  9613. spin_unlock(&fs_info->trans_lock);
  9614. ret = find_free_dev_extent_start(trans, device, minlen, start,
  9615. &start, &len);
  9616. if (trans)
  9617. btrfs_put_transaction(trans);
  9618. if (ret) {
  9619. up_read(&fs_info->commit_root_sem);
  9620. mutex_unlock(&fs_info->chunk_mutex);
  9621. if (ret == -ENOSPC)
  9622. ret = 0;
  9623. break;
  9624. }
  9625. ret = btrfs_issue_discard(device->bdev, start, len, &bytes);
  9626. up_read(&fs_info->commit_root_sem);
  9627. mutex_unlock(&fs_info->chunk_mutex);
  9628. if (ret)
  9629. break;
  9630. start += len;
  9631. *trimmed += bytes;
  9632. if (fatal_signal_pending(current)) {
  9633. ret = -ERESTARTSYS;
  9634. break;
  9635. }
  9636. cond_resched();
  9637. }
  9638. return ret;
  9639. }
  9640. int btrfs_trim_fs(struct btrfs_fs_info *fs_info, struct fstrim_range *range)
  9641. {
  9642. struct btrfs_block_group_cache *cache = NULL;
  9643. struct btrfs_device *device;
  9644. struct list_head *devices;
  9645. u64 group_trimmed;
  9646. u64 start;
  9647. u64 end;
  9648. u64 trimmed = 0;
  9649. u64 total_bytes = btrfs_super_total_bytes(fs_info->super_copy);
  9650. int ret = 0;
  9651. /*
  9652. * try to trim all FS space, our block group may start from non-zero.
  9653. */
  9654. if (range->len == total_bytes)
  9655. cache = btrfs_lookup_first_block_group(fs_info, range->start);
  9656. else
  9657. cache = btrfs_lookup_block_group(fs_info, range->start);
  9658. while (cache) {
  9659. if (cache->key.objectid >= (range->start + range->len)) {
  9660. btrfs_put_block_group(cache);
  9661. break;
  9662. }
  9663. start = max(range->start, cache->key.objectid);
  9664. end = min(range->start + range->len,
  9665. cache->key.objectid + cache->key.offset);
  9666. if (end - start >= range->minlen) {
  9667. if (!block_group_cache_done(cache)) {
  9668. ret = cache_block_group(cache, 0);
  9669. if (ret) {
  9670. btrfs_put_block_group(cache);
  9671. break;
  9672. }
  9673. ret = wait_block_group_cache_done(cache);
  9674. if (ret) {
  9675. btrfs_put_block_group(cache);
  9676. break;
  9677. }
  9678. }
  9679. ret = btrfs_trim_block_group(cache,
  9680. &group_trimmed,
  9681. start,
  9682. end,
  9683. range->minlen);
  9684. trimmed += group_trimmed;
  9685. if (ret) {
  9686. btrfs_put_block_group(cache);
  9687. break;
  9688. }
  9689. }
  9690. cache = next_block_group(fs_info, cache);
  9691. }
  9692. mutex_lock(&fs_info->fs_devices->device_list_mutex);
  9693. devices = &fs_info->fs_devices->alloc_list;
  9694. list_for_each_entry(device, devices, dev_alloc_list) {
  9695. ret = btrfs_trim_free_extents(device, range->minlen,
  9696. &group_trimmed);
  9697. if (ret)
  9698. break;
  9699. trimmed += group_trimmed;
  9700. }
  9701. mutex_unlock(&fs_info->fs_devices->device_list_mutex);
  9702. range->len = trimmed;
  9703. return ret;
  9704. }
  9705. /*
  9706. * btrfs_{start,end}_write_no_snapshotting() are similar to
  9707. * mnt_{want,drop}_write(), they are used to prevent some tasks from writing
  9708. * data into the page cache through nocow before the subvolume is snapshoted,
  9709. * but flush the data into disk after the snapshot creation, or to prevent
  9710. * operations while snapshotting is ongoing and that cause the snapshot to be
  9711. * inconsistent (writes followed by expanding truncates for example).
  9712. */
  9713. void btrfs_end_write_no_snapshotting(struct btrfs_root *root)
  9714. {
  9715. percpu_counter_dec(&root->subv_writers->counter);
  9716. /*
  9717. * Make sure counter is updated before we wake up waiters.
  9718. */
  9719. smp_mb();
  9720. if (waitqueue_active(&root->subv_writers->wait))
  9721. wake_up(&root->subv_writers->wait);
  9722. }
  9723. int btrfs_start_write_no_snapshotting(struct btrfs_root *root)
  9724. {
  9725. if (atomic_read(&root->will_be_snapshotted))
  9726. return 0;
  9727. percpu_counter_inc(&root->subv_writers->counter);
  9728. /*
  9729. * Make sure counter is updated before we check for snapshot creation.
  9730. */
  9731. smp_mb();
  9732. if (atomic_read(&root->will_be_snapshotted)) {
  9733. btrfs_end_write_no_snapshotting(root);
  9734. return 0;
  9735. }
  9736. return 1;
  9737. }
  9738. void btrfs_wait_for_snapshot_creation(struct btrfs_root *root)
  9739. {
  9740. while (true) {
  9741. int ret;
  9742. ret = btrfs_start_write_no_snapshotting(root);
  9743. if (ret)
  9744. break;
  9745. wait_on_atomic_t(&root->will_be_snapshotted, atomic_t_wait,
  9746. TASK_UNINTERRUPTIBLE);
  9747. }
  9748. }