extent_io.c 125 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423
  1. // SPDX-License-Identifier: GPL-2.0
  2. #include <linux/bitops.h>
  3. #include <linux/slab.h>
  4. #include <linux/bio.h>
  5. #include <linux/mm.h>
  6. #include <linux/pagemap.h>
  7. #include <linux/page-flags.h>
  8. #include <linux/sched/mm.h>
  9. #include <linux/spinlock.h>
  10. #include <linux/blkdev.h>
  11. #include <linux/swap.h>
  12. #include <linux/writeback.h>
  13. #include <linux/pagevec.h>
  14. #include <linux/prefetch.h>
  15. #include <linux/fsverity.h>
  16. #include "extent_io.h"
  17. #include "extent-io-tree.h"
  18. #include "extent_map.h"
  19. #include "ctree.h"
  20. #include "btrfs_inode.h"
  21. #include "bio.h"
  22. #include "locking.h"
  23. #include "backref.h"
  24. #include "disk-io.h"
  25. #include "subpage.h"
  26. #include "zoned.h"
  27. #include "block-group.h"
  28. #include "compression.h"
  29. #include "fs.h"
  30. #include "accessors.h"
  31. #include "file-item.h"
  32. #include "file.h"
  33. #include "dev-replace.h"
  34. #include "super.h"
  35. #include "transaction.h"
  36. static struct kmem_cache *extent_buffer_cache;
  37. #ifdef CONFIG_BTRFS_DEBUG
  38. static inline void btrfs_leak_debug_add_eb(struct extent_buffer *eb)
  39. {
  40. struct btrfs_fs_info *fs_info = eb->fs_info;
  41. unsigned long flags;
  42. spin_lock_irqsave(&fs_info->eb_leak_lock, flags);
  43. list_add(&eb->leak_list, &fs_info->allocated_ebs);
  44. spin_unlock_irqrestore(&fs_info->eb_leak_lock, flags);
  45. }
  46. static inline void btrfs_leak_debug_del_eb(struct extent_buffer *eb)
  47. {
  48. struct btrfs_fs_info *fs_info = eb->fs_info;
  49. unsigned long flags;
  50. spin_lock_irqsave(&fs_info->eb_leak_lock, flags);
  51. list_del(&eb->leak_list);
  52. spin_unlock_irqrestore(&fs_info->eb_leak_lock, flags);
  53. }
  54. void btrfs_extent_buffer_leak_debug_check(struct btrfs_fs_info *fs_info)
  55. {
  56. struct extent_buffer *eb;
  57. unsigned long flags;
  58. /*
  59. * If we didn't get into open_ctree our allocated_ebs will not be
  60. * initialized, so just skip this.
  61. */
  62. if (!fs_info->allocated_ebs.next)
  63. return;
  64. WARN_ON(!list_empty(&fs_info->allocated_ebs));
  65. spin_lock_irqsave(&fs_info->eb_leak_lock, flags);
  66. while (!list_empty(&fs_info->allocated_ebs)) {
  67. eb = list_first_entry(&fs_info->allocated_ebs,
  68. struct extent_buffer, leak_list);
  69. pr_err(
  70. "BTRFS: buffer leak start %llu len %u refs %d bflags %lu owner %llu\n",
  71. eb->start, eb->len, atomic_read(&eb->refs), eb->bflags,
  72. btrfs_header_owner(eb));
  73. list_del(&eb->leak_list);
  74. WARN_ON_ONCE(1);
  75. kmem_cache_free(extent_buffer_cache, eb);
  76. }
  77. spin_unlock_irqrestore(&fs_info->eb_leak_lock, flags);
  78. }
  79. #else
  80. #define btrfs_leak_debug_add_eb(eb) do {} while (0)
  81. #define btrfs_leak_debug_del_eb(eb) do {} while (0)
  82. #endif
  83. /*
  84. * Structure to record info about the bio being assembled, and other info like
  85. * how many bytes are there before stripe/ordered extent boundary.
  86. */
  87. struct btrfs_bio_ctrl {
  88. struct btrfs_bio *bbio;
  89. enum btrfs_compression_type compress_type;
  90. u32 len_to_oe_boundary;
  91. blk_opf_t opf;
  92. btrfs_bio_end_io_t end_io_func;
  93. struct writeback_control *wbc;
  94. /*
  95. * The sectors of the page which are going to be submitted by
  96. * extent_writepage_io().
  97. * This is to avoid touching ranges covered by compression/inline.
  98. */
  99. unsigned long submit_bitmap;
  100. struct readahead_control *ractl;
  101. /*
  102. * The start offset of the last used extent map by a read operation.
  103. *
  104. * This is for proper compressed read merge.
  105. * U64_MAX means we are starting the read and have made no progress yet.
  106. *
  107. * The current btrfs_bio_is_contig() only uses disk_bytenr as
  108. * the condition to check if the read can be merged with previous
  109. * bio, which is not correct. E.g. two file extents pointing to the
  110. * same extent but with different offset.
  111. *
  112. * So here we need to do extra checks to only merge reads that are
  113. * covered by the same extent map.
  114. * Just extent_map::start will be enough, as they are unique
  115. * inside the same inode.
  116. */
  117. u64 last_em_start;
  118. };
  119. static void submit_one_bio(struct btrfs_bio_ctrl *bio_ctrl)
  120. {
  121. struct btrfs_bio *bbio = bio_ctrl->bbio;
  122. if (!bbio)
  123. return;
  124. /* Caller should ensure the bio has at least some range added */
  125. ASSERT(bbio->bio.bi_iter.bi_size);
  126. if (btrfs_op(&bbio->bio) == BTRFS_MAP_READ &&
  127. bio_ctrl->compress_type != BTRFS_COMPRESS_NONE)
  128. btrfs_submit_compressed_read(bbio);
  129. else
  130. btrfs_submit_bbio(bbio, 0);
  131. /* The bbio is owned by the end_io handler now */
  132. bio_ctrl->bbio = NULL;
  133. }
  134. /*
  135. * Submit or fail the current bio in the bio_ctrl structure.
  136. */
  137. static void submit_write_bio(struct btrfs_bio_ctrl *bio_ctrl, int ret)
  138. {
  139. struct btrfs_bio *bbio = bio_ctrl->bbio;
  140. if (!bbio)
  141. return;
  142. if (ret) {
  143. ASSERT(ret < 0);
  144. btrfs_bio_end_io(bbio, errno_to_blk_status(ret));
  145. /* The bio is owned by the end_io handler now */
  146. bio_ctrl->bbio = NULL;
  147. } else {
  148. submit_one_bio(bio_ctrl);
  149. }
  150. }
  151. int __init extent_buffer_init_cachep(void)
  152. {
  153. extent_buffer_cache = kmem_cache_create("btrfs_extent_buffer",
  154. sizeof(struct extent_buffer), 0, 0,
  155. NULL);
  156. if (!extent_buffer_cache)
  157. return -ENOMEM;
  158. return 0;
  159. }
  160. void __cold extent_buffer_free_cachep(void)
  161. {
  162. /*
  163. * Make sure all delayed rcu free are flushed before we
  164. * destroy caches.
  165. */
  166. rcu_barrier();
  167. kmem_cache_destroy(extent_buffer_cache);
  168. }
  169. static void process_one_folio(struct btrfs_fs_info *fs_info,
  170. struct folio *folio, const struct folio *locked_folio,
  171. unsigned long page_ops, u64 start, u64 end)
  172. {
  173. u32 len;
  174. ASSERT(end + 1 - start != 0 && end + 1 - start < U32_MAX);
  175. len = end + 1 - start;
  176. if (page_ops & PAGE_SET_ORDERED)
  177. btrfs_folio_clamp_set_ordered(fs_info, folio, start, len);
  178. if (page_ops & PAGE_START_WRITEBACK) {
  179. btrfs_folio_clamp_clear_dirty(fs_info, folio, start, len);
  180. btrfs_folio_clamp_set_writeback(fs_info, folio, start, len);
  181. }
  182. if (page_ops & PAGE_END_WRITEBACK)
  183. btrfs_folio_clamp_clear_writeback(fs_info, folio, start, len);
  184. if (folio != locked_folio && (page_ops & PAGE_UNLOCK))
  185. btrfs_folio_end_lock(fs_info, folio, start, len);
  186. }
  187. static void __process_folios_contig(struct address_space *mapping,
  188. const struct folio *locked_folio, u64 start,
  189. u64 end, unsigned long page_ops)
  190. {
  191. struct btrfs_fs_info *fs_info = inode_to_fs_info(mapping->host);
  192. pgoff_t start_index = start >> PAGE_SHIFT;
  193. pgoff_t end_index = end >> PAGE_SHIFT;
  194. pgoff_t index = start_index;
  195. struct folio_batch fbatch;
  196. int i;
  197. folio_batch_init(&fbatch);
  198. while (index <= end_index) {
  199. int found_folios;
  200. found_folios = filemap_get_folios_contig(mapping, &index,
  201. end_index, &fbatch);
  202. for (i = 0; i < found_folios; i++) {
  203. struct folio *folio = fbatch.folios[i];
  204. process_one_folio(fs_info, folio, locked_folio,
  205. page_ops, start, end);
  206. }
  207. folio_batch_release(&fbatch);
  208. cond_resched();
  209. }
  210. }
  211. static noinline void __unlock_for_delalloc(const struct inode *inode,
  212. const struct folio *locked_folio,
  213. u64 start, u64 end)
  214. {
  215. unsigned long index = start >> PAGE_SHIFT;
  216. unsigned long end_index = end >> PAGE_SHIFT;
  217. ASSERT(locked_folio);
  218. if (index == locked_folio->index && end_index == index)
  219. return;
  220. __process_folios_contig(inode->i_mapping, locked_folio, start, end,
  221. PAGE_UNLOCK);
  222. }
  223. static noinline int lock_delalloc_folios(struct inode *inode,
  224. const struct folio *locked_folio,
  225. u64 start, u64 end)
  226. {
  227. struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
  228. struct address_space *mapping = inode->i_mapping;
  229. pgoff_t start_index = start >> PAGE_SHIFT;
  230. pgoff_t end_index = end >> PAGE_SHIFT;
  231. pgoff_t index = start_index;
  232. u64 processed_end = start;
  233. struct folio_batch fbatch;
  234. if (index == locked_folio->index && index == end_index)
  235. return 0;
  236. folio_batch_init(&fbatch);
  237. while (index <= end_index) {
  238. unsigned int found_folios, i;
  239. found_folios = filemap_get_folios_contig(mapping, &index,
  240. end_index, &fbatch);
  241. if (found_folios == 0)
  242. goto out;
  243. for (i = 0; i < found_folios; i++) {
  244. struct folio *folio = fbatch.folios[i];
  245. u64 range_start;
  246. u32 range_len;
  247. if (folio == locked_folio)
  248. continue;
  249. folio_lock(folio);
  250. if (!folio_test_dirty(folio) || folio->mapping != mapping) {
  251. folio_unlock(folio);
  252. goto out;
  253. }
  254. range_start = max_t(u64, folio_pos(folio), start);
  255. range_len = min_t(u64, folio_pos(folio) + folio_size(folio),
  256. end + 1) - range_start;
  257. btrfs_folio_set_lock(fs_info, folio, range_start, range_len);
  258. processed_end = range_start + range_len - 1;
  259. }
  260. folio_batch_release(&fbatch);
  261. cond_resched();
  262. }
  263. return 0;
  264. out:
  265. folio_batch_release(&fbatch);
  266. if (processed_end > start)
  267. __unlock_for_delalloc(inode, locked_folio, start,
  268. processed_end);
  269. return -EAGAIN;
  270. }
  271. /*
  272. * Find and lock a contiguous range of bytes in the file marked as delalloc, no
  273. * more than @max_bytes.
  274. *
  275. * @start: The original start bytenr to search.
  276. * Will store the extent range start bytenr.
  277. * @end: The original end bytenr of the search range
  278. * Will store the extent range end bytenr.
  279. *
  280. * Return true if we find a delalloc range which starts inside the original
  281. * range, and @start/@end will store the delalloc range start/end.
  282. *
  283. * Return false if we can't find any delalloc range which starts inside the
  284. * original range, and @start/@end will be the non-delalloc range start/end.
  285. */
  286. EXPORT_FOR_TESTS
  287. noinline_for_stack bool find_lock_delalloc_range(struct inode *inode,
  288. struct folio *locked_folio,
  289. u64 *start, u64 *end)
  290. {
  291. struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
  292. struct extent_io_tree *tree = &BTRFS_I(inode)->io_tree;
  293. const u64 orig_start = *start;
  294. const u64 orig_end = *end;
  295. /* The sanity tests may not set a valid fs_info. */
  296. u64 max_bytes = fs_info ? fs_info->max_extent_size : BTRFS_MAX_EXTENT_SIZE;
  297. u64 delalloc_start;
  298. u64 delalloc_end;
  299. bool found;
  300. struct extent_state *cached_state = NULL;
  301. int ret;
  302. int loops = 0;
  303. /* Caller should pass a valid @end to indicate the search range end */
  304. ASSERT(orig_end > orig_start);
  305. /* The range should at least cover part of the folio */
  306. ASSERT(!(orig_start >= folio_pos(locked_folio) + folio_size(locked_folio) ||
  307. orig_end <= folio_pos(locked_folio)));
  308. again:
  309. /* step one, find a bunch of delalloc bytes starting at start */
  310. delalloc_start = *start;
  311. delalloc_end = 0;
  312. /*
  313. * If @max_bytes is smaller than a block, btrfs_find_delalloc_range() can
  314. * return early without handling any dirty ranges.
  315. */
  316. ASSERT(max_bytes >= fs_info->sectorsize);
  317. found = btrfs_find_delalloc_range(tree, &delalloc_start, &delalloc_end,
  318. max_bytes, &cached_state);
  319. if (!found || delalloc_end <= *start || delalloc_start > orig_end) {
  320. *start = delalloc_start;
  321. /* @delalloc_end can be -1, never go beyond @orig_end */
  322. *end = min(delalloc_end, orig_end);
  323. free_extent_state(cached_state);
  324. return false;
  325. }
  326. /*
  327. * start comes from the offset of locked_folio. We have to lock
  328. * folios in order, so we can't process delalloc bytes before
  329. * locked_folio
  330. */
  331. if (delalloc_start < *start)
  332. delalloc_start = *start;
  333. /*
  334. * make sure to limit the number of folios we try to lock down
  335. */
  336. if (delalloc_end + 1 - delalloc_start > max_bytes)
  337. delalloc_end = delalloc_start + max_bytes - 1;
  338. /* step two, lock all the folioss after the folios that has start */
  339. ret = lock_delalloc_folios(inode, locked_folio, delalloc_start,
  340. delalloc_end);
  341. ASSERT(!ret || ret == -EAGAIN);
  342. if (ret == -EAGAIN) {
  343. /*
  344. * Some of the folios are gone, lets avoid looping by
  345. * shortening the size of the delalloc range we're searching.
  346. */
  347. free_extent_state(cached_state);
  348. cached_state = NULL;
  349. if (!loops) {
  350. max_bytes = fs_info->sectorsize;
  351. loops = 1;
  352. goto again;
  353. } else {
  354. found = false;
  355. goto out_failed;
  356. }
  357. }
  358. /* step three, lock the state bits for the whole range */
  359. lock_extent(tree, delalloc_start, delalloc_end, &cached_state);
  360. /* then test to make sure it is all still delalloc */
  361. ret = test_range_bit(tree, delalloc_start, delalloc_end,
  362. EXTENT_DELALLOC, cached_state);
  363. unlock_extent(tree, delalloc_start, delalloc_end, &cached_state);
  364. if (!ret) {
  365. __unlock_for_delalloc(inode, locked_folio, delalloc_start,
  366. delalloc_end);
  367. cond_resched();
  368. goto again;
  369. }
  370. *start = delalloc_start;
  371. *end = delalloc_end;
  372. out_failed:
  373. return found;
  374. }
  375. void extent_clear_unlock_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
  376. const struct folio *locked_folio,
  377. struct extent_state **cached,
  378. u32 clear_bits, unsigned long page_ops)
  379. {
  380. clear_extent_bit(&inode->io_tree, start, end, clear_bits, cached);
  381. __process_folios_contig(inode->vfs_inode.i_mapping, locked_folio, start,
  382. end, page_ops);
  383. }
  384. static bool btrfs_verify_folio(struct folio *folio, u64 start, u32 len)
  385. {
  386. struct btrfs_fs_info *fs_info = folio_to_fs_info(folio);
  387. if (!fsverity_active(folio->mapping->host) ||
  388. btrfs_folio_test_uptodate(fs_info, folio, start, len) ||
  389. start >= i_size_read(folio->mapping->host))
  390. return true;
  391. return fsverity_verify_folio(folio);
  392. }
  393. static void end_folio_read(struct folio *folio, bool uptodate, u64 start, u32 len)
  394. {
  395. struct btrfs_fs_info *fs_info = folio_to_fs_info(folio);
  396. ASSERT(folio_pos(folio) <= start &&
  397. start + len <= folio_pos(folio) + PAGE_SIZE);
  398. if (uptodate && btrfs_verify_folio(folio, start, len))
  399. btrfs_folio_set_uptodate(fs_info, folio, start, len);
  400. else
  401. btrfs_folio_clear_uptodate(fs_info, folio, start, len);
  402. if (!btrfs_is_subpage(fs_info, folio->mapping))
  403. folio_unlock(folio);
  404. else
  405. btrfs_folio_end_lock(fs_info, folio, start, len);
  406. }
  407. /*
  408. * After a write IO is done, we need to:
  409. *
  410. * - clear the uptodate bits on error
  411. * - clear the writeback bits in the extent tree for the range
  412. * - filio_end_writeback() if there is no more pending io for the folio
  413. *
  414. * Scheduling is not allowed, so the extent state tree is expected
  415. * to have one and only one object corresponding to this IO.
  416. */
  417. static void end_bbio_data_write(struct btrfs_bio *bbio)
  418. {
  419. struct btrfs_fs_info *fs_info = bbio->fs_info;
  420. struct bio *bio = &bbio->bio;
  421. int error = blk_status_to_errno(bio->bi_status);
  422. struct folio_iter fi;
  423. const u32 sectorsize = fs_info->sectorsize;
  424. ASSERT(!bio_flagged(bio, BIO_CLONED));
  425. bio_for_each_folio_all(fi, bio) {
  426. struct folio *folio = fi.folio;
  427. u64 start = folio_pos(folio) + fi.offset;
  428. u32 len = fi.length;
  429. /* Only order 0 (single page) folios are allowed for data. */
  430. ASSERT(folio_order(folio) == 0);
  431. /* Our read/write should always be sector aligned. */
  432. if (!IS_ALIGNED(fi.offset, sectorsize))
  433. btrfs_err(fs_info,
  434. "partial page write in btrfs with offset %zu and length %zu",
  435. fi.offset, fi.length);
  436. else if (!IS_ALIGNED(fi.length, sectorsize))
  437. btrfs_info(fs_info,
  438. "incomplete page write with offset %zu and length %zu",
  439. fi.offset, fi.length);
  440. btrfs_finish_ordered_extent(bbio->ordered, folio, start, len,
  441. !error);
  442. if (error)
  443. mapping_set_error(folio->mapping, error);
  444. btrfs_folio_clear_writeback(fs_info, folio, start, len);
  445. }
  446. bio_put(bio);
  447. }
  448. static void begin_folio_read(struct btrfs_fs_info *fs_info, struct folio *folio)
  449. {
  450. ASSERT(folio_test_locked(folio));
  451. if (!btrfs_is_subpage(fs_info, folio->mapping))
  452. return;
  453. ASSERT(folio_test_private(folio));
  454. btrfs_folio_set_lock(fs_info, folio, folio_pos(folio), PAGE_SIZE);
  455. }
  456. /*
  457. * After a data read IO is done, we need to:
  458. *
  459. * - clear the uptodate bits on error
  460. * - set the uptodate bits if things worked
  461. * - set the folio up to date if all extents in the tree are uptodate
  462. * - clear the lock bit in the extent tree
  463. * - unlock the folio if there are no other extents locked for it
  464. *
  465. * Scheduling is not allowed, so the extent state tree is expected
  466. * to have one and only one object corresponding to this IO.
  467. */
  468. static void end_bbio_data_read(struct btrfs_bio *bbio)
  469. {
  470. struct btrfs_fs_info *fs_info = bbio->fs_info;
  471. struct bio *bio = &bbio->bio;
  472. struct folio_iter fi;
  473. const u32 sectorsize = fs_info->sectorsize;
  474. ASSERT(!bio_flagged(bio, BIO_CLONED));
  475. bio_for_each_folio_all(fi, &bbio->bio) {
  476. bool uptodate = !bio->bi_status;
  477. struct folio *folio = fi.folio;
  478. struct inode *inode = folio->mapping->host;
  479. u64 start;
  480. u64 end;
  481. u32 len;
  482. btrfs_debug(fs_info,
  483. "%s: bi_sector=%llu, err=%d, mirror=%u",
  484. __func__, bio->bi_iter.bi_sector, bio->bi_status,
  485. bbio->mirror_num);
  486. /*
  487. * We always issue full-sector reads, but if some block in a
  488. * folio fails to read, blk_update_request() will advance
  489. * bv_offset and adjust bv_len to compensate. Print a warning
  490. * for unaligned offsets, and an error if they don't add up to
  491. * a full sector.
  492. */
  493. if (!IS_ALIGNED(fi.offset, sectorsize))
  494. btrfs_err(fs_info,
  495. "partial page read in btrfs with offset %zu and length %zu",
  496. fi.offset, fi.length);
  497. else if (!IS_ALIGNED(fi.offset + fi.length, sectorsize))
  498. btrfs_info(fs_info,
  499. "incomplete page read with offset %zu and length %zu",
  500. fi.offset, fi.length);
  501. start = folio_pos(folio) + fi.offset;
  502. end = start + fi.length - 1;
  503. len = fi.length;
  504. if (likely(uptodate)) {
  505. loff_t i_size = i_size_read(inode);
  506. /*
  507. * Zero out the remaining part if this range straddles
  508. * i_size.
  509. *
  510. * Here we should only zero the range inside the folio,
  511. * not touch anything else.
  512. *
  513. * NOTE: i_size is exclusive while end is inclusive and
  514. * folio_contains() takes PAGE_SIZE units.
  515. */
  516. if (folio_contains(folio, i_size >> PAGE_SHIFT) &&
  517. i_size <= end) {
  518. u32 zero_start = max(offset_in_folio(folio, i_size),
  519. offset_in_folio(folio, start));
  520. u32 zero_len = offset_in_folio(folio, end) + 1 -
  521. zero_start;
  522. folio_zero_range(folio, zero_start, zero_len);
  523. }
  524. }
  525. /* Update page status and unlock. */
  526. end_folio_read(folio, uptodate, start, len);
  527. }
  528. bio_put(bio);
  529. }
  530. /*
  531. * Populate every free slot in a provided array with folios using GFP_NOFS.
  532. *
  533. * @nr_folios: number of folios to allocate
  534. * @folio_array: the array to fill with folios; any existing non-NULL entries in
  535. * the array will be skipped
  536. *
  537. * Return: 0 if all folios were able to be allocated;
  538. * -ENOMEM otherwise, the partially allocated folios would be freed and
  539. * the array slots zeroed
  540. */
  541. int btrfs_alloc_folio_array(unsigned int nr_folios, struct folio **folio_array)
  542. {
  543. for (int i = 0; i < nr_folios; i++) {
  544. if (folio_array[i])
  545. continue;
  546. folio_array[i] = folio_alloc(GFP_NOFS, 0);
  547. if (!folio_array[i])
  548. goto error;
  549. }
  550. return 0;
  551. error:
  552. for (int i = 0; i < nr_folios; i++) {
  553. if (folio_array[i])
  554. folio_put(folio_array[i]);
  555. }
  556. return -ENOMEM;
  557. }
  558. /*
  559. * Populate every free slot in a provided array with pages, using GFP_NOFS.
  560. *
  561. * @nr_pages: number of pages to allocate
  562. * @page_array: the array to fill with pages; any existing non-null entries in
  563. * the array will be skipped
  564. * @nofail: whether using __GFP_NOFAIL flag
  565. *
  566. * Return: 0 if all pages were able to be allocated;
  567. * -ENOMEM otherwise, the partially allocated pages would be freed and
  568. * the array slots zeroed
  569. */
  570. int btrfs_alloc_page_array(unsigned int nr_pages, struct page **page_array,
  571. bool nofail)
  572. {
  573. const gfp_t gfp = nofail ? (GFP_NOFS | __GFP_NOFAIL) : GFP_NOFS;
  574. unsigned int allocated;
  575. for (allocated = 0; allocated < nr_pages;) {
  576. unsigned int last = allocated;
  577. allocated = alloc_pages_bulk_array(gfp, nr_pages, page_array);
  578. if (unlikely(allocated == last)) {
  579. /* No progress, fail and do cleanup. */
  580. for (int i = 0; i < allocated; i++) {
  581. __free_page(page_array[i]);
  582. page_array[i] = NULL;
  583. }
  584. return -ENOMEM;
  585. }
  586. }
  587. return 0;
  588. }
  589. /*
  590. * Populate needed folios for the extent buffer.
  591. *
  592. * For now, the folios populated are always in order 0 (aka, single page).
  593. */
  594. static int alloc_eb_folio_array(struct extent_buffer *eb, bool nofail)
  595. {
  596. struct page *page_array[INLINE_EXTENT_BUFFER_PAGES] = { 0 };
  597. int num_pages = num_extent_pages(eb);
  598. int ret;
  599. ret = btrfs_alloc_page_array(num_pages, page_array, nofail);
  600. if (ret < 0)
  601. return ret;
  602. for (int i = 0; i < num_pages; i++)
  603. eb->folios[i] = page_folio(page_array[i]);
  604. eb->folio_size = PAGE_SIZE;
  605. eb->folio_shift = PAGE_SHIFT;
  606. return 0;
  607. }
  608. static bool btrfs_bio_is_contig(struct btrfs_bio_ctrl *bio_ctrl,
  609. struct folio *folio, u64 disk_bytenr,
  610. unsigned int pg_offset)
  611. {
  612. struct bio *bio = &bio_ctrl->bbio->bio;
  613. struct bio_vec *bvec = bio_last_bvec_all(bio);
  614. const sector_t sector = disk_bytenr >> SECTOR_SHIFT;
  615. struct folio *bv_folio = page_folio(bvec->bv_page);
  616. if (bio_ctrl->compress_type != BTRFS_COMPRESS_NONE) {
  617. /*
  618. * For compression, all IO should have its logical bytenr set
  619. * to the starting bytenr of the compressed extent.
  620. */
  621. return bio->bi_iter.bi_sector == sector;
  622. }
  623. /*
  624. * The contig check requires the following conditions to be met:
  625. *
  626. * 1) The folios are belonging to the same inode
  627. * This is implied by the call chain.
  628. *
  629. * 2) The range has adjacent logical bytenr
  630. *
  631. * 3) The range has adjacent file offset
  632. * This is required for the usage of btrfs_bio->file_offset.
  633. */
  634. return bio_end_sector(bio) == sector &&
  635. folio_pos(bv_folio) + bvec->bv_offset + bvec->bv_len ==
  636. folio_pos(folio) + pg_offset;
  637. }
  638. static void alloc_new_bio(struct btrfs_inode *inode,
  639. struct btrfs_bio_ctrl *bio_ctrl,
  640. u64 disk_bytenr, u64 file_offset)
  641. {
  642. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  643. struct btrfs_bio *bbio;
  644. bbio = btrfs_bio_alloc(BIO_MAX_VECS, bio_ctrl->opf, fs_info,
  645. bio_ctrl->end_io_func, NULL);
  646. bbio->bio.bi_iter.bi_sector = disk_bytenr >> SECTOR_SHIFT;
  647. bbio->inode = inode;
  648. bbio->file_offset = file_offset;
  649. bio_ctrl->bbio = bbio;
  650. bio_ctrl->len_to_oe_boundary = U32_MAX;
  651. /* Limit data write bios to the ordered boundary. */
  652. if (bio_ctrl->wbc) {
  653. struct btrfs_ordered_extent *ordered;
  654. ordered = btrfs_lookup_ordered_extent(inode, file_offset);
  655. if (ordered) {
  656. bio_ctrl->len_to_oe_boundary = min_t(u32, U32_MAX,
  657. ordered->file_offset +
  658. ordered->disk_num_bytes - file_offset);
  659. bbio->ordered = ordered;
  660. }
  661. /*
  662. * Pick the last added device to support cgroup writeback. For
  663. * multi-device file systems this means blk-cgroup policies have
  664. * to always be set on the last added/replaced device.
  665. * This is a bit odd but has been like that for a long time.
  666. */
  667. bio_set_dev(&bbio->bio, fs_info->fs_devices->latest_dev->bdev);
  668. wbc_init_bio(bio_ctrl->wbc, &bbio->bio);
  669. }
  670. }
  671. /*
  672. * @disk_bytenr: logical bytenr where the write will be
  673. * @page: page to add to the bio
  674. * @size: portion of page that we want to write to
  675. * @pg_offset: offset of the new bio or to check whether we are adding
  676. * a contiguous page to the previous one
  677. *
  678. * The will either add the page into the existing @bio_ctrl->bbio, or allocate a
  679. * new one in @bio_ctrl->bbio.
  680. * The mirror number for this IO should already be initizlied in
  681. * @bio_ctrl->mirror_num.
  682. */
  683. static void submit_extent_folio(struct btrfs_bio_ctrl *bio_ctrl,
  684. u64 disk_bytenr, struct folio *folio,
  685. size_t size, unsigned long pg_offset)
  686. {
  687. struct btrfs_inode *inode = folio_to_inode(folio);
  688. ASSERT(pg_offset + size <= PAGE_SIZE);
  689. ASSERT(bio_ctrl->end_io_func);
  690. if (bio_ctrl->bbio &&
  691. !btrfs_bio_is_contig(bio_ctrl, folio, disk_bytenr, pg_offset))
  692. submit_one_bio(bio_ctrl);
  693. do {
  694. u32 len = size;
  695. /* Allocate new bio if needed */
  696. if (!bio_ctrl->bbio) {
  697. alloc_new_bio(inode, bio_ctrl, disk_bytenr,
  698. folio_pos(folio) + pg_offset);
  699. }
  700. /* Cap to the current ordered extent boundary if there is one. */
  701. if (len > bio_ctrl->len_to_oe_boundary) {
  702. ASSERT(bio_ctrl->compress_type == BTRFS_COMPRESS_NONE);
  703. ASSERT(is_data_inode(inode));
  704. len = bio_ctrl->len_to_oe_boundary;
  705. }
  706. if (!bio_add_folio(&bio_ctrl->bbio->bio, folio, len, pg_offset)) {
  707. /* bio full: move on to a new one */
  708. submit_one_bio(bio_ctrl);
  709. continue;
  710. }
  711. if (bio_ctrl->wbc)
  712. wbc_account_cgroup_owner(bio_ctrl->wbc, folio,
  713. len);
  714. size -= len;
  715. pg_offset += len;
  716. disk_bytenr += len;
  717. /*
  718. * len_to_oe_boundary defaults to U32_MAX, which isn't folio or
  719. * sector aligned. alloc_new_bio() then sets it to the end of
  720. * our ordered extent for writes into zoned devices.
  721. *
  722. * When len_to_oe_boundary is tracking an ordered extent, we
  723. * trust the ordered extent code to align things properly, and
  724. * the check above to cap our write to the ordered extent
  725. * boundary is correct.
  726. *
  727. * When len_to_oe_boundary is U32_MAX, the cap above would
  728. * result in a 4095 byte IO for the last folio right before
  729. * we hit the bio limit of UINT_MAX. bio_add_folio() has all
  730. * the checks required to make sure we don't overflow the bio,
  731. * and we should just ignore len_to_oe_boundary completely
  732. * unless we're using it to track an ordered extent.
  733. *
  734. * It's pretty hard to make a bio sized U32_MAX, but it can
  735. * happen when the page cache is able to feed us contiguous
  736. * folios for large extents.
  737. */
  738. if (bio_ctrl->len_to_oe_boundary != U32_MAX)
  739. bio_ctrl->len_to_oe_boundary -= len;
  740. /* Ordered extent boundary: move on to a new bio. */
  741. if (bio_ctrl->len_to_oe_boundary == 0)
  742. submit_one_bio(bio_ctrl);
  743. } while (size);
  744. }
  745. static int attach_extent_buffer_folio(struct extent_buffer *eb,
  746. struct folio *folio,
  747. struct btrfs_subpage *prealloc)
  748. {
  749. struct btrfs_fs_info *fs_info = eb->fs_info;
  750. int ret = 0;
  751. /*
  752. * If the page is mapped to btree inode, we should hold the private
  753. * lock to prevent race.
  754. * For cloned or dummy extent buffers, their pages are not mapped and
  755. * will not race with any other ebs.
  756. */
  757. if (folio->mapping)
  758. lockdep_assert_held(&folio->mapping->i_private_lock);
  759. if (fs_info->nodesize >= PAGE_SIZE) {
  760. if (!folio_test_private(folio))
  761. folio_attach_private(folio, eb);
  762. else
  763. WARN_ON(folio_get_private(folio) != eb);
  764. return 0;
  765. }
  766. /* Already mapped, just free prealloc */
  767. if (folio_test_private(folio)) {
  768. btrfs_free_subpage(prealloc);
  769. return 0;
  770. }
  771. if (prealloc)
  772. /* Has preallocated memory for subpage */
  773. folio_attach_private(folio, prealloc);
  774. else
  775. /* Do new allocation to attach subpage */
  776. ret = btrfs_attach_subpage(fs_info, folio, BTRFS_SUBPAGE_METADATA);
  777. return ret;
  778. }
  779. int set_page_extent_mapped(struct page *page)
  780. {
  781. return set_folio_extent_mapped(page_folio(page));
  782. }
  783. int set_folio_extent_mapped(struct folio *folio)
  784. {
  785. struct btrfs_fs_info *fs_info;
  786. ASSERT(folio->mapping);
  787. if (folio_test_private(folio))
  788. return 0;
  789. fs_info = folio_to_fs_info(folio);
  790. if (btrfs_is_subpage(fs_info, folio->mapping))
  791. return btrfs_attach_subpage(fs_info, folio, BTRFS_SUBPAGE_DATA);
  792. folio_attach_private(folio, (void *)EXTENT_FOLIO_PRIVATE);
  793. return 0;
  794. }
  795. void clear_folio_extent_mapped(struct folio *folio)
  796. {
  797. struct btrfs_fs_info *fs_info;
  798. ASSERT(folio->mapping);
  799. if (!folio_test_private(folio))
  800. return;
  801. fs_info = folio_to_fs_info(folio);
  802. if (btrfs_is_subpage(fs_info, folio->mapping))
  803. return btrfs_detach_subpage(fs_info, folio);
  804. folio_detach_private(folio);
  805. }
  806. static struct extent_map *get_extent_map(struct btrfs_inode *inode,
  807. struct folio *folio, u64 start,
  808. u64 len, struct extent_map **em_cached)
  809. {
  810. struct extent_map *em;
  811. ASSERT(em_cached);
  812. if (*em_cached) {
  813. em = *em_cached;
  814. if (extent_map_in_tree(em) && start >= em->start &&
  815. start < extent_map_end(em)) {
  816. refcount_inc(&em->refs);
  817. return em;
  818. }
  819. free_extent_map(em);
  820. *em_cached = NULL;
  821. }
  822. em = btrfs_get_extent(inode, folio, start, len);
  823. if (!IS_ERR(em)) {
  824. BUG_ON(*em_cached);
  825. refcount_inc(&em->refs);
  826. *em_cached = em;
  827. }
  828. return em;
  829. }
  830. static void btrfs_readahead_expand(struct readahead_control *ractl,
  831. const struct extent_map *em)
  832. {
  833. const u64 ra_pos = readahead_pos(ractl);
  834. const u64 ra_end = ra_pos + readahead_length(ractl);
  835. const u64 em_end = em->start + em->len;
  836. /* No expansion for holes and inline extents. */
  837. if (em->disk_bytenr > EXTENT_MAP_LAST_BYTE)
  838. return;
  839. ASSERT(em_end >= ra_pos);
  840. if (em_end > ra_end)
  841. readahead_expand(ractl, ra_pos, em_end - ra_pos);
  842. }
  843. /*
  844. * basic readpage implementation. Locked extent state structs are inserted
  845. * into the tree that are removed when the IO is done (by the end_io
  846. * handlers)
  847. * XXX JDM: This needs looking at to ensure proper page locking
  848. * return 0 on success, otherwise return error
  849. */
  850. static int btrfs_do_readpage(struct folio *folio, struct extent_map **em_cached,
  851. struct btrfs_bio_ctrl *bio_ctrl)
  852. {
  853. struct inode *inode = folio->mapping->host;
  854. struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
  855. u64 start = folio_pos(folio);
  856. const u64 end = start + PAGE_SIZE - 1;
  857. u64 cur = start;
  858. u64 extent_offset;
  859. u64 last_byte = i_size_read(inode);
  860. u64 block_start;
  861. struct extent_map *em;
  862. int ret = 0;
  863. size_t pg_offset = 0;
  864. size_t iosize;
  865. size_t blocksize = fs_info->sectorsize;
  866. ret = set_folio_extent_mapped(folio);
  867. if (ret < 0) {
  868. folio_unlock(folio);
  869. return ret;
  870. }
  871. if (folio_contains(folio, last_byte >> PAGE_SHIFT)) {
  872. size_t zero_offset = offset_in_folio(folio, last_byte);
  873. if (zero_offset) {
  874. iosize = folio_size(folio) - zero_offset;
  875. folio_zero_range(folio, zero_offset, iosize);
  876. }
  877. }
  878. bio_ctrl->end_io_func = end_bbio_data_read;
  879. begin_folio_read(fs_info, folio);
  880. while (cur <= end) {
  881. enum btrfs_compression_type compress_type = BTRFS_COMPRESS_NONE;
  882. bool force_bio_submit = false;
  883. u64 disk_bytenr;
  884. ASSERT(IS_ALIGNED(cur, fs_info->sectorsize));
  885. if (cur >= last_byte) {
  886. iosize = folio_size(folio) - pg_offset;
  887. folio_zero_range(folio, pg_offset, iosize);
  888. end_folio_read(folio, true, cur, iosize);
  889. break;
  890. }
  891. em = get_extent_map(BTRFS_I(inode), folio, cur, end - cur + 1, em_cached);
  892. if (IS_ERR(em)) {
  893. end_folio_read(folio, false, cur, end + 1 - cur);
  894. return PTR_ERR(em);
  895. }
  896. extent_offset = cur - em->start;
  897. BUG_ON(extent_map_end(em) <= cur);
  898. BUG_ON(end < cur);
  899. compress_type = extent_map_compression(em);
  900. iosize = min(extent_map_end(em) - cur, end - cur + 1);
  901. iosize = ALIGN(iosize, blocksize);
  902. /*
  903. * Only expand readahead for extents which are already creating
  904. * the pages anyway in add_ra_bio_pages, which is compressed
  905. * extents in the non subpage case.
  906. */
  907. if (bio_ctrl->ractl &&
  908. !btrfs_is_subpage(fs_info, folio->mapping) &&
  909. compress_type != BTRFS_COMPRESS_NONE)
  910. btrfs_readahead_expand(bio_ctrl->ractl, em);
  911. if (compress_type != BTRFS_COMPRESS_NONE)
  912. disk_bytenr = em->disk_bytenr;
  913. else
  914. disk_bytenr = extent_map_block_start(em) + extent_offset;
  915. block_start = extent_map_block_start(em);
  916. if (em->flags & EXTENT_FLAG_PREALLOC)
  917. block_start = EXTENT_MAP_HOLE;
  918. /*
  919. * If we have a file range that points to a compressed extent
  920. * and it's followed by a consecutive file range that points
  921. * to the same compressed extent (possibly with a different
  922. * offset and/or length, so it either points to the whole extent
  923. * or only part of it), we must make sure we do not submit a
  924. * single bio to populate the folios for the 2 ranges because
  925. * this makes the compressed extent read zero out the folios
  926. * belonging to the 2nd range. Imagine the following scenario:
  927. *
  928. * File layout
  929. * [0 - 8K] [8K - 24K]
  930. * | |
  931. * | |
  932. * points to extent X, points to extent X,
  933. * offset 4K, length of 8K offset 0, length 16K
  934. *
  935. * [extent X, compressed length = 4K uncompressed length = 16K]
  936. *
  937. * If the bio to read the compressed extent covers both ranges,
  938. * it will decompress extent X into the folios belonging to the
  939. * first range and then it will stop, zeroing out the remaining
  940. * folios that belong to the other range that points to extent X.
  941. * So here we make sure we submit 2 bios, one for the first
  942. * range and another one for the third range. Both will target
  943. * the same physical extent from disk, but we can't currently
  944. * make the compressed bio endio callback populate the folios
  945. * for both ranges because each compressed bio is tightly
  946. * coupled with a single extent map, and each range can have
  947. * an extent map with a different offset value relative to the
  948. * uncompressed data of our extent and different lengths. This
  949. * is a corner case so we prioritize correctness over
  950. * non-optimal behavior (submitting 2 bios for the same extent).
  951. */
  952. if (compress_type != BTRFS_COMPRESS_NONE &&
  953. bio_ctrl->last_em_start != U64_MAX &&
  954. bio_ctrl->last_em_start != em->start)
  955. force_bio_submit = true;
  956. bio_ctrl->last_em_start = em->start;
  957. free_extent_map(em);
  958. em = NULL;
  959. /* we've found a hole, just zero and go on */
  960. if (block_start == EXTENT_MAP_HOLE) {
  961. folio_zero_range(folio, pg_offset, iosize);
  962. end_folio_read(folio, true, cur, iosize);
  963. cur = cur + iosize;
  964. pg_offset += iosize;
  965. continue;
  966. }
  967. /* the get_extent function already copied into the folio */
  968. if (block_start == EXTENT_MAP_INLINE) {
  969. end_folio_read(folio, true, cur, iosize);
  970. cur = cur + iosize;
  971. pg_offset += iosize;
  972. continue;
  973. }
  974. if (bio_ctrl->compress_type != compress_type) {
  975. submit_one_bio(bio_ctrl);
  976. bio_ctrl->compress_type = compress_type;
  977. }
  978. if (force_bio_submit)
  979. submit_one_bio(bio_ctrl);
  980. submit_extent_folio(bio_ctrl, disk_bytenr, folio, iosize,
  981. pg_offset);
  982. cur = cur + iosize;
  983. pg_offset += iosize;
  984. }
  985. return 0;
  986. }
  987. int btrfs_read_folio(struct file *file, struct folio *folio)
  988. {
  989. struct btrfs_inode *inode = folio_to_inode(folio);
  990. const u64 start = folio_pos(folio);
  991. const u64 end = start + folio_size(folio) - 1;
  992. struct extent_state *cached_state = NULL;
  993. struct btrfs_bio_ctrl bio_ctrl = {
  994. .opf = REQ_OP_READ,
  995. .last_em_start = U64_MAX,
  996. };
  997. struct extent_map *em_cached = NULL;
  998. int ret;
  999. btrfs_lock_and_flush_ordered_range(inode, start, end, &cached_state);
  1000. ret = btrfs_do_readpage(folio, &em_cached, &bio_ctrl);
  1001. unlock_extent(&inode->io_tree, start, end, &cached_state);
  1002. free_extent_map(em_cached);
  1003. /*
  1004. * If btrfs_do_readpage() failed we will want to submit the assembled
  1005. * bio to do the cleanup.
  1006. */
  1007. submit_one_bio(&bio_ctrl);
  1008. return ret;
  1009. }
  1010. static void set_delalloc_bitmap(struct folio *folio, unsigned long *delalloc_bitmap,
  1011. u64 start, u32 len)
  1012. {
  1013. struct btrfs_fs_info *fs_info = folio_to_fs_info(folio);
  1014. const u64 folio_start = folio_pos(folio);
  1015. unsigned int start_bit;
  1016. unsigned int nbits;
  1017. ASSERT(start >= folio_start && start + len <= folio_start + PAGE_SIZE);
  1018. start_bit = (start - folio_start) >> fs_info->sectorsize_bits;
  1019. nbits = len >> fs_info->sectorsize_bits;
  1020. ASSERT(bitmap_test_range_all_zero(delalloc_bitmap, start_bit, nbits));
  1021. bitmap_set(delalloc_bitmap, start_bit, nbits);
  1022. }
  1023. static bool find_next_delalloc_bitmap(struct folio *folio,
  1024. unsigned long *delalloc_bitmap, u64 start,
  1025. u64 *found_start, u32 *found_len)
  1026. {
  1027. struct btrfs_fs_info *fs_info = folio_to_fs_info(folio);
  1028. const u64 folio_start = folio_pos(folio);
  1029. const unsigned int bitmap_size = fs_info->sectors_per_page;
  1030. unsigned int start_bit;
  1031. unsigned int first_zero;
  1032. unsigned int first_set;
  1033. ASSERT(start >= folio_start && start < folio_start + PAGE_SIZE);
  1034. start_bit = (start - folio_start) >> fs_info->sectorsize_bits;
  1035. first_set = find_next_bit(delalloc_bitmap, bitmap_size, start_bit);
  1036. if (first_set >= bitmap_size)
  1037. return false;
  1038. *found_start = folio_start + (first_set << fs_info->sectorsize_bits);
  1039. first_zero = find_next_zero_bit(delalloc_bitmap, bitmap_size, first_set);
  1040. *found_len = (first_zero - first_set) << fs_info->sectorsize_bits;
  1041. return true;
  1042. }
  1043. /*
  1044. * Do all of the delayed allocation setup.
  1045. *
  1046. * Return >0 if all the dirty blocks are submitted async (compression) or inlined.
  1047. * The @folio should no longer be touched (treat it as already unlocked).
  1048. *
  1049. * Return 0 if there is still dirty block that needs to be submitted through
  1050. * extent_writepage_io().
  1051. * bio_ctrl->submit_bitmap will indicate which blocks of the folio should be
  1052. * submitted, and @folio is still kept locked.
  1053. *
  1054. * Return <0 if there is any error hit.
  1055. * Any allocated ordered extent range covering this folio will be marked
  1056. * finished (IOERR), and @folio is still kept locked.
  1057. */
  1058. static noinline_for_stack int writepage_delalloc(struct btrfs_inode *inode,
  1059. struct folio *folio,
  1060. struct btrfs_bio_ctrl *bio_ctrl)
  1061. {
  1062. struct btrfs_fs_info *fs_info = inode_to_fs_info(&inode->vfs_inode);
  1063. struct writeback_control *wbc = bio_ctrl->wbc;
  1064. const bool is_subpage = btrfs_is_subpage(fs_info, folio->mapping);
  1065. const u64 page_start = folio_pos(folio);
  1066. const u64 page_end = page_start + folio_size(folio) - 1;
  1067. unsigned long delalloc_bitmap = 0;
  1068. /*
  1069. * Save the last found delalloc end. As the delalloc end can go beyond
  1070. * page boundary, thus we cannot rely on subpage bitmap to locate the
  1071. * last delalloc end.
  1072. */
  1073. u64 last_delalloc_end = 0;
  1074. /*
  1075. * The range end (exclusive) of the last successfully finished delalloc
  1076. * range.
  1077. * Any range covered by ordered extent must either be manually marked
  1078. * finished (error handling), or has IO submitted (and finish the
  1079. * ordered extent normally).
  1080. *
  1081. * This records the end of ordered extent cleanup if we hit an error.
  1082. */
  1083. u64 last_finished_delalloc_end = page_start;
  1084. u64 delalloc_start = page_start;
  1085. u64 delalloc_end = page_end;
  1086. u64 delalloc_to_write = 0;
  1087. int ret = 0;
  1088. int bit;
  1089. /* Save the dirty bitmap as our submission bitmap will be a subset of it. */
  1090. if (btrfs_is_subpage(fs_info, inode->vfs_inode.i_mapping)) {
  1091. ASSERT(fs_info->sectors_per_page > 1);
  1092. btrfs_get_subpage_dirty_bitmap(fs_info, folio, &bio_ctrl->submit_bitmap);
  1093. } else {
  1094. bio_ctrl->submit_bitmap = 1;
  1095. }
  1096. for_each_set_bit(bit, &bio_ctrl->submit_bitmap, fs_info->sectors_per_page) {
  1097. u64 start = page_start + (bit << fs_info->sectorsize_bits);
  1098. btrfs_folio_set_lock(fs_info, folio, start, fs_info->sectorsize);
  1099. }
  1100. /* Lock all (subpage) delalloc ranges inside the folio first. */
  1101. while (delalloc_start < page_end) {
  1102. delalloc_end = page_end;
  1103. if (!find_lock_delalloc_range(&inode->vfs_inode, folio,
  1104. &delalloc_start, &delalloc_end)) {
  1105. delalloc_start = delalloc_end + 1;
  1106. continue;
  1107. }
  1108. set_delalloc_bitmap(folio, &delalloc_bitmap, delalloc_start,
  1109. min(delalloc_end, page_end) + 1 - delalloc_start);
  1110. last_delalloc_end = delalloc_end;
  1111. delalloc_start = delalloc_end + 1;
  1112. }
  1113. delalloc_start = page_start;
  1114. if (!last_delalloc_end)
  1115. goto out;
  1116. /* Run the delalloc ranges for the above locked ranges. */
  1117. while (delalloc_start < page_end) {
  1118. u64 found_start;
  1119. u32 found_len;
  1120. bool found;
  1121. if (!is_subpage) {
  1122. /*
  1123. * For non-subpage case, the found delalloc range must
  1124. * cover this folio and there must be only one locked
  1125. * delalloc range.
  1126. */
  1127. found_start = page_start;
  1128. found_len = last_delalloc_end + 1 - found_start;
  1129. found = true;
  1130. } else {
  1131. found = find_next_delalloc_bitmap(folio, &delalloc_bitmap,
  1132. delalloc_start, &found_start, &found_len);
  1133. }
  1134. if (!found)
  1135. break;
  1136. /*
  1137. * The subpage range covers the last sector, the delalloc range may
  1138. * end beyond the folio boundary, use the saved delalloc_end
  1139. * instead.
  1140. */
  1141. if (found_start + found_len >= page_end)
  1142. found_len = last_delalloc_end + 1 - found_start;
  1143. if (ret >= 0) {
  1144. /*
  1145. * Some delalloc range may be created by previous folios.
  1146. * Thus we still need to clean up this range during error
  1147. * handling.
  1148. */
  1149. last_finished_delalloc_end = found_start;
  1150. /* No errors hit so far, run the current delalloc range. */
  1151. ret = btrfs_run_delalloc_range(inode, folio,
  1152. found_start,
  1153. found_start + found_len - 1,
  1154. wbc);
  1155. if (ret >= 0)
  1156. last_finished_delalloc_end = found_start + found_len;
  1157. } else {
  1158. /*
  1159. * We've hit an error during previous delalloc range,
  1160. * have to cleanup the remaining locked ranges.
  1161. */
  1162. unlock_extent(&inode->io_tree, found_start,
  1163. found_start + found_len - 1, NULL);
  1164. __unlock_for_delalloc(&inode->vfs_inode, folio,
  1165. found_start,
  1166. found_start + found_len - 1);
  1167. }
  1168. /*
  1169. * We have some ranges that's going to be submitted asynchronously
  1170. * (compression or inline). These range have their own control
  1171. * on when to unlock the pages. We should not touch them
  1172. * anymore, so clear the range from the submission bitmap.
  1173. */
  1174. if (ret > 0) {
  1175. unsigned int start_bit = (found_start - page_start) >>
  1176. fs_info->sectorsize_bits;
  1177. unsigned int end_bit = (min(page_end + 1, found_start + found_len) -
  1178. page_start) >> fs_info->sectorsize_bits;
  1179. bitmap_clear(&bio_ctrl->submit_bitmap, start_bit, end_bit - start_bit);
  1180. }
  1181. /*
  1182. * Above btrfs_run_delalloc_range() may have unlocked the folio,
  1183. * thus for the last range, we cannot touch the folio anymore.
  1184. */
  1185. if (found_start + found_len >= last_delalloc_end + 1)
  1186. break;
  1187. delalloc_start = found_start + found_len;
  1188. }
  1189. /*
  1190. * It's possible we had some ordered extents created before we hit
  1191. * an error, cleanup non-async successfully created delalloc ranges.
  1192. */
  1193. if (unlikely(ret < 0)) {
  1194. unsigned int bitmap_size = min(
  1195. (last_finished_delalloc_end - page_start) >>
  1196. fs_info->sectorsize_bits,
  1197. fs_info->sectors_per_page);
  1198. for_each_set_bit(bit, &bio_ctrl->submit_bitmap, bitmap_size)
  1199. btrfs_mark_ordered_io_finished(inode, folio,
  1200. page_start + (bit << fs_info->sectorsize_bits),
  1201. fs_info->sectorsize, false);
  1202. return ret;
  1203. }
  1204. out:
  1205. if (last_delalloc_end)
  1206. delalloc_end = last_delalloc_end;
  1207. else
  1208. delalloc_end = page_end;
  1209. /*
  1210. * delalloc_end is already one less than the total length, so
  1211. * we don't subtract one from PAGE_SIZE
  1212. */
  1213. delalloc_to_write +=
  1214. DIV_ROUND_UP(delalloc_end + 1 - page_start, PAGE_SIZE);
  1215. /*
  1216. * If all ranges are submitted asynchronously, we just need to account
  1217. * for them here.
  1218. */
  1219. if (bitmap_empty(&bio_ctrl->submit_bitmap, fs_info->sectors_per_page)) {
  1220. wbc->nr_to_write -= delalloc_to_write;
  1221. return 1;
  1222. }
  1223. if (wbc->nr_to_write < delalloc_to_write) {
  1224. int thresh = 8192;
  1225. if (delalloc_to_write < thresh * 2)
  1226. thresh = delalloc_to_write;
  1227. wbc->nr_to_write = min_t(u64, delalloc_to_write,
  1228. thresh);
  1229. }
  1230. return 0;
  1231. }
  1232. /*
  1233. * Return 0 if we have submitted or queued the sector for submission.
  1234. * Return <0 for critical errors.
  1235. *
  1236. * Caller should make sure filepos < i_size and handle filepos >= i_size case.
  1237. */
  1238. static int submit_one_sector(struct btrfs_inode *inode,
  1239. struct folio *folio,
  1240. u64 filepos, struct btrfs_bio_ctrl *bio_ctrl,
  1241. loff_t i_size)
  1242. {
  1243. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  1244. struct extent_map *em;
  1245. u64 block_start;
  1246. u64 disk_bytenr;
  1247. u64 extent_offset;
  1248. u64 em_end;
  1249. const u32 sectorsize = fs_info->sectorsize;
  1250. ASSERT(IS_ALIGNED(filepos, sectorsize));
  1251. /* @filepos >= i_size case should be handled by the caller. */
  1252. ASSERT(filepos < i_size);
  1253. em = btrfs_get_extent(inode, NULL, filepos, sectorsize);
  1254. if (IS_ERR(em))
  1255. return PTR_ERR_OR_ZERO(em);
  1256. extent_offset = filepos - em->start;
  1257. em_end = extent_map_end(em);
  1258. ASSERT(filepos <= em_end);
  1259. ASSERT(IS_ALIGNED(em->start, sectorsize));
  1260. ASSERT(IS_ALIGNED(em->len, sectorsize));
  1261. block_start = extent_map_block_start(em);
  1262. disk_bytenr = extent_map_block_start(em) + extent_offset;
  1263. ASSERT(!extent_map_is_compressed(em));
  1264. ASSERT(block_start != EXTENT_MAP_HOLE);
  1265. ASSERT(block_start != EXTENT_MAP_INLINE);
  1266. free_extent_map(em);
  1267. em = NULL;
  1268. /*
  1269. * Although the PageDirty bit is cleared before entering this
  1270. * function, subpage dirty bit is not cleared.
  1271. * So clear subpage dirty bit here so next time we won't submit
  1272. * a folio for a range already written to disk.
  1273. */
  1274. btrfs_folio_clear_dirty(fs_info, folio, filepos, sectorsize);
  1275. btrfs_set_range_writeback(inode, filepos, filepos + sectorsize - 1);
  1276. /*
  1277. * Above call should set the whole folio with writeback flag, even
  1278. * just for a single subpage sector.
  1279. * As long as the folio is properly locked and the range is correct,
  1280. * we should always get the folio with writeback flag.
  1281. */
  1282. ASSERT(folio_test_writeback(folio));
  1283. submit_extent_folio(bio_ctrl, disk_bytenr, folio,
  1284. sectorsize, filepos - folio_pos(folio));
  1285. return 0;
  1286. }
  1287. /*
  1288. * Helper for extent_writepage(). This calls the writepage start hooks,
  1289. * and does the loop to map the page into extents and bios.
  1290. *
  1291. * We return 1 if the IO is started and the page is unlocked,
  1292. * 0 if all went well (page still locked)
  1293. * < 0 if there were errors (page still locked)
  1294. */
  1295. static noinline_for_stack int extent_writepage_io(struct btrfs_inode *inode,
  1296. struct folio *folio,
  1297. u64 start, u32 len,
  1298. struct btrfs_bio_ctrl *bio_ctrl,
  1299. loff_t i_size)
  1300. {
  1301. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  1302. unsigned long range_bitmap = 0;
  1303. bool submitted_io = false;
  1304. int found_error = 0;
  1305. const u64 folio_start = folio_pos(folio);
  1306. u64 cur;
  1307. int bit;
  1308. int ret = 0;
  1309. ASSERT(start >= folio_start &&
  1310. start + len <= folio_start + folio_size(folio));
  1311. ret = btrfs_writepage_cow_fixup(folio);
  1312. if (ret) {
  1313. /* Fixup worker will requeue */
  1314. folio_redirty_for_writepage(bio_ctrl->wbc, folio);
  1315. folio_unlock(folio);
  1316. return 1;
  1317. }
  1318. for (cur = start; cur < start + len; cur += fs_info->sectorsize)
  1319. set_bit((cur - folio_start) >> fs_info->sectorsize_bits, &range_bitmap);
  1320. bitmap_and(&bio_ctrl->submit_bitmap, &bio_ctrl->submit_bitmap, &range_bitmap,
  1321. fs_info->sectors_per_page);
  1322. bio_ctrl->end_io_func = end_bbio_data_write;
  1323. for_each_set_bit(bit, &bio_ctrl->submit_bitmap, fs_info->sectors_per_page) {
  1324. cur = folio_pos(folio) + (bit << fs_info->sectorsize_bits);
  1325. if (cur >= i_size) {
  1326. btrfs_mark_ordered_io_finished(inode, folio, cur,
  1327. start + len - cur, true);
  1328. /*
  1329. * This range is beyond i_size, thus we don't need to
  1330. * bother writing back.
  1331. * But we still need to clear the dirty subpage bit, or
  1332. * the next time the folio gets dirtied, we will try to
  1333. * writeback the sectors with subpage dirty bits,
  1334. * causing writeback without ordered extent.
  1335. */
  1336. btrfs_folio_clear_dirty(fs_info, folio, cur,
  1337. start + len - cur);
  1338. break;
  1339. }
  1340. ret = submit_one_sector(inode, folio, cur, bio_ctrl, i_size);
  1341. if (unlikely(ret < 0)) {
  1342. /*
  1343. * bio_ctrl may contain a bio crossing several folios.
  1344. * Submit it immediately so that the bio has a chance
  1345. * to finish normally, other than marked as error.
  1346. */
  1347. submit_one_bio(bio_ctrl);
  1348. /*
  1349. * Failed to grab the extent map which should be very rare.
  1350. * Since there is no bio submitted to finish the ordered
  1351. * extent, we have to manually finish this sector.
  1352. */
  1353. btrfs_mark_ordered_io_finished(inode, folio, cur,
  1354. fs_info->sectorsize, false);
  1355. if (!found_error)
  1356. found_error = ret;
  1357. continue;
  1358. }
  1359. submitted_io = true;
  1360. }
  1361. /*
  1362. * If we didn't submitted any sector (>= i_size), folio dirty get
  1363. * cleared but PAGECACHE_TAG_DIRTY is not cleared (only cleared
  1364. * by folio_start_writeback() if the folio is not dirty).
  1365. *
  1366. * Here we set writeback and clear for the range. If the full folio
  1367. * is no longer dirty then we clear the PAGECACHE_TAG_DIRTY tag.
  1368. *
  1369. * If we hit any error, the corresponding sector will still be dirty
  1370. * thus no need to clear PAGECACHE_TAG_DIRTY.
  1371. */
  1372. if (!submitted_io && !found_error) {
  1373. btrfs_folio_set_writeback(fs_info, folio, start, len);
  1374. btrfs_folio_clear_writeback(fs_info, folio, start, len);
  1375. }
  1376. return found_error;
  1377. }
  1378. /*
  1379. * the writepage semantics are similar to regular writepage. extent
  1380. * records are inserted to lock ranges in the tree, and as dirty areas
  1381. * are found, they are marked writeback. Then the lock bits are removed
  1382. * and the end_io handler clears the writeback ranges
  1383. *
  1384. * Return 0 if everything goes well.
  1385. * Return <0 for error.
  1386. */
  1387. static int extent_writepage(struct folio *folio, struct btrfs_bio_ctrl *bio_ctrl)
  1388. {
  1389. struct btrfs_inode *inode = BTRFS_I(folio->mapping->host);
  1390. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  1391. int ret;
  1392. size_t pg_offset;
  1393. loff_t i_size = i_size_read(&inode->vfs_inode);
  1394. unsigned long end_index = i_size >> PAGE_SHIFT;
  1395. trace_extent_writepage(folio, &inode->vfs_inode, bio_ctrl->wbc);
  1396. WARN_ON(!folio_test_locked(folio));
  1397. pg_offset = offset_in_folio(folio, i_size);
  1398. if (folio->index > end_index ||
  1399. (folio->index == end_index && !pg_offset)) {
  1400. folio_invalidate(folio, 0, folio_size(folio));
  1401. folio_unlock(folio);
  1402. return 0;
  1403. }
  1404. if (folio->index == end_index)
  1405. folio_zero_range(folio, pg_offset, folio_size(folio) - pg_offset);
  1406. /*
  1407. * Default to unlock the whole folio.
  1408. * The proper bitmap can only be initialized until writepage_delalloc().
  1409. */
  1410. bio_ctrl->submit_bitmap = (unsigned long)-1;
  1411. ret = set_folio_extent_mapped(folio);
  1412. if (ret < 0)
  1413. goto done;
  1414. ret = writepage_delalloc(inode, folio, bio_ctrl);
  1415. if (ret == 1)
  1416. return 0;
  1417. if (ret)
  1418. goto done;
  1419. ret = extent_writepage_io(inode, folio, folio_pos(folio),
  1420. PAGE_SIZE, bio_ctrl, i_size);
  1421. if (ret == 1)
  1422. return 0;
  1423. bio_ctrl->wbc->nr_to_write--;
  1424. done:
  1425. if (ret < 0)
  1426. mapping_set_error(folio->mapping, ret);
  1427. /*
  1428. * Only unlock ranges that are submitted. As there can be some async
  1429. * submitted ranges inside the folio.
  1430. */
  1431. btrfs_folio_end_lock_bitmap(fs_info, folio, bio_ctrl->submit_bitmap);
  1432. ASSERT(ret <= 0);
  1433. return ret;
  1434. }
  1435. void wait_on_extent_buffer_writeback(struct extent_buffer *eb)
  1436. {
  1437. wait_on_bit_io(&eb->bflags, EXTENT_BUFFER_WRITEBACK,
  1438. TASK_UNINTERRUPTIBLE);
  1439. }
  1440. /*
  1441. * Lock extent buffer status and pages for writeback.
  1442. *
  1443. * Return %false if the extent buffer doesn't need to be submitted (e.g. the
  1444. * extent buffer is not dirty)
  1445. * Return %true is the extent buffer is submitted to bio.
  1446. */
  1447. static noinline_for_stack bool lock_extent_buffer_for_io(struct extent_buffer *eb,
  1448. struct writeback_control *wbc)
  1449. {
  1450. struct btrfs_fs_info *fs_info = eb->fs_info;
  1451. bool ret = false;
  1452. btrfs_tree_lock(eb);
  1453. while (test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags)) {
  1454. btrfs_tree_unlock(eb);
  1455. if (wbc->sync_mode != WB_SYNC_ALL)
  1456. return false;
  1457. wait_on_extent_buffer_writeback(eb);
  1458. btrfs_tree_lock(eb);
  1459. }
  1460. /*
  1461. * We need to do this to prevent races in people who check if the eb is
  1462. * under IO since we can end up having no IO bits set for a short period
  1463. * of time.
  1464. */
  1465. spin_lock(&eb->refs_lock);
  1466. if (test_and_clear_bit(EXTENT_BUFFER_DIRTY, &eb->bflags)) {
  1467. set_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
  1468. spin_unlock(&eb->refs_lock);
  1469. btrfs_set_header_flag(eb, BTRFS_HEADER_FLAG_WRITTEN);
  1470. percpu_counter_add_batch(&fs_info->dirty_metadata_bytes,
  1471. -eb->len,
  1472. fs_info->dirty_metadata_batch);
  1473. ret = true;
  1474. } else {
  1475. spin_unlock(&eb->refs_lock);
  1476. }
  1477. btrfs_tree_unlock(eb);
  1478. return ret;
  1479. }
  1480. static void set_btree_ioerr(struct extent_buffer *eb)
  1481. {
  1482. struct btrfs_fs_info *fs_info = eb->fs_info;
  1483. set_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags);
  1484. /*
  1485. * A read may stumble upon this buffer later, make sure that it gets an
  1486. * error and knows there was an error.
  1487. */
  1488. clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
  1489. /*
  1490. * We need to set the mapping with the io error as well because a write
  1491. * error will flip the file system readonly, and then syncfs() will
  1492. * return a 0 because we are readonly if we don't modify the err seq for
  1493. * the superblock.
  1494. */
  1495. mapping_set_error(eb->fs_info->btree_inode->i_mapping, -EIO);
  1496. /*
  1497. * If writeback for a btree extent that doesn't belong to a log tree
  1498. * failed, increment the counter transaction->eb_write_errors.
  1499. * We do this because while the transaction is running and before it's
  1500. * committing (when we call filemap_fdata[write|wait]_range against
  1501. * the btree inode), we might have
  1502. * btree_inode->i_mapping->a_ops->writepages() called by the VM - if it
  1503. * returns an error or an error happens during writeback, when we're
  1504. * committing the transaction we wouldn't know about it, since the pages
  1505. * can be no longer dirty nor marked anymore for writeback (if a
  1506. * subsequent modification to the extent buffer didn't happen before the
  1507. * transaction commit), which makes filemap_fdata[write|wait]_range not
  1508. * able to find the pages which contain errors at transaction
  1509. * commit time. So if this happens we must abort the transaction,
  1510. * otherwise we commit a super block with btree roots that point to
  1511. * btree nodes/leafs whose content on disk is invalid - either garbage
  1512. * or the content of some node/leaf from a past generation that got
  1513. * cowed or deleted and is no longer valid.
  1514. *
  1515. * Note: setting AS_EIO/AS_ENOSPC in the btree inode's i_mapping would
  1516. * not be enough - we need to distinguish between log tree extents vs
  1517. * non-log tree extents, and the next filemap_fdatawait_range() call
  1518. * will catch and clear such errors in the mapping - and that call might
  1519. * be from a log sync and not from a transaction commit. Also, checking
  1520. * for the eb flag EXTENT_BUFFER_WRITE_ERR at transaction commit time is
  1521. * not done and would not be reliable - the eb might have been released
  1522. * from memory and reading it back again means that flag would not be
  1523. * set (since it's a runtime flag, not persisted on disk).
  1524. *
  1525. * Using the flags below in the btree inode also makes us achieve the
  1526. * goal of AS_EIO/AS_ENOSPC when writepages() returns success, started
  1527. * writeback for all dirty pages and before filemap_fdatawait_range()
  1528. * is called, the writeback for all dirty pages had already finished
  1529. * with errors - because we were not using AS_EIO/AS_ENOSPC,
  1530. * filemap_fdatawait_range() would return success, as it could not know
  1531. * that writeback errors happened (the pages were no longer tagged for
  1532. * writeback).
  1533. */
  1534. switch (eb->log_index) {
  1535. case -1:
  1536. set_bit(BTRFS_FS_BTREE_ERR, &fs_info->flags);
  1537. break;
  1538. case 0:
  1539. set_bit(BTRFS_FS_LOG1_ERR, &fs_info->flags);
  1540. break;
  1541. case 1:
  1542. set_bit(BTRFS_FS_LOG2_ERR, &fs_info->flags);
  1543. break;
  1544. default:
  1545. BUG(); /* unexpected, logic error */
  1546. }
  1547. }
  1548. /*
  1549. * The endio specific version which won't touch any unsafe spinlock in endio
  1550. * context.
  1551. */
  1552. static struct extent_buffer *find_extent_buffer_nolock(
  1553. const struct btrfs_fs_info *fs_info, u64 start)
  1554. {
  1555. struct extent_buffer *eb;
  1556. rcu_read_lock();
  1557. eb = radix_tree_lookup(&fs_info->buffer_radix,
  1558. start >> fs_info->sectorsize_bits);
  1559. if (eb && atomic_inc_not_zero(&eb->refs)) {
  1560. rcu_read_unlock();
  1561. return eb;
  1562. }
  1563. rcu_read_unlock();
  1564. return NULL;
  1565. }
  1566. static void end_bbio_meta_write(struct btrfs_bio *bbio)
  1567. {
  1568. struct extent_buffer *eb = bbio->private;
  1569. struct btrfs_fs_info *fs_info = eb->fs_info;
  1570. bool uptodate = !bbio->bio.bi_status;
  1571. struct folio_iter fi;
  1572. u32 bio_offset = 0;
  1573. if (!uptodate)
  1574. set_btree_ioerr(eb);
  1575. bio_for_each_folio_all(fi, &bbio->bio) {
  1576. u64 start = eb->start + bio_offset;
  1577. struct folio *folio = fi.folio;
  1578. u32 len = fi.length;
  1579. btrfs_folio_clear_writeback(fs_info, folio, start, len);
  1580. bio_offset += len;
  1581. }
  1582. clear_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags);
  1583. smp_mb__after_atomic();
  1584. wake_up_bit(&eb->bflags, EXTENT_BUFFER_WRITEBACK);
  1585. bio_put(&bbio->bio);
  1586. }
  1587. static void prepare_eb_write(struct extent_buffer *eb)
  1588. {
  1589. u32 nritems;
  1590. unsigned long start;
  1591. unsigned long end;
  1592. clear_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags);
  1593. /* Set btree blocks beyond nritems with 0 to avoid stale content */
  1594. nritems = btrfs_header_nritems(eb);
  1595. if (btrfs_header_level(eb) > 0) {
  1596. end = btrfs_node_key_ptr_offset(eb, nritems);
  1597. memzero_extent_buffer(eb, end, eb->len - end);
  1598. } else {
  1599. /*
  1600. * Leaf:
  1601. * header 0 1 2 .. N ... data_N .. data_2 data_1 data_0
  1602. */
  1603. start = btrfs_item_nr_offset(eb, nritems);
  1604. end = btrfs_item_nr_offset(eb, 0);
  1605. if (nritems == 0)
  1606. end += BTRFS_LEAF_DATA_SIZE(eb->fs_info);
  1607. else
  1608. end += btrfs_item_offset(eb, nritems - 1);
  1609. memzero_extent_buffer(eb, start, end - start);
  1610. }
  1611. }
  1612. static noinline_for_stack void write_one_eb(struct extent_buffer *eb,
  1613. struct writeback_control *wbc)
  1614. {
  1615. struct btrfs_fs_info *fs_info = eb->fs_info;
  1616. struct btrfs_bio *bbio;
  1617. prepare_eb_write(eb);
  1618. bbio = btrfs_bio_alloc(INLINE_EXTENT_BUFFER_PAGES,
  1619. REQ_OP_WRITE | REQ_META | wbc_to_write_flags(wbc),
  1620. eb->fs_info, end_bbio_meta_write, eb);
  1621. bbio->bio.bi_iter.bi_sector = eb->start >> SECTOR_SHIFT;
  1622. bio_set_dev(&bbio->bio, fs_info->fs_devices->latest_dev->bdev);
  1623. wbc_init_bio(wbc, &bbio->bio);
  1624. bbio->inode = BTRFS_I(eb->fs_info->btree_inode);
  1625. bbio->file_offset = eb->start;
  1626. if (fs_info->nodesize < PAGE_SIZE) {
  1627. struct folio *folio = eb->folios[0];
  1628. bool ret;
  1629. folio_lock(folio);
  1630. btrfs_subpage_set_writeback(fs_info, folio, eb->start, eb->len);
  1631. if (btrfs_subpage_clear_and_test_dirty(fs_info, folio, eb->start,
  1632. eb->len)) {
  1633. folio_clear_dirty_for_io(folio);
  1634. wbc->nr_to_write--;
  1635. }
  1636. ret = bio_add_folio(&bbio->bio, folio, eb->len,
  1637. eb->start - folio_pos(folio));
  1638. ASSERT(ret);
  1639. wbc_account_cgroup_owner(wbc, folio, eb->len);
  1640. folio_unlock(folio);
  1641. } else {
  1642. int num_folios = num_extent_folios(eb);
  1643. for (int i = 0; i < num_folios; i++) {
  1644. struct folio *folio = eb->folios[i];
  1645. bool ret;
  1646. folio_lock(folio);
  1647. folio_clear_dirty_for_io(folio);
  1648. folio_start_writeback(folio);
  1649. ret = bio_add_folio(&bbio->bio, folio, eb->folio_size, 0);
  1650. ASSERT(ret);
  1651. wbc_account_cgroup_owner(wbc, folio, eb->folio_size);
  1652. wbc->nr_to_write -= folio_nr_pages(folio);
  1653. folio_unlock(folio);
  1654. }
  1655. }
  1656. btrfs_submit_bbio(bbio, 0);
  1657. }
  1658. /*
  1659. * Submit one subpage btree page.
  1660. *
  1661. * The main difference to submit_eb_page() is:
  1662. * - Page locking
  1663. * For subpage, we don't rely on page locking at all.
  1664. *
  1665. * - Flush write bio
  1666. * We only flush bio if we may be unable to fit current extent buffers into
  1667. * current bio.
  1668. *
  1669. * Return >=0 for the number of submitted extent buffers.
  1670. * Return <0 for fatal error.
  1671. */
  1672. static int submit_eb_subpage(struct folio *folio, struct writeback_control *wbc)
  1673. {
  1674. struct btrfs_fs_info *fs_info = folio_to_fs_info(folio);
  1675. int submitted = 0;
  1676. u64 folio_start = folio_pos(folio);
  1677. int bit_start = 0;
  1678. int sectors_per_node = fs_info->nodesize >> fs_info->sectorsize_bits;
  1679. /* Lock and write each dirty extent buffers in the range */
  1680. while (bit_start < fs_info->sectors_per_page) {
  1681. struct btrfs_subpage *subpage = folio_get_private(folio);
  1682. struct extent_buffer *eb;
  1683. unsigned long flags;
  1684. u64 start;
  1685. /*
  1686. * Take private lock to ensure the subpage won't be detached
  1687. * in the meantime.
  1688. */
  1689. spin_lock(&folio->mapping->i_private_lock);
  1690. if (!folio_test_private(folio)) {
  1691. spin_unlock(&folio->mapping->i_private_lock);
  1692. break;
  1693. }
  1694. spin_lock_irqsave(&subpage->lock, flags);
  1695. if (!test_bit(bit_start + btrfs_bitmap_nr_dirty * fs_info->sectors_per_page,
  1696. subpage->bitmaps)) {
  1697. spin_unlock_irqrestore(&subpage->lock, flags);
  1698. spin_unlock(&folio->mapping->i_private_lock);
  1699. bit_start += sectors_per_node;
  1700. continue;
  1701. }
  1702. start = folio_start + bit_start * fs_info->sectorsize;
  1703. bit_start += sectors_per_node;
  1704. /*
  1705. * Here we just want to grab the eb without touching extra
  1706. * spin locks, so call find_extent_buffer_nolock().
  1707. */
  1708. eb = find_extent_buffer_nolock(fs_info, start);
  1709. spin_unlock_irqrestore(&subpage->lock, flags);
  1710. spin_unlock(&folio->mapping->i_private_lock);
  1711. /*
  1712. * The eb has already reached 0 refs thus find_extent_buffer()
  1713. * doesn't return it. We don't need to write back such eb
  1714. * anyway.
  1715. */
  1716. if (!eb)
  1717. continue;
  1718. if (lock_extent_buffer_for_io(eb, wbc)) {
  1719. write_one_eb(eb, wbc);
  1720. submitted++;
  1721. }
  1722. free_extent_buffer(eb);
  1723. }
  1724. return submitted;
  1725. }
  1726. /*
  1727. * Submit all page(s) of one extent buffer.
  1728. *
  1729. * @page: the page of one extent buffer
  1730. * @eb_context: to determine if we need to submit this page, if current page
  1731. * belongs to this eb, we don't need to submit
  1732. *
  1733. * The caller should pass each page in their bytenr order, and here we use
  1734. * @eb_context to determine if we have submitted pages of one extent buffer.
  1735. *
  1736. * If we have, we just skip until we hit a new page that doesn't belong to
  1737. * current @eb_context.
  1738. *
  1739. * If not, we submit all the page(s) of the extent buffer.
  1740. *
  1741. * Return >0 if we have submitted the extent buffer successfully.
  1742. * Return 0 if we don't need to submit the page, as it's already submitted by
  1743. * previous call.
  1744. * Return <0 for fatal error.
  1745. */
  1746. static int submit_eb_page(struct folio *folio, struct btrfs_eb_write_context *ctx)
  1747. {
  1748. struct writeback_control *wbc = ctx->wbc;
  1749. struct address_space *mapping = folio->mapping;
  1750. struct extent_buffer *eb;
  1751. int ret;
  1752. if (!folio_test_private(folio))
  1753. return 0;
  1754. if (folio_to_fs_info(folio)->nodesize < PAGE_SIZE)
  1755. return submit_eb_subpage(folio, wbc);
  1756. spin_lock(&mapping->i_private_lock);
  1757. if (!folio_test_private(folio)) {
  1758. spin_unlock(&mapping->i_private_lock);
  1759. return 0;
  1760. }
  1761. eb = folio_get_private(folio);
  1762. /*
  1763. * Shouldn't happen and normally this would be a BUG_ON but no point
  1764. * crashing the machine for something we can survive anyway.
  1765. */
  1766. if (WARN_ON(!eb)) {
  1767. spin_unlock(&mapping->i_private_lock);
  1768. return 0;
  1769. }
  1770. if (eb == ctx->eb) {
  1771. spin_unlock(&mapping->i_private_lock);
  1772. return 0;
  1773. }
  1774. ret = atomic_inc_not_zero(&eb->refs);
  1775. spin_unlock(&mapping->i_private_lock);
  1776. if (!ret)
  1777. return 0;
  1778. ctx->eb = eb;
  1779. ret = btrfs_check_meta_write_pointer(eb->fs_info, ctx);
  1780. if (ret) {
  1781. if (ret == -EBUSY)
  1782. ret = 0;
  1783. free_extent_buffer(eb);
  1784. return ret;
  1785. }
  1786. if (!lock_extent_buffer_for_io(eb, wbc)) {
  1787. free_extent_buffer(eb);
  1788. return 0;
  1789. }
  1790. /* Implies write in zoned mode. */
  1791. if (ctx->zoned_bg) {
  1792. /* Mark the last eb in the block group. */
  1793. btrfs_schedule_zone_finish_bg(ctx->zoned_bg, eb);
  1794. ctx->zoned_bg->meta_write_pointer += eb->len;
  1795. }
  1796. write_one_eb(eb, wbc);
  1797. free_extent_buffer(eb);
  1798. return 1;
  1799. }
  1800. int btree_write_cache_pages(struct address_space *mapping,
  1801. struct writeback_control *wbc)
  1802. {
  1803. struct btrfs_eb_write_context ctx = { .wbc = wbc };
  1804. struct btrfs_fs_info *fs_info = inode_to_fs_info(mapping->host);
  1805. int ret = 0;
  1806. int done = 0;
  1807. int nr_to_write_done = 0;
  1808. struct folio_batch fbatch;
  1809. unsigned int nr_folios;
  1810. pgoff_t index;
  1811. pgoff_t end; /* Inclusive */
  1812. int scanned = 0;
  1813. xa_mark_t tag;
  1814. folio_batch_init(&fbatch);
  1815. if (wbc->range_cyclic) {
  1816. index = mapping->writeback_index; /* Start from prev offset */
  1817. end = -1;
  1818. /*
  1819. * Start from the beginning does not need to cycle over the
  1820. * range, mark it as scanned.
  1821. */
  1822. scanned = (index == 0);
  1823. } else {
  1824. index = wbc->range_start >> PAGE_SHIFT;
  1825. end = wbc->range_end >> PAGE_SHIFT;
  1826. scanned = 1;
  1827. }
  1828. if (wbc->sync_mode == WB_SYNC_ALL)
  1829. tag = PAGECACHE_TAG_TOWRITE;
  1830. else
  1831. tag = PAGECACHE_TAG_DIRTY;
  1832. btrfs_zoned_meta_io_lock(fs_info);
  1833. retry:
  1834. if (wbc->sync_mode == WB_SYNC_ALL)
  1835. tag_pages_for_writeback(mapping, index, end);
  1836. while (!done && !nr_to_write_done && (index <= end) &&
  1837. (nr_folios = filemap_get_folios_tag(mapping, &index, end,
  1838. tag, &fbatch))) {
  1839. unsigned i;
  1840. for (i = 0; i < nr_folios; i++) {
  1841. struct folio *folio = fbatch.folios[i];
  1842. ret = submit_eb_page(folio, &ctx);
  1843. if (ret == 0)
  1844. continue;
  1845. if (ret < 0) {
  1846. done = 1;
  1847. break;
  1848. }
  1849. /*
  1850. * the filesystem may choose to bump up nr_to_write.
  1851. * We have to make sure to honor the new nr_to_write
  1852. * at any time
  1853. */
  1854. nr_to_write_done = wbc->nr_to_write <= 0;
  1855. }
  1856. folio_batch_release(&fbatch);
  1857. cond_resched();
  1858. }
  1859. if (!scanned && !done) {
  1860. /*
  1861. * We hit the last page and there is more work to be done: wrap
  1862. * back to the start of the file
  1863. */
  1864. scanned = 1;
  1865. index = 0;
  1866. goto retry;
  1867. }
  1868. /*
  1869. * If something went wrong, don't allow any metadata write bio to be
  1870. * submitted.
  1871. *
  1872. * This would prevent use-after-free if we had dirty pages not
  1873. * cleaned up, which can still happen by fuzzed images.
  1874. *
  1875. * - Bad extent tree
  1876. * Allowing existing tree block to be allocated for other trees.
  1877. *
  1878. * - Log tree operations
  1879. * Exiting tree blocks get allocated to log tree, bumps its
  1880. * generation, then get cleaned in tree re-balance.
  1881. * Such tree block will not be written back, since it's clean,
  1882. * thus no WRITTEN flag set.
  1883. * And after log writes back, this tree block is not traced by
  1884. * any dirty extent_io_tree.
  1885. *
  1886. * - Offending tree block gets re-dirtied from its original owner
  1887. * Since it has bumped generation, no WRITTEN flag, it can be
  1888. * reused without COWing. This tree block will not be traced
  1889. * by btrfs_transaction::dirty_pages.
  1890. *
  1891. * Now such dirty tree block will not be cleaned by any dirty
  1892. * extent io tree. Thus we don't want to submit such wild eb
  1893. * if the fs already has error.
  1894. *
  1895. * We can get ret > 0 from submit_extent_folio() indicating how many ebs
  1896. * were submitted. Reset it to 0 to avoid false alerts for the caller.
  1897. */
  1898. if (ret > 0)
  1899. ret = 0;
  1900. if (!ret && BTRFS_FS_ERROR(fs_info))
  1901. ret = -EROFS;
  1902. if (ctx.zoned_bg)
  1903. btrfs_put_block_group(ctx.zoned_bg);
  1904. btrfs_zoned_meta_io_unlock(fs_info);
  1905. return ret;
  1906. }
  1907. /*
  1908. * Walk the list of dirty pages of the given address space and write all of them.
  1909. *
  1910. * @mapping: address space structure to write
  1911. * @wbc: subtract the number of written pages from *@wbc->nr_to_write
  1912. * @bio_ctrl: holds context for the write, namely the bio
  1913. *
  1914. * If a page is already under I/O, write_cache_pages() skips it, even
  1915. * if it's dirty. This is desirable behaviour for memory-cleaning writeback,
  1916. * but it is INCORRECT for data-integrity system calls such as fsync(). fsync()
  1917. * and msync() need to guarantee that all the data which was dirty at the time
  1918. * the call was made get new I/O started against them. If wbc->sync_mode is
  1919. * WB_SYNC_ALL then we were called for data integrity and we must wait for
  1920. * existing IO to complete.
  1921. */
  1922. static int extent_write_cache_pages(struct address_space *mapping,
  1923. struct btrfs_bio_ctrl *bio_ctrl)
  1924. {
  1925. struct writeback_control *wbc = bio_ctrl->wbc;
  1926. struct inode *inode = mapping->host;
  1927. int ret = 0;
  1928. int done = 0;
  1929. int nr_to_write_done = 0;
  1930. struct folio_batch fbatch;
  1931. unsigned int nr_folios;
  1932. pgoff_t index;
  1933. pgoff_t end; /* Inclusive */
  1934. pgoff_t done_index;
  1935. int range_whole = 0;
  1936. int scanned = 0;
  1937. xa_mark_t tag;
  1938. /*
  1939. * We have to hold onto the inode so that ordered extents can do their
  1940. * work when the IO finishes. The alternative to this is failing to add
  1941. * an ordered extent if the igrab() fails there and that is a huge pain
  1942. * to deal with, so instead just hold onto the inode throughout the
  1943. * writepages operation. If it fails here we are freeing up the inode
  1944. * anyway and we'd rather not waste our time writing out stuff that is
  1945. * going to be truncated anyway.
  1946. */
  1947. if (!igrab(inode))
  1948. return 0;
  1949. folio_batch_init(&fbatch);
  1950. if (wbc->range_cyclic) {
  1951. index = mapping->writeback_index; /* Start from prev offset */
  1952. end = -1;
  1953. /*
  1954. * Start from the beginning does not need to cycle over the
  1955. * range, mark it as scanned.
  1956. */
  1957. scanned = (index == 0);
  1958. } else {
  1959. index = wbc->range_start >> PAGE_SHIFT;
  1960. end = wbc->range_end >> PAGE_SHIFT;
  1961. if (wbc->range_start == 0 && wbc->range_end == LLONG_MAX)
  1962. range_whole = 1;
  1963. scanned = 1;
  1964. }
  1965. /*
  1966. * We do the tagged writepage as long as the snapshot flush bit is set
  1967. * and we are the first one who do the filemap_flush() on this inode.
  1968. *
  1969. * The nr_to_write == LONG_MAX is needed to make sure other flushers do
  1970. * not race in and drop the bit.
  1971. */
  1972. if (range_whole && wbc->nr_to_write == LONG_MAX &&
  1973. test_and_clear_bit(BTRFS_INODE_SNAPSHOT_FLUSH,
  1974. &BTRFS_I(inode)->runtime_flags))
  1975. wbc->tagged_writepages = 1;
  1976. if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
  1977. tag = PAGECACHE_TAG_TOWRITE;
  1978. else
  1979. tag = PAGECACHE_TAG_DIRTY;
  1980. retry:
  1981. if (wbc->sync_mode == WB_SYNC_ALL || wbc->tagged_writepages)
  1982. tag_pages_for_writeback(mapping, index, end);
  1983. done_index = index;
  1984. while (!done && !nr_to_write_done && (index <= end) &&
  1985. (nr_folios = filemap_get_folios_tag(mapping, &index,
  1986. end, tag, &fbatch))) {
  1987. unsigned i;
  1988. for (i = 0; i < nr_folios; i++) {
  1989. struct folio *folio = fbatch.folios[i];
  1990. done_index = folio_next_index(folio);
  1991. /*
  1992. * At this point we hold neither the i_pages lock nor
  1993. * the page lock: the page may be truncated or
  1994. * invalidated (changing page->mapping to NULL),
  1995. * or even swizzled back from swapper_space to
  1996. * tmpfs file mapping
  1997. */
  1998. if (!folio_trylock(folio)) {
  1999. submit_write_bio(bio_ctrl, 0);
  2000. folio_lock(folio);
  2001. }
  2002. if (unlikely(folio->mapping != mapping)) {
  2003. folio_unlock(folio);
  2004. continue;
  2005. }
  2006. if (!folio_test_dirty(folio)) {
  2007. /* Someone wrote it for us. */
  2008. folio_unlock(folio);
  2009. continue;
  2010. }
  2011. if (wbc->sync_mode != WB_SYNC_NONE) {
  2012. if (folio_test_writeback(folio))
  2013. submit_write_bio(bio_ctrl, 0);
  2014. folio_wait_writeback(folio);
  2015. }
  2016. if (folio_test_writeback(folio) ||
  2017. !folio_clear_dirty_for_io(folio)) {
  2018. folio_unlock(folio);
  2019. continue;
  2020. }
  2021. ret = extent_writepage(folio, bio_ctrl);
  2022. if (ret < 0) {
  2023. done = 1;
  2024. break;
  2025. }
  2026. /*
  2027. * The filesystem may choose to bump up nr_to_write.
  2028. * We have to make sure to honor the new nr_to_write
  2029. * at any time.
  2030. */
  2031. nr_to_write_done = (wbc->sync_mode == WB_SYNC_NONE &&
  2032. wbc->nr_to_write <= 0);
  2033. }
  2034. folio_batch_release(&fbatch);
  2035. cond_resched();
  2036. }
  2037. if (!scanned && !done) {
  2038. /*
  2039. * We hit the last page and there is more work to be done: wrap
  2040. * back to the start of the file
  2041. */
  2042. scanned = 1;
  2043. index = 0;
  2044. /*
  2045. * If we're looping we could run into a page that is locked by a
  2046. * writer and that writer could be waiting on writeback for a
  2047. * page in our current bio, and thus deadlock, so flush the
  2048. * write bio here.
  2049. */
  2050. submit_write_bio(bio_ctrl, 0);
  2051. goto retry;
  2052. }
  2053. if (wbc->range_cyclic || (wbc->nr_to_write > 0 && range_whole))
  2054. mapping->writeback_index = done_index;
  2055. btrfs_add_delayed_iput(BTRFS_I(inode));
  2056. return ret;
  2057. }
  2058. /*
  2059. * Submit the pages in the range to bio for call sites which delalloc range has
  2060. * already been ran (aka, ordered extent inserted) and all pages are still
  2061. * locked.
  2062. */
  2063. void extent_write_locked_range(struct inode *inode, const struct folio *locked_folio,
  2064. u64 start, u64 end, struct writeback_control *wbc,
  2065. bool pages_dirty)
  2066. {
  2067. bool found_error = false;
  2068. int ret = 0;
  2069. struct address_space *mapping = inode->i_mapping;
  2070. struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
  2071. const u32 sectorsize = fs_info->sectorsize;
  2072. loff_t i_size = i_size_read(inode);
  2073. u64 cur = start;
  2074. struct btrfs_bio_ctrl bio_ctrl = {
  2075. .wbc = wbc,
  2076. .opf = REQ_OP_WRITE | wbc_to_write_flags(wbc),
  2077. };
  2078. if (wbc->no_cgroup_owner)
  2079. bio_ctrl.opf |= REQ_BTRFS_CGROUP_PUNT;
  2080. ASSERT(IS_ALIGNED(start, sectorsize) && IS_ALIGNED(end + 1, sectorsize));
  2081. while (cur <= end) {
  2082. u64 cur_end = min(round_down(cur, PAGE_SIZE) + PAGE_SIZE - 1, end);
  2083. u32 cur_len = cur_end + 1 - cur;
  2084. struct folio *folio;
  2085. folio = __filemap_get_folio(mapping, cur >> PAGE_SHIFT, 0, 0);
  2086. /*
  2087. * This shouldn't happen, the pages are pinned and locked, this
  2088. * code is just in case, but shouldn't actually be run.
  2089. */
  2090. if (IS_ERR(folio)) {
  2091. btrfs_mark_ordered_io_finished(BTRFS_I(inode), NULL,
  2092. cur, cur_len, false);
  2093. mapping_set_error(mapping, PTR_ERR(folio));
  2094. cur = cur_end + 1;
  2095. continue;
  2096. }
  2097. ASSERT(folio_test_locked(folio));
  2098. if (pages_dirty && folio != locked_folio)
  2099. ASSERT(folio_test_dirty(folio));
  2100. /*
  2101. * Set the submission bitmap to submit all sectors.
  2102. * extent_writepage_io() will do the truncation correctly.
  2103. */
  2104. bio_ctrl.submit_bitmap = (unsigned long)-1;
  2105. ret = extent_writepage_io(BTRFS_I(inode), folio, cur, cur_len,
  2106. &bio_ctrl, i_size);
  2107. if (ret == 1)
  2108. goto next_page;
  2109. if (ret)
  2110. mapping_set_error(mapping, ret);
  2111. btrfs_folio_end_lock(fs_info, folio, cur, cur_len);
  2112. if (ret < 0)
  2113. found_error = true;
  2114. next_page:
  2115. folio_put(folio);
  2116. cur = cur_end + 1;
  2117. }
  2118. submit_write_bio(&bio_ctrl, found_error ? ret : 0);
  2119. }
  2120. int btrfs_writepages(struct address_space *mapping, struct writeback_control *wbc)
  2121. {
  2122. struct inode *inode = mapping->host;
  2123. int ret = 0;
  2124. struct btrfs_bio_ctrl bio_ctrl = {
  2125. .wbc = wbc,
  2126. .opf = REQ_OP_WRITE | wbc_to_write_flags(wbc),
  2127. };
  2128. /*
  2129. * Allow only a single thread to do the reloc work in zoned mode to
  2130. * protect the write pointer updates.
  2131. */
  2132. btrfs_zoned_data_reloc_lock(BTRFS_I(inode));
  2133. ret = extent_write_cache_pages(mapping, &bio_ctrl);
  2134. submit_write_bio(&bio_ctrl, ret);
  2135. btrfs_zoned_data_reloc_unlock(BTRFS_I(inode));
  2136. return ret;
  2137. }
  2138. void btrfs_readahead(struct readahead_control *rac)
  2139. {
  2140. struct btrfs_bio_ctrl bio_ctrl = {
  2141. .opf = REQ_OP_READ | REQ_RAHEAD,
  2142. .ractl = rac,
  2143. .last_em_start = U64_MAX,
  2144. };
  2145. struct folio *folio;
  2146. struct btrfs_inode *inode = BTRFS_I(rac->mapping->host);
  2147. const u64 start = readahead_pos(rac);
  2148. const u64 end = start + readahead_length(rac) - 1;
  2149. struct extent_state *cached_state = NULL;
  2150. struct extent_map *em_cached = NULL;
  2151. btrfs_lock_and_flush_ordered_range(inode, start, end, &cached_state);
  2152. while ((folio = readahead_folio(rac)) != NULL)
  2153. btrfs_do_readpage(folio, &em_cached, &bio_ctrl);
  2154. unlock_extent(&inode->io_tree, start, end, &cached_state);
  2155. if (em_cached)
  2156. free_extent_map(em_cached);
  2157. submit_one_bio(&bio_ctrl);
  2158. }
  2159. /*
  2160. * basic invalidate_folio code, this waits on any locked or writeback
  2161. * ranges corresponding to the folio, and then deletes any extent state
  2162. * records from the tree
  2163. */
  2164. int extent_invalidate_folio(struct extent_io_tree *tree,
  2165. struct folio *folio, size_t offset)
  2166. {
  2167. struct extent_state *cached_state = NULL;
  2168. u64 start = folio_pos(folio);
  2169. u64 end = start + folio_size(folio) - 1;
  2170. size_t blocksize = folio_to_fs_info(folio)->sectorsize;
  2171. /* This function is only called for the btree inode */
  2172. ASSERT(tree->owner == IO_TREE_BTREE_INODE_IO);
  2173. start += ALIGN(offset, blocksize);
  2174. if (start > end)
  2175. return 0;
  2176. lock_extent(tree, start, end, &cached_state);
  2177. folio_wait_writeback(folio);
  2178. /*
  2179. * Currently for btree io tree, only EXTENT_LOCKED is utilized,
  2180. * so here we only need to unlock the extent range to free any
  2181. * existing extent state.
  2182. */
  2183. unlock_extent(tree, start, end, &cached_state);
  2184. return 0;
  2185. }
  2186. /*
  2187. * a helper for release_folio, this tests for areas of the page that
  2188. * are locked or under IO and drops the related state bits if it is safe
  2189. * to drop the page.
  2190. */
  2191. static bool try_release_extent_state(struct extent_io_tree *tree,
  2192. struct folio *folio, gfp_t mask)
  2193. {
  2194. u64 start = folio_pos(folio);
  2195. u64 end = start + PAGE_SIZE - 1;
  2196. bool ret;
  2197. if (test_range_bit_exists(tree, start, end, EXTENT_LOCKED)) {
  2198. ret = false;
  2199. } else {
  2200. u32 clear_bits = ~(EXTENT_LOCKED | EXTENT_NODATASUM |
  2201. EXTENT_DELALLOC_NEW | EXTENT_CTLBITS |
  2202. EXTENT_QGROUP_RESERVED);
  2203. int ret2;
  2204. /*
  2205. * At this point we can safely clear everything except the
  2206. * locked bit, the nodatasum bit and the delalloc new bit.
  2207. * The delalloc new bit will be cleared by ordered extent
  2208. * completion.
  2209. */
  2210. ret2 = __clear_extent_bit(tree, start, end, clear_bits, NULL, NULL);
  2211. /* if clear_extent_bit failed for enomem reasons,
  2212. * we can't allow the release to continue.
  2213. */
  2214. if (ret2 < 0)
  2215. ret = false;
  2216. else
  2217. ret = true;
  2218. }
  2219. return ret;
  2220. }
  2221. /*
  2222. * a helper for release_folio. As long as there are no locked extents
  2223. * in the range corresponding to the page, both state records and extent
  2224. * map records are removed
  2225. */
  2226. bool try_release_extent_mapping(struct folio *folio, gfp_t mask)
  2227. {
  2228. u64 start = folio_pos(folio);
  2229. u64 end = start + PAGE_SIZE - 1;
  2230. struct btrfs_inode *inode = folio_to_inode(folio);
  2231. struct extent_io_tree *io_tree = &inode->io_tree;
  2232. while (start <= end) {
  2233. const u64 cur_gen = btrfs_get_fs_generation(inode->root->fs_info);
  2234. const u64 len = end - start + 1;
  2235. struct extent_map_tree *extent_tree = &inode->extent_tree;
  2236. struct extent_map *em;
  2237. write_lock(&extent_tree->lock);
  2238. em = lookup_extent_mapping(extent_tree, start, len);
  2239. if (!em) {
  2240. write_unlock(&extent_tree->lock);
  2241. break;
  2242. }
  2243. if ((em->flags & EXTENT_FLAG_PINNED) || em->start != start) {
  2244. write_unlock(&extent_tree->lock);
  2245. free_extent_map(em);
  2246. break;
  2247. }
  2248. if (test_range_bit_exists(io_tree, em->start,
  2249. extent_map_end(em) - 1, EXTENT_LOCKED))
  2250. goto next;
  2251. /*
  2252. * If it's not in the list of modified extents, used by a fast
  2253. * fsync, we can remove it. If it's being logged we can safely
  2254. * remove it since fsync took an extra reference on the em.
  2255. */
  2256. if (list_empty(&em->list) || (em->flags & EXTENT_FLAG_LOGGING))
  2257. goto remove_em;
  2258. /*
  2259. * If it's in the list of modified extents, remove it only if
  2260. * its generation is older then the current one, in which case
  2261. * we don't need it for a fast fsync. Otherwise don't remove it,
  2262. * we could be racing with an ongoing fast fsync that could miss
  2263. * the new extent.
  2264. */
  2265. if (em->generation >= cur_gen)
  2266. goto next;
  2267. remove_em:
  2268. /*
  2269. * We only remove extent maps that are not in the list of
  2270. * modified extents or that are in the list but with a
  2271. * generation lower then the current generation, so there is no
  2272. * need to set the full fsync flag on the inode (it hurts the
  2273. * fsync performance for workloads with a data size that exceeds
  2274. * or is close to the system's memory).
  2275. */
  2276. remove_extent_mapping(inode, em);
  2277. /* Once for the inode's extent map tree. */
  2278. free_extent_map(em);
  2279. next:
  2280. start = extent_map_end(em);
  2281. write_unlock(&extent_tree->lock);
  2282. /* Once for us, for the lookup_extent_mapping() reference. */
  2283. free_extent_map(em);
  2284. if (need_resched()) {
  2285. /*
  2286. * If we need to resched but we can't block just exit
  2287. * and leave any remaining extent maps.
  2288. */
  2289. if (!gfpflags_allow_blocking(mask))
  2290. break;
  2291. cond_resched();
  2292. }
  2293. }
  2294. return try_release_extent_state(io_tree, folio, mask);
  2295. }
  2296. static void __free_extent_buffer(struct extent_buffer *eb)
  2297. {
  2298. kmem_cache_free(extent_buffer_cache, eb);
  2299. }
  2300. static int extent_buffer_under_io(const struct extent_buffer *eb)
  2301. {
  2302. return (test_bit(EXTENT_BUFFER_WRITEBACK, &eb->bflags) ||
  2303. test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
  2304. }
  2305. static bool folio_range_has_eb(struct btrfs_fs_info *fs_info, struct folio *folio)
  2306. {
  2307. struct btrfs_subpage *subpage;
  2308. lockdep_assert_held(&folio->mapping->i_private_lock);
  2309. if (folio_test_private(folio)) {
  2310. subpage = folio_get_private(folio);
  2311. if (atomic_read(&subpage->eb_refs))
  2312. return true;
  2313. }
  2314. return false;
  2315. }
  2316. static void detach_extent_buffer_folio(const struct extent_buffer *eb, struct folio *folio)
  2317. {
  2318. struct btrfs_fs_info *fs_info = eb->fs_info;
  2319. const bool mapped = !test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
  2320. /*
  2321. * For mapped eb, we're going to change the folio private, which should
  2322. * be done under the i_private_lock.
  2323. */
  2324. if (mapped)
  2325. spin_lock(&folio->mapping->i_private_lock);
  2326. if (!folio_test_private(folio)) {
  2327. if (mapped)
  2328. spin_unlock(&folio->mapping->i_private_lock);
  2329. return;
  2330. }
  2331. if (fs_info->nodesize >= PAGE_SIZE) {
  2332. /*
  2333. * We do this since we'll remove the pages after we've
  2334. * removed the eb from the radix tree, so we could race
  2335. * and have this page now attached to the new eb. So
  2336. * only clear folio if it's still connected to
  2337. * this eb.
  2338. */
  2339. if (folio_test_private(folio) && folio_get_private(folio) == eb) {
  2340. BUG_ON(test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags));
  2341. BUG_ON(folio_test_dirty(folio));
  2342. BUG_ON(folio_test_writeback(folio));
  2343. /* We need to make sure we haven't be attached to a new eb. */
  2344. folio_detach_private(folio);
  2345. }
  2346. if (mapped)
  2347. spin_unlock(&folio->mapping->i_private_lock);
  2348. return;
  2349. }
  2350. /*
  2351. * For subpage, we can have dummy eb with folio private attached. In
  2352. * this case, we can directly detach the private as such folio is only
  2353. * attached to one dummy eb, no sharing.
  2354. */
  2355. if (!mapped) {
  2356. btrfs_detach_subpage(fs_info, folio);
  2357. return;
  2358. }
  2359. btrfs_folio_dec_eb_refs(fs_info, folio);
  2360. /*
  2361. * We can only detach the folio private if there are no other ebs in the
  2362. * page range and no unfinished IO.
  2363. */
  2364. if (!folio_range_has_eb(fs_info, folio))
  2365. btrfs_detach_subpage(fs_info, folio);
  2366. spin_unlock(&folio->mapping->i_private_lock);
  2367. }
  2368. /* Release all pages attached to the extent buffer */
  2369. static void btrfs_release_extent_buffer_pages(const struct extent_buffer *eb)
  2370. {
  2371. ASSERT(!extent_buffer_under_io(eb));
  2372. for (int i = 0; i < INLINE_EXTENT_BUFFER_PAGES; i++) {
  2373. struct folio *folio = eb->folios[i];
  2374. if (!folio)
  2375. continue;
  2376. detach_extent_buffer_folio(eb, folio);
  2377. /* One for when we allocated the folio. */
  2378. folio_put(folio);
  2379. }
  2380. }
  2381. /*
  2382. * Helper for releasing the extent buffer.
  2383. */
  2384. static inline void btrfs_release_extent_buffer(struct extent_buffer *eb)
  2385. {
  2386. btrfs_release_extent_buffer_pages(eb);
  2387. btrfs_leak_debug_del_eb(eb);
  2388. __free_extent_buffer(eb);
  2389. }
  2390. static struct extent_buffer *
  2391. __alloc_extent_buffer(struct btrfs_fs_info *fs_info, u64 start,
  2392. unsigned long len)
  2393. {
  2394. struct extent_buffer *eb = NULL;
  2395. eb = kmem_cache_zalloc(extent_buffer_cache, GFP_NOFS|__GFP_NOFAIL);
  2396. eb->start = start;
  2397. eb->len = len;
  2398. eb->fs_info = fs_info;
  2399. init_rwsem(&eb->lock);
  2400. btrfs_leak_debug_add_eb(eb);
  2401. spin_lock_init(&eb->refs_lock);
  2402. atomic_set(&eb->refs, 1);
  2403. ASSERT(len <= BTRFS_MAX_METADATA_BLOCKSIZE);
  2404. return eb;
  2405. }
  2406. struct extent_buffer *btrfs_clone_extent_buffer(const struct extent_buffer *src)
  2407. {
  2408. struct extent_buffer *new;
  2409. int num_folios = num_extent_folios(src);
  2410. int ret;
  2411. new = __alloc_extent_buffer(src->fs_info, src->start, src->len);
  2412. if (new == NULL)
  2413. return NULL;
  2414. /*
  2415. * Set UNMAPPED before calling btrfs_release_extent_buffer(), as
  2416. * btrfs_release_extent_buffer() have different behavior for
  2417. * UNMAPPED subpage extent buffer.
  2418. */
  2419. set_bit(EXTENT_BUFFER_UNMAPPED, &new->bflags);
  2420. ret = alloc_eb_folio_array(new, false);
  2421. if (ret) {
  2422. btrfs_release_extent_buffer(new);
  2423. return NULL;
  2424. }
  2425. for (int i = 0; i < num_folios; i++) {
  2426. struct folio *folio = new->folios[i];
  2427. ret = attach_extent_buffer_folio(new, folio, NULL);
  2428. if (ret < 0) {
  2429. btrfs_release_extent_buffer(new);
  2430. return NULL;
  2431. }
  2432. WARN_ON(folio_test_dirty(folio));
  2433. }
  2434. copy_extent_buffer_full(new, src);
  2435. set_extent_buffer_uptodate(new);
  2436. return new;
  2437. }
  2438. struct extent_buffer *__alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
  2439. u64 start, unsigned long len)
  2440. {
  2441. struct extent_buffer *eb;
  2442. int num_folios = 0;
  2443. int ret;
  2444. eb = __alloc_extent_buffer(fs_info, start, len);
  2445. if (!eb)
  2446. return NULL;
  2447. ret = alloc_eb_folio_array(eb, false);
  2448. if (ret)
  2449. goto err;
  2450. num_folios = num_extent_folios(eb);
  2451. for (int i = 0; i < num_folios; i++) {
  2452. ret = attach_extent_buffer_folio(eb, eb->folios[i], NULL);
  2453. if (ret < 0)
  2454. goto err;
  2455. }
  2456. set_extent_buffer_uptodate(eb);
  2457. btrfs_set_header_nritems(eb, 0);
  2458. set_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
  2459. return eb;
  2460. err:
  2461. for (int i = 0; i < num_folios; i++) {
  2462. if (eb->folios[i]) {
  2463. detach_extent_buffer_folio(eb, eb->folios[i]);
  2464. folio_put(eb->folios[i]);
  2465. }
  2466. }
  2467. __free_extent_buffer(eb);
  2468. return NULL;
  2469. }
  2470. struct extent_buffer *alloc_dummy_extent_buffer(struct btrfs_fs_info *fs_info,
  2471. u64 start)
  2472. {
  2473. return __alloc_dummy_extent_buffer(fs_info, start, fs_info->nodesize);
  2474. }
  2475. static void check_buffer_tree_ref(struct extent_buffer *eb)
  2476. {
  2477. int refs;
  2478. /*
  2479. * The TREE_REF bit is first set when the extent_buffer is added
  2480. * to the radix tree. It is also reset, if unset, when a new reference
  2481. * is created by find_extent_buffer.
  2482. *
  2483. * It is only cleared in two cases: freeing the last non-tree
  2484. * reference to the extent_buffer when its STALE bit is set or
  2485. * calling release_folio when the tree reference is the only reference.
  2486. *
  2487. * In both cases, care is taken to ensure that the extent_buffer's
  2488. * pages are not under io. However, release_folio can be concurrently
  2489. * called with creating new references, which is prone to race
  2490. * conditions between the calls to check_buffer_tree_ref in those
  2491. * codepaths and clearing TREE_REF in try_release_extent_buffer.
  2492. *
  2493. * The actual lifetime of the extent_buffer in the radix tree is
  2494. * adequately protected by the refcount, but the TREE_REF bit and
  2495. * its corresponding reference are not. To protect against this
  2496. * class of races, we call check_buffer_tree_ref from the codepaths
  2497. * which trigger io. Note that once io is initiated, TREE_REF can no
  2498. * longer be cleared, so that is the moment at which any such race is
  2499. * best fixed.
  2500. */
  2501. refs = atomic_read(&eb->refs);
  2502. if (refs >= 2 && test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
  2503. return;
  2504. spin_lock(&eb->refs_lock);
  2505. if (!test_and_set_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
  2506. atomic_inc(&eb->refs);
  2507. spin_unlock(&eb->refs_lock);
  2508. }
  2509. static void mark_extent_buffer_accessed(struct extent_buffer *eb)
  2510. {
  2511. int num_folios= num_extent_folios(eb);
  2512. check_buffer_tree_ref(eb);
  2513. for (int i = 0; i < num_folios; i++)
  2514. folio_mark_accessed(eb->folios[i]);
  2515. }
  2516. struct extent_buffer *find_extent_buffer(struct btrfs_fs_info *fs_info,
  2517. u64 start)
  2518. {
  2519. struct extent_buffer *eb;
  2520. eb = find_extent_buffer_nolock(fs_info, start);
  2521. if (!eb)
  2522. return NULL;
  2523. /*
  2524. * Lock our eb's refs_lock to avoid races with free_extent_buffer().
  2525. * When we get our eb it might be flagged with EXTENT_BUFFER_STALE and
  2526. * another task running free_extent_buffer() might have seen that flag
  2527. * set, eb->refs == 2, that the buffer isn't under IO (dirty and
  2528. * writeback flags not set) and it's still in the tree (flag
  2529. * EXTENT_BUFFER_TREE_REF set), therefore being in the process of
  2530. * decrementing the extent buffer's reference count twice. So here we
  2531. * could race and increment the eb's reference count, clear its stale
  2532. * flag, mark it as dirty and drop our reference before the other task
  2533. * finishes executing free_extent_buffer, which would later result in
  2534. * an attempt to free an extent buffer that is dirty.
  2535. */
  2536. if (test_bit(EXTENT_BUFFER_STALE, &eb->bflags)) {
  2537. spin_lock(&eb->refs_lock);
  2538. spin_unlock(&eb->refs_lock);
  2539. }
  2540. mark_extent_buffer_accessed(eb);
  2541. return eb;
  2542. }
  2543. struct extent_buffer *alloc_test_extent_buffer(struct btrfs_fs_info *fs_info,
  2544. u64 start)
  2545. {
  2546. #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
  2547. struct extent_buffer *eb, *exists = NULL;
  2548. int ret;
  2549. eb = find_extent_buffer(fs_info, start);
  2550. if (eb)
  2551. return eb;
  2552. eb = alloc_dummy_extent_buffer(fs_info, start);
  2553. if (!eb)
  2554. return ERR_PTR(-ENOMEM);
  2555. eb->fs_info = fs_info;
  2556. again:
  2557. ret = radix_tree_preload(GFP_NOFS);
  2558. if (ret) {
  2559. exists = ERR_PTR(ret);
  2560. goto free_eb;
  2561. }
  2562. spin_lock(&fs_info->buffer_lock);
  2563. ret = radix_tree_insert(&fs_info->buffer_radix,
  2564. start >> fs_info->sectorsize_bits, eb);
  2565. spin_unlock(&fs_info->buffer_lock);
  2566. radix_tree_preload_end();
  2567. if (ret == -EEXIST) {
  2568. exists = find_extent_buffer(fs_info, start);
  2569. if (exists)
  2570. goto free_eb;
  2571. else
  2572. goto again;
  2573. }
  2574. check_buffer_tree_ref(eb);
  2575. set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
  2576. return eb;
  2577. free_eb:
  2578. btrfs_release_extent_buffer(eb);
  2579. return exists;
  2580. #else
  2581. /* Stub to avoid linker error when compiled with optimizations turned off. */
  2582. return NULL;
  2583. #endif
  2584. }
  2585. static struct extent_buffer *grab_extent_buffer(
  2586. struct btrfs_fs_info *fs_info, struct page *page)
  2587. {
  2588. struct folio *folio = page_folio(page);
  2589. struct extent_buffer *exists;
  2590. lockdep_assert_held(&page->mapping->i_private_lock);
  2591. /*
  2592. * For subpage case, we completely rely on radix tree to ensure we
  2593. * don't try to insert two ebs for the same bytenr. So here we always
  2594. * return NULL and just continue.
  2595. */
  2596. if (fs_info->nodesize < PAGE_SIZE)
  2597. return NULL;
  2598. /* Page not yet attached to an extent buffer */
  2599. if (!folio_test_private(folio))
  2600. return NULL;
  2601. /*
  2602. * We could have already allocated an eb for this page and attached one
  2603. * so lets see if we can get a ref on the existing eb, and if we can we
  2604. * know it's good and we can just return that one, else we know we can
  2605. * just overwrite folio private.
  2606. */
  2607. exists = folio_get_private(folio);
  2608. if (atomic_inc_not_zero(&exists->refs))
  2609. return exists;
  2610. WARN_ON(PageDirty(page));
  2611. folio_detach_private(folio);
  2612. return NULL;
  2613. }
  2614. static int check_eb_alignment(struct btrfs_fs_info *fs_info, u64 start)
  2615. {
  2616. if (!IS_ALIGNED(start, fs_info->sectorsize)) {
  2617. btrfs_err(fs_info, "bad tree block start %llu", start);
  2618. return -EINVAL;
  2619. }
  2620. if (fs_info->nodesize < PAGE_SIZE &&
  2621. offset_in_page(start) + fs_info->nodesize > PAGE_SIZE) {
  2622. btrfs_err(fs_info,
  2623. "tree block crosses page boundary, start %llu nodesize %u",
  2624. start, fs_info->nodesize);
  2625. return -EINVAL;
  2626. }
  2627. if (fs_info->nodesize >= PAGE_SIZE &&
  2628. !PAGE_ALIGNED(start)) {
  2629. btrfs_err(fs_info,
  2630. "tree block is not page aligned, start %llu nodesize %u",
  2631. start, fs_info->nodesize);
  2632. return -EINVAL;
  2633. }
  2634. if (!IS_ALIGNED(start, fs_info->nodesize) &&
  2635. !test_and_set_bit(BTRFS_FS_UNALIGNED_TREE_BLOCK, &fs_info->flags)) {
  2636. btrfs_warn(fs_info,
  2637. "tree block not nodesize aligned, start %llu nodesize %u, can be resolved by a full metadata balance",
  2638. start, fs_info->nodesize);
  2639. }
  2640. return 0;
  2641. }
  2642. /*
  2643. * Return 0 if eb->folios[i] is attached to btree inode successfully.
  2644. * Return >0 if there is already another extent buffer for the range,
  2645. * and @found_eb_ret would be updated.
  2646. * Return -EAGAIN if the filemap has an existing folio but with different size
  2647. * than @eb.
  2648. * The caller needs to free the existing folios and retry using the same order.
  2649. */
  2650. static int attach_eb_folio_to_filemap(struct extent_buffer *eb, int i,
  2651. struct btrfs_subpage *prealloc,
  2652. struct extent_buffer **found_eb_ret)
  2653. {
  2654. struct btrfs_fs_info *fs_info = eb->fs_info;
  2655. struct address_space *mapping = fs_info->btree_inode->i_mapping;
  2656. const unsigned long index = eb->start >> PAGE_SHIFT;
  2657. struct folio *existing_folio = NULL;
  2658. int ret;
  2659. ASSERT(found_eb_ret);
  2660. /* Caller should ensure the folio exists. */
  2661. ASSERT(eb->folios[i]);
  2662. retry:
  2663. ret = filemap_add_folio(mapping, eb->folios[i], index + i,
  2664. GFP_NOFS | __GFP_NOFAIL);
  2665. if (!ret)
  2666. goto finish;
  2667. existing_folio = filemap_lock_folio(mapping, index + i);
  2668. /* The page cache only exists for a very short time, just retry. */
  2669. if (IS_ERR(existing_folio)) {
  2670. existing_folio = NULL;
  2671. goto retry;
  2672. }
  2673. /* For now, we should only have single-page folios for btree inode. */
  2674. ASSERT(folio_nr_pages(existing_folio) == 1);
  2675. if (folio_size(existing_folio) != eb->folio_size) {
  2676. folio_unlock(existing_folio);
  2677. folio_put(existing_folio);
  2678. return -EAGAIN;
  2679. }
  2680. finish:
  2681. spin_lock(&mapping->i_private_lock);
  2682. if (existing_folio && fs_info->nodesize < PAGE_SIZE) {
  2683. /* We're going to reuse the existing page, can drop our folio now. */
  2684. __free_page(folio_page(eb->folios[i], 0));
  2685. eb->folios[i] = existing_folio;
  2686. } else if (existing_folio) {
  2687. struct extent_buffer *existing_eb;
  2688. existing_eb = grab_extent_buffer(fs_info,
  2689. folio_page(existing_folio, 0));
  2690. if (existing_eb) {
  2691. /* The extent buffer still exists, we can use it directly. */
  2692. *found_eb_ret = existing_eb;
  2693. spin_unlock(&mapping->i_private_lock);
  2694. folio_unlock(existing_folio);
  2695. folio_put(existing_folio);
  2696. return 1;
  2697. }
  2698. /* The extent buffer no longer exists, we can reuse the folio. */
  2699. __free_page(folio_page(eb->folios[i], 0));
  2700. eb->folios[i] = existing_folio;
  2701. }
  2702. eb->folio_size = folio_size(eb->folios[i]);
  2703. eb->folio_shift = folio_shift(eb->folios[i]);
  2704. /* Should not fail, as we have preallocated the memory. */
  2705. ret = attach_extent_buffer_folio(eb, eb->folios[i], prealloc);
  2706. ASSERT(!ret);
  2707. /*
  2708. * To inform we have an extra eb under allocation, so that
  2709. * detach_extent_buffer_page() won't release the folio private when the
  2710. * eb hasn't been inserted into radix tree yet.
  2711. *
  2712. * The ref will be decreased when the eb releases the page, in
  2713. * detach_extent_buffer_page(). Thus needs no special handling in the
  2714. * error path.
  2715. */
  2716. btrfs_folio_inc_eb_refs(fs_info, eb->folios[i]);
  2717. spin_unlock(&mapping->i_private_lock);
  2718. return 0;
  2719. }
  2720. struct extent_buffer *alloc_extent_buffer(struct btrfs_fs_info *fs_info,
  2721. u64 start, u64 owner_root, int level)
  2722. {
  2723. unsigned long len = fs_info->nodesize;
  2724. int num_folios;
  2725. int attached = 0;
  2726. struct extent_buffer *eb;
  2727. struct extent_buffer *existing_eb = NULL;
  2728. struct btrfs_subpage *prealloc = NULL;
  2729. u64 lockdep_owner = owner_root;
  2730. bool page_contig = true;
  2731. int uptodate = 1;
  2732. int ret;
  2733. if (check_eb_alignment(fs_info, start))
  2734. return ERR_PTR(-EINVAL);
  2735. #if BITS_PER_LONG == 32
  2736. if (start >= MAX_LFS_FILESIZE) {
  2737. btrfs_err_rl(fs_info,
  2738. "extent buffer %llu is beyond 32bit page cache limit", start);
  2739. btrfs_err_32bit_limit(fs_info);
  2740. return ERR_PTR(-EOVERFLOW);
  2741. }
  2742. if (start >= BTRFS_32BIT_EARLY_WARN_THRESHOLD)
  2743. btrfs_warn_32bit_limit(fs_info);
  2744. #endif
  2745. eb = find_extent_buffer(fs_info, start);
  2746. if (eb)
  2747. return eb;
  2748. eb = __alloc_extent_buffer(fs_info, start, len);
  2749. if (!eb)
  2750. return ERR_PTR(-ENOMEM);
  2751. /*
  2752. * The reloc trees are just snapshots, so we need them to appear to be
  2753. * just like any other fs tree WRT lockdep.
  2754. */
  2755. if (lockdep_owner == BTRFS_TREE_RELOC_OBJECTID)
  2756. lockdep_owner = BTRFS_FS_TREE_OBJECTID;
  2757. btrfs_set_buffer_lockdep_class(lockdep_owner, eb, level);
  2758. /*
  2759. * Preallocate folio private for subpage case, so that we won't
  2760. * allocate memory with i_private_lock nor page lock hold.
  2761. *
  2762. * The memory will be freed by attach_extent_buffer_page() or freed
  2763. * manually if we exit earlier.
  2764. */
  2765. if (fs_info->nodesize < PAGE_SIZE) {
  2766. prealloc = btrfs_alloc_subpage(fs_info, BTRFS_SUBPAGE_METADATA);
  2767. if (IS_ERR(prealloc)) {
  2768. ret = PTR_ERR(prealloc);
  2769. goto out;
  2770. }
  2771. }
  2772. reallocate:
  2773. /* Allocate all pages first. */
  2774. ret = alloc_eb_folio_array(eb, true);
  2775. if (ret < 0) {
  2776. btrfs_free_subpage(prealloc);
  2777. goto out;
  2778. }
  2779. num_folios = num_extent_folios(eb);
  2780. /* Attach all pages to the filemap. */
  2781. for (int i = 0; i < num_folios; i++) {
  2782. struct folio *folio;
  2783. ret = attach_eb_folio_to_filemap(eb, i, prealloc, &existing_eb);
  2784. if (ret > 0) {
  2785. ASSERT(existing_eb);
  2786. goto out;
  2787. }
  2788. /*
  2789. * TODO: Special handling for a corner case where the order of
  2790. * folios mismatch between the new eb and filemap.
  2791. *
  2792. * This happens when:
  2793. *
  2794. * - the new eb is using higher order folio
  2795. *
  2796. * - the filemap is still using 0-order folios for the range
  2797. * This can happen at the previous eb allocation, and we don't
  2798. * have higher order folio for the call.
  2799. *
  2800. * - the existing eb has already been freed
  2801. *
  2802. * In this case, we have to free the existing folios first, and
  2803. * re-allocate using the same order.
  2804. * Thankfully this is not going to happen yet, as we're still
  2805. * using 0-order folios.
  2806. */
  2807. if (unlikely(ret == -EAGAIN)) {
  2808. ASSERT(0);
  2809. goto reallocate;
  2810. }
  2811. attached++;
  2812. /*
  2813. * Only after attach_eb_folio_to_filemap(), eb->folios[] is
  2814. * reliable, as we may choose to reuse the existing page cache
  2815. * and free the allocated page.
  2816. */
  2817. folio = eb->folios[i];
  2818. WARN_ON(btrfs_folio_test_dirty(fs_info, folio, eb->start, eb->len));
  2819. /*
  2820. * Check if the current page is physically contiguous with previous eb
  2821. * page.
  2822. * At this stage, either we allocated a large folio, thus @i
  2823. * would only be 0, or we fall back to per-page allocation.
  2824. */
  2825. if (i && folio_page(eb->folios[i - 1], 0) + 1 != folio_page(folio, 0))
  2826. page_contig = false;
  2827. if (!btrfs_folio_test_uptodate(fs_info, folio, eb->start, eb->len))
  2828. uptodate = 0;
  2829. /*
  2830. * We can't unlock the pages just yet since the extent buffer
  2831. * hasn't been properly inserted in the radix tree, this
  2832. * opens a race with btree_release_folio which can free a page
  2833. * while we are still filling in all pages for the buffer and
  2834. * we could crash.
  2835. */
  2836. }
  2837. if (uptodate)
  2838. set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
  2839. /* All pages are physically contiguous, can skip cross page handling. */
  2840. if (page_contig)
  2841. eb->addr = folio_address(eb->folios[0]) + offset_in_page(eb->start);
  2842. again:
  2843. ret = radix_tree_preload(GFP_NOFS);
  2844. if (ret)
  2845. goto out;
  2846. spin_lock(&fs_info->buffer_lock);
  2847. ret = radix_tree_insert(&fs_info->buffer_radix,
  2848. start >> fs_info->sectorsize_bits, eb);
  2849. spin_unlock(&fs_info->buffer_lock);
  2850. radix_tree_preload_end();
  2851. if (ret == -EEXIST) {
  2852. ret = 0;
  2853. existing_eb = find_extent_buffer(fs_info, start);
  2854. if (existing_eb)
  2855. goto out;
  2856. else
  2857. goto again;
  2858. }
  2859. /* add one reference for the tree */
  2860. check_buffer_tree_ref(eb);
  2861. set_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags);
  2862. /*
  2863. * Now it's safe to unlock the pages because any calls to
  2864. * btree_release_folio will correctly detect that a page belongs to a
  2865. * live buffer and won't free them prematurely.
  2866. */
  2867. for (int i = 0; i < num_folios; i++)
  2868. unlock_page(folio_page(eb->folios[i], 0));
  2869. return eb;
  2870. out:
  2871. WARN_ON(!atomic_dec_and_test(&eb->refs));
  2872. /*
  2873. * Any attached folios need to be detached before we unlock them. This
  2874. * is because when we're inserting our new folios into the mapping, and
  2875. * then attaching our eb to that folio. If we fail to insert our folio
  2876. * we'll lookup the folio for that index, and grab that EB. We do not
  2877. * want that to grab this eb, as we're getting ready to free it. So we
  2878. * have to detach it first and then unlock it.
  2879. *
  2880. * We have to drop our reference and NULL it out here because in the
  2881. * subpage case detaching does a btrfs_folio_dec_eb_refs() for our eb.
  2882. * Below when we call btrfs_release_extent_buffer() we will call
  2883. * detach_extent_buffer_folio() on our remaining pages in the !subpage
  2884. * case. If we left eb->folios[i] populated in the subpage case we'd
  2885. * double put our reference and be super sad.
  2886. */
  2887. for (int i = 0; i < attached; i++) {
  2888. ASSERT(eb->folios[i]);
  2889. detach_extent_buffer_folio(eb, eb->folios[i]);
  2890. unlock_page(folio_page(eb->folios[i], 0));
  2891. folio_put(eb->folios[i]);
  2892. eb->folios[i] = NULL;
  2893. }
  2894. /*
  2895. * Now all pages of that extent buffer is unmapped, set UNMAPPED flag,
  2896. * so it can be cleaned up without utlizing page->mapping.
  2897. */
  2898. set_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
  2899. btrfs_release_extent_buffer(eb);
  2900. if (ret < 0)
  2901. return ERR_PTR(ret);
  2902. ASSERT(existing_eb);
  2903. return existing_eb;
  2904. }
  2905. static inline void btrfs_release_extent_buffer_rcu(struct rcu_head *head)
  2906. {
  2907. struct extent_buffer *eb =
  2908. container_of(head, struct extent_buffer, rcu_head);
  2909. __free_extent_buffer(eb);
  2910. }
  2911. static int release_extent_buffer(struct extent_buffer *eb)
  2912. __releases(&eb->refs_lock)
  2913. {
  2914. lockdep_assert_held(&eb->refs_lock);
  2915. WARN_ON(atomic_read(&eb->refs) == 0);
  2916. if (atomic_dec_and_test(&eb->refs)) {
  2917. if (test_and_clear_bit(EXTENT_BUFFER_IN_TREE, &eb->bflags)) {
  2918. struct btrfs_fs_info *fs_info = eb->fs_info;
  2919. spin_unlock(&eb->refs_lock);
  2920. spin_lock(&fs_info->buffer_lock);
  2921. radix_tree_delete(&fs_info->buffer_radix,
  2922. eb->start >> fs_info->sectorsize_bits);
  2923. spin_unlock(&fs_info->buffer_lock);
  2924. } else {
  2925. spin_unlock(&eb->refs_lock);
  2926. }
  2927. btrfs_leak_debug_del_eb(eb);
  2928. /* Should be safe to release our pages at this point */
  2929. btrfs_release_extent_buffer_pages(eb);
  2930. #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
  2931. if (unlikely(test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags))) {
  2932. __free_extent_buffer(eb);
  2933. return 1;
  2934. }
  2935. #endif
  2936. call_rcu(&eb->rcu_head, btrfs_release_extent_buffer_rcu);
  2937. return 1;
  2938. }
  2939. spin_unlock(&eb->refs_lock);
  2940. return 0;
  2941. }
  2942. void free_extent_buffer(struct extent_buffer *eb)
  2943. {
  2944. int refs;
  2945. if (!eb)
  2946. return;
  2947. refs = atomic_read(&eb->refs);
  2948. while (1) {
  2949. if ((!test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) && refs <= 3)
  2950. || (test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags) &&
  2951. refs == 1))
  2952. break;
  2953. if (atomic_try_cmpxchg(&eb->refs, &refs, refs - 1))
  2954. return;
  2955. }
  2956. spin_lock(&eb->refs_lock);
  2957. if (atomic_read(&eb->refs) == 2 &&
  2958. test_bit(EXTENT_BUFFER_STALE, &eb->bflags) &&
  2959. !extent_buffer_under_io(eb) &&
  2960. test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
  2961. atomic_dec(&eb->refs);
  2962. /*
  2963. * I know this is terrible, but it's temporary until we stop tracking
  2964. * the uptodate bits and such for the extent buffers.
  2965. */
  2966. release_extent_buffer(eb);
  2967. }
  2968. void free_extent_buffer_stale(struct extent_buffer *eb)
  2969. {
  2970. if (!eb)
  2971. return;
  2972. spin_lock(&eb->refs_lock);
  2973. set_bit(EXTENT_BUFFER_STALE, &eb->bflags);
  2974. if (atomic_read(&eb->refs) == 2 && !extent_buffer_under_io(eb) &&
  2975. test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags))
  2976. atomic_dec(&eb->refs);
  2977. release_extent_buffer(eb);
  2978. }
  2979. static void btree_clear_folio_dirty(struct folio *folio)
  2980. {
  2981. ASSERT(folio_test_dirty(folio));
  2982. ASSERT(folio_test_locked(folio));
  2983. folio_clear_dirty_for_io(folio);
  2984. xa_lock_irq(&folio->mapping->i_pages);
  2985. if (!folio_test_dirty(folio))
  2986. __xa_clear_mark(&folio->mapping->i_pages,
  2987. folio_index(folio), PAGECACHE_TAG_DIRTY);
  2988. xa_unlock_irq(&folio->mapping->i_pages);
  2989. }
  2990. static void clear_subpage_extent_buffer_dirty(const struct extent_buffer *eb)
  2991. {
  2992. struct btrfs_fs_info *fs_info = eb->fs_info;
  2993. struct folio *folio = eb->folios[0];
  2994. bool last;
  2995. /* btree_clear_folio_dirty() needs page locked. */
  2996. folio_lock(folio);
  2997. last = btrfs_subpage_clear_and_test_dirty(fs_info, folio, eb->start, eb->len);
  2998. if (last)
  2999. btree_clear_folio_dirty(folio);
  3000. folio_unlock(folio);
  3001. WARN_ON(atomic_read(&eb->refs) == 0);
  3002. }
  3003. void btrfs_clear_buffer_dirty(struct btrfs_trans_handle *trans,
  3004. struct extent_buffer *eb)
  3005. {
  3006. struct btrfs_fs_info *fs_info = eb->fs_info;
  3007. int num_folios;
  3008. btrfs_assert_tree_write_locked(eb);
  3009. if (trans && btrfs_header_generation(eb) != trans->transid)
  3010. return;
  3011. /*
  3012. * Instead of clearing the dirty flag off of the buffer, mark it as
  3013. * EXTENT_BUFFER_ZONED_ZEROOUT. This allows us to preserve
  3014. * write-ordering in zoned mode, without the need to later re-dirty
  3015. * the extent_buffer.
  3016. *
  3017. * The actual zeroout of the buffer will happen later in
  3018. * btree_csum_one_bio.
  3019. */
  3020. if (btrfs_is_zoned(fs_info) && test_bit(EXTENT_BUFFER_DIRTY, &eb->bflags)) {
  3021. set_bit(EXTENT_BUFFER_ZONED_ZEROOUT, &eb->bflags);
  3022. return;
  3023. }
  3024. if (!test_and_clear_bit(EXTENT_BUFFER_DIRTY, &eb->bflags))
  3025. return;
  3026. percpu_counter_add_batch(&fs_info->dirty_metadata_bytes, -eb->len,
  3027. fs_info->dirty_metadata_batch);
  3028. if (eb->fs_info->nodesize < PAGE_SIZE)
  3029. return clear_subpage_extent_buffer_dirty(eb);
  3030. num_folios = num_extent_folios(eb);
  3031. for (int i = 0; i < num_folios; i++) {
  3032. struct folio *folio = eb->folios[i];
  3033. if (!folio_test_dirty(folio))
  3034. continue;
  3035. folio_lock(folio);
  3036. btree_clear_folio_dirty(folio);
  3037. folio_unlock(folio);
  3038. }
  3039. WARN_ON(atomic_read(&eb->refs) == 0);
  3040. }
  3041. void set_extent_buffer_dirty(struct extent_buffer *eb)
  3042. {
  3043. int num_folios;
  3044. bool was_dirty;
  3045. check_buffer_tree_ref(eb);
  3046. was_dirty = test_and_set_bit(EXTENT_BUFFER_DIRTY, &eb->bflags);
  3047. num_folios = num_extent_folios(eb);
  3048. WARN_ON(atomic_read(&eb->refs) == 0);
  3049. WARN_ON(!test_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags));
  3050. WARN_ON(test_bit(EXTENT_BUFFER_ZONED_ZEROOUT, &eb->bflags));
  3051. if (!was_dirty) {
  3052. bool subpage = eb->fs_info->nodesize < PAGE_SIZE;
  3053. /*
  3054. * For subpage case, we can have other extent buffers in the
  3055. * same page, and in clear_subpage_extent_buffer_dirty() we
  3056. * have to clear page dirty without subpage lock held.
  3057. * This can cause race where our page gets dirty cleared after
  3058. * we just set it.
  3059. *
  3060. * Thankfully, clear_subpage_extent_buffer_dirty() has locked
  3061. * its page for other reasons, we can use page lock to prevent
  3062. * the above race.
  3063. */
  3064. if (subpage)
  3065. lock_page(folio_page(eb->folios[0], 0));
  3066. for (int i = 0; i < num_folios; i++)
  3067. btrfs_folio_set_dirty(eb->fs_info, eb->folios[i],
  3068. eb->start, eb->len);
  3069. if (subpage)
  3070. unlock_page(folio_page(eb->folios[0], 0));
  3071. percpu_counter_add_batch(&eb->fs_info->dirty_metadata_bytes,
  3072. eb->len,
  3073. eb->fs_info->dirty_metadata_batch);
  3074. }
  3075. #ifdef CONFIG_BTRFS_DEBUG
  3076. for (int i = 0; i < num_folios; i++)
  3077. ASSERT(folio_test_dirty(eb->folios[i]));
  3078. #endif
  3079. }
  3080. void clear_extent_buffer_uptodate(struct extent_buffer *eb)
  3081. {
  3082. struct btrfs_fs_info *fs_info = eb->fs_info;
  3083. int num_folios = num_extent_folios(eb);
  3084. clear_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
  3085. for (int i = 0; i < num_folios; i++) {
  3086. struct folio *folio = eb->folios[i];
  3087. if (!folio)
  3088. continue;
  3089. /*
  3090. * This is special handling for metadata subpage, as regular
  3091. * btrfs_is_subpage() can not handle cloned/dummy metadata.
  3092. */
  3093. if (fs_info->nodesize >= PAGE_SIZE)
  3094. folio_clear_uptodate(folio);
  3095. else
  3096. btrfs_subpage_clear_uptodate(fs_info, folio,
  3097. eb->start, eb->len);
  3098. }
  3099. }
  3100. void set_extent_buffer_uptodate(struct extent_buffer *eb)
  3101. {
  3102. struct btrfs_fs_info *fs_info = eb->fs_info;
  3103. int num_folios = num_extent_folios(eb);
  3104. set_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags);
  3105. for (int i = 0; i < num_folios; i++) {
  3106. struct folio *folio = eb->folios[i];
  3107. /*
  3108. * This is special handling for metadata subpage, as regular
  3109. * btrfs_is_subpage() can not handle cloned/dummy metadata.
  3110. */
  3111. if (fs_info->nodesize >= PAGE_SIZE)
  3112. folio_mark_uptodate(folio);
  3113. else
  3114. btrfs_subpage_set_uptodate(fs_info, folio,
  3115. eb->start, eb->len);
  3116. }
  3117. }
  3118. static void clear_extent_buffer_reading(struct extent_buffer *eb)
  3119. {
  3120. clear_bit(EXTENT_BUFFER_READING, &eb->bflags);
  3121. smp_mb__after_atomic();
  3122. wake_up_bit(&eb->bflags, EXTENT_BUFFER_READING);
  3123. }
  3124. static void end_bbio_meta_read(struct btrfs_bio *bbio)
  3125. {
  3126. struct extent_buffer *eb = bbio->private;
  3127. struct btrfs_fs_info *fs_info = eb->fs_info;
  3128. bool uptodate = !bbio->bio.bi_status;
  3129. struct folio_iter fi;
  3130. u32 bio_offset = 0;
  3131. /*
  3132. * If the extent buffer is marked UPTODATE before the read operation
  3133. * completes, other calls to read_extent_buffer_pages() will return
  3134. * early without waiting for the read to finish, causing data races.
  3135. */
  3136. WARN_ON(test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags));
  3137. eb->read_mirror = bbio->mirror_num;
  3138. if (uptodate &&
  3139. btrfs_validate_extent_buffer(eb, &bbio->parent_check) < 0)
  3140. uptodate = false;
  3141. if (uptodate) {
  3142. set_extent_buffer_uptodate(eb);
  3143. } else {
  3144. clear_extent_buffer_uptodate(eb);
  3145. set_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
  3146. }
  3147. bio_for_each_folio_all(fi, &bbio->bio) {
  3148. struct folio *folio = fi.folio;
  3149. u64 start = eb->start + bio_offset;
  3150. u32 len = fi.length;
  3151. if (uptodate)
  3152. btrfs_folio_set_uptodate(fs_info, folio, start, len);
  3153. else
  3154. btrfs_folio_clear_uptodate(fs_info, folio, start, len);
  3155. bio_offset += len;
  3156. }
  3157. clear_extent_buffer_reading(eb);
  3158. free_extent_buffer(eb);
  3159. bio_put(&bbio->bio);
  3160. }
  3161. int read_extent_buffer_pages(struct extent_buffer *eb, int wait, int mirror_num,
  3162. const struct btrfs_tree_parent_check *check)
  3163. {
  3164. struct btrfs_bio *bbio;
  3165. bool ret;
  3166. if (test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
  3167. return 0;
  3168. /*
  3169. * We could have had EXTENT_BUFFER_UPTODATE cleared by the write
  3170. * operation, which could potentially still be in flight. In this case
  3171. * we simply want to return an error.
  3172. */
  3173. if (unlikely(test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags)))
  3174. return -EIO;
  3175. /* Someone else is already reading the buffer, just wait for it. */
  3176. if (test_and_set_bit(EXTENT_BUFFER_READING, &eb->bflags))
  3177. goto done;
  3178. /*
  3179. * Between the initial test_bit(EXTENT_BUFFER_UPTODATE) and the above
  3180. * test_and_set_bit(EXTENT_BUFFER_READING), someone else could have
  3181. * started and finished reading the same eb. In this case, UPTODATE
  3182. * will now be set, and we shouldn't read it in again.
  3183. */
  3184. if (unlikely(test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))) {
  3185. clear_extent_buffer_reading(eb);
  3186. return 0;
  3187. }
  3188. clear_bit(EXTENT_BUFFER_READ_ERR, &eb->bflags);
  3189. eb->read_mirror = 0;
  3190. check_buffer_tree_ref(eb);
  3191. atomic_inc(&eb->refs);
  3192. bbio = btrfs_bio_alloc(INLINE_EXTENT_BUFFER_PAGES,
  3193. REQ_OP_READ | REQ_META, eb->fs_info,
  3194. end_bbio_meta_read, eb);
  3195. bbio->bio.bi_iter.bi_sector = eb->start >> SECTOR_SHIFT;
  3196. bbio->inode = BTRFS_I(eb->fs_info->btree_inode);
  3197. bbio->file_offset = eb->start;
  3198. memcpy(&bbio->parent_check, check, sizeof(*check));
  3199. if (eb->fs_info->nodesize < PAGE_SIZE) {
  3200. ret = bio_add_folio(&bbio->bio, eb->folios[0], eb->len,
  3201. eb->start - folio_pos(eb->folios[0]));
  3202. ASSERT(ret);
  3203. } else {
  3204. int num_folios = num_extent_folios(eb);
  3205. for (int i = 0; i < num_folios; i++) {
  3206. struct folio *folio = eb->folios[i];
  3207. ret = bio_add_folio(&bbio->bio, folio, eb->folio_size, 0);
  3208. ASSERT(ret);
  3209. }
  3210. }
  3211. btrfs_submit_bbio(bbio, mirror_num);
  3212. done:
  3213. if (wait == WAIT_COMPLETE) {
  3214. wait_on_bit_io(&eb->bflags, EXTENT_BUFFER_READING, TASK_UNINTERRUPTIBLE);
  3215. if (!test_bit(EXTENT_BUFFER_UPTODATE, &eb->bflags))
  3216. return -EIO;
  3217. }
  3218. return 0;
  3219. }
  3220. static bool report_eb_range(const struct extent_buffer *eb, unsigned long start,
  3221. unsigned long len)
  3222. {
  3223. btrfs_warn(eb->fs_info,
  3224. "access to eb bytenr %llu len %u out of range start %lu len %lu",
  3225. eb->start, eb->len, start, len);
  3226. WARN_ON(IS_ENABLED(CONFIG_BTRFS_DEBUG));
  3227. return true;
  3228. }
  3229. /*
  3230. * Check if the [start, start + len) range is valid before reading/writing
  3231. * the eb.
  3232. * NOTE: @start and @len are offset inside the eb, not logical address.
  3233. *
  3234. * Caller should not touch the dst/src memory if this function returns error.
  3235. */
  3236. static inline int check_eb_range(const struct extent_buffer *eb,
  3237. unsigned long start, unsigned long len)
  3238. {
  3239. unsigned long offset;
  3240. /* start, start + len should not go beyond eb->len nor overflow */
  3241. if (unlikely(check_add_overflow(start, len, &offset) || offset > eb->len))
  3242. return report_eb_range(eb, start, len);
  3243. return false;
  3244. }
  3245. void read_extent_buffer(const struct extent_buffer *eb, void *dstv,
  3246. unsigned long start, unsigned long len)
  3247. {
  3248. const int unit_size = eb->folio_size;
  3249. size_t cur;
  3250. size_t offset;
  3251. char *dst = (char *)dstv;
  3252. unsigned long i = get_eb_folio_index(eb, start);
  3253. if (check_eb_range(eb, start, len)) {
  3254. /*
  3255. * Invalid range hit, reset the memory, so callers won't get
  3256. * some random garbage for their uninitialized memory.
  3257. */
  3258. memset(dstv, 0, len);
  3259. return;
  3260. }
  3261. if (eb->addr) {
  3262. memcpy(dstv, eb->addr + start, len);
  3263. return;
  3264. }
  3265. offset = get_eb_offset_in_folio(eb, start);
  3266. while (len > 0) {
  3267. char *kaddr;
  3268. cur = min(len, unit_size - offset);
  3269. kaddr = folio_address(eb->folios[i]);
  3270. memcpy(dst, kaddr + offset, cur);
  3271. dst += cur;
  3272. len -= cur;
  3273. offset = 0;
  3274. i++;
  3275. }
  3276. }
  3277. int read_extent_buffer_to_user_nofault(const struct extent_buffer *eb,
  3278. void __user *dstv,
  3279. unsigned long start, unsigned long len)
  3280. {
  3281. const int unit_size = eb->folio_size;
  3282. size_t cur;
  3283. size_t offset;
  3284. char __user *dst = (char __user *)dstv;
  3285. unsigned long i = get_eb_folio_index(eb, start);
  3286. int ret = 0;
  3287. WARN_ON(start > eb->len);
  3288. WARN_ON(start + len > eb->start + eb->len);
  3289. if (eb->addr) {
  3290. if (copy_to_user_nofault(dstv, eb->addr + start, len))
  3291. ret = -EFAULT;
  3292. return ret;
  3293. }
  3294. offset = get_eb_offset_in_folio(eb, start);
  3295. while (len > 0) {
  3296. char *kaddr;
  3297. cur = min(len, unit_size - offset);
  3298. kaddr = folio_address(eb->folios[i]);
  3299. if (copy_to_user_nofault(dst, kaddr + offset, cur)) {
  3300. ret = -EFAULT;
  3301. break;
  3302. }
  3303. dst += cur;
  3304. len -= cur;
  3305. offset = 0;
  3306. i++;
  3307. }
  3308. return ret;
  3309. }
  3310. int memcmp_extent_buffer(const struct extent_buffer *eb, const void *ptrv,
  3311. unsigned long start, unsigned long len)
  3312. {
  3313. const int unit_size = eb->folio_size;
  3314. size_t cur;
  3315. size_t offset;
  3316. char *kaddr;
  3317. char *ptr = (char *)ptrv;
  3318. unsigned long i = get_eb_folio_index(eb, start);
  3319. int ret = 0;
  3320. if (check_eb_range(eb, start, len))
  3321. return -EINVAL;
  3322. if (eb->addr)
  3323. return memcmp(ptrv, eb->addr + start, len);
  3324. offset = get_eb_offset_in_folio(eb, start);
  3325. while (len > 0) {
  3326. cur = min(len, unit_size - offset);
  3327. kaddr = folio_address(eb->folios[i]);
  3328. ret = memcmp(ptr, kaddr + offset, cur);
  3329. if (ret)
  3330. break;
  3331. ptr += cur;
  3332. len -= cur;
  3333. offset = 0;
  3334. i++;
  3335. }
  3336. return ret;
  3337. }
  3338. /*
  3339. * Check that the extent buffer is uptodate.
  3340. *
  3341. * For regular sector size == PAGE_SIZE case, check if @page is uptodate.
  3342. * For subpage case, check if the range covered by the eb has EXTENT_UPTODATE.
  3343. */
  3344. static void assert_eb_folio_uptodate(const struct extent_buffer *eb, int i)
  3345. {
  3346. struct btrfs_fs_info *fs_info = eb->fs_info;
  3347. struct folio *folio = eb->folios[i];
  3348. ASSERT(folio);
  3349. /*
  3350. * If we are using the commit root we could potentially clear a page
  3351. * Uptodate while we're using the extent buffer that we've previously
  3352. * looked up. We don't want to complain in this case, as the page was
  3353. * valid before, we just didn't write it out. Instead we want to catch
  3354. * the case where we didn't actually read the block properly, which
  3355. * would have !PageUptodate and !EXTENT_BUFFER_WRITE_ERR.
  3356. */
  3357. if (test_bit(EXTENT_BUFFER_WRITE_ERR, &eb->bflags))
  3358. return;
  3359. if (fs_info->nodesize < PAGE_SIZE) {
  3360. folio = eb->folios[0];
  3361. ASSERT(i == 0);
  3362. if (WARN_ON(!btrfs_subpage_test_uptodate(fs_info, folio,
  3363. eb->start, eb->len)))
  3364. btrfs_subpage_dump_bitmap(fs_info, folio, eb->start, eb->len);
  3365. } else {
  3366. WARN_ON(!folio_test_uptodate(folio));
  3367. }
  3368. }
  3369. static void __write_extent_buffer(const struct extent_buffer *eb,
  3370. const void *srcv, unsigned long start,
  3371. unsigned long len, bool use_memmove)
  3372. {
  3373. const int unit_size = eb->folio_size;
  3374. size_t cur;
  3375. size_t offset;
  3376. char *kaddr;
  3377. const char *src = (const char *)srcv;
  3378. unsigned long i = get_eb_folio_index(eb, start);
  3379. /* For unmapped (dummy) ebs, no need to check their uptodate status. */
  3380. const bool check_uptodate = !test_bit(EXTENT_BUFFER_UNMAPPED, &eb->bflags);
  3381. if (check_eb_range(eb, start, len))
  3382. return;
  3383. if (eb->addr) {
  3384. if (use_memmove)
  3385. memmove(eb->addr + start, srcv, len);
  3386. else
  3387. memcpy(eb->addr + start, srcv, len);
  3388. return;
  3389. }
  3390. offset = get_eb_offset_in_folio(eb, start);
  3391. while (len > 0) {
  3392. if (check_uptodate)
  3393. assert_eb_folio_uptodate(eb, i);
  3394. cur = min(len, unit_size - offset);
  3395. kaddr = folio_address(eb->folios[i]);
  3396. if (use_memmove)
  3397. memmove(kaddr + offset, src, cur);
  3398. else
  3399. memcpy(kaddr + offset, src, cur);
  3400. src += cur;
  3401. len -= cur;
  3402. offset = 0;
  3403. i++;
  3404. }
  3405. }
  3406. void write_extent_buffer(const struct extent_buffer *eb, const void *srcv,
  3407. unsigned long start, unsigned long len)
  3408. {
  3409. return __write_extent_buffer(eb, srcv, start, len, false);
  3410. }
  3411. static void memset_extent_buffer(const struct extent_buffer *eb, int c,
  3412. unsigned long start, unsigned long len)
  3413. {
  3414. const int unit_size = eb->folio_size;
  3415. unsigned long cur = start;
  3416. if (eb->addr) {
  3417. memset(eb->addr + start, c, len);
  3418. return;
  3419. }
  3420. while (cur < start + len) {
  3421. unsigned long index = get_eb_folio_index(eb, cur);
  3422. unsigned int offset = get_eb_offset_in_folio(eb, cur);
  3423. unsigned int cur_len = min(start + len - cur, unit_size - offset);
  3424. assert_eb_folio_uptodate(eb, index);
  3425. memset(folio_address(eb->folios[index]) + offset, c, cur_len);
  3426. cur += cur_len;
  3427. }
  3428. }
  3429. void memzero_extent_buffer(const struct extent_buffer *eb, unsigned long start,
  3430. unsigned long len)
  3431. {
  3432. if (check_eb_range(eb, start, len))
  3433. return;
  3434. return memset_extent_buffer(eb, 0, start, len);
  3435. }
  3436. void copy_extent_buffer_full(const struct extent_buffer *dst,
  3437. const struct extent_buffer *src)
  3438. {
  3439. const int unit_size = src->folio_size;
  3440. unsigned long cur = 0;
  3441. ASSERT(dst->len == src->len);
  3442. while (cur < src->len) {
  3443. unsigned long index = get_eb_folio_index(src, cur);
  3444. unsigned long offset = get_eb_offset_in_folio(src, cur);
  3445. unsigned long cur_len = min(src->len, unit_size - offset);
  3446. void *addr = folio_address(src->folios[index]) + offset;
  3447. write_extent_buffer(dst, addr, cur, cur_len);
  3448. cur += cur_len;
  3449. }
  3450. }
  3451. void copy_extent_buffer(const struct extent_buffer *dst,
  3452. const struct extent_buffer *src,
  3453. unsigned long dst_offset, unsigned long src_offset,
  3454. unsigned long len)
  3455. {
  3456. const int unit_size = dst->folio_size;
  3457. u64 dst_len = dst->len;
  3458. size_t cur;
  3459. size_t offset;
  3460. char *kaddr;
  3461. unsigned long i = get_eb_folio_index(dst, dst_offset);
  3462. if (check_eb_range(dst, dst_offset, len) ||
  3463. check_eb_range(src, src_offset, len))
  3464. return;
  3465. WARN_ON(src->len != dst_len);
  3466. offset = get_eb_offset_in_folio(dst, dst_offset);
  3467. while (len > 0) {
  3468. assert_eb_folio_uptodate(dst, i);
  3469. cur = min(len, (unsigned long)(unit_size - offset));
  3470. kaddr = folio_address(dst->folios[i]);
  3471. read_extent_buffer(src, kaddr + offset, src_offset, cur);
  3472. src_offset += cur;
  3473. len -= cur;
  3474. offset = 0;
  3475. i++;
  3476. }
  3477. }
  3478. /*
  3479. * Calculate the folio and offset of the byte containing the given bit number.
  3480. *
  3481. * @eb: the extent buffer
  3482. * @start: offset of the bitmap item in the extent buffer
  3483. * @nr: bit number
  3484. * @folio_index: return index of the folio in the extent buffer that contains
  3485. * the given bit number
  3486. * @folio_offset: return offset into the folio given by folio_index
  3487. *
  3488. * This helper hides the ugliness of finding the byte in an extent buffer which
  3489. * contains a given bit.
  3490. */
  3491. static inline void eb_bitmap_offset(const struct extent_buffer *eb,
  3492. unsigned long start, unsigned long nr,
  3493. unsigned long *folio_index,
  3494. size_t *folio_offset)
  3495. {
  3496. size_t byte_offset = BIT_BYTE(nr);
  3497. size_t offset;
  3498. /*
  3499. * The byte we want is the offset of the extent buffer + the offset of
  3500. * the bitmap item in the extent buffer + the offset of the byte in the
  3501. * bitmap item.
  3502. */
  3503. offset = start + offset_in_eb_folio(eb, eb->start) + byte_offset;
  3504. *folio_index = offset >> eb->folio_shift;
  3505. *folio_offset = offset_in_eb_folio(eb, offset);
  3506. }
  3507. /*
  3508. * Determine whether a bit in a bitmap item is set.
  3509. *
  3510. * @eb: the extent buffer
  3511. * @start: offset of the bitmap item in the extent buffer
  3512. * @nr: bit number to test
  3513. */
  3514. int extent_buffer_test_bit(const struct extent_buffer *eb, unsigned long start,
  3515. unsigned long nr)
  3516. {
  3517. unsigned long i;
  3518. size_t offset;
  3519. u8 *kaddr;
  3520. eb_bitmap_offset(eb, start, nr, &i, &offset);
  3521. assert_eb_folio_uptodate(eb, i);
  3522. kaddr = folio_address(eb->folios[i]);
  3523. return 1U & (kaddr[offset] >> (nr & (BITS_PER_BYTE - 1)));
  3524. }
  3525. static u8 *extent_buffer_get_byte(const struct extent_buffer *eb, unsigned long bytenr)
  3526. {
  3527. unsigned long index = get_eb_folio_index(eb, bytenr);
  3528. if (check_eb_range(eb, bytenr, 1))
  3529. return NULL;
  3530. return folio_address(eb->folios[index]) + get_eb_offset_in_folio(eb, bytenr);
  3531. }
  3532. /*
  3533. * Set an area of a bitmap to 1.
  3534. *
  3535. * @eb: the extent buffer
  3536. * @start: offset of the bitmap item in the extent buffer
  3537. * @pos: bit number of the first bit
  3538. * @len: number of bits to set
  3539. */
  3540. void extent_buffer_bitmap_set(const struct extent_buffer *eb, unsigned long start,
  3541. unsigned long pos, unsigned long len)
  3542. {
  3543. unsigned int first_byte = start + BIT_BYTE(pos);
  3544. unsigned int last_byte = start + BIT_BYTE(pos + len - 1);
  3545. const bool same_byte = (first_byte == last_byte);
  3546. u8 mask = BITMAP_FIRST_BYTE_MASK(pos);
  3547. u8 *kaddr;
  3548. if (same_byte)
  3549. mask &= BITMAP_LAST_BYTE_MASK(pos + len);
  3550. /* Handle the first byte. */
  3551. kaddr = extent_buffer_get_byte(eb, first_byte);
  3552. *kaddr |= mask;
  3553. if (same_byte)
  3554. return;
  3555. /* Handle the byte aligned part. */
  3556. ASSERT(first_byte + 1 <= last_byte);
  3557. memset_extent_buffer(eb, 0xff, first_byte + 1, last_byte - first_byte - 1);
  3558. /* Handle the last byte. */
  3559. kaddr = extent_buffer_get_byte(eb, last_byte);
  3560. *kaddr |= BITMAP_LAST_BYTE_MASK(pos + len);
  3561. }
  3562. /*
  3563. * Clear an area of a bitmap.
  3564. *
  3565. * @eb: the extent buffer
  3566. * @start: offset of the bitmap item in the extent buffer
  3567. * @pos: bit number of the first bit
  3568. * @len: number of bits to clear
  3569. */
  3570. void extent_buffer_bitmap_clear(const struct extent_buffer *eb,
  3571. unsigned long start, unsigned long pos,
  3572. unsigned long len)
  3573. {
  3574. unsigned int first_byte = start + BIT_BYTE(pos);
  3575. unsigned int last_byte = start + BIT_BYTE(pos + len - 1);
  3576. const bool same_byte = (first_byte == last_byte);
  3577. u8 mask = BITMAP_FIRST_BYTE_MASK(pos);
  3578. u8 *kaddr;
  3579. if (same_byte)
  3580. mask &= BITMAP_LAST_BYTE_MASK(pos + len);
  3581. /* Handle the first byte. */
  3582. kaddr = extent_buffer_get_byte(eb, first_byte);
  3583. *kaddr &= ~mask;
  3584. if (same_byte)
  3585. return;
  3586. /* Handle the byte aligned part. */
  3587. ASSERT(first_byte + 1 <= last_byte);
  3588. memset_extent_buffer(eb, 0, first_byte + 1, last_byte - first_byte - 1);
  3589. /* Handle the last byte. */
  3590. kaddr = extent_buffer_get_byte(eb, last_byte);
  3591. *kaddr &= ~BITMAP_LAST_BYTE_MASK(pos + len);
  3592. }
  3593. static inline bool areas_overlap(unsigned long src, unsigned long dst, unsigned long len)
  3594. {
  3595. unsigned long distance = (src > dst) ? src - dst : dst - src;
  3596. return distance < len;
  3597. }
  3598. void memcpy_extent_buffer(const struct extent_buffer *dst,
  3599. unsigned long dst_offset, unsigned long src_offset,
  3600. unsigned long len)
  3601. {
  3602. const int unit_size = dst->folio_size;
  3603. unsigned long cur_off = 0;
  3604. if (check_eb_range(dst, dst_offset, len) ||
  3605. check_eb_range(dst, src_offset, len))
  3606. return;
  3607. if (dst->addr) {
  3608. const bool use_memmove = areas_overlap(src_offset, dst_offset, len);
  3609. if (use_memmove)
  3610. memmove(dst->addr + dst_offset, dst->addr + src_offset, len);
  3611. else
  3612. memcpy(dst->addr + dst_offset, dst->addr + src_offset, len);
  3613. return;
  3614. }
  3615. while (cur_off < len) {
  3616. unsigned long cur_src = cur_off + src_offset;
  3617. unsigned long folio_index = get_eb_folio_index(dst, cur_src);
  3618. unsigned long folio_off = get_eb_offset_in_folio(dst, cur_src);
  3619. unsigned long cur_len = min(src_offset + len - cur_src,
  3620. unit_size - folio_off);
  3621. void *src_addr = folio_address(dst->folios[folio_index]) + folio_off;
  3622. const bool use_memmove = areas_overlap(src_offset + cur_off,
  3623. dst_offset + cur_off, cur_len);
  3624. __write_extent_buffer(dst, src_addr, dst_offset + cur_off, cur_len,
  3625. use_memmove);
  3626. cur_off += cur_len;
  3627. }
  3628. }
  3629. void memmove_extent_buffer(const struct extent_buffer *dst,
  3630. unsigned long dst_offset, unsigned long src_offset,
  3631. unsigned long len)
  3632. {
  3633. unsigned long dst_end = dst_offset + len - 1;
  3634. unsigned long src_end = src_offset + len - 1;
  3635. if (check_eb_range(dst, dst_offset, len) ||
  3636. check_eb_range(dst, src_offset, len))
  3637. return;
  3638. if (dst_offset < src_offset) {
  3639. memcpy_extent_buffer(dst, dst_offset, src_offset, len);
  3640. return;
  3641. }
  3642. if (dst->addr) {
  3643. memmove(dst->addr + dst_offset, dst->addr + src_offset, len);
  3644. return;
  3645. }
  3646. while (len > 0) {
  3647. unsigned long src_i;
  3648. size_t cur;
  3649. size_t dst_off_in_folio;
  3650. size_t src_off_in_folio;
  3651. void *src_addr;
  3652. bool use_memmove;
  3653. src_i = get_eb_folio_index(dst, src_end);
  3654. dst_off_in_folio = get_eb_offset_in_folio(dst, dst_end);
  3655. src_off_in_folio = get_eb_offset_in_folio(dst, src_end);
  3656. cur = min_t(unsigned long, len, src_off_in_folio + 1);
  3657. cur = min(cur, dst_off_in_folio + 1);
  3658. src_addr = folio_address(dst->folios[src_i]) + src_off_in_folio -
  3659. cur + 1;
  3660. use_memmove = areas_overlap(src_end - cur + 1, dst_end - cur + 1,
  3661. cur);
  3662. __write_extent_buffer(dst, src_addr, dst_end - cur + 1, cur,
  3663. use_memmove);
  3664. dst_end -= cur;
  3665. src_end -= cur;
  3666. len -= cur;
  3667. }
  3668. }
  3669. #define GANG_LOOKUP_SIZE 16
  3670. static struct extent_buffer *get_next_extent_buffer(
  3671. const struct btrfs_fs_info *fs_info, struct folio *folio, u64 bytenr)
  3672. {
  3673. struct extent_buffer *gang[GANG_LOOKUP_SIZE];
  3674. struct extent_buffer *found = NULL;
  3675. u64 folio_start = folio_pos(folio);
  3676. u64 cur = folio_start;
  3677. ASSERT(in_range(bytenr, folio_start, PAGE_SIZE));
  3678. lockdep_assert_held(&fs_info->buffer_lock);
  3679. while (cur < folio_start + PAGE_SIZE) {
  3680. int ret;
  3681. int i;
  3682. ret = radix_tree_gang_lookup(&fs_info->buffer_radix,
  3683. (void **)gang, cur >> fs_info->sectorsize_bits,
  3684. min_t(unsigned int, GANG_LOOKUP_SIZE,
  3685. PAGE_SIZE / fs_info->nodesize));
  3686. if (ret == 0)
  3687. goto out;
  3688. for (i = 0; i < ret; i++) {
  3689. /* Already beyond page end */
  3690. if (gang[i]->start >= folio_start + PAGE_SIZE)
  3691. goto out;
  3692. /* Found one */
  3693. if (gang[i]->start >= bytenr) {
  3694. found = gang[i];
  3695. goto out;
  3696. }
  3697. }
  3698. cur = gang[ret - 1]->start + gang[ret - 1]->len;
  3699. }
  3700. out:
  3701. return found;
  3702. }
  3703. static int try_release_subpage_extent_buffer(struct folio *folio)
  3704. {
  3705. struct btrfs_fs_info *fs_info = folio_to_fs_info(folio);
  3706. u64 cur = folio_pos(folio);
  3707. const u64 end = cur + PAGE_SIZE;
  3708. int ret;
  3709. while (cur < end) {
  3710. struct extent_buffer *eb = NULL;
  3711. /*
  3712. * Unlike try_release_extent_buffer() which uses folio private
  3713. * to grab buffer, for subpage case we rely on radix tree, thus
  3714. * we need to ensure radix tree consistency.
  3715. *
  3716. * We also want an atomic snapshot of the radix tree, thus go
  3717. * with spinlock rather than RCU.
  3718. */
  3719. spin_lock(&fs_info->buffer_lock);
  3720. eb = get_next_extent_buffer(fs_info, folio, cur);
  3721. if (!eb) {
  3722. /* No more eb in the page range after or at cur */
  3723. spin_unlock(&fs_info->buffer_lock);
  3724. break;
  3725. }
  3726. cur = eb->start + eb->len;
  3727. /*
  3728. * The same as try_release_extent_buffer(), to ensure the eb
  3729. * won't disappear out from under us.
  3730. */
  3731. spin_lock(&eb->refs_lock);
  3732. if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
  3733. spin_unlock(&eb->refs_lock);
  3734. spin_unlock(&fs_info->buffer_lock);
  3735. break;
  3736. }
  3737. spin_unlock(&fs_info->buffer_lock);
  3738. /*
  3739. * If tree ref isn't set then we know the ref on this eb is a
  3740. * real ref, so just return, this eb will likely be freed soon
  3741. * anyway.
  3742. */
  3743. if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
  3744. spin_unlock(&eb->refs_lock);
  3745. break;
  3746. }
  3747. /*
  3748. * Here we don't care about the return value, we will always
  3749. * check the folio private at the end. And
  3750. * release_extent_buffer() will release the refs_lock.
  3751. */
  3752. release_extent_buffer(eb);
  3753. }
  3754. /*
  3755. * Finally to check if we have cleared folio private, as if we have
  3756. * released all ebs in the page, the folio private should be cleared now.
  3757. */
  3758. spin_lock(&folio->mapping->i_private_lock);
  3759. if (!folio_test_private(folio))
  3760. ret = 1;
  3761. else
  3762. ret = 0;
  3763. spin_unlock(&folio->mapping->i_private_lock);
  3764. return ret;
  3765. }
  3766. int try_release_extent_buffer(struct folio *folio)
  3767. {
  3768. struct extent_buffer *eb;
  3769. if (folio_to_fs_info(folio)->nodesize < PAGE_SIZE)
  3770. return try_release_subpage_extent_buffer(folio);
  3771. /*
  3772. * We need to make sure nobody is changing folio private, as we rely on
  3773. * folio private as the pointer to extent buffer.
  3774. */
  3775. spin_lock(&folio->mapping->i_private_lock);
  3776. if (!folio_test_private(folio)) {
  3777. spin_unlock(&folio->mapping->i_private_lock);
  3778. return 1;
  3779. }
  3780. eb = folio_get_private(folio);
  3781. BUG_ON(!eb);
  3782. /*
  3783. * This is a little awful but should be ok, we need to make sure that
  3784. * the eb doesn't disappear out from under us while we're looking at
  3785. * this page.
  3786. */
  3787. spin_lock(&eb->refs_lock);
  3788. if (atomic_read(&eb->refs) != 1 || extent_buffer_under_io(eb)) {
  3789. spin_unlock(&eb->refs_lock);
  3790. spin_unlock(&folio->mapping->i_private_lock);
  3791. return 0;
  3792. }
  3793. spin_unlock(&folio->mapping->i_private_lock);
  3794. /*
  3795. * If tree ref isn't set then we know the ref on this eb is a real ref,
  3796. * so just return, this page will likely be freed soon anyway.
  3797. */
  3798. if (!test_and_clear_bit(EXTENT_BUFFER_TREE_REF, &eb->bflags)) {
  3799. spin_unlock(&eb->refs_lock);
  3800. return 0;
  3801. }
  3802. return release_extent_buffer(eb);
  3803. }
  3804. /*
  3805. * Attempt to readahead a child block.
  3806. *
  3807. * @fs_info: the fs_info
  3808. * @bytenr: bytenr to read
  3809. * @owner_root: objectid of the root that owns this eb
  3810. * @gen: generation for the uptodate check, can be 0
  3811. * @level: level for the eb
  3812. *
  3813. * Attempt to readahead a tree block at @bytenr. If @gen is 0 then we do a
  3814. * normal uptodate check of the eb, without checking the generation. If we have
  3815. * to read the block we will not block on anything.
  3816. */
  3817. void btrfs_readahead_tree_block(struct btrfs_fs_info *fs_info,
  3818. u64 bytenr, u64 owner_root, u64 gen, int level)
  3819. {
  3820. struct btrfs_tree_parent_check check = {
  3821. .has_first_key = 0,
  3822. .level = level,
  3823. .transid = gen
  3824. };
  3825. struct extent_buffer *eb;
  3826. int ret;
  3827. eb = btrfs_find_create_tree_block(fs_info, bytenr, owner_root, level);
  3828. if (IS_ERR(eb))
  3829. return;
  3830. if (btrfs_buffer_uptodate(eb, gen, 1)) {
  3831. free_extent_buffer(eb);
  3832. return;
  3833. }
  3834. ret = read_extent_buffer_pages(eb, WAIT_NONE, 0, &check);
  3835. if (ret < 0)
  3836. free_extent_buffer_stale(eb);
  3837. else
  3838. free_extent_buffer(eb);
  3839. }
  3840. /*
  3841. * Readahead a node's child block.
  3842. *
  3843. * @node: parent node we're reading from
  3844. * @slot: slot in the parent node for the child we want to read
  3845. *
  3846. * A helper for btrfs_readahead_tree_block, we simply read the bytenr pointed at
  3847. * the slot in the node provided.
  3848. */
  3849. void btrfs_readahead_node_child(struct extent_buffer *node, int slot)
  3850. {
  3851. btrfs_readahead_tree_block(node->fs_info,
  3852. btrfs_node_blockptr(node, slot),
  3853. btrfs_header_owner(node),
  3854. btrfs_node_ptr_generation(node, slot),
  3855. btrfs_header_level(node) - 1);
  3856. }