extent-tree.c 301 KB

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