extent_map.c 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420
  1. // SPDX-License-Identifier: GPL-2.0
  2. #include <linux/err.h>
  3. #include <linux/slab.h>
  4. #include <linux/spinlock.h>
  5. #include "messages.h"
  6. #include "ctree.h"
  7. #include "extent_map.h"
  8. #include "compression.h"
  9. #include "btrfs_inode.h"
  10. #include "disk-io.h"
  11. static struct kmem_cache *extent_map_cache;
  12. int __init extent_map_init(void)
  13. {
  14. extent_map_cache = kmem_cache_create("btrfs_extent_map",
  15. sizeof(struct extent_map), 0, 0, NULL);
  16. if (!extent_map_cache)
  17. return -ENOMEM;
  18. return 0;
  19. }
  20. void __cold extent_map_exit(void)
  21. {
  22. kmem_cache_destroy(extent_map_cache);
  23. }
  24. /*
  25. * Initialize the extent tree @tree. Should be called for each new inode or
  26. * other user of the extent_map interface.
  27. */
  28. void extent_map_tree_init(struct extent_map_tree *tree)
  29. {
  30. tree->root = RB_ROOT;
  31. INIT_LIST_HEAD(&tree->modified_extents);
  32. rwlock_init(&tree->lock);
  33. }
  34. /*
  35. * Allocate a new extent_map structure. The new structure is returned with a
  36. * reference count of one and needs to be freed using free_extent_map()
  37. */
  38. struct extent_map *alloc_extent_map(void)
  39. {
  40. struct extent_map *em;
  41. em = kmem_cache_zalloc(extent_map_cache, GFP_NOFS);
  42. if (!em)
  43. return NULL;
  44. RB_CLEAR_NODE(&em->rb_node);
  45. refcount_set(&em->refs, 1);
  46. INIT_LIST_HEAD(&em->list);
  47. return em;
  48. }
  49. /*
  50. * Drop the reference out on @em by one and free the structure if the reference
  51. * count hits zero.
  52. */
  53. void free_extent_map(struct extent_map *em)
  54. {
  55. if (!em)
  56. return;
  57. if (refcount_dec_and_test(&em->refs)) {
  58. WARN_ON(extent_map_in_tree(em));
  59. WARN_ON(!list_empty(&em->list));
  60. kmem_cache_free(extent_map_cache, em);
  61. }
  62. }
  63. /* Do the math around the end of an extent, handling wrapping. */
  64. static u64 range_end(u64 start, u64 len)
  65. {
  66. if (start + len < start)
  67. return (u64)-1;
  68. return start + len;
  69. }
  70. static void dec_evictable_extent_maps(struct btrfs_inode *inode)
  71. {
  72. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  73. if (!btrfs_is_testing(fs_info) && is_fstree(btrfs_root_id(inode->root)))
  74. percpu_counter_dec(&fs_info->evictable_extent_maps);
  75. }
  76. static int tree_insert(struct rb_root *root, struct extent_map *em)
  77. {
  78. struct rb_node **p = &root->rb_node;
  79. struct rb_node *parent = NULL;
  80. struct extent_map *entry = NULL;
  81. struct rb_node *orig_parent = NULL;
  82. u64 end = range_end(em->start, em->len);
  83. while (*p) {
  84. parent = *p;
  85. entry = rb_entry(parent, struct extent_map, rb_node);
  86. if (em->start < entry->start)
  87. p = &(*p)->rb_left;
  88. else if (em->start >= extent_map_end(entry))
  89. p = &(*p)->rb_right;
  90. else
  91. return -EEXIST;
  92. }
  93. orig_parent = parent;
  94. while (parent && em->start >= extent_map_end(entry)) {
  95. parent = rb_next(parent);
  96. entry = rb_entry(parent, struct extent_map, rb_node);
  97. }
  98. if (parent)
  99. if (end > entry->start && em->start < extent_map_end(entry))
  100. return -EEXIST;
  101. parent = orig_parent;
  102. entry = rb_entry(parent, struct extent_map, rb_node);
  103. while (parent && em->start < entry->start) {
  104. parent = rb_prev(parent);
  105. entry = rb_entry(parent, struct extent_map, rb_node);
  106. }
  107. if (parent)
  108. if (end > entry->start && em->start < extent_map_end(entry))
  109. return -EEXIST;
  110. rb_link_node(&em->rb_node, orig_parent, p);
  111. rb_insert_color(&em->rb_node, root);
  112. return 0;
  113. }
  114. /*
  115. * Search through the tree for an extent_map with a given offset. If it can't
  116. * be found, try to find some neighboring extents
  117. */
  118. static struct rb_node *__tree_search(struct rb_root *root, u64 offset,
  119. struct rb_node **prev_or_next_ret)
  120. {
  121. struct rb_node *n = root->rb_node;
  122. struct rb_node *prev = NULL;
  123. struct rb_node *orig_prev = NULL;
  124. struct extent_map *entry;
  125. struct extent_map *prev_entry = NULL;
  126. ASSERT(prev_or_next_ret);
  127. while (n) {
  128. entry = rb_entry(n, struct extent_map, rb_node);
  129. prev = n;
  130. prev_entry = entry;
  131. if (offset < entry->start)
  132. n = n->rb_left;
  133. else if (offset >= extent_map_end(entry))
  134. n = n->rb_right;
  135. else
  136. return n;
  137. }
  138. orig_prev = prev;
  139. while (prev && offset >= extent_map_end(prev_entry)) {
  140. prev = rb_next(prev);
  141. prev_entry = rb_entry(prev, struct extent_map, rb_node);
  142. }
  143. /*
  144. * Previous extent map found, return as in this case the caller does not
  145. * care about the next one.
  146. */
  147. if (prev) {
  148. *prev_or_next_ret = prev;
  149. return NULL;
  150. }
  151. prev = orig_prev;
  152. prev_entry = rb_entry(prev, struct extent_map, rb_node);
  153. while (prev && offset < prev_entry->start) {
  154. prev = rb_prev(prev);
  155. prev_entry = rb_entry(prev, struct extent_map, rb_node);
  156. }
  157. *prev_or_next_ret = prev;
  158. return NULL;
  159. }
  160. static inline u64 extent_map_block_len(const struct extent_map *em)
  161. {
  162. if (extent_map_is_compressed(em))
  163. return em->disk_num_bytes;
  164. return em->len;
  165. }
  166. static inline u64 extent_map_block_end(const struct extent_map *em)
  167. {
  168. const u64 block_start = extent_map_block_start(em);
  169. const u64 block_end = block_start + extent_map_block_len(em);
  170. if (block_end < block_start)
  171. return (u64)-1;
  172. return block_end;
  173. }
  174. static bool can_merge_extent_map(const struct extent_map *em)
  175. {
  176. if (em->flags & EXTENT_FLAG_PINNED)
  177. return false;
  178. /* Don't merge compressed extents, we need to know their actual size. */
  179. if (extent_map_is_compressed(em))
  180. return false;
  181. if (em->flags & EXTENT_FLAG_LOGGING)
  182. return false;
  183. /*
  184. * We don't want to merge stuff that hasn't been written to the log yet
  185. * since it may not reflect exactly what is on disk, and that would be
  186. * bad.
  187. */
  188. if (!list_empty(&em->list))
  189. return false;
  190. return true;
  191. }
  192. /* Check to see if two extent_map structs are adjacent and safe to merge. */
  193. static bool mergeable_maps(const struct extent_map *prev, const struct extent_map *next)
  194. {
  195. if (extent_map_end(prev) != next->start)
  196. return false;
  197. /*
  198. * The merged flag is not an on-disk flag, it just indicates we had the
  199. * extent maps of 2 (or more) adjacent extents merged, so factor it out.
  200. */
  201. if ((prev->flags & ~EXTENT_FLAG_MERGED) !=
  202. (next->flags & ~EXTENT_FLAG_MERGED))
  203. return false;
  204. if (next->disk_bytenr < EXTENT_MAP_LAST_BYTE - 1)
  205. return extent_map_block_start(next) == extent_map_block_end(prev);
  206. /* HOLES and INLINE extents. */
  207. return next->disk_bytenr == prev->disk_bytenr;
  208. }
  209. /*
  210. * Handle the on-disk data extents merge for @prev and @next.
  211. *
  212. * @prev: left extent to merge
  213. * @next: right extent to merge
  214. * @merged: the extent we will not discard after the merge; updated with new values
  215. *
  216. * After this, one of the two extents is the new merged extent and the other is
  217. * removed from the tree and likely freed. Note that @merged is one of @prev/@next
  218. * so there is const/non-const aliasing occurring here.
  219. *
  220. * Only touches disk_bytenr/disk_num_bytes/offset/ram_bytes.
  221. * For now only uncompressed regular extent can be merged.
  222. */
  223. static void merge_ondisk_extents(const struct extent_map *prev, const struct extent_map *next,
  224. struct extent_map *merged)
  225. {
  226. u64 new_disk_bytenr;
  227. u64 new_disk_num_bytes;
  228. u64 new_offset;
  229. /* @prev and @next should not be compressed. */
  230. ASSERT(!extent_map_is_compressed(prev));
  231. ASSERT(!extent_map_is_compressed(next));
  232. /*
  233. * There are two different cases where @prev and @next can be merged.
  234. *
  235. * 1) They are referring to the same data extent:
  236. *
  237. * |<----- data extent A ----->|
  238. * |<- prev ->|<- next ->|
  239. *
  240. * 2) They are referring to different data extents but still adjacent:
  241. *
  242. * |<-- data extent A -->|<-- data extent B -->|
  243. * |<- prev ->|<- next ->|
  244. *
  245. * The calculation here always merges the data extents first, then updates
  246. * @offset using the new data extents.
  247. *
  248. * For case 1), the merged data extent would be the same.
  249. * For case 2), we just merge the two data extents into one.
  250. */
  251. new_disk_bytenr = min(prev->disk_bytenr, next->disk_bytenr);
  252. new_disk_num_bytes = max(prev->disk_bytenr + prev->disk_num_bytes,
  253. next->disk_bytenr + next->disk_num_bytes) -
  254. new_disk_bytenr;
  255. new_offset = prev->disk_bytenr + prev->offset - new_disk_bytenr;
  256. merged->disk_bytenr = new_disk_bytenr;
  257. merged->disk_num_bytes = new_disk_num_bytes;
  258. merged->ram_bytes = new_disk_num_bytes;
  259. merged->offset = new_offset;
  260. }
  261. static void dump_extent_map(struct btrfs_fs_info *fs_info, const char *prefix,
  262. struct extent_map *em)
  263. {
  264. if (!IS_ENABLED(CONFIG_BTRFS_DEBUG))
  265. return;
  266. btrfs_crit(fs_info,
  267. "%s, start=%llu len=%llu disk_bytenr=%llu disk_num_bytes=%llu ram_bytes=%llu offset=%llu flags=0x%x",
  268. prefix, em->start, em->len, em->disk_bytenr, em->disk_num_bytes,
  269. em->ram_bytes, em->offset, em->flags);
  270. ASSERT(0);
  271. }
  272. /* Internal sanity checks for btrfs debug builds. */
  273. static void validate_extent_map(struct btrfs_fs_info *fs_info, struct extent_map *em)
  274. {
  275. if (!IS_ENABLED(CONFIG_BTRFS_DEBUG))
  276. return;
  277. if (em->disk_bytenr < EXTENT_MAP_LAST_BYTE) {
  278. if (em->disk_num_bytes == 0)
  279. dump_extent_map(fs_info, "zero disk_num_bytes", em);
  280. if (em->offset + em->len > em->ram_bytes)
  281. dump_extent_map(fs_info, "ram_bytes too small", em);
  282. if (em->offset + em->len > em->disk_num_bytes &&
  283. !extent_map_is_compressed(em))
  284. dump_extent_map(fs_info, "disk_num_bytes too small", em);
  285. if (!extent_map_is_compressed(em) &&
  286. em->ram_bytes != em->disk_num_bytes)
  287. dump_extent_map(fs_info,
  288. "ram_bytes mismatch with disk_num_bytes for non-compressed em",
  289. em);
  290. } else if (em->offset) {
  291. dump_extent_map(fs_info, "non-zero offset for hole/inline", em);
  292. }
  293. }
  294. static void try_merge_map(struct btrfs_inode *inode, struct extent_map *em)
  295. {
  296. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  297. struct extent_map_tree *tree = &inode->extent_tree;
  298. struct extent_map *merge = NULL;
  299. struct rb_node *rb;
  300. /*
  301. * We can't modify an extent map that is in the tree and that is being
  302. * used by another task, as it can cause that other task to see it in
  303. * inconsistent state during the merging. We always have 1 reference for
  304. * the tree and 1 for this task (which is unpinning the extent map or
  305. * clearing the logging flag), so anything > 2 means it's being used by
  306. * other tasks too.
  307. */
  308. if (refcount_read(&em->refs) > 2)
  309. return;
  310. if (!can_merge_extent_map(em))
  311. return;
  312. if (em->start != 0) {
  313. rb = rb_prev(&em->rb_node);
  314. if (rb)
  315. merge = rb_entry(rb, struct extent_map, rb_node);
  316. if (rb && can_merge_extent_map(merge) && mergeable_maps(merge, em)) {
  317. em->start = merge->start;
  318. em->len += merge->len;
  319. em->generation = max(em->generation, merge->generation);
  320. if (em->disk_bytenr < EXTENT_MAP_LAST_BYTE)
  321. merge_ondisk_extents(merge, em, em);
  322. em->flags |= EXTENT_FLAG_MERGED;
  323. validate_extent_map(fs_info, em);
  324. rb_erase(&merge->rb_node, &tree->root);
  325. RB_CLEAR_NODE(&merge->rb_node);
  326. free_extent_map(merge);
  327. dec_evictable_extent_maps(inode);
  328. }
  329. }
  330. rb = rb_next(&em->rb_node);
  331. if (rb)
  332. merge = rb_entry(rb, struct extent_map, rb_node);
  333. if (rb && can_merge_extent_map(merge) && mergeable_maps(em, merge)) {
  334. em->len += merge->len;
  335. if (em->disk_bytenr < EXTENT_MAP_LAST_BYTE)
  336. merge_ondisk_extents(em, merge, em);
  337. validate_extent_map(fs_info, em);
  338. rb_erase(&merge->rb_node, &tree->root);
  339. RB_CLEAR_NODE(&merge->rb_node);
  340. em->generation = max(em->generation, merge->generation);
  341. em->flags |= EXTENT_FLAG_MERGED;
  342. free_extent_map(merge);
  343. dec_evictable_extent_maps(inode);
  344. }
  345. }
  346. /*
  347. * Unpin an extent from the cache.
  348. *
  349. * @inode: the inode from which we are unpinning an extent range
  350. * @start: logical offset in the file
  351. * @len: length of the extent
  352. * @gen: generation that this extent has been modified in
  353. *
  354. * Called after an extent has been written to disk properly. Set the generation
  355. * to the generation that actually added the file item to the inode so we know
  356. * we need to sync this extent when we call fsync().
  357. *
  358. * Returns: 0 on success
  359. * -ENOENT when the extent is not found in the tree
  360. * -EUCLEAN if the found extent does not match the expected start
  361. */
  362. int unpin_extent_cache(struct btrfs_inode *inode, u64 start, u64 len, u64 gen)
  363. {
  364. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  365. struct extent_map_tree *tree = &inode->extent_tree;
  366. int ret = 0;
  367. struct extent_map *em;
  368. write_lock(&tree->lock);
  369. em = lookup_extent_mapping(tree, start, len);
  370. if (WARN_ON(!em)) {
  371. btrfs_warn(fs_info,
  372. "no extent map found for inode %llu (root %lld) when unpinning extent range [%llu, %llu), generation %llu",
  373. btrfs_ino(inode), btrfs_root_id(inode->root),
  374. start, start + len, gen);
  375. ret = -ENOENT;
  376. goto out;
  377. }
  378. if (WARN_ON(em->start != start)) {
  379. btrfs_warn(fs_info,
  380. "found extent map for inode %llu (root %lld) with unexpected start offset %llu when unpinning extent range [%llu, %llu), generation %llu",
  381. btrfs_ino(inode), btrfs_root_id(inode->root),
  382. em->start, start, start + len, gen);
  383. ret = -EUCLEAN;
  384. goto out;
  385. }
  386. em->generation = gen;
  387. em->flags &= ~EXTENT_FLAG_PINNED;
  388. try_merge_map(inode, em);
  389. out:
  390. write_unlock(&tree->lock);
  391. free_extent_map(em);
  392. return ret;
  393. }
  394. void clear_em_logging(struct btrfs_inode *inode, struct extent_map *em)
  395. {
  396. lockdep_assert_held_write(&inode->extent_tree.lock);
  397. em->flags &= ~EXTENT_FLAG_LOGGING;
  398. if (extent_map_in_tree(em))
  399. try_merge_map(inode, em);
  400. }
  401. static inline void setup_extent_mapping(struct btrfs_inode *inode,
  402. struct extent_map *em,
  403. int modified)
  404. {
  405. refcount_inc(&em->refs);
  406. ASSERT(list_empty(&em->list));
  407. if (modified)
  408. list_add(&em->list, &inode->extent_tree.modified_extents);
  409. else
  410. try_merge_map(inode, em);
  411. }
  412. /*
  413. * Add a new extent map to an inode's extent map tree.
  414. *
  415. * @inode: the target inode
  416. * @em: map to insert
  417. * @modified: indicate whether the given @em should be added to the
  418. * modified list, which indicates the extent needs to be logged
  419. *
  420. * Insert @em into the @inode's extent map tree or perform a simple
  421. * forward/backward merge with existing mappings. The extent_map struct passed
  422. * in will be inserted into the tree directly, with an additional reference
  423. * taken, or a reference dropped if the merge attempt was successful.
  424. */
  425. static int add_extent_mapping(struct btrfs_inode *inode,
  426. struct extent_map *em, int modified)
  427. {
  428. struct extent_map_tree *tree = &inode->extent_tree;
  429. struct btrfs_root *root = inode->root;
  430. struct btrfs_fs_info *fs_info = root->fs_info;
  431. int ret;
  432. lockdep_assert_held_write(&tree->lock);
  433. validate_extent_map(fs_info, em);
  434. ret = tree_insert(&tree->root, em);
  435. if (ret)
  436. return ret;
  437. setup_extent_mapping(inode, em, modified);
  438. if (!btrfs_is_testing(fs_info) && is_fstree(btrfs_root_id(root)))
  439. percpu_counter_inc(&fs_info->evictable_extent_maps);
  440. return 0;
  441. }
  442. static struct extent_map *
  443. __lookup_extent_mapping(struct extent_map_tree *tree,
  444. u64 start, u64 len, int strict)
  445. {
  446. struct extent_map *em;
  447. struct rb_node *rb_node;
  448. struct rb_node *prev_or_next = NULL;
  449. u64 end = range_end(start, len);
  450. rb_node = __tree_search(&tree->root, start, &prev_or_next);
  451. if (!rb_node) {
  452. if (prev_or_next)
  453. rb_node = prev_or_next;
  454. else
  455. return NULL;
  456. }
  457. em = rb_entry(rb_node, struct extent_map, rb_node);
  458. if (strict && !(end > em->start && start < extent_map_end(em)))
  459. return NULL;
  460. refcount_inc(&em->refs);
  461. return em;
  462. }
  463. /*
  464. * Lookup extent_map that intersects @start + @len range.
  465. *
  466. * @tree: tree to lookup in
  467. * @start: byte offset to start the search
  468. * @len: length of the lookup range
  469. *
  470. * Find and return the first extent_map struct in @tree that intersects the
  471. * [start, len] range. There may be additional objects in the tree that
  472. * intersect, so check the object returned carefully to make sure that no
  473. * additional lookups are needed.
  474. */
  475. struct extent_map *lookup_extent_mapping(struct extent_map_tree *tree,
  476. u64 start, u64 len)
  477. {
  478. return __lookup_extent_mapping(tree, start, len, 1);
  479. }
  480. /*
  481. * Find a nearby extent map intersecting @start + @len (not an exact search).
  482. *
  483. * @tree: tree to lookup in
  484. * @start: byte offset to start the search
  485. * @len: length of the lookup range
  486. *
  487. * Find and return the first extent_map struct in @tree that intersects the
  488. * [start, len] range.
  489. *
  490. * If one can't be found, any nearby extent may be returned
  491. */
  492. struct extent_map *search_extent_mapping(struct extent_map_tree *tree,
  493. u64 start, u64 len)
  494. {
  495. return __lookup_extent_mapping(tree, start, len, 0);
  496. }
  497. /*
  498. * Remove an extent_map from its inode's extent tree.
  499. *
  500. * @inode: the inode the extent map belongs to
  501. * @em: extent map being removed
  502. *
  503. * Remove @em from the extent tree of @inode. No reference counts are dropped,
  504. * and no checks are done to see if the range is in use.
  505. */
  506. void remove_extent_mapping(struct btrfs_inode *inode, struct extent_map *em)
  507. {
  508. struct extent_map_tree *tree = &inode->extent_tree;
  509. lockdep_assert_held_write(&tree->lock);
  510. WARN_ON(em->flags & EXTENT_FLAG_PINNED);
  511. rb_erase(&em->rb_node, &tree->root);
  512. if (!(em->flags & EXTENT_FLAG_LOGGING))
  513. list_del_init(&em->list);
  514. RB_CLEAR_NODE(&em->rb_node);
  515. dec_evictable_extent_maps(inode);
  516. }
  517. static void replace_extent_mapping(struct btrfs_inode *inode,
  518. struct extent_map *cur,
  519. struct extent_map *new,
  520. int modified)
  521. {
  522. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  523. struct extent_map_tree *tree = &inode->extent_tree;
  524. lockdep_assert_held_write(&tree->lock);
  525. validate_extent_map(fs_info, new);
  526. WARN_ON(cur->flags & EXTENT_FLAG_PINNED);
  527. ASSERT(extent_map_in_tree(cur));
  528. if (!(cur->flags & EXTENT_FLAG_LOGGING))
  529. list_del_init(&cur->list);
  530. rb_replace_node(&cur->rb_node, &new->rb_node, &tree->root);
  531. RB_CLEAR_NODE(&cur->rb_node);
  532. setup_extent_mapping(inode, new, modified);
  533. }
  534. static struct extent_map *next_extent_map(const struct extent_map *em)
  535. {
  536. struct rb_node *next;
  537. next = rb_next(&em->rb_node);
  538. if (!next)
  539. return NULL;
  540. return container_of(next, struct extent_map, rb_node);
  541. }
  542. static struct extent_map *prev_extent_map(struct extent_map *em)
  543. {
  544. struct rb_node *prev;
  545. prev = rb_prev(&em->rb_node);
  546. if (!prev)
  547. return NULL;
  548. return container_of(prev, struct extent_map, rb_node);
  549. }
  550. /*
  551. * Helper for btrfs_get_extent. Given an existing extent in the tree,
  552. * the existing extent is the nearest extent to map_start,
  553. * and an extent that you want to insert, deal with overlap and insert
  554. * the best fitted new extent into the tree.
  555. */
  556. static noinline int merge_extent_mapping(struct btrfs_inode *inode,
  557. struct extent_map *existing,
  558. struct extent_map *em,
  559. u64 map_start)
  560. {
  561. struct extent_map *prev;
  562. struct extent_map *next;
  563. u64 start;
  564. u64 end;
  565. u64 start_diff;
  566. if (map_start < em->start || map_start >= extent_map_end(em))
  567. return -EINVAL;
  568. if (existing->start > map_start) {
  569. next = existing;
  570. prev = prev_extent_map(next);
  571. } else {
  572. prev = existing;
  573. next = next_extent_map(prev);
  574. }
  575. start = prev ? extent_map_end(prev) : em->start;
  576. start = max_t(u64, start, em->start);
  577. end = next ? next->start : extent_map_end(em);
  578. end = min_t(u64, end, extent_map_end(em));
  579. start_diff = start - em->start;
  580. em->start = start;
  581. em->len = end - start;
  582. if (em->disk_bytenr < EXTENT_MAP_LAST_BYTE)
  583. em->offset += start_diff;
  584. return add_extent_mapping(inode, em, 0);
  585. }
  586. /*
  587. * Add extent mapping into an inode's extent map tree.
  588. *
  589. * @inode: target inode
  590. * @em_in: extent we are inserting
  591. * @start: start of the logical range btrfs_get_extent() is requesting
  592. * @len: length of the logical range btrfs_get_extent() is requesting
  593. *
  594. * Note that @em_in's range may be different from [start, start+len),
  595. * but they must be overlapped.
  596. *
  597. * Insert @em_in into the inode's extent map tree. In case there is an
  598. * overlapping range, handle the -EEXIST by either:
  599. * a) Returning the existing extent in @em_in if @start is within the
  600. * existing em.
  601. * b) Merge the existing extent with @em_in passed in.
  602. *
  603. * Return 0 on success, otherwise -EEXIST.
  604. *
  605. */
  606. int btrfs_add_extent_mapping(struct btrfs_inode *inode,
  607. struct extent_map **em_in, u64 start, u64 len)
  608. {
  609. int ret;
  610. struct extent_map *em = *em_in;
  611. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  612. /*
  613. * Tree-checker should have rejected any inline extent with non-zero
  614. * file offset. Here just do a sanity check.
  615. */
  616. if (em->disk_bytenr == EXTENT_MAP_INLINE)
  617. ASSERT(em->start == 0);
  618. ret = add_extent_mapping(inode, em, 0);
  619. /* it is possible that someone inserted the extent into the tree
  620. * while we had the lock dropped. It is also possible that
  621. * an overlapping map exists in the tree
  622. */
  623. if (ret == -EEXIST) {
  624. struct extent_map *existing;
  625. existing = search_extent_mapping(&inode->extent_tree, start, len);
  626. trace_btrfs_handle_em_exist(fs_info, existing, em, start, len);
  627. /*
  628. * existing will always be non-NULL, since there must be
  629. * extent causing the -EEXIST.
  630. */
  631. if (start >= existing->start &&
  632. start < extent_map_end(existing)) {
  633. free_extent_map(em);
  634. *em_in = existing;
  635. ret = 0;
  636. } else {
  637. u64 orig_start = em->start;
  638. u64 orig_len = em->len;
  639. /*
  640. * The existing extent map is the one nearest to
  641. * the [start, start + len) range which overlaps
  642. */
  643. ret = merge_extent_mapping(inode, existing, em, start);
  644. if (WARN_ON(ret)) {
  645. free_extent_map(em);
  646. *em_in = NULL;
  647. btrfs_warn(fs_info,
  648. "extent map merge error existing [%llu, %llu) with em [%llu, %llu) start %llu",
  649. existing->start, extent_map_end(existing),
  650. orig_start, orig_start + orig_len, start);
  651. }
  652. free_extent_map(existing);
  653. }
  654. }
  655. ASSERT(ret == 0 || ret == -EEXIST);
  656. return ret;
  657. }
  658. /*
  659. * Drop all extent maps from a tree in the fastest possible way, rescheduling
  660. * if needed. This avoids searching the tree, from the root down to the first
  661. * extent map, before each deletion.
  662. */
  663. static void drop_all_extent_maps_fast(struct btrfs_inode *inode)
  664. {
  665. struct extent_map_tree *tree = &inode->extent_tree;
  666. struct rb_node *node;
  667. write_lock(&tree->lock);
  668. node = rb_first(&tree->root);
  669. while (node) {
  670. struct extent_map *em;
  671. struct rb_node *next = rb_next(node);
  672. em = rb_entry(node, struct extent_map, rb_node);
  673. em->flags &= ~(EXTENT_FLAG_PINNED | EXTENT_FLAG_LOGGING);
  674. remove_extent_mapping(inode, em);
  675. free_extent_map(em);
  676. if (cond_resched_rwlock_write(&tree->lock))
  677. node = rb_first(&tree->root);
  678. else
  679. node = next;
  680. }
  681. write_unlock(&tree->lock);
  682. }
  683. /*
  684. * Drop all extent maps in a given range.
  685. *
  686. * @inode: The target inode.
  687. * @start: Start offset of the range.
  688. * @end: End offset of the range (inclusive value).
  689. * @skip_pinned: Indicate if pinned extent maps should be ignored or not.
  690. *
  691. * This drops all the extent maps that intersect the given range [@start, @end].
  692. * Extent maps that partially overlap the range and extend behind or beyond it,
  693. * are split.
  694. * The caller should have locked an appropriate file range in the inode's io
  695. * tree before calling this function.
  696. */
  697. void btrfs_drop_extent_map_range(struct btrfs_inode *inode, u64 start, u64 end,
  698. bool skip_pinned)
  699. {
  700. struct extent_map *split;
  701. struct extent_map *split2;
  702. struct extent_map *em;
  703. struct extent_map_tree *em_tree = &inode->extent_tree;
  704. u64 len = end - start + 1;
  705. WARN_ON(end < start);
  706. if (end == (u64)-1) {
  707. if (start == 0 && !skip_pinned) {
  708. drop_all_extent_maps_fast(inode);
  709. return;
  710. }
  711. len = (u64)-1;
  712. } else {
  713. /* Make end offset exclusive for use in the loop below. */
  714. end++;
  715. }
  716. /*
  717. * It's ok if we fail to allocate the extent maps, see the comment near
  718. * the bottom of the loop below. We only need two spare extent maps in
  719. * the worst case, where the first extent map that intersects our range
  720. * starts before the range and the last extent map that intersects our
  721. * range ends after our range (and they might be the same extent map),
  722. * because we need to split those two extent maps at the boundaries.
  723. */
  724. split = alloc_extent_map();
  725. split2 = alloc_extent_map();
  726. write_lock(&em_tree->lock);
  727. em = lookup_extent_mapping(em_tree, start, len);
  728. while (em) {
  729. /* extent_map_end() returns exclusive value (last byte + 1). */
  730. const u64 em_end = extent_map_end(em);
  731. struct extent_map *next_em = NULL;
  732. u64 gen;
  733. unsigned long flags;
  734. bool modified;
  735. if (em_end < end) {
  736. next_em = next_extent_map(em);
  737. if (next_em) {
  738. if (next_em->start < end)
  739. refcount_inc(&next_em->refs);
  740. else
  741. next_em = NULL;
  742. }
  743. }
  744. if (skip_pinned && (em->flags & EXTENT_FLAG_PINNED)) {
  745. start = em_end;
  746. goto next;
  747. }
  748. flags = em->flags;
  749. /*
  750. * In case we split the extent map, we want to preserve the
  751. * EXTENT_FLAG_LOGGING flag on our extent map, but we don't want
  752. * it on the new extent maps.
  753. */
  754. em->flags &= ~(EXTENT_FLAG_PINNED | EXTENT_FLAG_LOGGING);
  755. modified = !list_empty(&em->list);
  756. /*
  757. * The extent map does not cross our target range, so no need to
  758. * split it, we can remove it directly.
  759. */
  760. if (em->start >= start && em_end <= end)
  761. goto remove_em;
  762. gen = em->generation;
  763. if (em->start < start) {
  764. if (!split) {
  765. split = split2;
  766. split2 = NULL;
  767. if (!split)
  768. goto remove_em;
  769. }
  770. split->start = em->start;
  771. split->len = start - em->start;
  772. if (em->disk_bytenr < EXTENT_MAP_LAST_BYTE) {
  773. split->disk_bytenr = em->disk_bytenr;
  774. split->disk_num_bytes = em->disk_num_bytes;
  775. split->offset = em->offset;
  776. split->ram_bytes = em->ram_bytes;
  777. } else {
  778. split->disk_bytenr = em->disk_bytenr;
  779. split->disk_num_bytes = 0;
  780. split->offset = 0;
  781. split->ram_bytes = split->len;
  782. }
  783. split->generation = gen;
  784. split->flags = flags;
  785. replace_extent_mapping(inode, em, split, modified);
  786. free_extent_map(split);
  787. split = split2;
  788. split2 = NULL;
  789. }
  790. if (em_end > end) {
  791. if (!split) {
  792. split = split2;
  793. split2 = NULL;
  794. if (!split)
  795. goto remove_em;
  796. }
  797. split->start = end;
  798. split->len = em_end - end;
  799. split->disk_bytenr = em->disk_bytenr;
  800. split->flags = flags;
  801. split->generation = gen;
  802. if (em->disk_bytenr < EXTENT_MAP_LAST_BYTE) {
  803. split->disk_num_bytes = em->disk_num_bytes;
  804. split->offset = em->offset + end - em->start;
  805. split->ram_bytes = em->ram_bytes;
  806. } else {
  807. split->disk_num_bytes = 0;
  808. split->offset = 0;
  809. split->ram_bytes = split->len;
  810. }
  811. if (extent_map_in_tree(em)) {
  812. replace_extent_mapping(inode, em, split, modified);
  813. } else {
  814. int ret;
  815. ret = add_extent_mapping(inode, split, modified);
  816. /* Logic error, shouldn't happen. */
  817. ASSERT(ret == 0);
  818. if (WARN_ON(ret != 0) && modified)
  819. btrfs_set_inode_full_sync(inode);
  820. }
  821. free_extent_map(split);
  822. split = NULL;
  823. }
  824. remove_em:
  825. if (extent_map_in_tree(em)) {
  826. /*
  827. * If the extent map is still in the tree it means that
  828. * either of the following is true:
  829. *
  830. * 1) It fits entirely in our range (doesn't end beyond
  831. * it or starts before it);
  832. *
  833. * 2) It starts before our range and/or ends after our
  834. * range, and we were not able to allocate the extent
  835. * maps for split operations, @split and @split2.
  836. *
  837. * If we are at case 2) then we just remove the entire
  838. * extent map - this is fine since if anyone needs it to
  839. * access the subranges outside our range, will just
  840. * load it again from the subvolume tree's file extent
  841. * item. However if the extent map was in the list of
  842. * modified extents, then we must mark the inode for a
  843. * full fsync, otherwise a fast fsync will miss this
  844. * extent if it's new and needs to be logged.
  845. */
  846. if ((em->start < start || em_end > end) && modified) {
  847. ASSERT(!split);
  848. btrfs_set_inode_full_sync(inode);
  849. }
  850. remove_extent_mapping(inode, em);
  851. }
  852. /*
  853. * Once for the tree reference (we replaced or removed the
  854. * extent map from the tree).
  855. */
  856. free_extent_map(em);
  857. next:
  858. /* Once for us (for our lookup reference). */
  859. free_extent_map(em);
  860. em = next_em;
  861. }
  862. write_unlock(&em_tree->lock);
  863. free_extent_map(split);
  864. free_extent_map(split2);
  865. }
  866. /*
  867. * Replace a range in the inode's extent map tree with a new extent map.
  868. *
  869. * @inode: The target inode.
  870. * @new_em: The new extent map to add to the inode's extent map tree.
  871. * @modified: Indicate if the new extent map should be added to the list of
  872. * modified extents (for fast fsync tracking).
  873. *
  874. * Drops all the extent maps in the inode's extent map tree that intersect the
  875. * range of the new extent map and adds the new extent map to the tree.
  876. * The caller should have locked an appropriate file range in the inode's io
  877. * tree before calling this function.
  878. */
  879. int btrfs_replace_extent_map_range(struct btrfs_inode *inode,
  880. struct extent_map *new_em,
  881. bool modified)
  882. {
  883. const u64 end = new_em->start + new_em->len - 1;
  884. struct extent_map_tree *tree = &inode->extent_tree;
  885. int ret;
  886. ASSERT(!extent_map_in_tree(new_em));
  887. /*
  888. * The caller has locked an appropriate file range in the inode's io
  889. * tree, but getting -EEXIST when adding the new extent map can still
  890. * happen in case there are extents that partially cover the range, and
  891. * this is due to two tasks operating on different parts of the extent.
  892. * See commit 18e83ac75bfe67 ("Btrfs: fix unexpected EEXIST from
  893. * btrfs_get_extent") for an example and details.
  894. */
  895. do {
  896. btrfs_drop_extent_map_range(inode, new_em->start, end, false);
  897. write_lock(&tree->lock);
  898. ret = add_extent_mapping(inode, new_em, modified);
  899. write_unlock(&tree->lock);
  900. } while (ret == -EEXIST);
  901. return ret;
  902. }
  903. /*
  904. * Split off the first pre bytes from the extent_map at [start, start + len],
  905. * and set the block_start for it to new_logical.
  906. *
  907. * This function is used when an ordered_extent needs to be split.
  908. */
  909. int split_extent_map(struct btrfs_inode *inode, u64 start, u64 len, u64 pre,
  910. u64 new_logical)
  911. {
  912. struct extent_map_tree *em_tree = &inode->extent_tree;
  913. struct extent_map *em;
  914. struct extent_map *split_pre = NULL;
  915. struct extent_map *split_mid = NULL;
  916. int ret = 0;
  917. unsigned long flags;
  918. ASSERT(pre != 0);
  919. ASSERT(pre < len);
  920. split_pre = alloc_extent_map();
  921. if (!split_pre)
  922. return -ENOMEM;
  923. split_mid = alloc_extent_map();
  924. if (!split_mid) {
  925. ret = -ENOMEM;
  926. goto out_free_pre;
  927. }
  928. lock_extent(&inode->io_tree, start, start + len - 1, NULL);
  929. write_lock(&em_tree->lock);
  930. em = lookup_extent_mapping(em_tree, start, len);
  931. if (!em) {
  932. ret = -EIO;
  933. goto out_unlock;
  934. }
  935. ASSERT(em->len == len);
  936. ASSERT(!extent_map_is_compressed(em));
  937. ASSERT(em->disk_bytenr < EXTENT_MAP_LAST_BYTE);
  938. ASSERT(em->flags & EXTENT_FLAG_PINNED);
  939. ASSERT(!(em->flags & EXTENT_FLAG_LOGGING));
  940. ASSERT(!list_empty(&em->list));
  941. flags = em->flags;
  942. em->flags &= ~EXTENT_FLAG_PINNED;
  943. /* First, replace the em with a new extent_map starting from * em->start */
  944. split_pre->start = em->start;
  945. split_pre->len = pre;
  946. split_pre->disk_bytenr = new_logical;
  947. split_pre->disk_num_bytes = split_pre->len;
  948. split_pre->offset = 0;
  949. split_pre->ram_bytes = split_pre->len;
  950. split_pre->flags = flags;
  951. split_pre->generation = em->generation;
  952. replace_extent_mapping(inode, em, split_pre, 1);
  953. /*
  954. * Now we only have an extent_map at:
  955. * [em->start, em->start + pre]
  956. */
  957. /* Insert the middle extent_map. */
  958. split_mid->start = em->start + pre;
  959. split_mid->len = em->len - pre;
  960. split_mid->disk_bytenr = extent_map_block_start(em) + pre;
  961. split_mid->disk_num_bytes = split_mid->len;
  962. split_mid->offset = 0;
  963. split_mid->ram_bytes = split_mid->len;
  964. split_mid->flags = flags;
  965. split_mid->generation = em->generation;
  966. add_extent_mapping(inode, split_mid, 1);
  967. /* Once for us */
  968. free_extent_map(em);
  969. /* Once for the tree */
  970. free_extent_map(em);
  971. out_unlock:
  972. write_unlock(&em_tree->lock);
  973. unlock_extent(&inode->io_tree, start, start + len - 1, NULL);
  974. free_extent_map(split_mid);
  975. out_free_pre:
  976. free_extent_map(split_pre);
  977. return ret;
  978. }
  979. struct btrfs_em_shrink_ctx {
  980. long nr_to_scan;
  981. long scanned;
  982. u64 last_ino;
  983. u64 last_root;
  984. };
  985. static long btrfs_scan_inode(struct btrfs_inode *inode, struct btrfs_em_shrink_ctx *ctx)
  986. {
  987. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  988. const u64 cur_fs_gen = btrfs_get_fs_generation(fs_info);
  989. struct extent_map_tree *tree = &inode->extent_tree;
  990. long nr_dropped = 0;
  991. struct rb_node *node;
  992. lockdep_assert_held_write(&tree->lock);
  993. /*
  994. * Take the mmap lock so that we serialize with the inode logging phase
  995. * of fsync because we may need to set the full sync flag on the inode,
  996. * in case we have to remove extent maps in the tree's list of modified
  997. * extents. If we set the full sync flag in the inode while an fsync is
  998. * in progress, we may risk missing new extents because before the flag
  999. * is set, fsync decides to only wait for writeback to complete and then
  1000. * during inode logging it sees the flag set and uses the subvolume tree
  1001. * to find new extents, which may not be there yet because ordered
  1002. * extents haven't completed yet.
  1003. *
  1004. * We also do a try lock because we don't want to block for too long and
  1005. * we are holding the extent map tree's lock in write mode.
  1006. */
  1007. if (!down_read_trylock(&inode->i_mmap_lock))
  1008. return 0;
  1009. node = rb_first(&tree->root);
  1010. while (node) {
  1011. struct rb_node *next = rb_next(node);
  1012. struct extent_map *em;
  1013. em = rb_entry(node, struct extent_map, rb_node);
  1014. ctx->scanned++;
  1015. if (em->flags & EXTENT_FLAG_PINNED)
  1016. goto next;
  1017. /*
  1018. * If the inode is in the list of modified extents (new) and its
  1019. * generation is the same (or is greater than) the current fs
  1020. * generation, it means it was not yet persisted so we have to
  1021. * set the full sync flag so that the next fsync will not miss
  1022. * it.
  1023. */
  1024. if (!list_empty(&em->list) && em->generation >= cur_fs_gen)
  1025. btrfs_set_inode_full_sync(inode);
  1026. remove_extent_mapping(inode, em);
  1027. trace_btrfs_extent_map_shrinker_remove_em(inode, em);
  1028. /* Drop the reference for the tree. */
  1029. free_extent_map(em);
  1030. nr_dropped++;
  1031. next:
  1032. if (ctx->scanned >= ctx->nr_to_scan)
  1033. break;
  1034. /*
  1035. * Stop if we need to reschedule or there's contention on the
  1036. * lock. This is to avoid slowing other tasks trying to take the
  1037. * lock.
  1038. */
  1039. if (need_resched() || rwlock_needbreak(&tree->lock) ||
  1040. btrfs_fs_closing(fs_info))
  1041. break;
  1042. node = next;
  1043. }
  1044. up_read(&inode->i_mmap_lock);
  1045. return nr_dropped;
  1046. }
  1047. static struct btrfs_inode *find_first_inode_to_shrink(struct btrfs_root *root,
  1048. u64 min_ino)
  1049. {
  1050. struct btrfs_inode *inode;
  1051. unsigned long from = min_ino;
  1052. xa_lock(&root->inodes);
  1053. while (true) {
  1054. struct extent_map_tree *tree;
  1055. inode = xa_find(&root->inodes, &from, ULONG_MAX, XA_PRESENT);
  1056. if (!inode)
  1057. break;
  1058. tree = &inode->extent_tree;
  1059. /*
  1060. * We want to be fast so if the lock is busy we don't want to
  1061. * spend time waiting for it (some task is about to do IO for
  1062. * the inode).
  1063. */
  1064. if (!write_trylock(&tree->lock))
  1065. goto next;
  1066. /*
  1067. * Skip inode if it doesn't have loaded extent maps, so we avoid
  1068. * getting a reference and doing an iput later. This includes
  1069. * cases like files that were opened for things like stat(2), or
  1070. * files with all extent maps previously released through the
  1071. * release folio callback (btrfs_release_folio()) or released in
  1072. * a previous run, or directories which never have extent maps.
  1073. */
  1074. if (RB_EMPTY_ROOT(&tree->root)) {
  1075. write_unlock(&tree->lock);
  1076. goto next;
  1077. }
  1078. if (igrab(&inode->vfs_inode))
  1079. break;
  1080. write_unlock(&tree->lock);
  1081. next:
  1082. from = btrfs_ino(inode) + 1;
  1083. cond_resched_lock(&root->inodes.xa_lock);
  1084. }
  1085. xa_unlock(&root->inodes);
  1086. return inode;
  1087. }
  1088. static long btrfs_scan_root(struct btrfs_root *root, struct btrfs_em_shrink_ctx *ctx)
  1089. {
  1090. struct btrfs_fs_info *fs_info = root->fs_info;
  1091. struct btrfs_inode *inode;
  1092. long nr_dropped = 0;
  1093. u64 min_ino = ctx->last_ino + 1;
  1094. inode = find_first_inode_to_shrink(root, min_ino);
  1095. while (inode) {
  1096. nr_dropped += btrfs_scan_inode(inode, ctx);
  1097. write_unlock(&inode->extent_tree.lock);
  1098. min_ino = btrfs_ino(inode) + 1;
  1099. ctx->last_ino = btrfs_ino(inode);
  1100. iput(&inode->vfs_inode);
  1101. if (ctx->scanned >= ctx->nr_to_scan ||
  1102. btrfs_fs_closing(fs_info))
  1103. break;
  1104. cond_resched();
  1105. inode = find_first_inode_to_shrink(root, min_ino);
  1106. }
  1107. if (inode) {
  1108. /*
  1109. * There are still inodes in this root or we happened to process
  1110. * the last one and reached the scan limit. In either case set
  1111. * the current root to this one, so we'll resume from the next
  1112. * inode if there is one or we will find out this was the last
  1113. * one and move to the next root.
  1114. */
  1115. ctx->last_root = btrfs_root_id(root);
  1116. } else {
  1117. /*
  1118. * No more inodes in this root, set extent_map_shrinker_last_ino to 0 so
  1119. * that when processing the next root we start from its first inode.
  1120. */
  1121. ctx->last_ino = 0;
  1122. ctx->last_root = btrfs_root_id(root) + 1;
  1123. }
  1124. return nr_dropped;
  1125. }
  1126. static void btrfs_extent_map_shrinker_worker(struct work_struct *work)
  1127. {
  1128. struct btrfs_fs_info *fs_info;
  1129. struct btrfs_em_shrink_ctx ctx;
  1130. u64 start_root_id;
  1131. u64 next_root_id;
  1132. bool cycled = false;
  1133. long nr_dropped = 0;
  1134. fs_info = container_of(work, struct btrfs_fs_info, extent_map_shrinker_work);
  1135. ctx.scanned = 0;
  1136. ctx.nr_to_scan = atomic64_read(&fs_info->extent_map_shrinker_nr_to_scan);
  1137. /*
  1138. * In case we have multiple tasks running this shrinker, make the next
  1139. * one start from the next inode in case it starts before we finish.
  1140. */
  1141. spin_lock(&fs_info->extent_map_shrinker_lock);
  1142. ctx.last_ino = fs_info->extent_map_shrinker_last_ino;
  1143. fs_info->extent_map_shrinker_last_ino++;
  1144. ctx.last_root = fs_info->extent_map_shrinker_last_root;
  1145. spin_unlock(&fs_info->extent_map_shrinker_lock);
  1146. start_root_id = ctx.last_root;
  1147. next_root_id = ctx.last_root;
  1148. if (trace_btrfs_extent_map_shrinker_scan_enter_enabled()) {
  1149. s64 nr = percpu_counter_sum_positive(&fs_info->evictable_extent_maps);
  1150. trace_btrfs_extent_map_shrinker_scan_enter(fs_info, ctx.nr_to_scan,
  1151. nr, ctx.last_root,
  1152. ctx.last_ino);
  1153. }
  1154. while (ctx.scanned < ctx.nr_to_scan && !btrfs_fs_closing(fs_info)) {
  1155. struct btrfs_root *root;
  1156. unsigned long count;
  1157. cond_resched();
  1158. spin_lock(&fs_info->fs_roots_radix_lock);
  1159. count = radix_tree_gang_lookup(&fs_info->fs_roots_radix,
  1160. (void **)&root,
  1161. (unsigned long)next_root_id, 1);
  1162. if (count == 0) {
  1163. spin_unlock(&fs_info->fs_roots_radix_lock);
  1164. if (start_root_id > 0 && !cycled) {
  1165. next_root_id = 0;
  1166. ctx.last_root = 0;
  1167. ctx.last_ino = 0;
  1168. cycled = true;
  1169. continue;
  1170. }
  1171. break;
  1172. }
  1173. next_root_id = btrfs_root_id(root) + 1;
  1174. root = btrfs_grab_root(root);
  1175. spin_unlock(&fs_info->fs_roots_radix_lock);
  1176. if (!root)
  1177. continue;
  1178. if (is_fstree(btrfs_root_id(root)))
  1179. nr_dropped += btrfs_scan_root(root, &ctx);
  1180. btrfs_put_root(root);
  1181. }
  1182. /*
  1183. * In case of multiple tasks running this extent map shrinking code this
  1184. * isn't perfect but it's simple and silences things like KCSAN. It's
  1185. * not possible to know which task made more progress because we can
  1186. * cycle back to the first root and first inode if it's not the first
  1187. * time the shrinker ran, see the above logic. Also a task that started
  1188. * later may finish ealier than another task and made less progress. So
  1189. * make this simple and update to the progress of the last task that
  1190. * finished, with the occasional possiblity of having two consecutive
  1191. * runs of the shrinker process the same inodes.
  1192. */
  1193. spin_lock(&fs_info->extent_map_shrinker_lock);
  1194. fs_info->extent_map_shrinker_last_ino = ctx.last_ino;
  1195. fs_info->extent_map_shrinker_last_root = ctx.last_root;
  1196. spin_unlock(&fs_info->extent_map_shrinker_lock);
  1197. if (trace_btrfs_extent_map_shrinker_scan_exit_enabled()) {
  1198. s64 nr = percpu_counter_sum_positive(&fs_info->evictable_extent_maps);
  1199. trace_btrfs_extent_map_shrinker_scan_exit(fs_info, nr_dropped,
  1200. nr, ctx.last_root,
  1201. ctx.last_ino);
  1202. }
  1203. atomic64_set(&fs_info->extent_map_shrinker_nr_to_scan, 0);
  1204. }
  1205. void btrfs_free_extent_maps(struct btrfs_fs_info *fs_info, long nr_to_scan)
  1206. {
  1207. /*
  1208. * Do nothing if the shrinker is already running. In case of high memory
  1209. * pressure we can have a lot of tasks calling us and all passing the
  1210. * same nr_to_scan value, but in reality we may need only to free
  1211. * nr_to_scan extent maps (or less). In case we need to free more than
  1212. * that, we will be called again by the fs shrinker, so no worries about
  1213. * not doing enough work to reclaim memory from extent maps.
  1214. * We can also be repeatedly called with the same nr_to_scan value
  1215. * simply because the shrinker runs asynchronously and multiple calls
  1216. * to this function are made before the shrinker does enough progress.
  1217. *
  1218. * That's why we set the atomic counter to nr_to_scan only if its
  1219. * current value is zero, instead of incrementing the counter by
  1220. * nr_to_scan.
  1221. */
  1222. if (atomic64_cmpxchg(&fs_info->extent_map_shrinker_nr_to_scan, 0, nr_to_scan) != 0)
  1223. return;
  1224. queue_work(system_unbound_wq, &fs_info->extent_map_shrinker_work);
  1225. }
  1226. void btrfs_init_extent_map_shrinker_work(struct btrfs_fs_info *fs_info)
  1227. {
  1228. atomic64_set(&fs_info->extent_map_shrinker_nr_to_scan, 0);
  1229. INIT_WORK(&fs_info->extent_map_shrinker_work, btrfs_extent_map_shrinker_worker);
  1230. }