xref: /linux/fs/btrfs/inode.c (revision 31b706da2cfd8ee3352391181ccf9696bed3d25d)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2007 Oracle.  All rights reserved.
4  */
5 
6 #include <linux/kernel.h>
7 #include <linux/bio.h>
8 #include <linux/blk-cgroup.h>
9 #include <linux/file.h>
10 #include <linux/filelock.h>
11 #include <linux/fs.h>
12 #include <linux/fs_struct.h>
13 #include <linux/pagemap.h>
14 #include <linux/highmem.h>
15 #include <linux/time.h>
16 #include <linux/init.h>
17 #include <linux/string.h>
18 #include <linux/backing-dev.h>
19 #include <linux/writeback.h>
20 #include <linux/compat.h>
21 #include <linux/xattr.h>
22 #include <linux/posix_acl.h>
23 #include <linux/falloc.h>
24 #include <linux/slab.h>
25 #include <linux/ratelimit.h>
26 #include <linux/btrfs.h>
27 #include <linux/blkdev.h>
28 #include <linux/posix_acl_xattr.h>
29 #include <linux/uio.h>
30 #include <linux/magic.h>
31 #include <linux/iversion.h>
32 #include <linux/swap.h>
33 #include <linux/migrate.h>
34 #include <linux/sched/mm.h>
35 #include <linux/iomap.h>
36 #include <linux/unaligned.h>
37 #include "misc.h"
38 #include "ctree.h"
39 #include "disk-io.h"
40 #include "transaction.h"
41 #include "btrfs_inode.h"
42 #include "ordered-data.h"
43 #include "xattr.h"
44 #include "tree-log.h"
45 #include "bio.h"
46 #include "compression.h"
47 #include "locking.h"
48 #include "props.h"
49 #include "qgroup.h"
50 #include "delalloc-space.h"
51 #include "block-group.h"
52 #include "space-info.h"
53 #include "zoned.h"
54 #include "subpage.h"
55 #include "inode-item.h"
56 #include "fs.h"
57 #include "accessors.h"
58 #include "extent-tree.h"
59 #include "root-tree.h"
60 #include "defrag.h"
61 #include "dir-item.h"
62 #include "file-item.h"
63 #include "uuid-tree.h"
64 #include "ioctl.h"
65 #include "file.h"
66 #include "acl.h"
67 #include "relocation.h"
68 #include "verity.h"
69 #include "super.h"
70 #include "orphan.h"
71 #include "backref.h"
72 #include "raid-stripe-tree.h"
73 #include "fiemap.h"
74 #include "delayed-inode.h"
75 
76 #define COW_FILE_RANGE_KEEP_LOCKED	(1UL << 0)
77 
78 struct btrfs_iget_args {
79 	u64 ino;
80 	struct btrfs_root *root;
81 };
82 
83 struct btrfs_rename_ctx {
84 	/* Output field. Stores the index number of the old directory entry. */
85 	u64 index;
86 };
87 
88 /*
89  * Used by data_reloc_print_warning_inode() to pass needed info for filename
90  * resolution and output of error message.
91  */
92 struct data_reloc_warn {
93 	struct btrfs_path path;
94 	struct btrfs_fs_info *fs_info;
95 	u64 extent_item_size;
96 	u64 logical;
97 	int mirror_num;
98 };
99 
100 /*
101  * For the file_extent_tree, we want to hold the inode lock when we lookup and
102  * update the disk_i_size, but lockdep will complain because our io_tree we hold
103  * the tree lock and get the inode lock when setting delalloc. These two things
104  * are unrelated, so make a class for the file_extent_tree so we don't get the
105  * two locking patterns mixed up.
106  */
107 static struct lock_class_key file_extent_tree_class;
108 
109 static const struct inode_operations btrfs_dir_inode_operations;
110 static const struct inode_operations btrfs_symlink_inode_operations;
111 static const struct inode_operations btrfs_special_inode_operations;
112 static const struct inode_operations btrfs_file_inode_operations;
113 static const struct address_space_operations btrfs_aops;
114 static const struct file_operations btrfs_dir_file_operations;
115 
116 static struct kmem_cache *btrfs_inode_cachep;
117 
118 static int btrfs_setsize(struct inode *inode, struct iattr *attr);
119 static int btrfs_truncate(struct btrfs_inode *inode, bool skip_writeback);
120 
121 static noinline int run_delalloc_cow(struct btrfs_inode *inode,
122 				     struct folio *locked_folio, u64 start,
123 				     u64 end, struct writeback_control *wbc,
124 				     bool pages_dirty);
125 
126 static int data_reloc_print_warning_inode(u64 inum, u64 offset, u64 num_bytes,
127 					  u64 root, void *warn_ctx)
128 {
129 	struct data_reloc_warn *warn = warn_ctx;
130 	struct btrfs_fs_info *fs_info = warn->fs_info;
131 	struct extent_buffer *eb;
132 	struct btrfs_inode_item *inode_item;
133 	struct inode_fs_paths *ipath __free(inode_fs_paths) = NULL;
134 	struct btrfs_root *local_root;
135 	struct btrfs_key key;
136 	unsigned int nofs_flag;
137 	u32 nlink;
138 	int ret;
139 
140 	local_root = btrfs_get_fs_root(fs_info, root, true);
141 	if (IS_ERR(local_root)) {
142 		ret = PTR_ERR(local_root);
143 		goto err;
144 	}
145 
146 	/* This makes the path point to (inum INODE_ITEM ioff). */
147 	key.objectid = inum;
148 	key.type = BTRFS_INODE_ITEM_KEY;
149 	key.offset = 0;
150 
151 	ret = btrfs_search_slot(NULL, local_root, &key, &warn->path, 0, 0);
152 	if (ret) {
153 		btrfs_put_root(local_root);
154 		btrfs_release_path(&warn->path);
155 		goto err;
156 	}
157 
158 	eb = warn->path.nodes[0];
159 	inode_item = btrfs_item_ptr(eb, warn->path.slots[0], struct btrfs_inode_item);
160 	nlink = btrfs_inode_nlink(eb, inode_item);
161 	btrfs_release_path(&warn->path);
162 
163 	nofs_flag = memalloc_nofs_save();
164 	ipath = init_ipath(4096, local_root, &warn->path);
165 	memalloc_nofs_restore(nofs_flag);
166 	if (IS_ERR(ipath)) {
167 		btrfs_put_root(local_root);
168 		ret = PTR_ERR(ipath);
169 		ipath = NULL;
170 		/*
171 		 * -ENOMEM, not a critical error, just output an generic error
172 		 * without filename.
173 		 */
174 		btrfs_warn(fs_info,
175 "checksum error at logical %llu mirror %u root %llu, inode %llu offset %llu",
176 			   warn->logical, warn->mirror_num, root, inum, offset);
177 		return ret;
178 	}
179 	ret = paths_from_inode(inum, ipath);
180 	if (ret < 0) {
181 		btrfs_put_root(local_root);
182 		goto err;
183 	}
184 
185 	/*
186 	 * We deliberately ignore the bit ipath might have been too small to
187 	 * hold all of the paths here
188 	 */
189 	for (int i = 0; i < ipath->fspath->elem_cnt; i++) {
190 		btrfs_warn(fs_info,
191 "checksum error at logical %llu mirror %u root %llu inode %llu offset %llu length %u links %u (path: %s)",
192 			   warn->logical, warn->mirror_num, root, inum, offset,
193 			   fs_info->sectorsize, nlink,
194 			   (char *)(unsigned long)ipath->fspath->val[i]);
195 	}
196 
197 	btrfs_put_root(local_root);
198 	return 0;
199 
200 err:
201 	btrfs_warn(fs_info,
202 "checksum error at logical %llu mirror %u root %llu inode %llu offset %llu, path resolving failed with ret=%d",
203 		   warn->logical, warn->mirror_num, root, inum, offset, ret);
204 
205 	return ret;
206 }
207 
208 /*
209  * Do extra user-friendly error output (e.g. lookup all the affected files).
210  *
211  * Return true if we succeeded doing the backref lookup.
212  * Return false if such lookup failed, and has to fallback to the old error message.
213  */
214 static void print_data_reloc_error(const struct btrfs_inode *inode, u64 file_off,
215 				   const u8 *csum, const u8 *csum_expected,
216 				   int mirror_num)
217 {
218 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
219 	BTRFS_PATH_AUTO_RELEASE(path);
220 	struct btrfs_key found_key = { 0 };
221 	struct extent_buffer *eb;
222 	struct btrfs_extent_item *ei;
223 	const u32 csum_size = fs_info->csum_size;
224 	u64 logical;
225 	u64 flags;
226 	u32 item_size;
227 	int ret;
228 
229 	logical = btrfs_get_reloc_bg_bytenr(fs_info);
230 
231 	if (logical == U64_MAX) {
232 		btrfs_warn_rl(fs_info, "has data reloc tree but no running relocation");
233 		btrfs_warn_rl(fs_info,
234 "csum failed root %lld ino %llu off %llu csum " BTRFS_CSUM_FMT " expected csum " BTRFS_CSUM_FMT " mirror %d",
235 			btrfs_root_id(inode->root), btrfs_ino(inode), file_off,
236 			BTRFS_CSUM_FMT_VALUE(csum_size, csum),
237 			BTRFS_CSUM_FMT_VALUE(csum_size, csum_expected),
238 			mirror_num);
239 		return;
240 	}
241 
242 	logical += file_off;
243 	btrfs_warn_rl(fs_info,
244 "csum failed root %lld ino %llu off %llu logical %llu csum " BTRFS_CSUM_FMT " expected csum " BTRFS_CSUM_FMT " mirror %d",
245 			btrfs_root_id(inode->root),
246 			btrfs_ino(inode), file_off, logical,
247 			BTRFS_CSUM_FMT_VALUE(csum_size, csum),
248 			BTRFS_CSUM_FMT_VALUE(csum_size, csum_expected),
249 			mirror_num);
250 
251 	ret = extent_from_logical(fs_info, logical, &path, &found_key, &flags);
252 	if (ret < 0) {
253 		btrfs_err_rl(fs_info, "failed to lookup extent item for logical %llu: %d",
254 			     logical, ret);
255 		return;
256 	}
257 	eb = path.nodes[0];
258 	ei = btrfs_item_ptr(eb, path.slots[0], struct btrfs_extent_item);
259 	item_size = btrfs_item_size(eb, path.slots[0]);
260 	if (flags & BTRFS_EXTENT_FLAG_TREE_BLOCK) {
261 		unsigned long ptr = 0;
262 		u64 ref_root;
263 		u8 ref_level;
264 
265 		while (true) {
266 			ret = tree_backref_for_extent(&ptr, eb, &found_key, ei,
267 						      item_size, &ref_root,
268 						      &ref_level);
269 			if (ret < 0) {
270 				btrfs_warn_rl(fs_info,
271 				"failed to resolve tree backref for logical %llu: %d",
272 					      logical, ret);
273 				break;
274 			}
275 			if (ret > 0)
276 				break;
277 
278 			btrfs_warn_rl(fs_info,
279 "csum error at logical %llu mirror %u: metadata %s (level %d) in tree %llu",
280 				logical, mirror_num,
281 				(ref_level ? "node" : "leaf"),
282 				ref_level, ref_root);
283 		}
284 	} else {
285 		struct btrfs_backref_walk_ctx ctx = { 0 };
286 		struct data_reloc_warn reloc_warn = { 0 };
287 
288 		/*
289 		 * Do not hold the path as later iterate_extent_inodes() call
290 		 * can be time consuming.
291 		 */
292 		btrfs_release_path(&path);
293 
294 		ctx.bytenr = found_key.objectid;
295 		ctx.extent_item_pos = logical - found_key.objectid;
296 		ctx.fs_info = fs_info;
297 
298 		reloc_warn.logical = logical;
299 		reloc_warn.extent_item_size = found_key.offset;
300 		reloc_warn.mirror_num = mirror_num;
301 		reloc_warn.fs_info = fs_info;
302 
303 		iterate_extent_inodes(&ctx, true,
304 				      data_reloc_print_warning_inode, &reloc_warn);
305 	}
306 }
307 
308 static void __cold btrfs_print_data_csum_error(struct btrfs_inode *inode,
309 		u64 logical_start, u8 *csum, u8 *csum_expected, int mirror_num)
310 {
311 	struct btrfs_root *root = inode->root;
312 	const u32 csum_size = root->fs_info->csum_size;
313 
314 	/* For data reloc tree, it's better to do a backref lookup instead. */
315 	if (btrfs_is_data_reloc_root(root))
316 		return print_data_reloc_error(inode, logical_start, csum,
317 					      csum_expected, mirror_num);
318 
319 	/* Output without objectid, which is more meaningful */
320 	if (btrfs_root_id(root) >= BTRFS_LAST_FREE_OBJECTID) {
321 		btrfs_warn_rl(root->fs_info,
322 "csum failed root %lld ino %lld off %llu csum " BTRFS_CSUM_FMT " expected csum " BTRFS_CSUM_FMT " mirror %d",
323 			btrfs_root_id(root), btrfs_ino(inode),
324 			logical_start,
325 			BTRFS_CSUM_FMT_VALUE(csum_size, csum),
326 			BTRFS_CSUM_FMT_VALUE(csum_size, csum_expected),
327 			mirror_num);
328 	} else {
329 		btrfs_warn_rl(root->fs_info,
330 "csum failed root %llu ino %llu off %llu csum " BTRFS_CSUM_FMT " expected csum " BTRFS_CSUM_FMT " mirror %d",
331 			btrfs_root_id(root), btrfs_ino(inode),
332 			logical_start,
333 			BTRFS_CSUM_FMT_VALUE(csum_size, csum),
334 			BTRFS_CSUM_FMT_VALUE(csum_size, csum_expected),
335 			mirror_num);
336 	}
337 }
338 
339 /*
340  * Lock inode i_rwsem based on arguments passed.
341  *
342  * ilock_flags can have the following bit set:
343  *
344  * BTRFS_ILOCK_SHARED - acquire a shared lock on the inode
345  * BTRFS_ILOCK_TRY - try to acquire the lock, if fails on first attempt
346  *		     return -EAGAIN
347  * BTRFS_ILOCK_MMAP - acquire a write lock on the i_mmap_lock
348  */
349 int btrfs_inode_lock(struct btrfs_inode *inode, unsigned int ilock_flags)
350 {
351 	if (ilock_flags & BTRFS_ILOCK_SHARED) {
352 		if (ilock_flags & BTRFS_ILOCK_TRY) {
353 			if (!inode_trylock_shared(&inode->vfs_inode))
354 				return -EAGAIN;
355 			else
356 				return 0;
357 		}
358 		inode_lock_shared(&inode->vfs_inode);
359 	} else {
360 		if (ilock_flags & BTRFS_ILOCK_TRY) {
361 			if (!inode_trylock(&inode->vfs_inode))
362 				return -EAGAIN;
363 			else
364 				return 0;
365 		}
366 		inode_lock(&inode->vfs_inode);
367 	}
368 	if (ilock_flags & BTRFS_ILOCK_MMAP)
369 		down_write(&inode->i_mmap_lock);
370 	return 0;
371 }
372 
373 /*
374  * Unlock inode i_rwsem.
375  *
376  * ilock_flags should contain the same bits set as passed to btrfs_inode_lock()
377  * to decide whether the lock acquired is shared or exclusive.
378  */
379 void btrfs_inode_unlock(struct btrfs_inode *inode, unsigned int ilock_flags)
380 {
381 	if (ilock_flags & BTRFS_ILOCK_MMAP)
382 		up_write(&inode->i_mmap_lock);
383 	if (ilock_flags & BTRFS_ILOCK_SHARED)
384 		inode_unlock_shared(&inode->vfs_inode);
385 	else
386 		inode_unlock(&inode->vfs_inode);
387 }
388 
389 /*
390  * Cleanup all submitted ordered extents in specified range to handle errors
391  * from the btrfs_run_delalloc_range() callback.
392  *
393  * NOTE: caller must ensure that when an error happens, it can not call
394  * extent_clear_unlock_delalloc() to clear both the bits EXTENT_DO_ACCOUNTING
395  * and EXTENT_DELALLOC simultaneously, because that causes the reserved metadata
396  * to be released, which we want to happen only when finishing the ordered
397  * extent (btrfs_finish_ordered_io()).
398  */
399 static inline void btrfs_cleanup_ordered_extents(struct btrfs_inode *inode,
400 						 u64 offset, u64 bytes)
401 {
402 	return btrfs_mark_ordered_io_finished(inode, offset, bytes, false);
403 }
404 
405 static int btrfs_dirty_inode(struct btrfs_inode *inode);
406 
407 static int btrfs_init_inode_security(struct btrfs_trans_handle *trans,
408 				     struct btrfs_new_inode_args *args)
409 {
410 	int ret;
411 
412 	if (args->default_acl) {
413 		ret = __btrfs_set_acl(trans, args->inode, args->default_acl,
414 				      ACL_TYPE_DEFAULT);
415 		if (ret)
416 			return ret;
417 	}
418 	if (args->acl) {
419 		ret = __btrfs_set_acl(trans, args->inode, args->acl, ACL_TYPE_ACCESS);
420 		if (ret)
421 			return ret;
422 	}
423 	if (!args->default_acl && !args->acl)
424 		cache_no_acl(args->inode);
425 	return btrfs_xattr_security_init(trans, args->inode, args->dir,
426 					 &args->dentry->d_name);
427 }
428 
429 /*
430  * this does all the hard work for inserting an inline extent into
431  * the btree.  The caller should have done a btrfs_drop_extents so that
432  * no overlapping inline items exist in the btree
433  */
434 static int insert_inline_extent(struct btrfs_trans_handle *trans,
435 				struct btrfs_path *path,
436 				struct btrfs_inode *inode, bool extent_inserted,
437 				size_t size, size_t compressed_size,
438 				int compress_type,
439 				struct folio *compressed_folio,
440 				bool update_i_size)
441 {
442 	struct btrfs_root *root = inode->root;
443 	struct extent_buffer *leaf;
444 	const u32 sectorsize = trans->fs_info->sectorsize;
445 	char *kaddr;
446 	unsigned long ptr;
447 	struct btrfs_file_extent_item *ei;
448 	int ret;
449 	size_t cur_size = size;
450 	u64 i_size;
451 
452 	/*
453 	 * The decompressed size must still be no larger than a sector.  Under
454 	 * heavy race, we can have size == 0 passed in, but that shouldn't be a
455 	 * big deal and we can continue the insertion.
456 	 */
457 	ASSERT(size <= sectorsize);
458 
459 	/*
460 	 * The compressed size also needs to be no larger than a page.
461 	 * That's also why we only need one folio as the parameter.
462 	 */
463 	if (compressed_folio) {
464 		ASSERT(compressed_size <= sectorsize);
465 		ASSERT(compressed_size <= PAGE_SIZE);
466 	} else {
467 		ASSERT(compressed_size == 0);
468 	}
469 
470 	if (compressed_size && compressed_folio)
471 		cur_size = compressed_size;
472 
473 	if (!extent_inserted) {
474 		struct btrfs_key key;
475 		size_t datasize;
476 
477 		key.objectid = btrfs_ino(inode);
478 		key.type = BTRFS_EXTENT_DATA_KEY;
479 		key.offset = 0;
480 
481 		datasize = btrfs_file_extent_calc_inline_size(cur_size);
482 		ret = btrfs_insert_empty_item(trans, root, path, &key,
483 					      datasize);
484 		if (ret)
485 			return ret;
486 	}
487 	leaf = path->nodes[0];
488 	ei = btrfs_item_ptr(leaf, path->slots[0],
489 			    struct btrfs_file_extent_item);
490 	btrfs_set_file_extent_generation(leaf, ei, trans->transid);
491 	btrfs_set_file_extent_type(leaf, ei, BTRFS_FILE_EXTENT_INLINE);
492 	btrfs_set_file_extent_encryption(leaf, ei, 0);
493 	btrfs_set_file_extent_other_encoding(leaf, ei, 0);
494 	btrfs_set_file_extent_ram_bytes(leaf, ei, size);
495 	ptr = btrfs_file_extent_inline_start(ei);
496 
497 	if (compress_type != BTRFS_COMPRESS_NONE) {
498 		kaddr = kmap_local_folio(compressed_folio, 0);
499 		write_extent_buffer(leaf, kaddr, ptr, compressed_size);
500 		kunmap_local(kaddr);
501 
502 		btrfs_set_file_extent_compression(leaf, ei,
503 						  compress_type);
504 	} else {
505 		struct folio *folio;
506 
507 		folio = filemap_get_folio(inode->vfs_inode.i_mapping, 0);
508 		ASSERT(!IS_ERR(folio));
509 		btrfs_set_file_extent_compression(leaf, ei, 0);
510 		kaddr = kmap_local_folio(folio, 0);
511 		write_extent_buffer(leaf, kaddr, ptr, size);
512 		kunmap_local(kaddr);
513 		folio_put(folio);
514 	}
515 	btrfs_release_path(path);
516 
517 	/*
518 	 * We align size to sectorsize for inline extents just for simplicity
519 	 * sake.
520 	 */
521 	ret = btrfs_inode_set_file_extent_range(inode, 0,
522 					ALIGN(size, root->fs_info->sectorsize));
523 	if (ret)
524 		return ret;
525 
526 	/*
527 	 * We're an inline extent, so nobody can extend the file past i_size
528 	 * without locking a page we already have locked.
529 	 *
530 	 * We must do any i_size and inode updates before we unlock the pages.
531 	 * Otherwise we could end up racing with unlink.
532 	 */
533 	i_size = i_size_read(&inode->vfs_inode);
534 	if (update_i_size && size > i_size) {
535 		i_size_write(&inode->vfs_inode, size);
536 		i_size = size;
537 	}
538 	inode->disk_i_size = i_size;
539 
540 	return 0;
541 }
542 
543 static bool can_cow_file_range_inline(struct btrfs_inode *inode,
544 				      u64 offset, u64 size,
545 				      size_t compressed_size)
546 {
547 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
548 	u64 data_len = (compressed_size ?: size);
549 
550 	/* Inline extents must start at offset 0. */
551 	if (offset != 0)
552 		return false;
553 
554 	/*
555 	 * Even for bs > ps cases, cow_file_range_inline() can only accept a
556 	 * single folio.
557 	 *
558 	 * This can be problematic and cause access beyond page boundary if a
559 	 * page sized folio is passed into that function.
560 	 * And encoded write is doing exactly that.
561 	 * So here limits the inlined extent size to PAGE_SIZE.
562 	 */
563 	if (size > PAGE_SIZE || compressed_size > PAGE_SIZE)
564 		return false;
565 
566 	/* Inline extents are limited to sectorsize. */
567 	if (size > fs_info->sectorsize)
568 		return false;
569 
570 	/* We do not allow a non-compressed extent to be as large as block size. */
571 	if (data_len >= fs_info->sectorsize)
572 		return false;
573 
574 	/* We cannot exceed the maximum inline data size. */
575 	if (data_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info))
576 		return false;
577 
578 	/* We cannot exceed the user specified max_inline size. */
579 	if (data_len > fs_info->max_inline)
580 		return false;
581 
582 	/* Inline extents must be the entirety of the file. */
583 	if (size < i_size_read(&inode->vfs_inode))
584 		return false;
585 
586 	/* Encrypted file cannot be inlined. */
587 	if (IS_ENCRYPTED(&inode->vfs_inode))
588 		return false;
589 
590 	return true;
591 }
592 
593 /*
594  * conditionally insert an inline extent into the file.  This
595  * does the checks required to make sure the data is small enough
596  * to fit as an inline extent.
597  *
598  * If being used directly, you must have already checked we're allowed to cow
599  * the range by getting true from can_cow_file_range_inline().
600  *
601  * Return 0 if the inlined extent is created successfully.
602  * Return <0 for critical error, and should be considered as an writeback error.
603  * Return >0 if can not create an inlined extent (mostly due to lack of meta space).
604  */
605 static noinline int __cow_file_range_inline(struct btrfs_inode *inode,
606 					    u64 size, size_t compressed_size,
607 					    int compress_type,
608 					    struct folio *compressed_folio,
609 					    bool update_i_size)
610 {
611 	struct btrfs_drop_extents_args drop_args = { 0 };
612 	struct btrfs_root *root = inode->root;
613 	struct btrfs_fs_info *fs_info = root->fs_info;
614 	struct btrfs_trans_handle *trans = NULL;
615 	u64 data_len = (compressed_size ?: size);
616 	int ret;
617 	struct btrfs_path *path;
618 
619 	path = btrfs_alloc_path();
620 	if (!path) {
621 		ret = -ENOMEM;
622 		goto out;
623 	}
624 
625 	trans = btrfs_join_transaction(root);
626 	if (IS_ERR(trans)) {
627 		ret = PTR_ERR(trans);
628 		trans = NULL;
629 		goto out;
630 	}
631 	trans->block_rsv = &inode->block_rsv;
632 
633 	drop_args.path = path;
634 	drop_args.start = 0;
635 	drop_args.end = fs_info->sectorsize;
636 	drop_args.drop_cache = true;
637 	drop_args.replace_extent = true;
638 	drop_args.extent_item_size = btrfs_file_extent_calc_inline_size(data_len);
639 	ret = btrfs_drop_extents(trans, root, inode, &drop_args);
640 	if (unlikely(ret)) {
641 		btrfs_abort_transaction(trans, ret);
642 		goto out;
643 	}
644 
645 	ret = insert_inline_extent(trans, path, inode, drop_args.extent_inserted,
646 				   size, compressed_size, compress_type,
647 				   compressed_folio, update_i_size);
648 	if (unlikely(ret && ret != -ENOSPC)) {
649 		btrfs_abort_transaction(trans, ret);
650 		goto out;
651 	} else if (ret == -ENOSPC) {
652 		ret = 1;
653 		goto out;
654 	}
655 
656 	btrfs_update_inode_bytes(inode, size, drop_args.bytes_found);
657 	ret = btrfs_update_inode(trans, inode);
658 	if (unlikely(ret && ret != -ENOSPC)) {
659 		btrfs_abort_transaction(trans, ret);
660 		goto out;
661 	} else if (ret == -ENOSPC) {
662 		ret = 1;
663 		goto out;
664 	}
665 
666 	btrfs_set_inode_full_sync(inode);
667 out:
668 	/*
669 	 * Don't forget to free the reserved space, as for inlined extent
670 	 * it won't count as data extent, free them directly here.
671 	 * And at reserve time, it's always aligned to sector size, so
672 	 * just free one sector here.
673 	 *
674 	 * If we fallback to non-inline (ret == 1) due to -ENOSPC, then we need
675 	 * to keep the data reservation.
676 	 */
677 	if (ret <= 0)
678 		btrfs_qgroup_free_data(inode, NULL, 0, fs_info->sectorsize, NULL);
679 	btrfs_free_path(path);
680 	if (trans)
681 		btrfs_end_transaction(trans);
682 	return ret;
683 }
684 
685 struct async_extent {
686 	u64 start;
687 	u64 ram_size;
688 	struct compressed_bio *cb;
689 	struct list_head list;
690 };
691 
692 struct async_chunk {
693 	struct btrfs_inode *inode;
694 	struct folio *locked_folio;
695 	u64 start;
696 	u64 end;
697 	blk_opf_t write_flags;
698 	struct list_head extents;
699 	struct cgroup_subsys_state *blkcg_css;
700 	struct btrfs_work work;
701 	struct async_cow *async_cow;
702 };
703 
704 struct async_cow {
705 	atomic_t num_chunks;
706 	struct async_chunk chunks[];
707 };
708 
709 static int add_async_extent(struct async_chunk *cow, u64 start, u64 ram_size,
710 			    struct compressed_bio *cb)
711 {
712 	struct async_extent *async_extent;
713 
714 	async_extent = kmalloc_obj(*async_extent, GFP_NOFS);
715 	if (!async_extent)
716 		return -ENOMEM;
717 	ASSERT(ram_size < U32_MAX);
718 	async_extent->start = start;
719 	async_extent->ram_size = ram_size;
720 	async_extent->cb = cb;
721 	list_add_tail(&async_extent->list, &cow->extents);
722 	return 0;
723 }
724 
725 /*
726  * Check if the inode needs to be submitted to compression, based on mount
727  * options, defragmentation, properties or heuristics.
728  */
729 static inline int inode_need_compress(struct btrfs_inode *inode, u64 start,
730 				      u64 end, bool check_inline)
731 {
732 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
733 
734 	if (unlikely(!btrfs_inode_can_compress(inode))) {
735 		DEBUG_WARN("BTRFS: unexpected compression for ino %llu", btrfs_ino(inode));
736 		return 0;
737 	}
738 
739 	/*
740 	 * If the delalloc range is only one fs block and can not be inlined,
741 	 * do not even bother try compression, as there will be no space saving
742 	 * and will always fallback to regular write later.
743 	 */
744 	if (end + 1 - start <= fs_info->sectorsize &&
745 	    (!check_inline || (start > 0 || end + 1 < inode->disk_i_size)))
746 		return 0;
747 
748 	/* Defrag ioctl takes precedence over mount options and properties. */
749 	if (inode->defrag_compress == BTRFS_DEFRAG_DONT_COMPRESS)
750 		return 0;
751 	if (BTRFS_COMPRESS_NONE < inode->defrag_compress &&
752 	    inode->defrag_compress < BTRFS_NR_COMPRESS_TYPES)
753 		return 1;
754 	/* force compress */
755 	if (btrfs_test_opt(fs_info, FORCE_COMPRESS))
756 		return 1;
757 	/* bad compression ratios */
758 	if (inode->flags & BTRFS_INODE_NOCOMPRESS)
759 		return 0;
760 	if (btrfs_test_opt(fs_info, COMPRESS) ||
761 	    inode->flags & BTRFS_INODE_COMPRESS ||
762 	    inode->prop_compress)
763 		return btrfs_compress_heuristic(inode, start, end);
764 	return 0;
765 }
766 
767 static inline void inode_should_defrag(struct btrfs_inode *inode,
768 		u64 start, u64 end, u64 num_bytes, u32 small_write)
769 {
770 	/* If this is a small write inside eof, kick off a defrag */
771 	if (num_bytes < small_write &&
772 	    (start > 0 || end + 1 < inode->disk_i_size))
773 		btrfs_add_inode_defrag(inode, small_write);
774 }
775 
776 static int extent_range_clear_dirty_for_io(struct btrfs_inode *inode, u64 start, u64 end)
777 {
778 	const pgoff_t end_index = end >> PAGE_SHIFT;
779 	struct folio *folio;
780 	int ret = 0;
781 
782 	for (pgoff_t index = start >> PAGE_SHIFT; index <= end_index; index++) {
783 		folio = filemap_get_folio(inode->vfs_inode.i_mapping, index);
784 		if (IS_ERR(folio)) {
785 			if (!ret)
786 				ret = PTR_ERR(folio);
787 			continue;
788 		}
789 		btrfs_folio_clamp_clear_dirty(inode->root->fs_info, folio, start,
790 					      end + 1 - start);
791 		folio_put(folio);
792 	}
793 	return ret;
794 }
795 
796 static struct folio *compressed_bio_last_folio(struct compressed_bio *cb)
797 {
798 	struct bio *bio = &cb->bbio.bio;
799 	struct bio_vec *bvec;
800 	phys_addr_t paddr;
801 
802 	/*
803 	 * Make sure all folios have the same min_folio_size.
804 	 *
805 	 * Otherwise we cannot simply use offset_in_offset(folio, bi_size) to
806 	 * calculate the end of the last folio.
807 	 */
808 	if (IS_ENABLED(CONFIG_BTRFS_ASSERT)) {
809 		struct btrfs_fs_info *fs_info = cb_to_fs_info(cb);
810 		const u32 min_folio_size = btrfs_min_folio_size(fs_info);
811 		struct folio_iter fi;
812 
813 		bio_for_each_folio_all(fi, bio)
814 			ASSERT(folio_size(fi.folio) == min_folio_size);
815 	}
816 
817 	/* The bio must not be empty. */
818 	ASSERT(bio->bi_vcnt);
819 
820 	bvec = &bio->bi_io_vec[bio->bi_vcnt - 1];
821 	paddr = bvec_phys(bvec) + bvec->bv_len - 1;
822 	return page_folio(phys_to_page(paddr));
823 }
824 
825 static void round_up_last_block(struct compressed_bio *cb, u32 blocksize)
826 {
827 	struct bio *bio = &cb->bbio.bio;
828 	struct folio *last_folio = compressed_bio_last_folio(cb);
829 	const u32 bio_size = bio->bi_iter.bi_size;
830 	const u32 foffset = offset_in_folio(last_folio, bio_size);
831 	const u32 padding_len = round_up(foffset, blocksize) - foffset;
832 	bool ret;
833 
834 	if (IS_ALIGNED(bio_size, blocksize))
835 		return;
836 
837 	folio_zero_range(last_folio, foffset, padding_len);
838 	ret = bio_add_folio(bio, last_folio, padding_len, foffset);
839 	/* The remaining part should be merged thus never fail. */
840 	ASSERT(ret);
841 }
842 
843 /*
844  * Work queue call back to started compression on a file and pages.
845  *
846  * This is done inside an ordered work queue, and the compression is spread
847  * across many cpus.  The actual IO submission is step two, and the ordered work
848  * queue takes care of making sure that happens in the same order things were
849  * put onto the queue by writepages and friends.
850  *
851  * If this code finds it can't get good compression, it puts an entry onto the
852  * work queue to write the uncompressed bytes.  This makes sure that both
853  * compressed inodes and uncompressed inodes are written in the same order that
854  * the flusher thread sent them down.
855  */
856 static void compress_file_range(struct btrfs_work *work)
857 {
858 	struct async_chunk *async_chunk =
859 		container_of(work, struct async_chunk, work);
860 	struct btrfs_inode *inode = async_chunk->inode;
861 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
862 	struct compressed_bio *cb = NULL;
863 	u64 blocksize = fs_info->sectorsize;
864 	u64 start = async_chunk->start;
865 	u64 end = async_chunk->end;
866 	u64 actual_end;
867 	u64 i_size;
868 	u32 cur_len;
869 	int ret = 0;
870 	unsigned long total_compressed = 0;
871 	unsigned long total_in = 0;
872 	int compress_type = fs_info->compress_type;
873 	int compress_level = fs_info->compress_level;
874 
875 	if (btrfs_is_shutdown(fs_info))
876 		goto cleanup_and_bail_uncompressed;
877 
878 	inode_should_defrag(inode, start, end, end - start + 1, SZ_16K);
879 
880 	/*
881 	 * We need to call clear_page_dirty_for_io on each page in the range.
882 	 * Otherwise applications with the file mmap'd can wander in and change
883 	 * the page contents while we are compressing them.
884 	 */
885 	ret = extent_range_clear_dirty_for_io(inode, start, end);
886 
887 	/*
888 	 * All the folios should have been locked thus no failure.
889 	 *
890 	 * And even if some folios are missing, btrfs_compress_bio()
891 	 * would handle them correctly, so here just do an ASSERT() check for
892 	 * early logic errors.
893 	 */
894 	ASSERT(ret == 0);
895 
896 	/*
897 	 * We need to save i_size before now because it could change in between
898 	 * us evaluating the size and assigning it.  This is because we lock and
899 	 * unlock the page in truncate and fallocate, and then modify the i_size
900 	 * later on.
901 	 *
902 	 * The barriers are to emulate READ_ONCE, remove that once i_size_read
903 	 * does that for us.
904 	 */
905 	barrier();
906 	i_size = i_size_read(&inode->vfs_inode);
907 	barrier();
908 	actual_end = min_t(u64, i_size, end + 1);
909 again:
910 	total_in = 0;
911 	cur_len = min(end + 1 - start, BTRFS_MAX_UNCOMPRESSED);
912 	ret = 0;
913 	cb = NULL;
914 
915 	/*
916 	 * we don't want to send crud past the end of i_size through
917 	 * compression, that's just a waste of CPU time.  So, if the
918 	 * end of the file is before the start of our current
919 	 * requested range of bytes, we bail out to the uncompressed
920 	 * cleanup code that can deal with all of this.
921 	 *
922 	 * It isn't really the fastest way to fix things, but this is a
923 	 * very uncommon corner.
924 	 */
925 	if (actual_end <= start)
926 		goto cleanup_and_bail_uncompressed;
927 
928 	/*
929 	 * We do compression for mount -o compress and when the inode has not
930 	 * been flagged as NOCOMPRESS.  This flag can change at any time if we
931 	 * discover bad compression ratios.
932 	 */
933 	if (!inode_need_compress(inode, start, end, false))
934 		goto cleanup_and_bail_uncompressed;
935 
936 	if (0 < inode->defrag_compress && inode->defrag_compress < BTRFS_NR_COMPRESS_TYPES) {
937 		compress_type = inode->defrag_compress;
938 		compress_level = inode->defrag_compress_level;
939 	} else if (inode->prop_compress) {
940 		compress_type = inode->prop_compress;
941 	}
942 
943 	/* Compression level is applied here. */
944 	cb = btrfs_compress_bio(inode, start, cur_len, compress_type,
945 				 compress_level, async_chunk->write_flags);
946 	if (IS_ERR(cb)) {
947 		cb = NULL;
948 		goto mark_incompressible;
949 	}
950 
951 	total_compressed = cb->bbio.bio.bi_iter.bi_size;
952 	total_in = cur_len;
953 
954 	/*
955 	 * We aren't doing an inline extent. Round the compressed size up to a
956 	 * block size boundary so the allocator does sane things.
957 	 */
958 	round_up_last_block(cb, blocksize);
959 	total_compressed = cb->bbio.bio.bi_iter.bi_size;
960 	ASSERT(IS_ALIGNED(total_compressed, blocksize));
961 
962 	/*
963 	 * One last check to make sure the compression is really a win, compare
964 	 * the page count read with the blocks on disk, compression must free at
965 	 * least one sector.
966 	 */
967 	total_in = round_up(total_in, fs_info->sectorsize);
968 	if (total_compressed + blocksize > total_in)
969 		goto mark_incompressible;
970 
971 
972 	/*
973 	 * The async work queues will take care of doing actual allocation on
974 	 * disk for these compressed pages, and will submit the bios.
975 	 */
976 	ret = add_async_extent(async_chunk, start, total_in, cb);
977 	BUG_ON(ret);
978 	if (start + total_in < end) {
979 		start += total_in;
980 		cond_resched();
981 		goto again;
982 	}
983 	return;
984 
985 mark_incompressible:
986 	if (!btrfs_test_opt(fs_info, FORCE_COMPRESS) && !inode->prop_compress)
987 		inode->flags |= BTRFS_INODE_NOCOMPRESS;
988 cleanup_and_bail_uncompressed:
989 	ret = add_async_extent(async_chunk, start, end - start + 1, NULL);
990 	BUG_ON(ret);
991 	if (cb)
992 		cleanup_compressed_bio(cb);
993 }
994 
995 static void submit_uncompressed_range(struct btrfs_inode *inode,
996 				      struct async_extent *async_extent,
997 				      struct folio *locked_folio)
998 {
999 	u64 start = async_extent->start;
1000 	u64 end = async_extent->start + async_extent->ram_size - 1;
1001 	int ret;
1002 	struct writeback_control wbc = {
1003 		.sync_mode		= WB_SYNC_ALL,
1004 		.range_start		= start,
1005 		.range_end		= end,
1006 		.no_cgroup_owner	= 1,
1007 	};
1008 
1009 	wbc_attach_fdatawrite_inode(&wbc, &inode->vfs_inode);
1010 	ret = run_delalloc_cow(inode, locked_folio, start, end,
1011 			       &wbc, false);
1012 	wbc_detach_inode(&wbc);
1013 	if (ret < 0) {
1014 		if (locked_folio)
1015 			btrfs_folio_end_lock(inode->root->fs_info, locked_folio,
1016 					     start, async_extent->ram_size);
1017 		btrfs_err_rl(inode->root->fs_info,
1018 			"%s failed, root=%llu inode=%llu start=%llu len=%llu: %d",
1019 			     __func__, btrfs_root_id(inode->root),
1020 			     btrfs_ino(inode), start, async_extent->ram_size, ret);
1021 	}
1022 }
1023 
1024 static void submit_one_async_extent(struct async_chunk *async_chunk,
1025 				    struct async_extent *async_extent,
1026 				    u64 *alloc_hint)
1027 {
1028 	struct btrfs_inode *inode = async_chunk->inode;
1029 	struct extent_io_tree *io_tree = &inode->io_tree;
1030 	struct btrfs_root *root = inode->root;
1031 	struct btrfs_fs_info *fs_info = root->fs_info;
1032 	struct btrfs_ordered_extent *ordered;
1033 	struct btrfs_file_extent file_extent;
1034 	struct btrfs_key ins;
1035 	struct folio *locked_folio = NULL;
1036 	struct extent_state *cached = NULL;
1037 	struct extent_map *em;
1038 	int ret = 0;
1039 	u32 compressed_size;
1040 	u64 start = async_extent->start;
1041 	u64 end = async_extent->start + async_extent->ram_size - 1;
1042 
1043 	if (async_chunk->blkcg_css)
1044 		kthread_associate_blkcg(async_chunk->blkcg_css);
1045 
1046 	/*
1047 	 * If async_chunk->locked_folio is in the async_extent range, we need to
1048 	 * handle it.
1049 	 */
1050 	if (async_chunk->locked_folio) {
1051 		u64 locked_folio_start = folio_pos(async_chunk->locked_folio);
1052 		u64 locked_folio_end = locked_folio_start +
1053 			folio_size(async_chunk->locked_folio) - 1;
1054 
1055 		if (!(start >= locked_folio_end || end <= locked_folio_start))
1056 			locked_folio = async_chunk->locked_folio;
1057 	}
1058 
1059 	if (!async_extent->cb) {
1060 		submit_uncompressed_range(inode, async_extent, locked_folio);
1061 		goto done;
1062 	}
1063 
1064 	compressed_size = async_extent->cb->bbio.bio.bi_iter.bi_size;
1065 	ret = btrfs_reserve_extent(root, async_extent->ram_size,
1066 				   compressed_size, compressed_size,
1067 				   0, *alloc_hint, &ins, true, true);
1068 	if (ret) {
1069 		/*
1070 		 * We can't reserve contiguous space for the compressed size.
1071 		 * Unlikely, but it's possible that we could have enough
1072 		 * non-contiguous space for the uncompressed size instead.  So
1073 		 * fall back to uncompressed.
1074 		 */
1075 		submit_uncompressed_range(inode, async_extent, locked_folio);
1076 		cleanup_compressed_bio(async_extent->cb);
1077 		async_extent->cb = NULL;
1078 		goto done;
1079 	}
1080 
1081 	btrfs_lock_extent(io_tree, start, end, &cached);
1082 
1083 	/* Here we're doing allocation and writeback of the compressed pages */
1084 	file_extent.disk_bytenr = ins.objectid;
1085 	file_extent.disk_num_bytes = ins.offset;
1086 	file_extent.ram_bytes = async_extent->ram_size;
1087 	file_extent.num_bytes = async_extent->ram_size;
1088 	file_extent.offset = 0;
1089 	file_extent.compression = async_extent->cb->compress_type;
1090 
1091 	async_extent->cb->bbio.bio.bi_iter.bi_sector = ins.objectid >> SECTOR_SHIFT;
1092 
1093 	em = btrfs_create_io_em(inode, start, &file_extent, BTRFS_ORDERED_COMPRESSED);
1094 	if (IS_ERR(em)) {
1095 		ret = PTR_ERR(em);
1096 		goto out_free_reserve;
1097 	}
1098 	btrfs_free_extent_map(em);
1099 
1100 	ordered = btrfs_alloc_ordered_extent(inode, start, &file_extent,
1101 					     1U << BTRFS_ORDERED_COMPRESSED);
1102 	if (IS_ERR(ordered)) {
1103 		btrfs_drop_extent_map_range(inode, start, end, false);
1104 		ret = PTR_ERR(ordered);
1105 		goto out_free_reserve;
1106 	}
1107 	async_extent->cb->bbio.ordered = ordered;
1108 	btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1109 
1110 	/* Clear dirty, set writeback and unlock the pages. */
1111 	extent_clear_unlock_delalloc(inode, start, end,
1112 			NULL, &cached, EXTENT_LOCKED | EXTENT_DELALLOC,
1113 			PAGE_UNLOCK | PAGE_START_WRITEBACK);
1114 	btrfs_submit_bbio(&async_extent->cb->bbio, 0);
1115 	async_extent->cb = NULL;
1116 
1117 	*alloc_hint = ins.objectid + ins.offset;
1118 done:
1119 	if (async_chunk->blkcg_css)
1120 		kthread_associate_blkcg(NULL);
1121 	kfree(async_extent);
1122 	return;
1123 
1124 out_free_reserve:
1125 	btrfs_dec_block_group_reservations(fs_info, ins.objectid);
1126 	btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, true);
1127 	mapping_set_error(inode->vfs_inode.i_mapping, -EIO);
1128 	extent_clear_unlock_delalloc(inode, start, end,
1129 				     NULL, &cached,
1130 				     EXTENT_LOCKED | EXTENT_DELALLOC |
1131 				     EXTENT_DELALLOC_NEW |
1132 				     EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV,
1133 				     PAGE_UNLOCK | PAGE_START_WRITEBACK |
1134 				     PAGE_END_WRITEBACK);
1135 	if (async_extent->cb)
1136 		cleanup_compressed_bio(async_extent->cb);
1137 	if (async_chunk->blkcg_css)
1138 		kthread_associate_blkcg(NULL);
1139 	btrfs_debug(fs_info,
1140 "async extent submission failed root=%lld inode=%llu start=%llu len=%llu ret=%d",
1141 		    btrfs_root_id(root), btrfs_ino(inode), start,
1142 		    async_extent->ram_size, ret);
1143 	kfree(async_extent);
1144 }
1145 
1146 u64 btrfs_get_extent_allocation_hint(struct btrfs_inode *inode, u64 start,
1147 				     u64 num_bytes)
1148 {
1149 	struct extent_map_tree *em_tree = &inode->extent_tree;
1150 	struct extent_map *em;
1151 	u64 alloc_hint = 0;
1152 
1153 	read_lock(&em_tree->lock);
1154 	em = btrfs_search_extent_mapping(em_tree, start, num_bytes);
1155 	if (em) {
1156 		/*
1157 		 * if block start isn't an actual block number then find the
1158 		 * first block in this inode and use that as a hint.  If that
1159 		 * block is also bogus then just don't worry about it.
1160 		 */
1161 		if (em->disk_bytenr >= EXTENT_MAP_LAST_BYTE) {
1162 			btrfs_free_extent_map(em);
1163 			em = btrfs_search_extent_mapping(em_tree, 0, 0);
1164 			if (em && em->disk_bytenr < EXTENT_MAP_LAST_BYTE)
1165 				alloc_hint = btrfs_extent_map_block_start(em);
1166 			if (em)
1167 				btrfs_free_extent_map(em);
1168 		} else {
1169 			alloc_hint = btrfs_extent_map_block_start(em);
1170 			btrfs_free_extent_map(em);
1171 		}
1172 	}
1173 	read_unlock(&em_tree->lock);
1174 
1175 	return alloc_hint;
1176 }
1177 
1178 /*
1179  * Handle COW for one range.
1180  *
1181  * @ins:		The key representing the allocated range.
1182  * @file_offset:	The file offset of the COW range
1183  * @num_bytes:		The expected length of the COW range
1184  *			The actually allocated length can be smaller than it.
1185  * @min_alloc_size:	The minimal extent size.
1186  * @alloc_hint:		The hint for the extent allocator.
1187  * @ret_alloc_size:	The COW range handles by this function.
1188  *
1189  * Return 0 if everything is fine and update @ret_alloc_size updated.  The
1190  * range is still locked, and caller should unlock the range after everything
1191  * is done or for error handling.
1192  *
1193  * Return <0 for error and @is updated for where the extra cleanup should
1194  * happen. The range [file_offset, file_offset + ret_alloc_size) will be
1195  * cleaned up by this function.
1196  */
1197 static int cow_one_range(struct btrfs_inode *inode, struct folio *locked_folio,
1198 			 struct btrfs_key *ins, struct extent_state **cached,
1199 			 u64 file_offset, u32 num_bytes, u32 min_alloc_size,
1200 			 u64 alloc_hint, u32 *ret_alloc_size)
1201 {
1202 	struct btrfs_root *root = inode->root;
1203 	struct btrfs_fs_info *fs_info = root->fs_info;
1204 	struct btrfs_ordered_extent *ordered;
1205 	struct btrfs_file_extent file_extent;
1206 	struct extent_map *em;
1207 	u32 cur_len = 0;
1208 	u64 cur_end;
1209 	int ret;
1210 
1211 	ret = btrfs_reserve_extent(root, num_bytes, num_bytes, min_alloc_size,
1212 				   0, alloc_hint, ins, true, true);
1213 	if (ret < 0) {
1214 		*ret_alloc_size = cur_len;
1215 		return ret;
1216 	}
1217 
1218 	cur_len = ins->offset;
1219 	cur_end = file_offset + cur_len - 1;
1220 
1221 	file_extent.disk_bytenr = ins->objectid;
1222 	file_extent.disk_num_bytes = ins->offset;
1223 	file_extent.num_bytes = ins->offset;
1224 	file_extent.ram_bytes = ins->offset;
1225 	file_extent.offset = 0;
1226 	file_extent.compression = BTRFS_COMPRESS_NONE;
1227 
1228 	/*
1229 	 * Locked range will be released either during error clean up (inside
1230 	 * this function or by the caller for previously successful ranges) or
1231 	 * after the whole range is finished.
1232 	 */
1233 	btrfs_lock_extent(&inode->io_tree, file_offset, cur_end, cached);
1234 	em = btrfs_create_io_em(inode, file_offset, &file_extent, BTRFS_ORDERED_REGULAR);
1235 	if (IS_ERR(em)) {
1236 		ret = PTR_ERR(em);
1237 		goto free_reserved;
1238 	}
1239 	btrfs_free_extent_map(em);
1240 
1241 	ordered = btrfs_alloc_ordered_extent(inode, file_offset, &file_extent,
1242 					     1U << BTRFS_ORDERED_REGULAR);
1243 	if (IS_ERR(ordered)) {
1244 		btrfs_drop_extent_map_range(inode, file_offset, cur_end, false);
1245 		ret = PTR_ERR(ordered);
1246 		goto free_reserved;
1247 	}
1248 
1249 	if (btrfs_is_data_reloc_root(root)) {
1250 		ret = btrfs_reloc_clone_csums(ordered);
1251 
1252 		/*
1253 		 * Only drop cache here, and process as normal.
1254 		 *
1255 		 * We must not allow extent_clear_unlock_delalloc() at
1256 		 * free_reserved label to free meta of this ordered extent, as
1257 		 * its meta should be freed by btrfs_finish_ordered_io().
1258 		 *
1259 		 * So we must continue until @start is increased to
1260 		 * skip current ordered extent.
1261 		 */
1262 		if (ret)
1263 			btrfs_drop_extent_map_range(inode, file_offset,
1264 						    cur_end, false);
1265 	}
1266 	btrfs_put_ordered_extent(ordered);
1267 	btrfs_dec_block_group_reservations(fs_info, ins->objectid);
1268 	/*
1269 	 * Error handling for btrfs_reloc_clone_csums().
1270 	 *
1271 	 * Treat the range as finished, thus only clear EXTENT_LOCKED | EXTENT_DELALLOC.
1272 	 * The accounting will be done by ordered extents.
1273 	 */
1274 	if (unlikely(ret < 0)) {
1275 		btrfs_cleanup_ordered_extents(inode, file_offset, cur_len);
1276 		extent_clear_unlock_delalloc(inode, file_offset, cur_end, locked_folio, cached,
1277 					     EXTENT_LOCKED | EXTENT_DELALLOC,
1278 					     PAGE_UNLOCK | PAGE_START_WRITEBACK |
1279 					     PAGE_END_WRITEBACK);
1280 		mapping_set_error(inode->vfs_inode.i_mapping, -EIO);
1281 	}
1282 	*ret_alloc_size = cur_len;
1283 	return ret;
1284 
1285 free_reserved:
1286 	/*
1287 	 * If we have reserved an extent for the current range and failed to
1288 	 * create the respective extent map or ordered extent, it means that
1289 	 * when we reserved the extent we decremented the extent's size from
1290 	 * the data space_info's bytes_may_use counter and
1291 	 * incremented the space_info's bytes_reserved counter by the same
1292 	 * amount.
1293 	 *
1294 	 * We must make sure extent_clear_unlock_delalloc() does not try
1295 	 * to decrement again the data space_info's bytes_may_use counter, which
1296 	 * will be handled by btrfs_free_reserved_extent().
1297 	 *
1298 	 * Therefore we do not pass it the flag EXTENT_CLEAR_DATA_RESV, but only
1299 	 * EXTENT_CLEAR_META_RESV.
1300 	 */
1301 	extent_clear_unlock_delalloc(inode, file_offset, cur_end, locked_folio, cached,
1302 				     EXTENT_LOCKED | EXTENT_DELALLOC |
1303 				     EXTENT_DELALLOC_NEW |
1304 				     EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV,
1305 				     PAGE_UNLOCK | PAGE_START_WRITEBACK |
1306 				     PAGE_END_WRITEBACK);
1307 	btrfs_qgroup_free_data(inode, NULL, file_offset, cur_len, NULL);
1308 	btrfs_dec_block_group_reservations(fs_info, ins->objectid);
1309 	btrfs_free_reserved_extent(fs_info, ins->objectid, ins->offset, true);
1310 	mapping_set_error(inode->vfs_inode.i_mapping, -EIO);
1311 	*ret_alloc_size = cur_len;
1312 	/*
1313 	 * We should not return -EAGAIN where it's a special return code for
1314 	 * zoned to catch btrfs_reserved_extent().
1315 	 */
1316 	ASSERT(ret != -EAGAIN);
1317 	return ret;
1318 }
1319 
1320 /*
1321  * when extent_io.c finds a delayed allocation range in the file,
1322  * the call backs end up in this code.  The basic idea is to
1323  * allocate extents on disk for the range, and create ordered data structs
1324  * in ram to track those extents.
1325  *
1326  * locked_folio is the folio that writepage had locked already.  We use
1327  * it to make sure we don't do extra locks or unlocks.
1328  *
1329  * When this function fails, it unlocks all folios except @locked_folio.
1330  *
1331  * When this function succeed and creates a normal extent, the folio locking
1332  * status depends on the passed in flags:
1333  *
1334  * - If COW_FILE_RANGE_KEEP_LOCKED flag is set, all folios are kept locked.
1335  * - Else all folios except for @locked_folio are unlocked.
1336  *
1337  * When a failure happens in the second or later iteration of the
1338  * while-loop, the ordered extents created in previous iterations are cleaned up.
1339  */
1340 static noinline int cow_file_range(struct btrfs_inode *inode,
1341 				   struct folio *locked_folio, u64 start,
1342 				   u64 end, u64 *done_offset,
1343 				   unsigned long flags)
1344 {
1345 	struct btrfs_root *root = inode->root;
1346 	struct btrfs_fs_info *fs_info = root->fs_info;
1347 	struct extent_state *cached = NULL;
1348 	u64 alloc_hint = 0;
1349 	u64 orig_start = start;
1350 	u64 num_bytes;
1351 	u32 min_alloc_size;
1352 	u32 blocksize = fs_info->sectorsize;
1353 	u32 cur_alloc_size = 0;
1354 	struct btrfs_key ins;
1355 	unsigned clear_bits;
1356 	unsigned long page_ops;
1357 	int ret = 0;
1358 
1359 	if (btrfs_is_shutdown(fs_info)) {
1360 		ret = -EIO;
1361 		goto out_unlock;
1362 	}
1363 
1364 	if (btrfs_is_free_space_inode(inode)) {
1365 		ret = -EINVAL;
1366 		goto out_unlock;
1367 	}
1368 
1369 	num_bytes = ALIGN(end - start + 1, blocksize);
1370 	num_bytes = max(blocksize,  num_bytes);
1371 	ASSERT(num_bytes <= btrfs_super_total_bytes(fs_info->super_copy));
1372 
1373 	inode_should_defrag(inode, start, end, num_bytes, SZ_64K);
1374 	alloc_hint = btrfs_get_extent_allocation_hint(inode, start, num_bytes);
1375 
1376 	/*
1377 	 * We're not doing compressed IO, don't unlock the first page (which
1378 	 * the caller expects to stay locked), don't clear any dirty bits and
1379 	 * don't set any writeback bits.
1380 	 *
1381 	 * Do set the Ordered (Private2) bit so we know this page was properly
1382 	 * setup for writepage.
1383 	 */
1384 	page_ops = ((flags & COW_FILE_RANGE_KEEP_LOCKED) ? 0 : PAGE_UNLOCK);
1385 
1386 	/*
1387 	 * Relocation relies on the relocated extents to have exactly the same
1388 	 * size as the original extents. Normally writeback for relocation data
1389 	 * extents follows a NOCOW path because relocation preallocates the
1390 	 * extents. However, due to an operation such as scrub turning a block
1391 	 * group to RO mode, it may fallback to COW mode, so we must make sure
1392 	 * an extent allocated during COW has exactly the requested size and can
1393 	 * not be split into smaller extents, otherwise relocation breaks and
1394 	 * fails during the stage where it updates the bytenr of file extent
1395 	 * items.
1396 	 */
1397 	if (btrfs_is_data_reloc_root(root))
1398 		min_alloc_size = num_bytes;
1399 	else
1400 		min_alloc_size = fs_info->sectorsize;
1401 
1402 	while (num_bytes > 0) {
1403 		ret = cow_one_range(inode, locked_folio, &ins, &cached, start,
1404 				    num_bytes, min_alloc_size, alloc_hint, &cur_alloc_size);
1405 
1406 		if (ret == -EAGAIN) {
1407 			/*
1408 			 * cow_one_range() only returns -EAGAIN for zoned
1409 			 * file systems (from btrfs_reserve_extent()), which
1410 			 * is an indication that there are
1411 			 * no active zones to allocate from at the moment.
1412 			 *
1413 			 * If this is the first loop iteration, wait for at
1414 			 * least one zone to finish before retrying the
1415 			 * allocation.  Otherwise ask the caller to write out
1416 			 * the already allocated blocks before coming back to
1417 			 * us, or return -ENOSPC if it can't handle retries.
1418 			 */
1419 			ASSERT(btrfs_is_zoned(fs_info));
1420 			if (start == orig_start) {
1421 				wait_on_bit_io(&inode->root->fs_info->flags,
1422 					       BTRFS_FS_NEED_ZONE_FINISH,
1423 					       TASK_UNINTERRUPTIBLE);
1424 				continue;
1425 			}
1426 			if (done_offset) {
1427 				/*
1428 				 * Move @end to the end of the processed range,
1429 				 * and exit the loop to unlock the processed extents.
1430 				 */
1431 				end = start - 1;
1432 				ret = 0;
1433 				break;
1434 			}
1435 			ret = -ENOSPC;
1436 		}
1437 		if (ret < 0)
1438 			goto out_unlock;
1439 
1440 		/* We should not allocate an extent larger than requested.*/
1441 		ASSERT(cur_alloc_size <= num_bytes);
1442 
1443 		num_bytes -= cur_alloc_size;
1444 		alloc_hint = ins.objectid + ins.offset;
1445 		start += cur_alloc_size;
1446 		cur_alloc_size = 0;
1447 	}
1448 	extent_clear_unlock_delalloc(inode, orig_start, end, locked_folio, &cached,
1449 				     EXTENT_LOCKED | EXTENT_DELALLOC, page_ops);
1450 	if (done_offset)
1451 		*done_offset = end;
1452 	return ret;
1453 
1454 out_unlock:
1455 	/*
1456 	 * Now, we have three regions to clean up:
1457 	 *
1458 	 * |-------(1)----|---(2)---|-------------(3)----------|
1459 	 * `- orig_start  `- start  `- start + cur_alloc_size  `- end
1460 	 *
1461 	 * We process each region below.
1462 	 */
1463 
1464 	/*
1465 	 * For the range (1). We have already instantiated the ordered extents
1466 	 * for this region, thus we need to cleanup those ordered extents.
1467 	 * EXTENT_DELALLOC_NEW | EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV
1468 	 * are also handled by the ordered extents cleanup.
1469 	 *
1470 	 * So here we only clear EXTENT_LOCKED and EXTENT_DELALLOC flag, and
1471 	 * finish the writeback of the involved folios, which will be never submitted.
1472 	 */
1473 	if (orig_start < start) {
1474 		clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC;
1475 		page_ops = PAGE_UNLOCK | PAGE_START_WRITEBACK | PAGE_END_WRITEBACK;
1476 
1477 		if (!locked_folio)
1478 			mapping_set_error(inode->vfs_inode.i_mapping, ret);
1479 
1480 		btrfs_cleanup_ordered_extents(inode, orig_start, start - orig_start);
1481 		extent_clear_unlock_delalloc(inode, orig_start, start - 1,
1482 					     locked_folio, NULL, clear_bits, page_ops);
1483 	}
1484 
1485 	clear_bits = EXTENT_LOCKED | EXTENT_DELALLOC | EXTENT_DELALLOC_NEW |
1486 		     EXTENT_DEFRAG | EXTENT_CLEAR_META_RESV;
1487 	page_ops = PAGE_UNLOCK | PAGE_START_WRITEBACK | PAGE_END_WRITEBACK;
1488 
1489 	/*
1490 	 * For the range (2) the error handling is done by cow_one_range() itself.
1491 	 * Nothing needs to be done.
1492 	 *
1493 	 * For the range (3). We never touched the region. In addition to the
1494 	 * clear_bits above, we add EXTENT_CLEAR_DATA_RESV to release the data
1495 	 * space_info's bytes_may_use counter, reserved in
1496 	 * btrfs_check_data_free_space().
1497 	 */
1498 	if (start + cur_alloc_size < end) {
1499 		clear_bits |= EXTENT_CLEAR_DATA_RESV;
1500 		extent_clear_unlock_delalloc(inode, start + cur_alloc_size,
1501 					     end, locked_folio,
1502 					     &cached, clear_bits, page_ops);
1503 		btrfs_qgroup_free_data(inode, NULL, start + cur_alloc_size,
1504 				       end - start - cur_alloc_size + 1, NULL);
1505 	}
1506 	btrfs_err(fs_info,
1507 "%s failed, root=%llu inode=%llu start=%llu len=%llu cur_offset=%llu cur_alloc_size=%u: %d",
1508 		  __func__, btrfs_root_id(inode->root),
1509 		  btrfs_ino(inode), orig_start, end + 1 - orig_start,
1510 		  start, cur_alloc_size, ret);
1511 	return ret;
1512 }
1513 
1514 /*
1515  * Phase two of compressed writeback.  This is the ordered portion of the code,
1516  * which only gets called in the order the work was queued.  We walk all the
1517  * async extents created by compress_file_range and send them down to the disk.
1518  *
1519  * If called with @do_free == true then it'll try to finish the work and free
1520  * the work struct eventually.
1521  */
1522 static noinline void submit_compressed_extents(struct btrfs_work *work, bool do_free)
1523 {
1524 	struct async_chunk *async_chunk = container_of(work, struct async_chunk,
1525 						     work);
1526 	struct btrfs_fs_info *fs_info = btrfs_work_owner(work);
1527 	struct async_extent *async_extent;
1528 	unsigned long nr_pages;
1529 	u64 alloc_hint = 0;
1530 
1531 	if (do_free) {
1532 		struct async_cow *async_cow;
1533 
1534 		btrfs_add_delayed_iput(async_chunk->inode);
1535 		if (async_chunk->blkcg_css)
1536 			css_put(async_chunk->blkcg_css);
1537 
1538 		async_cow = async_chunk->async_cow;
1539 		if (atomic_dec_and_test(&async_cow->num_chunks))
1540 			kvfree(async_cow);
1541 		return;
1542 	}
1543 
1544 	nr_pages = (async_chunk->end - async_chunk->start + PAGE_SIZE) >>
1545 		PAGE_SHIFT;
1546 
1547 	while (!list_empty(&async_chunk->extents)) {
1548 		async_extent = list_first_entry(&async_chunk->extents,
1549 						struct async_extent, list);
1550 		list_del(&async_extent->list);
1551 		submit_one_async_extent(async_chunk, async_extent, &alloc_hint);
1552 	}
1553 
1554 	/* atomic_sub_return implies a barrier */
1555 	if (atomic_sub_return(nr_pages, &fs_info->async_delalloc_pages) <
1556 	    5 * SZ_1M)
1557 		cond_wake_up_nomb(&fs_info->async_submit_wait);
1558 }
1559 
1560 static bool run_delalloc_compressed(struct btrfs_inode *inode,
1561 				    struct folio *locked_folio, u64 start,
1562 				    u64 end, struct writeback_control *wbc)
1563 {
1564 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
1565 	struct cgroup_subsys_state *blkcg_css = wbc_blkcg_css(wbc);
1566 	struct async_cow *ctx;
1567 	struct async_chunk *async_chunk;
1568 	unsigned long nr_pages;
1569 	u64 num_chunks = DIV_ROUND_UP(end - start, BTRFS_COMPRESSION_CHUNK_SIZE);
1570 	int i;
1571 	unsigned nofs_flag;
1572 	const blk_opf_t write_flags = wbc_to_write_flags(wbc);
1573 
1574 	nofs_flag = memalloc_nofs_save();
1575 	ctx = kvmalloc_flex(*ctx, chunks, num_chunks);
1576 	memalloc_nofs_restore(nofs_flag);
1577 	if (!ctx)
1578 		return false;
1579 
1580 	set_bit(BTRFS_INODE_HAS_ASYNC_EXTENT, &inode->runtime_flags);
1581 
1582 	async_chunk = ctx->chunks;
1583 	atomic_set(&ctx->num_chunks, num_chunks);
1584 
1585 	for (i = 0; i < num_chunks; i++) {
1586 		u64 cur_end = min(end, start + BTRFS_COMPRESSION_CHUNK_SIZE - 1);
1587 
1588 		/*
1589 		 * igrab is called higher up in the call chain, take only the
1590 		 * lightweight reference for the callback lifetime
1591 		 */
1592 		ihold(&inode->vfs_inode);
1593 		async_chunk[i].async_cow = ctx;
1594 		async_chunk[i].inode = inode;
1595 		async_chunk[i].start = start;
1596 		async_chunk[i].end = cur_end;
1597 		async_chunk[i].write_flags = write_flags;
1598 		INIT_LIST_HEAD(&async_chunk[i].extents);
1599 
1600 		/*
1601 		 * The locked_folio comes all the way from writepage and its
1602 		 * the original folio we were actually given.  As we spread
1603 		 * this large delalloc region across multiple async_chunk
1604 		 * structs, only the first struct needs a pointer to
1605 		 * locked_folio.
1606 		 *
1607 		 * This way we don't need racey decisions about who is supposed
1608 		 * to unlock it.
1609 		 */
1610 		if (locked_folio) {
1611 			/*
1612 			 * Depending on the compressibility, the pages might or
1613 			 * might not go through async.  We want all of them to
1614 			 * be accounted against wbc once.  Let's do it here
1615 			 * before the paths diverge.  wbc accounting is used
1616 			 * only for foreign writeback detection and doesn't
1617 			 * need full accuracy.  Just account the whole thing
1618 			 * against the first page.
1619 			 */
1620 			wbc_account_cgroup_owner(wbc, locked_folio,
1621 						 cur_end - start);
1622 			async_chunk[i].locked_folio = locked_folio;
1623 			locked_folio = NULL;
1624 		} else {
1625 			async_chunk[i].locked_folio = NULL;
1626 		}
1627 
1628 		if (blkcg_css != blkcg_root_css) {
1629 			css_get(blkcg_css);
1630 			async_chunk[i].blkcg_css = blkcg_css;
1631 			async_chunk[i].write_flags |= REQ_BTRFS_CGROUP_PUNT;
1632 		} else {
1633 			async_chunk[i].blkcg_css = NULL;
1634 		}
1635 
1636 		btrfs_init_work(&async_chunk[i].work, compress_file_range,
1637 				submit_compressed_extents);
1638 
1639 		nr_pages = DIV_ROUND_UP(cur_end - start, PAGE_SIZE);
1640 		atomic_add(nr_pages, &fs_info->async_delalloc_pages);
1641 
1642 		btrfs_queue_work(fs_info->delalloc_workers, &async_chunk[i].work);
1643 
1644 		start = cur_end + 1;
1645 	}
1646 	return true;
1647 }
1648 
1649 /*
1650  * Run the delalloc range from start to end, and write back any dirty pages
1651  * covered by the range.
1652  */
1653 static noinline int run_delalloc_cow(struct btrfs_inode *inode,
1654 				     struct folio *locked_folio, u64 start,
1655 				     u64 end, struct writeback_control *wbc,
1656 				     bool pages_dirty)
1657 {
1658 	u64 done_offset = end;
1659 	int ret;
1660 
1661 	while (start <= end) {
1662 		ret = cow_file_range(inode, locked_folio, start, end,
1663 				     &done_offset, COW_FILE_RANGE_KEEP_LOCKED);
1664 		if (ret)
1665 			return ret;
1666 		extent_write_locked_range(&inode->vfs_inode, locked_folio,
1667 					  start, done_offset, wbc, pages_dirty);
1668 		start = done_offset + 1;
1669 	}
1670 
1671 	return 1;
1672 }
1673 
1674 static int fallback_to_cow(struct btrfs_inode *inode,
1675 			   struct folio *locked_folio, const u64 start,
1676 			   const u64 end)
1677 {
1678 	const bool is_space_ino = btrfs_is_free_space_inode(inode);
1679 	const bool is_reloc_ino = btrfs_is_data_reloc_root(inode->root);
1680 	const u64 range_bytes = end + 1 - start;
1681 	struct extent_io_tree *io_tree = &inode->io_tree;
1682 	struct extent_state *cached_state = NULL;
1683 	u64 range_start = start;
1684 	u64 count;
1685 	int ret;
1686 
1687 	/*
1688 	 * If EXTENT_NORESERVE is set it means that when the buffered write was
1689 	 * made we had not enough available data space and therefore we did not
1690 	 * reserve data space for it, since we though we could do NOCOW for the
1691 	 * respective file range (either there is prealloc extent or the inode
1692 	 * has the NOCOW bit set).
1693 	 *
1694 	 * However when we need to fallback to COW mode (because for example the
1695 	 * block group for the corresponding extent was turned to RO mode by a
1696 	 * scrub or relocation) we need to do the following:
1697 	 *
1698 	 * 1) We increment the bytes_may_use counter of the data space info.
1699 	 *    If COW succeeds, it allocates a new data extent and after doing
1700 	 *    that it decrements the space info's bytes_may_use counter and
1701 	 *    increments its bytes_reserved counter by the same amount (we do
1702 	 *    this at btrfs_add_reserved_bytes()). So we need to increment the
1703 	 *    bytes_may_use counter to compensate (when space is reserved at
1704 	 *    buffered write time, the bytes_may_use counter is incremented);
1705 	 *
1706 	 * 2) We clear the EXTENT_NORESERVE bit from the range. We do this so
1707 	 *    that if the COW path fails for any reason, it decrements (through
1708 	 *    extent_clear_unlock_delalloc()) the bytes_may_use counter of the
1709 	 *    data space info, which we incremented in the step above.
1710 	 *
1711 	 * If we need to fallback to cow and the inode corresponds to a free
1712 	 * space cache inode or an inode of the data relocation tree, we must
1713 	 * also increment bytes_may_use of the data space_info for the same
1714 	 * reason. Space caches and relocated data extents always get a prealloc
1715 	 * extent for them, however scrub or balance may have set the block
1716 	 * group that contains that extent to RO mode and therefore force COW
1717 	 * when starting writeback.
1718 	 */
1719 	btrfs_lock_extent(io_tree, start, end, &cached_state);
1720 	count = btrfs_count_range_bits(io_tree, &range_start, end, range_bytes,
1721 				       EXTENT_NORESERVE, false, NULL);
1722 	if (count > 0 || is_space_ino || is_reloc_ino) {
1723 		u64 bytes = count;
1724 		struct btrfs_fs_info *fs_info = inode->root->fs_info;
1725 		struct btrfs_space_info *sinfo = fs_info->data_sinfo;
1726 
1727 		if (is_space_ino || is_reloc_ino)
1728 			bytes = range_bytes;
1729 
1730 		spin_lock(&sinfo->lock);
1731 		btrfs_space_info_update_bytes_may_use(sinfo, bytes);
1732 		spin_unlock(&sinfo->lock);
1733 
1734 		if (count > 0)
1735 			btrfs_clear_extent_bit(io_tree, start, end, EXTENT_NORESERVE,
1736 					       &cached_state);
1737 	}
1738 	btrfs_unlock_extent(io_tree, start, end, &cached_state);
1739 
1740 	/*
1741 	 * Don't try to create inline extents, as a mix of inline extent that
1742 	 * is written out and unlocked directly and a normal NOCOW extent
1743 	 * doesn't work.
1744 	 *
1745 	 * And here we do not unlock the folio after a successful run.
1746 	 * The folios will be unlocked after everything is finished, or by error handling.
1747 	 *
1748 	 * This is to ensure error handling won't need to clear dirty/ordered flags without
1749 	 * a locked folio, which can race with writeback.
1750 	 */
1751 	ret = cow_file_range(inode, locked_folio, start, end, NULL,
1752 			     COW_FILE_RANGE_KEEP_LOCKED);
1753 	ASSERT(ret != 1);
1754 	return ret;
1755 }
1756 
1757 struct can_nocow_file_extent_args {
1758 	/* Input fields. */
1759 
1760 	/* Start file offset of the range we want to NOCOW. */
1761 	u64 start;
1762 	/* End file offset (inclusive) of the range we want to NOCOW. */
1763 	u64 end;
1764 	bool writeback_path;
1765 	/*
1766 	 * Free the path passed to can_nocow_file_extent() once it's not needed
1767 	 * anymore.
1768 	 */
1769 	bool free_path;
1770 
1771 	/*
1772 	 * Output fields. Only set when can_nocow_file_extent() returns 1.
1773 	 * The expected file extent for the NOCOW write.
1774 	 */
1775 	struct btrfs_file_extent file_extent;
1776 };
1777 
1778 /*
1779  * Check if we can NOCOW the file extent that the path points to.
1780  * This function may return with the path released, so the caller should check
1781  * if path->nodes[0] is NULL or not if it needs to use the path afterwards.
1782  *
1783  * Returns: < 0 on error
1784  *            0 if we can not NOCOW
1785  *            1 if we can NOCOW
1786  */
1787 static int can_nocow_file_extent(struct btrfs_path *path,
1788 				 struct btrfs_key *key,
1789 				 struct btrfs_inode *inode,
1790 				 struct can_nocow_file_extent_args *args)
1791 {
1792 	const bool is_freespace_inode = btrfs_is_free_space_inode(inode);
1793 	struct extent_buffer *leaf = path->nodes[0];
1794 	struct btrfs_root *root = inode->root;
1795 	struct btrfs_file_extent_item *fi;
1796 	struct btrfs_root *csum_root;
1797 	u64 io_start;
1798 	u64 extent_end;
1799 	u8 extent_type;
1800 	int can_nocow = 0;
1801 	int ret = 0;
1802 	bool nowait = path->nowait;
1803 
1804 	/* If there are pending snapshots for this root, we must do COW. */
1805 	if (args->writeback_path && !is_freespace_inode &&
1806 	    atomic_read(&root->snapshot_force_cow))
1807 		goto out;
1808 
1809 	fi = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
1810 	extent_type = btrfs_file_extent_type(leaf, fi);
1811 
1812 	if (extent_type == BTRFS_FILE_EXTENT_INLINE)
1813 		goto out;
1814 
1815 	if (!(inode->flags & BTRFS_INODE_NODATACOW) &&
1816 	    extent_type == BTRFS_FILE_EXTENT_REG)
1817 		goto out;
1818 
1819 	/*
1820 	 * If the extent was created before the generation where the last snapshot
1821 	 * for its subvolume was created, then this implies the extent is shared,
1822 	 * hence we must COW.
1823 	 */
1824 	if (btrfs_file_extent_generation(leaf, fi) <=
1825 	    btrfs_root_last_snapshot(&root->root_item))
1826 		goto out;
1827 
1828 	/* An explicit hole, must COW. */
1829 	if (btrfs_file_extent_disk_bytenr(leaf, fi) == 0)
1830 		goto out;
1831 
1832 	/* Compressed/encrypted/encoded extents must be COWed. */
1833 	if (btrfs_file_extent_compression(leaf, fi) ||
1834 	    btrfs_file_extent_encryption(leaf, fi) ||
1835 	    btrfs_file_extent_other_encoding(leaf, fi))
1836 		goto out;
1837 
1838 	extent_end = btrfs_file_extent_end(path);
1839 
1840 	args->file_extent.disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1841 	args->file_extent.disk_num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
1842 	args->file_extent.ram_bytes = btrfs_file_extent_ram_bytes(leaf, fi);
1843 	args->file_extent.offset = btrfs_file_extent_offset(leaf, fi);
1844 	args->file_extent.compression = btrfs_file_extent_compression(leaf, fi);
1845 
1846 	/*
1847 	 * The following checks can be expensive, as they need to take other
1848 	 * locks and do btree or rbtree searches, so release the path to avoid
1849 	 * blocking other tasks for too long.
1850 	 */
1851 	btrfs_release_path(path);
1852 
1853 	ret = btrfs_cross_ref_exist(inode, key->offset - args->file_extent.offset,
1854 				    args->file_extent.disk_bytenr, path);
1855 	WARN_ON_ONCE(ret > 0 && is_freespace_inode);
1856 	if (ret != 0)
1857 		goto out;
1858 
1859 	if (args->free_path) {
1860 		/*
1861 		 * We don't need the path anymore, plus through the
1862 		 * btrfs_lookup_csums_list() call below we will end up allocating
1863 		 * another path. So free the path to avoid unnecessary extra
1864 		 * memory usage.
1865 		 */
1866 		btrfs_free_path(path);
1867 		path = NULL;
1868 	}
1869 
1870 	args->file_extent.num_bytes = min(args->end + 1, extent_end) - args->start;
1871 	args->file_extent.offset += args->start - key->offset;
1872 	io_start = args->file_extent.disk_bytenr + args->file_extent.offset;
1873 
1874 	/*
1875 	 * Force COW if csums exist in the range. This ensures that csums for a
1876 	 * given extent are either valid or do not exist.
1877 	 */
1878 
1879 	csum_root = btrfs_csum_root(root->fs_info, io_start);
1880 	if (unlikely(!csum_root)) {
1881 		btrfs_err(root->fs_info,
1882 			  "missing csum root for extent at bytenr %llu", io_start);
1883 		ret = -EUCLEAN;
1884 		goto out;
1885 	}
1886 
1887 	ret = btrfs_lookup_csums_list(csum_root, io_start,
1888 				      io_start + args->file_extent.num_bytes - 1,
1889 				      NULL, nowait);
1890 	WARN_ON_ONCE(ret > 0 && is_freespace_inode);
1891 	if (ret != 0)
1892 		goto out;
1893 
1894 	can_nocow = 1;
1895  out:
1896 	if (args->free_path && path)
1897 		btrfs_free_path(path);
1898 
1899 	return ret < 0 ? ret : can_nocow;
1900 }
1901 
1902 static int nocow_one_range(struct btrfs_inode *inode, struct folio *locked_folio,
1903 			   struct extent_state **cached,
1904 			   struct can_nocow_file_extent_args *nocow_args,
1905 			   u64 file_pos, bool is_prealloc)
1906 {
1907 	struct btrfs_ordered_extent *ordered;
1908 	const u64 len = nocow_args->file_extent.num_bytes;
1909 	const u64 end = file_pos + len - 1;
1910 	int ret = 0;
1911 
1912 	btrfs_lock_extent(&inode->io_tree, file_pos, end, cached);
1913 
1914 	if (is_prealloc) {
1915 		struct extent_map *em;
1916 
1917 		em = btrfs_create_io_em(inode, file_pos, &nocow_args->file_extent,
1918 					BTRFS_ORDERED_PREALLOC);
1919 		if (IS_ERR(em)) {
1920 			ret = PTR_ERR(em);
1921 			goto error;
1922 		}
1923 		btrfs_free_extent_map(em);
1924 	}
1925 
1926 	ordered = btrfs_alloc_ordered_extent(inode, file_pos, &nocow_args->file_extent,
1927 					     is_prealloc
1928 					     ? (1U << BTRFS_ORDERED_PREALLOC)
1929 					     : (1U << BTRFS_ORDERED_NOCOW));
1930 	if (IS_ERR(ordered)) {
1931 		if (is_prealloc)
1932 			btrfs_drop_extent_map_range(inode, file_pos, end, false);
1933 		ret = PTR_ERR(ordered);
1934 		goto error;
1935 	}
1936 
1937 	if (btrfs_is_data_reloc_root(inode->root))
1938 		/*
1939 		 * Errors are handled later, as we must prevent
1940 		 * extent_clear_unlock_delalloc() in error handler from freeing
1941 		 * metadata of the created ordered extent.
1942 		 */
1943 		ret = btrfs_reloc_clone_csums(ordered);
1944 	btrfs_put_ordered_extent(ordered);
1945 
1946 	if (ret < 0)
1947 		goto error;
1948 	extent_clear_unlock_delalloc(inode, file_pos, end, locked_folio, cached,
1949 				     EXTENT_LOCKED | EXTENT_DELALLOC |
1950 				     EXTENT_CLEAR_DATA_RESV, 0);
1951 	return ret;
1952 
1953 error:
1954 	btrfs_cleanup_ordered_extents(inode, file_pos, len);
1955 	extent_clear_unlock_delalloc(inode, file_pos, end, locked_folio, cached,
1956 				     EXTENT_LOCKED | EXTENT_DELALLOC |
1957 				     EXTENT_CLEAR_DATA_RESV,
1958 				     PAGE_UNLOCK | PAGE_START_WRITEBACK |
1959 				     PAGE_END_WRITEBACK);
1960 	btrfs_err(inode->root->fs_info,
1961 		  "%s failed, root=%lld inode=%llu start=%llu len=%llu: %d",
1962 		  __func__, btrfs_root_id(inode->root), btrfs_ino(inode),
1963 		  file_pos, len, ret);
1964 	return ret;
1965 }
1966 
1967 /*
1968  * When nocow writeback calls back.  This checks for snapshots or COW copies
1969  * of the extents that exist in the file, and COWs the file as required.
1970  *
1971  * If no cow copies or snapshots exist, we write directly to the existing
1972  * blocks on disk
1973  */
1974 static noinline int run_delalloc_nocow(struct btrfs_inode *inode,
1975 				       struct folio *locked_folio,
1976 				       const u64 start, const u64 end)
1977 {
1978 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
1979 	struct btrfs_root *root = inode->root;
1980 	struct btrfs_path *path = NULL;
1981 	u64 cow_start = (u64)-1;
1982 	/*
1983 	 * If not 0, represents the inclusive end of the last fallback_to_cow()
1984 	 * range. Only for error handling.
1985 	 *
1986 	 * The same for nocow_end, it's to avoid double cleaning up the range
1987 	 * already cleaned by nocow_one_range().
1988 	 */
1989 	u64 cow_end = 0;
1990 	u64 nocow_end = 0;
1991 	u64 cur_offset = start;
1992 	int ret;
1993 	bool check_prev = true;
1994 	u64 ino = btrfs_ino(inode);
1995 	struct can_nocow_file_extent_args nocow_args = { 0 };
1996 	/* The range that has ordered extent(s). */
1997 	u64 oe_cleanup_start;
1998 	u64 oe_cleanup_len = 0;
1999 	/* The range that is untouched. */
2000 	u64 untouched_start;
2001 	u64 untouched_len = 0;
2002 
2003 	/*
2004 	 * Normally on a zoned device we're only doing COW writes, but in case
2005 	 * of relocation on a zoned filesystem serializes I/O so that we're only
2006 	 * writing sequentially and can end up here as well.
2007 	 */
2008 	ASSERT(!btrfs_is_zoned(fs_info) || btrfs_is_data_reloc_root(root));
2009 
2010 	if (btrfs_is_shutdown(fs_info)) {
2011 		ret = -EIO;
2012 		goto error;
2013 	}
2014 	path = btrfs_alloc_path();
2015 	if (!path) {
2016 		ret = -ENOMEM;
2017 		goto error;
2018 	}
2019 
2020 	nocow_args.end = end;
2021 	nocow_args.writeback_path = true;
2022 
2023 	while (cur_offset <= end) {
2024 		struct btrfs_block_group *nocow_bg = NULL;
2025 		struct btrfs_key found_key;
2026 		struct btrfs_file_extent_item *fi;
2027 		struct extent_buffer *leaf;
2028 		struct extent_state *cached_state = NULL;
2029 		u64 extent_end;
2030 		int extent_type;
2031 
2032 		ret = btrfs_lookup_file_extent(NULL, root, path, ino,
2033 					       cur_offset, 0);
2034 		if (ret < 0)
2035 			goto error;
2036 
2037 		/*
2038 		 * If there is no extent for our range when doing the initial
2039 		 * search, then go back to the previous slot as it will be the
2040 		 * one containing the search offset
2041 		 */
2042 		if (ret > 0 && path->slots[0] > 0 && check_prev) {
2043 			leaf = path->nodes[0];
2044 			btrfs_item_key_to_cpu(leaf, &found_key,
2045 					      path->slots[0] - 1);
2046 			if (found_key.objectid == ino &&
2047 			    found_key.type == BTRFS_EXTENT_DATA_KEY)
2048 				path->slots[0]--;
2049 		}
2050 		check_prev = false;
2051 next_slot:
2052 		/* Go to next leaf if we have exhausted the current one */
2053 		leaf = path->nodes[0];
2054 		if (path->slots[0] >= btrfs_header_nritems(leaf)) {
2055 			ret = btrfs_next_leaf(root, path);
2056 			if (ret < 0)
2057 				goto error;
2058 			if (ret > 0)
2059 				break;
2060 			leaf = path->nodes[0];
2061 		}
2062 
2063 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
2064 
2065 		/* Didn't find anything for our INO */
2066 		if (found_key.objectid > ino)
2067 			break;
2068 		/*
2069 		 * Keep searching until we find an EXTENT_ITEM or there are no
2070 		 * more extents for this inode
2071 		 */
2072 		if (WARN_ON_ONCE(found_key.objectid < ino) ||
2073 		    found_key.type < BTRFS_EXTENT_DATA_KEY) {
2074 			path->slots[0]++;
2075 			goto next_slot;
2076 		}
2077 
2078 		/* Found key is not EXTENT_DATA_KEY or starts after req range */
2079 		if (found_key.type > BTRFS_EXTENT_DATA_KEY ||
2080 		    found_key.offset > end)
2081 			break;
2082 
2083 		/*
2084 		 * If the found extent starts after requested offset, then
2085 		 * adjust cur_offset to be right before this extent begins.
2086 		 */
2087 		if (found_key.offset > cur_offset) {
2088 			if (cow_start == (u64)-1)
2089 				cow_start = cur_offset;
2090 			cur_offset = found_key.offset;
2091 			goto next_slot;
2092 		}
2093 
2094 		/*
2095 		 * Found extent which begins before our range and potentially
2096 		 * intersect it
2097 		 */
2098 		fi = btrfs_item_ptr(leaf, path->slots[0],
2099 				    struct btrfs_file_extent_item);
2100 		extent_type = btrfs_file_extent_type(leaf, fi);
2101 		/* If this is triggered then we have a memory corruption. */
2102 		ASSERT(extent_type < BTRFS_NR_FILE_EXTENT_TYPES);
2103 		if (WARN_ON(extent_type >= BTRFS_NR_FILE_EXTENT_TYPES)) {
2104 			ret = -EUCLEAN;
2105 			goto error;
2106 		}
2107 		extent_end = btrfs_file_extent_end(path);
2108 
2109 		/*
2110 		 * If the extent we got ends before our current offset, skip to
2111 		 * the next extent.
2112 		 */
2113 		if (extent_end <= cur_offset) {
2114 			path->slots[0]++;
2115 			goto next_slot;
2116 		}
2117 
2118 		nocow_args.start = cur_offset;
2119 		ret = can_nocow_file_extent(path, &found_key, inode, &nocow_args);
2120 		if (ret < 0)
2121 			goto error;
2122 		if (ret == 0)
2123 			goto must_cow;
2124 
2125 		ret = 0;
2126 		nocow_bg = btrfs_inc_nocow_writers(fs_info,
2127 				nocow_args.file_extent.disk_bytenr +
2128 				nocow_args.file_extent.offset);
2129 		if (!nocow_bg) {
2130 must_cow:
2131 			/*
2132 			 * If we can't perform NOCOW writeback for the range,
2133 			 * then record the beginning of the range that needs to
2134 			 * be COWed.  It will be written out before the next
2135 			 * NOCOW range if we find one, or when exiting this
2136 			 * loop.
2137 			 */
2138 			if (cow_start == (u64)-1)
2139 				cow_start = cur_offset;
2140 			cur_offset = extent_end;
2141 			if (cur_offset > end)
2142 				break;
2143 			if (!path->nodes[0])
2144 				continue;
2145 			path->slots[0]++;
2146 			goto next_slot;
2147 		}
2148 
2149 		/*
2150 		 * COW range from cow_start to found_key.offset - 1. As the key
2151 		 * will contain the beginning of the first extent that can be
2152 		 * NOCOW, following one which needs to be COW'ed
2153 		 */
2154 		if (cow_start != (u64)-1) {
2155 			ret = fallback_to_cow(inode, locked_folio, cow_start,
2156 					      found_key.offset - 1);
2157 			if (ret) {
2158 				cow_end = found_key.offset - 1;
2159 				btrfs_dec_nocow_writers(nocow_bg);
2160 				goto error;
2161 			}
2162 			cow_start = (u64)-1;
2163 		}
2164 
2165 		ret = nocow_one_range(inode, locked_folio, &cached_state,
2166 				      &nocow_args, cur_offset,
2167 				      extent_type == BTRFS_FILE_EXTENT_PREALLOC);
2168 		btrfs_dec_nocow_writers(nocow_bg);
2169 		if (ret < 0) {
2170 			nocow_end = cur_offset + nocow_args.file_extent.num_bytes - 1;
2171 			goto error;
2172 		}
2173 		cur_offset = extent_end;
2174 	}
2175 	btrfs_release_path(path);
2176 
2177 	if (cur_offset <= end && cow_start == (u64)-1)
2178 		cow_start = cur_offset;
2179 
2180 	if (cow_start != (u64)-1) {
2181 		ret = fallback_to_cow(inode, locked_folio, cow_start, end);
2182 		if (ret) {
2183 			cow_end = end;
2184 			goto error;
2185 		}
2186 		cow_start = (u64)-1;
2187 	}
2188 
2189 	/*
2190 	 * Everything is finished without an error, can unlock the folios now.
2191 	 *
2192 	 * No need to touch the io tree range nor set folio ordered flag, as
2193 	 * fallback_to_cow() and nocow_one_range() have already handled them.
2194 	 */
2195 	extent_clear_unlock_delalloc(inode, start, end, locked_folio, NULL, 0, PAGE_UNLOCK);
2196 
2197 	btrfs_free_path(path);
2198 	return 0;
2199 
2200 error:
2201 	if (cow_start == (u64)-1) {
2202 		/*
2203 		 * case a)
2204 		 *    start           cur_offset               end
2205 		 *    |   OE cleanup  |       Untouched        |
2206 		 *
2207 		 * We finished a fallback_to_cow() or nocow_one_range() call,
2208 		 * but failed to check the next range.
2209 		 *
2210 		 * or
2211 		 *    start           cur_offset   nocow_end   end
2212 		 *    |   OE cleanup  |   Skip     | Untouched |
2213 		 *
2214 		 * nocow_one_range() failed, the range [cur_offset, nocow_end] is
2215 		 * already cleaned up.
2216 		 */
2217 		oe_cleanup_start = start;
2218 		oe_cleanup_len = cur_offset - start;
2219 		if (nocow_end)
2220 			untouched_start = nocow_end + 1;
2221 		else
2222 			untouched_start = cur_offset;
2223 		untouched_len = end + 1 - untouched_start;
2224 	} else if (cow_start != (u64)-1 && cow_end == 0) {
2225 		/*
2226 		 * case b)
2227 		 *    start        cow_start    cur_offset   end
2228 		 *    | OE cleanup |        Untouched        |
2229 		 *
2230 		 * We got a range that needs COW, but before we hit the next NOCOW range,
2231 		 * thus [cow_start, cur_offset) doesn't yet have any OE.
2232 		 */
2233 		oe_cleanup_start = start;
2234 		oe_cleanup_len = cow_start - start;
2235 		untouched_start = cow_start;
2236 		untouched_len = end + 1 - untouched_start;
2237 	} else {
2238 		/*
2239 		 * case c)
2240 		 *    start        cow_start    cow_end      end
2241 		 *    | OE cleanup |   Skip     |  Untouched |
2242 		 *
2243 		 * fallback_to_cow() failed, and fallback_to_cow() will do the
2244 		 * cleanup for its range, we shouldn't touch the range
2245 		 * [cow_start, cow_end].
2246 		 */
2247 		ASSERT(cow_start != (u64)-1 && cow_end != 0);
2248 		oe_cleanup_start = start;
2249 		oe_cleanup_len = cow_start - start;
2250 		untouched_start = cow_end + 1;
2251 		untouched_len = end + 1 - untouched_start;
2252 	}
2253 
2254 	if (oe_cleanup_len) {
2255 		const u64 oe_cleanup_end = oe_cleanup_start + oe_cleanup_len - 1;
2256 		btrfs_cleanup_ordered_extents(inode, oe_cleanup_start, oe_cleanup_len);
2257 		extent_clear_unlock_delalloc(inode, oe_cleanup_start, oe_cleanup_end,
2258 					     locked_folio, NULL,
2259 					     EXTENT_LOCKED | EXTENT_DELALLOC,
2260 					     PAGE_UNLOCK | PAGE_START_WRITEBACK |
2261 					     PAGE_END_WRITEBACK);
2262 	}
2263 
2264 	if (untouched_len) {
2265 		struct extent_state *cached = NULL;
2266 		const u64 untouched_end = untouched_start + untouched_len - 1;
2267 
2268 		/*
2269 		 * We need to lock the extent here because we're clearing DELALLOC and
2270 		 * we're not locked at this point.
2271 		 */
2272 		btrfs_lock_extent(&inode->io_tree, untouched_start, untouched_end, &cached);
2273 		extent_clear_unlock_delalloc(inode, untouched_start, untouched_end,
2274 					     locked_folio, &cached,
2275 					     EXTENT_LOCKED | EXTENT_DELALLOC |
2276 					     EXTENT_DEFRAG |
2277 					     EXTENT_DO_ACCOUNTING, PAGE_UNLOCK |
2278 					     PAGE_START_WRITEBACK |
2279 					     PAGE_END_WRITEBACK);
2280 		btrfs_qgroup_free_data(inode, NULL, untouched_start, untouched_len, NULL);
2281 	}
2282 	btrfs_free_path(path);
2283 	btrfs_err(fs_info,
2284 "%s failed, root=%llu inode=%llu start=%llu len=%llu cur_offset=%llu oe_cleanup=%llu oe_cleanup_len=%llu untouched_start=%llu untouched_len=%llu: %d",
2285 		  __func__, btrfs_root_id(inode->root), btrfs_ino(inode),
2286 		  start, end + 1 - start, cur_offset, oe_cleanup_start, oe_cleanup_len,
2287 		  untouched_start, untouched_len, ret);
2288 	return ret;
2289 }
2290 
2291 static bool should_nocow(struct btrfs_inode *inode, u64 start, u64 end)
2292 {
2293 	if (inode->flags & (BTRFS_INODE_NODATACOW | BTRFS_INODE_PREALLOC)) {
2294 		if (data_race(inode->defrag_bytes) &&
2295 		    btrfs_test_range_bit_exists(&inode->io_tree, start, end, EXTENT_DEFRAG))
2296 			return false;
2297 		return true;
2298 	}
2299 	return false;
2300 }
2301 
2302 /*
2303  * Return 0 if an inlined extent is created successfully.
2304  * Return <0 if critical error happened.
2305  * Return >0 if an inline extent can not be created.
2306  */
2307 static int run_delalloc_inline(struct btrfs_inode *inode, struct folio *locked_folio)
2308 {
2309 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
2310 	struct compressed_bio *cb = NULL;
2311 	struct extent_state *cached = NULL;
2312 	const u64 i_size = i_size_read(&inode->vfs_inode);
2313 	const u32 blocksize = fs_info->sectorsize;
2314 	int compress_type = fs_info->compress_type;
2315 	int compress_level = fs_info->compress_level;
2316 	u32 compressed_size = 0;
2317 	int ret;
2318 
2319 	ASSERT(folio_pos(locked_folio) == 0);
2320 
2321 	if (btrfs_inode_can_compress(inode) &&
2322 	    inode_need_compress(inode, 0, blocksize, true)) {
2323 		if (inode->defrag_compress > 0 &&
2324 		    inode->defrag_compress < BTRFS_NR_COMPRESS_TYPES) {
2325 			compress_type = inode->defrag_compress;
2326 			compress_level = inode->defrag_compress_level;
2327 		} else if (inode->prop_compress) {
2328 			compress_type = inode->prop_compress;
2329 		}
2330 		cb = btrfs_compress_bio(inode, 0, blocksize, compress_type, compress_level, 0);
2331 		if (IS_ERR(cb)) {
2332 			cb = NULL;
2333 			/* Just fall back to non-compressed case. */
2334 		} else {
2335 			compressed_size = cb->bbio.bio.bi_iter.bi_size;
2336 		}
2337 	}
2338 	if (!can_cow_file_range_inline(inode, 0, i_size, compressed_size)) {
2339 		if (cb)
2340 			cleanup_compressed_bio(cb);
2341 		return 1;
2342 	}
2343 
2344 	btrfs_lock_extent(&inode->io_tree, 0, blocksize - 1, &cached);
2345 	if (cb) {
2346 		ret = __cow_file_range_inline(inode, i_size, compressed_size, compress_type,
2347 					      bio_first_folio_all(&cb->bbio.bio), false);
2348 		cleanup_compressed_bio(cb);
2349 		cb = NULL;
2350 	} else {
2351 		ret = __cow_file_range_inline(inode, i_size, 0, BTRFS_COMPRESS_NONE,
2352 					      NULL, false);
2353 	}
2354 	/*
2355 	 * We failed to insert inline extent due to lack of meta space.
2356 	 * Just unlock the extent io range and fallback to regular COW/NOCOW path.
2357 	 */
2358 	if (ret > 0) {
2359 		btrfs_unlock_extent(&inode->io_tree, 0, blocksize - 1, &cached);
2360 		return ret;
2361 	}
2362 
2363 	/*
2364 	 * In the successful case (ret == 0 here), btrfs_run_delalloc_range()
2365 	 * will return 1.
2366 	 *
2367 	 * Quite a bit further up the callstack in extent_writepage(), ret == 1
2368 	 * is treated as a short circuited success and does not unlock the folio,
2369 	 * so we must do it here.
2370 	 *
2371 	 * For failure case, the @locked_folio does get unlocked by
2372 	 * btrfs_folio_end_lock_bitmap(), so we must *not* unlock it here.
2373 	 *
2374 	 * So if ret == 0, we let extent_clear_unlock_delalloc() to unlock the
2375 	 * folio by passing NULL as @locked_folio.
2376 	 * Otherwise pass @locked_folio as usual.
2377 	 */
2378 	if (ret == 0)
2379 		locked_folio = NULL;
2380 	extent_clear_unlock_delalloc(inode, 0, blocksize - 1, locked_folio, &cached,
2381 				     EXTENT_DELALLOC | EXTENT_DELALLOC_NEW | EXTENT_DEFRAG |
2382 				     EXTENT_DO_ACCOUNTING | EXTENT_LOCKED,
2383 				     PAGE_UNLOCK | PAGE_START_WRITEBACK | PAGE_END_WRITEBACK);
2384 	return ret;
2385 }
2386 
2387 /*
2388  * Function to process delayed allocation (create CoW) for ranges which are
2389  * being touched for the first time.
2390  */
2391 int btrfs_run_delalloc_range(struct btrfs_inode *inode, struct folio *locked_folio,
2392 			     u64 start, u64 end, struct writeback_control *wbc)
2393 {
2394 	const bool zoned = btrfs_is_zoned(inode->root->fs_info);
2395 
2396 	/*
2397 	 * The range must cover part of the @locked_folio, or a return of 1
2398 	 * can confuse the caller.
2399 	 */
2400 	ASSERT(!(end <= folio_pos(locked_folio) ||
2401 		 start >= folio_next_pos(locked_folio)));
2402 
2403 	if (start == 0 && end + 1 <= inode->root->fs_info->sectorsize &&
2404 	    end + 1 >= inode->disk_i_size) {
2405 		int ret;
2406 
2407 		ret = run_delalloc_inline(inode, locked_folio);
2408 		if (ret < 0)
2409 			return ret;
2410 		if (ret == 0)
2411 			return 1;
2412 		/*
2413 		 * Continue regular handling if we can not create an
2414 		 * inlined extent.
2415 		 */
2416 	}
2417 
2418 	if (should_nocow(inode, start, end))
2419 		return run_delalloc_nocow(inode, locked_folio, start, end);
2420 
2421 	if (btrfs_inode_can_compress(inode) &&
2422 	    inode_need_compress(inode, start, end, false) &&
2423 	    run_delalloc_compressed(inode, locked_folio, start, end, wbc))
2424 		return 1;
2425 
2426 	if (zoned)
2427 		return run_delalloc_cow(inode, locked_folio, start, end, wbc, true);
2428 	else
2429 		return cow_file_range(inode, locked_folio, start, end, NULL, 0);
2430 }
2431 
2432 void btrfs_split_delalloc_extent(struct btrfs_inode *inode,
2433 				 struct extent_state *orig, u64 split)
2434 {
2435 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
2436 	u64 size;
2437 
2438 	lockdep_assert_held(&inode->io_tree.lock);
2439 
2440 	/* not delalloc, ignore it */
2441 	if (!(orig->state & EXTENT_DELALLOC))
2442 		return;
2443 
2444 	size = orig->end - orig->start + 1;
2445 	if (size > fs_info->max_extent_size) {
2446 		u32 num_extents;
2447 		u64 new_size;
2448 
2449 		/*
2450 		 * See the explanation in btrfs_merge_delalloc_extent, the same
2451 		 * applies here, just in reverse.
2452 		 */
2453 		new_size = orig->end - split + 1;
2454 		num_extents = count_max_extents(fs_info, new_size);
2455 		new_size = split - orig->start;
2456 		num_extents += count_max_extents(fs_info, new_size);
2457 		if (count_max_extents(fs_info, size) >= num_extents)
2458 			return;
2459 	}
2460 
2461 	spin_lock(&inode->lock);
2462 	btrfs_mod_outstanding_extents(inode, 1);
2463 	spin_unlock(&inode->lock);
2464 }
2465 
2466 /*
2467  * Handle merged delayed allocation extents so we can keep track of new extents
2468  * that are just merged onto old extents, such as when we are doing sequential
2469  * writes, so we can properly account for the metadata space we'll need.
2470  */
2471 void btrfs_merge_delalloc_extent(struct btrfs_inode *inode, struct extent_state *new,
2472 				 struct extent_state *other)
2473 {
2474 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
2475 	u64 new_size, old_size;
2476 	u32 num_extents;
2477 
2478 	lockdep_assert_held(&inode->io_tree.lock);
2479 
2480 	/* not delalloc, ignore it */
2481 	if (!(other->state & EXTENT_DELALLOC))
2482 		return;
2483 
2484 	if (new->start > other->start)
2485 		new_size = new->end - other->start + 1;
2486 	else
2487 		new_size = other->end - new->start + 1;
2488 
2489 	/* we're not bigger than the max, unreserve the space and go */
2490 	if (new_size <= fs_info->max_extent_size) {
2491 		spin_lock(&inode->lock);
2492 		btrfs_mod_outstanding_extents(inode, -1);
2493 		spin_unlock(&inode->lock);
2494 		return;
2495 	}
2496 
2497 	/*
2498 	 * We have to add up either side to figure out how many extents were
2499 	 * accounted for before we merged into one big extent.  If the number of
2500 	 * extents we accounted for is <= the amount we need for the new range
2501 	 * then we can return, otherwise drop.  Think of it like this
2502 	 *
2503 	 * [ 4k][MAX_SIZE]
2504 	 *
2505 	 * So we've grown the extent by a MAX_SIZE extent, this would mean we
2506 	 * need 2 outstanding extents, on one side we have 1 and the other side
2507 	 * we have 1 so they are == and we can return.  But in this case
2508 	 *
2509 	 * [MAX_SIZE+4k][MAX_SIZE+4k]
2510 	 *
2511 	 * Each range on their own accounts for 2 extents, but merged together
2512 	 * they are only 3 extents worth of accounting, so we need to drop in
2513 	 * this case.
2514 	 */
2515 	old_size = other->end - other->start + 1;
2516 	num_extents = count_max_extents(fs_info, old_size);
2517 	old_size = new->end - new->start + 1;
2518 	num_extents += count_max_extents(fs_info, old_size);
2519 	if (count_max_extents(fs_info, new_size) >= num_extents)
2520 		return;
2521 
2522 	spin_lock(&inode->lock);
2523 	btrfs_mod_outstanding_extents(inode, -1);
2524 	spin_unlock(&inode->lock);
2525 }
2526 
2527 static void btrfs_add_delalloc_inode(struct btrfs_inode *inode)
2528 {
2529 	struct btrfs_root *root = inode->root;
2530 	struct btrfs_fs_info *fs_info = root->fs_info;
2531 
2532 	spin_lock(&root->delalloc_lock);
2533 	ASSERT(list_empty(&inode->delalloc_inodes));
2534 	list_add_tail(&inode->delalloc_inodes, &root->delalloc_inodes);
2535 	root->nr_delalloc_inodes++;
2536 	if (root->nr_delalloc_inodes == 1) {
2537 		spin_lock(&fs_info->delalloc_root_lock);
2538 		ASSERT(list_empty(&root->delalloc_root));
2539 		list_add_tail(&root->delalloc_root, &fs_info->delalloc_roots);
2540 		spin_unlock(&fs_info->delalloc_root_lock);
2541 	}
2542 	spin_unlock(&root->delalloc_lock);
2543 }
2544 
2545 void btrfs_del_delalloc_inode(struct btrfs_inode *inode)
2546 {
2547 	struct btrfs_root *root = inode->root;
2548 	struct btrfs_fs_info *fs_info = root->fs_info;
2549 
2550 	lockdep_assert_held(&root->delalloc_lock);
2551 
2552 	/*
2553 	 * We may be called after the inode was already deleted from the list,
2554 	 * namely in the transaction abort path btrfs_destroy_delalloc_inodes(),
2555 	 * and then later through btrfs_clear_delalloc_extent() while the inode
2556 	 * still has ->delalloc_bytes > 0.
2557 	 */
2558 	if (!list_empty(&inode->delalloc_inodes)) {
2559 		list_del_init(&inode->delalloc_inodes);
2560 		root->nr_delalloc_inodes--;
2561 		if (!root->nr_delalloc_inodes) {
2562 			ASSERT(list_empty(&root->delalloc_inodes));
2563 			spin_lock(&fs_info->delalloc_root_lock);
2564 			ASSERT(!list_empty(&root->delalloc_root));
2565 			list_del_init(&root->delalloc_root);
2566 			spin_unlock(&fs_info->delalloc_root_lock);
2567 		}
2568 	}
2569 }
2570 
2571 /*
2572  * Properly track delayed allocation bytes in the inode and to maintain the
2573  * list of inodes that have pending delalloc work to be done.
2574  */
2575 void btrfs_set_delalloc_extent(struct btrfs_inode *inode, struct extent_state *state,
2576 			       u32 bits)
2577 {
2578 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
2579 
2580 	lockdep_assert_held(&inode->io_tree.lock);
2581 
2582 	WARN_ON((bits & EXTENT_DEFRAG) && !(bits & EXTENT_DELALLOC));
2583 	/*
2584 	 * set_bit and clear bit hooks normally require _irqsave/restore
2585 	 * but in this case, we are only testing for the DELALLOC
2586 	 * bit, which is only set or cleared with irqs on
2587 	 */
2588 	if (!(state->state & EXTENT_DELALLOC) && (bits & EXTENT_DELALLOC)) {
2589 		u64 len = state->end + 1 - state->start;
2590 		u64 prev_delalloc_bytes;
2591 		u32 num_extents = count_max_extents(fs_info, len);
2592 
2593 		spin_lock(&inode->lock);
2594 		btrfs_mod_outstanding_extents(inode, num_extents);
2595 		spin_unlock(&inode->lock);
2596 
2597 		/* For sanity tests */
2598 		if (btrfs_is_testing(fs_info))
2599 			return;
2600 
2601 		percpu_counter_add_batch(&fs_info->delalloc_bytes, len,
2602 					 fs_info->delalloc_batch);
2603 		spin_lock(&inode->lock);
2604 		prev_delalloc_bytes = inode->delalloc_bytes;
2605 		inode->delalloc_bytes += len;
2606 		if (bits & EXTENT_DEFRAG)
2607 			inode->defrag_bytes += len;
2608 		spin_unlock(&inode->lock);
2609 
2610 		/*
2611 		 * We don't need to be under the protection of the inode's lock,
2612 		 * because we are called while holding the inode's io_tree lock
2613 		 * and are therefore protected against concurrent calls of this
2614 		 * function and btrfs_clear_delalloc_extent().
2615 		 */
2616 		if (!btrfs_is_free_space_inode(inode) && prev_delalloc_bytes == 0)
2617 			btrfs_add_delalloc_inode(inode);
2618 	}
2619 
2620 	if (!(state->state & EXTENT_DELALLOC_NEW) &&
2621 	    (bits & EXTENT_DELALLOC_NEW)) {
2622 		spin_lock(&inode->lock);
2623 		inode->new_delalloc_bytes += state->end + 1 - state->start;
2624 		spin_unlock(&inode->lock);
2625 	}
2626 }
2627 
2628 /*
2629  * Once a range is no longer delalloc this function ensures that proper
2630  * accounting happens.
2631  */
2632 void btrfs_clear_delalloc_extent(struct btrfs_inode *inode,
2633 				 struct extent_state *state, u32 bits)
2634 {
2635 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
2636 	u64 len = state->end + 1 - state->start;
2637 	u32 num_extents = count_max_extents(fs_info, len);
2638 
2639 	lockdep_assert_held(&inode->io_tree.lock);
2640 
2641 	if ((state->state & EXTENT_DEFRAG) && (bits & EXTENT_DEFRAG)) {
2642 		spin_lock(&inode->lock);
2643 		inode->defrag_bytes -= len;
2644 		spin_unlock(&inode->lock);
2645 	}
2646 
2647 	/*
2648 	 * set_bit and clear bit hooks normally require _irqsave/restore
2649 	 * but in this case, we are only testing for the DELALLOC
2650 	 * bit, which is only set or cleared with irqs on
2651 	 */
2652 	if ((state->state & EXTENT_DELALLOC) && (bits & EXTENT_DELALLOC)) {
2653 		struct btrfs_root *root = inode->root;
2654 		u64 new_delalloc_bytes;
2655 
2656 		spin_lock(&inode->lock);
2657 		btrfs_mod_outstanding_extents(inode, -num_extents);
2658 		spin_unlock(&inode->lock);
2659 
2660 		/*
2661 		 * We don't reserve metadata space for space cache inodes so we
2662 		 * don't need to call delalloc_release_metadata if there is an
2663 		 * error.
2664 		 */
2665 		if (bits & EXTENT_CLEAR_META_RESV &&
2666 		    root != fs_info->tree_root)
2667 			btrfs_delalloc_release_metadata(inode, len, true);
2668 
2669 		/* For sanity tests. */
2670 		if (btrfs_is_testing(fs_info))
2671 			return;
2672 
2673 		if (!btrfs_is_data_reloc_root(root) &&
2674 		    !btrfs_is_free_space_inode(inode) &&
2675 		    !(state->state & EXTENT_NORESERVE) &&
2676 		    (bits & EXTENT_CLEAR_DATA_RESV))
2677 			btrfs_free_reserved_data_space_noquota(inode, len);
2678 
2679 		percpu_counter_add_batch(&fs_info->delalloc_bytes, -len,
2680 					 fs_info->delalloc_batch);
2681 		spin_lock(&inode->lock);
2682 		inode->delalloc_bytes -= len;
2683 		new_delalloc_bytes = inode->delalloc_bytes;
2684 		spin_unlock(&inode->lock);
2685 
2686 		/*
2687 		 * We don't need to be under the protection of the inode's lock,
2688 		 * because we are called while holding the inode's io_tree lock
2689 		 * and are therefore protected against concurrent calls of this
2690 		 * function and btrfs_set_delalloc_extent().
2691 		 */
2692 		if (!btrfs_is_free_space_inode(inode) && new_delalloc_bytes == 0) {
2693 			spin_lock(&root->delalloc_lock);
2694 			btrfs_del_delalloc_inode(inode);
2695 			spin_unlock(&root->delalloc_lock);
2696 		}
2697 	}
2698 
2699 	if ((state->state & EXTENT_DELALLOC_NEW) &&
2700 	    (bits & EXTENT_DELALLOC_NEW)) {
2701 		spin_lock(&inode->lock);
2702 		ASSERT(inode->new_delalloc_bytes >= len);
2703 		inode->new_delalloc_bytes -= len;
2704 		if (bits & EXTENT_ADD_INODE_BYTES)
2705 			inode_add_bytes(&inode->vfs_inode, len);
2706 		spin_unlock(&inode->lock);
2707 	}
2708 }
2709 
2710 /*
2711  * Given an ordered extent and insert all its checksums into the csum tree.
2712  *
2713  * This happens at IO completion time based on sums calculated at bio
2714  * submission time.
2715  */
2716 static int add_pending_csums(struct btrfs_trans_handle *trans,
2717 			     struct btrfs_ordered_extent *oe)
2718 {
2719 	struct btrfs_ordered_sum *sum;
2720 	struct btrfs_root *csum_root = NULL;
2721 	int ret;
2722 
2723 	list_for_each_entry(sum, &oe->csum_list, list) {
2724 		if (!csum_root) {
2725 			csum_root = btrfs_csum_root(trans->fs_info,
2726 						    sum->logical);
2727 			if (unlikely(!csum_root)) {
2728 				btrfs_err(trans->fs_info,
2729 				  "missing csum root for extent at bytenr %llu",
2730 					  sum->logical);
2731 				return -EUCLEAN;
2732 			}
2733 		}
2734 		trans->adding_csums = true;
2735 		ret = btrfs_insert_data_csums(trans, csum_root, sum);
2736 		trans->adding_csums = false;
2737 		if (ret)
2738 			return ret;
2739 	}
2740 	return 0;
2741 }
2742 
2743 static int btrfs_find_new_delalloc_bytes(struct btrfs_inode *inode,
2744 					 const u64 start,
2745 					 const u64 len,
2746 					 struct extent_state **cached_state)
2747 {
2748 	u64 search_start = start;
2749 	const u64 end = start + len - 1;
2750 
2751 	while (search_start < end) {
2752 		const u64 search_len = end - search_start + 1;
2753 		struct extent_map *em;
2754 		u64 em_len;
2755 		int ret = 0;
2756 
2757 		em = btrfs_get_extent(inode, NULL, search_start, search_len);
2758 		if (IS_ERR(em))
2759 			return PTR_ERR(em);
2760 
2761 		if (em->disk_bytenr != EXTENT_MAP_HOLE)
2762 			goto next;
2763 
2764 		em_len = em->len;
2765 		if (em->start < search_start)
2766 			em_len -= search_start - em->start;
2767 		if (em_len > search_len)
2768 			em_len = search_len;
2769 
2770 		ret = btrfs_set_extent_bit(&inode->io_tree, search_start,
2771 					   search_start + em_len - 1,
2772 					   EXTENT_DELALLOC_NEW, cached_state);
2773 next:
2774 		search_start = btrfs_extent_map_end(em);
2775 		btrfs_free_extent_map(em);
2776 		if (ret)
2777 			return ret;
2778 	}
2779 	return 0;
2780 }
2781 
2782 int btrfs_set_extent_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
2783 			      unsigned int extra_bits,
2784 			      struct extent_state **cached_state)
2785 {
2786 	const u32 blocksize = inode->root->fs_info->sectorsize;
2787 
2788 	/* Basic alignment check. */
2789 	ASSERT(IS_ALIGNED(start, blocksize), "start=%llu blocksize=%u",
2790 	       start, blocksize);
2791 	ASSERT(IS_ALIGNED(end + 1, blocksize), "inclusive end=%llu blocksize=%u",
2792 	       end, blocksize);
2793 
2794 	if (start >= i_size_read(&inode->vfs_inode) &&
2795 	    !(inode->flags & BTRFS_INODE_PREALLOC)) {
2796 		/*
2797 		 * There can't be any extents following eof in this case so just
2798 		 * set the delalloc new bit for the range directly.
2799 		 */
2800 		extra_bits |= EXTENT_DELALLOC_NEW;
2801 	} else {
2802 		int ret;
2803 
2804 		ret = btrfs_find_new_delalloc_bytes(inode, start,
2805 						    end + 1 - start,
2806 						    cached_state);
2807 		if (ret)
2808 			return ret;
2809 	}
2810 
2811 	return btrfs_set_extent_bit(&inode->io_tree, start, end,
2812 				    EXTENT_DELALLOC | extra_bits, cached_state);
2813 }
2814 
2815 /*
2816  * Clear the old accounting flags and set EXTENT_DELALLOC for the range.
2817  *
2818  * Return <0 for error, in that case no range has EXTENT_DELALLOC bit cleared or set.
2819  */
2820 int btrfs_reset_extent_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
2821 				unsigned int extra_bits, struct extent_state **cached_state)
2822 {
2823 	const u32 blocksize = inode->root->fs_info->sectorsize;
2824 
2825 	/* The @extra_bits can only be EXTENT_NORESERVE for now. */
2826 	ASSERT(!(extra_bits & ~EXTENT_NORESERVE), "extra_bits=0x%x", extra_bits);
2827 
2828 	/* Basic alignment check. */
2829 	ASSERT(IS_ALIGNED(start, blocksize), "start=%llu blocksize=%u",
2830 	       start, blocksize);
2831 	ASSERT(IS_ALIGNED(end + 1, blocksize), "inclusive end=%llu blocksize=%u",
2832 	       end, blocksize);
2833 
2834 	/*
2835 	 * Check and set DELALLOC_NEW flag, this needs to search tree thus can
2836 	 * fail early.  Thus we want to do this before clearing EXTENT_DELALLOC.
2837 	 */
2838 	if (start >= i_size_read(&inode->vfs_inode) &&
2839 	    !(inode->flags & BTRFS_INODE_PREALLOC)) {
2840 		/*
2841 		 * There can't be any extents following EOF in this case so just
2842 		 * set the delalloc new bit for the range directly.
2843 		 */
2844 		extra_bits |= EXTENT_DELALLOC_NEW;
2845 	} else {
2846 		int ret;
2847 
2848 		ret = btrfs_find_new_delalloc_bytes(inode, start, end + 1 - start,
2849 						    NULL);
2850 		if (unlikely(ret))
2851 			return ret;
2852 	}
2853 	/* Clear the old accounting as the range may already be dirty. */
2854 	btrfs_clear_extent_bit(&inode->io_tree, start, end,
2855 			       EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
2856 			       EXTENT_DEFRAG, cached_state);
2857 	return btrfs_set_extent_bit(&inode->io_tree, start, end,
2858 				    EXTENT_DELALLOC | extra_bits, cached_state);
2859 }
2860 
2861 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
2862 				       struct btrfs_inode *inode, u64 file_pos,
2863 				       struct btrfs_file_extent_item *stack_fi,
2864 				       const bool update_inode_bytes,
2865 				       u64 qgroup_reserved)
2866 {
2867 	struct btrfs_root *root = inode->root;
2868 	const u64 sectorsize = root->fs_info->sectorsize;
2869 	BTRFS_PATH_AUTO_FREE(path);
2870 	struct extent_buffer *leaf;
2871 	struct btrfs_key ins;
2872 	u64 disk_num_bytes = btrfs_stack_file_extent_disk_num_bytes(stack_fi);
2873 	u64 disk_bytenr = btrfs_stack_file_extent_disk_bytenr(stack_fi);
2874 	u64 offset = btrfs_stack_file_extent_offset(stack_fi);
2875 	u64 num_bytes = btrfs_stack_file_extent_num_bytes(stack_fi);
2876 	u64 ram_bytes = btrfs_stack_file_extent_ram_bytes(stack_fi);
2877 	struct btrfs_drop_extents_args drop_args = { 0 };
2878 	int ret;
2879 
2880 	path = btrfs_alloc_path();
2881 	if (!path)
2882 		return -ENOMEM;
2883 
2884 	/*
2885 	 * we may be replacing one extent in the tree with another.
2886 	 * The new extent is pinned in the extent map, and we don't want
2887 	 * to drop it from the cache until it is completely in the btree.
2888 	 *
2889 	 * So, tell btrfs_drop_extents to leave this extent in the cache.
2890 	 * the caller is expected to unpin it and allow it to be merged
2891 	 * with the others.
2892 	 */
2893 	drop_args.path = path;
2894 	drop_args.start = file_pos;
2895 	drop_args.end = file_pos + num_bytes;
2896 	drop_args.replace_extent = true;
2897 	drop_args.extent_item_size = sizeof(*stack_fi);
2898 	ret = btrfs_drop_extents(trans, root, inode, &drop_args);
2899 	if (ret)
2900 		return ret;
2901 
2902 	if (!drop_args.extent_inserted) {
2903 		ins.objectid = btrfs_ino(inode);
2904 		ins.type = BTRFS_EXTENT_DATA_KEY;
2905 		ins.offset = file_pos;
2906 
2907 		ret = btrfs_insert_empty_item(trans, root, path, &ins,
2908 					      sizeof(*stack_fi));
2909 		if (ret)
2910 			return ret;
2911 	}
2912 	leaf = path->nodes[0];
2913 	btrfs_set_stack_file_extent_generation(stack_fi, trans->transid);
2914 	write_extent_buffer(leaf, stack_fi,
2915 			btrfs_item_ptr_offset(leaf, path->slots[0]),
2916 			sizeof(struct btrfs_file_extent_item));
2917 
2918 	btrfs_release_path(path);
2919 
2920 	/*
2921 	 * If we dropped an inline extent here, we know the range where it is
2922 	 * was not marked with the EXTENT_DELALLOC_NEW bit, so we update the
2923 	 * number of bytes only for that range containing the inline extent.
2924 	 * The remaining of the range will be processed when clearing the
2925 	 * EXTENT_DELALLOC_BIT bit through the ordered extent completion.
2926 	 */
2927 	if (file_pos == 0 && !IS_ALIGNED(drop_args.bytes_found, sectorsize)) {
2928 		u64 inline_size = round_down(drop_args.bytes_found, sectorsize);
2929 
2930 		inline_size = drop_args.bytes_found - inline_size;
2931 		btrfs_update_inode_bytes(inode, sectorsize, inline_size);
2932 		drop_args.bytes_found -= inline_size;
2933 		num_bytes -= sectorsize;
2934 	}
2935 
2936 	if (update_inode_bytes)
2937 		btrfs_update_inode_bytes(inode, num_bytes, drop_args.bytes_found);
2938 
2939 	ins.objectid = disk_bytenr;
2940 	ins.type = BTRFS_EXTENT_ITEM_KEY;
2941 	ins.offset = disk_num_bytes;
2942 
2943 	ret = btrfs_inode_set_file_extent_range(inode, file_pos, ram_bytes);
2944 	if (ret)
2945 		return ret;
2946 
2947 	return btrfs_alloc_reserved_file_extent(trans, root, btrfs_ino(inode),
2948 						file_pos - offset,
2949 						qgroup_reserved, &ins);
2950 }
2951 
2952 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
2953 					 u64 start, u64 len)
2954 {
2955 	struct btrfs_block_group *cache;
2956 
2957 	cache = btrfs_lookup_block_group(fs_info, start);
2958 	ASSERT(cache);
2959 
2960 	spin_lock(&cache->lock);
2961 	cache->delalloc_bytes -= len;
2962 	spin_unlock(&cache->lock);
2963 
2964 	btrfs_put_block_group(cache);
2965 }
2966 
2967 static int insert_ordered_extent_file_extent(struct btrfs_trans_handle *trans,
2968 					     struct btrfs_ordered_extent *oe)
2969 {
2970 	struct btrfs_file_extent_item stack_fi;
2971 	bool update_inode_bytes;
2972 	u64 num_bytes = oe->num_bytes;
2973 	u64 ram_bytes = oe->ram_bytes;
2974 
2975 	memset(&stack_fi, 0, sizeof(stack_fi));
2976 	btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_REG);
2977 	btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, oe->disk_bytenr);
2978 	btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi,
2979 						   oe->disk_num_bytes);
2980 	btrfs_set_stack_file_extent_offset(&stack_fi, oe->offset);
2981 	if (test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags))
2982 		num_bytes = oe->truncated_len;
2983 	btrfs_set_stack_file_extent_num_bytes(&stack_fi, num_bytes);
2984 	btrfs_set_stack_file_extent_ram_bytes(&stack_fi, ram_bytes);
2985 	btrfs_set_stack_file_extent_compression(&stack_fi, oe->compress_type);
2986 	/* Encryption and other encoding is reserved and all 0 */
2987 
2988 	/*
2989 	 * For delalloc, when completing an ordered extent we update the inode's
2990 	 * bytes when clearing the range in the inode's io tree, so pass false
2991 	 * as the argument 'update_inode_bytes' to insert_reserved_file_extent(),
2992 	 * except if the ordered extent was truncated.
2993 	 */
2994 	update_inode_bytes = test_bit(BTRFS_ORDERED_DIRECT, &oe->flags) ||
2995 			     test_bit(BTRFS_ORDERED_ENCODED, &oe->flags) ||
2996 			     test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags);
2997 
2998 	return insert_reserved_file_extent(trans, oe->inode,
2999 					   oe->file_offset, &stack_fi,
3000 					   update_inode_bytes, oe->qgroup_rsv);
3001 }
3002 
3003 /*
3004  * As ordered data IO finishes, this gets called so we can finish
3005  * an ordered extent if the range of bytes in the file it covers are
3006  * fully written.
3007  */
3008 int btrfs_finish_one_ordered(struct btrfs_ordered_extent *ordered_extent)
3009 {
3010 	struct btrfs_inode *inode = ordered_extent->inode;
3011 	struct btrfs_root *root = inode->root;
3012 	struct btrfs_fs_info *fs_info = root->fs_info;
3013 	struct btrfs_trans_handle *trans = NULL;
3014 	struct extent_io_tree *io_tree = &inode->io_tree;
3015 	struct extent_state *cached_state = NULL;
3016 	u64 start, end;
3017 	int compress_type = 0;
3018 	int ret = 0;
3019 	u64 logical_len = ordered_extent->num_bytes;
3020 	bool freespace_inode;
3021 	bool truncated = false;
3022 	bool clear_reserved_extent = true;
3023 	unsigned int clear_bits = 0;
3024 
3025 	start = ordered_extent->file_offset;
3026 	end = start + ordered_extent->num_bytes - 1;
3027 
3028 	if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3029 	    !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
3030 	    !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags) &&
3031 	    !test_bit(BTRFS_ORDERED_ENCODED, &ordered_extent->flags))
3032 		clear_bits |= EXTENT_DELALLOC_NEW;
3033 
3034 	if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags))
3035 		clear_bits |= EXTENT_DEFRAG;
3036 
3037 	freespace_inode = btrfs_is_free_space_inode(inode);
3038 	if (!freespace_inode)
3039 		btrfs_lockdep_acquire(fs_info, btrfs_ordered_extent);
3040 
3041 	if (unlikely(test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags))) {
3042 		ret = -EIO;
3043 		goto out;
3044 	}
3045 
3046 	ret = btrfs_zone_finish_endio(fs_info, ordered_extent->disk_bytenr,
3047 				      ordered_extent->disk_num_bytes);
3048 	if (ret)
3049 		goto out;
3050 
3051 	if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
3052 		truncated = true;
3053 		logical_len = ordered_extent->truncated_len;
3054 		/* Truncated the entire extent, don't bother adding */
3055 		if (!logical_len)
3056 			goto out;
3057 	}
3058 
3059 	/*
3060 	 * If it's a COW write we need to lock the extent range as we will be
3061 	 * inserting/replacing file extent items and unpinning an extent map.
3062 	 * This must be taken before joining a transaction, as it's a higher
3063 	 * level lock (like the inode's VFS lock), otherwise we can run into an
3064 	 * ABBA deadlock with other tasks (transactions work like a lock,
3065 	 * depending on their current state).
3066 	 */
3067 	if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
3068 		clear_bits |= EXTENT_LOCKED | EXTENT_FINISHING_ORDERED;
3069 		btrfs_lock_extent_bits(io_tree, start, end,
3070 				       EXTENT_LOCKED | EXTENT_FINISHING_ORDERED,
3071 				       &cached_state);
3072 	}
3073 
3074 	if (freespace_inode)
3075 		trans = btrfs_join_transaction_spacecache(root);
3076 	else
3077 		trans = btrfs_join_transaction(root);
3078 	if (IS_ERR(trans)) {
3079 		ret = PTR_ERR(trans);
3080 		trans = NULL;
3081 		goto out;
3082 	}
3083 
3084 	trans->block_rsv = &inode->block_rsv;
3085 
3086 	ret = btrfs_insert_raid_extent(trans, ordered_extent);
3087 	if (unlikely(ret)) {
3088 		btrfs_abort_transaction(trans, ret);
3089 		goto out;
3090 	}
3091 
3092 	if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
3093 		/* Logic error */
3094 		ASSERT(list_empty(&ordered_extent->csum_list));
3095 		if (unlikely(!list_empty(&ordered_extent->csum_list))) {
3096 			ret = -EINVAL;
3097 			btrfs_abort_transaction(trans, ret);
3098 			goto out;
3099 		}
3100 
3101 		btrfs_inode_safe_disk_i_size_write(inode, 0);
3102 		ret = btrfs_update_inode_fallback(trans, inode);
3103 		if (unlikely(ret)) {
3104 			/* -ENOMEM or corruption */
3105 			btrfs_abort_transaction(trans, ret);
3106 		}
3107 		goto out;
3108 	}
3109 
3110 	if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3111 		compress_type = ordered_extent->compress_type;
3112 	if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3113 		BUG_ON(compress_type);
3114 		ret = btrfs_mark_extent_written(trans, inode,
3115 						ordered_extent->file_offset,
3116 						ordered_extent->file_offset +
3117 						logical_len);
3118 		btrfs_zoned_release_data_reloc_bg(fs_info, ordered_extent->disk_bytenr,
3119 						  ordered_extent->disk_num_bytes);
3120 		if (unlikely(ret < 0)) {
3121 			btrfs_abort_transaction(trans, ret);
3122 			goto out;
3123 		}
3124 	} else {
3125 		BUG_ON(root == fs_info->tree_root);
3126 		ret = insert_ordered_extent_file_extent(trans, ordered_extent);
3127 		if (unlikely(ret < 0)) {
3128 			btrfs_abort_transaction(trans, ret);
3129 			goto out;
3130 		}
3131 		clear_reserved_extent = false;
3132 		btrfs_release_delalloc_bytes(fs_info,
3133 					     ordered_extent->disk_bytenr,
3134 					     ordered_extent->disk_num_bytes);
3135 	}
3136 
3137 	ret = btrfs_unpin_extent_cache(inode, ordered_extent->file_offset,
3138 				       ordered_extent->num_bytes, trans->transid);
3139 	if (unlikely(ret < 0)) {
3140 		btrfs_abort_transaction(trans, ret);
3141 		goto out;
3142 	}
3143 
3144 	ret = add_pending_csums(trans, ordered_extent);
3145 	if (unlikely(ret)) {
3146 		btrfs_abort_transaction(trans, ret);
3147 		goto out;
3148 	}
3149 
3150 	/*
3151 	 * If this is a new delalloc range, clear its new delalloc flag to
3152 	 * update the inode's number of bytes. This needs to be done first
3153 	 * before updating the inode item.
3154 	 */
3155 	if ((clear_bits & EXTENT_DELALLOC_NEW) &&
3156 	    !test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags))
3157 		btrfs_clear_extent_bit(&inode->io_tree, start, end,
3158 				       EXTENT_DELALLOC_NEW | EXTENT_ADD_INODE_BYTES,
3159 				       &cached_state);
3160 
3161 	btrfs_inode_safe_disk_i_size_write(inode, 0);
3162 	ret = btrfs_update_inode_fallback(trans, inode);
3163 	if (unlikely(ret)) { /* -ENOMEM or corruption */
3164 		btrfs_abort_transaction(trans, ret);
3165 		goto out;
3166 	}
3167 out:
3168 	if (clear_bits)
3169 		btrfs_clear_extent_bit(&inode->io_tree, start, end, clear_bits,
3170 				       &cached_state);
3171 
3172 	if (trans)
3173 		btrfs_end_transaction(trans);
3174 
3175 	if (ret || truncated) {
3176 		/*
3177 		 * If we failed to finish this ordered extent for any reason we
3178 		 * need to make sure BTRFS_ORDERED_IOERR is set on the ordered
3179 		 * extent, and mark the inode with the error if it wasn't
3180 		 * already set.  Any error during writeback would have already
3181 		 * set the mapping error, so we need to set it if we're the ones
3182 		 * marking this ordered extent as failed.
3183 		 */
3184 		if (ret)
3185 			btrfs_mark_ordered_extent_error(ordered_extent);
3186 
3187 		/*
3188 		 * Drop extent maps for the part of the extent we didn't write.
3189 		 *
3190 		 * We have an exception here for the free_space_inode, this is
3191 		 * because when we do btrfs_get_extent() on the free space inode
3192 		 * we will search the commit root.  If this is a new block group
3193 		 * we won't find anything, and we will trip over the assert in
3194 		 * writepage where we do ASSERT(em->block_start !=
3195 		 * EXTENT_MAP_HOLE).
3196 		 *
3197 		 * Theoretically we could also skip this for any NOCOW extent as
3198 		 * we don't mess with the extent map tree in the NOCOW case, but
3199 		 * for now simply skip this if we are the free space inode.
3200 		 */
3201 		if (!btrfs_is_free_space_inode(inode)) {
3202 			u64 unwritten_start = start;
3203 
3204 			if (truncated)
3205 				unwritten_start += logical_len;
3206 
3207 			btrfs_drop_extent_map_range(inode, unwritten_start,
3208 						    end, false);
3209 		}
3210 
3211 		/*
3212 		 * If the ordered extent had an IOERR or something else went
3213 		 * wrong we need to return the space for this ordered extent
3214 		 * back to the allocator.  We only free the extent in the
3215 		 * truncated case if we didn't write out the extent at all.
3216 		 *
3217 		 * If we made it past insert_reserved_file_extent before we
3218 		 * errored out then we don't need to do this as the accounting
3219 		 * has already been done.
3220 		 */
3221 		if ((ret || !logical_len) &&
3222 		    clear_reserved_extent &&
3223 		    !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3224 		    !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3225 			/*
3226 			 * Discard the range before returning it back to the
3227 			 * free space pool
3228 			 */
3229 			if (ret && btrfs_test_opt(fs_info, DISCARD_SYNC))
3230 				btrfs_discard_extent(fs_info,
3231 						ordered_extent->disk_bytenr,
3232 						ordered_extent->disk_num_bytes,
3233 						NULL, true);
3234 			btrfs_free_reserved_extent(fs_info,
3235 					ordered_extent->disk_bytenr,
3236 					ordered_extent->disk_num_bytes, true);
3237 			/*
3238 			 * Actually free the qgroup rsv which was released when
3239 			 * the ordered extent was created.
3240 			 */
3241 			btrfs_qgroup_free_refroot(fs_info, btrfs_root_id(inode->root),
3242 						  ordered_extent->qgroup_rsv,
3243 						  BTRFS_QGROUP_RSV_DATA);
3244 		}
3245 	}
3246 
3247 	/*
3248 	 * This needs to be done to make sure anybody waiting knows we are done
3249 	 * updating everything for this ordered extent.
3250 	 */
3251 	btrfs_remove_ordered_extent(ordered_extent);
3252 
3253 	/* once for us */
3254 	btrfs_put_ordered_extent(ordered_extent);
3255 	/* once for the tree */
3256 	btrfs_put_ordered_extent(ordered_extent);
3257 
3258 	return ret;
3259 }
3260 
3261 int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered)
3262 {
3263 	if (btrfs_is_zoned(ordered->inode->root->fs_info) &&
3264 	    !test_bit(BTRFS_ORDERED_IOERR, &ordered->flags) &&
3265 	    list_empty(&ordered->bioc_list))
3266 		btrfs_finish_ordered_zoned(ordered);
3267 	return btrfs_finish_one_ordered(ordered);
3268 }
3269 
3270 /*
3271  * Calculate the checksum of an fs block at physical memory address @paddr,
3272  * and save the result to @dest.
3273  *
3274  * The folio containing @paddr must be large enough to contain a full fs block.
3275  */
3276 void btrfs_calculate_block_csum_folio(struct btrfs_fs_info *fs_info,
3277 				      const phys_addr_t paddr, u8 *dest)
3278 {
3279 	struct folio *folio = page_folio(phys_to_page(paddr));
3280 	const u32 blocksize = fs_info->sectorsize;
3281 	const u32 step = min(blocksize, PAGE_SIZE);
3282 	const u32 nr_steps = blocksize / step;
3283 	phys_addr_t paddrs[BTRFS_MAX_BLOCKSIZE / PAGE_SIZE];
3284 
3285 	/* The full block must be inside the folio. */
3286 	ASSERT(offset_in_folio(folio, paddr) + blocksize <= folio_size(folio));
3287 
3288 	for (int i = 0; i < nr_steps; i++) {
3289 		u32 pindex = offset_in_folio(folio, paddr + i * step) >> PAGE_SHIFT;
3290 
3291 		/*
3292 		 * For bs <= ps cases, we will only run the loop once, so the offset
3293 		 * inside the page will only added to paddrs[0].
3294 		 *
3295 		 * For bs > ps cases, the block must be page aligned, thus offset
3296 		 * inside the page will always be 0.
3297 		 */
3298 		paddrs[i] = page_to_phys(folio_page(folio, pindex)) + offset_in_page(paddr);
3299 	}
3300 	return btrfs_calculate_block_csum_pages(fs_info, paddrs, dest);
3301 }
3302 
3303 /*
3304  * Calculate the checksum of a fs block backed by multiple noncontiguous pages
3305  * at @paddrs[] and save the result to @dest.
3306  *
3307  * The folio containing @paddr must be large enough to contain a full fs block.
3308  */
3309 void btrfs_calculate_block_csum_pages(struct btrfs_fs_info *fs_info,
3310 				      const phys_addr_t paddrs[], u8 *dest)
3311 {
3312 	const u32 blocksize = fs_info->sectorsize;
3313 	const u32 step = min(blocksize, PAGE_SIZE);
3314 	const u32 nr_steps = blocksize / step;
3315 	struct btrfs_csum_ctx csum;
3316 
3317 	btrfs_csum_init(&csum, fs_info->csum_type);
3318 	for (int i = 0; i < nr_steps; i++) {
3319 		const phys_addr_t paddr = paddrs[i];
3320 		void *kaddr;
3321 
3322 		ASSERT(offset_in_page(paddr) + step <= PAGE_SIZE);
3323 		kaddr = kmap_local_page(phys_to_page(paddr)) + offset_in_page(paddr);
3324 		btrfs_csum_update(&csum, kaddr, step);
3325 		kunmap_local(kaddr);
3326 	}
3327 	btrfs_csum_final(&csum, dest);
3328 }
3329 
3330 /*
3331  * Verify the checksum for a single sector without any extra action that depend
3332  * on the type of I/O.
3333  *
3334  * @kaddr must be a properly kmapped address.
3335  */
3336 int btrfs_check_block_csum(struct btrfs_fs_info *fs_info, phys_addr_t paddr, u8 *csum,
3337 			   const u8 * const csum_expected)
3338 {
3339 	btrfs_calculate_block_csum_folio(fs_info, paddr, csum);
3340 	if (unlikely(memcmp(csum, csum_expected, fs_info->csum_size) != 0))
3341 		return -EIO;
3342 	return 0;
3343 }
3344 
3345 /*
3346  * Verify the checksum of a single data sector, which can be scattered at
3347  * different noncontiguous pages.
3348  *
3349  * @bbio:	btrfs_io_bio which contains the csum
3350  * @dev:	device the sector is on
3351  * @bio_offset:	offset to the beginning of the bio (in bytes)
3352  * @paddrs:	physical addresses which back the fs block
3353  *
3354  * Check if the checksum on a data block is valid.  When a checksum mismatch is
3355  * detected, report the error and fill the corrupted range with zero.
3356  *
3357  * Return %true if the sector is ok or had no checksum to start with, else %false.
3358  */
3359 bool btrfs_data_csum_ok(struct btrfs_bio *bbio, struct btrfs_device *dev,
3360 			u32 bio_offset, const phys_addr_t paddrs[])
3361 {
3362 	struct btrfs_inode *inode = bbio->inode;
3363 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
3364 	const u32 blocksize = fs_info->sectorsize;
3365 	const u32 step = min(blocksize, PAGE_SIZE);
3366 	const u32 nr_steps = blocksize / step;
3367 	u64 file_offset = bbio->file_offset + bio_offset;
3368 	u64 end = file_offset + blocksize - 1;
3369 	u8 *csum_expected;
3370 	u8 csum[BTRFS_CSUM_SIZE];
3371 
3372 	if (!bbio->csum)
3373 		return true;
3374 
3375 	if (btrfs_is_data_reloc_root(inode->root) &&
3376 	    btrfs_test_range_bit(&inode->io_tree, file_offset, end, EXTENT_NODATASUM,
3377 				 NULL)) {
3378 		/* Skip the range without csum for data reloc inode */
3379 		btrfs_clear_extent_bit(&inode->io_tree, file_offset, end,
3380 				       EXTENT_NODATASUM, NULL);
3381 		return true;
3382 	}
3383 
3384 	csum_expected = bbio->csum + (bio_offset >> fs_info->sectorsize_bits) *
3385 				fs_info->csum_size;
3386 	btrfs_calculate_block_csum_pages(fs_info, paddrs, csum);
3387 	if (unlikely(memcmp(csum, csum_expected, fs_info->csum_size) != 0))
3388 		goto zeroit;
3389 	return true;
3390 
3391 zeroit:
3392 	btrfs_print_data_csum_error(inode, file_offset, csum, csum_expected,
3393 				    bbio->mirror_num);
3394 	if (dev)
3395 		btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS);
3396 	for (int i = 0; i < nr_steps; i++)
3397 		memzero_page(phys_to_page(paddrs[i]), offset_in_page(paddrs[i]), step);
3398 	return false;
3399 }
3400 
3401 /*
3402  * Perform a delayed iput on @inode.
3403  *
3404  * @inode: The inode we want to perform iput on
3405  *
3406  * This function uses the generic vfs_inode::i_count to track whether we should
3407  * just decrement it (in case it's > 1) or if this is the last iput then link
3408  * the inode to the delayed iput machinery. Delayed iputs are processed at
3409  * transaction commit time/superblock commit/cleaner kthread.
3410  */
3411 void btrfs_add_delayed_iput(struct btrfs_inode *inode)
3412 {
3413 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
3414 	unsigned long flags;
3415 
3416 	if (atomic_add_unless(&inode->vfs_inode.i_count, -1, 1))
3417 		return;
3418 
3419 	WARN_ON_ONCE(test_bit(BTRFS_FS_STATE_NO_DELAYED_IPUT, &fs_info->fs_state));
3420 	atomic_inc(&fs_info->nr_delayed_iputs);
3421 	/*
3422 	 * Need to be irq safe here because we can be called from either an irq
3423 	 * context (see bio.c and btrfs_put_ordered_extent()) or a non-irq
3424 	 * context.
3425 	 */
3426 	spin_lock_irqsave(&fs_info->delayed_iput_lock, flags);
3427 	ASSERT(list_empty(&inode->delayed_iput));
3428 	list_add_tail(&inode->delayed_iput, &fs_info->delayed_iputs);
3429 	spin_unlock_irqrestore(&fs_info->delayed_iput_lock, flags);
3430 	if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
3431 		wake_up_process(fs_info->cleaner_kthread);
3432 }
3433 
3434 static void run_delayed_iput_locked(struct btrfs_fs_info *fs_info,
3435 				    struct btrfs_inode *inode)
3436 {
3437 	list_del_init(&inode->delayed_iput);
3438 	spin_unlock_irq(&fs_info->delayed_iput_lock);
3439 	iput(&inode->vfs_inode);
3440 	if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
3441 		wake_up(&fs_info->delayed_iputs_wait);
3442 	spin_lock_irq(&fs_info->delayed_iput_lock);
3443 }
3444 
3445 static void btrfs_run_delayed_iput(struct btrfs_fs_info *fs_info,
3446 				   struct btrfs_inode *inode)
3447 {
3448 	if (!list_empty(&inode->delayed_iput)) {
3449 		spin_lock_irq(&fs_info->delayed_iput_lock);
3450 		if (!list_empty(&inode->delayed_iput))
3451 			run_delayed_iput_locked(fs_info, inode);
3452 		spin_unlock_irq(&fs_info->delayed_iput_lock);
3453 	}
3454 }
3455 
3456 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3457 {
3458 	/*
3459 	 * btrfs_put_ordered_extent() can run in irq context (see bio.c), which
3460 	 * calls btrfs_add_delayed_iput() and that needs to lock
3461 	 * fs_info->delayed_iput_lock. So we need to disable irqs here to
3462 	 * prevent a deadlock.
3463 	 */
3464 	spin_lock_irq(&fs_info->delayed_iput_lock);
3465 	while (!list_empty(&fs_info->delayed_iputs)) {
3466 		struct btrfs_inode *inode;
3467 
3468 		inode = list_first_entry(&fs_info->delayed_iputs,
3469 				struct btrfs_inode, delayed_iput);
3470 		run_delayed_iput_locked(fs_info, inode);
3471 		if (need_resched()) {
3472 			spin_unlock_irq(&fs_info->delayed_iput_lock);
3473 			cond_resched();
3474 			spin_lock_irq(&fs_info->delayed_iput_lock);
3475 		}
3476 	}
3477 	spin_unlock_irq(&fs_info->delayed_iput_lock);
3478 }
3479 
3480 /*
3481  * Wait for flushing all delayed iputs
3482  *
3483  * @fs_info:  the filesystem
3484  *
3485  * This will wait on any delayed iputs that are currently running with KILLABLE
3486  * set.  Once they are all done running we will return, unless we are killed in
3487  * which case we return EINTR. This helps in user operations like fallocate etc
3488  * that might get blocked on the iputs.
3489  *
3490  * Return EINTR if we were killed, 0 if nothing's pending
3491  */
3492 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
3493 {
3494 	int ret = wait_event_killable(fs_info->delayed_iputs_wait,
3495 			atomic_read(&fs_info->nr_delayed_iputs) == 0);
3496 	if (ret)
3497 		return -EINTR;
3498 	return 0;
3499 }
3500 
3501 /*
3502  * This creates an orphan entry for the given inode in case something goes wrong
3503  * in the middle of an unlink.
3504  */
3505 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3506 		     struct btrfs_inode *inode)
3507 {
3508 	int ret;
3509 
3510 	ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3511 	if (unlikely(ret && ret != -EEXIST)) {
3512 		btrfs_abort_transaction(trans, ret);
3513 		return ret;
3514 	}
3515 
3516 	return 0;
3517 }
3518 
3519 /*
3520  * We have done the delete so we can go ahead and remove the orphan item for
3521  * this particular inode.
3522  */
3523 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3524 			    struct btrfs_inode *inode)
3525 {
3526 	return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
3527 }
3528 
3529 /*
3530  * this cleans up any orphans that may be left on the list from the last use
3531  * of this root.
3532  */
3533 int btrfs_orphan_cleanup(struct btrfs_root *root)
3534 {
3535 	struct btrfs_fs_info *fs_info = root->fs_info;
3536 	BTRFS_PATH_AUTO_FREE(path);
3537 	struct extent_buffer *leaf;
3538 	struct btrfs_key key, found_key;
3539 	struct btrfs_trans_handle *trans;
3540 	u64 last_objectid = 0;
3541 	int ret = 0, nr_unlink = 0;
3542 
3543 	if (test_and_set_bit(BTRFS_ROOT_ORPHAN_CLEANUP, &root->state))
3544 		return 0;
3545 
3546 	path = btrfs_alloc_path();
3547 	if (!path) {
3548 		ret = -ENOMEM;
3549 		goto out;
3550 	}
3551 	path->reada = READA_BACK;
3552 
3553 	key.objectid = BTRFS_ORPHAN_OBJECTID;
3554 	key.type = BTRFS_ORPHAN_ITEM_KEY;
3555 	key.offset = (u64)-1;
3556 
3557 	while (1) {
3558 		struct btrfs_inode *inode;
3559 
3560 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3561 		if (ret < 0)
3562 			goto out;
3563 
3564 		/*
3565 		 * if ret == 0 means we found what we were searching for, which
3566 		 * is weird, but possible, so only screw with path if we didn't
3567 		 * find the key and see if we have stuff that matches
3568 		 */
3569 		if (ret > 0) {
3570 			ret = 0;
3571 			if (path->slots[0] == 0)
3572 				break;
3573 			path->slots[0]--;
3574 		}
3575 
3576 		/* pull out the item */
3577 		leaf = path->nodes[0];
3578 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3579 
3580 		/* make sure the item matches what we want */
3581 		if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3582 			break;
3583 		if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3584 			break;
3585 
3586 		/* release the path since we're done with it */
3587 		btrfs_release_path(path);
3588 
3589 		/*
3590 		 * this is where we are basically btrfs_lookup, without the
3591 		 * crossing root thing.  we store the inode number in the
3592 		 * offset of the orphan item.
3593 		 */
3594 
3595 		if (found_key.offset == last_objectid) {
3596 			/*
3597 			 * We found the same inode as before. This means we were
3598 			 * not able to remove its items via eviction triggered
3599 			 * by an iput(). A transaction abort may have happened,
3600 			 * due to -ENOSPC for example, so try to grab the error
3601 			 * that lead to a transaction abort, if any.
3602 			 */
3603 			btrfs_err(fs_info,
3604 				  "Error removing orphan entry, stopping orphan cleanup");
3605 			ret = BTRFS_FS_ERROR(fs_info) ?: -EINVAL;
3606 			goto out;
3607 		}
3608 
3609 		last_objectid = found_key.offset;
3610 
3611 		found_key.objectid = found_key.offset;
3612 		found_key.type = BTRFS_INODE_ITEM_KEY;
3613 		found_key.offset = 0;
3614 		inode = btrfs_iget(last_objectid, root);
3615 		if (IS_ERR(inode)) {
3616 			ret = PTR_ERR(inode);
3617 			inode = NULL;
3618 			if (ret != -ENOENT)
3619 				goto out;
3620 		}
3621 
3622 		if (!inode && root == fs_info->tree_root) {
3623 			struct btrfs_root *dead_root;
3624 			bool is_dead_root = false;
3625 
3626 			/*
3627 			 * This is an orphan in the tree root. Currently these
3628 			 * could come from 2 sources:
3629 			 *  a) a root (snapshot/subvolume) deletion in progress
3630 			 *  b) a free space cache inode
3631 			 * We need to distinguish those two, as the orphan item
3632 			 * for a root must not get deleted before the deletion
3633 			 * of the snapshot/subvolume's tree completes.
3634 			 *
3635 			 * btrfs_find_orphan_roots() ran before us, which has
3636 			 * found all deleted roots and loaded them into
3637 			 * fs_info->fs_roots_radix. So here we can find if an
3638 			 * orphan item corresponds to a deleted root by looking
3639 			 * up the root from that radix tree.
3640 			 */
3641 
3642 			spin_lock(&fs_info->fs_roots_radix_lock);
3643 			dead_root = radix_tree_lookup(&fs_info->fs_roots_radix,
3644 							 (unsigned long)found_key.objectid);
3645 			if (dead_root && btrfs_root_refs(&dead_root->root_item) == 0)
3646 				is_dead_root = true;
3647 			spin_unlock(&fs_info->fs_roots_radix_lock);
3648 
3649 			if (is_dead_root) {
3650 				/* prevent this orphan from being found again */
3651 				key.offset = found_key.objectid - 1;
3652 				continue;
3653 			}
3654 
3655 		}
3656 
3657 		/*
3658 		 * If we have an inode with links, there are a couple of
3659 		 * possibilities:
3660 		 *
3661 		 * 1. We were halfway through creating fsverity metadata for the
3662 		 * file. In that case, the orphan item represents incomplete
3663 		 * fsverity metadata which must be cleaned up with
3664 		 * btrfs_drop_verity_items and deleting the orphan item.
3665 
3666 		 * 2. Old kernels (before v3.12) used to create an
3667 		 * orphan item for truncate indicating that there were possibly
3668 		 * extent items past i_size that needed to be deleted. In v3.12,
3669 		 * truncate was changed to update i_size in sync with the extent
3670 		 * items, but the (useless) orphan item was still created. Since
3671 		 * v4.18, we don't create the orphan item for truncate at all.
3672 		 *
3673 		 * So, this item could mean that we need to do a truncate, but
3674 		 * only if this filesystem was last used on a pre-v3.12 kernel
3675 		 * and was not cleanly unmounted. The odds of that are quite
3676 		 * slim, and it's a pain to do the truncate now, so just delete
3677 		 * the orphan item.
3678 		 *
3679 		 * It's also possible that this orphan item was supposed to be
3680 		 * deleted but wasn't. The inode number may have been reused,
3681 		 * but either way, we can delete the orphan item.
3682 		 */
3683 		if (!inode || inode->vfs_inode.i_nlink) {
3684 			if (inode) {
3685 				ret = btrfs_drop_verity_items(inode);
3686 				iput(&inode->vfs_inode);
3687 				inode = NULL;
3688 				if (ret)
3689 					goto out;
3690 			}
3691 			trans = btrfs_start_transaction(root, 1);
3692 			if (IS_ERR(trans)) {
3693 				ret = PTR_ERR(trans);
3694 				goto out;
3695 			}
3696 			btrfs_debug(fs_info, "auto deleting %Lu",
3697 				    found_key.objectid);
3698 			ret = btrfs_del_orphan_item(trans, root,
3699 						    found_key.objectid);
3700 			btrfs_end_transaction(trans);
3701 			if (ret)
3702 				goto out;
3703 			continue;
3704 		}
3705 
3706 		nr_unlink++;
3707 
3708 		/* this will do delete_inode and everything for us */
3709 		iput(&inode->vfs_inode);
3710 	}
3711 	/* release the path since we're done with it */
3712 	btrfs_release_path(path);
3713 
3714 	if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3715 		trans = btrfs_join_transaction(root);
3716 		if (!IS_ERR(trans))
3717 			btrfs_end_transaction(trans);
3718 	}
3719 
3720 	if (nr_unlink)
3721 		btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3722 
3723 out:
3724 	if (ret)
3725 		btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3726 	return ret;
3727 }
3728 
3729 /*
3730  * Look ahead in the leaf for xattrs. If we don't find any then we know there
3731  * can't be any ACLs.
3732  *
3733  * @leaf:       the eb leaf where to search
3734  * @slot:       the slot the inode is in
3735  * @objectid:   the objectid of the inode
3736  *
3737  * Return true if there is xattr/ACL, false otherwise.
3738  */
3739 static noinline bool acls_after_inode_item(struct extent_buffer *leaf,
3740 					   int slot, u64 objectid,
3741 					   int *first_xattr_slot)
3742 {
3743 	u32 nritems = btrfs_header_nritems(leaf);
3744 	struct btrfs_key found_key;
3745 	static u64 xattr_access = 0;
3746 	static u64 xattr_default = 0;
3747 	int scanned = 0;
3748 
3749 	if (!xattr_access) {
3750 		xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3751 					strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3752 		xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3753 					strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3754 	}
3755 
3756 	slot++;
3757 	*first_xattr_slot = -1;
3758 	while (slot < nritems) {
3759 		btrfs_item_key_to_cpu(leaf, &found_key, slot);
3760 
3761 		/* We found a different objectid, there must be no ACLs. */
3762 		if (found_key.objectid != objectid)
3763 			return false;
3764 
3765 		/* We found an xattr, assume we've got an ACL. */
3766 		if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3767 			if (*first_xattr_slot == -1)
3768 				*first_xattr_slot = slot;
3769 			if (found_key.offset == xattr_access ||
3770 			    found_key.offset == xattr_default)
3771 				return true;
3772 		}
3773 
3774 		/*
3775 		 * We found a key greater than an xattr key, there can't be any
3776 		 * ACLs later on.
3777 		 */
3778 		if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3779 			return false;
3780 
3781 		slot++;
3782 		scanned++;
3783 
3784 		/*
3785 		 * The item order goes like:
3786 		 * - inode
3787 		 * - inode backrefs
3788 		 * - xattrs
3789 		 * - extents,
3790 		 *
3791 		 * so if there are lots of hard links to an inode there can be
3792 		 * a lot of backrefs.  Don't waste time searching too hard,
3793 		 * this is just an optimization.
3794 		 */
3795 		if (scanned >= 8)
3796 			break;
3797 	}
3798 	/*
3799 	 * We hit the end of the leaf before we found an xattr or something
3800 	 * larger than an xattr.  We have to assume the inode has ACLs.
3801 	 */
3802 	if (*first_xattr_slot == -1)
3803 		*first_xattr_slot = slot;
3804 	return true;
3805 }
3806 
3807 static int btrfs_init_file_extent_tree(struct btrfs_inode *inode)
3808 {
3809 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
3810 
3811 	if (WARN_ON_ONCE(inode->file_extent_tree))
3812 		return 0;
3813 	if (btrfs_fs_incompat(fs_info, NO_HOLES))
3814 		return 0;
3815 	if (!S_ISREG(inode->vfs_inode.i_mode))
3816 		return 0;
3817 	if (btrfs_is_free_space_inode(inode))
3818 		return 0;
3819 
3820 	inode->file_extent_tree = kmalloc_obj(struct extent_io_tree);
3821 	if (!inode->file_extent_tree)
3822 		return -ENOMEM;
3823 
3824 	btrfs_extent_io_tree_init(fs_info, inode->file_extent_tree,
3825 				  IO_TREE_INODE_FILE_EXTENT);
3826 	/* Lockdep class is set only for the file extent tree. */
3827 	lockdep_set_class(&inode->file_extent_tree->lock, &file_extent_tree_class);
3828 
3829 	return 0;
3830 }
3831 
3832 static int btrfs_add_inode_to_root(struct btrfs_inode *inode, bool prealloc)
3833 {
3834 	struct btrfs_root *root = inode->root;
3835 	struct btrfs_inode *existing;
3836 	const u64 ino = btrfs_ino(inode);
3837 	int ret;
3838 
3839 	if (inode_unhashed(&inode->vfs_inode))
3840 		return 0;
3841 
3842 	if (prealloc) {
3843 		ret = xa_reserve(&root->inodes, ino, GFP_NOFS);
3844 		if (ret)
3845 			return ret;
3846 	}
3847 
3848 	existing = xa_store(&root->inodes, ino, inode, GFP_ATOMIC);
3849 
3850 	if (xa_is_err(existing)) {
3851 		ret = xa_err(existing);
3852 		ASSERT(ret != -EINVAL);
3853 		ASSERT(ret != -ENOMEM);
3854 		return ret;
3855 	} else if (existing) {
3856 		WARN_ON(!(inode_state_read_once(&existing->vfs_inode) & (I_WILL_FREE | I_FREEING)));
3857 	}
3858 
3859 	return 0;
3860 }
3861 
3862 /*
3863  * Read a locked inode from the btree into the in-memory inode and add it to
3864  * its root list/tree.
3865  *
3866  * On failure clean up the inode.
3867  */
3868 static int btrfs_read_locked_inode(struct btrfs_inode *inode, struct btrfs_path *path)
3869 {
3870 	struct btrfs_root *root = inode->root;
3871 	struct btrfs_fs_info *fs_info = root->fs_info;
3872 	struct extent_buffer *leaf;
3873 	struct btrfs_inode_item *inode_item;
3874 	struct inode *vfs_inode = &inode->vfs_inode;
3875 	struct btrfs_key location;
3876 	unsigned long ptr;
3877 	int maybe_acls;
3878 	u32 rdev;
3879 	int ret;
3880 	bool filled = false;
3881 	int first_xattr_slot;
3882 
3883 	ret = btrfs_fill_inode(inode, &rdev);
3884 	if (!ret)
3885 		filled = true;
3886 
3887 	ASSERT(path);
3888 
3889 	btrfs_get_inode_key(inode, &location);
3890 
3891 	ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
3892 	if (ret) {
3893 		/*
3894 		 * ret > 0 can come from btrfs_search_slot called by
3895 		 * btrfs_lookup_inode(), this means the inode was not found.
3896 		 */
3897 		if (ret > 0)
3898 			ret = -ENOENT;
3899 		goto out;
3900 	}
3901 
3902 	leaf = path->nodes[0];
3903 
3904 	if (filled)
3905 		goto cache_index;
3906 
3907 	inode_item = btrfs_item_ptr(leaf, path->slots[0],
3908 				    struct btrfs_inode_item);
3909 	vfs_inode->i_mode = btrfs_inode_mode(leaf, inode_item);
3910 	set_nlink(vfs_inode, btrfs_inode_nlink(leaf, inode_item));
3911 	i_uid_write(vfs_inode, btrfs_inode_uid(leaf, inode_item));
3912 	i_gid_write(vfs_inode, btrfs_inode_gid(leaf, inode_item));
3913 	btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
3914 
3915 	inode_set_atime(vfs_inode, btrfs_timespec_sec(leaf, &inode_item->atime),
3916 			btrfs_timespec_nsec(leaf, &inode_item->atime));
3917 
3918 	inode_set_mtime(vfs_inode, btrfs_timespec_sec(leaf, &inode_item->mtime),
3919 			btrfs_timespec_nsec(leaf, &inode_item->mtime));
3920 
3921 	inode_set_ctime(vfs_inode, btrfs_timespec_sec(leaf, &inode_item->ctime),
3922 			btrfs_timespec_nsec(leaf, &inode_item->ctime));
3923 
3924 	inode->i_otime_sec = btrfs_timespec_sec(leaf, &inode_item->otime);
3925 	inode->i_otime_nsec = btrfs_timespec_nsec(leaf, &inode_item->otime);
3926 
3927 	inode_set_bytes(vfs_inode, btrfs_inode_nbytes(leaf, inode_item));
3928 	inode->generation = btrfs_inode_generation(leaf, inode_item);
3929 	inode->last_trans = btrfs_inode_transid(leaf, inode_item);
3930 
3931 	inode_set_iversion_queried(vfs_inode, btrfs_inode_sequence(leaf, inode_item));
3932 	vfs_inode->i_generation = inode->generation;
3933 	vfs_inode->i_rdev = 0;
3934 	rdev = btrfs_inode_rdev(leaf, inode_item);
3935 
3936 	if (S_ISDIR(vfs_inode->i_mode))
3937 		inode->index_cnt = (u64)-1;
3938 
3939 	btrfs_inode_split_flags(btrfs_inode_flags(leaf, inode_item),
3940 				&inode->flags, &inode->ro_flags);
3941 	btrfs_update_inode_mapping_flags(inode);
3942 	btrfs_set_inode_mapping_order(inode);
3943 
3944 cache_index:
3945 	/*
3946 	 * If we were modified in the current generation and evicted from memory
3947 	 * and then re-read we need to do a full sync since we don't have any
3948 	 * idea about which extents were modified before we were evicted from
3949 	 * cache.
3950 	 *
3951 	 * This is required for both inode re-read from disk and delayed inode
3952 	 * in the delayed_nodes xarray.
3953 	 */
3954 	if (inode->last_trans == btrfs_get_fs_generation(fs_info))
3955 		set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
3956 
3957 	/*
3958 	 * We don't persist the id of the transaction where an unlink operation
3959 	 * against the inode was last made. So here we assume the inode might
3960 	 * have been evicted, and therefore the exact value of last_unlink_trans
3961 	 * lost, and set it to last_trans to avoid metadata inconsistencies
3962 	 * between the inode and its parent if the inode is fsync'ed and the log
3963 	 * replayed. For example, in the scenario:
3964 	 *
3965 	 * touch mydir/foo
3966 	 * ln mydir/foo mydir/bar
3967 	 * sync
3968 	 * unlink mydir/bar
3969 	 * echo 2 > /proc/sys/vm/drop_caches   # evicts inode
3970 	 * xfs_io -c fsync mydir/foo
3971 	 * <power failure>
3972 	 * mount fs, triggers fsync log replay
3973 	 *
3974 	 * We must make sure that when we fsync our inode foo we also log its
3975 	 * parent inode, otherwise after log replay the parent still has the
3976 	 * dentry with the "bar" name but our inode foo has a link count of 1
3977 	 * and doesn't have an inode ref with the name "bar" anymore.
3978 	 *
3979 	 * Setting last_unlink_trans to last_trans is a pessimistic approach,
3980 	 * but it guarantees correctness at the expense of occasional full
3981 	 * transaction commits on fsync if our inode is a directory, or if our
3982 	 * inode is not a directory, logging its parent unnecessarily.
3983 	 */
3984 	inode->last_unlink_trans = inode->last_trans;
3985 
3986 	/*
3987 	 * Same logic as for last_unlink_trans. We don't persist the generation
3988 	 * of the last transaction where this inode was used for a reflink
3989 	 * operation, so after eviction and reloading the inode we must be
3990 	 * pessimistic and assume the last transaction that modified the inode.
3991 	 */
3992 	inode->last_reflink_trans = inode->last_trans;
3993 
3994 	path->slots[0]++;
3995 	if (vfs_inode->i_nlink != 1 ||
3996 	    path->slots[0] >= btrfs_header_nritems(leaf))
3997 		goto cache_acl;
3998 
3999 	btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
4000 	if (location.objectid != btrfs_ino(inode))
4001 		goto cache_acl;
4002 
4003 	ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
4004 	if (location.type == BTRFS_INODE_REF_KEY) {
4005 		struct btrfs_inode_ref *ref;
4006 
4007 		ref = (struct btrfs_inode_ref *)ptr;
4008 		inode->dir_index = btrfs_inode_ref_index(leaf, ref);
4009 	} else if (location.type == BTRFS_INODE_EXTREF_KEY) {
4010 		struct btrfs_inode_extref *extref;
4011 
4012 		extref = (struct btrfs_inode_extref *)ptr;
4013 		inode->dir_index = btrfs_inode_extref_index(leaf, extref);
4014 	}
4015 cache_acl:
4016 	/*
4017 	 * try to precache a NULL acl entry for files that don't have
4018 	 * any xattrs or acls
4019 	 */
4020 	maybe_acls = acls_after_inode_item(leaf, path->slots[0],
4021 					   btrfs_ino(inode), &first_xattr_slot);
4022 	if (first_xattr_slot != -1) {
4023 		path->slots[0] = first_xattr_slot;
4024 		ret = btrfs_load_inode_props(inode, path);
4025 		if (ret)
4026 			btrfs_err(fs_info,
4027 				  "error loading props for ino %llu (root %llu): %d",
4028 				  btrfs_ino(inode), btrfs_root_id(root), ret);
4029 	}
4030 
4031 	/*
4032 	 * We don't need the path anymore, so release it to avoid holding a read
4033 	 * lock on a leaf while calling btrfs_init_file_extent_tree(), which can
4034 	 * allocate memory that triggers reclaim (GFP_KERNEL) and cause a locking
4035 	 * dependency.
4036 	 */
4037 	btrfs_release_path(path);
4038 
4039 	ret = btrfs_init_file_extent_tree(inode);
4040 	if (ret)
4041 		goto out;
4042 	btrfs_inode_set_file_extent_range(inode, 0,
4043 			  round_up(i_size_read(vfs_inode), fs_info->sectorsize));
4044 
4045 	if (!maybe_acls)
4046 		cache_no_acl(vfs_inode);
4047 
4048 	switch (vfs_inode->i_mode & S_IFMT) {
4049 	case S_IFREG:
4050 		vfs_inode->i_mapping->a_ops = &btrfs_aops;
4051 		vfs_inode->i_fop = &btrfs_file_operations;
4052 		vfs_inode->i_op = &btrfs_file_inode_operations;
4053 		break;
4054 	case S_IFDIR:
4055 		vfs_inode->i_fop = &btrfs_dir_file_operations;
4056 		vfs_inode->i_op = &btrfs_dir_inode_operations;
4057 		break;
4058 	case S_IFLNK:
4059 		vfs_inode->i_op = &btrfs_symlink_inode_operations;
4060 		inode_nohighmem(vfs_inode);
4061 		vfs_inode->i_mapping->a_ops = &btrfs_aops;
4062 		break;
4063 	default:
4064 		vfs_inode->i_op = &btrfs_special_inode_operations;
4065 		init_special_inode(vfs_inode, vfs_inode->i_mode, rdev);
4066 		break;
4067 	}
4068 
4069 	btrfs_sync_inode_flags_to_i_flags(inode);
4070 
4071 	ret = btrfs_add_inode_to_root(inode, true);
4072 	if (ret)
4073 		goto out;
4074 
4075 	return 0;
4076 out:
4077 	/*
4078 	 * We may have a read locked leaf and iget_failed() triggers inode
4079 	 * eviction which needs to release the delayed inode and that needs
4080 	 * to lock the delayed inode's mutex. This can cause a ABBA deadlock
4081 	 * with a task running delayed items, as that require first locking
4082 	 * the delayed inode's mutex and then modifying its subvolume btree.
4083 	 * So release the path before iget_failed().
4084 	 */
4085 	btrfs_release_path(path);
4086 	iget_failed(vfs_inode);
4087 	return ret;
4088 }
4089 
4090 /*
4091  * given a leaf and an inode, copy the inode fields into the leaf
4092  */
4093 static void fill_inode_item(struct btrfs_trans_handle *trans,
4094 			    struct extent_buffer *leaf,
4095 			    struct btrfs_inode_item *item,
4096 			    struct inode *inode)
4097 {
4098 	u64 flags;
4099 
4100 	btrfs_set_inode_uid(leaf, item, i_uid_read(inode));
4101 	btrfs_set_inode_gid(leaf, item, i_gid_read(inode));
4102 	btrfs_set_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size);
4103 	btrfs_set_inode_mode(leaf, item, inode->i_mode);
4104 	btrfs_set_inode_nlink(leaf, item, inode->i_nlink);
4105 
4106 	btrfs_set_timespec_sec(leaf, &item->atime, inode_get_atime_sec(inode));
4107 	btrfs_set_timespec_nsec(leaf, &item->atime, inode_get_atime_nsec(inode));
4108 
4109 	btrfs_set_timespec_sec(leaf, &item->mtime, inode_get_mtime_sec(inode));
4110 	btrfs_set_timespec_nsec(leaf, &item->mtime, inode_get_mtime_nsec(inode));
4111 
4112 	btrfs_set_timespec_sec(leaf, &item->ctime, inode_get_ctime_sec(inode));
4113 	btrfs_set_timespec_nsec(leaf, &item->ctime, inode_get_ctime_nsec(inode));
4114 
4115 	btrfs_set_timespec_sec(leaf, &item->otime, BTRFS_I(inode)->i_otime_sec);
4116 	btrfs_set_timespec_nsec(leaf, &item->otime, BTRFS_I(inode)->i_otime_nsec);
4117 
4118 	btrfs_set_inode_nbytes(leaf, item, inode_get_bytes(inode));
4119 	btrfs_set_inode_generation(leaf, item, BTRFS_I(inode)->generation);
4120 	btrfs_set_inode_sequence(leaf, item, inode_peek_iversion(inode));
4121 	btrfs_set_inode_transid(leaf, item, trans->transid);
4122 	btrfs_set_inode_rdev(leaf, item, inode->i_rdev);
4123 	flags = btrfs_inode_combine_flags(BTRFS_I(inode)->flags,
4124 					  BTRFS_I(inode)->ro_flags);
4125 	btrfs_set_inode_flags(leaf, item, flags);
4126 	btrfs_set_inode_block_group(leaf, item, 0);
4127 }
4128 
4129 /*
4130  * copy everything in the in-memory inode into the btree.
4131  */
4132 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
4133 					    struct btrfs_inode *inode)
4134 {
4135 	struct btrfs_inode_item *inode_item;
4136 	BTRFS_PATH_AUTO_FREE(path);
4137 	struct extent_buffer *leaf;
4138 	struct btrfs_key key;
4139 	int ret;
4140 
4141 	path = btrfs_alloc_path();
4142 	if (!path)
4143 		return -ENOMEM;
4144 
4145 	btrfs_get_inode_key(inode, &key);
4146 	ret = btrfs_lookup_inode(trans, inode->root, path, &key, 1);
4147 	if (ret) {
4148 		if (ret > 0)
4149 			ret = -ENOENT;
4150 		return ret;
4151 	}
4152 
4153 	leaf = path->nodes[0];
4154 	inode_item = btrfs_item_ptr(leaf, path->slots[0],
4155 				    struct btrfs_inode_item);
4156 
4157 	fill_inode_item(trans, leaf, inode_item, &inode->vfs_inode);
4158 	btrfs_set_inode_last_trans(trans, inode);
4159 	return 0;
4160 }
4161 
4162 /*
4163  * copy everything in the in-memory inode into the btree.
4164  */
4165 int btrfs_update_inode(struct btrfs_trans_handle *trans,
4166 		       struct btrfs_inode *inode)
4167 {
4168 	struct btrfs_root *root = inode->root;
4169 	struct btrfs_fs_info *fs_info = root->fs_info;
4170 	int ret;
4171 
4172 	/*
4173 	 * If the inode is a free space inode, we can deadlock during commit
4174 	 * if we put it into the delayed code.
4175 	 *
4176 	 * The data relocation inode should also be directly updated
4177 	 * without delay
4178 	 */
4179 	if (!btrfs_is_free_space_inode(inode)
4180 	    && !btrfs_is_data_reloc_root(root)
4181 	    && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
4182 		btrfs_update_root_times(trans, root);
4183 
4184 		ret = btrfs_delayed_update_inode(trans, inode);
4185 		if (!ret)
4186 			btrfs_set_inode_last_trans(trans, inode);
4187 		return ret;
4188 	}
4189 
4190 	return btrfs_update_inode_item(trans, inode);
4191 }
4192 
4193 int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
4194 				struct btrfs_inode *inode)
4195 {
4196 	int ret;
4197 
4198 	ret = btrfs_update_inode(trans, inode);
4199 	if (ret == -ENOSPC)
4200 		return btrfs_update_inode_item(trans, inode);
4201 	return ret;
4202 }
4203 
4204 static void update_time_after_link_or_unlink(struct btrfs_inode *dir)
4205 {
4206 	struct timespec64 now;
4207 
4208 	/*
4209 	 * If we are replaying a log tree, we do not want to update the mtime
4210 	 * and ctime of the parent directory with the current time, since the
4211 	 * log replay procedure is responsible for setting them to their correct
4212 	 * values (the ones it had when the fsync was done).
4213 	 */
4214 	if (test_bit(BTRFS_FS_LOG_RECOVERING, &dir->root->fs_info->flags))
4215 		return;
4216 
4217 	now = inode_set_ctime_current(&dir->vfs_inode);
4218 	inode_set_mtime_to_ts(&dir->vfs_inode, now);
4219 }
4220 
4221 /*
4222  * unlink helper that gets used here in inode.c and in the tree logging
4223  * recovery code.  It remove a link in a directory with a given name, and
4224  * also drops the back refs in the inode to the directory
4225  */
4226 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4227 				struct btrfs_inode *dir,
4228 				struct btrfs_inode *inode,
4229 				const struct fscrypt_str *name,
4230 				struct btrfs_rename_ctx *rename_ctx)
4231 {
4232 	struct btrfs_root *root = dir->root;
4233 	struct btrfs_fs_info *fs_info = root->fs_info;
4234 	struct btrfs_path *path;
4235 	int ret = 0;
4236 	struct btrfs_dir_item *di;
4237 	u64 index;
4238 	u64 ino = btrfs_ino(inode);
4239 	u64 dir_ino = btrfs_ino(dir);
4240 
4241 	path = btrfs_alloc_path();
4242 	if (!path)
4243 		return -ENOMEM;
4244 
4245 	di = btrfs_lookup_dir_item(trans, root, path, dir_ino, name, -1);
4246 	if (IS_ERR_OR_NULL(di)) {
4247 		btrfs_free_path(path);
4248 		return di ? PTR_ERR(di) : -ENOENT;
4249 	}
4250 	ret = btrfs_delete_one_dir_name(trans, root, path, di);
4251 	/*
4252 	 * Down the call chains below we'll also need to allocate a path, so no
4253 	 * need to hold on to this one for longer than necessary.
4254 	 */
4255 	btrfs_free_path(path);
4256 	if (ret)
4257 		return ret;
4258 
4259 	/*
4260 	 * If we don't have dir index, we have to get it by looking up
4261 	 * the inode ref, since we get the inode ref, remove it directly,
4262 	 * it is unnecessary to do delayed deletion.
4263 	 *
4264 	 * But if we have dir index, needn't search inode ref to get it.
4265 	 * Since the inode ref is close to the inode item, it is better
4266 	 * that we delay to delete it, and just do this deletion when
4267 	 * we update the inode item.
4268 	 */
4269 	if (inode->dir_index) {
4270 		ret = btrfs_delayed_delete_inode_ref(inode);
4271 		if (!ret) {
4272 			index = inode->dir_index;
4273 			goto skip_backref;
4274 		}
4275 	}
4276 
4277 	ret = btrfs_del_inode_ref(trans, root, name, ino, dir_ino, &index);
4278 	if (unlikely(ret)) {
4279 		btrfs_crit(fs_info,
4280 	   "failed to delete reference to %.*s, root %llu inode %llu parent %llu",
4281 			   name->len, name->name, btrfs_root_id(root), ino, dir_ino);
4282 		btrfs_abort_transaction(trans, ret);
4283 		return ret;
4284 	}
4285 skip_backref:
4286 	if (rename_ctx)
4287 		rename_ctx->index = index;
4288 
4289 	ret = btrfs_delete_delayed_dir_index(trans, dir, index);
4290 	if (unlikely(ret)) {
4291 		btrfs_abort_transaction(trans, ret);
4292 		return ret;
4293 	}
4294 
4295 	/*
4296 	 * If we are in a rename context, we don't need to update anything in the
4297 	 * log. That will be done later during the rename by btrfs_log_new_name().
4298 	 * Besides that, doing it here would only cause extra unnecessary btree
4299 	 * operations on the log tree, increasing latency for applications.
4300 	 */
4301 	if (!rename_ctx) {
4302 		btrfs_del_inode_ref_in_log(trans, name, inode, dir);
4303 		btrfs_del_dir_entries_in_log(trans, name, dir, index);
4304 	}
4305 
4306 	/*
4307 	 * If we have a pending delayed iput we could end up with the final iput
4308 	 * being run in btrfs-cleaner context.  If we have enough of these built
4309 	 * up we can end up burning a lot of time in btrfs-cleaner without any
4310 	 * way to throttle the unlinks.  Since we're currently holding a ref on
4311 	 * the inode we can run the delayed iput here without any issues as the
4312 	 * final iput won't be done until after we drop the ref we're currently
4313 	 * holding.
4314 	 */
4315 	btrfs_run_delayed_iput(fs_info, inode);
4316 
4317 	btrfs_i_size_write(dir, dir->vfs_inode.i_size - name->len * 2);
4318 	inode_inc_iversion(&inode->vfs_inode);
4319 	inode_set_ctime_current(&inode->vfs_inode);
4320 	inode_inc_iversion(&dir->vfs_inode);
4321 	update_time_after_link_or_unlink(dir);
4322 
4323 	return btrfs_update_inode(trans, dir);
4324 }
4325 
4326 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4327 		       struct btrfs_inode *dir, struct btrfs_inode *inode,
4328 		       const struct fscrypt_str *name)
4329 {
4330 	int ret;
4331 
4332 	ret = __btrfs_unlink_inode(trans, dir, inode, name, NULL);
4333 	if (!ret) {
4334 		drop_nlink(&inode->vfs_inode);
4335 		ret = btrfs_update_inode(trans, inode);
4336 	}
4337 	return ret;
4338 }
4339 
4340 /*
4341  * helper to start transaction for unlink and rmdir.
4342  *
4343  * unlink and rmdir are special in btrfs, they do not always free space, so
4344  * if we cannot make our reservations the normal way try and see if there is
4345  * plenty of slack room in the global reserve to migrate, otherwise we cannot
4346  * allow the unlink to occur.
4347  */
4348 static struct btrfs_trans_handle *__unlink_start_trans(struct btrfs_inode *dir)
4349 {
4350 	struct btrfs_root *root = dir->root;
4351 
4352 	return btrfs_start_transaction_fallback_global_rsv(root,
4353 						   BTRFS_UNLINK_METADATA_UNITS);
4354 }
4355 
4356 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4357 {
4358 	struct btrfs_trans_handle *trans;
4359 	struct inode *inode = d_inode(dentry);
4360 	int ret;
4361 	struct fscrypt_name fname;
4362 
4363 	ret = fscrypt_setup_filename(dir, &dentry->d_name, 1, &fname);
4364 	if (ret)
4365 		return ret;
4366 
4367 	/* This needs to handle no-key deletions later on */
4368 
4369 	trans = __unlink_start_trans(BTRFS_I(dir));
4370 	if (IS_ERR(trans)) {
4371 		ret = PTR_ERR(trans);
4372 		goto fscrypt_free;
4373 	}
4374 
4375 	btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4376 				false);
4377 
4378 	ret = btrfs_unlink_inode(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4379 				 &fname.disk_name);
4380 	if (ret)
4381 		goto end_trans;
4382 
4383 	if (inode->i_nlink == 0) {
4384 		ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4385 		if (ret)
4386 			goto end_trans;
4387 	}
4388 
4389 end_trans:
4390 	btrfs_end_transaction(trans);
4391 	btrfs_btree_balance_dirty(BTRFS_I(dir)->root->fs_info);
4392 fscrypt_free:
4393 	fscrypt_free_filename(&fname);
4394 	return ret;
4395 }
4396 
4397 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4398 			       struct btrfs_inode *dir, struct dentry *dentry)
4399 {
4400 	struct btrfs_root *root = dir->root;
4401 	struct btrfs_inode *inode = BTRFS_I(d_inode(dentry));
4402 	BTRFS_PATH_AUTO_FREE(path);
4403 	struct extent_buffer *leaf;
4404 	struct btrfs_dir_item *di;
4405 	struct btrfs_key key;
4406 	u64 index;
4407 	int ret;
4408 	u64 objectid;
4409 	u64 dir_ino = btrfs_ino(dir);
4410 	struct fscrypt_name fname;
4411 
4412 	ret = fscrypt_setup_filename(&dir->vfs_inode, &dentry->d_name, 1, &fname);
4413 	if (ret)
4414 		return ret;
4415 
4416 	/* This needs to handle no-key deletions later on */
4417 
4418 	if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) {
4419 		objectid = btrfs_root_id(inode->root);
4420 	} else if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4421 		objectid = inode->ref_root_id;
4422 	} else {
4423 		WARN_ON(1);
4424 		fscrypt_free_filename(&fname);
4425 		return -EINVAL;
4426 	}
4427 
4428 	path = btrfs_alloc_path();
4429 	if (!path) {
4430 		ret = -ENOMEM;
4431 		goto out;
4432 	}
4433 
4434 	di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4435 				   &fname.disk_name, -1);
4436 	if (IS_ERR_OR_NULL(di)) {
4437 		ret = di ? PTR_ERR(di) : -ENOENT;
4438 		goto out;
4439 	}
4440 
4441 	leaf = path->nodes[0];
4442 	btrfs_dir_item_key_to_cpu(leaf, di, &key);
4443 	WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4444 	ret = btrfs_delete_one_dir_name(trans, root, path, di);
4445 	if (unlikely(ret)) {
4446 		btrfs_abort_transaction(trans, ret);
4447 		goto out;
4448 	}
4449 	btrfs_release_path(path);
4450 
4451 	/*
4452 	 * This is a placeholder inode for a subvolume we didn't have a
4453 	 * reference to at the time of the snapshot creation.  In the meantime
4454 	 * we could have renamed the real subvol link into our snapshot, so
4455 	 * depending on btrfs_del_root_ref to return -ENOENT here is incorrect.
4456 	 * Instead simply lookup the dir_index_item for this entry so we can
4457 	 * remove it.  Otherwise we know we have a ref to the root and we can
4458 	 * call btrfs_del_root_ref, and it _shouldn't_ fail.
4459 	 */
4460 	if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4461 		di = btrfs_search_dir_index_item(root, path, dir_ino, &fname.disk_name);
4462 		if (IS_ERR(di)) {
4463 			ret = PTR_ERR(di);
4464 			btrfs_abort_transaction(trans, ret);
4465 			goto out;
4466 		}
4467 
4468 		leaf = path->nodes[0];
4469 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4470 		index = key.offset;
4471 		btrfs_release_path(path);
4472 	} else {
4473 		ret = btrfs_del_root_ref(trans, objectid,
4474 					 btrfs_root_id(root), dir_ino,
4475 					 &index, &fname.disk_name);
4476 		if (unlikely(ret)) {
4477 			btrfs_abort_transaction(trans, ret);
4478 			goto out;
4479 		}
4480 	}
4481 
4482 	ret = btrfs_delete_delayed_dir_index(trans, dir, index);
4483 	if (unlikely(ret)) {
4484 		btrfs_abort_transaction(trans, ret);
4485 		goto out;
4486 	}
4487 
4488 	btrfs_i_size_write(dir, dir->vfs_inode.i_size - fname.disk_name.len * 2);
4489 	inode_inc_iversion(&dir->vfs_inode);
4490 	inode_set_mtime_to_ts(&dir->vfs_inode, inode_set_ctime_current(&dir->vfs_inode));
4491 	ret = btrfs_update_inode_fallback(trans, dir);
4492 	if (ret)
4493 		btrfs_abort_transaction(trans, ret);
4494 out:
4495 	fscrypt_free_filename(&fname);
4496 	return ret;
4497 }
4498 
4499 /*
4500  * Helper to check if the subvolume references other subvolumes or if it's
4501  * default.
4502  */
4503 static noinline int may_destroy_subvol(struct btrfs_root *root)
4504 {
4505 	struct btrfs_fs_info *fs_info = root->fs_info;
4506 	BTRFS_PATH_AUTO_FREE(path);
4507 	struct btrfs_dir_item *di;
4508 	struct btrfs_key key;
4509 	struct fscrypt_str name = FSTR_INIT("default", 7);
4510 	u64 dir_id;
4511 	int ret;
4512 
4513 	path = btrfs_alloc_path();
4514 	if (!path)
4515 		return -ENOMEM;
4516 
4517 	/* Make sure this root isn't set as the default subvol */
4518 	dir_id = btrfs_super_root_dir(fs_info->super_copy);
4519 	di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
4520 				   dir_id, &name, 0);
4521 	if (!IS_ERR_OR_NULL(di)) {
4522 		btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
4523 		if (key.objectid == btrfs_root_id(root)) {
4524 			ret = -EPERM;
4525 			btrfs_err(fs_info,
4526 				  "deleting default subvolume %llu is not allowed",
4527 				  key.objectid);
4528 			return ret;
4529 		}
4530 		btrfs_release_path(path);
4531 	}
4532 
4533 	key.objectid = btrfs_root_id(root);
4534 	key.type = BTRFS_ROOT_REF_KEY;
4535 	key.offset = (u64)-1;
4536 
4537 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4538 	if (ret < 0)
4539 		return ret;
4540 	if (unlikely(ret == 0)) {
4541 		/*
4542 		 * Key with offset -1 found, there would have to exist a root
4543 		 * with such id, but this is out of valid range.
4544 		 */
4545 		return -EUCLEAN;
4546 	}
4547 
4548 	ret = 0;
4549 	if (path->slots[0] > 0) {
4550 		path->slots[0]--;
4551 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4552 		if (key.objectid == btrfs_root_id(root) && key.type == BTRFS_ROOT_REF_KEY)
4553 			ret = -ENOTEMPTY;
4554 	}
4555 
4556 	return ret;
4557 }
4558 
4559 /* Delete all dentries for inodes belonging to the root */
4560 static void btrfs_prune_dentries(struct btrfs_root *root)
4561 {
4562 	struct btrfs_fs_info *fs_info = root->fs_info;
4563 	struct btrfs_inode *inode;
4564 	u64 min_ino = 0;
4565 
4566 	if (!BTRFS_FS_ERROR(fs_info))
4567 		WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4568 
4569 	inode = btrfs_find_first_inode(root, min_ino);
4570 	while (inode) {
4571 		if (icount_read_once(&inode->vfs_inode) > 1)
4572 			d_prune_aliases(&inode->vfs_inode);
4573 
4574 		min_ino = btrfs_ino(inode) + 1;
4575 		/*
4576 		 * btrfs_drop_inode() will have it removed from the inode
4577 		 * cache when its usage count hits zero.
4578 		 */
4579 		iput(&inode->vfs_inode);
4580 		cond_resched();
4581 		inode = btrfs_find_first_inode(root, min_ino);
4582 	}
4583 }
4584 
4585 int btrfs_delete_subvolume(struct btrfs_inode *dir, struct dentry *dentry)
4586 {
4587 	struct btrfs_root *root = dir->root;
4588 	struct btrfs_fs_info *fs_info = root->fs_info;
4589 	struct inode *inode = d_inode(dentry);
4590 	struct btrfs_root *dest = BTRFS_I(inode)->root;
4591 	struct btrfs_trans_handle *trans;
4592 	struct btrfs_block_rsv block_rsv;
4593 	u64 root_flags;
4594 	u64 qgroup_reserved = 0;
4595 	int ret;
4596 
4597 	down_write(&fs_info->subvol_sem);
4598 
4599 	/*
4600 	 * Don't allow to delete a subvolume with send in progress. This is
4601 	 * inside the inode lock so the error handling that has to drop the bit
4602 	 * again is not run concurrently.
4603 	 */
4604 	spin_lock(&dest->root_item_lock);
4605 	if (dest->send_in_progress) {
4606 		spin_unlock(&dest->root_item_lock);
4607 		btrfs_warn(fs_info,
4608 			   "attempt to delete subvolume %llu during send",
4609 			   btrfs_root_id(dest));
4610 		ret = -EPERM;
4611 		goto out_up_write;
4612 	}
4613 	if (atomic_read(&dest->nr_swapfiles)) {
4614 		spin_unlock(&dest->root_item_lock);
4615 		btrfs_warn(fs_info,
4616 			   "attempt to delete subvolume %llu with active swapfile",
4617 			   btrfs_root_id(dest));
4618 		ret = -EPERM;
4619 		goto out_up_write;
4620 	}
4621 	root_flags = btrfs_root_flags(&dest->root_item);
4622 	btrfs_set_root_flags(&dest->root_item,
4623 			     root_flags | BTRFS_ROOT_SUBVOL_DEAD);
4624 	spin_unlock(&dest->root_item_lock);
4625 
4626 	ret = may_destroy_subvol(dest);
4627 	if (ret)
4628 		goto out_undead;
4629 
4630 	btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4631 	/*
4632 	 * One for dir inode,
4633 	 * two for dir entries,
4634 	 * two for root ref/backref.
4635 	 */
4636 	ret = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
4637 	if (ret)
4638 		goto out_undead;
4639 	qgroup_reserved = block_rsv.qgroup_rsv_reserved;
4640 
4641 	trans = btrfs_start_transaction(root, 0);
4642 	if (IS_ERR(trans)) {
4643 		ret = PTR_ERR(trans);
4644 		goto out_release;
4645 	}
4646 	btrfs_qgroup_convert_reserved_meta(root, qgroup_reserved);
4647 	qgroup_reserved = 0;
4648 	trans->block_rsv = &block_rsv;
4649 	trans->bytes_reserved = block_rsv.size;
4650 
4651 	btrfs_record_snapshot_destroy(trans, dir);
4652 
4653 	ret = btrfs_unlink_subvol(trans, dir, dentry);
4654 	if (unlikely(ret)) {
4655 		btrfs_abort_transaction(trans, ret);
4656 		goto out_end_trans;
4657 	}
4658 
4659 	ret = btrfs_record_root_in_trans(trans, dest);
4660 	if (unlikely(ret)) {
4661 		btrfs_abort_transaction(trans, ret);
4662 		goto out_end_trans;
4663 	}
4664 
4665 	memset(&dest->root_item.drop_progress, 0,
4666 		sizeof(dest->root_item.drop_progress));
4667 	btrfs_set_root_drop_level(&dest->root_item, 0);
4668 	btrfs_set_root_refs(&dest->root_item, 0);
4669 
4670 	if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
4671 		ret = btrfs_insert_orphan_item(trans,
4672 					fs_info->tree_root,
4673 					btrfs_root_id(dest));
4674 		if (unlikely(ret)) {
4675 			btrfs_abort_transaction(trans, ret);
4676 			goto out_end_trans;
4677 		}
4678 	}
4679 
4680 	ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
4681 				     BTRFS_UUID_KEY_SUBVOL, btrfs_root_id(dest));
4682 	if (unlikely(ret && ret != -ENOENT)) {
4683 		btrfs_abort_transaction(trans, ret);
4684 		goto out_end_trans;
4685 	}
4686 	if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4687 		ret = btrfs_uuid_tree_remove(trans,
4688 					  dest->root_item.received_uuid,
4689 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4690 					  btrfs_root_id(dest));
4691 		if (unlikely(ret && ret != -ENOENT)) {
4692 			btrfs_abort_transaction(trans, ret);
4693 			goto out_end_trans;
4694 		}
4695 	}
4696 
4697 	free_anon_bdev(dest->anon_dev);
4698 	dest->anon_dev = 0;
4699 out_end_trans:
4700 	trans->block_rsv = NULL;
4701 	trans->bytes_reserved = 0;
4702 	ret = btrfs_end_transaction(trans);
4703 	inode->i_flags |= S_DEAD;
4704 out_release:
4705 	btrfs_block_rsv_release(fs_info, &block_rsv, (u64)-1, NULL);
4706 	if (qgroup_reserved)
4707 		btrfs_qgroup_free_meta_prealloc(root, qgroup_reserved);
4708 out_undead:
4709 	if (ret) {
4710 		spin_lock(&dest->root_item_lock);
4711 		root_flags = btrfs_root_flags(&dest->root_item);
4712 		btrfs_set_root_flags(&dest->root_item,
4713 				root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4714 		spin_unlock(&dest->root_item_lock);
4715 	}
4716 out_up_write:
4717 	up_write(&fs_info->subvol_sem);
4718 	if (!ret) {
4719 		d_invalidate(dentry);
4720 		btrfs_prune_dentries(dest);
4721 		ASSERT(dest->send_in_progress == 0);
4722 	}
4723 
4724 	return ret;
4725 }
4726 
4727 static int btrfs_rmdir(struct inode *vfs_dir, struct dentry *dentry)
4728 {
4729 	struct btrfs_inode *dir = BTRFS_I(vfs_dir);
4730 	struct btrfs_inode *inode = BTRFS_I(d_inode(dentry));
4731 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
4732 	int ret = 0;
4733 	struct btrfs_trans_handle *trans;
4734 	struct fscrypt_name fname;
4735 
4736 	if (inode->vfs_inode.i_size > BTRFS_EMPTY_DIR_SIZE)
4737 		return -ENOTEMPTY;
4738 	if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) {
4739 		if (unlikely(btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))) {
4740 			btrfs_err(fs_info,
4741 			"extent tree v2 doesn't support snapshot deletion yet");
4742 			return -EOPNOTSUPP;
4743 		}
4744 		return btrfs_delete_subvolume(dir, dentry);
4745 	}
4746 
4747 	ret = fscrypt_setup_filename(vfs_dir, &dentry->d_name, 1, &fname);
4748 	if (ret)
4749 		return ret;
4750 
4751 	/* This needs to handle no-key deletions later on */
4752 
4753 	trans = __unlink_start_trans(dir);
4754 	if (IS_ERR(trans)) {
4755 		ret = PTR_ERR(trans);
4756 		goto out_notrans;
4757 	}
4758 
4759 	/*
4760 	 * Propagate the last_unlink_trans value of the deleted dir to its
4761 	 * parent directory. This is to prevent an unrecoverable log tree in the
4762 	 * case we do something like this:
4763 	 * 1) create dir foo
4764 	 * 2) create snapshot under dir foo
4765 	 * 3) delete the snapshot
4766 	 * 4) rmdir foo
4767 	 * 5) mkdir foo
4768 	 * 6) fsync foo or some file inside foo
4769 	 *
4770 	 * This is because we can't unlink other roots when replaying the dir
4771 	 * deletes for directory foo.
4772 	 */
4773 	if (inode->last_unlink_trans >= trans->transid)
4774 		btrfs_record_snapshot_destroy(trans, dir);
4775 
4776 	if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4777 		ret = btrfs_unlink_subvol(trans, dir, dentry);
4778 		goto out;
4779 	}
4780 
4781 	ret = btrfs_orphan_add(trans, inode);
4782 	if (ret)
4783 		goto out;
4784 
4785 	btrfs_record_unlink_dir(trans, dir, inode, false);
4786 
4787 	/* now the directory is empty */
4788 	ret = btrfs_unlink_inode(trans, dir, inode, &fname.disk_name);
4789 	if (!ret)
4790 		btrfs_i_size_write(inode, 0);
4791 out:
4792 	btrfs_end_transaction(trans);
4793 out_notrans:
4794 	btrfs_btree_balance_dirty(fs_info);
4795 	fscrypt_free_filename(&fname);
4796 
4797 	return ret;
4798 }
4799 
4800 static bool is_inside_block(u64 bytenr, u64 blockstart, u32 blocksize)
4801 {
4802 	ASSERT(IS_ALIGNED(blockstart, blocksize), "blockstart=%llu blocksize=%u",
4803 		blockstart, blocksize);
4804 
4805 	if (blockstart <= bytenr && bytenr <= blockstart + blocksize - 1)
4806 		return true;
4807 	return false;
4808 }
4809 
4810 static int truncate_block_zero_beyond_eof(struct btrfs_inode *inode, u64 start)
4811 {
4812 	const pgoff_t index = (start >> PAGE_SHIFT);
4813 	struct address_space *mapping = inode->vfs_inode.i_mapping;
4814 	struct folio *folio;
4815 	u64 zero_start;
4816 	u64 zero_end;
4817 	int ret = 0;
4818 
4819 again:
4820 	folio = filemap_lock_folio(mapping, index);
4821 	/* No folio present. */
4822 	if (IS_ERR(folio))
4823 		return 0;
4824 
4825 	if (!folio_test_uptodate(folio)) {
4826 		ret = btrfs_read_folio(NULL, folio);
4827 		folio_lock(folio);
4828 		if (folio->mapping != mapping) {
4829 			folio_unlock(folio);
4830 			folio_put(folio);
4831 			goto again;
4832 		}
4833 		if (unlikely(!folio_test_uptodate(folio))) {
4834 			ret = -EIO;
4835 			goto out_unlock;
4836 		}
4837 	}
4838 	folio_wait_writeback(folio);
4839 
4840 	/*
4841 	 * We do not need to lock extents nor wait for OE, as it's already
4842 	 * beyond EOF.
4843 	 */
4844 
4845 	zero_start = max_t(u64, folio_pos(folio), start);
4846 	zero_end = folio_next_pos(folio);
4847 	folio_zero_range(folio, zero_start - folio_pos(folio),
4848 			 zero_end - zero_start);
4849 
4850 out_unlock:
4851 	folio_unlock(folio);
4852 	folio_put(folio);
4853 	return ret;
4854 }
4855 
4856 /*
4857  * Handle the truncation of a fs block.
4858  *
4859  * @inode  - inode that we're zeroing
4860  * @offset - the file offset of the block to truncate
4861  *           The value must be inside [@start, @end], and the function will do
4862  *           extra checks if the block that covers @offset needs to be zeroed.
4863  * @start  - the start file offset of the range we want to zero
4864  * @end    - the end (inclusive) file offset of the range we want to zero.
4865  *
4866  * If the range is not block aligned, read out the folio that covers @offset,
4867  * and if needed zero blocks that are inside the folio and covered by [@start, @end).
4868  * If @start or @end + 1 lands inside a block, that block will be marked dirty
4869  * for writeback.
4870  *
4871  * This is utilized by hole punch, zero range, file expansion.
4872  */
4873 int btrfs_truncate_block(struct btrfs_inode *inode, u64 offset, u64 start, u64 end)
4874 {
4875 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
4876 	struct address_space *mapping = inode->vfs_inode.i_mapping;
4877 	struct extent_io_tree *io_tree = &inode->io_tree;
4878 	struct btrfs_ordered_extent *ordered;
4879 	struct extent_state *cached_state = NULL;
4880 	struct extent_changeset *data_reserved = NULL;
4881 	bool only_release_metadata = false;
4882 	u32 blocksize = fs_info->sectorsize;
4883 	pgoff_t index = (offset >> PAGE_SHIFT);
4884 	struct folio *folio;
4885 	gfp_t mask = btrfs_alloc_write_mask(mapping);
4886 	int ret = 0;
4887 	const bool in_head_block = is_inside_block(offset, round_down(start, blocksize),
4888 						   blocksize);
4889 	const bool in_tail_block = is_inside_block(offset, round_down(end, blocksize),
4890 						   blocksize);
4891 	bool need_truncate_head = false;
4892 	bool need_truncate_tail = false;
4893 	u64 zero_start;
4894 	u64 zero_end;
4895 	u64 block_start;
4896 	u64 block_end;
4897 
4898 	/* @offset should be inside the range. */
4899 	ASSERT(start <= offset && offset <= end, "offset=%llu start=%llu end=%llu",
4900 	       offset, start, end);
4901 
4902 	/* The range is aligned at both ends. */
4903 	if (IS_ALIGNED(start, blocksize) && IS_ALIGNED(end + 1, blocksize)) {
4904 		/*
4905 		 * For block size < page size case, we may have polluted blocks
4906 		 * beyond EOF. So we also need to zero them out.
4907 		 */
4908 		if (end == (u64)-1 && blocksize < PAGE_SIZE)
4909 			ret = truncate_block_zero_beyond_eof(inode, start);
4910 		goto out;
4911 	}
4912 
4913 	/*
4914 	 * @offset may not be inside the head nor tail block. In that case we
4915 	 * don't need to do anything.
4916 	 */
4917 	if (!in_head_block && !in_tail_block)
4918 		goto out;
4919 
4920 	/*
4921 	 * Skip the truncation if the range in the target block is already aligned.
4922 	 * The seemingly complex check will also handle the same block case.
4923 	 */
4924 	if (in_head_block && !IS_ALIGNED(start, blocksize))
4925 		need_truncate_head = true;
4926 	if (in_tail_block && !IS_ALIGNED(end + 1, blocksize))
4927 		need_truncate_tail = true;
4928 	if (!need_truncate_head && !need_truncate_tail)
4929 		goto out;
4930 
4931 	block_start = round_down(offset, blocksize);
4932 	block_end = block_start + blocksize - 1;
4933 
4934 	ret = btrfs_check_data_free_space(inode, &data_reserved, block_start,
4935 					  blocksize, false);
4936 	if (ret < 0) {
4937 		size_t write_bytes = blocksize;
4938 
4939 		if (btrfs_check_nocow_lock(inode, block_start, &write_bytes, false) > 0) {
4940 			/* For nocow case, no need to reserve data space. */
4941 			ASSERT(write_bytes == blocksize, "write_bytes=%zu blocksize=%u",
4942 			       write_bytes, blocksize);
4943 			only_release_metadata = true;
4944 		} else {
4945 			goto out;
4946 		}
4947 	}
4948 	ret = btrfs_delalloc_reserve_metadata(inode, blocksize, blocksize, false);
4949 	if (ret < 0) {
4950 		if (!only_release_metadata)
4951 			btrfs_free_reserved_data_space(inode, data_reserved,
4952 						       block_start, blocksize);
4953 		goto out;
4954 	}
4955 again:
4956 	folio = __filemap_get_folio(mapping, index,
4957 				    FGP_LOCK | FGP_ACCESSED | FGP_CREAT, mask);
4958 	if (IS_ERR(folio)) {
4959 		if (only_release_metadata)
4960 			btrfs_delalloc_release_metadata(inode, blocksize, true);
4961 		else
4962 			btrfs_delalloc_release_space(inode, data_reserved,
4963 						     block_start, blocksize, true);
4964 		btrfs_delalloc_release_extents(inode, blocksize);
4965 		ret = PTR_ERR(folio);
4966 		goto out;
4967 	}
4968 
4969 	if (!folio_test_uptodate(folio)) {
4970 		ret = btrfs_read_folio(NULL, folio);
4971 		folio_lock(folio);
4972 		if (folio->mapping != mapping) {
4973 			folio_unlock(folio);
4974 			folio_put(folio);
4975 			goto again;
4976 		}
4977 		if (unlikely(!folio_test_uptodate(folio))) {
4978 			ret = -EIO;
4979 			goto out_unlock;
4980 		}
4981 	}
4982 
4983 	/*
4984 	 * We unlock the page after the io is completed and then re-lock it
4985 	 * above.  release_folio() could have come in between that and cleared
4986 	 * folio private, but left the page in the mapping.  Set the page mapped
4987 	 * here to make sure it's properly set for the subpage stuff.
4988 	 */
4989 	ret = set_folio_extent_mapped(folio);
4990 	if (ret < 0)
4991 		goto out_unlock;
4992 
4993 	folio_wait_writeback(folio);
4994 
4995 	btrfs_lock_extent(io_tree, block_start, block_end, &cached_state);
4996 
4997 	ordered = btrfs_lookup_ordered_extent(inode, block_start);
4998 	if (ordered) {
4999 		btrfs_unlock_extent(io_tree, block_start, block_end, &cached_state);
5000 		folio_unlock(folio);
5001 		folio_put(folio);
5002 		btrfs_start_ordered_extent(ordered);
5003 		btrfs_put_ordered_extent(ordered);
5004 		goto again;
5005 	}
5006 
5007 	ret = btrfs_reset_extent_delalloc(inode, block_start, block_end, 0, &cached_state);
5008 	if (ret) {
5009 		btrfs_unlock_extent(io_tree, block_start, block_end, &cached_state);
5010 		goto out_unlock;
5011 	}
5012 
5013 	if (end == (u64)-1) {
5014 		/*
5015 		 * We're truncating beyond EOF, the remaining blocks normally are
5016 		 * already holes thus no need to zero again, but it's possible for
5017 		 * fs block size < page size cases to have memory mapped writes
5018 		 * to pollute ranges beyond EOF.
5019 		 *
5020 		 * In that case although such polluted blocks beyond EOF will
5021 		 * not reach disk, it still affects our page caches.
5022 		 */
5023 		zero_start = max_t(u64, folio_pos(folio), start);
5024 		zero_end = min_t(u64, folio_next_pos(folio) - 1, end);
5025 	} else {
5026 		zero_start = max_t(u64, block_start, start);
5027 		zero_end = min_t(u64, block_end, end);
5028 	}
5029 	folio_zero_range(folio, zero_start - folio_pos(folio),
5030 			 zero_end - zero_start + 1);
5031 
5032 	btrfs_folio_set_dirty(fs_info, folio, block_start,
5033 			      block_end + 1 - block_start);
5034 
5035 	if (only_release_metadata)
5036 		btrfs_set_extent_bit(&inode->io_tree, block_start, block_end,
5037 				     EXTENT_NORESERVE, &cached_state);
5038 
5039 	btrfs_unlock_extent(io_tree, block_start, block_end, &cached_state);
5040 
5041 out_unlock:
5042 	if (ret) {
5043 		if (only_release_metadata)
5044 			btrfs_delalloc_release_metadata(inode, blocksize, true);
5045 		else
5046 			btrfs_delalloc_release_space(inode, data_reserved,
5047 					block_start, blocksize, true);
5048 	}
5049 	btrfs_delalloc_release_extents(inode, blocksize);
5050 	folio_unlock(folio);
5051 	folio_put(folio);
5052 out:
5053 	if (only_release_metadata)
5054 		btrfs_check_nocow_unlock(inode);
5055 	extent_changeset_free(data_reserved);
5056 	return ret;
5057 }
5058 
5059 static int maybe_insert_hole(struct btrfs_inode *inode, u64 offset, u64 len)
5060 {
5061 	struct btrfs_root *root = inode->root;
5062 	struct btrfs_fs_info *fs_info = root->fs_info;
5063 	struct btrfs_trans_handle *trans;
5064 	struct btrfs_drop_extents_args drop_args = { 0 };
5065 	int ret;
5066 
5067 	/*
5068 	 * If NO_HOLES is enabled, we don't need to do anything.
5069 	 * Later, up in the call chain, either btrfs_set_inode_last_sub_trans()
5070 	 * or btrfs_update_inode() will be called, which guarantee that the next
5071 	 * fsync will know this inode was changed and needs to be logged.
5072 	 */
5073 	if (btrfs_fs_incompat(fs_info, NO_HOLES))
5074 		return 0;
5075 
5076 	/*
5077 	 * 1 - for the one we're dropping
5078 	 * 1 - for the one we're adding
5079 	 * 1 - for updating the inode.
5080 	 */
5081 	trans = btrfs_start_transaction(root, 3);
5082 	if (IS_ERR(trans))
5083 		return PTR_ERR(trans);
5084 
5085 	drop_args.start = offset;
5086 	drop_args.end = offset + len;
5087 	drop_args.drop_cache = true;
5088 
5089 	ret = btrfs_drop_extents(trans, root, inode, &drop_args);
5090 	if (unlikely(ret)) {
5091 		btrfs_abort_transaction(trans, ret);
5092 		btrfs_end_transaction(trans);
5093 		return ret;
5094 	}
5095 
5096 	ret = btrfs_insert_hole_extent(trans, root, btrfs_ino(inode), offset, len);
5097 	if (ret) {
5098 		btrfs_abort_transaction(trans, ret);
5099 	} else {
5100 		btrfs_update_inode_bytes(inode, 0, drop_args.bytes_found);
5101 		btrfs_update_inode(trans, inode);
5102 	}
5103 	btrfs_end_transaction(trans);
5104 	return ret;
5105 }
5106 
5107 /*
5108  * This function puts in dummy file extents for the area we're creating a hole
5109  * for.  So if we are truncating this file to a larger size we need to insert
5110  * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
5111  * the range between oldsize and size
5112  */
5113 int btrfs_cont_expand(struct btrfs_inode *inode, loff_t oldsize, loff_t size)
5114 {
5115 	struct btrfs_root *root = inode->root;
5116 	struct btrfs_fs_info *fs_info = root->fs_info;
5117 	struct extent_io_tree *io_tree = &inode->io_tree;
5118 	struct extent_map *em = NULL;
5119 	struct extent_state *cached_state = NULL;
5120 	u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
5121 	u64 block_end = ALIGN(size, fs_info->sectorsize);
5122 	u64 last_byte;
5123 	u64 cur_offset;
5124 	u64 hole_size;
5125 	int ret = 0;
5126 
5127 	/*
5128 	 * If our size started in the middle of a block we need to zero out the
5129 	 * rest of the block before we expand the i_size, otherwise we could
5130 	 * expose stale data.
5131 	 */
5132 	ret = btrfs_truncate_block(inode, oldsize, oldsize, -1);
5133 	if (ret)
5134 		return ret;
5135 
5136 	if (size <= hole_start)
5137 		return 0;
5138 
5139 	btrfs_lock_and_flush_ordered_range(inode, hole_start, block_end - 1,
5140 					   &cached_state);
5141 	cur_offset = hole_start;
5142 	while (1) {
5143 		em = btrfs_get_extent(inode, NULL, cur_offset, block_end - cur_offset);
5144 		if (IS_ERR(em)) {
5145 			ret = PTR_ERR(em);
5146 			em = NULL;
5147 			break;
5148 		}
5149 		last_byte = min(btrfs_extent_map_end(em), block_end);
5150 		last_byte = ALIGN(last_byte, fs_info->sectorsize);
5151 		hole_size = last_byte - cur_offset;
5152 
5153 		if (!(em->flags & EXTENT_FLAG_PREALLOC)) {
5154 			struct extent_map *hole_em;
5155 
5156 			ret = maybe_insert_hole(inode, cur_offset, hole_size);
5157 			if (ret)
5158 				break;
5159 
5160 			ret = btrfs_inode_set_file_extent_range(inode,
5161 							cur_offset, hole_size);
5162 			if (ret)
5163 				break;
5164 
5165 			hole_em = btrfs_alloc_extent_map();
5166 			if (!hole_em) {
5167 				btrfs_drop_extent_map_range(inode, cur_offset,
5168 						    cur_offset + hole_size - 1,
5169 						    false);
5170 				btrfs_set_inode_full_sync(inode);
5171 				goto next;
5172 			}
5173 			hole_em->start = cur_offset;
5174 			hole_em->len = hole_size;
5175 
5176 			hole_em->disk_bytenr = EXTENT_MAP_HOLE;
5177 			hole_em->disk_num_bytes = 0;
5178 			hole_em->ram_bytes = hole_size;
5179 			hole_em->generation = btrfs_get_fs_generation(fs_info);
5180 
5181 			ret = btrfs_replace_extent_map_range(inode, hole_em, true);
5182 			btrfs_free_extent_map(hole_em);
5183 		} else {
5184 			ret = btrfs_inode_set_file_extent_range(inode,
5185 							cur_offset, hole_size);
5186 			if (ret)
5187 				break;
5188 		}
5189 next:
5190 		btrfs_free_extent_map(em);
5191 		em = NULL;
5192 		cur_offset = last_byte;
5193 		if (cur_offset >= block_end)
5194 			break;
5195 	}
5196 	btrfs_free_extent_map(em);
5197 	btrfs_unlock_extent(io_tree, hole_start, block_end - 1, &cached_state);
5198 	return ret;
5199 }
5200 
5201 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5202 {
5203 	struct btrfs_root *root = BTRFS_I(inode)->root;
5204 	struct btrfs_trans_handle *trans;
5205 	loff_t oldsize = i_size_read(inode);
5206 	loff_t newsize = attr->ia_size;
5207 	int mask = attr->ia_valid;
5208 	int ret;
5209 
5210 	/*
5211 	 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5212 	 * special case where we need to update the times despite not having
5213 	 * these flags set.  For all other operations the VFS set these flags
5214 	 * explicitly if it wants a timestamp update.
5215 	 */
5216 	if (newsize != oldsize) {
5217 		inode_inc_iversion(inode);
5218 		if (!(mask & (ATTR_CTIME | ATTR_MTIME))) {
5219 			inode_set_mtime_to_ts(inode,
5220 					      inode_set_ctime_current(inode));
5221 		}
5222 	}
5223 
5224 	if (newsize > oldsize) {
5225 		/*
5226 		 * Don't do an expanding truncate while snapshotting is ongoing.
5227 		 * This is to ensure the snapshot captures a fully consistent
5228 		 * state of this file - if the snapshot captures this expanding
5229 		 * truncation, it must capture all writes that happened before
5230 		 * this truncation.
5231 		 */
5232 		btrfs_drew_write_lock(&root->snapshot_lock);
5233 		ret = btrfs_cont_expand(BTRFS_I(inode), oldsize, newsize);
5234 		if (ret) {
5235 			btrfs_drew_write_unlock(&root->snapshot_lock);
5236 			return ret;
5237 		}
5238 
5239 		trans = btrfs_start_transaction(root, 1);
5240 		if (IS_ERR(trans)) {
5241 			btrfs_drew_write_unlock(&root->snapshot_lock);
5242 			return PTR_ERR(trans);
5243 		}
5244 
5245 		i_size_write(inode, newsize);
5246 		btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
5247 		pagecache_isize_extended(inode, oldsize, newsize);
5248 		ret = btrfs_update_inode(trans, BTRFS_I(inode));
5249 		btrfs_drew_write_unlock(&root->snapshot_lock);
5250 		btrfs_end_transaction(trans);
5251 	} else {
5252 		struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
5253 
5254 		if (btrfs_is_zoned(fs_info)) {
5255 			ret = btrfs_wait_ordered_range(BTRFS_I(inode),
5256 					ALIGN(newsize, fs_info->sectorsize),
5257 					(u64)-1);
5258 			if (ret)
5259 				return ret;
5260 		}
5261 
5262 		/*
5263 		 * We're truncating a file that used to have good data down to
5264 		 * zero. Make sure any new writes to the file get on disk
5265 		 * on close.
5266 		 */
5267 		if (newsize == 0 && oldsize != 0)
5268 			set_bit(BTRFS_INODE_FLUSH_ON_CLOSE,
5269 				&BTRFS_I(inode)->runtime_flags);
5270 
5271 		truncate_setsize(inode, newsize);
5272 
5273 		inode_dio_wait(inode);
5274 
5275 		ret = btrfs_truncate(BTRFS_I(inode), newsize == oldsize);
5276 		if (ret && inode->i_nlink) {
5277 			int ret2;
5278 
5279 			/*
5280 			 * Truncate failed, so fix up the in-memory size. We
5281 			 * adjusted disk_i_size down as we removed extents, so
5282 			 * wait for disk_i_size to be stable and then update the
5283 			 * in-memory size to match.
5284 			 */
5285 			ret2 = btrfs_wait_ordered_range(BTRFS_I(inode), 0, (u64)-1);
5286 			if (ret2)
5287 				return ret2;
5288 			i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5289 		}
5290 	}
5291 
5292 	return ret;
5293 }
5294 
5295 static int btrfs_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
5296 			 struct iattr *attr)
5297 {
5298 	struct inode *inode = d_inode(dentry);
5299 	struct btrfs_root *root = BTRFS_I(inode)->root;
5300 	int ret;
5301 
5302 	if (btrfs_root_readonly(root))
5303 		return -EROFS;
5304 
5305 	ret = setattr_prepare(idmap, dentry, attr);
5306 	if (ret)
5307 		return ret;
5308 
5309 	if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5310 		ret = btrfs_setsize(inode, attr);
5311 		if (ret)
5312 			return ret;
5313 	}
5314 
5315 	if (attr->ia_valid) {
5316 		setattr_copy(idmap, inode, attr);
5317 		inode_inc_iversion(inode);
5318 		ret = btrfs_dirty_inode(BTRFS_I(inode));
5319 
5320 		if (!ret && attr->ia_valid & ATTR_MODE)
5321 			ret = posix_acl_chmod(idmap, dentry, inode->i_mode);
5322 	}
5323 
5324 	return ret;
5325 }
5326 
5327 /*
5328  * While truncating the inode pages during eviction, we get the VFS
5329  * calling btrfs_invalidate_folio() against each folio of the inode. This
5330  * is slow because the calls to btrfs_invalidate_folio() result in a
5331  * huge amount of calls to lock_extent() and clear_extent_bit(),
5332  * which keep merging and splitting extent_state structures over and over,
5333  * wasting lots of time.
5334  *
5335  * Therefore if the inode is being evicted, let btrfs_invalidate_folio()
5336  * skip all those expensive operations on a per folio basis and do only
5337  * the ordered io finishing, while we release here the extent_map and
5338  * extent_state structures, without the excessive merging and splitting.
5339  */
5340 static void evict_inode_truncate_pages(struct inode *inode)
5341 {
5342 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5343 	struct rb_node *node;
5344 
5345 	ASSERT(inode_state_read_once(inode) & I_FREEING);
5346 	truncate_inode_pages_final(&inode->i_data);
5347 
5348 	btrfs_drop_extent_map_range(BTRFS_I(inode), 0, (u64)-1, false);
5349 
5350 	/*
5351 	 * Keep looping until we have no more ranges in the io tree.
5352 	 * We can have ongoing bios started by readahead that have
5353 	 * their endio callback (extent_io.c:end_bio_extent_readpage)
5354 	 * still in progress (unlocked the pages in the bio but did not yet
5355 	 * unlocked the ranges in the io tree). Therefore this means some
5356 	 * ranges can still be locked and eviction started because before
5357 	 * submitting those bios, which are executed by a separate task (work
5358 	 * queue kthread), inode references (inode->i_count) were not taken
5359 	 * (which would be dropped in the end io callback of each bio).
5360 	 * Therefore here we effectively end up waiting for those bios and
5361 	 * anyone else holding locked ranges without having bumped the inode's
5362 	 * reference count - if we don't do it, when they access the inode's
5363 	 * io_tree to unlock a range it may be too late, leading to an
5364 	 * use-after-free issue.
5365 	 */
5366 	spin_lock(&io_tree->lock);
5367 	while (!RB_EMPTY_ROOT(&io_tree->state)) {
5368 		struct extent_state *state;
5369 		struct extent_state *cached_state = NULL;
5370 		u64 start;
5371 		u64 end;
5372 		unsigned state_flags;
5373 
5374 		node = rb_first(&io_tree->state);
5375 		state = rb_entry(node, struct extent_state, rb_node);
5376 		start = state->start;
5377 		end = state->end;
5378 		state_flags = state->state;
5379 		spin_unlock(&io_tree->lock);
5380 
5381 		btrfs_lock_extent(io_tree, start, end, &cached_state);
5382 
5383 		/*
5384 		 * If still has DELALLOC flag, the extent didn't reach disk,
5385 		 * and its reserved space won't be freed by delayed_ref.
5386 		 * So we need to free its reserved space here.
5387 		 * (Refer to comment in btrfs_invalidate_folio, case 2)
5388 		 *
5389 		 * Note, end is the bytenr of last byte, so we need + 1 here.
5390 		 */
5391 		if (state_flags & EXTENT_DELALLOC)
5392 			btrfs_qgroup_free_data(BTRFS_I(inode), NULL, start,
5393 					       end - start + 1, NULL);
5394 
5395 		btrfs_clear_extent_bit(io_tree, start, end,
5396 				       EXTENT_CLEAR_ALL_BITS | EXTENT_DO_ACCOUNTING,
5397 				       &cached_state);
5398 
5399 		cond_resched();
5400 		spin_lock(&io_tree->lock);
5401 	}
5402 	spin_unlock(&io_tree->lock);
5403 }
5404 
5405 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
5406 							struct btrfs_block_rsv *rsv)
5407 {
5408 	struct btrfs_fs_info *fs_info = root->fs_info;
5409 	struct btrfs_trans_handle *trans;
5410 	u64 delayed_refs_extra = btrfs_calc_delayed_ref_bytes(fs_info, 1);
5411 	int ret;
5412 
5413 	/*
5414 	 * Eviction should be taking place at some place safe because of our
5415 	 * delayed iputs.  However the normal flushing code will run delayed
5416 	 * iputs, so we cannot use FLUSH_ALL otherwise we'll deadlock.
5417 	 *
5418 	 * We reserve the delayed_refs_extra here again because we can't use
5419 	 * btrfs_start_transaction(root, 0) for the same deadlocky reason as
5420 	 * above.  We reserve our extra bit here because we generate a ton of
5421 	 * delayed refs activity by truncating.
5422 	 *
5423 	 * BTRFS_RESERVE_FLUSH_EVICT will steal from the global_rsv if it can,
5424 	 * if we fail to make this reservation we can re-try without the
5425 	 * delayed_refs_extra so we can make some forward progress.
5426 	 */
5427 	ret = btrfs_block_rsv_refill(fs_info, rsv, rsv->size + delayed_refs_extra,
5428 				     BTRFS_RESERVE_FLUSH_EVICT);
5429 	if (ret) {
5430 		ret = btrfs_block_rsv_refill(fs_info, rsv, rsv->size,
5431 					     BTRFS_RESERVE_FLUSH_EVICT);
5432 		if (ret) {
5433 			btrfs_warn(fs_info,
5434 				   "could not allocate space for delete; will truncate on mount");
5435 			return ERR_PTR(-ENOSPC);
5436 		}
5437 		delayed_refs_extra = 0;
5438 	}
5439 
5440 	trans = btrfs_join_transaction(root);
5441 	if (IS_ERR(trans))
5442 		return trans;
5443 
5444 	if (delayed_refs_extra) {
5445 		trans->block_rsv = &fs_info->trans_block_rsv;
5446 		trans->bytes_reserved = delayed_refs_extra;
5447 		btrfs_block_rsv_migrate(rsv, trans->block_rsv,
5448 					delayed_refs_extra, true);
5449 	}
5450 	return trans;
5451 }
5452 
5453 void btrfs_evict_inode(struct inode *inode)
5454 {
5455 	struct btrfs_fs_info *fs_info;
5456 	struct btrfs_trans_handle *trans;
5457 	struct btrfs_root *root = BTRFS_I(inode)->root;
5458 	struct btrfs_block_rsv rsv;
5459 	int ret;
5460 
5461 	trace_btrfs_inode_evict(inode);
5462 
5463 	if (!root)
5464 		goto clear_inode;
5465 
5466 	fs_info = inode_to_fs_info(inode);
5467 	evict_inode_truncate_pages(inode);
5468 
5469 	if (inode->i_nlink &&
5470 	    ((btrfs_root_refs(&root->root_item) != 0 &&
5471 	      btrfs_root_id(root) != BTRFS_ROOT_TREE_OBJECTID) ||
5472 	     btrfs_is_free_space_inode(BTRFS_I(inode))))
5473 		goto out;
5474 
5475 	if (is_bad_inode(inode))
5476 		goto out;
5477 
5478 	if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5479 		goto out;
5480 
5481 	if (inode->i_nlink > 0) {
5482 		BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5483 		       btrfs_root_id(root) != BTRFS_ROOT_TREE_OBJECTID);
5484 		goto out;
5485 	}
5486 
5487 	/*
5488 	 * This makes sure the inode item in tree is uptodate and the space for
5489 	 * the inode update is released.
5490 	 */
5491 	ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5492 	if (ret)
5493 		goto out;
5494 
5495 	/*
5496 	 * This drops any pending insert or delete operations we have for this
5497 	 * inode.  We could have a delayed dir index deletion queued up, but
5498 	 * we're removing the inode completely so that'll be taken care of in
5499 	 * the truncate.
5500 	 */
5501 	btrfs_kill_delayed_inode_items(BTRFS_I(inode));
5502 
5503 	btrfs_init_metadata_block_rsv(fs_info, &rsv, BTRFS_BLOCK_RSV_TEMP);
5504 	rsv.size = btrfs_calc_metadata_size(fs_info, 1);
5505 	rsv.failfast = true;
5506 
5507 	btrfs_i_size_write(BTRFS_I(inode), 0);
5508 
5509 	while (1) {
5510 		struct btrfs_truncate_control control = {
5511 			.inode = BTRFS_I(inode),
5512 			.ino = btrfs_ino(BTRFS_I(inode)),
5513 			.new_size = 0,
5514 			.min_type = 0,
5515 		};
5516 
5517 		trans = evict_refill_and_join(root, &rsv);
5518 		if (IS_ERR(trans))
5519 			goto out_release;
5520 
5521 		trans->block_rsv = &rsv;
5522 
5523 		ret = btrfs_truncate_inode_items(trans, root, &control);
5524 		trans->block_rsv = &fs_info->trans_block_rsv;
5525 		btrfs_end_transaction(trans);
5526 		/*
5527 		 * We have not added new delayed items for our inode after we
5528 		 * have flushed its delayed items, so no need to throttle on
5529 		 * delayed items. However we have modified extent buffers.
5530 		 */
5531 		btrfs_btree_balance_dirty_nodelay(fs_info);
5532 		if (ret && ret != -ENOSPC && ret != -EAGAIN)
5533 			goto out_release;
5534 		else if (!ret)
5535 			break;
5536 	}
5537 
5538 	/*
5539 	 * Errors here aren't a big deal, it just means we leave orphan items in
5540 	 * the tree. They will be cleaned up on the next mount. If the inode
5541 	 * number gets reused, cleanup deletes the orphan item without doing
5542 	 * anything, and unlink reuses the existing orphan item.
5543 	 *
5544 	 * If it turns out that we are dropping too many of these, we might want
5545 	 * to add a mechanism for retrying these after a commit.
5546 	 */
5547 	trans = evict_refill_and_join(root, &rsv);
5548 	if (!IS_ERR(trans)) {
5549 		trans->block_rsv = &rsv;
5550 		btrfs_orphan_del(trans, BTRFS_I(inode));
5551 		trans->block_rsv = &fs_info->trans_block_rsv;
5552 		btrfs_end_transaction(trans);
5553 	}
5554 
5555 out_release:
5556 	btrfs_block_rsv_release(fs_info, &rsv, (u64)-1, NULL);
5557 out:
5558 	/*
5559 	 * If we didn't successfully delete, the orphan item will still be in
5560 	 * the tree and we'll retry on the next mount. Again, we might also want
5561 	 * to retry these periodically in the future.
5562 	 */
5563 	btrfs_remove_delayed_node(BTRFS_I(inode));
5564 clear_inode:
5565 	clear_inode(inode);
5566 }
5567 
5568 /*
5569  * Return the key found in the dir entry in the location pointer, fill @type
5570  * with BTRFS_FT_*, and return 0.
5571  *
5572  * If no dir entries were found, returns -ENOENT.
5573  * If found a corrupted location in dir entry, returns -EUCLEAN.
5574  */
5575 static int btrfs_inode_by_name(struct btrfs_inode *dir, struct dentry *dentry,
5576 			       struct btrfs_key *location, u8 *type)
5577 {
5578 	struct btrfs_dir_item *di;
5579 	BTRFS_PATH_AUTO_FREE(path);
5580 	struct btrfs_root *root = dir->root;
5581 	int ret = 0;
5582 	struct fscrypt_name fname;
5583 
5584 	path = btrfs_alloc_path();
5585 	if (!path)
5586 		return -ENOMEM;
5587 
5588 	ret = fscrypt_setup_filename(&dir->vfs_inode, &dentry->d_name, 1, &fname);
5589 	if (ret < 0)
5590 		return ret;
5591 	/*
5592 	 * fscrypt_setup_filename() should never return a positive value, but
5593 	 * gcc on sparc/parisc thinks it can, so assert that doesn't happen.
5594 	 */
5595 	ASSERT(ret == 0);
5596 
5597 	/* This needs to handle no-key deletions later on */
5598 
5599 	di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir),
5600 				   &fname.disk_name, 0);
5601 	if (IS_ERR_OR_NULL(di)) {
5602 		ret = di ? PTR_ERR(di) : -ENOENT;
5603 		goto out;
5604 	}
5605 
5606 	btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5607 	if (unlikely(location->type != BTRFS_INODE_ITEM_KEY &&
5608 		     location->type != BTRFS_ROOT_ITEM_KEY)) {
5609 		ret = -EUCLEAN;
5610 		btrfs_warn(root->fs_info,
5611 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location " BTRFS_KEY_FMT ")",
5612 			   __func__, fname.disk_name.name, btrfs_ino(dir),
5613 			   BTRFS_KEY_FMT_VALUE(location));
5614 	}
5615 	if (!ret)
5616 		*type = btrfs_dir_ftype(path->nodes[0], di);
5617 out:
5618 	fscrypt_free_filename(&fname);
5619 	return ret;
5620 }
5621 
5622 /*
5623  * when we hit a tree root in a directory, the btrfs part of the inode
5624  * needs to be changed to reflect the root directory of the tree root.  This
5625  * is kind of like crossing a mount point.
5626  */
5627 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5628 				    struct btrfs_inode *dir,
5629 				    struct dentry *dentry,
5630 				    struct btrfs_key *location,
5631 				    struct btrfs_root **sub_root)
5632 {
5633 	BTRFS_PATH_AUTO_FREE(path);
5634 	struct btrfs_root *new_root;
5635 	struct btrfs_root_ref *ref;
5636 	struct extent_buffer *leaf;
5637 	struct btrfs_key key;
5638 	int ret;
5639 	int err = 0;
5640 	struct fscrypt_name fname;
5641 
5642 	ret = fscrypt_setup_filename(&dir->vfs_inode, &dentry->d_name, 0, &fname);
5643 	if (ret)
5644 		return ret;
5645 
5646 	path = btrfs_alloc_path();
5647 	if (!path) {
5648 		err = -ENOMEM;
5649 		goto out;
5650 	}
5651 
5652 	err = -ENOENT;
5653 	key.objectid = btrfs_root_id(dir->root);
5654 	key.type = BTRFS_ROOT_REF_KEY;
5655 	key.offset = location->objectid;
5656 
5657 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5658 	if (ret) {
5659 		if (ret < 0)
5660 			err = ret;
5661 		goto out;
5662 	}
5663 
5664 	leaf = path->nodes[0];
5665 	ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5666 	if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
5667 	    btrfs_root_ref_name_len(leaf, ref) != fname.disk_name.len)
5668 		goto out;
5669 
5670 	ret = memcmp_extent_buffer(leaf, fname.disk_name.name,
5671 				   (unsigned long)(ref + 1), fname.disk_name.len);
5672 	if (ret)
5673 		goto out;
5674 
5675 	btrfs_release_path(path);
5676 
5677 	new_root = btrfs_get_fs_root(fs_info, location->objectid, true);
5678 	if (IS_ERR(new_root)) {
5679 		err = PTR_ERR(new_root);
5680 		goto out;
5681 	}
5682 
5683 	*sub_root = new_root;
5684 	location->objectid = btrfs_root_dirid(&new_root->root_item);
5685 	location->type = BTRFS_INODE_ITEM_KEY;
5686 	location->offset = 0;
5687 	err = 0;
5688 out:
5689 	fscrypt_free_filename(&fname);
5690 	return err;
5691 }
5692 
5693 
5694 
5695 static void btrfs_del_inode_from_root(struct btrfs_inode *inode)
5696 {
5697 	struct btrfs_root *root = inode->root;
5698 	struct btrfs_inode *entry;
5699 	bool empty = false;
5700 
5701 	xa_lock(&root->inodes);
5702 	/*
5703 	 * This btrfs_inode is being freed and has already been unhashed at this
5704 	 * point. It's possible that another btrfs_inode has already been
5705 	 * allocated for the same inode and inserted itself into the root, so
5706 	 * don't delete it in that case.
5707 	 *
5708 	 * Note that this shouldn't need to allocate memory, so the gfp flags
5709 	 * don't really matter.
5710 	 */
5711 	entry = __xa_cmpxchg(&root->inodes, btrfs_ino(inode), inode, NULL,
5712 			     GFP_ATOMIC);
5713 	if (entry == inode)
5714 		empty = xa_empty(&root->inodes);
5715 	xa_unlock(&root->inodes);
5716 
5717 	if (empty && btrfs_root_refs(&root->root_item) == 0) {
5718 		xa_lock(&root->inodes);
5719 		empty = xa_empty(&root->inodes);
5720 		xa_unlock(&root->inodes);
5721 		if (empty)
5722 			btrfs_add_dead_root(root);
5723 	}
5724 }
5725 
5726 
5727 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5728 {
5729 	struct btrfs_iget_args *args = p;
5730 
5731 	btrfs_set_inode_number(BTRFS_I(inode), args->ino);
5732 	BTRFS_I(inode)->root = btrfs_grab_root(args->root);
5733 
5734 	if (args->root && args->root == args->root->fs_info->tree_root &&
5735 	    args->ino != BTRFS_BTREE_INODE_OBJECTID)
5736 		set_bit(BTRFS_INODE_FREE_SPACE_INODE,
5737 			&BTRFS_I(inode)->runtime_flags);
5738 	return 0;
5739 }
5740 
5741 static int btrfs_find_actor(struct inode *inode, void *opaque)
5742 {
5743 	struct btrfs_iget_args *args = opaque;
5744 
5745 	return args->ino == btrfs_ino(BTRFS_I(inode)) &&
5746 		args->root == BTRFS_I(inode)->root;
5747 }
5748 
5749 static struct btrfs_inode *btrfs_iget_locked(u64 ino, struct btrfs_root *root)
5750 {
5751 	struct inode *inode;
5752 	struct btrfs_iget_args args;
5753 	unsigned long hashval = btrfs_inode_hash(ino, root);
5754 
5755 	args.ino = ino;
5756 	args.root = root;
5757 
5758 	inode = iget5_locked_rcu(root->fs_info->sb, hashval, btrfs_find_actor,
5759 			     btrfs_init_locked_inode,
5760 			     (void *)&args);
5761 	if (!inode)
5762 		return NULL;
5763 	return BTRFS_I(inode);
5764 }
5765 
5766 /*
5767  * Get an inode object given its inode number and corresponding root.  Path is
5768  * preallocated to prevent recursing back to iget through allocator.
5769  */
5770 struct btrfs_inode *btrfs_iget_path(u64 ino, struct btrfs_root *root,
5771 				    struct btrfs_path *path)
5772 {
5773 	struct btrfs_inode *inode;
5774 	int ret;
5775 
5776 	inode = btrfs_iget_locked(ino, root);
5777 	if (!inode)
5778 		return ERR_PTR(-ENOMEM);
5779 
5780 	if (!(inode_state_read_once(&inode->vfs_inode) & I_NEW))
5781 		return inode;
5782 
5783 	ret = btrfs_read_locked_inode(inode, path);
5784 	if (ret)
5785 		return ERR_PTR(ret);
5786 
5787 	unlock_new_inode(&inode->vfs_inode);
5788 	return inode;
5789 }
5790 
5791 /*
5792  * Get an inode object given its inode number and corresponding root.
5793  */
5794 struct btrfs_inode *btrfs_iget(u64 ino, struct btrfs_root *root)
5795 {
5796 	struct btrfs_inode *inode;
5797 	struct btrfs_path *path;
5798 	int ret;
5799 
5800 	inode = btrfs_iget_locked(ino, root);
5801 	if (!inode)
5802 		return ERR_PTR(-ENOMEM);
5803 
5804 	if (!(inode_state_read_once(&inode->vfs_inode) & I_NEW))
5805 		return inode;
5806 
5807 	path = btrfs_alloc_path();
5808 	if (!path) {
5809 		iget_failed(&inode->vfs_inode);
5810 		return ERR_PTR(-ENOMEM);
5811 	}
5812 
5813 	ret = btrfs_read_locked_inode(inode, path);
5814 	btrfs_free_path(path);
5815 	if (ret)
5816 		return ERR_PTR(ret);
5817 
5818 	if (S_ISDIR(inode->vfs_inode.i_mode))
5819 		inode->vfs_inode.i_opflags |= IOP_FASTPERM_MAY_EXEC;
5820 	unlock_new_inode(&inode->vfs_inode);
5821 	return inode;
5822 }
5823 
5824 static struct btrfs_inode *new_simple_dir(struct inode *dir,
5825 					  struct btrfs_key *key,
5826 					  struct btrfs_root *root)
5827 {
5828 	struct timespec64 ts;
5829 	struct inode *vfs_inode;
5830 	struct btrfs_inode *inode;
5831 
5832 	vfs_inode = new_inode(dir->i_sb);
5833 	if (!vfs_inode)
5834 		return ERR_PTR(-ENOMEM);
5835 
5836 	inode = BTRFS_I(vfs_inode);
5837 	inode->root = btrfs_grab_root(root);
5838 	inode->ref_root_id = key->objectid;
5839 	set_bit(BTRFS_INODE_ROOT_STUB, &inode->runtime_flags);
5840 	set_bit(BTRFS_INODE_DUMMY, &inode->runtime_flags);
5841 
5842 	btrfs_set_inode_number(inode, BTRFS_EMPTY_SUBVOL_DIR_OBJECTID);
5843 	/*
5844 	 * We only need lookup, the rest is read-only and there's no inode
5845 	 * associated with the dentry
5846 	 */
5847 	vfs_inode->i_op = &simple_dir_inode_operations;
5848 	vfs_inode->i_opflags &= ~IOP_XATTR;
5849 	vfs_inode->i_fop = &simple_dir_operations;
5850 	vfs_inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
5851 
5852 	ts = inode_set_ctime_current(vfs_inode);
5853 	inode_set_mtime_to_ts(vfs_inode, ts);
5854 	inode_set_atime_to_ts(vfs_inode, inode_get_atime(dir));
5855 	inode->i_otime_sec = ts.tv_sec;
5856 	inode->i_otime_nsec = ts.tv_nsec;
5857 
5858 	vfs_inode->i_uid = dir->i_uid;
5859 	vfs_inode->i_gid = dir->i_gid;
5860 
5861 	return inode;
5862 }
5863 
5864 static_assert(BTRFS_FT_UNKNOWN == FT_UNKNOWN);
5865 static_assert(BTRFS_FT_REG_FILE == FT_REG_FILE);
5866 static_assert(BTRFS_FT_DIR == FT_DIR);
5867 static_assert(BTRFS_FT_CHRDEV == FT_CHRDEV);
5868 static_assert(BTRFS_FT_BLKDEV == FT_BLKDEV);
5869 static_assert(BTRFS_FT_FIFO == FT_FIFO);
5870 static_assert(BTRFS_FT_SOCK == FT_SOCK);
5871 static_assert(BTRFS_FT_SYMLINK == FT_SYMLINK);
5872 
5873 static inline u8 btrfs_inode_type(const struct btrfs_inode *inode)
5874 {
5875 	return fs_umode_to_ftype(inode->vfs_inode.i_mode);
5876 }
5877 
5878 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
5879 {
5880 	struct btrfs_fs_info *fs_info = inode_to_fs_info(dir);
5881 	struct btrfs_inode *inode;
5882 	struct btrfs_root *root = BTRFS_I(dir)->root;
5883 	struct btrfs_root *sub_root = root;
5884 	struct btrfs_key location = { 0 };
5885 	u8 di_type = 0;
5886 	int ret = 0;
5887 
5888 	if (dentry->d_name.len > BTRFS_NAME_LEN)
5889 		return ERR_PTR(-ENAMETOOLONG);
5890 
5891 	ret = btrfs_inode_by_name(BTRFS_I(dir), dentry, &location, &di_type);
5892 	if (ret < 0)
5893 		return ERR_PTR(ret);
5894 
5895 	if (location.type == BTRFS_INODE_ITEM_KEY) {
5896 		inode = btrfs_iget(location.objectid, root);
5897 		if (IS_ERR(inode))
5898 			return ERR_CAST(inode);
5899 
5900 		/* Do extra check against inode mode with di_type */
5901 		if (unlikely(btrfs_inode_type(inode) != di_type)) {
5902 			btrfs_crit(fs_info,
5903 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
5904 				  inode->vfs_inode.i_mode, btrfs_inode_type(inode),
5905 				  di_type);
5906 			iput(&inode->vfs_inode);
5907 			return ERR_PTR(-EUCLEAN);
5908 		}
5909 		return &inode->vfs_inode;
5910 	}
5911 
5912 	ret = fixup_tree_root_location(fs_info, BTRFS_I(dir), dentry,
5913 				       &location, &sub_root);
5914 	if (ret < 0) {
5915 		if (ret != -ENOENT)
5916 			inode = ERR_PTR(ret);
5917 		else
5918 			inode = new_simple_dir(dir, &location, root);
5919 	} else {
5920 		inode = btrfs_iget(location.objectid, sub_root);
5921 		btrfs_put_root(sub_root);
5922 
5923 		if (IS_ERR(inode))
5924 			return ERR_CAST(inode);
5925 
5926 		down_read(&fs_info->cleanup_work_sem);
5927 		if (!sb_rdonly(inode->vfs_inode.i_sb))
5928 			ret = btrfs_orphan_cleanup(sub_root);
5929 		up_read(&fs_info->cleanup_work_sem);
5930 		if (ret) {
5931 			iput(&inode->vfs_inode);
5932 			inode = ERR_PTR(ret);
5933 		}
5934 	}
5935 
5936 	if (IS_ERR(inode))
5937 		return ERR_CAST(inode);
5938 
5939 	return &inode->vfs_inode;
5940 }
5941 
5942 static int btrfs_dentry_delete(const struct dentry *dentry)
5943 {
5944 	struct btrfs_root *root;
5945 	struct inode *inode = d_inode(dentry);
5946 
5947 	if (!inode && !IS_ROOT(dentry))
5948 		inode = d_inode(dentry->d_parent);
5949 
5950 	if (inode) {
5951 		root = BTRFS_I(inode)->root;
5952 		if (btrfs_root_refs(&root->root_item) == 0)
5953 			return 1;
5954 
5955 		if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
5956 			return 1;
5957 	}
5958 	return 0;
5959 }
5960 
5961 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
5962 				   unsigned int flags)
5963 {
5964 	struct inode *inode = btrfs_lookup_dentry(dir, dentry);
5965 
5966 	if (inode == ERR_PTR(-ENOENT))
5967 		inode = NULL;
5968 	return d_splice_alias(inode, dentry);
5969 }
5970 
5971 /*
5972  * Find the highest existing sequence number in a directory and then set the
5973  * in-memory index_cnt variable to the first free sequence number.
5974  */
5975 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
5976 {
5977 	struct btrfs_root *root = inode->root;
5978 	struct btrfs_key key, found_key;
5979 	BTRFS_PATH_AUTO_FREE(path);
5980 	struct extent_buffer *leaf;
5981 	int ret;
5982 
5983 	key.objectid = btrfs_ino(inode);
5984 	key.type = BTRFS_DIR_INDEX_KEY;
5985 	key.offset = (u64)-1;
5986 
5987 	path = btrfs_alloc_path();
5988 	if (!path)
5989 		return -ENOMEM;
5990 
5991 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
5992 	if (ret < 0)
5993 		return ret;
5994 
5995 	if (unlikely(ret == 0)) {
5996 		/*
5997 		 * Key with offset -1 found, there would have to exist a dir
5998 		 * index item with such offset, but this is out of the valid
5999 		 * range.
6000 		 */
6001 		btrfs_err(root->fs_info,
6002 			  "unexpected exact match for DIR_INDEX key, inode %llu",
6003 			  btrfs_ino(inode));
6004 		return -EUCLEAN;
6005 	}
6006 
6007 	if (path->slots[0] == 0) {
6008 		inode->index_cnt = BTRFS_DIR_START_INDEX;
6009 		return 0;
6010 	}
6011 
6012 	path->slots[0]--;
6013 
6014 	leaf = path->nodes[0];
6015 	btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6016 
6017 	if (found_key.objectid != btrfs_ino(inode) ||
6018 	    found_key.type != BTRFS_DIR_INDEX_KEY) {
6019 		inode->index_cnt = BTRFS_DIR_START_INDEX;
6020 		return 0;
6021 	}
6022 
6023 	inode->index_cnt = found_key.offset + 1;
6024 
6025 	return 0;
6026 }
6027 
6028 static int btrfs_get_dir_last_index(struct btrfs_inode *dir, u64 *index)
6029 {
6030 	int ret = 0;
6031 
6032 	btrfs_inode_lock(dir, 0);
6033 	if (dir->index_cnt == (u64)-1) {
6034 		ret = btrfs_inode_delayed_dir_index_count(dir);
6035 		if (ret) {
6036 			ret = btrfs_set_inode_index_count(dir);
6037 			if (ret)
6038 				goto out;
6039 		}
6040 	}
6041 
6042 	/* index_cnt is the index number of next new entry, so decrement it. */
6043 	*index = dir->index_cnt - 1;
6044 out:
6045 	btrfs_inode_unlock(dir, 0);
6046 
6047 	return ret;
6048 }
6049 
6050 /*
6051  * All this infrastructure exists because dir_emit can fault, and we are holding
6052  * the tree lock when doing readdir.  For now just allocate a buffer and copy
6053  * our information into that, and then dir_emit from the buffer.  This is
6054  * similar to what NFS does, only we don't keep the buffer around in pagecache
6055  * because I'm afraid I'll mess that up.  Long term we need to make filldir do
6056  * copy_to_user_inatomic so we don't have to worry about page faulting under the
6057  * tree lock.
6058  */
6059 static int btrfs_opendir(struct inode *inode, struct file *file)
6060 {
6061 	struct btrfs_file_private *private;
6062 	u64 last_index;
6063 	int ret;
6064 
6065 	ret = btrfs_get_dir_last_index(BTRFS_I(inode), &last_index);
6066 	if (ret)
6067 		return ret;
6068 
6069 	private = kzalloc_obj(struct btrfs_file_private);
6070 	if (!private)
6071 		return -ENOMEM;
6072 	private->last_index = last_index;
6073 	private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
6074 	if (!private->filldir_buf) {
6075 		kfree(private);
6076 		return -ENOMEM;
6077 	}
6078 	file->private_data = private;
6079 	return 0;
6080 }
6081 
6082 static loff_t btrfs_dir_llseek(struct file *file, loff_t offset, int whence)
6083 {
6084 	struct btrfs_file_private *private = file->private_data;
6085 	int ret;
6086 
6087 	ret = btrfs_get_dir_last_index(BTRFS_I(file_inode(file)),
6088 				       &private->last_index);
6089 	if (ret)
6090 		return ret;
6091 
6092 	return generic_file_llseek(file, offset, whence);
6093 }
6094 
6095 struct dir_entry {
6096 	u64 ino;
6097 	u64 offset;
6098 	unsigned type;
6099 	int name_len;
6100 };
6101 
6102 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
6103 {
6104 	while (entries--) {
6105 		struct dir_entry *entry = addr;
6106 		char *name = (char *)(entry + 1);
6107 
6108 		ctx->pos = get_unaligned(&entry->offset);
6109 		if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
6110 					 get_unaligned(&entry->ino),
6111 					 get_unaligned(&entry->type)))
6112 			return 1;
6113 		addr += sizeof(struct dir_entry) +
6114 			get_unaligned(&entry->name_len);
6115 		ctx->pos++;
6116 	}
6117 	return 0;
6118 }
6119 
6120 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
6121 {
6122 	struct inode *inode = file_inode(file);
6123 	struct btrfs_root *root = BTRFS_I(inode)->root;
6124 	struct btrfs_file_private *private = file->private_data;
6125 	struct btrfs_dir_item *di;
6126 	struct btrfs_key key;
6127 	struct btrfs_key found_key;
6128 	BTRFS_PATH_AUTO_FREE(path);
6129 	void *addr;
6130 	LIST_HEAD(ins_list);
6131 	LIST_HEAD(del_list);
6132 	int ret;
6133 	char *name_ptr;
6134 	int name_len;
6135 	int entries = 0;
6136 	int total_len = 0;
6137 	bool put = false;
6138 	struct btrfs_key location;
6139 
6140 	if (!dir_emit_dots(file, ctx))
6141 		return 0;
6142 
6143 	path = btrfs_alloc_path();
6144 	if (!path)
6145 		return -ENOMEM;
6146 
6147 	addr = private->filldir_buf;
6148 	path->reada = READA_FORWARD;
6149 
6150 	put = btrfs_readdir_get_delayed_items(BTRFS_I(inode), private->last_index,
6151 					      &ins_list, &del_list);
6152 
6153 again:
6154 	key.type = BTRFS_DIR_INDEX_KEY;
6155 	key.offset = ctx->pos;
6156 	key.objectid = btrfs_ino(BTRFS_I(inode));
6157 
6158 	btrfs_for_each_slot(root, &key, &found_key, path, ret) {
6159 		struct dir_entry *entry;
6160 		struct extent_buffer *leaf = path->nodes[0];
6161 		u8 ftype;
6162 
6163 		if (found_key.objectid != key.objectid)
6164 			break;
6165 		if (found_key.type != BTRFS_DIR_INDEX_KEY)
6166 			break;
6167 		if (found_key.offset < ctx->pos)
6168 			continue;
6169 		if (found_key.offset > private->last_index)
6170 			break;
6171 		if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
6172 			continue;
6173 		di = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item);
6174 		name_len = btrfs_dir_name_len(leaf, di);
6175 		if ((total_len + sizeof(struct dir_entry) + name_len) >=
6176 		    PAGE_SIZE) {
6177 			btrfs_release_path(path);
6178 			ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6179 			if (ret)
6180 				goto nopos;
6181 			addr = private->filldir_buf;
6182 			entries = 0;
6183 			total_len = 0;
6184 			goto again;
6185 		}
6186 
6187 		ftype = btrfs_dir_flags_to_ftype(btrfs_dir_flags(leaf, di));
6188 		entry = addr;
6189 		name_ptr = (char *)(entry + 1);
6190 		read_extent_buffer(leaf, name_ptr,
6191 				   (unsigned long)(di + 1), name_len);
6192 		put_unaligned(name_len, &entry->name_len);
6193 		put_unaligned(fs_ftype_to_dtype(ftype), &entry->type);
6194 		btrfs_dir_item_key_to_cpu(leaf, di, &location);
6195 		put_unaligned(location.objectid, &entry->ino);
6196 		put_unaligned(found_key.offset, &entry->offset);
6197 		entries++;
6198 		addr += sizeof(struct dir_entry) + name_len;
6199 		total_len += sizeof(struct dir_entry) + name_len;
6200 	}
6201 	/* Catch error encountered during iteration */
6202 	if (ret < 0)
6203 		goto err;
6204 
6205 	btrfs_release_path(path);
6206 
6207 	ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6208 	if (ret)
6209 		goto nopos;
6210 
6211 	if (btrfs_readdir_delayed_dir_index(ctx, &ins_list))
6212 		goto nopos;
6213 
6214 	/*
6215 	 * Stop new entries from being returned after we return the last
6216 	 * entry.
6217 	 *
6218 	 * New directory entries are assigned a strictly increasing
6219 	 * offset.  This means that new entries created during readdir
6220 	 * are *guaranteed* to be seen in the future by that readdir.
6221 	 * This has broken buggy programs which operate on names as
6222 	 * they're returned by readdir.  Until we reuse freed offsets
6223 	 * we have this hack to stop new entries from being returned
6224 	 * under the assumption that they'll never reach this huge
6225 	 * offset.
6226 	 *
6227 	 * This is being careful not to overflow 32bit loff_t unless the
6228 	 * last entry requires it because doing so has broken 32bit apps
6229 	 * in the past.
6230 	 */
6231 	if (ctx->pos >= INT_MAX)
6232 		ctx->pos = LLONG_MAX;
6233 	else
6234 		ctx->pos = INT_MAX;
6235 nopos:
6236 	ret = 0;
6237 err:
6238 	if (put)
6239 		btrfs_readdir_put_delayed_items(BTRFS_I(inode), &ins_list, &del_list);
6240 	return ret;
6241 }
6242 
6243 /*
6244  * This is somewhat expensive, updating the tree every time the
6245  * inode changes.  But, it is most likely to find the inode in cache.
6246  * FIXME, needs more benchmarking...there are no reasons other than performance
6247  * to keep or drop this code.
6248  */
6249 static int btrfs_dirty_inode(struct btrfs_inode *inode)
6250 {
6251 	struct btrfs_root *root = inode->root;
6252 	struct btrfs_fs_info *fs_info = root->fs_info;
6253 	struct btrfs_trans_handle *trans;
6254 	int ret;
6255 
6256 	if (test_bit(BTRFS_INODE_DUMMY, &inode->runtime_flags))
6257 		return 0;
6258 
6259 	trans = btrfs_join_transaction(root);
6260 	if (IS_ERR(trans))
6261 		return PTR_ERR(trans);
6262 
6263 	ret = btrfs_update_inode(trans, inode);
6264 	if (ret == -ENOSPC || ret == -EDQUOT) {
6265 		/* whoops, lets try again with the full transaction */
6266 		btrfs_end_transaction(trans);
6267 		trans = btrfs_start_transaction(root, 1);
6268 		if (IS_ERR(trans))
6269 			return PTR_ERR(trans);
6270 
6271 		ret = btrfs_update_inode(trans, inode);
6272 	}
6273 	btrfs_end_transaction(trans);
6274 	if (inode->delayed_node)
6275 		btrfs_balance_delayed_items(fs_info);
6276 
6277 	return ret;
6278 }
6279 
6280 /*
6281  * We need our own ->update_time so that we can return error on ENOSPC for
6282  * updating the inode in the case of file write and mmap writes.
6283  */
6284 static int btrfs_update_time(struct inode *inode, enum fs_update_time type,
6285 		unsigned int flags)
6286 {
6287 	struct btrfs_root *root = BTRFS_I(inode)->root;
6288 	int dirty;
6289 
6290 	if (btrfs_root_readonly(root))
6291 		return -EROFS;
6292 	if (flags & IOCB_NOWAIT)
6293 		return -EAGAIN;
6294 
6295 	dirty = inode_update_time(inode, type, flags);
6296 	if (dirty <= 0)
6297 		return dirty;
6298 	return btrfs_dirty_inode(BTRFS_I(inode));
6299 }
6300 
6301 /*
6302  * helper to find a free sequence number in a given directory.  This current
6303  * code is very simple, later versions will do smarter things in the btree
6304  */
6305 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6306 {
6307 	int ret = 0;
6308 
6309 	if (dir->index_cnt == (u64)-1) {
6310 		ret = btrfs_inode_delayed_dir_index_count(dir);
6311 		if (ret) {
6312 			ret = btrfs_set_inode_index_count(dir);
6313 			if (ret)
6314 				return ret;
6315 		}
6316 	}
6317 
6318 	*index = dir->index_cnt;
6319 	dir->index_cnt++;
6320 
6321 	return ret;
6322 }
6323 
6324 static int btrfs_insert_inode_locked(struct inode *inode)
6325 {
6326 	struct btrfs_iget_args args;
6327 
6328 	args.ino = btrfs_ino(BTRFS_I(inode));
6329 	args.root = BTRFS_I(inode)->root;
6330 
6331 	return insert_inode_locked4(inode,
6332 		   btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6333 		   btrfs_find_actor, &args);
6334 }
6335 
6336 int btrfs_new_inode_prepare(struct btrfs_new_inode_args *args,
6337 			    unsigned int *trans_num_items)
6338 {
6339 	struct inode *dir = args->dir;
6340 	struct inode *inode = args->inode;
6341 	int ret;
6342 
6343 	if (!args->orphan) {
6344 		ret = fscrypt_setup_filename(dir, &args->dentry->d_name, 0,
6345 					     &args->fname);
6346 		if (ret)
6347 			return ret;
6348 	}
6349 
6350 	ret = posix_acl_create(dir, &inode->i_mode, &args->default_acl, &args->acl);
6351 	if (ret) {
6352 		fscrypt_free_filename(&args->fname);
6353 		return ret;
6354 	}
6355 
6356 	/* 1 to add inode item */
6357 	*trans_num_items = 1;
6358 	/* 1 to add compression property */
6359 	if (BTRFS_I(dir)->prop_compress)
6360 		(*trans_num_items)++;
6361 	/* 1 to add default ACL xattr */
6362 	if (args->default_acl)
6363 		(*trans_num_items)++;
6364 	/* 1 to add access ACL xattr */
6365 	if (args->acl)
6366 		(*trans_num_items)++;
6367 #ifdef CONFIG_SECURITY
6368 	/* 1 to add LSM xattr */
6369 	if (dir->i_security)
6370 		(*trans_num_items)++;
6371 #endif
6372 	if (args->orphan) {
6373 		/* 1 to add orphan item */
6374 		(*trans_num_items)++;
6375 	} else {
6376 		/*
6377 		 * 1 to add dir item
6378 		 * 1 to add dir index
6379 		 * 1 to update parent inode item
6380 		 *
6381 		 * No need for 1 unit for the inode ref item because it is
6382 		 * inserted in a batch together with the inode item at
6383 		 * btrfs_create_new_inode().
6384 		 */
6385 		*trans_num_items += 3;
6386 	}
6387 	return 0;
6388 }
6389 
6390 void btrfs_new_inode_args_destroy(struct btrfs_new_inode_args *args)
6391 {
6392 	posix_acl_release(args->acl);
6393 	posix_acl_release(args->default_acl);
6394 	fscrypt_free_filename(&args->fname);
6395 }
6396 
6397 /*
6398  * Inherit flags from the parent inode.
6399  *
6400  * Currently only the compression flags and the cow flags are inherited.
6401  */
6402 static void btrfs_inherit_iflags(struct btrfs_inode *inode, struct btrfs_inode *dir)
6403 {
6404 	unsigned int flags;
6405 
6406 	flags = dir->flags;
6407 
6408 	if (flags & BTRFS_INODE_NOCOMPRESS) {
6409 		inode->flags &= ~BTRFS_INODE_COMPRESS;
6410 		inode->flags |= BTRFS_INODE_NOCOMPRESS;
6411 	} else if (flags & BTRFS_INODE_COMPRESS) {
6412 		inode->flags &= ~BTRFS_INODE_NOCOMPRESS;
6413 		inode->flags |= BTRFS_INODE_COMPRESS;
6414 	}
6415 
6416 	if (flags & BTRFS_INODE_NODATACOW) {
6417 		inode->flags |= BTRFS_INODE_NODATACOW;
6418 		if (S_ISREG(inode->vfs_inode.i_mode))
6419 			inode->flags |= BTRFS_INODE_NODATASUM;
6420 	}
6421 
6422 	btrfs_sync_inode_flags_to_i_flags(inode);
6423 }
6424 
6425 int btrfs_create_new_inode(struct btrfs_trans_handle *trans,
6426 			   struct btrfs_new_inode_args *args)
6427 {
6428 	struct timespec64 ts;
6429 	struct inode *dir = args->dir;
6430 	struct inode *inode = args->inode;
6431 	const struct fscrypt_str *name = args->orphan ? NULL : &args->fname.disk_name;
6432 	struct btrfs_fs_info *fs_info = inode_to_fs_info(dir);
6433 	struct btrfs_root *root;
6434 	struct btrfs_inode_item *inode_item;
6435 	struct btrfs_path *path;
6436 	u64 objectid;
6437 	struct btrfs_inode_ref *ref;
6438 	struct btrfs_key key[2];
6439 	u32 sizes[2];
6440 	struct btrfs_item_batch batch;
6441 	unsigned long ptr;
6442 	int ret;
6443 	bool xa_reserved = false;
6444 
6445 	if (!args->orphan && !args->subvol) {
6446 		/*
6447 		 * Before anything else, check if we can add the name to the
6448 		 * parent directory. We want to avoid a dir item overflow in
6449 		 * case we have an existing dir item due to existing name
6450 		 * hash collisions. We do this check here before we call
6451 		 * btrfs_add_link() down below so that we can avoid a
6452 		 * transaction abort (which could be exploited by malicious
6453 		 * users).
6454 		 *
6455 		 * For subvolumes we already do this in btrfs_mksubvol().
6456 		 */
6457 		ret = btrfs_check_dir_item_collision(BTRFS_I(dir)->root,
6458 						     btrfs_ino(BTRFS_I(dir)),
6459 						     name);
6460 		if (ret < 0)
6461 			return ret;
6462 	}
6463 
6464 	path = btrfs_alloc_path();
6465 	if (!path)
6466 		return -ENOMEM;
6467 
6468 	if (!args->subvol)
6469 		BTRFS_I(inode)->root = btrfs_grab_root(BTRFS_I(dir)->root);
6470 	root = BTRFS_I(inode)->root;
6471 
6472 	ret = btrfs_init_file_extent_tree(BTRFS_I(inode));
6473 	if (ret)
6474 		goto out;
6475 
6476 	ret = btrfs_get_free_objectid(root, &objectid);
6477 	if (ret)
6478 		goto out;
6479 	btrfs_set_inode_number(BTRFS_I(inode), objectid);
6480 
6481 	ret = xa_reserve(&root->inodes, objectid, GFP_NOFS);
6482 	if (ret)
6483 		goto out;
6484 	xa_reserved = true;
6485 
6486 	if (args->orphan) {
6487 		/*
6488 		 * O_TMPFILE, set link count to 0, so that after this point, we
6489 		 * fill in an inode item with the correct link count.
6490 		 */
6491 		set_nlink(inode, 0);
6492 	} else {
6493 		trace_btrfs_inode_request(dir);
6494 
6495 		ret = btrfs_set_inode_index(BTRFS_I(dir), &BTRFS_I(inode)->dir_index);
6496 		if (ret)
6497 			goto out;
6498 	}
6499 
6500 	if (S_ISDIR(inode->i_mode))
6501 		BTRFS_I(inode)->index_cnt = BTRFS_DIR_START_INDEX;
6502 
6503 	BTRFS_I(inode)->generation = trans->transid;
6504 	inode->i_generation = BTRFS_I(inode)->generation;
6505 
6506 	/*
6507 	 * We don't have any capability xattrs set here yet, shortcut any
6508 	 * queries for the xattrs here.  If we add them later via the inode
6509 	 * security init path or any other path this flag will be cleared.
6510 	 */
6511 	set_bit(BTRFS_INODE_NO_CAP_XATTR, &BTRFS_I(inode)->runtime_flags);
6512 
6513 	/*
6514 	 * Subvolumes don't inherit flags from their parent directory.
6515 	 * Originally this was probably by accident, but we probably can't
6516 	 * change it now without compatibility issues.
6517 	 */
6518 	if (!args->subvol)
6519 		btrfs_inherit_iflags(BTRFS_I(inode), BTRFS_I(dir));
6520 
6521 	btrfs_set_inode_mapping_order(BTRFS_I(inode));
6522 	if (S_ISREG(inode->i_mode)) {
6523 		if (btrfs_test_opt(fs_info, NODATASUM))
6524 			BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6525 		if (btrfs_test_opt(fs_info, NODATACOW))
6526 			BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6527 				BTRFS_INODE_NODATASUM;
6528 		btrfs_update_inode_mapping_flags(BTRFS_I(inode));
6529 	}
6530 
6531 	ret = btrfs_insert_inode_locked(inode);
6532 	if (ret < 0) {
6533 		if (!args->orphan)
6534 			BTRFS_I(dir)->index_cnt--;
6535 		goto out;
6536 	}
6537 
6538 	/*
6539 	 * We could have gotten an inode number from somebody who was fsynced
6540 	 * and then removed in this same transaction, so let's just set full
6541 	 * sync since it will be a full sync anyway and this will blow away the
6542 	 * old info in the log.
6543 	 */
6544 	btrfs_set_inode_full_sync(BTRFS_I(inode));
6545 
6546 	key[0].objectid = objectid;
6547 	key[0].type = BTRFS_INODE_ITEM_KEY;
6548 	key[0].offset = 0;
6549 
6550 	sizes[0] = sizeof(struct btrfs_inode_item);
6551 
6552 	if (!args->orphan) {
6553 		/*
6554 		 * Start new inodes with an inode_ref. This is slightly more
6555 		 * efficient for small numbers of hard links since they will
6556 		 * be packed into one item. Extended refs will kick in if we
6557 		 * add more hard links than can fit in the ref item.
6558 		 */
6559 		key[1].objectid = objectid;
6560 		key[1].type = BTRFS_INODE_REF_KEY;
6561 		if (args->subvol) {
6562 			key[1].offset = objectid;
6563 			sizes[1] = 2 + sizeof(*ref);
6564 		} else {
6565 			key[1].offset = btrfs_ino(BTRFS_I(dir));
6566 			sizes[1] = name->len + sizeof(*ref);
6567 		}
6568 	}
6569 
6570 	batch.keys = &key[0];
6571 	batch.data_sizes = &sizes[0];
6572 	batch.total_data_size = sizes[0] + (args->orphan ? 0 : sizes[1]);
6573 	batch.nr = args->orphan ? 1 : 2;
6574 	ret = btrfs_insert_empty_items(trans, root, path, &batch);
6575 	if (unlikely(ret != 0)) {
6576 		btrfs_abort_transaction(trans, ret);
6577 		goto discard;
6578 	}
6579 
6580 	ts = simple_inode_init_ts(inode);
6581 	BTRFS_I(inode)->i_otime_sec = ts.tv_sec;
6582 	BTRFS_I(inode)->i_otime_nsec = ts.tv_nsec;
6583 
6584 	/*
6585 	 * We're going to fill the inode item now, so at this point the inode
6586 	 * must be fully initialized.
6587 	 */
6588 
6589 	inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6590 				  struct btrfs_inode_item);
6591 	memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6592 			     sizeof(*inode_item));
6593 	fill_inode_item(trans, path->nodes[0], inode_item, inode);
6594 
6595 	if (!args->orphan) {
6596 		ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6597 				     struct btrfs_inode_ref);
6598 		ptr = (unsigned long)(ref + 1);
6599 		if (args->subvol) {
6600 			btrfs_set_inode_ref_name_len(path->nodes[0], ref, 2);
6601 			btrfs_set_inode_ref_index(path->nodes[0], ref, 0);
6602 			write_extent_buffer(path->nodes[0], "..", ptr, 2);
6603 		} else {
6604 			btrfs_set_inode_ref_name_len(path->nodes[0], ref,
6605 						     name->len);
6606 			btrfs_set_inode_ref_index(path->nodes[0], ref,
6607 						  BTRFS_I(inode)->dir_index);
6608 			write_extent_buffer(path->nodes[0], name->name, ptr,
6609 					    name->len);
6610 		}
6611 	}
6612 
6613 	/*
6614 	 * We don't need the path anymore, plus inheriting properties, adding
6615 	 * ACLs, security xattrs, orphan item or adding the link, will result in
6616 	 * allocating yet another path. So just free our path.
6617 	 */
6618 	btrfs_free_path(path);
6619 	path = NULL;
6620 
6621 	if (args->subvol) {
6622 		struct btrfs_inode *parent;
6623 
6624 		/*
6625 		 * Subvolumes inherit properties from their parent subvolume,
6626 		 * not the directory they were created in.
6627 		 */
6628 		parent = btrfs_iget(BTRFS_FIRST_FREE_OBJECTID, BTRFS_I(dir)->root);
6629 		if (IS_ERR(parent)) {
6630 			ret = PTR_ERR(parent);
6631 		} else {
6632 			ret = btrfs_inode_inherit_props(trans, BTRFS_I(inode),
6633 							parent);
6634 			iput(&parent->vfs_inode);
6635 		}
6636 	} else {
6637 		ret = btrfs_inode_inherit_props(trans, BTRFS_I(inode),
6638 						BTRFS_I(dir));
6639 	}
6640 	if (ret) {
6641 		btrfs_err(fs_info,
6642 			  "error inheriting props for ino %llu (root %llu): %d",
6643 			  btrfs_ino(BTRFS_I(inode)), btrfs_root_id(root), ret);
6644 	}
6645 
6646 	/*
6647 	 * Subvolumes don't inherit ACLs or get passed to the LSM. This is
6648 	 * probably a bug.
6649 	 */
6650 	if (!args->subvol) {
6651 		ret = btrfs_init_inode_security(trans, args);
6652 		if (unlikely(ret)) {
6653 			btrfs_abort_transaction(trans, ret);
6654 			goto discard;
6655 		}
6656 	}
6657 
6658 	ret = btrfs_add_inode_to_root(BTRFS_I(inode), false);
6659 	if (WARN_ON(ret)) {
6660 		/* Shouldn't happen, we used xa_reserve() before. */
6661 		btrfs_abort_transaction(trans, ret);
6662 		goto discard;
6663 	}
6664 
6665 	trace_btrfs_inode_new(inode);
6666 	btrfs_set_inode_last_trans(trans, BTRFS_I(inode));
6667 
6668 	btrfs_update_root_times(trans, root);
6669 
6670 	if (args->orphan) {
6671 		ret = btrfs_orphan_add(trans, BTRFS_I(inode));
6672 		if (unlikely(ret)) {
6673 			btrfs_abort_transaction(trans, ret);
6674 			goto discard;
6675 		}
6676 	} else {
6677 		ret = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode), name,
6678 				     false, BTRFS_I(inode)->dir_index);
6679 		if (unlikely(ret)) {
6680 			btrfs_abort_transaction(trans, ret);
6681 			goto discard;
6682 		}
6683 	}
6684 
6685 	return 0;
6686 
6687 discard:
6688 	/*
6689 	 * discard_new_inode() calls iput(), but the caller owns the reference
6690 	 * to the inode.
6691 	 */
6692 	ihold(inode);
6693 	discard_new_inode(inode);
6694 out:
6695 	if (xa_reserved)
6696 		xa_release(&root->inodes, objectid);
6697 
6698 	btrfs_free_path(path);
6699 	return ret;
6700 }
6701 
6702 /*
6703  * utility function to add 'inode' into 'parent_inode' with
6704  * a give name and a given sequence number.
6705  * if 'add_backref' is true, also insert a backref from the
6706  * inode to the parent directory.
6707  */
6708 int btrfs_add_link(struct btrfs_trans_handle *trans,
6709 		   struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6710 		   const struct fscrypt_str *name, bool add_backref, u64 index)
6711 {
6712 	int ret = 0;
6713 	struct btrfs_key key;
6714 	struct btrfs_root *root = parent_inode->root;
6715 	u64 ino = btrfs_ino(inode);
6716 	u64 parent_ino = btrfs_ino(parent_inode);
6717 
6718 	if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6719 		memcpy(&key, &inode->root->root_key, sizeof(key));
6720 	} else {
6721 		key.objectid = ino;
6722 		key.type = BTRFS_INODE_ITEM_KEY;
6723 		key.offset = 0;
6724 	}
6725 
6726 	if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6727 		ret = btrfs_add_root_ref(trans, key.objectid,
6728 					 btrfs_root_id(root), parent_ino,
6729 					 index, name);
6730 	} else if (add_backref) {
6731 		ret = btrfs_insert_inode_ref(trans, root, name,
6732 					     ino, parent_ino, index);
6733 	}
6734 
6735 	/* Nothing to clean up yet */
6736 	if (ret)
6737 		return ret;
6738 
6739 	ret = btrfs_insert_dir_item(trans, name, parent_inode, &key,
6740 				    btrfs_inode_type(inode), index);
6741 	if (ret == -EEXIST || ret == -EOVERFLOW)
6742 		goto fail_dir_item;
6743 	else if (unlikely(ret)) {
6744 		btrfs_abort_transaction(trans, ret);
6745 		return ret;
6746 	}
6747 
6748 	btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6749 			   name->len * 2);
6750 	inode_inc_iversion(&parent_inode->vfs_inode);
6751 	update_time_after_link_or_unlink(parent_inode);
6752 
6753 	ret = btrfs_update_inode(trans, parent_inode);
6754 	if (ret)
6755 		btrfs_abort_transaction(trans, ret);
6756 	return ret;
6757 
6758 fail_dir_item:
6759 	if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6760 		u64 local_index;
6761 		int ret2;
6762 
6763 		ret2 = btrfs_del_root_ref(trans, key.objectid, btrfs_root_id(root),
6764 					  parent_ino, &local_index, name);
6765 		if (ret2)
6766 			btrfs_abort_transaction(trans, ret2);
6767 	} else if (add_backref) {
6768 		int ret2;
6769 
6770 		ret2 = btrfs_del_inode_ref(trans, root, name, ino, parent_ino, NULL);
6771 		if (ret2)
6772 			btrfs_abort_transaction(trans, ret2);
6773 	}
6774 
6775 	/* Return the original error code */
6776 	return ret;
6777 }
6778 
6779 static int btrfs_create_common(struct inode *dir, struct dentry *dentry,
6780 			       struct inode *inode)
6781 {
6782 	struct btrfs_fs_info *fs_info = inode_to_fs_info(dir);
6783 	struct btrfs_root *root = BTRFS_I(dir)->root;
6784 	struct btrfs_new_inode_args new_inode_args = {
6785 		.dir = dir,
6786 		.dentry = dentry,
6787 		.inode = inode,
6788 	};
6789 	unsigned int trans_num_items;
6790 	struct btrfs_trans_handle *trans;
6791 	int ret;
6792 
6793 	ret = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
6794 	if (ret)
6795 		goto out_inode;
6796 
6797 	trans = btrfs_start_transaction(root, trans_num_items);
6798 	if (IS_ERR(trans)) {
6799 		ret = PTR_ERR(trans);
6800 		goto out_new_inode_args;
6801 	}
6802 
6803 	ret = btrfs_create_new_inode(trans, &new_inode_args);
6804 	if (!ret) {
6805 		if (S_ISDIR(inode->i_mode))
6806 			inode->i_opflags |= IOP_FASTPERM_MAY_EXEC;
6807 		d_instantiate_new(dentry, inode);
6808 	}
6809 
6810 	btrfs_end_transaction(trans);
6811 	btrfs_btree_balance_dirty(fs_info);
6812 out_new_inode_args:
6813 	btrfs_new_inode_args_destroy(&new_inode_args);
6814 out_inode:
6815 	if (ret)
6816 		iput(inode);
6817 	return ret;
6818 }
6819 
6820 static int btrfs_mknod(struct mnt_idmap *idmap, struct inode *dir,
6821 		       struct dentry *dentry, umode_t mode, dev_t rdev)
6822 {
6823 	struct inode *inode;
6824 
6825 	inode = new_inode(dir->i_sb);
6826 	if (!inode)
6827 		return -ENOMEM;
6828 	inode_init_owner(idmap, inode, dir, mode);
6829 	inode->i_op = &btrfs_special_inode_operations;
6830 	init_special_inode(inode, inode->i_mode, rdev);
6831 	return btrfs_create_common(dir, dentry, inode);
6832 }
6833 
6834 static int btrfs_create(struct mnt_idmap *idmap, struct inode *dir,
6835 			struct dentry *dentry, umode_t mode, bool excl)
6836 {
6837 	struct inode *inode;
6838 
6839 	inode = new_inode(dir->i_sb);
6840 	if (!inode)
6841 		return -ENOMEM;
6842 	inode_init_owner(idmap, inode, dir, mode);
6843 	inode->i_fop = &btrfs_file_operations;
6844 	inode->i_op = &btrfs_file_inode_operations;
6845 	inode->i_mapping->a_ops = &btrfs_aops;
6846 	return btrfs_create_common(dir, dentry, inode);
6847 }
6848 
6849 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
6850 		      struct dentry *dentry)
6851 {
6852 	struct btrfs_trans_handle *trans = NULL;
6853 	struct btrfs_root *root = BTRFS_I(dir)->root;
6854 	struct inode *inode = d_inode(old_dentry);
6855 	struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
6856 	struct fscrypt_name fname;
6857 	u64 index;
6858 	int ret;
6859 
6860 	/* do not allow sys_link's with other subvols of the same device */
6861 	if (btrfs_root_id(root) != btrfs_root_id(BTRFS_I(inode)->root))
6862 		return -EXDEV;
6863 
6864 	if (inode->i_nlink >= BTRFS_LINK_MAX)
6865 		return -EMLINK;
6866 
6867 	ret = fscrypt_setup_filename(dir, &dentry->d_name, 0, &fname);
6868 	if (ret)
6869 		goto fail;
6870 
6871 	ret = btrfs_set_inode_index(BTRFS_I(dir), &index);
6872 	if (ret)
6873 		goto fail;
6874 
6875 	/*
6876 	 * 2 items for inode and inode ref
6877 	 * 2 items for dir items
6878 	 * 1 item for parent inode
6879 	 * 1 item for orphan item deletion if O_TMPFILE
6880 	 */
6881 	trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
6882 	if (IS_ERR(trans)) {
6883 		ret = PTR_ERR(trans);
6884 		trans = NULL;
6885 		goto fail;
6886 	}
6887 
6888 	/* There are several dir indexes for this inode, clear the cache. */
6889 	BTRFS_I(inode)->dir_index = 0ULL;
6890 	inode_inc_iversion(inode);
6891 	inode_set_ctime_current(inode);
6892 
6893 	ret = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
6894 			     &fname.disk_name, true, index);
6895 	if (ret)
6896 		goto fail;
6897 
6898 	/* Link added now we update the inode item with the new link count. */
6899 	inc_nlink(inode);
6900 	ret = btrfs_update_inode(trans, BTRFS_I(inode));
6901 	if (unlikely(ret)) {
6902 		btrfs_abort_transaction(trans, ret);
6903 		goto fail;
6904 	}
6905 
6906 	if (inode->i_nlink == 1) {
6907 		/*
6908 		 * If the new hard link count is 1, it's a file created with the
6909 		 * open(2) O_TMPFILE flag.
6910 		 */
6911 		ret = btrfs_orphan_del(trans, BTRFS_I(inode));
6912 		if (unlikely(ret)) {
6913 			btrfs_abort_transaction(trans, ret);
6914 			goto fail;
6915 		}
6916 	}
6917 
6918 	/* Grab reference for the new dentry passed to d_instantiate(). */
6919 	ihold(inode);
6920 	d_instantiate(dentry, inode);
6921 	btrfs_log_new_name(trans, old_dentry, NULL, 0, dentry->d_parent);
6922 
6923 fail:
6924 	fscrypt_free_filename(&fname);
6925 	if (trans)
6926 		btrfs_end_transaction(trans);
6927 	btrfs_btree_balance_dirty(fs_info);
6928 	return ret;
6929 }
6930 
6931 static struct dentry *btrfs_mkdir(struct mnt_idmap *idmap, struct inode *dir,
6932 				  struct dentry *dentry, umode_t mode)
6933 {
6934 	struct inode *inode;
6935 
6936 	inode = new_inode(dir->i_sb);
6937 	if (!inode)
6938 		return ERR_PTR(-ENOMEM);
6939 	inode_init_owner(idmap, inode, dir, S_IFDIR | mode);
6940 	inode->i_op = &btrfs_dir_inode_operations;
6941 	inode->i_fop = &btrfs_dir_file_operations;
6942 	return ERR_PTR(btrfs_create_common(dir, dentry, inode));
6943 }
6944 
6945 static noinline int uncompress_inline(struct btrfs_path *path,
6946 				      struct folio *folio,
6947 				      struct btrfs_file_extent_item *item)
6948 {
6949 	int ret;
6950 	struct extent_buffer *leaf = path->nodes[0];
6951 	const u32 blocksize = leaf->fs_info->sectorsize;
6952 	char *tmp;
6953 	size_t max_size;
6954 	unsigned long inline_size;
6955 	unsigned long ptr;
6956 	int compress_type;
6957 
6958 	compress_type = btrfs_file_extent_compression(leaf, item);
6959 	max_size = btrfs_file_extent_ram_bytes(leaf, item);
6960 	inline_size = btrfs_file_extent_inline_item_len(leaf, path->slots[0]);
6961 	tmp = kmalloc(inline_size, GFP_NOFS);
6962 	if (!tmp)
6963 		return -ENOMEM;
6964 	ptr = btrfs_file_extent_inline_start(item);
6965 
6966 	read_extent_buffer(leaf, tmp, ptr, inline_size);
6967 
6968 	max_size = min_t(unsigned long, blocksize, max_size);
6969 	ret = btrfs_decompress(compress_type, tmp, folio, 0, inline_size,
6970 			       max_size);
6971 
6972 	/*
6973 	 * decompression code contains a memset to fill in any space between the end
6974 	 * of the uncompressed data and the end of max_size in case the decompressed
6975 	 * data ends up shorter than ram_bytes.  That doesn't cover the hole between
6976 	 * the end of an inline extent and the beginning of the next block, so we
6977 	 * cover that region here.
6978 	 */
6979 
6980 	if (max_size < blocksize)
6981 		folio_zero_range(folio, max_size, blocksize - max_size);
6982 	kfree(tmp);
6983 	return ret;
6984 }
6985 
6986 static int read_inline_extent(struct btrfs_path *path, struct folio *folio)
6987 {
6988 	const u32 blocksize = path->nodes[0]->fs_info->sectorsize;
6989 	struct btrfs_file_extent_item *fi;
6990 	void *kaddr;
6991 	size_t copy_size;
6992 
6993 	if (!folio || folio_test_uptodate(folio))
6994 		return 0;
6995 
6996 	ASSERT(folio_pos(folio) == 0);
6997 
6998 	fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
6999 			    struct btrfs_file_extent_item);
7000 	if (btrfs_file_extent_compression(path->nodes[0], fi) != BTRFS_COMPRESS_NONE)
7001 		return uncompress_inline(path, folio, fi);
7002 
7003 	copy_size = min_t(u64, blocksize,
7004 			  btrfs_file_extent_ram_bytes(path->nodes[0], fi));
7005 	kaddr = kmap_local_folio(folio, 0);
7006 	read_extent_buffer(path->nodes[0], kaddr,
7007 			   btrfs_file_extent_inline_start(fi), copy_size);
7008 	kunmap_local(kaddr);
7009 	if (copy_size < blocksize)
7010 		folio_zero_range(folio, copy_size, blocksize - copy_size);
7011 	return 0;
7012 }
7013 
7014 /*
7015  * Lookup the first extent overlapping a range in a file.
7016  *
7017  * @inode:	file to search in
7018  * @page:	page to read extent data into if the extent is inline
7019  * @start:	file offset
7020  * @len:	length of range starting at @start
7021  *
7022  * Return the first &struct extent_map which overlaps the given range, reading
7023  * it from the B-tree and caching it if necessary. Note that there may be more
7024  * extents which overlap the given range after the returned extent_map.
7025  *
7026  * If @page is not NULL and the extent is inline, this also reads the extent
7027  * data directly into the page and marks the extent up to date in the io_tree.
7028  *
7029  * Return: ERR_PTR on error, non-NULL extent_map on success.
7030  */
7031 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
7032 				    struct folio *folio, u64 start, u64 len)
7033 {
7034 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
7035 	int ret = 0;
7036 	u64 extent_start = 0;
7037 	u64 extent_end = 0;
7038 	u64 objectid = btrfs_ino(inode);
7039 	int extent_type = -1;
7040 	struct btrfs_path *path = NULL;
7041 	struct btrfs_root *root = inode->root;
7042 	struct btrfs_file_extent_item *item;
7043 	struct extent_buffer *leaf;
7044 	struct btrfs_key found_key;
7045 	struct extent_map *em = NULL;
7046 	struct extent_map_tree *em_tree = &inode->extent_tree;
7047 
7048 	read_lock(&em_tree->lock);
7049 	em = btrfs_lookup_extent_mapping(em_tree, start, len);
7050 	read_unlock(&em_tree->lock);
7051 
7052 	if (em) {
7053 		if (em->start > start || btrfs_extent_map_end(em) <= start)
7054 			btrfs_free_extent_map(em);
7055 		else if (em->disk_bytenr == EXTENT_MAP_INLINE && folio)
7056 			btrfs_free_extent_map(em);
7057 		else
7058 			goto out;
7059 	}
7060 	em = btrfs_alloc_extent_map();
7061 	if (!em) {
7062 		ret = -ENOMEM;
7063 		goto out;
7064 	}
7065 	em->start = EXTENT_MAP_HOLE;
7066 	em->disk_bytenr = EXTENT_MAP_HOLE;
7067 	em->len = (u64)-1;
7068 
7069 	path = btrfs_alloc_path();
7070 	if (!path) {
7071 		ret = -ENOMEM;
7072 		goto out;
7073 	}
7074 
7075 	/* Chances are we'll be called again, so go ahead and do readahead */
7076 	path->reada = READA_FORWARD;
7077 
7078 	/*
7079 	 * The same explanation in load_free_space_cache applies here as well,
7080 	 * we only read when we're loading the free space cache, and at that
7081 	 * point the commit_root has everything we need.
7082 	 */
7083 	if (btrfs_is_free_space_inode(inode)) {
7084 		path->search_commit_root = true;
7085 		path->skip_locking = true;
7086 	}
7087 
7088 	ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
7089 	if (ret < 0) {
7090 		goto out;
7091 	} else if (ret > 0) {
7092 		if (path->slots[0] == 0)
7093 			goto not_found;
7094 		path->slots[0]--;
7095 		ret = 0;
7096 	}
7097 
7098 	leaf = path->nodes[0];
7099 	item = btrfs_item_ptr(leaf, path->slots[0],
7100 			      struct btrfs_file_extent_item);
7101 	btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7102 	if (found_key.objectid != objectid ||
7103 	    found_key.type != BTRFS_EXTENT_DATA_KEY) {
7104 		/*
7105 		 * If we backup past the first extent we want to move forward
7106 		 * and see if there is an extent in front of us, otherwise we'll
7107 		 * say there is a hole for our whole search range which can
7108 		 * cause problems.
7109 		 */
7110 		extent_end = start;
7111 		goto next;
7112 	}
7113 
7114 	extent_type = btrfs_file_extent_type(leaf, item);
7115 	extent_start = found_key.offset;
7116 	extent_end = btrfs_file_extent_end(path);
7117 	if (extent_type == BTRFS_FILE_EXTENT_REG ||
7118 	    extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
7119 		/* Only regular file could have regular/prealloc extent */
7120 		if (unlikely(!S_ISREG(inode->vfs_inode.i_mode))) {
7121 			ret = -EUCLEAN;
7122 			btrfs_crit(fs_info,
7123 		"regular/prealloc extent found for non-regular inode %llu",
7124 				   btrfs_ino(inode));
7125 			goto out;
7126 		}
7127 		trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
7128 						       extent_start);
7129 	} else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
7130 		trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
7131 						      path->slots[0],
7132 						      extent_start);
7133 	}
7134 next:
7135 	if (start >= extent_end) {
7136 		path->slots[0]++;
7137 		if (path->slots[0] >= btrfs_header_nritems(leaf)) {
7138 			ret = btrfs_next_leaf(root, path);
7139 			if (ret < 0)
7140 				goto out;
7141 			else if (ret > 0)
7142 				goto not_found;
7143 
7144 			leaf = path->nodes[0];
7145 		}
7146 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7147 		if (found_key.objectid != objectid ||
7148 		    found_key.type != BTRFS_EXTENT_DATA_KEY)
7149 			goto not_found;
7150 		if (start + len <= found_key.offset)
7151 			goto not_found;
7152 		if (start > found_key.offset)
7153 			goto next;
7154 
7155 		/* New extent overlaps with existing one */
7156 		em->start = start;
7157 		em->len = found_key.offset - start;
7158 		em->disk_bytenr = EXTENT_MAP_HOLE;
7159 		goto insert;
7160 	}
7161 
7162 	btrfs_extent_item_to_extent_map(inode, path, item, em);
7163 
7164 	if (extent_type == BTRFS_FILE_EXTENT_REG ||
7165 	    extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
7166 		goto insert;
7167 	} else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
7168 		/*
7169 		 * Inline extent can only exist at file offset 0. This is
7170 		 * ensured by tree-checker and inline extent creation path.
7171 		 * Thus all members representing file offsets should be zero.
7172 		 */
7173 		ASSERT(extent_start == 0);
7174 		ASSERT(em->start == 0);
7175 
7176 		/*
7177 		 * btrfs_extent_item_to_extent_map() should have properly
7178 		 * initialized em members already.
7179 		 *
7180 		 * Other members are not utilized for inline extents.
7181 		 */
7182 		ASSERT(em->disk_bytenr == EXTENT_MAP_INLINE);
7183 		ASSERT(em->len == fs_info->sectorsize);
7184 
7185 		ret = read_inline_extent(path, folio);
7186 		if (ret < 0)
7187 			goto out;
7188 		goto insert;
7189 	}
7190 not_found:
7191 	em->start = start;
7192 	em->len = len;
7193 	em->disk_bytenr = EXTENT_MAP_HOLE;
7194 insert:
7195 	ret = 0;
7196 	btrfs_release_path(path);
7197 	if (unlikely(em->start > start || btrfs_extent_map_end(em) <= start)) {
7198 		btrfs_err(fs_info,
7199 			  "bad extent! em: [%llu %llu] passed [%llu %llu]",
7200 			  em->start, em->len, start, len);
7201 		ret = -EIO;
7202 		goto out;
7203 	}
7204 
7205 	write_lock(&em_tree->lock);
7206 	ret = btrfs_add_extent_mapping(inode, &em, start, len);
7207 	write_unlock(&em_tree->lock);
7208 out:
7209 	btrfs_free_path(path);
7210 
7211 	trace_btrfs_get_extent(root, inode, em);
7212 
7213 	if (ret) {
7214 		btrfs_free_extent_map(em);
7215 		return ERR_PTR(ret);
7216 	}
7217 	return em;
7218 }
7219 
7220 static bool btrfs_extent_readonly(struct btrfs_fs_info *fs_info, u64 bytenr)
7221 {
7222 	struct btrfs_block_group *block_group;
7223 	bool readonly = false;
7224 
7225 	block_group = btrfs_lookup_block_group(fs_info, bytenr);
7226 	if (!block_group || block_group->ro)
7227 		readonly = true;
7228 	if (block_group)
7229 		btrfs_put_block_group(block_group);
7230 	return readonly;
7231 }
7232 
7233 /*
7234  * Check if we can do nocow write into the range [@offset, @offset + @len)
7235  *
7236  * @offset:	File offset
7237  * @len:	The length to write, will be updated to the nocow writeable
7238  *		range
7239  * @orig_start:	(optional) Return the original file offset of the file extent
7240  * @orig_len:	(optional) Return the original on-disk length of the file extent
7241  * @ram_bytes:	(optional) Return the ram_bytes of the file extent
7242  *
7243  * Return:
7244  * >0	and update @len if we can do nocow write
7245  *  0	if we can't do nocow write
7246  * <0	if error happened
7247  *
7248  * NOTE: This only checks the file extents, caller is responsible to wait for
7249  *	 any ordered extents.
7250  */
7251 noinline int can_nocow_extent(struct btrfs_inode *inode, u64 offset, u64 *len,
7252 			      struct btrfs_file_extent *file_extent,
7253 			      bool nowait)
7254 {
7255 	struct btrfs_root *root = inode->root;
7256 	struct btrfs_fs_info *fs_info = root->fs_info;
7257 	struct can_nocow_file_extent_args nocow_args = { 0 };
7258 	BTRFS_PATH_AUTO_FREE(path);
7259 	int ret;
7260 	struct extent_buffer *leaf;
7261 	struct extent_io_tree *io_tree = &inode->io_tree;
7262 	struct btrfs_file_extent_item *fi;
7263 	struct btrfs_key key;
7264 	int found_type;
7265 
7266 	path = btrfs_alloc_path();
7267 	if (!path)
7268 		return -ENOMEM;
7269 	path->nowait = nowait;
7270 
7271 	ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
7272 				       offset, 0);
7273 	if (ret < 0)
7274 		return ret;
7275 
7276 	if (ret == 1) {
7277 		if (path->slots[0] == 0) {
7278 			/* Can't find the item, must COW. */
7279 			return 0;
7280 		}
7281 		path->slots[0]--;
7282 	}
7283 	ret = 0;
7284 	leaf = path->nodes[0];
7285 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
7286 	if (key.objectid != btrfs_ino(inode) ||
7287 	    key.type != BTRFS_EXTENT_DATA_KEY) {
7288 		/* Not our file or wrong item type, must COW. */
7289 		return 0;
7290 	}
7291 
7292 	if (key.offset > offset) {
7293 		/* Wrong offset, must COW. */
7294 		return 0;
7295 	}
7296 
7297 	if (btrfs_file_extent_end(path) <= offset)
7298 		return 0;
7299 
7300 	fi = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
7301 	found_type = btrfs_file_extent_type(leaf, fi);
7302 
7303 	nocow_args.start = offset;
7304 	nocow_args.end = offset + *len - 1;
7305 	nocow_args.free_path = true;
7306 
7307 	ret = can_nocow_file_extent(path, &key, inode, &nocow_args);
7308 	/* can_nocow_file_extent() has freed the path. */
7309 	path = NULL;
7310 
7311 	if (ret != 1) {
7312 		/* Treat errors as not being able to NOCOW. */
7313 		return 0;
7314 	}
7315 
7316 	if (btrfs_extent_readonly(fs_info,
7317 				  nocow_args.file_extent.disk_bytenr +
7318 				  nocow_args.file_extent.offset))
7319 		return 0;
7320 
7321 	if (!(inode->flags & BTRFS_INODE_NODATACOW) &&
7322 	    found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7323 		u64 range_end;
7324 
7325 		range_end = round_up(offset + nocow_args.file_extent.num_bytes,
7326 				     root->fs_info->sectorsize) - 1;
7327 		ret = btrfs_test_range_bit_exists(io_tree, offset, range_end,
7328 						  EXTENT_DELALLOC);
7329 		if (ret)
7330 			return -EAGAIN;
7331 	}
7332 
7333 	if (file_extent)
7334 		memcpy(file_extent, &nocow_args.file_extent, sizeof(*file_extent));
7335 
7336 	*len = nocow_args.file_extent.num_bytes;
7337 
7338 	return 1;
7339 }
7340 
7341 /* The callers of this must take lock_extent() */
7342 struct extent_map *btrfs_create_io_em(struct btrfs_inode *inode, u64 start,
7343 				      const struct btrfs_file_extent *file_extent,
7344 				      int type)
7345 {
7346 	struct extent_map *em;
7347 	int ret;
7348 
7349 	/*
7350 	 * Note the missing NOCOW type.
7351 	 *
7352 	 * For pure NOCOW writes, we should not create an io extent map, but
7353 	 * just reusing the existing one.
7354 	 * Only PREALLOC writes (NOCOW write into preallocated range) can
7355 	 * create an io extent map.
7356 	 */
7357 	ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7358 	       type == BTRFS_ORDERED_COMPRESSED ||
7359 	       type == BTRFS_ORDERED_REGULAR);
7360 
7361 	switch (type) {
7362 	case BTRFS_ORDERED_PREALLOC:
7363 		/* We're only referring part of a larger preallocated extent. */
7364 		ASSERT(file_extent->num_bytes <= file_extent->ram_bytes);
7365 		break;
7366 	case BTRFS_ORDERED_REGULAR:
7367 		/* COW results a new extent matching our file extent size. */
7368 		ASSERT(file_extent->disk_num_bytes == file_extent->num_bytes);
7369 		ASSERT(file_extent->ram_bytes == file_extent->num_bytes);
7370 
7371 		/* Since it's a new extent, we should not have any offset. */
7372 		ASSERT(file_extent->offset == 0);
7373 		break;
7374 	case BTRFS_ORDERED_COMPRESSED:
7375 		/* Must be compressed. */
7376 		ASSERT(file_extent->compression != BTRFS_COMPRESS_NONE);
7377 
7378 		/*
7379 		 * Encoded write can make us to refer to part of the
7380 		 * uncompressed extent.
7381 		 */
7382 		ASSERT(file_extent->num_bytes <= file_extent->ram_bytes);
7383 		break;
7384 	}
7385 
7386 	em = btrfs_alloc_extent_map();
7387 	if (!em)
7388 		return ERR_PTR(-ENOMEM);
7389 
7390 	em->start = start;
7391 	em->len = file_extent->num_bytes;
7392 	em->disk_bytenr = file_extent->disk_bytenr;
7393 	em->disk_num_bytes = file_extent->disk_num_bytes;
7394 	em->ram_bytes = file_extent->ram_bytes;
7395 	em->generation = -1;
7396 	em->offset = file_extent->offset;
7397 	em->flags |= EXTENT_FLAG_PINNED;
7398 	if (type == BTRFS_ORDERED_COMPRESSED)
7399 		btrfs_extent_map_set_compression(em, file_extent->compression);
7400 
7401 	ret = btrfs_replace_extent_map_range(inode, em, true);
7402 	if (ret) {
7403 		btrfs_free_extent_map(em);
7404 		return ERR_PTR(ret);
7405 	}
7406 
7407 	/* em got 2 refs now, callers needs to do btrfs_free_extent_map once. */
7408 	return em;
7409 }
7410 
7411 /*
7412  * For release_folio() and invalidate_folio() we have a race window where
7413  * folio_end_writeback() is called but the subpage spinlock is not yet released.
7414  * If we continue to release/invalidate the page, we could cause use-after-free
7415  * for subpage spinlock.  So this function is to spin and wait for subpage
7416  * spinlock.
7417  */
7418 static void wait_subpage_spinlock(struct folio *folio)
7419 {
7420 	struct btrfs_fs_info *fs_info = folio_to_fs_info(folio);
7421 	struct btrfs_folio_state *bfs;
7422 
7423 	if (!btrfs_is_subpage(fs_info, folio))
7424 		return;
7425 
7426 	ASSERT(folio_test_private(folio) && folio_get_private(folio));
7427 	bfs = folio_get_private(folio);
7428 
7429 	/*
7430 	 * This may look insane as we just acquire the spinlock and release it,
7431 	 * without doing anything.  But we just want to make sure no one is
7432 	 * still holding the subpage spinlock.
7433 	 * And since the page is not dirty nor writeback, and we have page
7434 	 * locked, the only possible way to hold a spinlock is from the endio
7435 	 * function to clear page writeback.
7436 	 *
7437 	 * Here we just acquire the spinlock so that all existing callers
7438 	 * should exit and we're safe to release/invalidate the page.
7439 	 */
7440 	spin_lock_irq(&bfs->lock);
7441 	spin_unlock_irq(&bfs->lock);
7442 }
7443 
7444 static int btrfs_launder_folio(struct folio *folio)
7445 {
7446 	return btrfs_qgroup_free_data(folio_to_inode(folio), NULL, folio_pos(folio),
7447 				      folio_size(folio), NULL);
7448 }
7449 
7450 static bool __btrfs_release_folio(struct folio *folio, gfp_t gfp_flags)
7451 {
7452 	if (try_release_extent_mapping(folio, gfp_flags)) {
7453 		wait_subpage_spinlock(folio);
7454 		clear_folio_extent_mapped(folio);
7455 		return true;
7456 	}
7457 	return false;
7458 }
7459 
7460 static bool btrfs_release_folio(struct folio *folio, gfp_t gfp_flags)
7461 {
7462 	if (folio_test_writeback(folio) || folio_test_dirty(folio))
7463 		return false;
7464 	return __btrfs_release_folio(folio, gfp_flags);
7465 }
7466 
7467 #ifdef CONFIG_MIGRATION
7468 static int btrfs_migrate_folio(struct address_space *mapping,
7469 			     struct folio *dst, struct folio *src,
7470 			     enum migrate_mode mode)
7471 {
7472 	int ret = filemap_migrate_folio(mapping, dst, src, mode);
7473 
7474 	if (ret)
7475 		return ret;
7476 	return 0;
7477 }
7478 #else
7479 #define btrfs_migrate_folio NULL
7480 #endif
7481 
7482 static void btrfs_invalidate_folio(struct folio *folio, size_t offset,
7483 				 size_t length)
7484 {
7485 	struct btrfs_inode *inode = folio_to_inode(folio);
7486 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
7487 	struct extent_io_tree *tree = &inode->io_tree;
7488 	struct extent_state *cached_state = NULL;
7489 	u64 page_start = folio_pos(folio);
7490 	u64 page_end = page_start + folio_size(folio) - 1;
7491 	u64 cur;
7492 	int inode_evicting = inode_state_read_once(&inode->vfs_inode) & I_FREEING;
7493 
7494 	/*
7495 	 * We have folio locked so no new ordered extent can be created on this
7496 	 * page, nor bio can be submitted for this folio.
7497 	 *
7498 	 * But already submitted bio can still be finished on this folio.
7499 	 * Furthermore, endio function won't skip folio which has Ordered
7500 	 * already cleared, so it's possible for endio and
7501 	 * invalidate_folio to do the same ordered extent accounting twice
7502 	 * on one folio.
7503 	 *
7504 	 * So here we wait for any submitted bios to finish, so that we won't
7505 	 * do double ordered extent accounting on the same folio.
7506 	 */
7507 	folio_wait_writeback(folio);
7508 	wait_subpage_spinlock(folio);
7509 
7510 	/*
7511 	 * For subpage case, we have call sites like
7512 	 * btrfs_punch_hole_lock_range() which passes range not aligned to
7513 	 * sectorsize.
7514 	 * If the range doesn't cover the full folio, we don't need to and
7515 	 * shouldn't clear page extent mapped, as folio->private can still
7516 	 * record subpage dirty bits for other part of the range.
7517 	 *
7518 	 * For cases that invalidate the full folio even the range doesn't
7519 	 * cover the full folio, like invalidating the last folio, we're
7520 	 * still safe to wait for ordered extent to finish.
7521 	 */
7522 	if (!(offset == 0 && length == folio_size(folio))) {
7523 		btrfs_release_folio(folio, GFP_NOFS);
7524 		return;
7525 	}
7526 
7527 	if (!inode_evicting)
7528 		btrfs_lock_extent(tree, page_start, page_end, &cached_state);
7529 
7530 	cur = page_start;
7531 	while (cur < page_end) {
7532 		struct btrfs_ordered_extent *ordered;
7533 		u64 range_end;
7534 		u32 range_len;
7535 		u32 extra_flags = 0;
7536 
7537 		ordered = btrfs_lookup_first_ordered_range(inode, cur,
7538 							   page_end + 1 - cur);
7539 		if (!ordered) {
7540 			range_end = page_end;
7541 			/*
7542 			 * No ordered extent covering this range, we are safe
7543 			 * to delete all extent states in the range.
7544 			 */
7545 			extra_flags = EXTENT_CLEAR_ALL_BITS;
7546 			goto next;
7547 		}
7548 		if (ordered->file_offset > cur) {
7549 			/*
7550 			 * There is a range between [cur, oe->file_offset) not
7551 			 * covered by any ordered extent.
7552 			 * We are safe to delete all extent states, and handle
7553 			 * the ordered extent in the next iteration.
7554 			 */
7555 			range_end = ordered->file_offset - 1;
7556 			extra_flags = EXTENT_CLEAR_ALL_BITS;
7557 			goto next;
7558 		}
7559 
7560 		range_end = min(ordered->file_offset + ordered->num_bytes - 1,
7561 				page_end);
7562 		ASSERT(range_end + 1 - cur < U32_MAX);
7563 		range_len = range_end + 1 - cur;
7564 		/*
7565 		 * If the range is not dirty, the range has been submitted and
7566 		 * since we have waited for the writeback, endio has been
7567 		 * executed, thus we must skip the range to avoid double
7568 		 * accounting for the ordered extent.
7569 		 */
7570 		if (!btrfs_folio_test_dirty(fs_info, folio, cur, range_len))
7571 			goto next;
7572 
7573 		/*
7574 		 * The range is dirty meaning it has not been submitted.
7575 		 * Here we need to truncate the OE range as the range will never
7576 		 * be submitted.
7577 		 *
7578 		 * IO on this page will never be started, so we need to account
7579 		 * for any ordered extents now. Don't clear EXTENT_DELALLOC_NEW
7580 		 * here, must leave that up for the ordered extent completion.
7581 		 *
7582 		 * This will also unlock the range for incoming
7583 		 * btrfs_finish_ordered_io().
7584 		 */
7585 		if (!inode_evicting)
7586 			btrfs_clear_extent_bit(tree, cur, range_end,
7587 					       EXTENT_DELALLOC |
7588 					       EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
7589 					       EXTENT_DEFRAG, &cached_state);
7590 
7591 		btrfs_mark_ordered_extent_truncated(ordered, cur - ordered->file_offset);
7592 
7593 		/*
7594 		 * If the ordered extent has finished, we're safe to delete all
7595 		 * the extent states of the range, otherwise
7596 		 * btrfs_finish_ordered_io() will get executed by endio for
7597 		 * other pages, so we can't delete extent states.
7598 		 */
7599 		if (btrfs_dec_test_ordered_pending(inode, &ordered,
7600 						   cur, range_end + 1 - cur)) {
7601 			btrfs_finish_ordered_io(ordered);
7602 			/*
7603 			 * The ordered extent has finished, now we're again
7604 			 * safe to delete all extent states of the range.
7605 			 */
7606 			extra_flags = EXTENT_CLEAR_ALL_BITS;
7607 		}
7608 next:
7609 		if (ordered)
7610 			btrfs_put_ordered_extent(ordered);
7611 		/*
7612 		 * Qgroup reserved space handler
7613 		 * Sector(s) here will be either:
7614 		 *
7615 		 * 1) Already written to disk or bio already finished
7616 		 *    Then its QGROUP_RESERVED bit in io_tree is already cleared.
7617 		 *    Qgroup will be handled by its qgroup_record then.
7618 		 *    btrfs_qgroup_free_data() call will do nothing here.
7619 		 *
7620 		 * 2) Not written to disk yet
7621 		 *    Then btrfs_qgroup_free_data() call will clear the
7622 		 *    QGROUP_RESERVED bit of its io_tree, and free the qgroup
7623 		 *    reserved data space.
7624 		 *    Since the IO will never happen for this page.
7625 		 */
7626 		btrfs_qgroup_free_data(inode, NULL, cur, range_end + 1 - cur, NULL);
7627 		if (!inode_evicting)
7628 			btrfs_clear_extent_bit(tree, cur, range_end, EXTENT_LOCKED |
7629 					       EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
7630 					       EXTENT_DEFRAG | extra_flags,
7631 					       &cached_state);
7632 		cur = range_end + 1;
7633 	}
7634 	btrfs_folio_clear_dirty(fs_info, folio, page_start, folio_size(folio));
7635 	btrfs_clear_folio_dirty_tag(folio);
7636 	if (!inode_evicting)
7637 		__btrfs_release_folio(folio, GFP_NOFS);
7638 	clear_folio_extent_mapped(folio);
7639 }
7640 
7641 static int btrfs_truncate(struct btrfs_inode *inode, bool skip_writeback)
7642 {
7643 	struct btrfs_truncate_control control = {
7644 		.inode = inode,
7645 		.ino = btrfs_ino(inode),
7646 		.min_type = BTRFS_EXTENT_DATA_KEY,
7647 		.clear_extent_range = true,
7648 		.new_size = inode->vfs_inode.i_size,
7649 	};
7650 	struct btrfs_root *root = inode->root;
7651 	struct btrfs_fs_info *fs_info = root->fs_info;
7652 	struct btrfs_block_rsv rsv;
7653 	int ret;
7654 	struct btrfs_trans_handle *trans;
7655 	const u64 min_size = btrfs_calc_metadata_size(fs_info, 1);
7656 	const u64 lock_start = round_down(inode->vfs_inode.i_size, fs_info->sectorsize);
7657 	const u64 i_size_up = round_up(inode->vfs_inode.i_size, fs_info->sectorsize);
7658 
7659 	/* Our inode is locked and the i_size can't be changed concurrently. */
7660 	btrfs_assert_inode_locked(inode);
7661 
7662 	if (!skip_writeback) {
7663 		ret = btrfs_wait_ordered_range(inode, lock_start, (u64)-1);
7664 		if (ret)
7665 			return ret;
7666 	}
7667 
7668 	/*
7669 	 * Yes ladies and gentlemen, this is indeed ugly.  We have a couple of
7670 	 * things going on here:
7671 	 *
7672 	 * 1) We need to reserve space to update our inode.
7673 	 *
7674 	 * 2) We need to have something to cache all the space that is going to
7675 	 * be free'd up by the truncate operation, but also have some slack
7676 	 * space reserved in case it uses space during the truncate (thank you
7677 	 * very much snapshotting).
7678 	 *
7679 	 * And we need these to be separate.  The fact is we can use a lot of
7680 	 * space doing the truncate, and we have no earthly idea how much space
7681 	 * we will use, so we need the truncate reservation to be separate so it
7682 	 * doesn't end up using space reserved for updating the inode.  We also
7683 	 * need to be able to stop the transaction and start a new one, which
7684 	 * means we need to be able to update the inode several times, and we
7685 	 * have no idea of knowing how many times that will be, so we can't just
7686 	 * reserve 1 item for the entirety of the operation, so that has to be
7687 	 * done separately as well.
7688 	 *
7689 	 * So that leaves us with
7690 	 *
7691 	 * 1) rsv - for the truncate reservation, which we will steal from the
7692 	 * transaction reservation.
7693 	 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
7694 	 * updating the inode.
7695 	 */
7696 	btrfs_init_metadata_block_rsv(fs_info, &rsv, BTRFS_BLOCK_RSV_TEMP);
7697 	rsv.size = min_size;
7698 	rsv.failfast = true;
7699 
7700 	/*
7701 	 * 1 for the truncate slack space
7702 	 * 1 for updating the inode.
7703 	 */
7704 	trans = btrfs_start_transaction(root, 2);
7705 	if (IS_ERR(trans)) {
7706 		ret = PTR_ERR(trans);
7707 		goto out;
7708 	}
7709 
7710 	/* Migrate the slack space for the truncate to our reserve */
7711 	ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, &rsv,
7712 				      min_size, false);
7713 	/*
7714 	 * We have reserved 2 metadata units when we started the transaction and
7715 	 * min_size matches 1 unit, so this should never fail, but if it does,
7716 	 * it's not critical we just fail truncation.
7717 	 */
7718 	if (WARN_ON(ret)) {
7719 		btrfs_end_transaction(trans);
7720 		goto out;
7721 	}
7722 
7723 	trans->block_rsv = &rsv;
7724 
7725 	while (1) {
7726 		struct extent_state *cached_state = NULL;
7727 
7728 		btrfs_lock_extent(&inode->io_tree, lock_start, (u64)-1, &cached_state);
7729 		/*
7730 		 * We want to drop from the next block forward in case this new
7731 		 * size is not block aligned since we will be keeping the last
7732 		 * block of the extent just the way it is.
7733 		 */
7734 		btrfs_drop_extent_map_range(inode, i_size_up, (u64)-1, false);
7735 
7736 		ret = btrfs_truncate_inode_items(trans, root, &control);
7737 
7738 		inode_sub_bytes(&inode->vfs_inode, control.sub_bytes);
7739 		btrfs_inode_safe_disk_i_size_write(inode, control.last_size);
7740 
7741 		btrfs_unlock_extent(&inode->io_tree, lock_start, (u64)-1, &cached_state);
7742 
7743 		trans->block_rsv = &fs_info->trans_block_rsv;
7744 		if (ret != -ENOSPC && ret != -EAGAIN)
7745 			break;
7746 
7747 		ret = btrfs_update_inode(trans, inode);
7748 		if (ret)
7749 			break;
7750 
7751 		btrfs_end_transaction(trans);
7752 		btrfs_btree_balance_dirty(fs_info);
7753 
7754 		trans = btrfs_start_transaction(root, 2);
7755 		if (IS_ERR(trans)) {
7756 			ret = PTR_ERR(trans);
7757 			trans = NULL;
7758 			break;
7759 		}
7760 
7761 		btrfs_block_rsv_release(fs_info, &rsv, -1, NULL);
7762 		ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
7763 					      &rsv, min_size, false);
7764 		/*
7765 		 * We have reserved 2 metadata units when we started the
7766 		 * transaction and min_size matches 1 unit, so this should never
7767 		 * fail, but if it does, it's not critical we just fail truncation.
7768 		 */
7769 		if (WARN_ON(ret))
7770 			break;
7771 
7772 		trans->block_rsv = &rsv;
7773 	}
7774 
7775 	/*
7776 	 * We can't call btrfs_truncate_block inside a trans handle as we could
7777 	 * deadlock with freeze, if we got BTRFS_NEED_TRUNCATE_BLOCK then we
7778 	 * know we've truncated everything except the last little bit, and can
7779 	 * do btrfs_truncate_block and then update the disk_i_size.
7780 	 */
7781 	if (ret == BTRFS_NEED_TRUNCATE_BLOCK) {
7782 		btrfs_end_transaction(trans);
7783 		btrfs_btree_balance_dirty(fs_info);
7784 
7785 		ret = btrfs_truncate_block(inode, inode->vfs_inode.i_size,
7786 					   inode->vfs_inode.i_size, (u64)-1);
7787 		if (ret)
7788 			goto out;
7789 		trans = btrfs_start_transaction(root, 1);
7790 		if (IS_ERR(trans)) {
7791 			ret = PTR_ERR(trans);
7792 			goto out;
7793 		}
7794 		btrfs_inode_safe_disk_i_size_write(inode, 0);
7795 	}
7796 
7797 	if (trans) {
7798 		int ret2;
7799 
7800 		trans->block_rsv = &fs_info->trans_block_rsv;
7801 		ret2 = btrfs_update_inode(trans, inode);
7802 		if (ret2 && !ret)
7803 			ret = ret2;
7804 
7805 		ret2 = btrfs_end_transaction(trans);
7806 		if (ret2 && !ret)
7807 			ret = ret2;
7808 		btrfs_btree_balance_dirty(fs_info);
7809 	}
7810 out:
7811 	btrfs_block_rsv_release(fs_info, &rsv, (u64)-1, NULL);
7812 	/*
7813 	 * So if we truncate and then write and fsync we normally would just
7814 	 * write the extents that changed, which is a problem if we need to
7815 	 * first truncate that entire inode.  So set this flag so we write out
7816 	 * all of the extents in the inode to the sync log so we're completely
7817 	 * safe.
7818 	 *
7819 	 * If no extents were dropped or trimmed we don't need to force the next
7820 	 * fsync to truncate all the inode's items from the log and re-log them
7821 	 * all. This means the truncate operation did not change the file size,
7822 	 * or changed it to a smaller size but there was only an implicit hole
7823 	 * between the old i_size and the new i_size, and there were no prealloc
7824 	 * extents beyond i_size to drop.
7825 	 */
7826 	if (control.extents_found > 0)
7827 		btrfs_set_inode_full_sync(inode);
7828 
7829 	return ret;
7830 }
7831 
7832 struct inode *btrfs_new_subvol_inode(struct mnt_idmap *idmap,
7833 				     struct inode *dir)
7834 {
7835 	struct inode *inode;
7836 
7837 	inode = new_inode(dir->i_sb);
7838 	if (inode) {
7839 		/*
7840 		 * Subvolumes don't inherit the sgid bit or the parent's gid if
7841 		 * the parent's sgid bit is set. This is probably a bug.
7842 		 */
7843 		inode_init_owner(idmap, inode, NULL,
7844 				 S_IFDIR | (~current_umask() & S_IRWXUGO));
7845 		inode->i_op = &btrfs_dir_inode_operations;
7846 		inode->i_fop = &btrfs_dir_file_operations;
7847 	}
7848 	return inode;
7849 }
7850 
7851 struct inode *btrfs_alloc_inode(struct super_block *sb)
7852 {
7853 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
7854 	struct btrfs_inode *ei;
7855 	struct inode *inode;
7856 
7857 	ei = alloc_inode_sb(sb, btrfs_inode_cachep, GFP_KERNEL);
7858 	if (!ei)
7859 		return NULL;
7860 
7861 	ei->root = NULL;
7862 	ei->generation = 0;
7863 	ei->last_trans = 0;
7864 	ei->last_sub_trans = 0;
7865 	ei->logged_trans = 0;
7866 	ei->delalloc_bytes = 0;
7867 	/* new_delalloc_bytes and last_dir_index_offset are in a union. */
7868 	ei->new_delalloc_bytes = 0;
7869 	ei->defrag_bytes = 0;
7870 	ei->disk_i_size = 0;
7871 	ei->flags = 0;
7872 	ei->ro_flags = 0;
7873 	/*
7874 	 * ->index_cnt will be properly initialized later when creating a new
7875 	 * inode (btrfs_create_new_inode()) or when reading an existing inode
7876 	 * from disk (btrfs_read_locked_inode()).
7877 	 */
7878 	ei->csum_bytes = 0;
7879 	ei->dir_index = 0;
7880 	ei->last_unlink_trans = 0;
7881 	ei->last_reflink_trans = 0;
7882 	ei->last_log_commit = 0;
7883 
7884 	spin_lock_init(&ei->lock);
7885 	ei->outstanding_extents = 0;
7886 	if (sb->s_magic != BTRFS_TEST_MAGIC)
7887 		btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
7888 					      BTRFS_BLOCK_RSV_DELALLOC);
7889 	ei->runtime_flags = 0;
7890 	ei->prop_compress = BTRFS_COMPRESS_NONE;
7891 	ei->defrag_compress = BTRFS_COMPRESS_NONE;
7892 
7893 	ei->delayed_node = NULL;
7894 
7895 	ei->i_otime_sec = 0;
7896 	ei->i_otime_nsec = 0;
7897 
7898 	inode = &ei->vfs_inode;
7899 	btrfs_extent_map_tree_init(&ei->extent_tree);
7900 
7901 	/* This io tree sets the valid inode. */
7902 	btrfs_extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO);
7903 	ei->io_tree.inode = ei;
7904 
7905 	ei->file_extent_tree = NULL;
7906 
7907 	mutex_init(&ei->log_mutex);
7908 	spin_lock_init(&ei->ordered_tree_lock);
7909 	ei->ordered_tree = RB_ROOT;
7910 	ei->ordered_tree_last = NULL;
7911 	INIT_LIST_HEAD(&ei->delalloc_inodes);
7912 	INIT_LIST_HEAD(&ei->delayed_iput);
7913 	init_rwsem(&ei->i_mmap_lock);
7914 
7915 	return inode;
7916 }
7917 
7918 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
7919 void btrfs_test_destroy_inode(struct inode *inode)
7920 {
7921 	btrfs_drop_extent_map_range(BTRFS_I(inode), 0, (u64)-1, false);
7922 	kfree(BTRFS_I(inode)->file_extent_tree);
7923 	kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
7924 }
7925 #endif
7926 
7927 void btrfs_free_inode(struct inode *inode)
7928 {
7929 	kfree(BTRFS_I(inode)->file_extent_tree);
7930 	kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
7931 }
7932 
7933 void btrfs_destroy_inode(struct inode *vfs_inode)
7934 {
7935 	struct btrfs_ordered_extent *ordered;
7936 	struct btrfs_inode *inode = BTRFS_I(vfs_inode);
7937 	struct btrfs_root *root = inode->root;
7938 	bool freespace_inode;
7939 
7940 	WARN_ON(!hlist_empty(&vfs_inode->i_dentry));
7941 	WARN_ON(vfs_inode->i_data.nrpages);
7942 	WARN_ON(inode->block_rsv.reserved);
7943 	WARN_ON(inode->block_rsv.size);
7944 	WARN_ON(inode->outstanding_extents);
7945 	if (!S_ISDIR(vfs_inode->i_mode)) {
7946 		WARN_ON(inode->delalloc_bytes);
7947 		WARN_ON(inode->new_delalloc_bytes);
7948 		WARN_ON(inode->csum_bytes);
7949 	}
7950 	if (!root || !btrfs_is_data_reloc_root(root))
7951 		WARN_ON(inode->defrag_bytes);
7952 
7953 	/*
7954 	 * This can happen where we create an inode, but somebody else also
7955 	 * created the same inode and we need to destroy the one we already
7956 	 * created.
7957 	 */
7958 	if (!root)
7959 		return;
7960 
7961 	/*
7962 	 * If this is a free space inode do not take the ordered extents lockdep
7963 	 * map.
7964 	 */
7965 	freespace_inode = btrfs_is_free_space_inode(inode);
7966 
7967 	while (1) {
7968 		ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
7969 		if (!ordered)
7970 			break;
7971 		else {
7972 			btrfs_err(root->fs_info,
7973 				  "found ordered extent %llu %llu on inode cleanup",
7974 				  ordered->file_offset, ordered->num_bytes);
7975 
7976 			if (!freespace_inode)
7977 				btrfs_lockdep_acquire(root->fs_info, btrfs_ordered_extent);
7978 
7979 			btrfs_remove_ordered_extent(ordered);
7980 			btrfs_put_ordered_extent(ordered);
7981 			btrfs_put_ordered_extent(ordered);
7982 		}
7983 	}
7984 	btrfs_qgroup_check_reserved_leak(inode);
7985 	btrfs_del_inode_from_root(inode);
7986 	btrfs_drop_extent_map_range(inode, 0, (u64)-1, false);
7987 	btrfs_inode_clear_file_extent_range(inode, 0, (u64)-1);
7988 	btrfs_put_root(inode->root);
7989 }
7990 
7991 int btrfs_drop_inode(struct inode *inode)
7992 {
7993 	struct btrfs_root *root = BTRFS_I(inode)->root;
7994 
7995 	if (root == NULL)
7996 		return 1;
7997 
7998 	/* the snap/subvol tree is on deleting */
7999 	if (btrfs_root_refs(&root->root_item) == 0)
8000 		return 1;
8001 	else
8002 		return inode_generic_drop(inode);
8003 }
8004 
8005 static void init_once(void *foo)
8006 {
8007 	struct btrfs_inode *ei = foo;
8008 
8009 	inode_init_once(&ei->vfs_inode);
8010 }
8011 
8012 void __cold btrfs_destroy_cachep(void)
8013 {
8014 	/*
8015 	 * Make sure all delayed rcu free inodes are flushed before we
8016 	 * destroy cache.
8017 	 */
8018 	rcu_barrier();
8019 	kmem_cache_destroy(btrfs_inode_cachep);
8020 }
8021 
8022 int __init btrfs_init_cachep(void)
8023 {
8024 	btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8025 			sizeof(struct btrfs_inode), 0,
8026 			SLAB_RECLAIM_ACCOUNT | SLAB_ACCOUNT,
8027 			init_once);
8028 	if (!btrfs_inode_cachep)
8029 		return -ENOMEM;
8030 
8031 	return 0;
8032 }
8033 
8034 static int btrfs_getattr(struct mnt_idmap *idmap,
8035 			 const struct path *path, struct kstat *stat,
8036 			 u32 request_mask, unsigned int flags)
8037 {
8038 	u64 delalloc_bytes;
8039 	u64 inode_bytes;
8040 	struct inode *inode = d_inode(path->dentry);
8041 	u32 blocksize = btrfs_sb(inode->i_sb)->sectorsize;
8042 	u32 bi_flags = BTRFS_I(inode)->flags;
8043 	u32 bi_ro_flags = BTRFS_I(inode)->ro_flags;
8044 
8045 	stat->result_mask |= STATX_BTIME;
8046 	stat->btime.tv_sec = BTRFS_I(inode)->i_otime_sec;
8047 	stat->btime.tv_nsec = BTRFS_I(inode)->i_otime_nsec;
8048 	if (bi_flags & BTRFS_INODE_APPEND)
8049 		stat->attributes |= STATX_ATTR_APPEND;
8050 	if (bi_flags & BTRFS_INODE_COMPRESS)
8051 		stat->attributes |= STATX_ATTR_COMPRESSED;
8052 	if (bi_flags & BTRFS_INODE_IMMUTABLE)
8053 		stat->attributes |= STATX_ATTR_IMMUTABLE;
8054 	if (bi_flags & BTRFS_INODE_NODUMP)
8055 		stat->attributes |= STATX_ATTR_NODUMP;
8056 	if (bi_ro_flags & BTRFS_INODE_RO_VERITY)
8057 		stat->attributes |= STATX_ATTR_VERITY;
8058 
8059 	stat->attributes_mask |= (STATX_ATTR_APPEND |
8060 				  STATX_ATTR_COMPRESSED |
8061 				  STATX_ATTR_IMMUTABLE |
8062 				  STATX_ATTR_NODUMP);
8063 
8064 	generic_fillattr(idmap, request_mask, inode, stat);
8065 	stat->dev = BTRFS_I(inode)->root->anon_dev;
8066 
8067 	stat->subvol = btrfs_root_id(BTRFS_I(inode)->root);
8068 	stat->result_mask |= STATX_SUBVOL;
8069 
8070 	spin_lock(&BTRFS_I(inode)->lock);
8071 	delalloc_bytes = BTRFS_I(inode)->new_delalloc_bytes;
8072 	inode_bytes = inode_get_bytes(inode);
8073 	spin_unlock(&BTRFS_I(inode)->lock);
8074 	stat->blocks = (ALIGN(inode_bytes, blocksize) +
8075 			ALIGN(delalloc_bytes, blocksize)) >> SECTOR_SHIFT;
8076 	return 0;
8077 }
8078 
8079 static int btrfs_rename_exchange(struct inode *old_dir,
8080 			      struct dentry *old_dentry,
8081 			      struct inode *new_dir,
8082 			      struct dentry *new_dentry)
8083 {
8084 	struct btrfs_fs_info *fs_info = inode_to_fs_info(old_dir);
8085 	struct btrfs_trans_handle *trans;
8086 	unsigned int trans_num_items;
8087 	struct btrfs_root *root = BTRFS_I(old_dir)->root;
8088 	struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8089 	struct inode *new_inode = new_dentry->d_inode;
8090 	struct inode *old_inode = old_dentry->d_inode;
8091 	struct btrfs_rename_ctx old_rename_ctx;
8092 	struct btrfs_rename_ctx new_rename_ctx;
8093 	u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
8094 	u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
8095 	u64 old_idx = 0;
8096 	u64 new_idx = 0;
8097 	int ret;
8098 	int ret2;
8099 	bool need_abort = false;
8100 	bool logs_pinned = false;
8101 	struct fscrypt_name old_fname, new_fname;
8102 	struct fscrypt_str *old_name, *new_name;
8103 
8104 	/*
8105 	 * For non-subvolumes allow exchange only within one subvolume, in the
8106 	 * same inode namespace. Two subvolumes (represented as directory) can
8107 	 * be exchanged as they're a logical link and have a fixed inode number.
8108 	 */
8109 	if (root != dest &&
8110 	    (old_ino != BTRFS_FIRST_FREE_OBJECTID ||
8111 	     new_ino != BTRFS_FIRST_FREE_OBJECTID))
8112 		return -EXDEV;
8113 
8114 	ret = fscrypt_setup_filename(old_dir, &old_dentry->d_name, 0, &old_fname);
8115 	if (ret)
8116 		return ret;
8117 
8118 	ret = fscrypt_setup_filename(new_dir, &new_dentry->d_name, 0, &new_fname);
8119 	if (ret) {
8120 		fscrypt_free_filename(&old_fname);
8121 		return ret;
8122 	}
8123 
8124 	old_name = &old_fname.disk_name;
8125 	new_name = &new_fname.disk_name;
8126 
8127 	/* close the race window with snapshot create/destroy ioctl */
8128 	if (old_ino == BTRFS_FIRST_FREE_OBJECTID ||
8129 	    new_ino == BTRFS_FIRST_FREE_OBJECTID)
8130 		down_read(&fs_info->subvol_sem);
8131 
8132 	/*
8133 	 * For each inode:
8134 	 * 1 to remove old dir item
8135 	 * 1 to remove old dir index
8136 	 * 1 to add new dir item
8137 	 * 1 to add new dir index
8138 	 * 1 to update parent inode
8139 	 *
8140 	 * If the parents are the same, we only need to account for one
8141 	 */
8142 	trans_num_items = (old_dir == new_dir ? 9 : 10);
8143 	if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8144 		/*
8145 		 * 1 to remove old root ref
8146 		 * 1 to remove old root backref
8147 		 * 1 to add new root ref
8148 		 * 1 to add new root backref
8149 		 */
8150 		trans_num_items += 4;
8151 	} else {
8152 		/*
8153 		 * 1 to update inode item
8154 		 * 1 to remove old inode ref
8155 		 * 1 to add new inode ref
8156 		 */
8157 		trans_num_items += 3;
8158 	}
8159 	if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
8160 		trans_num_items += 4;
8161 	else
8162 		trans_num_items += 3;
8163 	trans = btrfs_start_transaction(root, trans_num_items);
8164 	if (IS_ERR(trans)) {
8165 		ret = PTR_ERR(trans);
8166 		goto out_notrans;
8167 	}
8168 
8169 	if (dest != root) {
8170 		ret = btrfs_record_root_in_trans(trans, dest);
8171 		if (ret)
8172 			goto out_fail;
8173 	}
8174 
8175 	/*
8176 	 * We need to find a free sequence number both in the source and
8177 	 * in the destination directory for the exchange.
8178 	 */
8179 	ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
8180 	if (ret)
8181 		goto out_fail;
8182 	ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
8183 	if (ret)
8184 		goto out_fail;
8185 
8186 	BTRFS_I(old_inode)->dir_index = 0ULL;
8187 	BTRFS_I(new_inode)->dir_index = 0ULL;
8188 
8189 	/* Reference for the source. */
8190 	if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8191 		/* force full log commit if subvolume involved. */
8192 		btrfs_set_log_full_commit(trans);
8193 	} else {
8194 		ret = btrfs_insert_inode_ref(trans, dest, new_name, old_ino,
8195 					     btrfs_ino(BTRFS_I(new_dir)),
8196 					     old_idx);
8197 		if (ret)
8198 			goto out_fail;
8199 		need_abort = true;
8200 	}
8201 
8202 	/* And now for the dest. */
8203 	if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
8204 		/* force full log commit if subvolume involved. */
8205 		btrfs_set_log_full_commit(trans);
8206 	} else {
8207 		ret = btrfs_insert_inode_ref(trans, root, old_name, new_ino,
8208 					     btrfs_ino(BTRFS_I(old_dir)),
8209 					     new_idx);
8210 		if (ret) {
8211 			if (unlikely(need_abort))
8212 				btrfs_abort_transaction(trans, ret);
8213 			goto out_fail;
8214 		}
8215 	}
8216 
8217 	/* Update inode version and ctime/mtime. */
8218 	inode_inc_iversion(old_dir);
8219 	inode_inc_iversion(new_dir);
8220 	inode_inc_iversion(old_inode);
8221 	inode_inc_iversion(new_inode);
8222 	simple_rename_timestamp(old_dir, old_dentry, new_dir, new_dentry);
8223 
8224 	if (old_ino != BTRFS_FIRST_FREE_OBJECTID &&
8225 	    new_ino != BTRFS_FIRST_FREE_OBJECTID) {
8226 		/*
8227 		 * If we are renaming in the same directory (and it's not for
8228 		 * root entries) pin the log early to prevent any concurrent
8229 		 * task from logging the directory after we removed the old
8230 		 * entries and before we add the new entries, otherwise that
8231 		 * task can sync a log without any entry for the inodes we are
8232 		 * renaming and therefore replaying that log, if a power failure
8233 		 * happens after syncing the log, would result in deleting the
8234 		 * inodes.
8235 		 *
8236 		 * If the rename affects two different directories, we want to
8237 		 * make sure the that there's no log commit that contains
8238 		 * updates for only one of the directories but not for the
8239 		 * other.
8240 		 *
8241 		 * If we are renaming an entry for a root, we don't care about
8242 		 * log updates since we called btrfs_set_log_full_commit().
8243 		 */
8244 		btrfs_pin_log_trans(root);
8245 		btrfs_pin_log_trans(dest);
8246 		logs_pinned = true;
8247 	}
8248 
8249 	if (old_dentry->d_parent != new_dentry->d_parent) {
8250 		btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
8251 					BTRFS_I(old_inode), true);
8252 		btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
8253 					BTRFS_I(new_inode), true);
8254 	}
8255 
8256 	/* src is a subvolume */
8257 	if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8258 		ret = btrfs_unlink_subvol(trans, BTRFS_I(old_dir), old_dentry);
8259 		if (unlikely(ret)) {
8260 			btrfs_abort_transaction(trans, ret);
8261 			goto out_fail;
8262 		}
8263 	} else { /* src is an inode */
8264 		ret = __btrfs_unlink_inode(trans, BTRFS_I(old_dir),
8265 					   BTRFS_I(old_dentry->d_inode),
8266 					   old_name, &old_rename_ctx);
8267 		if (unlikely(ret)) {
8268 			btrfs_abort_transaction(trans, ret);
8269 			goto out_fail;
8270 		}
8271 		ret = btrfs_update_inode(trans, BTRFS_I(old_inode));
8272 		if (unlikely(ret)) {
8273 			btrfs_abort_transaction(trans, ret);
8274 			goto out_fail;
8275 		}
8276 	}
8277 
8278 	/* dest is a subvolume */
8279 	if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
8280 		ret = btrfs_unlink_subvol(trans, BTRFS_I(new_dir), new_dentry);
8281 		if (unlikely(ret)) {
8282 			btrfs_abort_transaction(trans, ret);
8283 			goto out_fail;
8284 		}
8285 	} else { /* dest is an inode */
8286 		ret = __btrfs_unlink_inode(trans, BTRFS_I(new_dir),
8287 					   BTRFS_I(new_dentry->d_inode),
8288 					   new_name, &new_rename_ctx);
8289 		if (unlikely(ret)) {
8290 			btrfs_abort_transaction(trans, ret);
8291 			goto out_fail;
8292 		}
8293 		ret = btrfs_update_inode(trans, BTRFS_I(new_inode));
8294 		if (unlikely(ret)) {
8295 			btrfs_abort_transaction(trans, ret);
8296 			goto out_fail;
8297 		}
8298 	}
8299 
8300 	ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
8301 			     new_name, false, old_idx);
8302 	if (unlikely(ret)) {
8303 		btrfs_abort_transaction(trans, ret);
8304 		goto out_fail;
8305 	}
8306 
8307 	ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
8308 			     old_name, false, new_idx);
8309 	if (unlikely(ret)) {
8310 		btrfs_abort_transaction(trans, ret);
8311 		goto out_fail;
8312 	}
8313 
8314 	if (old_inode->i_nlink == 1)
8315 		BTRFS_I(old_inode)->dir_index = old_idx;
8316 	if (new_inode->i_nlink == 1)
8317 		BTRFS_I(new_inode)->dir_index = new_idx;
8318 
8319 	/*
8320 	 * Do the log updates for all inodes.
8321 	 *
8322 	 * If either entry is for a root we don't need to update the logs since
8323 	 * we've called btrfs_set_log_full_commit() before.
8324 	 */
8325 	if (logs_pinned) {
8326 		btrfs_log_new_name(trans, old_dentry, BTRFS_I(old_dir),
8327 				   old_rename_ctx.index, new_dentry->d_parent);
8328 		btrfs_log_new_name(trans, new_dentry, BTRFS_I(new_dir),
8329 				   new_rename_ctx.index, old_dentry->d_parent);
8330 	}
8331 
8332 out_fail:
8333 	if (logs_pinned) {
8334 		btrfs_end_log_trans(root);
8335 		btrfs_end_log_trans(dest);
8336 	}
8337 	ret2 = btrfs_end_transaction(trans);
8338 	ret = ret ? ret : ret2;
8339 out_notrans:
8340 	if (new_ino == BTRFS_FIRST_FREE_OBJECTID ||
8341 	    old_ino == BTRFS_FIRST_FREE_OBJECTID)
8342 		up_read(&fs_info->subvol_sem);
8343 
8344 	fscrypt_free_filename(&new_fname);
8345 	fscrypt_free_filename(&old_fname);
8346 	return ret;
8347 }
8348 
8349 static struct inode *new_whiteout_inode(struct mnt_idmap *idmap,
8350 					struct inode *dir)
8351 {
8352 	struct inode *inode;
8353 
8354 	inode = new_inode(dir->i_sb);
8355 	if (inode) {
8356 		inode_init_owner(idmap, inode, dir,
8357 				 S_IFCHR | WHITEOUT_MODE);
8358 		inode->i_op = &btrfs_special_inode_operations;
8359 		init_special_inode(inode, inode->i_mode, WHITEOUT_DEV);
8360 	}
8361 	return inode;
8362 }
8363 
8364 static int btrfs_rename(struct mnt_idmap *idmap,
8365 			struct inode *old_dir, struct dentry *old_dentry,
8366 			struct inode *new_dir, struct dentry *new_dentry,
8367 			unsigned int flags)
8368 {
8369 	struct btrfs_fs_info *fs_info = inode_to_fs_info(old_dir);
8370 	struct btrfs_new_inode_args whiteout_args = {
8371 		.dir = old_dir,
8372 		.dentry = old_dentry,
8373 	};
8374 	struct btrfs_trans_handle *trans;
8375 	unsigned int trans_num_items;
8376 	struct btrfs_root *root = BTRFS_I(old_dir)->root;
8377 	struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8378 	struct inode *new_inode = d_inode(new_dentry);
8379 	struct inode *old_inode = d_inode(old_dentry);
8380 	struct btrfs_rename_ctx rename_ctx;
8381 	u64 index = 0;
8382 	int ret;
8383 	int ret2;
8384 	u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
8385 	struct fscrypt_name old_fname, new_fname;
8386 	bool logs_pinned = false;
8387 
8388 	if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
8389 		return -EPERM;
8390 
8391 	/* we only allow rename subvolume link between subvolumes */
8392 	if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
8393 		return -EXDEV;
8394 
8395 	if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
8396 	    (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
8397 		return -ENOTEMPTY;
8398 
8399 	if (S_ISDIR(old_inode->i_mode) && new_inode &&
8400 	    new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
8401 		return -ENOTEMPTY;
8402 
8403 	ret = fscrypt_setup_filename(old_dir, &old_dentry->d_name, 0, &old_fname);
8404 	if (ret)
8405 		return ret;
8406 
8407 	ret = fscrypt_setup_filename(new_dir, &new_dentry->d_name, 0, &new_fname);
8408 	if (ret) {
8409 		fscrypt_free_filename(&old_fname);
8410 		return ret;
8411 	}
8412 
8413 	/* check for collisions, even if the  name isn't there */
8414 	ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino, &new_fname.disk_name);
8415 	if (ret) {
8416 		if (ret == -EEXIST) {
8417 			/* we shouldn't get
8418 			 * eexist without a new_inode */
8419 			if (WARN_ON(!new_inode)) {
8420 				goto out_fscrypt_names;
8421 			}
8422 		} else {
8423 			/* maybe -EOVERFLOW */
8424 			goto out_fscrypt_names;
8425 		}
8426 	}
8427 	ret = 0;
8428 
8429 	/*
8430 	 * we're using rename to replace one file with another.  Start IO on it
8431 	 * now so  we don't add too much work to the end of the transaction
8432 	 */
8433 	if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
8434 		filemap_flush(old_inode->i_mapping);
8435 
8436 	if (flags & RENAME_WHITEOUT) {
8437 		whiteout_args.inode = new_whiteout_inode(idmap, old_dir);
8438 		if (!whiteout_args.inode) {
8439 			ret = -ENOMEM;
8440 			goto out_fscrypt_names;
8441 		}
8442 		ret = btrfs_new_inode_prepare(&whiteout_args, &trans_num_items);
8443 		if (ret)
8444 			goto out_whiteout_inode;
8445 	} else {
8446 		/* 1 to update the old parent inode. */
8447 		trans_num_items = 1;
8448 	}
8449 
8450 	if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8451 		/* Close the race window with snapshot create/destroy ioctl */
8452 		down_read(&fs_info->subvol_sem);
8453 		/*
8454 		 * 1 to remove old root ref
8455 		 * 1 to remove old root backref
8456 		 * 1 to add new root ref
8457 		 * 1 to add new root backref
8458 		 */
8459 		trans_num_items += 4;
8460 	} else {
8461 		/*
8462 		 * 1 to update inode
8463 		 * 1 to remove old inode ref
8464 		 * 1 to add new inode ref
8465 		 */
8466 		trans_num_items += 3;
8467 	}
8468 	/*
8469 	 * 1 to remove old dir item
8470 	 * 1 to remove old dir index
8471 	 * 1 to add new dir item
8472 	 * 1 to add new dir index
8473 	 */
8474 	trans_num_items += 4;
8475 	/* 1 to update new parent inode if it's not the same as the old parent */
8476 	if (new_dir != old_dir)
8477 		trans_num_items++;
8478 	if (new_inode) {
8479 		/*
8480 		 * 1 to update inode
8481 		 * 1 to remove inode ref
8482 		 * 1 to remove dir item
8483 		 * 1 to remove dir index
8484 		 * 1 to possibly add orphan item
8485 		 */
8486 		trans_num_items += 5;
8487 	}
8488 	trans = btrfs_start_transaction(root, trans_num_items);
8489 	if (IS_ERR(trans)) {
8490 		ret = PTR_ERR(trans);
8491 		goto out_notrans;
8492 	}
8493 
8494 	if (dest != root) {
8495 		ret = btrfs_record_root_in_trans(trans, dest);
8496 		if (ret)
8497 			goto out_fail;
8498 	}
8499 
8500 	ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
8501 	if (ret)
8502 		goto out_fail;
8503 
8504 	BTRFS_I(old_inode)->dir_index = 0ULL;
8505 	if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8506 		/* force full log commit if subvolume involved. */
8507 		btrfs_set_log_full_commit(trans);
8508 	} else {
8509 		ret = btrfs_insert_inode_ref(trans, dest, &new_fname.disk_name,
8510 					     old_ino, btrfs_ino(BTRFS_I(new_dir)),
8511 					     index);
8512 		if (ret)
8513 			goto out_fail;
8514 	}
8515 
8516 	inode_inc_iversion(old_dir);
8517 	inode_inc_iversion(new_dir);
8518 	inode_inc_iversion(old_inode);
8519 	simple_rename_timestamp(old_dir, old_dentry, new_dir, new_dentry);
8520 
8521 	if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
8522 		/*
8523 		 * If we are renaming in the same directory (and it's not a
8524 		 * root entry) pin the log to prevent any concurrent task from
8525 		 * logging the directory after we removed the old entry and
8526 		 * before we add the new entry, otherwise that task can sync
8527 		 * a log without any entry for the inode we are renaming and
8528 		 * therefore replaying that log, if a power failure happens
8529 		 * after syncing the log, would result in deleting the inode.
8530 		 *
8531 		 * If the rename affects two different directories, we want to
8532 		 * make sure the that there's no log commit that contains
8533 		 * updates for only one of the directories but not for the
8534 		 * other.
8535 		 *
8536 		 * If we are renaming an entry for a root, we don't care about
8537 		 * log updates since we called btrfs_set_log_full_commit().
8538 		 */
8539 		btrfs_pin_log_trans(root);
8540 		btrfs_pin_log_trans(dest);
8541 		logs_pinned = true;
8542 	}
8543 
8544 	if (old_dentry->d_parent != new_dentry->d_parent)
8545 		btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
8546 					BTRFS_I(old_inode), true);
8547 
8548 	if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8549 		ret = btrfs_unlink_subvol(trans, BTRFS_I(old_dir), old_dentry);
8550 		if (unlikely(ret)) {
8551 			btrfs_abort_transaction(trans, ret);
8552 			goto out_fail;
8553 		}
8554 	} else {
8555 		ret = __btrfs_unlink_inode(trans, BTRFS_I(old_dir),
8556 					   BTRFS_I(d_inode(old_dentry)),
8557 					   &old_fname.disk_name, &rename_ctx);
8558 		if (unlikely(ret)) {
8559 			btrfs_abort_transaction(trans, ret);
8560 			goto out_fail;
8561 		}
8562 		ret = btrfs_update_inode(trans, BTRFS_I(old_inode));
8563 		if (unlikely(ret)) {
8564 			btrfs_abort_transaction(trans, ret);
8565 			goto out_fail;
8566 		}
8567 	}
8568 
8569 	if (new_inode) {
8570 		inode_inc_iversion(new_inode);
8571 		if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
8572 			     BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
8573 			ret = btrfs_unlink_subvol(trans, BTRFS_I(new_dir), new_dentry);
8574 			if (unlikely(ret)) {
8575 				btrfs_abort_transaction(trans, ret);
8576 				goto out_fail;
8577 			}
8578 			BUG_ON(new_inode->i_nlink == 0);
8579 		} else {
8580 			ret = btrfs_unlink_inode(trans, BTRFS_I(new_dir),
8581 						 BTRFS_I(d_inode(new_dentry)),
8582 						 &new_fname.disk_name);
8583 			if (unlikely(ret)) {
8584 				btrfs_abort_transaction(trans, ret);
8585 				goto out_fail;
8586 			}
8587 		}
8588 		if (new_inode->i_nlink == 0) {
8589 			ret = btrfs_orphan_add(trans,
8590 					BTRFS_I(d_inode(new_dentry)));
8591 			if (unlikely(ret)) {
8592 				btrfs_abort_transaction(trans, ret);
8593 				goto out_fail;
8594 			}
8595 		}
8596 	}
8597 
8598 	ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
8599 			     &new_fname.disk_name, false, index);
8600 	if (unlikely(ret)) {
8601 		btrfs_abort_transaction(trans, ret);
8602 		goto out_fail;
8603 	}
8604 
8605 	if (old_inode->i_nlink == 1)
8606 		BTRFS_I(old_inode)->dir_index = index;
8607 
8608 	if (logs_pinned)
8609 		btrfs_log_new_name(trans, old_dentry, BTRFS_I(old_dir),
8610 				   rename_ctx.index, new_dentry->d_parent);
8611 
8612 	if (flags & RENAME_WHITEOUT) {
8613 		ret = btrfs_create_new_inode(trans, &whiteout_args);
8614 		if (unlikely(ret)) {
8615 			btrfs_abort_transaction(trans, ret);
8616 			goto out_fail;
8617 		} else {
8618 			unlock_new_inode(whiteout_args.inode);
8619 			iput(whiteout_args.inode);
8620 			whiteout_args.inode = NULL;
8621 		}
8622 	}
8623 out_fail:
8624 	if (logs_pinned) {
8625 		btrfs_end_log_trans(root);
8626 		btrfs_end_log_trans(dest);
8627 	}
8628 	ret2 = btrfs_end_transaction(trans);
8629 	ret = ret ? ret : ret2;
8630 out_notrans:
8631 	if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8632 		up_read(&fs_info->subvol_sem);
8633 	if (flags & RENAME_WHITEOUT)
8634 		btrfs_new_inode_args_destroy(&whiteout_args);
8635 out_whiteout_inode:
8636 	if (flags & RENAME_WHITEOUT)
8637 		iput(whiteout_args.inode);
8638 out_fscrypt_names:
8639 	fscrypt_free_filename(&old_fname);
8640 	fscrypt_free_filename(&new_fname);
8641 	return ret;
8642 }
8643 
8644 static int btrfs_rename2(struct mnt_idmap *idmap, struct inode *old_dir,
8645 			 struct dentry *old_dentry, struct inode *new_dir,
8646 			 struct dentry *new_dentry, unsigned int flags)
8647 {
8648 	int ret;
8649 
8650 	if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
8651 		return -EINVAL;
8652 
8653 	if (flags & RENAME_EXCHANGE)
8654 		ret = btrfs_rename_exchange(old_dir, old_dentry, new_dir,
8655 					    new_dentry);
8656 	else
8657 		ret = btrfs_rename(idmap, old_dir, old_dentry, new_dir,
8658 				   new_dentry, flags);
8659 
8660 	btrfs_btree_balance_dirty(BTRFS_I(new_dir)->root->fs_info);
8661 
8662 	return ret;
8663 }
8664 
8665 struct btrfs_delalloc_work {
8666 	struct inode *inode;
8667 	struct completion completion;
8668 	struct list_head list;
8669 	struct btrfs_work work;
8670 };
8671 
8672 static void btrfs_run_delalloc_work(struct btrfs_work *work)
8673 {
8674 	struct btrfs_delalloc_work *delalloc_work;
8675 	struct inode *inode;
8676 
8677 	delalloc_work = container_of(work, struct btrfs_delalloc_work,
8678 				     work);
8679 	inode = delalloc_work->inode;
8680 	filemap_flush(inode->i_mapping);
8681 	if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8682 				&BTRFS_I(inode)->runtime_flags))
8683 		filemap_flush(inode->i_mapping);
8684 
8685 	iput(inode);
8686 	complete(&delalloc_work->completion);
8687 }
8688 
8689 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
8690 {
8691 	struct btrfs_delalloc_work *work;
8692 
8693 	work = kmalloc_obj(*work, GFP_NOFS);
8694 	if (!work)
8695 		return NULL;
8696 
8697 	init_completion(&work->completion);
8698 	INIT_LIST_HEAD(&work->list);
8699 	work->inode = inode;
8700 	btrfs_init_work(&work->work, btrfs_run_delalloc_work, NULL);
8701 
8702 	return work;
8703 }
8704 
8705 /*
8706  * some fairly slow code that needs optimization. This walks the list
8707  * of all the inodes with pending delalloc and forces them to disk.
8708  */
8709 static int start_delalloc_inodes(struct btrfs_root *root, long *nr_to_write,
8710 				 bool snapshot, bool in_reclaim_context)
8711 {
8712 	struct btrfs_delalloc_work *work, *next;
8713 	LIST_HEAD(works);
8714 	LIST_HEAD(splice);
8715 	int ret = 0;
8716 
8717 	mutex_lock(&root->delalloc_mutex);
8718 	spin_lock(&root->delalloc_lock);
8719 	list_splice_init(&root->delalloc_inodes, &splice);
8720 	while (!list_empty(&splice)) {
8721 		struct btrfs_inode *inode;
8722 		struct inode *tmp_inode;
8723 
8724 		inode = list_first_entry(&splice, struct btrfs_inode, delalloc_inodes);
8725 
8726 		list_move_tail(&inode->delalloc_inodes, &root->delalloc_inodes);
8727 
8728 		if (in_reclaim_context &&
8729 		    test_bit(BTRFS_INODE_NO_DELALLOC_FLUSH, &inode->runtime_flags))
8730 			continue;
8731 
8732 		tmp_inode = igrab(&inode->vfs_inode);
8733 		if (!tmp_inode) {
8734 			cond_resched_lock(&root->delalloc_lock);
8735 			continue;
8736 		}
8737 		spin_unlock(&root->delalloc_lock);
8738 
8739 		if (snapshot)
8740 			set_bit(BTRFS_INODE_SNAPSHOT_FLUSH, &inode->runtime_flags);
8741 		if (nr_to_write == NULL) {
8742 			work = btrfs_alloc_delalloc_work(tmp_inode);
8743 			if (!work) {
8744 				iput(tmp_inode);
8745 				ret = -ENOMEM;
8746 				goto out;
8747 			}
8748 			list_add_tail(&work->list, &works);
8749 			btrfs_queue_work(root->fs_info->flush_workers,
8750 					 &work->work);
8751 		} else {
8752 			ret = filemap_flush_nr(tmp_inode->i_mapping,
8753 					nr_to_write);
8754 			btrfs_add_delayed_iput(inode);
8755 
8756 			if (ret || *nr_to_write <= 0)
8757 				goto out;
8758 		}
8759 		cond_resched();
8760 		spin_lock(&root->delalloc_lock);
8761 	}
8762 	spin_unlock(&root->delalloc_lock);
8763 
8764 out:
8765 	list_for_each_entry_safe(work, next, &works, list) {
8766 		list_del_init(&work->list);
8767 		wait_for_completion(&work->completion);
8768 		kfree(work);
8769 	}
8770 
8771 	if (!list_empty(&splice)) {
8772 		spin_lock(&root->delalloc_lock);
8773 		list_splice_tail(&splice, &root->delalloc_inodes);
8774 		spin_unlock(&root->delalloc_lock);
8775 	}
8776 	mutex_unlock(&root->delalloc_mutex);
8777 	return ret;
8778 }
8779 
8780 int btrfs_start_delalloc_snapshot(struct btrfs_root *root, bool in_reclaim_context)
8781 {
8782 	struct btrfs_fs_info *fs_info = root->fs_info;
8783 
8784 	if (unlikely(BTRFS_FS_ERROR(fs_info)))
8785 		return -EROFS;
8786 	return start_delalloc_inodes(root, NULL, true, in_reclaim_context);
8787 }
8788 
8789 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, long nr,
8790 			       bool in_reclaim_context)
8791 {
8792 	long *nr_to_write = nr == LONG_MAX ? NULL : &nr;
8793 	struct btrfs_root *root;
8794 	LIST_HEAD(splice);
8795 	int ret;
8796 
8797 	if (unlikely(BTRFS_FS_ERROR(fs_info)))
8798 		return -EROFS;
8799 
8800 	mutex_lock(&fs_info->delalloc_root_mutex);
8801 	spin_lock(&fs_info->delalloc_root_lock);
8802 	list_splice_init(&fs_info->delalloc_roots, &splice);
8803 	while (!list_empty(&splice)) {
8804 		root = list_first_entry(&splice, struct btrfs_root,
8805 					delalloc_root);
8806 		root = btrfs_grab_root(root);
8807 		BUG_ON(!root);
8808 		list_move_tail(&root->delalloc_root,
8809 			       &fs_info->delalloc_roots);
8810 		spin_unlock(&fs_info->delalloc_root_lock);
8811 
8812 		ret = start_delalloc_inodes(root, nr_to_write, false,
8813 				in_reclaim_context);
8814 		btrfs_put_root(root);
8815 		if (ret < 0 || nr <= 0)
8816 			goto out;
8817 		spin_lock(&fs_info->delalloc_root_lock);
8818 	}
8819 	spin_unlock(&fs_info->delalloc_root_lock);
8820 
8821 	ret = 0;
8822 out:
8823 	if (!list_empty(&splice)) {
8824 		spin_lock(&fs_info->delalloc_root_lock);
8825 		list_splice_tail(&splice, &fs_info->delalloc_roots);
8826 		spin_unlock(&fs_info->delalloc_root_lock);
8827 	}
8828 	mutex_unlock(&fs_info->delalloc_root_mutex);
8829 	return ret;
8830 }
8831 
8832 static int btrfs_symlink(struct mnt_idmap *idmap, struct inode *dir,
8833 			 struct dentry *dentry, const char *symname)
8834 {
8835 	struct btrfs_fs_info *fs_info = inode_to_fs_info(dir);
8836 	struct btrfs_trans_handle *trans;
8837 	struct btrfs_root *root = BTRFS_I(dir)->root;
8838 	struct btrfs_path *path;
8839 	struct btrfs_key key;
8840 	struct inode *inode;
8841 	struct btrfs_new_inode_args new_inode_args = {
8842 		.dir = dir,
8843 		.dentry = dentry,
8844 	};
8845 	unsigned int trans_num_items;
8846 	int ret;
8847 	int name_len;
8848 	int datasize;
8849 	unsigned long ptr;
8850 	struct btrfs_file_extent_item *ei;
8851 	struct extent_buffer *leaf;
8852 
8853 	name_len = strlen(symname);
8854 	/*
8855 	 * Symlinks utilize uncompressed inline extent data, which should not
8856 	 * reach block size.
8857 	 */
8858 	if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
8859 	    name_len >= fs_info->sectorsize)
8860 		return -ENAMETOOLONG;
8861 
8862 	inode = new_inode(dir->i_sb);
8863 	if (!inode)
8864 		return -ENOMEM;
8865 	inode_init_owner(idmap, inode, dir, S_IFLNK | S_IRWXUGO);
8866 	inode->i_op = &btrfs_symlink_inode_operations;
8867 	inode_nohighmem(inode);
8868 	inode->i_mapping->a_ops = &btrfs_aops;
8869 	btrfs_i_size_write(BTRFS_I(inode), name_len);
8870 	inode_set_bytes(inode, name_len);
8871 
8872 	new_inode_args.inode = inode;
8873 	ret = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
8874 	if (ret)
8875 		goto out_inode;
8876 	/* 1 additional item for the inline extent */
8877 	trans_num_items++;
8878 
8879 	trans = btrfs_start_transaction(root, trans_num_items);
8880 	if (IS_ERR(trans)) {
8881 		ret = PTR_ERR(trans);
8882 		goto out_new_inode_args;
8883 	}
8884 
8885 	ret = btrfs_create_new_inode(trans, &new_inode_args);
8886 	if (ret)
8887 		goto out;
8888 
8889 	path = btrfs_alloc_path();
8890 	if (unlikely(!path)) {
8891 		ret = -ENOMEM;
8892 		btrfs_abort_transaction(trans, ret);
8893 		discard_new_inode(inode);
8894 		inode = NULL;
8895 		goto out;
8896 	}
8897 	key.objectid = btrfs_ino(BTRFS_I(inode));
8898 	key.type = BTRFS_EXTENT_DATA_KEY;
8899 	key.offset = 0;
8900 	datasize = btrfs_file_extent_calc_inline_size(name_len);
8901 	ret = btrfs_insert_empty_item(trans, root, path, &key, datasize);
8902 	if (unlikely(ret)) {
8903 		btrfs_abort_transaction(trans, ret);
8904 		btrfs_free_path(path);
8905 		discard_new_inode(inode);
8906 		inode = NULL;
8907 		goto out;
8908 	}
8909 	leaf = path->nodes[0];
8910 	ei = btrfs_item_ptr(leaf, path->slots[0],
8911 			    struct btrfs_file_extent_item);
8912 	btrfs_set_file_extent_generation(leaf, ei, trans->transid);
8913 	btrfs_set_file_extent_type(leaf, ei,
8914 				   BTRFS_FILE_EXTENT_INLINE);
8915 	btrfs_set_file_extent_encryption(leaf, ei, 0);
8916 	btrfs_set_file_extent_compression(leaf, ei, 0);
8917 	btrfs_set_file_extent_other_encoding(leaf, ei, 0);
8918 	btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
8919 
8920 	ptr = btrfs_file_extent_inline_start(ei);
8921 	write_extent_buffer(leaf, symname, ptr, name_len);
8922 	btrfs_free_path(path);
8923 
8924 	d_instantiate_new(dentry, inode);
8925 	ret = 0;
8926 out:
8927 	btrfs_end_transaction(trans);
8928 	btrfs_btree_balance_dirty(fs_info);
8929 out_new_inode_args:
8930 	btrfs_new_inode_args_destroy(&new_inode_args);
8931 out_inode:
8932 	if (ret)
8933 		iput(inode);
8934 	return ret;
8935 }
8936 
8937 static struct btrfs_trans_handle *insert_prealloc_file_extent(
8938 				       struct btrfs_trans_handle *trans_in,
8939 				       struct btrfs_inode *inode,
8940 				       struct btrfs_key *ins,
8941 				       u64 file_offset)
8942 {
8943 	struct btrfs_file_extent_item stack_fi;
8944 	struct btrfs_replace_extent_info extent_info;
8945 	struct btrfs_trans_handle *trans = trans_in;
8946 	struct btrfs_path *path;
8947 	u64 start = ins->objectid;
8948 	u64 len = ins->offset;
8949 	u64 qgroup_released = 0;
8950 	int ret;
8951 
8952 	memset(&stack_fi, 0, sizeof(stack_fi));
8953 
8954 	btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_PREALLOC);
8955 	btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, start);
8956 	btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi, len);
8957 	btrfs_set_stack_file_extent_num_bytes(&stack_fi, len);
8958 	btrfs_set_stack_file_extent_ram_bytes(&stack_fi, len);
8959 	btrfs_set_stack_file_extent_compression(&stack_fi, BTRFS_COMPRESS_NONE);
8960 	/* Encryption and other encoding is reserved and all 0 */
8961 
8962 	ret = btrfs_qgroup_release_data(inode, file_offset, len, &qgroup_released);
8963 	if (ret < 0)
8964 		return ERR_PTR(ret);
8965 
8966 	if (trans) {
8967 		ret = insert_reserved_file_extent(trans, inode,
8968 						  file_offset, &stack_fi,
8969 						  true, qgroup_released);
8970 		if (ret)
8971 			goto free_qgroup;
8972 		return trans;
8973 	}
8974 
8975 	extent_info.disk_offset = start;
8976 	extent_info.disk_len = len;
8977 	extent_info.data_offset = 0;
8978 	extent_info.data_len = len;
8979 	extent_info.file_offset = file_offset;
8980 	extent_info.extent_buf = (char *)&stack_fi;
8981 	extent_info.is_new_extent = true;
8982 	extent_info.update_times = true;
8983 	extent_info.qgroup_reserved = qgroup_released;
8984 	extent_info.insertions = 0;
8985 
8986 	path = btrfs_alloc_path();
8987 	if (!path) {
8988 		ret = -ENOMEM;
8989 		goto free_qgroup;
8990 	}
8991 
8992 	ret = btrfs_replace_file_extents(inode, path, file_offset,
8993 				     file_offset + len - 1, &extent_info,
8994 				     &trans);
8995 	btrfs_free_path(path);
8996 	if (ret)
8997 		goto free_qgroup;
8998 	return trans;
8999 
9000 free_qgroup:
9001 	/*
9002 	 * We have released qgroup data range at the beginning of the function,
9003 	 * and normally qgroup_released bytes will be freed when committing
9004 	 * transaction.
9005 	 * But if we error out early, we have to free what we have released
9006 	 * or we leak qgroup data reservation.
9007 	 */
9008 	btrfs_qgroup_free_refroot(inode->root->fs_info,
9009 			btrfs_root_id(inode->root), qgroup_released,
9010 			BTRFS_QGROUP_RSV_DATA);
9011 	return ERR_PTR(ret);
9012 }
9013 
9014 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
9015 				       u64 start, u64 num_bytes, u64 min_size,
9016 				       loff_t actual_len, u64 *alloc_hint,
9017 				       struct btrfs_trans_handle *trans)
9018 {
9019 	struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
9020 	struct extent_map *em;
9021 	struct btrfs_root *root = BTRFS_I(inode)->root;
9022 	struct btrfs_key ins;
9023 	u64 cur_offset = start;
9024 	u64 clear_offset = start;
9025 	u64 i_size;
9026 	u64 cur_bytes;
9027 	u64 last_alloc = (u64)-1;
9028 	int ret = 0;
9029 	bool own_trans = true;
9030 	u64 end = start + num_bytes - 1;
9031 
9032 	if (trans)
9033 		own_trans = false;
9034 	while (num_bytes > 0) {
9035 		cur_bytes = min_t(u64, num_bytes, SZ_256M);
9036 		cur_bytes = max(cur_bytes, min_size);
9037 		/*
9038 		 * If we are severely fragmented we could end up with really
9039 		 * small allocations, so if the allocator is returning small
9040 		 * chunks lets make its job easier by only searching for those
9041 		 * sized chunks.
9042 		 */
9043 		cur_bytes = min(cur_bytes, last_alloc);
9044 		ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
9045 				min_size, 0, *alloc_hint, &ins, true, false);
9046 		if (ret)
9047 			break;
9048 
9049 		/*
9050 		 * We've reserved this space, and thus converted it from
9051 		 * ->bytes_may_use to ->bytes_reserved.  Any error that happens
9052 		 * from here on out we will only need to clear our reservation
9053 		 * for the remaining unreserved area, so advance our
9054 		 * clear_offset by our extent size.
9055 		 */
9056 		clear_offset += ins.offset;
9057 
9058 		last_alloc = ins.offset;
9059 		trans = insert_prealloc_file_extent(trans, BTRFS_I(inode),
9060 						    &ins, cur_offset);
9061 		/*
9062 		 * Now that we inserted the prealloc extent we can finally
9063 		 * decrement the number of reservations in the block group.
9064 		 * If we did it before, we could race with relocation and have
9065 		 * relocation miss the reserved extent, making it fail later.
9066 		 */
9067 		btrfs_dec_block_group_reservations(fs_info, ins.objectid);
9068 		if (IS_ERR(trans)) {
9069 			ret = PTR_ERR(trans);
9070 			btrfs_free_reserved_extent(fs_info, ins.objectid,
9071 						   ins.offset, false);
9072 			break;
9073 		}
9074 
9075 		em = btrfs_alloc_extent_map();
9076 		if (!em) {
9077 			btrfs_drop_extent_map_range(BTRFS_I(inode), cur_offset,
9078 					    cur_offset + ins.offset - 1, false);
9079 			btrfs_set_inode_full_sync(BTRFS_I(inode));
9080 			goto next;
9081 		}
9082 
9083 		em->start = cur_offset;
9084 		em->len = ins.offset;
9085 		em->disk_bytenr = ins.objectid;
9086 		em->offset = 0;
9087 		em->disk_num_bytes = ins.offset;
9088 		em->ram_bytes = ins.offset;
9089 		em->flags |= EXTENT_FLAG_PREALLOC;
9090 		em->generation = trans->transid;
9091 
9092 		ret = btrfs_replace_extent_map_range(BTRFS_I(inode), em, true);
9093 		btrfs_free_extent_map(em);
9094 next:
9095 		num_bytes -= ins.offset;
9096 		cur_offset += ins.offset;
9097 		*alloc_hint = ins.objectid + ins.offset;
9098 
9099 		inode_inc_iversion(inode);
9100 		inode_set_ctime_current(inode);
9101 		BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
9102 		if (!(mode & FALLOC_FL_KEEP_SIZE) &&
9103 		    (actual_len > inode->i_size) &&
9104 		    (cur_offset > inode->i_size)) {
9105 			u64 range_start;
9106 			u64 range_end;
9107 
9108 			if (cur_offset > actual_len)
9109 				i_size = actual_len;
9110 			else
9111 				i_size = cur_offset;
9112 
9113 			/*
9114 			 * Make sure the file_extent_tree covers the entire
9115 			 * range [old_i_size, new_i_size) before we update
9116 			 * disk_i_size. Without this, a previous KEEP_SIZE
9117 			 * prealloc that extended past i_size (and was lost
9118 			 * across umount/mount because file_extent_tree is
9119 			 * only populated up to round_up(i_size) on inode
9120 			 * load) can leave a gap inside this range. That gap
9121 			 * would cause btrfs_inode_safe_disk_i_size_write()
9122 			 * (via find_contiguous_extent_bit() starting at 0)
9123 			 * to truncate disk_i_size to the start of the gap,
9124 			 * making the persisted size smaller than i_size.
9125 			 */
9126 			range_start = round_down(inode->i_size, fs_info->sectorsize);
9127 			range_end = round_up(i_size, fs_info->sectorsize);
9128 			ret = btrfs_inode_set_file_extent_range(BTRFS_I(inode),
9129 					range_start, range_end - range_start);
9130 			if (ret) {
9131 				btrfs_abort_transaction(trans, ret);
9132 				if (own_trans)
9133 					btrfs_end_transaction(trans);
9134 				break;
9135 			}
9136 
9137 			i_size_write(inode, i_size);
9138 			btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
9139 		}
9140 
9141 		ret = btrfs_update_inode(trans, BTRFS_I(inode));
9142 
9143 		if (unlikely(ret)) {
9144 			btrfs_abort_transaction(trans, ret);
9145 			if (own_trans)
9146 				btrfs_end_transaction(trans);
9147 			break;
9148 		}
9149 
9150 		if (own_trans) {
9151 			btrfs_end_transaction(trans);
9152 			trans = NULL;
9153 		}
9154 	}
9155 	if (clear_offset < end)
9156 		btrfs_free_reserved_data_space(BTRFS_I(inode), NULL, clear_offset,
9157 			end - clear_offset + 1);
9158 	return ret;
9159 }
9160 
9161 int btrfs_prealloc_file_range(struct inode *inode, int mode,
9162 			      u64 start, u64 num_bytes, u64 min_size,
9163 			      loff_t actual_len, u64 *alloc_hint)
9164 {
9165 	return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9166 					   min_size, actual_len, alloc_hint,
9167 					   NULL);
9168 }
9169 
9170 int btrfs_prealloc_file_range_trans(struct inode *inode,
9171 				    struct btrfs_trans_handle *trans, int mode,
9172 				    u64 start, u64 num_bytes, u64 min_size,
9173 				    loff_t actual_len, u64 *alloc_hint)
9174 {
9175 	return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9176 					   min_size, actual_len, alloc_hint, trans);
9177 }
9178 
9179 /*
9180  * NOTE: in case you are adding MAY_EXEC check for directories:
9181  * we are marking them with IOP_FASTPERM_MAY_EXEC, allowing path lookup to
9182  * elide calls here.
9183  */
9184 static int btrfs_permission(struct mnt_idmap *idmap,
9185 			    struct inode *inode, int mask)
9186 {
9187 	struct btrfs_root *root = BTRFS_I(inode)->root;
9188 	umode_t mode = inode->i_mode;
9189 
9190 	if (mask & MAY_WRITE &&
9191 	    (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
9192 		if (btrfs_root_readonly(root))
9193 			return -EROFS;
9194 		if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
9195 			return -EACCES;
9196 	}
9197 	return generic_permission(idmap, inode, mask);
9198 }
9199 
9200 static int btrfs_tmpfile(struct mnt_idmap *idmap, struct inode *dir,
9201 			 struct file *file, umode_t mode)
9202 {
9203 	struct btrfs_fs_info *fs_info = inode_to_fs_info(dir);
9204 	struct btrfs_trans_handle *trans;
9205 	struct btrfs_root *root = BTRFS_I(dir)->root;
9206 	struct inode *inode;
9207 	struct btrfs_new_inode_args new_inode_args = {
9208 		.dir = dir,
9209 		.dentry = file->f_path.dentry,
9210 		.orphan = true,
9211 	};
9212 	unsigned int trans_num_items;
9213 	int ret;
9214 
9215 	inode = new_inode(dir->i_sb);
9216 	if (!inode)
9217 		return -ENOMEM;
9218 	inode_init_owner(idmap, inode, dir, mode);
9219 	inode->i_fop = &btrfs_file_operations;
9220 	inode->i_op = &btrfs_file_inode_operations;
9221 	inode->i_mapping->a_ops = &btrfs_aops;
9222 
9223 	new_inode_args.inode = inode;
9224 	ret = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
9225 	if (ret)
9226 		goto out_inode;
9227 
9228 	trans = btrfs_start_transaction(root, trans_num_items);
9229 	if (IS_ERR(trans)) {
9230 		ret = PTR_ERR(trans);
9231 		goto out_new_inode_args;
9232 	}
9233 
9234 	ret = btrfs_create_new_inode(trans, &new_inode_args);
9235 
9236 	/*
9237 	 * We set number of links to 0 in btrfs_create_new_inode(), and here we
9238 	 * set it to 1 because d_tmpfile() will issue a warning if the count is
9239 	 * 0, through:
9240 	 *
9241 	 *    d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
9242 	 */
9243 	set_nlink(inode, 1);
9244 
9245 	if (!ret) {
9246 		d_tmpfile(file, inode);
9247 		unlock_new_inode(inode);
9248 		mark_inode_dirty(inode);
9249 	}
9250 
9251 	btrfs_end_transaction(trans);
9252 	btrfs_btree_balance_dirty(fs_info);
9253 out_new_inode_args:
9254 	btrfs_new_inode_args_destroy(&new_inode_args);
9255 out_inode:
9256 	if (ret)
9257 		iput(inode);
9258 	return finish_open_simple(file, ret);
9259 }
9260 
9261 int btrfs_encoded_io_compression_from_extent(struct btrfs_fs_info *fs_info,
9262 					     int compress_type)
9263 {
9264 	switch (compress_type) {
9265 	case BTRFS_COMPRESS_NONE:
9266 		return BTRFS_ENCODED_IO_COMPRESSION_NONE;
9267 	case BTRFS_COMPRESS_ZLIB:
9268 		return BTRFS_ENCODED_IO_COMPRESSION_ZLIB;
9269 	case BTRFS_COMPRESS_LZO:
9270 		/*
9271 		 * The LZO format depends on the sector size. 64K is the maximum
9272 		 * sector size that we support.
9273 		 */
9274 		if (fs_info->sectorsize < SZ_4K || fs_info->sectorsize > SZ_64K)
9275 			return -EINVAL;
9276 		return BTRFS_ENCODED_IO_COMPRESSION_LZO_4K +
9277 		       (fs_info->sectorsize_bits - 12);
9278 	case BTRFS_COMPRESS_ZSTD:
9279 		return BTRFS_ENCODED_IO_COMPRESSION_ZSTD;
9280 	default:
9281 		return -EUCLEAN;
9282 	}
9283 }
9284 
9285 static ssize_t btrfs_encoded_read_inline(
9286 				struct kiocb *iocb,
9287 				struct iov_iter *iter, u64 start,
9288 				u64 lockend,
9289 				struct extent_state **cached_state,
9290 				u64 extent_start, size_t count,
9291 				struct btrfs_ioctl_encoded_io_args *encoded,
9292 				bool *unlocked)
9293 {
9294 	struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
9295 	struct btrfs_root *root = inode->root;
9296 	struct btrfs_fs_info *fs_info = root->fs_info;
9297 	struct extent_io_tree *io_tree = &inode->io_tree;
9298 	BTRFS_PATH_AUTO_FREE(path);
9299 	struct extent_buffer *leaf;
9300 	struct btrfs_file_extent_item *item;
9301 	u64 ram_bytes;
9302 	unsigned long ptr;
9303 	void *tmp;
9304 	ssize_t ret;
9305 	const bool nowait = (iocb->ki_flags & IOCB_NOWAIT);
9306 
9307 	path = btrfs_alloc_path();
9308 	if (!path)
9309 		return -ENOMEM;
9310 
9311 	path->nowait = nowait;
9312 
9313 	ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
9314 				       extent_start, 0);
9315 	if (ret) {
9316 		if (unlikely(ret > 0)) {
9317 			/* The extent item disappeared? */
9318 			return -EIO;
9319 		}
9320 		return ret;
9321 	}
9322 	leaf = path->nodes[0];
9323 	item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
9324 
9325 	ram_bytes = btrfs_file_extent_ram_bytes(leaf, item);
9326 	ptr = btrfs_file_extent_inline_start(item);
9327 
9328 	encoded->len = min_t(u64, extent_start + ram_bytes,
9329 			     inode->vfs_inode.i_size) - iocb->ki_pos;
9330 	ret = btrfs_encoded_io_compression_from_extent(fs_info,
9331 				 btrfs_file_extent_compression(leaf, item));
9332 	if (ret < 0)
9333 		return ret;
9334 	encoded->compression = ret;
9335 	if (encoded->compression) {
9336 		size_t inline_size;
9337 
9338 		inline_size = btrfs_file_extent_inline_item_len(leaf,
9339 								path->slots[0]);
9340 		if (inline_size > count)
9341 			return -ENOBUFS;
9342 
9343 		count = inline_size;
9344 		encoded->unencoded_len = ram_bytes;
9345 		encoded->unencoded_offset = iocb->ki_pos - extent_start;
9346 	} else {
9347 		count = min_t(u64, count, encoded->len);
9348 		encoded->len = count;
9349 		encoded->unencoded_len = count;
9350 		ptr += iocb->ki_pos - extent_start;
9351 	}
9352 
9353 	tmp = kmalloc(count, GFP_NOFS);
9354 	if (!tmp)
9355 		return -ENOMEM;
9356 
9357 	read_extent_buffer(leaf, tmp, ptr, count);
9358 	btrfs_release_path(path);
9359 	btrfs_unlock_extent(io_tree, start, lockend, cached_state);
9360 	btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
9361 	*unlocked = true;
9362 
9363 	ret = copy_to_iter(tmp, count, iter);
9364 	if (ret != count)
9365 		ret = -EFAULT;
9366 	kfree(tmp);
9367 
9368 	return ret;
9369 }
9370 
9371 struct btrfs_encoded_read_private {
9372 	struct completion *sync_reads;
9373 	void *uring_ctx;
9374 	refcount_t pending_refs;
9375 	blk_status_t status;
9376 };
9377 
9378 static void btrfs_encoded_read_endio(struct btrfs_bio *bbio)
9379 {
9380 	struct btrfs_encoded_read_private *priv = bbio->private;
9381 
9382 	if (bbio->bio.bi_status) {
9383 		/*
9384 		 * The memory barrier implied by the refcount_dec_and_test() here
9385 		 * pairs with the memory barrier implied by the refcount_dec_and_test()
9386 		 * in btrfs_encoded_read_regular_fill_pages() to ensure that
9387 		 * this write is observed before the load of status in
9388 		 * btrfs_encoded_read_regular_fill_pages().
9389 		 */
9390 		WRITE_ONCE(priv->status, bbio->bio.bi_status);
9391 	}
9392 	if (refcount_dec_and_test(&priv->pending_refs)) {
9393 		int err = blk_status_to_errno(READ_ONCE(priv->status));
9394 
9395 		if (priv->uring_ctx) {
9396 			btrfs_uring_read_extent_endio(priv->uring_ctx, err);
9397 			kfree(priv);
9398 		} else {
9399 			complete(priv->sync_reads);
9400 		}
9401 	}
9402 	bio_put(&bbio->bio);
9403 }
9404 
9405 int btrfs_encoded_read_regular_fill_pages(struct btrfs_inode *inode,
9406 					  u64 disk_bytenr, u64 disk_io_size,
9407 					  struct page **pages, void *uring_ctx)
9408 {
9409 	struct btrfs_encoded_read_private *priv, sync_priv;
9410 	struct completion sync_reads;
9411 	unsigned long i = 0;
9412 	struct btrfs_bio *bbio;
9413 	int ret;
9414 
9415 	/*
9416 	 * Fast path for synchronous reads which completes in this call, io_uring
9417 	 * needs longer time span.
9418 	 */
9419 	if (uring_ctx) {
9420 		priv = kmalloc_obj(struct btrfs_encoded_read_private, GFP_NOFS);
9421 		if (!priv)
9422 			return -ENOMEM;
9423 	} else {
9424 		priv = &sync_priv;
9425 		init_completion(&sync_reads);
9426 		priv->sync_reads = &sync_reads;
9427 	}
9428 
9429 	refcount_set(&priv->pending_refs, 1);
9430 	priv->status = 0;
9431 	priv->uring_ctx = uring_ctx;
9432 
9433 	bbio = btrfs_bio_alloc(BIO_MAX_VECS, REQ_OP_READ, inode, 0,
9434 			       btrfs_encoded_read_endio, priv);
9435 	bbio->bio.bi_iter.bi_sector = disk_bytenr >> SECTOR_SHIFT;
9436 
9437 	do {
9438 		size_t bytes = min_t(u64, disk_io_size, PAGE_SIZE);
9439 
9440 		if (bio_add_page(&bbio->bio, pages[i], bytes, 0) < bytes) {
9441 			refcount_inc(&priv->pending_refs);
9442 			btrfs_submit_bbio(bbio, 0);
9443 
9444 			bbio = btrfs_bio_alloc(BIO_MAX_VECS, REQ_OP_READ, inode, 0,
9445 					       btrfs_encoded_read_endio, priv);
9446 			bbio->bio.bi_iter.bi_sector = disk_bytenr >> SECTOR_SHIFT;
9447 			continue;
9448 		}
9449 
9450 		i++;
9451 		disk_bytenr += bytes;
9452 		disk_io_size -= bytes;
9453 	} while (disk_io_size);
9454 
9455 	refcount_inc(&priv->pending_refs);
9456 	btrfs_submit_bbio(bbio, 0);
9457 
9458 	if (uring_ctx) {
9459 		if (refcount_dec_and_test(&priv->pending_refs)) {
9460 			ret = blk_status_to_errno(READ_ONCE(priv->status));
9461 			btrfs_uring_read_extent_endio(uring_ctx, ret);
9462 			kfree(priv);
9463 			return ret;
9464 		}
9465 
9466 		return -EIOCBQUEUED;
9467 	} else {
9468 		if (!refcount_dec_and_test(&priv->pending_refs))
9469 			wait_for_completion_io(&sync_reads);
9470 		/* See btrfs_encoded_read_endio() for ordering. */
9471 		return blk_status_to_errno(READ_ONCE(priv->status));
9472 	}
9473 }
9474 
9475 ssize_t btrfs_encoded_read_regular(struct kiocb *iocb, struct iov_iter *iter,
9476 				   u64 start, u64 lockend,
9477 				   struct extent_state **cached_state,
9478 				   u64 disk_bytenr, u64 disk_io_size,
9479 				   size_t count, bool compressed, bool *unlocked)
9480 {
9481 	struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
9482 	struct extent_io_tree *io_tree = &inode->io_tree;
9483 	struct page **pages;
9484 	unsigned long nr_pages, i;
9485 	u64 cur;
9486 	size_t page_offset;
9487 	ssize_t ret;
9488 
9489 	nr_pages = DIV_ROUND_UP(disk_io_size, PAGE_SIZE);
9490 	pages = kzalloc_objs(struct page *, nr_pages, GFP_NOFS);
9491 	if (!pages)
9492 		return -ENOMEM;
9493 	ret = btrfs_alloc_page_array(nr_pages, pages, GFP_NOFS);
9494 	if (ret) {
9495 		ret = -ENOMEM;
9496 		goto out;
9497 		}
9498 
9499 	ret = btrfs_encoded_read_regular_fill_pages(inode, disk_bytenr,
9500 						    disk_io_size, pages, NULL);
9501 	if (ret)
9502 		goto out;
9503 
9504 	btrfs_unlock_extent(io_tree, start, lockend, cached_state);
9505 	btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
9506 	*unlocked = true;
9507 
9508 	if (compressed) {
9509 		i = 0;
9510 		page_offset = 0;
9511 	} else {
9512 		i = (iocb->ki_pos - start) >> PAGE_SHIFT;
9513 		page_offset = (iocb->ki_pos - start) & (PAGE_SIZE - 1);
9514 	}
9515 	cur = 0;
9516 	while (cur < count) {
9517 		size_t bytes = min_t(size_t, count - cur,
9518 				     PAGE_SIZE - page_offset);
9519 
9520 		if (copy_page_to_iter(pages[i], page_offset, bytes,
9521 				      iter) != bytes) {
9522 			ret = -EFAULT;
9523 			goto out;
9524 		}
9525 		i++;
9526 		cur += bytes;
9527 		page_offset = 0;
9528 	}
9529 	ret = count;
9530 out:
9531 	for (i = 0; i < nr_pages; i++) {
9532 		if (pages[i])
9533 			__free_page(pages[i]);
9534 	}
9535 	kfree(pages);
9536 	return ret;
9537 }
9538 
9539 ssize_t btrfs_encoded_read(struct kiocb *iocb, struct iov_iter *iter,
9540 			   struct btrfs_ioctl_encoded_io_args *encoded,
9541 			   struct extent_state **cached_state,
9542 			   u64 *disk_bytenr, u64 *disk_io_size)
9543 {
9544 	struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
9545 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
9546 	struct extent_io_tree *io_tree = &inode->io_tree;
9547 	ssize_t ret;
9548 	size_t count = iov_iter_count(iter);
9549 	u64 start, lockend;
9550 	struct extent_map *em;
9551 	const bool nowait = (iocb->ki_flags & IOCB_NOWAIT);
9552 	bool unlocked = false;
9553 
9554 	file_accessed(iocb->ki_filp);
9555 
9556 	ret = btrfs_inode_lock(inode,
9557 			       BTRFS_ILOCK_SHARED | (nowait ? BTRFS_ILOCK_TRY : 0));
9558 	if (ret)
9559 		return ret;
9560 
9561 	if (iocb->ki_pos >= inode->vfs_inode.i_size) {
9562 		btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
9563 		return 0;
9564 	}
9565 	start = ALIGN_DOWN(iocb->ki_pos, fs_info->sectorsize);
9566 	/*
9567 	 * We don't know how long the extent containing iocb->ki_pos is, but if
9568 	 * it's compressed we know that it won't be longer than this.
9569 	 */
9570 	lockend = start + BTRFS_MAX_UNCOMPRESSED - 1;
9571 
9572 	if (nowait) {
9573 		struct btrfs_ordered_extent *ordered;
9574 
9575 		if (filemap_range_needs_writeback(inode->vfs_inode.i_mapping,
9576 						  start, lockend)) {
9577 			ret = -EAGAIN;
9578 			goto out_unlock_inode;
9579 		}
9580 
9581 		if (!btrfs_try_lock_extent(io_tree, start, lockend, cached_state)) {
9582 			ret = -EAGAIN;
9583 			goto out_unlock_inode;
9584 		}
9585 
9586 		ordered = btrfs_lookup_ordered_range(inode, start,
9587 						     lockend - start + 1);
9588 		if (ordered) {
9589 			btrfs_put_ordered_extent(ordered);
9590 			btrfs_unlock_extent(io_tree, start, lockend, cached_state);
9591 			ret = -EAGAIN;
9592 			goto out_unlock_inode;
9593 		}
9594 	} else {
9595 		for (;;) {
9596 			struct btrfs_ordered_extent *ordered;
9597 
9598 			ret = btrfs_wait_ordered_range(inode, start,
9599 						       lockend - start + 1);
9600 			if (ret)
9601 				goto out_unlock_inode;
9602 
9603 			btrfs_lock_extent(io_tree, start, lockend, cached_state);
9604 			ordered = btrfs_lookup_ordered_range(inode, start,
9605 							     lockend - start + 1);
9606 			if (!ordered)
9607 				break;
9608 			btrfs_put_ordered_extent(ordered);
9609 			btrfs_unlock_extent(io_tree, start, lockend, cached_state);
9610 			cond_resched();
9611 		}
9612 	}
9613 
9614 	em = btrfs_get_extent(inode, NULL, start, lockend - start + 1);
9615 	if (IS_ERR(em)) {
9616 		ret = PTR_ERR(em);
9617 		goto out_unlock_extent;
9618 	}
9619 
9620 	if (em->disk_bytenr == EXTENT_MAP_INLINE) {
9621 		u64 extent_start = em->start;
9622 
9623 		/*
9624 		 * For inline extents we get everything we need out of the
9625 		 * extent item.
9626 		 */
9627 		btrfs_free_extent_map(em);
9628 		em = NULL;
9629 		ret = btrfs_encoded_read_inline(iocb, iter, start, lockend,
9630 						cached_state, extent_start,
9631 						count, encoded, &unlocked);
9632 		goto out_unlock_extent;
9633 	}
9634 
9635 	/*
9636 	 * We only want to return up to EOF even if the extent extends beyond
9637 	 * that.
9638 	 */
9639 	encoded->len = min_t(u64, btrfs_extent_map_end(em),
9640 			     inode->vfs_inode.i_size) - iocb->ki_pos;
9641 	if (em->disk_bytenr == EXTENT_MAP_HOLE ||
9642 	    (em->flags & EXTENT_FLAG_PREALLOC)) {
9643 		*disk_bytenr = EXTENT_MAP_HOLE;
9644 		count = min_t(u64, count, encoded->len);
9645 		encoded->len = count;
9646 		encoded->unencoded_len = count;
9647 	} else if (btrfs_extent_map_is_compressed(em)) {
9648 		*disk_bytenr = em->disk_bytenr;
9649 		/*
9650 		 * Bail if the buffer isn't large enough to return the whole
9651 		 * compressed extent.
9652 		 */
9653 		if (em->disk_num_bytes > count) {
9654 			ret = -ENOBUFS;
9655 			goto out_em;
9656 		}
9657 		*disk_io_size = em->disk_num_bytes;
9658 		count = em->disk_num_bytes;
9659 		encoded->unencoded_len = em->ram_bytes;
9660 		encoded->unencoded_offset = iocb->ki_pos - (em->start - em->offset);
9661 		ret = btrfs_encoded_io_compression_from_extent(fs_info,
9662 					       btrfs_extent_map_compression(em));
9663 		if (ret < 0)
9664 			goto out_em;
9665 		encoded->compression = ret;
9666 	} else {
9667 		*disk_bytenr = btrfs_extent_map_block_start(em) + (start - em->start);
9668 		if (encoded->len > count)
9669 			encoded->len = count;
9670 		/*
9671 		 * Don't read beyond what we locked. This also limits the page
9672 		 * allocations that we'll do.
9673 		 */
9674 		*disk_io_size = min(lockend + 1, iocb->ki_pos + encoded->len) - start;
9675 		count = start + *disk_io_size - iocb->ki_pos;
9676 		encoded->len = count;
9677 		encoded->unencoded_len = count;
9678 		*disk_io_size = ALIGN(*disk_io_size, fs_info->sectorsize);
9679 	}
9680 	btrfs_free_extent_map(em);
9681 	em = NULL;
9682 
9683 	if (*disk_bytenr == EXTENT_MAP_HOLE) {
9684 		btrfs_unlock_extent(io_tree, start, lockend, cached_state);
9685 		btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
9686 		unlocked = true;
9687 		ret = iov_iter_zero(count, iter);
9688 		if (ret != count)
9689 			ret = -EFAULT;
9690 	} else {
9691 		ret = -EIOCBQUEUED;
9692 		goto out_unlock_extent;
9693 	}
9694 
9695 out_em:
9696 	btrfs_free_extent_map(em);
9697 out_unlock_extent:
9698 	/* Leave inode and extent locked if we need to do a read. */
9699 	if (!unlocked && ret != -EIOCBQUEUED)
9700 		btrfs_unlock_extent(io_tree, start, lockend, cached_state);
9701 out_unlock_inode:
9702 	if (!unlocked && ret != -EIOCBQUEUED)
9703 		btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
9704 	return ret;
9705 }
9706 
9707 ssize_t btrfs_do_encoded_write(struct kiocb *iocb, struct iov_iter *from,
9708 			       const struct btrfs_ioctl_encoded_io_args *encoded)
9709 {
9710 	struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
9711 	struct btrfs_root *root = inode->root;
9712 	struct btrfs_fs_info *fs_info = root->fs_info;
9713 	struct extent_io_tree *io_tree = &inode->io_tree;
9714 	struct extent_changeset *data_reserved = NULL;
9715 	struct extent_state *cached_state = NULL;
9716 	struct btrfs_ordered_extent *ordered;
9717 	struct btrfs_file_extent file_extent;
9718 	struct compressed_bio *cb = NULL;
9719 	int compression;
9720 	size_t orig_count;
9721 	const u32 min_folio_size = btrfs_min_folio_size(fs_info);
9722 	const u32 blocksize = fs_info->sectorsize;
9723 	u64 start, end;
9724 	u64 num_bytes, ram_bytes, disk_num_bytes;
9725 	struct btrfs_key ins;
9726 	bool extent_reserved = false;
9727 	struct extent_map *em;
9728 	ssize_t ret;
9729 
9730 	switch (encoded->compression) {
9731 	case BTRFS_ENCODED_IO_COMPRESSION_ZLIB:
9732 		compression = BTRFS_COMPRESS_ZLIB;
9733 		break;
9734 	case BTRFS_ENCODED_IO_COMPRESSION_ZSTD:
9735 		compression = BTRFS_COMPRESS_ZSTD;
9736 		break;
9737 	case BTRFS_ENCODED_IO_COMPRESSION_LZO_4K:
9738 	case BTRFS_ENCODED_IO_COMPRESSION_LZO_8K:
9739 	case BTRFS_ENCODED_IO_COMPRESSION_LZO_16K:
9740 	case BTRFS_ENCODED_IO_COMPRESSION_LZO_32K:
9741 	case BTRFS_ENCODED_IO_COMPRESSION_LZO_64K:
9742 		/* The sector size must match for LZO. */
9743 		if (encoded->compression -
9744 		    BTRFS_ENCODED_IO_COMPRESSION_LZO_4K + 12 !=
9745 		    fs_info->sectorsize_bits)
9746 			return -EINVAL;
9747 		compression = BTRFS_COMPRESS_LZO;
9748 		break;
9749 	default:
9750 		return -EINVAL;
9751 	}
9752 	if (encoded->encryption != BTRFS_ENCODED_IO_ENCRYPTION_NONE)
9753 		return -EINVAL;
9754 
9755 	/*
9756 	 * Compressed extents should always have checksums, so error out if we
9757 	 * have a NOCOW file or inode was created while mounted with NODATASUM.
9758 	 */
9759 	if (inode->flags & BTRFS_INODE_NODATASUM)
9760 		return -EINVAL;
9761 
9762 	orig_count = iov_iter_count(from);
9763 
9764 	/* The extent size must be sane. */
9765 	if (encoded->unencoded_len > BTRFS_MAX_UNCOMPRESSED ||
9766 	    orig_count > BTRFS_MAX_COMPRESSED || orig_count == 0)
9767 		return -EINVAL;
9768 
9769 	/*
9770 	 * The compressed data must be smaller than the decompressed data.
9771 	 *
9772 	 * It's of course possible for data to compress to larger or the same
9773 	 * size, but the buffered I/O path falls back to no compression for such
9774 	 * data, and we don't want to break any assumptions by creating these
9775 	 * extents.
9776 	 *
9777 	 * Note that this is less strict than the current check we have that the
9778 	 * compressed data must be at least one sector smaller than the
9779 	 * decompressed data. We only want to enforce the weaker requirement
9780 	 * from old kernels that it is at least one byte smaller.
9781 	 */
9782 	if (orig_count >= encoded->unencoded_len)
9783 		return -EINVAL;
9784 
9785 	/* The extent must start on a sector boundary. */
9786 	start = iocb->ki_pos;
9787 	if (!IS_ALIGNED(start, fs_info->sectorsize))
9788 		return -EINVAL;
9789 
9790 	/*
9791 	 * The extent must end on a sector boundary. However, we allow a write
9792 	 * which ends at or extends i_size to have an unaligned length; we round
9793 	 * up the extent size and set i_size to the unaligned end.
9794 	 */
9795 	if (start + encoded->len < inode->vfs_inode.i_size &&
9796 	    !IS_ALIGNED(start + encoded->len, fs_info->sectorsize))
9797 		return -EINVAL;
9798 
9799 	/* Finally, the offset in the unencoded data must be sector-aligned. */
9800 	if (!IS_ALIGNED(encoded->unencoded_offset, fs_info->sectorsize))
9801 		return -EINVAL;
9802 
9803 	num_bytes = ALIGN(encoded->len, fs_info->sectorsize);
9804 	ram_bytes = ALIGN(encoded->unencoded_len, fs_info->sectorsize);
9805 	end = start + num_bytes - 1;
9806 
9807 	/*
9808 	 * If the extent cannot be inline, the compressed data on disk must be
9809 	 * sector-aligned. For convenience, we extend it with zeroes if it
9810 	 * isn't.
9811 	 */
9812 	disk_num_bytes = ALIGN(orig_count, fs_info->sectorsize);
9813 
9814 	cb = btrfs_alloc_compressed_write(inode, start, num_bytes);
9815 	for (int i = 0; i * min_folio_size < disk_num_bytes; i++) {
9816 		struct folio *folio;
9817 		size_t bytes = min(min_folio_size, iov_iter_count(from));
9818 		char *kaddr;
9819 
9820 		folio = btrfs_alloc_compr_folio(fs_info, GFP_NOFS);
9821 		if (!folio) {
9822 			ret = -ENOMEM;
9823 			goto out_cb;
9824 		}
9825 		kaddr = kmap_local_folio(folio, 0);
9826 		ret = copy_from_iter(kaddr, bytes, from);
9827 		kunmap_local(kaddr);
9828 		if (ret != bytes) {
9829 			folio_put(folio);
9830 			ret = -EFAULT;
9831 			goto out_cb;
9832 		}
9833 		if (!IS_ALIGNED(bytes, blocksize))
9834 			folio_zero_range(folio, bytes, round_up(bytes, blocksize) - bytes);
9835 		ret = bio_add_folio(&cb->bbio.bio, folio, round_up(bytes, blocksize), 0);
9836 		if (unlikely(!ret)) {
9837 			folio_put(folio);
9838 			ret = -EINVAL;
9839 			goto out_cb;
9840 		}
9841 	}
9842 	ASSERT(cb->bbio.bio.bi_iter.bi_size == disk_num_bytes);
9843 
9844 	for (;;) {
9845 		ret = btrfs_wait_ordered_range(inode, start, num_bytes);
9846 		if (ret)
9847 			goto out_cb;
9848 		ret = invalidate_inode_pages2_range(inode->vfs_inode.i_mapping,
9849 						    start >> PAGE_SHIFT,
9850 						    end >> PAGE_SHIFT);
9851 		if (ret)
9852 			goto out_cb;
9853 		btrfs_lock_extent(io_tree, start, end, &cached_state);
9854 		ordered = btrfs_lookup_ordered_range(inode, start, num_bytes);
9855 		if (!ordered &&
9856 		    !filemap_range_has_page(inode->vfs_inode.i_mapping, start, end))
9857 			break;
9858 		if (ordered)
9859 			btrfs_put_ordered_extent(ordered);
9860 		btrfs_unlock_extent(io_tree, start, end, &cached_state);
9861 		cond_resched();
9862 	}
9863 
9864 	/*
9865 	 * We don't use the higher-level delalloc space functions because our
9866 	 * num_bytes and disk_num_bytes are different.
9867 	 */
9868 	ret = btrfs_alloc_data_chunk_ondemand(inode, disk_num_bytes);
9869 	if (ret)
9870 		goto out_unlock;
9871 	ret = btrfs_qgroup_reserve_data(inode, &data_reserved, start, num_bytes);
9872 	if (ret)
9873 		goto out_free_data_space;
9874 	ret = btrfs_delalloc_reserve_metadata(inode, num_bytes, disk_num_bytes,
9875 					      false);
9876 	if (ret)
9877 		goto out_qgroup_free_data;
9878 
9879 	/* Try an inline extent first. */
9880 	if (encoded->unencoded_len == encoded->len &&
9881 	    encoded->unencoded_offset == 0 &&
9882 	    can_cow_file_range_inline(inode, start, encoded->len, orig_count)) {
9883 		ret = __cow_file_range_inline(inode, encoded->len,
9884 					      orig_count, compression,
9885 					      bio_first_folio_all(&cb->bbio.bio),
9886 					      true);
9887 		if (ret <= 0) {
9888 			if (ret == 0)
9889 				ret = orig_count;
9890 			goto out_delalloc_release;
9891 		}
9892 	}
9893 
9894 	ret = btrfs_reserve_extent(root, disk_num_bytes, disk_num_bytes,
9895 				   disk_num_bytes, 0, 0, &ins, true, true);
9896 	if (ret)
9897 		goto out_delalloc_release;
9898 	extent_reserved = true;
9899 
9900 	file_extent.disk_bytenr = ins.objectid;
9901 	file_extent.disk_num_bytes = ins.offset;
9902 	file_extent.num_bytes = num_bytes;
9903 	file_extent.ram_bytes = ram_bytes;
9904 	file_extent.offset = encoded->unencoded_offset;
9905 	file_extent.compression = compression;
9906 	em = btrfs_create_io_em(inode, start, &file_extent, BTRFS_ORDERED_COMPRESSED);
9907 	if (IS_ERR(em)) {
9908 		ret = PTR_ERR(em);
9909 		goto out_free_reserved;
9910 	}
9911 	btrfs_free_extent_map(em);
9912 
9913 	ordered = btrfs_alloc_ordered_extent(inode, start, &file_extent,
9914 				       (1U << BTRFS_ORDERED_ENCODED) |
9915 				       (1U << BTRFS_ORDERED_COMPRESSED));
9916 	if (IS_ERR(ordered)) {
9917 		btrfs_drop_extent_map_range(inode, start, end, false);
9918 		ret = PTR_ERR(ordered);
9919 		goto out_free_reserved;
9920 	}
9921 	btrfs_dec_block_group_reservations(fs_info, ins.objectid);
9922 
9923 	if (start + encoded->len > inode->vfs_inode.i_size)
9924 		i_size_write(&inode->vfs_inode, start + encoded->len);
9925 
9926 	btrfs_unlock_extent(io_tree, start, end, &cached_state);
9927 
9928 	btrfs_delalloc_release_extents(inode, num_bytes);
9929 
9930 	btrfs_submit_compressed_write(ordered, cb);
9931 	ret = orig_count;
9932 	goto out;
9933 
9934 out_free_reserved:
9935 	btrfs_dec_block_group_reservations(fs_info, ins.objectid);
9936 	btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, true);
9937 out_delalloc_release:
9938 	btrfs_delalloc_release_extents(inode, num_bytes);
9939 	btrfs_delalloc_release_metadata(inode, disk_num_bytes, ret < 0);
9940 out_qgroup_free_data:
9941 	if (ret < 0)
9942 		btrfs_qgroup_free_data(inode, data_reserved, start, num_bytes, NULL);
9943 out_free_data_space:
9944 	/*
9945 	 * If btrfs_reserve_extent() succeeded, then we already decremented
9946 	 * bytes_may_use.
9947 	 */
9948 	if (!extent_reserved)
9949 		btrfs_free_reserved_data_space_noquota(inode, disk_num_bytes);
9950 out_unlock:
9951 	btrfs_unlock_extent(io_tree, start, end, &cached_state);
9952 out_cb:
9953 	if (cb)
9954 		cleanup_compressed_bio(cb);
9955 out:
9956 	if (ret >= 0)
9957 		iocb->ki_pos += encoded->len;
9958 	return ret;
9959 }
9960 
9961 #ifdef CONFIG_SWAP
9962 /*
9963  * Add an entry indicating a block group or device which is pinned by a
9964  * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
9965  * negative errno on failure.
9966  */
9967 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
9968 				  bool is_block_group)
9969 {
9970 	struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
9971 	struct btrfs_swapfile_pin *sp, *entry;
9972 	struct rb_node **p;
9973 	struct rb_node *parent = NULL;
9974 
9975 	sp = kmalloc_obj(*sp, GFP_NOFS);
9976 	if (!sp)
9977 		return -ENOMEM;
9978 	sp->ptr = ptr;
9979 	sp->inode = inode;
9980 	sp->is_block_group = is_block_group;
9981 	sp->bg_extent_count = 1;
9982 
9983 	spin_lock(&fs_info->swapfile_pins_lock);
9984 	p = &fs_info->swapfile_pins.rb_node;
9985 	while (*p) {
9986 		parent = *p;
9987 		entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
9988 		if (sp->ptr < entry->ptr ||
9989 		    (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
9990 			p = &(*p)->rb_left;
9991 		} else if (sp->ptr > entry->ptr ||
9992 			   (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
9993 			p = &(*p)->rb_right;
9994 		} else {
9995 			if (is_block_group)
9996 				entry->bg_extent_count++;
9997 			spin_unlock(&fs_info->swapfile_pins_lock);
9998 			kfree(sp);
9999 			return 1;
10000 		}
10001 	}
10002 	rb_link_node(&sp->node, parent, p);
10003 	rb_insert_color(&sp->node, &fs_info->swapfile_pins);
10004 	spin_unlock(&fs_info->swapfile_pins_lock);
10005 	return 0;
10006 }
10007 
10008 /* Free all of the entries pinned by this swapfile. */
10009 static void btrfs_free_swapfile_pins(struct inode *inode)
10010 {
10011 	struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10012 	struct btrfs_swapfile_pin *sp;
10013 	struct rb_node *node, *next;
10014 
10015 	spin_lock(&fs_info->swapfile_pins_lock);
10016 	node = rb_first(&fs_info->swapfile_pins);
10017 	while (node) {
10018 		next = rb_next(node);
10019 		sp = rb_entry(node, struct btrfs_swapfile_pin, node);
10020 		if (sp->inode == inode) {
10021 			rb_erase(&sp->node, &fs_info->swapfile_pins);
10022 			if (sp->is_block_group) {
10023 				btrfs_dec_block_group_swap_extents(sp->ptr,
10024 							   sp->bg_extent_count);
10025 				btrfs_put_block_group(sp->ptr);
10026 			}
10027 			kfree(sp);
10028 		}
10029 		node = next;
10030 	}
10031 	spin_unlock(&fs_info->swapfile_pins_lock);
10032 }
10033 
10034 struct btrfs_swap_info {
10035 	u64 start;
10036 	u64 block_start;
10037 	u64 block_len;
10038 	u64 lowest_ppage;
10039 	u64 highest_ppage;
10040 	unsigned long nr_pages;
10041 	int nr_extents;
10042 };
10043 
10044 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
10045 				 struct btrfs_swap_info *bsi)
10046 {
10047 	unsigned long nr_pages;
10048 	unsigned long max_pages;
10049 	u64 first_ppage, first_ppage_reported, next_ppage;
10050 	int ret;
10051 
10052 	/*
10053 	 * Our swapfile may have had its size extended after the swap header was
10054 	 * written. In that case activating the swapfile should not go beyond
10055 	 * the max size set in the swap header.
10056 	 */
10057 	if (bsi->nr_pages >= sis->max)
10058 		return 0;
10059 
10060 	max_pages = sis->max - bsi->nr_pages;
10061 	first_ppage = PAGE_ALIGN(bsi->block_start) >> PAGE_SHIFT;
10062 	next_ppage = PAGE_ALIGN_DOWN(bsi->block_start + bsi->block_len) >> PAGE_SHIFT;
10063 
10064 	if (first_ppage >= next_ppage)
10065 		return 0;
10066 	nr_pages = next_ppage - first_ppage;
10067 	nr_pages = min(nr_pages, max_pages);
10068 
10069 	first_ppage_reported = first_ppage;
10070 	if (bsi->start == 0)
10071 		first_ppage_reported++;
10072 	if (bsi->lowest_ppage > first_ppage_reported)
10073 		bsi->lowest_ppage = first_ppage_reported;
10074 	if (bsi->highest_ppage < (next_ppage - 1))
10075 		bsi->highest_ppage = next_ppage - 1;
10076 
10077 	ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
10078 	if (ret < 0)
10079 		return ret;
10080 	bsi->nr_extents += ret;
10081 	bsi->nr_pages += nr_pages;
10082 	return 0;
10083 }
10084 
10085 static void btrfs_swap_deactivate(struct file *file)
10086 {
10087 	struct inode *inode = file_inode(file);
10088 
10089 	btrfs_free_swapfile_pins(inode);
10090 	atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
10091 }
10092 
10093 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10094 			       sector_t *span)
10095 {
10096 	struct inode *inode = file_inode(file);
10097 	struct btrfs_root *root = BTRFS_I(inode)->root;
10098 	struct btrfs_fs_info *fs_info = root->fs_info;
10099 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10100 	struct extent_state *cached_state = NULL;
10101 	struct btrfs_chunk_map *map = NULL;
10102 	struct btrfs_device *device = NULL;
10103 	struct btrfs_swap_info bsi = {
10104 		.lowest_ppage = (sector_t)-1ULL,
10105 	};
10106 	struct btrfs_backref_share_check_ctx *backref_ctx = NULL;
10107 	struct btrfs_path *path = NULL;
10108 	int ret = 0;
10109 	u64 isize;
10110 	u64 prev_extent_end = 0;
10111 
10112 	/*
10113 	 * Acquire the inode's mmap lock to prevent races with memory mapped
10114 	 * writes, as they could happen after we flush delalloc below and before
10115 	 * we lock the extent range further below. The inode was already locked
10116 	 * up in the call chain.
10117 	 */
10118 	btrfs_assert_inode_locked(BTRFS_I(inode));
10119 	down_write(&BTRFS_I(inode)->i_mmap_lock);
10120 
10121 	/*
10122 	 * If the swap file was just created, make sure delalloc is done. If the
10123 	 * file changes again after this, the user is doing something stupid and
10124 	 * we don't really care.
10125 	 */
10126 	ret = btrfs_wait_ordered_range(BTRFS_I(inode), 0, (u64)-1);
10127 	if (ret)
10128 		goto out_unlock_mmap;
10129 
10130 	/*
10131 	 * The inode is locked, so these flags won't change after we check them.
10132 	 */
10133 	if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
10134 		btrfs_warn(fs_info, "swapfile must not be compressed");
10135 		ret = -EINVAL;
10136 		goto out_unlock_mmap;
10137 	}
10138 	if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
10139 		btrfs_warn(fs_info, "swapfile must not be copy-on-write");
10140 		ret = -EINVAL;
10141 		goto out_unlock_mmap;
10142 	}
10143 	if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
10144 		btrfs_warn(fs_info, "swapfile must not be checksummed");
10145 		ret = -EINVAL;
10146 		goto out_unlock_mmap;
10147 	}
10148 
10149 	path = btrfs_alloc_path();
10150 	backref_ctx = btrfs_alloc_backref_share_check_ctx();
10151 	if (!path || !backref_ctx) {
10152 		ret = -ENOMEM;
10153 		goto out_unlock_mmap;
10154 	}
10155 
10156 	/*
10157 	 * Balance or device remove/replace/resize can move stuff around from
10158 	 * under us. The exclop protection makes sure they aren't running/won't
10159 	 * run concurrently while we are mapping the swap extents, and
10160 	 * fs_info->swapfile_pins prevents them from running while the swap
10161 	 * file is active and moving the extents. Note that this also prevents
10162 	 * a concurrent device add which isn't actually necessary, but it's not
10163 	 * really worth the trouble to allow it.
10164 	 */
10165 	if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_SWAP_ACTIVATE)) {
10166 		btrfs_warn(fs_info,
10167 	   "cannot activate swapfile while exclusive operation is running");
10168 		ret = -EBUSY;
10169 		goto out_unlock_mmap;
10170 	}
10171 
10172 	/*
10173 	 * Prevent snapshot creation while we are activating the swap file.
10174 	 * We do not want to race with snapshot creation. If snapshot creation
10175 	 * already started before we bumped nr_swapfiles from 0 to 1 and
10176 	 * completes before the first write into the swap file after it is
10177 	 * activated, than that write would fallback to COW.
10178 	 */
10179 	if (!btrfs_drew_try_write_lock(&root->snapshot_lock)) {
10180 		btrfs_exclop_finish(fs_info);
10181 		btrfs_warn(fs_info,
10182 	   "cannot activate swapfile because snapshot creation is in progress");
10183 		ret = -EINVAL;
10184 		goto out_unlock_mmap;
10185 	}
10186 	/*
10187 	 * Snapshots can create extents which require COW even if NODATACOW is
10188 	 * set. We use this counter to prevent snapshots. We must increment it
10189 	 * before walking the extents because we don't want a concurrent
10190 	 * snapshot to run after we've already checked the extents.
10191 	 *
10192 	 * It is possible that subvolume is marked for deletion but still not
10193 	 * removed yet. To prevent this race, we check the root status before
10194 	 * activating the swapfile.
10195 	 */
10196 	spin_lock(&root->root_item_lock);
10197 	if (btrfs_root_dead(root)) {
10198 		spin_unlock(&root->root_item_lock);
10199 
10200 		btrfs_drew_write_unlock(&root->snapshot_lock);
10201 		btrfs_exclop_finish(fs_info);
10202 		btrfs_warn(fs_info,
10203 		"cannot activate swapfile because subvolume %llu is being deleted",
10204 			btrfs_root_id(root));
10205 		ret = -EPERM;
10206 		goto out_unlock_mmap;
10207 	}
10208 	atomic_inc(&root->nr_swapfiles);
10209 	spin_unlock(&root->root_item_lock);
10210 
10211 	isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
10212 
10213 	btrfs_lock_extent(io_tree, 0, isize - 1, &cached_state);
10214 	while (prev_extent_end < isize) {
10215 		struct btrfs_key key;
10216 		struct extent_buffer *leaf;
10217 		struct btrfs_file_extent_item *ei;
10218 		struct btrfs_block_group *bg;
10219 		u64 logical_block_start;
10220 		u64 physical_block_start;
10221 		u64 extent_gen;
10222 		u64 disk_bytenr;
10223 		u64 len;
10224 
10225 		key.objectid = btrfs_ino(BTRFS_I(inode));
10226 		key.type = BTRFS_EXTENT_DATA_KEY;
10227 		key.offset = prev_extent_end;
10228 
10229 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
10230 		if (ret < 0)
10231 			goto out;
10232 
10233 		/*
10234 		 * If key not found it means we have an implicit hole (NO_HOLES
10235 		 * is enabled).
10236 		 */
10237 		if (ret > 0) {
10238 			btrfs_warn(fs_info, "swapfile must not have holes");
10239 			ret = -EINVAL;
10240 			goto out;
10241 		}
10242 
10243 		leaf = path->nodes[0];
10244 		ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
10245 
10246 		if (btrfs_file_extent_type(leaf, ei) == BTRFS_FILE_EXTENT_INLINE) {
10247 			/*
10248 			 * It's unlikely we'll ever actually find ourselves
10249 			 * here, as a file small enough to fit inline won't be
10250 			 * big enough to store more than the swap header, but in
10251 			 * case something changes in the future, let's catch it
10252 			 * here rather than later.
10253 			 */
10254 			btrfs_warn(fs_info, "swapfile must not be inline");
10255 			ret = -EINVAL;
10256 			goto out;
10257 		}
10258 
10259 		if (btrfs_file_extent_compression(leaf, ei) != BTRFS_COMPRESS_NONE) {
10260 			btrfs_warn(fs_info, "swapfile must not be compressed");
10261 			ret = -EINVAL;
10262 			goto out;
10263 		}
10264 
10265 		disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, ei);
10266 		if (disk_bytenr == 0) {
10267 			btrfs_warn(fs_info, "swapfile must not have holes");
10268 			ret = -EINVAL;
10269 			goto out;
10270 		}
10271 
10272 		logical_block_start = disk_bytenr + btrfs_file_extent_offset(leaf, ei);
10273 		extent_gen = btrfs_file_extent_generation(leaf, ei);
10274 		prev_extent_end = btrfs_file_extent_end(path);
10275 
10276 		if (prev_extent_end > isize)
10277 			len = isize - key.offset;
10278 		else
10279 			len = btrfs_file_extent_num_bytes(leaf, ei);
10280 
10281 		backref_ctx->curr_leaf_bytenr = leaf->start;
10282 
10283 		/*
10284 		 * Don't need the path anymore, release to avoid deadlocks when
10285 		 * calling btrfs_is_data_extent_shared() because when joining a
10286 		 * transaction it can block waiting for the current one's commit
10287 		 * which in turn may be trying to lock the same leaf to flush
10288 		 * delayed items for example.
10289 		 */
10290 		btrfs_release_path(path);
10291 
10292 		ret = btrfs_is_data_extent_shared(BTRFS_I(inode), disk_bytenr,
10293 						  extent_gen, backref_ctx);
10294 		if (ret < 0) {
10295 			goto out;
10296 		} else if (ret > 0) {
10297 			btrfs_warn(fs_info,
10298 				   "swapfile must not be copy-on-write");
10299 			ret = -EINVAL;
10300 			goto out;
10301 		}
10302 
10303 		map = btrfs_get_chunk_map(fs_info, logical_block_start, len);
10304 		if (IS_ERR(map)) {
10305 			ret = PTR_ERR(map);
10306 			goto out;
10307 		}
10308 
10309 		if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
10310 			btrfs_warn(fs_info,
10311 				   "swapfile must have single data profile");
10312 			ret = -EINVAL;
10313 			goto out;
10314 		}
10315 
10316 		if (device == NULL) {
10317 			device = map->stripes[0].dev;
10318 			ret = btrfs_add_swapfile_pin(inode, device, false);
10319 			if (ret == 1)
10320 				ret = 0;
10321 			else if (ret)
10322 				goto out;
10323 		} else if (device != map->stripes[0].dev) {
10324 			btrfs_warn(fs_info, "swapfile must be on one device");
10325 			ret = -EINVAL;
10326 			goto out;
10327 		}
10328 
10329 		physical_block_start = (map->stripes[0].physical +
10330 					(logical_block_start - map->start));
10331 		btrfs_free_chunk_map(map);
10332 		map = NULL;
10333 
10334 		bg = btrfs_lookup_block_group(fs_info, logical_block_start);
10335 		if (!bg) {
10336 			btrfs_warn(fs_info,
10337 			   "could not find block group containing swapfile");
10338 			ret = -EINVAL;
10339 			goto out;
10340 		}
10341 
10342 		if (!btrfs_inc_block_group_swap_extents(bg)) {
10343 			btrfs_warn(fs_info,
10344 			   "block group for swapfile at %llu is read-only%s",
10345 			   bg->start,
10346 			   atomic_read(&fs_info->scrubs_running) ?
10347 				       " (scrub running)" : "");
10348 			btrfs_put_block_group(bg);
10349 			ret = -EINVAL;
10350 			goto out;
10351 		}
10352 
10353 		ret = btrfs_add_swapfile_pin(inode, bg, true);
10354 		if (ret) {
10355 			btrfs_put_block_group(bg);
10356 			if (ret == 1)
10357 				ret = 0;
10358 			else
10359 				goto out;
10360 		}
10361 
10362 		if (bsi.block_len &&
10363 		    bsi.block_start + bsi.block_len == physical_block_start) {
10364 			bsi.block_len += len;
10365 		} else {
10366 			if (bsi.block_len) {
10367 				ret = btrfs_add_swap_extent(sis, &bsi);
10368 				if (ret)
10369 					goto out;
10370 			}
10371 			bsi.start = key.offset;
10372 			bsi.block_start = physical_block_start;
10373 			bsi.block_len = len;
10374 		}
10375 
10376 		if (fatal_signal_pending(current)) {
10377 			ret = -EINTR;
10378 			goto out;
10379 		}
10380 
10381 		cond_resched();
10382 	}
10383 
10384 	if (bsi.block_len)
10385 		ret = btrfs_add_swap_extent(sis, &bsi);
10386 
10387 out:
10388 	if (!IS_ERR_OR_NULL(map))
10389 		btrfs_free_chunk_map(map);
10390 
10391 	btrfs_unlock_extent(io_tree, 0, isize - 1, &cached_state);
10392 
10393 	if (ret)
10394 		btrfs_swap_deactivate(file);
10395 
10396 	btrfs_drew_write_unlock(&root->snapshot_lock);
10397 
10398 	btrfs_exclop_finish(fs_info);
10399 
10400 out_unlock_mmap:
10401 	up_write(&BTRFS_I(inode)->i_mmap_lock);
10402 	btrfs_free_backref_share_ctx(backref_ctx);
10403 	btrfs_free_path(path);
10404 	if (ret)
10405 		return ret;
10406 
10407 	if (device)
10408 		sis->bdev = device->bdev;
10409 	*span = bsi.highest_ppage - bsi.lowest_ppage + 1;
10410 	sis->max = bsi.nr_pages;
10411 	sis->pages = bsi.nr_pages - 1;
10412 	return bsi.nr_extents;
10413 }
10414 #else
10415 static void btrfs_swap_deactivate(struct file *file)
10416 {
10417 }
10418 
10419 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10420 			       sector_t *span)
10421 {
10422 	return -EOPNOTSUPP;
10423 }
10424 #endif
10425 
10426 /*
10427  * Update the number of bytes used in the VFS' inode. When we replace extents in
10428  * a range (clone, dedupe, fallocate's zero range), we must update the number of
10429  * bytes used by the inode in an atomic manner, so that concurrent stat(2) calls
10430  * always get a correct value.
10431  */
10432 void btrfs_update_inode_bytes(struct btrfs_inode *inode,
10433 			      const u64 add_bytes,
10434 			      const u64 del_bytes)
10435 {
10436 	if (add_bytes == del_bytes)
10437 		return;
10438 
10439 	spin_lock(&inode->lock);
10440 	if (del_bytes > 0)
10441 		inode_sub_bytes(&inode->vfs_inode, del_bytes);
10442 	if (add_bytes > 0)
10443 		inode_add_bytes(&inode->vfs_inode, add_bytes);
10444 	spin_unlock(&inode->lock);
10445 }
10446 
10447 /*
10448  * Verify that there are no ordered extents for a given file range.
10449  *
10450  * @inode:   The target inode.
10451  * @start:   Start offset of the file range, should be sector size aligned.
10452  * @end:     End offset (inclusive) of the file range, its value +1 should be
10453  *           sector size aligned.
10454  *
10455  * This should typically be used for cases where we locked an inode's VFS lock in
10456  * exclusive mode, we have also locked the inode's i_mmap_lock in exclusive mode,
10457  * we have flushed all delalloc in the range, we have waited for all ordered
10458  * extents in the range to complete and finally we have locked the file range in
10459  * the inode's io_tree.
10460  */
10461 void btrfs_assert_inode_range_clean(struct btrfs_inode *inode, u64 start, u64 end)
10462 {
10463 	struct btrfs_root *root = inode->root;
10464 	struct btrfs_ordered_extent *ordered;
10465 
10466 	if (!IS_ENABLED(CONFIG_BTRFS_ASSERT))
10467 		return;
10468 
10469 	ordered = btrfs_lookup_first_ordered_range(inode, start, end + 1 - start);
10470 	if (ordered) {
10471 		btrfs_err(root->fs_info,
10472 "found unexpected ordered extent in file range [%llu, %llu] for inode %llu root %llu (ordered range [%llu, %llu])",
10473 			  start, end, btrfs_ino(inode), btrfs_root_id(root),
10474 			  ordered->file_offset,
10475 			  ordered->file_offset + ordered->num_bytes - 1);
10476 		btrfs_put_ordered_extent(ordered);
10477 	}
10478 
10479 	ASSERT(ordered == NULL);
10480 }
10481 
10482 /*
10483  * Find the first inode with a minimum number.
10484  *
10485  * @root:	The root to search for.
10486  * @min_ino:	The minimum inode number.
10487  *
10488  * Find the first inode in the @root with a number >= @min_ino and return it.
10489  * Returns NULL if no such inode found.
10490  */
10491 struct btrfs_inode *btrfs_find_first_inode(struct btrfs_root *root, u64 min_ino)
10492 {
10493 	struct btrfs_inode *inode;
10494 	unsigned long from = min_ino;
10495 
10496 	xa_lock(&root->inodes);
10497 	while (true) {
10498 		inode = xa_find(&root->inodes, &from, ULONG_MAX, XA_PRESENT);
10499 		if (!inode)
10500 			break;
10501 		if (igrab(&inode->vfs_inode))
10502 			break;
10503 
10504 		from = btrfs_ino(inode) + 1;
10505 		xa_unlock(&root->inodes);
10506 		cond_resched();
10507 		xa_lock(&root->inodes);
10508 	}
10509 	xa_unlock(&root->inodes);
10510 
10511 	return inode;
10512 }
10513 
10514 static const struct inode_operations btrfs_dir_inode_operations = {
10515 	.getattr	= btrfs_getattr,
10516 	.lookup		= btrfs_lookup,
10517 	.create		= btrfs_create,
10518 	.unlink		= btrfs_unlink,
10519 	.link		= btrfs_link,
10520 	.mkdir		= btrfs_mkdir,
10521 	.rmdir		= btrfs_rmdir,
10522 	.rename		= btrfs_rename2,
10523 	.symlink	= btrfs_symlink,
10524 	.setattr	= btrfs_setattr,
10525 	.mknod		= btrfs_mknod,
10526 	.listxattr	= btrfs_listxattr,
10527 	.permission	= btrfs_permission,
10528 	.get_inode_acl	= btrfs_get_acl,
10529 	.set_acl	= btrfs_set_acl,
10530 	.update_time	= btrfs_update_time,
10531 	.tmpfile        = btrfs_tmpfile,
10532 	.fileattr_get	= btrfs_fileattr_get,
10533 	.fileattr_set	= btrfs_fileattr_set,
10534 };
10535 
10536 static const struct file_operations btrfs_dir_file_operations = {
10537 	.llseek		= btrfs_dir_llseek,
10538 	.read		= generic_read_dir,
10539 	.iterate_shared	= btrfs_real_readdir,
10540 	.open		= btrfs_opendir,
10541 	.unlocked_ioctl	= btrfs_ioctl,
10542 #ifdef CONFIG_COMPAT
10543 	.compat_ioctl	= btrfs_compat_ioctl,
10544 #endif
10545 	.release        = btrfs_release_file,
10546 	.fsync		= btrfs_sync_file,
10547 	.setlease	= generic_setlease,
10548 };
10549 
10550 /*
10551  * btrfs doesn't support the bmap operation because swapfiles
10552  * use bmap to make a mapping of extents in the file.  They assume
10553  * these extents won't change over the life of the file and they
10554  * use the bmap result to do IO directly to the drive.
10555  *
10556  * the btrfs bmap call would return logical addresses that aren't
10557  * suitable for IO and they also will change frequently as COW
10558  * operations happen.  So, swapfile + btrfs == corruption.
10559  *
10560  * For now we're avoiding this by dropping bmap.
10561  */
10562 static const struct address_space_operations btrfs_aops = {
10563 	.read_folio	= btrfs_read_folio,
10564 	.writepages	= btrfs_writepages,
10565 	.readahead	= btrfs_readahead,
10566 	.invalidate_folio = btrfs_invalidate_folio,
10567 	.launder_folio	= btrfs_launder_folio,
10568 	.release_folio	= btrfs_release_folio,
10569 	.migrate_folio	= btrfs_migrate_folio,
10570 	.dirty_folio	= filemap_dirty_folio,
10571 	.error_remove_folio = generic_error_remove_folio,
10572 	.swap_activate	= btrfs_swap_activate,
10573 	.swap_deactivate = btrfs_swap_deactivate,
10574 };
10575 
10576 static const struct inode_operations btrfs_file_inode_operations = {
10577 	.getattr	= btrfs_getattr,
10578 	.setattr	= btrfs_setattr,
10579 	.listxattr      = btrfs_listxattr,
10580 	.permission	= btrfs_permission,
10581 	.fiemap		= btrfs_fiemap,
10582 	.get_inode_acl	= btrfs_get_acl,
10583 	.set_acl	= btrfs_set_acl,
10584 	.update_time	= btrfs_update_time,
10585 	.fileattr_get	= btrfs_fileattr_get,
10586 	.fileattr_set	= btrfs_fileattr_set,
10587 };
10588 static const struct inode_operations btrfs_special_inode_operations = {
10589 	.getattr	= btrfs_getattr,
10590 	.setattr	= btrfs_setattr,
10591 	.permission	= btrfs_permission,
10592 	.listxattr	= btrfs_listxattr,
10593 	.get_inode_acl	= btrfs_get_acl,
10594 	.set_acl	= btrfs_set_acl,
10595 	.update_time	= btrfs_update_time,
10596 };
10597 static const struct inode_operations btrfs_symlink_inode_operations = {
10598 	.get_link	= page_get_link,
10599 	.getattr	= btrfs_getattr,
10600 	.setattr	= btrfs_setattr,
10601 	.permission	= btrfs_permission,
10602 	.listxattr	= btrfs_listxattr,
10603 	.update_time	= btrfs_update_time,
10604 };
10605 
10606 const struct dentry_operations btrfs_dentry_operations = {
10607 	.d_delete	= btrfs_dentry_delete,
10608 };
10609