extent-tree.c 299 KB

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