extent-tree.c 300 KB

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