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