defrag.c 41 KB

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