extent-tree.c 294 KB

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