extent-tree.c 302 KB

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