extent_map.c 39 KB

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