extent-tree.c 301 KB

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