extent-tree.c 299 KB

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