backref.c 101 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Copyright (C) 2011 STRATO. All rights reserved.
  4. */
  5. #include <linux/mm.h>
  6. #include <linux/rbtree.h>
  7. #include <trace/events/btrfs.h>
  8. #include "ctree.h"
  9. #include "disk-io.h"
  10. #include "backref.h"
  11. #include "ulist.h"
  12. #include "transaction.h"
  13. #include "delayed-ref.h"
  14. #include "locking.h"
  15. #include "misc.h"
  16. #include "tree-mod-log.h"
  17. #include "fs.h"
  18. #include "accessors.h"
  19. #include "extent-tree.h"
  20. #include "relocation.h"
  21. #include "tree-checker.h"
  22. /* Just arbitrary numbers so we can be sure one of these happened. */
  23. #define BACKREF_FOUND_SHARED 6
  24. #define BACKREF_FOUND_NOT_SHARED 7
  25. struct extent_inode_elem {
  26. u64 inum;
  27. u64 offset;
  28. u64 num_bytes;
  29. struct extent_inode_elem *next;
  30. };
  31. static int check_extent_in_eb(struct btrfs_backref_walk_ctx *ctx,
  32. const struct btrfs_key *key,
  33. const struct extent_buffer *eb,
  34. const struct btrfs_file_extent_item *fi,
  35. struct extent_inode_elem **eie)
  36. {
  37. const u64 data_len = btrfs_file_extent_num_bytes(eb, fi);
  38. u64 offset = key->offset;
  39. struct extent_inode_elem *e;
  40. const u64 *root_ids;
  41. int root_count;
  42. bool cached;
  43. if (!ctx->ignore_extent_item_pos &&
  44. !btrfs_file_extent_compression(eb, fi) &&
  45. !btrfs_file_extent_encryption(eb, fi) &&
  46. !btrfs_file_extent_other_encoding(eb, fi)) {
  47. u64 data_offset;
  48. data_offset = btrfs_file_extent_offset(eb, fi);
  49. if (ctx->extent_item_pos < data_offset ||
  50. ctx->extent_item_pos >= data_offset + data_len)
  51. return 1;
  52. offset += ctx->extent_item_pos - data_offset;
  53. }
  54. if (!ctx->indirect_ref_iterator || !ctx->cache_lookup)
  55. goto add_inode_elem;
  56. cached = ctx->cache_lookup(eb->start, ctx->user_ctx, &root_ids,
  57. &root_count);
  58. if (!cached)
  59. goto add_inode_elem;
  60. for (int i = 0; i < root_count; i++) {
  61. int ret;
  62. ret = ctx->indirect_ref_iterator(key->objectid, offset,
  63. data_len, root_ids[i],
  64. ctx->user_ctx);
  65. if (ret)
  66. return ret;
  67. }
  68. add_inode_elem:
  69. e = kmalloc_obj(*e, GFP_NOFS);
  70. if (!e)
  71. return -ENOMEM;
  72. e->next = *eie;
  73. e->inum = key->objectid;
  74. e->offset = offset;
  75. e->num_bytes = data_len;
  76. *eie = e;
  77. return 0;
  78. }
  79. static void free_inode_elem_list(struct extent_inode_elem *eie)
  80. {
  81. struct extent_inode_elem *eie_next;
  82. for (; eie; eie = eie_next) {
  83. eie_next = eie->next;
  84. kfree(eie);
  85. }
  86. }
  87. static int find_extent_in_eb(struct btrfs_backref_walk_ctx *ctx,
  88. const struct extent_buffer *eb,
  89. struct extent_inode_elem **eie)
  90. {
  91. u64 disk_byte;
  92. struct btrfs_key key;
  93. struct btrfs_file_extent_item *fi;
  94. int slot;
  95. int nritems;
  96. int extent_type;
  97. int ret;
  98. /*
  99. * from the shared data ref, we only have the leaf but we need
  100. * the key. thus, we must look into all items and see that we
  101. * find one (some) with a reference to our extent item.
  102. */
  103. nritems = btrfs_header_nritems(eb);
  104. for (slot = 0; slot < nritems; ++slot) {
  105. btrfs_item_key_to_cpu(eb, &key, slot);
  106. if (key.type != BTRFS_EXTENT_DATA_KEY)
  107. continue;
  108. fi = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
  109. extent_type = btrfs_file_extent_type(eb, fi);
  110. if (extent_type == BTRFS_FILE_EXTENT_INLINE)
  111. continue;
  112. /* don't skip BTRFS_FILE_EXTENT_PREALLOC, we can handle that */
  113. disk_byte = btrfs_file_extent_disk_bytenr(eb, fi);
  114. if (disk_byte != ctx->bytenr)
  115. continue;
  116. ret = check_extent_in_eb(ctx, &key, eb, fi, eie);
  117. if (ret == BTRFS_ITERATE_EXTENT_INODES_STOP || ret < 0)
  118. return ret;
  119. }
  120. return 0;
  121. }
  122. struct preftree {
  123. struct rb_root_cached root;
  124. unsigned int count;
  125. };
  126. #define PREFTREE_INIT { .root = RB_ROOT_CACHED, .count = 0 }
  127. struct preftrees {
  128. struct preftree direct; /* BTRFS_SHARED_[DATA|BLOCK]_REF_KEY */
  129. struct preftree indirect; /* BTRFS_[TREE_BLOCK|EXTENT_DATA]_REF_KEY */
  130. struct preftree indirect_missing_keys;
  131. };
  132. /*
  133. * Checks for a shared extent during backref search.
  134. *
  135. * The share_count tracks prelim_refs (direct and indirect) having a
  136. * ref->count >0:
  137. * - incremented when a ref->count transitions to >0
  138. * - decremented when a ref->count transitions to <1
  139. */
  140. struct share_check {
  141. struct btrfs_backref_share_check_ctx *ctx;
  142. struct btrfs_root *root;
  143. u64 inum;
  144. u64 data_bytenr;
  145. u64 data_extent_gen;
  146. /*
  147. * Counts number of inodes that refer to an extent (different inodes in
  148. * the same root or different roots) that we could find. The sharedness
  149. * check typically stops once this counter gets greater than 1, so it
  150. * may not reflect the total number of inodes.
  151. */
  152. int share_count;
  153. /*
  154. * The number of times we found our inode refers to the data extent we
  155. * are determining the sharedness. In other words, how many file extent
  156. * items we could find for our inode that point to our target data
  157. * extent. The value we get here after finishing the extent sharedness
  158. * check may be smaller than reality, but if it ends up being greater
  159. * than 1, then we know for sure the inode has multiple file extent
  160. * items that point to our inode, and we can safely assume it's useful
  161. * to cache the sharedness check result.
  162. */
  163. int self_ref_count;
  164. bool have_delayed_delete_refs;
  165. };
  166. static inline int extent_is_shared(struct share_check *sc)
  167. {
  168. return (sc && sc->share_count > 1) ? BACKREF_FOUND_SHARED : 0;
  169. }
  170. static struct kmem_cache *btrfs_prelim_ref_cache;
  171. int __init btrfs_prelim_ref_init(void)
  172. {
  173. btrfs_prelim_ref_cache = kmem_cache_create("btrfs_prelim_ref",
  174. sizeof(struct prelim_ref), 0, 0, NULL);
  175. if (!btrfs_prelim_ref_cache)
  176. return -ENOMEM;
  177. return 0;
  178. }
  179. void __cold btrfs_prelim_ref_exit(void)
  180. {
  181. kmem_cache_destroy(btrfs_prelim_ref_cache);
  182. }
  183. static void free_pref(struct prelim_ref *ref)
  184. {
  185. kmem_cache_free(btrfs_prelim_ref_cache, ref);
  186. }
  187. /*
  188. * Return 0 when both refs are for the same block (and can be merged).
  189. * A -1 return indicates ref1 is a 'lower' block than ref2, while 1
  190. * indicates a 'higher' block.
  191. */
  192. static int prelim_ref_compare(const struct prelim_ref *ref1,
  193. const struct prelim_ref *ref2)
  194. {
  195. if (ref1->level < ref2->level)
  196. return -1;
  197. if (ref1->level > ref2->level)
  198. return 1;
  199. if (ref1->root_id < ref2->root_id)
  200. return -1;
  201. if (ref1->root_id > ref2->root_id)
  202. return 1;
  203. if (ref1->key_for_search.type < ref2->key_for_search.type)
  204. return -1;
  205. if (ref1->key_for_search.type > ref2->key_for_search.type)
  206. return 1;
  207. if (ref1->key_for_search.objectid < ref2->key_for_search.objectid)
  208. return -1;
  209. if (ref1->key_for_search.objectid > ref2->key_for_search.objectid)
  210. return 1;
  211. if (ref1->key_for_search.offset < ref2->key_for_search.offset)
  212. return -1;
  213. if (ref1->key_for_search.offset > ref2->key_for_search.offset)
  214. return 1;
  215. if (ref1->parent < ref2->parent)
  216. return -1;
  217. if (ref1->parent > ref2->parent)
  218. return 1;
  219. return 0;
  220. }
  221. static int prelim_ref_rb_add_cmp(const struct rb_node *new,
  222. const struct rb_node *exist)
  223. {
  224. const struct prelim_ref *ref_new =
  225. rb_entry(new, struct prelim_ref, rbnode);
  226. const struct prelim_ref *ref_exist =
  227. rb_entry(exist, struct prelim_ref, rbnode);
  228. /*
  229. * prelim_ref_compare() expects the first parameter as the existing one,
  230. * different from the rb_find_add_cached() order.
  231. */
  232. return prelim_ref_compare(ref_exist, ref_new);
  233. }
  234. static void update_share_count(struct share_check *sc, int oldcount,
  235. int newcount, const struct prelim_ref *newref)
  236. {
  237. if ((!sc) || (oldcount == 0 && newcount < 1))
  238. return;
  239. if (oldcount > 0 && newcount < 1)
  240. sc->share_count--;
  241. else if (oldcount < 1 && newcount > 0)
  242. sc->share_count++;
  243. if (newref->root_id == btrfs_root_id(sc->root) &&
  244. newref->wanted_disk_byte == sc->data_bytenr &&
  245. newref->key_for_search.objectid == sc->inum)
  246. sc->self_ref_count += newref->count;
  247. }
  248. /*
  249. * Add @newref to the @root rbtree, merging identical refs.
  250. *
  251. * Callers should assume that newref has been freed after calling.
  252. */
  253. static void prelim_ref_insert(const struct btrfs_fs_info *fs_info,
  254. struct preftree *preftree,
  255. struct prelim_ref *newref,
  256. struct share_check *sc)
  257. {
  258. struct rb_root_cached *root;
  259. struct rb_node *exist;
  260. root = &preftree->root;
  261. exist = rb_find_add_cached(&newref->rbnode, root, prelim_ref_rb_add_cmp);
  262. if (exist) {
  263. struct prelim_ref *ref = rb_entry(exist, struct prelim_ref, rbnode);
  264. /* Identical refs, merge them and free @newref */
  265. struct extent_inode_elem *eie = ref->inode_list;
  266. while (eie && eie->next)
  267. eie = eie->next;
  268. if (!eie)
  269. ref->inode_list = newref->inode_list;
  270. else
  271. eie->next = newref->inode_list;
  272. trace_btrfs_prelim_ref_merge(fs_info, ref, newref,
  273. preftree->count);
  274. /*
  275. * A delayed ref can have newref->count < 0.
  276. * The ref->count is updated to follow any
  277. * BTRFS_[ADD|DROP]_DELAYED_REF actions.
  278. */
  279. update_share_count(sc, ref->count,
  280. ref->count + newref->count, newref);
  281. ref->count += newref->count;
  282. free_pref(newref);
  283. return;
  284. }
  285. update_share_count(sc, 0, newref->count, newref);
  286. preftree->count++;
  287. trace_btrfs_prelim_ref_insert(fs_info, newref, NULL, preftree->count);
  288. }
  289. /*
  290. * Release the entire tree. We don't care about internal consistency so
  291. * just free everything and then reset the tree root.
  292. */
  293. static void prelim_release(struct preftree *preftree)
  294. {
  295. struct prelim_ref *ref, *next_ref;
  296. rbtree_postorder_for_each_entry_safe(ref, next_ref,
  297. &preftree->root.rb_root, rbnode) {
  298. free_inode_elem_list(ref->inode_list);
  299. free_pref(ref);
  300. }
  301. preftree->root = RB_ROOT_CACHED;
  302. preftree->count = 0;
  303. }
  304. /*
  305. * the rules for all callers of this function are:
  306. * - obtaining the parent is the goal
  307. * - if you add a key, you must know that it is a correct key
  308. * - if you cannot add the parent or a correct key, then we will look into the
  309. * block later to set a correct key
  310. *
  311. * delayed refs
  312. * ============
  313. * backref type | shared | indirect | shared | indirect
  314. * information | tree | tree | data | data
  315. * --------------------+--------+----------+--------+----------
  316. * parent logical | y | - | - | -
  317. * key to resolve | - | y | y | y
  318. * tree block logical | - | - | - | -
  319. * root for resolving | y | y | y | y
  320. *
  321. * - column 1: we've the parent -> done
  322. * - column 2, 3, 4: we use the key to find the parent
  323. *
  324. * on disk refs (inline or keyed)
  325. * ==============================
  326. * backref type | shared | indirect | shared | indirect
  327. * information | tree | tree | data | data
  328. * --------------------+--------+----------+--------+----------
  329. * parent logical | y | - | y | -
  330. * key to resolve | - | - | - | y
  331. * tree block logical | y | y | y | y
  332. * root for resolving | - | y | y | y
  333. *
  334. * - column 1, 3: we've the parent -> done
  335. * - column 2: we take the first key from the block to find the parent
  336. * (see add_missing_keys)
  337. * - column 4: we use the key to find the parent
  338. *
  339. * additional information that's available but not required to find the parent
  340. * block might help in merging entries to gain some speed.
  341. */
  342. static int add_prelim_ref(const struct btrfs_fs_info *fs_info,
  343. struct preftree *preftree, u64 root_id,
  344. const struct btrfs_key *key, int level, u64 parent,
  345. u64 wanted_disk_byte, int count,
  346. struct share_check *sc, gfp_t gfp_mask)
  347. {
  348. struct prelim_ref *ref;
  349. if (root_id == BTRFS_DATA_RELOC_TREE_OBJECTID)
  350. return 0;
  351. ref = kmem_cache_alloc(btrfs_prelim_ref_cache, gfp_mask);
  352. if (!ref)
  353. return -ENOMEM;
  354. ref->root_id = root_id;
  355. if (key)
  356. ref->key_for_search = *key;
  357. else
  358. memset(&ref->key_for_search, 0, sizeof(ref->key_for_search));
  359. ref->inode_list = NULL;
  360. ref->level = level;
  361. ref->count = count;
  362. ref->parent = parent;
  363. ref->wanted_disk_byte = wanted_disk_byte;
  364. prelim_ref_insert(fs_info, preftree, ref, sc);
  365. return extent_is_shared(sc);
  366. }
  367. /* direct refs use root == 0, key == NULL */
  368. static int add_direct_ref(const struct btrfs_fs_info *fs_info,
  369. struct preftrees *preftrees, int level, u64 parent,
  370. u64 wanted_disk_byte, int count,
  371. struct share_check *sc, gfp_t gfp_mask)
  372. {
  373. return add_prelim_ref(fs_info, &preftrees->direct, 0, NULL, level,
  374. parent, wanted_disk_byte, count, sc, gfp_mask);
  375. }
  376. /* indirect refs use parent == 0 */
  377. static int add_indirect_ref(const struct btrfs_fs_info *fs_info,
  378. struct preftrees *preftrees, u64 root_id,
  379. const struct btrfs_key *key, int level,
  380. u64 wanted_disk_byte, int count,
  381. struct share_check *sc, gfp_t gfp_mask)
  382. {
  383. struct preftree *tree = &preftrees->indirect;
  384. if (!key)
  385. tree = &preftrees->indirect_missing_keys;
  386. return add_prelim_ref(fs_info, tree, root_id, key, level, 0,
  387. wanted_disk_byte, count, sc, gfp_mask);
  388. }
  389. static int is_shared_data_backref(struct preftrees *preftrees, u64 bytenr)
  390. {
  391. struct rb_node **p = &preftrees->direct.root.rb_root.rb_node;
  392. struct rb_node *parent = NULL;
  393. struct prelim_ref *ref = NULL;
  394. struct prelim_ref target = {};
  395. int result;
  396. target.parent = bytenr;
  397. while (*p) {
  398. parent = *p;
  399. ref = rb_entry(parent, struct prelim_ref, rbnode);
  400. result = prelim_ref_compare(ref, &target);
  401. if (result < 0)
  402. p = &(*p)->rb_left;
  403. else if (result > 0)
  404. p = &(*p)->rb_right;
  405. else
  406. return 1;
  407. }
  408. return 0;
  409. }
  410. static int add_all_parents(struct btrfs_backref_walk_ctx *ctx,
  411. struct btrfs_root *root, struct btrfs_path *path,
  412. struct ulist *parents,
  413. struct preftrees *preftrees, struct prelim_ref *ref,
  414. int level)
  415. {
  416. int ret = 0;
  417. int slot;
  418. struct extent_buffer *eb;
  419. struct btrfs_key key;
  420. struct btrfs_key *key_for_search = &ref->key_for_search;
  421. struct btrfs_file_extent_item *fi;
  422. struct extent_inode_elem *eie = NULL, *old = NULL;
  423. u64 disk_byte;
  424. u64 wanted_disk_byte = ref->wanted_disk_byte;
  425. u64 count = 0;
  426. u64 data_offset;
  427. u8 type;
  428. if (level != 0) {
  429. eb = path->nodes[level];
  430. ret = ulist_add(parents, eb->start, 0, GFP_NOFS);
  431. if (ret < 0)
  432. return ret;
  433. return 0;
  434. }
  435. /*
  436. * 1. We normally enter this function with the path already pointing to
  437. * the first item to check. But sometimes, we may enter it with
  438. * slot == nritems.
  439. * 2. We are searching for normal backref but bytenr of this leaf
  440. * matches shared data backref
  441. * 3. The leaf owner is not equal to the root we are searching
  442. *
  443. * For these cases, go to the next leaf before we continue.
  444. */
  445. eb = path->nodes[0];
  446. if (path->slots[0] >= btrfs_header_nritems(eb) ||
  447. is_shared_data_backref(preftrees, eb->start) ||
  448. ref->root_id != btrfs_header_owner(eb)) {
  449. if (ctx->time_seq == BTRFS_SEQ_LAST)
  450. ret = btrfs_next_leaf(root, path);
  451. else
  452. ret = btrfs_next_old_leaf(root, path, ctx->time_seq);
  453. }
  454. while (!ret && count < ref->count) {
  455. eb = path->nodes[0];
  456. slot = path->slots[0];
  457. btrfs_item_key_to_cpu(eb, &key, slot);
  458. if (key.objectid != key_for_search->objectid ||
  459. key.type != BTRFS_EXTENT_DATA_KEY)
  460. break;
  461. /*
  462. * We are searching for normal backref but bytenr of this leaf
  463. * matches shared data backref, OR
  464. * the leaf owner is not equal to the root we are searching for
  465. */
  466. if (slot == 0 &&
  467. (is_shared_data_backref(preftrees, eb->start) ||
  468. ref->root_id != btrfs_header_owner(eb))) {
  469. if (ctx->time_seq == BTRFS_SEQ_LAST)
  470. ret = btrfs_next_leaf(root, path);
  471. else
  472. ret = btrfs_next_old_leaf(root, path, ctx->time_seq);
  473. continue;
  474. }
  475. fi = btrfs_item_ptr(eb, slot, struct btrfs_file_extent_item);
  476. type = btrfs_file_extent_type(eb, fi);
  477. if (type == BTRFS_FILE_EXTENT_INLINE)
  478. goto next;
  479. disk_byte = btrfs_file_extent_disk_bytenr(eb, fi);
  480. data_offset = btrfs_file_extent_offset(eb, fi);
  481. if (disk_byte == wanted_disk_byte) {
  482. eie = NULL;
  483. old = NULL;
  484. if (ref->key_for_search.offset == key.offset - data_offset)
  485. count++;
  486. else
  487. goto next;
  488. if (!ctx->skip_inode_ref_list) {
  489. ret = check_extent_in_eb(ctx, &key, eb, fi, &eie);
  490. if (ret == BTRFS_ITERATE_EXTENT_INODES_STOP ||
  491. ret < 0)
  492. break;
  493. }
  494. if (ret > 0)
  495. goto next;
  496. ret = ulist_add_merge_ptr(parents, eb->start,
  497. eie, (void **)&old, GFP_NOFS);
  498. if (ret < 0)
  499. break;
  500. if (!ret && !ctx->skip_inode_ref_list) {
  501. while (old->next)
  502. old = old->next;
  503. old->next = eie;
  504. }
  505. eie = NULL;
  506. }
  507. next:
  508. if (ctx->time_seq == BTRFS_SEQ_LAST)
  509. ret = btrfs_next_item(root, path);
  510. else
  511. ret = btrfs_next_old_item(root, path, ctx->time_seq);
  512. }
  513. if (ret == BTRFS_ITERATE_EXTENT_INODES_STOP || ret < 0)
  514. free_inode_elem_list(eie);
  515. else if (ret > 0)
  516. ret = 0;
  517. return ret;
  518. }
  519. /*
  520. * resolve an indirect backref in the form (root_id, key, level)
  521. * to a logical address
  522. */
  523. static int resolve_indirect_ref(struct btrfs_backref_walk_ctx *ctx,
  524. struct btrfs_path *path,
  525. struct preftrees *preftrees,
  526. struct prelim_ref *ref, struct ulist *parents)
  527. {
  528. struct btrfs_root *root;
  529. struct extent_buffer *eb;
  530. int ret = 0;
  531. int root_level;
  532. int level = ref->level;
  533. struct btrfs_key search_key = ref->key_for_search;
  534. /*
  535. * If we're search_commit_root we could possibly be holding locks on
  536. * other tree nodes. This happens when qgroups does backref walks when
  537. * adding new delayed refs. To deal with this we need to look in cache
  538. * for the root, and if we don't find it then we need to search the
  539. * tree_root's commit root, thus the btrfs_get_fs_root_commit_root usage
  540. * here.
  541. */
  542. if (path->search_commit_root)
  543. root = btrfs_get_fs_root_commit_root(ctx->fs_info, path, ref->root_id);
  544. else
  545. root = btrfs_get_fs_root(ctx->fs_info, ref->root_id, false);
  546. if (IS_ERR(root)) {
  547. ret = PTR_ERR(root);
  548. goto out_free;
  549. }
  550. if (!path->search_commit_root &&
  551. test_bit(BTRFS_ROOT_DELETING, &root->state)) {
  552. ret = -ENOENT;
  553. goto out;
  554. }
  555. if (btrfs_is_testing(ctx->fs_info)) {
  556. ret = -ENOENT;
  557. goto out;
  558. }
  559. if (path->search_commit_root)
  560. root_level = btrfs_header_level(root->commit_root);
  561. else if (ctx->time_seq == BTRFS_SEQ_LAST)
  562. root_level = btrfs_header_level(root->node);
  563. else
  564. root_level = btrfs_old_root_level(root, ctx->time_seq);
  565. if (root_level + 1 == level)
  566. goto out;
  567. /*
  568. * We can often find data backrefs with an offset that is too large
  569. * (>= LLONG_MAX, maximum allowed file offset) due to underflows when
  570. * subtracting a file's offset with the data offset of its
  571. * corresponding extent data item. This can happen for example in the
  572. * clone ioctl.
  573. *
  574. * So if we detect such case we set the search key's offset to zero to
  575. * make sure we will find the matching file extent item at
  576. * add_all_parents(), otherwise we will miss it because the offset
  577. * taken form the backref is much larger then the offset of the file
  578. * extent item. This can make us scan a very large number of file
  579. * extent items, but at least it will not make us miss any.
  580. *
  581. * This is an ugly workaround for a behaviour that should have never
  582. * existed, but it does and a fix for the clone ioctl would touch a lot
  583. * of places, cause backwards incompatibility and would not fix the
  584. * problem for extents cloned with older kernels.
  585. */
  586. if (search_key.type == BTRFS_EXTENT_DATA_KEY &&
  587. search_key.offset >= LLONG_MAX)
  588. search_key.offset = 0;
  589. path->lowest_level = level;
  590. if (ctx->time_seq == BTRFS_SEQ_LAST)
  591. ret = btrfs_search_slot(NULL, root, &search_key, path, 0, 0);
  592. else
  593. ret = btrfs_search_old_slot(root, &search_key, path, ctx->time_seq);
  594. btrfs_debug(ctx->fs_info,
  595. "search slot in root %llu (level %d, ref count %d) returned %d for key " BTRFS_KEY_FMT,
  596. ref->root_id, level, ref->count, ret,
  597. BTRFS_KEY_FMT_VALUE(&ref->key_for_search));
  598. if (ret < 0)
  599. goto out;
  600. eb = path->nodes[level];
  601. while (!eb) {
  602. if (WARN_ON(!level)) {
  603. ret = 1;
  604. goto out;
  605. }
  606. level--;
  607. eb = path->nodes[level];
  608. }
  609. ret = add_all_parents(ctx, root, path, parents, preftrees, ref, level);
  610. out:
  611. btrfs_put_root(root);
  612. out_free:
  613. path->lowest_level = 0;
  614. btrfs_release_path(path);
  615. return ret;
  616. }
  617. static struct extent_inode_elem *
  618. unode_aux_to_inode_list(struct ulist_node *node)
  619. {
  620. if (!node)
  621. return NULL;
  622. return (struct extent_inode_elem *)(uintptr_t)node->aux;
  623. }
  624. static void free_leaf_list(struct ulist *ulist)
  625. {
  626. struct ulist_node *node;
  627. struct ulist_iterator uiter;
  628. ULIST_ITER_INIT(&uiter);
  629. while ((node = ulist_next(ulist, &uiter)))
  630. free_inode_elem_list(unode_aux_to_inode_list(node));
  631. ulist_free(ulist);
  632. }
  633. /*
  634. * We maintain three separate rbtrees: one for direct refs, one for
  635. * indirect refs which have a key, and one for indirect refs which do not
  636. * have a key. Each tree does merge on insertion.
  637. *
  638. * Once all of the references are located, we iterate over the tree of
  639. * indirect refs with missing keys. An appropriate key is located and
  640. * the ref is moved onto the tree for indirect refs. After all missing
  641. * keys are thus located, we iterate over the indirect ref tree, resolve
  642. * each reference, and then insert the resolved reference onto the
  643. * direct tree (merging there too).
  644. *
  645. * New backrefs (i.e., for parent nodes) are added to the appropriate
  646. * rbtree as they are encountered. The new backrefs are subsequently
  647. * resolved as above.
  648. */
  649. static int resolve_indirect_refs(struct btrfs_backref_walk_ctx *ctx,
  650. struct btrfs_path *path,
  651. struct preftrees *preftrees,
  652. struct share_check *sc)
  653. {
  654. int ret = 0;
  655. struct ulist *parents;
  656. struct ulist_node *node;
  657. struct ulist_iterator uiter;
  658. struct rb_node *rnode;
  659. parents = ulist_alloc(GFP_NOFS);
  660. if (!parents)
  661. return -ENOMEM;
  662. /*
  663. * We could trade memory usage for performance here by iterating
  664. * the tree, allocating new refs for each insertion, and then
  665. * freeing the entire indirect tree when we're done. In some test
  666. * cases, the tree can grow quite large (~200k objects).
  667. */
  668. while ((rnode = rb_first_cached(&preftrees->indirect.root))) {
  669. struct prelim_ref *ref;
  670. int ret2;
  671. ref = rb_entry(rnode, struct prelim_ref, rbnode);
  672. if (WARN(ref->parent,
  673. "BUG: direct ref found in indirect tree")) {
  674. ret = -EINVAL;
  675. goto out;
  676. }
  677. rb_erase_cached(&ref->rbnode, &preftrees->indirect.root);
  678. preftrees->indirect.count--;
  679. if (ref->count == 0) {
  680. free_pref(ref);
  681. continue;
  682. }
  683. if (sc && ref->root_id != btrfs_root_id(sc->root)) {
  684. free_pref(ref);
  685. ret = BACKREF_FOUND_SHARED;
  686. goto out;
  687. }
  688. ret2 = resolve_indirect_ref(ctx, path, preftrees, ref, parents);
  689. /*
  690. * we can only tolerate ENOENT,otherwise,we should catch error
  691. * and return directly.
  692. */
  693. if (ret2 == -ENOENT) {
  694. prelim_ref_insert(ctx->fs_info, &preftrees->direct, ref,
  695. NULL);
  696. continue;
  697. } else if (ret2) {
  698. free_pref(ref);
  699. ret = ret2;
  700. goto out;
  701. }
  702. /* we put the first parent into the ref at hand */
  703. ULIST_ITER_INIT(&uiter);
  704. node = ulist_next(parents, &uiter);
  705. ref->parent = node ? node->val : 0;
  706. ref->inode_list = unode_aux_to_inode_list(node);
  707. /* Add a prelim_ref(s) for any other parent(s). */
  708. while ((node = ulist_next(parents, &uiter))) {
  709. struct prelim_ref *new_ref;
  710. new_ref = kmem_cache_alloc(btrfs_prelim_ref_cache,
  711. GFP_NOFS);
  712. if (!new_ref) {
  713. free_pref(ref);
  714. ret = -ENOMEM;
  715. goto out;
  716. }
  717. memcpy(new_ref, ref, sizeof(*ref));
  718. new_ref->parent = node->val;
  719. new_ref->inode_list = unode_aux_to_inode_list(node);
  720. prelim_ref_insert(ctx->fs_info, &preftrees->direct,
  721. new_ref, NULL);
  722. }
  723. /*
  724. * Now it's a direct ref, put it in the direct tree. We must
  725. * do this last because the ref could be merged/freed here.
  726. */
  727. prelim_ref_insert(ctx->fs_info, &preftrees->direct, ref, NULL);
  728. ulist_reinit(parents);
  729. cond_resched();
  730. }
  731. out:
  732. /*
  733. * We may have inode lists attached to refs in the parents ulist, so we
  734. * must free them before freeing the ulist and its refs.
  735. */
  736. free_leaf_list(parents);
  737. return ret;
  738. }
  739. /*
  740. * read tree blocks and add keys where required.
  741. */
  742. static int add_missing_keys(struct btrfs_fs_info *fs_info,
  743. struct preftrees *preftrees, bool lock)
  744. {
  745. struct prelim_ref *ref;
  746. struct extent_buffer *eb;
  747. struct preftree *tree = &preftrees->indirect_missing_keys;
  748. struct rb_node *node;
  749. while ((node = rb_first_cached(&tree->root))) {
  750. struct btrfs_tree_parent_check check = { 0 };
  751. ref = rb_entry(node, struct prelim_ref, rbnode);
  752. rb_erase_cached(node, &tree->root);
  753. BUG_ON(ref->parent); /* should not be a direct ref */
  754. BUG_ON(ref->key_for_search.type);
  755. BUG_ON(!ref->wanted_disk_byte);
  756. check.level = ref->level - 1;
  757. check.owner_root = ref->root_id;
  758. eb = read_tree_block(fs_info, ref->wanted_disk_byte, &check);
  759. if (IS_ERR(eb)) {
  760. free_pref(ref);
  761. return PTR_ERR(eb);
  762. }
  763. if (unlikely(!extent_buffer_uptodate(eb))) {
  764. free_pref(ref);
  765. free_extent_buffer(eb);
  766. return -EIO;
  767. }
  768. if (lock)
  769. btrfs_tree_read_lock(eb);
  770. if (btrfs_header_level(eb) == 0)
  771. btrfs_item_key_to_cpu(eb, &ref->key_for_search, 0);
  772. else
  773. btrfs_node_key_to_cpu(eb, &ref->key_for_search, 0);
  774. if (lock)
  775. btrfs_tree_read_unlock(eb);
  776. free_extent_buffer(eb);
  777. prelim_ref_insert(fs_info, &preftrees->indirect, ref, NULL);
  778. cond_resched();
  779. }
  780. return 0;
  781. }
  782. /*
  783. * add all currently queued delayed refs from this head whose seq nr is
  784. * smaller or equal that seq to the list
  785. */
  786. static int add_delayed_refs(const struct btrfs_fs_info *fs_info,
  787. struct btrfs_delayed_ref_head *head, u64 seq,
  788. struct preftrees *preftrees, struct share_check *sc)
  789. {
  790. struct btrfs_delayed_ref_node *node;
  791. struct btrfs_key key;
  792. struct rb_node *n;
  793. int count;
  794. int ret = 0;
  795. spin_lock(&head->lock);
  796. for (n = rb_first_cached(&head->ref_tree); n; n = rb_next(n)) {
  797. node = rb_entry(n, struct btrfs_delayed_ref_node,
  798. ref_node);
  799. if (node->seq > seq)
  800. continue;
  801. switch (node->action) {
  802. case BTRFS_ADD_DELAYED_EXTENT:
  803. case BTRFS_UPDATE_DELAYED_HEAD:
  804. WARN_ON(1);
  805. continue;
  806. case BTRFS_ADD_DELAYED_REF:
  807. count = node->ref_mod;
  808. break;
  809. case BTRFS_DROP_DELAYED_REF:
  810. count = node->ref_mod * -1;
  811. break;
  812. default:
  813. BUG();
  814. }
  815. switch (node->type) {
  816. case BTRFS_TREE_BLOCK_REF_KEY: {
  817. /* NORMAL INDIRECT METADATA backref */
  818. struct btrfs_key *key_ptr = NULL;
  819. /* The owner of a tree block ref is the level. */
  820. int level = btrfs_delayed_ref_owner(node);
  821. if (head->extent_op && head->extent_op->update_key) {
  822. btrfs_disk_key_to_cpu(&key, &head->extent_op->key);
  823. key_ptr = &key;
  824. }
  825. ret = add_indirect_ref(fs_info, preftrees, node->ref_root,
  826. key_ptr, level + 1, node->bytenr,
  827. count, sc, GFP_ATOMIC);
  828. break;
  829. }
  830. case BTRFS_SHARED_BLOCK_REF_KEY: {
  831. /*
  832. * SHARED DIRECT METADATA backref
  833. *
  834. * The owner of a tree block ref is the level.
  835. */
  836. int level = btrfs_delayed_ref_owner(node);
  837. ret = add_direct_ref(fs_info, preftrees, level + 1,
  838. node->parent, node->bytenr, count,
  839. sc, GFP_ATOMIC);
  840. break;
  841. }
  842. case BTRFS_EXTENT_DATA_REF_KEY: {
  843. /* NORMAL INDIRECT DATA backref */
  844. key.objectid = btrfs_delayed_ref_owner(node);
  845. key.type = BTRFS_EXTENT_DATA_KEY;
  846. key.offset = btrfs_delayed_ref_offset(node);
  847. /*
  848. * If we have a share check context and a reference for
  849. * another inode, we can't exit immediately. This is
  850. * because even if this is a BTRFS_ADD_DELAYED_REF
  851. * reference we may find next a BTRFS_DROP_DELAYED_REF
  852. * which cancels out this ADD reference.
  853. *
  854. * If this is a DROP reference and there was no previous
  855. * ADD reference, then we need to signal that when we
  856. * process references from the extent tree (through
  857. * add_inline_refs() and add_keyed_refs()), we should
  858. * not exit early if we find a reference for another
  859. * inode, because one of the delayed DROP references
  860. * may cancel that reference in the extent tree.
  861. */
  862. if (sc && count < 0)
  863. sc->have_delayed_delete_refs = true;
  864. ret = add_indirect_ref(fs_info, preftrees, node->ref_root,
  865. &key, 0, node->bytenr, count, sc,
  866. GFP_ATOMIC);
  867. break;
  868. }
  869. case BTRFS_SHARED_DATA_REF_KEY: {
  870. /* SHARED DIRECT FULL backref */
  871. ret = add_direct_ref(fs_info, preftrees, 0, node->parent,
  872. node->bytenr, count, sc,
  873. GFP_ATOMIC);
  874. break;
  875. }
  876. default:
  877. WARN_ON(1);
  878. }
  879. /*
  880. * We must ignore BACKREF_FOUND_SHARED until all delayed
  881. * refs have been checked.
  882. */
  883. if (ret && (ret != BACKREF_FOUND_SHARED))
  884. break;
  885. }
  886. if (!ret)
  887. ret = extent_is_shared(sc);
  888. spin_unlock(&head->lock);
  889. return ret;
  890. }
  891. /*
  892. * add all inline backrefs for bytenr to the list
  893. *
  894. * Returns 0 on success, <0 on error, or BACKREF_FOUND_SHARED.
  895. */
  896. static int add_inline_refs(struct btrfs_backref_walk_ctx *ctx,
  897. struct btrfs_path *path,
  898. int *info_level, struct preftrees *preftrees,
  899. struct share_check *sc)
  900. {
  901. int ret = 0;
  902. int slot;
  903. struct extent_buffer *leaf;
  904. struct btrfs_key key;
  905. struct btrfs_key found_key;
  906. unsigned long ptr;
  907. unsigned long end;
  908. struct btrfs_extent_item *ei;
  909. u64 flags;
  910. u64 item_size;
  911. /*
  912. * enumerate all inline refs
  913. */
  914. leaf = path->nodes[0];
  915. slot = path->slots[0];
  916. item_size = btrfs_item_size(leaf, slot);
  917. ei = btrfs_item_ptr(leaf, slot, struct btrfs_extent_item);
  918. if (ctx->check_extent_item) {
  919. ret = ctx->check_extent_item(ctx->bytenr, ei, leaf, ctx->user_ctx);
  920. if (ret)
  921. return ret;
  922. }
  923. flags = btrfs_extent_flags(leaf, ei);
  924. btrfs_item_key_to_cpu(leaf, &found_key, slot);
  925. ptr = (unsigned long)(ei + 1);
  926. end = (unsigned long)ei + item_size;
  927. if (found_key.type == BTRFS_EXTENT_ITEM_KEY &&
  928. flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
  929. struct btrfs_tree_block_info *info;
  930. info = (struct btrfs_tree_block_info *)ptr;
  931. *info_level = btrfs_tree_block_level(leaf, info);
  932. ptr += sizeof(struct btrfs_tree_block_info);
  933. BUG_ON(ptr > end);
  934. } else if (found_key.type == BTRFS_METADATA_ITEM_KEY) {
  935. *info_level = found_key.offset;
  936. } else {
  937. BUG_ON(!(flags & BTRFS_EXTENT_FLAG_DATA));
  938. }
  939. while (ptr < end) {
  940. struct btrfs_extent_inline_ref *iref;
  941. u64 offset;
  942. int type;
  943. iref = (struct btrfs_extent_inline_ref *)ptr;
  944. type = btrfs_get_extent_inline_ref_type(leaf, iref,
  945. BTRFS_REF_TYPE_ANY);
  946. if (unlikely(type == BTRFS_REF_TYPE_INVALID))
  947. return -EUCLEAN;
  948. offset = btrfs_extent_inline_ref_offset(leaf, iref);
  949. switch (type) {
  950. case BTRFS_SHARED_BLOCK_REF_KEY:
  951. ret = add_direct_ref(ctx->fs_info, preftrees,
  952. *info_level + 1, offset,
  953. ctx->bytenr, 1, NULL, GFP_NOFS);
  954. break;
  955. case BTRFS_SHARED_DATA_REF_KEY: {
  956. struct btrfs_shared_data_ref *sdref;
  957. int count;
  958. sdref = (struct btrfs_shared_data_ref *)(iref + 1);
  959. count = btrfs_shared_data_ref_count(leaf, sdref);
  960. ret = add_direct_ref(ctx->fs_info, preftrees, 0, offset,
  961. ctx->bytenr, count, sc, GFP_NOFS);
  962. break;
  963. }
  964. case BTRFS_TREE_BLOCK_REF_KEY:
  965. ret = add_indirect_ref(ctx->fs_info, preftrees, offset,
  966. NULL, *info_level + 1,
  967. ctx->bytenr, 1, NULL, GFP_NOFS);
  968. break;
  969. case BTRFS_EXTENT_DATA_REF_KEY: {
  970. struct btrfs_extent_data_ref *dref;
  971. int count;
  972. u64 root;
  973. dref = (struct btrfs_extent_data_ref *)(&iref->offset);
  974. count = btrfs_extent_data_ref_count(leaf, dref);
  975. key.objectid = btrfs_extent_data_ref_objectid(leaf,
  976. dref);
  977. key.type = BTRFS_EXTENT_DATA_KEY;
  978. key.offset = btrfs_extent_data_ref_offset(leaf, dref);
  979. if (sc && key.objectid != sc->inum &&
  980. !sc->have_delayed_delete_refs) {
  981. ret = BACKREF_FOUND_SHARED;
  982. break;
  983. }
  984. root = btrfs_extent_data_ref_root(leaf, dref);
  985. if (!ctx->skip_data_ref ||
  986. !ctx->skip_data_ref(root, key.objectid, key.offset,
  987. ctx->user_ctx))
  988. ret = add_indirect_ref(ctx->fs_info, preftrees,
  989. root, &key, 0, ctx->bytenr,
  990. count, sc, GFP_NOFS);
  991. break;
  992. }
  993. case BTRFS_EXTENT_OWNER_REF_KEY:
  994. ASSERT(btrfs_fs_incompat(ctx->fs_info, SIMPLE_QUOTA));
  995. break;
  996. default:
  997. WARN_ON(1);
  998. }
  999. if (ret)
  1000. return ret;
  1001. ptr += btrfs_extent_inline_ref_size(type);
  1002. }
  1003. return 0;
  1004. }
  1005. /*
  1006. * add all non-inline backrefs for bytenr to the list
  1007. *
  1008. * Returns 0 on success, <0 on error, or BACKREF_FOUND_SHARED.
  1009. */
  1010. static int add_keyed_refs(struct btrfs_backref_walk_ctx *ctx,
  1011. struct btrfs_root *extent_root,
  1012. struct btrfs_path *path,
  1013. int info_level, struct preftrees *preftrees,
  1014. struct share_check *sc)
  1015. {
  1016. struct btrfs_fs_info *fs_info = extent_root->fs_info;
  1017. int ret;
  1018. int slot;
  1019. struct extent_buffer *leaf;
  1020. struct btrfs_key key;
  1021. while (1) {
  1022. ret = btrfs_next_item(extent_root, path);
  1023. if (ret < 0)
  1024. break;
  1025. if (ret) {
  1026. ret = 0;
  1027. break;
  1028. }
  1029. slot = path->slots[0];
  1030. leaf = path->nodes[0];
  1031. btrfs_item_key_to_cpu(leaf, &key, slot);
  1032. if (key.objectid != ctx->bytenr)
  1033. break;
  1034. if (key.type < BTRFS_TREE_BLOCK_REF_KEY)
  1035. continue;
  1036. if (key.type > BTRFS_SHARED_DATA_REF_KEY)
  1037. break;
  1038. switch (key.type) {
  1039. case BTRFS_SHARED_BLOCK_REF_KEY:
  1040. /* SHARED DIRECT METADATA backref */
  1041. ret = add_direct_ref(fs_info, preftrees,
  1042. info_level + 1, key.offset,
  1043. ctx->bytenr, 1, NULL, GFP_NOFS);
  1044. break;
  1045. case BTRFS_SHARED_DATA_REF_KEY: {
  1046. /* SHARED DIRECT FULL backref */
  1047. struct btrfs_shared_data_ref *sdref;
  1048. int count;
  1049. sdref = btrfs_item_ptr(leaf, slot,
  1050. struct btrfs_shared_data_ref);
  1051. count = btrfs_shared_data_ref_count(leaf, sdref);
  1052. ret = add_direct_ref(fs_info, preftrees, 0,
  1053. key.offset, ctx->bytenr, count,
  1054. sc, GFP_NOFS);
  1055. break;
  1056. }
  1057. case BTRFS_TREE_BLOCK_REF_KEY:
  1058. /* NORMAL INDIRECT METADATA backref */
  1059. ret = add_indirect_ref(fs_info, preftrees, key.offset,
  1060. NULL, info_level + 1, ctx->bytenr,
  1061. 1, NULL, GFP_NOFS);
  1062. break;
  1063. case BTRFS_EXTENT_DATA_REF_KEY: {
  1064. /* NORMAL INDIRECT DATA backref */
  1065. struct btrfs_extent_data_ref *dref;
  1066. int count;
  1067. u64 root;
  1068. dref = btrfs_item_ptr(leaf, slot,
  1069. struct btrfs_extent_data_ref);
  1070. count = btrfs_extent_data_ref_count(leaf, dref);
  1071. key.objectid = btrfs_extent_data_ref_objectid(leaf,
  1072. dref);
  1073. key.type = BTRFS_EXTENT_DATA_KEY;
  1074. key.offset = btrfs_extent_data_ref_offset(leaf, dref);
  1075. if (sc && key.objectid != sc->inum &&
  1076. !sc->have_delayed_delete_refs) {
  1077. ret = BACKREF_FOUND_SHARED;
  1078. break;
  1079. }
  1080. root = btrfs_extent_data_ref_root(leaf, dref);
  1081. if (!ctx->skip_data_ref ||
  1082. !ctx->skip_data_ref(root, key.objectid, key.offset,
  1083. ctx->user_ctx))
  1084. ret = add_indirect_ref(fs_info, preftrees, root,
  1085. &key, 0, ctx->bytenr,
  1086. count, sc, GFP_NOFS);
  1087. break;
  1088. }
  1089. default:
  1090. WARN_ON(1);
  1091. }
  1092. if (ret)
  1093. return ret;
  1094. }
  1095. return ret;
  1096. }
  1097. /*
  1098. * The caller has joined a transaction or is holding a read lock on the
  1099. * fs_info->commit_root_sem semaphore, so no need to worry about the root's last
  1100. * snapshot field changing while updating or checking the cache.
  1101. */
  1102. static bool lookup_backref_shared_cache(struct btrfs_backref_share_check_ctx *ctx,
  1103. struct btrfs_root *root,
  1104. u64 bytenr, int level, bool *is_shared)
  1105. {
  1106. const struct btrfs_fs_info *fs_info = root->fs_info;
  1107. struct btrfs_backref_shared_cache_entry *entry;
  1108. if (!current->journal_info)
  1109. lockdep_assert_held(&fs_info->commit_root_sem);
  1110. if (!ctx->use_path_cache)
  1111. return false;
  1112. if (WARN_ON_ONCE(level >= BTRFS_MAX_LEVEL))
  1113. return false;
  1114. /*
  1115. * Level -1 is used for the data extent, which is not reliable to cache
  1116. * because its reference count can increase or decrease without us
  1117. * realizing. We cache results only for extent buffers that lead from
  1118. * the root node down to the leaf with the file extent item.
  1119. */
  1120. ASSERT(level >= 0);
  1121. entry = &ctx->path_cache_entries[level];
  1122. /* Unused cache entry or being used for some other extent buffer. */
  1123. if (entry->bytenr != bytenr)
  1124. return false;
  1125. /*
  1126. * We cached a false result, but the last snapshot generation of the
  1127. * root changed, so we now have a snapshot. Don't trust the result.
  1128. */
  1129. if (!entry->is_shared &&
  1130. entry->gen != btrfs_root_last_snapshot(&root->root_item))
  1131. return false;
  1132. /*
  1133. * If we cached a true result and the last generation used for dropping
  1134. * a root changed, we can not trust the result, because the dropped root
  1135. * could be a snapshot sharing this extent buffer.
  1136. */
  1137. if (entry->is_shared &&
  1138. entry->gen != btrfs_get_last_root_drop_gen(fs_info))
  1139. return false;
  1140. *is_shared = entry->is_shared;
  1141. /*
  1142. * If the node at this level is shared, than all nodes below are also
  1143. * shared. Currently some of the nodes below may be marked as not shared
  1144. * because we have just switched from one leaf to another, and switched
  1145. * also other nodes above the leaf and below the current level, so mark
  1146. * them as shared.
  1147. */
  1148. if (*is_shared) {
  1149. for (int i = 0; i < level; i++) {
  1150. ctx->path_cache_entries[i].is_shared = true;
  1151. ctx->path_cache_entries[i].gen = entry->gen;
  1152. }
  1153. }
  1154. return true;
  1155. }
  1156. /*
  1157. * The caller has joined a transaction or is holding a read lock on the
  1158. * fs_info->commit_root_sem semaphore, so no need to worry about the root's last
  1159. * snapshot field changing while updating or checking the cache.
  1160. */
  1161. static void store_backref_shared_cache(struct btrfs_backref_share_check_ctx *ctx,
  1162. struct btrfs_root *root,
  1163. u64 bytenr, int level, bool is_shared)
  1164. {
  1165. const struct btrfs_fs_info *fs_info = root->fs_info;
  1166. struct btrfs_backref_shared_cache_entry *entry;
  1167. u64 gen;
  1168. if (!current->journal_info)
  1169. lockdep_assert_held(&fs_info->commit_root_sem);
  1170. if (!ctx->use_path_cache)
  1171. return;
  1172. if (WARN_ON_ONCE(level >= BTRFS_MAX_LEVEL))
  1173. return;
  1174. /*
  1175. * Level -1 is used for the data extent, which is not reliable to cache
  1176. * because its reference count can increase or decrease without us
  1177. * realizing. We cache results only for extent buffers that lead from
  1178. * the root node down to the leaf with the file extent item.
  1179. */
  1180. ASSERT(level >= 0);
  1181. if (is_shared)
  1182. gen = btrfs_get_last_root_drop_gen(fs_info);
  1183. else
  1184. gen = btrfs_root_last_snapshot(&root->root_item);
  1185. entry = &ctx->path_cache_entries[level];
  1186. entry->bytenr = bytenr;
  1187. entry->is_shared = is_shared;
  1188. entry->gen = gen;
  1189. /*
  1190. * If we found an extent buffer is shared, set the cache result for all
  1191. * extent buffers below it to true. As nodes in the path are COWed,
  1192. * their sharedness is moved to their children, and if a leaf is COWed,
  1193. * then the sharedness of a data extent becomes direct, the refcount of
  1194. * data extent is increased in the extent item at the extent tree.
  1195. */
  1196. if (is_shared) {
  1197. for (int i = 0; i < level; i++) {
  1198. entry = &ctx->path_cache_entries[i];
  1199. entry->is_shared = is_shared;
  1200. entry->gen = gen;
  1201. }
  1202. }
  1203. }
  1204. /*
  1205. * this adds all existing backrefs (inline backrefs, backrefs and delayed
  1206. * refs) for the given bytenr to the refs list, merges duplicates and resolves
  1207. * indirect refs to their parent bytenr.
  1208. * When roots are found, they're added to the roots list
  1209. *
  1210. * @ctx: Backref walking context object, must be not NULL.
  1211. * @sc: If !NULL, then immediately return BACKREF_FOUND_SHARED when a
  1212. * shared extent is detected.
  1213. *
  1214. * Otherwise this returns 0 for success and <0 for an error.
  1215. *
  1216. * FIXME some caching might speed things up
  1217. */
  1218. static int find_parent_nodes(struct btrfs_backref_walk_ctx *ctx,
  1219. struct share_check *sc)
  1220. {
  1221. struct btrfs_root *root = btrfs_extent_root(ctx->fs_info, ctx->bytenr);
  1222. struct btrfs_key key;
  1223. struct btrfs_path *path;
  1224. struct btrfs_delayed_ref_root *delayed_refs = NULL;
  1225. struct btrfs_delayed_ref_head *head;
  1226. int info_level = 0;
  1227. int ret;
  1228. struct prelim_ref *ref;
  1229. struct rb_node *node;
  1230. struct extent_inode_elem *eie = NULL;
  1231. struct preftrees preftrees = {
  1232. .direct = PREFTREE_INIT,
  1233. .indirect = PREFTREE_INIT,
  1234. .indirect_missing_keys = PREFTREE_INIT
  1235. };
  1236. if (unlikely(!root)) {
  1237. btrfs_err(ctx->fs_info,
  1238. "missing extent root for extent at bytenr %llu",
  1239. ctx->bytenr);
  1240. return -EUCLEAN;
  1241. }
  1242. /* Roots ulist is not needed when using a sharedness check context. */
  1243. if (sc)
  1244. ASSERT(ctx->roots == NULL);
  1245. key.objectid = ctx->bytenr;
  1246. if (btrfs_fs_incompat(ctx->fs_info, SKINNY_METADATA))
  1247. key.type = BTRFS_METADATA_ITEM_KEY;
  1248. else
  1249. key.type = BTRFS_EXTENT_ITEM_KEY;
  1250. key.offset = (u64)-1;
  1251. path = btrfs_alloc_path();
  1252. if (!path)
  1253. return -ENOMEM;
  1254. if (!ctx->trans) {
  1255. path->search_commit_root = true;
  1256. path->skip_locking = true;
  1257. }
  1258. if (ctx->time_seq == BTRFS_SEQ_LAST)
  1259. path->skip_locking = true;
  1260. again:
  1261. head = NULL;
  1262. ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
  1263. if (ret < 0)
  1264. goto out;
  1265. if (unlikely(ret == 0)) {
  1266. /*
  1267. * Key with offset -1 found, there would have to exist an extent
  1268. * item with such offset, but this is out of the valid range.
  1269. */
  1270. ret = -EUCLEAN;
  1271. goto out;
  1272. }
  1273. if (ctx->trans && likely(ctx->trans->type != __TRANS_DUMMY) &&
  1274. ctx->time_seq != BTRFS_SEQ_LAST) {
  1275. /*
  1276. * We have a specific time_seq we care about and trans which
  1277. * means we have the path lock, we need to grab the ref head and
  1278. * lock it so we have a consistent view of the refs at the given
  1279. * time.
  1280. */
  1281. delayed_refs = &ctx->trans->transaction->delayed_refs;
  1282. spin_lock(&delayed_refs->lock);
  1283. head = btrfs_find_delayed_ref_head(ctx->fs_info, delayed_refs,
  1284. ctx->bytenr);
  1285. if (head) {
  1286. if (!mutex_trylock(&head->mutex)) {
  1287. refcount_inc(&head->refs);
  1288. spin_unlock(&delayed_refs->lock);
  1289. btrfs_release_path(path);
  1290. /*
  1291. * Mutex was contended, block until it's
  1292. * released and try again
  1293. */
  1294. mutex_lock(&head->mutex);
  1295. mutex_unlock(&head->mutex);
  1296. btrfs_put_delayed_ref_head(head);
  1297. goto again;
  1298. }
  1299. spin_unlock(&delayed_refs->lock);
  1300. ret = add_delayed_refs(ctx->fs_info, head, ctx->time_seq,
  1301. &preftrees, sc);
  1302. mutex_unlock(&head->mutex);
  1303. if (ret)
  1304. goto out;
  1305. } else {
  1306. spin_unlock(&delayed_refs->lock);
  1307. }
  1308. }
  1309. if (path->slots[0]) {
  1310. struct extent_buffer *leaf;
  1311. int slot;
  1312. path->slots[0]--;
  1313. leaf = path->nodes[0];
  1314. slot = path->slots[0];
  1315. btrfs_item_key_to_cpu(leaf, &key, slot);
  1316. if (key.objectid == ctx->bytenr &&
  1317. (key.type == BTRFS_EXTENT_ITEM_KEY ||
  1318. key.type == BTRFS_METADATA_ITEM_KEY)) {
  1319. ret = add_inline_refs(ctx, path, &info_level,
  1320. &preftrees, sc);
  1321. if (ret)
  1322. goto out;
  1323. ret = add_keyed_refs(ctx, root, path, info_level,
  1324. &preftrees, sc);
  1325. if (ret)
  1326. goto out;
  1327. }
  1328. }
  1329. /*
  1330. * If we have a share context and we reached here, it means the extent
  1331. * is not directly shared (no multiple reference items for it),
  1332. * otherwise we would have exited earlier with a return value of
  1333. * BACKREF_FOUND_SHARED after processing delayed references or while
  1334. * processing inline or keyed references from the extent tree.
  1335. * The extent may however be indirectly shared through shared subtrees
  1336. * as a result from creating snapshots, so we determine below what is
  1337. * its parent node, in case we are dealing with a metadata extent, or
  1338. * what's the leaf (or leaves), from a fs tree, that has a file extent
  1339. * item pointing to it in case we are dealing with a data extent.
  1340. */
  1341. ASSERT(extent_is_shared(sc) == 0);
  1342. /*
  1343. * If we are here for a data extent and we have a share_check structure
  1344. * it means the data extent is not directly shared (does not have
  1345. * multiple reference items), so we have to check if a path in the fs
  1346. * tree (going from the root node down to the leaf that has the file
  1347. * extent item pointing to the data extent) is shared, that is, if any
  1348. * of the extent buffers in the path is referenced by other trees.
  1349. */
  1350. if (sc && ctx->bytenr == sc->data_bytenr) {
  1351. /*
  1352. * If our data extent is from a generation more recent than the
  1353. * last generation used to snapshot the root, then we know that
  1354. * it can not be shared through subtrees, so we can skip
  1355. * resolving indirect references, there's no point in
  1356. * determining the extent buffers for the path from the fs tree
  1357. * root node down to the leaf that has the file extent item that
  1358. * points to the data extent.
  1359. */
  1360. if (sc->data_extent_gen >
  1361. btrfs_root_last_snapshot(&sc->root->root_item)) {
  1362. ret = BACKREF_FOUND_NOT_SHARED;
  1363. goto out;
  1364. }
  1365. /*
  1366. * If we are only determining if a data extent is shared or not
  1367. * and the corresponding file extent item is located in the same
  1368. * leaf as the previous file extent item, we can skip resolving
  1369. * indirect references for a data extent, since the fs tree path
  1370. * is the same (same leaf, so same path). We skip as long as the
  1371. * cached result for the leaf is valid and only if there's only
  1372. * one file extent item pointing to the data extent, because in
  1373. * the case of multiple file extent items, they may be located
  1374. * in different leaves and therefore we have multiple paths.
  1375. */
  1376. if (sc->ctx->curr_leaf_bytenr == sc->ctx->prev_leaf_bytenr &&
  1377. sc->self_ref_count == 1) {
  1378. bool cached;
  1379. bool is_shared;
  1380. cached = lookup_backref_shared_cache(sc->ctx, sc->root,
  1381. sc->ctx->curr_leaf_bytenr,
  1382. 0, &is_shared);
  1383. if (cached) {
  1384. if (is_shared)
  1385. ret = BACKREF_FOUND_SHARED;
  1386. else
  1387. ret = BACKREF_FOUND_NOT_SHARED;
  1388. goto out;
  1389. }
  1390. }
  1391. }
  1392. btrfs_release_path(path);
  1393. ret = add_missing_keys(ctx->fs_info, &preftrees, !path->skip_locking);
  1394. if (ret)
  1395. goto out;
  1396. WARN_ON(!RB_EMPTY_ROOT(&preftrees.indirect_missing_keys.root.rb_root));
  1397. ret = resolve_indirect_refs(ctx, path, &preftrees, sc);
  1398. if (ret)
  1399. goto out;
  1400. WARN_ON(!RB_EMPTY_ROOT(&preftrees.indirect.root.rb_root));
  1401. /*
  1402. * This walks the tree of merged and resolved refs. Tree blocks are
  1403. * read in as needed. Unique entries are added to the ulist, and
  1404. * the list of found roots is updated.
  1405. *
  1406. * We release the entire tree in one go before returning.
  1407. */
  1408. node = rb_first_cached(&preftrees.direct.root);
  1409. while (node) {
  1410. ref = rb_entry(node, struct prelim_ref, rbnode);
  1411. node = rb_next(&ref->rbnode);
  1412. /*
  1413. * ref->count < 0 can happen here if there are delayed
  1414. * refs with a node->action of BTRFS_DROP_DELAYED_REF.
  1415. * prelim_ref_insert() relies on this when merging
  1416. * identical refs to keep the overall count correct.
  1417. * prelim_ref_insert() will merge only those refs
  1418. * which compare identically. Any refs having
  1419. * e.g. different offsets would not be merged,
  1420. * and would retain their original ref->count < 0.
  1421. */
  1422. if (ctx->roots && ref->count && ref->root_id && ref->parent == 0) {
  1423. /* no parent == root of tree */
  1424. ret = ulist_add(ctx->roots, ref->root_id, 0, GFP_NOFS);
  1425. if (ret < 0)
  1426. goto out;
  1427. }
  1428. if (ref->count && ref->parent) {
  1429. if (!ctx->skip_inode_ref_list && !ref->inode_list &&
  1430. ref->level == 0) {
  1431. struct btrfs_tree_parent_check check = { 0 };
  1432. struct extent_buffer *eb;
  1433. check.level = ref->level;
  1434. eb = read_tree_block(ctx->fs_info, ref->parent,
  1435. &check);
  1436. if (IS_ERR(eb)) {
  1437. ret = PTR_ERR(eb);
  1438. goto out;
  1439. }
  1440. if (unlikely(!extent_buffer_uptodate(eb))) {
  1441. free_extent_buffer(eb);
  1442. ret = -EIO;
  1443. goto out;
  1444. }
  1445. if (!path->skip_locking)
  1446. btrfs_tree_read_lock(eb);
  1447. ret = find_extent_in_eb(ctx, eb, &eie);
  1448. if (!path->skip_locking)
  1449. btrfs_tree_read_unlock(eb);
  1450. free_extent_buffer(eb);
  1451. if (ret == BTRFS_ITERATE_EXTENT_INODES_STOP ||
  1452. ret < 0)
  1453. goto out;
  1454. ref->inode_list = eie;
  1455. /*
  1456. * We transferred the list ownership to the ref,
  1457. * so set to NULL to avoid a double free in case
  1458. * an error happens after this.
  1459. */
  1460. eie = NULL;
  1461. }
  1462. ret = ulist_add_merge_ptr(ctx->refs, ref->parent,
  1463. ref->inode_list,
  1464. (void **)&eie, GFP_NOFS);
  1465. if (ret < 0)
  1466. goto out;
  1467. if (!ret && !ctx->skip_inode_ref_list) {
  1468. /*
  1469. * We've recorded that parent, so we must extend
  1470. * its inode list here.
  1471. *
  1472. * However if there was corruption we may not
  1473. * have found an eie, return an error in this
  1474. * case.
  1475. */
  1476. ASSERT(eie);
  1477. if (unlikely(!eie)) {
  1478. ret = -EUCLEAN;
  1479. goto out;
  1480. }
  1481. while (eie->next)
  1482. eie = eie->next;
  1483. eie->next = ref->inode_list;
  1484. }
  1485. eie = NULL;
  1486. /*
  1487. * We have transferred the inode list ownership from
  1488. * this ref to the ref we added to the 'refs' ulist.
  1489. * So set this ref's inode list to NULL to avoid
  1490. * use-after-free when our caller uses it or double
  1491. * frees in case an error happens before we return.
  1492. */
  1493. ref->inode_list = NULL;
  1494. }
  1495. cond_resched();
  1496. }
  1497. out:
  1498. btrfs_free_path(path);
  1499. prelim_release(&preftrees.direct);
  1500. prelim_release(&preftrees.indirect);
  1501. prelim_release(&preftrees.indirect_missing_keys);
  1502. if (ret == BTRFS_ITERATE_EXTENT_INODES_STOP || ret < 0)
  1503. free_inode_elem_list(eie);
  1504. return ret;
  1505. }
  1506. /*
  1507. * Finds all leaves with a reference to the specified combination of
  1508. * @ctx->bytenr and @ctx->extent_item_pos. The bytenr of the found leaves are
  1509. * added to the ulist at @ctx->refs, and that ulist is allocated by this
  1510. * function. The caller should free the ulist with free_leaf_list() if
  1511. * @ctx->ignore_extent_item_pos is false, otherwise a simple ulist_free() is
  1512. * enough.
  1513. *
  1514. * Returns 0 on success and < 0 on error. On error @ctx->refs is not allocated.
  1515. */
  1516. int btrfs_find_all_leafs(struct btrfs_backref_walk_ctx *ctx)
  1517. {
  1518. int ret;
  1519. ASSERT(ctx->refs == NULL);
  1520. ctx->refs = ulist_alloc(GFP_NOFS);
  1521. if (!ctx->refs)
  1522. return -ENOMEM;
  1523. ret = find_parent_nodes(ctx, NULL);
  1524. if (ret == BTRFS_ITERATE_EXTENT_INODES_STOP ||
  1525. (ret < 0 && ret != -ENOENT)) {
  1526. free_leaf_list(ctx->refs);
  1527. ctx->refs = NULL;
  1528. return ret;
  1529. }
  1530. return 0;
  1531. }
  1532. /*
  1533. * Walk all backrefs for a given extent to find all roots that reference this
  1534. * extent. Walking a backref means finding all extents that reference this
  1535. * extent and in turn walk the backrefs of those, too. Naturally this is a
  1536. * recursive process, but here it is implemented in an iterative fashion: We
  1537. * find all referencing extents for the extent in question and put them on a
  1538. * list. In turn, we find all referencing extents for those, further appending
  1539. * to the list. The way we iterate the list allows adding more elements after
  1540. * the current while iterating. The process stops when we reach the end of the
  1541. * list.
  1542. *
  1543. * Found roots are added to @ctx->roots, which is allocated by this function if
  1544. * it points to NULL, in which case the caller is responsible for freeing it
  1545. * after it's not needed anymore.
  1546. * This function requires @ctx->refs to be NULL, as it uses it for allocating a
  1547. * ulist to do temporary work, and frees it before returning.
  1548. *
  1549. * Returns 0 on success, < 0 on error.
  1550. */
  1551. static int btrfs_find_all_roots_safe(struct btrfs_backref_walk_ctx *ctx)
  1552. {
  1553. const u64 orig_bytenr = ctx->bytenr;
  1554. const bool orig_skip_inode_ref_list = ctx->skip_inode_ref_list;
  1555. bool roots_ulist_allocated = false;
  1556. struct ulist_iterator uiter;
  1557. int ret = 0;
  1558. ASSERT(ctx->refs == NULL);
  1559. ctx->refs = ulist_alloc(GFP_NOFS);
  1560. if (!ctx->refs)
  1561. return -ENOMEM;
  1562. if (!ctx->roots) {
  1563. ctx->roots = ulist_alloc(GFP_NOFS);
  1564. if (!ctx->roots) {
  1565. ulist_free(ctx->refs);
  1566. ctx->refs = NULL;
  1567. return -ENOMEM;
  1568. }
  1569. roots_ulist_allocated = true;
  1570. }
  1571. ctx->skip_inode_ref_list = true;
  1572. ULIST_ITER_INIT(&uiter);
  1573. while (1) {
  1574. struct ulist_node *node;
  1575. ret = find_parent_nodes(ctx, NULL);
  1576. if (ret < 0 && ret != -ENOENT) {
  1577. if (roots_ulist_allocated) {
  1578. ulist_free(ctx->roots);
  1579. ctx->roots = NULL;
  1580. }
  1581. break;
  1582. }
  1583. ret = 0;
  1584. node = ulist_next(ctx->refs, &uiter);
  1585. if (!node)
  1586. break;
  1587. ctx->bytenr = node->val;
  1588. cond_resched();
  1589. }
  1590. ulist_free(ctx->refs);
  1591. ctx->refs = NULL;
  1592. ctx->bytenr = orig_bytenr;
  1593. ctx->skip_inode_ref_list = orig_skip_inode_ref_list;
  1594. return ret;
  1595. }
  1596. int btrfs_find_all_roots(struct btrfs_backref_walk_ctx *ctx,
  1597. bool skip_commit_root_sem)
  1598. {
  1599. int ret;
  1600. if (!ctx->trans && !skip_commit_root_sem)
  1601. down_read(&ctx->fs_info->commit_root_sem);
  1602. ret = btrfs_find_all_roots_safe(ctx);
  1603. if (!ctx->trans && !skip_commit_root_sem)
  1604. up_read(&ctx->fs_info->commit_root_sem);
  1605. return ret;
  1606. }
  1607. struct btrfs_backref_share_check_ctx *btrfs_alloc_backref_share_check_ctx(void)
  1608. {
  1609. struct btrfs_backref_share_check_ctx *ctx;
  1610. ctx = kzalloc_obj(*ctx);
  1611. if (!ctx)
  1612. return NULL;
  1613. ulist_init(&ctx->refs);
  1614. return ctx;
  1615. }
  1616. void btrfs_free_backref_share_ctx(struct btrfs_backref_share_check_ctx *ctx)
  1617. {
  1618. if (!ctx)
  1619. return;
  1620. ulist_release(&ctx->refs);
  1621. kfree(ctx);
  1622. }
  1623. /*
  1624. * Check if a data extent is shared or not.
  1625. *
  1626. * @inode: The inode whose extent we are checking.
  1627. * @bytenr: Logical bytenr of the extent we are checking.
  1628. * @extent_gen: Generation of the extent (file extent item) or 0 if it is
  1629. * not known.
  1630. * @ctx: A backref sharedness check context.
  1631. *
  1632. * btrfs_is_data_extent_shared uses the backref walking code but will short
  1633. * circuit as soon as it finds a root or inode that doesn't match the
  1634. * one passed in. This provides a significant performance benefit for
  1635. * callers (such as fiemap) which want to know whether the extent is
  1636. * shared but do not need a ref count.
  1637. *
  1638. * This attempts to attach to the running transaction in order to account for
  1639. * delayed refs, but continues on even when no running transaction exists.
  1640. *
  1641. * Return: 0 if extent is not shared, 1 if it is shared, < 0 on error.
  1642. */
  1643. int btrfs_is_data_extent_shared(struct btrfs_inode *inode, u64 bytenr,
  1644. u64 extent_gen,
  1645. struct btrfs_backref_share_check_ctx *ctx)
  1646. {
  1647. struct btrfs_backref_walk_ctx walk_ctx = { 0 };
  1648. struct btrfs_root *root = inode->root;
  1649. struct btrfs_fs_info *fs_info = root->fs_info;
  1650. struct btrfs_trans_handle *trans;
  1651. struct ulist_iterator uiter;
  1652. struct ulist_node *node;
  1653. struct btrfs_seq_list elem = BTRFS_SEQ_LIST_INIT(elem);
  1654. int ret = 0;
  1655. struct share_check shared = {
  1656. .ctx = ctx,
  1657. .root = root,
  1658. .inum = btrfs_ino(inode),
  1659. .data_bytenr = bytenr,
  1660. .data_extent_gen = extent_gen,
  1661. .share_count = 0,
  1662. .self_ref_count = 0,
  1663. .have_delayed_delete_refs = false,
  1664. };
  1665. int level;
  1666. bool leaf_cached;
  1667. bool leaf_is_shared;
  1668. for (int i = 0; i < BTRFS_BACKREF_CTX_PREV_EXTENTS_SIZE; i++) {
  1669. if (ctx->prev_extents_cache[i].bytenr == bytenr)
  1670. return ctx->prev_extents_cache[i].is_shared;
  1671. }
  1672. ulist_init(&ctx->refs);
  1673. trans = btrfs_join_transaction_nostart(root);
  1674. if (IS_ERR(trans)) {
  1675. if (PTR_ERR(trans) != -ENOENT && PTR_ERR(trans) != -EROFS) {
  1676. ret = PTR_ERR(trans);
  1677. goto out;
  1678. }
  1679. trans = NULL;
  1680. down_read(&fs_info->commit_root_sem);
  1681. } else {
  1682. btrfs_get_tree_mod_seq(fs_info, &elem);
  1683. walk_ctx.time_seq = elem.seq;
  1684. }
  1685. ctx->use_path_cache = true;
  1686. /*
  1687. * We may have previously determined that the current leaf is shared.
  1688. * If it is, then we have a data extent that is shared due to a shared
  1689. * subtree (caused by snapshotting) and we don't need to check for data
  1690. * backrefs. If the leaf is not shared, then we must do backref walking
  1691. * to determine if the data extent is shared through reflinks.
  1692. */
  1693. leaf_cached = lookup_backref_shared_cache(ctx, root,
  1694. ctx->curr_leaf_bytenr, 0,
  1695. &leaf_is_shared);
  1696. if (leaf_cached && leaf_is_shared) {
  1697. ret = 1;
  1698. goto out_trans;
  1699. }
  1700. walk_ctx.skip_inode_ref_list = true;
  1701. walk_ctx.trans = trans;
  1702. walk_ctx.fs_info = fs_info;
  1703. walk_ctx.refs = &ctx->refs;
  1704. /* -1 means we are in the bytenr of the data extent. */
  1705. level = -1;
  1706. ULIST_ITER_INIT(&uiter);
  1707. while (1) {
  1708. const unsigned long prev_ref_count = ctx->refs.nnodes;
  1709. walk_ctx.bytenr = bytenr;
  1710. ret = find_parent_nodes(&walk_ctx, &shared);
  1711. if (ret == BACKREF_FOUND_SHARED ||
  1712. ret == BACKREF_FOUND_NOT_SHARED) {
  1713. /* If shared must return 1, otherwise return 0. */
  1714. ret = (ret == BACKREF_FOUND_SHARED) ? 1 : 0;
  1715. if (level >= 0)
  1716. store_backref_shared_cache(ctx, root, bytenr,
  1717. level, ret == 1);
  1718. break;
  1719. }
  1720. if (ret < 0 && ret != -ENOENT)
  1721. break;
  1722. ret = 0;
  1723. /*
  1724. * More than one extent buffer (bytenr) may have been added to
  1725. * the ctx->refs ulist, in which case we have to check multiple
  1726. * tree paths in case the first one is not shared, so we can not
  1727. * use the path cache which is made for a single path. Multiple
  1728. * extent buffers at the current level happen when:
  1729. *
  1730. * 1) level -1, the data extent: If our data extent was not
  1731. * directly shared (without multiple reference items), then
  1732. * it might have a single reference item with a count > 1 for
  1733. * the same offset, which means there are 2 (or more) file
  1734. * extent items that point to the data extent - this happens
  1735. * when a file extent item needs to be split and then one
  1736. * item gets moved to another leaf due to a b+tree leaf split
  1737. * when inserting some item. In this case the file extent
  1738. * items may be located in different leaves and therefore
  1739. * some of the leaves may be referenced through shared
  1740. * subtrees while others are not. Since our extent buffer
  1741. * cache only works for a single path (by far the most common
  1742. * case and simpler to deal with), we can not use it if we
  1743. * have multiple leaves (which implies multiple paths).
  1744. *
  1745. * 2) level >= 0, a tree node/leaf: We can have a mix of direct
  1746. * and indirect references on a b+tree node/leaf, so we have
  1747. * to check multiple paths, and the extent buffer (the
  1748. * current bytenr) may be shared or not. One example is
  1749. * during relocation as we may get a shared tree block ref
  1750. * (direct ref) and a non-shared tree block ref (indirect
  1751. * ref) for the same node/leaf.
  1752. */
  1753. if ((ctx->refs.nnodes - prev_ref_count) > 1)
  1754. ctx->use_path_cache = false;
  1755. if (level >= 0)
  1756. store_backref_shared_cache(ctx, root, bytenr,
  1757. level, false);
  1758. node = ulist_next(&ctx->refs, &uiter);
  1759. if (!node)
  1760. break;
  1761. bytenr = node->val;
  1762. if (ctx->use_path_cache) {
  1763. bool is_shared;
  1764. bool cached;
  1765. level++;
  1766. cached = lookup_backref_shared_cache(ctx, root, bytenr,
  1767. level, &is_shared);
  1768. if (cached) {
  1769. ret = (is_shared ? 1 : 0);
  1770. break;
  1771. }
  1772. }
  1773. shared.share_count = 0;
  1774. shared.have_delayed_delete_refs = false;
  1775. cond_resched();
  1776. }
  1777. /*
  1778. * If the path cache is disabled, then it means at some tree level we
  1779. * got multiple parents due to a mix of direct and indirect backrefs or
  1780. * multiple leaves with file extent items pointing to the same data
  1781. * extent. We have to invalidate the cache and cache only the sharedness
  1782. * result for the levels where we got only one node/reference.
  1783. */
  1784. if (!ctx->use_path_cache) {
  1785. int i = 0;
  1786. level--;
  1787. if (ret >= 0 && level >= 0) {
  1788. bytenr = ctx->path_cache_entries[level].bytenr;
  1789. ctx->use_path_cache = true;
  1790. store_backref_shared_cache(ctx, root, bytenr, level, ret);
  1791. i = level + 1;
  1792. }
  1793. for ( ; i < BTRFS_MAX_LEVEL; i++)
  1794. ctx->path_cache_entries[i].bytenr = 0;
  1795. }
  1796. /*
  1797. * Cache the sharedness result for the data extent if we know our inode
  1798. * has more than 1 file extent item that refers to the data extent.
  1799. */
  1800. if (ret >= 0 && shared.self_ref_count > 1) {
  1801. int slot = ctx->prev_extents_cache_slot;
  1802. ctx->prev_extents_cache[slot].bytenr = shared.data_bytenr;
  1803. ctx->prev_extents_cache[slot].is_shared = (ret == 1);
  1804. slot = (slot + 1) % BTRFS_BACKREF_CTX_PREV_EXTENTS_SIZE;
  1805. ctx->prev_extents_cache_slot = slot;
  1806. }
  1807. out_trans:
  1808. if (trans) {
  1809. btrfs_put_tree_mod_seq(fs_info, &elem);
  1810. btrfs_end_transaction(trans);
  1811. } else {
  1812. up_read(&fs_info->commit_root_sem);
  1813. }
  1814. out:
  1815. ulist_release(&ctx->refs);
  1816. ctx->prev_leaf_bytenr = ctx->curr_leaf_bytenr;
  1817. return ret;
  1818. }
  1819. int btrfs_find_one_extref(struct btrfs_root *root, u64 inode_objectid,
  1820. u64 start_off, struct btrfs_path *path,
  1821. struct btrfs_inode_extref **ret_extref,
  1822. u64 *found_off)
  1823. {
  1824. int ret, slot;
  1825. struct btrfs_key key;
  1826. struct btrfs_key found_key;
  1827. struct btrfs_inode_extref *extref;
  1828. const struct extent_buffer *leaf;
  1829. unsigned long ptr;
  1830. key.objectid = inode_objectid;
  1831. key.type = BTRFS_INODE_EXTREF_KEY;
  1832. key.offset = start_off;
  1833. ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
  1834. if (ret < 0)
  1835. return ret;
  1836. while (1) {
  1837. leaf = path->nodes[0];
  1838. slot = path->slots[0];
  1839. if (slot >= btrfs_header_nritems(leaf)) {
  1840. /*
  1841. * If the item at offset is not found,
  1842. * btrfs_search_slot will point us to the slot
  1843. * where it should be inserted. In our case
  1844. * that will be the slot directly before the
  1845. * next INODE_REF_KEY_V2 item. In the case
  1846. * that we're pointing to the last slot in a
  1847. * leaf, we must move one leaf over.
  1848. */
  1849. ret = btrfs_next_leaf(root, path);
  1850. if (ret) {
  1851. if (ret >= 1)
  1852. ret = -ENOENT;
  1853. break;
  1854. }
  1855. continue;
  1856. }
  1857. btrfs_item_key_to_cpu(leaf, &found_key, slot);
  1858. /*
  1859. * Check that we're still looking at an extended ref key for
  1860. * this particular objectid. If we have different
  1861. * objectid or type then there are no more to be found
  1862. * in the tree and we can exit.
  1863. */
  1864. ret = -ENOENT;
  1865. if (found_key.objectid != inode_objectid)
  1866. break;
  1867. if (found_key.type != BTRFS_INODE_EXTREF_KEY)
  1868. break;
  1869. ret = 0;
  1870. ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
  1871. extref = (struct btrfs_inode_extref *)ptr;
  1872. *ret_extref = extref;
  1873. if (found_off)
  1874. *found_off = found_key.offset;
  1875. break;
  1876. }
  1877. return ret;
  1878. }
  1879. /*
  1880. * this iterates to turn a name (from iref/extref) into a full filesystem path.
  1881. * Elements of the path are separated by '/' and the path is guaranteed to be
  1882. * 0-terminated. the path is only given within the current file system.
  1883. * Therefore, it never starts with a '/'. the caller is responsible to provide
  1884. * "size" bytes in "dest". the dest buffer will be filled backwards. finally,
  1885. * the start point of the resulting string is returned. this pointer is within
  1886. * dest, normally.
  1887. * in case the path buffer would overflow, the pointer is decremented further
  1888. * as if output was written to the buffer, though no more output is actually
  1889. * generated. that way, the caller can determine how much space would be
  1890. * required for the path to fit into the buffer. in that case, the returned
  1891. * value will be smaller than dest. callers must check this!
  1892. */
  1893. char *btrfs_ref_to_path(struct btrfs_root *fs_root, struct btrfs_path *path,
  1894. u32 name_len, unsigned long name_off,
  1895. struct extent_buffer *eb_in, u64 parent,
  1896. char *dest, u32 size)
  1897. {
  1898. int slot;
  1899. u64 next_inum;
  1900. int ret;
  1901. s64 bytes_left = ((s64)size) - 1;
  1902. struct extent_buffer *eb = eb_in;
  1903. struct btrfs_key found_key;
  1904. struct btrfs_inode_ref *iref;
  1905. if (bytes_left >= 0)
  1906. dest[bytes_left] = '\0';
  1907. while (1) {
  1908. bytes_left -= name_len;
  1909. if (bytes_left >= 0)
  1910. read_extent_buffer(eb, dest + bytes_left,
  1911. name_off, name_len);
  1912. if (eb != eb_in) {
  1913. if (!path->skip_locking)
  1914. btrfs_tree_read_unlock(eb);
  1915. free_extent_buffer(eb);
  1916. }
  1917. ret = btrfs_find_item(fs_root, path, parent, 0,
  1918. BTRFS_INODE_REF_KEY, &found_key);
  1919. if (ret > 0)
  1920. ret = -ENOENT;
  1921. if (ret)
  1922. break;
  1923. next_inum = found_key.offset;
  1924. /* regular exit ahead */
  1925. if (parent == next_inum)
  1926. break;
  1927. slot = path->slots[0];
  1928. eb = path->nodes[0];
  1929. /* make sure we can use eb after releasing the path */
  1930. if (eb != eb_in) {
  1931. path->nodes[0] = NULL;
  1932. path->locks[0] = 0;
  1933. }
  1934. btrfs_release_path(path);
  1935. iref = btrfs_item_ptr(eb, slot, struct btrfs_inode_ref);
  1936. name_len = btrfs_inode_ref_name_len(eb, iref);
  1937. name_off = (unsigned long)(iref + 1);
  1938. parent = next_inum;
  1939. --bytes_left;
  1940. if (bytes_left >= 0)
  1941. dest[bytes_left] = '/';
  1942. }
  1943. btrfs_release_path(path);
  1944. if (ret)
  1945. return ERR_PTR(ret);
  1946. return dest + bytes_left;
  1947. }
  1948. /*
  1949. * this makes the path point to (logical EXTENT_ITEM *)
  1950. * returns BTRFS_EXTENT_FLAG_DATA for data, BTRFS_EXTENT_FLAG_TREE_BLOCK for
  1951. * tree blocks and <0 on error.
  1952. */
  1953. int extent_from_logical(struct btrfs_fs_info *fs_info, u64 logical,
  1954. struct btrfs_path *path, struct btrfs_key *found_key,
  1955. u64 *flags_ret)
  1956. {
  1957. struct btrfs_root *extent_root = btrfs_extent_root(fs_info, logical);
  1958. int ret;
  1959. u64 flags;
  1960. u64 size = 0;
  1961. const struct extent_buffer *eb;
  1962. struct btrfs_extent_item *ei;
  1963. struct btrfs_key key;
  1964. if (unlikely(!extent_root)) {
  1965. btrfs_err(fs_info,
  1966. "missing extent root for extent at bytenr %llu",
  1967. logical);
  1968. return -EUCLEAN;
  1969. }
  1970. key.objectid = logical;
  1971. if (btrfs_fs_incompat(fs_info, SKINNY_METADATA))
  1972. key.type = BTRFS_METADATA_ITEM_KEY;
  1973. else
  1974. key.type = BTRFS_EXTENT_ITEM_KEY;
  1975. key.offset = (u64)-1;
  1976. ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
  1977. if (ret < 0)
  1978. return ret;
  1979. if (unlikely(ret == 0)) {
  1980. /*
  1981. * Key with offset -1 found, there would have to exist an extent
  1982. * item with such offset, but this is out of the valid range.
  1983. */
  1984. return -EUCLEAN;
  1985. }
  1986. ret = btrfs_previous_extent_item(extent_root, path, 0);
  1987. if (ret) {
  1988. if (ret > 0)
  1989. ret = -ENOENT;
  1990. return ret;
  1991. }
  1992. btrfs_item_key_to_cpu(path->nodes[0], found_key, path->slots[0]);
  1993. if (found_key->type == BTRFS_METADATA_ITEM_KEY)
  1994. size = fs_info->nodesize;
  1995. else if (found_key->type == BTRFS_EXTENT_ITEM_KEY)
  1996. size = found_key->offset;
  1997. if (found_key->objectid > logical ||
  1998. found_key->objectid + size <= logical) {
  1999. btrfs_debug(fs_info,
  2000. "logical %llu is not within any extent", logical);
  2001. return -ENOENT;
  2002. }
  2003. eb = path->nodes[0];
  2004. ei = btrfs_item_ptr(eb, path->slots[0], struct btrfs_extent_item);
  2005. flags = btrfs_extent_flags(eb, ei);
  2006. btrfs_debug(fs_info,
  2007. "logical %llu is at position %llu within the extent (%llu EXTENT_ITEM %llu) flags %#llx size %u",
  2008. logical, logical - found_key->objectid, found_key->objectid,
  2009. found_key->offset, flags, btrfs_item_size(eb, path->slots[0]));
  2010. WARN_ON(!flags_ret);
  2011. if (flags_ret) {
  2012. if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK)
  2013. *flags_ret = BTRFS_EXTENT_FLAG_TREE_BLOCK;
  2014. else if (flags & BTRFS_EXTENT_FLAG_DATA)
  2015. *flags_ret = BTRFS_EXTENT_FLAG_DATA;
  2016. else
  2017. BUG();
  2018. return 0;
  2019. }
  2020. return -EIO;
  2021. }
  2022. /*
  2023. * helper function to iterate extent inline refs. ptr must point to a 0 value
  2024. * for the first call and may be modified. it is used to track state.
  2025. * if more refs exist, 0 is returned and the next call to
  2026. * get_extent_inline_ref must pass the modified ptr parameter to get the
  2027. * next ref. after the last ref was processed, 1 is returned.
  2028. * returns <0 on error
  2029. */
  2030. static int get_extent_inline_ref(unsigned long *ptr,
  2031. const struct extent_buffer *eb,
  2032. const struct btrfs_key *key,
  2033. const struct btrfs_extent_item *ei,
  2034. u32 item_size,
  2035. struct btrfs_extent_inline_ref **out_eiref,
  2036. int *out_type)
  2037. {
  2038. unsigned long end;
  2039. u64 flags;
  2040. struct btrfs_tree_block_info *info;
  2041. if (!*ptr) {
  2042. /* first call */
  2043. flags = btrfs_extent_flags(eb, ei);
  2044. if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
  2045. if (key->type == BTRFS_METADATA_ITEM_KEY) {
  2046. /* a skinny metadata extent */
  2047. *out_eiref =
  2048. (struct btrfs_extent_inline_ref *)(ei + 1);
  2049. } else {
  2050. WARN_ON(key->type != BTRFS_EXTENT_ITEM_KEY);
  2051. info = (struct btrfs_tree_block_info *)(ei + 1);
  2052. *out_eiref =
  2053. (struct btrfs_extent_inline_ref *)(info + 1);
  2054. }
  2055. } else {
  2056. *out_eiref = (struct btrfs_extent_inline_ref *)(ei + 1);
  2057. }
  2058. *ptr = (unsigned long)*out_eiref;
  2059. if ((unsigned long)(*ptr) >= (unsigned long)ei + item_size)
  2060. return -ENOENT;
  2061. }
  2062. end = (unsigned long)ei + item_size;
  2063. *out_eiref = (struct btrfs_extent_inline_ref *)(*ptr);
  2064. *out_type = btrfs_get_extent_inline_ref_type(eb, *out_eiref,
  2065. BTRFS_REF_TYPE_ANY);
  2066. if (unlikely(*out_type == BTRFS_REF_TYPE_INVALID))
  2067. return -EUCLEAN;
  2068. *ptr += btrfs_extent_inline_ref_size(*out_type);
  2069. WARN_ON(*ptr > end);
  2070. if (*ptr == end)
  2071. return 1; /* last */
  2072. return 0;
  2073. }
  2074. /*
  2075. * reads the tree block backref for an extent. tree level and root are returned
  2076. * through out_level and out_root. ptr must point to a 0 value for the first
  2077. * call and may be modified (see get_extent_inline_ref comment).
  2078. * returns 0 if data was provided, 1 if there was no more data to provide or
  2079. * <0 on error.
  2080. */
  2081. int tree_backref_for_extent(unsigned long *ptr, struct extent_buffer *eb,
  2082. struct btrfs_key *key, struct btrfs_extent_item *ei,
  2083. u32 item_size, u64 *out_root, u8 *out_level)
  2084. {
  2085. int ret;
  2086. int type;
  2087. struct btrfs_extent_inline_ref *eiref;
  2088. if (*ptr == (unsigned long)-1)
  2089. return 1;
  2090. while (1) {
  2091. ret = get_extent_inline_ref(ptr, eb, key, ei, item_size,
  2092. &eiref, &type);
  2093. if (ret < 0)
  2094. return ret;
  2095. if (type == BTRFS_TREE_BLOCK_REF_KEY ||
  2096. type == BTRFS_SHARED_BLOCK_REF_KEY)
  2097. break;
  2098. if (ret == 1)
  2099. return 1;
  2100. }
  2101. /* we can treat both ref types equally here */
  2102. *out_root = btrfs_extent_inline_ref_offset(eb, eiref);
  2103. if (key->type == BTRFS_EXTENT_ITEM_KEY) {
  2104. struct btrfs_tree_block_info *info;
  2105. info = (struct btrfs_tree_block_info *)(ei + 1);
  2106. *out_level = btrfs_tree_block_level(eb, info);
  2107. } else {
  2108. ASSERT(key->type == BTRFS_METADATA_ITEM_KEY);
  2109. *out_level = (u8)key->offset;
  2110. }
  2111. if (ret == 1)
  2112. *ptr = (unsigned long)-1;
  2113. return 0;
  2114. }
  2115. static int iterate_leaf_refs(struct btrfs_fs_info *fs_info,
  2116. struct extent_inode_elem *inode_list,
  2117. u64 root, u64 extent_item_objectid,
  2118. iterate_extent_inodes_t *iterate, void *ctx)
  2119. {
  2120. struct extent_inode_elem *eie;
  2121. int ret = 0;
  2122. for (eie = inode_list; eie; eie = eie->next) {
  2123. btrfs_debug(fs_info,
  2124. "ref for %llu resolved, key (%llu EXTEND_DATA %llu), root %llu",
  2125. extent_item_objectid, eie->inum,
  2126. eie->offset, root);
  2127. ret = iterate(eie->inum, eie->offset, eie->num_bytes, root, ctx);
  2128. if (ret) {
  2129. btrfs_debug(fs_info,
  2130. "stopping iteration for %llu due to ret=%d",
  2131. extent_item_objectid, ret);
  2132. break;
  2133. }
  2134. }
  2135. return ret;
  2136. }
  2137. /*
  2138. * calls iterate() for every inode that references the extent identified by
  2139. * the given parameters.
  2140. * when the iterator function returns a non-zero value, iteration stops.
  2141. */
  2142. int iterate_extent_inodes(struct btrfs_backref_walk_ctx *ctx,
  2143. bool search_commit_root,
  2144. iterate_extent_inodes_t *iterate, void *user_ctx)
  2145. {
  2146. int ret;
  2147. struct ulist *refs;
  2148. struct ulist_node *ref_node;
  2149. struct btrfs_seq_list seq_elem = BTRFS_SEQ_LIST_INIT(seq_elem);
  2150. struct ulist_iterator ref_uiter;
  2151. btrfs_debug(ctx->fs_info, "resolving all inodes for extent %llu",
  2152. ctx->bytenr);
  2153. ASSERT(ctx->trans == NULL);
  2154. ASSERT(ctx->roots == NULL);
  2155. if (!search_commit_root) {
  2156. struct btrfs_trans_handle *trans;
  2157. trans = btrfs_attach_transaction(ctx->fs_info->tree_root);
  2158. if (IS_ERR(trans)) {
  2159. if (PTR_ERR(trans) != -ENOENT &&
  2160. PTR_ERR(trans) != -EROFS)
  2161. return PTR_ERR(trans);
  2162. trans = NULL;
  2163. }
  2164. ctx->trans = trans;
  2165. }
  2166. if (ctx->trans) {
  2167. btrfs_get_tree_mod_seq(ctx->fs_info, &seq_elem);
  2168. ctx->time_seq = seq_elem.seq;
  2169. } else {
  2170. down_read(&ctx->fs_info->commit_root_sem);
  2171. }
  2172. ret = btrfs_find_all_leafs(ctx);
  2173. if (ret)
  2174. goto out;
  2175. refs = ctx->refs;
  2176. ctx->refs = NULL;
  2177. ULIST_ITER_INIT(&ref_uiter);
  2178. while (!ret && (ref_node = ulist_next(refs, &ref_uiter))) {
  2179. const u64 leaf_bytenr = ref_node->val;
  2180. struct ulist_node *root_node;
  2181. struct ulist_iterator root_uiter;
  2182. struct extent_inode_elem *inode_list;
  2183. inode_list = (struct extent_inode_elem *)(uintptr_t)ref_node->aux;
  2184. if (ctx->cache_lookup) {
  2185. const u64 *root_ids;
  2186. int root_count;
  2187. bool cached;
  2188. cached = ctx->cache_lookup(leaf_bytenr, ctx->user_ctx,
  2189. &root_ids, &root_count);
  2190. if (cached) {
  2191. for (int i = 0; i < root_count; i++) {
  2192. ret = iterate_leaf_refs(ctx->fs_info,
  2193. inode_list,
  2194. root_ids[i],
  2195. leaf_bytenr,
  2196. iterate,
  2197. user_ctx);
  2198. if (ret)
  2199. break;
  2200. }
  2201. continue;
  2202. }
  2203. }
  2204. if (!ctx->roots) {
  2205. ctx->roots = ulist_alloc(GFP_NOFS);
  2206. if (!ctx->roots) {
  2207. ret = -ENOMEM;
  2208. break;
  2209. }
  2210. }
  2211. ctx->bytenr = leaf_bytenr;
  2212. ret = btrfs_find_all_roots_safe(ctx);
  2213. if (ret)
  2214. break;
  2215. if (ctx->cache_store)
  2216. ctx->cache_store(leaf_bytenr, ctx->roots, ctx->user_ctx);
  2217. ULIST_ITER_INIT(&root_uiter);
  2218. while (!ret && (root_node = ulist_next(ctx->roots, &root_uiter))) {
  2219. btrfs_debug(ctx->fs_info,
  2220. "root %llu references leaf %llu, data list %#llx",
  2221. root_node->val, ref_node->val,
  2222. ref_node->aux);
  2223. ret = iterate_leaf_refs(ctx->fs_info, inode_list,
  2224. root_node->val, ctx->bytenr,
  2225. iterate, user_ctx);
  2226. }
  2227. ulist_reinit(ctx->roots);
  2228. }
  2229. free_leaf_list(refs);
  2230. out:
  2231. if (ctx->trans) {
  2232. btrfs_put_tree_mod_seq(ctx->fs_info, &seq_elem);
  2233. btrfs_end_transaction(ctx->trans);
  2234. ctx->trans = NULL;
  2235. } else {
  2236. up_read(&ctx->fs_info->commit_root_sem);
  2237. }
  2238. ulist_free(ctx->roots);
  2239. ctx->roots = NULL;
  2240. if (ret == BTRFS_ITERATE_EXTENT_INODES_STOP)
  2241. ret = 0;
  2242. return ret;
  2243. }
  2244. static int build_ino_list(u64 inum, u64 offset, u64 num_bytes, u64 root, void *ctx)
  2245. {
  2246. struct btrfs_data_container *inodes = ctx;
  2247. const size_t c = 3 * sizeof(u64);
  2248. if (inodes->bytes_left >= c) {
  2249. inodes->bytes_left -= c;
  2250. inodes->val[inodes->elem_cnt] = inum;
  2251. inodes->val[inodes->elem_cnt + 1] = offset;
  2252. inodes->val[inodes->elem_cnt + 2] = root;
  2253. inodes->elem_cnt += 3;
  2254. } else {
  2255. inodes->bytes_missing += c - inodes->bytes_left;
  2256. inodes->bytes_left = 0;
  2257. inodes->elem_missed += 3;
  2258. }
  2259. return 0;
  2260. }
  2261. int iterate_inodes_from_logical(u64 logical, struct btrfs_fs_info *fs_info,
  2262. void *ctx, bool ignore_offset)
  2263. {
  2264. struct btrfs_backref_walk_ctx walk_ctx = { 0 };
  2265. int ret;
  2266. u64 flags = 0;
  2267. struct btrfs_key found_key;
  2268. struct btrfs_path *path;
  2269. path = btrfs_alloc_path();
  2270. if (!path)
  2271. return -ENOMEM;
  2272. ret = extent_from_logical(fs_info, logical, path, &found_key, &flags);
  2273. btrfs_free_path(path);
  2274. if (ret < 0)
  2275. return ret;
  2276. if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK)
  2277. return -EINVAL;
  2278. walk_ctx.bytenr = found_key.objectid;
  2279. if (ignore_offset)
  2280. walk_ctx.ignore_extent_item_pos = true;
  2281. else
  2282. walk_ctx.extent_item_pos = logical - found_key.objectid;
  2283. walk_ctx.fs_info = fs_info;
  2284. return iterate_extent_inodes(&walk_ctx, false, build_ino_list, ctx);
  2285. }
  2286. static int inode_to_path(u64 inum, u32 name_len, unsigned long name_off,
  2287. struct extent_buffer *eb, struct inode_fs_paths *ipath);
  2288. static int iterate_inode_refs(u64 inum, struct inode_fs_paths *ipath)
  2289. {
  2290. int ret = 0;
  2291. int slot;
  2292. u32 cur;
  2293. u32 len;
  2294. u32 name_len;
  2295. u64 parent = 0;
  2296. int found = 0;
  2297. struct btrfs_root *fs_root = ipath->fs_root;
  2298. struct btrfs_path *path = ipath->btrfs_path;
  2299. struct extent_buffer *eb;
  2300. struct btrfs_inode_ref *iref;
  2301. struct btrfs_key found_key;
  2302. while (!ret) {
  2303. ret = btrfs_find_item(fs_root, path, inum,
  2304. parent ? parent + 1 : 0, BTRFS_INODE_REF_KEY,
  2305. &found_key);
  2306. if (ret < 0)
  2307. break;
  2308. if (ret) {
  2309. ret = found ? 0 : -ENOENT;
  2310. break;
  2311. }
  2312. ++found;
  2313. parent = found_key.offset;
  2314. slot = path->slots[0];
  2315. eb = btrfs_clone_extent_buffer(path->nodes[0]);
  2316. if (!eb) {
  2317. ret = -ENOMEM;
  2318. break;
  2319. }
  2320. btrfs_release_path(path);
  2321. iref = btrfs_item_ptr(eb, slot, struct btrfs_inode_ref);
  2322. for (cur = 0; cur < btrfs_item_size(eb, slot); cur += len) {
  2323. name_len = btrfs_inode_ref_name_len(eb, iref);
  2324. /* path must be released before calling iterate()! */
  2325. btrfs_debug(fs_root->fs_info,
  2326. "following ref at offset %u for inode %llu in tree %llu",
  2327. cur, found_key.objectid,
  2328. btrfs_root_id(fs_root));
  2329. ret = inode_to_path(parent, name_len,
  2330. (unsigned long)(iref + 1), eb, ipath);
  2331. if (ret)
  2332. break;
  2333. len = sizeof(*iref) + name_len;
  2334. iref = (struct btrfs_inode_ref *)((char *)iref + len);
  2335. }
  2336. free_extent_buffer(eb);
  2337. }
  2338. btrfs_release_path(path);
  2339. return ret;
  2340. }
  2341. static int iterate_inode_extrefs(u64 inum, struct inode_fs_paths *ipath)
  2342. {
  2343. int ret;
  2344. int slot;
  2345. u64 offset = 0;
  2346. u64 parent;
  2347. int found = 0;
  2348. struct btrfs_root *fs_root = ipath->fs_root;
  2349. struct btrfs_path *path = ipath->btrfs_path;
  2350. struct extent_buffer *eb;
  2351. struct btrfs_inode_extref *extref;
  2352. u32 item_size;
  2353. u32 cur_offset;
  2354. unsigned long ptr;
  2355. while (1) {
  2356. ret = btrfs_find_one_extref(fs_root, inum, offset, path, &extref,
  2357. &offset);
  2358. if (ret < 0)
  2359. break;
  2360. if (ret) {
  2361. ret = found ? 0 : -ENOENT;
  2362. break;
  2363. }
  2364. ++found;
  2365. slot = path->slots[0];
  2366. eb = btrfs_clone_extent_buffer(path->nodes[0]);
  2367. if (!eb) {
  2368. ret = -ENOMEM;
  2369. break;
  2370. }
  2371. btrfs_release_path(path);
  2372. item_size = btrfs_item_size(eb, slot);
  2373. ptr = btrfs_item_ptr_offset(eb, slot);
  2374. cur_offset = 0;
  2375. while (cur_offset < item_size) {
  2376. u32 name_len;
  2377. extref = (struct btrfs_inode_extref *)(ptr + cur_offset);
  2378. parent = btrfs_inode_extref_parent(eb, extref);
  2379. name_len = btrfs_inode_extref_name_len(eb, extref);
  2380. ret = inode_to_path(parent, name_len,
  2381. (unsigned long)&extref->name, eb, ipath);
  2382. if (ret)
  2383. break;
  2384. cur_offset += btrfs_inode_extref_name_len(eb, extref);
  2385. cur_offset += sizeof(*extref);
  2386. }
  2387. free_extent_buffer(eb);
  2388. offset++;
  2389. }
  2390. btrfs_release_path(path);
  2391. return ret;
  2392. }
  2393. /*
  2394. * returns 0 if the path could be dumped (probably truncated)
  2395. * returns <0 in case of an error
  2396. */
  2397. static int inode_to_path(u64 inum, u32 name_len, unsigned long name_off,
  2398. struct extent_buffer *eb, struct inode_fs_paths *ipath)
  2399. {
  2400. char *fspath;
  2401. char *fspath_min;
  2402. int i = ipath->fspath->elem_cnt;
  2403. const int s_ptr = sizeof(char *);
  2404. u32 bytes_left;
  2405. bytes_left = ipath->fspath->bytes_left > s_ptr ?
  2406. ipath->fspath->bytes_left - s_ptr : 0;
  2407. fspath_min = (char *)ipath->fspath->val + (i + 1) * s_ptr;
  2408. fspath = btrfs_ref_to_path(ipath->fs_root, ipath->btrfs_path, name_len,
  2409. name_off, eb, inum, fspath_min, bytes_left);
  2410. if (IS_ERR(fspath))
  2411. return PTR_ERR(fspath);
  2412. if (fspath > fspath_min) {
  2413. ipath->fspath->val[i] = (u64)(unsigned long)fspath;
  2414. ++ipath->fspath->elem_cnt;
  2415. ipath->fspath->bytes_left = fspath - fspath_min;
  2416. } else {
  2417. ++ipath->fspath->elem_missed;
  2418. ipath->fspath->bytes_missing += fspath_min - fspath;
  2419. ipath->fspath->bytes_left = 0;
  2420. }
  2421. return 0;
  2422. }
  2423. /*
  2424. * this dumps all file system paths to the inode into the ipath struct, provided
  2425. * is has been created large enough. each path is zero-terminated and accessed
  2426. * from ipath->fspath->val[i].
  2427. * when it returns, there are ipath->fspath->elem_cnt number of paths available
  2428. * in ipath->fspath->val[]. when the allocated space wasn't sufficient, the
  2429. * number of missed paths is recorded in ipath->fspath->elem_missed, otherwise,
  2430. * it's zero. ipath->fspath->bytes_missing holds the number of bytes that would
  2431. * have been needed to return all paths.
  2432. */
  2433. int paths_from_inode(u64 inum, struct inode_fs_paths *ipath)
  2434. {
  2435. int ret;
  2436. int found_refs = 0;
  2437. ret = iterate_inode_refs(inum, ipath);
  2438. if (!ret)
  2439. ++found_refs;
  2440. else if (ret != -ENOENT)
  2441. return ret;
  2442. ret = iterate_inode_extrefs(inum, ipath);
  2443. if (ret == -ENOENT && found_refs)
  2444. return 0;
  2445. return ret;
  2446. }
  2447. struct btrfs_data_container *init_data_container(u32 total_bytes)
  2448. {
  2449. struct btrfs_data_container *data;
  2450. size_t alloc_bytes;
  2451. alloc_bytes = max_t(size_t, total_bytes, sizeof(*data));
  2452. data = kvzalloc(alloc_bytes, GFP_KERNEL);
  2453. if (!data)
  2454. return ERR_PTR(-ENOMEM);
  2455. if (total_bytes >= sizeof(*data))
  2456. data->bytes_left = total_bytes - sizeof(*data);
  2457. else
  2458. data->bytes_missing = sizeof(*data) - total_bytes;
  2459. return data;
  2460. }
  2461. /*
  2462. * allocates space to return multiple file system paths for an inode.
  2463. * total_bytes to allocate are passed, note that space usable for actual path
  2464. * information will be total_bytes - sizeof(struct inode_fs_paths).
  2465. * the returned pointer must be freed with __free_inode_fs_paths() in the end.
  2466. */
  2467. struct inode_fs_paths *init_ipath(s32 total_bytes, struct btrfs_root *fs_root,
  2468. struct btrfs_path *path)
  2469. {
  2470. struct inode_fs_paths *ifp;
  2471. struct btrfs_data_container *fspath;
  2472. fspath = init_data_container(total_bytes);
  2473. if (IS_ERR(fspath))
  2474. return ERR_CAST(fspath);
  2475. ifp = kmalloc_obj(*ifp);
  2476. if (!ifp) {
  2477. kvfree(fspath);
  2478. return ERR_PTR(-ENOMEM);
  2479. }
  2480. ifp->btrfs_path = path;
  2481. ifp->fspath = fspath;
  2482. ifp->fs_root = fs_root;
  2483. return ifp;
  2484. }
  2485. struct btrfs_backref_iter *btrfs_backref_iter_alloc(struct btrfs_fs_info *fs_info)
  2486. {
  2487. struct btrfs_backref_iter *ret;
  2488. ret = kzalloc_obj(*ret, GFP_NOFS);
  2489. if (!ret)
  2490. return NULL;
  2491. ret->path = btrfs_alloc_path();
  2492. if (!ret->path) {
  2493. kfree(ret);
  2494. return NULL;
  2495. }
  2496. /* Current backref iterator only supports iteration in commit root */
  2497. ret->path->search_commit_root = true;
  2498. ret->path->skip_locking = true;
  2499. ret->fs_info = fs_info;
  2500. return ret;
  2501. }
  2502. static void btrfs_backref_iter_release(struct btrfs_backref_iter *iter)
  2503. {
  2504. iter->bytenr = 0;
  2505. iter->item_ptr = 0;
  2506. iter->cur_ptr = 0;
  2507. iter->end_ptr = 0;
  2508. btrfs_release_path(iter->path);
  2509. memset(&iter->cur_key, 0, sizeof(iter->cur_key));
  2510. }
  2511. int btrfs_backref_iter_start(struct btrfs_backref_iter *iter, u64 bytenr)
  2512. {
  2513. struct btrfs_fs_info *fs_info = iter->fs_info;
  2514. struct btrfs_root *extent_root = btrfs_extent_root(fs_info, bytenr);
  2515. struct btrfs_path *path = iter->path;
  2516. struct btrfs_extent_item *ei;
  2517. struct btrfs_key key;
  2518. int ret;
  2519. if (unlikely(!extent_root)) {
  2520. btrfs_err(fs_info,
  2521. "missing extent root for extent at bytenr %llu",
  2522. bytenr);
  2523. return -EUCLEAN;
  2524. }
  2525. key.objectid = bytenr;
  2526. key.type = BTRFS_METADATA_ITEM_KEY;
  2527. key.offset = (u64)-1;
  2528. iter->bytenr = bytenr;
  2529. ret = btrfs_search_slot(NULL, extent_root, &key, path, 0, 0);
  2530. if (ret < 0)
  2531. return ret;
  2532. if (unlikely(ret == 0)) {
  2533. /*
  2534. * Key with offset -1 found, there would have to exist an extent
  2535. * item with such offset, but this is out of the valid range.
  2536. */
  2537. ret = -EUCLEAN;
  2538. goto release;
  2539. }
  2540. if (unlikely(path->slots[0] == 0)) {
  2541. DEBUG_WARN();
  2542. ret = -EUCLEAN;
  2543. goto release;
  2544. }
  2545. path->slots[0]--;
  2546. btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
  2547. if ((key.type != BTRFS_EXTENT_ITEM_KEY &&
  2548. key.type != BTRFS_METADATA_ITEM_KEY) || key.objectid != bytenr) {
  2549. ret = -ENOENT;
  2550. goto release;
  2551. }
  2552. memcpy(&iter->cur_key, &key, sizeof(key));
  2553. iter->item_ptr = (u32)btrfs_item_ptr_offset(path->nodes[0],
  2554. path->slots[0]);
  2555. iter->end_ptr = (u32)(iter->item_ptr +
  2556. btrfs_item_size(path->nodes[0], path->slots[0]));
  2557. ei = btrfs_item_ptr(path->nodes[0], path->slots[0],
  2558. struct btrfs_extent_item);
  2559. /*
  2560. * Only support iteration on tree backref yet.
  2561. *
  2562. * This is an extra precaution for non skinny-metadata, where
  2563. * EXTENT_ITEM is also used for tree blocks, that we can only use
  2564. * extent flags to determine if it's a tree block.
  2565. */
  2566. if (btrfs_extent_flags(path->nodes[0], ei) & BTRFS_EXTENT_FLAG_DATA) {
  2567. ret = -ENOTSUPP;
  2568. goto release;
  2569. }
  2570. iter->cur_ptr = (u32)(iter->item_ptr + sizeof(*ei));
  2571. /* If there is no inline backref, go search for keyed backref */
  2572. if (iter->cur_ptr >= iter->end_ptr) {
  2573. ret = btrfs_next_item(extent_root, path);
  2574. /* No inline nor keyed ref */
  2575. if (ret > 0) {
  2576. ret = -ENOENT;
  2577. goto release;
  2578. }
  2579. if (ret < 0)
  2580. goto release;
  2581. btrfs_item_key_to_cpu(path->nodes[0], &iter->cur_key,
  2582. path->slots[0]);
  2583. if (iter->cur_key.objectid != bytenr ||
  2584. (iter->cur_key.type != BTRFS_SHARED_BLOCK_REF_KEY &&
  2585. iter->cur_key.type != BTRFS_TREE_BLOCK_REF_KEY)) {
  2586. ret = -ENOENT;
  2587. goto release;
  2588. }
  2589. iter->cur_ptr = (u32)btrfs_item_ptr_offset(path->nodes[0],
  2590. path->slots[0]);
  2591. iter->item_ptr = iter->cur_ptr;
  2592. iter->end_ptr = (u32)(iter->item_ptr + btrfs_item_size(
  2593. path->nodes[0], path->slots[0]));
  2594. }
  2595. return 0;
  2596. release:
  2597. btrfs_backref_iter_release(iter);
  2598. return ret;
  2599. }
  2600. static bool btrfs_backref_iter_is_inline_ref(struct btrfs_backref_iter *iter)
  2601. {
  2602. if (iter->cur_key.type == BTRFS_EXTENT_ITEM_KEY ||
  2603. iter->cur_key.type == BTRFS_METADATA_ITEM_KEY)
  2604. return true;
  2605. return false;
  2606. }
  2607. /*
  2608. * Go to the next backref item of current bytenr, can be either inlined or
  2609. * keyed.
  2610. *
  2611. * Caller needs to check whether it's inline ref or not by iter->cur_key.
  2612. *
  2613. * Return 0 if we get next backref without problem.
  2614. * Return >0 if there is no extra backref for this bytenr.
  2615. * Return <0 if there is something wrong happened.
  2616. */
  2617. int btrfs_backref_iter_next(struct btrfs_backref_iter *iter)
  2618. {
  2619. struct extent_buffer *eb = iter->path->nodes[0];
  2620. struct btrfs_root *extent_root;
  2621. struct btrfs_path *path = iter->path;
  2622. struct btrfs_extent_inline_ref *iref;
  2623. int ret;
  2624. u32 size;
  2625. if (btrfs_backref_iter_is_inline_ref(iter)) {
  2626. /* We're still inside the inline refs */
  2627. ASSERT(iter->cur_ptr < iter->end_ptr);
  2628. if (btrfs_backref_has_tree_block_info(iter)) {
  2629. /* First tree block info */
  2630. size = sizeof(struct btrfs_tree_block_info);
  2631. } else {
  2632. /* Use inline ref type to determine the size */
  2633. int type;
  2634. iref = (struct btrfs_extent_inline_ref *)
  2635. ((unsigned long)iter->cur_ptr);
  2636. type = btrfs_extent_inline_ref_type(eb, iref);
  2637. size = btrfs_extent_inline_ref_size(type);
  2638. }
  2639. iter->cur_ptr += size;
  2640. if (iter->cur_ptr < iter->end_ptr)
  2641. return 0;
  2642. /* All inline items iterated, fall through */
  2643. }
  2644. /* We're at keyed items, there is no inline item, go to the next one */
  2645. extent_root = btrfs_extent_root(iter->fs_info, iter->bytenr);
  2646. if (unlikely(!extent_root)) {
  2647. btrfs_err(iter->fs_info,
  2648. "missing extent root for extent at bytenr %llu",
  2649. iter->bytenr);
  2650. return -EUCLEAN;
  2651. }
  2652. ret = btrfs_next_item(extent_root, iter->path);
  2653. if (ret)
  2654. return ret;
  2655. btrfs_item_key_to_cpu(path->nodes[0], &iter->cur_key, path->slots[0]);
  2656. if (iter->cur_key.objectid != iter->bytenr ||
  2657. (iter->cur_key.type != BTRFS_TREE_BLOCK_REF_KEY &&
  2658. iter->cur_key.type != BTRFS_SHARED_BLOCK_REF_KEY))
  2659. return 1;
  2660. iter->item_ptr = (u32)btrfs_item_ptr_offset(path->nodes[0],
  2661. path->slots[0]);
  2662. iter->cur_ptr = iter->item_ptr;
  2663. iter->end_ptr = iter->item_ptr + (u32)btrfs_item_size(path->nodes[0],
  2664. path->slots[0]);
  2665. return 0;
  2666. }
  2667. void btrfs_backref_init_cache(struct btrfs_fs_info *fs_info,
  2668. struct btrfs_backref_cache *cache, bool is_reloc)
  2669. {
  2670. int i;
  2671. cache->rb_root = RB_ROOT;
  2672. for (i = 0; i < BTRFS_MAX_LEVEL; i++)
  2673. INIT_LIST_HEAD(&cache->pending[i]);
  2674. INIT_LIST_HEAD(&cache->pending_edge);
  2675. INIT_LIST_HEAD(&cache->useless_node);
  2676. cache->fs_info = fs_info;
  2677. cache->is_reloc = is_reloc;
  2678. }
  2679. struct btrfs_backref_node *btrfs_backref_alloc_node(
  2680. struct btrfs_backref_cache *cache, u64 bytenr, int level)
  2681. {
  2682. struct btrfs_backref_node *node;
  2683. ASSERT(level >= 0 && level < BTRFS_MAX_LEVEL);
  2684. node = kzalloc_obj(*node, GFP_NOFS);
  2685. if (!node)
  2686. return node;
  2687. INIT_LIST_HEAD(&node->list);
  2688. INIT_LIST_HEAD(&node->upper);
  2689. INIT_LIST_HEAD(&node->lower);
  2690. RB_CLEAR_NODE(&node->rb_node);
  2691. cache->nr_nodes++;
  2692. node->level = level;
  2693. node->bytenr = bytenr;
  2694. return node;
  2695. }
  2696. void btrfs_backref_free_node(struct btrfs_backref_cache *cache,
  2697. struct btrfs_backref_node *node)
  2698. {
  2699. if (node) {
  2700. ASSERT(list_empty(&node->list));
  2701. ASSERT(list_empty(&node->lower));
  2702. ASSERT(node->eb == NULL);
  2703. cache->nr_nodes--;
  2704. btrfs_put_root(node->root);
  2705. kfree(node);
  2706. }
  2707. }
  2708. struct btrfs_backref_edge *btrfs_backref_alloc_edge(
  2709. struct btrfs_backref_cache *cache)
  2710. {
  2711. struct btrfs_backref_edge *edge;
  2712. edge = kzalloc_obj(*edge, GFP_NOFS);
  2713. if (edge)
  2714. cache->nr_edges++;
  2715. return edge;
  2716. }
  2717. void btrfs_backref_free_edge(struct btrfs_backref_cache *cache,
  2718. struct btrfs_backref_edge *edge)
  2719. {
  2720. if (edge) {
  2721. cache->nr_edges--;
  2722. kfree(edge);
  2723. }
  2724. }
  2725. void btrfs_backref_unlock_node_buffer(struct btrfs_backref_node *node)
  2726. {
  2727. if (node->locked) {
  2728. btrfs_tree_unlock(node->eb);
  2729. node->locked = 0;
  2730. }
  2731. }
  2732. void btrfs_backref_drop_node_buffer(struct btrfs_backref_node *node)
  2733. {
  2734. if (node->eb) {
  2735. btrfs_backref_unlock_node_buffer(node);
  2736. free_extent_buffer(node->eb);
  2737. node->eb = NULL;
  2738. }
  2739. }
  2740. /*
  2741. * Drop the backref node from cache without cleaning up its children
  2742. * edges.
  2743. *
  2744. * This can only be called on node without parent edges.
  2745. * The children edges are still kept as is.
  2746. */
  2747. void btrfs_backref_drop_node(struct btrfs_backref_cache *tree,
  2748. struct btrfs_backref_node *node)
  2749. {
  2750. ASSERT(list_empty(&node->upper));
  2751. btrfs_backref_drop_node_buffer(node);
  2752. list_del_init(&node->list);
  2753. list_del_init(&node->lower);
  2754. if (!RB_EMPTY_NODE(&node->rb_node))
  2755. rb_erase(&node->rb_node, &tree->rb_root);
  2756. btrfs_backref_free_node(tree, node);
  2757. }
  2758. /*
  2759. * Drop the backref node from cache, also cleaning up all its
  2760. * upper edges and any uncached nodes in the path.
  2761. *
  2762. * This cleanup happens bottom up, thus the node should either
  2763. * be the lowest node in the cache or a detached node.
  2764. */
  2765. void btrfs_backref_cleanup_node(struct btrfs_backref_cache *cache,
  2766. struct btrfs_backref_node *node)
  2767. {
  2768. struct btrfs_backref_edge *edge;
  2769. if (!node)
  2770. return;
  2771. while (!list_empty(&node->upper)) {
  2772. edge = list_first_entry(&node->upper, struct btrfs_backref_edge,
  2773. list[LOWER]);
  2774. list_del(&edge->list[LOWER]);
  2775. list_del(&edge->list[UPPER]);
  2776. btrfs_backref_free_edge(cache, edge);
  2777. }
  2778. btrfs_backref_drop_node(cache, node);
  2779. }
  2780. /*
  2781. * Release all nodes/edges from current cache
  2782. */
  2783. void btrfs_backref_release_cache(struct btrfs_backref_cache *cache)
  2784. {
  2785. struct btrfs_backref_node *node;
  2786. while ((node = rb_entry_safe(rb_first(&cache->rb_root),
  2787. struct btrfs_backref_node, rb_node)))
  2788. btrfs_backref_cleanup_node(cache, node);
  2789. ASSERT(list_empty(&cache->pending_edge));
  2790. ASSERT(list_empty(&cache->useless_node));
  2791. ASSERT(!cache->nr_nodes);
  2792. ASSERT(!cache->nr_edges);
  2793. }
  2794. static void btrfs_backref_link_edge(struct btrfs_backref_edge *edge,
  2795. struct btrfs_backref_node *lower,
  2796. struct btrfs_backref_node *upper)
  2797. {
  2798. ASSERT(upper && lower && upper->level == lower->level + 1);
  2799. edge->node[LOWER] = lower;
  2800. edge->node[UPPER] = upper;
  2801. list_add_tail(&edge->list[LOWER], &lower->upper);
  2802. }
  2803. /*
  2804. * Handle direct tree backref
  2805. *
  2806. * Direct tree backref means, the backref item shows its parent bytenr
  2807. * directly. This is for SHARED_BLOCK_REF backref (keyed or inlined).
  2808. *
  2809. * @ref_key: The converted backref key.
  2810. * For keyed backref, it's the item key.
  2811. * For inlined backref, objectid is the bytenr,
  2812. * type is btrfs_inline_ref_type, offset is
  2813. * btrfs_inline_ref_offset.
  2814. */
  2815. static int handle_direct_tree_backref(struct btrfs_backref_cache *cache,
  2816. struct btrfs_key *ref_key,
  2817. struct btrfs_backref_node *cur)
  2818. {
  2819. struct btrfs_backref_edge *edge;
  2820. struct btrfs_backref_node *upper;
  2821. struct rb_node *rb_node;
  2822. ASSERT(ref_key->type == BTRFS_SHARED_BLOCK_REF_KEY);
  2823. /* Only reloc root uses backref pointing to itself */
  2824. if (ref_key->objectid == ref_key->offset) {
  2825. struct btrfs_root *root;
  2826. cur->is_reloc_root = 1;
  2827. /* Only reloc backref cache cares about a specific root */
  2828. if (cache->is_reloc) {
  2829. root = find_reloc_root(cache->fs_info, cur->bytenr);
  2830. if (!root)
  2831. return -ENOENT;
  2832. cur->root = root;
  2833. } else {
  2834. /*
  2835. * For generic purpose backref cache, reloc root node
  2836. * is useless.
  2837. */
  2838. list_add(&cur->list, &cache->useless_node);
  2839. }
  2840. return 0;
  2841. }
  2842. edge = btrfs_backref_alloc_edge(cache);
  2843. if (!edge)
  2844. return -ENOMEM;
  2845. rb_node = rb_simple_search(&cache->rb_root, ref_key->offset);
  2846. if (!rb_node) {
  2847. /* Parent node not yet cached */
  2848. upper = btrfs_backref_alloc_node(cache, ref_key->offset,
  2849. cur->level + 1);
  2850. if (!upper) {
  2851. btrfs_backref_free_edge(cache, edge);
  2852. return -ENOMEM;
  2853. }
  2854. /*
  2855. * Backrefs for the upper level block isn't cached, add the
  2856. * block to pending list
  2857. */
  2858. list_add_tail(&edge->list[UPPER], &cache->pending_edge);
  2859. } else {
  2860. /* Parent node already cached */
  2861. upper = rb_entry(rb_node, struct btrfs_backref_node, rb_node);
  2862. ASSERT(upper->checked);
  2863. INIT_LIST_HEAD(&edge->list[UPPER]);
  2864. }
  2865. btrfs_backref_link_edge(edge, cur, upper);
  2866. return 0;
  2867. }
  2868. /*
  2869. * Handle indirect tree backref
  2870. *
  2871. * Indirect tree backref means, we only know which tree the node belongs to.
  2872. * We still need to do a tree search to find out the parents. This is for
  2873. * TREE_BLOCK_REF backref (keyed or inlined).
  2874. *
  2875. * @trans: Transaction handle.
  2876. * @ref_key: The same as @ref_key in handle_direct_tree_backref()
  2877. * @tree_key: The first key of this tree block.
  2878. * @path: A clean (released) path, to avoid allocating path every time
  2879. * the function get called.
  2880. */
  2881. static int handle_indirect_tree_backref(struct btrfs_trans_handle *trans,
  2882. struct btrfs_backref_cache *cache,
  2883. struct btrfs_path *path,
  2884. struct btrfs_key *ref_key,
  2885. struct btrfs_key *tree_key,
  2886. struct btrfs_backref_node *cur)
  2887. {
  2888. struct btrfs_fs_info *fs_info = cache->fs_info;
  2889. struct btrfs_backref_node *upper;
  2890. struct btrfs_backref_node *lower;
  2891. struct btrfs_backref_edge *edge;
  2892. struct extent_buffer *eb;
  2893. struct btrfs_root *root;
  2894. struct rb_node *rb_node;
  2895. int level;
  2896. bool need_check = true;
  2897. int ret;
  2898. root = btrfs_get_fs_root(fs_info, ref_key->offset, false);
  2899. if (IS_ERR(root))
  2900. return PTR_ERR(root);
  2901. /* We shouldn't be using backref cache for non-shareable roots. */
  2902. if (unlikely(!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))) {
  2903. btrfs_put_root(root);
  2904. return -EUCLEAN;
  2905. }
  2906. if (btrfs_root_level(&root->root_item) == cur->level) {
  2907. /* Tree root */
  2908. ASSERT(btrfs_root_bytenr(&root->root_item) == cur->bytenr);
  2909. /*
  2910. * For reloc backref cache, we may ignore reloc root. But for
  2911. * general purpose backref cache, we can't rely on
  2912. * btrfs_should_ignore_reloc_root() as it may conflict with
  2913. * current running relocation and lead to missing root.
  2914. *
  2915. * For general purpose backref cache, reloc root detection is
  2916. * completely relying on direct backref (key->offset is parent
  2917. * bytenr), thus only do such check for reloc cache.
  2918. */
  2919. if (btrfs_should_ignore_reloc_root(root) && cache->is_reloc) {
  2920. btrfs_put_root(root);
  2921. list_add(&cur->list, &cache->useless_node);
  2922. } else {
  2923. cur->root = root;
  2924. }
  2925. return 0;
  2926. }
  2927. level = cur->level + 1;
  2928. /* Search the tree to find parent blocks referring to the block */
  2929. path->search_commit_root = true;
  2930. path->skip_locking = true;
  2931. path->lowest_level = level;
  2932. ret = btrfs_search_slot(NULL, root, tree_key, path, 0, 0);
  2933. path->lowest_level = 0;
  2934. if (ret < 0) {
  2935. btrfs_put_root(root);
  2936. return ret;
  2937. }
  2938. if (ret > 0 && path->slots[level] > 0)
  2939. path->slots[level]--;
  2940. eb = path->nodes[level];
  2941. if (btrfs_node_blockptr(eb, path->slots[level]) != cur->bytenr) {
  2942. btrfs_err(fs_info,
  2943. "couldn't find block (%llu) (level %d) in tree (%llu) with key " BTRFS_KEY_FMT,
  2944. cur->bytenr, level - 1, btrfs_root_id(root),
  2945. BTRFS_KEY_FMT_VALUE(tree_key));
  2946. btrfs_put_root(root);
  2947. ret = -ENOENT;
  2948. goto out;
  2949. }
  2950. lower = cur;
  2951. /* Add all nodes and edges in the path */
  2952. for (; level < BTRFS_MAX_LEVEL; level++) {
  2953. if (!path->nodes[level]) {
  2954. ASSERT(btrfs_root_bytenr(&root->root_item) ==
  2955. lower->bytenr);
  2956. /* Same as previous should_ignore_reloc_root() call */
  2957. if (btrfs_should_ignore_reloc_root(root) &&
  2958. cache->is_reloc) {
  2959. btrfs_put_root(root);
  2960. list_add(&lower->list, &cache->useless_node);
  2961. } else {
  2962. lower->root = root;
  2963. }
  2964. break;
  2965. }
  2966. edge = btrfs_backref_alloc_edge(cache);
  2967. if (!edge) {
  2968. btrfs_put_root(root);
  2969. ret = -ENOMEM;
  2970. goto out;
  2971. }
  2972. eb = path->nodes[level];
  2973. rb_node = rb_simple_search(&cache->rb_root, eb->start);
  2974. if (!rb_node) {
  2975. upper = btrfs_backref_alloc_node(cache, eb->start,
  2976. lower->level + 1);
  2977. if (!upper) {
  2978. btrfs_put_root(root);
  2979. btrfs_backref_free_edge(cache, edge);
  2980. ret = -ENOMEM;
  2981. goto out;
  2982. }
  2983. upper->owner = btrfs_header_owner(eb);
  2984. /* We shouldn't be using backref cache for non shareable roots. */
  2985. if (unlikely(!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))) {
  2986. btrfs_put_root(root);
  2987. btrfs_backref_free_edge(cache, edge);
  2988. btrfs_backref_free_node(cache, upper);
  2989. ret = -EUCLEAN;
  2990. goto out;
  2991. }
  2992. /*
  2993. * If we know the block isn't shared we can avoid
  2994. * checking its backrefs.
  2995. */
  2996. if (btrfs_block_can_be_shared(trans, root, eb))
  2997. upper->checked = 0;
  2998. else
  2999. upper->checked = 1;
  3000. /*
  3001. * Add the block to pending list if we need to check its
  3002. * backrefs, we only do this once while walking up a
  3003. * tree as we will catch anything else later on.
  3004. */
  3005. if (!upper->checked && need_check) {
  3006. need_check = false;
  3007. list_add_tail(&edge->list[UPPER],
  3008. &cache->pending_edge);
  3009. } else {
  3010. if (upper->checked)
  3011. need_check = true;
  3012. INIT_LIST_HEAD(&edge->list[UPPER]);
  3013. }
  3014. } else {
  3015. upper = rb_entry(rb_node, struct btrfs_backref_node,
  3016. rb_node);
  3017. ASSERT(upper->checked);
  3018. INIT_LIST_HEAD(&edge->list[UPPER]);
  3019. if (!upper->owner)
  3020. upper->owner = btrfs_header_owner(eb);
  3021. }
  3022. btrfs_backref_link_edge(edge, lower, upper);
  3023. if (rb_node) {
  3024. btrfs_put_root(root);
  3025. break;
  3026. }
  3027. lower = upper;
  3028. upper = NULL;
  3029. }
  3030. out:
  3031. btrfs_release_path(path);
  3032. return ret;
  3033. }
  3034. /*
  3035. * Add backref node @cur into @cache.
  3036. *
  3037. * NOTE: Even if the function returned 0, @cur is not yet cached as its upper
  3038. * links aren't yet bi-directional. Needs to finish such links.
  3039. * Use btrfs_backref_finish_upper_links() to finish such linkage.
  3040. *
  3041. * @trans: Transaction handle.
  3042. * @path: Released path for indirect tree backref lookup
  3043. * @iter: Released backref iter for extent tree search
  3044. * @node_key: The first key of the tree block
  3045. */
  3046. int btrfs_backref_add_tree_node(struct btrfs_trans_handle *trans,
  3047. struct btrfs_backref_cache *cache,
  3048. struct btrfs_path *path,
  3049. struct btrfs_backref_iter *iter,
  3050. struct btrfs_key *node_key,
  3051. struct btrfs_backref_node *cur)
  3052. {
  3053. struct btrfs_backref_edge *edge;
  3054. struct btrfs_backref_node *exist;
  3055. int ret;
  3056. ret = btrfs_backref_iter_start(iter, cur->bytenr);
  3057. if (ret < 0)
  3058. return ret;
  3059. /*
  3060. * We skip the first btrfs_tree_block_info, as we don't use the key
  3061. * stored in it, but fetch it from the tree block
  3062. */
  3063. if (btrfs_backref_has_tree_block_info(iter)) {
  3064. ret = btrfs_backref_iter_next(iter);
  3065. if (ret < 0)
  3066. goto out;
  3067. /* No extra backref? This means the tree block is corrupted */
  3068. if (unlikely(ret > 0)) {
  3069. ret = -EUCLEAN;
  3070. goto out;
  3071. }
  3072. }
  3073. WARN_ON(cur->checked);
  3074. if (!list_empty(&cur->upper)) {
  3075. /*
  3076. * The backref was added previously when processing backref of
  3077. * type BTRFS_TREE_BLOCK_REF_KEY
  3078. */
  3079. ASSERT(list_is_singular(&cur->upper));
  3080. edge = list_first_entry(&cur->upper, struct btrfs_backref_edge,
  3081. list[LOWER]);
  3082. ASSERT(list_empty(&edge->list[UPPER]));
  3083. exist = edge->node[UPPER];
  3084. /*
  3085. * Add the upper level block to pending list if we need check
  3086. * its backrefs
  3087. */
  3088. if (!exist->checked)
  3089. list_add_tail(&edge->list[UPPER], &cache->pending_edge);
  3090. } else {
  3091. exist = NULL;
  3092. }
  3093. for (; ret == 0; ret = btrfs_backref_iter_next(iter)) {
  3094. struct extent_buffer *eb;
  3095. struct btrfs_key key;
  3096. int type;
  3097. cond_resched();
  3098. eb = iter->path->nodes[0];
  3099. key.objectid = iter->bytenr;
  3100. if (btrfs_backref_iter_is_inline_ref(iter)) {
  3101. struct btrfs_extent_inline_ref *iref;
  3102. /* Update key for inline backref */
  3103. iref = (struct btrfs_extent_inline_ref *)
  3104. ((unsigned long)iter->cur_ptr);
  3105. type = btrfs_get_extent_inline_ref_type(eb, iref,
  3106. BTRFS_REF_TYPE_BLOCK);
  3107. if (unlikely(type == BTRFS_REF_TYPE_INVALID)) {
  3108. ret = -EUCLEAN;
  3109. goto out;
  3110. }
  3111. key.type = type;
  3112. key.offset = btrfs_extent_inline_ref_offset(eb, iref);
  3113. } else {
  3114. key.type = iter->cur_key.type;
  3115. key.offset = iter->cur_key.offset;
  3116. }
  3117. /*
  3118. * Parent node found and matches current inline ref, no need to
  3119. * rebuild this node for this inline ref
  3120. */
  3121. if (exist &&
  3122. ((key.type == BTRFS_TREE_BLOCK_REF_KEY &&
  3123. exist->owner == key.offset) ||
  3124. (key.type == BTRFS_SHARED_BLOCK_REF_KEY &&
  3125. exist->bytenr == key.offset))) {
  3126. exist = NULL;
  3127. continue;
  3128. }
  3129. /* SHARED_BLOCK_REF means key.offset is the parent bytenr */
  3130. if (key.type == BTRFS_SHARED_BLOCK_REF_KEY) {
  3131. ret = handle_direct_tree_backref(cache, &key, cur);
  3132. if (ret < 0)
  3133. goto out;
  3134. } else if (key.type == BTRFS_TREE_BLOCK_REF_KEY) {
  3135. /*
  3136. * key.type == BTRFS_TREE_BLOCK_REF_KEY, inline ref
  3137. * offset means the root objectid. We need to search
  3138. * the tree to get its parent bytenr.
  3139. */
  3140. ret = handle_indirect_tree_backref(trans, cache, path,
  3141. &key, node_key, cur);
  3142. if (ret < 0)
  3143. goto out;
  3144. }
  3145. /*
  3146. * Unrecognized tree backref items (if it can pass tree-checker)
  3147. * would be ignored.
  3148. */
  3149. }
  3150. ret = 0;
  3151. cur->checked = 1;
  3152. WARN_ON(exist);
  3153. out:
  3154. btrfs_backref_iter_release(iter);
  3155. return ret;
  3156. }
  3157. /*
  3158. * Finish the upwards linkage created by btrfs_backref_add_tree_node()
  3159. */
  3160. int btrfs_backref_finish_upper_links(struct btrfs_backref_cache *cache,
  3161. struct btrfs_backref_node *start)
  3162. {
  3163. struct list_head *useless_node = &cache->useless_node;
  3164. struct btrfs_backref_edge *edge;
  3165. struct rb_node *rb_node;
  3166. LIST_HEAD(pending_edge);
  3167. ASSERT(start->checked);
  3168. rb_node = rb_simple_insert(&cache->rb_root, &start->simple_node);
  3169. if (rb_node)
  3170. btrfs_backref_panic(cache->fs_info, start->bytenr, -EEXIST);
  3171. /*
  3172. * Use breadth first search to iterate all related edges.
  3173. *
  3174. * The starting points are all the edges of this node
  3175. */
  3176. list_for_each_entry(edge, &start->upper, list[LOWER])
  3177. list_add_tail(&edge->list[UPPER], &pending_edge);
  3178. while (!list_empty(&pending_edge)) {
  3179. struct btrfs_backref_node *upper;
  3180. struct btrfs_backref_node *lower;
  3181. edge = list_first_entry(&pending_edge,
  3182. struct btrfs_backref_edge, list[UPPER]);
  3183. list_del_init(&edge->list[UPPER]);
  3184. upper = edge->node[UPPER];
  3185. lower = edge->node[LOWER];
  3186. /* Parent is detached, no need to keep any edges */
  3187. if (upper->detached) {
  3188. list_del(&edge->list[LOWER]);
  3189. btrfs_backref_free_edge(cache, edge);
  3190. /* Lower node is orphan, queue for cleanup */
  3191. if (list_empty(&lower->upper))
  3192. list_add(&lower->list, useless_node);
  3193. continue;
  3194. }
  3195. /*
  3196. * All new nodes added in current build_backref_tree() haven't
  3197. * been linked to the cache rb tree.
  3198. * So if we have upper->rb_node populated, this means a cache
  3199. * hit. We only need to link the edge, as @upper and all its
  3200. * parents have already been linked.
  3201. */
  3202. if (!RB_EMPTY_NODE(&upper->rb_node)) {
  3203. list_add_tail(&edge->list[UPPER], &upper->lower);
  3204. continue;
  3205. }
  3206. /* Sanity check, we shouldn't have any unchecked nodes */
  3207. if (unlikely(!upper->checked)) {
  3208. DEBUG_WARN("we should not have any unchecked nodes");
  3209. return -EUCLEAN;
  3210. }
  3211. rb_node = rb_simple_insert(&cache->rb_root, &upper->simple_node);
  3212. if (unlikely(rb_node))
  3213. btrfs_backref_panic(cache->fs_info, upper->bytenr, -EEXIST);
  3214. list_add_tail(&edge->list[UPPER], &upper->lower);
  3215. /*
  3216. * Also queue all the parent edges of this uncached node
  3217. * to finish the upper linkage
  3218. */
  3219. list_for_each_entry(edge, &upper->upper, list[LOWER])
  3220. list_add_tail(&edge->list[UPPER], &pending_edge);
  3221. }
  3222. return 0;
  3223. }
  3224. void btrfs_backref_error_cleanup(struct btrfs_backref_cache *cache,
  3225. struct btrfs_backref_node *node)
  3226. {
  3227. struct btrfs_backref_node *lower;
  3228. struct btrfs_backref_node *upper;
  3229. struct btrfs_backref_edge *edge;
  3230. while (!list_empty(&cache->useless_node)) {
  3231. lower = list_first_entry(&cache->useless_node,
  3232. struct btrfs_backref_node, list);
  3233. list_del_init(&lower->list);
  3234. }
  3235. while (!list_empty(&cache->pending_edge)) {
  3236. edge = list_first_entry(&cache->pending_edge,
  3237. struct btrfs_backref_edge, list[UPPER]);
  3238. list_del(&edge->list[UPPER]);
  3239. list_del(&edge->list[LOWER]);
  3240. lower = edge->node[LOWER];
  3241. upper = edge->node[UPPER];
  3242. btrfs_backref_free_edge(cache, edge);
  3243. /*
  3244. * Lower is no longer linked to any upper backref nodes and
  3245. * isn't in the cache, we can free it ourselves.
  3246. */
  3247. if (list_empty(&lower->upper) &&
  3248. RB_EMPTY_NODE(&lower->rb_node))
  3249. list_add(&lower->list, &cache->useless_node);
  3250. if (!RB_EMPTY_NODE(&upper->rb_node))
  3251. continue;
  3252. /* Add this guy's upper edges to the list to process */
  3253. list_for_each_entry(edge, &upper->upper, list[LOWER])
  3254. list_add_tail(&edge->list[UPPER],
  3255. &cache->pending_edge);
  3256. if (list_empty(&upper->upper))
  3257. list_add(&upper->list, &cache->useless_node);
  3258. }
  3259. while (!list_empty(&cache->useless_node)) {
  3260. lower = list_first_entry(&cache->useless_node,
  3261. struct btrfs_backref_node, list);
  3262. list_del_init(&lower->list);
  3263. if (lower == node)
  3264. node = NULL;
  3265. btrfs_backref_drop_node(cache, lower);
  3266. }
  3267. btrfs_backref_cleanup_node(cache, node);
  3268. ASSERT(list_empty(&cache->useless_node) &&
  3269. list_empty(&cache->pending_edge));
  3270. }