disk-io.c 131 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Copyright (C) 2007 Oracle. All rights reserved.
  4. */
  5. #include <linux/fs.h>
  6. #include <linux/blkdev.h>
  7. #include <linux/radix-tree.h>
  8. #include <linux/writeback.h>
  9. #include <linux/workqueue.h>
  10. #include <linux/kthread.h>
  11. #include <linux/slab.h>
  12. #include <linux/migrate.h>
  13. #include <linux/ratelimit.h>
  14. #include <linux/uuid.h>
  15. #include <linux/semaphore.h>
  16. #include <linux/error-injection.h>
  17. #include <linux/crc32c.h>
  18. #include <linux/sched/mm.h>
  19. #include <asm/unaligned.h>
  20. #include <crypto/hash.h>
  21. #include "ctree.h"
  22. #include "disk-io.h"
  23. #include "transaction.h"
  24. #include "btrfs_inode.h"
  25. #include "volumes.h"
  26. #include "print-tree.h"
  27. #include "locking.h"
  28. #include "tree-log.h"
  29. #include "free-space-cache.h"
  30. #include "free-space-tree.h"
  31. #include "inode-map.h"
  32. #include "check-integrity.h"
  33. #include "rcu-string.h"
  34. #include "dev-replace.h"
  35. #include "raid56.h"
  36. #include "sysfs.h"
  37. #include "qgroup.h"
  38. #include "compression.h"
  39. #include "tree-checker.h"
  40. #include "ref-verify.h"
  41. #include "block-group.h"
  42. #include "discard.h"
  43. #include "space-info.h"
  44. #define BTRFS_SUPER_FLAG_SUPP (BTRFS_HEADER_FLAG_WRITTEN |\
  45. BTRFS_HEADER_FLAG_RELOC |\
  46. BTRFS_SUPER_FLAG_ERROR |\
  47. BTRFS_SUPER_FLAG_SEEDING |\
  48. BTRFS_SUPER_FLAG_METADUMP |\
  49. BTRFS_SUPER_FLAG_METADUMP_V2)
  50. static void end_workqueue_fn(struct btrfs_work *work);
  51. static void btrfs_destroy_ordered_extents(struct btrfs_root *root);
  52. static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
  53. struct btrfs_fs_info *fs_info);
  54. static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root);
  55. static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
  56. struct extent_io_tree *dirty_pages,
  57. int mark);
  58. static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
  59. struct extent_io_tree *pinned_extents);
  60. static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info);
  61. static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info);
  62. /*
  63. * btrfs_end_io_wq structs are used to do processing in task context when an IO
  64. * is complete. This is used during reads to verify checksums, and it is used
  65. * by writes to insert metadata for new file extents after IO is complete.
  66. */
  67. struct btrfs_end_io_wq {
  68. struct bio *bio;
  69. bio_end_io_t *end_io;
  70. void *private;
  71. struct btrfs_fs_info *info;
  72. blk_status_t status;
  73. enum btrfs_wq_endio_type metadata;
  74. struct btrfs_work work;
  75. };
  76. static struct kmem_cache *btrfs_end_io_wq_cache;
  77. int __init btrfs_end_io_wq_init(void)
  78. {
  79. btrfs_end_io_wq_cache = kmem_cache_create("btrfs_end_io_wq",
  80. sizeof(struct btrfs_end_io_wq),
  81. 0,
  82. SLAB_MEM_SPREAD,
  83. NULL);
  84. if (!btrfs_end_io_wq_cache)
  85. return -ENOMEM;
  86. return 0;
  87. }
  88. void __cold btrfs_end_io_wq_exit(void)
  89. {
  90. kmem_cache_destroy(btrfs_end_io_wq_cache);
  91. }
  92. static void btrfs_free_csum_hash(struct btrfs_fs_info *fs_info)
  93. {
  94. if (fs_info->csum_shash)
  95. crypto_free_shash(fs_info->csum_shash);
  96. }
  97. /*
  98. * async submit bios are used to offload expensive checksumming
  99. * onto the worker threads. They checksum file and metadata bios
  100. * just before they are sent down the IO stack.
  101. */
  102. struct async_submit_bio {
  103. void *private_data;
  104. struct bio *bio;
  105. extent_submit_bio_start_t *submit_bio_start;
  106. int mirror_num;
  107. /*
  108. * bio_offset is optional, can be used if the pages in the bio
  109. * can't tell us where in the file the bio should go
  110. */
  111. u64 bio_offset;
  112. struct btrfs_work work;
  113. blk_status_t status;
  114. };
  115. /*
  116. * Lockdep class keys for extent_buffer->lock's in this root. For a given
  117. * eb, the lockdep key is determined by the btrfs_root it belongs to and
  118. * the level the eb occupies in the tree.
  119. *
  120. * Different roots are used for different purposes and may nest inside each
  121. * other and they require separate keysets. As lockdep keys should be
  122. * static, assign keysets according to the purpose of the root as indicated
  123. * by btrfs_root->root_key.objectid. This ensures that all special purpose
  124. * roots have separate keysets.
  125. *
  126. * Lock-nesting across peer nodes is always done with the immediate parent
  127. * node locked thus preventing deadlock. As lockdep doesn't know this, use
  128. * subclass to avoid triggering lockdep warning in such cases.
  129. *
  130. * The key is set by the readpage_end_io_hook after the buffer has passed
  131. * csum validation but before the pages are unlocked. It is also set by
  132. * btrfs_init_new_buffer on freshly allocated blocks.
  133. *
  134. * We also add a check to make sure the highest level of the tree is the
  135. * same as our lockdep setup here. If BTRFS_MAX_LEVEL changes, this code
  136. * needs update as well.
  137. */
  138. #ifdef CONFIG_DEBUG_LOCK_ALLOC
  139. # if BTRFS_MAX_LEVEL != 8
  140. # error
  141. # endif
  142. static struct btrfs_lockdep_keyset {
  143. u64 id; /* root objectid */
  144. const char *name_stem; /* lock name stem */
  145. char names[BTRFS_MAX_LEVEL + 1][20];
  146. struct lock_class_key keys[BTRFS_MAX_LEVEL + 1];
  147. } btrfs_lockdep_keysets[] = {
  148. { .id = BTRFS_ROOT_TREE_OBJECTID, .name_stem = "root" },
  149. { .id = BTRFS_EXTENT_TREE_OBJECTID, .name_stem = "extent" },
  150. { .id = BTRFS_CHUNK_TREE_OBJECTID, .name_stem = "chunk" },
  151. { .id = BTRFS_DEV_TREE_OBJECTID, .name_stem = "dev" },
  152. { .id = BTRFS_FS_TREE_OBJECTID, .name_stem = "fs" },
  153. { .id = BTRFS_CSUM_TREE_OBJECTID, .name_stem = "csum" },
  154. { .id = BTRFS_QUOTA_TREE_OBJECTID, .name_stem = "quota" },
  155. { .id = BTRFS_TREE_LOG_OBJECTID, .name_stem = "log" },
  156. { .id = BTRFS_TREE_RELOC_OBJECTID, .name_stem = "treloc" },
  157. { .id = BTRFS_DATA_RELOC_TREE_OBJECTID, .name_stem = "dreloc" },
  158. { .id = BTRFS_UUID_TREE_OBJECTID, .name_stem = "uuid" },
  159. { .id = BTRFS_FREE_SPACE_TREE_OBJECTID, .name_stem = "free-space" },
  160. { .id = 0, .name_stem = "tree" },
  161. };
  162. void __init btrfs_init_lockdep(void)
  163. {
  164. int i, j;
  165. /* initialize lockdep class names */
  166. for (i = 0; i < ARRAY_SIZE(btrfs_lockdep_keysets); i++) {
  167. struct btrfs_lockdep_keyset *ks = &btrfs_lockdep_keysets[i];
  168. for (j = 0; j < ARRAY_SIZE(ks->names); j++)
  169. snprintf(ks->names[j], sizeof(ks->names[j]),
  170. "btrfs-%s-%02d", ks->name_stem, j);
  171. }
  172. }
  173. void btrfs_set_buffer_lockdep_class(u64 objectid, struct extent_buffer *eb,
  174. int level)
  175. {
  176. struct btrfs_lockdep_keyset *ks;
  177. BUG_ON(level >= ARRAY_SIZE(ks->keys));
  178. /* find the matching keyset, id 0 is the default entry */
  179. for (ks = btrfs_lockdep_keysets; ks->id; ks++)
  180. if (ks->id == objectid)
  181. break;
  182. lockdep_set_class_and_name(&eb->lock,
  183. &ks->keys[level], ks->names[level]);
  184. }
  185. #endif
  186. /*
  187. * Compute the csum of a btree block and store the result to provided buffer.
  188. */
  189. static void csum_tree_block(struct extent_buffer *buf, u8 *result)
  190. {
  191. struct btrfs_fs_info *fs_info = buf->fs_info;
  192. const int num_pages = fs_info->nodesize >> PAGE_SHIFT;
  193. SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
  194. char *kaddr;
  195. int i;
  196. shash->tfm = fs_info->csum_shash;
  197. crypto_shash_init(shash);
  198. kaddr = page_address(buf->pages[0]);
  199. crypto_shash_update(shash, kaddr + BTRFS_CSUM_SIZE,
  200. PAGE_SIZE - BTRFS_CSUM_SIZE);
  201. for (i = 1; i < num_pages; i++) {
  202. kaddr = page_address(buf->pages[i]);
  203. crypto_shash_update(shash, kaddr, PAGE_SIZE);
  204. }
  205. memset(result, 0, BTRFS_CSUM_SIZE);
  206. crypto_shash_final(shash, result);
  207. }
  208. /*
  209. * we can't consider a given block up to date unless the transid of the
  210. * block matches the transid in the parent node's pointer. This is how we
  211. * detect blocks that either didn't get written at all or got written
  212. * in the wrong place.
  213. */
  214. static int verify_parent_transid(struct extent_io_tree *io_tree,
  215. struct extent_buffer *eb, u64 parent_transid,
  216. int atomic)
  217. {
  218. struct extent_state *cached_state = NULL;
  219. int ret;
  220. bool need_lock = (current->journal_info == BTRFS_SEND_TRANS_STUB);
  221. if (!parent_transid || btrfs_header_generation(eb) == parent_transid)
  222. return 0;
  223. if (atomic)
  224. return -EAGAIN;
  225. if (need_lock) {
  226. btrfs_tree_read_lock(eb);
  227. btrfs_set_lock_blocking_read(eb);
  228. }
  229. lock_extent_bits(io_tree, eb->start, eb->start + eb->len - 1,
  230. &cached_state);
  231. if (extent_buffer_uptodate(eb) &&
  232. btrfs_header_generation(eb) == parent_transid) {
  233. ret = 0;
  234. goto out;
  235. }
  236. btrfs_err_rl(eb->fs_info,
  237. "parent transid verify failed on %llu wanted %llu found %llu",
  238. eb->start,
  239. parent_transid, btrfs_header_generation(eb));
  240. ret = 1;
  241. /*
  242. * Things reading via commit roots that don't have normal protection,
  243. * like send, can have a really old block in cache that may point at a
  244. * block that has been freed and re-allocated. So don't clear uptodate
  245. * if we find an eb that is under IO (dirty/writeback) because we could
  246. * end up reading in the stale data and then writing it back out and
  247. * making everybody very sad.
  248. */
  249. if (!extent_buffer_under_io(eb))
  250. clear_extent_buffer_uptodate(eb);
  251. out:
  252. unlock_extent_cached(io_tree, eb->start, eb->start + eb->len - 1,
  253. &cached_state);
  254. if (need_lock)
  255. btrfs_tree_read_unlock_blocking(eb);
  256. return ret;
  257. }
  258. static bool btrfs_supported_super_csum(u16 csum_type)
  259. {
  260. switch (csum_type) {
  261. case BTRFS_CSUM_TYPE_CRC32:
  262. case BTRFS_CSUM_TYPE_XXHASH:
  263. case BTRFS_CSUM_TYPE_SHA256:
  264. case BTRFS_CSUM_TYPE_BLAKE2:
  265. return true;
  266. default:
  267. return false;
  268. }
  269. }
  270. /*
  271. * Return 0 if the superblock checksum type matches the checksum value of that
  272. * algorithm. Pass the raw disk superblock data.
  273. */
  274. static int btrfs_check_super_csum(struct btrfs_fs_info *fs_info,
  275. char *raw_disk_sb)
  276. {
  277. struct btrfs_super_block *disk_sb =
  278. (struct btrfs_super_block *)raw_disk_sb;
  279. char result[BTRFS_CSUM_SIZE];
  280. SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
  281. shash->tfm = fs_info->csum_shash;
  282. /*
  283. * The super_block structure does not span the whole
  284. * BTRFS_SUPER_INFO_SIZE range, we expect that the unused space is
  285. * filled with zeros and is included in the checksum.
  286. */
  287. crypto_shash_digest(shash, raw_disk_sb + BTRFS_CSUM_SIZE,
  288. BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE, result);
  289. if (memcmp(disk_sb->csum, result, btrfs_super_csum_size(disk_sb)))
  290. return 1;
  291. return 0;
  292. }
  293. int btrfs_verify_level_key(struct extent_buffer *eb, int level,
  294. struct btrfs_key *first_key, u64 parent_transid)
  295. {
  296. struct btrfs_fs_info *fs_info = eb->fs_info;
  297. int found_level;
  298. struct btrfs_key found_key;
  299. int ret;
  300. found_level = btrfs_header_level(eb);
  301. if (found_level != level) {
  302. WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
  303. KERN_ERR "BTRFS: tree level check failed\n");
  304. btrfs_err(fs_info,
  305. "tree level mismatch detected, bytenr=%llu level expected=%u has=%u",
  306. eb->start, level, found_level);
  307. return -EIO;
  308. }
  309. if (!first_key)
  310. return 0;
  311. /*
  312. * For live tree block (new tree blocks in current transaction),
  313. * we need proper lock context to avoid race, which is impossible here.
  314. * So we only checks tree blocks which is read from disk, whose
  315. * generation <= fs_info->last_trans_committed.
  316. */
  317. if (btrfs_header_generation(eb) > fs_info->last_trans_committed)
  318. return 0;
  319. /* We have @first_key, so this @eb must have at least one item */
  320. if (btrfs_header_nritems(eb) == 0) {
  321. btrfs_err(fs_info,
  322. "invalid tree nritems, bytenr=%llu nritems=0 expect >0",
  323. eb->start);
  324. WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
  325. return -EUCLEAN;
  326. }
  327. if (found_level)
  328. btrfs_node_key_to_cpu(eb, &found_key, 0);
  329. else
  330. btrfs_item_key_to_cpu(eb, &found_key, 0);
  331. ret = btrfs_comp_cpu_keys(first_key, &found_key);
  332. if (ret) {
  333. WARN(IS_ENABLED(CONFIG_BTRFS_DEBUG),
  334. KERN_ERR "BTRFS: tree first key check failed\n");
  335. btrfs_err(fs_info,
  336. "tree first key mismatch detected, bytenr=%llu parent_transid=%llu key expected=(%llu,%u,%llu) has=(%llu,%u,%llu)",
  337. eb->start, parent_transid, first_key->objectid,
  338. first_key->type, first_key->offset,
  339. found_key.objectid, found_key.type,
  340. found_key.offset);
  341. }
  342. return ret;
  343. }
  344. /*
  345. * helper to read a given tree block, doing retries as required when
  346. * the checksums don't match and we have alternate mirrors to try.
  347. *
  348. * @parent_transid: expected transid, skip check if 0
  349. * @level: expected level, mandatory check
  350. * @first_key: expected key of first slot, skip check if NULL
  351. */
  352. static int btree_read_extent_buffer_pages(struct extent_buffer *eb,
  353. u64 parent_transid, int level,
  354. struct btrfs_key *first_key)
  355. {
  356. struct btrfs_fs_info *fs_info = eb->fs_info;
  357. struct extent_io_tree *io_tree;
  358. int failed = 0;
  359. int ret;
  360. int num_copies = 0;
  361. int mirror_num = 0;
  362. int failed_mirror = 0;
  363. io_tree = &BTRFS_I(fs_info->btree_inode)->io_tree;
  364. while (1) {
  365. clear_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
  366. ret = read_extent_buffer_pages(eb, WAIT_COMPLETE, mirror_num);
  367. if (!ret) {
  368. if (verify_parent_transid(io_tree, eb,
  369. parent_transid, 0))
  370. ret = -EIO;
  371. else if (btrfs_verify_level_key(eb, level,
  372. first_key, parent_transid))
  373. ret = -EUCLEAN;
  374. else
  375. break;
  376. }
  377. num_copies = btrfs_num_copies(fs_info,
  378. eb->start, eb->len);
  379. if (num_copies == 1)
  380. break;
  381. if (!failed_mirror) {
  382. failed = 1;
  383. failed_mirror = eb->read_mirror;
  384. }
  385. mirror_num++;
  386. if (mirror_num == failed_mirror)
  387. mirror_num++;
  388. if (mirror_num > num_copies)
  389. break;
  390. }
  391. if (failed && !ret && failed_mirror)
  392. btrfs_repair_eb_io_failure(eb, failed_mirror);
  393. return ret;
  394. }
  395. /*
  396. * checksum a dirty tree block before IO. This has extra checks to make sure
  397. * we only fill in the checksum field in the first page of a multi-page block
  398. */
  399. static int csum_dirty_buffer(struct btrfs_fs_info *fs_info, struct page *page)
  400. {
  401. u64 start = page_offset(page);
  402. u64 found_start;
  403. u8 result[BTRFS_CSUM_SIZE];
  404. u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
  405. struct extent_buffer *eb;
  406. int ret;
  407. eb = (struct extent_buffer *)page->private;
  408. if (page != eb->pages[0])
  409. return 0;
  410. found_start = btrfs_header_bytenr(eb);
  411. /*
  412. * Please do not consolidate these warnings into a single if.
  413. * It is useful to know what went wrong.
  414. */
  415. if (WARN_ON(found_start != start))
  416. return -EUCLEAN;
  417. if (WARN_ON(!PageUptodate(page)))
  418. return -EUCLEAN;
  419. ASSERT(memcmp_extent_buffer(eb, fs_info->fs_devices->metadata_uuid,
  420. offsetof(struct btrfs_header, fsid),
  421. BTRFS_FSID_SIZE) == 0);
  422. csum_tree_block(eb, result);
  423. if (btrfs_header_level(eb))
  424. ret = btrfs_check_node(eb);
  425. else
  426. ret = btrfs_check_leaf_full(eb);
  427. if (ret < 0) {
  428. btrfs_print_tree(eb, 0);
  429. btrfs_err(fs_info,
  430. "block=%llu write time tree block corruption detected",
  431. eb->start);
  432. WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
  433. return ret;
  434. }
  435. write_extent_buffer(eb, result, 0, csum_size);
  436. return 0;
  437. }
  438. static int check_tree_block_fsid(struct extent_buffer *eb)
  439. {
  440. struct btrfs_fs_info *fs_info = eb->fs_info;
  441. struct btrfs_fs_devices *fs_devices = fs_info->fs_devices, *seed_devs;
  442. u8 fsid[BTRFS_FSID_SIZE];
  443. u8 *metadata_uuid;
  444. read_extent_buffer(eb, fsid, offsetof(struct btrfs_header, fsid),
  445. BTRFS_FSID_SIZE);
  446. /*
  447. * Checking the incompat flag is only valid for the current fs. For
  448. * seed devices it's forbidden to have their uuid changed so reading
  449. * ->fsid in this case is fine
  450. */
  451. if (btrfs_fs_incompat(fs_info, METADATA_UUID))
  452. metadata_uuid = fs_devices->metadata_uuid;
  453. else
  454. metadata_uuid = fs_devices->fsid;
  455. if (!memcmp(fsid, metadata_uuid, BTRFS_FSID_SIZE))
  456. return 0;
  457. list_for_each_entry(seed_devs, &fs_devices->seed_list, seed_list)
  458. if (!memcmp(fsid, seed_devs->fsid, BTRFS_FSID_SIZE))
  459. return 0;
  460. return 1;
  461. }
  462. int btrfs_validate_metadata_buffer(struct btrfs_io_bio *io_bio, u64 phy_offset,
  463. struct page *page, u64 start, u64 end,
  464. int mirror)
  465. {
  466. u64 found_start;
  467. int found_level;
  468. struct extent_buffer *eb;
  469. struct btrfs_fs_info *fs_info;
  470. u16 csum_size;
  471. int ret = 0;
  472. u8 result[BTRFS_CSUM_SIZE];
  473. int reads_done;
  474. if (!page->private)
  475. goto out;
  476. eb = (struct extent_buffer *)page->private;
  477. fs_info = eb->fs_info;
  478. csum_size = btrfs_super_csum_size(fs_info->super_copy);
  479. /* the pending IO might have been the only thing that kept this buffer
  480. * in memory. Make sure we have a ref for all this other checks
  481. */
  482. atomic_inc(&eb->refs);
  483. reads_done = atomic_dec_and_test(&eb->io_pages);
  484. if (!reads_done)
  485. goto err;
  486. eb->read_mirror = mirror;
  487. if (test_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags)) {
  488. ret = -EIO;
  489. goto err;
  490. }
  491. found_start = btrfs_header_bytenr(eb);
  492. if (found_start != eb->start) {
  493. btrfs_err_rl(fs_info, "bad tree block start, want %llu have %llu",
  494. eb->start, found_start);
  495. ret = -EIO;
  496. goto err;
  497. }
  498. if (check_tree_block_fsid(eb)) {
  499. btrfs_err_rl(fs_info, "bad fsid on block %llu",
  500. eb->start);
  501. ret = -EIO;
  502. goto err;
  503. }
  504. found_level = btrfs_header_level(eb);
  505. if (found_level >= BTRFS_MAX_LEVEL) {
  506. btrfs_err(fs_info, "bad tree block level %d on %llu",
  507. (int)btrfs_header_level(eb), eb->start);
  508. ret = -EIO;
  509. goto err;
  510. }
  511. btrfs_set_buffer_lockdep_class(btrfs_header_owner(eb),
  512. eb, found_level);
  513. csum_tree_block(eb, result);
  514. if (memcmp_extent_buffer(eb, result, 0, csum_size)) {
  515. u8 val[BTRFS_CSUM_SIZE] = { 0 };
  516. read_extent_buffer(eb, &val, 0, csum_size);
  517. btrfs_warn_rl(fs_info,
  518. "%s checksum verify failed on %llu wanted " CSUM_FMT " found " CSUM_FMT " level %d",
  519. fs_info->sb->s_id, eb->start,
  520. CSUM_FMT_VALUE(csum_size, val),
  521. CSUM_FMT_VALUE(csum_size, result),
  522. btrfs_header_level(eb));
  523. ret = -EUCLEAN;
  524. goto err;
  525. }
  526. /*
  527. * If this is a leaf block and it is corrupt, set the corrupt bit so
  528. * that we don't try and read the other copies of this block, just
  529. * return -EIO.
  530. */
  531. if (found_level == 0 && btrfs_check_leaf_full(eb)) {
  532. set_bit(EXTENT_BUFFER_CORRUPT, &eb->bflags);
  533. ret = -EIO;
  534. }
  535. if (found_level > 0 && btrfs_check_node(eb))
  536. ret = -EIO;
  537. if (!ret)
  538. set_extent_buffer_uptodate(eb);
  539. else
  540. btrfs_err(fs_info,
  541. "block=%llu read time tree block corruption detected",
  542. eb->start);
  543. err:
  544. if (reads_done &&
  545. test_and_clear_bit(EXTENT_BUFFER_READAHEAD, &eb->bflags))
  546. btree_readahead_hook(eb, ret);
  547. if (ret) {
  548. /*
  549. * our io error hook is going to dec the io pages
  550. * again, we have to make sure it has something
  551. * to decrement
  552. */
  553. atomic_inc(&eb->io_pages);
  554. clear_extent_buffer_uptodate(eb);
  555. }
  556. free_extent_buffer(eb);
  557. out:
  558. return ret;
  559. }
  560. static void end_workqueue_bio(struct bio *bio)
  561. {
  562. struct btrfs_end_io_wq *end_io_wq = bio->bi_private;
  563. struct btrfs_fs_info *fs_info;
  564. struct btrfs_workqueue *wq;
  565. fs_info = end_io_wq->info;
  566. end_io_wq->status = bio->bi_status;
  567. if (bio_op(bio) == REQ_OP_WRITE) {
  568. if (end_io_wq->metadata == BTRFS_WQ_ENDIO_METADATA)
  569. wq = fs_info->endio_meta_write_workers;
  570. else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_FREE_SPACE)
  571. wq = fs_info->endio_freespace_worker;
  572. else if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56)
  573. wq = fs_info->endio_raid56_workers;
  574. else
  575. wq = fs_info->endio_write_workers;
  576. } else {
  577. if (end_io_wq->metadata == BTRFS_WQ_ENDIO_RAID56)
  578. wq = fs_info->endio_raid56_workers;
  579. else if (end_io_wq->metadata)
  580. wq = fs_info->endio_meta_workers;
  581. else
  582. wq = fs_info->endio_workers;
  583. }
  584. btrfs_init_work(&end_io_wq->work, end_workqueue_fn, NULL, NULL);
  585. btrfs_queue_work(wq, &end_io_wq->work);
  586. }
  587. blk_status_t btrfs_bio_wq_end_io(struct btrfs_fs_info *info, struct bio *bio,
  588. enum btrfs_wq_endio_type metadata)
  589. {
  590. struct btrfs_end_io_wq *end_io_wq;
  591. end_io_wq = kmem_cache_alloc(btrfs_end_io_wq_cache, GFP_NOFS);
  592. if (!end_io_wq)
  593. return BLK_STS_RESOURCE;
  594. end_io_wq->private = bio->bi_private;
  595. end_io_wq->end_io = bio->bi_end_io;
  596. end_io_wq->info = info;
  597. end_io_wq->status = 0;
  598. end_io_wq->bio = bio;
  599. end_io_wq->metadata = metadata;
  600. bio->bi_private = end_io_wq;
  601. bio->bi_end_io = end_workqueue_bio;
  602. return 0;
  603. }
  604. static void run_one_async_start(struct btrfs_work *work)
  605. {
  606. struct async_submit_bio *async;
  607. blk_status_t ret;
  608. async = container_of(work, struct async_submit_bio, work);
  609. ret = async->submit_bio_start(async->private_data, async->bio,
  610. async->bio_offset);
  611. if (ret)
  612. async->status = ret;
  613. }
  614. /*
  615. * In order to insert checksums into the metadata in large chunks, we wait
  616. * until bio submission time. All the pages in the bio are checksummed and
  617. * sums are attached onto the ordered extent record.
  618. *
  619. * At IO completion time the csums attached on the ordered extent record are
  620. * inserted into the tree.
  621. */
  622. static void run_one_async_done(struct btrfs_work *work)
  623. {
  624. struct async_submit_bio *async;
  625. struct inode *inode;
  626. blk_status_t ret;
  627. async = container_of(work, struct async_submit_bio, work);
  628. inode = async->private_data;
  629. /* If an error occurred we just want to clean up the bio and move on */
  630. if (async->status) {
  631. async->bio->bi_status = async->status;
  632. bio_endio(async->bio);
  633. return;
  634. }
  635. /*
  636. * All of the bios that pass through here are from async helpers.
  637. * Use REQ_CGROUP_PUNT to issue them from the owning cgroup's context.
  638. * This changes nothing when cgroups aren't in use.
  639. */
  640. async->bio->bi_opf |= REQ_CGROUP_PUNT;
  641. ret = btrfs_map_bio(btrfs_sb(inode->i_sb), async->bio, async->mirror_num);
  642. if (ret) {
  643. async->bio->bi_status = ret;
  644. bio_endio(async->bio);
  645. }
  646. }
  647. static void run_one_async_free(struct btrfs_work *work)
  648. {
  649. struct async_submit_bio *async;
  650. async = container_of(work, struct async_submit_bio, work);
  651. kfree(async);
  652. }
  653. blk_status_t btrfs_wq_submit_bio(struct btrfs_fs_info *fs_info, struct bio *bio,
  654. int mirror_num, unsigned long bio_flags,
  655. u64 bio_offset, void *private_data,
  656. extent_submit_bio_start_t *submit_bio_start)
  657. {
  658. struct async_submit_bio *async;
  659. async = kmalloc(sizeof(*async), GFP_NOFS);
  660. if (!async)
  661. return BLK_STS_RESOURCE;
  662. async->private_data = private_data;
  663. async->bio = bio;
  664. async->mirror_num = mirror_num;
  665. async->submit_bio_start = submit_bio_start;
  666. btrfs_init_work(&async->work, run_one_async_start, run_one_async_done,
  667. run_one_async_free);
  668. async->bio_offset = bio_offset;
  669. async->status = 0;
  670. if (op_is_sync(bio->bi_opf))
  671. btrfs_set_work_high_priority(&async->work);
  672. btrfs_queue_work(fs_info->workers, &async->work);
  673. return 0;
  674. }
  675. static blk_status_t btree_csum_one_bio(struct bio *bio)
  676. {
  677. struct bio_vec *bvec;
  678. struct btrfs_root *root;
  679. int ret = 0;
  680. struct bvec_iter_all iter_all;
  681. ASSERT(!bio_flagged(bio, BIO_CLONED));
  682. bio_for_each_segment_all(bvec, bio, iter_all) {
  683. root = BTRFS_I(bvec->bv_page->mapping->host)->root;
  684. ret = csum_dirty_buffer(root->fs_info, bvec->bv_page);
  685. if (ret)
  686. break;
  687. }
  688. return errno_to_blk_status(ret);
  689. }
  690. static blk_status_t btree_submit_bio_start(void *private_data, struct bio *bio,
  691. u64 bio_offset)
  692. {
  693. /*
  694. * when we're called for a write, we're already in the async
  695. * submission context. Just jump into btrfs_map_bio
  696. */
  697. return btree_csum_one_bio(bio);
  698. }
  699. static int check_async_write(struct btrfs_fs_info *fs_info,
  700. struct btrfs_inode *bi)
  701. {
  702. if (atomic_read(&bi->sync_writers))
  703. return 0;
  704. if (test_bit(BTRFS_FS_CSUM_IMPL_FAST, &fs_info->flags))
  705. return 0;
  706. return 1;
  707. }
  708. blk_status_t btrfs_submit_metadata_bio(struct inode *inode, struct bio *bio,
  709. int mirror_num, unsigned long bio_flags)
  710. {
  711. struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
  712. int async = check_async_write(fs_info, BTRFS_I(inode));
  713. blk_status_t ret;
  714. if (bio_op(bio) != REQ_OP_WRITE) {
  715. /*
  716. * called for a read, do the setup so that checksum validation
  717. * can happen in the async kernel threads
  718. */
  719. ret = btrfs_bio_wq_end_io(fs_info, bio,
  720. BTRFS_WQ_ENDIO_METADATA);
  721. if (ret)
  722. goto out_w_error;
  723. ret = btrfs_map_bio(fs_info, bio, mirror_num);
  724. } else if (!async) {
  725. ret = btree_csum_one_bio(bio);
  726. if (ret)
  727. goto out_w_error;
  728. ret = btrfs_map_bio(fs_info, bio, mirror_num);
  729. } else {
  730. /*
  731. * kthread helpers are used to submit writes so that
  732. * checksumming can happen in parallel across all CPUs
  733. */
  734. ret = btrfs_wq_submit_bio(fs_info, bio, mirror_num, 0,
  735. 0, inode, btree_submit_bio_start);
  736. }
  737. if (ret)
  738. goto out_w_error;
  739. return 0;
  740. out_w_error:
  741. bio->bi_status = ret;
  742. bio_endio(bio);
  743. return ret;
  744. }
  745. #ifdef CONFIG_MIGRATION
  746. static int btree_migratepage(struct address_space *mapping,
  747. struct page *newpage, struct page *page,
  748. enum migrate_mode mode)
  749. {
  750. /*
  751. * we can't safely write a btree page from here,
  752. * we haven't done the locking hook
  753. */
  754. if (PageDirty(page))
  755. return -EAGAIN;
  756. /*
  757. * Buffers may be managed in a filesystem specific way.
  758. * We must have no buffers or drop them.
  759. */
  760. if (page_has_private(page) &&
  761. !try_to_release_page(page, GFP_KERNEL))
  762. return -EAGAIN;
  763. return migrate_page(mapping, newpage, page, mode);
  764. }
  765. #endif
  766. static int btree_writepages(struct address_space *mapping,
  767. struct writeback_control *wbc)
  768. {
  769. struct btrfs_fs_info *fs_info;
  770. int ret;
  771. if (wbc->sync_mode == WB_SYNC_NONE) {
  772. if (wbc->for_kupdate)
  773. return 0;
  774. fs_info = BTRFS_I(mapping->host)->root->fs_info;
  775. /* this is a bit racy, but that's ok */
  776. ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
  777. BTRFS_DIRTY_METADATA_THRESH,
  778. fs_info->dirty_metadata_batch);
  779. if (ret < 0)
  780. return 0;
  781. }
  782. return btree_write_cache_pages(mapping, wbc);
  783. }
  784. static int btree_releasepage(struct page *page, gfp_t gfp_flags)
  785. {
  786. if (PageWriteback(page) || PageDirty(page))
  787. return 0;
  788. return try_release_extent_buffer(page);
  789. }
  790. static void btree_invalidatepage(struct page *page, unsigned int offset,
  791. unsigned int length)
  792. {
  793. struct extent_io_tree *tree;
  794. tree = &BTRFS_I(page->mapping->host)->io_tree;
  795. extent_invalidatepage(tree, page, offset);
  796. btree_releasepage(page, GFP_NOFS);
  797. if (PagePrivate(page)) {
  798. btrfs_warn(BTRFS_I(page->mapping->host)->root->fs_info,
  799. "page private not zero on page %llu",
  800. (unsigned long long)page_offset(page));
  801. detach_page_private(page);
  802. }
  803. }
  804. static int btree_set_page_dirty(struct page *page)
  805. {
  806. #ifdef DEBUG
  807. struct extent_buffer *eb;
  808. BUG_ON(!PagePrivate(page));
  809. eb = (struct extent_buffer *)page->private;
  810. BUG_ON(!eb);
  811. BUG_ON(!test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
  812. BUG_ON(!atomic_read(&eb->refs));
  813. btrfs_assert_tree_locked(eb);
  814. #endif
  815. return __set_page_dirty_nobuffers(page);
  816. }
  817. static const struct address_space_operations btree_aops = {
  818. .writepages = btree_writepages,
  819. .releasepage = btree_releasepage,
  820. .invalidatepage = btree_invalidatepage,
  821. #ifdef CONFIG_MIGRATION
  822. .migratepage = btree_migratepage,
  823. #endif
  824. .set_page_dirty = btree_set_page_dirty,
  825. };
  826. void readahead_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr)
  827. {
  828. struct extent_buffer *buf = NULL;
  829. int ret;
  830. buf = btrfs_find_create_tree_block(fs_info, bytenr);
  831. if (IS_ERR(buf))
  832. return;
  833. ret = read_extent_buffer_pages(buf, WAIT_NONE, 0);
  834. if (ret < 0)
  835. free_extent_buffer_stale(buf);
  836. else
  837. free_extent_buffer(buf);
  838. }
  839. struct extent_buffer *btrfs_find_create_tree_block(
  840. struct btrfs_fs_info *fs_info,
  841. u64 bytenr)
  842. {
  843. if (btrfs_is_testing(fs_info))
  844. return alloc_test_extent_buffer(fs_info, bytenr);
  845. return alloc_extent_buffer(fs_info, bytenr);
  846. }
  847. /*
  848. * Read tree block at logical address @bytenr and do variant basic but critical
  849. * verification.
  850. *
  851. * @parent_transid: expected transid of this tree block, skip check if 0
  852. * @level: expected level, mandatory check
  853. * @first_key: expected key in slot 0, skip check if NULL
  854. */
  855. struct extent_buffer *read_tree_block(struct btrfs_fs_info *fs_info, u64 bytenr,
  856. u64 parent_transid, int level,
  857. struct btrfs_key *first_key)
  858. {
  859. struct extent_buffer *buf = NULL;
  860. int ret;
  861. buf = btrfs_find_create_tree_block(fs_info, bytenr);
  862. if (IS_ERR(buf))
  863. return buf;
  864. ret = btree_read_extent_buffer_pages(buf, parent_transid,
  865. level, first_key);
  866. if (ret) {
  867. free_extent_buffer_stale(buf);
  868. return ERR_PTR(ret);
  869. }
  870. return buf;
  871. }
  872. void btrfs_clean_tree_block(struct extent_buffer *buf)
  873. {
  874. struct btrfs_fs_info *fs_info = buf->fs_info;
  875. if (btrfs_header_generation(buf) ==
  876. fs_info->running_transaction->transid) {
  877. btrfs_assert_tree_locked(buf);
  878. if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &buf->bflags)) {
  879. percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
  880. -buf->len,
  881. fs_info->dirty_metadata_batch);
  882. /* ugh, clear_extent_buffer_dirty needs to lock the page */
  883. btrfs_set_lock_blocking_write(buf);
  884. clear_extent_buffer_dirty(buf);
  885. }
  886. }
  887. }
  888. static void __setup_root(struct btrfs_root *root, struct btrfs_fs_info *fs_info,
  889. u64 objectid)
  890. {
  891. bool dummy = test_bit(BTRFS_FS_STATE_DUMMY_FS_INFO, &fs_info->fs_state);
  892. root->fs_info = fs_info;
  893. root->node = NULL;
  894. root->commit_root = NULL;
  895. root->state = 0;
  896. root->orphan_cleanup_state = 0;
  897. root->last_trans = 0;
  898. root->highest_objectid = 0;
  899. root->nr_delalloc_inodes = 0;
  900. root->nr_ordered_extents = 0;
  901. root->inode_tree = RB_ROOT;
  902. INIT_RADIX_TREE(&root->delayed_nodes_tree, GFP_ATOMIC);
  903. root->block_rsv = NULL;
  904. INIT_LIST_HEAD(&root->dirty_list);
  905. INIT_LIST_HEAD(&root->root_list);
  906. INIT_LIST_HEAD(&root->delalloc_inodes);
  907. INIT_LIST_HEAD(&root->delalloc_root);
  908. INIT_LIST_HEAD(&root->ordered_extents);
  909. INIT_LIST_HEAD(&root->ordered_root);
  910. INIT_LIST_HEAD(&root->reloc_dirty_list);
  911. INIT_LIST_HEAD(&root->logged_list[0]);
  912. INIT_LIST_HEAD(&root->logged_list[1]);
  913. spin_lock_init(&root->inode_lock);
  914. spin_lock_init(&root->delalloc_lock);
  915. spin_lock_init(&root->ordered_extent_lock);
  916. spin_lock_init(&root->accounting_lock);
  917. spin_lock_init(&root->log_extents_lock[0]);
  918. spin_lock_init(&root->log_extents_lock[1]);
  919. spin_lock_init(&root->qgroup_meta_rsv_lock);
  920. mutex_init(&root->objectid_mutex);
  921. mutex_init(&root->log_mutex);
  922. mutex_init(&root->ordered_extent_mutex);
  923. mutex_init(&root->delalloc_mutex);
  924. init_waitqueue_head(&root->qgroup_flush_wait);
  925. init_waitqueue_head(&root->log_writer_wait);
  926. init_waitqueue_head(&root->log_commit_wait[0]);
  927. init_waitqueue_head(&root->log_commit_wait[1]);
  928. INIT_LIST_HEAD(&root->log_ctxs[0]);
  929. INIT_LIST_HEAD(&root->log_ctxs[1]);
  930. atomic_set(&root->log_commit[0], 0);
  931. atomic_set(&root->log_commit[1], 0);
  932. atomic_set(&root->log_writers, 0);
  933. atomic_set(&root->log_batch, 0);
  934. refcount_set(&root->refs, 1);
  935. atomic_set(&root->snapshot_force_cow, 0);
  936. atomic_set(&root->nr_swapfiles, 0);
  937. root->log_transid = 0;
  938. root->log_transid_committed = -1;
  939. root->last_log_commit = 0;
  940. if (!dummy) {
  941. extent_io_tree_init(fs_info, &root->dirty_log_pages,
  942. IO_TREE_ROOT_DIRTY_LOG_PAGES, NULL);
  943. extent_io_tree_init(fs_info, &root->log_csum_range,
  944. IO_TREE_LOG_CSUM_RANGE, NULL);
  945. }
  946. memset(&root->root_key, 0, sizeof(root->root_key));
  947. memset(&root->root_item, 0, sizeof(root->root_item));
  948. memset(&root->defrag_progress, 0, sizeof(root->defrag_progress));
  949. root->root_key.objectid = objectid;
  950. root->anon_dev = 0;
  951. spin_lock_init(&root->root_item_lock);
  952. btrfs_qgroup_init_swapped_blocks(&root->swapped_blocks);
  953. #ifdef CONFIG_BTRFS_DEBUG
  954. INIT_LIST_HEAD(&root->leak_list);
  955. spin_lock(&fs_info->fs_roots_radix_lock);
  956. list_add_tail(&root->leak_list, &fs_info->allocated_roots);
  957. spin_unlock(&fs_info->fs_roots_radix_lock);
  958. #endif
  959. }
  960. static struct btrfs_root *btrfs_alloc_root(struct btrfs_fs_info *fs_info,
  961. u64 objectid, gfp_t flags)
  962. {
  963. struct btrfs_root *root = kzalloc(sizeof(*root), flags);
  964. if (root)
  965. __setup_root(root, fs_info, objectid);
  966. return root;
  967. }
  968. #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
  969. /* Should only be used by the testing infrastructure */
  970. struct btrfs_root *btrfs_alloc_dummy_root(struct btrfs_fs_info *fs_info)
  971. {
  972. struct btrfs_root *root;
  973. if (!fs_info)
  974. return ERR_PTR(-EINVAL);
  975. root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID, GFP_KERNEL);
  976. if (!root)
  977. return ERR_PTR(-ENOMEM);
  978. /* We don't use the stripesize in selftest, set it as sectorsize */
  979. root->alloc_bytenr = 0;
  980. return root;
  981. }
  982. #endif
  983. struct btrfs_root *btrfs_create_tree(struct btrfs_trans_handle *trans,
  984. u64 objectid)
  985. {
  986. struct btrfs_fs_info *fs_info = trans->fs_info;
  987. struct extent_buffer *leaf;
  988. struct btrfs_root *tree_root = fs_info->tree_root;
  989. struct btrfs_root *root;
  990. struct btrfs_key key;
  991. unsigned int nofs_flag;
  992. int ret = 0;
  993. /*
  994. * We're holding a transaction handle, so use a NOFS memory allocation
  995. * context to avoid deadlock if reclaim happens.
  996. */
  997. nofs_flag = memalloc_nofs_save();
  998. root = btrfs_alloc_root(fs_info, objectid, GFP_KERNEL);
  999. memalloc_nofs_restore(nofs_flag);
  1000. if (!root)
  1001. return ERR_PTR(-ENOMEM);
  1002. root->root_key.objectid = objectid;
  1003. root->root_key.type = BTRFS_ROOT_ITEM_KEY;
  1004. root->root_key.offset = 0;
  1005. leaf = btrfs_alloc_tree_block(trans, root, 0, objectid, NULL, 0, 0, 0,
  1006. BTRFS_NESTING_NORMAL);
  1007. if (IS_ERR(leaf)) {
  1008. ret = PTR_ERR(leaf);
  1009. leaf = NULL;
  1010. goto fail;
  1011. }
  1012. root->node = leaf;
  1013. btrfs_mark_buffer_dirty(leaf);
  1014. root->commit_root = btrfs_root_node(root);
  1015. set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
  1016. root->root_item.flags = 0;
  1017. root->root_item.byte_limit = 0;
  1018. btrfs_set_root_bytenr(&root->root_item, leaf->start);
  1019. btrfs_set_root_generation(&root->root_item, trans->transid);
  1020. btrfs_set_root_level(&root->root_item, 0);
  1021. btrfs_set_root_refs(&root->root_item, 1);
  1022. btrfs_set_root_used(&root->root_item, leaf->len);
  1023. btrfs_set_root_last_snapshot(&root->root_item, 0);
  1024. btrfs_set_root_dirid(&root->root_item, 0);
  1025. if (is_fstree(objectid))
  1026. generate_random_guid(root->root_item.uuid);
  1027. else
  1028. export_guid(root->root_item.uuid, &guid_null);
  1029. root->root_item.drop_level = 0;
  1030. key.objectid = objectid;
  1031. key.type = BTRFS_ROOT_ITEM_KEY;
  1032. key.offset = 0;
  1033. ret = btrfs_insert_root(trans, tree_root, &key, &root->root_item);
  1034. if (ret)
  1035. goto fail;
  1036. btrfs_tree_unlock(leaf);
  1037. return root;
  1038. fail:
  1039. if (leaf)
  1040. btrfs_tree_unlock(leaf);
  1041. btrfs_put_root(root);
  1042. return ERR_PTR(ret);
  1043. }
  1044. static struct btrfs_root *alloc_log_tree(struct btrfs_trans_handle *trans,
  1045. struct btrfs_fs_info *fs_info)
  1046. {
  1047. struct btrfs_root *root;
  1048. struct extent_buffer *leaf;
  1049. root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID, GFP_NOFS);
  1050. if (!root)
  1051. return ERR_PTR(-ENOMEM);
  1052. root->root_key.objectid = BTRFS_TREE_LOG_OBJECTID;
  1053. root->root_key.type = BTRFS_ROOT_ITEM_KEY;
  1054. root->root_key.offset = BTRFS_TREE_LOG_OBJECTID;
  1055. /*
  1056. * DON'T set SHAREABLE bit for log trees.
  1057. *
  1058. * Log trees are not exposed to user space thus can't be snapshotted,
  1059. * and they go away before a real commit is actually done.
  1060. *
  1061. * They do store pointers to file data extents, and those reference
  1062. * counts still get updated (along with back refs to the log tree).
  1063. */
  1064. leaf = btrfs_alloc_tree_block(trans, root, 0, BTRFS_TREE_LOG_OBJECTID,
  1065. NULL, 0, 0, 0, BTRFS_NESTING_NORMAL);
  1066. if (IS_ERR(leaf)) {
  1067. btrfs_put_root(root);
  1068. return ERR_CAST(leaf);
  1069. }
  1070. root->node = leaf;
  1071. btrfs_mark_buffer_dirty(root->node);
  1072. btrfs_tree_unlock(root->node);
  1073. return root;
  1074. }
  1075. int btrfs_init_log_root_tree(struct btrfs_trans_handle *trans,
  1076. struct btrfs_fs_info *fs_info)
  1077. {
  1078. struct btrfs_root *log_root;
  1079. log_root = alloc_log_tree(trans, fs_info);
  1080. if (IS_ERR(log_root))
  1081. return PTR_ERR(log_root);
  1082. WARN_ON(fs_info->log_root_tree);
  1083. fs_info->log_root_tree = log_root;
  1084. return 0;
  1085. }
  1086. int btrfs_add_log_tree(struct btrfs_trans_handle *trans,
  1087. struct btrfs_root *root)
  1088. {
  1089. struct btrfs_fs_info *fs_info = root->fs_info;
  1090. struct btrfs_root *log_root;
  1091. struct btrfs_inode_item *inode_item;
  1092. log_root = alloc_log_tree(trans, fs_info);
  1093. if (IS_ERR(log_root))
  1094. return PTR_ERR(log_root);
  1095. log_root->last_trans = trans->transid;
  1096. log_root->root_key.offset = root->root_key.objectid;
  1097. inode_item = &log_root->root_item.inode;
  1098. btrfs_set_stack_inode_generation(inode_item, 1);
  1099. btrfs_set_stack_inode_size(inode_item, 3);
  1100. btrfs_set_stack_inode_nlink(inode_item, 1);
  1101. btrfs_set_stack_inode_nbytes(inode_item,
  1102. fs_info->nodesize);
  1103. btrfs_set_stack_inode_mode(inode_item, S_IFDIR | 0755);
  1104. btrfs_set_root_node(&log_root->root_item, log_root->node);
  1105. WARN_ON(root->log_root);
  1106. root->log_root = log_root;
  1107. root->log_transid = 0;
  1108. root->log_transid_committed = -1;
  1109. root->last_log_commit = 0;
  1110. return 0;
  1111. }
  1112. static struct btrfs_root *read_tree_root_path(struct btrfs_root *tree_root,
  1113. struct btrfs_path *path,
  1114. struct btrfs_key *key)
  1115. {
  1116. struct btrfs_root *root;
  1117. struct btrfs_fs_info *fs_info = tree_root->fs_info;
  1118. u64 generation;
  1119. int ret;
  1120. int level;
  1121. root = btrfs_alloc_root(fs_info, key->objectid, GFP_NOFS);
  1122. if (!root)
  1123. return ERR_PTR(-ENOMEM);
  1124. ret = btrfs_find_root(tree_root, key, path,
  1125. &root->root_item, &root->root_key);
  1126. if (ret) {
  1127. if (ret > 0)
  1128. ret = -ENOENT;
  1129. goto fail;
  1130. }
  1131. generation = btrfs_root_generation(&root->root_item);
  1132. level = btrfs_root_level(&root->root_item);
  1133. root->node = read_tree_block(fs_info,
  1134. btrfs_root_bytenr(&root->root_item),
  1135. generation, level, NULL);
  1136. if (IS_ERR(root->node)) {
  1137. ret = PTR_ERR(root->node);
  1138. root->node = NULL;
  1139. goto fail;
  1140. } else if (!btrfs_buffer_uptodate(root->node, generation, 0)) {
  1141. ret = -EIO;
  1142. goto fail;
  1143. }
  1144. root->commit_root = btrfs_root_node(root);
  1145. return root;
  1146. fail:
  1147. btrfs_put_root(root);
  1148. return ERR_PTR(ret);
  1149. }
  1150. struct btrfs_root *btrfs_read_tree_root(struct btrfs_root *tree_root,
  1151. struct btrfs_key *key)
  1152. {
  1153. struct btrfs_root *root;
  1154. struct btrfs_path *path;
  1155. path = btrfs_alloc_path();
  1156. if (!path)
  1157. return ERR_PTR(-ENOMEM);
  1158. root = read_tree_root_path(tree_root, path, key);
  1159. btrfs_free_path(path);
  1160. return root;
  1161. }
  1162. /*
  1163. * Initialize subvolume root in-memory structure
  1164. *
  1165. * @anon_dev: anonymous device to attach to the root, if zero, allocate new
  1166. */
  1167. static int btrfs_init_fs_root(struct btrfs_root *root, dev_t anon_dev)
  1168. {
  1169. int ret;
  1170. unsigned int nofs_flag;
  1171. root->free_ino_ctl = kzalloc(sizeof(*root->free_ino_ctl), GFP_NOFS);
  1172. root->free_ino_pinned = kzalloc(sizeof(*root->free_ino_pinned),
  1173. GFP_NOFS);
  1174. if (!root->free_ino_pinned || !root->free_ino_ctl) {
  1175. ret = -ENOMEM;
  1176. goto fail;
  1177. }
  1178. /*
  1179. * We might be called under a transaction (e.g. indirect backref
  1180. * resolution) which could deadlock if it triggers memory reclaim
  1181. */
  1182. nofs_flag = memalloc_nofs_save();
  1183. ret = btrfs_drew_lock_init(&root->snapshot_lock);
  1184. memalloc_nofs_restore(nofs_flag);
  1185. if (ret)
  1186. goto fail;
  1187. if (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID &&
  1188. root->root_key.objectid != BTRFS_DATA_RELOC_TREE_OBJECTID) {
  1189. set_bit(BTRFS_ROOT_SHAREABLE, &root->state);
  1190. btrfs_check_and_init_root_item(&root->root_item);
  1191. }
  1192. btrfs_init_free_ino_ctl(root);
  1193. spin_lock_init(&root->ino_cache_lock);
  1194. init_waitqueue_head(&root->ino_cache_wait);
  1195. /*
  1196. * Don't assign anonymous block device to roots that are not exposed to
  1197. * userspace, the id pool is limited to 1M
  1198. */
  1199. if (is_fstree(root->root_key.objectid) &&
  1200. btrfs_root_refs(&root->root_item) > 0) {
  1201. if (!anon_dev) {
  1202. ret = get_anon_bdev(&root->anon_dev);
  1203. if (ret)
  1204. goto fail;
  1205. } else {
  1206. root->anon_dev = anon_dev;
  1207. }
  1208. }
  1209. mutex_lock(&root->objectid_mutex);
  1210. ret = btrfs_find_highest_objectid(root,
  1211. &root->highest_objectid);
  1212. if (ret) {
  1213. mutex_unlock(&root->objectid_mutex);
  1214. goto fail;
  1215. }
  1216. ASSERT(root->highest_objectid <= BTRFS_LAST_FREE_OBJECTID);
  1217. mutex_unlock(&root->objectid_mutex);
  1218. return 0;
  1219. fail:
  1220. /* The caller is responsible to call btrfs_free_fs_root */
  1221. return ret;
  1222. }
  1223. static struct btrfs_root *btrfs_lookup_fs_root(struct btrfs_fs_info *fs_info,
  1224. u64 root_id)
  1225. {
  1226. struct btrfs_root *root;
  1227. spin_lock(&fs_info->fs_roots_radix_lock);
  1228. root = radix_tree_lookup(&fs_info->fs_roots_radix,
  1229. (unsigned long)root_id);
  1230. if (root)
  1231. root = btrfs_grab_root(root);
  1232. spin_unlock(&fs_info->fs_roots_radix_lock);
  1233. return root;
  1234. }
  1235. static struct btrfs_root *btrfs_get_global_root(struct btrfs_fs_info *fs_info,
  1236. u64 objectid)
  1237. {
  1238. if (objectid == BTRFS_ROOT_TREE_OBJECTID)
  1239. return btrfs_grab_root(fs_info->tree_root);
  1240. if (objectid == BTRFS_EXTENT_TREE_OBJECTID)
  1241. return btrfs_grab_root(fs_info->extent_root);
  1242. if (objectid == BTRFS_CHUNK_TREE_OBJECTID)
  1243. return btrfs_grab_root(fs_info->chunk_root);
  1244. if (objectid == BTRFS_DEV_TREE_OBJECTID)
  1245. return btrfs_grab_root(fs_info->dev_root);
  1246. if (objectid == BTRFS_CSUM_TREE_OBJECTID)
  1247. return btrfs_grab_root(fs_info->csum_root);
  1248. if (objectid == BTRFS_QUOTA_TREE_OBJECTID)
  1249. return btrfs_grab_root(fs_info->quota_root) ?
  1250. fs_info->quota_root : ERR_PTR(-ENOENT);
  1251. if (objectid == BTRFS_UUID_TREE_OBJECTID)
  1252. return btrfs_grab_root(fs_info->uuid_root) ?
  1253. fs_info->uuid_root : ERR_PTR(-ENOENT);
  1254. if (objectid == BTRFS_FREE_SPACE_TREE_OBJECTID)
  1255. return btrfs_grab_root(fs_info->free_space_root) ?
  1256. fs_info->free_space_root : ERR_PTR(-ENOENT);
  1257. return NULL;
  1258. }
  1259. int btrfs_insert_fs_root(struct btrfs_fs_info *fs_info,
  1260. struct btrfs_root *root)
  1261. {
  1262. int ret;
  1263. ret = radix_tree_preload(GFP_NOFS);
  1264. if (ret)
  1265. return ret;
  1266. spin_lock(&fs_info->fs_roots_radix_lock);
  1267. ret = radix_tree_insert(&fs_info->fs_roots_radix,
  1268. (unsigned long)root->root_key.objectid,
  1269. root);
  1270. if (ret == 0) {
  1271. btrfs_grab_root(root);
  1272. set_bit(BTRFS_ROOT_IN_RADIX, &root->state);
  1273. }
  1274. spin_unlock(&fs_info->fs_roots_radix_lock);
  1275. radix_tree_preload_end();
  1276. return ret;
  1277. }
  1278. void btrfs_check_leaked_roots(struct btrfs_fs_info *fs_info)
  1279. {
  1280. #ifdef CONFIG_BTRFS_DEBUG
  1281. struct btrfs_root *root;
  1282. while (!list_empty(&fs_info->allocated_roots)) {
  1283. char buf[BTRFS_ROOT_NAME_BUF_LEN];
  1284. root = list_first_entry(&fs_info->allocated_roots,
  1285. struct btrfs_root, leak_list);
  1286. btrfs_err(fs_info, "leaked root %s refcount %d",
  1287. btrfs_root_name(&root->root_key, buf),
  1288. refcount_read(&root->refs));
  1289. while (refcount_read(&root->refs) > 1)
  1290. btrfs_put_root(root);
  1291. btrfs_put_root(root);
  1292. }
  1293. #endif
  1294. }
  1295. void btrfs_free_fs_info(struct btrfs_fs_info *fs_info)
  1296. {
  1297. percpu_counter_destroy(&fs_info->dirty_metadata_bytes);
  1298. percpu_counter_destroy(&fs_info->delalloc_bytes);
  1299. percpu_counter_destroy(&fs_info->dio_bytes);
  1300. percpu_counter_destroy(&fs_info->dev_replace.bio_counter);
  1301. btrfs_free_csum_hash(fs_info);
  1302. btrfs_free_stripe_hash_table(fs_info);
  1303. btrfs_free_ref_cache(fs_info);
  1304. kfree(fs_info->balance_ctl);
  1305. kfree(fs_info->delayed_root);
  1306. btrfs_put_root(fs_info->extent_root);
  1307. btrfs_put_root(fs_info->tree_root);
  1308. btrfs_put_root(fs_info->chunk_root);
  1309. btrfs_put_root(fs_info->dev_root);
  1310. btrfs_put_root(fs_info->csum_root);
  1311. btrfs_put_root(fs_info->quota_root);
  1312. btrfs_put_root(fs_info->uuid_root);
  1313. btrfs_put_root(fs_info->free_space_root);
  1314. btrfs_put_root(fs_info->fs_root);
  1315. btrfs_put_root(fs_info->data_reloc_root);
  1316. btrfs_check_leaked_roots(fs_info);
  1317. btrfs_extent_buffer_leak_debug_check(fs_info);
  1318. kfree(fs_info->super_copy);
  1319. kfree(fs_info->super_for_commit);
  1320. kvfree(fs_info);
  1321. }
  1322. /*
  1323. * Get an in-memory reference of a root structure.
  1324. *
  1325. * For essential trees like root/extent tree, we grab it from fs_info directly.
  1326. * For subvolume trees, we check the cached filesystem roots first. If not
  1327. * found, then read it from disk and add it to cached fs roots.
  1328. *
  1329. * Caller should release the root by calling btrfs_put_root() after the usage.
  1330. *
  1331. * NOTE: Reloc and log trees can't be read by this function as they share the
  1332. * same root objectid.
  1333. *
  1334. * @objectid: root id
  1335. * @anon_dev: preallocated anonymous block device number for new roots,
  1336. * pass 0 for new allocation.
  1337. * @check_ref: whether to check root item references, If true, return -ENOENT
  1338. * for orphan roots
  1339. */
  1340. static struct btrfs_root *btrfs_get_root_ref(struct btrfs_fs_info *fs_info,
  1341. u64 objectid, dev_t anon_dev,
  1342. bool check_ref)
  1343. {
  1344. struct btrfs_root *root;
  1345. struct btrfs_path *path;
  1346. struct btrfs_key key;
  1347. int ret;
  1348. root = btrfs_get_global_root(fs_info, objectid);
  1349. if (root)
  1350. return root;
  1351. again:
  1352. root = btrfs_lookup_fs_root(fs_info, objectid);
  1353. if (root) {
  1354. /* Shouldn't get preallocated anon_dev for cached roots */
  1355. ASSERT(!anon_dev);
  1356. if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
  1357. btrfs_put_root(root);
  1358. return ERR_PTR(-ENOENT);
  1359. }
  1360. return root;
  1361. }
  1362. key.objectid = objectid;
  1363. key.type = BTRFS_ROOT_ITEM_KEY;
  1364. key.offset = (u64)-1;
  1365. root = btrfs_read_tree_root(fs_info->tree_root, &key);
  1366. if (IS_ERR(root))
  1367. return root;
  1368. if (check_ref && btrfs_root_refs(&root->root_item) == 0) {
  1369. ret = -ENOENT;
  1370. goto fail;
  1371. }
  1372. ret = btrfs_init_fs_root(root, anon_dev);
  1373. if (ret)
  1374. goto fail;
  1375. path = btrfs_alloc_path();
  1376. if (!path) {
  1377. ret = -ENOMEM;
  1378. goto fail;
  1379. }
  1380. key.objectid = BTRFS_ORPHAN_OBJECTID;
  1381. key.type = BTRFS_ORPHAN_ITEM_KEY;
  1382. key.offset = objectid;
  1383. ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
  1384. btrfs_free_path(path);
  1385. if (ret < 0)
  1386. goto fail;
  1387. if (ret == 0)
  1388. set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state);
  1389. ret = btrfs_insert_fs_root(fs_info, root);
  1390. if (ret) {
  1391. if (ret == -EEXIST) {
  1392. btrfs_put_root(root);
  1393. goto again;
  1394. }
  1395. goto fail;
  1396. }
  1397. return root;
  1398. fail:
  1399. /*
  1400. * If our caller provided us an anonymous device, then it's his
  1401. * responsability to free it in case we fail. So we have to set our
  1402. * root's anon_dev to 0 to avoid a double free, once by btrfs_put_root()
  1403. * and once again by our caller.
  1404. */
  1405. if (anon_dev)
  1406. root->anon_dev = 0;
  1407. btrfs_put_root(root);
  1408. return ERR_PTR(ret);
  1409. }
  1410. /*
  1411. * Get in-memory reference of a root structure
  1412. *
  1413. * @objectid: tree objectid
  1414. * @check_ref: if set, verify that the tree exists and the item has at least
  1415. * one reference
  1416. */
  1417. struct btrfs_root *btrfs_get_fs_root(struct btrfs_fs_info *fs_info,
  1418. u64 objectid, bool check_ref)
  1419. {
  1420. return btrfs_get_root_ref(fs_info, objectid, 0, check_ref);
  1421. }
  1422. /*
  1423. * Get in-memory reference of a root structure, created as new, optionally pass
  1424. * the anonymous block device id
  1425. *
  1426. * @objectid: tree objectid
  1427. * @anon_dev: if zero, allocate a new anonymous block device or use the
  1428. * parameter value
  1429. */
  1430. struct btrfs_root *btrfs_get_new_fs_root(struct btrfs_fs_info *fs_info,
  1431. u64 objectid, dev_t anon_dev)
  1432. {
  1433. return btrfs_get_root_ref(fs_info, objectid, anon_dev, true);
  1434. }
  1435. /*
  1436. * btrfs_get_fs_root_commit_root - return a root for the given objectid
  1437. * @fs_info: the fs_info
  1438. * @objectid: the objectid we need to lookup
  1439. *
  1440. * This is exclusively used for backref walking, and exists specifically because
  1441. * of how qgroups does lookups. Qgroups will do a backref lookup at delayed ref
  1442. * creation time, which means we may have to read the tree_root in order to look
  1443. * up a fs root that is not in memory. If the root is not in memory we will
  1444. * read the tree root commit root and look up the fs root from there. This is a
  1445. * temporary root, it will not be inserted into the radix tree as it doesn't
  1446. * have the most uptodate information, it'll simply be discarded once the
  1447. * backref code is finished using the root.
  1448. */
  1449. struct btrfs_root *btrfs_get_fs_root_commit_root(struct btrfs_fs_info *fs_info,
  1450. struct btrfs_path *path,
  1451. u64 objectid)
  1452. {
  1453. struct btrfs_root *root;
  1454. struct btrfs_key key;
  1455. ASSERT(path->search_commit_root && path->skip_locking);
  1456. /*
  1457. * This can return -ENOENT if we ask for a root that doesn't exist, but
  1458. * since this is called via the backref walking code we won't be looking
  1459. * up a root that doesn't exist, unless there's corruption. So if root
  1460. * != NULL just return it.
  1461. */
  1462. root = btrfs_get_global_root(fs_info, objectid);
  1463. if (root)
  1464. return root;
  1465. root = btrfs_lookup_fs_root(fs_info, objectid);
  1466. if (root)
  1467. return root;
  1468. key.objectid = objectid;
  1469. key.type = BTRFS_ROOT_ITEM_KEY;
  1470. key.offset = (u64)-1;
  1471. root = read_tree_root_path(fs_info->tree_root, path, &key);
  1472. btrfs_release_path(path);
  1473. return root;
  1474. }
  1475. /*
  1476. * called by the kthread helper functions to finally call the bio end_io
  1477. * functions. This is where read checksum verification actually happens
  1478. */
  1479. static void end_workqueue_fn(struct btrfs_work *work)
  1480. {
  1481. struct bio *bio;
  1482. struct btrfs_end_io_wq *end_io_wq;
  1483. end_io_wq = container_of(work, struct btrfs_end_io_wq, work);
  1484. bio = end_io_wq->bio;
  1485. bio->bi_status = end_io_wq->status;
  1486. bio->bi_private = end_io_wq->private;
  1487. bio->bi_end_io = end_io_wq->end_io;
  1488. bio_endio(bio);
  1489. kmem_cache_free(btrfs_end_io_wq_cache, end_io_wq);
  1490. }
  1491. static int cleaner_kthread(void *arg)
  1492. {
  1493. struct btrfs_root *root = arg;
  1494. struct btrfs_fs_info *fs_info = root->fs_info;
  1495. int again;
  1496. while (1) {
  1497. again = 0;
  1498. set_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
  1499. /* Make the cleaner go to sleep early. */
  1500. if (btrfs_need_cleaner_sleep(fs_info))
  1501. goto sleep;
  1502. /*
  1503. * Do not do anything if we might cause open_ctree() to block
  1504. * before we have finished mounting the filesystem.
  1505. */
  1506. if (!test_bit(BTRFS_FS_OPEN, &fs_info->flags))
  1507. goto sleep;
  1508. if (!mutex_trylock(&fs_info->cleaner_mutex))
  1509. goto sleep;
  1510. /*
  1511. * Avoid the problem that we change the status of the fs
  1512. * during the above check and trylock.
  1513. */
  1514. if (btrfs_need_cleaner_sleep(fs_info)) {
  1515. mutex_unlock(&fs_info->cleaner_mutex);
  1516. goto sleep;
  1517. }
  1518. btrfs_run_delayed_iputs(fs_info);
  1519. again = btrfs_clean_one_deleted_snapshot(root);
  1520. mutex_unlock(&fs_info->cleaner_mutex);
  1521. /*
  1522. * The defragger has dealt with the R/O remount and umount,
  1523. * needn't do anything special here.
  1524. */
  1525. btrfs_run_defrag_inodes(fs_info);
  1526. /*
  1527. * Acquires fs_info->delete_unused_bgs_mutex to avoid racing
  1528. * with relocation (btrfs_relocate_chunk) and relocation
  1529. * acquires fs_info->cleaner_mutex (btrfs_relocate_block_group)
  1530. * after acquiring fs_info->delete_unused_bgs_mutex. So we
  1531. * can't hold, nor need to, fs_info->cleaner_mutex when deleting
  1532. * unused block groups.
  1533. */
  1534. btrfs_delete_unused_bgs(fs_info);
  1535. sleep:
  1536. clear_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags);
  1537. if (kthread_should_park())
  1538. kthread_parkme();
  1539. if (kthread_should_stop())
  1540. return 0;
  1541. if (!again) {
  1542. set_current_state(TASK_INTERRUPTIBLE);
  1543. schedule();
  1544. __set_current_state(TASK_RUNNING);
  1545. }
  1546. }
  1547. }
  1548. static int transaction_kthread(void *arg)
  1549. {
  1550. struct btrfs_root *root = arg;
  1551. struct btrfs_fs_info *fs_info = root->fs_info;
  1552. struct btrfs_trans_handle *trans;
  1553. struct btrfs_transaction *cur;
  1554. u64 transid;
  1555. time64_t now;
  1556. unsigned long delay;
  1557. bool cannot_commit;
  1558. do {
  1559. cannot_commit = false;
  1560. delay = HZ * fs_info->commit_interval;
  1561. mutex_lock(&fs_info->transaction_kthread_mutex);
  1562. spin_lock(&fs_info->trans_lock);
  1563. cur = fs_info->running_transaction;
  1564. if (!cur) {
  1565. spin_unlock(&fs_info->trans_lock);
  1566. goto sleep;
  1567. }
  1568. now = ktime_get_seconds();
  1569. if (cur->state < TRANS_STATE_COMMIT_START &&
  1570. (now < cur->start_time ||
  1571. now - cur->start_time < fs_info->commit_interval)) {
  1572. spin_unlock(&fs_info->trans_lock);
  1573. delay = HZ * 5;
  1574. goto sleep;
  1575. }
  1576. transid = cur->transid;
  1577. spin_unlock(&fs_info->trans_lock);
  1578. /* If the file system is aborted, this will always fail. */
  1579. trans = btrfs_attach_transaction(root);
  1580. if (IS_ERR(trans)) {
  1581. if (PTR_ERR(trans) != -ENOENT)
  1582. cannot_commit = true;
  1583. goto sleep;
  1584. }
  1585. if (transid == trans->transid) {
  1586. btrfs_commit_transaction(trans);
  1587. } else {
  1588. btrfs_end_transaction(trans);
  1589. }
  1590. sleep:
  1591. wake_up_process(fs_info->cleaner_kthread);
  1592. mutex_unlock(&fs_info->transaction_kthread_mutex);
  1593. if (unlikely(test_bit(BTRFS_FS_STATE_ERROR,
  1594. &fs_info->fs_state)))
  1595. btrfs_cleanup_transaction(fs_info);
  1596. if (!kthread_should_stop() &&
  1597. (!btrfs_transaction_blocked(fs_info) ||
  1598. cannot_commit))
  1599. schedule_timeout_interruptible(delay);
  1600. } while (!kthread_should_stop());
  1601. return 0;
  1602. }
  1603. /*
  1604. * This will find the highest generation in the array of root backups. The
  1605. * index of the highest array is returned, or -EINVAL if we can't find
  1606. * anything.
  1607. *
  1608. * We check to make sure the array is valid by comparing the
  1609. * generation of the latest root in the array with the generation
  1610. * in the super block. If they don't match we pitch it.
  1611. */
  1612. static int find_newest_super_backup(struct btrfs_fs_info *info)
  1613. {
  1614. const u64 newest_gen = btrfs_super_generation(info->super_copy);
  1615. u64 cur;
  1616. struct btrfs_root_backup *root_backup;
  1617. int i;
  1618. for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
  1619. root_backup = info->super_copy->super_roots + i;
  1620. cur = btrfs_backup_tree_root_gen(root_backup);
  1621. if (cur == newest_gen)
  1622. return i;
  1623. }
  1624. return -EINVAL;
  1625. }
  1626. /*
  1627. * copy all the root pointers into the super backup array.
  1628. * this will bump the backup pointer by one when it is
  1629. * done
  1630. */
  1631. static void backup_super_roots(struct btrfs_fs_info *info)
  1632. {
  1633. const int next_backup = info->backup_root_index;
  1634. struct btrfs_root_backup *root_backup;
  1635. root_backup = info->super_for_commit->super_roots + next_backup;
  1636. /*
  1637. * make sure all of our padding and empty slots get zero filled
  1638. * regardless of which ones we use today
  1639. */
  1640. memset(root_backup, 0, sizeof(*root_backup));
  1641. info->backup_root_index = (next_backup + 1) % BTRFS_NUM_BACKUP_ROOTS;
  1642. btrfs_set_backup_tree_root(root_backup, info->tree_root->node->start);
  1643. btrfs_set_backup_tree_root_gen(root_backup,
  1644. btrfs_header_generation(info->tree_root->node));
  1645. btrfs_set_backup_tree_root_level(root_backup,
  1646. btrfs_header_level(info->tree_root->node));
  1647. btrfs_set_backup_chunk_root(root_backup, info->chunk_root->node->start);
  1648. btrfs_set_backup_chunk_root_gen(root_backup,
  1649. btrfs_header_generation(info->chunk_root->node));
  1650. btrfs_set_backup_chunk_root_level(root_backup,
  1651. btrfs_header_level(info->chunk_root->node));
  1652. btrfs_set_backup_extent_root(root_backup, info->extent_root->node->start);
  1653. btrfs_set_backup_extent_root_gen(root_backup,
  1654. btrfs_header_generation(info->extent_root->node));
  1655. btrfs_set_backup_extent_root_level(root_backup,
  1656. btrfs_header_level(info->extent_root->node));
  1657. /*
  1658. * we might commit during log recovery, which happens before we set
  1659. * the fs_root. Make sure it is valid before we fill it in.
  1660. */
  1661. if (info->fs_root && info->fs_root->node) {
  1662. btrfs_set_backup_fs_root(root_backup,
  1663. info->fs_root->node->start);
  1664. btrfs_set_backup_fs_root_gen(root_backup,
  1665. btrfs_header_generation(info->fs_root->node));
  1666. btrfs_set_backup_fs_root_level(root_backup,
  1667. btrfs_header_level(info->fs_root->node));
  1668. }
  1669. btrfs_set_backup_dev_root(root_backup, info->dev_root->node->start);
  1670. btrfs_set_backup_dev_root_gen(root_backup,
  1671. btrfs_header_generation(info->dev_root->node));
  1672. btrfs_set_backup_dev_root_level(root_backup,
  1673. btrfs_header_level(info->dev_root->node));
  1674. btrfs_set_backup_csum_root(root_backup, info->csum_root->node->start);
  1675. btrfs_set_backup_csum_root_gen(root_backup,
  1676. btrfs_header_generation(info->csum_root->node));
  1677. btrfs_set_backup_csum_root_level(root_backup,
  1678. btrfs_header_level(info->csum_root->node));
  1679. btrfs_set_backup_total_bytes(root_backup,
  1680. btrfs_super_total_bytes(info->super_copy));
  1681. btrfs_set_backup_bytes_used(root_backup,
  1682. btrfs_super_bytes_used(info->super_copy));
  1683. btrfs_set_backup_num_devices(root_backup,
  1684. btrfs_super_num_devices(info->super_copy));
  1685. /*
  1686. * if we don't copy this out to the super_copy, it won't get remembered
  1687. * for the next commit
  1688. */
  1689. memcpy(&info->super_copy->super_roots,
  1690. &info->super_for_commit->super_roots,
  1691. sizeof(*root_backup) * BTRFS_NUM_BACKUP_ROOTS);
  1692. }
  1693. /*
  1694. * read_backup_root - Reads a backup root based on the passed priority. Prio 0
  1695. * is the newest, prio 1/2/3 are 2nd newest/3rd newest/4th (oldest) backup roots
  1696. *
  1697. * fs_info - filesystem whose backup roots need to be read
  1698. * priority - priority of backup root required
  1699. *
  1700. * Returns backup root index on success and -EINVAL otherwise.
  1701. */
  1702. static int read_backup_root(struct btrfs_fs_info *fs_info, u8 priority)
  1703. {
  1704. int backup_index = find_newest_super_backup(fs_info);
  1705. struct btrfs_super_block *super = fs_info->super_copy;
  1706. struct btrfs_root_backup *root_backup;
  1707. if (priority < BTRFS_NUM_BACKUP_ROOTS && backup_index >= 0) {
  1708. if (priority == 0)
  1709. return backup_index;
  1710. backup_index = backup_index + BTRFS_NUM_BACKUP_ROOTS - priority;
  1711. backup_index %= BTRFS_NUM_BACKUP_ROOTS;
  1712. } else {
  1713. return -EINVAL;
  1714. }
  1715. root_backup = super->super_roots + backup_index;
  1716. btrfs_set_super_generation(super,
  1717. btrfs_backup_tree_root_gen(root_backup));
  1718. btrfs_set_super_root(super, btrfs_backup_tree_root(root_backup));
  1719. btrfs_set_super_root_level(super,
  1720. btrfs_backup_tree_root_level(root_backup));
  1721. btrfs_set_super_bytes_used(super, btrfs_backup_bytes_used(root_backup));
  1722. /*
  1723. * Fixme: the total bytes and num_devices need to match or we should
  1724. * need a fsck
  1725. */
  1726. btrfs_set_super_total_bytes(super, btrfs_backup_total_bytes(root_backup));
  1727. btrfs_set_super_num_devices(super, btrfs_backup_num_devices(root_backup));
  1728. return backup_index;
  1729. }
  1730. /* helper to cleanup workers */
  1731. static void btrfs_stop_all_workers(struct btrfs_fs_info *fs_info)
  1732. {
  1733. btrfs_destroy_workqueue(fs_info->fixup_workers);
  1734. btrfs_destroy_workqueue(fs_info->delalloc_workers);
  1735. btrfs_destroy_workqueue(fs_info->workers);
  1736. btrfs_destroy_workqueue(fs_info->endio_workers);
  1737. btrfs_destroy_workqueue(fs_info->endio_raid56_workers);
  1738. btrfs_destroy_workqueue(fs_info->rmw_workers);
  1739. btrfs_destroy_workqueue(fs_info->endio_write_workers);
  1740. btrfs_destroy_workqueue(fs_info->endio_freespace_worker);
  1741. btrfs_destroy_workqueue(fs_info->delayed_workers);
  1742. btrfs_destroy_workqueue(fs_info->caching_workers);
  1743. btrfs_destroy_workqueue(fs_info->readahead_workers);
  1744. btrfs_destroy_workqueue(fs_info->flush_workers);
  1745. btrfs_destroy_workqueue(fs_info->qgroup_rescan_workers);
  1746. if (fs_info->discard_ctl.discard_workers)
  1747. destroy_workqueue(fs_info->discard_ctl.discard_workers);
  1748. /*
  1749. * Now that all other work queues are destroyed, we can safely destroy
  1750. * the queues used for metadata I/O, since tasks from those other work
  1751. * queues can do metadata I/O operations.
  1752. */
  1753. btrfs_destroy_workqueue(fs_info->endio_meta_workers);
  1754. btrfs_destroy_workqueue(fs_info->endio_meta_write_workers);
  1755. }
  1756. static void free_root_extent_buffers(struct btrfs_root *root)
  1757. {
  1758. if (root) {
  1759. free_extent_buffer(root->node);
  1760. free_extent_buffer(root->commit_root);
  1761. root->node = NULL;
  1762. root->commit_root = NULL;
  1763. }
  1764. }
  1765. /* helper to cleanup tree roots */
  1766. static void free_root_pointers(struct btrfs_fs_info *info, bool free_chunk_root)
  1767. {
  1768. free_root_extent_buffers(info->tree_root);
  1769. free_root_extent_buffers(info->dev_root);
  1770. free_root_extent_buffers(info->extent_root);
  1771. free_root_extent_buffers(info->csum_root);
  1772. free_root_extent_buffers(info->quota_root);
  1773. free_root_extent_buffers(info->uuid_root);
  1774. free_root_extent_buffers(info->fs_root);
  1775. free_root_extent_buffers(info->data_reloc_root);
  1776. if (free_chunk_root)
  1777. free_root_extent_buffers(info->chunk_root);
  1778. free_root_extent_buffers(info->free_space_root);
  1779. }
  1780. void btrfs_put_root(struct btrfs_root *root)
  1781. {
  1782. if (!root)
  1783. return;
  1784. if (refcount_dec_and_test(&root->refs)) {
  1785. WARN_ON(!RB_EMPTY_ROOT(&root->inode_tree));
  1786. WARN_ON(test_bit(BTRFS_ROOT_DEAD_RELOC_TREE, &root->state));
  1787. if (root->anon_dev)
  1788. free_anon_bdev(root->anon_dev);
  1789. btrfs_drew_lock_destroy(&root->snapshot_lock);
  1790. free_root_extent_buffers(root);
  1791. kfree(root->free_ino_ctl);
  1792. kfree(root->free_ino_pinned);
  1793. #ifdef CONFIG_BTRFS_DEBUG
  1794. spin_lock(&root->fs_info->fs_roots_radix_lock);
  1795. list_del_init(&root->leak_list);
  1796. spin_unlock(&root->fs_info->fs_roots_radix_lock);
  1797. #endif
  1798. kfree(root);
  1799. }
  1800. }
  1801. void btrfs_free_fs_roots(struct btrfs_fs_info *fs_info)
  1802. {
  1803. int ret;
  1804. struct btrfs_root *gang[8];
  1805. int i;
  1806. while (!list_empty(&fs_info->dead_roots)) {
  1807. gang[0] = list_entry(fs_info->dead_roots.next,
  1808. struct btrfs_root, root_list);
  1809. list_del(&gang[0]->root_list);
  1810. if (test_bit(BTRFS_ROOT_IN_RADIX, &gang[0]->state))
  1811. btrfs_drop_and_free_fs_root(fs_info, gang[0]);
  1812. btrfs_put_root(gang[0]);
  1813. }
  1814. while (1) {
  1815. ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
  1816. (void **)gang, 0,
  1817. ARRAY_SIZE(gang));
  1818. if (!ret)
  1819. break;
  1820. for (i = 0; i < ret; i++)
  1821. btrfs_drop_and_free_fs_root(fs_info, gang[i]);
  1822. }
  1823. }
  1824. static void btrfs_init_scrub(struct btrfs_fs_info *fs_info)
  1825. {
  1826. mutex_init(&fs_info->scrub_lock);
  1827. atomic_set(&fs_info->scrubs_running, 0);
  1828. atomic_set(&fs_info->scrub_pause_req, 0);
  1829. atomic_set(&fs_info->scrubs_paused, 0);
  1830. atomic_set(&fs_info->scrub_cancel_req, 0);
  1831. init_waitqueue_head(&fs_info->scrub_pause_wait);
  1832. refcount_set(&fs_info->scrub_workers_refcnt, 0);
  1833. }
  1834. static void btrfs_init_balance(struct btrfs_fs_info *fs_info)
  1835. {
  1836. spin_lock_init(&fs_info->balance_lock);
  1837. mutex_init(&fs_info->balance_mutex);
  1838. atomic_set(&fs_info->balance_pause_req, 0);
  1839. atomic_set(&fs_info->balance_cancel_req, 0);
  1840. fs_info->balance_ctl = NULL;
  1841. init_waitqueue_head(&fs_info->balance_wait_q);
  1842. }
  1843. static void btrfs_init_btree_inode(struct btrfs_fs_info *fs_info)
  1844. {
  1845. struct inode *inode = fs_info->btree_inode;
  1846. inode->i_ino = BTRFS_BTREE_INODE_OBJECTID;
  1847. set_nlink(inode, 1);
  1848. /*
  1849. * we set the i_size on the btree inode to the max possible int.
  1850. * the real end of the address space is determined by all of
  1851. * the devices in the system
  1852. */
  1853. inode->i_size = OFFSET_MAX;
  1854. inode->i_mapping->a_ops = &btree_aops;
  1855. RB_CLEAR_NODE(&BTRFS_I(inode)->rb_node);
  1856. extent_io_tree_init(fs_info, &BTRFS_I(inode)->io_tree,
  1857. IO_TREE_BTREE_INODE_IO, inode);
  1858. BTRFS_I(inode)->io_tree.track_uptodate = false;
  1859. extent_map_tree_init(&BTRFS_I(inode)->extent_tree);
  1860. BTRFS_I(inode)->root = btrfs_grab_root(fs_info->tree_root);
  1861. memset(&BTRFS_I(inode)->location, 0, sizeof(struct btrfs_key));
  1862. set_bit(BTRFS_INODE_DUMMY, &BTRFS_I(inode)->runtime_flags);
  1863. btrfs_insert_inode_hash(inode);
  1864. }
  1865. static void btrfs_init_dev_replace_locks(struct btrfs_fs_info *fs_info)
  1866. {
  1867. mutex_init(&fs_info->dev_replace.lock_finishing_cancel_unmount);
  1868. init_rwsem(&fs_info->dev_replace.rwsem);
  1869. init_waitqueue_head(&fs_info->dev_replace.replace_wait);
  1870. }
  1871. static void btrfs_init_qgroup(struct btrfs_fs_info *fs_info)
  1872. {
  1873. spin_lock_init(&fs_info->qgroup_lock);
  1874. mutex_init(&fs_info->qgroup_ioctl_lock);
  1875. fs_info->qgroup_tree = RB_ROOT;
  1876. INIT_LIST_HEAD(&fs_info->dirty_qgroups);
  1877. fs_info->qgroup_seq = 1;
  1878. fs_info->qgroup_ulist = NULL;
  1879. fs_info->qgroup_rescan_running = false;
  1880. mutex_init(&fs_info->qgroup_rescan_lock);
  1881. }
  1882. static int btrfs_init_workqueues(struct btrfs_fs_info *fs_info,
  1883. struct btrfs_fs_devices *fs_devices)
  1884. {
  1885. u32 max_active = fs_info->thread_pool_size;
  1886. unsigned int flags = WQ_MEM_RECLAIM | WQ_FREEZABLE | WQ_UNBOUND;
  1887. fs_info->workers =
  1888. btrfs_alloc_workqueue(fs_info, "worker",
  1889. flags | WQ_HIGHPRI, max_active, 16);
  1890. fs_info->delalloc_workers =
  1891. btrfs_alloc_workqueue(fs_info, "delalloc",
  1892. flags, max_active, 2);
  1893. fs_info->flush_workers =
  1894. btrfs_alloc_workqueue(fs_info, "flush_delalloc",
  1895. flags, max_active, 0);
  1896. fs_info->caching_workers =
  1897. btrfs_alloc_workqueue(fs_info, "cache", flags, max_active, 0);
  1898. fs_info->fixup_workers =
  1899. btrfs_alloc_workqueue(fs_info, "fixup", flags, 1, 0);
  1900. /*
  1901. * endios are largely parallel and should have a very
  1902. * low idle thresh
  1903. */
  1904. fs_info->endio_workers =
  1905. btrfs_alloc_workqueue(fs_info, "endio", flags, max_active, 4);
  1906. fs_info->endio_meta_workers =
  1907. btrfs_alloc_workqueue(fs_info, "endio-meta", flags,
  1908. max_active, 4);
  1909. fs_info->endio_meta_write_workers =
  1910. btrfs_alloc_workqueue(fs_info, "endio-meta-write", flags,
  1911. max_active, 2);
  1912. fs_info->endio_raid56_workers =
  1913. btrfs_alloc_workqueue(fs_info, "endio-raid56", flags,
  1914. max_active, 4);
  1915. fs_info->rmw_workers =
  1916. btrfs_alloc_workqueue(fs_info, "rmw", flags, max_active, 2);
  1917. fs_info->endio_write_workers =
  1918. btrfs_alloc_workqueue(fs_info, "endio-write", flags,
  1919. max_active, 2);
  1920. fs_info->endio_freespace_worker =
  1921. btrfs_alloc_workqueue(fs_info, "freespace-write", flags,
  1922. max_active, 0);
  1923. fs_info->delayed_workers =
  1924. btrfs_alloc_workqueue(fs_info, "delayed-meta", flags,
  1925. max_active, 0);
  1926. fs_info->readahead_workers =
  1927. btrfs_alloc_workqueue(fs_info, "readahead", flags,
  1928. max_active, 2);
  1929. fs_info->qgroup_rescan_workers =
  1930. btrfs_alloc_workqueue(fs_info, "qgroup-rescan", flags, 1, 0);
  1931. fs_info->discard_ctl.discard_workers =
  1932. alloc_workqueue("btrfs_discard", WQ_UNBOUND | WQ_FREEZABLE, 1);
  1933. if (!(fs_info->workers && fs_info->delalloc_workers &&
  1934. fs_info->flush_workers &&
  1935. fs_info->endio_workers && fs_info->endio_meta_workers &&
  1936. fs_info->endio_meta_write_workers &&
  1937. fs_info->endio_write_workers && fs_info->endio_raid56_workers &&
  1938. fs_info->endio_freespace_worker && fs_info->rmw_workers &&
  1939. fs_info->caching_workers && fs_info->readahead_workers &&
  1940. fs_info->fixup_workers && fs_info->delayed_workers &&
  1941. fs_info->qgroup_rescan_workers &&
  1942. fs_info->discard_ctl.discard_workers)) {
  1943. return -ENOMEM;
  1944. }
  1945. return 0;
  1946. }
  1947. static int btrfs_init_csum_hash(struct btrfs_fs_info *fs_info, u16 csum_type)
  1948. {
  1949. struct crypto_shash *csum_shash;
  1950. const char *csum_driver = btrfs_super_csum_driver(csum_type);
  1951. csum_shash = crypto_alloc_shash(csum_driver, 0, 0);
  1952. if (IS_ERR(csum_shash)) {
  1953. btrfs_err(fs_info, "error allocating %s hash for checksum",
  1954. csum_driver);
  1955. return PTR_ERR(csum_shash);
  1956. }
  1957. fs_info->csum_shash = csum_shash;
  1958. return 0;
  1959. }
  1960. static int btrfs_replay_log(struct btrfs_fs_info *fs_info,
  1961. struct btrfs_fs_devices *fs_devices)
  1962. {
  1963. int ret;
  1964. struct btrfs_root *log_tree_root;
  1965. struct btrfs_super_block *disk_super = fs_info->super_copy;
  1966. u64 bytenr = btrfs_super_log_root(disk_super);
  1967. int level = btrfs_super_log_root_level(disk_super);
  1968. if (fs_devices->rw_devices == 0) {
  1969. btrfs_warn(fs_info, "log replay required on RO media");
  1970. return -EIO;
  1971. }
  1972. log_tree_root = btrfs_alloc_root(fs_info, BTRFS_TREE_LOG_OBJECTID,
  1973. GFP_KERNEL);
  1974. if (!log_tree_root)
  1975. return -ENOMEM;
  1976. log_tree_root->node = read_tree_block(fs_info, bytenr,
  1977. fs_info->generation + 1,
  1978. level, NULL);
  1979. if (IS_ERR(log_tree_root->node)) {
  1980. btrfs_warn(fs_info, "failed to read log tree");
  1981. ret = PTR_ERR(log_tree_root->node);
  1982. log_tree_root->node = NULL;
  1983. btrfs_put_root(log_tree_root);
  1984. return ret;
  1985. } else if (!extent_buffer_uptodate(log_tree_root->node)) {
  1986. btrfs_err(fs_info, "failed to read log tree");
  1987. btrfs_put_root(log_tree_root);
  1988. return -EIO;
  1989. }
  1990. /* returns with log_tree_root freed on success */
  1991. ret = btrfs_recover_log_trees(log_tree_root);
  1992. if (ret) {
  1993. btrfs_handle_fs_error(fs_info, ret,
  1994. "Failed to recover log tree");
  1995. btrfs_put_root(log_tree_root);
  1996. return ret;
  1997. }
  1998. if (sb_rdonly(fs_info->sb)) {
  1999. ret = btrfs_commit_super(fs_info);
  2000. if (ret)
  2001. return ret;
  2002. }
  2003. return 0;
  2004. }
  2005. static int btrfs_read_roots(struct btrfs_fs_info *fs_info)
  2006. {
  2007. struct btrfs_root *tree_root = fs_info->tree_root;
  2008. struct btrfs_root *root;
  2009. struct btrfs_key location;
  2010. int ret;
  2011. BUG_ON(!fs_info->tree_root);
  2012. location.objectid = BTRFS_EXTENT_TREE_OBJECTID;
  2013. location.type = BTRFS_ROOT_ITEM_KEY;
  2014. location.offset = 0;
  2015. root = btrfs_read_tree_root(tree_root, &location);
  2016. if (IS_ERR(root)) {
  2017. ret = PTR_ERR(root);
  2018. goto out;
  2019. }
  2020. set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
  2021. fs_info->extent_root = root;
  2022. location.objectid = BTRFS_DEV_TREE_OBJECTID;
  2023. root = btrfs_read_tree_root(tree_root, &location);
  2024. if (IS_ERR(root)) {
  2025. ret = PTR_ERR(root);
  2026. goto out;
  2027. }
  2028. set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
  2029. fs_info->dev_root = root;
  2030. btrfs_init_devices_late(fs_info);
  2031. location.objectid = BTRFS_CSUM_TREE_OBJECTID;
  2032. root = btrfs_read_tree_root(tree_root, &location);
  2033. if (IS_ERR(root)) {
  2034. ret = PTR_ERR(root);
  2035. goto out;
  2036. }
  2037. set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
  2038. fs_info->csum_root = root;
  2039. /*
  2040. * This tree can share blocks with some other fs tree during relocation
  2041. * and we need a proper setup by btrfs_get_fs_root
  2042. */
  2043. root = btrfs_get_fs_root(tree_root->fs_info,
  2044. BTRFS_DATA_RELOC_TREE_OBJECTID, true);
  2045. if (IS_ERR(root)) {
  2046. ret = PTR_ERR(root);
  2047. goto out;
  2048. }
  2049. set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
  2050. fs_info->data_reloc_root = root;
  2051. location.objectid = BTRFS_QUOTA_TREE_OBJECTID;
  2052. root = btrfs_read_tree_root(tree_root, &location);
  2053. if (!IS_ERR(root)) {
  2054. set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
  2055. set_bit(BTRFS_FS_QUOTA_ENABLED, &fs_info->flags);
  2056. fs_info->quota_root = root;
  2057. }
  2058. location.objectid = BTRFS_UUID_TREE_OBJECTID;
  2059. root = btrfs_read_tree_root(tree_root, &location);
  2060. if (IS_ERR(root)) {
  2061. ret = PTR_ERR(root);
  2062. if (ret != -ENOENT)
  2063. goto out;
  2064. } else {
  2065. set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
  2066. fs_info->uuid_root = root;
  2067. }
  2068. if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
  2069. location.objectid = BTRFS_FREE_SPACE_TREE_OBJECTID;
  2070. root = btrfs_read_tree_root(tree_root, &location);
  2071. if (IS_ERR(root)) {
  2072. ret = PTR_ERR(root);
  2073. goto out;
  2074. }
  2075. set_bit(BTRFS_ROOT_TRACK_DIRTY, &root->state);
  2076. fs_info->free_space_root = root;
  2077. }
  2078. return 0;
  2079. out:
  2080. btrfs_warn(fs_info, "failed to read root (objectid=%llu): %d",
  2081. location.objectid, ret);
  2082. return ret;
  2083. }
  2084. /*
  2085. * Real super block validation
  2086. * NOTE: super csum type and incompat features will not be checked here.
  2087. *
  2088. * @sb: super block to check
  2089. * @mirror_num: the super block number to check its bytenr:
  2090. * 0 the primary (1st) sb
  2091. * 1, 2 2nd and 3rd backup copy
  2092. * -1 skip bytenr check
  2093. */
  2094. static int validate_super(struct btrfs_fs_info *fs_info,
  2095. struct btrfs_super_block *sb, int mirror_num)
  2096. {
  2097. u64 nodesize = btrfs_super_nodesize(sb);
  2098. u64 sectorsize = btrfs_super_sectorsize(sb);
  2099. int ret = 0;
  2100. if (btrfs_super_magic(sb) != BTRFS_MAGIC) {
  2101. btrfs_err(fs_info, "no valid FS found");
  2102. ret = -EINVAL;
  2103. }
  2104. if (btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP) {
  2105. btrfs_err(fs_info, "unrecognized or unsupported super flag: %llu",
  2106. btrfs_super_flags(sb) & ~BTRFS_SUPER_FLAG_SUPP);
  2107. ret = -EINVAL;
  2108. }
  2109. if (btrfs_super_root_level(sb) >= BTRFS_MAX_LEVEL) {
  2110. btrfs_err(fs_info, "tree_root level too big: %d >= %d",
  2111. btrfs_super_root_level(sb), BTRFS_MAX_LEVEL);
  2112. ret = -EINVAL;
  2113. }
  2114. if (btrfs_super_chunk_root_level(sb) >= BTRFS_MAX_LEVEL) {
  2115. btrfs_err(fs_info, "chunk_root level too big: %d >= %d",
  2116. btrfs_super_chunk_root_level(sb), BTRFS_MAX_LEVEL);
  2117. ret = -EINVAL;
  2118. }
  2119. if (btrfs_super_log_root_level(sb) >= BTRFS_MAX_LEVEL) {
  2120. btrfs_err(fs_info, "log_root level too big: %d >= %d",
  2121. btrfs_super_log_root_level(sb), BTRFS_MAX_LEVEL);
  2122. ret = -EINVAL;
  2123. }
  2124. /*
  2125. * Check sectorsize and nodesize first, other check will need it.
  2126. * Check all possible sectorsize(4K, 8K, 16K, 32K, 64K) here.
  2127. */
  2128. if (!is_power_of_2(sectorsize) || sectorsize < 4096 ||
  2129. sectorsize > BTRFS_MAX_METADATA_BLOCKSIZE) {
  2130. btrfs_err(fs_info, "invalid sectorsize %llu", sectorsize);
  2131. ret = -EINVAL;
  2132. }
  2133. /* Only PAGE SIZE is supported yet */
  2134. if (sectorsize != PAGE_SIZE) {
  2135. btrfs_err(fs_info,
  2136. "sectorsize %llu not supported yet, only support %lu",
  2137. sectorsize, PAGE_SIZE);
  2138. ret = -EINVAL;
  2139. }
  2140. if (!is_power_of_2(nodesize) || nodesize < sectorsize ||
  2141. nodesize > BTRFS_MAX_METADATA_BLOCKSIZE) {
  2142. btrfs_err(fs_info, "invalid nodesize %llu", nodesize);
  2143. ret = -EINVAL;
  2144. }
  2145. if (nodesize != le32_to_cpu(sb->__unused_leafsize)) {
  2146. btrfs_err(fs_info, "invalid leafsize %u, should be %llu",
  2147. le32_to_cpu(sb->__unused_leafsize), nodesize);
  2148. ret = -EINVAL;
  2149. }
  2150. /* Root alignment check */
  2151. if (!IS_ALIGNED(btrfs_super_root(sb), sectorsize)) {
  2152. btrfs_warn(fs_info, "tree_root block unaligned: %llu",
  2153. btrfs_super_root(sb));
  2154. ret = -EINVAL;
  2155. }
  2156. if (!IS_ALIGNED(btrfs_super_chunk_root(sb), sectorsize)) {
  2157. btrfs_warn(fs_info, "chunk_root block unaligned: %llu",
  2158. btrfs_super_chunk_root(sb));
  2159. ret = -EINVAL;
  2160. }
  2161. if (!IS_ALIGNED(btrfs_super_log_root(sb), sectorsize)) {
  2162. btrfs_warn(fs_info, "log_root block unaligned: %llu",
  2163. btrfs_super_log_root(sb));
  2164. ret = -EINVAL;
  2165. }
  2166. if (memcmp(fs_info->fs_devices->fsid, fs_info->super_copy->fsid,
  2167. BTRFS_FSID_SIZE)) {
  2168. btrfs_err(fs_info,
  2169. "superblock fsid doesn't match fsid of fs_devices: %pU != %pU",
  2170. fs_info->super_copy->fsid, fs_info->fs_devices->fsid);
  2171. ret = -EINVAL;
  2172. }
  2173. if (btrfs_fs_incompat(fs_info, METADATA_UUID) &&
  2174. memcmp(fs_info->fs_devices->metadata_uuid,
  2175. fs_info->super_copy->metadata_uuid, BTRFS_FSID_SIZE)) {
  2176. btrfs_err(fs_info,
  2177. "superblock metadata_uuid doesn't match metadata uuid of fs_devices: %pU != %pU",
  2178. fs_info->super_copy->metadata_uuid,
  2179. fs_info->fs_devices->metadata_uuid);
  2180. ret = -EINVAL;
  2181. }
  2182. if (memcmp(fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid,
  2183. BTRFS_FSID_SIZE) != 0) {
  2184. btrfs_err(fs_info,
  2185. "dev_item UUID does not match metadata fsid: %pU != %pU",
  2186. fs_info->fs_devices->metadata_uuid, sb->dev_item.fsid);
  2187. ret = -EINVAL;
  2188. }
  2189. /*
  2190. * Hint to catch really bogus numbers, bitflips or so, more exact checks are
  2191. * done later
  2192. */
  2193. if (btrfs_super_bytes_used(sb) < 6 * btrfs_super_nodesize(sb)) {
  2194. btrfs_err(fs_info, "bytes_used is too small %llu",
  2195. btrfs_super_bytes_used(sb));
  2196. ret = -EINVAL;
  2197. }
  2198. if (!is_power_of_2(btrfs_super_stripesize(sb))) {
  2199. btrfs_err(fs_info, "invalid stripesize %u",
  2200. btrfs_super_stripesize(sb));
  2201. ret = -EINVAL;
  2202. }
  2203. if (btrfs_super_num_devices(sb) > (1UL << 31))
  2204. btrfs_warn(fs_info, "suspicious number of devices: %llu",
  2205. btrfs_super_num_devices(sb));
  2206. if (btrfs_super_num_devices(sb) == 0) {
  2207. btrfs_err(fs_info, "number of devices is 0");
  2208. ret = -EINVAL;
  2209. }
  2210. if (mirror_num >= 0 &&
  2211. btrfs_super_bytenr(sb) != btrfs_sb_offset(mirror_num)) {
  2212. btrfs_err(fs_info, "super offset mismatch %llu != %u",
  2213. btrfs_super_bytenr(sb), BTRFS_SUPER_INFO_OFFSET);
  2214. ret = -EINVAL;
  2215. }
  2216. /*
  2217. * Obvious sys_chunk_array corruptions, it must hold at least one key
  2218. * and one chunk
  2219. */
  2220. if (btrfs_super_sys_array_size(sb) > BTRFS_SYSTEM_CHUNK_ARRAY_SIZE) {
  2221. btrfs_err(fs_info, "system chunk array too big %u > %u",
  2222. btrfs_super_sys_array_size(sb),
  2223. BTRFS_SYSTEM_CHUNK_ARRAY_SIZE);
  2224. ret = -EINVAL;
  2225. }
  2226. if (btrfs_super_sys_array_size(sb) < sizeof(struct btrfs_disk_key)
  2227. + sizeof(struct btrfs_chunk)) {
  2228. btrfs_err(fs_info, "system chunk array too small %u < %zu",
  2229. btrfs_super_sys_array_size(sb),
  2230. sizeof(struct btrfs_disk_key)
  2231. + sizeof(struct btrfs_chunk));
  2232. ret = -EINVAL;
  2233. }
  2234. /*
  2235. * The generation is a global counter, we'll trust it more than the others
  2236. * but it's still possible that it's the one that's wrong.
  2237. */
  2238. if (btrfs_super_generation(sb) < btrfs_super_chunk_root_generation(sb))
  2239. btrfs_warn(fs_info,
  2240. "suspicious: generation < chunk_root_generation: %llu < %llu",
  2241. btrfs_super_generation(sb),
  2242. btrfs_super_chunk_root_generation(sb));
  2243. if (btrfs_super_generation(sb) < btrfs_super_cache_generation(sb)
  2244. && btrfs_super_cache_generation(sb) != (u64)-1)
  2245. btrfs_warn(fs_info,
  2246. "suspicious: generation < cache_generation: %llu < %llu",
  2247. btrfs_super_generation(sb),
  2248. btrfs_super_cache_generation(sb));
  2249. return ret;
  2250. }
  2251. /*
  2252. * Validation of super block at mount time.
  2253. * Some checks already done early at mount time, like csum type and incompat
  2254. * flags will be skipped.
  2255. */
  2256. static int btrfs_validate_mount_super(struct btrfs_fs_info *fs_info)
  2257. {
  2258. return validate_super(fs_info, fs_info->super_copy, 0);
  2259. }
  2260. /*
  2261. * Validation of super block at write time.
  2262. * Some checks like bytenr check will be skipped as their values will be
  2263. * overwritten soon.
  2264. * Extra checks like csum type and incompat flags will be done here.
  2265. */
  2266. static int btrfs_validate_write_super(struct btrfs_fs_info *fs_info,
  2267. struct btrfs_super_block *sb)
  2268. {
  2269. int ret;
  2270. ret = validate_super(fs_info, sb, -1);
  2271. if (ret < 0)
  2272. goto out;
  2273. if (!btrfs_supported_super_csum(btrfs_super_csum_type(sb))) {
  2274. ret = -EUCLEAN;
  2275. btrfs_err(fs_info, "invalid csum type, has %u want %u",
  2276. btrfs_super_csum_type(sb), BTRFS_CSUM_TYPE_CRC32);
  2277. goto out;
  2278. }
  2279. if (btrfs_super_incompat_flags(sb) & ~BTRFS_FEATURE_INCOMPAT_SUPP) {
  2280. ret = -EUCLEAN;
  2281. btrfs_err(fs_info,
  2282. "invalid incompat flags, has 0x%llx valid mask 0x%llx",
  2283. btrfs_super_incompat_flags(sb),
  2284. (unsigned long long)BTRFS_FEATURE_INCOMPAT_SUPP);
  2285. goto out;
  2286. }
  2287. out:
  2288. if (ret < 0)
  2289. btrfs_err(fs_info,
  2290. "super block corruption detected before writing it to disk");
  2291. return ret;
  2292. }
  2293. static int __cold init_tree_roots(struct btrfs_fs_info *fs_info)
  2294. {
  2295. int backup_index = find_newest_super_backup(fs_info);
  2296. struct btrfs_super_block *sb = fs_info->super_copy;
  2297. struct btrfs_root *tree_root = fs_info->tree_root;
  2298. bool handle_error = false;
  2299. int ret = 0;
  2300. int i;
  2301. for (i = 0; i < BTRFS_NUM_BACKUP_ROOTS; i++) {
  2302. u64 generation;
  2303. int level;
  2304. if (handle_error) {
  2305. if (!IS_ERR(tree_root->node))
  2306. free_extent_buffer(tree_root->node);
  2307. tree_root->node = NULL;
  2308. if (!btrfs_test_opt(fs_info, USEBACKUPROOT))
  2309. break;
  2310. free_root_pointers(fs_info, 0);
  2311. /*
  2312. * Don't use the log in recovery mode, it won't be
  2313. * valid
  2314. */
  2315. btrfs_set_super_log_root(sb, 0);
  2316. /* We can't trust the free space cache either */
  2317. btrfs_set_opt(fs_info->mount_opt, CLEAR_CACHE);
  2318. ret = read_backup_root(fs_info, i);
  2319. backup_index = ret;
  2320. if (ret < 0)
  2321. return ret;
  2322. }
  2323. generation = btrfs_super_generation(sb);
  2324. level = btrfs_super_root_level(sb);
  2325. tree_root->node = read_tree_block(fs_info, btrfs_super_root(sb),
  2326. generation, level, NULL);
  2327. if (IS_ERR(tree_root->node)) {
  2328. handle_error = true;
  2329. ret = PTR_ERR(tree_root->node);
  2330. tree_root->node = NULL;
  2331. btrfs_warn(fs_info, "couldn't read tree root");
  2332. continue;
  2333. } else if (!extent_buffer_uptodate(tree_root->node)) {
  2334. handle_error = true;
  2335. ret = -EIO;
  2336. btrfs_warn(fs_info, "error while reading tree root");
  2337. continue;
  2338. }
  2339. btrfs_set_root_node(&tree_root->root_item, tree_root->node);
  2340. tree_root->commit_root = btrfs_root_node(tree_root);
  2341. btrfs_set_root_refs(&tree_root->root_item, 1);
  2342. /*
  2343. * No need to hold btrfs_root::objectid_mutex since the fs
  2344. * hasn't been fully initialised and we are the only user
  2345. */
  2346. ret = btrfs_find_highest_objectid(tree_root,
  2347. &tree_root->highest_objectid);
  2348. if (ret < 0) {
  2349. handle_error = true;
  2350. continue;
  2351. }
  2352. ASSERT(tree_root->highest_objectid <= BTRFS_LAST_FREE_OBJECTID);
  2353. ret = btrfs_read_roots(fs_info);
  2354. if (ret < 0) {
  2355. handle_error = true;
  2356. continue;
  2357. }
  2358. /* All successful */
  2359. fs_info->generation = generation;
  2360. fs_info->last_trans_committed = generation;
  2361. /* Always begin writing backup roots after the one being used */
  2362. if (backup_index < 0) {
  2363. fs_info->backup_root_index = 0;
  2364. } else {
  2365. fs_info->backup_root_index = backup_index + 1;
  2366. fs_info->backup_root_index %= BTRFS_NUM_BACKUP_ROOTS;
  2367. }
  2368. break;
  2369. }
  2370. return ret;
  2371. }
  2372. void btrfs_init_fs_info(struct btrfs_fs_info *fs_info)
  2373. {
  2374. INIT_RADIX_TREE(&fs_info->fs_roots_radix, GFP_ATOMIC);
  2375. INIT_RADIX_TREE(&fs_info->buffer_radix, GFP_ATOMIC);
  2376. INIT_LIST_HEAD(&fs_info->trans_list);
  2377. INIT_LIST_HEAD(&fs_info->dead_roots);
  2378. INIT_LIST_HEAD(&fs_info->delayed_iputs);
  2379. INIT_LIST_HEAD(&fs_info->delalloc_roots);
  2380. INIT_LIST_HEAD(&fs_info->caching_block_groups);
  2381. spin_lock_init(&fs_info->delalloc_root_lock);
  2382. spin_lock_init(&fs_info->trans_lock);
  2383. spin_lock_init(&fs_info->fs_roots_radix_lock);
  2384. spin_lock_init(&fs_info->delayed_iput_lock);
  2385. spin_lock_init(&fs_info->defrag_inodes_lock);
  2386. spin_lock_init(&fs_info->super_lock);
  2387. spin_lock_init(&fs_info->buffer_lock);
  2388. spin_lock_init(&fs_info->unused_bgs_lock);
  2389. rwlock_init(&fs_info->tree_mod_log_lock);
  2390. mutex_init(&fs_info->unused_bg_unpin_mutex);
  2391. mutex_init(&fs_info->delete_unused_bgs_mutex);
  2392. mutex_init(&fs_info->reloc_mutex);
  2393. mutex_init(&fs_info->delalloc_root_mutex);
  2394. seqlock_init(&fs_info->profiles_lock);
  2395. INIT_LIST_HEAD(&fs_info->dirty_cowonly_roots);
  2396. INIT_LIST_HEAD(&fs_info->space_info);
  2397. INIT_LIST_HEAD(&fs_info->tree_mod_seq_list);
  2398. INIT_LIST_HEAD(&fs_info->unused_bgs);
  2399. #ifdef CONFIG_BTRFS_DEBUG
  2400. INIT_LIST_HEAD(&fs_info->allocated_roots);
  2401. INIT_LIST_HEAD(&fs_info->allocated_ebs);
  2402. spin_lock_init(&fs_info->eb_leak_lock);
  2403. #endif
  2404. extent_map_tree_init(&fs_info->mapping_tree);
  2405. btrfs_init_block_rsv(&fs_info->global_block_rsv,
  2406. BTRFS_BLOCK_RSV_GLOBAL);
  2407. btrfs_init_block_rsv(&fs_info->trans_block_rsv, BTRFS_BLOCK_RSV_TRANS);
  2408. btrfs_init_block_rsv(&fs_info->chunk_block_rsv, BTRFS_BLOCK_RSV_CHUNK);
  2409. btrfs_init_block_rsv(&fs_info->empty_block_rsv, BTRFS_BLOCK_RSV_EMPTY);
  2410. btrfs_init_block_rsv(&fs_info->delayed_block_rsv,
  2411. BTRFS_BLOCK_RSV_DELOPS);
  2412. btrfs_init_block_rsv(&fs_info->delayed_refs_rsv,
  2413. BTRFS_BLOCK_RSV_DELREFS);
  2414. atomic_set(&fs_info->async_delalloc_pages, 0);
  2415. atomic_set(&fs_info->defrag_running, 0);
  2416. atomic_set(&fs_info->reada_works_cnt, 0);
  2417. atomic_set(&fs_info->nr_delayed_iputs, 0);
  2418. atomic64_set(&fs_info->tree_mod_seq, 0);
  2419. fs_info->max_inline = BTRFS_DEFAULT_MAX_INLINE;
  2420. fs_info->metadata_ratio = 0;
  2421. fs_info->defrag_inodes = RB_ROOT;
  2422. atomic64_set(&fs_info->free_chunk_space, 0);
  2423. fs_info->tree_mod_log = RB_ROOT;
  2424. fs_info->commit_interval = BTRFS_DEFAULT_COMMIT_INTERVAL;
  2425. fs_info->avg_delayed_ref_runtime = NSEC_PER_SEC >> 6; /* div by 64 */
  2426. /* readahead state */
  2427. INIT_RADIX_TREE(&fs_info->reada_tree, GFP_NOFS & ~__GFP_DIRECT_RECLAIM);
  2428. spin_lock_init(&fs_info->reada_lock);
  2429. btrfs_init_ref_verify(fs_info);
  2430. fs_info->thread_pool_size = min_t(unsigned long,
  2431. num_online_cpus() + 2, 8);
  2432. INIT_LIST_HEAD(&fs_info->ordered_roots);
  2433. spin_lock_init(&fs_info->ordered_root_lock);
  2434. btrfs_init_scrub(fs_info);
  2435. #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
  2436. fs_info->check_integrity_print_mask = 0;
  2437. #endif
  2438. btrfs_init_balance(fs_info);
  2439. btrfs_init_async_reclaim_work(fs_info);
  2440. spin_lock_init(&fs_info->block_group_cache_lock);
  2441. fs_info->block_group_cache_tree = RB_ROOT;
  2442. fs_info->first_logical_byte = (u64)-1;
  2443. extent_io_tree_init(fs_info, &fs_info->excluded_extents,
  2444. IO_TREE_FS_EXCLUDED_EXTENTS, NULL);
  2445. set_bit(BTRFS_FS_BARRIER, &fs_info->flags);
  2446. mutex_init(&fs_info->ordered_operations_mutex);
  2447. mutex_init(&fs_info->tree_log_mutex);
  2448. mutex_init(&fs_info->chunk_mutex);
  2449. mutex_init(&fs_info->transaction_kthread_mutex);
  2450. mutex_init(&fs_info->cleaner_mutex);
  2451. mutex_init(&fs_info->ro_block_group_mutex);
  2452. init_rwsem(&fs_info->commit_root_sem);
  2453. init_rwsem(&fs_info->cleanup_work_sem);
  2454. init_rwsem(&fs_info->subvol_sem);
  2455. sema_init(&fs_info->uuid_tree_rescan_sem, 1);
  2456. btrfs_init_dev_replace_locks(fs_info);
  2457. btrfs_init_qgroup(fs_info);
  2458. btrfs_discard_init(fs_info);
  2459. btrfs_init_free_cluster(&fs_info->meta_alloc_cluster);
  2460. btrfs_init_free_cluster(&fs_info->data_alloc_cluster);
  2461. init_waitqueue_head(&fs_info->transaction_throttle);
  2462. init_waitqueue_head(&fs_info->transaction_wait);
  2463. init_waitqueue_head(&fs_info->transaction_blocked_wait);
  2464. init_waitqueue_head(&fs_info->async_submit_wait);
  2465. init_waitqueue_head(&fs_info->delayed_iputs_wait);
  2466. /* Usable values until the real ones are cached from the superblock */
  2467. fs_info->nodesize = 4096;
  2468. fs_info->sectorsize = 4096;
  2469. fs_info->stripesize = 4096;
  2470. spin_lock_init(&fs_info->swapfile_pins_lock);
  2471. fs_info->swapfile_pins = RB_ROOT;
  2472. fs_info->send_in_progress = 0;
  2473. }
  2474. static int init_mount_fs_info(struct btrfs_fs_info *fs_info, struct super_block *sb)
  2475. {
  2476. int ret;
  2477. fs_info->sb = sb;
  2478. sb->s_blocksize = BTRFS_BDEV_BLOCKSIZE;
  2479. sb->s_blocksize_bits = blksize_bits(BTRFS_BDEV_BLOCKSIZE);
  2480. ret = percpu_counter_init(&fs_info->dio_bytes, 0, GFP_KERNEL);
  2481. if (ret)
  2482. return ret;
  2483. ret = percpu_counter_init(&fs_info->dirty_metadata_bytes, 0, GFP_KERNEL);
  2484. if (ret)
  2485. return ret;
  2486. fs_info->dirty_metadata_batch = PAGE_SIZE *
  2487. (1 + ilog2(nr_cpu_ids));
  2488. ret = percpu_counter_init(&fs_info->delalloc_bytes, 0, GFP_KERNEL);
  2489. if (ret)
  2490. return ret;
  2491. ret = percpu_counter_init(&fs_info->dev_replace.bio_counter, 0,
  2492. GFP_KERNEL);
  2493. if (ret)
  2494. return ret;
  2495. fs_info->delayed_root = kmalloc(sizeof(struct btrfs_delayed_root),
  2496. GFP_KERNEL);
  2497. if (!fs_info->delayed_root)
  2498. return -ENOMEM;
  2499. btrfs_init_delayed_root(fs_info->delayed_root);
  2500. return btrfs_alloc_stripe_hash_table(fs_info);
  2501. }
  2502. static int btrfs_uuid_rescan_kthread(void *data)
  2503. {
  2504. struct btrfs_fs_info *fs_info = (struct btrfs_fs_info *)data;
  2505. int ret;
  2506. /*
  2507. * 1st step is to iterate through the existing UUID tree and
  2508. * to delete all entries that contain outdated data.
  2509. * 2nd step is to add all missing entries to the UUID tree.
  2510. */
  2511. ret = btrfs_uuid_tree_iterate(fs_info);
  2512. if (ret < 0) {
  2513. if (ret != -EINTR)
  2514. btrfs_warn(fs_info, "iterating uuid_tree failed %d",
  2515. ret);
  2516. up(&fs_info->uuid_tree_rescan_sem);
  2517. return ret;
  2518. }
  2519. return btrfs_uuid_scan_kthread(data);
  2520. }
  2521. static int btrfs_check_uuid_tree(struct btrfs_fs_info *fs_info)
  2522. {
  2523. struct task_struct *task;
  2524. down(&fs_info->uuid_tree_rescan_sem);
  2525. task = kthread_run(btrfs_uuid_rescan_kthread, fs_info, "btrfs-uuid");
  2526. if (IS_ERR(task)) {
  2527. /* fs_info->update_uuid_tree_gen remains 0 in all error case */
  2528. btrfs_warn(fs_info, "failed to start uuid_rescan task");
  2529. up(&fs_info->uuid_tree_rescan_sem);
  2530. return PTR_ERR(task);
  2531. }
  2532. return 0;
  2533. }
  2534. int __cold open_ctree(struct super_block *sb, struct btrfs_fs_devices *fs_devices,
  2535. char *options)
  2536. {
  2537. u32 sectorsize;
  2538. u32 nodesize;
  2539. u32 stripesize;
  2540. u64 generation;
  2541. u64 features;
  2542. u16 csum_type;
  2543. struct btrfs_super_block *disk_super;
  2544. struct btrfs_fs_info *fs_info = btrfs_sb(sb);
  2545. struct btrfs_root *tree_root;
  2546. struct btrfs_root *chunk_root;
  2547. int ret;
  2548. int err = -EINVAL;
  2549. int clear_free_space_tree = 0;
  2550. int level;
  2551. ret = init_mount_fs_info(fs_info, sb);
  2552. if (ret) {
  2553. err = ret;
  2554. goto fail;
  2555. }
  2556. /* These need to be init'ed before we start creating inodes and such. */
  2557. tree_root = btrfs_alloc_root(fs_info, BTRFS_ROOT_TREE_OBJECTID,
  2558. GFP_KERNEL);
  2559. fs_info->tree_root = tree_root;
  2560. chunk_root = btrfs_alloc_root(fs_info, BTRFS_CHUNK_TREE_OBJECTID,
  2561. GFP_KERNEL);
  2562. fs_info->chunk_root = chunk_root;
  2563. if (!tree_root || !chunk_root) {
  2564. err = -ENOMEM;
  2565. goto fail;
  2566. }
  2567. fs_info->btree_inode = new_inode(sb);
  2568. if (!fs_info->btree_inode) {
  2569. err = -ENOMEM;
  2570. goto fail;
  2571. }
  2572. mapping_set_gfp_mask(fs_info->btree_inode->i_mapping, GFP_NOFS);
  2573. btrfs_init_btree_inode(fs_info);
  2574. invalidate_bdev(fs_devices->latest_bdev);
  2575. /*
  2576. * Read super block and check the signature bytes only
  2577. */
  2578. disk_super = btrfs_read_dev_super(fs_devices->latest_bdev);
  2579. if (IS_ERR(disk_super)) {
  2580. err = PTR_ERR(disk_super);
  2581. goto fail_alloc;
  2582. }
  2583. /*
  2584. * Verify the type first, if that or the checksum value are
  2585. * corrupted, we'll find out
  2586. */
  2587. csum_type = btrfs_super_csum_type(disk_super);
  2588. if (!btrfs_supported_super_csum(csum_type)) {
  2589. btrfs_err(fs_info, "unsupported checksum algorithm: %u",
  2590. csum_type);
  2591. err = -EINVAL;
  2592. btrfs_release_disk_super(disk_super);
  2593. goto fail_alloc;
  2594. }
  2595. ret = btrfs_init_csum_hash(fs_info, csum_type);
  2596. if (ret) {
  2597. err = ret;
  2598. btrfs_release_disk_super(disk_super);
  2599. goto fail_alloc;
  2600. }
  2601. /*
  2602. * We want to check superblock checksum, the type is stored inside.
  2603. * Pass the whole disk block of size BTRFS_SUPER_INFO_SIZE (4k).
  2604. */
  2605. if (btrfs_check_super_csum(fs_info, (u8 *)disk_super)) {
  2606. btrfs_err(fs_info, "superblock checksum mismatch");
  2607. err = -EINVAL;
  2608. btrfs_release_disk_super(disk_super);
  2609. goto fail_alloc;
  2610. }
  2611. /*
  2612. * super_copy is zeroed at allocation time and we never touch the
  2613. * following bytes up to INFO_SIZE, the checksum is calculated from
  2614. * the whole block of INFO_SIZE
  2615. */
  2616. memcpy(fs_info->super_copy, disk_super, sizeof(*fs_info->super_copy));
  2617. btrfs_release_disk_super(disk_super);
  2618. disk_super = fs_info->super_copy;
  2619. features = btrfs_super_flags(disk_super);
  2620. if (features & BTRFS_SUPER_FLAG_CHANGING_FSID_V2) {
  2621. features &= ~BTRFS_SUPER_FLAG_CHANGING_FSID_V2;
  2622. btrfs_set_super_flags(disk_super, features);
  2623. btrfs_info(fs_info,
  2624. "found metadata UUID change in progress flag, clearing");
  2625. }
  2626. memcpy(fs_info->super_for_commit, fs_info->super_copy,
  2627. sizeof(*fs_info->super_for_commit));
  2628. ret = btrfs_validate_mount_super(fs_info);
  2629. if (ret) {
  2630. btrfs_err(fs_info, "superblock contains fatal errors");
  2631. err = -EINVAL;
  2632. goto fail_alloc;
  2633. }
  2634. if (!btrfs_super_root(disk_super))
  2635. goto fail_alloc;
  2636. /* check FS state, whether FS is broken. */
  2637. if (btrfs_super_flags(disk_super) & BTRFS_SUPER_FLAG_ERROR)
  2638. set_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state);
  2639. /*
  2640. * In the long term, we'll store the compression type in the super
  2641. * block, and it'll be used for per file compression control.
  2642. */
  2643. fs_info->compress_type = BTRFS_COMPRESS_ZLIB;
  2644. /*
  2645. * Flag our filesystem as having big metadata blocks if they are bigger
  2646. * than the page size
  2647. */
  2648. if (btrfs_super_nodesize(disk_super) > PAGE_SIZE) {
  2649. if (!(features & BTRFS_FEATURE_INCOMPAT_BIG_METADATA))
  2650. btrfs_info(fs_info,
  2651. "flagging fs with big metadata feature");
  2652. features |= BTRFS_FEATURE_INCOMPAT_BIG_METADATA;
  2653. }
  2654. /* Set up fs_info before parsing mount options */
  2655. nodesize = btrfs_super_nodesize(disk_super);
  2656. sectorsize = btrfs_super_sectorsize(disk_super);
  2657. stripesize = sectorsize;
  2658. fs_info->dirty_metadata_batch = nodesize * (1 + ilog2(nr_cpu_ids));
  2659. fs_info->delalloc_batch = sectorsize * 512 * (1 + ilog2(nr_cpu_ids));
  2660. /* Cache block sizes */
  2661. fs_info->nodesize = nodesize;
  2662. fs_info->sectorsize = sectorsize;
  2663. fs_info->stripesize = stripesize;
  2664. ret = btrfs_parse_options(fs_info, options, sb->s_flags);
  2665. if (ret) {
  2666. err = ret;
  2667. goto fail_alloc;
  2668. }
  2669. features = btrfs_super_incompat_flags(disk_super) &
  2670. ~BTRFS_FEATURE_INCOMPAT_SUPP;
  2671. if (features) {
  2672. btrfs_err(fs_info,
  2673. "cannot mount because of unsupported optional features (%llx)",
  2674. features);
  2675. err = -EINVAL;
  2676. goto fail_alloc;
  2677. }
  2678. features = btrfs_super_incompat_flags(disk_super);
  2679. features |= BTRFS_FEATURE_INCOMPAT_MIXED_BACKREF;
  2680. if (fs_info->compress_type == BTRFS_COMPRESS_LZO)
  2681. features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_LZO;
  2682. else if (fs_info->compress_type == BTRFS_COMPRESS_ZSTD)
  2683. features |= BTRFS_FEATURE_INCOMPAT_COMPRESS_ZSTD;
  2684. if (features & BTRFS_FEATURE_INCOMPAT_SKINNY_METADATA)
  2685. btrfs_info(fs_info, "has skinny extents");
  2686. /*
  2687. * mixed block groups end up with duplicate but slightly offset
  2688. * extent buffers for the same range. It leads to corruptions
  2689. */
  2690. if ((features & BTRFS_FEATURE_INCOMPAT_MIXED_GROUPS) &&
  2691. (sectorsize != nodesize)) {
  2692. btrfs_err(fs_info,
  2693. "unequal nodesize/sectorsize (%u != %u) are not allowed for mixed block groups",
  2694. nodesize, sectorsize);
  2695. goto fail_alloc;
  2696. }
  2697. /*
  2698. * Needn't use the lock because there is no other task which will
  2699. * update the flag.
  2700. */
  2701. btrfs_set_super_incompat_flags(disk_super, features);
  2702. features = btrfs_super_compat_ro_flags(disk_super) &
  2703. ~BTRFS_FEATURE_COMPAT_RO_SUPP;
  2704. if (!sb_rdonly(sb) && features) {
  2705. btrfs_err(fs_info,
  2706. "cannot mount read-write because of unsupported optional features (%llx)",
  2707. features);
  2708. err = -EINVAL;
  2709. goto fail_alloc;
  2710. }
  2711. ret = btrfs_init_workqueues(fs_info, fs_devices);
  2712. if (ret) {
  2713. err = ret;
  2714. goto fail_sb_buffer;
  2715. }
  2716. sb->s_bdi->ra_pages *= btrfs_super_num_devices(disk_super);
  2717. sb->s_bdi->ra_pages = max(sb->s_bdi->ra_pages, SZ_4M / PAGE_SIZE);
  2718. sb->s_blocksize = sectorsize;
  2719. sb->s_blocksize_bits = blksize_bits(sectorsize);
  2720. memcpy(&sb->s_uuid, fs_info->fs_devices->fsid, BTRFS_FSID_SIZE);
  2721. mutex_lock(&fs_info->chunk_mutex);
  2722. ret = btrfs_read_sys_array(fs_info);
  2723. mutex_unlock(&fs_info->chunk_mutex);
  2724. if (ret) {
  2725. btrfs_err(fs_info, "failed to read the system array: %d", ret);
  2726. goto fail_sb_buffer;
  2727. }
  2728. generation = btrfs_super_chunk_root_generation(disk_super);
  2729. level = btrfs_super_chunk_root_level(disk_super);
  2730. chunk_root->node = read_tree_block(fs_info,
  2731. btrfs_super_chunk_root(disk_super),
  2732. generation, level, NULL);
  2733. if (IS_ERR(chunk_root->node) ||
  2734. !extent_buffer_uptodate(chunk_root->node)) {
  2735. btrfs_err(fs_info, "failed to read chunk root");
  2736. if (!IS_ERR(chunk_root->node))
  2737. free_extent_buffer(chunk_root->node);
  2738. chunk_root->node = NULL;
  2739. goto fail_tree_roots;
  2740. }
  2741. btrfs_set_root_node(&chunk_root->root_item, chunk_root->node);
  2742. chunk_root->commit_root = btrfs_root_node(chunk_root);
  2743. read_extent_buffer(chunk_root->node, fs_info->chunk_tree_uuid,
  2744. offsetof(struct btrfs_header, chunk_tree_uuid),
  2745. BTRFS_UUID_SIZE);
  2746. ret = btrfs_read_chunk_tree(fs_info);
  2747. if (ret) {
  2748. btrfs_err(fs_info, "failed to read chunk tree: %d", ret);
  2749. goto fail_tree_roots;
  2750. }
  2751. /*
  2752. * Keep the devid that is marked to be the target device for the
  2753. * device replace procedure
  2754. */
  2755. btrfs_free_extra_devids(fs_devices, 0);
  2756. if (!fs_devices->latest_bdev) {
  2757. btrfs_err(fs_info, "failed to read devices");
  2758. goto fail_tree_roots;
  2759. }
  2760. ret = init_tree_roots(fs_info);
  2761. if (ret)
  2762. goto fail_tree_roots;
  2763. /*
  2764. * If we have a uuid root and we're not being told to rescan we need to
  2765. * check the generation here so we can set the
  2766. * BTRFS_FS_UPDATE_UUID_TREE_GEN bit. Otherwise we could commit the
  2767. * transaction during a balance or the log replay without updating the
  2768. * uuid generation, and then if we crash we would rescan the uuid tree,
  2769. * even though it was perfectly fine.
  2770. */
  2771. if (fs_info->uuid_root && !btrfs_test_opt(fs_info, RESCAN_UUID_TREE) &&
  2772. fs_info->generation == btrfs_super_uuid_tree_generation(disk_super))
  2773. set_bit(BTRFS_FS_UPDATE_UUID_TREE_GEN, &fs_info->flags);
  2774. ret = btrfs_verify_dev_extents(fs_info);
  2775. if (ret) {
  2776. btrfs_err(fs_info,
  2777. "failed to verify dev extents against chunks: %d",
  2778. ret);
  2779. goto fail_block_groups;
  2780. }
  2781. ret = btrfs_recover_balance(fs_info);
  2782. if (ret) {
  2783. btrfs_err(fs_info, "failed to recover balance: %d", ret);
  2784. goto fail_block_groups;
  2785. }
  2786. ret = btrfs_init_dev_stats(fs_info);
  2787. if (ret) {
  2788. btrfs_err(fs_info, "failed to init dev_stats: %d", ret);
  2789. goto fail_block_groups;
  2790. }
  2791. ret = btrfs_init_dev_replace(fs_info);
  2792. if (ret) {
  2793. btrfs_err(fs_info, "failed to init dev_replace: %d", ret);
  2794. goto fail_block_groups;
  2795. }
  2796. btrfs_free_extra_devids(fs_devices, 1);
  2797. ret = btrfs_sysfs_add_fsid(fs_devices);
  2798. if (ret) {
  2799. btrfs_err(fs_info, "failed to init sysfs fsid interface: %d",
  2800. ret);
  2801. goto fail_block_groups;
  2802. }
  2803. ret = btrfs_sysfs_add_mounted(fs_info);
  2804. if (ret) {
  2805. btrfs_err(fs_info, "failed to init sysfs interface: %d", ret);
  2806. goto fail_fsdev_sysfs;
  2807. }
  2808. ret = btrfs_init_space_info(fs_info);
  2809. if (ret) {
  2810. btrfs_err(fs_info, "failed to initialize space info: %d", ret);
  2811. goto fail_sysfs;
  2812. }
  2813. ret = btrfs_read_block_groups(fs_info);
  2814. if (ret) {
  2815. btrfs_err(fs_info, "failed to read block groups: %d", ret);
  2816. goto fail_sysfs;
  2817. }
  2818. if (!sb_rdonly(sb) && fs_info->fs_devices->missing_devices &&
  2819. !btrfs_check_rw_degradable(fs_info, NULL)) {
  2820. btrfs_warn(fs_info,
  2821. "writable mount is not allowed due to too many missing devices");
  2822. goto fail_sysfs;
  2823. }
  2824. fs_info->cleaner_kthread = kthread_run(cleaner_kthread, tree_root,
  2825. "btrfs-cleaner");
  2826. if (IS_ERR(fs_info->cleaner_kthread))
  2827. goto fail_sysfs;
  2828. fs_info->transaction_kthread = kthread_run(transaction_kthread,
  2829. tree_root,
  2830. "btrfs-transaction");
  2831. if (IS_ERR(fs_info->transaction_kthread))
  2832. goto fail_cleaner;
  2833. if (!btrfs_test_opt(fs_info, NOSSD) &&
  2834. !fs_info->fs_devices->rotating) {
  2835. btrfs_set_and_info(fs_info, SSD, "enabling ssd optimizations");
  2836. }
  2837. /*
  2838. * Mount does not set all options immediately, we can do it now and do
  2839. * not have to wait for transaction commit
  2840. */
  2841. btrfs_apply_pending_changes(fs_info);
  2842. #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
  2843. if (btrfs_test_opt(fs_info, CHECK_INTEGRITY)) {
  2844. ret = btrfsic_mount(fs_info, fs_devices,
  2845. btrfs_test_opt(fs_info,
  2846. CHECK_INTEGRITY_INCLUDING_EXTENT_DATA) ?
  2847. 1 : 0,
  2848. fs_info->check_integrity_print_mask);
  2849. if (ret)
  2850. btrfs_warn(fs_info,
  2851. "failed to initialize integrity check module: %d",
  2852. ret);
  2853. }
  2854. #endif
  2855. ret = btrfs_read_qgroup_config(fs_info);
  2856. if (ret)
  2857. goto fail_trans_kthread;
  2858. if (btrfs_build_ref_tree(fs_info))
  2859. btrfs_err(fs_info, "couldn't build ref tree");
  2860. /* do not make disk changes in broken FS or nologreplay is given */
  2861. if (btrfs_super_log_root(disk_super) != 0 &&
  2862. !btrfs_test_opt(fs_info, NOLOGREPLAY)) {
  2863. btrfs_info(fs_info, "start tree-log replay");
  2864. ret = btrfs_replay_log(fs_info, fs_devices);
  2865. if (ret) {
  2866. err = ret;
  2867. goto fail_qgroup;
  2868. }
  2869. }
  2870. ret = btrfs_find_orphan_roots(fs_info);
  2871. if (ret)
  2872. goto fail_qgroup;
  2873. if (!sb_rdonly(sb)) {
  2874. ret = btrfs_cleanup_fs_roots(fs_info);
  2875. if (ret)
  2876. goto fail_qgroup;
  2877. mutex_lock(&fs_info->cleaner_mutex);
  2878. ret = btrfs_recover_relocation(tree_root);
  2879. mutex_unlock(&fs_info->cleaner_mutex);
  2880. if (ret < 0) {
  2881. btrfs_warn(fs_info, "failed to recover relocation: %d",
  2882. ret);
  2883. err = -EINVAL;
  2884. goto fail_qgroup;
  2885. }
  2886. }
  2887. fs_info->fs_root = btrfs_get_fs_root(fs_info, BTRFS_FS_TREE_OBJECTID, true);
  2888. if (IS_ERR(fs_info->fs_root)) {
  2889. err = PTR_ERR(fs_info->fs_root);
  2890. btrfs_warn(fs_info, "failed to read fs tree: %d", err);
  2891. fs_info->fs_root = NULL;
  2892. goto fail_qgroup;
  2893. }
  2894. if (sb_rdonly(sb))
  2895. return 0;
  2896. if (btrfs_test_opt(fs_info, CLEAR_CACHE) &&
  2897. btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
  2898. clear_free_space_tree = 1;
  2899. } else if (btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE) &&
  2900. !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE_VALID)) {
  2901. btrfs_warn(fs_info, "free space tree is invalid");
  2902. clear_free_space_tree = 1;
  2903. }
  2904. if (clear_free_space_tree) {
  2905. btrfs_info(fs_info, "clearing free space tree");
  2906. ret = btrfs_clear_free_space_tree(fs_info);
  2907. if (ret) {
  2908. btrfs_warn(fs_info,
  2909. "failed to clear free space tree: %d", ret);
  2910. close_ctree(fs_info);
  2911. return ret;
  2912. }
  2913. }
  2914. if (btrfs_test_opt(fs_info, FREE_SPACE_TREE) &&
  2915. !btrfs_fs_compat_ro(fs_info, FREE_SPACE_TREE)) {
  2916. btrfs_info(fs_info, "creating free space tree");
  2917. ret = btrfs_create_free_space_tree(fs_info);
  2918. if (ret) {
  2919. btrfs_warn(fs_info,
  2920. "failed to create free space tree: %d", ret);
  2921. close_ctree(fs_info);
  2922. return ret;
  2923. }
  2924. }
  2925. down_read(&fs_info->cleanup_work_sem);
  2926. if ((ret = btrfs_orphan_cleanup(fs_info->fs_root)) ||
  2927. (ret = btrfs_orphan_cleanup(fs_info->tree_root))) {
  2928. up_read(&fs_info->cleanup_work_sem);
  2929. close_ctree(fs_info);
  2930. return ret;
  2931. }
  2932. up_read(&fs_info->cleanup_work_sem);
  2933. ret = btrfs_resume_balance_async(fs_info);
  2934. if (ret) {
  2935. btrfs_warn(fs_info, "failed to resume balance: %d", ret);
  2936. close_ctree(fs_info);
  2937. return ret;
  2938. }
  2939. ret = btrfs_resume_dev_replace_async(fs_info);
  2940. if (ret) {
  2941. btrfs_warn(fs_info, "failed to resume device replace: %d", ret);
  2942. close_ctree(fs_info);
  2943. return ret;
  2944. }
  2945. btrfs_qgroup_rescan_resume(fs_info);
  2946. btrfs_discard_resume(fs_info);
  2947. if (!fs_info->uuid_root) {
  2948. btrfs_info(fs_info, "creating UUID tree");
  2949. ret = btrfs_create_uuid_tree(fs_info);
  2950. if (ret) {
  2951. btrfs_warn(fs_info,
  2952. "failed to create the UUID tree: %d", ret);
  2953. close_ctree(fs_info);
  2954. return ret;
  2955. }
  2956. } else if (btrfs_test_opt(fs_info, RESCAN_UUID_TREE) ||
  2957. fs_info->generation !=
  2958. btrfs_super_uuid_tree_generation(disk_super)) {
  2959. btrfs_info(fs_info, "checking UUID tree");
  2960. ret = btrfs_check_uuid_tree(fs_info);
  2961. if (ret) {
  2962. btrfs_warn(fs_info,
  2963. "failed to check the UUID tree: %d", ret);
  2964. close_ctree(fs_info);
  2965. return ret;
  2966. }
  2967. }
  2968. set_bit(BTRFS_FS_OPEN, &fs_info->flags);
  2969. /*
  2970. * backuproot only affect mount behavior, and if open_ctree succeeded,
  2971. * no need to keep the flag
  2972. */
  2973. btrfs_clear_opt(fs_info->mount_opt, USEBACKUPROOT);
  2974. return 0;
  2975. fail_qgroup:
  2976. btrfs_free_qgroup_config(fs_info);
  2977. fail_trans_kthread:
  2978. kthread_stop(fs_info->transaction_kthread);
  2979. btrfs_cleanup_transaction(fs_info);
  2980. btrfs_free_fs_roots(fs_info);
  2981. fail_cleaner:
  2982. kthread_stop(fs_info->cleaner_kthread);
  2983. /*
  2984. * make sure we're done with the btree inode before we stop our
  2985. * kthreads
  2986. */
  2987. filemap_write_and_wait(fs_info->btree_inode->i_mapping);
  2988. fail_sysfs:
  2989. btrfs_sysfs_remove_mounted(fs_info);
  2990. fail_fsdev_sysfs:
  2991. btrfs_sysfs_remove_fsid(fs_info->fs_devices);
  2992. fail_block_groups:
  2993. btrfs_put_block_group_cache(fs_info);
  2994. fail_tree_roots:
  2995. if (fs_info->data_reloc_root)
  2996. btrfs_drop_and_free_fs_root(fs_info, fs_info->data_reloc_root);
  2997. free_root_pointers(fs_info, true);
  2998. invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
  2999. fail_sb_buffer:
  3000. btrfs_stop_all_workers(fs_info);
  3001. btrfs_free_block_groups(fs_info);
  3002. fail_alloc:
  3003. btrfs_mapping_tree_free(&fs_info->mapping_tree);
  3004. iput(fs_info->btree_inode);
  3005. fail:
  3006. btrfs_close_devices(fs_info->fs_devices);
  3007. return err;
  3008. }
  3009. ALLOW_ERROR_INJECTION(open_ctree, ERRNO);
  3010. static void btrfs_end_super_write(struct bio *bio)
  3011. {
  3012. struct btrfs_device *device = bio->bi_private;
  3013. struct bio_vec *bvec;
  3014. struct bvec_iter_all iter_all;
  3015. struct page *page;
  3016. bio_for_each_segment_all(bvec, bio, iter_all) {
  3017. page = bvec->bv_page;
  3018. if (bio->bi_status) {
  3019. btrfs_warn_rl_in_rcu(device->fs_info,
  3020. "lost page write due to IO error on %s (%d)",
  3021. rcu_str_deref(device->name),
  3022. blk_status_to_errno(bio->bi_status));
  3023. ClearPageUptodate(page);
  3024. SetPageError(page);
  3025. btrfs_dev_stat_inc_and_print(device,
  3026. BTRFS_DEV_STAT_WRITE_ERRS);
  3027. } else {
  3028. SetPageUptodate(page);
  3029. }
  3030. put_page(page);
  3031. unlock_page(page);
  3032. }
  3033. bio_put(bio);
  3034. }
  3035. struct btrfs_super_block *btrfs_read_dev_one_super(struct block_device *bdev,
  3036. int copy_num)
  3037. {
  3038. struct btrfs_super_block *super;
  3039. struct page *page;
  3040. u64 bytenr;
  3041. struct address_space *mapping = bdev->bd_inode->i_mapping;
  3042. bytenr = btrfs_sb_offset(copy_num);
  3043. if (bytenr + BTRFS_SUPER_INFO_SIZE >= i_size_read(bdev->bd_inode))
  3044. return ERR_PTR(-EINVAL);
  3045. page = read_cache_page_gfp(mapping, bytenr >> PAGE_SHIFT, GFP_NOFS);
  3046. if (IS_ERR(page))
  3047. return ERR_CAST(page);
  3048. super = page_address(page);
  3049. if (btrfs_super_magic(super) != BTRFS_MAGIC) {
  3050. btrfs_release_disk_super(super);
  3051. return ERR_PTR(-ENODATA);
  3052. }
  3053. if (btrfs_super_bytenr(super) != bytenr) {
  3054. btrfs_release_disk_super(super);
  3055. return ERR_PTR(-EINVAL);
  3056. }
  3057. return super;
  3058. }
  3059. struct btrfs_super_block *btrfs_read_dev_super(struct block_device *bdev)
  3060. {
  3061. struct btrfs_super_block *super, *latest = NULL;
  3062. int i;
  3063. u64 transid = 0;
  3064. /* we would like to check all the supers, but that would make
  3065. * a btrfs mount succeed after a mkfs from a different FS.
  3066. * So, we need to add a special mount option to scan for
  3067. * later supers, using BTRFS_SUPER_MIRROR_MAX instead
  3068. */
  3069. for (i = 0; i < 1; i++) {
  3070. super = btrfs_read_dev_one_super(bdev, i);
  3071. if (IS_ERR(super))
  3072. continue;
  3073. if (!latest || btrfs_super_generation(super) > transid) {
  3074. if (latest)
  3075. btrfs_release_disk_super(super);
  3076. latest = super;
  3077. transid = btrfs_super_generation(super);
  3078. }
  3079. }
  3080. return super;
  3081. }
  3082. /*
  3083. * Write superblock @sb to the @device. Do not wait for completion, all the
  3084. * pages we use for writing are locked.
  3085. *
  3086. * Write @max_mirrors copies of the superblock, where 0 means default that fit
  3087. * the expected device size at commit time. Note that max_mirrors must be
  3088. * same for write and wait phases.
  3089. *
  3090. * Return number of errors when page is not found or submission fails.
  3091. */
  3092. static int write_dev_supers(struct btrfs_device *device,
  3093. struct btrfs_super_block *sb, int max_mirrors)
  3094. {
  3095. struct btrfs_fs_info *fs_info = device->fs_info;
  3096. struct address_space *mapping = device->bdev->bd_inode->i_mapping;
  3097. SHASH_DESC_ON_STACK(shash, fs_info->csum_shash);
  3098. int i;
  3099. int errors = 0;
  3100. u64 bytenr;
  3101. if (max_mirrors == 0)
  3102. max_mirrors = BTRFS_SUPER_MIRROR_MAX;
  3103. shash->tfm = fs_info->csum_shash;
  3104. for (i = 0; i < max_mirrors; i++) {
  3105. struct page *page;
  3106. struct bio *bio;
  3107. struct btrfs_super_block *disk_super;
  3108. bytenr = btrfs_sb_offset(i);
  3109. if (bytenr + BTRFS_SUPER_INFO_SIZE >=
  3110. device->commit_total_bytes)
  3111. break;
  3112. btrfs_set_super_bytenr(sb, bytenr);
  3113. crypto_shash_digest(shash, (const char *)sb + BTRFS_CSUM_SIZE,
  3114. BTRFS_SUPER_INFO_SIZE - BTRFS_CSUM_SIZE,
  3115. sb->csum);
  3116. page = find_or_create_page(mapping, bytenr >> PAGE_SHIFT,
  3117. GFP_NOFS);
  3118. if (!page) {
  3119. btrfs_err(device->fs_info,
  3120. "couldn't get super block page for bytenr %llu",
  3121. bytenr);
  3122. errors++;
  3123. continue;
  3124. }
  3125. /* Bump the refcount for wait_dev_supers() */
  3126. get_page(page);
  3127. disk_super = page_address(page);
  3128. memcpy(disk_super, sb, BTRFS_SUPER_INFO_SIZE);
  3129. /*
  3130. * Directly use bios here instead of relying on the page cache
  3131. * to do I/O, so we don't lose the ability to do integrity
  3132. * checking.
  3133. */
  3134. bio = bio_alloc(GFP_NOFS, 1);
  3135. bio_set_dev(bio, device->bdev);
  3136. bio->bi_iter.bi_sector = bytenr >> SECTOR_SHIFT;
  3137. bio->bi_private = device;
  3138. bio->bi_end_io = btrfs_end_super_write;
  3139. __bio_add_page(bio, page, BTRFS_SUPER_INFO_SIZE,
  3140. offset_in_page(bytenr));
  3141. /*
  3142. * We FUA only the first super block. The others we allow to
  3143. * go down lazy and there's a short window where the on-disk
  3144. * copies might still contain the older version.
  3145. */
  3146. bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_META | REQ_PRIO;
  3147. if (i == 0 && !btrfs_test_opt(device->fs_info, NOBARRIER))
  3148. bio->bi_opf |= REQ_FUA;
  3149. btrfsic_submit_bio(bio);
  3150. }
  3151. return errors < i ? 0 : -1;
  3152. }
  3153. /*
  3154. * Wait for write completion of superblocks done by write_dev_supers,
  3155. * @max_mirrors same for write and wait phases.
  3156. *
  3157. * Return number of errors when page is not found or not marked up to
  3158. * date.
  3159. */
  3160. static int wait_dev_supers(struct btrfs_device *device, int max_mirrors)
  3161. {
  3162. int i;
  3163. int errors = 0;
  3164. bool primary_failed = false;
  3165. u64 bytenr;
  3166. if (max_mirrors == 0)
  3167. max_mirrors = BTRFS_SUPER_MIRROR_MAX;
  3168. for (i = 0; i < max_mirrors; i++) {
  3169. struct page *page;
  3170. bytenr = btrfs_sb_offset(i);
  3171. if (bytenr + BTRFS_SUPER_INFO_SIZE >=
  3172. device->commit_total_bytes)
  3173. break;
  3174. page = find_get_page(device->bdev->bd_inode->i_mapping,
  3175. bytenr >> PAGE_SHIFT);
  3176. if (!page) {
  3177. errors++;
  3178. if (i == 0)
  3179. primary_failed = true;
  3180. continue;
  3181. }
  3182. /* Page is submitted locked and unlocked once the IO completes */
  3183. wait_on_page_locked(page);
  3184. if (PageError(page)) {
  3185. errors++;
  3186. if (i == 0)
  3187. primary_failed = true;
  3188. }
  3189. /* Drop our reference */
  3190. put_page(page);
  3191. /* Drop the reference from the writing run */
  3192. put_page(page);
  3193. }
  3194. /* log error, force error return */
  3195. if (primary_failed) {
  3196. btrfs_err(device->fs_info, "error writing primary super block to device %llu",
  3197. device->devid);
  3198. return -1;
  3199. }
  3200. return errors < i ? 0 : -1;
  3201. }
  3202. /*
  3203. * endio for the write_dev_flush, this will wake anyone waiting
  3204. * for the barrier when it is done
  3205. */
  3206. static void btrfs_end_empty_barrier(struct bio *bio)
  3207. {
  3208. complete(bio->bi_private);
  3209. }
  3210. /*
  3211. * Submit a flush request to the device if it supports it. Error handling is
  3212. * done in the waiting counterpart.
  3213. */
  3214. static void write_dev_flush(struct btrfs_device *device)
  3215. {
  3216. struct bio *bio = device->flush_bio;
  3217. #ifndef CONFIG_BTRFS_FS_CHECK_INTEGRITY
  3218. /*
  3219. * When a disk has write caching disabled, we skip submission of a bio
  3220. * with flush and sync requests before writing the superblock, since
  3221. * it's not needed. However when the integrity checker is enabled, this
  3222. * results in reports that there are metadata blocks referred by a
  3223. * superblock that were not properly flushed. So don't skip the bio
  3224. * submission only when the integrity checker is enabled for the sake
  3225. * of simplicity, since this is a debug tool and not meant for use in
  3226. * non-debug builds.
  3227. */
  3228. struct request_queue *q = bdev_get_queue(device->bdev);
  3229. if (!test_bit(QUEUE_FLAG_WC, &q->queue_flags))
  3230. return;
  3231. #endif
  3232. bio_reset(bio);
  3233. bio->bi_end_io = btrfs_end_empty_barrier;
  3234. bio_set_dev(bio, device->bdev);
  3235. bio->bi_opf = REQ_OP_WRITE | REQ_SYNC | REQ_PREFLUSH;
  3236. init_completion(&device->flush_wait);
  3237. bio->bi_private = &device->flush_wait;
  3238. btrfsic_submit_bio(bio);
  3239. set_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
  3240. }
  3241. /*
  3242. * If the flush bio has been submitted by write_dev_flush, wait for it.
  3243. */
  3244. static blk_status_t wait_dev_flush(struct btrfs_device *device)
  3245. {
  3246. struct bio *bio = device->flush_bio;
  3247. if (!test_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state))
  3248. return BLK_STS_OK;
  3249. clear_bit(BTRFS_DEV_STATE_FLUSH_SENT, &device->dev_state);
  3250. wait_for_completion_io(&device->flush_wait);
  3251. return bio->bi_status;
  3252. }
  3253. static int check_barrier_error(struct btrfs_fs_info *fs_info)
  3254. {
  3255. if (!btrfs_check_rw_degradable(fs_info, NULL))
  3256. return -EIO;
  3257. return 0;
  3258. }
  3259. /*
  3260. * send an empty flush down to each device in parallel,
  3261. * then wait for them
  3262. */
  3263. static int barrier_all_devices(struct btrfs_fs_info *info)
  3264. {
  3265. struct list_head *head;
  3266. struct btrfs_device *dev;
  3267. int errors_wait = 0;
  3268. blk_status_t ret;
  3269. lockdep_assert_held(&info->fs_devices->device_list_mutex);
  3270. /* send down all the barriers */
  3271. head = &info->fs_devices->devices;
  3272. list_for_each_entry(dev, head, dev_list) {
  3273. if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
  3274. continue;
  3275. if (!dev->bdev)
  3276. continue;
  3277. if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
  3278. !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
  3279. continue;
  3280. write_dev_flush(dev);
  3281. dev->last_flush_error = BLK_STS_OK;
  3282. }
  3283. /* wait for all the barriers */
  3284. list_for_each_entry(dev, head, dev_list) {
  3285. if (test_bit(BTRFS_DEV_STATE_MISSING, &dev->dev_state))
  3286. continue;
  3287. if (!dev->bdev) {
  3288. errors_wait++;
  3289. continue;
  3290. }
  3291. if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
  3292. !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
  3293. continue;
  3294. ret = wait_dev_flush(dev);
  3295. if (ret) {
  3296. dev->last_flush_error = ret;
  3297. btrfs_dev_stat_inc_and_print(dev,
  3298. BTRFS_DEV_STAT_FLUSH_ERRS);
  3299. errors_wait++;
  3300. }
  3301. }
  3302. if (errors_wait) {
  3303. /*
  3304. * At some point we need the status of all disks
  3305. * to arrive at the volume status. So error checking
  3306. * is being pushed to a separate loop.
  3307. */
  3308. return check_barrier_error(info);
  3309. }
  3310. return 0;
  3311. }
  3312. int btrfs_get_num_tolerated_disk_barrier_failures(u64 flags)
  3313. {
  3314. int raid_type;
  3315. int min_tolerated = INT_MAX;
  3316. if ((flags & BTRFS_BLOCK_GROUP_PROFILE_MASK) == 0 ||
  3317. (flags & BTRFS_AVAIL_ALLOC_BIT_SINGLE))
  3318. min_tolerated = min_t(int, min_tolerated,
  3319. btrfs_raid_array[BTRFS_RAID_SINGLE].
  3320. tolerated_failures);
  3321. for (raid_type = 0; raid_type < BTRFS_NR_RAID_TYPES; raid_type++) {
  3322. if (raid_type == BTRFS_RAID_SINGLE)
  3323. continue;
  3324. if (!(flags & btrfs_raid_array[raid_type].bg_flag))
  3325. continue;
  3326. min_tolerated = min_t(int, min_tolerated,
  3327. btrfs_raid_array[raid_type].
  3328. tolerated_failures);
  3329. }
  3330. if (min_tolerated == INT_MAX) {
  3331. pr_warn("BTRFS: unknown raid flag: %llu", flags);
  3332. min_tolerated = 0;
  3333. }
  3334. return min_tolerated;
  3335. }
  3336. int write_all_supers(struct btrfs_fs_info *fs_info, int max_mirrors)
  3337. {
  3338. struct list_head *head;
  3339. struct btrfs_device *dev;
  3340. struct btrfs_super_block *sb;
  3341. struct btrfs_dev_item *dev_item;
  3342. int ret;
  3343. int do_barriers;
  3344. int max_errors;
  3345. int total_errors = 0;
  3346. u64 flags;
  3347. do_barriers = !btrfs_test_opt(fs_info, NOBARRIER);
  3348. /*
  3349. * max_mirrors == 0 indicates we're from commit_transaction,
  3350. * not from fsync where the tree roots in fs_info have not
  3351. * been consistent on disk.
  3352. */
  3353. if (max_mirrors == 0)
  3354. backup_super_roots(fs_info);
  3355. sb = fs_info->super_for_commit;
  3356. dev_item = &sb->dev_item;
  3357. mutex_lock(&fs_info->fs_devices->device_list_mutex);
  3358. head = &fs_info->fs_devices->devices;
  3359. max_errors = btrfs_super_num_devices(fs_info->super_copy) - 1;
  3360. if (do_barriers) {
  3361. ret = barrier_all_devices(fs_info);
  3362. if (ret) {
  3363. mutex_unlock(
  3364. &fs_info->fs_devices->device_list_mutex);
  3365. btrfs_handle_fs_error(fs_info, ret,
  3366. "errors while submitting device barriers.");
  3367. return ret;
  3368. }
  3369. }
  3370. list_for_each_entry(dev, head, dev_list) {
  3371. if (!dev->bdev) {
  3372. total_errors++;
  3373. continue;
  3374. }
  3375. if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
  3376. !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
  3377. continue;
  3378. btrfs_set_stack_device_generation(dev_item, 0);
  3379. btrfs_set_stack_device_type(dev_item, dev->type);
  3380. btrfs_set_stack_device_id(dev_item, dev->devid);
  3381. btrfs_set_stack_device_total_bytes(dev_item,
  3382. dev->commit_total_bytes);
  3383. btrfs_set_stack_device_bytes_used(dev_item,
  3384. dev->commit_bytes_used);
  3385. btrfs_set_stack_device_io_align(dev_item, dev->io_align);
  3386. btrfs_set_stack_device_io_width(dev_item, dev->io_width);
  3387. btrfs_set_stack_device_sector_size(dev_item, dev->sector_size);
  3388. memcpy(dev_item->uuid, dev->uuid, BTRFS_UUID_SIZE);
  3389. memcpy(dev_item->fsid, dev->fs_devices->metadata_uuid,
  3390. BTRFS_FSID_SIZE);
  3391. flags = btrfs_super_flags(sb);
  3392. btrfs_set_super_flags(sb, flags | BTRFS_HEADER_FLAG_WRITTEN);
  3393. ret = btrfs_validate_write_super(fs_info, sb);
  3394. if (ret < 0) {
  3395. mutex_unlock(&fs_info->fs_devices->device_list_mutex);
  3396. btrfs_handle_fs_error(fs_info, -EUCLEAN,
  3397. "unexpected superblock corruption detected");
  3398. return -EUCLEAN;
  3399. }
  3400. ret = write_dev_supers(dev, sb, max_mirrors);
  3401. if (ret)
  3402. total_errors++;
  3403. }
  3404. if (total_errors > max_errors) {
  3405. btrfs_err(fs_info, "%d errors while writing supers",
  3406. total_errors);
  3407. mutex_unlock(&fs_info->fs_devices->device_list_mutex);
  3408. /* FUA is masked off if unsupported and can't be the reason */
  3409. btrfs_handle_fs_error(fs_info, -EIO,
  3410. "%d errors while writing supers",
  3411. total_errors);
  3412. return -EIO;
  3413. }
  3414. total_errors = 0;
  3415. list_for_each_entry(dev, head, dev_list) {
  3416. if (!dev->bdev)
  3417. continue;
  3418. if (!test_bit(BTRFS_DEV_STATE_IN_FS_METADATA, &dev->dev_state) ||
  3419. !test_bit(BTRFS_DEV_STATE_WRITEABLE, &dev->dev_state))
  3420. continue;
  3421. ret = wait_dev_supers(dev, max_mirrors);
  3422. if (ret)
  3423. total_errors++;
  3424. }
  3425. mutex_unlock(&fs_info->fs_devices->device_list_mutex);
  3426. if (total_errors > max_errors) {
  3427. btrfs_handle_fs_error(fs_info, -EIO,
  3428. "%d errors while writing supers",
  3429. total_errors);
  3430. return -EIO;
  3431. }
  3432. return 0;
  3433. }
  3434. /* Drop a fs root from the radix tree and free it. */
  3435. void btrfs_drop_and_free_fs_root(struct btrfs_fs_info *fs_info,
  3436. struct btrfs_root *root)
  3437. {
  3438. bool drop_ref = false;
  3439. spin_lock(&fs_info->fs_roots_radix_lock);
  3440. radix_tree_delete(&fs_info->fs_roots_radix,
  3441. (unsigned long)root->root_key.objectid);
  3442. if (test_and_clear_bit(BTRFS_ROOT_IN_RADIX, &root->state))
  3443. drop_ref = true;
  3444. spin_unlock(&fs_info->fs_roots_radix_lock);
  3445. if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state)) {
  3446. ASSERT(root->log_root == NULL);
  3447. if (root->reloc_root) {
  3448. btrfs_put_root(root->reloc_root);
  3449. root->reloc_root = NULL;
  3450. }
  3451. }
  3452. if (root->free_ino_pinned)
  3453. __btrfs_remove_free_space_cache(root->free_ino_pinned);
  3454. if (root->free_ino_ctl)
  3455. __btrfs_remove_free_space_cache(root->free_ino_ctl);
  3456. if (root->ino_cache_inode) {
  3457. iput(root->ino_cache_inode);
  3458. root->ino_cache_inode = NULL;
  3459. }
  3460. if (drop_ref)
  3461. btrfs_put_root(root);
  3462. }
  3463. int btrfs_cleanup_fs_roots(struct btrfs_fs_info *fs_info)
  3464. {
  3465. u64 root_objectid = 0;
  3466. struct btrfs_root *gang[8];
  3467. int i = 0;
  3468. int err = 0;
  3469. unsigned int ret = 0;
  3470. while (1) {
  3471. spin_lock(&fs_info->fs_roots_radix_lock);
  3472. ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
  3473. (void **)gang, root_objectid,
  3474. ARRAY_SIZE(gang));
  3475. if (!ret) {
  3476. spin_unlock(&fs_info->fs_roots_radix_lock);
  3477. break;
  3478. }
  3479. root_objectid = gang[ret - 1]->root_key.objectid + 1;
  3480. for (i = 0; i < ret; i++) {
  3481. /* Avoid to grab roots in dead_roots */
  3482. if (btrfs_root_refs(&gang[i]->root_item) == 0) {
  3483. gang[i] = NULL;
  3484. continue;
  3485. }
  3486. /* grab all the search result for later use */
  3487. gang[i] = btrfs_grab_root(gang[i]);
  3488. }
  3489. spin_unlock(&fs_info->fs_roots_radix_lock);
  3490. for (i = 0; i < ret; i++) {
  3491. if (!gang[i])
  3492. continue;
  3493. root_objectid = gang[i]->root_key.objectid;
  3494. err = btrfs_orphan_cleanup(gang[i]);
  3495. if (err)
  3496. break;
  3497. btrfs_put_root(gang[i]);
  3498. }
  3499. root_objectid++;
  3500. }
  3501. /* release the uncleaned roots due to error */
  3502. for (; i < ret; i++) {
  3503. if (gang[i])
  3504. btrfs_put_root(gang[i]);
  3505. }
  3506. return err;
  3507. }
  3508. int btrfs_commit_super(struct btrfs_fs_info *fs_info)
  3509. {
  3510. struct btrfs_root *root = fs_info->tree_root;
  3511. struct btrfs_trans_handle *trans;
  3512. mutex_lock(&fs_info->cleaner_mutex);
  3513. btrfs_run_delayed_iputs(fs_info);
  3514. mutex_unlock(&fs_info->cleaner_mutex);
  3515. wake_up_process(fs_info->cleaner_kthread);
  3516. /* wait until ongoing cleanup work done */
  3517. down_write(&fs_info->cleanup_work_sem);
  3518. up_write(&fs_info->cleanup_work_sem);
  3519. trans = btrfs_join_transaction(root);
  3520. if (IS_ERR(trans))
  3521. return PTR_ERR(trans);
  3522. return btrfs_commit_transaction(trans);
  3523. }
  3524. void __cold close_ctree(struct btrfs_fs_info *fs_info)
  3525. {
  3526. int ret;
  3527. set_bit(BTRFS_FS_CLOSING_START, &fs_info->flags);
  3528. /*
  3529. * We don't want the cleaner to start new transactions, add more delayed
  3530. * iputs, etc. while we're closing. We can't use kthread_stop() yet
  3531. * because that frees the task_struct, and the transaction kthread might
  3532. * still try to wake up the cleaner.
  3533. */
  3534. kthread_park(fs_info->cleaner_kthread);
  3535. /* wait for the qgroup rescan worker to stop */
  3536. btrfs_qgroup_wait_for_completion(fs_info, false);
  3537. /* wait for the uuid_scan task to finish */
  3538. down(&fs_info->uuid_tree_rescan_sem);
  3539. /* avoid complains from lockdep et al., set sem back to initial state */
  3540. up(&fs_info->uuid_tree_rescan_sem);
  3541. /* pause restriper - we want to resume on mount */
  3542. btrfs_pause_balance(fs_info);
  3543. btrfs_dev_replace_suspend_for_unmount(fs_info);
  3544. btrfs_scrub_cancel(fs_info);
  3545. /* wait for any defraggers to finish */
  3546. wait_event(fs_info->transaction_wait,
  3547. (atomic_read(&fs_info->defrag_running) == 0));
  3548. /* clear out the rbtree of defraggable inodes */
  3549. btrfs_cleanup_defrag_inodes(fs_info);
  3550. cancel_work_sync(&fs_info->async_reclaim_work);
  3551. cancel_work_sync(&fs_info->async_data_reclaim_work);
  3552. /* Cancel or finish ongoing discard work */
  3553. btrfs_discard_cleanup(fs_info);
  3554. if (!sb_rdonly(fs_info->sb)) {
  3555. /*
  3556. * The cleaner kthread is stopped, so do one final pass over
  3557. * unused block groups.
  3558. */
  3559. btrfs_delete_unused_bgs(fs_info);
  3560. /*
  3561. * There might be existing delayed inode workers still running
  3562. * and holding an empty delayed inode item. We must wait for
  3563. * them to complete first because they can create a transaction.
  3564. * This happens when someone calls btrfs_balance_delayed_items()
  3565. * and then a transaction commit runs the same delayed nodes
  3566. * before any delayed worker has done something with the nodes.
  3567. * We must wait for any worker here and not at transaction
  3568. * commit time since that could cause a deadlock.
  3569. * This is a very rare case.
  3570. */
  3571. btrfs_flush_workqueue(fs_info->delayed_workers);
  3572. ret = btrfs_commit_super(fs_info);
  3573. if (ret)
  3574. btrfs_err(fs_info, "commit super ret %d", ret);
  3575. }
  3576. if (test_bit(BTRFS_FS_STATE_ERROR, &fs_info->fs_state) ||
  3577. test_bit(BTRFS_FS_STATE_TRANS_ABORTED, &fs_info->fs_state))
  3578. btrfs_error_commit_super(fs_info);
  3579. kthread_stop(fs_info->transaction_kthread);
  3580. kthread_stop(fs_info->cleaner_kthread);
  3581. ASSERT(list_empty(&fs_info->delayed_iputs));
  3582. set_bit(BTRFS_FS_CLOSING_DONE, &fs_info->flags);
  3583. if (btrfs_check_quota_leak(fs_info)) {
  3584. WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
  3585. btrfs_err(fs_info, "qgroup reserved space leaked");
  3586. }
  3587. btrfs_free_qgroup_config(fs_info);
  3588. ASSERT(list_empty(&fs_info->delalloc_roots));
  3589. if (percpu_counter_sum(&fs_info->delalloc_bytes)) {
  3590. btrfs_info(fs_info, "at unmount delalloc count %lld",
  3591. percpu_counter_sum(&fs_info->delalloc_bytes));
  3592. }
  3593. if (percpu_counter_sum(&fs_info->dio_bytes))
  3594. btrfs_info(fs_info, "at unmount dio bytes count %lld",
  3595. percpu_counter_sum(&fs_info->dio_bytes));
  3596. btrfs_sysfs_remove_mounted(fs_info);
  3597. btrfs_sysfs_remove_fsid(fs_info->fs_devices);
  3598. btrfs_put_block_group_cache(fs_info);
  3599. /*
  3600. * we must make sure there is not any read request to
  3601. * submit after we stopping all workers.
  3602. */
  3603. invalidate_inode_pages2(fs_info->btree_inode->i_mapping);
  3604. btrfs_stop_all_workers(fs_info);
  3605. clear_bit(BTRFS_FS_OPEN, &fs_info->flags);
  3606. free_root_pointers(fs_info, true);
  3607. btrfs_free_fs_roots(fs_info);
  3608. /*
  3609. * We must free the block groups after dropping the fs_roots as we could
  3610. * have had an IO error and have left over tree log blocks that aren't
  3611. * cleaned up until the fs roots are freed. This makes the block group
  3612. * accounting appear to be wrong because there's pending reserved bytes,
  3613. * so make sure we do the block group cleanup afterwards.
  3614. */
  3615. btrfs_free_block_groups(fs_info);
  3616. iput(fs_info->btree_inode);
  3617. #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
  3618. if (btrfs_test_opt(fs_info, CHECK_INTEGRITY))
  3619. btrfsic_unmount(fs_info->fs_devices);
  3620. #endif
  3621. btrfs_mapping_tree_free(&fs_info->mapping_tree);
  3622. btrfs_close_devices(fs_info->fs_devices);
  3623. }
  3624. int btrfs_buffer_uptodate(struct extent_buffer *buf, u64 parent_transid,
  3625. int atomic)
  3626. {
  3627. int ret;
  3628. struct inode *btree_inode = buf->pages[0]->mapping->host;
  3629. ret = extent_buffer_uptodate(buf);
  3630. if (!ret)
  3631. return ret;
  3632. ret = verify_parent_transid(&BTRFS_I(btree_inode)->io_tree, buf,
  3633. parent_transid, atomic);
  3634. if (ret == -EAGAIN)
  3635. return ret;
  3636. return !ret;
  3637. }
  3638. void btrfs_mark_buffer_dirty(struct extent_buffer *buf)
  3639. {
  3640. struct btrfs_fs_info *fs_info;
  3641. struct btrfs_root *root;
  3642. u64 transid = btrfs_header_generation(buf);
  3643. int was_dirty;
  3644. #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
  3645. /*
  3646. * This is a fast path so only do this check if we have sanity tests
  3647. * enabled. Normal people shouldn't be using unmapped buffers as dirty
  3648. * outside of the sanity tests.
  3649. */
  3650. if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &buf->bflags)))
  3651. return;
  3652. #endif
  3653. root = BTRFS_I(buf->pages[0]->mapping->host)->root;
  3654. fs_info = root->fs_info;
  3655. btrfs_assert_tree_locked(buf);
  3656. if (transid != fs_info->generation)
  3657. WARN(1, KERN_CRIT "btrfs transid mismatch buffer %llu, found %llu running %llu\n",
  3658. buf->start, transid, fs_info->generation);
  3659. was_dirty = set_extent_buffer_dirty(buf);
  3660. if (!was_dirty)
  3661. percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
  3662. buf->len,
  3663. fs_info->dirty_metadata_batch);
  3664. #ifdef CONFIG_BTRFS_FS_CHECK_INTEGRITY
  3665. /*
  3666. * Since btrfs_mark_buffer_dirty() can be called with item pointer set
  3667. * but item data not updated.
  3668. * So here we should only check item pointers, not item data.
  3669. */
  3670. if (btrfs_header_level(buf) == 0 &&
  3671. btrfs_check_leaf_relaxed(buf)) {
  3672. btrfs_print_leaf(buf);
  3673. ASSERT(0);
  3674. }
  3675. #endif
  3676. }
  3677. static void __btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info,
  3678. int flush_delayed)
  3679. {
  3680. /*
  3681. * looks as though older kernels can get into trouble with
  3682. * this code, they end up stuck in balance_dirty_pages forever
  3683. */
  3684. int ret;
  3685. if (current->flags & PF_MEMALLOC)
  3686. return;
  3687. if (flush_delayed)
  3688. btrfs_balance_delayed_items(fs_info);
  3689. ret = __percpu_counter_compare(&fs_info->dirty_metadata_bytes,
  3690. BTRFS_DIRTY_METADATA_THRESH,
  3691. fs_info->dirty_metadata_batch);
  3692. if (ret > 0) {
  3693. balance_dirty_pages_ratelimited(fs_info->btree_inode->i_mapping);
  3694. }
  3695. }
  3696. void btrfs_btree_balance_dirty(struct btrfs_fs_info *fs_info)
  3697. {
  3698. __btrfs_btree_balance_dirty(fs_info, 1);
  3699. }
  3700. void btrfs_btree_balance_dirty_nodelay(struct btrfs_fs_info *fs_info)
  3701. {
  3702. __btrfs_btree_balance_dirty(fs_info, 0);
  3703. }
  3704. int btrfs_read_buffer(struct extent_buffer *buf, u64 parent_transid, int level,
  3705. struct btrfs_key *first_key)
  3706. {
  3707. return btree_read_extent_buffer_pages(buf, parent_transid,
  3708. level, first_key);
  3709. }
  3710. static void btrfs_error_commit_super(struct btrfs_fs_info *fs_info)
  3711. {
  3712. /* cleanup FS via transaction */
  3713. btrfs_cleanup_transaction(fs_info);
  3714. mutex_lock(&fs_info->cleaner_mutex);
  3715. btrfs_run_delayed_iputs(fs_info);
  3716. mutex_unlock(&fs_info->cleaner_mutex);
  3717. down_write(&fs_info->cleanup_work_sem);
  3718. up_write(&fs_info->cleanup_work_sem);
  3719. }
  3720. static void btrfs_drop_all_logs(struct btrfs_fs_info *fs_info)
  3721. {
  3722. struct btrfs_root *gang[8];
  3723. u64 root_objectid = 0;
  3724. int ret;
  3725. spin_lock(&fs_info->fs_roots_radix_lock);
  3726. while ((ret = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
  3727. (void **)gang, root_objectid,
  3728. ARRAY_SIZE(gang))) != 0) {
  3729. int i;
  3730. for (i = 0; i < ret; i++)
  3731. gang[i] = btrfs_grab_root(gang[i]);
  3732. spin_unlock(&fs_info->fs_roots_radix_lock);
  3733. for (i = 0; i < ret; i++) {
  3734. if (!gang[i])
  3735. continue;
  3736. root_objectid = gang[i]->root_key.objectid;
  3737. btrfs_free_log(NULL, gang[i]);
  3738. btrfs_put_root(gang[i]);
  3739. }
  3740. root_objectid++;
  3741. spin_lock(&fs_info->fs_roots_radix_lock);
  3742. }
  3743. spin_unlock(&fs_info->fs_roots_radix_lock);
  3744. btrfs_free_log_root_tree(NULL, fs_info);
  3745. }
  3746. static void btrfs_destroy_ordered_extents(struct btrfs_root *root)
  3747. {
  3748. struct btrfs_ordered_extent *ordered;
  3749. spin_lock(&root->ordered_extent_lock);
  3750. /*
  3751. * This will just short circuit the ordered completion stuff which will
  3752. * make sure the ordered extent gets properly cleaned up.
  3753. */
  3754. list_for_each_entry(ordered, &root->ordered_extents,
  3755. root_extent_list)
  3756. set_bit(BTRFS_ORDERED_IOERR, &ordered->flags);
  3757. spin_unlock(&root->ordered_extent_lock);
  3758. }
  3759. static void btrfs_destroy_all_ordered_extents(struct btrfs_fs_info *fs_info)
  3760. {
  3761. struct btrfs_root *root;
  3762. struct list_head splice;
  3763. INIT_LIST_HEAD(&splice);
  3764. spin_lock(&fs_info->ordered_root_lock);
  3765. list_splice_init(&fs_info->ordered_roots, &splice);
  3766. while (!list_empty(&splice)) {
  3767. root = list_first_entry(&splice, struct btrfs_root,
  3768. ordered_root);
  3769. list_move_tail(&root->ordered_root,
  3770. &fs_info->ordered_roots);
  3771. spin_unlock(&fs_info->ordered_root_lock);
  3772. btrfs_destroy_ordered_extents(root);
  3773. cond_resched();
  3774. spin_lock(&fs_info->ordered_root_lock);
  3775. }
  3776. spin_unlock(&fs_info->ordered_root_lock);
  3777. /*
  3778. * We need this here because if we've been flipped read-only we won't
  3779. * get sync() from the umount, so we need to make sure any ordered
  3780. * extents that haven't had their dirty pages IO start writeout yet
  3781. * actually get run and error out properly.
  3782. */
  3783. btrfs_wait_ordered_roots(fs_info, U64_MAX, 0, (u64)-1);
  3784. }
  3785. static int btrfs_destroy_delayed_refs(struct btrfs_transaction *trans,
  3786. struct btrfs_fs_info *fs_info)
  3787. {
  3788. struct rb_node *node;
  3789. struct btrfs_delayed_ref_root *delayed_refs;
  3790. struct btrfs_delayed_ref_node *ref;
  3791. int ret = 0;
  3792. delayed_refs = &trans->delayed_refs;
  3793. spin_lock(&delayed_refs->lock);
  3794. if (atomic_read(&delayed_refs->num_entries) == 0) {
  3795. spin_unlock(&delayed_refs->lock);
  3796. btrfs_debug(fs_info, "delayed_refs has NO entry");
  3797. return ret;
  3798. }
  3799. while ((node = rb_first_cached(&delayed_refs->href_root)) != NULL) {
  3800. struct btrfs_delayed_ref_head *head;
  3801. struct rb_node *n;
  3802. bool pin_bytes = false;
  3803. head = rb_entry(node, struct btrfs_delayed_ref_head,
  3804. href_node);
  3805. if (btrfs_delayed_ref_lock(delayed_refs, head))
  3806. continue;
  3807. spin_lock(&head->lock);
  3808. while ((n = rb_first_cached(&head->ref_tree)) != NULL) {
  3809. ref = rb_entry(n, struct btrfs_delayed_ref_node,
  3810. ref_node);
  3811. ref->in_tree = 0;
  3812. rb_erase_cached(&ref->ref_node, &head->ref_tree);
  3813. RB_CLEAR_NODE(&ref->ref_node);
  3814. if (!list_empty(&ref->add_list))
  3815. list_del(&ref->add_list);
  3816. atomic_dec(&delayed_refs->num_entries);
  3817. btrfs_put_delayed_ref(ref);
  3818. }
  3819. if (head->must_insert_reserved)
  3820. pin_bytes = true;
  3821. btrfs_free_delayed_extent_op(head->extent_op);
  3822. btrfs_delete_ref_head(delayed_refs, head);
  3823. spin_unlock(&head->lock);
  3824. spin_unlock(&delayed_refs->lock);
  3825. mutex_unlock(&head->mutex);
  3826. if (pin_bytes) {
  3827. struct btrfs_block_group *cache;
  3828. cache = btrfs_lookup_block_group(fs_info, head->bytenr);
  3829. BUG_ON(!cache);
  3830. spin_lock(&cache->space_info->lock);
  3831. spin_lock(&cache->lock);
  3832. cache->pinned += head->num_bytes;
  3833. btrfs_space_info_update_bytes_pinned(fs_info,
  3834. cache->space_info, head->num_bytes);
  3835. cache->reserved -= head->num_bytes;
  3836. cache->space_info->bytes_reserved -= head->num_bytes;
  3837. spin_unlock(&cache->lock);
  3838. spin_unlock(&cache->space_info->lock);
  3839. percpu_counter_add_batch(
  3840. &cache->space_info->total_bytes_pinned,
  3841. head->num_bytes, BTRFS_TOTAL_BYTES_PINNED_BATCH);
  3842. btrfs_put_block_group(cache);
  3843. btrfs_error_unpin_extent_range(fs_info, head->bytenr,
  3844. head->bytenr + head->num_bytes - 1);
  3845. }
  3846. btrfs_cleanup_ref_head_accounting(fs_info, delayed_refs, head);
  3847. btrfs_put_delayed_ref_head(head);
  3848. cond_resched();
  3849. spin_lock(&delayed_refs->lock);
  3850. }
  3851. btrfs_qgroup_destroy_extent_records(trans);
  3852. spin_unlock(&delayed_refs->lock);
  3853. return ret;
  3854. }
  3855. static void btrfs_destroy_delalloc_inodes(struct btrfs_root *root)
  3856. {
  3857. struct btrfs_inode *btrfs_inode;
  3858. struct list_head splice;
  3859. INIT_LIST_HEAD(&splice);
  3860. spin_lock(&root->delalloc_lock);
  3861. list_splice_init(&root->delalloc_inodes, &splice);
  3862. while (!list_empty(&splice)) {
  3863. struct inode *inode = NULL;
  3864. btrfs_inode = list_first_entry(&splice, struct btrfs_inode,
  3865. delalloc_inodes);
  3866. __btrfs_del_delalloc_inode(root, btrfs_inode);
  3867. spin_unlock(&root->delalloc_lock);
  3868. /*
  3869. * Make sure we get a live inode and that it'll not disappear
  3870. * meanwhile.
  3871. */
  3872. inode = igrab(&btrfs_inode->vfs_inode);
  3873. if (inode) {
  3874. invalidate_inode_pages2(inode->i_mapping);
  3875. iput(inode);
  3876. }
  3877. spin_lock(&root->delalloc_lock);
  3878. }
  3879. spin_unlock(&root->delalloc_lock);
  3880. }
  3881. static void btrfs_destroy_all_delalloc_inodes(struct btrfs_fs_info *fs_info)
  3882. {
  3883. struct btrfs_root *root;
  3884. struct list_head splice;
  3885. INIT_LIST_HEAD(&splice);
  3886. spin_lock(&fs_info->delalloc_root_lock);
  3887. list_splice_init(&fs_info->delalloc_roots, &splice);
  3888. while (!list_empty(&splice)) {
  3889. root = list_first_entry(&splice, struct btrfs_root,
  3890. delalloc_root);
  3891. root = btrfs_grab_root(root);
  3892. BUG_ON(!root);
  3893. spin_unlock(&fs_info->delalloc_root_lock);
  3894. btrfs_destroy_delalloc_inodes(root);
  3895. btrfs_put_root(root);
  3896. spin_lock(&fs_info->delalloc_root_lock);
  3897. }
  3898. spin_unlock(&fs_info->delalloc_root_lock);
  3899. }
  3900. static int btrfs_destroy_marked_extents(struct btrfs_fs_info *fs_info,
  3901. struct extent_io_tree *dirty_pages,
  3902. int mark)
  3903. {
  3904. int ret;
  3905. struct extent_buffer *eb;
  3906. u64 start = 0;
  3907. u64 end;
  3908. while (1) {
  3909. ret = find_first_extent_bit(dirty_pages, start, &start, &end,
  3910. mark, NULL);
  3911. if (ret)
  3912. break;
  3913. clear_extent_bits(dirty_pages, start, end, mark);
  3914. while (start <= end) {
  3915. eb = find_extent_buffer(fs_info, start);
  3916. start += fs_info->nodesize;
  3917. if (!eb)
  3918. continue;
  3919. wait_on_extent_buffer_writeback(eb);
  3920. if (test_and_clear_bit(EXTENT_BUFFER_DIRTY,
  3921. &eb->bflags))
  3922. clear_extent_buffer_dirty(eb);
  3923. free_extent_buffer_stale(eb);
  3924. }
  3925. }
  3926. return ret;
  3927. }
  3928. static int btrfs_destroy_pinned_extent(struct btrfs_fs_info *fs_info,
  3929. struct extent_io_tree *unpin)
  3930. {
  3931. u64 start;
  3932. u64 end;
  3933. int ret;
  3934. while (1) {
  3935. struct extent_state *cached_state = NULL;
  3936. /*
  3937. * The btrfs_finish_extent_commit() may get the same range as
  3938. * ours between find_first_extent_bit and clear_extent_dirty.
  3939. * Hence, hold the unused_bg_unpin_mutex to avoid double unpin
  3940. * the same extent range.
  3941. */
  3942. mutex_lock(&fs_info->unused_bg_unpin_mutex);
  3943. ret = find_first_extent_bit(unpin, 0, &start, &end,
  3944. EXTENT_DIRTY, &cached_state);
  3945. if (ret) {
  3946. mutex_unlock(&fs_info->unused_bg_unpin_mutex);
  3947. break;
  3948. }
  3949. clear_extent_dirty(unpin, start, end, &cached_state);
  3950. free_extent_state(cached_state);
  3951. btrfs_error_unpin_extent_range(fs_info, start, end);
  3952. mutex_unlock(&fs_info->unused_bg_unpin_mutex);
  3953. cond_resched();
  3954. }
  3955. return 0;
  3956. }
  3957. static void btrfs_cleanup_bg_io(struct btrfs_block_group *cache)
  3958. {
  3959. struct inode *inode;
  3960. inode = cache->io_ctl.inode;
  3961. if (inode) {
  3962. invalidate_inode_pages2(inode->i_mapping);
  3963. BTRFS_I(inode)->generation = 0;
  3964. cache->io_ctl.inode = NULL;
  3965. iput(inode);
  3966. }
  3967. ASSERT(cache->io_ctl.pages == NULL);
  3968. btrfs_put_block_group(cache);
  3969. }
  3970. void btrfs_cleanup_dirty_bgs(struct btrfs_transaction *cur_trans,
  3971. struct btrfs_fs_info *fs_info)
  3972. {
  3973. struct btrfs_block_group *cache;
  3974. spin_lock(&cur_trans->dirty_bgs_lock);
  3975. while (!list_empty(&cur_trans->dirty_bgs)) {
  3976. cache = list_first_entry(&cur_trans->dirty_bgs,
  3977. struct btrfs_block_group,
  3978. dirty_list);
  3979. if (!list_empty(&cache->io_list)) {
  3980. spin_unlock(&cur_trans->dirty_bgs_lock);
  3981. list_del_init(&cache->io_list);
  3982. btrfs_cleanup_bg_io(cache);
  3983. spin_lock(&cur_trans->dirty_bgs_lock);
  3984. }
  3985. list_del_init(&cache->dirty_list);
  3986. spin_lock(&cache->lock);
  3987. cache->disk_cache_state = BTRFS_DC_ERROR;
  3988. spin_unlock(&cache->lock);
  3989. spin_unlock(&cur_trans->dirty_bgs_lock);
  3990. btrfs_put_block_group(cache);
  3991. btrfs_delayed_refs_rsv_release(fs_info, 1);
  3992. spin_lock(&cur_trans->dirty_bgs_lock);
  3993. }
  3994. spin_unlock(&cur_trans->dirty_bgs_lock);
  3995. /*
  3996. * Refer to the definition of io_bgs member for details why it's safe
  3997. * to use it without any locking
  3998. */
  3999. while (!list_empty(&cur_trans->io_bgs)) {
  4000. cache = list_first_entry(&cur_trans->io_bgs,
  4001. struct btrfs_block_group,
  4002. io_list);
  4003. list_del_init(&cache->io_list);
  4004. spin_lock(&cache->lock);
  4005. cache->disk_cache_state = BTRFS_DC_ERROR;
  4006. spin_unlock(&cache->lock);
  4007. btrfs_cleanup_bg_io(cache);
  4008. }
  4009. }
  4010. void btrfs_cleanup_one_transaction(struct btrfs_transaction *cur_trans,
  4011. struct btrfs_fs_info *fs_info)
  4012. {
  4013. struct btrfs_device *dev, *tmp;
  4014. btrfs_cleanup_dirty_bgs(cur_trans, fs_info);
  4015. ASSERT(list_empty(&cur_trans->dirty_bgs));
  4016. ASSERT(list_empty(&cur_trans->io_bgs));
  4017. list_for_each_entry_safe(dev, tmp, &cur_trans->dev_update_list,
  4018. post_commit_list) {
  4019. list_del_init(&dev->post_commit_list);
  4020. }
  4021. btrfs_destroy_delayed_refs(cur_trans, fs_info);
  4022. cur_trans->state = TRANS_STATE_COMMIT_START;
  4023. wake_up(&fs_info->transaction_blocked_wait);
  4024. cur_trans->state = TRANS_STATE_UNBLOCKED;
  4025. wake_up(&fs_info->transaction_wait);
  4026. btrfs_destroy_delayed_inodes(fs_info);
  4027. btrfs_destroy_marked_extents(fs_info, &cur_trans->dirty_pages,
  4028. EXTENT_DIRTY);
  4029. btrfs_destroy_pinned_extent(fs_info, &cur_trans->pinned_extents);
  4030. cur_trans->state =TRANS_STATE_COMPLETED;
  4031. wake_up(&cur_trans->commit_wait);
  4032. }
  4033. static int btrfs_cleanup_transaction(struct btrfs_fs_info *fs_info)
  4034. {
  4035. struct btrfs_transaction *t;
  4036. mutex_lock(&fs_info->transaction_kthread_mutex);
  4037. spin_lock(&fs_info->trans_lock);
  4038. while (!list_empty(&fs_info->trans_list)) {
  4039. t = list_first_entry(&fs_info->trans_list,
  4040. struct btrfs_transaction, list);
  4041. if (t->state >= TRANS_STATE_COMMIT_START) {
  4042. refcount_inc(&t->use_count);
  4043. spin_unlock(&fs_info->trans_lock);
  4044. btrfs_wait_for_commit(fs_info, t->transid);
  4045. btrfs_put_transaction(t);
  4046. spin_lock(&fs_info->trans_lock);
  4047. continue;
  4048. }
  4049. if (t == fs_info->running_transaction) {
  4050. t->state = TRANS_STATE_COMMIT_DOING;
  4051. spin_unlock(&fs_info->trans_lock);
  4052. /*
  4053. * We wait for 0 num_writers since we don't hold a trans
  4054. * handle open currently for this transaction.
  4055. */
  4056. wait_event(t->writer_wait,
  4057. atomic_read(&t->num_writers) == 0);
  4058. } else {
  4059. spin_unlock(&fs_info->trans_lock);
  4060. }
  4061. btrfs_cleanup_one_transaction(t, fs_info);
  4062. spin_lock(&fs_info->trans_lock);
  4063. if (t == fs_info->running_transaction)
  4064. fs_info->running_transaction = NULL;
  4065. list_del_init(&t->list);
  4066. spin_unlock(&fs_info->trans_lock);
  4067. btrfs_put_transaction(t);
  4068. trace_btrfs_transaction_commit(fs_info->tree_root);
  4069. spin_lock(&fs_info->trans_lock);
  4070. }
  4071. spin_unlock(&fs_info->trans_lock);
  4072. btrfs_destroy_all_ordered_extents(fs_info);
  4073. btrfs_destroy_delayed_inodes(fs_info);
  4074. btrfs_assert_delayed_root_empty(fs_info);
  4075. btrfs_destroy_all_delalloc_inodes(fs_info);
  4076. btrfs_drop_all_logs(fs_info);
  4077. mutex_unlock(&fs_info->transaction_kthread_mutex);
  4078. return 0;
  4079. }