extent-tree.c 302 KB

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