defrag.c 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Copyright (C) 2007 Oracle. All rights reserved.
  4. */
  5. #include <linux/sched.h>
  6. #include "ctree.h"
  7. #include "disk-io.h"
  8. #include "transaction.h"
  9. #include "locking.h"
  10. #include "accessors.h"
  11. #include "messages.h"
  12. #include "delalloc-space.h"
  13. #include "subpage.h"
  14. #include "defrag.h"
  15. #include "file-item.h"
  16. #include "super.h"
  17. static struct kmem_cache *btrfs_inode_defrag_cachep;
  18. /*
  19. * When auto defrag is enabled we queue up these defrag structs to remember
  20. * which inodes need defragging passes.
  21. */
  22. struct inode_defrag {
  23. struct rb_node rb_node;
  24. /* Inode number */
  25. u64 ino;
  26. /*
  27. * Transid where the defrag was added, we search for extents newer than
  28. * this.
  29. */
  30. u64 transid;
  31. /* Root objectid */
  32. u64 root;
  33. /*
  34. * The extent size threshold for autodefrag.
  35. *
  36. * This value is different for compressed/non-compressed extents, thus
  37. * needs to be passed from higher layer.
  38. * (aka, inode_should_defrag())
  39. */
  40. u32 extent_thresh;
  41. };
  42. static int compare_inode_defrag(const struct inode_defrag *defrag1,
  43. const struct inode_defrag *defrag2)
  44. {
  45. if (defrag1->root > defrag2->root)
  46. return 1;
  47. else if (defrag1->root < defrag2->root)
  48. return -1;
  49. else if (defrag1->ino > defrag2->ino)
  50. return 1;
  51. else if (defrag1->ino < defrag2->ino)
  52. return -1;
  53. else
  54. return 0;
  55. }
  56. /*
  57. * Insert a record for an inode into the defrag tree. The lock must be held
  58. * already.
  59. *
  60. * If you're inserting a record for an older transid than an existing record,
  61. * the transid already in the tree is lowered.
  62. */
  63. static int btrfs_insert_inode_defrag(struct btrfs_inode *inode,
  64. struct inode_defrag *defrag)
  65. {
  66. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  67. struct inode_defrag *entry;
  68. struct rb_node **p;
  69. struct rb_node *parent = NULL;
  70. int ret;
  71. p = &fs_info->defrag_inodes.rb_node;
  72. while (*p) {
  73. parent = *p;
  74. entry = rb_entry(parent, struct inode_defrag, rb_node);
  75. ret = compare_inode_defrag(defrag, entry);
  76. if (ret < 0)
  77. p = &parent->rb_left;
  78. else if (ret > 0)
  79. p = &parent->rb_right;
  80. else {
  81. /*
  82. * If we're reinserting an entry for an old defrag run,
  83. * make sure to lower the transid of our existing
  84. * record.
  85. */
  86. if (defrag->transid < entry->transid)
  87. entry->transid = defrag->transid;
  88. entry->extent_thresh = min(defrag->extent_thresh,
  89. entry->extent_thresh);
  90. return -EEXIST;
  91. }
  92. }
  93. set_bit(BTRFS_INODE_IN_DEFRAG, &inode->runtime_flags);
  94. rb_link_node(&defrag->rb_node, parent, p);
  95. rb_insert_color(&defrag->rb_node, &fs_info->defrag_inodes);
  96. return 0;
  97. }
  98. static inline int need_auto_defrag(struct btrfs_fs_info *fs_info)
  99. {
  100. if (!btrfs_test_opt(fs_info, AUTO_DEFRAG))
  101. return 0;
  102. if (btrfs_fs_closing(fs_info))
  103. return 0;
  104. return 1;
  105. }
  106. /*
  107. * Insert a defrag record for this inode if auto defrag is enabled. No errors
  108. * returned as they're not considered fatal.
  109. */
  110. void btrfs_add_inode_defrag(struct btrfs_inode *inode, u32 extent_thresh)
  111. {
  112. struct btrfs_root *root = inode->root;
  113. struct btrfs_fs_info *fs_info = root->fs_info;
  114. struct inode_defrag *defrag;
  115. int ret;
  116. if (!need_auto_defrag(fs_info))
  117. return;
  118. if (test_bit(BTRFS_INODE_IN_DEFRAG, &inode->runtime_flags))
  119. return;
  120. defrag = kmem_cache_zalloc(btrfs_inode_defrag_cachep, GFP_NOFS);
  121. if (!defrag)
  122. return;
  123. defrag->ino = btrfs_ino(inode);
  124. defrag->transid = btrfs_get_root_last_trans(root);
  125. defrag->root = btrfs_root_id(root);
  126. defrag->extent_thresh = extent_thresh;
  127. spin_lock(&fs_info->defrag_inodes_lock);
  128. if (!test_bit(BTRFS_INODE_IN_DEFRAG, &inode->runtime_flags)) {
  129. /*
  130. * If we set IN_DEFRAG flag and evict the inode from memory,
  131. * and then re-read this inode, this new inode doesn't have
  132. * IN_DEFRAG flag. At the case, we may find the existed defrag.
  133. */
  134. ret = btrfs_insert_inode_defrag(inode, defrag);
  135. if (ret)
  136. kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
  137. } else {
  138. kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
  139. }
  140. spin_unlock(&fs_info->defrag_inodes_lock);
  141. }
  142. /*
  143. * Pick the defragable inode that we want, if it doesn't exist, we will get the
  144. * next one.
  145. */
  146. static struct inode_defrag *btrfs_pick_defrag_inode(
  147. struct btrfs_fs_info *fs_info, u64 root, u64 ino)
  148. {
  149. struct inode_defrag *entry = NULL;
  150. struct inode_defrag tmp;
  151. struct rb_node *p;
  152. struct rb_node *parent = NULL;
  153. int ret;
  154. tmp.ino = ino;
  155. tmp.root = root;
  156. spin_lock(&fs_info->defrag_inodes_lock);
  157. p = fs_info->defrag_inodes.rb_node;
  158. while (p) {
  159. parent = p;
  160. entry = rb_entry(parent, struct inode_defrag, rb_node);
  161. ret = compare_inode_defrag(&tmp, entry);
  162. if (ret < 0)
  163. p = parent->rb_left;
  164. else if (ret > 0)
  165. p = parent->rb_right;
  166. else
  167. goto out;
  168. }
  169. if (parent && compare_inode_defrag(&tmp, entry) > 0) {
  170. parent = rb_next(parent);
  171. if (parent)
  172. entry = rb_entry(parent, struct inode_defrag, rb_node);
  173. else
  174. entry = NULL;
  175. }
  176. out:
  177. if (entry)
  178. rb_erase(parent, &fs_info->defrag_inodes);
  179. spin_unlock(&fs_info->defrag_inodes_lock);
  180. return entry;
  181. }
  182. void btrfs_cleanup_defrag_inodes(struct btrfs_fs_info *fs_info)
  183. {
  184. struct inode_defrag *defrag, *next;
  185. spin_lock(&fs_info->defrag_inodes_lock);
  186. rbtree_postorder_for_each_entry_safe(defrag, next,
  187. &fs_info->defrag_inodes, rb_node)
  188. kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
  189. fs_info->defrag_inodes = RB_ROOT;
  190. spin_unlock(&fs_info->defrag_inodes_lock);
  191. }
  192. #define BTRFS_DEFRAG_BATCH 1024
  193. static int btrfs_run_defrag_inode(struct btrfs_fs_info *fs_info,
  194. struct inode_defrag *defrag,
  195. struct file_ra_state *ra)
  196. {
  197. struct btrfs_root *inode_root;
  198. struct inode *inode;
  199. struct btrfs_ioctl_defrag_range_args range;
  200. int ret = 0;
  201. u64 cur = 0;
  202. again:
  203. if (test_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state))
  204. goto cleanup;
  205. if (!need_auto_defrag(fs_info))
  206. goto cleanup;
  207. /* Get the inode */
  208. inode_root = btrfs_get_fs_root(fs_info, defrag->root, true);
  209. if (IS_ERR(inode_root)) {
  210. ret = PTR_ERR(inode_root);
  211. goto cleanup;
  212. }
  213. inode = btrfs_iget(defrag->ino, inode_root);
  214. btrfs_put_root(inode_root);
  215. if (IS_ERR(inode)) {
  216. ret = PTR_ERR(inode);
  217. goto cleanup;
  218. }
  219. if (cur >= i_size_read(inode)) {
  220. iput(inode);
  221. goto cleanup;
  222. }
  223. /* Do a chunk of defrag */
  224. clear_bit(BTRFS_INODE_IN_DEFRAG, &BTRFS_I(inode)->runtime_flags);
  225. memset(&range, 0, sizeof(range));
  226. range.len = (u64)-1;
  227. range.start = cur;
  228. range.extent_thresh = defrag->extent_thresh;
  229. file_ra_state_init(ra, inode->i_mapping);
  230. sb_start_write(fs_info->sb);
  231. ret = btrfs_defrag_file(inode, ra, &range, defrag->transid,
  232. BTRFS_DEFRAG_BATCH);
  233. sb_end_write(fs_info->sb);
  234. iput(inode);
  235. if (ret < 0)
  236. goto cleanup;
  237. cur = max(cur + fs_info->sectorsize, range.start);
  238. goto again;
  239. cleanup:
  240. kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
  241. return ret;
  242. }
  243. /*
  244. * Run through the list of inodes in the FS that need defragging.
  245. */
  246. int btrfs_run_defrag_inodes(struct btrfs_fs_info *fs_info)
  247. {
  248. struct inode_defrag *defrag;
  249. u64 first_ino = 0;
  250. u64 root_objectid = 0;
  251. atomic_inc(&fs_info->defrag_running);
  252. while (1) {
  253. struct file_ra_state ra = { 0 };
  254. /* Pause the auto defragger. */
  255. if (test_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state))
  256. break;
  257. if (!need_auto_defrag(fs_info))
  258. break;
  259. /* find an inode to defrag */
  260. defrag = btrfs_pick_defrag_inode(fs_info, root_objectid, first_ino);
  261. if (!defrag) {
  262. if (root_objectid || first_ino) {
  263. root_objectid = 0;
  264. first_ino = 0;
  265. continue;
  266. } else {
  267. break;
  268. }
  269. }
  270. first_ino = defrag->ino + 1;
  271. root_objectid = defrag->root;
  272. btrfs_run_defrag_inode(fs_info, defrag, &ra);
  273. }
  274. atomic_dec(&fs_info->defrag_running);
  275. /*
  276. * During unmount, we use the transaction_wait queue to wait for the
  277. * defragger to stop.
  278. */
  279. wake_up(&fs_info->transaction_wait);
  280. return 0;
  281. }
  282. /*
  283. * Check if two blocks addresses are close, used by defrag.
  284. */
  285. static bool close_blocks(u64 blocknr, u64 other, u32 blocksize)
  286. {
  287. if (blocknr < other && other - (blocknr + blocksize) < SZ_32K)
  288. return true;
  289. if (blocknr > other && blocknr - (other + blocksize) < SZ_32K)
  290. return true;
  291. return false;
  292. }
  293. /*
  294. * Go through all the leaves pointed to by a node and reallocate them so that
  295. * disk order is close to key order.
  296. */
  297. static int btrfs_realloc_node(struct btrfs_trans_handle *trans,
  298. struct btrfs_root *root,
  299. struct extent_buffer *parent,
  300. int start_slot, u64 *last_ret,
  301. struct btrfs_key *progress)
  302. {
  303. struct btrfs_fs_info *fs_info = root->fs_info;
  304. const u32 blocksize = fs_info->nodesize;
  305. const int end_slot = btrfs_header_nritems(parent) - 1;
  306. u64 search_start = *last_ret;
  307. u64 last_block = 0;
  308. int ret = 0;
  309. bool progress_passed = false;
  310. /*
  311. * COWing must happen through a running transaction, which always
  312. * matches the current fs generation (it's a transaction with a state
  313. * less than TRANS_STATE_UNBLOCKED). If it doesn't, then turn the fs
  314. * into error state to prevent the commit of any transaction.
  315. */
  316. if (unlikely(trans->transaction != fs_info->running_transaction ||
  317. trans->transid != fs_info->generation)) {
  318. btrfs_abort_transaction(trans, -EUCLEAN);
  319. btrfs_crit(fs_info,
  320. "unexpected transaction when attempting to reallocate parent %llu for root %llu, transaction %llu running transaction %llu fs generation %llu",
  321. parent->start, btrfs_root_id(root), trans->transid,
  322. fs_info->running_transaction->transid,
  323. fs_info->generation);
  324. return -EUCLEAN;
  325. }
  326. if (btrfs_header_nritems(parent) <= 1)
  327. return 0;
  328. for (int i = start_slot; i <= end_slot; i++) {
  329. struct extent_buffer *cur;
  330. struct btrfs_disk_key disk_key;
  331. u64 blocknr;
  332. u64 other;
  333. bool close = true;
  334. btrfs_node_key(parent, &disk_key, i);
  335. if (!progress_passed && btrfs_comp_keys(&disk_key, progress) < 0)
  336. continue;
  337. progress_passed = true;
  338. blocknr = btrfs_node_blockptr(parent, i);
  339. if (last_block == 0)
  340. last_block = blocknr;
  341. if (i > 0) {
  342. other = btrfs_node_blockptr(parent, i - 1);
  343. close = close_blocks(blocknr, other, blocksize);
  344. }
  345. if (!close && i < end_slot) {
  346. other = btrfs_node_blockptr(parent, i + 1);
  347. close = close_blocks(blocknr, other, blocksize);
  348. }
  349. if (close) {
  350. last_block = blocknr;
  351. continue;
  352. }
  353. cur = btrfs_read_node_slot(parent, i);
  354. if (IS_ERR(cur))
  355. return PTR_ERR(cur);
  356. if (search_start == 0)
  357. search_start = last_block;
  358. btrfs_tree_lock(cur);
  359. ret = btrfs_force_cow_block(trans, root, cur, parent, i,
  360. &cur, search_start,
  361. min(16 * blocksize,
  362. (end_slot - i) * blocksize),
  363. BTRFS_NESTING_COW);
  364. if (ret) {
  365. btrfs_tree_unlock(cur);
  366. free_extent_buffer(cur);
  367. break;
  368. }
  369. search_start = cur->start;
  370. last_block = cur->start;
  371. *last_ret = search_start;
  372. btrfs_tree_unlock(cur);
  373. free_extent_buffer(cur);
  374. }
  375. return ret;
  376. }
  377. /*
  378. * Defrag all the leaves in a given btree.
  379. * Read all the leaves and try to get key order to
  380. * better reflect disk order
  381. */
  382. static int btrfs_defrag_leaves(struct btrfs_trans_handle *trans,
  383. struct btrfs_root *root)
  384. {
  385. struct btrfs_path *path = NULL;
  386. struct btrfs_key key;
  387. int ret = 0;
  388. int wret;
  389. int level;
  390. int next_key_ret = 0;
  391. u64 last_ret = 0;
  392. if (!test_bit(BTRFS_ROOT_SHAREABLE, &root->state))
  393. goto out;
  394. path = btrfs_alloc_path();
  395. if (!path) {
  396. ret = -ENOMEM;
  397. goto out;
  398. }
  399. level = btrfs_header_level(root->node);
  400. if (level == 0)
  401. goto out;
  402. if (root->defrag_progress.objectid == 0) {
  403. struct extent_buffer *root_node;
  404. u32 nritems;
  405. root_node = btrfs_lock_root_node(root);
  406. nritems = btrfs_header_nritems(root_node);
  407. root->defrag_max.objectid = 0;
  408. /* from above we know this is not a leaf */
  409. btrfs_node_key_to_cpu(root_node, &root->defrag_max,
  410. nritems - 1);
  411. btrfs_tree_unlock(root_node);
  412. free_extent_buffer(root_node);
  413. memset(&key, 0, sizeof(key));
  414. } else {
  415. memcpy(&key, &root->defrag_progress, sizeof(key));
  416. }
  417. path->keep_locks = 1;
  418. ret = btrfs_search_forward(root, &key, path, BTRFS_OLDEST_GENERATION);
  419. if (ret < 0)
  420. goto out;
  421. if (ret > 0) {
  422. ret = 0;
  423. goto out;
  424. }
  425. btrfs_release_path(path);
  426. /*
  427. * We don't need a lock on a leaf. btrfs_realloc_node() will lock all
  428. * leafs from path->nodes[1], so set lowest_level to 1 to avoid later
  429. * a deadlock (attempting to write lock an already write locked leaf).
  430. */
  431. path->lowest_level = 1;
  432. wret = btrfs_search_slot(trans, root, &key, path, 0, 1);
  433. if (wret < 0) {
  434. ret = wret;
  435. goto out;
  436. }
  437. if (!path->nodes[1]) {
  438. ret = 0;
  439. goto out;
  440. }
  441. /*
  442. * The node at level 1 must always be locked when our path has
  443. * keep_locks set and lowest_level is 1, regardless of the value of
  444. * path->slots[1].
  445. */
  446. ASSERT(path->locks[1] != 0);
  447. ret = btrfs_realloc_node(trans, root,
  448. path->nodes[1], 0,
  449. &last_ret,
  450. &root->defrag_progress);
  451. if (ret) {
  452. WARN_ON(ret == -EAGAIN);
  453. goto out;
  454. }
  455. /*
  456. * Now that we reallocated the node we can find the next key. Note that
  457. * btrfs_find_next_key() can release our path and do another search
  458. * without COWing, this is because even with path->keep_locks = 1,
  459. * btrfs_search_slot() / ctree.c:unlock_up() does not keeps a lock on a
  460. * node when path->slots[node_level - 1] does not point to the last
  461. * item or a slot beyond the last item (ctree.c:unlock_up()). Therefore
  462. * we search for the next key after reallocating our node.
  463. */
  464. path->slots[1] = btrfs_header_nritems(path->nodes[1]);
  465. next_key_ret = btrfs_find_next_key(root, path, &key, 1,
  466. BTRFS_OLDEST_GENERATION);
  467. if (next_key_ret == 0) {
  468. memcpy(&root->defrag_progress, &key, sizeof(key));
  469. ret = -EAGAIN;
  470. }
  471. out:
  472. btrfs_free_path(path);
  473. if (ret == -EAGAIN) {
  474. if (root->defrag_max.objectid > root->defrag_progress.objectid)
  475. goto done;
  476. if (root->defrag_max.type > root->defrag_progress.type)
  477. goto done;
  478. if (root->defrag_max.offset > root->defrag_progress.offset)
  479. goto done;
  480. ret = 0;
  481. }
  482. done:
  483. if (ret != -EAGAIN)
  484. memset(&root->defrag_progress, 0,
  485. sizeof(root->defrag_progress));
  486. return ret;
  487. }
  488. /*
  489. * Defrag a given btree. Every leaf in the btree is read and defragmented.
  490. */
  491. int btrfs_defrag_root(struct btrfs_root *root)
  492. {
  493. struct btrfs_fs_info *fs_info = root->fs_info;
  494. int ret;
  495. if (test_and_set_bit(BTRFS_ROOT_DEFRAG_RUNNING, &root->state))
  496. return 0;
  497. while (1) {
  498. struct btrfs_trans_handle *trans;
  499. trans = btrfs_start_transaction(root, 0);
  500. if (IS_ERR(trans)) {
  501. ret = PTR_ERR(trans);
  502. break;
  503. }
  504. ret = btrfs_defrag_leaves(trans, root);
  505. btrfs_end_transaction(trans);
  506. btrfs_btree_balance_dirty(fs_info);
  507. cond_resched();
  508. if (btrfs_fs_closing(fs_info) || ret != -EAGAIN)
  509. break;
  510. if (btrfs_defrag_cancelled(fs_info)) {
  511. btrfs_debug(fs_info, "defrag_root cancelled");
  512. ret = -EAGAIN;
  513. break;
  514. }
  515. }
  516. clear_bit(BTRFS_ROOT_DEFRAG_RUNNING, &root->state);
  517. return ret;
  518. }
  519. /*
  520. * Defrag specific helper to get an extent map.
  521. *
  522. * Differences between this and btrfs_get_extent() are:
  523. *
  524. * - No extent_map will be added to inode->extent_tree
  525. * To reduce memory usage in the long run.
  526. *
  527. * - Extra optimization to skip file extents older than @newer_than
  528. * By using btrfs_search_forward() we can skip entire file ranges that
  529. * have extents created in past transactions, because btrfs_search_forward()
  530. * will not visit leaves and nodes with a generation smaller than given
  531. * minimal generation threshold (@newer_than).
  532. *
  533. * Return valid em if we find a file extent matching the requirement.
  534. * Return NULL if we can not find a file extent matching the requirement.
  535. *
  536. * Return ERR_PTR() for error.
  537. */
  538. static struct extent_map *defrag_get_extent(struct btrfs_inode *inode,
  539. u64 start, u64 newer_than)
  540. {
  541. struct btrfs_root *root = inode->root;
  542. struct btrfs_file_extent_item *fi;
  543. struct btrfs_path path = { 0 };
  544. struct extent_map *em;
  545. struct btrfs_key key;
  546. u64 ino = btrfs_ino(inode);
  547. int ret;
  548. em = alloc_extent_map();
  549. if (!em) {
  550. ret = -ENOMEM;
  551. goto err;
  552. }
  553. key.objectid = ino;
  554. key.type = BTRFS_EXTENT_DATA_KEY;
  555. key.offset = start;
  556. if (newer_than) {
  557. ret = btrfs_search_forward(root, &key, &path, newer_than);
  558. if (ret < 0)
  559. goto err;
  560. /* Can't find anything newer */
  561. if (ret > 0)
  562. goto not_found;
  563. } else {
  564. ret = btrfs_search_slot(NULL, root, &key, &path, 0, 0);
  565. if (ret < 0)
  566. goto err;
  567. }
  568. if (path.slots[0] >= btrfs_header_nritems(path.nodes[0])) {
  569. /*
  570. * If btrfs_search_slot() makes path to point beyond nritems,
  571. * we should not have an empty leaf, as this inode must at
  572. * least have its INODE_ITEM.
  573. */
  574. ASSERT(btrfs_header_nritems(path.nodes[0]));
  575. path.slots[0] = btrfs_header_nritems(path.nodes[0]) - 1;
  576. }
  577. btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
  578. /* Perfect match, no need to go one slot back */
  579. if (key.objectid == ino && key.type == BTRFS_EXTENT_DATA_KEY &&
  580. key.offset == start)
  581. goto iterate;
  582. /* We didn't find a perfect match, needs to go one slot back */
  583. if (path.slots[0] > 0) {
  584. btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
  585. if (key.objectid == ino && key.type == BTRFS_EXTENT_DATA_KEY)
  586. path.slots[0]--;
  587. }
  588. iterate:
  589. /* Iterate through the path to find a file extent covering @start */
  590. while (true) {
  591. u64 extent_end;
  592. if (path.slots[0] >= btrfs_header_nritems(path.nodes[0]))
  593. goto next;
  594. btrfs_item_key_to_cpu(path.nodes[0], &key, path.slots[0]);
  595. /*
  596. * We may go one slot back to INODE_REF/XATTR item, then
  597. * need to go forward until we reach an EXTENT_DATA.
  598. * But we should still has the correct ino as key.objectid.
  599. */
  600. if (WARN_ON(key.objectid < ino) || key.type < BTRFS_EXTENT_DATA_KEY)
  601. goto next;
  602. /* It's beyond our target range, definitely not extent found */
  603. if (key.objectid > ino || key.type > BTRFS_EXTENT_DATA_KEY)
  604. goto not_found;
  605. /*
  606. * | |<- File extent ->|
  607. * \- start
  608. *
  609. * This means there is a hole between start and key.offset.
  610. */
  611. if (key.offset > start) {
  612. em->start = start;
  613. em->disk_bytenr = EXTENT_MAP_HOLE;
  614. em->disk_num_bytes = 0;
  615. em->ram_bytes = 0;
  616. em->offset = 0;
  617. em->len = key.offset - start;
  618. break;
  619. }
  620. fi = btrfs_item_ptr(path.nodes[0], path.slots[0],
  621. struct btrfs_file_extent_item);
  622. extent_end = btrfs_file_extent_end(&path);
  623. /*
  624. * |<- file extent ->| |
  625. * \- start
  626. *
  627. * We haven't reached start, search next slot.
  628. */
  629. if (extent_end <= start)
  630. goto next;
  631. /* Now this extent covers @start, convert it to em */
  632. btrfs_extent_item_to_extent_map(inode, &path, fi, em);
  633. break;
  634. next:
  635. ret = btrfs_next_item(root, &path);
  636. if (ret < 0)
  637. goto err;
  638. if (ret > 0)
  639. goto not_found;
  640. }
  641. btrfs_release_path(&path);
  642. return em;
  643. not_found:
  644. btrfs_release_path(&path);
  645. free_extent_map(em);
  646. return NULL;
  647. err:
  648. btrfs_release_path(&path);
  649. free_extent_map(em);
  650. return ERR_PTR(ret);
  651. }
  652. static struct extent_map *defrag_lookup_extent(struct inode *inode, u64 start,
  653. u64 newer_than, bool locked)
  654. {
  655. struct extent_map_tree *em_tree = &BTRFS_I(inode)->extent_tree;
  656. struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
  657. struct extent_map *em;
  658. const u32 sectorsize = BTRFS_I(inode)->root->fs_info->sectorsize;
  659. /*
  660. * Hopefully we have this extent in the tree already, try without the
  661. * full extent lock.
  662. */
  663. read_lock(&em_tree->lock);
  664. em = lookup_extent_mapping(em_tree, start, sectorsize);
  665. read_unlock(&em_tree->lock);
  666. /*
  667. * We can get a merged extent, in that case, we need to re-search
  668. * tree to get the original em for defrag.
  669. *
  670. * This is because even if we have adjacent extents that are contiguous
  671. * and compatible (same type and flags), we still want to defrag them
  672. * so that we use less metadata (extent items in the extent tree and
  673. * file extent items in the inode's subvolume tree).
  674. */
  675. if (em && (em->flags & EXTENT_FLAG_MERGED)) {
  676. free_extent_map(em);
  677. em = NULL;
  678. }
  679. if (!em) {
  680. struct extent_state *cached = NULL;
  681. u64 end = start + sectorsize - 1;
  682. /* Get the big lock and read metadata off disk. */
  683. if (!locked)
  684. lock_extent(io_tree, start, end, &cached);
  685. em = defrag_get_extent(BTRFS_I(inode), start, newer_than);
  686. if (!locked)
  687. unlock_extent(io_tree, start, end, &cached);
  688. if (IS_ERR(em))
  689. return NULL;
  690. }
  691. return em;
  692. }
  693. static u32 get_extent_max_capacity(const struct btrfs_fs_info *fs_info,
  694. const struct extent_map *em)
  695. {
  696. if (extent_map_is_compressed(em))
  697. return BTRFS_MAX_COMPRESSED;
  698. return fs_info->max_extent_size;
  699. }
  700. static bool defrag_check_next_extent(struct inode *inode, struct extent_map *em,
  701. u32 extent_thresh, u64 newer_than, bool locked)
  702. {
  703. struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
  704. struct extent_map *next;
  705. bool ret = false;
  706. /* This is the last extent */
  707. if (em->start + em->len >= i_size_read(inode))
  708. return false;
  709. /*
  710. * Here we need to pass @newer_then when checking the next extent, or
  711. * we will hit a case we mark current extent for defrag, but the next
  712. * one will not be a target.
  713. * This will just cause extra IO without really reducing the fragments.
  714. */
  715. next = defrag_lookup_extent(inode, em->start + em->len, newer_than, locked);
  716. /* No more em or hole */
  717. if (!next || next->disk_bytenr >= EXTENT_MAP_LAST_BYTE)
  718. goto out;
  719. if (next->flags & EXTENT_FLAG_PREALLOC)
  720. goto out;
  721. /*
  722. * If the next extent is at its max capacity, defragging current extent
  723. * makes no sense, as the total number of extents won't change.
  724. */
  725. if (next->len >= get_extent_max_capacity(fs_info, em))
  726. goto out;
  727. /* Skip older extent */
  728. if (next->generation < newer_than)
  729. goto out;
  730. /* Also check extent size */
  731. if (next->len >= extent_thresh)
  732. goto out;
  733. ret = true;
  734. out:
  735. free_extent_map(next);
  736. return ret;
  737. }
  738. /*
  739. * Prepare one page to be defragged.
  740. *
  741. * This will ensure:
  742. *
  743. * - Returned page is locked and has been set up properly.
  744. * - No ordered extent exists in the page.
  745. * - The page is uptodate.
  746. *
  747. * NOTE: Caller should also wait for page writeback after the cluster is
  748. * prepared, here we don't do writeback wait for each page.
  749. */
  750. static struct folio *defrag_prepare_one_folio(struct btrfs_inode *inode, pgoff_t index)
  751. {
  752. struct address_space *mapping = inode->vfs_inode.i_mapping;
  753. gfp_t mask = btrfs_alloc_write_mask(mapping);
  754. u64 page_start = (u64)index << PAGE_SHIFT;
  755. u64 page_end = page_start + PAGE_SIZE - 1;
  756. struct extent_state *cached_state = NULL;
  757. struct folio *folio;
  758. int ret;
  759. again:
  760. folio = __filemap_get_folio(mapping, index,
  761. FGP_LOCK | FGP_ACCESSED | FGP_CREAT, mask);
  762. if (IS_ERR(folio))
  763. return folio;
  764. /*
  765. * Since we can defragment files opened read-only, we can encounter
  766. * transparent huge pages here (see CONFIG_READ_ONLY_THP_FOR_FS). We
  767. * can't do I/O using huge pages yet, so return an error for now.
  768. * Filesystem transparent huge pages are typically only used for
  769. * executables that explicitly enable them, so this isn't very
  770. * restrictive.
  771. */
  772. if (folio_test_large(folio)) {
  773. folio_unlock(folio);
  774. folio_put(folio);
  775. return ERR_PTR(-ETXTBSY);
  776. }
  777. ret = set_folio_extent_mapped(folio);
  778. if (ret < 0) {
  779. folio_unlock(folio);
  780. folio_put(folio);
  781. return ERR_PTR(ret);
  782. }
  783. /* Wait for any existing ordered extent in the range */
  784. while (1) {
  785. struct btrfs_ordered_extent *ordered;
  786. lock_extent(&inode->io_tree, page_start, page_end, &cached_state);
  787. ordered = btrfs_lookup_ordered_range(inode, page_start, PAGE_SIZE);
  788. unlock_extent(&inode->io_tree, page_start, page_end,
  789. &cached_state);
  790. if (!ordered)
  791. break;
  792. folio_unlock(folio);
  793. btrfs_start_ordered_extent(ordered);
  794. btrfs_put_ordered_extent(ordered);
  795. folio_lock(folio);
  796. /*
  797. * We unlocked the folio above, so we need check if it was
  798. * released or not.
  799. */
  800. if (folio->mapping != mapping || !folio->private) {
  801. folio_unlock(folio);
  802. folio_put(folio);
  803. goto again;
  804. }
  805. }
  806. /*
  807. * Now the page range has no ordered extent any more. Read the page to
  808. * make it uptodate.
  809. */
  810. if (!folio_test_uptodate(folio)) {
  811. btrfs_read_folio(NULL, folio);
  812. folio_lock(folio);
  813. if (folio->mapping != mapping || !folio->private) {
  814. folio_unlock(folio);
  815. folio_put(folio);
  816. goto again;
  817. }
  818. if (!folio_test_uptodate(folio)) {
  819. folio_unlock(folio);
  820. folio_put(folio);
  821. return ERR_PTR(-EIO);
  822. }
  823. }
  824. return folio;
  825. }
  826. struct defrag_target_range {
  827. struct list_head list;
  828. u64 start;
  829. u64 len;
  830. };
  831. /*
  832. * Collect all valid target extents.
  833. *
  834. * @start: file offset to lookup
  835. * @len: length to lookup
  836. * @extent_thresh: file extent size threshold, any extent size >= this value
  837. * will be ignored
  838. * @newer_than: only defrag extents newer than this value
  839. * @do_compress: whether the defrag is doing compression
  840. * if true, @extent_thresh will be ignored and all regular
  841. * file extents meeting @newer_than will be targets.
  842. * @locked: if the range has already held extent lock
  843. * @target_list: list of targets file extents
  844. */
  845. static int defrag_collect_targets(struct btrfs_inode *inode,
  846. u64 start, u64 len, u32 extent_thresh,
  847. u64 newer_than, bool do_compress,
  848. bool locked, struct list_head *target_list,
  849. u64 *last_scanned_ret)
  850. {
  851. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  852. bool last_is_target = false;
  853. u64 cur = start;
  854. int ret = 0;
  855. while (cur < start + len) {
  856. struct extent_map *em;
  857. struct defrag_target_range *new;
  858. bool next_mergeable = true;
  859. u64 range_len;
  860. last_is_target = false;
  861. em = defrag_lookup_extent(&inode->vfs_inode, cur, newer_than, locked);
  862. if (!em)
  863. break;
  864. /*
  865. * If the file extent is an inlined one, we may still want to
  866. * defrag it (fallthrough) if it will cause a regular extent.
  867. * This is for users who want to convert inline extents to
  868. * regular ones through max_inline= mount option.
  869. */
  870. if (em->disk_bytenr == EXTENT_MAP_INLINE &&
  871. em->len <= inode->root->fs_info->max_inline)
  872. goto next;
  873. /* Skip holes and preallocated extents. */
  874. if (em->disk_bytenr == EXTENT_MAP_HOLE ||
  875. (em->flags & EXTENT_FLAG_PREALLOC))
  876. goto next;
  877. /* Skip older extent */
  878. if (em->generation < newer_than)
  879. goto next;
  880. /* This em is under writeback, no need to defrag */
  881. if (em->generation == (u64)-1)
  882. goto next;
  883. /*
  884. * Our start offset might be in the middle of an existing extent
  885. * map, so take that into account.
  886. */
  887. range_len = em->len - (cur - em->start);
  888. /*
  889. * If this range of the extent map is already flagged for delalloc,
  890. * skip it, because:
  891. *
  892. * 1) We could deadlock later, when trying to reserve space for
  893. * delalloc, because in case we can't immediately reserve space
  894. * the flusher can start delalloc and wait for the respective
  895. * ordered extents to complete. The deadlock would happen
  896. * because we do the space reservation while holding the range
  897. * locked, and starting writeback, or finishing an ordered
  898. * extent, requires locking the range;
  899. *
  900. * 2) If there's delalloc there, it means there's dirty pages for
  901. * which writeback has not started yet (we clean the delalloc
  902. * flag when starting writeback and after creating an ordered
  903. * extent). If we mark pages in an adjacent range for defrag,
  904. * then we will have a larger contiguous range for delalloc,
  905. * very likely resulting in a larger extent after writeback is
  906. * triggered (except in a case of free space fragmentation).
  907. */
  908. if (test_range_bit_exists(&inode->io_tree, cur, cur + range_len - 1,
  909. EXTENT_DELALLOC))
  910. goto next;
  911. /*
  912. * For do_compress case, we want to compress all valid file
  913. * extents, thus no @extent_thresh or mergeable check.
  914. */
  915. if (do_compress)
  916. goto add;
  917. /* Skip too large extent */
  918. if (em->len >= extent_thresh)
  919. goto next;
  920. /*
  921. * Skip extents already at its max capacity, this is mostly for
  922. * compressed extents, which max cap is only 128K.
  923. */
  924. if (em->len >= get_extent_max_capacity(fs_info, em))
  925. goto next;
  926. /*
  927. * Normally there are no more extents after an inline one, thus
  928. * @next_mergeable will normally be false and not defragged.
  929. * So if an inline extent passed all above checks, just add it
  930. * for defrag, and be converted to regular extents.
  931. */
  932. if (em->disk_bytenr == EXTENT_MAP_INLINE)
  933. goto add;
  934. next_mergeable = defrag_check_next_extent(&inode->vfs_inode, em,
  935. extent_thresh, newer_than, locked);
  936. if (!next_mergeable) {
  937. struct defrag_target_range *last;
  938. /* Empty target list, no way to merge with last entry */
  939. if (list_empty(target_list))
  940. goto next;
  941. last = list_entry(target_list->prev,
  942. struct defrag_target_range, list);
  943. /* Not mergeable with last entry */
  944. if (last->start + last->len != cur)
  945. goto next;
  946. /* Mergeable, fall through to add it to @target_list. */
  947. }
  948. add:
  949. last_is_target = true;
  950. range_len = min(extent_map_end(em), start + len) - cur;
  951. /*
  952. * This one is a good target, check if it can be merged into
  953. * last range of the target list.
  954. */
  955. if (!list_empty(target_list)) {
  956. struct defrag_target_range *last;
  957. last = list_entry(target_list->prev,
  958. struct defrag_target_range, list);
  959. ASSERT(last->start + last->len <= cur);
  960. if (last->start + last->len == cur) {
  961. /* Mergeable, enlarge the last entry */
  962. last->len += range_len;
  963. goto next;
  964. }
  965. /* Fall through to allocate a new entry */
  966. }
  967. /* Allocate new defrag_target_range */
  968. new = kmalloc(sizeof(*new), GFP_NOFS);
  969. if (!new) {
  970. free_extent_map(em);
  971. ret = -ENOMEM;
  972. break;
  973. }
  974. new->start = cur;
  975. new->len = range_len;
  976. list_add_tail(&new->list, target_list);
  977. next:
  978. cur = extent_map_end(em);
  979. free_extent_map(em);
  980. }
  981. if (ret < 0) {
  982. struct defrag_target_range *entry;
  983. struct defrag_target_range *tmp;
  984. list_for_each_entry_safe(entry, tmp, target_list, list) {
  985. list_del_init(&entry->list);
  986. kfree(entry);
  987. }
  988. }
  989. if (!ret && last_scanned_ret) {
  990. /*
  991. * If the last extent is not a target, the caller can skip to
  992. * the end of that extent.
  993. * Otherwise, we can only go the end of the specified range.
  994. */
  995. if (!last_is_target)
  996. *last_scanned_ret = max(cur, *last_scanned_ret);
  997. else
  998. *last_scanned_ret = max(start + len, *last_scanned_ret);
  999. }
  1000. return ret;
  1001. }
  1002. #define CLUSTER_SIZE (SZ_256K)
  1003. static_assert(PAGE_ALIGNED(CLUSTER_SIZE));
  1004. /*
  1005. * Defrag one contiguous target range.
  1006. *
  1007. * @inode: target inode
  1008. * @target: target range to defrag
  1009. * @pages: locked pages covering the defrag range
  1010. * @nr_pages: number of locked pages
  1011. *
  1012. * Caller should ensure:
  1013. *
  1014. * - Pages are prepared
  1015. * Pages should be locked, no ordered extent in the pages range,
  1016. * no writeback.
  1017. *
  1018. * - Extent bits are locked
  1019. */
  1020. static int defrag_one_locked_target(struct btrfs_inode *inode,
  1021. struct defrag_target_range *target,
  1022. struct folio **folios, int nr_pages,
  1023. struct extent_state **cached_state)
  1024. {
  1025. struct btrfs_fs_info *fs_info = inode->root->fs_info;
  1026. struct extent_changeset *data_reserved = NULL;
  1027. const u64 start = target->start;
  1028. const u64 len = target->len;
  1029. unsigned long last_index = (start + len - 1) >> PAGE_SHIFT;
  1030. unsigned long start_index = start >> PAGE_SHIFT;
  1031. unsigned long first_index = folios[0]->index;
  1032. int ret = 0;
  1033. int i;
  1034. ASSERT(last_index - first_index + 1 <= nr_pages);
  1035. ret = btrfs_delalloc_reserve_space(inode, &data_reserved, start, len);
  1036. if (ret < 0)
  1037. return ret;
  1038. clear_extent_bit(&inode->io_tree, start, start + len - 1,
  1039. EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
  1040. EXTENT_DEFRAG, cached_state);
  1041. set_extent_bit(&inode->io_tree, start, start + len - 1,
  1042. EXTENT_DELALLOC | EXTENT_DEFRAG, cached_state);
  1043. /* Update the page status */
  1044. for (i = start_index - first_index; i <= last_index - first_index; i++) {
  1045. folio_clear_checked(folios[i]);
  1046. btrfs_folio_clamp_set_dirty(fs_info, folios[i], start, len);
  1047. }
  1048. btrfs_delalloc_release_extents(inode, len);
  1049. extent_changeset_free(data_reserved);
  1050. return ret;
  1051. }
  1052. static int defrag_one_range(struct btrfs_inode *inode, u64 start, u32 len,
  1053. u32 extent_thresh, u64 newer_than, bool do_compress,
  1054. u64 *last_scanned_ret)
  1055. {
  1056. struct extent_state *cached_state = NULL;
  1057. struct defrag_target_range *entry;
  1058. struct defrag_target_range *tmp;
  1059. LIST_HEAD(target_list);
  1060. struct folio **folios;
  1061. const u32 sectorsize = inode->root->fs_info->sectorsize;
  1062. u64 last_index = (start + len - 1) >> PAGE_SHIFT;
  1063. u64 start_index = start >> PAGE_SHIFT;
  1064. unsigned int nr_pages = last_index - start_index + 1;
  1065. int ret = 0;
  1066. int i;
  1067. ASSERT(nr_pages <= CLUSTER_SIZE / PAGE_SIZE);
  1068. ASSERT(IS_ALIGNED(start, sectorsize) && IS_ALIGNED(len, sectorsize));
  1069. folios = kcalloc(nr_pages, sizeof(struct folio *), GFP_NOFS);
  1070. if (!folios)
  1071. return -ENOMEM;
  1072. /* Prepare all pages */
  1073. for (i = 0; i < nr_pages; i++) {
  1074. folios[i] = defrag_prepare_one_folio(inode, start_index + i);
  1075. if (IS_ERR(folios[i])) {
  1076. ret = PTR_ERR(folios[i]);
  1077. nr_pages = i;
  1078. goto free_folios;
  1079. }
  1080. }
  1081. for (i = 0; i < nr_pages; i++)
  1082. folio_wait_writeback(folios[i]);
  1083. /* Lock the pages range */
  1084. lock_extent(&inode->io_tree, start_index << PAGE_SHIFT,
  1085. (last_index << PAGE_SHIFT) + PAGE_SIZE - 1,
  1086. &cached_state);
  1087. /*
  1088. * Now we have a consistent view about the extent map, re-check
  1089. * which range really needs to be defragged.
  1090. *
  1091. * And this time we have extent locked already, pass @locked = true
  1092. * so that we won't relock the extent range and cause deadlock.
  1093. */
  1094. ret = defrag_collect_targets(inode, start, len, extent_thresh,
  1095. newer_than, do_compress, true,
  1096. &target_list, last_scanned_ret);
  1097. if (ret < 0)
  1098. goto unlock_extent;
  1099. list_for_each_entry(entry, &target_list, list) {
  1100. ret = defrag_one_locked_target(inode, entry, folios, nr_pages,
  1101. &cached_state);
  1102. if (ret < 0)
  1103. break;
  1104. }
  1105. list_for_each_entry_safe(entry, tmp, &target_list, list) {
  1106. list_del_init(&entry->list);
  1107. kfree(entry);
  1108. }
  1109. unlock_extent:
  1110. unlock_extent(&inode->io_tree, start_index << PAGE_SHIFT,
  1111. (last_index << PAGE_SHIFT) + PAGE_SIZE - 1,
  1112. &cached_state);
  1113. free_folios:
  1114. for (i = 0; i < nr_pages; i++) {
  1115. folio_unlock(folios[i]);
  1116. folio_put(folios[i]);
  1117. }
  1118. kfree(folios);
  1119. return ret;
  1120. }
  1121. static int defrag_one_cluster(struct btrfs_inode *inode,
  1122. struct file_ra_state *ra,
  1123. u64 start, u32 len, u32 extent_thresh,
  1124. u64 newer_than, bool do_compress,
  1125. unsigned long *sectors_defragged,
  1126. unsigned long max_sectors,
  1127. u64 *last_scanned_ret)
  1128. {
  1129. const u32 sectorsize = inode->root->fs_info->sectorsize;
  1130. struct defrag_target_range *entry;
  1131. struct defrag_target_range *tmp;
  1132. LIST_HEAD(target_list);
  1133. int ret;
  1134. ret = defrag_collect_targets(inode, start, len, extent_thresh,
  1135. newer_than, do_compress, false,
  1136. &target_list, NULL);
  1137. if (ret < 0)
  1138. goto out;
  1139. list_for_each_entry(entry, &target_list, list) {
  1140. u32 range_len = entry->len;
  1141. /* Reached or beyond the limit */
  1142. if (max_sectors && *sectors_defragged >= max_sectors) {
  1143. ret = 1;
  1144. break;
  1145. }
  1146. if (max_sectors)
  1147. range_len = min_t(u32, range_len,
  1148. (max_sectors - *sectors_defragged) * sectorsize);
  1149. /*
  1150. * If defrag_one_range() has updated last_scanned_ret,
  1151. * our range may already be invalid (e.g. hole punched).
  1152. * Skip if our range is before last_scanned_ret, as there is
  1153. * no need to defrag the range anymore.
  1154. */
  1155. if (entry->start + range_len <= *last_scanned_ret)
  1156. continue;
  1157. page_cache_sync_readahead(inode->vfs_inode.i_mapping,
  1158. ra, NULL, entry->start >> PAGE_SHIFT,
  1159. ((entry->start + range_len - 1) >> PAGE_SHIFT) -
  1160. (entry->start >> PAGE_SHIFT) + 1);
  1161. /*
  1162. * Here we may not defrag any range if holes are punched before
  1163. * we locked the pages.
  1164. * But that's fine, it only affects the @sectors_defragged
  1165. * accounting.
  1166. */
  1167. ret = defrag_one_range(inode, entry->start, range_len,
  1168. extent_thresh, newer_than, do_compress,
  1169. last_scanned_ret);
  1170. if (ret < 0)
  1171. break;
  1172. *sectors_defragged += range_len >>
  1173. inode->root->fs_info->sectorsize_bits;
  1174. }
  1175. out:
  1176. list_for_each_entry_safe(entry, tmp, &target_list, list) {
  1177. list_del_init(&entry->list);
  1178. kfree(entry);
  1179. }
  1180. if (ret >= 0)
  1181. *last_scanned_ret = max(*last_scanned_ret, start + len);
  1182. return ret;
  1183. }
  1184. /*
  1185. * Entry point to file defragmentation.
  1186. *
  1187. * @inode: inode to be defragged
  1188. * @ra: readahead state
  1189. * @range: defrag options including range and flags
  1190. * @newer_than: minimum transid to defrag
  1191. * @max_to_defrag: max number of sectors to be defragged, if 0, the whole inode
  1192. * will be defragged.
  1193. *
  1194. * Return <0 for error.
  1195. * Return >=0 for the number of sectors defragged, and range->start will be updated
  1196. * to indicate the file offset where next defrag should be started at.
  1197. * (Mostly for autodefrag, which sets @max_to_defrag thus we may exit early without
  1198. * defragging all the range).
  1199. */
  1200. int btrfs_defrag_file(struct inode *inode, struct file_ra_state *ra,
  1201. struct btrfs_ioctl_defrag_range_args *range,
  1202. u64 newer_than, unsigned long max_to_defrag)
  1203. {
  1204. struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
  1205. unsigned long sectors_defragged = 0;
  1206. u64 isize = i_size_read(inode);
  1207. u64 cur;
  1208. u64 last_byte;
  1209. bool do_compress = (range->flags & BTRFS_DEFRAG_RANGE_COMPRESS);
  1210. int compress_type = BTRFS_COMPRESS_ZLIB;
  1211. int ret = 0;
  1212. u32 extent_thresh = range->extent_thresh;
  1213. pgoff_t start_index;
  1214. ASSERT(ra);
  1215. if (isize == 0)
  1216. return 0;
  1217. if (range->start >= isize)
  1218. return -EINVAL;
  1219. if (do_compress) {
  1220. if (range->compress_type >= BTRFS_NR_COMPRESS_TYPES)
  1221. return -EINVAL;
  1222. if (range->compress_type)
  1223. compress_type = range->compress_type;
  1224. }
  1225. if (extent_thresh == 0)
  1226. extent_thresh = SZ_256K;
  1227. if (range->start + range->len > range->start) {
  1228. /* Got a specific range */
  1229. last_byte = min(isize, range->start + range->len);
  1230. } else {
  1231. /* Defrag until file end */
  1232. last_byte = isize;
  1233. }
  1234. /* Align the range */
  1235. cur = round_down(range->start, fs_info->sectorsize);
  1236. last_byte = round_up(last_byte, fs_info->sectorsize) - 1;
  1237. /*
  1238. * Make writeback start from the beginning of the range, so that the
  1239. * defrag range can be written sequentially.
  1240. */
  1241. start_index = cur >> PAGE_SHIFT;
  1242. if (start_index < inode->i_mapping->writeback_index)
  1243. inode->i_mapping->writeback_index = start_index;
  1244. while (cur < last_byte) {
  1245. const unsigned long prev_sectors_defragged = sectors_defragged;
  1246. u64 last_scanned = cur;
  1247. u64 cluster_end;
  1248. if (btrfs_defrag_cancelled(fs_info)) {
  1249. ret = -EAGAIN;
  1250. break;
  1251. }
  1252. /* We want the cluster end at page boundary when possible */
  1253. cluster_end = (((cur >> PAGE_SHIFT) +
  1254. (SZ_256K >> PAGE_SHIFT)) << PAGE_SHIFT) - 1;
  1255. cluster_end = min(cluster_end, last_byte);
  1256. btrfs_inode_lock(BTRFS_I(inode), 0);
  1257. if (IS_SWAPFILE(inode)) {
  1258. ret = -ETXTBSY;
  1259. btrfs_inode_unlock(BTRFS_I(inode), 0);
  1260. break;
  1261. }
  1262. if (!(inode->i_sb->s_flags & SB_ACTIVE)) {
  1263. btrfs_inode_unlock(BTRFS_I(inode), 0);
  1264. break;
  1265. }
  1266. if (do_compress)
  1267. BTRFS_I(inode)->defrag_compress = compress_type;
  1268. ret = defrag_one_cluster(BTRFS_I(inode), ra, cur,
  1269. cluster_end + 1 - cur, extent_thresh,
  1270. newer_than, do_compress, &sectors_defragged,
  1271. max_to_defrag, &last_scanned);
  1272. if (sectors_defragged > prev_sectors_defragged)
  1273. balance_dirty_pages_ratelimited(inode->i_mapping);
  1274. btrfs_inode_unlock(BTRFS_I(inode), 0);
  1275. if (ret < 0)
  1276. break;
  1277. cur = max(cluster_end + 1, last_scanned);
  1278. if (ret > 0) {
  1279. ret = 0;
  1280. break;
  1281. }
  1282. cond_resched();
  1283. }
  1284. /*
  1285. * Update range.start for autodefrag, this will indicate where to start
  1286. * in next run.
  1287. */
  1288. range->start = cur;
  1289. if (sectors_defragged) {
  1290. /*
  1291. * We have defragged some sectors, for compression case they
  1292. * need to be written back immediately.
  1293. */
  1294. if (range->flags & BTRFS_DEFRAG_RANGE_START_IO) {
  1295. filemap_flush(inode->i_mapping);
  1296. if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
  1297. &BTRFS_I(inode)->runtime_flags))
  1298. filemap_flush(inode->i_mapping);
  1299. }
  1300. if (range->compress_type == BTRFS_COMPRESS_LZO)
  1301. btrfs_set_fs_incompat(fs_info, COMPRESS_LZO);
  1302. else if (range->compress_type == BTRFS_COMPRESS_ZSTD)
  1303. btrfs_set_fs_incompat(fs_info, COMPRESS_ZSTD);
  1304. ret = sectors_defragged;
  1305. }
  1306. if (do_compress) {
  1307. btrfs_inode_lock(BTRFS_I(inode), 0);
  1308. BTRFS_I(inode)->defrag_compress = BTRFS_COMPRESS_NONE;
  1309. btrfs_inode_unlock(BTRFS_I(inode), 0);
  1310. }
  1311. return ret;
  1312. }
  1313. void __cold btrfs_auto_defrag_exit(void)
  1314. {
  1315. kmem_cache_destroy(btrfs_inode_defrag_cachep);
  1316. }
  1317. int __init btrfs_auto_defrag_init(void)
  1318. {
  1319. btrfs_inode_defrag_cachep = kmem_cache_create("btrfs_inode_defrag",
  1320. sizeof(struct inode_defrag), 0, 0, NULL);
  1321. if (!btrfs_inode_defrag_cachep)
  1322. return -ENOMEM;
  1323. return 0;
  1324. }