extent-tree.c 304 KB

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