relocation.c 154 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Copyright (C) 2009 Oracle. All rights reserved.
  4. */
  5. #include <linux/sched.h>
  6. #include <linux/pagemap.h>
  7. #include <linux/writeback.h>
  8. #include <linux/blkdev.h>
  9. #include <linux/rbtree.h>
  10. #include <linux/slab.h>
  11. #include <linux/error-injection.h>
  12. #include "ctree.h"
  13. #include "disk-io.h"
  14. #include "transaction.h"
  15. #include "volumes.h"
  16. #include "locking.h"
  17. #include "btrfs_inode.h"
  18. #include "async-thread.h"
  19. #include "free-space-cache.h"
  20. #include "qgroup.h"
  21. #include "print-tree.h"
  22. #include "delalloc-space.h"
  23. #include "block-group.h"
  24. #include "backref.h"
  25. #include "misc.h"
  26. #include "subpage.h"
  27. #include "zoned.h"
  28. #include "inode-item.h"
  29. #include "space-info.h"
  30. #include "fs.h"
  31. #include "accessors.h"
  32. #include "extent-tree.h"
  33. #include "root-tree.h"
  34. #include "file-item.h"
  35. #include "relocation.h"
  36. #include "super.h"
  37. #include "tree-checker.h"
  38. #include "raid-stripe-tree.h"
  39. #include "free-space-tree.h"
  40. /*
  41. * Relocation overview
  42. *
  43. * [What does relocation do]
  44. *
  45. * The objective of relocation is to relocate all extents of the target block
  46. * group to other block groups.
  47. * This is utilized by resize (shrink only), profile converting, compacting
  48. * space, or balance routine to spread chunks over devices.
  49. *
  50. * Before | After
  51. * ------------------------------------------------------------------
  52. * BG A: 10 data extents | BG A: deleted
  53. * BG B: 2 data extents | BG B: 10 data extents (2 old + 8 relocated)
  54. * BG C: 1 extents | BG C: 3 data extents (1 old + 2 relocated)
  55. *
  56. * [How does relocation work]
  57. *
  58. * 1. Mark the target block group read-only
  59. * New extents won't be allocated from the target block group.
  60. *
  61. * 2.1 Record each extent in the target block group
  62. * To build a proper map of extents to be relocated.
  63. *
  64. * 2.2 Build data reloc tree and reloc trees
  65. * Data reloc tree will contain an inode, recording all newly relocated
  66. * data extents.
  67. * There will be only one data reloc tree for one data block group.
  68. *
  69. * Reloc tree will be a special snapshot of its source tree, containing
  70. * relocated tree blocks.
  71. * Each tree referring to a tree block in target block group will get its
  72. * reloc tree built.
  73. *
  74. * 2.3 Swap source tree with its corresponding reloc tree
  75. * Each involved tree only refers to new extents after swap.
  76. *
  77. * 3. Cleanup reloc trees and data reloc tree.
  78. * As old extents in the target block group are still referenced by reloc
  79. * trees, we need to clean them up before really freeing the target block
  80. * group.
  81. *
  82. * The main complexity is in steps 2.2 and 2.3.
  83. *
  84. * The entry point of relocation is relocate_block_group() function.
  85. */
  86. #define RELOCATION_RESERVED_NODES 256
  87. /*
  88. * map address of tree root to tree
  89. */
  90. struct mapping_node {
  91. union {
  92. /* Use rb_simple_node for search/insert */
  93. struct {
  94. struct rb_node rb_node;
  95. u64 bytenr;
  96. };
  97. struct rb_simple_node simple_node;
  98. };
  99. void *data;
  100. };
  101. struct mapping_tree {
  102. struct rb_root rb_root;
  103. spinlock_t lock;
  104. };
  105. /*
  106. * present a tree block to process
  107. */
  108. struct tree_block {
  109. union {
  110. /* Use rb_simple_node for search/insert */
  111. struct {
  112. struct rb_node rb_node;
  113. u64 bytenr;
  114. };
  115. struct rb_simple_node simple_node;
  116. };
  117. u64 owner;
  118. struct btrfs_key key;
  119. u8 level;
  120. bool key_ready;
  121. };
  122. #define MAX_EXTENTS 128
  123. struct file_extent_cluster {
  124. u64 start;
  125. u64 end;
  126. u64 boundary[MAX_EXTENTS];
  127. unsigned int nr;
  128. u64 owning_root;
  129. };
  130. /* Stages of data relocation. */
  131. enum reloc_stage {
  132. MOVE_DATA_EXTENTS,
  133. UPDATE_DATA_PTRS
  134. };
  135. struct reloc_control {
  136. /* block group to relocate */
  137. struct btrfs_block_group *block_group;
  138. /* extent tree */
  139. struct btrfs_root *extent_root;
  140. /* inode for moving data */
  141. struct inode *data_inode;
  142. struct btrfs_block_rsv *block_rsv;
  143. struct btrfs_backref_cache backref_cache;
  144. struct file_extent_cluster cluster;
  145. /* tree blocks have been processed */
  146. struct extent_io_tree processed_blocks;
  147. /* map start of tree root to corresponding reloc tree */
  148. struct mapping_tree reloc_root_tree;
  149. /* list of reloc trees */
  150. struct list_head reloc_roots;
  151. /* list of subvolume trees that get relocated */
  152. struct list_head dirty_subvol_roots;
  153. /* size of metadata reservation for merging reloc trees */
  154. u64 merging_rsv_size;
  155. /* size of relocated tree nodes */
  156. u64 nodes_relocated;
  157. /* reserved size for block group relocation*/
  158. u64 reserved_bytes;
  159. u64 search_start;
  160. u64 extents_found;
  161. enum reloc_stage stage;
  162. bool create_reloc_tree;
  163. bool merge_reloc_tree;
  164. bool found_file_extent;
  165. };
  166. static void mark_block_processed(struct reloc_control *rc,
  167. struct btrfs_backref_node *node)
  168. {
  169. u32 blocksize;
  170. if (node->level == 0 ||
  171. in_range(node->bytenr, rc->block_group->start,
  172. rc->block_group->length)) {
  173. blocksize = rc->extent_root->fs_info->nodesize;
  174. btrfs_set_extent_bit(&rc->processed_blocks, node->bytenr,
  175. node->bytenr + blocksize - 1, EXTENT_DIRTY,
  176. NULL);
  177. }
  178. node->processed = 1;
  179. }
  180. /*
  181. * walk up backref nodes until reach node presents tree root
  182. */
  183. static struct btrfs_backref_node *walk_up_backref(
  184. struct btrfs_backref_node *node,
  185. struct btrfs_backref_edge *edges[], int *index)
  186. {
  187. struct btrfs_backref_edge *edge;
  188. int idx = *index;
  189. while (!list_empty(&node->upper)) {
  190. edge = list_first_entry(&node->upper, struct btrfs_backref_edge,
  191. list[LOWER]);
  192. edges[idx++] = edge;
  193. node = edge->node[UPPER];
  194. }
  195. BUG_ON(node->detached);
  196. *index = idx;
  197. return node;
  198. }
  199. /*
  200. * walk down backref nodes to find start of next reference path
  201. */
  202. static struct btrfs_backref_node *walk_down_backref(
  203. struct btrfs_backref_edge *edges[], int *index)
  204. {
  205. struct btrfs_backref_edge *edge;
  206. struct btrfs_backref_node *lower;
  207. int idx = *index;
  208. while (idx > 0) {
  209. edge = edges[idx - 1];
  210. lower = edge->node[LOWER];
  211. if (list_is_last(&edge->list[LOWER], &lower->upper)) {
  212. idx--;
  213. continue;
  214. }
  215. edge = list_first_entry(&edge->list[LOWER], struct btrfs_backref_edge,
  216. list[LOWER]);
  217. edges[idx - 1] = edge;
  218. *index = idx;
  219. return edge->node[UPPER];
  220. }
  221. *index = 0;
  222. return NULL;
  223. }
  224. static bool reloc_root_is_dead(const struct btrfs_root *root)
  225. {
  226. /*
  227. * Pair with set_bit/clear_bit in clean_dirty_subvols and
  228. * btrfs_update_reloc_root. We need to see the updated bit before
  229. * trying to access reloc_root
  230. */
  231. smp_rmb();
  232. if (test_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state))
  233. return true;
  234. return false;
  235. }
  236. /*
  237. * Check if this subvolume tree has valid reloc tree.
  238. *
  239. * Reloc tree after swap is considered dead, thus not considered as valid.
  240. * This is enough for most callers, as they don't distinguish dead reloc root
  241. * from no reloc root. But btrfs_should_ignore_reloc_root() below is a
  242. * special case.
  243. */
  244. static bool have_reloc_root(const struct btrfs_root *root)
  245. {
  246. if (reloc_root_is_dead(root))
  247. return false;
  248. if (!root->reloc_root)
  249. return false;
  250. return true;
  251. }
  252. bool btrfs_should_ignore_reloc_root(const struct btrfs_root *root)
  253. {
  254. struct btrfs_root *reloc_root;
  255. if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
  256. return false;
  257. /* This root has been merged with its reloc tree, we can ignore it */
  258. if (reloc_root_is_dead(root))
  259. return true;
  260. reloc_root = root->reloc_root;
  261. if (!reloc_root)
  262. return false;
  263. if (btrfs_header_generation(reloc_root->commit_root) ==
  264. root->fs_info->running_transaction->transid)
  265. return false;
  266. /*
  267. * If there is reloc tree and it was created in previous transaction
  268. * backref lookup can find the reloc tree, so backref node for the fs
  269. * tree root is useless for relocation.
  270. */
  271. return true;
  272. }
  273. /*
  274. * find reloc tree by address of tree root
  275. */
  276. struct btrfs_root *find_reloc_root(struct btrfs_fs_info *fs_info, u64 bytenr)
  277. {
  278. struct reloc_control *rc = fs_info->reloc_ctl;
  279. struct rb_node *rb_node;
  280. struct mapping_node *node;
  281. struct btrfs_root *root = NULL;
  282. ASSERT(rc);
  283. spin_lock(&rc->reloc_root_tree.lock);
  284. rb_node = rb_simple_search(&rc->reloc_root_tree.rb_root, bytenr);
  285. if (rb_node) {
  286. node = rb_entry(rb_node, struct mapping_node, rb_node);
  287. root = node->data;
  288. }
  289. spin_unlock(&rc->reloc_root_tree.lock);
  290. return btrfs_grab_root(root);
  291. }
  292. /*
  293. * For useless nodes, do two major clean ups:
  294. *
  295. * - Cleanup the children edges and nodes
  296. * If child node is also orphan (no parent) during cleanup, then the child
  297. * node will also be cleaned up.
  298. *
  299. * - Freeing up leaves (level 0), keeps nodes detached
  300. * For nodes, the node is still cached as "detached"
  301. *
  302. * Return false if @node is not in the @useless_nodes list.
  303. * Return true if @node is in the @useless_nodes list.
  304. */
  305. static bool handle_useless_nodes(struct reloc_control *rc,
  306. struct btrfs_backref_node *node)
  307. {
  308. struct btrfs_backref_cache *cache = &rc->backref_cache;
  309. struct list_head *useless_node = &cache->useless_node;
  310. bool ret = false;
  311. while (!list_empty(useless_node)) {
  312. struct btrfs_backref_node *cur;
  313. cur = list_first_entry(useless_node, struct btrfs_backref_node,
  314. list);
  315. list_del_init(&cur->list);
  316. /* Only tree root nodes can be added to @useless_nodes */
  317. ASSERT(list_empty(&cur->upper));
  318. if (cur == node)
  319. ret = true;
  320. /* Cleanup the lower edges */
  321. while (!list_empty(&cur->lower)) {
  322. struct btrfs_backref_edge *edge;
  323. struct btrfs_backref_node *lower;
  324. edge = list_first_entry(&cur->lower, struct btrfs_backref_edge,
  325. list[UPPER]);
  326. list_del(&edge->list[UPPER]);
  327. list_del(&edge->list[LOWER]);
  328. lower = edge->node[LOWER];
  329. btrfs_backref_free_edge(cache, edge);
  330. /* Child node is also orphan, queue for cleanup */
  331. if (list_empty(&lower->upper))
  332. list_add(&lower->list, useless_node);
  333. }
  334. /* Mark this block processed for relocation */
  335. mark_block_processed(rc, cur);
  336. /*
  337. * Backref nodes for tree leaves are deleted from the cache.
  338. * Backref nodes for upper level tree blocks are left in the
  339. * cache to avoid unnecessary backref lookup.
  340. */
  341. if (cur->level > 0) {
  342. cur->detached = 1;
  343. } else {
  344. rb_erase(&cur->rb_node, &cache->rb_root);
  345. btrfs_backref_free_node(cache, cur);
  346. }
  347. }
  348. return ret;
  349. }
  350. /*
  351. * Build backref tree for a given tree block. Root of the backref tree
  352. * corresponds the tree block, leaves of the backref tree correspond roots of
  353. * b-trees that reference the tree block.
  354. *
  355. * The basic idea of this function is check backrefs of a given block to find
  356. * upper level blocks that reference the block, and then check backrefs of
  357. * these upper level blocks recursively. The recursion stops when tree root is
  358. * reached or backrefs for the block is cached.
  359. *
  360. * NOTE: if we find that backrefs for a block are cached, we know backrefs for
  361. * all upper level blocks that directly/indirectly reference the block are also
  362. * cached.
  363. */
  364. static noinline_for_stack struct btrfs_backref_node *build_backref_tree(
  365. struct btrfs_trans_handle *trans,
  366. struct reloc_control *rc, struct btrfs_key *node_key,
  367. int level, u64 bytenr)
  368. {
  369. struct btrfs_backref_iter *iter;
  370. struct btrfs_backref_cache *cache = &rc->backref_cache;
  371. /* For searching parent of TREE_BLOCK_REF */
  372. struct btrfs_path *path;
  373. struct btrfs_backref_node *cur;
  374. struct btrfs_backref_node *node = NULL;
  375. struct btrfs_backref_edge *edge;
  376. int ret;
  377. iter = btrfs_backref_iter_alloc(rc->extent_root->fs_info);
  378. if (!iter)
  379. return ERR_PTR(-ENOMEM);
  380. path = btrfs_alloc_path();
  381. if (!path) {
  382. ret = -ENOMEM;
  383. goto out;
  384. }
  385. node = btrfs_backref_alloc_node(cache, bytenr, level);
  386. if (!node) {
  387. ret = -ENOMEM;
  388. goto out;
  389. }
  390. cur = node;
  391. /* Breadth-first search to build backref cache */
  392. do {
  393. ret = btrfs_backref_add_tree_node(trans, cache, path, iter,
  394. node_key, cur);
  395. if (ret < 0)
  396. goto out;
  397. edge = list_first_entry_or_null(&cache->pending_edge,
  398. struct btrfs_backref_edge, list[UPPER]);
  399. /*
  400. * The pending list isn't empty, take the first block to
  401. * process
  402. */
  403. if (edge) {
  404. list_del_init(&edge->list[UPPER]);
  405. cur = edge->node[UPPER];
  406. }
  407. } while (edge);
  408. /* Finish the upper linkage of newly added edges/nodes */
  409. ret = btrfs_backref_finish_upper_links(cache, node);
  410. if (ret < 0)
  411. goto out;
  412. if (handle_useless_nodes(rc, node))
  413. node = NULL;
  414. out:
  415. btrfs_free_path(iter->path);
  416. kfree(iter);
  417. btrfs_free_path(path);
  418. if (ret) {
  419. btrfs_backref_error_cleanup(cache, node);
  420. return ERR_PTR(ret);
  421. }
  422. ASSERT(!node || !node->detached);
  423. ASSERT(list_empty(&cache->useless_node) &&
  424. list_empty(&cache->pending_edge));
  425. return node;
  426. }
  427. /*
  428. * helper to add 'address of tree root -> reloc tree' mapping
  429. */
  430. static int __add_reloc_root(struct btrfs_root *root)
  431. {
  432. struct btrfs_fs_info *fs_info = root->fs_info;
  433. struct rb_node *rb_node;
  434. struct mapping_node *node;
  435. struct reloc_control *rc = fs_info->reloc_ctl;
  436. node = kmalloc_obj(*node, GFP_NOFS);
  437. if (!node)
  438. return -ENOMEM;
  439. node->bytenr = root->commit_root->start;
  440. node->data = root;
  441. spin_lock(&rc->reloc_root_tree.lock);
  442. rb_node = rb_simple_insert(&rc->reloc_root_tree.rb_root, &node->simple_node);
  443. spin_unlock(&rc->reloc_root_tree.lock);
  444. if (rb_node) {
  445. btrfs_err(fs_info,
  446. "Duplicate root found for start=%llu while inserting into relocation tree",
  447. node->bytenr);
  448. return -EEXIST;
  449. }
  450. list_add_tail(&root->root_list, &rc->reloc_roots);
  451. return 0;
  452. }
  453. /*
  454. * helper to delete the 'address of tree root -> reloc tree'
  455. * mapping
  456. */
  457. static void __del_reloc_root(struct btrfs_root *root)
  458. {
  459. struct btrfs_fs_info *fs_info = root->fs_info;
  460. struct rb_node *rb_node;
  461. struct mapping_node AUTO_KFREE(node);
  462. struct reloc_control *rc = fs_info->reloc_ctl;
  463. bool put_ref = false;
  464. if (rc && root->node) {
  465. spin_lock(&rc->reloc_root_tree.lock);
  466. rb_node = rb_simple_search(&rc->reloc_root_tree.rb_root,
  467. root->commit_root->start);
  468. if (rb_node) {
  469. node = rb_entry(rb_node, struct mapping_node, rb_node);
  470. rb_erase(&node->rb_node, &rc->reloc_root_tree.rb_root);
  471. RB_CLEAR_NODE(&node->rb_node);
  472. }
  473. spin_unlock(&rc->reloc_root_tree.lock);
  474. ASSERT(!node || (struct btrfs_root *)node->data == root);
  475. }
  476. /*
  477. * We only put the reloc root here if it's on the list. There's a lot
  478. * of places where the pattern is to splice the rc->reloc_roots, process
  479. * the reloc roots, and then add the reloc root back onto
  480. * rc->reloc_roots. If we call __del_reloc_root while it's off of the
  481. * list we don't want the reference being dropped, because the guy
  482. * messing with the list is in charge of the reference.
  483. */
  484. spin_lock(&fs_info->trans_lock);
  485. if (!list_empty(&root->root_list)) {
  486. put_ref = true;
  487. list_del_init(&root->root_list);
  488. }
  489. spin_unlock(&fs_info->trans_lock);
  490. if (put_ref)
  491. btrfs_put_root(root);
  492. }
  493. /*
  494. * helper to update the 'address of tree root -> reloc tree'
  495. * mapping
  496. */
  497. static int __update_reloc_root(struct btrfs_root *root)
  498. {
  499. struct btrfs_fs_info *fs_info = root->fs_info;
  500. struct rb_node *rb_node;
  501. struct mapping_node *node = NULL;
  502. struct reloc_control *rc = fs_info->reloc_ctl;
  503. spin_lock(&rc->reloc_root_tree.lock);
  504. rb_node = rb_simple_search(&rc->reloc_root_tree.rb_root,
  505. root->commit_root->start);
  506. if (rb_node) {
  507. node = rb_entry(rb_node, struct mapping_node, rb_node);
  508. rb_erase(&node->rb_node, &rc->reloc_root_tree.rb_root);
  509. }
  510. spin_unlock(&rc->reloc_root_tree.lock);
  511. if (!node)
  512. return 0;
  513. BUG_ON((struct btrfs_root *)node->data != root);
  514. spin_lock(&rc->reloc_root_tree.lock);
  515. node->bytenr = root->node->start;
  516. rb_node = rb_simple_insert(&rc->reloc_root_tree.rb_root, &node->simple_node);
  517. spin_unlock(&rc->reloc_root_tree.lock);
  518. if (rb_node)
  519. btrfs_backref_panic(fs_info, node->bytenr, -EEXIST);
  520. return 0;
  521. }
  522. static struct btrfs_root *create_reloc_root(struct btrfs_trans_handle *trans,
  523. struct btrfs_root *root, u64 objectid)
  524. {
  525. struct btrfs_fs_info *fs_info = root->fs_info;
  526. struct btrfs_root *reloc_root;
  527. struct extent_buffer *eb;
  528. struct btrfs_root_item AUTO_KFREE(root_item);
  529. struct btrfs_key root_key;
  530. int ret = 0;
  531. root_item = kmalloc(sizeof(*root_item), GFP_NOFS);
  532. if (!root_item)
  533. return ERR_PTR(-ENOMEM);
  534. root_key.objectid = BTRFS_TREE_RELOC_OBJECTID;
  535. root_key.type = BTRFS_ROOT_ITEM_KEY;
  536. root_key.offset = objectid;
  537. if (btrfs_root_id(root) == objectid) {
  538. u64 commit_root_gen;
  539. /*
  540. * Relocation will wait for cleaner thread, and any half-dropped
  541. * subvolume will be fully cleaned up at mount time.
  542. * So here we shouldn't hit a subvolume with non-zero drop_progress.
  543. *
  544. * If this isn't the case, error out since it can make us attempt to
  545. * drop references for extents that were already dropped before.
  546. */
  547. if (unlikely(btrfs_disk_key_objectid(&root->root_item.drop_progress))) {
  548. struct btrfs_key cpu_key;
  549. btrfs_disk_key_to_cpu(&cpu_key, &root->root_item.drop_progress);
  550. btrfs_err(fs_info,
  551. "cannot relocate partially dropped subvolume %llu, drop progress key " BTRFS_KEY_FMT,
  552. objectid, BTRFS_KEY_FMT_VALUE(&cpu_key));
  553. return ERR_PTR(-EUCLEAN);
  554. }
  555. /* called by btrfs_init_reloc_root */
  556. ret = btrfs_copy_root(trans, root, root->commit_root, &eb,
  557. BTRFS_TREE_RELOC_OBJECTID);
  558. if (ret)
  559. return ERR_PTR(ret);
  560. /*
  561. * Set the last_snapshot field to the generation of the commit
  562. * root - like this ctree.c:btrfs_block_can_be_shared() behaves
  563. * correctly (returns true) when the relocation root is created
  564. * either inside the critical section of a transaction commit
  565. * (through transaction.c:qgroup_account_snapshot()) and when
  566. * it's created before the transaction commit is started.
  567. */
  568. commit_root_gen = btrfs_header_generation(root->commit_root);
  569. btrfs_set_root_last_snapshot(&root->root_item, commit_root_gen);
  570. } else {
  571. /*
  572. * called by btrfs_reloc_post_snapshot_hook.
  573. * the source tree is a reloc tree, all tree blocks
  574. * modified after it was created have RELOC flag
  575. * set in their headers. so it's OK to not update
  576. * the 'last_snapshot'.
  577. */
  578. ret = btrfs_copy_root(trans, root, root->node, &eb,
  579. BTRFS_TREE_RELOC_OBJECTID);
  580. if (ret)
  581. return ERR_PTR(ret);
  582. }
  583. /*
  584. * We have changed references at this point, we must abort the
  585. * transaction if anything fails (i.e. 'goto abort').
  586. */
  587. memcpy(root_item, &root->root_item, sizeof(*root_item));
  588. btrfs_set_root_bytenr(root_item, eb->start);
  589. btrfs_set_root_level(root_item, btrfs_header_level(eb));
  590. btrfs_set_root_generation(root_item, trans->transid);
  591. if (btrfs_root_id(root) == objectid) {
  592. btrfs_set_root_refs(root_item, 0);
  593. memset(&root_item->drop_progress, 0,
  594. sizeof(struct btrfs_disk_key));
  595. btrfs_set_root_drop_level(root_item, 0);
  596. }
  597. btrfs_tree_unlock(eb);
  598. free_extent_buffer(eb);
  599. ret = btrfs_insert_root(trans, fs_info->tree_root,
  600. &root_key, root_item);
  601. if (ret)
  602. goto abort;
  603. reloc_root = btrfs_read_tree_root(fs_info->tree_root, &root_key);
  604. if (IS_ERR(reloc_root)) {
  605. ret = PTR_ERR(reloc_root);
  606. goto abort;
  607. }
  608. set_bit(BTRFS_ROOT_SHAREABLE, &reloc_root->state);
  609. btrfs_set_root_last_trans(reloc_root, trans->transid);
  610. return reloc_root;
  611. abort:
  612. btrfs_abort_transaction(trans, ret);
  613. return ERR_PTR(ret);
  614. }
  615. /*
  616. * create reloc tree for a given fs tree. reloc tree is just a
  617. * snapshot of the fs tree with special root objectid.
  618. *
  619. * The reloc_root comes out of here with two references, one for
  620. * root->reloc_root, and another for being on the rc->reloc_roots list.
  621. */
  622. int btrfs_init_reloc_root(struct btrfs_trans_handle *trans,
  623. struct btrfs_root *root)
  624. {
  625. struct btrfs_fs_info *fs_info = root->fs_info;
  626. struct btrfs_root *reloc_root;
  627. struct reloc_control *rc = fs_info->reloc_ctl;
  628. struct btrfs_block_rsv *rsv;
  629. int clear_rsv = 0;
  630. int ret;
  631. if (!rc)
  632. return 0;
  633. /*
  634. * The subvolume has reloc tree but the swap is finished, no need to
  635. * create/update the dead reloc tree
  636. */
  637. if (reloc_root_is_dead(root))
  638. return 0;
  639. /*
  640. * This is subtle but important. We do not do
  641. * record_root_in_transaction for reloc roots, instead we record their
  642. * corresponding fs root, and then here we update the last trans for the
  643. * reloc root. This means that we have to do this for the entire life
  644. * of the reloc root, regardless of which stage of the relocation we are
  645. * in.
  646. */
  647. if (root->reloc_root) {
  648. reloc_root = root->reloc_root;
  649. btrfs_set_root_last_trans(reloc_root, trans->transid);
  650. return 0;
  651. }
  652. /*
  653. * We are merging reloc roots, we do not need new reloc trees. Also
  654. * reloc trees never need their own reloc tree.
  655. */
  656. if (!rc->create_reloc_tree || btrfs_root_id(root) == BTRFS_TREE_RELOC_OBJECTID)
  657. return 0;
  658. if (!trans->reloc_reserved) {
  659. rsv = trans->block_rsv;
  660. trans->block_rsv = rc->block_rsv;
  661. clear_rsv = 1;
  662. }
  663. reloc_root = create_reloc_root(trans, root, btrfs_root_id(root));
  664. if (clear_rsv)
  665. trans->block_rsv = rsv;
  666. if (IS_ERR(reloc_root))
  667. return PTR_ERR(reloc_root);
  668. ret = __add_reloc_root(reloc_root);
  669. ASSERT(ret != -EEXIST);
  670. if (ret) {
  671. /* Pairs with create_reloc_root */
  672. btrfs_put_root(reloc_root);
  673. return ret;
  674. }
  675. root->reloc_root = btrfs_grab_root(reloc_root);
  676. return 0;
  677. }
  678. /*
  679. * update root item of reloc tree
  680. */
  681. int btrfs_update_reloc_root(struct btrfs_trans_handle *trans,
  682. struct btrfs_root *root)
  683. {
  684. struct btrfs_fs_info *fs_info = root->fs_info;
  685. struct btrfs_root *reloc_root;
  686. struct btrfs_root_item *root_item;
  687. int ret;
  688. if (!have_reloc_root(root))
  689. return 0;
  690. reloc_root = root->reloc_root;
  691. root_item = &reloc_root->root_item;
  692. /*
  693. * We are probably ok here, but __del_reloc_root() will drop its ref of
  694. * the root. We have the ref for root->reloc_root, but just in case
  695. * hold it while we update the reloc root.
  696. */
  697. btrfs_grab_root(reloc_root);
  698. /* root->reloc_root will stay until current relocation finished */
  699. if (fs_info->reloc_ctl && fs_info->reloc_ctl->merge_reloc_tree &&
  700. btrfs_root_refs(root_item) == 0) {
  701. set_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state);
  702. /*
  703. * Mark the tree as dead before we change reloc_root so
  704. * have_reloc_root will not touch it from now on.
  705. */
  706. smp_wmb();
  707. __del_reloc_root(reloc_root);
  708. }
  709. if (reloc_root->commit_root != reloc_root->node) {
  710. __update_reloc_root(reloc_root);
  711. btrfs_set_root_node(root_item, reloc_root->node);
  712. free_extent_buffer(reloc_root->commit_root);
  713. reloc_root->commit_root = btrfs_root_node(reloc_root);
  714. }
  715. ret = btrfs_update_root(trans, fs_info->tree_root,
  716. &reloc_root->root_key, root_item);
  717. btrfs_put_root(reloc_root);
  718. return ret;
  719. }
  720. /*
  721. * get new location of data
  722. */
  723. static int get_new_location(struct inode *reloc_inode, u64 *new_bytenr,
  724. u64 bytenr, u64 num_bytes)
  725. {
  726. struct btrfs_root *root = BTRFS_I(reloc_inode)->root;
  727. BTRFS_PATH_AUTO_FREE(path);
  728. struct btrfs_file_extent_item *fi;
  729. struct extent_buffer *leaf;
  730. int ret;
  731. path = btrfs_alloc_path();
  732. if (!path)
  733. return -ENOMEM;
  734. bytenr -= BTRFS_I(reloc_inode)->reloc_block_group_start;
  735. ret = btrfs_lookup_file_extent(NULL, root, path,
  736. btrfs_ino(BTRFS_I(reloc_inode)), bytenr, 0);
  737. if (ret < 0)
  738. return ret;
  739. if (ret > 0)
  740. return -ENOENT;
  741. leaf = path->nodes[0];
  742. fi = btrfs_item_ptr(leaf, path->slots[0],
  743. struct btrfs_file_extent_item);
  744. BUG_ON(btrfs_file_extent_offset(leaf, fi) ||
  745. btrfs_file_extent_compression(leaf, fi) ||
  746. btrfs_file_extent_encryption(leaf, fi) ||
  747. btrfs_file_extent_other_encoding(leaf, fi));
  748. if (num_bytes != btrfs_file_extent_disk_num_bytes(leaf, fi))
  749. return -EINVAL;
  750. *new_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
  751. return 0;
  752. }
  753. /*
  754. * update file extent items in the tree leaf to point to
  755. * the new locations.
  756. */
  757. static noinline_for_stack
  758. int replace_file_extents(struct btrfs_trans_handle *trans,
  759. struct reloc_control *rc,
  760. struct btrfs_root *root,
  761. struct extent_buffer *leaf)
  762. {
  763. struct btrfs_fs_info *fs_info = root->fs_info;
  764. struct btrfs_key key;
  765. struct btrfs_file_extent_item *fi;
  766. struct btrfs_inode *inode = NULL;
  767. u64 parent;
  768. u64 bytenr;
  769. u64 new_bytenr = 0;
  770. u64 num_bytes;
  771. u64 end;
  772. u32 nritems;
  773. u32 i;
  774. int ret = 0;
  775. int first = 1;
  776. if (rc->stage != UPDATE_DATA_PTRS)
  777. return 0;
  778. /* reloc trees always use full backref */
  779. if (btrfs_root_id(root) == BTRFS_TREE_RELOC_OBJECTID)
  780. parent = leaf->start;
  781. else
  782. parent = 0;
  783. nritems = btrfs_header_nritems(leaf);
  784. for (i = 0; i < nritems; i++) {
  785. struct btrfs_ref ref = { 0 };
  786. cond_resched();
  787. btrfs_item_key_to_cpu(leaf, &key, i);
  788. if (key.type != BTRFS_EXTENT_DATA_KEY)
  789. continue;
  790. fi = btrfs_item_ptr(leaf, i, struct btrfs_file_extent_item);
  791. if (btrfs_file_extent_type(leaf, fi) ==
  792. BTRFS_FILE_EXTENT_INLINE)
  793. continue;
  794. bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
  795. num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
  796. if (bytenr == 0)
  797. continue;
  798. if (!in_range(bytenr, rc->block_group->start,
  799. rc->block_group->length))
  800. continue;
  801. /*
  802. * if we are modifying block in fs tree, wait for read_folio
  803. * to complete and drop the extent cache
  804. */
  805. if (btrfs_root_id(root) != BTRFS_TREE_RELOC_OBJECTID) {
  806. if (first) {
  807. inode = btrfs_find_first_inode(root, key.objectid);
  808. first = 0;
  809. } else if (inode && btrfs_ino(inode) < key.objectid) {
  810. btrfs_add_delayed_iput(inode);
  811. inode = btrfs_find_first_inode(root, key.objectid);
  812. }
  813. if (inode && btrfs_ino(inode) == key.objectid) {
  814. struct extent_state *cached_state = NULL;
  815. end = key.offset +
  816. btrfs_file_extent_num_bytes(leaf, fi);
  817. WARN_ON(!IS_ALIGNED(key.offset,
  818. fs_info->sectorsize));
  819. WARN_ON(!IS_ALIGNED(end, fs_info->sectorsize));
  820. end--;
  821. /* Take mmap lock to serialize with reflinks. */
  822. if (!down_read_trylock(&inode->i_mmap_lock))
  823. continue;
  824. ret = btrfs_try_lock_extent(&inode->io_tree, key.offset,
  825. end, &cached_state);
  826. if (!ret) {
  827. up_read(&inode->i_mmap_lock);
  828. continue;
  829. }
  830. btrfs_drop_extent_map_range(inode, key.offset, end, true);
  831. btrfs_unlock_extent(&inode->io_tree, key.offset, end,
  832. &cached_state);
  833. up_read(&inode->i_mmap_lock);
  834. }
  835. }
  836. ret = get_new_location(rc->data_inode, &new_bytenr,
  837. bytenr, num_bytes);
  838. if (ret) {
  839. /*
  840. * Don't have to abort since we've not changed anything
  841. * in the file extent yet.
  842. */
  843. break;
  844. }
  845. btrfs_set_file_extent_disk_bytenr(leaf, fi, new_bytenr);
  846. key.offset -= btrfs_file_extent_offset(leaf, fi);
  847. ref.action = BTRFS_ADD_DELAYED_REF;
  848. ref.bytenr = new_bytenr;
  849. ref.num_bytes = num_bytes;
  850. ref.parent = parent;
  851. ref.owning_root = btrfs_root_id(root);
  852. ref.ref_root = btrfs_header_owner(leaf);
  853. btrfs_init_data_ref(&ref, key.objectid, key.offset,
  854. btrfs_root_id(root), false);
  855. ret = btrfs_inc_extent_ref(trans, &ref);
  856. if (unlikely(ret)) {
  857. btrfs_abort_transaction(trans, ret);
  858. break;
  859. }
  860. ref.action = BTRFS_DROP_DELAYED_REF;
  861. ref.bytenr = bytenr;
  862. ref.num_bytes = num_bytes;
  863. ref.parent = parent;
  864. ref.owning_root = btrfs_root_id(root);
  865. ref.ref_root = btrfs_header_owner(leaf);
  866. btrfs_init_data_ref(&ref, key.objectid, key.offset,
  867. btrfs_root_id(root), false);
  868. ret = btrfs_free_extent(trans, &ref);
  869. if (unlikely(ret)) {
  870. btrfs_abort_transaction(trans, ret);
  871. break;
  872. }
  873. }
  874. if (inode)
  875. btrfs_add_delayed_iput(inode);
  876. return ret;
  877. }
  878. static noinline_for_stack int memcmp_node_keys(const struct extent_buffer *eb,
  879. int slot, const struct btrfs_path *path,
  880. int level)
  881. {
  882. struct btrfs_disk_key key1;
  883. struct btrfs_disk_key key2;
  884. btrfs_node_key(eb, &key1, slot);
  885. btrfs_node_key(path->nodes[level], &key2, path->slots[level]);
  886. return memcmp(&key1, &key2, sizeof(key1));
  887. }
  888. /*
  889. * try to replace tree blocks in fs tree with the new blocks
  890. * in reloc tree. tree blocks haven't been modified since the
  891. * reloc tree was create can be replaced.
  892. *
  893. * if a block was replaced, level of the block + 1 is returned.
  894. * if no block got replaced, 0 is returned. if there are other
  895. * errors, a negative error number is returned.
  896. */
  897. static noinline_for_stack
  898. int replace_path(struct btrfs_trans_handle *trans, struct reloc_control *rc,
  899. struct btrfs_root *dest, struct btrfs_root *src,
  900. struct btrfs_path *path, struct btrfs_key *next_key,
  901. int lowest_level, int max_level)
  902. {
  903. struct btrfs_fs_info *fs_info = dest->fs_info;
  904. struct extent_buffer *eb;
  905. struct extent_buffer *parent;
  906. struct btrfs_ref ref = { 0 };
  907. struct btrfs_key key;
  908. u64 old_bytenr;
  909. u64 new_bytenr;
  910. u64 old_ptr_gen;
  911. u64 new_ptr_gen;
  912. u64 last_snapshot;
  913. u32 blocksize;
  914. int cow = 0;
  915. int level;
  916. int ret;
  917. int slot;
  918. ASSERT(btrfs_root_id(src) == BTRFS_TREE_RELOC_OBJECTID);
  919. ASSERT(btrfs_root_id(dest) != BTRFS_TREE_RELOC_OBJECTID);
  920. last_snapshot = btrfs_root_last_snapshot(&src->root_item);
  921. again:
  922. slot = path->slots[lowest_level];
  923. btrfs_node_key_to_cpu(path->nodes[lowest_level], &key, slot);
  924. eb = btrfs_lock_root_node(dest);
  925. level = btrfs_header_level(eb);
  926. if (level < lowest_level) {
  927. btrfs_tree_unlock(eb);
  928. free_extent_buffer(eb);
  929. return 0;
  930. }
  931. if (cow) {
  932. ret = btrfs_cow_block(trans, dest, eb, NULL, 0, &eb,
  933. BTRFS_NESTING_COW);
  934. if (ret) {
  935. btrfs_tree_unlock(eb);
  936. free_extent_buffer(eb);
  937. return ret;
  938. }
  939. }
  940. if (next_key) {
  941. next_key->objectid = (u64)-1;
  942. next_key->type = (u8)-1;
  943. next_key->offset = (u64)-1;
  944. }
  945. parent = eb;
  946. while (1) {
  947. level = btrfs_header_level(parent);
  948. ASSERT(level >= lowest_level);
  949. ret = btrfs_bin_search(parent, 0, &key, &slot);
  950. if (ret < 0)
  951. break;
  952. if (ret && slot > 0)
  953. slot--;
  954. if (next_key && slot + 1 < btrfs_header_nritems(parent))
  955. btrfs_node_key_to_cpu(parent, next_key, slot + 1);
  956. old_bytenr = btrfs_node_blockptr(parent, slot);
  957. blocksize = fs_info->nodesize;
  958. old_ptr_gen = btrfs_node_ptr_generation(parent, slot);
  959. if (level <= max_level) {
  960. eb = path->nodes[level];
  961. new_bytenr = btrfs_node_blockptr(eb,
  962. path->slots[level]);
  963. new_ptr_gen = btrfs_node_ptr_generation(eb,
  964. path->slots[level]);
  965. } else {
  966. new_bytenr = 0;
  967. new_ptr_gen = 0;
  968. }
  969. if (WARN_ON(new_bytenr > 0 && new_bytenr == old_bytenr)) {
  970. ret = level;
  971. break;
  972. }
  973. if (new_bytenr == 0 || old_ptr_gen > last_snapshot ||
  974. memcmp_node_keys(parent, slot, path, level)) {
  975. if (level <= lowest_level) {
  976. ret = 0;
  977. break;
  978. }
  979. eb = btrfs_read_node_slot(parent, slot);
  980. if (IS_ERR(eb)) {
  981. ret = PTR_ERR(eb);
  982. break;
  983. }
  984. btrfs_tree_lock(eb);
  985. if (cow) {
  986. ret = btrfs_cow_block(trans, dest, eb, parent,
  987. slot, &eb,
  988. BTRFS_NESTING_COW);
  989. if (ret) {
  990. btrfs_tree_unlock(eb);
  991. free_extent_buffer(eb);
  992. break;
  993. }
  994. }
  995. btrfs_tree_unlock(parent);
  996. free_extent_buffer(parent);
  997. parent = eb;
  998. continue;
  999. }
  1000. if (!cow) {
  1001. btrfs_tree_unlock(parent);
  1002. free_extent_buffer(parent);
  1003. cow = 1;
  1004. goto again;
  1005. }
  1006. btrfs_node_key_to_cpu(path->nodes[level], &key,
  1007. path->slots[level]);
  1008. btrfs_release_path(path);
  1009. path->lowest_level = level;
  1010. set_bit(BTRFS_ROOT_RESET_LOCKDEP_CLASS, &src->state);
  1011. ret = btrfs_search_slot(trans, src, &key, path, 0, 1);
  1012. clear_bit(BTRFS_ROOT_RESET_LOCKDEP_CLASS, &src->state);
  1013. path->lowest_level = 0;
  1014. if (ret) {
  1015. if (ret > 0)
  1016. ret = -ENOENT;
  1017. break;
  1018. }
  1019. /*
  1020. * Info qgroup to trace both subtrees.
  1021. *
  1022. * We must trace both trees.
  1023. * 1) Tree reloc subtree
  1024. * If not traced, we will leak data numbers
  1025. * 2) Fs subtree
  1026. * If not traced, we will double count old data
  1027. *
  1028. * We don't scan the subtree right now, but only record
  1029. * the swapped tree blocks.
  1030. * The real subtree rescan is delayed until we have new
  1031. * CoW on the subtree root node before transaction commit.
  1032. */
  1033. ret = btrfs_qgroup_add_swapped_blocks(dest,
  1034. rc->block_group, parent, slot,
  1035. path->nodes[level], path->slots[level],
  1036. last_snapshot);
  1037. if (ret < 0)
  1038. break;
  1039. /*
  1040. * swap blocks in fs tree and reloc tree.
  1041. */
  1042. btrfs_set_node_blockptr(parent, slot, new_bytenr);
  1043. btrfs_set_node_ptr_generation(parent, slot, new_ptr_gen);
  1044. btrfs_set_node_blockptr(path->nodes[level],
  1045. path->slots[level], old_bytenr);
  1046. btrfs_set_node_ptr_generation(path->nodes[level],
  1047. path->slots[level], old_ptr_gen);
  1048. ref.action = BTRFS_ADD_DELAYED_REF;
  1049. ref.bytenr = old_bytenr;
  1050. ref.num_bytes = blocksize;
  1051. ref.parent = path->nodes[level]->start;
  1052. ref.owning_root = btrfs_root_id(src);
  1053. ref.ref_root = btrfs_root_id(src);
  1054. btrfs_init_tree_ref(&ref, level - 1, 0, true);
  1055. ret = btrfs_inc_extent_ref(trans, &ref);
  1056. if (unlikely(ret)) {
  1057. btrfs_abort_transaction(trans, ret);
  1058. break;
  1059. }
  1060. ref.action = BTRFS_ADD_DELAYED_REF;
  1061. ref.bytenr = new_bytenr;
  1062. ref.num_bytes = blocksize;
  1063. ref.parent = 0;
  1064. ref.owning_root = btrfs_root_id(dest);
  1065. ref.ref_root = btrfs_root_id(dest);
  1066. btrfs_init_tree_ref(&ref, level - 1, 0, true);
  1067. ret = btrfs_inc_extent_ref(trans, &ref);
  1068. if (unlikely(ret)) {
  1069. btrfs_abort_transaction(trans, ret);
  1070. break;
  1071. }
  1072. /* We don't know the real owning_root, use 0. */
  1073. ref.action = BTRFS_DROP_DELAYED_REF;
  1074. ref.bytenr = new_bytenr;
  1075. ref.num_bytes = blocksize;
  1076. ref.parent = path->nodes[level]->start;
  1077. ref.owning_root = 0;
  1078. ref.ref_root = btrfs_root_id(src);
  1079. btrfs_init_tree_ref(&ref, level - 1, 0, true);
  1080. ret = btrfs_free_extent(trans, &ref);
  1081. if (unlikely(ret)) {
  1082. btrfs_abort_transaction(trans, ret);
  1083. break;
  1084. }
  1085. /* We don't know the real owning_root, use 0. */
  1086. ref.action = BTRFS_DROP_DELAYED_REF;
  1087. ref.bytenr = old_bytenr;
  1088. ref.num_bytes = blocksize;
  1089. ref.parent = 0;
  1090. ref.owning_root = 0;
  1091. ref.ref_root = btrfs_root_id(dest);
  1092. btrfs_init_tree_ref(&ref, level - 1, 0, true);
  1093. ret = btrfs_free_extent(trans, &ref);
  1094. if (unlikely(ret)) {
  1095. btrfs_abort_transaction(trans, ret);
  1096. break;
  1097. }
  1098. btrfs_unlock_up_safe(path, 0);
  1099. ret = level;
  1100. break;
  1101. }
  1102. btrfs_tree_unlock(parent);
  1103. free_extent_buffer(parent);
  1104. return ret;
  1105. }
  1106. /*
  1107. * helper to find next relocated block in reloc tree
  1108. */
  1109. static noinline_for_stack
  1110. int walk_up_reloc_tree(struct btrfs_root *root, struct btrfs_path *path,
  1111. int *level)
  1112. {
  1113. struct extent_buffer *eb;
  1114. int i;
  1115. u64 last_snapshot;
  1116. u32 nritems;
  1117. last_snapshot = btrfs_root_last_snapshot(&root->root_item);
  1118. for (i = 0; i < *level; i++) {
  1119. free_extent_buffer(path->nodes[i]);
  1120. path->nodes[i] = NULL;
  1121. }
  1122. for (i = *level; i < BTRFS_MAX_LEVEL && path->nodes[i]; i++) {
  1123. eb = path->nodes[i];
  1124. nritems = btrfs_header_nritems(eb);
  1125. while (path->slots[i] + 1 < nritems) {
  1126. path->slots[i]++;
  1127. if (btrfs_node_ptr_generation(eb, path->slots[i]) <=
  1128. last_snapshot)
  1129. continue;
  1130. *level = i;
  1131. return 0;
  1132. }
  1133. free_extent_buffer(path->nodes[i]);
  1134. path->nodes[i] = NULL;
  1135. }
  1136. return 1;
  1137. }
  1138. /*
  1139. * walk down reloc tree to find relocated block of lowest level
  1140. */
  1141. static noinline_for_stack
  1142. int walk_down_reloc_tree(struct btrfs_root *root, struct btrfs_path *path,
  1143. int *level)
  1144. {
  1145. struct extent_buffer *eb = NULL;
  1146. int i;
  1147. u64 ptr_gen = 0;
  1148. u64 last_snapshot;
  1149. u32 nritems;
  1150. last_snapshot = btrfs_root_last_snapshot(&root->root_item);
  1151. for (i = *level; i > 0; i--) {
  1152. eb = path->nodes[i];
  1153. nritems = btrfs_header_nritems(eb);
  1154. while (path->slots[i] < nritems) {
  1155. ptr_gen = btrfs_node_ptr_generation(eb, path->slots[i]);
  1156. if (ptr_gen > last_snapshot)
  1157. break;
  1158. path->slots[i]++;
  1159. }
  1160. if (path->slots[i] >= nritems) {
  1161. if (i == *level)
  1162. break;
  1163. *level = i + 1;
  1164. return 0;
  1165. }
  1166. if (i == 1) {
  1167. *level = i;
  1168. return 0;
  1169. }
  1170. eb = btrfs_read_node_slot(eb, path->slots[i]);
  1171. if (IS_ERR(eb))
  1172. return PTR_ERR(eb);
  1173. BUG_ON(btrfs_header_level(eb) != i - 1);
  1174. path->nodes[i - 1] = eb;
  1175. path->slots[i - 1] = 0;
  1176. }
  1177. return 1;
  1178. }
  1179. /*
  1180. * invalidate extent cache for file extents whose key in range of
  1181. * [min_key, max_key)
  1182. */
  1183. static int invalidate_extent_cache(struct btrfs_root *root,
  1184. const struct btrfs_key *min_key,
  1185. const struct btrfs_key *max_key)
  1186. {
  1187. struct btrfs_fs_info *fs_info = root->fs_info;
  1188. struct btrfs_inode *inode = NULL;
  1189. u64 objectid;
  1190. u64 start, end;
  1191. u64 ino;
  1192. objectid = min_key->objectid;
  1193. while (1) {
  1194. struct extent_state *cached_state = NULL;
  1195. cond_resched();
  1196. if (inode)
  1197. iput(&inode->vfs_inode);
  1198. if (objectid > max_key->objectid)
  1199. break;
  1200. inode = btrfs_find_first_inode(root, objectid);
  1201. if (!inode)
  1202. break;
  1203. ino = btrfs_ino(inode);
  1204. if (ino > max_key->objectid) {
  1205. iput(&inode->vfs_inode);
  1206. break;
  1207. }
  1208. objectid = ino + 1;
  1209. if (!S_ISREG(inode->vfs_inode.i_mode))
  1210. continue;
  1211. if (unlikely(min_key->objectid == ino)) {
  1212. if (min_key->type > BTRFS_EXTENT_DATA_KEY)
  1213. continue;
  1214. if (min_key->type < BTRFS_EXTENT_DATA_KEY)
  1215. start = 0;
  1216. else {
  1217. start = min_key->offset;
  1218. WARN_ON(!IS_ALIGNED(start, fs_info->sectorsize));
  1219. }
  1220. } else {
  1221. start = 0;
  1222. }
  1223. if (unlikely(max_key->objectid == ino)) {
  1224. if (max_key->type < BTRFS_EXTENT_DATA_KEY)
  1225. continue;
  1226. if (max_key->type > BTRFS_EXTENT_DATA_KEY) {
  1227. end = (u64)-1;
  1228. } else {
  1229. if (max_key->offset == 0)
  1230. continue;
  1231. end = max_key->offset;
  1232. WARN_ON(!IS_ALIGNED(end, fs_info->sectorsize));
  1233. end--;
  1234. }
  1235. } else {
  1236. end = (u64)-1;
  1237. }
  1238. /* the lock_extent waits for read_folio to complete */
  1239. btrfs_lock_extent(&inode->io_tree, start, end, &cached_state);
  1240. btrfs_drop_extent_map_range(inode, start, end, true);
  1241. btrfs_unlock_extent(&inode->io_tree, start, end, &cached_state);
  1242. }
  1243. return 0;
  1244. }
  1245. static int find_next_key(struct btrfs_path *path, int level,
  1246. struct btrfs_key *key)
  1247. {
  1248. while (level < BTRFS_MAX_LEVEL) {
  1249. if (!path->nodes[level])
  1250. break;
  1251. if (path->slots[level] + 1 <
  1252. btrfs_header_nritems(path->nodes[level])) {
  1253. btrfs_node_key_to_cpu(path->nodes[level], key,
  1254. path->slots[level] + 1);
  1255. return 0;
  1256. }
  1257. level++;
  1258. }
  1259. return 1;
  1260. }
  1261. /*
  1262. * Insert current subvolume into reloc_control::dirty_subvol_roots
  1263. */
  1264. static int insert_dirty_subvol(struct btrfs_trans_handle *trans,
  1265. struct reloc_control *rc,
  1266. struct btrfs_root *root)
  1267. {
  1268. struct btrfs_root *reloc_root = root->reloc_root;
  1269. struct btrfs_root_item *reloc_root_item;
  1270. int ret;
  1271. /* @root must be a subvolume tree root with a valid reloc tree */
  1272. ASSERT(btrfs_root_id(root) != BTRFS_TREE_RELOC_OBJECTID);
  1273. ASSERT(reloc_root);
  1274. reloc_root_item = &reloc_root->root_item;
  1275. memset(&reloc_root_item->drop_progress, 0,
  1276. sizeof(reloc_root_item->drop_progress));
  1277. btrfs_set_root_drop_level(reloc_root_item, 0);
  1278. btrfs_set_root_refs(reloc_root_item, 0);
  1279. ret = btrfs_update_reloc_root(trans, root);
  1280. if (ret)
  1281. return ret;
  1282. if (list_empty(&root->reloc_dirty_list)) {
  1283. btrfs_grab_root(root);
  1284. list_add_tail(&root->reloc_dirty_list, &rc->dirty_subvol_roots);
  1285. }
  1286. return 0;
  1287. }
  1288. static int clean_dirty_subvols(struct reloc_control *rc)
  1289. {
  1290. struct btrfs_root *root;
  1291. struct btrfs_root *next;
  1292. int ret = 0;
  1293. int ret2;
  1294. list_for_each_entry_safe(root, next, &rc->dirty_subvol_roots,
  1295. reloc_dirty_list) {
  1296. if (btrfs_root_id(root) != BTRFS_TREE_RELOC_OBJECTID) {
  1297. /* Merged subvolume, cleanup its reloc root */
  1298. struct btrfs_root *reloc_root = root->reloc_root;
  1299. list_del_init(&root->reloc_dirty_list);
  1300. root->reloc_root = NULL;
  1301. /*
  1302. * Need barrier to ensure clear_bit() only happens after
  1303. * root->reloc_root = NULL. Pairs with have_reloc_root.
  1304. */
  1305. smp_wmb();
  1306. clear_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state);
  1307. if (reloc_root) {
  1308. /*
  1309. * btrfs_drop_snapshot drops our ref we hold for
  1310. * ->reloc_root. If it fails however we must
  1311. * drop the ref ourselves.
  1312. */
  1313. ret2 = btrfs_drop_snapshot(reloc_root, false, true);
  1314. if (ret2 < 0) {
  1315. btrfs_put_root(reloc_root);
  1316. if (!ret)
  1317. ret = ret2;
  1318. }
  1319. }
  1320. btrfs_put_root(root);
  1321. } else {
  1322. /* Orphan reloc tree, just clean it up */
  1323. ret2 = btrfs_drop_snapshot(root, false, true);
  1324. if (ret2 < 0) {
  1325. btrfs_put_root(root);
  1326. if (!ret)
  1327. ret = ret2;
  1328. }
  1329. }
  1330. }
  1331. return ret;
  1332. }
  1333. /*
  1334. * merge the relocated tree blocks in reloc tree with corresponding
  1335. * fs tree.
  1336. */
  1337. static noinline_for_stack int merge_reloc_root(struct reloc_control *rc,
  1338. struct btrfs_root *root)
  1339. {
  1340. struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
  1341. struct btrfs_key key;
  1342. struct btrfs_key next_key;
  1343. struct btrfs_trans_handle *trans = NULL;
  1344. struct btrfs_root *reloc_root;
  1345. struct btrfs_root_item *root_item;
  1346. struct btrfs_path *path;
  1347. struct extent_buffer *leaf;
  1348. int reserve_level;
  1349. int level;
  1350. int max_level;
  1351. int replaced = 0;
  1352. int ret = 0;
  1353. u32 min_reserved;
  1354. path = btrfs_alloc_path();
  1355. if (!path)
  1356. return -ENOMEM;
  1357. path->reada = READA_FORWARD;
  1358. reloc_root = root->reloc_root;
  1359. root_item = &reloc_root->root_item;
  1360. if (btrfs_disk_key_objectid(&root_item->drop_progress) == 0) {
  1361. level = btrfs_root_level(root_item);
  1362. refcount_inc(&reloc_root->node->refs);
  1363. path->nodes[level] = reloc_root->node;
  1364. path->slots[level] = 0;
  1365. } else {
  1366. btrfs_disk_key_to_cpu(&key, &root_item->drop_progress);
  1367. level = btrfs_root_drop_level(root_item);
  1368. BUG_ON(level == 0);
  1369. path->lowest_level = level;
  1370. ret = btrfs_search_slot(NULL, reloc_root, &key, path, 0, 0);
  1371. path->lowest_level = 0;
  1372. if (ret < 0) {
  1373. btrfs_free_path(path);
  1374. return ret;
  1375. }
  1376. btrfs_node_key_to_cpu(path->nodes[level], &next_key,
  1377. path->slots[level]);
  1378. WARN_ON(memcmp(&key, &next_key, sizeof(key)));
  1379. btrfs_unlock_up_safe(path, 0);
  1380. }
  1381. /*
  1382. * In merge_reloc_root(), we modify the upper level pointer to swap the
  1383. * tree blocks between reloc tree and subvolume tree. Thus for tree
  1384. * block COW, we COW at most from level 1 to root level for each tree.
  1385. *
  1386. * Thus the needed metadata size is at most root_level * nodesize,
  1387. * and * 2 since we have two trees to COW.
  1388. */
  1389. reserve_level = max_t(int, 1, btrfs_root_level(root_item));
  1390. min_reserved = fs_info->nodesize * reserve_level * 2;
  1391. memset(&next_key, 0, sizeof(next_key));
  1392. while (1) {
  1393. ret = btrfs_block_rsv_refill(fs_info, rc->block_rsv,
  1394. min_reserved,
  1395. BTRFS_RESERVE_FLUSH_LIMIT);
  1396. if (ret)
  1397. goto out;
  1398. trans = btrfs_start_transaction(root, 0);
  1399. if (IS_ERR(trans)) {
  1400. ret = PTR_ERR(trans);
  1401. trans = NULL;
  1402. goto out;
  1403. }
  1404. /*
  1405. * At this point we no longer have a reloc_control, so we can't
  1406. * depend on btrfs_init_reloc_root to update our last_trans.
  1407. *
  1408. * But that's ok, we started the trans handle on our
  1409. * corresponding fs_root, which means it's been added to the
  1410. * dirty list. At commit time we'll still call
  1411. * btrfs_update_reloc_root() and update our root item
  1412. * appropriately.
  1413. */
  1414. btrfs_set_root_last_trans(reloc_root, trans->transid);
  1415. trans->block_rsv = rc->block_rsv;
  1416. replaced = 0;
  1417. max_level = level;
  1418. ret = walk_down_reloc_tree(reloc_root, path, &level);
  1419. if (ret < 0)
  1420. goto out;
  1421. if (ret > 0)
  1422. break;
  1423. if (!find_next_key(path, level, &key) &&
  1424. btrfs_comp_cpu_keys(&next_key, &key) >= 0) {
  1425. ret = 0;
  1426. } else {
  1427. ret = replace_path(trans, rc, root, reloc_root, path,
  1428. &next_key, level, max_level);
  1429. }
  1430. if (ret < 0)
  1431. goto out;
  1432. if (ret > 0) {
  1433. level = ret;
  1434. btrfs_node_key_to_cpu(path->nodes[level], &key,
  1435. path->slots[level]);
  1436. replaced = 1;
  1437. }
  1438. ret = walk_up_reloc_tree(reloc_root, path, &level);
  1439. if (ret > 0)
  1440. break;
  1441. BUG_ON(level == 0);
  1442. /*
  1443. * save the merging progress in the drop_progress.
  1444. * this is OK since root refs == 1 in this case.
  1445. */
  1446. btrfs_node_key(path->nodes[level], &root_item->drop_progress,
  1447. path->slots[level]);
  1448. btrfs_set_root_drop_level(root_item, level);
  1449. btrfs_end_transaction_throttle(trans);
  1450. trans = NULL;
  1451. btrfs_btree_balance_dirty(fs_info);
  1452. if (replaced && rc->stage == UPDATE_DATA_PTRS)
  1453. invalidate_extent_cache(root, &key, &next_key);
  1454. }
  1455. /*
  1456. * handle the case only one block in the fs tree need to be
  1457. * relocated and the block is tree root.
  1458. */
  1459. leaf = btrfs_lock_root_node(root);
  1460. ret = btrfs_cow_block(trans, root, leaf, NULL, 0, &leaf,
  1461. BTRFS_NESTING_COW);
  1462. btrfs_tree_unlock(leaf);
  1463. free_extent_buffer(leaf);
  1464. out:
  1465. btrfs_free_path(path);
  1466. if (ret == 0) {
  1467. ret = insert_dirty_subvol(trans, rc, root);
  1468. if (ret)
  1469. btrfs_abort_transaction(trans, ret);
  1470. }
  1471. if (trans)
  1472. btrfs_end_transaction_throttle(trans);
  1473. btrfs_btree_balance_dirty(fs_info);
  1474. if (replaced && rc->stage == UPDATE_DATA_PTRS)
  1475. invalidate_extent_cache(root, &key, &next_key);
  1476. return ret;
  1477. }
  1478. static noinline_for_stack
  1479. int prepare_to_merge(struct reloc_control *rc, int err)
  1480. {
  1481. struct btrfs_root *root = rc->extent_root;
  1482. struct btrfs_fs_info *fs_info = root->fs_info;
  1483. struct btrfs_root *reloc_root;
  1484. struct btrfs_trans_handle *trans;
  1485. LIST_HEAD(reloc_roots);
  1486. u64 num_bytes = 0;
  1487. int ret;
  1488. mutex_lock(&fs_info->reloc_mutex);
  1489. rc->merging_rsv_size += fs_info->nodesize * (BTRFS_MAX_LEVEL - 1) * 2;
  1490. rc->merging_rsv_size += rc->nodes_relocated * 2;
  1491. mutex_unlock(&fs_info->reloc_mutex);
  1492. again:
  1493. if (!err) {
  1494. num_bytes = rc->merging_rsv_size;
  1495. ret = btrfs_block_rsv_add(fs_info, rc->block_rsv, num_bytes,
  1496. BTRFS_RESERVE_FLUSH_ALL);
  1497. if (ret)
  1498. err = ret;
  1499. }
  1500. trans = btrfs_join_transaction(rc->extent_root);
  1501. if (IS_ERR(trans)) {
  1502. if (!err)
  1503. btrfs_block_rsv_release(fs_info, rc->block_rsv,
  1504. num_bytes, NULL);
  1505. return PTR_ERR(trans);
  1506. }
  1507. if (!err) {
  1508. if (num_bytes != rc->merging_rsv_size) {
  1509. btrfs_end_transaction(trans);
  1510. btrfs_block_rsv_release(fs_info, rc->block_rsv,
  1511. num_bytes, NULL);
  1512. goto again;
  1513. }
  1514. }
  1515. rc->merge_reloc_tree = true;
  1516. while (!list_empty(&rc->reloc_roots)) {
  1517. reloc_root = list_first_entry(&rc->reloc_roots,
  1518. struct btrfs_root, root_list);
  1519. list_del_init(&reloc_root->root_list);
  1520. root = btrfs_get_fs_root(fs_info, reloc_root->root_key.offset,
  1521. false);
  1522. if (IS_ERR(root)) {
  1523. /*
  1524. * Even if we have an error we need this reloc root
  1525. * back on our list so we can clean up properly.
  1526. */
  1527. list_add(&reloc_root->root_list, &reloc_roots);
  1528. btrfs_abort_transaction(trans, (int)PTR_ERR(root));
  1529. if (!err)
  1530. err = PTR_ERR(root);
  1531. break;
  1532. }
  1533. if (unlikely(root->reloc_root != reloc_root)) {
  1534. if (root->reloc_root) {
  1535. btrfs_err(fs_info,
  1536. "reloc tree mismatch, root %lld has reloc root key (%lld %u %llu) gen %llu, expect reloc root key (%lld %u %llu) gen %llu",
  1537. btrfs_root_id(root),
  1538. btrfs_root_id(root->reloc_root),
  1539. root->reloc_root->root_key.type,
  1540. root->reloc_root->root_key.offset,
  1541. btrfs_root_generation(
  1542. &root->reloc_root->root_item),
  1543. btrfs_root_id(reloc_root),
  1544. reloc_root->root_key.type,
  1545. reloc_root->root_key.offset,
  1546. btrfs_root_generation(
  1547. &reloc_root->root_item));
  1548. } else {
  1549. btrfs_err(fs_info,
  1550. "reloc tree mismatch, root %lld has no reloc root, expect reloc root key (%lld %u %llu) gen %llu",
  1551. btrfs_root_id(root),
  1552. btrfs_root_id(reloc_root),
  1553. reloc_root->root_key.type,
  1554. reloc_root->root_key.offset,
  1555. btrfs_root_generation(
  1556. &reloc_root->root_item));
  1557. }
  1558. list_add(&reloc_root->root_list, &reloc_roots);
  1559. btrfs_put_root(root);
  1560. btrfs_abort_transaction(trans, -EUCLEAN);
  1561. if (!err)
  1562. err = -EUCLEAN;
  1563. break;
  1564. }
  1565. /*
  1566. * set reference count to 1, so btrfs_recover_relocation
  1567. * knows it should resumes merging
  1568. */
  1569. if (!err)
  1570. btrfs_set_root_refs(&reloc_root->root_item, 1);
  1571. ret = btrfs_update_reloc_root(trans, root);
  1572. /*
  1573. * Even if we have an error we need this reloc root back on our
  1574. * list so we can clean up properly.
  1575. */
  1576. list_add(&reloc_root->root_list, &reloc_roots);
  1577. btrfs_put_root(root);
  1578. if (unlikely(ret)) {
  1579. btrfs_abort_transaction(trans, ret);
  1580. if (!err)
  1581. err = ret;
  1582. break;
  1583. }
  1584. }
  1585. list_splice(&reloc_roots, &rc->reloc_roots);
  1586. if (!err)
  1587. err = btrfs_commit_transaction(trans);
  1588. else
  1589. btrfs_end_transaction(trans);
  1590. return err;
  1591. }
  1592. static noinline_for_stack
  1593. void free_reloc_roots(struct list_head *list)
  1594. {
  1595. struct btrfs_root *reloc_root, *tmp;
  1596. list_for_each_entry_safe(reloc_root, tmp, list, root_list)
  1597. __del_reloc_root(reloc_root);
  1598. }
  1599. static noinline_for_stack
  1600. void merge_reloc_roots(struct reloc_control *rc)
  1601. {
  1602. struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
  1603. struct btrfs_root *root;
  1604. struct btrfs_root *reloc_root;
  1605. LIST_HEAD(reloc_roots);
  1606. int found = 0;
  1607. int ret = 0;
  1608. again:
  1609. root = rc->extent_root;
  1610. /*
  1611. * this serializes us with btrfs_record_root_in_transaction,
  1612. * we have to make sure nobody is in the middle of
  1613. * adding their roots to the list while we are
  1614. * doing this splice
  1615. */
  1616. mutex_lock(&fs_info->reloc_mutex);
  1617. list_splice_init(&rc->reloc_roots, &reloc_roots);
  1618. mutex_unlock(&fs_info->reloc_mutex);
  1619. while (!list_empty(&reloc_roots)) {
  1620. found = 1;
  1621. reloc_root = list_first_entry(&reloc_roots, struct btrfs_root, root_list);
  1622. root = btrfs_get_fs_root(fs_info, reloc_root->root_key.offset,
  1623. false);
  1624. if (btrfs_root_refs(&reloc_root->root_item) > 0) {
  1625. if (WARN_ON(IS_ERR(root))) {
  1626. /*
  1627. * For recovery we read the fs roots on mount,
  1628. * and if we didn't find the root then we marked
  1629. * the reloc root as a garbage root. For normal
  1630. * relocation obviously the root should exist in
  1631. * memory. However there's no reason we can't
  1632. * handle the error properly here just in case.
  1633. */
  1634. ret = PTR_ERR(root);
  1635. goto out;
  1636. }
  1637. if (WARN_ON(root->reloc_root != reloc_root)) {
  1638. /*
  1639. * This can happen if on-disk metadata has some
  1640. * corruption, e.g. bad reloc tree key offset.
  1641. */
  1642. ret = -EINVAL;
  1643. goto out;
  1644. }
  1645. ret = merge_reloc_root(rc, root);
  1646. btrfs_put_root(root);
  1647. if (ret) {
  1648. if (list_empty(&reloc_root->root_list))
  1649. list_add_tail(&reloc_root->root_list,
  1650. &reloc_roots);
  1651. goto out;
  1652. }
  1653. } else {
  1654. if (!IS_ERR(root)) {
  1655. if (root->reloc_root == reloc_root) {
  1656. root->reloc_root = NULL;
  1657. btrfs_put_root(reloc_root);
  1658. }
  1659. clear_bit(BTRFS_ROOT_DEAD_RELOC_TREE,
  1660. &root->state);
  1661. btrfs_put_root(root);
  1662. }
  1663. list_del_init(&reloc_root->root_list);
  1664. /* Don't forget to queue this reloc root for cleanup */
  1665. list_add_tail(&reloc_root->reloc_dirty_list,
  1666. &rc->dirty_subvol_roots);
  1667. }
  1668. }
  1669. if (found) {
  1670. found = 0;
  1671. goto again;
  1672. }
  1673. out:
  1674. if (ret) {
  1675. btrfs_handle_fs_error(fs_info, ret, NULL);
  1676. free_reloc_roots(&reloc_roots);
  1677. /* new reloc root may be added */
  1678. mutex_lock(&fs_info->reloc_mutex);
  1679. list_splice_init(&rc->reloc_roots, &reloc_roots);
  1680. mutex_unlock(&fs_info->reloc_mutex);
  1681. free_reloc_roots(&reloc_roots);
  1682. }
  1683. /*
  1684. * We used to have
  1685. *
  1686. * BUG_ON(!RB_EMPTY_ROOT(&rc->reloc_root_tree.rb_root));
  1687. *
  1688. * here, but it's wrong. If we fail to start the transaction in
  1689. * prepare_to_merge() we will have only 0 ref reloc roots, none of which
  1690. * have actually been removed from the reloc_root_tree rb tree. This is
  1691. * fine because we're bailing here, and we hold a reference on the root
  1692. * for the list that holds it, so these roots will be cleaned up when we
  1693. * do the reloc_dirty_list afterwards. Meanwhile the root->reloc_root
  1694. * will be cleaned up on unmount.
  1695. *
  1696. * The remaining nodes will be cleaned up by free_reloc_control.
  1697. */
  1698. }
  1699. static void free_block_list(struct rb_root *blocks)
  1700. {
  1701. struct tree_block *block;
  1702. struct rb_node *rb_node;
  1703. while ((rb_node = rb_first(blocks))) {
  1704. block = rb_entry(rb_node, struct tree_block, rb_node);
  1705. rb_erase(rb_node, blocks);
  1706. kfree(block);
  1707. }
  1708. }
  1709. static int record_reloc_root_in_trans(struct btrfs_trans_handle *trans,
  1710. struct btrfs_root *reloc_root)
  1711. {
  1712. struct btrfs_fs_info *fs_info = reloc_root->fs_info;
  1713. struct btrfs_root *root;
  1714. int ret;
  1715. if (btrfs_get_root_last_trans(reloc_root) == trans->transid)
  1716. return 0;
  1717. root = btrfs_get_fs_root(fs_info, reloc_root->root_key.offset, false);
  1718. /*
  1719. * This should succeed, since we can't have a reloc root without having
  1720. * already looked up the actual root and created the reloc root for this
  1721. * root.
  1722. *
  1723. * However if there's some sort of corruption where we have a ref to a
  1724. * reloc root without a corresponding root this could return ENOENT.
  1725. */
  1726. if (IS_ERR(root)) {
  1727. DEBUG_WARN("error %ld reading root for reloc root", PTR_ERR(root));
  1728. return PTR_ERR(root);
  1729. }
  1730. if (unlikely(root->reloc_root != reloc_root)) {
  1731. DEBUG_WARN("unexpected reloc root found");
  1732. btrfs_err(fs_info,
  1733. "root %llu has two reloc roots associated with it",
  1734. reloc_root->root_key.offset);
  1735. btrfs_put_root(root);
  1736. return -EUCLEAN;
  1737. }
  1738. ret = btrfs_record_root_in_trans(trans, root);
  1739. btrfs_put_root(root);
  1740. return ret;
  1741. }
  1742. static noinline_for_stack
  1743. struct btrfs_root *select_reloc_root(struct btrfs_trans_handle *trans,
  1744. struct reloc_control *rc,
  1745. struct btrfs_backref_node *node,
  1746. struct btrfs_backref_edge *edges[])
  1747. {
  1748. struct btrfs_backref_node *next;
  1749. struct btrfs_root *root;
  1750. int index = 0;
  1751. int ret;
  1752. next = walk_up_backref(node, edges, &index);
  1753. root = next->root;
  1754. /*
  1755. * If there is no root, then our references for this block are
  1756. * incomplete, as we should be able to walk all the way up to a block
  1757. * that is owned by a root.
  1758. *
  1759. * This path is only for SHAREABLE roots, so if we come upon a
  1760. * non-SHAREABLE root then we have backrefs that resolve improperly.
  1761. *
  1762. * Both of these cases indicate file system corruption, or a bug in the
  1763. * backref walking code.
  1764. */
  1765. if (unlikely(!root)) {
  1766. btrfs_err(trans->fs_info,
  1767. "bytenr %llu doesn't have a backref path ending in a root",
  1768. node->bytenr);
  1769. return ERR_PTR(-EUCLEAN);
  1770. }
  1771. if (unlikely(!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))) {
  1772. btrfs_err(trans->fs_info,
  1773. "bytenr %llu has multiple refs with one ending in a non-shareable root",
  1774. node->bytenr);
  1775. return ERR_PTR(-EUCLEAN);
  1776. }
  1777. if (btrfs_root_id(root) == BTRFS_TREE_RELOC_OBJECTID) {
  1778. ret = record_reloc_root_in_trans(trans, root);
  1779. if (ret)
  1780. return ERR_PTR(ret);
  1781. goto found;
  1782. }
  1783. ret = btrfs_record_root_in_trans(trans, root);
  1784. if (ret)
  1785. return ERR_PTR(ret);
  1786. root = root->reloc_root;
  1787. /*
  1788. * We could have raced with another thread which failed, so
  1789. * root->reloc_root may not be set, return ENOENT in this case.
  1790. */
  1791. if (!root)
  1792. return ERR_PTR(-ENOENT);
  1793. if (unlikely(next->new_bytenr)) {
  1794. /*
  1795. * We just created the reloc root, so we shouldn't have
  1796. * ->new_bytenr set yet. If it is then we have multiple roots
  1797. * pointing at the same bytenr which indicates corruption, or
  1798. * we've made a mistake in the backref walking code.
  1799. */
  1800. ASSERT(next->new_bytenr == 0);
  1801. btrfs_err(trans->fs_info,
  1802. "bytenr %llu possibly has multiple roots pointing at the same bytenr %llu",
  1803. node->bytenr, next->bytenr);
  1804. return ERR_PTR(-EUCLEAN);
  1805. }
  1806. next->new_bytenr = root->node->start;
  1807. btrfs_put_root(next->root);
  1808. next->root = btrfs_grab_root(root);
  1809. ASSERT(next->root);
  1810. mark_block_processed(rc, next);
  1811. found:
  1812. next = node;
  1813. /* setup backref node path for btrfs_reloc_cow_block */
  1814. while (1) {
  1815. rc->backref_cache.path[next->level] = next;
  1816. if (--index < 0)
  1817. break;
  1818. next = edges[index]->node[UPPER];
  1819. }
  1820. return root;
  1821. }
  1822. /*
  1823. * Select a tree root for relocation.
  1824. *
  1825. * Return NULL if the block is not shareable. We should use do_relocation() in
  1826. * this case.
  1827. *
  1828. * Return a tree root pointer if the block is shareable.
  1829. * Return -ENOENT if the block is root of reloc tree.
  1830. */
  1831. static noinline_for_stack
  1832. struct btrfs_root *select_one_root(struct btrfs_backref_node *node)
  1833. {
  1834. struct btrfs_backref_node *next;
  1835. struct btrfs_root *root;
  1836. struct btrfs_root *fs_root = NULL;
  1837. struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
  1838. int index = 0;
  1839. next = node;
  1840. while (1) {
  1841. cond_resched();
  1842. next = walk_up_backref(next, edges, &index);
  1843. root = next->root;
  1844. /*
  1845. * This can occur if we have incomplete extent refs leading all
  1846. * the way up a particular path, in this case return -EUCLEAN.
  1847. */
  1848. if (unlikely(!root))
  1849. return ERR_PTR(-EUCLEAN);
  1850. /* No other choice for non-shareable tree */
  1851. if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
  1852. return root;
  1853. if (btrfs_root_id(root) != BTRFS_TREE_RELOC_OBJECTID)
  1854. fs_root = root;
  1855. if (next != node)
  1856. return NULL;
  1857. next = walk_down_backref(edges, &index);
  1858. if (!next || next->level <= node->level)
  1859. break;
  1860. }
  1861. if (!fs_root)
  1862. return ERR_PTR(-ENOENT);
  1863. return fs_root;
  1864. }
  1865. static noinline_for_stack u64 calcu_metadata_size(struct reloc_control *rc,
  1866. struct btrfs_backref_node *node)
  1867. {
  1868. struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
  1869. struct btrfs_backref_node *next = node;
  1870. struct btrfs_backref_edge *edge;
  1871. struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
  1872. u64 num_bytes = 0;
  1873. int index = 0;
  1874. BUG_ON(node->processed);
  1875. while (next) {
  1876. cond_resched();
  1877. while (1) {
  1878. if (next->processed)
  1879. break;
  1880. num_bytes += fs_info->nodesize;
  1881. if (list_empty(&next->upper))
  1882. break;
  1883. edge = list_first_entry(&next->upper, struct btrfs_backref_edge,
  1884. list[LOWER]);
  1885. edges[index++] = edge;
  1886. next = edge->node[UPPER];
  1887. }
  1888. next = walk_down_backref(edges, &index);
  1889. }
  1890. return num_bytes;
  1891. }
  1892. static int refill_metadata_space(struct btrfs_trans_handle *trans,
  1893. struct reloc_control *rc, u64 num_bytes)
  1894. {
  1895. struct btrfs_fs_info *fs_info = trans->fs_info;
  1896. int ret;
  1897. trans->block_rsv = rc->block_rsv;
  1898. rc->reserved_bytes += num_bytes;
  1899. /*
  1900. * We are under a transaction here so we can only do limited flushing.
  1901. * If we get an enospc just kick back -EAGAIN so we know to drop the
  1902. * transaction and try to refill when we can flush all the things.
  1903. */
  1904. ret = btrfs_block_rsv_refill(fs_info, rc->block_rsv, num_bytes,
  1905. BTRFS_RESERVE_FLUSH_LIMIT);
  1906. if (ret) {
  1907. u64 tmp = fs_info->nodesize * RELOCATION_RESERVED_NODES;
  1908. while (tmp <= rc->reserved_bytes)
  1909. tmp <<= 1;
  1910. /*
  1911. * only one thread can access block_rsv at this point,
  1912. * so we don't need hold lock to protect block_rsv.
  1913. * we expand more reservation size here to allow enough
  1914. * space for relocation and we will return earlier in
  1915. * enospc case.
  1916. */
  1917. rc->block_rsv->size = tmp + fs_info->nodesize *
  1918. RELOCATION_RESERVED_NODES;
  1919. return -EAGAIN;
  1920. }
  1921. return 0;
  1922. }
  1923. static int reserve_metadata_space(struct btrfs_trans_handle *trans,
  1924. struct reloc_control *rc,
  1925. struct btrfs_backref_node *node)
  1926. {
  1927. u64 num_bytes;
  1928. num_bytes = calcu_metadata_size(rc, node) * 2;
  1929. return refill_metadata_space(trans, rc, num_bytes);
  1930. }
  1931. /*
  1932. * relocate a block tree, and then update pointers in upper level
  1933. * blocks that reference the block to point to the new location.
  1934. *
  1935. * if called by link_to_upper, the block has already been relocated.
  1936. * in that case this function just updates pointers.
  1937. */
  1938. static int do_relocation(struct btrfs_trans_handle *trans,
  1939. struct reloc_control *rc,
  1940. struct btrfs_backref_node *node,
  1941. struct btrfs_key *key,
  1942. struct btrfs_path *path, int lowest)
  1943. {
  1944. struct btrfs_backref_node *upper;
  1945. struct btrfs_backref_edge *edge;
  1946. struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
  1947. struct btrfs_root *root;
  1948. struct extent_buffer *eb;
  1949. u32 blocksize;
  1950. u64 bytenr;
  1951. int slot;
  1952. int ret = 0;
  1953. /*
  1954. * If we are lowest then this is the first time we're processing this
  1955. * block, and thus shouldn't have an eb associated with it yet.
  1956. */
  1957. ASSERT(!lowest || !node->eb);
  1958. path->lowest_level = node->level + 1;
  1959. rc->backref_cache.path[node->level] = node;
  1960. list_for_each_entry(edge, &node->upper, list[LOWER]) {
  1961. cond_resched();
  1962. upper = edge->node[UPPER];
  1963. root = select_reloc_root(trans, rc, upper, edges);
  1964. if (IS_ERR(root)) {
  1965. ret = PTR_ERR(root);
  1966. goto next;
  1967. }
  1968. if (upper->eb && !upper->locked) {
  1969. if (!lowest) {
  1970. ret = btrfs_bin_search(upper->eb, 0, key, &slot);
  1971. if (ret < 0)
  1972. goto next;
  1973. BUG_ON(ret);
  1974. bytenr = btrfs_node_blockptr(upper->eb, slot);
  1975. if (node->eb->start == bytenr)
  1976. goto next;
  1977. }
  1978. btrfs_backref_drop_node_buffer(upper);
  1979. }
  1980. if (!upper->eb) {
  1981. ret = btrfs_search_slot(trans, root, key, path, 0, 1);
  1982. if (ret) {
  1983. if (ret > 0)
  1984. ret = -ENOENT;
  1985. btrfs_release_path(path);
  1986. break;
  1987. }
  1988. if (!upper->eb) {
  1989. upper->eb = path->nodes[upper->level];
  1990. path->nodes[upper->level] = NULL;
  1991. } else {
  1992. BUG_ON(upper->eb != path->nodes[upper->level]);
  1993. }
  1994. upper->locked = 1;
  1995. path->locks[upper->level] = 0;
  1996. slot = path->slots[upper->level];
  1997. btrfs_release_path(path);
  1998. } else {
  1999. ret = btrfs_bin_search(upper->eb, 0, key, &slot);
  2000. if (ret < 0)
  2001. goto next;
  2002. BUG_ON(ret);
  2003. }
  2004. bytenr = btrfs_node_blockptr(upper->eb, slot);
  2005. if (lowest) {
  2006. if (unlikely(bytenr != node->bytenr)) {
  2007. btrfs_err(root->fs_info,
  2008. "lowest leaf/node mismatch: bytenr %llu node->bytenr %llu slot %d upper %llu",
  2009. bytenr, node->bytenr, slot,
  2010. upper->eb->start);
  2011. ret = -EIO;
  2012. goto next;
  2013. }
  2014. } else {
  2015. if (node->eb->start == bytenr)
  2016. goto next;
  2017. }
  2018. blocksize = root->fs_info->nodesize;
  2019. eb = btrfs_read_node_slot(upper->eb, slot);
  2020. if (IS_ERR(eb)) {
  2021. ret = PTR_ERR(eb);
  2022. goto next;
  2023. }
  2024. btrfs_tree_lock(eb);
  2025. if (!node->eb) {
  2026. ret = btrfs_cow_block(trans, root, eb, upper->eb,
  2027. slot, &eb, BTRFS_NESTING_COW);
  2028. btrfs_tree_unlock(eb);
  2029. free_extent_buffer(eb);
  2030. if (ret < 0)
  2031. goto next;
  2032. /*
  2033. * We've just COWed this block, it should have updated
  2034. * the correct backref node entry.
  2035. */
  2036. ASSERT(node->eb == eb);
  2037. } else {
  2038. struct btrfs_ref ref = {
  2039. .action = BTRFS_ADD_DELAYED_REF,
  2040. .bytenr = node->eb->start,
  2041. .num_bytes = blocksize,
  2042. .parent = upper->eb->start,
  2043. .owning_root = btrfs_header_owner(upper->eb),
  2044. .ref_root = btrfs_header_owner(upper->eb),
  2045. };
  2046. btrfs_set_node_blockptr(upper->eb, slot,
  2047. node->eb->start);
  2048. btrfs_set_node_ptr_generation(upper->eb, slot,
  2049. trans->transid);
  2050. btrfs_mark_buffer_dirty(trans, upper->eb);
  2051. btrfs_init_tree_ref(&ref, node->level,
  2052. btrfs_root_id(root), false);
  2053. ret = btrfs_inc_extent_ref(trans, &ref);
  2054. if (!ret)
  2055. ret = btrfs_drop_subtree(trans, root, eb,
  2056. upper->eb);
  2057. if (unlikely(ret))
  2058. btrfs_abort_transaction(trans, ret);
  2059. }
  2060. next:
  2061. if (!upper->pending)
  2062. btrfs_backref_drop_node_buffer(upper);
  2063. else
  2064. btrfs_backref_unlock_node_buffer(upper);
  2065. if (ret)
  2066. break;
  2067. }
  2068. if (!ret && node->pending) {
  2069. btrfs_backref_drop_node_buffer(node);
  2070. list_del_init(&node->list);
  2071. node->pending = 0;
  2072. }
  2073. path->lowest_level = 0;
  2074. /*
  2075. * We should have allocated all of our space in the block rsv and thus
  2076. * shouldn't ENOSPC.
  2077. */
  2078. ASSERT(ret != -ENOSPC);
  2079. return ret;
  2080. }
  2081. static int link_to_upper(struct btrfs_trans_handle *trans,
  2082. struct reloc_control *rc,
  2083. struct btrfs_backref_node *node,
  2084. struct btrfs_path *path)
  2085. {
  2086. struct btrfs_key key;
  2087. btrfs_node_key_to_cpu(node->eb, &key, 0);
  2088. return do_relocation(trans, rc, node, &key, path, 0);
  2089. }
  2090. static int finish_pending_nodes(struct btrfs_trans_handle *trans,
  2091. struct reloc_control *rc,
  2092. struct btrfs_path *path, int err)
  2093. {
  2094. LIST_HEAD(list);
  2095. struct btrfs_backref_cache *cache = &rc->backref_cache;
  2096. struct btrfs_backref_node *node;
  2097. int level;
  2098. int ret;
  2099. for (level = 0; level < BTRFS_MAX_LEVEL; level++) {
  2100. while (!list_empty(&cache->pending[level])) {
  2101. node = list_first_entry(&cache->pending[level],
  2102. struct btrfs_backref_node, list);
  2103. list_move_tail(&node->list, &list);
  2104. BUG_ON(!node->pending);
  2105. if (!err) {
  2106. ret = link_to_upper(trans, rc, node, path);
  2107. if (ret < 0)
  2108. err = ret;
  2109. }
  2110. }
  2111. list_splice_init(&list, &cache->pending[level]);
  2112. }
  2113. return err;
  2114. }
  2115. /*
  2116. * mark a block and all blocks directly/indirectly reference the block
  2117. * as processed.
  2118. */
  2119. static void update_processed_blocks(struct reloc_control *rc,
  2120. struct btrfs_backref_node *node)
  2121. {
  2122. struct btrfs_backref_node *next = node;
  2123. struct btrfs_backref_edge *edge;
  2124. struct btrfs_backref_edge *edges[BTRFS_MAX_LEVEL - 1];
  2125. int index = 0;
  2126. while (next) {
  2127. cond_resched();
  2128. while (1) {
  2129. if (next->processed)
  2130. break;
  2131. mark_block_processed(rc, next);
  2132. if (list_empty(&next->upper))
  2133. break;
  2134. edge = list_first_entry(&next->upper, struct btrfs_backref_edge,
  2135. list[LOWER]);
  2136. edges[index++] = edge;
  2137. next = edge->node[UPPER];
  2138. }
  2139. next = walk_down_backref(edges, &index);
  2140. }
  2141. }
  2142. static int tree_block_processed(u64 bytenr, struct reloc_control *rc)
  2143. {
  2144. u32 blocksize = rc->extent_root->fs_info->nodesize;
  2145. if (btrfs_test_range_bit(&rc->processed_blocks, bytenr,
  2146. bytenr + blocksize - 1, EXTENT_DIRTY, NULL))
  2147. return 1;
  2148. return 0;
  2149. }
  2150. static int get_tree_block_key(struct btrfs_fs_info *fs_info,
  2151. struct tree_block *block)
  2152. {
  2153. struct btrfs_tree_parent_check check = {
  2154. .level = block->level,
  2155. .owner_root = block->owner,
  2156. .transid = block->key.offset
  2157. };
  2158. struct extent_buffer *eb;
  2159. eb = read_tree_block(fs_info, block->bytenr, &check);
  2160. if (IS_ERR(eb))
  2161. return PTR_ERR(eb);
  2162. if (unlikely(!extent_buffer_uptodate(eb))) {
  2163. free_extent_buffer(eb);
  2164. return -EIO;
  2165. }
  2166. if (block->level == 0)
  2167. btrfs_item_key_to_cpu(eb, &block->key, 0);
  2168. else
  2169. btrfs_node_key_to_cpu(eb, &block->key, 0);
  2170. free_extent_buffer(eb);
  2171. block->key_ready = true;
  2172. return 0;
  2173. }
  2174. /*
  2175. * helper function to relocate a tree block
  2176. */
  2177. static int relocate_tree_block(struct btrfs_trans_handle *trans,
  2178. struct reloc_control *rc,
  2179. struct btrfs_backref_node *node,
  2180. struct btrfs_key *key,
  2181. struct btrfs_path *path)
  2182. {
  2183. struct btrfs_root *root;
  2184. int ret = 0;
  2185. if (!node)
  2186. return 0;
  2187. /*
  2188. * If we fail here we want to drop our backref_node because we are going
  2189. * to start over and regenerate the tree for it.
  2190. */
  2191. ret = reserve_metadata_space(trans, rc, node);
  2192. if (ret)
  2193. goto out;
  2194. BUG_ON(node->processed);
  2195. root = select_one_root(node);
  2196. if (IS_ERR(root)) {
  2197. ret = PTR_ERR(root);
  2198. /* See explanation in select_one_root for the -EUCLEAN case. */
  2199. ASSERT(ret == -ENOENT);
  2200. if (ret == -ENOENT) {
  2201. ret = 0;
  2202. update_processed_blocks(rc, node);
  2203. }
  2204. goto out;
  2205. }
  2206. if (root) {
  2207. if (test_bit(BTRFS_ROOT_SHAREABLE, &root->state)) {
  2208. /*
  2209. * This block was the root block of a root, and this is
  2210. * the first time we're processing the block and thus it
  2211. * should not have had the ->new_bytenr modified.
  2212. *
  2213. * However in the case of corruption we could have
  2214. * multiple refs pointing to the same block improperly,
  2215. * and thus we would trip over these checks. ASSERT()
  2216. * for the developer case, because it could indicate a
  2217. * bug in the backref code, however error out for a
  2218. * normal user in the case of corruption.
  2219. */
  2220. ASSERT(node->new_bytenr == 0);
  2221. if (unlikely(node->new_bytenr)) {
  2222. btrfs_err(root->fs_info,
  2223. "bytenr %llu has improper references to it",
  2224. node->bytenr);
  2225. ret = -EUCLEAN;
  2226. goto out;
  2227. }
  2228. ret = btrfs_record_root_in_trans(trans, root);
  2229. if (ret)
  2230. goto out;
  2231. /*
  2232. * Another thread could have failed, need to check if we
  2233. * have reloc_root actually set.
  2234. */
  2235. if (!root->reloc_root) {
  2236. ret = -ENOENT;
  2237. goto out;
  2238. }
  2239. root = root->reloc_root;
  2240. node->new_bytenr = root->node->start;
  2241. btrfs_put_root(node->root);
  2242. node->root = btrfs_grab_root(root);
  2243. ASSERT(node->root);
  2244. } else {
  2245. btrfs_err(root->fs_info,
  2246. "bytenr %llu resolved to a non-shareable root",
  2247. node->bytenr);
  2248. ret = -EUCLEAN;
  2249. goto out;
  2250. }
  2251. if (!ret)
  2252. update_processed_blocks(rc, node);
  2253. } else {
  2254. ret = do_relocation(trans, rc, node, key, path, 1);
  2255. }
  2256. out:
  2257. if (ret || node->level == 0)
  2258. btrfs_backref_cleanup_node(&rc->backref_cache, node);
  2259. return ret;
  2260. }
  2261. static int relocate_cowonly_block(struct btrfs_trans_handle *trans,
  2262. struct reloc_control *rc, struct tree_block *block,
  2263. struct btrfs_path *path)
  2264. {
  2265. struct btrfs_fs_info *fs_info = trans->fs_info;
  2266. struct btrfs_root *root;
  2267. u64 num_bytes;
  2268. int nr_levels;
  2269. int ret;
  2270. root = btrfs_get_fs_root(fs_info, block->owner, true);
  2271. if (IS_ERR(root))
  2272. return PTR_ERR(root);
  2273. nr_levels = max(btrfs_header_level(root->node) - block->level, 0) + 1;
  2274. num_bytes = fs_info->nodesize * nr_levels;
  2275. ret = refill_metadata_space(trans, rc, num_bytes);
  2276. if (ret) {
  2277. btrfs_put_root(root);
  2278. return ret;
  2279. }
  2280. path->lowest_level = block->level;
  2281. if (root == root->fs_info->chunk_root)
  2282. btrfs_reserve_chunk_metadata(trans, false);
  2283. ret = btrfs_search_slot(trans, root, &block->key, path, 0, 1);
  2284. path->lowest_level = 0;
  2285. btrfs_release_path(path);
  2286. if (root == root->fs_info->chunk_root)
  2287. btrfs_trans_release_chunk_metadata(trans);
  2288. if (ret > 0)
  2289. ret = 0;
  2290. btrfs_put_root(root);
  2291. return ret;
  2292. }
  2293. /*
  2294. * relocate a list of blocks
  2295. */
  2296. static noinline_for_stack
  2297. int relocate_tree_blocks(struct btrfs_trans_handle *trans,
  2298. struct reloc_control *rc, struct rb_root *blocks)
  2299. {
  2300. struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
  2301. struct btrfs_backref_node *node;
  2302. struct btrfs_path *path;
  2303. struct tree_block *block;
  2304. struct tree_block *next;
  2305. int ret = 0;
  2306. path = btrfs_alloc_path();
  2307. if (!path) {
  2308. ret = -ENOMEM;
  2309. goto out_free_blocks;
  2310. }
  2311. /* Kick in readahead for tree blocks with missing keys */
  2312. rbtree_postorder_for_each_entry_safe(block, next, blocks, rb_node) {
  2313. if (!block->key_ready)
  2314. btrfs_readahead_tree_block(fs_info, block->bytenr,
  2315. block->owner, 0,
  2316. block->level);
  2317. }
  2318. /* Get first keys */
  2319. rbtree_postorder_for_each_entry_safe(block, next, blocks, rb_node) {
  2320. if (!block->key_ready) {
  2321. ret = get_tree_block_key(fs_info, block);
  2322. if (ret)
  2323. goto out_free_path;
  2324. }
  2325. }
  2326. /* Do tree relocation */
  2327. rbtree_postorder_for_each_entry_safe(block, next, blocks, rb_node) {
  2328. /*
  2329. * For COWonly blocks, or the data reloc tree, we only need to
  2330. * COW down to the block, there's no need to generate a backref
  2331. * tree.
  2332. */
  2333. if (block->owner &&
  2334. (!btrfs_is_fstree(block->owner) ||
  2335. block->owner == BTRFS_DATA_RELOC_TREE_OBJECTID)) {
  2336. ret = relocate_cowonly_block(trans, rc, block, path);
  2337. if (ret)
  2338. break;
  2339. continue;
  2340. }
  2341. node = build_backref_tree(trans, rc, &block->key,
  2342. block->level, block->bytenr);
  2343. if (IS_ERR(node)) {
  2344. ret = PTR_ERR(node);
  2345. goto out;
  2346. }
  2347. ret = relocate_tree_block(trans, rc, node, &block->key,
  2348. path);
  2349. if (ret < 0)
  2350. break;
  2351. }
  2352. out:
  2353. ret = finish_pending_nodes(trans, rc, path, ret);
  2354. out_free_path:
  2355. btrfs_free_path(path);
  2356. out_free_blocks:
  2357. free_block_list(blocks);
  2358. return ret;
  2359. }
  2360. static noinline_for_stack int prealloc_file_extent_cluster(struct reloc_control *rc)
  2361. {
  2362. const struct file_extent_cluster *cluster = &rc->cluster;
  2363. struct btrfs_inode *inode = BTRFS_I(rc->data_inode);
  2364. u64 alloc_hint = 0;
  2365. u64 start;
  2366. u64 end;
  2367. u64 offset = inode->reloc_block_group_start;
  2368. u64 num_bytes;
  2369. int nr;
  2370. int ret = 0;
  2371. u64 prealloc_start = cluster->start - offset;
  2372. u64 prealloc_end = cluster->end - offset;
  2373. u64 cur_offset = prealloc_start;
  2374. /*
  2375. * For blocksize < folio size case (either bs < page size or large folios),
  2376. * beyond i_size, all blocks are filled with zero.
  2377. *
  2378. * If the current cluster covers the above range, btrfs_do_readpage()
  2379. * will skip the read, and relocate_one_folio() will later writeback
  2380. * the padding zeros as new data, causing data corruption.
  2381. *
  2382. * Here we have to invalidate the cache covering our cluster.
  2383. */
  2384. ret = filemap_invalidate_inode(&inode->vfs_inode, true, prealloc_start,
  2385. prealloc_end);
  2386. if (ret < 0)
  2387. return ret;
  2388. BUG_ON(cluster->start != cluster->boundary[0]);
  2389. ret = btrfs_alloc_data_chunk_ondemand(inode,
  2390. prealloc_end + 1 - prealloc_start);
  2391. if (ret)
  2392. return ret;
  2393. btrfs_inode_lock(inode, 0);
  2394. for (nr = 0; nr < cluster->nr; nr++) {
  2395. struct extent_state *cached_state = NULL;
  2396. start = cluster->boundary[nr] - offset;
  2397. if (nr + 1 < cluster->nr)
  2398. end = cluster->boundary[nr + 1] - 1 - offset;
  2399. else
  2400. end = cluster->end - offset;
  2401. btrfs_lock_extent(&inode->io_tree, start, end, &cached_state);
  2402. num_bytes = end + 1 - start;
  2403. ret = btrfs_prealloc_file_range(&inode->vfs_inode, 0, start,
  2404. num_bytes, num_bytes,
  2405. end + 1, &alloc_hint);
  2406. cur_offset = end + 1;
  2407. btrfs_unlock_extent(&inode->io_tree, start, end, &cached_state);
  2408. if (ret)
  2409. break;
  2410. }
  2411. btrfs_inode_unlock(inode, 0);
  2412. if (cur_offset < prealloc_end)
  2413. btrfs_free_reserved_data_space_noquota(inode,
  2414. prealloc_end + 1 - cur_offset);
  2415. return ret;
  2416. }
  2417. static noinline_for_stack int setup_relocation_extent_mapping(struct reloc_control *rc)
  2418. {
  2419. struct btrfs_inode *inode = BTRFS_I(rc->data_inode);
  2420. struct extent_map *em;
  2421. struct extent_state *cached_state = NULL;
  2422. u64 offset = inode->reloc_block_group_start;
  2423. u64 start = rc->cluster.start - offset;
  2424. u64 end = rc->cluster.end - offset;
  2425. int ret = 0;
  2426. em = btrfs_alloc_extent_map();
  2427. if (!em)
  2428. return -ENOMEM;
  2429. em->start = start;
  2430. em->len = end + 1 - start;
  2431. em->disk_bytenr = rc->cluster.start;
  2432. em->disk_num_bytes = em->len;
  2433. em->ram_bytes = em->len;
  2434. em->flags |= EXTENT_FLAG_PINNED;
  2435. btrfs_lock_extent(&inode->io_tree, start, end, &cached_state);
  2436. ret = btrfs_replace_extent_map_range(inode, em, false);
  2437. btrfs_unlock_extent(&inode->io_tree, start, end, &cached_state);
  2438. btrfs_free_extent_map(em);
  2439. return ret;
  2440. }
  2441. /*
  2442. * Allow error injection to test balance/relocation cancellation
  2443. */
  2444. noinline int btrfs_should_cancel_balance(const struct btrfs_fs_info *fs_info)
  2445. {
  2446. return atomic_read(&fs_info->balance_cancel_req) ||
  2447. atomic_read(&fs_info->reloc_cancel_req) ||
  2448. fatal_signal_pending(current);
  2449. }
  2450. ALLOW_ERROR_INJECTION(btrfs_should_cancel_balance, TRUE);
  2451. static u64 get_cluster_boundary_end(const struct file_extent_cluster *cluster,
  2452. int cluster_nr)
  2453. {
  2454. /* Last extent, use cluster end directly */
  2455. if (cluster_nr >= cluster->nr - 1)
  2456. return cluster->end;
  2457. /* Use next boundary start*/
  2458. return cluster->boundary[cluster_nr + 1] - 1;
  2459. }
  2460. static int relocate_one_folio(struct reloc_control *rc,
  2461. struct file_ra_state *ra,
  2462. int *cluster_nr, u64 *file_offset_ret)
  2463. {
  2464. const struct file_extent_cluster *cluster = &rc->cluster;
  2465. struct inode *inode = rc->data_inode;
  2466. struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
  2467. const u64 orig_file_offset = *file_offset_ret;
  2468. u64 offset = BTRFS_I(inode)->reloc_block_group_start;
  2469. const pgoff_t last_index = (cluster->end - offset) >> PAGE_SHIFT;
  2470. const pgoff_t index = orig_file_offset >> PAGE_SHIFT;
  2471. gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
  2472. struct folio *folio;
  2473. u64 folio_start;
  2474. u64 folio_end;
  2475. u64 cur;
  2476. int ret;
  2477. const bool use_rst = btrfs_need_stripe_tree_update(fs_info, rc->block_group->flags);
  2478. ASSERT(index <= last_index);
  2479. again:
  2480. folio = filemap_lock_folio(inode->i_mapping, index);
  2481. if (IS_ERR(folio)) {
  2482. /*
  2483. * On relocation we're doing readahead on the relocation inode,
  2484. * but if the filesystem is backed by a RAID stripe tree we can
  2485. * get ENOENT (e.g. due to preallocated extents not being
  2486. * mapped in the RST) from the lookup.
  2487. *
  2488. * But readahead doesn't handle the error and submits invalid
  2489. * reads to the device, causing a assertion failures.
  2490. */
  2491. if (!use_rst)
  2492. page_cache_sync_readahead(inode->i_mapping, ra, NULL,
  2493. index, last_index + 1 - index);
  2494. folio = __filemap_get_folio(inode->i_mapping, index,
  2495. FGP_LOCK | FGP_ACCESSED | FGP_CREAT,
  2496. mask);
  2497. if (IS_ERR(folio))
  2498. return PTR_ERR(folio);
  2499. }
  2500. if (folio_test_readahead(folio) && !use_rst)
  2501. page_cache_async_readahead(inode->i_mapping, ra, NULL,
  2502. folio, last_index + 1 - index);
  2503. if (!folio_test_uptodate(folio)) {
  2504. btrfs_read_folio(NULL, folio);
  2505. folio_lock(folio);
  2506. if (unlikely(!folio_test_uptodate(folio))) {
  2507. ret = -EIO;
  2508. goto release_folio;
  2509. }
  2510. if (folio->mapping != inode->i_mapping) {
  2511. folio_unlock(folio);
  2512. folio_put(folio);
  2513. goto again;
  2514. }
  2515. }
  2516. /*
  2517. * We could have lost folio private when we dropped the lock to read the
  2518. * folio above, make sure we set_folio_extent_mapped() here so we have any
  2519. * of the subpage blocksize stuff we need in place.
  2520. */
  2521. ret = set_folio_extent_mapped(folio);
  2522. if (ret < 0)
  2523. goto release_folio;
  2524. folio_start = folio_pos(folio);
  2525. folio_end = folio_start + folio_size(folio) - 1;
  2526. /*
  2527. * Start from the cluster, as for subpage case, the cluster can start
  2528. * inside the folio.
  2529. */
  2530. cur = max(folio_start, cluster->boundary[*cluster_nr] - offset);
  2531. while (cur <= folio_end) {
  2532. struct extent_state *cached_state = NULL;
  2533. u64 extent_start = cluster->boundary[*cluster_nr] - offset;
  2534. u64 extent_end = get_cluster_boundary_end(cluster,
  2535. *cluster_nr) - offset;
  2536. u64 clamped_start = max(folio_start, extent_start);
  2537. u64 clamped_end = min(folio_end, extent_end);
  2538. u32 clamped_len = clamped_end + 1 - clamped_start;
  2539. /* Reserve metadata for this range */
  2540. ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode),
  2541. clamped_len, clamped_len,
  2542. false);
  2543. if (ret)
  2544. goto release_folio;
  2545. /* Mark the range delalloc and dirty for later writeback */
  2546. btrfs_lock_extent(&BTRFS_I(inode)->io_tree, clamped_start,
  2547. clamped_end, &cached_state);
  2548. ret = btrfs_set_extent_delalloc(BTRFS_I(inode), clamped_start,
  2549. clamped_end, 0, &cached_state);
  2550. if (ret) {
  2551. btrfs_clear_extent_bit(&BTRFS_I(inode)->io_tree,
  2552. clamped_start, clamped_end,
  2553. EXTENT_LOCKED | EXTENT_BOUNDARY,
  2554. &cached_state);
  2555. btrfs_delalloc_release_metadata(BTRFS_I(inode),
  2556. clamped_len, true);
  2557. btrfs_delalloc_release_extents(BTRFS_I(inode),
  2558. clamped_len);
  2559. goto release_folio;
  2560. }
  2561. btrfs_folio_set_dirty(fs_info, folio, clamped_start, clamped_len);
  2562. /*
  2563. * Set the boundary if it's inside the folio.
  2564. * Data relocation requires the destination extents to have the
  2565. * same size as the source.
  2566. * EXTENT_BOUNDARY bit prevents current extent from being merged
  2567. * with previous extent.
  2568. */
  2569. if (in_range(cluster->boundary[*cluster_nr] - offset,
  2570. folio_start, folio_size(folio))) {
  2571. u64 boundary_start = cluster->boundary[*cluster_nr] -
  2572. offset;
  2573. u64 boundary_end = boundary_start +
  2574. fs_info->sectorsize - 1;
  2575. btrfs_set_extent_bit(&BTRFS_I(inode)->io_tree,
  2576. boundary_start, boundary_end,
  2577. EXTENT_BOUNDARY, NULL);
  2578. }
  2579. btrfs_unlock_extent(&BTRFS_I(inode)->io_tree, clamped_start, clamped_end,
  2580. &cached_state);
  2581. btrfs_delalloc_release_extents(BTRFS_I(inode), clamped_len);
  2582. cur += clamped_len;
  2583. /* Crossed extent end, go to next extent */
  2584. if (cur >= extent_end) {
  2585. (*cluster_nr)++;
  2586. /* Just finished the last extent of the cluster, exit. */
  2587. if (*cluster_nr >= cluster->nr)
  2588. break;
  2589. }
  2590. }
  2591. folio_unlock(folio);
  2592. folio_put(folio);
  2593. balance_dirty_pages_ratelimited(inode->i_mapping);
  2594. btrfs_throttle(fs_info);
  2595. if (btrfs_should_cancel_balance(fs_info))
  2596. ret = -ECANCELED;
  2597. *file_offset_ret = folio_end + 1;
  2598. return ret;
  2599. release_folio:
  2600. folio_unlock(folio);
  2601. folio_put(folio);
  2602. return ret;
  2603. }
  2604. static int relocate_file_extent_cluster(struct reloc_control *rc)
  2605. {
  2606. struct inode *inode = rc->data_inode;
  2607. const struct file_extent_cluster *cluster = &rc->cluster;
  2608. u64 offset = BTRFS_I(inode)->reloc_block_group_start;
  2609. u64 cur_file_offset = cluster->start - offset;
  2610. struct file_ra_state AUTO_KFREE(ra);
  2611. int cluster_nr = 0;
  2612. int ret = 0;
  2613. if (!cluster->nr)
  2614. return 0;
  2615. ra = kzalloc(sizeof(*ra), GFP_NOFS);
  2616. if (!ra)
  2617. return -ENOMEM;
  2618. ret = prealloc_file_extent_cluster(rc);
  2619. if (ret)
  2620. return ret;
  2621. file_ra_state_init(ra, inode->i_mapping);
  2622. ret = setup_relocation_extent_mapping(rc);
  2623. if (ret)
  2624. return ret;
  2625. while (cur_file_offset < cluster->end - offset) {
  2626. ret = relocate_one_folio(rc, ra, &cluster_nr, &cur_file_offset);
  2627. if (ret)
  2628. break;
  2629. }
  2630. if (ret == 0)
  2631. WARN_ON(cluster_nr != cluster->nr);
  2632. return ret;
  2633. }
  2634. static noinline_for_stack int relocate_data_extent(struct reloc_control *rc,
  2635. const struct btrfs_key *extent_key)
  2636. {
  2637. struct inode *inode = rc->data_inode;
  2638. struct file_extent_cluster *cluster = &rc->cluster;
  2639. int ret;
  2640. struct btrfs_root *root = BTRFS_I(inode)->root;
  2641. if (cluster->nr > 0 && extent_key->objectid != cluster->end + 1) {
  2642. ret = relocate_file_extent_cluster(rc);
  2643. if (ret)
  2644. return ret;
  2645. cluster->nr = 0;
  2646. }
  2647. /*
  2648. * Under simple quotas, we set root->relocation_src_root when we find
  2649. * the extent. If adjacent extents have different owners, we can't merge
  2650. * them while relocating. Handle this by storing the owning root that
  2651. * started a cluster and if we see an extent from a different root break
  2652. * cluster formation (just like the above case of non-adjacent extents).
  2653. *
  2654. * Without simple quotas, relocation_src_root is always 0, so we should
  2655. * never see a mismatch, and it should have no effect on relocation
  2656. * clusters.
  2657. */
  2658. if (cluster->nr > 0 && cluster->owning_root != root->relocation_src_root) {
  2659. u64 tmp = root->relocation_src_root;
  2660. /*
  2661. * root->relocation_src_root is the state that actually affects
  2662. * the preallocation we do here, so set it to the root owning
  2663. * the cluster we need to relocate.
  2664. */
  2665. root->relocation_src_root = cluster->owning_root;
  2666. ret = relocate_file_extent_cluster(rc);
  2667. if (ret)
  2668. return ret;
  2669. cluster->nr = 0;
  2670. /* And reset it back for the current extent's owning root. */
  2671. root->relocation_src_root = tmp;
  2672. }
  2673. if (!cluster->nr) {
  2674. cluster->start = extent_key->objectid;
  2675. cluster->owning_root = root->relocation_src_root;
  2676. }
  2677. else
  2678. BUG_ON(cluster->nr >= MAX_EXTENTS);
  2679. cluster->end = extent_key->objectid + extent_key->offset - 1;
  2680. cluster->boundary[cluster->nr] = extent_key->objectid;
  2681. cluster->nr++;
  2682. if (cluster->nr >= MAX_EXTENTS) {
  2683. ret = relocate_file_extent_cluster(rc);
  2684. if (ret)
  2685. return ret;
  2686. cluster->nr = 0;
  2687. }
  2688. return 0;
  2689. }
  2690. /*
  2691. * helper to add a tree block to the list.
  2692. * the major work is getting the generation and level of the block
  2693. */
  2694. static int add_tree_block(struct reloc_control *rc,
  2695. const struct btrfs_key *extent_key,
  2696. struct btrfs_path *path,
  2697. struct rb_root *blocks)
  2698. {
  2699. struct extent_buffer *eb;
  2700. struct btrfs_extent_item *ei;
  2701. struct btrfs_tree_block_info *bi;
  2702. struct tree_block *block;
  2703. struct rb_node *rb_node;
  2704. u32 item_size;
  2705. int level = -1;
  2706. u64 generation;
  2707. u64 owner = 0;
  2708. eb = path->nodes[0];
  2709. item_size = btrfs_item_size(eb, path->slots[0]);
  2710. if (extent_key->type == BTRFS_METADATA_ITEM_KEY ||
  2711. item_size >= sizeof(*ei) + sizeof(*bi)) {
  2712. unsigned long ptr = 0, end;
  2713. ei = btrfs_item_ptr(eb, path->slots[0],
  2714. struct btrfs_extent_item);
  2715. end = (unsigned long)ei + item_size;
  2716. if (extent_key->type == BTRFS_EXTENT_ITEM_KEY) {
  2717. bi = (struct btrfs_tree_block_info *)(ei + 1);
  2718. level = btrfs_tree_block_level(eb, bi);
  2719. ptr = (unsigned long)(bi + 1);
  2720. } else {
  2721. level = (int)extent_key->offset;
  2722. ptr = (unsigned long)(ei + 1);
  2723. }
  2724. generation = btrfs_extent_generation(eb, ei);
  2725. /*
  2726. * We're reading random blocks without knowing their owner ahead
  2727. * of time. This is ok most of the time, as all reloc roots and
  2728. * fs roots have the same lock type. However normal trees do
  2729. * not, and the only way to know ahead of time is to read the
  2730. * inline ref offset. We know it's an fs root if
  2731. *
  2732. * 1. There's more than one ref.
  2733. * 2. There's a SHARED_DATA_REF_KEY set.
  2734. * 3. FULL_BACKREF is set on the flags.
  2735. *
  2736. * Otherwise it's safe to assume that the ref offset == the
  2737. * owner of this block, so we can use that when calling
  2738. * read_tree_block.
  2739. */
  2740. if (btrfs_extent_refs(eb, ei) == 1 &&
  2741. !(btrfs_extent_flags(eb, ei) &
  2742. BTRFS_BLOCK_FLAG_FULL_BACKREF) &&
  2743. ptr < end) {
  2744. struct btrfs_extent_inline_ref *iref;
  2745. int type;
  2746. iref = (struct btrfs_extent_inline_ref *)ptr;
  2747. type = btrfs_get_extent_inline_ref_type(eb, iref,
  2748. BTRFS_REF_TYPE_BLOCK);
  2749. if (type == BTRFS_REF_TYPE_INVALID)
  2750. return -EINVAL;
  2751. if (type == BTRFS_TREE_BLOCK_REF_KEY)
  2752. owner = btrfs_extent_inline_ref_offset(eb, iref);
  2753. }
  2754. } else {
  2755. btrfs_print_leaf(eb);
  2756. btrfs_err(rc->block_group->fs_info,
  2757. "unrecognized tree backref at tree block %llu slot %u",
  2758. eb->start, path->slots[0]);
  2759. btrfs_release_path(path);
  2760. return -EUCLEAN;
  2761. }
  2762. btrfs_release_path(path);
  2763. BUG_ON(level == -1);
  2764. block = kmalloc_obj(*block, GFP_NOFS);
  2765. if (!block)
  2766. return -ENOMEM;
  2767. block->bytenr = extent_key->objectid;
  2768. block->key.objectid = rc->extent_root->fs_info->nodesize;
  2769. block->key.offset = generation;
  2770. block->level = level;
  2771. block->key_ready = false;
  2772. block->owner = owner;
  2773. rb_node = rb_simple_insert(blocks, &block->simple_node);
  2774. if (rb_node)
  2775. btrfs_backref_panic(rc->extent_root->fs_info, block->bytenr,
  2776. -EEXIST);
  2777. return 0;
  2778. }
  2779. /*
  2780. * helper to add tree blocks for backref of type BTRFS_SHARED_DATA_REF_KEY
  2781. */
  2782. static int __add_tree_block(struct reloc_control *rc,
  2783. u64 bytenr, u32 blocksize,
  2784. struct rb_root *blocks)
  2785. {
  2786. struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
  2787. BTRFS_PATH_AUTO_FREE(path);
  2788. struct btrfs_key key;
  2789. int ret;
  2790. bool skinny = btrfs_fs_incompat(fs_info, SKINNY_METADATA);
  2791. if (tree_block_processed(bytenr, rc))
  2792. return 0;
  2793. if (rb_simple_search(blocks, bytenr))
  2794. return 0;
  2795. path = btrfs_alloc_path();
  2796. if (!path)
  2797. return -ENOMEM;
  2798. again:
  2799. key.objectid = bytenr;
  2800. if (skinny) {
  2801. key.type = BTRFS_METADATA_ITEM_KEY;
  2802. key.offset = (u64)-1;
  2803. } else {
  2804. key.type = BTRFS_EXTENT_ITEM_KEY;
  2805. key.offset = blocksize;
  2806. }
  2807. path->search_commit_root = true;
  2808. path->skip_locking = true;
  2809. ret = btrfs_search_slot(NULL, rc->extent_root, &key, path, 0, 0);
  2810. if (ret < 0)
  2811. return ret;
  2812. if (ret > 0 && skinny) {
  2813. if (path->slots[0]) {
  2814. path->slots[0]--;
  2815. btrfs_item_key_to_cpu(path->nodes[0], &key,
  2816. path->slots[0]);
  2817. if (key.objectid == bytenr &&
  2818. (key.type == BTRFS_METADATA_ITEM_KEY ||
  2819. (key.type == BTRFS_EXTENT_ITEM_KEY &&
  2820. key.offset == blocksize)))
  2821. ret = 0;
  2822. }
  2823. if (ret) {
  2824. skinny = false;
  2825. btrfs_release_path(path);
  2826. goto again;
  2827. }
  2828. }
  2829. if (ret) {
  2830. ASSERT(ret == 1);
  2831. btrfs_print_leaf(path->nodes[0]);
  2832. btrfs_err(fs_info,
  2833. "tree block extent item (%llu) is not found in extent tree",
  2834. bytenr);
  2835. WARN_ON(1);
  2836. return -EINVAL;
  2837. }
  2838. return add_tree_block(rc, &key, path, blocks);
  2839. }
  2840. static int delete_block_group_cache(struct btrfs_block_group *block_group,
  2841. struct inode *inode,
  2842. u64 ino)
  2843. {
  2844. struct btrfs_fs_info *fs_info = block_group->fs_info;
  2845. struct btrfs_root *root = fs_info->tree_root;
  2846. struct btrfs_trans_handle *trans;
  2847. struct btrfs_inode *btrfs_inode;
  2848. int ret = 0;
  2849. if (inode)
  2850. goto truncate;
  2851. btrfs_inode = btrfs_iget(ino, root);
  2852. if (IS_ERR(btrfs_inode))
  2853. return -ENOENT;
  2854. inode = &btrfs_inode->vfs_inode;
  2855. truncate:
  2856. ret = btrfs_check_trunc_cache_free_space(fs_info,
  2857. &fs_info->global_block_rsv);
  2858. if (ret)
  2859. goto out;
  2860. trans = btrfs_join_transaction(root);
  2861. if (IS_ERR(trans)) {
  2862. ret = PTR_ERR(trans);
  2863. goto out;
  2864. }
  2865. ret = btrfs_truncate_free_space_cache(trans, block_group, inode);
  2866. btrfs_end_transaction(trans);
  2867. btrfs_btree_balance_dirty(fs_info);
  2868. out:
  2869. iput(inode);
  2870. return ret;
  2871. }
  2872. /*
  2873. * Locate the free space cache EXTENT_DATA in root tree leaf and delete the
  2874. * cache inode, to avoid free space cache data extent blocking data relocation.
  2875. */
  2876. static int delete_v1_space_cache(struct extent_buffer *leaf,
  2877. struct btrfs_block_group *block_group,
  2878. u64 data_bytenr)
  2879. {
  2880. u64 space_cache_ino;
  2881. struct btrfs_file_extent_item *ei;
  2882. struct btrfs_key key;
  2883. bool found = false;
  2884. int i;
  2885. if (btrfs_header_owner(leaf) != BTRFS_ROOT_TREE_OBJECTID)
  2886. return 0;
  2887. for (i = 0; i < btrfs_header_nritems(leaf); i++) {
  2888. u8 type;
  2889. btrfs_item_key_to_cpu(leaf, &key, i);
  2890. if (key.type != BTRFS_EXTENT_DATA_KEY)
  2891. continue;
  2892. ei = btrfs_item_ptr(leaf, i, struct btrfs_file_extent_item);
  2893. type = btrfs_file_extent_type(leaf, ei);
  2894. if ((type == BTRFS_FILE_EXTENT_REG ||
  2895. type == BTRFS_FILE_EXTENT_PREALLOC) &&
  2896. btrfs_file_extent_disk_bytenr(leaf, ei) == data_bytenr) {
  2897. found = true;
  2898. space_cache_ino = key.objectid;
  2899. break;
  2900. }
  2901. }
  2902. if (!found)
  2903. return -ENOENT;
  2904. return delete_block_group_cache(block_group, NULL, space_cache_ino);
  2905. }
  2906. /*
  2907. * helper to find all tree blocks that reference a given data extent
  2908. */
  2909. static noinline_for_stack int add_data_references(struct reloc_control *rc,
  2910. const struct btrfs_key *extent_key,
  2911. struct btrfs_path *path,
  2912. struct rb_root *blocks)
  2913. {
  2914. struct btrfs_backref_walk_ctx ctx = { 0 };
  2915. struct ulist_iterator leaf_uiter;
  2916. struct ulist_node *ref_node = NULL;
  2917. const u32 blocksize = rc->extent_root->fs_info->nodesize;
  2918. int ret = 0;
  2919. btrfs_release_path(path);
  2920. ctx.bytenr = extent_key->objectid;
  2921. ctx.skip_inode_ref_list = true;
  2922. ctx.fs_info = rc->extent_root->fs_info;
  2923. ret = btrfs_find_all_leafs(&ctx);
  2924. if (ret < 0)
  2925. return ret;
  2926. ULIST_ITER_INIT(&leaf_uiter);
  2927. while ((ref_node = ulist_next(ctx.refs, &leaf_uiter))) {
  2928. struct btrfs_tree_parent_check check = { 0 };
  2929. struct extent_buffer *eb;
  2930. eb = read_tree_block(ctx.fs_info, ref_node->val, &check);
  2931. if (IS_ERR(eb)) {
  2932. ret = PTR_ERR(eb);
  2933. break;
  2934. }
  2935. ret = delete_v1_space_cache(eb, rc->block_group,
  2936. extent_key->objectid);
  2937. free_extent_buffer(eb);
  2938. if (ret < 0)
  2939. break;
  2940. ret = __add_tree_block(rc, ref_node->val, blocksize, blocks);
  2941. if (ret < 0)
  2942. break;
  2943. }
  2944. if (ret < 0)
  2945. free_block_list(blocks);
  2946. ulist_free(ctx.refs);
  2947. return ret;
  2948. }
  2949. /*
  2950. * helper to find next unprocessed extent
  2951. */
  2952. static noinline_for_stack
  2953. int find_next_extent(struct reloc_control *rc, struct btrfs_path *path,
  2954. struct btrfs_key *extent_key)
  2955. {
  2956. struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
  2957. struct btrfs_key key;
  2958. struct extent_buffer *leaf;
  2959. u64 start, end, last;
  2960. int ret;
  2961. last = rc->block_group->start + rc->block_group->length;
  2962. while (1) {
  2963. bool block_found;
  2964. cond_resched();
  2965. if (rc->search_start >= last) {
  2966. ret = 1;
  2967. break;
  2968. }
  2969. key.objectid = rc->search_start;
  2970. key.type = BTRFS_EXTENT_ITEM_KEY;
  2971. key.offset = 0;
  2972. path->search_commit_root = true;
  2973. path->skip_locking = true;
  2974. ret = btrfs_search_slot(NULL, rc->extent_root, &key, path,
  2975. 0, 0);
  2976. if (ret < 0)
  2977. break;
  2978. next:
  2979. leaf = path->nodes[0];
  2980. if (path->slots[0] >= btrfs_header_nritems(leaf)) {
  2981. ret = btrfs_next_leaf(rc->extent_root, path);
  2982. if (ret != 0)
  2983. break;
  2984. leaf = path->nodes[0];
  2985. }
  2986. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  2987. if (key.objectid >= last) {
  2988. ret = 1;
  2989. break;
  2990. }
  2991. if (key.type != BTRFS_EXTENT_ITEM_KEY &&
  2992. key.type != BTRFS_METADATA_ITEM_KEY) {
  2993. path->slots[0]++;
  2994. goto next;
  2995. }
  2996. if (key.type == BTRFS_EXTENT_ITEM_KEY &&
  2997. key.objectid + key.offset <= rc->search_start) {
  2998. path->slots[0]++;
  2999. goto next;
  3000. }
  3001. if (key.type == BTRFS_METADATA_ITEM_KEY &&
  3002. key.objectid + fs_info->nodesize <=
  3003. rc->search_start) {
  3004. path->slots[0]++;
  3005. goto next;
  3006. }
  3007. block_found = btrfs_find_first_extent_bit(&rc->processed_blocks,
  3008. key.objectid, &start, &end,
  3009. EXTENT_DIRTY, NULL);
  3010. if (block_found && start <= key.objectid) {
  3011. btrfs_release_path(path);
  3012. rc->search_start = end + 1;
  3013. } else {
  3014. if (key.type == BTRFS_EXTENT_ITEM_KEY)
  3015. rc->search_start = key.objectid + key.offset;
  3016. else
  3017. rc->search_start = key.objectid +
  3018. fs_info->nodesize;
  3019. memcpy(extent_key, &key, sizeof(key));
  3020. return 0;
  3021. }
  3022. }
  3023. btrfs_release_path(path);
  3024. return ret;
  3025. }
  3026. static void set_reloc_control(struct reloc_control *rc)
  3027. {
  3028. struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
  3029. mutex_lock(&fs_info->reloc_mutex);
  3030. fs_info->reloc_ctl = rc;
  3031. mutex_unlock(&fs_info->reloc_mutex);
  3032. }
  3033. static void unset_reloc_control(struct reloc_control *rc)
  3034. {
  3035. struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
  3036. mutex_lock(&fs_info->reloc_mutex);
  3037. fs_info->reloc_ctl = NULL;
  3038. mutex_unlock(&fs_info->reloc_mutex);
  3039. }
  3040. static noinline_for_stack
  3041. int prepare_to_relocate(struct reloc_control *rc)
  3042. {
  3043. struct btrfs_trans_handle *trans;
  3044. int ret;
  3045. rc->block_rsv = btrfs_alloc_block_rsv(rc->extent_root->fs_info,
  3046. BTRFS_BLOCK_RSV_TEMP);
  3047. if (!rc->block_rsv)
  3048. return -ENOMEM;
  3049. memset(&rc->cluster, 0, sizeof(rc->cluster));
  3050. rc->search_start = rc->block_group->start;
  3051. rc->extents_found = 0;
  3052. rc->nodes_relocated = 0;
  3053. rc->merging_rsv_size = 0;
  3054. rc->reserved_bytes = 0;
  3055. rc->block_rsv->size = rc->extent_root->fs_info->nodesize *
  3056. RELOCATION_RESERVED_NODES;
  3057. ret = btrfs_block_rsv_refill(rc->extent_root->fs_info,
  3058. rc->block_rsv, rc->block_rsv->size,
  3059. BTRFS_RESERVE_FLUSH_ALL);
  3060. if (ret)
  3061. return ret;
  3062. rc->create_reloc_tree = true;
  3063. set_reloc_control(rc);
  3064. trans = btrfs_join_transaction(rc->extent_root);
  3065. if (IS_ERR(trans)) {
  3066. unset_reloc_control(rc);
  3067. /*
  3068. * extent tree is not a ref_cow tree and has no reloc_root to
  3069. * cleanup. And callers are responsible to free the above
  3070. * block rsv.
  3071. */
  3072. return PTR_ERR(trans);
  3073. }
  3074. ret = btrfs_commit_transaction(trans);
  3075. if (ret)
  3076. unset_reloc_control(rc);
  3077. return ret;
  3078. }
  3079. static noinline_for_stack int relocate_block_group(struct reloc_control *rc)
  3080. {
  3081. struct btrfs_fs_info *fs_info = rc->extent_root->fs_info;
  3082. struct rb_root blocks = RB_ROOT;
  3083. struct btrfs_key key;
  3084. struct btrfs_trans_handle *trans = NULL;
  3085. BTRFS_PATH_AUTO_FREE(path);
  3086. struct btrfs_extent_item *ei;
  3087. u64 flags;
  3088. int ret;
  3089. int err = 0;
  3090. int progress = 0;
  3091. path = btrfs_alloc_path();
  3092. if (!path)
  3093. return -ENOMEM;
  3094. path->reada = READA_FORWARD;
  3095. ret = prepare_to_relocate(rc);
  3096. if (ret) {
  3097. err = ret;
  3098. goto out_free;
  3099. }
  3100. while (1) {
  3101. rc->reserved_bytes = 0;
  3102. ret = btrfs_block_rsv_refill(fs_info, rc->block_rsv,
  3103. rc->block_rsv->size,
  3104. BTRFS_RESERVE_FLUSH_ALL);
  3105. if (ret) {
  3106. err = ret;
  3107. break;
  3108. }
  3109. progress++;
  3110. trans = btrfs_start_transaction(rc->extent_root, 0);
  3111. if (IS_ERR(trans)) {
  3112. err = PTR_ERR(trans);
  3113. trans = NULL;
  3114. break;
  3115. }
  3116. restart:
  3117. if (rc->backref_cache.last_trans != trans->transid)
  3118. btrfs_backref_release_cache(&rc->backref_cache);
  3119. rc->backref_cache.last_trans = trans->transid;
  3120. ret = find_next_extent(rc, path, &key);
  3121. if (ret < 0)
  3122. err = ret;
  3123. if (ret != 0)
  3124. break;
  3125. rc->extents_found++;
  3126. ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
  3127. struct btrfs_extent_item);
  3128. flags = btrfs_extent_flags(path->nodes[0], ei);
  3129. /*
  3130. * If we are relocating a simple quota owned extent item, we
  3131. * need to note the owner on the reloc data root so that when
  3132. * we allocate the replacement item, we can attribute it to the
  3133. * correct eventual owner (rather than the reloc data root).
  3134. */
  3135. if (btrfs_qgroup_mode(fs_info) == BTRFS_QGROUP_MODE_SIMPLE) {
  3136. struct btrfs_root *root = BTRFS_I(rc->data_inode)->root;
  3137. u64 owning_root_id = btrfs_get_extent_owner_root(fs_info,
  3138. path->nodes[0],
  3139. path->slots[0]);
  3140. root->relocation_src_root = owning_root_id;
  3141. }
  3142. if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
  3143. ret = add_tree_block(rc, &key, path, &blocks);
  3144. } else if (rc->stage == UPDATE_DATA_PTRS &&
  3145. (flags & BTRFS_EXTENT_FLAG_DATA)) {
  3146. ret = add_data_references(rc, &key, path, &blocks);
  3147. } else {
  3148. btrfs_release_path(path);
  3149. ret = 0;
  3150. }
  3151. if (ret < 0) {
  3152. err = ret;
  3153. break;
  3154. }
  3155. if (!RB_EMPTY_ROOT(&blocks)) {
  3156. ret = relocate_tree_blocks(trans, rc, &blocks);
  3157. if (ret < 0) {
  3158. if (ret != -EAGAIN) {
  3159. err = ret;
  3160. break;
  3161. }
  3162. rc->extents_found--;
  3163. rc->search_start = key.objectid;
  3164. }
  3165. }
  3166. btrfs_end_transaction_throttle(trans);
  3167. btrfs_btree_balance_dirty(fs_info);
  3168. trans = NULL;
  3169. if (rc->stage == MOVE_DATA_EXTENTS &&
  3170. (flags & BTRFS_EXTENT_FLAG_DATA)) {
  3171. rc->found_file_extent = true;
  3172. ret = relocate_data_extent(rc, &key);
  3173. if (ret < 0) {
  3174. err = ret;
  3175. break;
  3176. }
  3177. }
  3178. if (btrfs_should_cancel_balance(fs_info)) {
  3179. err = -ECANCELED;
  3180. break;
  3181. }
  3182. }
  3183. if (trans && progress && err == -ENOSPC) {
  3184. ret = btrfs_force_chunk_alloc(trans, rc->block_group->flags);
  3185. if (ret == 1) {
  3186. err = 0;
  3187. progress = 0;
  3188. goto restart;
  3189. }
  3190. }
  3191. btrfs_release_path(path);
  3192. btrfs_clear_extent_bit(&rc->processed_blocks, 0, (u64)-1, EXTENT_DIRTY, NULL);
  3193. if (trans) {
  3194. btrfs_end_transaction_throttle(trans);
  3195. btrfs_btree_balance_dirty(fs_info);
  3196. }
  3197. if (!err && !btrfs_fs_incompat(fs_info, REMAP_TREE)) {
  3198. ret = relocate_file_extent_cluster(rc);
  3199. if (ret < 0)
  3200. err = ret;
  3201. }
  3202. rc->create_reloc_tree = false;
  3203. set_reloc_control(rc);
  3204. btrfs_backref_release_cache(&rc->backref_cache);
  3205. btrfs_block_rsv_release(fs_info, rc->block_rsv, (u64)-1, NULL);
  3206. /*
  3207. * Even in the case when the relocation is cancelled, we should all go
  3208. * through prepare_to_merge() and merge_reloc_roots().
  3209. *
  3210. * For error (including cancelled balance), prepare_to_merge() will
  3211. * mark all reloc trees orphan, then queue them for cleanup in
  3212. * merge_reloc_roots()
  3213. */
  3214. err = prepare_to_merge(rc, err);
  3215. merge_reloc_roots(rc);
  3216. rc->merge_reloc_tree = false;
  3217. unset_reloc_control(rc);
  3218. btrfs_block_rsv_release(fs_info, rc->block_rsv, (u64)-1, NULL);
  3219. /* get rid of pinned extents */
  3220. trans = btrfs_join_transaction(rc->extent_root);
  3221. if (IS_ERR(trans)) {
  3222. err = PTR_ERR(trans);
  3223. goto out_free;
  3224. }
  3225. ret = btrfs_commit_transaction(trans);
  3226. if (ret && !err)
  3227. err = ret;
  3228. out_free:
  3229. ret = clean_dirty_subvols(rc);
  3230. if (ret < 0 && !err)
  3231. err = ret;
  3232. btrfs_free_block_rsv(fs_info, rc->block_rsv);
  3233. return err;
  3234. }
  3235. static int __insert_orphan_inode(struct btrfs_trans_handle *trans,
  3236. struct btrfs_root *root, u64 objectid)
  3237. {
  3238. BTRFS_PATH_AUTO_FREE(path);
  3239. struct btrfs_inode_item *item;
  3240. struct extent_buffer *leaf;
  3241. int ret;
  3242. path = btrfs_alloc_path();
  3243. if (!path)
  3244. return -ENOMEM;
  3245. ret = btrfs_insert_empty_inode(trans, root, path, objectid);
  3246. if (ret)
  3247. return ret;
  3248. leaf = path->nodes[0];
  3249. item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_inode_item);
  3250. memzero_extent_buffer(leaf, (unsigned long)item, sizeof(*item));
  3251. btrfs_set_inode_generation(leaf, item, 1);
  3252. btrfs_set_inode_size(leaf, item, 0);
  3253. btrfs_set_inode_mode(leaf, item, S_IFREG | 0600);
  3254. btrfs_set_inode_flags(leaf, item, BTRFS_INODE_NOCOMPRESS |
  3255. BTRFS_INODE_PREALLOC);
  3256. return 0;
  3257. }
  3258. static void delete_orphan_inode(struct btrfs_trans_handle *trans,
  3259. struct btrfs_root *root, u64 objectid)
  3260. {
  3261. BTRFS_PATH_AUTO_FREE(path);
  3262. struct btrfs_key key;
  3263. int ret = 0;
  3264. path = btrfs_alloc_path();
  3265. if (!path) {
  3266. ret = -ENOMEM;
  3267. goto out;
  3268. }
  3269. key.objectid = objectid;
  3270. key.type = BTRFS_INODE_ITEM_KEY;
  3271. key.offset = 0;
  3272. ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
  3273. if (ret) {
  3274. if (ret > 0)
  3275. ret = -ENOENT;
  3276. goto out;
  3277. }
  3278. ret = btrfs_del_item(trans, root, path);
  3279. out:
  3280. if (ret)
  3281. btrfs_abort_transaction(trans, ret);
  3282. }
  3283. /*
  3284. * helper to create inode for data relocation.
  3285. * the inode is in data relocation tree and its link count is 0
  3286. */
  3287. static noinline_for_stack struct inode *create_reloc_inode(
  3288. const struct btrfs_block_group *group)
  3289. {
  3290. struct btrfs_fs_info *fs_info = group->fs_info;
  3291. struct btrfs_inode *inode = NULL;
  3292. struct btrfs_trans_handle *trans;
  3293. struct btrfs_root *root;
  3294. u64 objectid;
  3295. int ret = 0;
  3296. root = btrfs_grab_root(fs_info->data_reloc_root);
  3297. trans = btrfs_start_transaction(root, 6);
  3298. if (IS_ERR(trans)) {
  3299. btrfs_put_root(root);
  3300. return ERR_CAST(trans);
  3301. }
  3302. ret = btrfs_get_free_objectid(root, &objectid);
  3303. if (ret)
  3304. goto out;
  3305. ret = __insert_orphan_inode(trans, root, objectid);
  3306. if (ret)
  3307. goto out;
  3308. inode = btrfs_iget(objectid, root);
  3309. if (IS_ERR(inode)) {
  3310. delete_orphan_inode(trans, root, objectid);
  3311. ret = PTR_ERR(inode);
  3312. inode = NULL;
  3313. goto out;
  3314. }
  3315. inode->reloc_block_group_start = group->start;
  3316. ret = btrfs_orphan_add(trans, inode);
  3317. out:
  3318. btrfs_put_root(root);
  3319. btrfs_end_transaction(trans);
  3320. btrfs_btree_balance_dirty(fs_info);
  3321. if (ret) {
  3322. if (inode)
  3323. iput(&inode->vfs_inode);
  3324. return ERR_PTR(ret);
  3325. }
  3326. return &inode->vfs_inode;
  3327. }
  3328. /*
  3329. * Mark start of chunk relocation that is cancellable. Check if the cancellation
  3330. * has been requested meanwhile and don't start in that case.
  3331. * NOTE: if this returns an error, reloc_chunk_end() must not be called.
  3332. *
  3333. * Return:
  3334. * 0 success
  3335. * -EINPROGRESS operation is already in progress, that's probably a bug
  3336. * -ECANCELED cancellation request was set before the operation started
  3337. */
  3338. static int reloc_chunk_start(struct btrfs_fs_info *fs_info)
  3339. {
  3340. if (test_and_set_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags)) {
  3341. /* This should not happen */
  3342. btrfs_err(fs_info, "reloc already running, cannot start");
  3343. return -EINPROGRESS;
  3344. }
  3345. if (atomic_read(&fs_info->reloc_cancel_req) > 0) {
  3346. btrfs_info(fs_info, "chunk relocation canceled on start");
  3347. /* On cancel, clear all requests. */
  3348. clear_and_wake_up_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags);
  3349. atomic_set(&fs_info->reloc_cancel_req, 0);
  3350. return -ECANCELED;
  3351. }
  3352. return 0;
  3353. }
  3354. /*
  3355. * Mark end of chunk relocation that is cancellable and wake any waiters.
  3356. * NOTE: call only if a previous call to reloc_chunk_start() succeeded.
  3357. */
  3358. static void reloc_chunk_end(struct btrfs_fs_info *fs_info)
  3359. {
  3360. ASSERT(test_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags));
  3361. /* Requested after start, clear bit first so any waiters can continue */
  3362. if (atomic_read(&fs_info->reloc_cancel_req) > 0)
  3363. btrfs_info(fs_info, "chunk relocation canceled during operation");
  3364. clear_and_wake_up_bit(BTRFS_FS_RELOC_RUNNING, &fs_info->flags);
  3365. atomic_set(&fs_info->reloc_cancel_req, 0);
  3366. }
  3367. static struct reloc_control *alloc_reloc_control(struct btrfs_fs_info *fs_info)
  3368. {
  3369. struct reloc_control *rc;
  3370. rc = kzalloc_obj(*rc, GFP_NOFS);
  3371. if (!rc)
  3372. return NULL;
  3373. INIT_LIST_HEAD(&rc->reloc_roots);
  3374. INIT_LIST_HEAD(&rc->dirty_subvol_roots);
  3375. btrfs_backref_init_cache(fs_info, &rc->backref_cache, true);
  3376. rc->reloc_root_tree.rb_root = RB_ROOT;
  3377. spin_lock_init(&rc->reloc_root_tree.lock);
  3378. btrfs_extent_io_tree_init(fs_info, &rc->processed_blocks, IO_TREE_RELOC_BLOCKS);
  3379. return rc;
  3380. }
  3381. static void free_reloc_control(struct reloc_control *rc)
  3382. {
  3383. struct mapping_node *node, *tmp;
  3384. free_reloc_roots(&rc->reloc_roots);
  3385. rbtree_postorder_for_each_entry_safe(node, tmp,
  3386. &rc->reloc_root_tree.rb_root, rb_node)
  3387. kfree(node);
  3388. kfree(rc);
  3389. }
  3390. /*
  3391. * Print the block group being relocated
  3392. */
  3393. static void describe_relocation(struct btrfs_block_group *block_group)
  3394. {
  3395. char buf[128] = "NONE";
  3396. btrfs_describe_block_groups(block_group->flags, buf, sizeof(buf));
  3397. btrfs_info(block_group->fs_info, "relocating block group %llu flags %s",
  3398. block_group->start, buf);
  3399. }
  3400. static const char *stage_to_string(enum reloc_stage stage)
  3401. {
  3402. if (stage == MOVE_DATA_EXTENTS)
  3403. return "move data extents";
  3404. if (stage == UPDATE_DATA_PTRS)
  3405. return "update data pointers";
  3406. return "unknown";
  3407. }
  3408. static int add_remap_tree_entries(struct btrfs_trans_handle *trans, struct btrfs_path *path,
  3409. struct btrfs_key *entries, unsigned int num_entries)
  3410. {
  3411. int ret;
  3412. struct btrfs_fs_info *fs_info = trans->fs_info;
  3413. struct btrfs_item_batch batch;
  3414. u32 *data_sizes;
  3415. u32 max_items;
  3416. max_items = BTRFS_LEAF_DATA_SIZE(trans->fs_info) / sizeof(struct btrfs_item);
  3417. data_sizes = kzalloc(sizeof(u32) * min_t(u32, num_entries, max_items), GFP_NOFS);
  3418. if (!data_sizes)
  3419. return -ENOMEM;
  3420. while (true) {
  3421. batch.keys = entries;
  3422. batch.data_sizes = data_sizes;
  3423. batch.total_data_size = 0;
  3424. batch.nr = min_t(u32, num_entries, max_items);
  3425. ret = btrfs_insert_empty_items(trans, fs_info->remap_root, path, &batch);
  3426. btrfs_release_path(path);
  3427. if (num_entries <= max_items)
  3428. break;
  3429. num_entries -= max_items;
  3430. entries += max_items;
  3431. }
  3432. kfree(data_sizes);
  3433. return ret;
  3434. }
  3435. struct space_run {
  3436. u64 start;
  3437. u64 end;
  3438. };
  3439. static void parse_bitmap(u64 block_size, const unsigned long *bitmap,
  3440. unsigned long size, u64 address, struct space_run *space_runs,
  3441. unsigned int *num_space_runs)
  3442. {
  3443. unsigned long pos, end;
  3444. u64 run_start, run_length;
  3445. pos = find_first_bit(bitmap, size);
  3446. if (pos == size)
  3447. return;
  3448. while (true) {
  3449. end = find_next_zero_bit(bitmap, size, pos);
  3450. run_start = address + (pos * block_size);
  3451. run_length = (end - pos) * block_size;
  3452. if (*num_space_runs != 0 &&
  3453. space_runs[*num_space_runs - 1].end == run_start) {
  3454. space_runs[*num_space_runs - 1].end += run_length;
  3455. } else {
  3456. space_runs[*num_space_runs].start = run_start;
  3457. space_runs[*num_space_runs].end = run_start + run_length;
  3458. (*num_space_runs)++;
  3459. }
  3460. if (end == size)
  3461. break;
  3462. pos = find_next_bit(bitmap, size, end + 1);
  3463. if (pos == size)
  3464. break;
  3465. }
  3466. }
  3467. static void adjust_block_group_remap_bytes(struct btrfs_trans_handle *trans,
  3468. struct btrfs_block_group *bg, s64 diff)
  3469. {
  3470. struct btrfs_fs_info *fs_info = trans->fs_info;
  3471. bool bg_already_dirty = true;
  3472. bool mark_unused = false;
  3473. spin_lock(&bg->lock);
  3474. bg->remap_bytes += diff;
  3475. if (bg->used == 0 && bg->remap_bytes == 0)
  3476. mark_unused = true;
  3477. spin_unlock(&bg->lock);
  3478. if (mark_unused)
  3479. btrfs_mark_bg_unused(bg);
  3480. spin_lock(&trans->transaction->dirty_bgs_lock);
  3481. if (list_empty(&bg->dirty_list)) {
  3482. list_add_tail(&bg->dirty_list, &trans->transaction->dirty_bgs);
  3483. bg_already_dirty = false;
  3484. btrfs_get_block_group(bg);
  3485. }
  3486. spin_unlock(&trans->transaction->dirty_bgs_lock);
  3487. /* Modified block groups are accounted for in the delayed_refs_rsv. */
  3488. if (!bg_already_dirty)
  3489. btrfs_inc_delayed_refs_rsv_bg_updates(fs_info);
  3490. }
  3491. /* Private structure for I/O from copy_remapped_data(). */
  3492. struct reloc_io_private {
  3493. struct completion done;
  3494. refcount_t pending_refs;
  3495. blk_status_t status;
  3496. };
  3497. static void reloc_endio(struct btrfs_bio *bbio)
  3498. {
  3499. struct reloc_io_private *priv = bbio->private;
  3500. if (bbio->bio.bi_status)
  3501. WRITE_ONCE(priv->status, bbio->bio.bi_status);
  3502. if (refcount_dec_and_test(&priv->pending_refs))
  3503. complete(&priv->done);
  3504. bio_put(&bbio->bio);
  3505. }
  3506. static int copy_remapped_data_io(struct btrfs_fs_info *fs_info,
  3507. struct reloc_io_private *priv,
  3508. struct page **pages, u64 addr, u64 length,
  3509. blk_opf_t op)
  3510. {
  3511. struct btrfs_bio *bbio;
  3512. int i;
  3513. init_completion(&priv->done);
  3514. refcount_set(&priv->pending_refs, 1);
  3515. priv->status = 0;
  3516. bbio = btrfs_bio_alloc(BIO_MAX_VECS, op, BTRFS_I(fs_info->btree_inode),
  3517. addr, reloc_endio, priv);
  3518. bbio->bio.bi_iter.bi_sector = (addr >> SECTOR_SHIFT);
  3519. bbio->is_remap = true;
  3520. i = 0;
  3521. do {
  3522. size_t bytes = min_t(u64, length, PAGE_SIZE);
  3523. if (bio_add_page(&bbio->bio, pages[i], bytes, 0) < bytes) {
  3524. refcount_inc(&priv->pending_refs);
  3525. btrfs_submit_bbio(bbio, 0);
  3526. bbio = btrfs_bio_alloc(BIO_MAX_VECS, op,
  3527. BTRFS_I(fs_info->btree_inode),
  3528. addr, reloc_endio, priv);
  3529. bbio->bio.bi_iter.bi_sector = (addr >> SECTOR_SHIFT);
  3530. bbio->is_remap = true;
  3531. continue;
  3532. }
  3533. i++;
  3534. addr += bytes;
  3535. length -= bytes;
  3536. } while (length);
  3537. refcount_inc(&priv->pending_refs);
  3538. btrfs_submit_bbio(bbio, 0);
  3539. if (!refcount_dec_and_test(&priv->pending_refs))
  3540. wait_for_completion_io(&priv->done);
  3541. return blk_status_to_errno(READ_ONCE(priv->status));
  3542. }
  3543. static int copy_remapped_data(struct btrfs_fs_info *fs_info, u64 old_addr,
  3544. u64 new_addr, u64 length)
  3545. {
  3546. int ret;
  3547. u64 copy_len = min_t(u64, length, SZ_1M);
  3548. struct page **pages;
  3549. struct reloc_io_private priv;
  3550. unsigned int nr_pages = DIV_ROUND_UP(length, PAGE_SIZE);
  3551. pages = kzalloc_objs(struct page *, nr_pages, GFP_NOFS);
  3552. if (!pages)
  3553. return -ENOMEM;
  3554. ret = btrfs_alloc_page_array(nr_pages, pages, 0);
  3555. if (ret) {
  3556. ret = -ENOMEM;
  3557. goto end;
  3558. }
  3559. /* Copy 1MB at a time, to avoid using too much memory. */
  3560. do {
  3561. u64 to_copy = min_t(u64, length, copy_len);
  3562. /* Limit to one bio. */
  3563. to_copy = min_t(u64, to_copy, BIO_MAX_VECS << PAGE_SHIFT);
  3564. ret = copy_remapped_data_io(fs_info, &priv, pages, old_addr,
  3565. to_copy, REQ_OP_READ);
  3566. if (ret)
  3567. goto end;
  3568. ret = copy_remapped_data_io(fs_info, &priv, pages, new_addr,
  3569. to_copy, REQ_OP_WRITE);
  3570. if (ret)
  3571. goto end;
  3572. if (to_copy == length)
  3573. break;
  3574. old_addr += to_copy;
  3575. new_addr += to_copy;
  3576. length -= to_copy;
  3577. } while (true);
  3578. ret = 0;
  3579. end:
  3580. for (int i = 0; i < nr_pages; i++) {
  3581. if (pages[i])
  3582. __free_page(pages[i]);
  3583. }
  3584. kfree(pages);
  3585. return ret;
  3586. }
  3587. static int add_remap_item(struct btrfs_trans_handle *trans,
  3588. struct btrfs_path *path, u64 new_addr, u64 length,
  3589. u64 old_addr)
  3590. {
  3591. struct btrfs_fs_info *fs_info = trans->fs_info;
  3592. struct btrfs_remap_item remap = { 0 };
  3593. struct btrfs_key key;
  3594. struct extent_buffer *leaf;
  3595. int ret;
  3596. key.objectid = old_addr;
  3597. key.type = BTRFS_REMAP_KEY;
  3598. key.offset = length;
  3599. ret = btrfs_insert_empty_item(trans, fs_info->remap_root, path,
  3600. &key, sizeof(struct btrfs_remap_item));
  3601. if (ret)
  3602. return ret;
  3603. leaf = path->nodes[0];
  3604. btrfs_set_stack_remap_address(&remap, new_addr);
  3605. write_extent_buffer(leaf, &remap, btrfs_item_ptr_offset(leaf, path->slots[0]),
  3606. sizeof(struct btrfs_remap_item));
  3607. btrfs_release_path(path);
  3608. return 0;
  3609. }
  3610. static int add_remap_backref_item(struct btrfs_trans_handle *trans,
  3611. struct btrfs_path *path, u64 new_addr,
  3612. u64 length, u64 old_addr)
  3613. {
  3614. struct btrfs_fs_info *fs_info = trans->fs_info;
  3615. struct btrfs_remap_item remap = { 0 };
  3616. struct btrfs_key key;
  3617. struct extent_buffer *leaf;
  3618. int ret;
  3619. key.objectid = new_addr;
  3620. key.type = BTRFS_REMAP_BACKREF_KEY;
  3621. key.offset = length;
  3622. ret = btrfs_insert_empty_item(trans, fs_info->remap_root, path, &key,
  3623. sizeof(struct btrfs_remap_item));
  3624. if (ret)
  3625. return ret;
  3626. leaf = path->nodes[0];
  3627. btrfs_set_stack_remap_address(&remap, old_addr);
  3628. write_extent_buffer(leaf, &remap, btrfs_item_ptr_offset(leaf, path->slots[0]),
  3629. sizeof(struct btrfs_remap_item));
  3630. btrfs_release_path(path);
  3631. return 0;
  3632. }
  3633. static int move_existing_remap(struct btrfs_fs_info *fs_info,
  3634. struct btrfs_path *path,
  3635. struct btrfs_block_group *bg, u64 new_addr,
  3636. u64 length, u64 old_addr)
  3637. {
  3638. struct btrfs_trans_handle *trans;
  3639. struct extent_buffer *leaf;
  3640. struct btrfs_remap_item *remap_ptr;
  3641. struct btrfs_remap_item remap = { 0 };
  3642. struct btrfs_key key, ins;
  3643. u64 dest_addr, dest_length, min_size;
  3644. struct btrfs_block_group *dest_bg;
  3645. int ret;
  3646. const bool is_data = (bg->flags & BTRFS_BLOCK_GROUP_DATA);
  3647. struct btrfs_space_info *sinfo = bg->space_info;
  3648. bool mutex_taken = false;
  3649. bool bg_needs_free_space;
  3650. spin_lock(&sinfo->lock);
  3651. btrfs_space_info_update_bytes_may_use(sinfo, length);
  3652. spin_unlock(&sinfo->lock);
  3653. if (is_data)
  3654. min_size = fs_info->sectorsize;
  3655. else
  3656. min_size = fs_info->nodesize;
  3657. ret = btrfs_reserve_extent(fs_info->fs_root, length, length, min_size,
  3658. 0, 0, &ins, is_data, false);
  3659. if (unlikely(ret)) {
  3660. spin_lock(&sinfo->lock);
  3661. btrfs_space_info_update_bytes_may_use(sinfo, -length);
  3662. spin_unlock(&sinfo->lock);
  3663. return ret;
  3664. }
  3665. dest_addr = ins.objectid;
  3666. dest_length = ins.offset;
  3667. dest_bg = btrfs_lookup_block_group(fs_info, dest_addr);
  3668. if (!is_data && !IS_ALIGNED(dest_length, fs_info->nodesize)) {
  3669. u64 new_length = ALIGN_DOWN(dest_length, fs_info->nodesize);
  3670. btrfs_free_reserved_extent(fs_info, dest_addr + new_length,
  3671. dest_length - new_length, 0);
  3672. dest_length = new_length;
  3673. }
  3674. trans = btrfs_join_transaction(fs_info->remap_root);
  3675. if (IS_ERR(trans)) {
  3676. ret = PTR_ERR(trans);
  3677. trans = NULL;
  3678. goto end;
  3679. }
  3680. mutex_lock(&fs_info->remap_mutex);
  3681. mutex_taken = true;
  3682. /* Find old remap entry. */
  3683. key.objectid = old_addr;
  3684. key.type = BTRFS_REMAP_KEY;
  3685. key.offset = length;
  3686. ret = btrfs_search_slot(trans, fs_info->remap_root, &key, path, 0, 1);
  3687. if (ret == 1) {
  3688. /*
  3689. * Not a problem if the remap entry wasn't found: that means
  3690. * that another transaction has deallocated the data.
  3691. * move_existing_remaps() loops until the BG contains no
  3692. * remaps, so we can just return 0 in this case.
  3693. */
  3694. btrfs_release_path(path);
  3695. ret = 0;
  3696. goto end;
  3697. } else if (unlikely(ret)) {
  3698. goto end;
  3699. }
  3700. ret = copy_remapped_data(fs_info, new_addr, dest_addr, dest_length);
  3701. if (unlikely(ret))
  3702. goto end;
  3703. /* Change data of old remap entry. */
  3704. leaf = path->nodes[0];
  3705. remap_ptr = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_remap_item);
  3706. btrfs_set_remap_address(leaf, remap_ptr, dest_addr);
  3707. btrfs_mark_buffer_dirty(trans, leaf);
  3708. if (dest_length != length) {
  3709. key.offset = dest_length;
  3710. btrfs_set_item_key_safe(trans, path, &key);
  3711. }
  3712. btrfs_release_path(path);
  3713. if (dest_length != length) {
  3714. /* Add remap item for remainder. */
  3715. ret = add_remap_item(trans, path, new_addr + dest_length,
  3716. length - dest_length, old_addr + dest_length);
  3717. if (unlikely(ret))
  3718. goto end;
  3719. }
  3720. /* Change or remove old backref. */
  3721. key.objectid = new_addr;
  3722. key.type = BTRFS_REMAP_BACKREF_KEY;
  3723. key.offset = length;
  3724. ret = btrfs_search_slot(trans, fs_info->remap_root, &key, path, -1, 1);
  3725. if (unlikely(ret)) {
  3726. if (ret == 1) {
  3727. btrfs_release_path(path);
  3728. ret = -ENOENT;
  3729. }
  3730. goto end;
  3731. }
  3732. leaf = path->nodes[0];
  3733. if (dest_length == length) {
  3734. ret = btrfs_del_item(trans, fs_info->remap_root, path);
  3735. if (unlikely(ret)) {
  3736. btrfs_release_path(path);
  3737. goto end;
  3738. }
  3739. } else {
  3740. key.objectid += dest_length;
  3741. key.offset -= dest_length;
  3742. btrfs_set_item_key_safe(trans, path, &key);
  3743. btrfs_set_stack_remap_address(&remap, old_addr + dest_length);
  3744. write_extent_buffer(leaf, &remap,
  3745. btrfs_item_ptr_offset(leaf, path->slots[0]),
  3746. sizeof(struct btrfs_remap_item));
  3747. }
  3748. btrfs_release_path(path);
  3749. /* Add new backref. */
  3750. ret = add_remap_backref_item(trans, path, dest_addr, dest_length, old_addr);
  3751. if (unlikely(ret))
  3752. goto end;
  3753. adjust_block_group_remap_bytes(trans, bg, -dest_length);
  3754. ret = btrfs_add_to_free_space_tree(trans, new_addr, dest_length);
  3755. if (unlikely(ret))
  3756. goto end;
  3757. adjust_block_group_remap_bytes(trans, dest_bg, dest_length);
  3758. mutex_lock(&dest_bg->free_space_lock);
  3759. bg_needs_free_space = test_bit(BLOCK_GROUP_FLAG_NEEDS_FREE_SPACE,
  3760. &dest_bg->runtime_flags);
  3761. mutex_unlock(&dest_bg->free_space_lock);
  3762. if (bg_needs_free_space) {
  3763. ret = btrfs_add_block_group_free_space(trans, dest_bg);
  3764. if (unlikely(ret))
  3765. goto end;
  3766. }
  3767. ret = btrfs_remove_from_free_space_tree(trans, dest_addr, dest_length);
  3768. if (unlikely(ret)) {
  3769. btrfs_remove_from_free_space_tree(trans, new_addr, dest_length);
  3770. goto end;
  3771. }
  3772. ret = 0;
  3773. end:
  3774. if (mutex_taken)
  3775. mutex_unlock(&fs_info->remap_mutex);
  3776. btrfs_dec_block_group_reservations(fs_info, dest_addr);
  3777. if (unlikely(ret)) {
  3778. btrfs_free_reserved_extent(fs_info, dest_addr, dest_length, 0);
  3779. if (trans) {
  3780. btrfs_abort_transaction(trans, ret);
  3781. btrfs_end_transaction(trans);
  3782. }
  3783. } else {
  3784. btrfs_free_reserved_bytes(dest_bg, dest_length, 0);
  3785. ret = btrfs_commit_transaction(trans);
  3786. }
  3787. btrfs_put_block_group(dest_bg);
  3788. return ret;
  3789. }
  3790. static int move_existing_remaps(struct btrfs_fs_info *fs_info,
  3791. struct btrfs_block_group *bg,
  3792. struct btrfs_path *path)
  3793. {
  3794. int ret;
  3795. struct btrfs_key key;
  3796. struct extent_buffer *leaf;
  3797. struct btrfs_remap_item *remap;
  3798. u64 old_addr;
  3799. /* Look for backrefs in remap tree. */
  3800. while (bg->remap_bytes > 0) {
  3801. key.objectid = bg->start;
  3802. key.type = BTRFS_REMAP_BACKREF_KEY;
  3803. key.offset = 0;
  3804. ret = btrfs_search_slot(NULL, fs_info->remap_root, &key, path, 0, 0);
  3805. if (ret < 0)
  3806. return ret;
  3807. leaf = path->nodes[0];
  3808. if (path->slots[0] >= btrfs_header_nritems(leaf)) {
  3809. ret = btrfs_next_leaf(fs_info->remap_root, path);
  3810. if (ret < 0) {
  3811. btrfs_release_path(path);
  3812. return ret;
  3813. }
  3814. if (ret) {
  3815. btrfs_release_path(path);
  3816. break;
  3817. }
  3818. leaf = path->nodes[0];
  3819. }
  3820. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  3821. if (key.type != BTRFS_REMAP_BACKREF_KEY) {
  3822. path->slots[0]++;
  3823. if (path->slots[0] >= btrfs_header_nritems(leaf)) {
  3824. ret = btrfs_next_leaf(fs_info->remap_root, path);
  3825. if (ret < 0) {
  3826. btrfs_release_path(path);
  3827. return ret;
  3828. }
  3829. if (ret) {
  3830. btrfs_release_path(path);
  3831. break;
  3832. }
  3833. leaf = path->nodes[0];
  3834. }
  3835. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  3836. }
  3837. remap = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_remap_item);
  3838. old_addr = btrfs_remap_address(leaf, remap);
  3839. btrfs_release_path(path);
  3840. ret = move_existing_remap(fs_info, path, bg, key.objectid,
  3841. key.offset, old_addr);
  3842. if (ret)
  3843. return ret;
  3844. }
  3845. ASSERT(bg->remap_bytes == 0);
  3846. return 0;
  3847. }
  3848. static int create_remap_tree_entries(struct btrfs_trans_handle *trans,
  3849. struct btrfs_path *path,
  3850. struct btrfs_block_group *bg)
  3851. {
  3852. struct btrfs_fs_info *fs_info = trans->fs_info;
  3853. struct btrfs_free_space_info *fsi;
  3854. struct btrfs_key key, found_key;
  3855. struct extent_buffer *leaf;
  3856. struct btrfs_root *space_root;
  3857. u32 extent_count;
  3858. struct space_run *space_runs = NULL;
  3859. unsigned int num_space_runs = 0;
  3860. struct btrfs_key *entries = NULL;
  3861. unsigned int max_entries, num_entries;
  3862. int ret;
  3863. mutex_lock(&bg->free_space_lock);
  3864. if (test_bit(BLOCK_GROUP_FLAG_NEEDS_FREE_SPACE, &bg->runtime_flags)) {
  3865. mutex_unlock(&bg->free_space_lock);
  3866. ret = btrfs_add_block_group_free_space(trans, bg);
  3867. if (ret)
  3868. return ret;
  3869. mutex_lock(&bg->free_space_lock);
  3870. }
  3871. fsi = btrfs_search_free_space_info(trans, bg, path, 0);
  3872. if (IS_ERR(fsi)) {
  3873. mutex_unlock(&bg->free_space_lock);
  3874. return PTR_ERR(fsi);
  3875. }
  3876. extent_count = btrfs_free_space_extent_count(path->nodes[0], fsi);
  3877. btrfs_release_path(path);
  3878. space_runs = kmalloc(sizeof(*space_runs) * extent_count, GFP_NOFS);
  3879. if (!space_runs) {
  3880. mutex_unlock(&bg->free_space_lock);
  3881. return -ENOMEM;
  3882. }
  3883. key.objectid = bg->start;
  3884. key.type = 0;
  3885. key.offset = 0;
  3886. space_root = btrfs_free_space_root(bg);
  3887. ret = btrfs_search_slot(trans, space_root, &key, path, 0, 0);
  3888. if (ret < 0) {
  3889. mutex_unlock(&bg->free_space_lock);
  3890. goto out;
  3891. }
  3892. ret = 0;
  3893. while (true) {
  3894. leaf = path->nodes[0];
  3895. btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
  3896. if (found_key.objectid >= bg->start + bg->length)
  3897. break;
  3898. if (found_key.type == BTRFS_FREE_SPACE_EXTENT_KEY) {
  3899. if (num_space_runs != 0 &&
  3900. space_runs[num_space_runs - 1].end == found_key.objectid) {
  3901. space_runs[num_space_runs - 1].end =
  3902. found_key.objectid + found_key.offset;
  3903. } else {
  3904. ASSERT(num_space_runs < extent_count);
  3905. space_runs[num_space_runs].start = found_key.objectid;
  3906. space_runs[num_space_runs].end =
  3907. found_key.objectid + found_key.offset;
  3908. num_space_runs++;
  3909. }
  3910. } else if (found_key.type == BTRFS_FREE_SPACE_BITMAP_KEY) {
  3911. void *bitmap;
  3912. unsigned long offset;
  3913. u32 data_size;
  3914. offset = btrfs_item_ptr_offset(leaf, path->slots[0]);
  3915. data_size = btrfs_item_size(leaf, path->slots[0]);
  3916. if (data_size != 0) {
  3917. bitmap = kmalloc(data_size, GFP_NOFS);
  3918. if (!bitmap) {
  3919. mutex_unlock(&bg->free_space_lock);
  3920. ret = -ENOMEM;
  3921. goto out;
  3922. }
  3923. read_extent_buffer(leaf, bitmap, offset, data_size);
  3924. parse_bitmap(fs_info->sectorsize, bitmap,
  3925. data_size * BITS_PER_BYTE,
  3926. found_key.objectid, space_runs,
  3927. &num_space_runs);
  3928. ASSERT(num_space_runs <= extent_count);
  3929. kfree(bitmap);
  3930. }
  3931. }
  3932. path->slots[0]++;
  3933. if (path->slots[0] >= btrfs_header_nritems(leaf)) {
  3934. ret = btrfs_next_leaf(space_root, path);
  3935. if (ret != 0) {
  3936. if (ret == 1)
  3937. ret = 0;
  3938. break;
  3939. }
  3940. leaf = path->nodes[0];
  3941. }
  3942. }
  3943. btrfs_release_path(path);
  3944. mutex_unlock(&bg->free_space_lock);
  3945. max_entries = extent_count + 2;
  3946. entries = kmalloc(sizeof(*entries) * max_entries, GFP_NOFS);
  3947. if (!entries) {
  3948. ret = -ENOMEM;
  3949. goto out;
  3950. }
  3951. num_entries = 0;
  3952. if (num_space_runs == 0) {
  3953. entries[num_entries].objectid = bg->start;
  3954. entries[num_entries].type = BTRFS_IDENTITY_REMAP_KEY;
  3955. entries[num_entries].offset = bg->length;
  3956. num_entries++;
  3957. } else {
  3958. if (space_runs[0].start > bg->start) {
  3959. entries[num_entries].objectid = bg->start;
  3960. entries[num_entries].type = BTRFS_IDENTITY_REMAP_KEY;
  3961. entries[num_entries].offset = space_runs[0].start - bg->start;
  3962. num_entries++;
  3963. }
  3964. for (unsigned int i = 1; i < num_space_runs; i++) {
  3965. entries[num_entries].objectid = space_runs[i - 1].end;
  3966. entries[num_entries].type = BTRFS_IDENTITY_REMAP_KEY;
  3967. entries[num_entries].offset =
  3968. space_runs[i].start - space_runs[i - 1].end;
  3969. num_entries++;
  3970. }
  3971. if (space_runs[num_space_runs - 1].end < bg->start + bg->length) {
  3972. entries[num_entries].objectid =
  3973. space_runs[num_space_runs - 1].end;
  3974. entries[num_entries].type = BTRFS_IDENTITY_REMAP_KEY;
  3975. entries[num_entries].offset =
  3976. bg->start + bg->length - space_runs[num_space_runs - 1].end;
  3977. num_entries++;
  3978. }
  3979. if (num_entries == 0)
  3980. goto out;
  3981. }
  3982. bg->identity_remap_count = num_entries;
  3983. ret = add_remap_tree_entries(trans, path, entries, num_entries);
  3984. out:
  3985. kfree(entries);
  3986. kfree(space_runs);
  3987. return ret;
  3988. }
  3989. static int find_next_identity_remap(struct btrfs_trans_handle *trans,
  3990. struct btrfs_path *path, u64 bg_end,
  3991. u64 last_start, u64 *start, u64 *length)
  3992. {
  3993. int ret;
  3994. struct btrfs_key key, found_key;
  3995. struct btrfs_root *remap_root = trans->fs_info->remap_root;
  3996. struct extent_buffer *leaf;
  3997. key.objectid = last_start;
  3998. key.type = BTRFS_IDENTITY_REMAP_KEY;
  3999. key.offset = 0;
  4000. ret = btrfs_search_slot(trans, remap_root, &key, path, 0, 0);
  4001. if (ret < 0)
  4002. goto out;
  4003. leaf = path->nodes[0];
  4004. while (true) {
  4005. if (path->slots[0] >= btrfs_header_nritems(leaf)) {
  4006. ret = btrfs_next_leaf(remap_root, path);
  4007. if (ret != 0) {
  4008. if (ret == 1)
  4009. ret = -ENOENT;
  4010. goto out;
  4011. }
  4012. leaf = path->nodes[0];
  4013. }
  4014. btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
  4015. if (found_key.objectid >= bg_end) {
  4016. ret = -ENOENT;
  4017. goto out;
  4018. }
  4019. if (found_key.type == BTRFS_IDENTITY_REMAP_KEY) {
  4020. *start = found_key.objectid;
  4021. *length = found_key.offset;
  4022. ret = 0;
  4023. goto out;
  4024. }
  4025. path->slots[0]++;
  4026. }
  4027. out:
  4028. btrfs_release_path(path);
  4029. return ret;
  4030. }
  4031. static int remove_chunk_stripes(struct btrfs_trans_handle *trans,
  4032. struct btrfs_chunk_map *chunk_map,
  4033. struct btrfs_path *path)
  4034. {
  4035. struct btrfs_fs_info *fs_info = trans->fs_info;
  4036. struct btrfs_key key;
  4037. struct extent_buffer *leaf;
  4038. struct btrfs_chunk *chunk;
  4039. int ret;
  4040. key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
  4041. key.type = BTRFS_CHUNK_ITEM_KEY;
  4042. key.offset = chunk_map->start;
  4043. btrfs_reserve_chunk_metadata(trans, false);
  4044. ret = btrfs_search_slot(trans, fs_info->chunk_root, &key, path, 0, 1);
  4045. if (ret) {
  4046. if (ret == 1) {
  4047. btrfs_release_path(path);
  4048. ret = -ENOENT;
  4049. }
  4050. btrfs_trans_release_chunk_metadata(trans);
  4051. return ret;
  4052. }
  4053. leaf = path->nodes[0];
  4054. chunk = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_chunk);
  4055. btrfs_set_chunk_num_stripes(leaf, chunk, 0);
  4056. btrfs_set_chunk_sub_stripes(leaf, chunk, 0);
  4057. btrfs_truncate_item(trans, path, offsetof(struct btrfs_chunk, stripe), 1);
  4058. btrfs_mark_buffer_dirty(trans, leaf);
  4059. btrfs_release_path(path);
  4060. btrfs_trans_release_chunk_metadata(trans);
  4061. return 0;
  4062. }
  4063. int btrfs_last_identity_remap_gone(struct btrfs_chunk_map *chunk_map,
  4064. struct btrfs_block_group *bg)
  4065. {
  4066. struct btrfs_fs_info *fs_info = bg->fs_info;
  4067. struct btrfs_trans_handle *trans;
  4068. int ret;
  4069. unsigned int num_items;
  4070. BTRFS_PATH_AUTO_FREE(path);
  4071. path = btrfs_alloc_path();
  4072. if (!path)
  4073. return -ENOMEM;
  4074. /*
  4075. * One item for each entry we're removing in the dev extents tree, and
  4076. * another for each device. DUP chunks are all on one device,
  4077. * everything else has one device per stripe.
  4078. */
  4079. if (bg->flags & BTRFS_BLOCK_GROUP_DUP)
  4080. num_items = chunk_map->num_stripes + 1;
  4081. else
  4082. num_items = 2 * chunk_map->num_stripes;
  4083. trans = btrfs_start_transaction_fallback_global_rsv(fs_info->tree_root, num_items);
  4084. if (IS_ERR(trans))
  4085. return PTR_ERR(trans);
  4086. ret = btrfs_remove_dev_extents(trans, chunk_map);
  4087. if (unlikely(ret)) {
  4088. btrfs_abort_transaction(trans, ret);
  4089. btrfs_end_transaction(trans);
  4090. return ret;
  4091. }
  4092. mutex_lock(&trans->fs_info->chunk_mutex);
  4093. for (unsigned int i = 0; i < chunk_map->num_stripes; i++) {
  4094. ret = btrfs_update_device(trans, chunk_map->stripes[i].dev);
  4095. if (unlikely(ret)) {
  4096. mutex_unlock(&trans->fs_info->chunk_mutex);
  4097. btrfs_abort_transaction(trans, ret);
  4098. btrfs_end_transaction(trans);
  4099. return ret;
  4100. }
  4101. }
  4102. mutex_unlock(&trans->fs_info->chunk_mutex);
  4103. write_lock(&trans->fs_info->mapping_tree_lock);
  4104. btrfs_chunk_map_device_clear_bits(chunk_map, CHUNK_ALLOCATED);
  4105. write_unlock(&trans->fs_info->mapping_tree_lock);
  4106. btrfs_remove_bg_from_sinfo(bg);
  4107. spin_lock(&bg->lock);
  4108. clear_bit(BLOCK_GROUP_FLAG_STRIPE_REMOVAL_PENDING, &bg->runtime_flags);
  4109. spin_unlock(&bg->lock);
  4110. ret = remove_chunk_stripes(trans, chunk_map, path);
  4111. if (unlikely(ret)) {
  4112. btrfs_abort_transaction(trans, ret);
  4113. btrfs_end_transaction(trans);
  4114. return ret;
  4115. }
  4116. ret = btrfs_commit_transaction(trans);
  4117. if (ret)
  4118. return ret;
  4119. return 0;
  4120. }
  4121. static void adjust_identity_remap_count(struct btrfs_trans_handle *trans,
  4122. struct btrfs_block_group *bg, int delta)
  4123. {
  4124. struct btrfs_fs_info *fs_info = trans->fs_info;
  4125. bool bg_already_dirty = true;
  4126. bool mark_fully_remapped = false;
  4127. WARN_ON(delta < 0 && -delta > bg->identity_remap_count);
  4128. spin_lock(&bg->lock);
  4129. bg->identity_remap_count += delta;
  4130. if (bg->identity_remap_count == 0 &&
  4131. !test_bit(BLOCK_GROUP_FLAG_FULLY_REMAPPED, &bg->runtime_flags)) {
  4132. set_bit(BLOCK_GROUP_FLAG_FULLY_REMAPPED, &bg->runtime_flags);
  4133. mark_fully_remapped = true;
  4134. }
  4135. spin_unlock(&bg->lock);
  4136. spin_lock(&trans->transaction->dirty_bgs_lock);
  4137. if (list_empty(&bg->dirty_list)) {
  4138. list_add_tail(&bg->dirty_list, &trans->transaction->dirty_bgs);
  4139. bg_already_dirty = false;
  4140. btrfs_get_block_group(bg);
  4141. }
  4142. spin_unlock(&trans->transaction->dirty_bgs_lock);
  4143. /* Modified block groups are accounted for in the delayed_refs_rsv. */
  4144. if (!bg_already_dirty)
  4145. btrfs_inc_delayed_refs_rsv_bg_updates(fs_info);
  4146. if (mark_fully_remapped)
  4147. btrfs_mark_bg_fully_remapped(bg, trans);
  4148. }
  4149. static int add_remap_entry(struct btrfs_trans_handle *trans,
  4150. struct btrfs_path *path,
  4151. struct btrfs_block_group *src_bg, u64 old_addr,
  4152. u64 new_addr, u64 length)
  4153. {
  4154. struct btrfs_fs_info *fs_info = trans->fs_info;
  4155. struct btrfs_key key, new_key;
  4156. int ret;
  4157. int identity_count_delta = 0;
  4158. key.objectid = old_addr;
  4159. key.type = (u8)-1;
  4160. key.offset = (u64)-1;
  4161. ret = btrfs_search_slot(trans, fs_info->remap_root, &key, path, -1, 1);
  4162. if (ret < 0)
  4163. goto end;
  4164. if (path->slots[0] == 0) {
  4165. ret = -ENOENT;
  4166. goto end;
  4167. }
  4168. path->slots[0]--;
  4169. btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
  4170. if (key.type != BTRFS_IDENTITY_REMAP_KEY ||
  4171. key.objectid > old_addr ||
  4172. key.objectid + key.offset <= old_addr) {
  4173. ret = -ENOENT;
  4174. goto end;
  4175. }
  4176. /* Shorten or delete identity mapping entry. */
  4177. if (key.objectid == old_addr) {
  4178. ret = btrfs_del_item(trans, fs_info->remap_root, path);
  4179. if (ret)
  4180. goto end;
  4181. identity_count_delta--;
  4182. } else {
  4183. new_key.objectid = key.objectid;
  4184. new_key.type = BTRFS_IDENTITY_REMAP_KEY;
  4185. new_key.offset = old_addr - key.objectid;
  4186. btrfs_set_item_key_safe(trans, path, &new_key);
  4187. }
  4188. btrfs_release_path(path);
  4189. /* Create new remap entry. */
  4190. ret = add_remap_item(trans, path, new_addr, length, old_addr);
  4191. if (ret)
  4192. goto end;
  4193. /* Add entry for remainder of identity mapping, if necessary. */
  4194. if (key.objectid + key.offset != old_addr + length) {
  4195. new_key.objectid = old_addr + length;
  4196. new_key.type = BTRFS_IDENTITY_REMAP_KEY;
  4197. new_key.offset = key.objectid + key.offset - old_addr - length;
  4198. ret = btrfs_insert_empty_item(trans, fs_info->remap_root,
  4199. path, &new_key, 0);
  4200. if (ret)
  4201. goto end;
  4202. btrfs_release_path(path);
  4203. identity_count_delta++;
  4204. }
  4205. /* Add backref. */
  4206. ret = add_remap_backref_item(trans, path, new_addr, length, old_addr);
  4207. if (ret)
  4208. goto end;
  4209. if (identity_count_delta != 0)
  4210. adjust_identity_remap_count(trans, src_bg, identity_count_delta);
  4211. end:
  4212. btrfs_release_path(path);
  4213. return ret;
  4214. }
  4215. static int mark_chunk_remapped(struct btrfs_trans_handle *trans,
  4216. struct btrfs_path *path, u64 start)
  4217. {
  4218. struct btrfs_fs_info *fs_info = trans->fs_info;
  4219. struct btrfs_chunk_map *chunk_map;
  4220. struct btrfs_key key;
  4221. u64 type;
  4222. int ret;
  4223. struct extent_buffer *leaf;
  4224. struct btrfs_chunk *chunk;
  4225. read_lock(&fs_info->mapping_tree_lock);
  4226. chunk_map = btrfs_find_chunk_map_nolock(fs_info, start, 1);
  4227. if (!chunk_map) {
  4228. read_unlock(&fs_info->mapping_tree_lock);
  4229. return -ENOENT;
  4230. }
  4231. chunk_map->type |= BTRFS_BLOCK_GROUP_REMAPPED;
  4232. type = chunk_map->type;
  4233. read_unlock(&fs_info->mapping_tree_lock);
  4234. key.objectid = BTRFS_FIRST_CHUNK_TREE_OBJECTID;
  4235. key.type = BTRFS_CHUNK_ITEM_KEY;
  4236. key.offset = start;
  4237. ret = btrfs_search_slot(trans, fs_info->chunk_root, &key, path, 0, 1);
  4238. if (ret == 1) {
  4239. ret = -ENOENT;
  4240. goto end;
  4241. } else if (ret < 0)
  4242. goto end;
  4243. leaf = path->nodes[0];
  4244. chunk = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_chunk);
  4245. btrfs_set_chunk_type(leaf, chunk, type);
  4246. btrfs_mark_buffer_dirty(trans, leaf);
  4247. ret = 0;
  4248. end:
  4249. btrfs_free_chunk_map(chunk_map);
  4250. btrfs_release_path(path);
  4251. return ret;
  4252. }
  4253. static int do_remap_reloc_trans(struct btrfs_fs_info *fs_info,
  4254. struct btrfs_block_group *src_bg,
  4255. struct btrfs_path *path, u64 *last_start)
  4256. {
  4257. struct btrfs_trans_handle *trans;
  4258. struct btrfs_root *extent_root;
  4259. struct btrfs_key ins;
  4260. struct btrfs_block_group *dest_bg = NULL;
  4261. u64 start = 0, remap_length = 0;
  4262. u64 length, new_addr, min_size;
  4263. int ret;
  4264. const bool is_data = (src_bg->flags & BTRFS_BLOCK_GROUP_DATA);
  4265. bool no_more = false;
  4266. bool made_reservation = false, bg_needs_free_space;
  4267. struct btrfs_space_info *sinfo = src_bg->space_info;
  4268. extent_root = btrfs_extent_root(fs_info, src_bg->start);
  4269. if (unlikely(!extent_root)) {
  4270. btrfs_err(fs_info,
  4271. "missing extent root for block group at offset %llu",
  4272. src_bg->start);
  4273. return -EUCLEAN;
  4274. }
  4275. trans = btrfs_start_transaction(extent_root, 0);
  4276. if (IS_ERR(trans))
  4277. return PTR_ERR(trans);
  4278. mutex_lock(&fs_info->remap_mutex);
  4279. ret = find_next_identity_remap(trans, path, src_bg->start + src_bg->length,
  4280. *last_start, &start, &remap_length);
  4281. if (ret == -ENOENT) {
  4282. no_more = true;
  4283. goto next;
  4284. } else if (ret) {
  4285. mutex_unlock(&fs_info->remap_mutex);
  4286. btrfs_end_transaction(trans);
  4287. return ret;
  4288. }
  4289. /* Try to reserve enough space for block. */
  4290. spin_lock(&sinfo->lock);
  4291. btrfs_space_info_update_bytes_may_use(sinfo, remap_length);
  4292. spin_unlock(&sinfo->lock);
  4293. if (is_data)
  4294. min_size = fs_info->sectorsize;
  4295. else
  4296. min_size = fs_info->nodesize;
  4297. /*
  4298. * We're using btrfs_reserve_extent() to allocate a contiguous
  4299. * logical address range, but this will become a remap item rather than
  4300. * an extent in the extent tree.
  4301. *
  4302. * Short allocations are fine: it means that we chop off the beginning
  4303. * of the identity remap that we're processing, and will tackle the
  4304. * rest of it the next time round.
  4305. */
  4306. ret = btrfs_reserve_extent(fs_info->fs_root, remap_length, remap_length,
  4307. min_size, 0, 0, &ins, is_data, false);
  4308. if (ret) {
  4309. spin_lock(&sinfo->lock);
  4310. btrfs_space_info_update_bytes_may_use(sinfo, -remap_length);
  4311. spin_unlock(&sinfo->lock);
  4312. mutex_unlock(&fs_info->remap_mutex);
  4313. btrfs_end_transaction(trans);
  4314. return ret;
  4315. }
  4316. made_reservation = true;
  4317. new_addr = ins.objectid;
  4318. length = ins.offset;
  4319. if (!is_data && !IS_ALIGNED(length, fs_info->nodesize)) {
  4320. u64 new_length = ALIGN_DOWN(length, fs_info->nodesize);
  4321. btrfs_free_reserved_extent(fs_info, new_addr + new_length,
  4322. length - new_length, 0);
  4323. length = new_length;
  4324. }
  4325. dest_bg = btrfs_lookup_block_group(fs_info, new_addr);
  4326. mutex_lock(&dest_bg->free_space_lock);
  4327. bg_needs_free_space = test_bit(BLOCK_GROUP_FLAG_NEEDS_FREE_SPACE,
  4328. &dest_bg->runtime_flags);
  4329. mutex_unlock(&dest_bg->free_space_lock);
  4330. if (bg_needs_free_space) {
  4331. ret = btrfs_add_block_group_free_space(trans, dest_bg);
  4332. if (ret)
  4333. goto fail;
  4334. }
  4335. ret = copy_remapped_data(fs_info, start, new_addr, length);
  4336. if (ret)
  4337. goto fail;
  4338. ret = btrfs_remove_from_free_space_tree(trans, new_addr, length);
  4339. if (ret)
  4340. goto fail;
  4341. ret = add_remap_entry(trans, path, src_bg, start, new_addr, length);
  4342. if (ret) {
  4343. btrfs_add_to_free_space_tree(trans, new_addr, length);
  4344. goto fail;
  4345. }
  4346. adjust_block_group_remap_bytes(trans, dest_bg, length);
  4347. btrfs_free_reserved_bytes(dest_bg, length, 0);
  4348. spin_lock(&sinfo->lock);
  4349. sinfo->bytes_readonly += length;
  4350. spin_unlock(&sinfo->lock);
  4351. next:
  4352. if (dest_bg)
  4353. btrfs_put_block_group(dest_bg);
  4354. if (made_reservation)
  4355. btrfs_dec_block_group_reservations(fs_info, new_addr);
  4356. mutex_unlock(&fs_info->remap_mutex);
  4357. if (src_bg->identity_remap_count == 0) {
  4358. bool mark_fully_remapped = false;
  4359. spin_lock(&src_bg->lock);
  4360. if (!test_bit(BLOCK_GROUP_FLAG_FULLY_REMAPPED, &src_bg->runtime_flags)) {
  4361. mark_fully_remapped = true;
  4362. set_bit(BLOCK_GROUP_FLAG_FULLY_REMAPPED, &src_bg->runtime_flags);
  4363. }
  4364. spin_unlock(&src_bg->lock);
  4365. if (mark_fully_remapped)
  4366. btrfs_mark_bg_fully_remapped(src_bg, trans);
  4367. }
  4368. ret = btrfs_end_transaction(trans);
  4369. if (ret)
  4370. return ret;
  4371. if (no_more)
  4372. return 1;
  4373. *last_start = start;
  4374. return 0;
  4375. fail:
  4376. if (dest_bg)
  4377. btrfs_put_block_group(dest_bg);
  4378. btrfs_free_reserved_extent(fs_info, new_addr, length, 0);
  4379. mutex_unlock(&fs_info->remap_mutex);
  4380. btrfs_end_transaction(trans);
  4381. return ret;
  4382. }
  4383. static int do_remap_reloc(struct btrfs_fs_info *fs_info, struct btrfs_path *path,
  4384. struct btrfs_block_group *bg)
  4385. {
  4386. u64 last_start = bg->start;
  4387. int ret;
  4388. while (true) {
  4389. ret = do_remap_reloc_trans(fs_info, bg, path, &last_start);
  4390. if (ret) {
  4391. if (ret == 1)
  4392. ret = 0;
  4393. break;
  4394. }
  4395. }
  4396. return ret;
  4397. }
  4398. int btrfs_translate_remap(struct btrfs_fs_info *fs_info, u64 *logical, u64 *length)
  4399. {
  4400. int ret;
  4401. struct btrfs_key key, found_key;
  4402. struct extent_buffer *leaf;
  4403. struct btrfs_remap_item *remap;
  4404. BTRFS_PATH_AUTO_FREE(path);
  4405. path = btrfs_alloc_path();
  4406. if (!path)
  4407. return -ENOMEM;
  4408. key.objectid = *logical;
  4409. key.type = (u8)-1;
  4410. key.offset = (u64)-1;
  4411. ret = btrfs_search_slot(NULL, fs_info->remap_root, &key, path, 0, 0);
  4412. if (ret < 0)
  4413. return ret;
  4414. leaf = path->nodes[0];
  4415. if (path->slots[0] == 0)
  4416. return -ENOENT;
  4417. path->slots[0]--;
  4418. btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
  4419. if (found_key.type != BTRFS_REMAP_KEY &&
  4420. found_key.type != BTRFS_IDENTITY_REMAP_KEY) {
  4421. return -ENOENT;
  4422. }
  4423. if (found_key.objectid > *logical ||
  4424. found_key.objectid + found_key.offset <= *logical) {
  4425. return -ENOENT;
  4426. }
  4427. if (*logical + *length > found_key.objectid + found_key.offset)
  4428. *length = found_key.objectid + found_key.offset - *logical;
  4429. if (found_key.type == BTRFS_IDENTITY_REMAP_KEY)
  4430. return 0;
  4431. remap = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_remap_item);
  4432. *logical += btrfs_remap_address(leaf, remap) - found_key.objectid;
  4433. return 0;
  4434. }
  4435. static int start_block_group_remapping(struct btrfs_fs_info *fs_info,
  4436. struct btrfs_path *path,
  4437. struct btrfs_block_group *bg)
  4438. {
  4439. struct btrfs_trans_handle *trans;
  4440. bool bg_already_dirty = true;
  4441. int ret, ret2;
  4442. ret = btrfs_cache_block_group(bg, true);
  4443. if (ret)
  4444. return ret;
  4445. trans = btrfs_start_transaction(fs_info->remap_root, 0);
  4446. if (IS_ERR(trans))
  4447. return PTR_ERR(trans);
  4448. /* We need to run delayed refs, to make sure FST is up to date. */
  4449. ret = btrfs_run_delayed_refs(trans, U64_MAX);
  4450. if (ret) {
  4451. btrfs_end_transaction(trans);
  4452. return ret;
  4453. }
  4454. mutex_lock(&fs_info->remap_mutex);
  4455. if (bg->flags & BTRFS_BLOCK_GROUP_REMAPPED) {
  4456. ret = 0;
  4457. goto end;
  4458. }
  4459. ret = create_remap_tree_entries(trans, path, bg);
  4460. if (unlikely(ret)) {
  4461. btrfs_abort_transaction(trans, ret);
  4462. goto end;
  4463. }
  4464. spin_lock(&bg->lock);
  4465. bg->flags |= BTRFS_BLOCK_GROUP_REMAPPED;
  4466. spin_unlock(&bg->lock);
  4467. spin_lock(&trans->transaction->dirty_bgs_lock);
  4468. if (list_empty(&bg->dirty_list)) {
  4469. list_add_tail(&bg->dirty_list, &trans->transaction->dirty_bgs);
  4470. bg_already_dirty = false;
  4471. btrfs_get_block_group(bg);
  4472. }
  4473. spin_unlock(&trans->transaction->dirty_bgs_lock);
  4474. /* Modified block groups are accounted for in the delayed_refs_rsv. */
  4475. if (!bg_already_dirty)
  4476. btrfs_inc_delayed_refs_rsv_bg_updates(fs_info);
  4477. ret = mark_chunk_remapped(trans, path, bg->start);
  4478. if (unlikely(ret)) {
  4479. btrfs_abort_transaction(trans, ret);
  4480. goto end;
  4481. }
  4482. ret = btrfs_remove_block_group_free_space(trans, bg);
  4483. if (unlikely(ret)) {
  4484. btrfs_abort_transaction(trans, ret);
  4485. goto end;
  4486. }
  4487. btrfs_remove_free_space_cache(bg);
  4488. end:
  4489. mutex_unlock(&fs_info->remap_mutex);
  4490. ret2 = btrfs_end_transaction(trans);
  4491. if (!ret)
  4492. ret = ret2;
  4493. return ret;
  4494. }
  4495. static int do_nonremap_reloc(struct btrfs_fs_info *fs_info, bool verbose,
  4496. struct reloc_control *rc)
  4497. {
  4498. int ret;
  4499. while (1) {
  4500. enum reloc_stage finishes_stage;
  4501. mutex_lock(&fs_info->cleaner_mutex);
  4502. ret = relocate_block_group(rc);
  4503. mutex_unlock(&fs_info->cleaner_mutex);
  4504. finishes_stage = rc->stage;
  4505. /*
  4506. * We may have gotten ENOSPC after we already dirtied some
  4507. * extents. If writeout happens while we're relocating a
  4508. * different block group we could end up hitting the
  4509. * BUG_ON(rc->stage == UPDATE_DATA_PTRS) in
  4510. * btrfs_reloc_cow_block. Make sure we write everything out
  4511. * properly so we don't trip over this problem, and then break
  4512. * out of the loop if we hit an error.
  4513. */
  4514. if (rc->stage == MOVE_DATA_EXTENTS && rc->found_file_extent) {
  4515. int wb_ret;
  4516. wb_ret = btrfs_wait_ordered_range(BTRFS_I(rc->data_inode),
  4517. 0, (u64)-1);
  4518. if (wb_ret && ret == 0)
  4519. ret = wb_ret;
  4520. invalidate_mapping_pages(rc->data_inode->i_mapping, 0, -1);
  4521. rc->stage = UPDATE_DATA_PTRS;
  4522. }
  4523. if (ret < 0)
  4524. return ret;
  4525. if (rc->extents_found == 0)
  4526. break;
  4527. if (verbose)
  4528. btrfs_info(fs_info, "found %llu extents, stage: %s",
  4529. rc->extents_found, stage_to_string(finishes_stage));
  4530. }
  4531. WARN_ON(rc->block_group->pinned > 0);
  4532. WARN_ON(rc->block_group->reserved > 0);
  4533. WARN_ON(rc->block_group->used > 0);
  4534. return 0;
  4535. }
  4536. /*
  4537. * function to relocate all extents in a block group.
  4538. */
  4539. int btrfs_relocate_block_group(struct btrfs_fs_info *fs_info, u64 group_start,
  4540. bool verbose)
  4541. {
  4542. struct btrfs_block_group *bg;
  4543. struct btrfs_root *extent_root = btrfs_extent_root(fs_info, group_start);
  4544. struct reloc_control *rc;
  4545. struct inode *inode;
  4546. struct btrfs_path *path = NULL;
  4547. int ret;
  4548. bool bg_is_ro = false;
  4549. if (unlikely(!extent_root)) {
  4550. btrfs_err(fs_info,
  4551. "missing extent root for block group at offset %llu",
  4552. group_start);
  4553. return -EUCLEAN;
  4554. }
  4555. /*
  4556. * This only gets set if we had a half-deleted snapshot on mount. We
  4557. * cannot allow relocation to start while we're still trying to clean up
  4558. * these pending deletions.
  4559. */
  4560. ret = wait_on_bit(&fs_info->flags, BTRFS_FS_UNFINISHED_DROPS, TASK_INTERRUPTIBLE);
  4561. if (ret)
  4562. return ret;
  4563. /* We may have been woken up by close_ctree, so bail if we're closing. */
  4564. if (btrfs_fs_closing(fs_info))
  4565. return -EINTR;
  4566. bg = btrfs_lookup_block_group(fs_info, group_start);
  4567. if (!bg)
  4568. return -ENOENT;
  4569. /*
  4570. * Relocation of a data block group creates ordered extents. Without
  4571. * sb_start_write(), we can freeze the filesystem while unfinished
  4572. * ordered extents are left. Such ordered extents can cause a deadlock
  4573. * e.g. when syncfs() is waiting for their completion but they can't
  4574. * finish because they block when joining a transaction, due to the
  4575. * fact that the freeze locks are being held in write mode.
  4576. */
  4577. if (bg->flags & BTRFS_BLOCK_GROUP_DATA)
  4578. ASSERT(sb_write_started(fs_info->sb));
  4579. if (btrfs_pinned_by_swapfile(fs_info, bg)) {
  4580. btrfs_put_block_group(bg);
  4581. return -ETXTBSY;
  4582. }
  4583. rc = alloc_reloc_control(fs_info);
  4584. if (!rc) {
  4585. btrfs_put_block_group(bg);
  4586. return -ENOMEM;
  4587. }
  4588. ret = reloc_chunk_start(fs_info);
  4589. if (ret < 0)
  4590. goto out_put_bg;
  4591. rc->extent_root = extent_root;
  4592. rc->block_group = bg;
  4593. ret = btrfs_inc_block_group_ro(rc->block_group, true);
  4594. if (ret)
  4595. goto out;
  4596. bg_is_ro = true;
  4597. path = btrfs_alloc_path();
  4598. if (!path) {
  4599. ret = -ENOMEM;
  4600. goto out;
  4601. }
  4602. inode = lookup_free_space_inode(rc->block_group, path);
  4603. btrfs_release_path(path);
  4604. if (!IS_ERR(inode))
  4605. ret = delete_block_group_cache(rc->block_group, inode, 0);
  4606. else
  4607. ret = PTR_ERR(inode);
  4608. if (ret && ret != -ENOENT)
  4609. goto out;
  4610. if (!btrfs_fs_incompat(fs_info, REMAP_TREE)) {
  4611. rc->data_inode = create_reloc_inode(rc->block_group);
  4612. if (IS_ERR(rc->data_inode)) {
  4613. ret = PTR_ERR(rc->data_inode);
  4614. rc->data_inode = NULL;
  4615. goto out;
  4616. }
  4617. }
  4618. if (verbose)
  4619. describe_relocation(rc->block_group);
  4620. btrfs_wait_block_group_reservations(rc->block_group);
  4621. btrfs_wait_nocow_writers(rc->block_group);
  4622. btrfs_wait_ordered_roots(fs_info, U64_MAX, rc->block_group);
  4623. ret = btrfs_zone_finish(rc->block_group);
  4624. WARN_ON(ret && ret != -EAGAIN);
  4625. if (should_relocate_using_remap_tree(bg)) {
  4626. if (bg->remap_bytes != 0) {
  4627. ret = move_existing_remaps(fs_info, bg, path);
  4628. if (ret)
  4629. goto out;
  4630. }
  4631. ret = start_block_group_remapping(fs_info, path, bg);
  4632. if (ret)
  4633. goto out;
  4634. ret = do_remap_reloc(fs_info, path, rc->block_group);
  4635. if (ret)
  4636. goto out;
  4637. btrfs_delete_unused_bgs(fs_info);
  4638. } else {
  4639. ret = do_nonremap_reloc(fs_info, verbose, rc);
  4640. }
  4641. out:
  4642. if (ret && bg_is_ro)
  4643. btrfs_dec_block_group_ro(rc->block_group);
  4644. if (!btrfs_fs_incompat(fs_info, REMAP_TREE))
  4645. iput(rc->data_inode);
  4646. btrfs_free_path(path);
  4647. reloc_chunk_end(fs_info);
  4648. out_put_bg:
  4649. btrfs_put_block_group(bg);
  4650. free_reloc_control(rc);
  4651. return ret;
  4652. }
  4653. static noinline_for_stack int mark_garbage_root(struct btrfs_root *root)
  4654. {
  4655. struct btrfs_fs_info *fs_info = root->fs_info;
  4656. struct btrfs_trans_handle *trans;
  4657. int ret, err;
  4658. trans = btrfs_start_transaction(fs_info->tree_root, 0);
  4659. if (IS_ERR(trans))
  4660. return PTR_ERR(trans);
  4661. memset(&root->root_item.drop_progress, 0,
  4662. sizeof(root->root_item.drop_progress));
  4663. btrfs_set_root_drop_level(&root->root_item, 0);
  4664. btrfs_set_root_refs(&root->root_item, 0);
  4665. ret = btrfs_update_root(trans, fs_info->tree_root,
  4666. &root->root_key, &root->root_item);
  4667. err = btrfs_end_transaction(trans);
  4668. if (err)
  4669. return err;
  4670. return ret;
  4671. }
  4672. /*
  4673. * recover relocation interrupted by system crash.
  4674. *
  4675. * this function resumes merging reloc trees with corresponding fs trees.
  4676. * this is important for keeping the sharing of tree blocks
  4677. */
  4678. int btrfs_recover_relocation(struct btrfs_fs_info *fs_info)
  4679. {
  4680. LIST_HEAD(reloc_roots);
  4681. struct btrfs_key key;
  4682. struct btrfs_root *fs_root;
  4683. struct btrfs_root *reloc_root;
  4684. struct btrfs_path *path;
  4685. struct extent_buffer *leaf;
  4686. struct reloc_control *rc = NULL;
  4687. struct btrfs_trans_handle *trans;
  4688. int ret2;
  4689. int ret = 0;
  4690. path = btrfs_alloc_path();
  4691. if (!path)
  4692. return -ENOMEM;
  4693. path->reada = READA_BACK;
  4694. key.objectid = BTRFS_TREE_RELOC_OBJECTID;
  4695. key.type = BTRFS_ROOT_ITEM_KEY;
  4696. key.offset = (u64)-1;
  4697. while (1) {
  4698. ret = btrfs_search_slot(NULL, fs_info->tree_root, &key,
  4699. path, 0, 0);
  4700. if (ret < 0)
  4701. goto out;
  4702. if (ret > 0) {
  4703. if (path->slots[0] == 0)
  4704. break;
  4705. path->slots[0]--;
  4706. }
  4707. ret = 0;
  4708. leaf = path->nodes[0];
  4709. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  4710. btrfs_release_path(path);
  4711. if (key.objectid != BTRFS_TREE_RELOC_OBJECTID ||
  4712. key.type != BTRFS_ROOT_ITEM_KEY)
  4713. break;
  4714. reloc_root = btrfs_read_tree_root(fs_info->tree_root, &key);
  4715. if (IS_ERR(reloc_root)) {
  4716. ret = PTR_ERR(reloc_root);
  4717. goto out;
  4718. }
  4719. set_bit(BTRFS_ROOT_SHAREABLE, &reloc_root->state);
  4720. list_add(&reloc_root->root_list, &reloc_roots);
  4721. if (btrfs_root_refs(&reloc_root->root_item) > 0) {
  4722. fs_root = btrfs_get_fs_root(fs_info,
  4723. reloc_root->root_key.offset, false);
  4724. if (IS_ERR(fs_root)) {
  4725. ret = PTR_ERR(fs_root);
  4726. if (ret != -ENOENT)
  4727. goto out;
  4728. ret = mark_garbage_root(reloc_root);
  4729. if (ret < 0)
  4730. goto out;
  4731. ret = 0;
  4732. } else {
  4733. btrfs_put_root(fs_root);
  4734. }
  4735. }
  4736. if (key.offset == 0)
  4737. break;
  4738. key.offset--;
  4739. }
  4740. btrfs_release_path(path);
  4741. if (list_empty(&reloc_roots))
  4742. goto out;
  4743. rc = alloc_reloc_control(fs_info);
  4744. if (!rc) {
  4745. ret = -ENOMEM;
  4746. goto out;
  4747. }
  4748. rc->extent_root = btrfs_extent_root(fs_info, 0);
  4749. if (unlikely(!rc->extent_root)) {
  4750. btrfs_err(fs_info, "missing extent root for extent at bytenr 0");
  4751. ret = -EUCLEAN;
  4752. goto out;
  4753. }
  4754. ret = reloc_chunk_start(fs_info);
  4755. if (ret < 0)
  4756. goto out_end;
  4757. set_reloc_control(rc);
  4758. trans = btrfs_join_transaction(rc->extent_root);
  4759. if (IS_ERR(trans)) {
  4760. ret = PTR_ERR(trans);
  4761. goto out_unset;
  4762. }
  4763. rc->merge_reloc_tree = true;
  4764. while (!list_empty(&reloc_roots)) {
  4765. reloc_root = list_first_entry(&reloc_roots, struct btrfs_root, root_list);
  4766. list_del(&reloc_root->root_list);
  4767. if (btrfs_root_refs(&reloc_root->root_item) == 0) {
  4768. list_add_tail(&reloc_root->root_list,
  4769. &rc->reloc_roots);
  4770. continue;
  4771. }
  4772. fs_root = btrfs_get_fs_root(fs_info, reloc_root->root_key.offset,
  4773. false);
  4774. if (IS_ERR(fs_root)) {
  4775. ret = PTR_ERR(fs_root);
  4776. list_add_tail(&reloc_root->root_list, &reloc_roots);
  4777. btrfs_end_transaction(trans);
  4778. goto out_unset;
  4779. }
  4780. ret = __add_reloc_root(reloc_root);
  4781. ASSERT(ret != -EEXIST);
  4782. if (ret) {
  4783. list_add_tail(&reloc_root->root_list, &reloc_roots);
  4784. btrfs_put_root(fs_root);
  4785. btrfs_end_transaction(trans);
  4786. goto out_unset;
  4787. }
  4788. fs_root->reloc_root = btrfs_grab_root(reloc_root);
  4789. btrfs_put_root(fs_root);
  4790. }
  4791. ret = btrfs_commit_transaction(trans);
  4792. if (ret)
  4793. goto out_unset;
  4794. merge_reloc_roots(rc);
  4795. unset_reloc_control(rc);
  4796. trans = btrfs_join_transaction(rc->extent_root);
  4797. if (IS_ERR(trans)) {
  4798. ret = PTR_ERR(trans);
  4799. goto out_clean;
  4800. }
  4801. ret = btrfs_commit_transaction(trans);
  4802. out_clean:
  4803. ret2 = clean_dirty_subvols(rc);
  4804. if (ret2 < 0 && !ret)
  4805. ret = ret2;
  4806. out_unset:
  4807. unset_reloc_control(rc);
  4808. reloc_chunk_end(fs_info);
  4809. out_end:
  4810. free_reloc_control(rc);
  4811. out:
  4812. free_reloc_roots(&reloc_roots);
  4813. btrfs_free_path(path);
  4814. if (ret == 0 && !btrfs_fs_incompat(fs_info, REMAP_TREE)) {
  4815. /* cleanup orphan inode in data relocation tree */
  4816. fs_root = btrfs_grab_root(fs_info->data_reloc_root);
  4817. ASSERT(fs_root);
  4818. ret = btrfs_orphan_cleanup(fs_root);
  4819. btrfs_put_root(fs_root);
  4820. }
  4821. return ret;
  4822. }
  4823. /*
  4824. * helper to add ordered checksum for data relocation.
  4825. *
  4826. * cloning checksum properly handles the nodatasum extents.
  4827. * it also saves CPU time to re-calculate the checksum.
  4828. */
  4829. int btrfs_reloc_clone_csums(struct btrfs_ordered_extent *ordered)
  4830. {
  4831. struct btrfs_inode *inode = ordered->inode;
  4832. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  4833. u64 disk_bytenr = ordered->file_offset + inode->reloc_block_group_start;
  4834. struct btrfs_root *csum_root = btrfs_csum_root(fs_info, disk_bytenr);
  4835. LIST_HEAD(list);
  4836. int ret;
  4837. if (unlikely(!csum_root)) {
  4838. btrfs_mark_ordered_extent_error(ordered);
  4839. btrfs_err(fs_info,
  4840. "missing csum root for extent at bytenr %llu",
  4841. disk_bytenr);
  4842. return -EUCLEAN;
  4843. }
  4844. ret = btrfs_lookup_csums_list(csum_root, disk_bytenr,
  4845. disk_bytenr + ordered->num_bytes - 1,
  4846. &list, false);
  4847. if (ret < 0) {
  4848. btrfs_mark_ordered_extent_error(ordered);
  4849. return ret;
  4850. }
  4851. while (!list_empty(&list)) {
  4852. struct btrfs_ordered_sum *sums =
  4853. list_first_entry(&list, struct btrfs_ordered_sum, list);
  4854. list_del_init(&sums->list);
  4855. /*
  4856. * We need to offset the new_bytenr based on where the csum is.
  4857. * We need to do this because we will read in entire prealloc
  4858. * extents but we may have written to say the middle of the
  4859. * prealloc extent, so we need to make sure the csum goes with
  4860. * the right disk offset.
  4861. *
  4862. * We can do this because the data reloc inode refers strictly
  4863. * to the on disk bytes, so we don't have to worry about
  4864. * disk_len vs real len like with real inodes since it's all
  4865. * disk length.
  4866. */
  4867. sums->logical = ordered->disk_bytenr + sums->logical - disk_bytenr;
  4868. btrfs_add_ordered_sum(ordered, sums);
  4869. }
  4870. return 0;
  4871. }
  4872. int btrfs_reloc_cow_block(struct btrfs_trans_handle *trans,
  4873. struct btrfs_root *root,
  4874. const struct extent_buffer *buf,
  4875. struct extent_buffer *cow)
  4876. {
  4877. struct btrfs_fs_info *fs_info = root->fs_info;
  4878. struct reloc_control *rc;
  4879. struct btrfs_backref_node *node;
  4880. int first_cow = 0;
  4881. int level;
  4882. int ret = 0;
  4883. rc = fs_info->reloc_ctl;
  4884. if (!rc)
  4885. return 0;
  4886. BUG_ON(rc->stage == UPDATE_DATA_PTRS && btrfs_is_data_reloc_root(root));
  4887. level = btrfs_header_level(buf);
  4888. if (btrfs_header_generation(buf) <=
  4889. btrfs_root_last_snapshot(&root->root_item))
  4890. first_cow = 1;
  4891. if (btrfs_root_id(root) == BTRFS_TREE_RELOC_OBJECTID && rc->create_reloc_tree) {
  4892. WARN_ON(!first_cow && level == 0);
  4893. node = rc->backref_cache.path[level];
  4894. /*
  4895. * If node->bytenr != buf->start and node->new_bytenr !=
  4896. * buf->start then we've got the wrong backref node for what we
  4897. * expected to see here and the cache is incorrect.
  4898. */
  4899. if (unlikely(node->bytenr != buf->start && node->new_bytenr != buf->start)) {
  4900. btrfs_err(fs_info,
  4901. "bytenr %llu was found but our backref cache was expecting %llu or %llu",
  4902. buf->start, node->bytenr, node->new_bytenr);
  4903. return -EUCLEAN;
  4904. }
  4905. btrfs_backref_drop_node_buffer(node);
  4906. refcount_inc(&cow->refs);
  4907. node->eb = cow;
  4908. node->new_bytenr = cow->start;
  4909. if (!node->pending) {
  4910. list_move_tail(&node->list,
  4911. &rc->backref_cache.pending[level]);
  4912. node->pending = 1;
  4913. }
  4914. if (first_cow)
  4915. mark_block_processed(rc, node);
  4916. if (first_cow && level > 0)
  4917. rc->nodes_relocated += buf->len;
  4918. }
  4919. if (level == 0 && first_cow && rc->stage == UPDATE_DATA_PTRS)
  4920. ret = replace_file_extents(trans, rc, root, cow);
  4921. return ret;
  4922. }
  4923. /*
  4924. * called before creating snapshot. it calculates metadata reservation
  4925. * required for relocating tree blocks in the snapshot
  4926. */
  4927. void btrfs_reloc_pre_snapshot(struct btrfs_pending_snapshot *pending,
  4928. u64 *bytes_to_reserve)
  4929. {
  4930. struct btrfs_root *root = pending->root;
  4931. struct reloc_control *rc = root->fs_info->reloc_ctl;
  4932. if (!rc || !have_reloc_root(root))
  4933. return;
  4934. if (!rc->merge_reloc_tree)
  4935. return;
  4936. root = root->reloc_root;
  4937. BUG_ON(btrfs_root_refs(&root->root_item) == 0);
  4938. /*
  4939. * relocation is in the stage of merging trees. the space
  4940. * used by merging a reloc tree is twice the size of
  4941. * relocated tree nodes in the worst case. half for cowing
  4942. * the reloc tree, half for cowing the fs tree. the space
  4943. * used by cowing the reloc tree will be freed after the
  4944. * tree is dropped. if we create snapshot, cowing the fs
  4945. * tree may use more space than it frees. so we need
  4946. * reserve extra space.
  4947. */
  4948. *bytes_to_reserve += rc->nodes_relocated;
  4949. }
  4950. /*
  4951. * called after snapshot is created. migrate block reservation
  4952. * and create reloc root for the newly created snapshot
  4953. *
  4954. * This is similar to btrfs_init_reloc_root(), we come out of here with two
  4955. * references held on the reloc_root, one for root->reloc_root and one for
  4956. * rc->reloc_roots.
  4957. */
  4958. int btrfs_reloc_post_snapshot(struct btrfs_trans_handle *trans,
  4959. struct btrfs_pending_snapshot *pending)
  4960. {
  4961. struct btrfs_root *root = pending->root;
  4962. struct btrfs_root *reloc_root;
  4963. struct btrfs_root *new_root;
  4964. struct reloc_control *rc = root->fs_info->reloc_ctl;
  4965. int ret;
  4966. if (!rc || !have_reloc_root(root))
  4967. return 0;
  4968. rc = root->fs_info->reloc_ctl;
  4969. rc->merging_rsv_size += rc->nodes_relocated;
  4970. if (rc->merge_reloc_tree) {
  4971. ret = btrfs_block_rsv_migrate(&pending->block_rsv,
  4972. rc->block_rsv,
  4973. rc->nodes_relocated, true);
  4974. if (ret)
  4975. return ret;
  4976. }
  4977. new_root = pending->snap;
  4978. reloc_root = create_reloc_root(trans, root->reloc_root, btrfs_root_id(new_root));
  4979. if (IS_ERR(reloc_root))
  4980. return PTR_ERR(reloc_root);
  4981. ret = __add_reloc_root(reloc_root);
  4982. ASSERT(ret != -EEXIST);
  4983. if (ret) {
  4984. /* Pairs with create_reloc_root */
  4985. btrfs_put_root(reloc_root);
  4986. return ret;
  4987. }
  4988. new_root->reloc_root = btrfs_grab_root(reloc_root);
  4989. return 0;
  4990. }
  4991. /*
  4992. * Get the current bytenr for the block group which is being relocated.
  4993. *
  4994. * Return U64_MAX if no running relocation.
  4995. */
  4996. u64 btrfs_get_reloc_bg_bytenr(const struct btrfs_fs_info *fs_info)
  4997. {
  4998. u64 logical = U64_MAX;
  4999. lockdep_assert_held(&fs_info->reloc_mutex);
  5000. if (fs_info->reloc_ctl && fs_info->reloc_ctl->block_group)
  5001. logical = fs_info->reloc_ctl->block_group->start;
  5002. return logical;
  5003. }
  5004. static int insert_remap_item(struct btrfs_trans_handle *trans, struct btrfs_path *path,
  5005. u64 old_addr, u64 length, u64 new_addr)
  5006. {
  5007. int ret;
  5008. struct btrfs_fs_info *fs_info = trans->fs_info;
  5009. struct btrfs_key key;
  5010. struct btrfs_remap_item remap = { 0 };
  5011. if (old_addr == new_addr) {
  5012. /* Add new identity remap item. */
  5013. key.objectid = old_addr;
  5014. key.type = BTRFS_IDENTITY_REMAP_KEY;
  5015. key.offset = length;
  5016. ret = btrfs_insert_empty_item(trans, fs_info->remap_root, path,
  5017. &key, 0);
  5018. if (ret)
  5019. return ret;
  5020. } else {
  5021. /* Add new remap item. */
  5022. key.objectid = old_addr;
  5023. key.type = BTRFS_REMAP_KEY;
  5024. key.offset = length;
  5025. ret = btrfs_insert_empty_item(trans, fs_info->remap_root,
  5026. path, &key, sizeof(struct btrfs_remap_item));
  5027. if (ret)
  5028. return ret;
  5029. btrfs_set_stack_remap_address(&remap, new_addr);
  5030. write_extent_buffer(path->nodes[0], &remap,
  5031. btrfs_item_ptr_offset(path->nodes[0], path->slots[0]),
  5032. sizeof(struct btrfs_remap_item));
  5033. btrfs_release_path(path);
  5034. /* Add new backref item. */
  5035. key.objectid = new_addr;
  5036. key.type = BTRFS_REMAP_BACKREF_KEY;
  5037. key.offset = length;
  5038. ret = btrfs_insert_empty_item(trans, fs_info->remap_root,
  5039. path, &key,
  5040. sizeof(struct btrfs_remap_item));
  5041. if (ret)
  5042. return ret;
  5043. btrfs_set_stack_remap_address(&remap, old_addr);
  5044. write_extent_buffer(path->nodes[0], &remap,
  5045. btrfs_item_ptr_offset(path->nodes[0], path->slots[0]),
  5046. sizeof(struct btrfs_remap_item));
  5047. }
  5048. btrfs_release_path(path);
  5049. return 0;
  5050. }
  5051. /*
  5052. * Punch a hole in the remap item or identity remap item pointed to by path,
  5053. * for the range [hole_start, hole_start + hole_length).
  5054. */
  5055. static int remove_range_from_remap_tree(struct btrfs_trans_handle *trans,
  5056. struct btrfs_path *path,
  5057. struct btrfs_block_group *bg,
  5058. u64 hole_start, u64 hole_length)
  5059. {
  5060. int ret;
  5061. struct btrfs_fs_info *fs_info = trans->fs_info;
  5062. struct extent_buffer *leaf = path->nodes[0];
  5063. struct btrfs_key key;
  5064. u64 hole_end, new_addr, remap_start, remap_length, remap_end;
  5065. u64 overlap_length;
  5066. bool is_identity_remap;
  5067. int identity_count_delta = 0;
  5068. hole_end = hole_start + hole_length;
  5069. btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
  5070. is_identity_remap = (key.type == BTRFS_IDENTITY_REMAP_KEY);
  5071. remap_start = key.objectid;
  5072. remap_length = key.offset;
  5073. remap_end = remap_start + remap_length;
  5074. if (is_identity_remap) {
  5075. new_addr = remap_start;
  5076. } else {
  5077. struct btrfs_remap_item *remap_ptr;
  5078. remap_ptr = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_remap_item);
  5079. new_addr = btrfs_remap_address(leaf, remap_ptr);
  5080. }
  5081. /* Delete old item. */
  5082. ret = btrfs_del_item(trans, fs_info->remap_root, path);
  5083. btrfs_release_path(path);
  5084. if (ret)
  5085. return ret;
  5086. if (is_identity_remap) {
  5087. identity_count_delta = -1;
  5088. } else {
  5089. /* Remove backref. */
  5090. key.objectid = new_addr;
  5091. key.type = BTRFS_REMAP_BACKREF_KEY;
  5092. key.offset = remap_length;
  5093. ret = btrfs_search_slot(trans, fs_info->remap_root, &key, path, -1, 1);
  5094. if (ret) {
  5095. if (ret == 1) {
  5096. btrfs_release_path(path);
  5097. ret = -ENOENT;
  5098. }
  5099. return ret;
  5100. }
  5101. ret = btrfs_del_item(trans, fs_info->remap_root, path);
  5102. btrfs_release_path(path);
  5103. if (ret)
  5104. return ret;
  5105. }
  5106. /* If hole_start > remap_start, re-add the start of the remap item. */
  5107. if (hole_start > remap_start) {
  5108. ret = insert_remap_item(trans, path, remap_start,
  5109. hole_start - remap_start, new_addr);
  5110. if (ret)
  5111. return ret;
  5112. if (is_identity_remap)
  5113. identity_count_delta++;
  5114. }
  5115. /* If hole_end < remap_end, re-add the end of the remap item. */
  5116. if (hole_end < remap_end) {
  5117. ret = insert_remap_item(trans, path, hole_end,
  5118. remap_end - hole_end,
  5119. hole_end - remap_start + new_addr);
  5120. if (ret)
  5121. return ret;
  5122. if (is_identity_remap)
  5123. identity_count_delta++;
  5124. }
  5125. if (identity_count_delta != 0)
  5126. adjust_identity_remap_count(trans, bg, identity_count_delta);
  5127. overlap_length = min_t(u64, hole_end, remap_end) -
  5128. max_t(u64, hole_start, remap_start);
  5129. if (!is_identity_remap) {
  5130. struct btrfs_block_group *dest_bg;
  5131. dest_bg = btrfs_lookup_block_group(fs_info, new_addr);
  5132. if (unlikely(!dest_bg))
  5133. return -EUCLEAN;
  5134. adjust_block_group_remap_bytes(trans, dest_bg, -overlap_length);
  5135. btrfs_put_block_group(dest_bg);
  5136. ret = btrfs_add_to_free_space_tree(trans,
  5137. hole_start - remap_start + new_addr,
  5138. overlap_length);
  5139. if (ret)
  5140. return ret;
  5141. }
  5142. ret = overlap_length;
  5143. return ret;
  5144. }
  5145. /*
  5146. * Return 1 if remove_range_from_remap_tree() has been called successfully,
  5147. * 0 if block group wasn't remapped, and a negative number on error.
  5148. */
  5149. int btrfs_remove_extent_from_remap_tree(struct btrfs_trans_handle *trans,
  5150. struct btrfs_path *path,
  5151. u64 bytenr, u64 num_bytes)
  5152. {
  5153. struct btrfs_fs_info *fs_info = trans->fs_info;
  5154. struct btrfs_key key, found_key;
  5155. struct extent_buffer *leaf;
  5156. struct btrfs_block_group *bg;
  5157. int ret, length;
  5158. if (!(btrfs_super_incompat_flags(fs_info->super_copy) &
  5159. BTRFS_FEATURE_INCOMPAT_REMAP_TREE))
  5160. return 0;
  5161. bg = btrfs_lookup_block_group(fs_info, bytenr);
  5162. if (!bg)
  5163. return 0;
  5164. mutex_lock(&fs_info->remap_mutex);
  5165. if (!(bg->flags & BTRFS_BLOCK_GROUP_REMAPPED)) {
  5166. mutex_unlock(&fs_info->remap_mutex);
  5167. btrfs_put_block_group(bg);
  5168. return 0;
  5169. }
  5170. do {
  5171. key.objectid = bytenr;
  5172. key.type = (u8)-1;
  5173. key.offset = (u64)-1;
  5174. ret = btrfs_search_slot(trans, fs_info->remap_root, &key, path, -1, 1);
  5175. if (ret < 0)
  5176. goto end;
  5177. leaf = path->nodes[0];
  5178. if (path->slots[0] == 0) {
  5179. ret = -ENOENT;
  5180. goto end;
  5181. }
  5182. path->slots[0]--;
  5183. btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
  5184. if (found_key.type != BTRFS_IDENTITY_REMAP_KEY &&
  5185. found_key.type != BTRFS_REMAP_KEY) {
  5186. ret = -ENOENT;
  5187. goto end;
  5188. }
  5189. if (bytenr < found_key.objectid ||
  5190. bytenr >= found_key.objectid + found_key.offset) {
  5191. ret = -ENOENT;
  5192. goto end;
  5193. }
  5194. length = remove_range_from_remap_tree(trans, path, bg, bytenr, num_bytes);
  5195. if (length < 0) {
  5196. ret = length;
  5197. goto end;
  5198. }
  5199. bytenr += length;
  5200. num_bytes -= length;
  5201. } while (num_bytes > 0);
  5202. ret = 1;
  5203. end:
  5204. mutex_unlock(&fs_info->remap_mutex);
  5205. btrfs_put_block_group(bg);
  5206. btrfs_release_path(path);
  5207. return ret;
  5208. }