extent-tree.c 299 KB

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