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