extent-tree.c 296 KB

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