extent-tree.c 296 KB

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