extent-tree.c 305 KB

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