xref: /linux/fs/btrfs/inode.c (revision f4cdf7ca9a1fdcca413157df19753f388a5a224e)
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 struct btrfs_writepage_fixup {
2816 	struct folio *folio;
2817 	struct btrfs_inode *inode;
2818 	struct work_struct work;
2819 };
2820 
2821 /*
2822  * Do the real fixup work of reserving space for the blocks a folio's fixup
2823  * state records. Queued by writepage_fixup() when writeback found the bits set.
2824  *
2825  * Since the fixup can be cancelled by a task dirtying with a reservation, we must
2826  * re-check the state of fixup under the folio lock.
2827  */
2828 static void btrfs_writepage_fixup_worker(struct work_struct *work)
2829 {
2830 	struct btrfs_writepage_fixup *fixup =
2831 		container_of(work, struct btrfs_writepage_fixup, work);
2832 	struct extent_state *cached_state = NULL;
2833 	struct extent_changeset *data_reserved = NULL;
2834 	unsigned long delalloc_bitmap[BITS_TO_LONGS(BTRFS_MAX_BLOCKS_PER_FOLIO)] = { 0 };
2835 	struct folio *folio = fixup->folio;
2836 	struct btrfs_inode *inode = fixup->inode;
2837 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
2838 	const unsigned int blocks_per_folio = btrfs_blocks_per_folio(fs_info, folio);
2839 	const u32 sectorsize = fs_info->sectorsize;
2840 	const u64 page_start = folio_pos(folio);
2841 	const u64 page_end = folio_next_pos(folio) - 1;
2842 	unsigned int start_bit;
2843 	unsigned int end_bit;
2844 	unsigned int bit;
2845 	bool reserved;
2846 	int ret;
2847 
2848 	/*
2849 	 * We would prefer to reserve under the folio lock when we know exactly
2850 	 * which blocks need a reservation. Unfortunately, since the reservation
2851 	 * can go into flushers which can go into writeback, which takes folio
2852 	 * locks, that is not possible. Therefore, we have to reserve for the
2853 	 * whole folio here, then release what we didn't end up needing once we
2854 	 * figure it out.
2855 	 *
2856 	 * Also note the slightly strange error checking. If fixup is actually
2857 	 * not set, we don't need to mark an error on the mapping. So hang on to
2858 	 * ret until after we lock and find out if we actually care.
2859 	 */
2860 	ret = btrfs_delalloc_reserve_space(inode, &data_reserved, page_start,
2861 					   folio_size(folio));
2862 	reserved = (ret == 0);
2863 again:
2864 	folio_lock(folio);
2865 
2866 	if (!folio->mapping || !folio_test_fixup_pending(folio)) {
2867 		ret = 0;
2868 		goto out;
2869 	}
2870 	if (ret)
2871 		goto out;
2872 
2873 	btrfs_lock_extent(&inode->io_tree, page_start, page_end, &cached_state);
2874 
2875 	for (bit = 0; bit < blocks_per_folio; bit++) {
2876 		struct btrfs_ordered_extent *ordered;
2877 		const u64 start = page_start + (bit << fs_info->sectorsize_bits);
2878 
2879 		if (test_bit(bit, delalloc_bitmap))
2880 			continue;
2881 		if (!btrfs_folio_test_fixup(fs_info, folio, start, sectorsize))
2882 			continue;
2883 		/*
2884 		 * Any task that sets EXTENT_DELALLOC clears the fixup bits
2885 		 * under the folio lock, so it should be impossible to observe
2886 		 * both under the lock. Setting delalloc twice would wrongly
2887 		 * double account the space.
2888 		 */
2889 		if (IS_ENABLED(CONFIG_BTRFS_DEBUG) &&
2890 		    unlikely(btrfs_test_range_bit_exists(&inode->io_tree, start,
2891 							 start + sectorsize - 1,
2892 							 EXTENT_DELALLOC))) {
2893 			DEBUG_WARN("fixup worker: delalloc and fixup conflict. ino %llu start %llu",
2894 				   btrfs_ino(inode), start);
2895 			btrfs_folio_clear_fixup(fs_info, folio, start, sectorsize);
2896 			continue;
2897 		}
2898 		ordered = btrfs_lookup_ordered_range(inode, start, sectorsize);
2899 		if (ordered) {
2900 			trace_btrfs_writepage_fixup_defer(inode, ordered);
2901 			btrfs_unlock_extent(&inode->io_tree, page_start,
2902 					    page_end, &cached_state);
2903 			folio_unlock(folio);
2904 			btrfs_start_ordered_extent(ordered);
2905 			btrfs_put_ordered_extent(ordered);
2906 			goto again;
2907 		}
2908 		ret = btrfs_set_extent_delalloc(inode, start,
2909 						start + sectorsize - 1, 0,
2910 						&cached_state);
2911 		if (ret)
2912 			break;
2913 		trace_btrfs_writepage_fixup_reserve(inode, start, sectorsize);
2914 		btrfs_folio_clear_fixup(fs_info, folio, start, sectorsize);
2915 		set_bit(bit, delalloc_bitmap);
2916 	}
2917 
2918 	btrfs_unlock_extent(&inode->io_tree, page_start, page_end, &cached_state);
2919 out:
2920 	if (ret < 0) {
2921 		/* Failure here is analogous to failure in writeback. */
2922 		mapping_set_error(folio->mapping, ret);
2923 		btrfs_folio_clear_fixup_dirty(fs_info, folio, page_start,
2924 					      folio_size(folio));
2925 	}
2926 	if (reserved) {
2927 		btrfs_delalloc_release_extents(inode, folio_size(folio));
2928 		for_each_clear_bitrange(start_bit, end_bit, delalloc_bitmap,
2929 					blocks_per_folio)
2930 			btrfs_delalloc_release_space(inode, data_reserved,
2931 				page_start + (start_bit << fs_info->sectorsize_bits),
2932 				(end_bit - start_bit) << fs_info->sectorsize_bits,
2933 				true);
2934 	}
2935 	folio_unlock(folio);
2936 	folio_put(folio);
2937 	kfree(fixup);
2938 	extent_changeset_free(data_reserved);
2939 	btrfs_add_delayed_iput(inode);
2940 }
2941 
2942 /*
2943  * Queue space reservation fixup work for blocks dirtied without a space reservation.
2944  *
2945  * Should be used by writeback while holding the folio locked.
2946  *
2947  * If we fail to queue fixup, then the folio state is unchanged and a future
2948  * writeback pass will still see it.
2949  */
2950 void btrfs_queue_writepage_fixup(struct btrfs_inode *inode, struct folio *folio)
2951 {
2952 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
2953 	struct btrfs_writepage_fixup *fixup;
2954 
2955 	/*
2956 	 * Disallow queueing more fixup during unmount to break the cycle
2957 	 * of writeback queuing fixup queuing writeback etc.
2958 	 *
2959 	 * If it actually hit, then something which was fixup wasn't written
2960 	 * which we should warn about.
2961 	 */
2962 	if (btrfs_fs_closing(fs_info)) {
2963 		btrfs_warn_rl(fs_info,
2964 	"dropping unqueued fixup blocks at unmount. root %lld ino %llu folio %llu",
2965 			      btrfs_root_id(inode->root), btrfs_ino(inode),
2966 			      folio_pos(folio));
2967 		btrfs_folio_clear_fixup_dirty(fs_info, folio,
2968 					      folio_pos(folio), folio_size(folio));
2969 		return;
2970 	}
2971 
2972 	fixup = kzalloc_obj(*fixup, GFP_NOFS);
2973 	if (!fixup)
2974 		return;
2975 
2976 	/*
2977 	 * This is called from within extent_write_cache_pages() which
2978 	 * has successfully done an igrab(). But that will be released at the
2979 	 * end of the writeback pass. We need to extend it for the worker as well.
2980 	 */
2981 	ihold(&inode->vfs_inode);
2982 	folio_get(folio);
2983 	INIT_WORK(&fixup->work, btrfs_writepage_fixup_worker);
2984 	fixup->folio = folio;
2985 	fixup->inode = inode;
2986 	queue_work(fs_info->fixup_workers, &fixup->work);
2987 }
2988 
2989 /*
2990  * Clear the old accounting flags and set EXTENT_DELALLOC for the range.
2991  *
2992  * Return <0 for error, in that case no range has EXTENT_DELALLOC bit cleared or set.
2993  */
2994 int btrfs_reset_extent_delalloc(struct btrfs_inode *inode, u64 start, u64 end,
2995 				unsigned int extra_bits, struct extent_state **cached_state)
2996 {
2997 	const u32 blocksize = inode->root->fs_info->sectorsize;
2998 
2999 	/* The @extra_bits can only be EXTENT_NORESERVE for now. */
3000 	ASSERT(!(extra_bits & ~EXTENT_NORESERVE), "extra_bits=0x%x", extra_bits);
3001 
3002 	/* Basic alignment check. */
3003 	ASSERT(IS_ALIGNED(start, blocksize), "start=%llu blocksize=%u",
3004 	       start, blocksize);
3005 	ASSERT(IS_ALIGNED(end + 1, blocksize), "inclusive end=%llu blocksize=%u",
3006 	       end, blocksize);
3007 
3008 	/*
3009 	 * Check and set DELALLOC_NEW flag, this needs to search tree thus can
3010 	 * fail early.  Thus we want to do this before clearing EXTENT_DELALLOC.
3011 	 */
3012 	if (start >= i_size_read(&inode->vfs_inode) &&
3013 	    !(inode->flags & BTRFS_INODE_PREALLOC)) {
3014 		/*
3015 		 * There can't be any extents following EOF in this case so just
3016 		 * set the delalloc new bit for the range directly.
3017 		 */
3018 		extra_bits |= EXTENT_DELALLOC_NEW;
3019 	} else {
3020 		int ret;
3021 
3022 		ret = btrfs_find_new_delalloc_bytes(inode, start, end + 1 - start,
3023 						    NULL);
3024 		if (unlikely(ret))
3025 			return ret;
3026 	}
3027 	/* Clear the old accounting as the range may already be dirty. */
3028 	btrfs_clear_extent_bit(&inode->io_tree, start, end,
3029 			       EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
3030 			       EXTENT_DEFRAG, cached_state);
3031 	return btrfs_set_extent_bit(&inode->io_tree, start, end,
3032 				    EXTENT_DELALLOC | extra_bits, cached_state);
3033 }
3034 
3035 static int insert_reserved_file_extent(struct btrfs_trans_handle *trans,
3036 				       struct btrfs_inode *inode, u64 file_pos,
3037 				       struct btrfs_file_extent_item *stack_fi,
3038 				       const bool update_inode_bytes,
3039 				       u64 qgroup_reserved)
3040 {
3041 	struct btrfs_root *root = inode->root;
3042 	const u64 sectorsize = root->fs_info->sectorsize;
3043 	BTRFS_PATH_AUTO_FREE(path);
3044 	struct extent_buffer *leaf;
3045 	struct btrfs_key ins;
3046 	u64 disk_num_bytes = btrfs_stack_file_extent_disk_num_bytes(stack_fi);
3047 	u64 disk_bytenr = btrfs_stack_file_extent_disk_bytenr(stack_fi);
3048 	u64 offset = btrfs_stack_file_extent_offset(stack_fi);
3049 	u64 num_bytes = btrfs_stack_file_extent_num_bytes(stack_fi);
3050 	u64 ram_bytes = btrfs_stack_file_extent_ram_bytes(stack_fi);
3051 	struct btrfs_drop_extents_args drop_args = { 0 };
3052 	int ret;
3053 
3054 	path = btrfs_alloc_path();
3055 	if (!path)
3056 		return -ENOMEM;
3057 
3058 	/*
3059 	 * we may be replacing one extent in the tree with another.
3060 	 * The new extent is pinned in the extent map, and we don't want
3061 	 * to drop it from the cache until it is completely in the btree.
3062 	 *
3063 	 * So, tell btrfs_drop_extents to leave this extent in the cache.
3064 	 * the caller is expected to unpin it and allow it to be merged
3065 	 * with the others.
3066 	 */
3067 	drop_args.path = path;
3068 	drop_args.start = file_pos;
3069 	drop_args.end = file_pos + num_bytes;
3070 	drop_args.replace_extent = true;
3071 	drop_args.extent_item_size = sizeof(*stack_fi);
3072 	ret = btrfs_drop_extents(trans, root, inode, &drop_args);
3073 	if (ret)
3074 		return ret;
3075 
3076 	if (!drop_args.extent_inserted) {
3077 		ins.objectid = btrfs_ino(inode);
3078 		ins.type = BTRFS_EXTENT_DATA_KEY;
3079 		ins.offset = file_pos;
3080 
3081 		ret = btrfs_insert_empty_item(trans, root, path, &ins,
3082 					      sizeof(*stack_fi));
3083 		if (ret)
3084 			return ret;
3085 	}
3086 	leaf = path->nodes[0];
3087 	btrfs_set_stack_file_extent_generation(stack_fi, trans->transid);
3088 	write_extent_buffer(leaf, stack_fi,
3089 			btrfs_item_ptr_offset(leaf, path->slots[0]),
3090 			sizeof(struct btrfs_file_extent_item));
3091 
3092 	btrfs_release_path(path);
3093 
3094 	/*
3095 	 * If we dropped an inline extent here, we know the range where it is
3096 	 * was not marked with the EXTENT_DELALLOC_NEW bit, so we update the
3097 	 * number of bytes only for that range containing the inline extent.
3098 	 * The remaining of the range will be processed when clearing the
3099 	 * EXTENT_DELALLOC_BIT bit through the ordered extent completion.
3100 	 */
3101 	if (file_pos == 0 && !IS_ALIGNED(drop_args.bytes_found, sectorsize)) {
3102 		u64 inline_size = round_down(drop_args.bytes_found, sectorsize);
3103 
3104 		inline_size = drop_args.bytes_found - inline_size;
3105 		btrfs_update_inode_bytes(inode, sectorsize, inline_size);
3106 		drop_args.bytes_found -= inline_size;
3107 		num_bytes -= sectorsize;
3108 	}
3109 
3110 	if (update_inode_bytes)
3111 		btrfs_update_inode_bytes(inode, num_bytes, drop_args.bytes_found);
3112 
3113 	ins.objectid = disk_bytenr;
3114 	ins.type = BTRFS_EXTENT_ITEM_KEY;
3115 	ins.offset = disk_num_bytes;
3116 
3117 	ret = btrfs_inode_set_file_extent_range(inode, file_pos, ram_bytes);
3118 	if (ret)
3119 		return ret;
3120 
3121 	return btrfs_alloc_reserved_file_extent(trans, root, btrfs_ino(inode),
3122 						file_pos - offset,
3123 						qgroup_reserved, &ins);
3124 }
3125 
3126 static void btrfs_release_delalloc_bytes(struct btrfs_fs_info *fs_info,
3127 					 u64 start, u64 len)
3128 {
3129 	struct btrfs_block_group *cache;
3130 
3131 	cache = btrfs_lookup_block_group(fs_info, start);
3132 	ASSERT(cache);
3133 
3134 	spin_lock(&cache->lock);
3135 	cache->delalloc_bytes -= len;
3136 	spin_unlock(&cache->lock);
3137 
3138 	btrfs_put_block_group(cache);
3139 }
3140 
3141 static int insert_ordered_extent_file_extent(struct btrfs_trans_handle *trans,
3142 					     struct btrfs_ordered_extent *oe)
3143 {
3144 	struct btrfs_file_extent_item stack_fi;
3145 	bool update_inode_bytes;
3146 	u64 num_bytes = oe->num_bytes;
3147 	u64 ram_bytes = oe->ram_bytes;
3148 
3149 	memset(&stack_fi, 0, sizeof(stack_fi));
3150 	btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_REG);
3151 	btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, oe->disk_bytenr);
3152 	btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi,
3153 						   oe->disk_num_bytes);
3154 	btrfs_set_stack_file_extent_offset(&stack_fi, oe->offset);
3155 	if (test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags))
3156 		num_bytes = oe->truncated_len;
3157 	btrfs_set_stack_file_extent_num_bytes(&stack_fi, num_bytes);
3158 	btrfs_set_stack_file_extent_ram_bytes(&stack_fi, ram_bytes);
3159 	btrfs_set_stack_file_extent_compression(&stack_fi, oe->compress_type);
3160 	/* Encryption and other encoding is reserved and all 0 */
3161 
3162 	/*
3163 	 * For delalloc, when completing an ordered extent we update the inode's
3164 	 * bytes when clearing the range in the inode's io tree, so pass false
3165 	 * as the argument 'update_inode_bytes' to insert_reserved_file_extent(),
3166 	 * except if the ordered extent was truncated.
3167 	 */
3168 	update_inode_bytes = test_bit(BTRFS_ORDERED_DIRECT, &oe->flags) ||
3169 			     test_bit(BTRFS_ORDERED_ENCODED, &oe->flags) ||
3170 			     test_bit(BTRFS_ORDERED_TRUNCATED, &oe->flags);
3171 
3172 	return insert_reserved_file_extent(trans, oe->inode,
3173 					   oe->file_offset, &stack_fi,
3174 					   update_inode_bytes, oe->qgroup_rsv);
3175 }
3176 
3177 /*
3178  * As ordered data IO finishes, this gets called so we can finish
3179  * an ordered extent if the range of bytes in the file it covers are
3180  * fully written.
3181  */
3182 int btrfs_finish_one_ordered(struct btrfs_ordered_extent *ordered_extent)
3183 {
3184 	struct btrfs_inode *inode = ordered_extent->inode;
3185 	struct btrfs_root *root = inode->root;
3186 	struct btrfs_fs_info *fs_info = root->fs_info;
3187 	struct btrfs_trans_handle *trans = NULL;
3188 	struct extent_io_tree *io_tree = &inode->io_tree;
3189 	struct extent_state *cached_state = NULL;
3190 	u64 start, end;
3191 	int compress_type = 0;
3192 	int ret = 0;
3193 	u64 logical_len = ordered_extent->num_bytes;
3194 	bool freespace_inode;
3195 	bool truncated = false;
3196 	bool clear_reserved_extent = true;
3197 	unsigned int clear_bits = 0;
3198 
3199 	start = ordered_extent->file_offset;
3200 	end = start + ordered_extent->num_bytes - 1;
3201 
3202 	if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3203 	    !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags) &&
3204 	    !test_bit(BTRFS_ORDERED_DIRECT, &ordered_extent->flags) &&
3205 	    !test_bit(BTRFS_ORDERED_ENCODED, &ordered_extent->flags))
3206 		clear_bits |= EXTENT_DELALLOC_NEW;
3207 
3208 	if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags))
3209 		clear_bits |= EXTENT_DEFRAG;
3210 
3211 	freespace_inode = btrfs_is_free_space_inode(inode);
3212 	if (!freespace_inode)
3213 		btrfs_lockdep_acquire(fs_info, btrfs_ordered_extent);
3214 
3215 	if (unlikely(test_bit(BTRFS_ORDERED_IOERR, &ordered_extent->flags))) {
3216 		ret = -EIO;
3217 		goto out;
3218 	}
3219 
3220 	ret = btrfs_zone_finish_endio(fs_info, ordered_extent->disk_bytenr,
3221 				      ordered_extent->disk_num_bytes);
3222 	if (ret)
3223 		goto out;
3224 
3225 	if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags)) {
3226 		truncated = true;
3227 		logical_len = ordered_extent->truncated_len;
3228 		/* Truncated the entire extent, don't bother adding */
3229 		if (!logical_len)
3230 			goto out;
3231 	}
3232 
3233 	/*
3234 	 * If it's a COW write we need to lock the extent range as we will be
3235 	 * inserting/replacing file extent items and unpinning an extent map.
3236 	 * This must be taken before joining a transaction, as it's a higher
3237 	 * level lock (like the inode's VFS lock), otherwise we can run into an
3238 	 * ABBA deadlock with other tasks (transactions work like a lock,
3239 	 * depending on their current state).
3240 	 */
3241 	if (!test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
3242 		clear_bits |= EXTENT_LOCKED | EXTENT_FINISHING_ORDERED;
3243 		btrfs_lock_extent_bits(io_tree, start, end,
3244 				       EXTENT_LOCKED | EXTENT_FINISHING_ORDERED,
3245 				       &cached_state);
3246 	}
3247 
3248 	if (freespace_inode)
3249 		trans = btrfs_join_transaction_spacecache(root);
3250 	else
3251 		trans = btrfs_join_transaction(root);
3252 	if (IS_ERR(trans)) {
3253 		ret = PTR_ERR(trans);
3254 		trans = NULL;
3255 		goto out;
3256 	}
3257 
3258 	trans->block_rsv = &inode->block_rsv;
3259 
3260 	ret = btrfs_insert_raid_extent(trans, ordered_extent);
3261 	if (unlikely(ret)) {
3262 		btrfs_abort_transaction(trans, ret);
3263 		goto out;
3264 	}
3265 
3266 	if (test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags)) {
3267 		/* Logic error */
3268 		ASSERT(list_empty(&ordered_extent->csum_list));
3269 		if (unlikely(!list_empty(&ordered_extent->csum_list))) {
3270 			ret = -EINVAL;
3271 			btrfs_abort_transaction(trans, ret);
3272 			goto out;
3273 		}
3274 
3275 		btrfs_inode_safe_disk_i_size_write(inode, 0);
3276 		ret = btrfs_update_inode_fallback(trans, inode);
3277 		if (unlikely(ret)) {
3278 			/* -ENOMEM or corruption */
3279 			btrfs_abort_transaction(trans, ret);
3280 		}
3281 		goto out;
3282 	}
3283 
3284 	if (test_bit(BTRFS_ORDERED_COMPRESSED, &ordered_extent->flags))
3285 		compress_type = ordered_extent->compress_type;
3286 	if (test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3287 		BUG_ON(compress_type);
3288 		ret = btrfs_mark_extent_written(trans, inode,
3289 						ordered_extent->file_offset,
3290 						ordered_extent->file_offset +
3291 						logical_len);
3292 		btrfs_zoned_release_data_reloc_bg(fs_info, ordered_extent->disk_bytenr,
3293 						  ordered_extent->disk_num_bytes);
3294 		if (unlikely(ret < 0)) {
3295 			btrfs_abort_transaction(trans, ret);
3296 			goto out;
3297 		}
3298 	} else {
3299 		BUG_ON(root == fs_info->tree_root);
3300 		ret = insert_ordered_extent_file_extent(trans, ordered_extent);
3301 		if (unlikely(ret < 0)) {
3302 			btrfs_abort_transaction(trans, ret);
3303 			goto out;
3304 		}
3305 		clear_reserved_extent = false;
3306 		btrfs_release_delalloc_bytes(fs_info,
3307 					     ordered_extent->disk_bytenr,
3308 					     ordered_extent->disk_num_bytes);
3309 	}
3310 
3311 	ret = btrfs_unpin_extent_cache(inode, ordered_extent->file_offset,
3312 				       ordered_extent->num_bytes, trans->transid);
3313 	if (unlikely(ret < 0)) {
3314 		btrfs_abort_transaction(trans, ret);
3315 		goto out;
3316 	}
3317 
3318 	ret = add_pending_csums(trans, ordered_extent);
3319 	if (unlikely(ret)) {
3320 		btrfs_abort_transaction(trans, ret);
3321 		goto out;
3322 	}
3323 
3324 	/*
3325 	 * If this is a new delalloc range, clear its new delalloc flag to
3326 	 * update the inode's number of bytes. This needs to be done first
3327 	 * before updating the inode item.
3328 	 */
3329 	if ((clear_bits & EXTENT_DELALLOC_NEW) &&
3330 	    !test_bit(BTRFS_ORDERED_TRUNCATED, &ordered_extent->flags))
3331 		btrfs_clear_extent_bit(&inode->io_tree, start, end,
3332 				       EXTENT_DELALLOC_NEW | EXTENT_ADD_INODE_BYTES,
3333 				       &cached_state);
3334 
3335 	btrfs_inode_safe_disk_i_size_write(inode, 0);
3336 	ret = btrfs_update_inode_fallback(trans, inode);
3337 	if (unlikely(ret)) { /* -ENOMEM or corruption */
3338 		btrfs_abort_transaction(trans, ret);
3339 		goto out;
3340 	}
3341 out:
3342 	if (clear_bits)
3343 		btrfs_clear_extent_bit(&inode->io_tree, start, end, clear_bits,
3344 				       &cached_state);
3345 
3346 	if (trans)
3347 		btrfs_end_transaction(trans);
3348 
3349 	if (ret || truncated) {
3350 		/*
3351 		 * If we failed to finish this ordered extent for any reason we
3352 		 * need to make sure BTRFS_ORDERED_IOERR is set on the ordered
3353 		 * extent, and mark the inode with the error if it wasn't
3354 		 * already set.  Any error during writeback would have already
3355 		 * set the mapping error, so we need to set it if we're the ones
3356 		 * marking this ordered extent as failed.
3357 		 */
3358 		if (ret)
3359 			btrfs_mark_ordered_extent_error(ordered_extent);
3360 
3361 		/*
3362 		 * Drop extent maps for the part of the extent we didn't write.
3363 		 *
3364 		 * We have an exception here for the free_space_inode, this is
3365 		 * because when we do btrfs_get_extent() on the free space inode
3366 		 * we will search the commit root.  If this is a new block group
3367 		 * we won't find anything, and we will trip over the assert in
3368 		 * writepage where we do ASSERT(em->block_start !=
3369 		 * EXTENT_MAP_HOLE).
3370 		 *
3371 		 * Theoretically we could also skip this for any NOCOW extent as
3372 		 * we don't mess with the extent map tree in the NOCOW case, but
3373 		 * for now simply skip this if we are the free space inode.
3374 		 */
3375 		if (!btrfs_is_free_space_inode(inode)) {
3376 			u64 unwritten_start = start;
3377 
3378 			if (truncated)
3379 				unwritten_start += logical_len;
3380 
3381 			btrfs_drop_extent_map_range(inode, unwritten_start,
3382 						    end, false);
3383 		}
3384 
3385 		/*
3386 		 * If the ordered extent had an IOERR or something else went
3387 		 * wrong we need to return the space for this ordered extent
3388 		 * back to the allocator.  We only free the extent in the
3389 		 * truncated case if we didn't write out the extent at all.
3390 		 *
3391 		 * If we made it past insert_reserved_file_extent before we
3392 		 * errored out then we don't need to do this as the accounting
3393 		 * has already been done.
3394 		 */
3395 		if ((ret || !logical_len) &&
3396 		    clear_reserved_extent &&
3397 		    !test_bit(BTRFS_ORDERED_NOCOW, &ordered_extent->flags) &&
3398 		    !test_bit(BTRFS_ORDERED_PREALLOC, &ordered_extent->flags)) {
3399 			/*
3400 			 * Discard the range before returning it back to the
3401 			 * free space pool
3402 			 */
3403 			if (ret && btrfs_test_opt(fs_info, DISCARD_SYNC))
3404 				btrfs_discard_extent(fs_info,
3405 						ordered_extent->disk_bytenr,
3406 						ordered_extent->disk_num_bytes,
3407 						NULL, true);
3408 			btrfs_free_reserved_extent(fs_info,
3409 					ordered_extent->disk_bytenr,
3410 					ordered_extent->disk_num_bytes, true);
3411 			/*
3412 			 * Actually free the qgroup rsv which was released when
3413 			 * the ordered extent was created.
3414 			 */
3415 			btrfs_qgroup_free_refroot(fs_info, btrfs_root_id(inode->root),
3416 						  ordered_extent->qgroup_rsv,
3417 						  BTRFS_QGROUP_RSV_DATA);
3418 		}
3419 	}
3420 
3421 	/*
3422 	 * This needs to be done to make sure anybody waiting knows we are done
3423 	 * updating everything for this ordered extent.
3424 	 */
3425 	btrfs_remove_ordered_extent(ordered_extent);
3426 
3427 	/* once for us */
3428 	btrfs_put_ordered_extent(ordered_extent);
3429 	/* once for the tree */
3430 	btrfs_put_ordered_extent(ordered_extent);
3431 
3432 	return ret;
3433 }
3434 
3435 int btrfs_finish_ordered_io(struct btrfs_ordered_extent *ordered)
3436 {
3437 	if (btrfs_is_zoned(ordered->inode->root->fs_info) &&
3438 	    !test_bit(BTRFS_ORDERED_IOERR, &ordered->flags) &&
3439 	    list_empty(&ordered->bioc_list))
3440 		btrfs_finish_ordered_zoned(ordered);
3441 	return btrfs_finish_one_ordered(ordered);
3442 }
3443 
3444 /*
3445  * Calculate the checksum of an fs block at physical memory address @paddr,
3446  * and save the result to @dest.
3447  *
3448  * The folio containing @paddr must be large enough to contain a full fs block.
3449  */
3450 void btrfs_calculate_block_csum_folio(struct btrfs_fs_info *fs_info,
3451 				      const phys_addr_t paddr, u8 *dest)
3452 {
3453 	struct folio *folio = page_folio(phys_to_page(paddr));
3454 	const u32 blocksize = fs_info->sectorsize;
3455 	const u32 step = min(blocksize, PAGE_SIZE);
3456 	const u32 nr_steps = blocksize / step;
3457 	phys_addr_t paddrs[BTRFS_MAX_BLOCKSIZE / PAGE_SIZE];
3458 
3459 	/* The full block must be inside the folio. */
3460 	ASSERT(offset_in_folio(folio, paddr) + blocksize <= folio_size(folio));
3461 
3462 	for (int i = 0; i < nr_steps; i++) {
3463 		u32 pindex = offset_in_folio(folio, paddr + i * step) >> PAGE_SHIFT;
3464 
3465 		/*
3466 		 * For bs <= ps cases, we will only run the loop once, so the offset
3467 		 * inside the page will only added to paddrs[0].
3468 		 *
3469 		 * For bs > ps cases, the block must be page aligned, thus offset
3470 		 * inside the page will always be 0.
3471 		 */
3472 		paddrs[i] = page_to_phys(folio_page(folio, pindex)) + offset_in_page(paddr);
3473 	}
3474 	return btrfs_calculate_block_csum_pages(fs_info, paddrs, dest);
3475 }
3476 
3477 /*
3478  * Calculate the checksum of a fs block backed by multiple noncontiguous pages
3479  * at @paddrs[] and save the result to @dest.
3480  *
3481  * The folio containing @paddr must be large enough to contain a full fs block.
3482  */
3483 void btrfs_calculate_block_csum_pages(struct btrfs_fs_info *fs_info,
3484 				      const phys_addr_t paddrs[], u8 *dest)
3485 {
3486 	const u32 blocksize = fs_info->sectorsize;
3487 	const u32 step = min(blocksize, PAGE_SIZE);
3488 	const u32 nr_steps = blocksize / step;
3489 	struct btrfs_csum_ctx csum;
3490 
3491 	btrfs_csum_init(&csum, fs_info->csum_type);
3492 	for (int i = 0; i < nr_steps; i++) {
3493 		const phys_addr_t paddr = paddrs[i];
3494 		void *kaddr;
3495 
3496 		ASSERT(offset_in_page(paddr) + step <= PAGE_SIZE);
3497 		kaddr = kmap_local_page(phys_to_page(paddr)) + offset_in_page(paddr);
3498 		btrfs_csum_update(&csum, kaddr, step);
3499 		kunmap_local(kaddr);
3500 	}
3501 	btrfs_csum_final(&csum, dest);
3502 }
3503 
3504 /*
3505  * Verify the checksum for a single sector without any extra action that depend
3506  * on the type of I/O.
3507  *
3508  * @kaddr must be a properly kmapped address.
3509  */
3510 int btrfs_check_block_csum(struct btrfs_fs_info *fs_info, phys_addr_t paddr, u8 *csum,
3511 			   const u8 * const csum_expected)
3512 {
3513 	btrfs_calculate_block_csum_folio(fs_info, paddr, csum);
3514 	if (unlikely(memcmp(csum, csum_expected, fs_info->csum_size) != 0))
3515 		return -EIO;
3516 	return 0;
3517 }
3518 
3519 /*
3520  * Verify the checksum of a single data sector, which can be scattered at
3521  * different noncontiguous pages.
3522  *
3523  * @bbio:	btrfs_io_bio which contains the csum
3524  * @dev:	device the sector is on
3525  * @bio_offset:	offset to the beginning of the bio (in bytes)
3526  * @paddrs:	physical addresses which back the fs block
3527  *
3528  * Check if the checksum on a data block is valid.  When a checksum mismatch is
3529  * detected, report the error and fill the corrupted range with zero.
3530  *
3531  * Return %true if the sector is ok or had no checksum to start with, else %false.
3532  */
3533 bool btrfs_data_csum_ok(struct btrfs_bio *bbio, struct btrfs_device *dev,
3534 			u32 bio_offset, const phys_addr_t paddrs[])
3535 {
3536 	struct btrfs_inode *inode = bbio->inode;
3537 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
3538 	const u32 blocksize = fs_info->sectorsize;
3539 	const u32 step = min(blocksize, PAGE_SIZE);
3540 	const u32 nr_steps = blocksize / step;
3541 	u64 file_offset = bbio->file_offset + bio_offset;
3542 	u64 end = file_offset + blocksize - 1;
3543 	u8 *csum_expected;
3544 	u8 csum[BTRFS_CSUM_SIZE];
3545 
3546 	if (!bbio->csum)
3547 		return true;
3548 
3549 	if (btrfs_is_data_reloc_root(inode->root) &&
3550 	    btrfs_test_range_bit(&inode->io_tree, file_offset, end, EXTENT_NODATASUM,
3551 				 NULL)) {
3552 		/* Skip the range without csum for data reloc inode */
3553 		btrfs_clear_extent_bit(&inode->io_tree, file_offset, end,
3554 				       EXTENT_NODATASUM, NULL);
3555 		return true;
3556 	}
3557 
3558 	csum_expected = bbio->csum + (bio_offset >> fs_info->sectorsize_bits) *
3559 				fs_info->csum_size;
3560 	btrfs_calculate_block_csum_pages(fs_info, paddrs, csum);
3561 	if (unlikely(memcmp(csum, csum_expected, fs_info->csum_size) != 0))
3562 		goto zeroit;
3563 	return true;
3564 
3565 zeroit:
3566 	btrfs_print_data_csum_error(inode, file_offset, csum, csum_expected,
3567 				    bbio->mirror_num);
3568 	if (dev)
3569 		btrfs_dev_stat_inc_and_print(dev, BTRFS_DEV_STAT_CORRUPTION_ERRS);
3570 	for (int i = 0; i < nr_steps; i++)
3571 		memzero_page(phys_to_page(paddrs[i]), offset_in_page(paddrs[i]), step);
3572 	return false;
3573 }
3574 
3575 /*
3576  * Perform a delayed iput on @inode.
3577  *
3578  * @inode: The inode we want to perform iput on
3579  *
3580  * This function uses the generic vfs_inode::i_count to track whether we should
3581  * just decrement it (in case it's > 1) or if this is the last iput then link
3582  * the inode to the delayed iput machinery. Delayed iputs are processed at
3583  * transaction commit time/superblock commit/cleaner kthread.
3584  */
3585 void btrfs_add_delayed_iput(struct btrfs_inode *inode)
3586 {
3587 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
3588 	unsigned long flags;
3589 
3590 	if (atomic_add_unless(&inode->vfs_inode.i_count, -1, 1))
3591 		return;
3592 
3593 	WARN_ON_ONCE(test_bit(BTRFS_FS_STATE_NO_DELAYED_IPUT, &fs_info->fs_state));
3594 	atomic_inc(&fs_info->nr_delayed_iputs);
3595 	/*
3596 	 * Need to be irq safe here because we can be called from either an irq
3597 	 * context (see bio.c and btrfs_put_ordered_extent()) or a non-irq
3598 	 * context.
3599 	 */
3600 	spin_lock_irqsave(&fs_info->delayed_iput_lock, flags);
3601 	ASSERT(list_empty(&inode->delayed_iput));
3602 	list_add_tail(&inode->delayed_iput, &fs_info->delayed_iputs);
3603 	spin_unlock_irqrestore(&fs_info->delayed_iput_lock, flags);
3604 	if (!test_bit(BTRFS_FS_CLEANER_RUNNING, &fs_info->flags))
3605 		wake_up_process(fs_info->cleaner_kthread);
3606 }
3607 
3608 static void run_delayed_iput_locked(struct btrfs_fs_info *fs_info,
3609 				    struct btrfs_inode *inode)
3610 {
3611 	list_del_init(&inode->delayed_iput);
3612 	spin_unlock_irq(&fs_info->delayed_iput_lock);
3613 	iput(&inode->vfs_inode);
3614 	if (atomic_dec_and_test(&fs_info->nr_delayed_iputs))
3615 		wake_up(&fs_info->delayed_iputs_wait);
3616 	spin_lock_irq(&fs_info->delayed_iput_lock);
3617 }
3618 
3619 static void btrfs_run_delayed_iput(struct btrfs_fs_info *fs_info,
3620 				   struct btrfs_inode *inode)
3621 {
3622 	if (!list_empty(&inode->delayed_iput)) {
3623 		spin_lock_irq(&fs_info->delayed_iput_lock);
3624 		if (!list_empty(&inode->delayed_iput))
3625 			run_delayed_iput_locked(fs_info, inode);
3626 		spin_unlock_irq(&fs_info->delayed_iput_lock);
3627 	}
3628 }
3629 
3630 void btrfs_run_delayed_iputs(struct btrfs_fs_info *fs_info)
3631 {
3632 	/*
3633 	 * btrfs_put_ordered_extent() can run in irq context (see bio.c), which
3634 	 * calls btrfs_add_delayed_iput() and that needs to lock
3635 	 * fs_info->delayed_iput_lock. So we need to disable irqs here to
3636 	 * prevent a deadlock.
3637 	 */
3638 	spin_lock_irq(&fs_info->delayed_iput_lock);
3639 	while (!list_empty(&fs_info->delayed_iputs)) {
3640 		struct btrfs_inode *inode;
3641 
3642 		inode = list_first_entry(&fs_info->delayed_iputs,
3643 				struct btrfs_inode, delayed_iput);
3644 		run_delayed_iput_locked(fs_info, inode);
3645 		if (need_resched()) {
3646 			spin_unlock_irq(&fs_info->delayed_iput_lock);
3647 			cond_resched();
3648 			spin_lock_irq(&fs_info->delayed_iput_lock);
3649 		}
3650 	}
3651 	spin_unlock_irq(&fs_info->delayed_iput_lock);
3652 }
3653 
3654 /*
3655  * Wait for flushing all delayed iputs
3656  *
3657  * @fs_info:  the filesystem
3658  *
3659  * This will wait on any delayed iputs that are currently running with KILLABLE
3660  * set.  Once they are all done running we will return, unless we are killed in
3661  * which case we return EINTR. This helps in user operations like fallocate etc
3662  * that might get blocked on the iputs.
3663  *
3664  * Return EINTR if we were killed, 0 if nothing's pending
3665  */
3666 int btrfs_wait_on_delayed_iputs(struct btrfs_fs_info *fs_info)
3667 {
3668 	int ret = wait_event_killable(fs_info->delayed_iputs_wait,
3669 			atomic_read(&fs_info->nr_delayed_iputs) == 0);
3670 	if (ret)
3671 		return -EINTR;
3672 	return 0;
3673 }
3674 
3675 /*
3676  * This creates an orphan entry for the given inode in case something goes wrong
3677  * in the middle of an unlink.
3678  */
3679 int btrfs_orphan_add(struct btrfs_trans_handle *trans,
3680 		     struct btrfs_inode *inode)
3681 {
3682 	int ret;
3683 
3684 	ret = btrfs_insert_orphan_item(trans, inode->root, btrfs_ino(inode));
3685 	if (unlikely(ret && ret != -EEXIST)) {
3686 		btrfs_abort_transaction(trans, ret);
3687 		return ret;
3688 	}
3689 
3690 	return 0;
3691 }
3692 
3693 /*
3694  * We have done the delete so we can go ahead and remove the orphan item for
3695  * this particular inode.
3696  */
3697 static int btrfs_orphan_del(struct btrfs_trans_handle *trans,
3698 			    struct btrfs_inode *inode)
3699 {
3700 	return btrfs_del_orphan_item(trans, inode->root, btrfs_ino(inode));
3701 }
3702 
3703 /*
3704  * this cleans up any orphans that may be left on the list from the last use
3705  * of this root.
3706  */
3707 int btrfs_orphan_cleanup(struct btrfs_root *root)
3708 {
3709 	struct btrfs_fs_info *fs_info = root->fs_info;
3710 	BTRFS_PATH_AUTO_FREE(path);
3711 	struct extent_buffer *leaf;
3712 	struct btrfs_key key, found_key;
3713 	struct btrfs_trans_handle *trans;
3714 	u64 last_objectid = 0;
3715 	int ret = 0, nr_unlink = 0;
3716 
3717 	if (test_and_set_bit(BTRFS_ROOT_ORPHAN_CLEANUP, &root->state))
3718 		return 0;
3719 
3720 	path = btrfs_alloc_path();
3721 	if (!path) {
3722 		ret = -ENOMEM;
3723 		goto out;
3724 	}
3725 	path->reada = READA_BACK;
3726 
3727 	key.objectid = BTRFS_ORPHAN_OBJECTID;
3728 	key.type = BTRFS_ORPHAN_ITEM_KEY;
3729 	key.offset = (u64)-1;
3730 
3731 	while (1) {
3732 		struct btrfs_inode *inode;
3733 
3734 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3735 		if (ret < 0)
3736 			goto out;
3737 
3738 		/*
3739 		 * if ret == 0 means we found what we were searching for, which
3740 		 * is weird, but possible, so only screw with path if we didn't
3741 		 * find the key and see if we have stuff that matches
3742 		 */
3743 		if (ret > 0) {
3744 			ret = 0;
3745 			if (path->slots[0] == 0)
3746 				break;
3747 			path->slots[0]--;
3748 		}
3749 
3750 		/* pull out the item */
3751 		leaf = path->nodes[0];
3752 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
3753 
3754 		/* make sure the item matches what we want */
3755 		if (found_key.objectid != BTRFS_ORPHAN_OBJECTID)
3756 			break;
3757 		if (found_key.type != BTRFS_ORPHAN_ITEM_KEY)
3758 			break;
3759 
3760 		/* release the path since we're done with it */
3761 		btrfs_release_path(path);
3762 
3763 		/*
3764 		 * this is where we are basically btrfs_lookup, without the
3765 		 * crossing root thing.  we store the inode number in the
3766 		 * offset of the orphan item.
3767 		 */
3768 
3769 		if (found_key.offset == last_objectid) {
3770 			/*
3771 			 * We found the same inode as before. This means we were
3772 			 * not able to remove its items via eviction triggered
3773 			 * by an iput(). A transaction abort may have happened,
3774 			 * due to -ENOSPC for example, so try to grab the error
3775 			 * that lead to a transaction abort, if any.
3776 			 */
3777 			btrfs_err(fs_info,
3778 				  "Error removing orphan entry, stopping orphan cleanup");
3779 			ret = BTRFS_FS_ERROR(fs_info) ?: -EINVAL;
3780 			goto out;
3781 		}
3782 
3783 		last_objectid = found_key.offset;
3784 
3785 		found_key.objectid = found_key.offset;
3786 		found_key.type = BTRFS_INODE_ITEM_KEY;
3787 		found_key.offset = 0;
3788 		inode = btrfs_iget(last_objectid, root);
3789 		if (IS_ERR(inode)) {
3790 			ret = PTR_ERR(inode);
3791 			inode = NULL;
3792 			if (ret != -ENOENT)
3793 				goto out;
3794 		}
3795 
3796 		if (!inode && root == fs_info->tree_root) {
3797 			struct btrfs_root *dead_root;
3798 			bool is_dead_root = false;
3799 
3800 			/*
3801 			 * This is an orphan in the tree root. Currently these
3802 			 * could come from 2 sources:
3803 			 *  a) a root (snapshot/subvolume) deletion in progress
3804 			 *  b) a free space cache inode
3805 			 * We need to distinguish those two, as the orphan item
3806 			 * for a root must not get deleted before the deletion
3807 			 * of the snapshot/subvolume's tree completes.
3808 			 *
3809 			 * btrfs_find_orphan_roots() ran before us, which has
3810 			 * found all deleted roots and loaded them into
3811 			 * fs_info->fs_roots_radix. So here we can find if an
3812 			 * orphan item corresponds to a deleted root by looking
3813 			 * up the root from that radix tree.
3814 			 */
3815 
3816 			spin_lock(&fs_info->fs_roots_radix_lock);
3817 			dead_root = radix_tree_lookup(&fs_info->fs_roots_radix,
3818 							 (unsigned long)found_key.objectid);
3819 			if (dead_root && btrfs_root_refs(&dead_root->root_item) == 0)
3820 				is_dead_root = true;
3821 			spin_unlock(&fs_info->fs_roots_radix_lock);
3822 
3823 			if (is_dead_root) {
3824 				/* prevent this orphan from being found again */
3825 				key.offset = found_key.objectid - 1;
3826 				continue;
3827 			}
3828 
3829 		}
3830 
3831 		/*
3832 		 * If we have an inode with links, there are a couple of
3833 		 * possibilities:
3834 		 *
3835 		 * 1. We were halfway through creating fsverity metadata for the
3836 		 * file. In that case, the orphan item represents incomplete
3837 		 * fsverity metadata which must be cleaned up with
3838 		 * btrfs_drop_verity_items and deleting the orphan item.
3839 
3840 		 * 2. Old kernels (before v3.12) used to create an
3841 		 * orphan item for truncate indicating that there were possibly
3842 		 * extent items past i_size that needed to be deleted. In v3.12,
3843 		 * truncate was changed to update i_size in sync with the extent
3844 		 * items, but the (useless) orphan item was still created. Since
3845 		 * v4.18, we don't create the orphan item for truncate at all.
3846 		 *
3847 		 * So, this item could mean that we need to do a truncate, but
3848 		 * only if this filesystem was last used on a pre-v3.12 kernel
3849 		 * and was not cleanly unmounted. The odds of that are quite
3850 		 * slim, and it's a pain to do the truncate now, so just delete
3851 		 * the orphan item.
3852 		 *
3853 		 * It's also possible that this orphan item was supposed to be
3854 		 * deleted but wasn't. The inode number may have been reused,
3855 		 * but either way, we can delete the orphan item.
3856 		 */
3857 		if (!inode || inode->vfs_inode.i_nlink) {
3858 			if (inode) {
3859 				ret = btrfs_drop_verity_items(inode);
3860 				iput(&inode->vfs_inode);
3861 				inode = NULL;
3862 				if (ret)
3863 					goto out;
3864 			}
3865 			trans = btrfs_start_transaction(root, 1);
3866 			if (IS_ERR(trans)) {
3867 				ret = PTR_ERR(trans);
3868 				goto out;
3869 			}
3870 			btrfs_debug(fs_info, "auto deleting %Lu",
3871 				    found_key.objectid);
3872 			ret = btrfs_del_orphan_item(trans, root,
3873 						    found_key.objectid);
3874 			btrfs_end_transaction(trans);
3875 			if (ret)
3876 				goto out;
3877 			continue;
3878 		}
3879 
3880 		nr_unlink++;
3881 
3882 		/* this will do delete_inode and everything for us */
3883 		iput(&inode->vfs_inode);
3884 	}
3885 	/* release the path since we're done with it */
3886 	btrfs_release_path(path);
3887 
3888 	if (test_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &root->state)) {
3889 		trans = btrfs_join_transaction(root);
3890 		if (!IS_ERR(trans))
3891 			btrfs_end_transaction(trans);
3892 	}
3893 
3894 	if (nr_unlink)
3895 		btrfs_debug(fs_info, "unlinked %d orphans", nr_unlink);
3896 
3897 out:
3898 	if (ret)
3899 		btrfs_err(fs_info, "could not do orphan cleanup %d", ret);
3900 	return ret;
3901 }
3902 
3903 /*
3904  * Look ahead in the leaf for xattrs. If we don't find any then we know there
3905  * can't be any ACLs.
3906  *
3907  * @leaf:       the eb leaf where to search
3908  * @slot:       the slot the inode is in
3909  * @objectid:   the objectid of the inode
3910  *
3911  * Return true if there is xattr/ACL, false otherwise.
3912  */
3913 static noinline bool acls_after_inode_item(struct extent_buffer *leaf,
3914 					   int slot, u64 objectid,
3915 					   int *first_xattr_slot)
3916 {
3917 	u32 nritems = btrfs_header_nritems(leaf);
3918 	struct btrfs_key found_key;
3919 	static u64 xattr_access = 0;
3920 	static u64 xattr_default = 0;
3921 	int scanned = 0;
3922 
3923 	if (!xattr_access) {
3924 		xattr_access = btrfs_name_hash(XATTR_NAME_POSIX_ACL_ACCESS,
3925 					strlen(XATTR_NAME_POSIX_ACL_ACCESS));
3926 		xattr_default = btrfs_name_hash(XATTR_NAME_POSIX_ACL_DEFAULT,
3927 					strlen(XATTR_NAME_POSIX_ACL_DEFAULT));
3928 	}
3929 
3930 	slot++;
3931 	*first_xattr_slot = -1;
3932 	while (slot < nritems) {
3933 		btrfs_item_key_to_cpu(leaf, &found_key, slot);
3934 
3935 		/* We found a different objectid, there must be no ACLs. */
3936 		if (found_key.objectid != objectid)
3937 			return false;
3938 
3939 		/* We found an xattr, assume we've got an ACL. */
3940 		if (found_key.type == BTRFS_XATTR_ITEM_KEY) {
3941 			if (*first_xattr_slot == -1)
3942 				*first_xattr_slot = slot;
3943 			if (found_key.offset == xattr_access ||
3944 			    found_key.offset == xattr_default)
3945 				return true;
3946 		}
3947 
3948 		/*
3949 		 * We found a key greater than an xattr key, there can't be any
3950 		 * ACLs later on.
3951 		 */
3952 		if (found_key.type > BTRFS_XATTR_ITEM_KEY)
3953 			return false;
3954 
3955 		slot++;
3956 		scanned++;
3957 
3958 		/*
3959 		 * The item order goes like:
3960 		 * - inode
3961 		 * - inode backrefs
3962 		 * - xattrs
3963 		 * - extents,
3964 		 *
3965 		 * so if there are lots of hard links to an inode there can be
3966 		 * a lot of backrefs.  Don't waste time searching too hard,
3967 		 * this is just an optimization.
3968 		 */
3969 		if (scanned >= 8)
3970 			break;
3971 	}
3972 	/*
3973 	 * We hit the end of the leaf before we found an xattr or something
3974 	 * larger than an xattr.  We have to assume the inode has ACLs.
3975 	 */
3976 	if (*first_xattr_slot == -1)
3977 		*first_xattr_slot = slot;
3978 	return true;
3979 }
3980 
3981 static int btrfs_init_file_extent_tree(struct btrfs_inode *inode)
3982 {
3983 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
3984 
3985 	if (WARN_ON_ONCE(inode->file_extent_tree))
3986 		return 0;
3987 	if (btrfs_fs_incompat(fs_info, NO_HOLES))
3988 		return 0;
3989 	if (!S_ISREG(inode->vfs_inode.i_mode))
3990 		return 0;
3991 	if (btrfs_is_free_space_inode(inode))
3992 		return 0;
3993 
3994 	inode->file_extent_tree = kmalloc_obj(struct extent_io_tree);
3995 	if (!inode->file_extent_tree)
3996 		return -ENOMEM;
3997 
3998 	btrfs_extent_io_tree_init(fs_info, inode->file_extent_tree,
3999 				  IO_TREE_INODE_FILE_EXTENT);
4000 	/* Lockdep class is set only for the file extent tree. */
4001 	lockdep_set_class(&inode->file_extent_tree->lock, &file_extent_tree_class);
4002 
4003 	return 0;
4004 }
4005 
4006 static int btrfs_add_inode_to_root(struct btrfs_inode *inode, bool prealloc)
4007 {
4008 	struct btrfs_root *root = inode->root;
4009 	struct btrfs_inode *existing;
4010 	const u64 ino = btrfs_ino(inode);
4011 	int ret;
4012 
4013 	if (inode_unhashed(&inode->vfs_inode))
4014 		return 0;
4015 
4016 	if (prealloc) {
4017 		ret = xa_reserve(&root->inodes, ino, GFP_NOFS);
4018 		if (ret)
4019 			return ret;
4020 	}
4021 
4022 	existing = xa_store(&root->inodes, ino, inode, GFP_ATOMIC);
4023 
4024 	if (xa_is_err(existing)) {
4025 		ret = xa_err(existing);
4026 		ASSERT(ret != -EINVAL);
4027 		ASSERT(ret != -ENOMEM);
4028 		return ret;
4029 	} else if (existing) {
4030 		WARN_ON(!(inode_state_read_once(&existing->vfs_inode) & (I_WILL_FREE | I_FREEING)));
4031 	}
4032 
4033 	return 0;
4034 }
4035 
4036 /*
4037  * Read a locked inode from the btree into the in-memory inode and add it to
4038  * its root list/tree.
4039  *
4040  * On failure clean up the inode.
4041  */
4042 static int btrfs_read_locked_inode(struct btrfs_inode *inode, struct btrfs_path *path)
4043 {
4044 	struct btrfs_root *root = inode->root;
4045 	struct btrfs_fs_info *fs_info = root->fs_info;
4046 	struct extent_buffer *leaf;
4047 	struct btrfs_inode_item *inode_item;
4048 	struct inode *vfs_inode = &inode->vfs_inode;
4049 	struct btrfs_key location;
4050 	unsigned long ptr;
4051 	int maybe_acls;
4052 	u32 rdev;
4053 	int ret;
4054 	bool filled = false;
4055 	int first_xattr_slot;
4056 
4057 	ret = btrfs_fill_inode(inode, &rdev);
4058 	if (!ret)
4059 		filled = true;
4060 
4061 	ASSERT(path);
4062 
4063 	btrfs_get_inode_key(inode, &location);
4064 
4065 	ret = btrfs_lookup_inode(NULL, root, path, &location, 0);
4066 	if (ret) {
4067 		/*
4068 		 * ret > 0 can come from btrfs_search_slot called by
4069 		 * btrfs_lookup_inode(), this means the inode was not found.
4070 		 */
4071 		if (ret > 0)
4072 			ret = -ENOENT;
4073 		goto out;
4074 	}
4075 
4076 	leaf = path->nodes[0];
4077 
4078 	if (filled)
4079 		goto cache_index;
4080 
4081 	inode_item = btrfs_item_ptr(leaf, path->slots[0],
4082 				    struct btrfs_inode_item);
4083 	vfs_inode->i_mode = btrfs_inode_mode(leaf, inode_item);
4084 	set_nlink(vfs_inode, btrfs_inode_nlink(leaf, inode_item));
4085 	i_uid_write(vfs_inode, btrfs_inode_uid(leaf, inode_item));
4086 	i_gid_write(vfs_inode, btrfs_inode_gid(leaf, inode_item));
4087 	btrfs_i_size_write(inode, btrfs_inode_size(leaf, inode_item));
4088 
4089 	inode_set_atime(vfs_inode, btrfs_timespec_sec(leaf, &inode_item->atime),
4090 			btrfs_timespec_nsec(leaf, &inode_item->atime));
4091 
4092 	inode_set_mtime(vfs_inode, btrfs_timespec_sec(leaf, &inode_item->mtime),
4093 			btrfs_timespec_nsec(leaf, &inode_item->mtime));
4094 
4095 	inode_set_ctime(vfs_inode, btrfs_timespec_sec(leaf, &inode_item->ctime),
4096 			btrfs_timespec_nsec(leaf, &inode_item->ctime));
4097 
4098 	inode->i_otime_sec = btrfs_timespec_sec(leaf, &inode_item->otime);
4099 	inode->i_otime_nsec = btrfs_timespec_nsec(leaf, &inode_item->otime);
4100 
4101 	inode_set_bytes(vfs_inode, btrfs_inode_nbytes(leaf, inode_item));
4102 	inode->generation = btrfs_inode_generation(leaf, inode_item);
4103 	inode->last_trans = btrfs_inode_transid(leaf, inode_item);
4104 
4105 	inode_set_iversion_queried(vfs_inode, btrfs_inode_sequence(leaf, inode_item));
4106 	vfs_inode->i_generation = inode->generation;
4107 	vfs_inode->i_rdev = 0;
4108 	rdev = btrfs_inode_rdev(leaf, inode_item);
4109 
4110 	if (S_ISDIR(vfs_inode->i_mode))
4111 		inode->index_cnt = (u64)-1;
4112 
4113 	btrfs_inode_split_flags(btrfs_inode_flags(leaf, inode_item),
4114 				&inode->flags, &inode->ro_flags);
4115 
4116 cache_index:
4117 	btrfs_update_inode_mapping_flags(inode);
4118 	btrfs_set_inode_mapping_order(inode);
4119 
4120 	/*
4121 	 * If we were modified in the current generation and evicted from memory
4122 	 * and then re-read we need to do a full sync since we don't have any
4123 	 * idea about which extents were modified before we were evicted from
4124 	 * cache.
4125 	 *
4126 	 * This is required for both inode re-read from disk and delayed inode
4127 	 * in the delayed_nodes xarray.
4128 	 */
4129 	if (inode->last_trans == btrfs_get_fs_generation(fs_info))
4130 		set_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags);
4131 
4132 	/*
4133 	 * We don't persist the id of the transaction where an unlink operation
4134 	 * against the inode was last made. So here we assume the inode might
4135 	 * have been evicted, and therefore the exact value of last_unlink_trans
4136 	 * lost, and set it to last_trans to avoid metadata inconsistencies
4137 	 * between the inode and its parent if the inode is fsync'ed and the log
4138 	 * replayed. For example, in the scenario:
4139 	 *
4140 	 * touch mydir/foo
4141 	 * ln mydir/foo mydir/bar
4142 	 * sync
4143 	 * unlink mydir/bar
4144 	 * echo 2 > /proc/sys/vm/drop_caches   # evicts inode
4145 	 * xfs_io -c fsync mydir/foo
4146 	 * <power failure>
4147 	 * mount fs, triggers fsync log replay
4148 	 *
4149 	 * We must make sure that when we fsync our inode foo we also log its
4150 	 * parent inode, otherwise after log replay the parent still has the
4151 	 * dentry with the "bar" name but our inode foo has a link count of 1
4152 	 * and doesn't have an inode ref with the name "bar" anymore.
4153 	 *
4154 	 * Setting last_unlink_trans to last_trans is a pessimistic approach,
4155 	 * but it guarantees correctness at the expense of occasional full
4156 	 * transaction commits on fsync if our inode is a directory, or if our
4157 	 * inode is not a directory, logging its parent unnecessarily.
4158 	 */
4159 	inode->last_unlink_trans = inode->last_trans;
4160 
4161 	/*
4162 	 * Same logic as for last_unlink_trans. We don't persist the generation
4163 	 * of the last transaction where this inode was used for a reflink
4164 	 * operation, so after eviction and reloading the inode we must be
4165 	 * pessimistic and assume the last transaction that modified the inode.
4166 	 */
4167 	inode->last_reflink_trans = inode->last_trans;
4168 
4169 	path->slots[0]++;
4170 	if (vfs_inode->i_nlink != 1 ||
4171 	    path->slots[0] >= btrfs_header_nritems(leaf))
4172 		goto cache_acl;
4173 
4174 	btrfs_item_key_to_cpu(leaf, &location, path->slots[0]);
4175 	if (location.objectid != btrfs_ino(inode))
4176 		goto cache_acl;
4177 
4178 	ptr = btrfs_item_ptr_offset(leaf, path->slots[0]);
4179 	if (location.type == BTRFS_INODE_REF_KEY) {
4180 		struct btrfs_inode_ref *ref;
4181 
4182 		ref = (struct btrfs_inode_ref *)ptr;
4183 		inode->dir_index = btrfs_inode_ref_index(leaf, ref);
4184 	} else if (location.type == BTRFS_INODE_EXTREF_KEY) {
4185 		struct btrfs_inode_extref *extref;
4186 
4187 		extref = (struct btrfs_inode_extref *)ptr;
4188 		inode->dir_index = btrfs_inode_extref_index(leaf, extref);
4189 	}
4190 cache_acl:
4191 	/*
4192 	 * try to precache a NULL acl entry for files that don't have
4193 	 * any xattrs or acls
4194 	 */
4195 	maybe_acls = acls_after_inode_item(leaf, path->slots[0],
4196 					   btrfs_ino(inode), &first_xattr_slot);
4197 	if (first_xattr_slot != -1) {
4198 		path->slots[0] = first_xattr_slot;
4199 		ret = btrfs_load_inode_props(inode, path);
4200 		if (ret)
4201 			btrfs_err(fs_info,
4202 				  "error loading props for ino %llu (root %llu): %d",
4203 				  btrfs_ino(inode), btrfs_root_id(root), ret);
4204 	}
4205 
4206 	/*
4207 	 * We don't need the path anymore, so release it to avoid holding a read
4208 	 * lock on a leaf while calling btrfs_init_file_extent_tree(), which can
4209 	 * allocate memory that triggers reclaim (GFP_KERNEL) and cause a locking
4210 	 * dependency.
4211 	 */
4212 	btrfs_release_path(path);
4213 
4214 	ret = btrfs_init_file_extent_tree(inode);
4215 	if (ret)
4216 		goto out;
4217 	btrfs_inode_set_file_extent_range(inode, 0,
4218 			  round_up(i_size_read(vfs_inode), fs_info->sectorsize));
4219 
4220 	if (!maybe_acls)
4221 		cache_no_acl(vfs_inode);
4222 
4223 	switch (vfs_inode->i_mode & S_IFMT) {
4224 	case S_IFREG:
4225 		vfs_inode->i_mapping->a_ops = &btrfs_aops;
4226 		vfs_inode->i_fop = &btrfs_file_operations;
4227 		vfs_inode->i_op = &btrfs_file_inode_operations;
4228 		break;
4229 	case S_IFDIR:
4230 		vfs_inode->i_fop = &btrfs_dir_file_operations;
4231 		vfs_inode->i_op = &btrfs_dir_inode_operations;
4232 		break;
4233 	case S_IFLNK:
4234 		vfs_inode->i_op = &btrfs_symlink_inode_operations;
4235 		inode_nohighmem(vfs_inode);
4236 		vfs_inode->i_mapping->a_ops = &btrfs_aops;
4237 		break;
4238 	default:
4239 		vfs_inode->i_op = &btrfs_special_inode_operations;
4240 		init_special_inode(vfs_inode, vfs_inode->i_mode, rdev);
4241 		break;
4242 	}
4243 
4244 	btrfs_sync_inode_flags_to_i_flags(inode);
4245 
4246 	ret = btrfs_add_inode_to_root(inode, true);
4247 	if (ret)
4248 		goto out;
4249 
4250 	return 0;
4251 out:
4252 	/*
4253 	 * We may have a read locked leaf and iget_failed() triggers inode
4254 	 * eviction which needs to release the delayed inode and that needs
4255 	 * to lock the delayed inode's mutex. This can cause a ABBA deadlock
4256 	 * with a task running delayed items, as that require first locking
4257 	 * the delayed inode's mutex and then modifying its subvolume btree.
4258 	 * So release the path before iget_failed().
4259 	 */
4260 	btrfs_release_path(path);
4261 	iget_failed(vfs_inode);
4262 	return ret;
4263 }
4264 
4265 /*
4266  * given a leaf and an inode, copy the inode fields into the leaf
4267  */
4268 static void fill_inode_item(struct btrfs_trans_handle *trans,
4269 			    struct extent_buffer *leaf,
4270 			    struct btrfs_inode_item *item,
4271 			    struct inode *inode)
4272 {
4273 	u64 flags;
4274 
4275 	btrfs_set_inode_uid(leaf, item, i_uid_read(inode));
4276 	btrfs_set_inode_gid(leaf, item, i_gid_read(inode));
4277 	btrfs_set_inode_size(leaf, item, BTRFS_I(inode)->disk_i_size);
4278 	btrfs_set_inode_mode(leaf, item, inode->i_mode);
4279 	btrfs_set_inode_nlink(leaf, item, inode->i_nlink);
4280 
4281 	btrfs_set_timespec_sec(leaf, &item->atime, inode_get_atime_sec(inode));
4282 	btrfs_set_timespec_nsec(leaf, &item->atime, inode_get_atime_nsec(inode));
4283 
4284 	btrfs_set_timespec_sec(leaf, &item->mtime, inode_get_mtime_sec(inode));
4285 	btrfs_set_timespec_nsec(leaf, &item->mtime, inode_get_mtime_nsec(inode));
4286 
4287 	btrfs_set_timespec_sec(leaf, &item->ctime, inode_get_ctime_sec(inode));
4288 	btrfs_set_timespec_nsec(leaf, &item->ctime, inode_get_ctime_nsec(inode));
4289 
4290 	btrfs_set_timespec_sec(leaf, &item->otime, BTRFS_I(inode)->i_otime_sec);
4291 	btrfs_set_timespec_nsec(leaf, &item->otime, BTRFS_I(inode)->i_otime_nsec);
4292 
4293 	btrfs_set_inode_nbytes(leaf, item, inode_get_bytes(inode));
4294 	btrfs_set_inode_generation(leaf, item, BTRFS_I(inode)->generation);
4295 	btrfs_set_inode_sequence(leaf, item, inode_peek_iversion(inode));
4296 	btrfs_set_inode_transid(leaf, item, trans->transid);
4297 	btrfs_set_inode_rdev(leaf, item, inode->i_rdev);
4298 	flags = btrfs_inode_combine_flags(BTRFS_I(inode)->flags,
4299 					  BTRFS_I(inode)->ro_flags);
4300 	btrfs_set_inode_flags(leaf, item, flags);
4301 	btrfs_set_inode_block_group(leaf, item, 0);
4302 }
4303 
4304 /*
4305  * copy everything in the in-memory inode into the btree.
4306  */
4307 static noinline int btrfs_update_inode_item(struct btrfs_trans_handle *trans,
4308 					    struct btrfs_inode *inode)
4309 {
4310 	struct btrfs_inode_item *inode_item;
4311 	BTRFS_PATH_AUTO_FREE(path);
4312 	struct extent_buffer *leaf;
4313 	struct btrfs_key key;
4314 	int ret;
4315 
4316 	path = btrfs_alloc_path();
4317 	if (!path)
4318 		return -ENOMEM;
4319 
4320 	btrfs_get_inode_key(inode, &key);
4321 	ret = btrfs_lookup_inode(trans, inode->root, path, &key, 1);
4322 	if (ret) {
4323 		if (ret > 0)
4324 			ret = -ENOENT;
4325 		return ret;
4326 	}
4327 
4328 	leaf = path->nodes[0];
4329 	inode_item = btrfs_item_ptr(leaf, path->slots[0],
4330 				    struct btrfs_inode_item);
4331 
4332 	fill_inode_item(trans, leaf, inode_item, &inode->vfs_inode);
4333 	btrfs_set_inode_last_trans(trans, inode);
4334 	return 0;
4335 }
4336 
4337 /*
4338  * copy everything in the in-memory inode into the btree.
4339  */
4340 int btrfs_update_inode(struct btrfs_trans_handle *trans,
4341 		       struct btrfs_inode *inode)
4342 {
4343 	struct btrfs_root *root = inode->root;
4344 	struct btrfs_fs_info *fs_info = root->fs_info;
4345 	int ret;
4346 
4347 	/*
4348 	 * If the inode is a free space inode, we can deadlock during commit
4349 	 * if we put it into the delayed code.
4350 	 *
4351 	 * The data relocation inode should also be directly updated
4352 	 * without delay
4353 	 */
4354 	if (!btrfs_is_free_space_inode(inode)
4355 	    && !btrfs_is_data_reloc_root(root)
4356 	    && !test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags)) {
4357 		btrfs_update_root_times(trans, root);
4358 
4359 		ret = btrfs_delayed_update_inode(trans, inode);
4360 		if (!ret)
4361 			btrfs_set_inode_last_trans(trans, inode);
4362 		return ret;
4363 	}
4364 
4365 	return btrfs_update_inode_item(trans, inode);
4366 }
4367 
4368 int btrfs_update_inode_fallback(struct btrfs_trans_handle *trans,
4369 				struct btrfs_inode *inode)
4370 {
4371 	int ret;
4372 
4373 	ret = btrfs_update_inode(trans, inode);
4374 	if (ret == -ENOSPC)
4375 		return btrfs_update_inode_item(trans, inode);
4376 	return ret;
4377 }
4378 
4379 static void update_time_after_link_or_unlink(struct btrfs_inode *dir)
4380 {
4381 	struct timespec64 now;
4382 
4383 	/*
4384 	 * If we are replaying a log tree, we do not want to update the mtime
4385 	 * and ctime of the parent directory with the current time, since the
4386 	 * log replay procedure is responsible for setting them to their correct
4387 	 * values (the ones it had when the fsync was done).
4388 	 */
4389 	if (test_bit(BTRFS_FS_LOG_RECOVERING, &dir->root->fs_info->flags))
4390 		return;
4391 
4392 	now = inode_set_ctime_current(&dir->vfs_inode);
4393 	inode_set_mtime_to_ts(&dir->vfs_inode, now);
4394 }
4395 
4396 /*
4397  * unlink helper that gets used here in inode.c and in the tree logging
4398  * recovery code.  It remove a link in a directory with a given name, and
4399  * also drops the back refs in the inode to the directory
4400  */
4401 static int __btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4402 				struct btrfs_inode *dir,
4403 				struct btrfs_inode *inode,
4404 				const struct fscrypt_str *name,
4405 				struct btrfs_rename_ctx *rename_ctx)
4406 {
4407 	struct btrfs_root *root = dir->root;
4408 	struct btrfs_fs_info *fs_info = root->fs_info;
4409 	struct btrfs_path *path;
4410 	int ret = 0;
4411 	struct btrfs_dir_item *di;
4412 	u64 index;
4413 	u64 ino = btrfs_ino(inode);
4414 	u64 dir_ino = btrfs_ino(dir);
4415 
4416 	path = btrfs_alloc_path();
4417 	if (!path)
4418 		return -ENOMEM;
4419 
4420 	di = btrfs_lookup_dir_item(trans, root, path, dir_ino, name, -1);
4421 	if (IS_ERR_OR_NULL(di)) {
4422 		btrfs_free_path(path);
4423 		return di ? PTR_ERR(di) : -ENOENT;
4424 	}
4425 	ret = btrfs_delete_one_dir_name(trans, root, path, di);
4426 	/*
4427 	 * Down the call chains below we'll also need to allocate a path, so no
4428 	 * need to hold on to this one for longer than necessary.
4429 	 */
4430 	btrfs_free_path(path);
4431 	if (ret)
4432 		return ret;
4433 
4434 	/*
4435 	 * If we don't have dir index, we have to get it by looking up
4436 	 * the inode ref, since we get the inode ref, remove it directly,
4437 	 * it is unnecessary to do delayed deletion.
4438 	 *
4439 	 * But if we have dir index, needn't search inode ref to get it.
4440 	 * Since the inode ref is close to the inode item, it is better
4441 	 * that we delay to delete it, and just do this deletion when
4442 	 * we update the inode item.
4443 	 */
4444 	if (inode->dir_index) {
4445 		ret = btrfs_delayed_delete_inode_ref(inode);
4446 		if (!ret) {
4447 			index = inode->dir_index;
4448 			goto skip_backref;
4449 		}
4450 	}
4451 
4452 	ret = btrfs_del_inode_ref(trans, root, name, ino, dir_ino, &index);
4453 	if (unlikely(ret)) {
4454 		btrfs_crit(fs_info,
4455 	   "failed to delete reference to %.*s, root %llu inode %llu parent %llu",
4456 			   name->len, name->name, btrfs_root_id(root), ino, dir_ino);
4457 		btrfs_abort_transaction(trans, ret);
4458 		return ret;
4459 	}
4460 skip_backref:
4461 	if (rename_ctx)
4462 		rename_ctx->index = index;
4463 
4464 	ret = btrfs_delete_delayed_dir_index(trans, dir, index);
4465 	if (unlikely(ret)) {
4466 		btrfs_abort_transaction(trans, ret);
4467 		return ret;
4468 	}
4469 
4470 	/*
4471 	 * If we are in a rename context, we don't need to update anything in the
4472 	 * log. That will be done later during the rename by btrfs_log_new_name().
4473 	 * Besides that, doing it here would only cause extra unnecessary btree
4474 	 * operations on the log tree, increasing latency for applications.
4475 	 */
4476 	if (!rename_ctx) {
4477 		btrfs_del_inode_ref_in_log(trans, name, inode, dir);
4478 		btrfs_del_dir_entries_in_log(trans, name, dir, index);
4479 	}
4480 
4481 	/*
4482 	 * If we have a pending delayed iput we could end up with the final iput
4483 	 * being run in btrfs-cleaner context.  If we have enough of these built
4484 	 * up we can end up burning a lot of time in btrfs-cleaner without any
4485 	 * way to throttle the unlinks.  Since we're currently holding a ref on
4486 	 * the inode we can run the delayed iput here without any issues as the
4487 	 * final iput won't be done until after we drop the ref we're currently
4488 	 * holding.
4489 	 */
4490 	btrfs_run_delayed_iput(fs_info, inode);
4491 
4492 	btrfs_i_size_write(dir, dir->vfs_inode.i_size - name->len * 2);
4493 	inode_inc_iversion(&inode->vfs_inode);
4494 	inode_set_ctime_current(&inode->vfs_inode);
4495 	inode_inc_iversion(&dir->vfs_inode);
4496 	update_time_after_link_or_unlink(dir);
4497 
4498 	return btrfs_update_inode(trans, dir);
4499 }
4500 
4501 int btrfs_unlink_inode(struct btrfs_trans_handle *trans,
4502 		       struct btrfs_inode *dir, struct btrfs_inode *inode,
4503 		       const struct fscrypt_str *name)
4504 {
4505 	int ret;
4506 
4507 	ret = __btrfs_unlink_inode(trans, dir, inode, name, NULL);
4508 	if (!ret) {
4509 		drop_nlink(&inode->vfs_inode);
4510 		ret = btrfs_update_inode(trans, inode);
4511 	}
4512 	return ret;
4513 }
4514 
4515 /*
4516  * helper to start transaction for unlink and rmdir.
4517  *
4518  * unlink and rmdir are special in btrfs, they do not always free space, so
4519  * if we cannot make our reservations the normal way try and see if there is
4520  * plenty of slack room in the global reserve to migrate, otherwise we cannot
4521  * allow the unlink to occur.
4522  */
4523 static struct btrfs_trans_handle *__unlink_start_trans(struct btrfs_inode *dir)
4524 {
4525 	struct btrfs_root *root = dir->root;
4526 
4527 	return btrfs_start_transaction_fallback_global_rsv(root,
4528 						   BTRFS_UNLINK_METADATA_UNITS);
4529 }
4530 
4531 static int btrfs_unlink(struct inode *dir, struct dentry *dentry)
4532 {
4533 	struct btrfs_trans_handle *trans;
4534 	struct inode *inode = d_inode(dentry);
4535 	int ret;
4536 	struct fscrypt_name fname;
4537 
4538 	ret = fscrypt_setup_filename(dir, &dentry->d_name, 1, &fname);
4539 	if (ret)
4540 		return ret;
4541 
4542 	/* This needs to handle no-key deletions later on */
4543 
4544 	trans = __unlink_start_trans(BTRFS_I(dir));
4545 	if (IS_ERR(trans)) {
4546 		ret = PTR_ERR(trans);
4547 		goto fscrypt_free;
4548 	}
4549 
4550 	btrfs_record_unlink_dir(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4551 				false);
4552 
4553 	ret = btrfs_unlink_inode(trans, BTRFS_I(dir), BTRFS_I(d_inode(dentry)),
4554 				 &fname.disk_name);
4555 	if (ret)
4556 		goto end_trans;
4557 
4558 	if (inode->i_nlink == 0) {
4559 		ret = btrfs_orphan_add(trans, BTRFS_I(inode));
4560 		if (ret)
4561 			goto end_trans;
4562 	}
4563 
4564 end_trans:
4565 	btrfs_end_transaction(trans);
4566 	btrfs_btree_balance_dirty(BTRFS_I(dir)->root->fs_info);
4567 fscrypt_free:
4568 	fscrypt_free_filename(&fname);
4569 	return ret;
4570 }
4571 
4572 static int btrfs_unlink_subvol(struct btrfs_trans_handle *trans,
4573 			       struct btrfs_inode *dir, struct dentry *dentry)
4574 {
4575 	struct btrfs_root *root = dir->root;
4576 	struct btrfs_inode *inode = BTRFS_I(d_inode(dentry));
4577 	BTRFS_PATH_AUTO_FREE(path);
4578 	struct extent_buffer *leaf;
4579 	struct btrfs_dir_item *di;
4580 	struct btrfs_key key;
4581 	u64 index;
4582 	int ret;
4583 	u64 objectid;
4584 	u64 dir_ino = btrfs_ino(dir);
4585 	struct fscrypt_name fname;
4586 
4587 	ret = fscrypt_setup_filename(&dir->vfs_inode, &dentry->d_name, 1, &fname);
4588 	if (ret)
4589 		return ret;
4590 
4591 	/* This needs to handle no-key deletions later on */
4592 
4593 	if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) {
4594 		objectid = btrfs_root_id(inode->root);
4595 	} else if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4596 		objectid = inode->ref_root_id;
4597 	} else {
4598 		WARN_ON(1);
4599 		fscrypt_free_filename(&fname);
4600 		return -EINVAL;
4601 	}
4602 
4603 	path = btrfs_alloc_path();
4604 	if (!path) {
4605 		ret = -ENOMEM;
4606 		goto out;
4607 	}
4608 
4609 	di = btrfs_lookup_dir_item(trans, root, path, dir_ino,
4610 				   &fname.disk_name, -1);
4611 	if (IS_ERR_OR_NULL(di)) {
4612 		ret = di ? PTR_ERR(di) : -ENOENT;
4613 		goto out;
4614 	}
4615 
4616 	leaf = path->nodes[0];
4617 	btrfs_dir_item_key_to_cpu(leaf, di, &key);
4618 	WARN_ON(key.type != BTRFS_ROOT_ITEM_KEY || key.objectid != objectid);
4619 	ret = btrfs_delete_one_dir_name(trans, root, path, di);
4620 	if (unlikely(ret)) {
4621 		btrfs_abort_transaction(trans, ret);
4622 		goto out;
4623 	}
4624 	btrfs_release_path(path);
4625 
4626 	/*
4627 	 * This is a placeholder inode for a subvolume we didn't have a
4628 	 * reference to at the time of the snapshot creation.  In the meantime
4629 	 * we could have renamed the real subvol link into our snapshot, so
4630 	 * depending on btrfs_del_root_ref to return -ENOENT here is incorrect.
4631 	 * Instead simply lookup the dir_index_item for this entry so we can
4632 	 * remove it.  Otherwise we know we have a ref to the root and we can
4633 	 * call btrfs_del_root_ref, and it _shouldn't_ fail.
4634 	 */
4635 	if (btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID) {
4636 		di = btrfs_search_dir_index_item(root, path, dir_ino, &fname.disk_name);
4637 		if (IS_ERR(di)) {
4638 			ret = PTR_ERR(di);
4639 			btrfs_abort_transaction(trans, ret);
4640 			goto out;
4641 		}
4642 
4643 		leaf = path->nodes[0];
4644 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
4645 		index = key.offset;
4646 		btrfs_release_path(path);
4647 	} else {
4648 		ret = btrfs_del_root_ref(trans, objectid,
4649 					 btrfs_root_id(root), dir_ino,
4650 					 &index, &fname.disk_name);
4651 		if (unlikely(ret)) {
4652 			btrfs_abort_transaction(trans, ret);
4653 			goto out;
4654 		}
4655 	}
4656 
4657 	ret = btrfs_delete_delayed_dir_index(trans, dir, index);
4658 	if (unlikely(ret)) {
4659 		btrfs_abort_transaction(trans, ret);
4660 		goto out;
4661 	}
4662 
4663 	btrfs_i_size_write(dir, dir->vfs_inode.i_size - fname.disk_name.len * 2);
4664 	inode_inc_iversion(&dir->vfs_inode);
4665 	inode_set_mtime_to_ts(&dir->vfs_inode, inode_set_ctime_current(&dir->vfs_inode));
4666 	ret = btrfs_update_inode_fallback(trans, dir);
4667 	if (ret)
4668 		btrfs_abort_transaction(trans, ret);
4669 out:
4670 	fscrypt_free_filename(&fname);
4671 	return ret;
4672 }
4673 
4674 /*
4675  * Helper to check if the subvolume references other subvolumes or if it's
4676  * default.
4677  */
4678 static noinline int may_destroy_subvol(struct btrfs_root *root)
4679 {
4680 	struct btrfs_fs_info *fs_info = root->fs_info;
4681 	BTRFS_PATH_AUTO_FREE(path);
4682 	struct btrfs_dir_item *di;
4683 	struct btrfs_key key;
4684 	struct fscrypt_str name = FSTR_INIT("default", 7);
4685 	u64 dir_id;
4686 	int ret;
4687 
4688 	path = btrfs_alloc_path();
4689 	if (!path)
4690 		return -ENOMEM;
4691 
4692 	/* Make sure this root isn't set as the default subvol */
4693 	dir_id = btrfs_super_root_dir(fs_info->super_copy);
4694 	di = btrfs_lookup_dir_item(NULL, fs_info->tree_root, path,
4695 				   dir_id, &name, 0);
4696 	if (!IS_ERR_OR_NULL(di)) {
4697 		btrfs_dir_item_key_to_cpu(path->nodes[0], di, &key);
4698 		if (key.objectid == btrfs_root_id(root)) {
4699 			ret = -EPERM;
4700 			btrfs_err(fs_info,
4701 				  "deleting default subvolume %llu is not allowed",
4702 				  key.objectid);
4703 			return ret;
4704 		}
4705 		btrfs_release_path(path);
4706 	}
4707 
4708 	key.objectid = btrfs_root_id(root);
4709 	key.type = BTRFS_ROOT_REF_KEY;
4710 	key.offset = (u64)-1;
4711 
4712 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
4713 	if (ret < 0)
4714 		return ret;
4715 	if (unlikely(ret == 0)) {
4716 		/*
4717 		 * Key with offset -1 found, there would have to exist a root
4718 		 * with such id, but this is out of valid range.
4719 		 */
4720 		return -EUCLEAN;
4721 	}
4722 
4723 	ret = 0;
4724 	if (path->slots[0] > 0) {
4725 		path->slots[0]--;
4726 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0]);
4727 		if (key.objectid == btrfs_root_id(root) && key.type == BTRFS_ROOT_REF_KEY)
4728 			ret = -ENOTEMPTY;
4729 	}
4730 
4731 	return ret;
4732 }
4733 
4734 /* Delete all dentries for inodes belonging to the root */
4735 static void btrfs_prune_dentries(struct btrfs_root *root)
4736 {
4737 	struct btrfs_fs_info *fs_info = root->fs_info;
4738 	struct btrfs_inode *inode;
4739 	u64 min_ino = 0;
4740 
4741 	if (!BTRFS_FS_ERROR(fs_info))
4742 		WARN_ON(btrfs_root_refs(&root->root_item) != 0);
4743 
4744 	inode = btrfs_find_first_inode(root, min_ino);
4745 	while (inode) {
4746 		if (icount_read_once(&inode->vfs_inode) > 1)
4747 			d_prune_aliases(&inode->vfs_inode);
4748 
4749 		min_ino = btrfs_ino(inode) + 1;
4750 		/*
4751 		 * btrfs_drop_inode() will have it removed from the inode
4752 		 * cache when its usage count hits zero.
4753 		 */
4754 		iput(&inode->vfs_inode);
4755 		cond_resched();
4756 		inode = btrfs_find_first_inode(root, min_ino);
4757 	}
4758 }
4759 
4760 int btrfs_delete_subvolume(struct btrfs_inode *dir, struct dentry *dentry)
4761 {
4762 	struct btrfs_root *root = dir->root;
4763 	struct btrfs_fs_info *fs_info = root->fs_info;
4764 	struct inode *inode = d_inode(dentry);
4765 	struct btrfs_root *dest = BTRFS_I(inode)->root;
4766 	struct btrfs_trans_handle *trans;
4767 	struct btrfs_block_rsv block_rsv;
4768 	u64 root_flags;
4769 	u64 qgroup_reserved = 0;
4770 	int ret;
4771 
4772 	down_write(&fs_info->subvol_sem);
4773 
4774 	/*
4775 	 * Don't allow to delete a subvolume with send in progress. This is
4776 	 * inside the inode lock so the error handling that has to drop the bit
4777 	 * again is not run concurrently.
4778 	 */
4779 	spin_lock(&dest->root_item_lock);
4780 	if (dest->send_in_progress) {
4781 		spin_unlock(&dest->root_item_lock);
4782 		btrfs_warn(fs_info,
4783 			   "attempt to delete subvolume %llu during send",
4784 			   btrfs_root_id(dest));
4785 		ret = -EPERM;
4786 		goto out_up_write;
4787 	}
4788 	if (atomic_read(&dest->nr_swapfiles)) {
4789 		spin_unlock(&dest->root_item_lock);
4790 		btrfs_warn(fs_info,
4791 			   "attempt to delete subvolume %llu with active swapfile",
4792 			   btrfs_root_id(dest));
4793 		ret = -EPERM;
4794 		goto out_up_write;
4795 	}
4796 	root_flags = btrfs_root_flags(&dest->root_item);
4797 	btrfs_set_root_flags(&dest->root_item,
4798 			     root_flags | BTRFS_ROOT_SUBVOL_DEAD);
4799 	spin_unlock(&dest->root_item_lock);
4800 
4801 	ret = may_destroy_subvol(dest);
4802 	if (ret)
4803 		goto out_undead;
4804 
4805 	btrfs_init_block_rsv(&block_rsv, BTRFS_BLOCK_RSV_TEMP);
4806 	/*
4807 	 * One for dir inode,
4808 	 * two for dir entries,
4809 	 * two for root ref/backref.
4810 	 */
4811 	ret = btrfs_subvolume_reserve_metadata(root, &block_rsv, 5, true);
4812 	if (ret)
4813 		goto out_undead;
4814 	qgroup_reserved = block_rsv.qgroup_rsv_reserved;
4815 
4816 	trans = btrfs_start_transaction(root, 0);
4817 	if (IS_ERR(trans)) {
4818 		ret = PTR_ERR(trans);
4819 		goto out_release;
4820 	}
4821 	btrfs_qgroup_convert_reserved_meta(root, qgroup_reserved);
4822 	qgroup_reserved = 0;
4823 	trans->block_rsv = &block_rsv;
4824 	trans->bytes_reserved = block_rsv.size;
4825 
4826 	btrfs_record_snapshot_destroy(trans, dir);
4827 
4828 	ret = btrfs_unlink_subvol(trans, dir, dentry);
4829 	if (unlikely(ret)) {
4830 		btrfs_abort_transaction(trans, ret);
4831 		goto out_end_trans;
4832 	}
4833 
4834 	ret = btrfs_record_root_in_trans(trans, dest);
4835 	if (unlikely(ret)) {
4836 		btrfs_abort_transaction(trans, ret);
4837 		goto out_end_trans;
4838 	}
4839 
4840 	memset(&dest->root_item.drop_progress, 0,
4841 		sizeof(dest->root_item.drop_progress));
4842 	btrfs_set_root_drop_level(&dest->root_item, 0);
4843 	btrfs_set_root_refs(&dest->root_item, 0);
4844 
4845 	if (!test_and_set_bit(BTRFS_ROOT_ORPHAN_ITEM_INSERTED, &dest->state)) {
4846 		ret = btrfs_insert_orphan_item(trans,
4847 					fs_info->tree_root,
4848 					btrfs_root_id(dest));
4849 		if (unlikely(ret)) {
4850 			btrfs_abort_transaction(trans, ret);
4851 			goto out_end_trans;
4852 		}
4853 	}
4854 
4855 	ret = btrfs_uuid_tree_remove(trans, dest->root_item.uuid,
4856 				     BTRFS_UUID_KEY_SUBVOL, btrfs_root_id(dest));
4857 	if (unlikely(ret && ret != -ENOENT)) {
4858 		btrfs_abort_transaction(trans, ret);
4859 		goto out_end_trans;
4860 	}
4861 	if (!btrfs_is_empty_uuid(dest->root_item.received_uuid)) {
4862 		ret = btrfs_uuid_tree_remove(trans,
4863 					  dest->root_item.received_uuid,
4864 					  BTRFS_UUID_KEY_RECEIVED_SUBVOL,
4865 					  btrfs_root_id(dest));
4866 		if (unlikely(ret && ret != -ENOENT)) {
4867 			btrfs_abort_transaction(trans, ret);
4868 			goto out_end_trans;
4869 		}
4870 	}
4871 
4872 	free_anon_bdev(dest->anon_dev);
4873 	dest->anon_dev = 0;
4874 out_end_trans:
4875 	trans->block_rsv = NULL;
4876 	trans->bytes_reserved = 0;
4877 	ret = btrfs_end_transaction(trans);
4878 	inode->i_flags |= S_DEAD;
4879 out_release:
4880 	btrfs_block_rsv_release(fs_info, &block_rsv, (u64)-1, NULL);
4881 	if (qgroup_reserved)
4882 		btrfs_qgroup_free_meta_prealloc(root, qgroup_reserved);
4883 out_undead:
4884 	if (ret) {
4885 		spin_lock(&dest->root_item_lock);
4886 		root_flags = btrfs_root_flags(&dest->root_item);
4887 		btrfs_set_root_flags(&dest->root_item,
4888 				root_flags & ~BTRFS_ROOT_SUBVOL_DEAD);
4889 		spin_unlock(&dest->root_item_lock);
4890 	}
4891 out_up_write:
4892 	up_write(&fs_info->subvol_sem);
4893 	if (!ret) {
4894 		d_invalidate(dentry);
4895 		btrfs_prune_dentries(dest);
4896 		ASSERT(dest->send_in_progress == 0);
4897 	}
4898 
4899 	return ret;
4900 }
4901 
4902 static int btrfs_rmdir(struct inode *vfs_dir, struct dentry *dentry)
4903 {
4904 	struct btrfs_inode *dir = BTRFS_I(vfs_dir);
4905 	struct btrfs_inode *inode = BTRFS_I(d_inode(dentry));
4906 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
4907 	int ret = 0;
4908 	struct btrfs_trans_handle *trans;
4909 	struct fscrypt_name fname;
4910 
4911 	if (inode->vfs_inode.i_size > BTRFS_EMPTY_DIR_SIZE)
4912 		return -ENOTEMPTY;
4913 	if (btrfs_ino(inode) == BTRFS_FIRST_FREE_OBJECTID) {
4914 		if (unlikely(btrfs_fs_incompat(fs_info, EXTENT_TREE_V2))) {
4915 			btrfs_err(fs_info,
4916 			"extent tree v2 doesn't support snapshot deletion yet");
4917 			return -EOPNOTSUPP;
4918 		}
4919 		return btrfs_delete_subvolume(dir, dentry);
4920 	}
4921 
4922 	ret = fscrypt_setup_filename(vfs_dir, &dentry->d_name, 1, &fname);
4923 	if (ret)
4924 		return ret;
4925 
4926 	/* This needs to handle no-key deletions later on */
4927 
4928 	trans = __unlink_start_trans(dir);
4929 	if (IS_ERR(trans)) {
4930 		ret = PTR_ERR(trans);
4931 		goto out_notrans;
4932 	}
4933 
4934 	/*
4935 	 * Propagate the last_unlink_trans value of the deleted dir to its
4936 	 * parent directory. This is to prevent an unrecoverable log tree in the
4937 	 * case we do something like this:
4938 	 * 1) create dir foo
4939 	 * 2) create snapshot under dir foo
4940 	 * 3) delete the snapshot
4941 	 * 4) rmdir foo
4942 	 * 5) mkdir foo
4943 	 * 6) fsync foo or some file inside foo
4944 	 *
4945 	 * This is because we can't unlink other roots when replaying the dir
4946 	 * deletes for directory foo.
4947 	 */
4948 	if (inode->last_unlink_trans >= trans->transid)
4949 		btrfs_record_snapshot_destroy(trans, dir);
4950 
4951 	if (unlikely(btrfs_ino(inode) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
4952 		ret = btrfs_unlink_subvol(trans, dir, dentry);
4953 		goto out;
4954 	}
4955 
4956 	ret = btrfs_orphan_add(trans, inode);
4957 	if (ret)
4958 		goto out;
4959 
4960 	btrfs_record_unlink_dir(trans, dir, inode, false);
4961 
4962 	/* now the directory is empty */
4963 	ret = btrfs_unlink_inode(trans, dir, inode, &fname.disk_name);
4964 	if (!ret)
4965 		btrfs_i_size_write(inode, 0);
4966 out:
4967 	btrfs_end_transaction(trans);
4968 out_notrans:
4969 	btrfs_btree_balance_dirty(fs_info);
4970 	fscrypt_free_filename(&fname);
4971 
4972 	return ret;
4973 }
4974 
4975 static bool is_inside_block(u64 bytenr, u64 blockstart, u32 blocksize)
4976 {
4977 	ASSERT(IS_ALIGNED(blockstart, blocksize), "blockstart=%llu blocksize=%u",
4978 		blockstart, blocksize);
4979 
4980 	if (blockstart <= bytenr && bytenr <= blockstart + blocksize - 1)
4981 		return true;
4982 	return false;
4983 }
4984 
4985 static int truncate_block_zero_beyond_eof(struct btrfs_inode *inode, u64 start)
4986 {
4987 	const pgoff_t index = (start >> PAGE_SHIFT);
4988 	struct address_space *mapping = inode->vfs_inode.i_mapping;
4989 	struct folio *folio;
4990 	u64 zero_start;
4991 	u64 zero_end;
4992 	int ret = 0;
4993 
4994 again:
4995 	folio = filemap_lock_folio(mapping, index);
4996 	/* No folio present. */
4997 	if (IS_ERR(folio))
4998 		return 0;
4999 
5000 	if (!folio_test_uptodate(folio)) {
5001 		ret = btrfs_read_folio(NULL, folio);
5002 		folio_lock(folio);
5003 		if (folio->mapping != mapping) {
5004 			folio_unlock(folio);
5005 			folio_put(folio);
5006 			goto again;
5007 		}
5008 		if (unlikely(!folio_test_uptodate(folio))) {
5009 			ret = -EIO;
5010 			goto out_unlock;
5011 		}
5012 	}
5013 	folio_wait_writeback(folio);
5014 
5015 	/*
5016 	 * We do not need to lock extents nor wait for OE, as it's already
5017 	 * beyond EOF.
5018 	 */
5019 
5020 	zero_start = max_t(u64, folio_pos(folio), start);
5021 	zero_end = folio_next_pos(folio);
5022 	folio_zero_range(folio, zero_start - folio_pos(folio),
5023 			 zero_end - zero_start);
5024 
5025 out_unlock:
5026 	folio_unlock(folio);
5027 	folio_put(folio);
5028 	return ret;
5029 }
5030 
5031 /*
5032  * Handle the truncation of a fs block.
5033  *
5034  * @inode  - inode that we're zeroing
5035  * @offset - the file offset of the block to truncate
5036  *           The value must be inside [@start, @end], and the function will do
5037  *           extra checks if the block that covers @offset needs to be zeroed.
5038  * @start  - the start file offset of the range we want to zero
5039  * @end    - the end (inclusive) file offset of the range we want to zero.
5040  *
5041  * If the range is not block aligned, read out the folio that covers @offset,
5042  * and if needed zero blocks that are inside the folio and covered by [@start, @end).
5043  * If @start or @end + 1 lands inside a block, that block will be marked dirty
5044  * for writeback.
5045  *
5046  * This is utilized by hole punch, zero range, file expansion.
5047  */
5048 int btrfs_truncate_block(struct btrfs_inode *inode, u64 offset, u64 start, u64 end)
5049 {
5050 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
5051 	struct address_space *mapping = inode->vfs_inode.i_mapping;
5052 	struct extent_io_tree *io_tree = &inode->io_tree;
5053 	struct btrfs_ordered_extent *ordered;
5054 	struct extent_state *cached_state = NULL;
5055 	struct extent_changeset *data_reserved = NULL;
5056 	bool only_release_metadata = false;
5057 	u32 blocksize = fs_info->sectorsize;
5058 	pgoff_t index = (offset >> PAGE_SHIFT);
5059 	struct folio *folio;
5060 	gfp_t mask = btrfs_alloc_write_mask(mapping);
5061 	int ret = 0;
5062 	const bool in_head_block = is_inside_block(offset, round_down(start, blocksize),
5063 						   blocksize);
5064 	const bool in_tail_block = is_inside_block(offset, round_down(end, blocksize),
5065 						   blocksize);
5066 	bool need_truncate_head = false;
5067 	bool need_truncate_tail = false;
5068 	u64 zero_start;
5069 	u64 zero_end;
5070 	u64 block_start;
5071 	u64 block_end;
5072 
5073 	/* @offset should be inside the range. */
5074 	ASSERT(start <= offset && offset <= end, "offset=%llu start=%llu end=%llu",
5075 	       offset, start, end);
5076 
5077 	/* The range is aligned at both ends. */
5078 	if (IS_ALIGNED(start, blocksize) && IS_ALIGNED(end + 1, blocksize)) {
5079 		/*
5080 		 * For block size < page size case, we may have polluted blocks
5081 		 * beyond EOF. So we also need to zero them out.
5082 		 */
5083 		if (end == (u64)-1 && blocksize < PAGE_SIZE)
5084 			ret = truncate_block_zero_beyond_eof(inode, start);
5085 		goto out;
5086 	}
5087 
5088 	/*
5089 	 * @offset may not be inside the head nor tail block. In that case we
5090 	 * don't need to do anything.
5091 	 */
5092 	if (!in_head_block && !in_tail_block)
5093 		goto out;
5094 
5095 	/*
5096 	 * Skip the truncation if the range in the target block is already aligned.
5097 	 * The seemingly complex check will also handle the same block case.
5098 	 */
5099 	if (in_head_block && !IS_ALIGNED(start, blocksize))
5100 		need_truncate_head = true;
5101 	if (in_tail_block && !IS_ALIGNED(end + 1, blocksize))
5102 		need_truncate_tail = true;
5103 	if (!need_truncate_head && !need_truncate_tail)
5104 		goto out;
5105 
5106 	block_start = round_down(offset, blocksize);
5107 	block_end = block_start + blocksize - 1;
5108 
5109 	ret = btrfs_check_data_free_space(inode, &data_reserved, block_start,
5110 					  blocksize, false);
5111 	if (ret < 0) {
5112 		size_t write_bytes = blocksize;
5113 
5114 		if (btrfs_check_nocow_lock(inode, block_start, &write_bytes, false) > 0) {
5115 			/* For nocow case, no need to reserve data space. */
5116 			ASSERT(write_bytes == blocksize, "write_bytes=%zu blocksize=%u",
5117 			       write_bytes, blocksize);
5118 			only_release_metadata = true;
5119 		} else {
5120 			goto out;
5121 		}
5122 	}
5123 	ret = btrfs_delalloc_reserve_metadata(inode, blocksize, blocksize, false);
5124 	if (ret < 0) {
5125 		if (!only_release_metadata)
5126 			btrfs_free_reserved_data_space(inode, data_reserved,
5127 						       block_start, blocksize);
5128 		goto out;
5129 	}
5130 again:
5131 	folio = __filemap_get_folio(mapping, index,
5132 				    FGP_LOCK | FGP_ACCESSED | FGP_CREAT, mask);
5133 	if (IS_ERR(folio)) {
5134 		if (only_release_metadata)
5135 			btrfs_delalloc_release_metadata(inode, blocksize, true);
5136 		else
5137 			btrfs_delalloc_release_space(inode, data_reserved,
5138 						     block_start, blocksize, true);
5139 		btrfs_delalloc_release_extents(inode, blocksize);
5140 		ret = PTR_ERR(folio);
5141 		goto out;
5142 	}
5143 
5144 	if (!folio_test_uptodate(folio)) {
5145 		ret = btrfs_read_folio(NULL, folio);
5146 		folio_lock(folio);
5147 		if (folio->mapping != mapping) {
5148 			folio_unlock(folio);
5149 			folio_put(folio);
5150 			goto again;
5151 		}
5152 		if (unlikely(!folio_test_uptodate(folio))) {
5153 			ret = -EIO;
5154 			goto out_unlock;
5155 		}
5156 	}
5157 
5158 	/*
5159 	 * We unlock the page after the io is completed and then re-lock it
5160 	 * above.  release_folio() could have come in between that and cleared
5161 	 * folio private, but left the page in the mapping.  Set the page mapped
5162 	 * here to make sure it's properly set for the subpage stuff.
5163 	 */
5164 	ret = set_folio_extent_mapped(folio);
5165 	if (ret < 0)
5166 		goto out_unlock;
5167 
5168 	folio_wait_writeback(folio);
5169 
5170 	btrfs_lock_extent(io_tree, block_start, block_end, &cached_state);
5171 
5172 	ordered = btrfs_lookup_ordered_extent(inode, block_start);
5173 	if (ordered) {
5174 		btrfs_unlock_extent(io_tree, block_start, block_end, &cached_state);
5175 		folio_unlock(folio);
5176 		folio_put(folio);
5177 		btrfs_start_ordered_extent(ordered);
5178 		btrfs_put_ordered_extent(ordered);
5179 		goto again;
5180 	}
5181 
5182 	ret = btrfs_reset_extent_delalloc(inode, block_start, block_end, 0, &cached_state);
5183 	if (ret) {
5184 		btrfs_unlock_extent(io_tree, block_start, block_end, &cached_state);
5185 		goto out_unlock;
5186 	}
5187 
5188 	if (end == (u64)-1) {
5189 		/*
5190 		 * We're truncating beyond EOF, the remaining blocks normally are
5191 		 * already holes thus no need to zero again, but it's possible for
5192 		 * fs block size < page size cases to have memory mapped writes
5193 		 * to pollute ranges beyond EOF.
5194 		 *
5195 		 * In that case although such polluted blocks beyond EOF will
5196 		 * not reach disk, it still affects our page caches.
5197 		 */
5198 		zero_start = max_t(u64, folio_pos(folio), start);
5199 		zero_end = min_t(u64, folio_next_pos(folio) - 1, end);
5200 	} else {
5201 		zero_start = max_t(u64, block_start, start);
5202 		zero_end = min_t(u64, block_end, end);
5203 	}
5204 	folio_zero_range(folio, zero_start - folio_pos(folio),
5205 			 zero_end - zero_start + 1);
5206 
5207 	btrfs_folio_set_dirty(fs_info, folio, block_start,
5208 			      block_end + 1 - block_start);
5209 
5210 	if (only_release_metadata)
5211 		btrfs_set_extent_bit(&inode->io_tree, block_start, block_end,
5212 				     EXTENT_NORESERVE, &cached_state);
5213 
5214 	btrfs_unlock_extent(io_tree, block_start, block_end, &cached_state);
5215 
5216 out_unlock:
5217 	if (ret) {
5218 		if (only_release_metadata)
5219 			btrfs_delalloc_release_metadata(inode, blocksize, true);
5220 		else
5221 			btrfs_delalloc_release_space(inode, data_reserved,
5222 					block_start, blocksize, true);
5223 	}
5224 	btrfs_delalloc_release_extents(inode, blocksize);
5225 	folio_unlock(folio);
5226 	folio_put(folio);
5227 out:
5228 	if (only_release_metadata)
5229 		btrfs_check_nocow_unlock(inode);
5230 	extent_changeset_free(data_reserved);
5231 	return ret;
5232 }
5233 
5234 static int maybe_insert_hole(struct btrfs_inode *inode, u64 offset, u64 len)
5235 {
5236 	struct btrfs_root *root = inode->root;
5237 	struct btrfs_fs_info *fs_info = root->fs_info;
5238 	struct btrfs_trans_handle *trans;
5239 	struct btrfs_drop_extents_args drop_args = { 0 };
5240 	int ret;
5241 
5242 	/*
5243 	 * If NO_HOLES is enabled, we don't need to do anything.
5244 	 * Later, up in the call chain, either btrfs_set_inode_last_sub_trans()
5245 	 * or btrfs_update_inode() will be called, which guarantee that the next
5246 	 * fsync will know this inode was changed and needs to be logged.
5247 	 */
5248 	if (btrfs_fs_incompat(fs_info, NO_HOLES))
5249 		return 0;
5250 
5251 	/*
5252 	 * 1 - for the one we're dropping
5253 	 * 1 - for the one we're adding
5254 	 * 1 - for updating the inode.
5255 	 */
5256 	trans = btrfs_start_transaction(root, 3);
5257 	if (IS_ERR(trans))
5258 		return PTR_ERR(trans);
5259 
5260 	drop_args.start = offset;
5261 	drop_args.end = offset + len;
5262 	drop_args.drop_cache = true;
5263 
5264 	ret = btrfs_drop_extents(trans, root, inode, &drop_args);
5265 	if (unlikely(ret)) {
5266 		btrfs_abort_transaction(trans, ret);
5267 		btrfs_end_transaction(trans);
5268 		return ret;
5269 	}
5270 
5271 	ret = btrfs_insert_hole_extent(trans, root, btrfs_ino(inode), offset, len);
5272 	if (ret) {
5273 		btrfs_abort_transaction(trans, ret);
5274 	} else {
5275 		btrfs_update_inode_bytes(inode, 0, drop_args.bytes_found);
5276 		btrfs_update_inode(trans, inode);
5277 	}
5278 	btrfs_end_transaction(trans);
5279 	return ret;
5280 }
5281 
5282 /*
5283  * This function puts in dummy file extents for the area we're creating a hole
5284  * for.  So if we are truncating this file to a larger size we need to insert
5285  * these file extents so that btrfs_get_extent will return a EXTENT_MAP_HOLE for
5286  * the range between oldsize and size
5287  */
5288 int btrfs_cont_expand(struct btrfs_inode *inode, loff_t oldsize, loff_t size)
5289 {
5290 	struct btrfs_root *root = inode->root;
5291 	struct btrfs_fs_info *fs_info = root->fs_info;
5292 	struct extent_io_tree *io_tree = &inode->io_tree;
5293 	struct extent_map *em = NULL;
5294 	struct extent_state *cached_state = NULL;
5295 	u64 hole_start = ALIGN(oldsize, fs_info->sectorsize);
5296 	u64 block_end = ALIGN(size, fs_info->sectorsize);
5297 	u64 last_byte;
5298 	u64 cur_offset;
5299 	u64 hole_size;
5300 	int ret = 0;
5301 
5302 	/*
5303 	 * If our size started in the middle of a block we need to zero out the
5304 	 * rest of the block before we expand the i_size, otherwise we could
5305 	 * expose stale data.
5306 	 */
5307 	ret = btrfs_truncate_block(inode, oldsize, oldsize, -1);
5308 	if (ret)
5309 		return ret;
5310 
5311 	if (size <= hole_start)
5312 		return 0;
5313 
5314 	btrfs_lock_and_flush_ordered_range(inode, hole_start, block_end - 1,
5315 					   &cached_state);
5316 	cur_offset = hole_start;
5317 	while (1) {
5318 		em = btrfs_get_extent(inode, NULL, cur_offset, block_end - cur_offset);
5319 		if (IS_ERR(em)) {
5320 			ret = PTR_ERR(em);
5321 			em = NULL;
5322 			break;
5323 		}
5324 		last_byte = min(btrfs_extent_map_end(em), block_end);
5325 		last_byte = ALIGN(last_byte, fs_info->sectorsize);
5326 		hole_size = last_byte - cur_offset;
5327 
5328 		if (!(em->flags & EXTENT_FLAG_PREALLOC)) {
5329 			struct extent_map *hole_em;
5330 
5331 			ret = maybe_insert_hole(inode, cur_offset, hole_size);
5332 			if (ret)
5333 				break;
5334 
5335 			ret = btrfs_inode_set_file_extent_range(inode,
5336 							cur_offset, hole_size);
5337 			if (ret)
5338 				break;
5339 
5340 			hole_em = btrfs_alloc_extent_map();
5341 			if (!hole_em) {
5342 				btrfs_drop_extent_map_range(inode, cur_offset,
5343 						    cur_offset + hole_size - 1,
5344 						    false);
5345 				btrfs_set_inode_full_sync(inode);
5346 				goto next;
5347 			}
5348 			hole_em->start = cur_offset;
5349 			hole_em->len = hole_size;
5350 
5351 			hole_em->disk_bytenr = EXTENT_MAP_HOLE;
5352 			hole_em->disk_num_bytes = 0;
5353 			hole_em->ram_bytes = hole_size;
5354 			hole_em->generation = btrfs_get_fs_generation(fs_info);
5355 
5356 			ret = btrfs_replace_extent_map_range(inode, hole_em, true);
5357 			btrfs_free_extent_map(hole_em);
5358 		} else {
5359 			ret = btrfs_inode_set_file_extent_range(inode,
5360 							cur_offset, hole_size);
5361 			if (ret)
5362 				break;
5363 		}
5364 next:
5365 		btrfs_free_extent_map(em);
5366 		em = NULL;
5367 		cur_offset = last_byte;
5368 		if (cur_offset >= block_end)
5369 			break;
5370 	}
5371 	btrfs_free_extent_map(em);
5372 	btrfs_unlock_extent(io_tree, hole_start, block_end - 1, &cached_state);
5373 	return ret;
5374 }
5375 
5376 static int btrfs_setsize(struct inode *inode, struct iattr *attr)
5377 {
5378 	struct btrfs_root *root = BTRFS_I(inode)->root;
5379 	struct btrfs_trans_handle *trans;
5380 	loff_t oldsize = i_size_read(inode);
5381 	loff_t newsize = attr->ia_size;
5382 	int mask = attr->ia_valid;
5383 	int ret;
5384 
5385 	/*
5386 	 * The regular truncate() case without ATTR_CTIME and ATTR_MTIME is a
5387 	 * special case where we need to update the times despite not having
5388 	 * these flags set.  For all other operations the VFS set these flags
5389 	 * explicitly if it wants a timestamp update.
5390 	 */
5391 	if (newsize != oldsize) {
5392 		inode_inc_iversion(inode);
5393 		if (!(mask & (ATTR_CTIME | ATTR_MTIME))) {
5394 			inode_set_mtime_to_ts(inode,
5395 					      inode_set_ctime_current(inode));
5396 		}
5397 	}
5398 
5399 	if (newsize > oldsize) {
5400 		/*
5401 		 * Don't do an expanding truncate while snapshotting is ongoing.
5402 		 * This is to ensure the snapshot captures a fully consistent
5403 		 * state of this file - if the snapshot captures this expanding
5404 		 * truncation, it must capture all writes that happened before
5405 		 * this truncation.
5406 		 */
5407 		btrfs_drew_write_lock(&root->snapshot_lock);
5408 		ret = btrfs_cont_expand(BTRFS_I(inode), oldsize, newsize);
5409 		if (ret) {
5410 			btrfs_drew_write_unlock(&root->snapshot_lock);
5411 			return ret;
5412 		}
5413 
5414 		trans = btrfs_start_transaction(root, 1);
5415 		if (IS_ERR(trans)) {
5416 			btrfs_drew_write_unlock(&root->snapshot_lock);
5417 			return PTR_ERR(trans);
5418 		}
5419 
5420 		i_size_write(inode, newsize);
5421 		btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
5422 		pagecache_isize_extended(inode, oldsize, newsize);
5423 		ret = btrfs_update_inode(trans, BTRFS_I(inode));
5424 		btrfs_drew_write_unlock(&root->snapshot_lock);
5425 		btrfs_end_transaction(trans);
5426 	} else {
5427 		struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
5428 
5429 		if (btrfs_is_zoned(fs_info)) {
5430 			ret = btrfs_wait_ordered_range(BTRFS_I(inode),
5431 					ALIGN(newsize, fs_info->sectorsize),
5432 					(u64)-1);
5433 			if (ret)
5434 				return ret;
5435 		}
5436 
5437 		/*
5438 		 * We're truncating a file that used to have good data down to
5439 		 * zero. Make sure any new writes to the file get on disk
5440 		 * on close.
5441 		 */
5442 		if (newsize == 0 && oldsize != 0)
5443 			set_bit(BTRFS_INODE_FLUSH_ON_CLOSE,
5444 				&BTRFS_I(inode)->runtime_flags);
5445 
5446 		truncate_setsize(inode, newsize);
5447 
5448 		inode_dio_wait(inode);
5449 
5450 		ret = btrfs_truncate(BTRFS_I(inode), newsize == oldsize);
5451 		if (ret && inode->i_nlink) {
5452 			int ret2;
5453 
5454 			/*
5455 			 * Truncate failed, so fix up the in-memory size. We
5456 			 * adjusted disk_i_size down as we removed extents, so
5457 			 * wait for disk_i_size to be stable and then update the
5458 			 * in-memory size to match.
5459 			 */
5460 			ret2 = btrfs_wait_ordered_range(BTRFS_I(inode), 0, (u64)-1);
5461 			if (ret2)
5462 				return ret2;
5463 			i_size_write(inode, BTRFS_I(inode)->disk_i_size);
5464 		}
5465 	}
5466 
5467 	return ret;
5468 }
5469 
5470 static int btrfs_setattr(struct mnt_idmap *idmap, struct dentry *dentry,
5471 			 struct iattr *attr)
5472 {
5473 	struct inode *inode = d_inode(dentry);
5474 	struct btrfs_root *root = BTRFS_I(inode)->root;
5475 	int ret;
5476 
5477 	if (btrfs_root_readonly(root))
5478 		return -EROFS;
5479 
5480 	ret = setattr_prepare(idmap, dentry, attr);
5481 	if (ret)
5482 		return ret;
5483 
5484 	if (S_ISREG(inode->i_mode) && (attr->ia_valid & ATTR_SIZE)) {
5485 		ret = btrfs_setsize(inode, attr);
5486 		if (ret)
5487 			return ret;
5488 	}
5489 
5490 	if (attr->ia_valid) {
5491 		setattr_copy(idmap, inode, attr);
5492 		inode_inc_iversion(inode);
5493 		ret = btrfs_dirty_inode(BTRFS_I(inode));
5494 
5495 		if (!ret && attr->ia_valid & ATTR_MODE)
5496 			ret = posix_acl_chmod(idmap, dentry, inode->i_mode);
5497 	}
5498 
5499 	return ret;
5500 }
5501 
5502 /*
5503  * While truncating the inode pages during eviction, we get the VFS
5504  * calling btrfs_invalidate_folio() against each folio of the inode. This
5505  * is slow because the calls to btrfs_invalidate_folio() result in a
5506  * huge amount of calls to lock_extent() and clear_extent_bit(),
5507  * which keep merging and splitting extent_state structures over and over,
5508  * wasting lots of time.
5509  *
5510  * Therefore if the inode is being evicted, let btrfs_invalidate_folio()
5511  * skip all those expensive operations on a per folio basis and do only
5512  * the ordered io finishing, while we release here the extent_map and
5513  * extent_state structures, without the excessive merging and splitting.
5514  */
5515 static void evict_inode_truncate_pages(struct inode *inode)
5516 {
5517 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
5518 	struct rb_node *node;
5519 
5520 	ASSERT(inode_state_read_once(inode) & I_FREEING);
5521 	truncate_inode_pages_final(&inode->i_data);
5522 
5523 	btrfs_drop_extent_map_range(BTRFS_I(inode), 0, (u64)-1, false);
5524 
5525 	/*
5526 	 * Keep looping until we have no more ranges in the io tree.
5527 	 * We can have ongoing bios started by readahead that have
5528 	 * their endio callback (extent_io.c:end_bio_extent_readpage)
5529 	 * still in progress (unlocked the pages in the bio but did not yet
5530 	 * unlocked the ranges in the io tree). Therefore this means some
5531 	 * ranges can still be locked and eviction started because before
5532 	 * submitting those bios, which are executed by a separate task (work
5533 	 * queue kthread), inode references (inode->i_count) were not taken
5534 	 * (which would be dropped in the end io callback of each bio).
5535 	 * Therefore here we effectively end up waiting for those bios and
5536 	 * anyone else holding locked ranges without having bumped the inode's
5537 	 * reference count - if we don't do it, when they access the inode's
5538 	 * io_tree to unlock a range it may be too late, leading to an
5539 	 * use-after-free issue.
5540 	 */
5541 	spin_lock(&io_tree->lock);
5542 	while (!RB_EMPTY_ROOT(&io_tree->state)) {
5543 		struct extent_state *state;
5544 		struct extent_state *cached_state = NULL;
5545 		u64 start;
5546 		u64 end;
5547 		unsigned state_flags;
5548 
5549 		node = rb_first(&io_tree->state);
5550 		state = rb_entry(node, struct extent_state, rb_node);
5551 		start = state->start;
5552 		end = state->end;
5553 		state_flags = state->state;
5554 		spin_unlock(&io_tree->lock);
5555 
5556 		btrfs_lock_extent(io_tree, start, end, &cached_state);
5557 
5558 		/*
5559 		 * If still has DELALLOC flag, the extent didn't reach disk,
5560 		 * and its reserved space won't be freed by delayed_ref.
5561 		 * So we need to free its reserved space here.
5562 		 * (Refer to comment in btrfs_invalidate_folio, case 2)
5563 		 *
5564 		 * Note, end is the bytenr of last byte, so we need + 1 here.
5565 		 */
5566 		if (state_flags & EXTENT_DELALLOC)
5567 			btrfs_qgroup_free_data(BTRFS_I(inode), NULL, start,
5568 					       end - start + 1, NULL);
5569 
5570 		btrfs_clear_extent_bit(io_tree, start, end,
5571 				       EXTENT_CLEAR_ALL_BITS | EXTENT_DO_ACCOUNTING,
5572 				       &cached_state);
5573 
5574 		cond_resched();
5575 		spin_lock(&io_tree->lock);
5576 	}
5577 	spin_unlock(&io_tree->lock);
5578 }
5579 
5580 static struct btrfs_trans_handle *evict_refill_and_join(struct btrfs_root *root,
5581 							struct btrfs_block_rsv *rsv)
5582 {
5583 	struct btrfs_fs_info *fs_info = root->fs_info;
5584 	struct btrfs_trans_handle *trans;
5585 	u64 delayed_refs_extra = btrfs_calc_delayed_ref_bytes(fs_info, 1);
5586 	int ret;
5587 
5588 	/*
5589 	 * Eviction should be taking place at some place safe because of our
5590 	 * delayed iputs.  However the normal flushing code will run delayed
5591 	 * iputs, so we cannot use FLUSH_ALL otherwise we'll deadlock.
5592 	 *
5593 	 * We reserve the delayed_refs_extra here again because we can't use
5594 	 * btrfs_start_transaction(root, 0) for the same deadlocky reason as
5595 	 * above.  We reserve our extra bit here because we generate a ton of
5596 	 * delayed refs activity by truncating.
5597 	 *
5598 	 * BTRFS_RESERVE_FLUSH_EVICT will steal from the global_rsv if it can,
5599 	 * if we fail to make this reservation we can re-try without the
5600 	 * delayed_refs_extra so we can make some forward progress.
5601 	 */
5602 	ret = btrfs_block_rsv_refill(fs_info, rsv, rsv->size + delayed_refs_extra,
5603 				     BTRFS_RESERVE_FLUSH_EVICT);
5604 	if (ret) {
5605 		ret = btrfs_block_rsv_refill(fs_info, rsv, rsv->size,
5606 					     BTRFS_RESERVE_FLUSH_EVICT);
5607 		if (ret) {
5608 			btrfs_warn(fs_info,
5609 				   "could not allocate space for delete; will truncate on mount");
5610 			return ERR_PTR(-ENOSPC);
5611 		}
5612 		delayed_refs_extra = 0;
5613 	}
5614 
5615 	trans = btrfs_join_transaction(root);
5616 	if (IS_ERR(trans))
5617 		return trans;
5618 
5619 	if (delayed_refs_extra) {
5620 		trans->block_rsv = &fs_info->trans_block_rsv;
5621 		trans->bytes_reserved = delayed_refs_extra;
5622 		btrfs_block_rsv_migrate(rsv, trans->block_rsv,
5623 					delayed_refs_extra, true);
5624 	}
5625 	return trans;
5626 }
5627 
5628 void btrfs_evict_inode(struct inode *inode)
5629 {
5630 	struct btrfs_fs_info *fs_info;
5631 	struct btrfs_trans_handle *trans;
5632 	struct btrfs_root *root = BTRFS_I(inode)->root;
5633 	struct btrfs_block_rsv rsv;
5634 	int ret;
5635 
5636 	trace_btrfs_inode_evict(inode);
5637 
5638 	if (!root)
5639 		goto clear_inode;
5640 
5641 	fs_info = inode_to_fs_info(inode);
5642 	evict_inode_truncate_pages(inode);
5643 
5644 	if (inode->i_nlink &&
5645 	    ((btrfs_root_refs(&root->root_item) != 0 &&
5646 	      btrfs_root_id(root) != BTRFS_ROOT_TREE_OBJECTID) ||
5647 	     btrfs_is_free_space_inode(BTRFS_I(inode))))
5648 		goto out;
5649 
5650 	if (is_bad_inode(inode))
5651 		goto out;
5652 
5653 	if (test_bit(BTRFS_FS_LOG_RECOVERING, &fs_info->flags))
5654 		goto out;
5655 
5656 	if (inode->i_nlink > 0) {
5657 		BUG_ON(btrfs_root_refs(&root->root_item) != 0 &&
5658 		       btrfs_root_id(root) != BTRFS_ROOT_TREE_OBJECTID);
5659 		goto out;
5660 	}
5661 
5662 	/*
5663 	 * This makes sure the inode item in tree is uptodate and the space for
5664 	 * the inode update is released.
5665 	 */
5666 	ret = btrfs_commit_inode_delayed_inode(BTRFS_I(inode));
5667 	if (ret)
5668 		goto out;
5669 
5670 	/*
5671 	 * This drops any pending insert or delete operations we have for this
5672 	 * inode.  We could have a delayed dir index deletion queued up, but
5673 	 * we're removing the inode completely so that'll be taken care of in
5674 	 * the truncate.
5675 	 */
5676 	btrfs_kill_delayed_inode_items(BTRFS_I(inode));
5677 
5678 	btrfs_init_metadata_block_rsv(fs_info, &rsv, BTRFS_BLOCK_RSV_TEMP);
5679 	rsv.size = btrfs_calc_metadata_size(fs_info, 1);
5680 	rsv.failfast = true;
5681 
5682 	btrfs_i_size_write(BTRFS_I(inode), 0);
5683 
5684 	while (1) {
5685 		struct btrfs_truncate_control control = {
5686 			.inode = BTRFS_I(inode),
5687 			.ino = btrfs_ino(BTRFS_I(inode)),
5688 			.new_size = 0,
5689 			.min_type = 0,
5690 		};
5691 
5692 		trans = evict_refill_and_join(root, &rsv);
5693 		if (IS_ERR(trans))
5694 			goto out_release;
5695 
5696 		trans->block_rsv = &rsv;
5697 
5698 		ret = btrfs_truncate_inode_items(trans, root, &control);
5699 		trans->block_rsv = &fs_info->trans_block_rsv;
5700 		btrfs_end_transaction(trans);
5701 		/*
5702 		 * We have not added new delayed items for our inode after we
5703 		 * have flushed its delayed items, so no need to throttle on
5704 		 * delayed items. However we have modified extent buffers.
5705 		 */
5706 		btrfs_btree_balance_dirty_nodelay(fs_info);
5707 		if (ret && ret != -ENOSPC && ret != -EAGAIN)
5708 			goto out_release;
5709 		else if (!ret)
5710 			break;
5711 	}
5712 
5713 	/*
5714 	 * Errors here aren't a big deal, it just means we leave orphan items in
5715 	 * the tree. They will be cleaned up on the next mount. If the inode
5716 	 * number gets reused, cleanup deletes the orphan item without doing
5717 	 * anything, and unlink reuses the existing orphan item.
5718 	 *
5719 	 * If it turns out that we are dropping too many of these, we might want
5720 	 * to add a mechanism for retrying these after a commit.
5721 	 */
5722 	trans = evict_refill_and_join(root, &rsv);
5723 	if (!IS_ERR(trans)) {
5724 		trans->block_rsv = &rsv;
5725 		btrfs_orphan_del(trans, BTRFS_I(inode));
5726 		trans->block_rsv = &fs_info->trans_block_rsv;
5727 		btrfs_end_transaction(trans);
5728 	}
5729 
5730 out_release:
5731 	btrfs_block_rsv_release(fs_info, &rsv, (u64)-1, NULL);
5732 out:
5733 	/*
5734 	 * If we didn't successfully delete, the orphan item will still be in
5735 	 * the tree and we'll retry on the next mount. Again, we might also want
5736 	 * to retry these periodically in the future.
5737 	 */
5738 	btrfs_remove_delayed_node(BTRFS_I(inode));
5739 clear_inode:
5740 	clear_inode(inode);
5741 }
5742 
5743 /*
5744  * Return the key found in the dir entry in the location pointer, fill @type
5745  * with BTRFS_FT_*, and return 0.
5746  *
5747  * If no dir entries were found, returns -ENOENT.
5748  * If found a corrupted location in dir entry, returns -EUCLEAN.
5749  */
5750 static int btrfs_inode_by_name(struct btrfs_inode *dir, struct dentry *dentry,
5751 			       struct btrfs_key *location, u8 *type)
5752 {
5753 	struct btrfs_dir_item *di;
5754 	BTRFS_PATH_AUTO_FREE(path);
5755 	struct btrfs_root *root = dir->root;
5756 	int ret = 0;
5757 	struct fscrypt_name fname;
5758 
5759 	path = btrfs_alloc_path();
5760 	if (!path)
5761 		return -ENOMEM;
5762 
5763 	ret = fscrypt_setup_filename(&dir->vfs_inode, &dentry->d_name, 1, &fname);
5764 	if (ret < 0)
5765 		return ret;
5766 	/*
5767 	 * fscrypt_setup_filename() should never return a positive value, but
5768 	 * gcc on sparc/parisc thinks it can, so assert that doesn't happen.
5769 	 */
5770 	ASSERT(ret == 0);
5771 
5772 	/* This needs to handle no-key deletions later on */
5773 
5774 	di = btrfs_lookup_dir_item(NULL, root, path, btrfs_ino(dir),
5775 				   &fname.disk_name, 0);
5776 	if (IS_ERR_OR_NULL(di)) {
5777 		ret = di ? PTR_ERR(di) : -ENOENT;
5778 		goto out;
5779 	}
5780 
5781 	btrfs_dir_item_key_to_cpu(path->nodes[0], di, location);
5782 	if (unlikely(location->type != BTRFS_INODE_ITEM_KEY &&
5783 		     location->type != BTRFS_ROOT_ITEM_KEY)) {
5784 		ret = -EUCLEAN;
5785 		btrfs_warn(root->fs_info,
5786 "%s gets something invalid in DIR_ITEM (name %s, directory ino %llu, location " BTRFS_KEY_FMT ")",
5787 			   __func__, fname.disk_name.name, btrfs_ino(dir),
5788 			   BTRFS_KEY_FMT_VALUE(location));
5789 	}
5790 	if (!ret)
5791 		*type = btrfs_dir_ftype(path->nodes[0], di);
5792 out:
5793 	fscrypt_free_filename(&fname);
5794 	return ret;
5795 }
5796 
5797 /*
5798  * when we hit a tree root in a directory, the btrfs part of the inode
5799  * needs to be changed to reflect the root directory of the tree root.  This
5800  * is kind of like crossing a mount point.
5801  */
5802 static int fixup_tree_root_location(struct btrfs_fs_info *fs_info,
5803 				    struct btrfs_inode *dir,
5804 				    struct dentry *dentry,
5805 				    struct btrfs_key *location,
5806 				    struct btrfs_root **sub_root)
5807 {
5808 	BTRFS_PATH_AUTO_FREE(path);
5809 	struct btrfs_root *new_root;
5810 	struct btrfs_root_ref *ref;
5811 	struct extent_buffer *leaf;
5812 	struct btrfs_key key;
5813 	int ret;
5814 	int err = 0;
5815 	struct fscrypt_name fname;
5816 
5817 	ret = fscrypt_setup_filename(&dir->vfs_inode, &dentry->d_name, 0, &fname);
5818 	if (ret)
5819 		return ret;
5820 
5821 	path = btrfs_alloc_path();
5822 	if (!path) {
5823 		err = -ENOMEM;
5824 		goto out;
5825 	}
5826 
5827 	err = -ENOENT;
5828 	key.objectid = btrfs_root_id(dir->root);
5829 	key.type = BTRFS_ROOT_REF_KEY;
5830 	key.offset = location->objectid;
5831 
5832 	ret = btrfs_search_slot(NULL, fs_info->tree_root, &key, path, 0, 0);
5833 	if (ret) {
5834 		if (ret < 0)
5835 			err = ret;
5836 		goto out;
5837 	}
5838 
5839 	leaf = path->nodes[0];
5840 	ref = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_root_ref);
5841 	if (btrfs_root_ref_dirid(leaf, ref) != btrfs_ino(dir) ||
5842 	    btrfs_root_ref_name_len(leaf, ref) != fname.disk_name.len)
5843 		goto out;
5844 
5845 	ret = memcmp_extent_buffer(leaf, fname.disk_name.name,
5846 				   (unsigned long)(ref + 1), fname.disk_name.len);
5847 	if (ret)
5848 		goto out;
5849 
5850 	btrfs_release_path(path);
5851 
5852 	new_root = btrfs_get_fs_root(fs_info, location->objectid, true);
5853 	if (IS_ERR(new_root)) {
5854 		err = PTR_ERR(new_root);
5855 		goto out;
5856 	}
5857 
5858 	*sub_root = new_root;
5859 	location->objectid = btrfs_root_dirid(&new_root->root_item);
5860 	location->type = BTRFS_INODE_ITEM_KEY;
5861 	location->offset = 0;
5862 	err = 0;
5863 out:
5864 	fscrypt_free_filename(&fname);
5865 	return err;
5866 }
5867 
5868 
5869 
5870 static void btrfs_del_inode_from_root(struct btrfs_inode *inode)
5871 {
5872 	struct btrfs_root *root = inode->root;
5873 	struct btrfs_inode *entry;
5874 	bool empty = false;
5875 
5876 	xa_lock(&root->inodes);
5877 	/*
5878 	 * This btrfs_inode is being freed and has already been unhashed at this
5879 	 * point. It's possible that another btrfs_inode has already been
5880 	 * allocated for the same inode and inserted itself into the root, so
5881 	 * don't delete it in that case.
5882 	 *
5883 	 * Note that this shouldn't need to allocate memory, so the gfp flags
5884 	 * don't really matter.
5885 	 */
5886 	entry = __xa_cmpxchg(&root->inodes, btrfs_ino(inode), inode, NULL,
5887 			     GFP_ATOMIC);
5888 	if (entry == inode)
5889 		empty = xa_empty(&root->inodes);
5890 	xa_unlock(&root->inodes);
5891 
5892 	if (empty && btrfs_root_refs(&root->root_item) == 0) {
5893 		xa_lock(&root->inodes);
5894 		empty = xa_empty(&root->inodes);
5895 		xa_unlock(&root->inodes);
5896 		if (empty)
5897 			btrfs_add_dead_root(root);
5898 	}
5899 }
5900 
5901 
5902 static int btrfs_init_locked_inode(struct inode *inode, void *p)
5903 {
5904 	struct btrfs_iget_args *args = p;
5905 
5906 	btrfs_set_inode_number(BTRFS_I(inode), args->ino);
5907 	BTRFS_I(inode)->root = btrfs_grab_root(args->root);
5908 
5909 	if (args->root && args->root == args->root->fs_info->tree_root &&
5910 	    args->ino != BTRFS_BTREE_INODE_OBJECTID)
5911 		set_bit(BTRFS_INODE_FREE_SPACE_INODE,
5912 			&BTRFS_I(inode)->runtime_flags);
5913 	return 0;
5914 }
5915 
5916 static int btrfs_find_actor(struct inode *inode, void *opaque)
5917 {
5918 	struct btrfs_iget_args *args = opaque;
5919 
5920 	return args->ino == btrfs_ino(BTRFS_I(inode)) &&
5921 		args->root == BTRFS_I(inode)->root;
5922 }
5923 
5924 static struct btrfs_inode *btrfs_iget_locked(u64 ino, struct btrfs_root *root)
5925 {
5926 	struct inode *inode;
5927 	struct btrfs_iget_args args;
5928 	unsigned long hashval = btrfs_inode_hash(ino, root);
5929 
5930 	args.ino = ino;
5931 	args.root = root;
5932 
5933 	inode = iget5_locked_rcu(root->fs_info->sb, hashval, btrfs_find_actor,
5934 			     btrfs_init_locked_inode,
5935 			     (void *)&args);
5936 	if (!inode)
5937 		return NULL;
5938 	return BTRFS_I(inode);
5939 }
5940 
5941 /*
5942  * Get an inode object given its inode number and corresponding root.  Path is
5943  * preallocated to prevent recursing back to iget through allocator.
5944  */
5945 struct btrfs_inode *btrfs_iget_path(u64 ino, struct btrfs_root *root,
5946 				    struct btrfs_path *path)
5947 {
5948 	struct btrfs_inode *inode;
5949 	int ret;
5950 
5951 	inode = btrfs_iget_locked(ino, root);
5952 	if (!inode)
5953 		return ERR_PTR(-ENOMEM);
5954 
5955 	if (!(inode_state_read_once(&inode->vfs_inode) & I_NEW))
5956 		return inode;
5957 
5958 	ret = btrfs_read_locked_inode(inode, path);
5959 	if (ret)
5960 		return ERR_PTR(ret);
5961 
5962 	unlock_new_inode(&inode->vfs_inode);
5963 	return inode;
5964 }
5965 
5966 /*
5967  * Get an inode object given its inode number and corresponding root.
5968  */
5969 struct btrfs_inode *btrfs_iget(u64 ino, struct btrfs_root *root)
5970 {
5971 	struct btrfs_inode *inode;
5972 	struct btrfs_path *path;
5973 	int ret;
5974 
5975 	inode = btrfs_iget_locked(ino, root);
5976 	if (!inode)
5977 		return ERR_PTR(-ENOMEM);
5978 
5979 	if (!(inode_state_read_once(&inode->vfs_inode) & I_NEW))
5980 		return inode;
5981 
5982 	path = btrfs_alloc_path();
5983 	if (!path) {
5984 		iget_failed(&inode->vfs_inode);
5985 		return ERR_PTR(-ENOMEM);
5986 	}
5987 
5988 	ret = btrfs_read_locked_inode(inode, path);
5989 	btrfs_free_path(path);
5990 	if (ret)
5991 		return ERR_PTR(ret);
5992 
5993 	if (S_ISDIR(inode->vfs_inode.i_mode))
5994 		inode->vfs_inode.i_opflags |= IOP_FASTPERM_MAY_EXEC;
5995 	unlock_new_inode(&inode->vfs_inode);
5996 	return inode;
5997 }
5998 
5999 static struct btrfs_inode *new_simple_dir(struct inode *dir,
6000 					  struct btrfs_key *key,
6001 					  struct btrfs_root *root)
6002 {
6003 	struct timespec64 ts;
6004 	struct inode *vfs_inode;
6005 	struct btrfs_inode *inode;
6006 
6007 	vfs_inode = new_inode(dir->i_sb);
6008 	if (!vfs_inode)
6009 		return ERR_PTR(-ENOMEM);
6010 
6011 	inode = BTRFS_I(vfs_inode);
6012 	inode->root = btrfs_grab_root(root);
6013 	inode->ref_root_id = key->objectid;
6014 	set_bit(BTRFS_INODE_ROOT_STUB, &inode->runtime_flags);
6015 	set_bit(BTRFS_INODE_DUMMY, &inode->runtime_flags);
6016 
6017 	btrfs_set_inode_number(inode, BTRFS_EMPTY_SUBVOL_DIR_OBJECTID);
6018 	/*
6019 	 * We only need lookup, the rest is read-only and there's no inode
6020 	 * associated with the dentry
6021 	 */
6022 	vfs_inode->i_op = &simple_dir_inode_operations;
6023 	vfs_inode->i_opflags &= ~IOP_XATTR;
6024 	vfs_inode->i_fop = &simple_dir_operations;
6025 	vfs_inode->i_mode = S_IFDIR | S_IRUGO | S_IWUSR | S_IXUGO;
6026 
6027 	ts = inode_set_ctime_current(vfs_inode);
6028 	inode_set_mtime_to_ts(vfs_inode, ts);
6029 	inode_set_atime_to_ts(vfs_inode, inode_get_atime(dir));
6030 	inode->i_otime_sec = ts.tv_sec;
6031 	inode->i_otime_nsec = ts.tv_nsec;
6032 
6033 	vfs_inode->i_uid = dir->i_uid;
6034 	vfs_inode->i_gid = dir->i_gid;
6035 
6036 	return inode;
6037 }
6038 
6039 static_assert(BTRFS_FT_UNKNOWN == FT_UNKNOWN);
6040 static_assert(BTRFS_FT_REG_FILE == FT_REG_FILE);
6041 static_assert(BTRFS_FT_DIR == FT_DIR);
6042 static_assert(BTRFS_FT_CHRDEV == FT_CHRDEV);
6043 static_assert(BTRFS_FT_BLKDEV == FT_BLKDEV);
6044 static_assert(BTRFS_FT_FIFO == FT_FIFO);
6045 static_assert(BTRFS_FT_SOCK == FT_SOCK);
6046 static_assert(BTRFS_FT_SYMLINK == FT_SYMLINK);
6047 
6048 static inline u8 btrfs_inode_type(const struct btrfs_inode *inode)
6049 {
6050 	return fs_umode_to_ftype(inode->vfs_inode.i_mode);
6051 }
6052 
6053 struct inode *btrfs_lookup_dentry(struct inode *dir, struct dentry *dentry)
6054 {
6055 	struct btrfs_fs_info *fs_info = inode_to_fs_info(dir);
6056 	struct btrfs_inode *inode;
6057 	struct btrfs_root *root = BTRFS_I(dir)->root;
6058 	struct btrfs_root *sub_root = root;
6059 	struct btrfs_key location = { 0 };
6060 	u8 di_type = 0;
6061 	int ret = 0;
6062 
6063 	if (dentry->d_name.len > BTRFS_NAME_LEN)
6064 		return ERR_PTR(-ENAMETOOLONG);
6065 
6066 	ret = btrfs_inode_by_name(BTRFS_I(dir), dentry, &location, &di_type);
6067 	if (ret < 0)
6068 		return ERR_PTR(ret);
6069 
6070 	if (location.type == BTRFS_INODE_ITEM_KEY) {
6071 		inode = btrfs_iget(location.objectid, root);
6072 		if (IS_ERR(inode))
6073 			return ERR_CAST(inode);
6074 
6075 		/* Do extra check against inode mode with di_type */
6076 		if (unlikely(btrfs_inode_type(inode) != di_type)) {
6077 			btrfs_crit(fs_info,
6078 "inode mode mismatch with dir: inode mode=0%o btrfs type=%u dir type=%u",
6079 				  inode->vfs_inode.i_mode, btrfs_inode_type(inode),
6080 				  di_type);
6081 			iput(&inode->vfs_inode);
6082 			return ERR_PTR(-EUCLEAN);
6083 		}
6084 		return &inode->vfs_inode;
6085 	}
6086 
6087 	ret = fixup_tree_root_location(fs_info, BTRFS_I(dir), dentry,
6088 				       &location, &sub_root);
6089 	if (ret < 0) {
6090 		if (ret != -ENOENT)
6091 			inode = ERR_PTR(ret);
6092 		else
6093 			inode = new_simple_dir(dir, &location, root);
6094 	} else {
6095 		inode = btrfs_iget(location.objectid, sub_root);
6096 		btrfs_put_root(sub_root);
6097 
6098 		if (IS_ERR(inode))
6099 			return ERR_CAST(inode);
6100 
6101 		down_read(&fs_info->cleanup_work_sem);
6102 		if (!sb_rdonly(inode->vfs_inode.i_sb))
6103 			ret = btrfs_orphan_cleanup(sub_root);
6104 		up_read(&fs_info->cleanup_work_sem);
6105 		if (ret) {
6106 			iput(&inode->vfs_inode);
6107 			inode = ERR_PTR(ret);
6108 		}
6109 	}
6110 
6111 	if (IS_ERR(inode))
6112 		return ERR_CAST(inode);
6113 
6114 	return &inode->vfs_inode;
6115 }
6116 
6117 static int btrfs_dentry_delete(const struct dentry *dentry)
6118 {
6119 	struct btrfs_root *root;
6120 	struct inode *inode = d_inode(dentry);
6121 
6122 	if (!inode && !IS_ROOT(dentry))
6123 		inode = d_inode(dentry->d_parent);
6124 
6125 	if (inode) {
6126 		root = BTRFS_I(inode)->root;
6127 		if (btrfs_root_refs(&root->root_item) == 0)
6128 			return 1;
6129 
6130 		if (btrfs_ino(BTRFS_I(inode)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
6131 			return 1;
6132 	}
6133 	return 0;
6134 }
6135 
6136 static struct dentry *btrfs_lookup(struct inode *dir, struct dentry *dentry,
6137 				   unsigned int flags)
6138 {
6139 	struct inode *inode = btrfs_lookup_dentry(dir, dentry);
6140 
6141 	if (inode == ERR_PTR(-ENOENT))
6142 		inode = NULL;
6143 	return d_splice_alias(inode, dentry);
6144 }
6145 
6146 /*
6147  * Find the highest existing sequence number in a directory and then set the
6148  * in-memory index_cnt variable to the first free sequence number.
6149  */
6150 static int btrfs_set_inode_index_count(struct btrfs_inode *inode)
6151 {
6152 	struct btrfs_root *root = inode->root;
6153 	struct btrfs_key key, found_key;
6154 	BTRFS_PATH_AUTO_FREE(path);
6155 	struct extent_buffer *leaf;
6156 	int ret;
6157 
6158 	key.objectid = btrfs_ino(inode);
6159 	key.type = BTRFS_DIR_INDEX_KEY;
6160 	key.offset = (u64)-1;
6161 
6162 	path = btrfs_alloc_path();
6163 	if (!path)
6164 		return -ENOMEM;
6165 
6166 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
6167 	if (ret < 0)
6168 		return ret;
6169 
6170 	if (unlikely(ret == 0)) {
6171 		/*
6172 		 * Key with offset -1 found, there would have to exist a dir
6173 		 * index item with such offset, but this is out of the valid
6174 		 * range.
6175 		 */
6176 		btrfs_err(root->fs_info,
6177 			  "unexpected exact match for DIR_INDEX key, inode %llu",
6178 			  btrfs_ino(inode));
6179 		return -EUCLEAN;
6180 	}
6181 
6182 	if (path->slots[0] == 0) {
6183 		inode->index_cnt = BTRFS_DIR_START_INDEX;
6184 		return 0;
6185 	}
6186 
6187 	path->slots[0]--;
6188 
6189 	leaf = path->nodes[0];
6190 	btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
6191 
6192 	if (found_key.objectid != btrfs_ino(inode) ||
6193 	    found_key.type != BTRFS_DIR_INDEX_KEY) {
6194 		inode->index_cnt = BTRFS_DIR_START_INDEX;
6195 		return 0;
6196 	}
6197 
6198 	inode->index_cnt = found_key.offset + 1;
6199 
6200 	return 0;
6201 }
6202 
6203 static int btrfs_get_dir_last_index(struct btrfs_inode *dir, u64 *index)
6204 {
6205 	int ret = 0;
6206 
6207 	btrfs_inode_lock(dir, 0);
6208 	if (dir->index_cnt == (u64)-1) {
6209 		ret = btrfs_inode_delayed_dir_index_count(dir);
6210 		if (ret) {
6211 			ret = btrfs_set_inode_index_count(dir);
6212 			if (ret)
6213 				goto out;
6214 		}
6215 	}
6216 
6217 	/* index_cnt is the index number of next new entry, so decrement it. */
6218 	*index = dir->index_cnt - 1;
6219 out:
6220 	btrfs_inode_unlock(dir, 0);
6221 
6222 	return ret;
6223 }
6224 
6225 /*
6226  * All this infrastructure exists because dir_emit can fault, and we are holding
6227  * the tree lock when doing readdir.  For now just allocate a buffer and copy
6228  * our information into that, and then dir_emit from the buffer.  This is
6229  * similar to what NFS does, only we don't keep the buffer around in pagecache
6230  * because I'm afraid I'll mess that up.  Long term we need to make filldir do
6231  * copy_to_user_inatomic so we don't have to worry about page faulting under the
6232  * tree lock.
6233  */
6234 static int btrfs_opendir(struct inode *inode, struct file *file)
6235 {
6236 	struct btrfs_file_private *private;
6237 	u64 last_index;
6238 	int ret;
6239 
6240 	ret = btrfs_get_dir_last_index(BTRFS_I(inode), &last_index);
6241 	if (ret)
6242 		return ret;
6243 
6244 	private = kzalloc_obj(struct btrfs_file_private);
6245 	if (!private)
6246 		return -ENOMEM;
6247 	private->last_index = last_index;
6248 	private->filldir_buf = kzalloc(PAGE_SIZE, GFP_KERNEL);
6249 	if (!private->filldir_buf) {
6250 		kfree(private);
6251 		return -ENOMEM;
6252 	}
6253 	file->private_data = private;
6254 	return 0;
6255 }
6256 
6257 static loff_t btrfs_dir_llseek(struct file *file, loff_t offset, int whence)
6258 {
6259 	struct btrfs_file_private *private = file->private_data;
6260 	int ret;
6261 
6262 	ret = btrfs_get_dir_last_index(BTRFS_I(file_inode(file)),
6263 				       &private->last_index);
6264 	if (ret)
6265 		return ret;
6266 
6267 	return generic_file_llseek(file, offset, whence);
6268 }
6269 
6270 struct dir_entry {
6271 	u64 ino;
6272 	u64 offset;
6273 	unsigned type;
6274 	int name_len;
6275 };
6276 
6277 static int btrfs_filldir(void *addr, int entries, struct dir_context *ctx)
6278 {
6279 	while (entries--) {
6280 		struct dir_entry *entry = addr;
6281 		char *name = (char *)(entry + 1);
6282 
6283 		ctx->pos = get_unaligned(&entry->offset);
6284 		if (!dir_emit(ctx, name, get_unaligned(&entry->name_len),
6285 					 get_unaligned(&entry->ino),
6286 					 get_unaligned(&entry->type)))
6287 			return 1;
6288 		addr += sizeof(struct dir_entry) +
6289 			get_unaligned(&entry->name_len);
6290 		ctx->pos++;
6291 	}
6292 	return 0;
6293 }
6294 
6295 static int btrfs_real_readdir(struct file *file, struct dir_context *ctx)
6296 {
6297 	struct inode *inode = file_inode(file);
6298 	struct btrfs_root *root = BTRFS_I(inode)->root;
6299 	struct btrfs_file_private *private = file->private_data;
6300 	struct btrfs_dir_item *di;
6301 	struct btrfs_key key;
6302 	struct btrfs_key found_key;
6303 	BTRFS_PATH_AUTO_FREE(path);
6304 	void *addr;
6305 	LIST_HEAD(ins_list);
6306 	LIST_HEAD(del_list);
6307 	int ret;
6308 	char *name_ptr;
6309 	int name_len;
6310 	int entries = 0;
6311 	int total_len = 0;
6312 	bool put = false;
6313 	struct btrfs_key location;
6314 
6315 	if (!dir_emit_dots(file, ctx))
6316 		return 0;
6317 
6318 	path = btrfs_alloc_path();
6319 	if (!path)
6320 		return -ENOMEM;
6321 
6322 	addr = private->filldir_buf;
6323 	path->reada = READA_FORWARD;
6324 
6325 	put = btrfs_readdir_get_delayed_items(BTRFS_I(inode), private->last_index,
6326 					      &ins_list, &del_list);
6327 
6328 again:
6329 	key.type = BTRFS_DIR_INDEX_KEY;
6330 	key.offset = ctx->pos;
6331 	key.objectid = btrfs_ino(BTRFS_I(inode));
6332 
6333 	btrfs_for_each_slot(root, &key, &found_key, path, ret) {
6334 		struct dir_entry *entry;
6335 		struct extent_buffer *leaf = path->nodes[0];
6336 		u8 ftype;
6337 
6338 		if (found_key.objectid != key.objectid)
6339 			break;
6340 		if (found_key.type != BTRFS_DIR_INDEX_KEY)
6341 			break;
6342 		if (found_key.offset < ctx->pos)
6343 			continue;
6344 		if (found_key.offset > private->last_index)
6345 			break;
6346 		if (btrfs_should_delete_dir_index(&del_list, found_key.offset))
6347 			continue;
6348 		di = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_dir_item);
6349 		name_len = btrfs_dir_name_len(leaf, di);
6350 		if ((total_len + sizeof(struct dir_entry) + name_len) >=
6351 		    PAGE_SIZE) {
6352 			btrfs_release_path(path);
6353 			ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6354 			if (ret)
6355 				goto nopos;
6356 			addr = private->filldir_buf;
6357 			entries = 0;
6358 			total_len = 0;
6359 			goto again;
6360 		}
6361 
6362 		ftype = btrfs_dir_flags_to_ftype(btrfs_dir_flags(leaf, di));
6363 		entry = addr;
6364 		name_ptr = (char *)(entry + 1);
6365 		read_extent_buffer(leaf, name_ptr,
6366 				   (unsigned long)(di + 1), name_len);
6367 		put_unaligned(name_len, &entry->name_len);
6368 		put_unaligned(fs_ftype_to_dtype(ftype), &entry->type);
6369 		btrfs_dir_item_key_to_cpu(leaf, di, &location);
6370 		put_unaligned(location.objectid, &entry->ino);
6371 		put_unaligned(found_key.offset, &entry->offset);
6372 		entries++;
6373 		addr += sizeof(struct dir_entry) + name_len;
6374 		total_len += sizeof(struct dir_entry) + name_len;
6375 	}
6376 	/* Catch error encountered during iteration */
6377 	if (ret < 0)
6378 		goto err;
6379 
6380 	btrfs_release_path(path);
6381 
6382 	ret = btrfs_filldir(private->filldir_buf, entries, ctx);
6383 	if (ret)
6384 		goto nopos;
6385 
6386 	if (btrfs_readdir_delayed_dir_index(ctx, &ins_list))
6387 		goto nopos;
6388 
6389 	/*
6390 	 * Stop new entries from being returned after we return the last
6391 	 * entry.
6392 	 *
6393 	 * New directory entries are assigned a strictly increasing
6394 	 * offset.  This means that new entries created during readdir
6395 	 * are *guaranteed* to be seen in the future by that readdir.
6396 	 * This has broken buggy programs which operate on names as
6397 	 * they're returned by readdir.  Until we reuse freed offsets
6398 	 * we have this hack to stop new entries from being returned
6399 	 * under the assumption that they'll never reach this huge
6400 	 * offset.
6401 	 *
6402 	 * This is being careful not to overflow 32bit loff_t unless the
6403 	 * last entry requires it because doing so has broken 32bit apps
6404 	 * in the past.
6405 	 */
6406 	if (ctx->pos >= INT_MAX)
6407 		ctx->pos = LLONG_MAX;
6408 	else
6409 		ctx->pos = INT_MAX;
6410 nopos:
6411 	ret = 0;
6412 err:
6413 	if (put)
6414 		btrfs_readdir_put_delayed_items(BTRFS_I(inode), &ins_list, &del_list);
6415 	return ret;
6416 }
6417 
6418 /*
6419  * This is somewhat expensive, updating the tree every time the
6420  * inode changes.  But, it is most likely to find the inode in cache.
6421  * FIXME, needs more benchmarking...there are no reasons other than performance
6422  * to keep or drop this code.
6423  */
6424 static int btrfs_dirty_inode(struct btrfs_inode *inode)
6425 {
6426 	struct btrfs_root *root = inode->root;
6427 	struct btrfs_fs_info *fs_info = root->fs_info;
6428 	struct btrfs_trans_handle *trans;
6429 	int ret;
6430 
6431 	if (test_bit(BTRFS_INODE_DUMMY, &inode->runtime_flags))
6432 		return 0;
6433 
6434 	trans = btrfs_join_transaction(root);
6435 	if (IS_ERR(trans))
6436 		return PTR_ERR(trans);
6437 
6438 	ret = btrfs_update_inode(trans, inode);
6439 	if (ret == -ENOSPC || ret == -EDQUOT) {
6440 		/* whoops, lets try again with the full transaction */
6441 		btrfs_end_transaction(trans);
6442 		trans = btrfs_start_transaction(root, 1);
6443 		if (IS_ERR(trans))
6444 			return PTR_ERR(trans);
6445 
6446 		ret = btrfs_update_inode(trans, inode);
6447 	}
6448 	btrfs_end_transaction(trans);
6449 	if (inode->delayed_node)
6450 		btrfs_balance_delayed_items(fs_info);
6451 
6452 	return ret;
6453 }
6454 
6455 /*
6456  * We need our own ->update_time so that we can return error on ENOSPC for
6457  * updating the inode in the case of file write and mmap writes.
6458  */
6459 static int btrfs_update_time(struct inode *inode, enum fs_update_time type,
6460 		unsigned int flags)
6461 {
6462 	struct btrfs_root *root = BTRFS_I(inode)->root;
6463 	int dirty;
6464 
6465 	if (btrfs_root_readonly(root))
6466 		return -EROFS;
6467 	if (flags & IOCB_NOWAIT)
6468 		return -EAGAIN;
6469 
6470 	dirty = inode_update_time(inode, type, flags);
6471 	if (dirty <= 0)
6472 		return dirty;
6473 	return btrfs_dirty_inode(BTRFS_I(inode));
6474 }
6475 
6476 /*
6477  * helper to find a free sequence number in a given directory.  This current
6478  * code is very simple, later versions will do smarter things in the btree
6479  */
6480 int btrfs_set_inode_index(struct btrfs_inode *dir, u64 *index)
6481 {
6482 	int ret = 0;
6483 
6484 	if (dir->index_cnt == (u64)-1) {
6485 		ret = btrfs_inode_delayed_dir_index_count(dir);
6486 		if (ret) {
6487 			ret = btrfs_set_inode_index_count(dir);
6488 			if (ret)
6489 				return ret;
6490 		}
6491 	}
6492 
6493 	*index = dir->index_cnt;
6494 	dir->index_cnt++;
6495 
6496 	return ret;
6497 }
6498 
6499 static int btrfs_insert_inode_locked(struct inode *inode)
6500 {
6501 	struct btrfs_iget_args args;
6502 
6503 	args.ino = btrfs_ino(BTRFS_I(inode));
6504 	args.root = BTRFS_I(inode)->root;
6505 
6506 	return insert_inode_locked4(inode,
6507 		   btrfs_inode_hash(inode->i_ino, BTRFS_I(inode)->root),
6508 		   btrfs_find_actor, &args);
6509 }
6510 
6511 int btrfs_new_inode_prepare(struct btrfs_new_inode_args *args,
6512 			    unsigned int *trans_num_items)
6513 {
6514 	struct inode *dir = args->dir;
6515 	struct inode *inode = args->inode;
6516 	int ret;
6517 
6518 	if (!args->orphan) {
6519 		ret = fscrypt_setup_filename(dir, &args->dentry->d_name, 0,
6520 					     &args->fname);
6521 		if (ret)
6522 			return ret;
6523 	}
6524 
6525 	ret = posix_acl_create(dir, &inode->i_mode, &args->default_acl, &args->acl);
6526 	if (ret) {
6527 		fscrypt_free_filename(&args->fname);
6528 		return ret;
6529 	}
6530 
6531 	/* 1 to add inode item */
6532 	*trans_num_items = 1;
6533 	/* 1 to add compression property */
6534 	if (BTRFS_I(dir)->prop_compress)
6535 		(*trans_num_items)++;
6536 	/* 1 to add default ACL xattr */
6537 	if (args->default_acl)
6538 		(*trans_num_items)++;
6539 	/* 1 to add access ACL xattr */
6540 	if (args->acl)
6541 		(*trans_num_items)++;
6542 #ifdef CONFIG_SECURITY
6543 	/* 1 to add LSM xattr */
6544 	if (dir->i_security)
6545 		(*trans_num_items)++;
6546 #endif
6547 	if (args->orphan) {
6548 		/* 1 to add orphan item */
6549 		(*trans_num_items)++;
6550 	} else {
6551 		/*
6552 		 * 1 to add dir item
6553 		 * 1 to add dir index
6554 		 * 1 to update parent inode item
6555 		 *
6556 		 * No need for 1 unit for the inode ref item because it is
6557 		 * inserted in a batch together with the inode item at
6558 		 * btrfs_create_new_inode().
6559 		 */
6560 		*trans_num_items += 3;
6561 	}
6562 	return 0;
6563 }
6564 
6565 void btrfs_new_inode_args_destroy(struct btrfs_new_inode_args *args)
6566 {
6567 	posix_acl_release(args->acl);
6568 	posix_acl_release(args->default_acl);
6569 	fscrypt_free_filename(&args->fname);
6570 }
6571 
6572 /*
6573  * Inherit flags from the parent inode.
6574  *
6575  * Currently only the compression flags and the cow flags are inherited.
6576  */
6577 static void btrfs_inherit_iflags(struct btrfs_inode *inode, struct btrfs_inode *dir)
6578 {
6579 	unsigned int flags;
6580 
6581 	flags = dir->flags;
6582 
6583 	if (flags & BTRFS_INODE_NOCOMPRESS) {
6584 		inode->flags &= ~BTRFS_INODE_COMPRESS;
6585 		inode->flags |= BTRFS_INODE_NOCOMPRESS;
6586 	} else if (flags & BTRFS_INODE_COMPRESS) {
6587 		inode->flags &= ~BTRFS_INODE_NOCOMPRESS;
6588 		inode->flags |= BTRFS_INODE_COMPRESS;
6589 	}
6590 
6591 	if (flags & BTRFS_INODE_NODATACOW) {
6592 		inode->flags |= BTRFS_INODE_NODATACOW;
6593 		if (S_ISREG(inode->vfs_inode.i_mode))
6594 			inode->flags |= BTRFS_INODE_NODATASUM;
6595 	}
6596 
6597 	btrfs_sync_inode_flags_to_i_flags(inode);
6598 }
6599 
6600 int btrfs_create_new_inode(struct btrfs_trans_handle *trans,
6601 			   struct btrfs_new_inode_args *args)
6602 {
6603 	struct timespec64 ts;
6604 	struct inode *dir = args->dir;
6605 	struct inode *inode = args->inode;
6606 	const struct fscrypt_str *name = args->orphan ? NULL : &args->fname.disk_name;
6607 	struct btrfs_fs_info *fs_info = inode_to_fs_info(dir);
6608 	struct btrfs_root *root;
6609 	struct btrfs_inode_item *inode_item;
6610 	struct btrfs_path *path;
6611 	u64 objectid;
6612 	struct btrfs_inode_ref *ref;
6613 	struct btrfs_key key[2];
6614 	u32 sizes[2];
6615 	struct btrfs_item_batch batch;
6616 	unsigned long ptr;
6617 	int ret;
6618 	bool xa_reserved = false;
6619 
6620 	if (!args->orphan && !args->subvol) {
6621 		/*
6622 		 * Before anything else, check if we can add the name to the
6623 		 * parent directory. We want to avoid a dir item overflow in
6624 		 * case we have an existing dir item due to existing name
6625 		 * hash collisions. We do this check here before we call
6626 		 * btrfs_add_link() down below so that we can avoid a
6627 		 * transaction abort (which could be exploited by malicious
6628 		 * users).
6629 		 *
6630 		 * For subvolumes we already do this in btrfs_mksubvol().
6631 		 */
6632 		ret = btrfs_check_dir_item_collision(BTRFS_I(dir)->root,
6633 						     btrfs_ino(BTRFS_I(dir)),
6634 						     name);
6635 		if (ret < 0)
6636 			return ret;
6637 	}
6638 
6639 	path = btrfs_alloc_path();
6640 	if (!path)
6641 		return -ENOMEM;
6642 
6643 	if (!args->subvol)
6644 		BTRFS_I(inode)->root = btrfs_grab_root(BTRFS_I(dir)->root);
6645 	root = BTRFS_I(inode)->root;
6646 
6647 	ret = btrfs_init_file_extent_tree(BTRFS_I(inode));
6648 	if (ret)
6649 		goto out;
6650 
6651 	ret = btrfs_get_free_objectid(root, &objectid);
6652 	if (ret)
6653 		goto out;
6654 	btrfs_set_inode_number(BTRFS_I(inode), objectid);
6655 
6656 	ret = xa_reserve(&root->inodes, objectid, GFP_NOFS);
6657 	if (ret)
6658 		goto out;
6659 	xa_reserved = true;
6660 
6661 	if (args->orphan) {
6662 		/*
6663 		 * O_TMPFILE, set link count to 0, so that after this point, we
6664 		 * fill in an inode item with the correct link count.
6665 		 */
6666 		set_nlink(inode, 0);
6667 	} else {
6668 		trace_btrfs_inode_request(dir);
6669 
6670 		ret = btrfs_set_inode_index(BTRFS_I(dir), &BTRFS_I(inode)->dir_index);
6671 		if (ret)
6672 			goto out;
6673 	}
6674 
6675 	if (S_ISDIR(inode->i_mode))
6676 		BTRFS_I(inode)->index_cnt = BTRFS_DIR_START_INDEX;
6677 
6678 	BTRFS_I(inode)->generation = trans->transid;
6679 	inode->i_generation = BTRFS_I(inode)->generation;
6680 
6681 	/*
6682 	 * We don't have any capability xattrs set here yet, shortcut any
6683 	 * queries for the xattrs here.  If we add them later via the inode
6684 	 * security init path or any other path this flag will be cleared.
6685 	 */
6686 	set_bit(BTRFS_INODE_NO_CAP_XATTR, &BTRFS_I(inode)->runtime_flags);
6687 
6688 	/*
6689 	 * Subvolumes don't inherit flags from their parent directory.
6690 	 * Originally this was probably by accident, but we probably can't
6691 	 * change it now without compatibility issues.
6692 	 */
6693 	if (!args->subvol)
6694 		btrfs_inherit_iflags(BTRFS_I(inode), BTRFS_I(dir));
6695 
6696 	btrfs_set_inode_mapping_order(BTRFS_I(inode));
6697 	if (S_ISREG(inode->i_mode)) {
6698 		if (btrfs_test_opt(fs_info, NODATASUM))
6699 			BTRFS_I(inode)->flags |= BTRFS_INODE_NODATASUM;
6700 		if (btrfs_test_opt(fs_info, NODATACOW))
6701 			BTRFS_I(inode)->flags |= BTRFS_INODE_NODATACOW |
6702 				BTRFS_INODE_NODATASUM;
6703 		btrfs_update_inode_mapping_flags(BTRFS_I(inode));
6704 	}
6705 
6706 	ret = btrfs_insert_inode_locked(inode);
6707 	if (ret < 0) {
6708 		if (!args->orphan)
6709 			BTRFS_I(dir)->index_cnt--;
6710 		goto out;
6711 	}
6712 
6713 	/*
6714 	 * We could have gotten an inode number from somebody who was fsynced
6715 	 * and then removed in this same transaction, so let's just set full
6716 	 * sync since it will be a full sync anyway and this will blow away the
6717 	 * old info in the log.
6718 	 */
6719 	btrfs_set_inode_full_sync(BTRFS_I(inode));
6720 
6721 	key[0].objectid = objectid;
6722 	key[0].type = BTRFS_INODE_ITEM_KEY;
6723 	key[0].offset = 0;
6724 
6725 	sizes[0] = sizeof(struct btrfs_inode_item);
6726 
6727 	if (!args->orphan) {
6728 		/*
6729 		 * Start new inodes with an inode_ref. This is slightly more
6730 		 * efficient for small numbers of hard links since they will
6731 		 * be packed into one item. Extended refs will kick in if we
6732 		 * add more hard links than can fit in the ref item.
6733 		 */
6734 		key[1].objectid = objectid;
6735 		key[1].type = BTRFS_INODE_REF_KEY;
6736 		if (args->subvol) {
6737 			key[1].offset = objectid;
6738 			sizes[1] = 2 + sizeof(*ref);
6739 		} else {
6740 			key[1].offset = btrfs_ino(BTRFS_I(dir));
6741 			sizes[1] = name->len + sizeof(*ref);
6742 		}
6743 	}
6744 
6745 	batch.keys = &key[0];
6746 	batch.data_sizes = &sizes[0];
6747 	batch.total_data_size = sizes[0] + (args->orphan ? 0 : sizes[1]);
6748 	batch.nr = args->orphan ? 1 : 2;
6749 	ret = btrfs_insert_empty_items(trans, root, path, &batch);
6750 	if (unlikely(ret != 0)) {
6751 		btrfs_abort_transaction(trans, ret);
6752 		goto discard;
6753 	}
6754 
6755 	ts = simple_inode_init_ts(inode);
6756 	BTRFS_I(inode)->i_otime_sec = ts.tv_sec;
6757 	BTRFS_I(inode)->i_otime_nsec = ts.tv_nsec;
6758 
6759 	/*
6760 	 * We're going to fill the inode item now, so at this point the inode
6761 	 * must be fully initialized.
6762 	 */
6763 
6764 	inode_item = btrfs_item_ptr(path->nodes[0], path->slots[0],
6765 				  struct btrfs_inode_item);
6766 	memzero_extent_buffer(path->nodes[0], (unsigned long)inode_item,
6767 			     sizeof(*inode_item));
6768 	fill_inode_item(trans, path->nodes[0], inode_item, inode);
6769 
6770 	if (!args->orphan) {
6771 		ref = btrfs_item_ptr(path->nodes[0], path->slots[0] + 1,
6772 				     struct btrfs_inode_ref);
6773 		ptr = (unsigned long)(ref + 1);
6774 		if (args->subvol) {
6775 			btrfs_set_inode_ref_name_len(path->nodes[0], ref, 2);
6776 			btrfs_set_inode_ref_index(path->nodes[0], ref, 0);
6777 			write_extent_buffer(path->nodes[0], "..", ptr, 2);
6778 		} else {
6779 			btrfs_set_inode_ref_name_len(path->nodes[0], ref,
6780 						     name->len);
6781 			btrfs_set_inode_ref_index(path->nodes[0], ref,
6782 						  BTRFS_I(inode)->dir_index);
6783 			write_extent_buffer(path->nodes[0], name->name, ptr,
6784 					    name->len);
6785 		}
6786 	}
6787 
6788 	/*
6789 	 * We don't need the path anymore, plus inheriting properties, adding
6790 	 * ACLs, security xattrs, orphan item or adding the link, will result in
6791 	 * allocating yet another path. So just free our path.
6792 	 */
6793 	btrfs_free_path(path);
6794 	path = NULL;
6795 
6796 	if (args->subvol) {
6797 		struct btrfs_inode *parent;
6798 
6799 		/*
6800 		 * Subvolumes inherit properties from their parent subvolume,
6801 		 * not the directory they were created in.
6802 		 */
6803 		parent = btrfs_iget(BTRFS_FIRST_FREE_OBJECTID, BTRFS_I(dir)->root);
6804 		if (IS_ERR(parent)) {
6805 			ret = PTR_ERR(parent);
6806 		} else {
6807 			ret = btrfs_inode_inherit_props(trans, BTRFS_I(inode),
6808 							parent);
6809 			iput(&parent->vfs_inode);
6810 		}
6811 	} else {
6812 		ret = btrfs_inode_inherit_props(trans, BTRFS_I(inode),
6813 						BTRFS_I(dir));
6814 	}
6815 	if (ret) {
6816 		btrfs_err(fs_info,
6817 			  "error inheriting props for ino %llu (root %llu): %d",
6818 			  btrfs_ino(BTRFS_I(inode)), btrfs_root_id(root), ret);
6819 	}
6820 
6821 	/*
6822 	 * Subvolumes don't inherit ACLs or get passed to the LSM. This is
6823 	 * probably a bug.
6824 	 */
6825 	if (!args->subvol) {
6826 		ret = btrfs_init_inode_security(trans, args);
6827 		if (unlikely(ret)) {
6828 			btrfs_abort_transaction(trans, ret);
6829 			goto discard;
6830 		}
6831 	}
6832 
6833 	ret = btrfs_add_inode_to_root(BTRFS_I(inode), false);
6834 	if (WARN_ON(ret)) {
6835 		/* Shouldn't happen, we used xa_reserve() before. */
6836 		btrfs_abort_transaction(trans, ret);
6837 		goto discard;
6838 	}
6839 
6840 	trace_btrfs_inode_new(inode);
6841 	btrfs_set_inode_last_trans(trans, BTRFS_I(inode));
6842 
6843 	btrfs_update_root_times(trans, root);
6844 
6845 	if (args->orphan) {
6846 		ret = btrfs_orphan_add(trans, BTRFS_I(inode));
6847 		if (unlikely(ret)) {
6848 			btrfs_abort_transaction(trans, ret);
6849 			goto discard;
6850 		}
6851 	} else {
6852 		ret = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode), name,
6853 				     false, BTRFS_I(inode)->dir_index);
6854 		if (unlikely(ret)) {
6855 			btrfs_abort_transaction(trans, ret);
6856 			goto discard;
6857 		}
6858 	}
6859 
6860 	return 0;
6861 
6862 discard:
6863 	/*
6864 	 * discard_new_inode() calls iput(), but the caller owns the reference
6865 	 * to the inode.
6866 	 */
6867 	ihold(inode);
6868 	discard_new_inode(inode);
6869 out:
6870 	if (xa_reserved)
6871 		xa_release(&root->inodes, objectid);
6872 
6873 	btrfs_free_path(path);
6874 	return ret;
6875 }
6876 
6877 /*
6878  * utility function to add 'inode' into 'parent_inode' with
6879  * a give name and a given sequence number.
6880  * if 'add_backref' is true, also insert a backref from the
6881  * inode to the parent directory.
6882  */
6883 int btrfs_add_link(struct btrfs_trans_handle *trans,
6884 		   struct btrfs_inode *parent_inode, struct btrfs_inode *inode,
6885 		   const struct fscrypt_str *name, bool add_backref, u64 index)
6886 {
6887 	int ret = 0;
6888 	struct btrfs_key key;
6889 	struct btrfs_root *root = parent_inode->root;
6890 	u64 ino = btrfs_ino(inode);
6891 	u64 parent_ino = btrfs_ino(parent_inode);
6892 
6893 	if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6894 		memcpy(&key, &inode->root->root_key, sizeof(key));
6895 	} else {
6896 		key.objectid = ino;
6897 		key.type = BTRFS_INODE_ITEM_KEY;
6898 		key.offset = 0;
6899 	}
6900 
6901 	if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6902 		ret = btrfs_add_root_ref(trans, key.objectid,
6903 					 btrfs_root_id(root), parent_ino,
6904 					 index, name);
6905 	} else if (add_backref) {
6906 		ret = btrfs_insert_inode_ref(trans, root, name,
6907 					     ino, parent_ino, index);
6908 	}
6909 
6910 	/* Nothing to clean up yet */
6911 	if (ret)
6912 		return ret;
6913 
6914 	ret = btrfs_insert_dir_item(trans, name, parent_inode, &key,
6915 				    btrfs_inode_type(inode), index);
6916 	if (ret == -EEXIST || ret == -EOVERFLOW)
6917 		goto fail_dir_item;
6918 	else if (unlikely(ret)) {
6919 		btrfs_abort_transaction(trans, ret);
6920 		return ret;
6921 	}
6922 
6923 	btrfs_i_size_write(parent_inode, parent_inode->vfs_inode.i_size +
6924 			   name->len * 2);
6925 	inode_inc_iversion(&parent_inode->vfs_inode);
6926 	update_time_after_link_or_unlink(parent_inode);
6927 
6928 	ret = btrfs_update_inode(trans, parent_inode);
6929 	if (ret)
6930 		btrfs_abort_transaction(trans, ret);
6931 	return ret;
6932 
6933 fail_dir_item:
6934 	if (unlikely(ino == BTRFS_FIRST_FREE_OBJECTID)) {
6935 		u64 local_index;
6936 		int ret2;
6937 
6938 		ret2 = btrfs_del_root_ref(trans, key.objectid, btrfs_root_id(root),
6939 					  parent_ino, &local_index, name);
6940 		if (ret2)
6941 			btrfs_abort_transaction(trans, ret2);
6942 	} else if (add_backref) {
6943 		int ret2;
6944 
6945 		ret2 = btrfs_del_inode_ref(trans, root, name, ino, parent_ino, NULL);
6946 		if (ret2)
6947 			btrfs_abort_transaction(trans, ret2);
6948 	}
6949 
6950 	/* Return the original error code */
6951 	return ret;
6952 }
6953 
6954 static int btrfs_create_common(struct inode *dir, struct dentry *dentry,
6955 			       struct inode *inode)
6956 {
6957 	struct btrfs_fs_info *fs_info = inode_to_fs_info(dir);
6958 	struct btrfs_root *root = BTRFS_I(dir)->root;
6959 	struct btrfs_new_inode_args new_inode_args = {
6960 		.dir = dir,
6961 		.dentry = dentry,
6962 		.inode = inode,
6963 	};
6964 	unsigned int trans_num_items;
6965 	struct btrfs_trans_handle *trans;
6966 	int ret;
6967 
6968 	ret = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
6969 	if (ret)
6970 		goto out_inode;
6971 
6972 	trans = btrfs_start_transaction(root, trans_num_items);
6973 	if (IS_ERR(trans)) {
6974 		ret = PTR_ERR(trans);
6975 		goto out_new_inode_args;
6976 	}
6977 
6978 	ret = btrfs_create_new_inode(trans, &new_inode_args);
6979 	if (!ret) {
6980 		if (S_ISDIR(inode->i_mode))
6981 			inode->i_opflags |= IOP_FASTPERM_MAY_EXEC;
6982 		d_instantiate_new(dentry, inode);
6983 	}
6984 
6985 	btrfs_end_transaction(trans);
6986 	btrfs_btree_balance_dirty(fs_info);
6987 out_new_inode_args:
6988 	btrfs_new_inode_args_destroy(&new_inode_args);
6989 out_inode:
6990 	if (ret)
6991 		iput(inode);
6992 	return ret;
6993 }
6994 
6995 static int btrfs_mknod(struct mnt_idmap *idmap, struct inode *dir,
6996 		       struct dentry *dentry, umode_t mode, dev_t rdev)
6997 {
6998 	struct inode *inode;
6999 
7000 	inode = new_inode(dir->i_sb);
7001 	if (!inode)
7002 		return -ENOMEM;
7003 	inode_init_owner(idmap, inode, dir, mode);
7004 	inode->i_op = &btrfs_special_inode_operations;
7005 	init_special_inode(inode, inode->i_mode, rdev);
7006 	return btrfs_create_common(dir, dentry, inode);
7007 }
7008 
7009 static int btrfs_create(struct mnt_idmap *idmap, struct inode *dir,
7010 			struct dentry *dentry, umode_t mode)
7011 {
7012 	struct inode *inode;
7013 
7014 	inode = new_inode(dir->i_sb);
7015 	if (!inode)
7016 		return -ENOMEM;
7017 	inode_init_owner(idmap, inode, dir, mode);
7018 	inode->i_fop = &btrfs_file_operations;
7019 	inode->i_op = &btrfs_file_inode_operations;
7020 	inode->i_mapping->a_ops = &btrfs_aops;
7021 	return btrfs_create_common(dir, dentry, inode);
7022 }
7023 
7024 static int btrfs_link(struct dentry *old_dentry, struct inode *dir,
7025 		      struct dentry *dentry)
7026 {
7027 	struct btrfs_trans_handle *trans = NULL;
7028 	struct btrfs_root *root = BTRFS_I(dir)->root;
7029 	struct inode *inode = d_inode(old_dentry);
7030 	struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
7031 	struct fscrypt_name fname;
7032 	u64 index;
7033 	int ret;
7034 
7035 	/* do not allow sys_link's with other subvols of the same device */
7036 	if (btrfs_root_id(root) != btrfs_root_id(BTRFS_I(inode)->root))
7037 		return -EXDEV;
7038 
7039 	if (inode->i_nlink >= BTRFS_LINK_MAX)
7040 		return -EMLINK;
7041 
7042 	ret = fscrypt_setup_filename(dir, &dentry->d_name, 0, &fname);
7043 	if (ret)
7044 		goto fail;
7045 
7046 	ret = btrfs_set_inode_index(BTRFS_I(dir), &index);
7047 	if (ret)
7048 		goto fail;
7049 
7050 	/*
7051 	 * 2 items for inode and inode ref
7052 	 * 2 items for dir items
7053 	 * 1 item for parent inode
7054 	 * 1 item for orphan item deletion if O_TMPFILE
7055 	 */
7056 	trans = btrfs_start_transaction(root, inode->i_nlink ? 5 : 6);
7057 	if (IS_ERR(trans)) {
7058 		ret = PTR_ERR(trans);
7059 		trans = NULL;
7060 		goto fail;
7061 	}
7062 
7063 	/* There are several dir indexes for this inode, clear the cache. */
7064 	BTRFS_I(inode)->dir_index = 0ULL;
7065 	inode_inc_iversion(inode);
7066 	inode_set_ctime_current(inode);
7067 
7068 	ret = btrfs_add_link(trans, BTRFS_I(dir), BTRFS_I(inode),
7069 			     &fname.disk_name, true, index);
7070 	if (ret)
7071 		goto fail;
7072 
7073 	/* Link added now we update the inode item with the new link count. */
7074 	inc_nlink(inode);
7075 	ret = btrfs_update_inode(trans, BTRFS_I(inode));
7076 	if (unlikely(ret)) {
7077 		btrfs_abort_transaction(trans, ret);
7078 		goto fail;
7079 	}
7080 
7081 	if (inode->i_nlink == 1) {
7082 		/*
7083 		 * If the new hard link count is 1, it's a file created with the
7084 		 * open(2) O_TMPFILE flag.
7085 		 */
7086 		ret = btrfs_orphan_del(trans, BTRFS_I(inode));
7087 		if (unlikely(ret)) {
7088 			btrfs_abort_transaction(trans, ret);
7089 			goto fail;
7090 		}
7091 	}
7092 
7093 	/* Grab reference for the new dentry passed to d_instantiate(). */
7094 	ihold(inode);
7095 	d_instantiate(dentry, inode);
7096 	btrfs_log_new_name(trans, old_dentry, NULL, 0, dentry->d_parent);
7097 
7098 fail:
7099 	fscrypt_free_filename(&fname);
7100 	if (trans)
7101 		btrfs_end_transaction(trans);
7102 	btrfs_btree_balance_dirty(fs_info);
7103 	return ret;
7104 }
7105 
7106 static struct dentry *btrfs_mkdir(struct mnt_idmap *idmap, struct inode *dir,
7107 				  struct dentry *dentry, umode_t mode)
7108 {
7109 	struct inode *inode;
7110 
7111 	inode = new_inode(dir->i_sb);
7112 	if (!inode)
7113 		return ERR_PTR(-ENOMEM);
7114 	inode_init_owner(idmap, inode, dir, mode);
7115 	inode->i_op = &btrfs_dir_inode_operations;
7116 	inode->i_fop = &btrfs_dir_file_operations;
7117 	return ERR_PTR(btrfs_create_common(dir, dentry, inode));
7118 }
7119 
7120 static noinline int uncompress_inline(struct btrfs_path *path,
7121 				      struct folio *folio,
7122 				      struct btrfs_file_extent_item *item)
7123 {
7124 	int ret;
7125 	struct extent_buffer *leaf = path->nodes[0];
7126 	const u32 blocksize = leaf->fs_info->sectorsize;
7127 	char *tmp;
7128 	size_t max_size;
7129 	unsigned long inline_size;
7130 	unsigned long ptr;
7131 	int compress_type;
7132 
7133 	compress_type = btrfs_file_extent_compression(leaf, item);
7134 	max_size = btrfs_file_extent_ram_bytes(leaf, item);
7135 	inline_size = btrfs_file_extent_inline_item_len(leaf, path->slots[0]);
7136 	tmp = kmalloc(inline_size, GFP_NOFS);
7137 	if (!tmp)
7138 		return -ENOMEM;
7139 	ptr = btrfs_file_extent_inline_start(item);
7140 
7141 	read_extent_buffer(leaf, tmp, ptr, inline_size);
7142 
7143 	max_size = min_t(unsigned long, blocksize, max_size);
7144 	ret = btrfs_decompress(compress_type, tmp, folio, 0, inline_size,
7145 			       max_size);
7146 
7147 	/*
7148 	 * decompression code contains a memset to fill in any space between the end
7149 	 * of the uncompressed data and the end of max_size in case the decompressed
7150 	 * data ends up shorter than ram_bytes.  That doesn't cover the hole between
7151 	 * the end of an inline extent and the beginning of the next block, so we
7152 	 * cover that region here.
7153 	 */
7154 
7155 	if (max_size < blocksize)
7156 		folio_zero_range(folio, max_size, blocksize - max_size);
7157 	kfree(tmp);
7158 	return ret;
7159 }
7160 
7161 static int read_inline_extent(struct btrfs_path *path, struct folio *folio)
7162 {
7163 	const u32 blocksize = path->nodes[0]->fs_info->sectorsize;
7164 	struct btrfs_file_extent_item *fi;
7165 	void *kaddr;
7166 	size_t copy_size;
7167 
7168 	if (!folio || folio_test_uptodate(folio))
7169 		return 0;
7170 
7171 	ASSERT(folio_pos(folio) == 0);
7172 
7173 	fi = btrfs_item_ptr(path->nodes[0], path->slots[0],
7174 			    struct btrfs_file_extent_item);
7175 	if (btrfs_file_extent_compression(path->nodes[0], fi) != BTRFS_COMPRESS_NONE)
7176 		return uncompress_inline(path, folio, fi);
7177 
7178 	copy_size = min_t(u64, blocksize,
7179 			  btrfs_file_extent_ram_bytes(path->nodes[0], fi));
7180 	kaddr = kmap_local_folio(folio, 0);
7181 	read_extent_buffer(path->nodes[0], kaddr,
7182 			   btrfs_file_extent_inline_start(fi), copy_size);
7183 	kunmap_local(kaddr);
7184 	if (copy_size < blocksize)
7185 		folio_zero_range(folio, copy_size, blocksize - copy_size);
7186 	return 0;
7187 }
7188 
7189 /*
7190  * Lookup the first extent overlapping a range in a file.
7191  *
7192  * @inode:	file to search in
7193  * @page:	page to read extent data into if the extent is inline
7194  * @start:	file offset
7195  * @len:	length of range starting at @start
7196  *
7197  * Return the first &struct extent_map which overlaps the given range, reading
7198  * it from the B-tree and caching it if necessary. Note that there may be more
7199  * extents which overlap the given range after the returned extent_map.
7200  *
7201  * If @page is not NULL and the extent is inline, this also reads the extent
7202  * data directly into the page and marks the extent up to date in the io_tree.
7203  *
7204  * Return: ERR_PTR on error, non-NULL extent_map on success.
7205  */
7206 struct extent_map *btrfs_get_extent(struct btrfs_inode *inode,
7207 				    struct folio *folio, u64 start, u64 len)
7208 {
7209 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
7210 	int ret = 0;
7211 	u64 extent_start = 0;
7212 	u64 extent_end = 0;
7213 	u64 objectid = btrfs_ino(inode);
7214 	int extent_type = -1;
7215 	struct btrfs_path *path = NULL;
7216 	struct btrfs_root *root = inode->root;
7217 	struct btrfs_file_extent_item *item;
7218 	struct extent_buffer *leaf;
7219 	struct btrfs_key found_key;
7220 	struct extent_map *em = NULL;
7221 	struct extent_map_tree *em_tree = &inode->extent_tree;
7222 
7223 	read_lock(&em_tree->lock);
7224 	em = btrfs_lookup_extent_mapping(em_tree, start, len);
7225 	read_unlock(&em_tree->lock);
7226 
7227 	if (em) {
7228 		if (em->start > start || btrfs_extent_map_end(em) <= start)
7229 			btrfs_free_extent_map(em);
7230 		else if (em->disk_bytenr == EXTENT_MAP_INLINE && folio)
7231 			btrfs_free_extent_map(em);
7232 		else
7233 			goto out;
7234 	}
7235 	em = btrfs_alloc_extent_map();
7236 	if (!em) {
7237 		ret = -ENOMEM;
7238 		goto out;
7239 	}
7240 	em->start = EXTENT_MAP_HOLE;
7241 	em->disk_bytenr = EXTENT_MAP_HOLE;
7242 	em->len = (u64)-1;
7243 
7244 	path = btrfs_alloc_path();
7245 	if (!path) {
7246 		ret = -ENOMEM;
7247 		goto out;
7248 	}
7249 
7250 	/* Chances are we'll be called again, so go ahead and do readahead */
7251 	path->reada = READA_FORWARD;
7252 
7253 	/*
7254 	 * The same explanation in load_free_space_cache applies here as well,
7255 	 * we only read when we're loading the free space cache, and at that
7256 	 * point the commit_root has everything we need.
7257 	 */
7258 	if (btrfs_is_free_space_inode(inode)) {
7259 		path->search_commit_root = true;
7260 		path->skip_locking = true;
7261 	}
7262 
7263 	ret = btrfs_lookup_file_extent(NULL, root, path, objectid, start, 0);
7264 	if (ret < 0) {
7265 		goto out;
7266 	} else if (ret > 0) {
7267 		if (path->slots[0] == 0)
7268 			goto not_found;
7269 		path->slots[0]--;
7270 		ret = 0;
7271 	}
7272 
7273 	leaf = path->nodes[0];
7274 	item = btrfs_item_ptr(leaf, path->slots[0],
7275 			      struct btrfs_file_extent_item);
7276 	btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7277 	if (found_key.objectid != objectid ||
7278 	    found_key.type != BTRFS_EXTENT_DATA_KEY) {
7279 		/*
7280 		 * If we backup past the first extent we want to move forward
7281 		 * and see if there is an extent in front of us, otherwise we'll
7282 		 * say there is a hole for our whole search range which can
7283 		 * cause problems.
7284 		 */
7285 		extent_end = start;
7286 		goto next;
7287 	}
7288 
7289 	extent_type = btrfs_file_extent_type(leaf, item);
7290 	extent_start = found_key.offset;
7291 	extent_end = btrfs_file_extent_end(path);
7292 	if (extent_type == BTRFS_FILE_EXTENT_REG ||
7293 	    extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
7294 		/* Only regular file could have regular/prealloc extent */
7295 		if (unlikely(!S_ISREG(inode->vfs_inode.i_mode))) {
7296 			ret = -EUCLEAN;
7297 			btrfs_crit(fs_info,
7298 		"regular/prealloc extent found for non-regular inode %llu",
7299 				   btrfs_ino(inode));
7300 			goto out;
7301 		}
7302 		trace_btrfs_get_extent_show_fi_regular(inode, leaf, item,
7303 						       extent_start);
7304 	} else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
7305 		trace_btrfs_get_extent_show_fi_inline(inode, leaf, item,
7306 						      path->slots[0],
7307 						      extent_start);
7308 	}
7309 next:
7310 	if (start >= extent_end) {
7311 		path->slots[0]++;
7312 		if (path->slots[0] >= btrfs_header_nritems(leaf)) {
7313 			ret = btrfs_next_leaf(root, path);
7314 			if (ret < 0)
7315 				goto out;
7316 			else if (ret > 0)
7317 				goto not_found;
7318 
7319 			leaf = path->nodes[0];
7320 		}
7321 		btrfs_item_key_to_cpu(leaf, &found_key, path->slots[0]);
7322 		if (found_key.objectid != objectid ||
7323 		    found_key.type != BTRFS_EXTENT_DATA_KEY)
7324 			goto not_found;
7325 		if (start + len <= found_key.offset)
7326 			goto not_found;
7327 		if (start > found_key.offset)
7328 			goto next;
7329 
7330 		/* New extent overlaps with existing one */
7331 		em->start = start;
7332 		em->len = found_key.offset - start;
7333 		em->disk_bytenr = EXTENT_MAP_HOLE;
7334 		goto insert;
7335 	}
7336 
7337 	btrfs_extent_item_to_extent_map(inode, path, item, em);
7338 
7339 	if (extent_type == BTRFS_FILE_EXTENT_REG ||
7340 	    extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
7341 		goto insert;
7342 	} else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
7343 		/*
7344 		 * Inline extent can only exist at file offset 0. This is
7345 		 * ensured by tree-checker and inline extent creation path.
7346 		 * Thus all members representing file offsets should be zero.
7347 		 */
7348 		ASSERT(extent_start == 0);
7349 		ASSERT(em->start == 0);
7350 
7351 		/*
7352 		 * btrfs_extent_item_to_extent_map() should have properly
7353 		 * initialized em members already.
7354 		 *
7355 		 * Other members are not utilized for inline extents.
7356 		 */
7357 		ASSERT(em->disk_bytenr == EXTENT_MAP_INLINE);
7358 		ASSERT(em->len == fs_info->sectorsize);
7359 
7360 		ret = read_inline_extent(path, folio);
7361 		if (ret < 0)
7362 			goto out;
7363 		goto insert;
7364 	}
7365 not_found:
7366 	em->start = start;
7367 	em->len = len;
7368 	em->disk_bytenr = EXTENT_MAP_HOLE;
7369 insert:
7370 	ret = 0;
7371 	btrfs_release_path(path);
7372 	if (unlikely(em->start > start || btrfs_extent_map_end(em) <= start)) {
7373 		btrfs_err(fs_info,
7374 			  "bad extent! em: [%llu %llu] passed [%llu %llu]",
7375 			  em->start, em->len, start, len);
7376 		ret = -EIO;
7377 		goto out;
7378 	}
7379 
7380 	write_lock(&em_tree->lock);
7381 	ret = btrfs_add_extent_mapping(inode, &em, start, len);
7382 	write_unlock(&em_tree->lock);
7383 out:
7384 	btrfs_free_path(path);
7385 
7386 	trace_btrfs_get_extent(root, inode, em);
7387 
7388 	if (ret) {
7389 		btrfs_free_extent_map(em);
7390 		return ERR_PTR(ret);
7391 	}
7392 	return em;
7393 }
7394 
7395 static bool btrfs_extent_readonly(struct btrfs_fs_info *fs_info, u64 bytenr)
7396 {
7397 	struct btrfs_block_group *block_group;
7398 	bool readonly = false;
7399 
7400 	block_group = btrfs_lookup_block_group(fs_info, bytenr);
7401 	if (!block_group || block_group->ro)
7402 		readonly = true;
7403 	if (block_group)
7404 		btrfs_put_block_group(block_group);
7405 	return readonly;
7406 }
7407 
7408 /*
7409  * Check if we can do nocow write into the range [@offset, @offset + @len)
7410  *
7411  * @offset:	File offset
7412  * @len:	The length to write, will be updated to the nocow writeable
7413  *		range
7414  * @orig_start:	(optional) Return the original file offset of the file extent
7415  * @orig_len:	(optional) Return the original on-disk length of the file extent
7416  * @ram_bytes:	(optional) Return the ram_bytes of the file extent
7417  *
7418  * Return:
7419  * >0	and update @len if we can do nocow write
7420  *  0	if we can't do nocow write
7421  * <0	if error happened
7422  *
7423  * NOTE: This only checks the file extents, caller is responsible to wait for
7424  *	 any ordered extents.
7425  */
7426 noinline int can_nocow_extent(struct btrfs_inode *inode, u64 offset, u64 *len,
7427 			      struct btrfs_file_extent *file_extent,
7428 			      bool nowait)
7429 {
7430 	struct btrfs_root *root = inode->root;
7431 	struct btrfs_fs_info *fs_info = root->fs_info;
7432 	struct can_nocow_file_extent_args nocow_args = { 0 };
7433 	BTRFS_PATH_AUTO_FREE(path);
7434 	int ret;
7435 	struct extent_buffer *leaf;
7436 	struct extent_io_tree *io_tree = &inode->io_tree;
7437 	struct btrfs_file_extent_item *fi;
7438 	struct btrfs_key key;
7439 	int found_type;
7440 
7441 	path = btrfs_alloc_path();
7442 	if (!path)
7443 		return -ENOMEM;
7444 	path->nowait = nowait;
7445 
7446 	ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
7447 				       offset, 0);
7448 	if (ret < 0)
7449 		return ret;
7450 
7451 	if (ret == 1) {
7452 		if (path->slots[0] == 0) {
7453 			/* Can't find the item, must COW. */
7454 			return 0;
7455 		}
7456 		path->slots[0]--;
7457 	}
7458 	ret = 0;
7459 	leaf = path->nodes[0];
7460 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
7461 	if (key.objectid != btrfs_ino(inode) ||
7462 	    key.type != BTRFS_EXTENT_DATA_KEY) {
7463 		/* Not our file or wrong item type, must COW. */
7464 		return 0;
7465 	}
7466 
7467 	if (key.offset > offset) {
7468 		/* Wrong offset, must COW. */
7469 		return 0;
7470 	}
7471 
7472 	if (btrfs_file_extent_end(path) <= offset)
7473 		return 0;
7474 
7475 	fi = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
7476 	found_type = btrfs_file_extent_type(leaf, fi);
7477 
7478 	nocow_args.start = offset;
7479 	nocow_args.end = offset + *len - 1;
7480 	nocow_args.free_path = true;
7481 
7482 	ret = can_nocow_file_extent(path, &key, inode, &nocow_args);
7483 	/* can_nocow_file_extent() has freed the path. */
7484 	path = NULL;
7485 
7486 	if (ret != 1) {
7487 		/* Treat errors as not being able to NOCOW. */
7488 		return 0;
7489 	}
7490 
7491 	if (btrfs_extent_readonly(fs_info,
7492 				  nocow_args.file_extent.disk_bytenr +
7493 				  nocow_args.file_extent.offset))
7494 		return 0;
7495 
7496 	if (!(inode->flags & BTRFS_INODE_NODATACOW) &&
7497 	    found_type == BTRFS_FILE_EXTENT_PREALLOC) {
7498 		u64 range_end;
7499 
7500 		range_end = round_up(offset + nocow_args.file_extent.num_bytes,
7501 				     root->fs_info->sectorsize) - 1;
7502 		ret = btrfs_test_range_bit_exists(io_tree, offset, range_end,
7503 						  EXTENT_DELALLOC);
7504 		if (ret)
7505 			return -EAGAIN;
7506 	}
7507 
7508 	if (file_extent)
7509 		memcpy(file_extent, &nocow_args.file_extent, sizeof(*file_extent));
7510 
7511 	*len = nocow_args.file_extent.num_bytes;
7512 
7513 	return 1;
7514 }
7515 
7516 /* The callers of this must take lock_extent() */
7517 struct extent_map *btrfs_create_io_em(struct btrfs_inode *inode, u64 start,
7518 				      const struct btrfs_file_extent *file_extent,
7519 				      int type)
7520 {
7521 	struct extent_map *em;
7522 	int ret;
7523 
7524 	/*
7525 	 * Note the missing NOCOW type.
7526 	 *
7527 	 * For pure NOCOW writes, we should not create an io extent map, but
7528 	 * just reusing the existing one.
7529 	 * Only PREALLOC writes (NOCOW write into preallocated range) can
7530 	 * create an io extent map.
7531 	 */
7532 	ASSERT(type == BTRFS_ORDERED_PREALLOC ||
7533 	       type == BTRFS_ORDERED_COMPRESSED ||
7534 	       type == BTRFS_ORDERED_REGULAR);
7535 
7536 	switch (type) {
7537 	case BTRFS_ORDERED_PREALLOC:
7538 		/* We're only referring part of a larger preallocated extent. */
7539 		ASSERT(file_extent->num_bytes <= file_extent->ram_bytes);
7540 		break;
7541 	case BTRFS_ORDERED_REGULAR:
7542 		/* COW results a new extent matching our file extent size. */
7543 		ASSERT(file_extent->disk_num_bytes == file_extent->num_bytes);
7544 		ASSERT(file_extent->ram_bytes == file_extent->num_bytes);
7545 
7546 		/* Since it's a new extent, we should not have any offset. */
7547 		ASSERT(file_extent->offset == 0);
7548 		break;
7549 	case BTRFS_ORDERED_COMPRESSED:
7550 		/* Must be compressed. */
7551 		ASSERT(file_extent->compression != BTRFS_COMPRESS_NONE);
7552 
7553 		/*
7554 		 * Encoded write can make us to refer to part of the
7555 		 * uncompressed extent.
7556 		 */
7557 		ASSERT(file_extent->num_bytes <= file_extent->ram_bytes);
7558 		break;
7559 	}
7560 
7561 	em = btrfs_alloc_extent_map();
7562 	if (!em)
7563 		return ERR_PTR(-ENOMEM);
7564 
7565 	em->start = start;
7566 	em->len = file_extent->num_bytes;
7567 	em->disk_bytenr = file_extent->disk_bytenr;
7568 	em->disk_num_bytes = file_extent->disk_num_bytes;
7569 	em->ram_bytes = file_extent->ram_bytes;
7570 	em->generation = -1;
7571 	em->offset = file_extent->offset;
7572 	em->flags |= EXTENT_FLAG_PINNED;
7573 	if (type == BTRFS_ORDERED_COMPRESSED)
7574 		btrfs_extent_map_set_compression(em, file_extent->compression);
7575 
7576 	ret = btrfs_replace_extent_map_range(inode, em, true);
7577 	if (ret) {
7578 		btrfs_free_extent_map(em);
7579 		return ERR_PTR(ret);
7580 	}
7581 
7582 	/* em got 2 refs now, callers needs to do btrfs_free_extent_map once. */
7583 	return em;
7584 }
7585 
7586 /*
7587  * For release_folio() and invalidate_folio() we have a race window where
7588  * folio_end_writeback() is called but the subpage spinlock is not yet released.
7589  * If we continue to release/invalidate the page, we could cause use-after-free
7590  * for subpage spinlock.  So this function is to spin and wait for subpage
7591  * spinlock.
7592  */
7593 static void wait_subpage_spinlock(struct folio *folio)
7594 {
7595 	struct btrfs_fs_info *fs_info = folio_to_fs_info(folio);
7596 	struct btrfs_folio_state *bfs;
7597 
7598 	if (!btrfs_is_subpage(fs_info, folio))
7599 		return;
7600 
7601 	ASSERT(folio_test_private(folio) && folio_get_private(folio));
7602 	bfs = folio_get_private(folio);
7603 
7604 	/*
7605 	 * This may look insane as we just acquire the spinlock and release it,
7606 	 * without doing anything.  But we just want to make sure no one is
7607 	 * still holding the subpage spinlock.
7608 	 * And since the page is not dirty nor writeback, and we have page
7609 	 * locked, the only possible way to hold a spinlock is from the endio
7610 	 * function to clear page writeback.
7611 	 *
7612 	 * Here we just acquire the spinlock so that all existing callers
7613 	 * should exit and we're safe to release/invalidate the page.
7614 	 */
7615 	spin_lock_irq(&bfs->lock);
7616 	spin_unlock_irq(&bfs->lock);
7617 }
7618 
7619 static int btrfs_launder_folio(struct folio *folio)
7620 {
7621 	return btrfs_qgroup_free_data(folio_to_inode(folio), NULL, folio_pos(folio),
7622 				      folio_size(folio), NULL);
7623 }
7624 
7625 static bool __btrfs_release_folio(struct folio *folio, gfp_t gfp_flags)
7626 {
7627 	if (try_release_extent_mapping(folio, gfp_flags)) {
7628 		wait_subpage_spinlock(folio);
7629 		clear_folio_extent_mapped(folio);
7630 		return true;
7631 	}
7632 	return false;
7633 }
7634 
7635 static bool btrfs_release_folio(struct folio *folio, gfp_t gfp_flags)
7636 {
7637 	if (folio_test_writeback(folio) || folio_test_dirty(folio))
7638 		return false;
7639 	return __btrfs_release_folio(folio, gfp_flags);
7640 }
7641 
7642 #ifdef CONFIG_MIGRATION
7643 static int btrfs_migrate_folio(struct address_space *mapping,
7644 			     struct folio *dst, struct folio *src,
7645 			     enum migrate_mode mode)
7646 {
7647 	int ret = filemap_migrate_folio(mapping, dst, src, mode);
7648 
7649 	if (ret)
7650 		return ret;
7651 	return 0;
7652 }
7653 #else
7654 #define btrfs_migrate_folio NULL
7655 #endif
7656 
7657 static void btrfs_invalidate_folio(struct folio *folio, size_t offset,
7658 				 size_t length)
7659 {
7660 	struct btrfs_inode *inode = folio_to_inode(folio);
7661 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
7662 	struct extent_io_tree *tree = &inode->io_tree;
7663 	struct extent_state *cached_state = NULL;
7664 	u64 page_start = folio_pos(folio);
7665 	u64 page_end = page_start + folio_size(folio) - 1;
7666 	u64 cur;
7667 	int inode_evicting = inode_state_read_once(&inode->vfs_inode) & I_FREEING;
7668 
7669 	/*
7670 	 * We have folio locked so no new ordered extent can be created on this
7671 	 * page, nor bio can be submitted for this folio.
7672 	 *
7673 	 * But already submitted bio can still be finished on this folio.
7674 	 * Furthermore, endio function won't skip folio which has Ordered
7675 	 * already cleared, so it's possible for endio and
7676 	 * invalidate_folio to do the same ordered extent accounting twice
7677 	 * on one folio.
7678 	 *
7679 	 * So here we wait for any submitted bios to finish, so that we won't
7680 	 * do double ordered extent accounting on the same folio.
7681 	 */
7682 	folio_wait_writeback(folio);
7683 	wait_subpage_spinlock(folio);
7684 
7685 	/*
7686 	 * The invalidated blocks are going away; drop any fixup blocks among
7687 	 * them, data included, as they have no space reservation.
7688 	 */
7689 	btrfs_folio_clear_fixup_dirty(fs_info, folio, page_start + offset, length);
7690 
7691 	/*
7692 	 * For subpage case, we have call sites like
7693 	 * btrfs_punch_hole_lock_range() which passes range not aligned to
7694 	 * sectorsize.
7695 	 * If the range doesn't cover the full folio, we don't need to and
7696 	 * shouldn't clear page extent mapped, as folio->private can still
7697 	 * record subpage dirty bits for other part of the range.
7698 	 *
7699 	 * For cases that invalidate the full folio even the range doesn't
7700 	 * cover the full folio, like invalidating the last folio, we're
7701 	 * still safe to wait for ordered extent to finish.
7702 	 */
7703 	if (!(offset == 0 && length == folio_size(folio))) {
7704 		btrfs_release_folio(folio, GFP_NOFS);
7705 		return;
7706 	}
7707 
7708 	if (!inode_evicting)
7709 		btrfs_lock_extent(tree, page_start, page_end, &cached_state);
7710 
7711 	cur = page_start;
7712 	while (cur < page_end) {
7713 		struct btrfs_ordered_extent *ordered;
7714 		u64 range_end;
7715 		u32 range_len;
7716 		u32 extra_flags = 0;
7717 
7718 		ordered = btrfs_lookup_first_ordered_range(inode, cur,
7719 							   page_end + 1 - cur);
7720 		if (!ordered) {
7721 			range_end = page_end;
7722 			/*
7723 			 * No ordered extent covering this range, we are safe
7724 			 * to delete all extent states in the range.
7725 			 */
7726 			extra_flags = EXTENT_CLEAR_ALL_BITS;
7727 			goto next;
7728 		}
7729 		if (ordered->file_offset > cur) {
7730 			/*
7731 			 * There is a range between [cur, oe->file_offset) not
7732 			 * covered by any ordered extent.
7733 			 * We are safe to delete all extent states, and handle
7734 			 * the ordered extent in the next iteration.
7735 			 */
7736 			range_end = ordered->file_offset - 1;
7737 			extra_flags = EXTENT_CLEAR_ALL_BITS;
7738 			goto next;
7739 		}
7740 
7741 		range_end = min(ordered->file_offset + ordered->num_bytes - 1,
7742 				page_end);
7743 		ASSERT(range_end + 1 - cur < U32_MAX);
7744 		range_len = range_end + 1 - cur;
7745 		/*
7746 		 * If the range is not dirty, the range has been submitted and
7747 		 * since we have waited for the writeback, endio has been
7748 		 * executed, thus we must skip the range to avoid double
7749 		 * accounting for the ordered extent.
7750 		 */
7751 		if (!btrfs_folio_test_dirty(fs_info, folio, cur, range_len))
7752 			goto next;
7753 
7754 		/*
7755 		 * The range is dirty meaning it has not been submitted.
7756 		 * Here we need to truncate the OE range as the range will never
7757 		 * be submitted.
7758 		 *
7759 		 * IO on this page will never be started, so we need to account
7760 		 * for any ordered extents now. Don't clear EXTENT_DELALLOC_NEW
7761 		 * here, must leave that up for the ordered extent completion.
7762 		 *
7763 		 * This will also unlock the range for incoming
7764 		 * btrfs_finish_ordered_io().
7765 		 */
7766 		if (!inode_evicting)
7767 			btrfs_clear_extent_bit(tree, cur, range_end,
7768 					       EXTENT_DELALLOC |
7769 					       EXTENT_LOCKED | EXTENT_DO_ACCOUNTING |
7770 					       EXTENT_DEFRAG, &cached_state);
7771 
7772 		btrfs_mark_ordered_extent_truncated(ordered, cur - ordered->file_offset);
7773 
7774 		/*
7775 		 * If the ordered extent has finished, we're safe to delete all
7776 		 * the extent states of the range, otherwise
7777 		 * btrfs_finish_ordered_io() will get executed by endio for
7778 		 * other pages, so we can't delete extent states.
7779 		 */
7780 		if (btrfs_dec_test_ordered_pending(inode, &ordered,
7781 						   cur, range_end + 1 - cur)) {
7782 			btrfs_finish_ordered_io(ordered);
7783 			/*
7784 			 * The ordered extent has finished, now we're again
7785 			 * safe to delete all extent states of the range.
7786 			 */
7787 			extra_flags = EXTENT_CLEAR_ALL_BITS;
7788 		}
7789 next:
7790 		if (ordered)
7791 			btrfs_put_ordered_extent(ordered);
7792 		/*
7793 		 * Qgroup reserved space handler
7794 		 * Sector(s) here will be either:
7795 		 *
7796 		 * 1) Already written to disk or bio already finished
7797 		 *    Then its QGROUP_RESERVED bit in io_tree is already cleared.
7798 		 *    Qgroup will be handled by its qgroup_record then.
7799 		 *    btrfs_qgroup_free_data() call will do nothing here.
7800 		 *
7801 		 * 2) Not written to disk yet
7802 		 *    Then btrfs_qgroup_free_data() call will clear the
7803 		 *    QGROUP_RESERVED bit of its io_tree, and free the qgroup
7804 		 *    reserved data space.
7805 		 *    Since the IO will never happen for this page.
7806 		 */
7807 		btrfs_qgroup_free_data(inode, NULL, cur, range_end + 1 - cur, NULL);
7808 		if (!inode_evicting)
7809 			btrfs_clear_extent_bit(tree, cur, range_end, EXTENT_LOCKED |
7810 					       EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING |
7811 					       EXTENT_DEFRAG | extra_flags,
7812 					       &cached_state);
7813 		cur = range_end + 1;
7814 	}
7815 	btrfs_folio_clear_dirty(fs_info, folio, page_start, folio_size(folio));
7816 	btrfs_clear_folio_dirty_tag(folio);
7817 	if (!inode_evicting)
7818 		__btrfs_release_folio(folio, GFP_NOFS);
7819 	clear_folio_extent_mapped(folio);
7820 }
7821 
7822 static int btrfs_truncate(struct btrfs_inode *inode, bool skip_writeback)
7823 {
7824 	struct btrfs_truncate_control control = {
7825 		.inode = inode,
7826 		.ino = btrfs_ino(inode),
7827 		.min_type = BTRFS_EXTENT_DATA_KEY,
7828 		.clear_extent_range = true,
7829 		.new_size = inode->vfs_inode.i_size,
7830 	};
7831 	struct btrfs_root *root = inode->root;
7832 	struct btrfs_fs_info *fs_info = root->fs_info;
7833 	struct btrfs_block_rsv rsv;
7834 	int ret;
7835 	struct btrfs_trans_handle *trans;
7836 	const u64 min_size = btrfs_calc_metadata_size(fs_info, 1);
7837 	const u64 lock_start = round_down(inode->vfs_inode.i_size, fs_info->sectorsize);
7838 	const u64 i_size_up = round_up(inode->vfs_inode.i_size, fs_info->sectorsize);
7839 
7840 	/* Our inode is locked and the i_size can't be changed concurrently. */
7841 	btrfs_assert_inode_locked(inode);
7842 
7843 	if (!skip_writeback) {
7844 		ret = btrfs_wait_ordered_range(inode, lock_start, (u64)-1);
7845 		if (ret)
7846 			return ret;
7847 	}
7848 
7849 	/*
7850 	 * Yes ladies and gentlemen, this is indeed ugly.  We have a couple of
7851 	 * things going on here:
7852 	 *
7853 	 * 1) We need to reserve space to update our inode.
7854 	 *
7855 	 * 2) We need to have something to cache all the space that is going to
7856 	 * be free'd up by the truncate operation, but also have some slack
7857 	 * space reserved in case it uses space during the truncate (thank you
7858 	 * very much snapshotting).
7859 	 *
7860 	 * And we need these to be separate.  The fact is we can use a lot of
7861 	 * space doing the truncate, and we have no earthly idea how much space
7862 	 * we will use, so we need the truncate reservation to be separate so it
7863 	 * doesn't end up using space reserved for updating the inode.  We also
7864 	 * need to be able to stop the transaction and start a new one, which
7865 	 * means we need to be able to update the inode several times, and we
7866 	 * have no idea of knowing how many times that will be, so we can't just
7867 	 * reserve 1 item for the entirety of the operation, so that has to be
7868 	 * done separately as well.
7869 	 *
7870 	 * So that leaves us with
7871 	 *
7872 	 * 1) rsv - for the truncate reservation, which we will steal from the
7873 	 * transaction reservation.
7874 	 * 2) fs_info->trans_block_rsv - this will have 1 items worth left for
7875 	 * updating the inode.
7876 	 */
7877 	btrfs_init_metadata_block_rsv(fs_info, &rsv, BTRFS_BLOCK_RSV_TEMP);
7878 	rsv.size = min_size;
7879 	rsv.failfast = true;
7880 
7881 	/*
7882 	 * 1 for the truncate slack space
7883 	 * 1 for updating the inode.
7884 	 */
7885 	trans = btrfs_start_transaction(root, 2);
7886 	if (IS_ERR(trans)) {
7887 		ret = PTR_ERR(trans);
7888 		goto out;
7889 	}
7890 
7891 	/* Migrate the slack space for the truncate to our reserve */
7892 	ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, &rsv,
7893 				      min_size, false);
7894 	/*
7895 	 * We have reserved 2 metadata units when we started the transaction and
7896 	 * min_size matches 1 unit, so this should never fail, but if it does,
7897 	 * it's not critical we just fail truncation.
7898 	 */
7899 	if (WARN_ON(ret)) {
7900 		btrfs_end_transaction(trans);
7901 		goto out;
7902 	}
7903 
7904 	trans->block_rsv = &rsv;
7905 
7906 	while (1) {
7907 		struct extent_state *cached_state = NULL;
7908 
7909 		btrfs_lock_extent(&inode->io_tree, lock_start, (u64)-1, &cached_state);
7910 		/*
7911 		 * We want to drop from the next block forward in case this new
7912 		 * size is not block aligned since we will be keeping the last
7913 		 * block of the extent just the way it is.
7914 		 */
7915 		btrfs_drop_extent_map_range(inode, i_size_up, (u64)-1, false);
7916 
7917 		ret = btrfs_truncate_inode_items(trans, root, &control);
7918 
7919 		inode_sub_bytes(&inode->vfs_inode, control.sub_bytes);
7920 		btrfs_inode_safe_disk_i_size_write(inode, control.last_size);
7921 
7922 		btrfs_unlock_extent(&inode->io_tree, lock_start, (u64)-1, &cached_state);
7923 
7924 		trans->block_rsv = &fs_info->trans_block_rsv;
7925 		if (ret != -ENOSPC && ret != -EAGAIN)
7926 			break;
7927 
7928 		ret = btrfs_update_inode(trans, inode);
7929 		if (ret)
7930 			break;
7931 
7932 		btrfs_end_transaction(trans);
7933 		btrfs_btree_balance_dirty(fs_info);
7934 
7935 		trans = btrfs_start_transaction(root, 2);
7936 		if (IS_ERR(trans)) {
7937 			ret = PTR_ERR(trans);
7938 			trans = NULL;
7939 			break;
7940 		}
7941 
7942 		btrfs_block_rsv_release(fs_info, &rsv, -1, NULL);
7943 		ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
7944 					      &rsv, min_size, false);
7945 		/*
7946 		 * We have reserved 2 metadata units when we started the
7947 		 * transaction and min_size matches 1 unit, so this should never
7948 		 * fail, but if it does, it's not critical we just fail truncation.
7949 		 */
7950 		if (WARN_ON(ret))
7951 			break;
7952 
7953 		trans->block_rsv = &rsv;
7954 	}
7955 
7956 	/*
7957 	 * We can't call btrfs_truncate_block inside a trans handle as we could
7958 	 * deadlock with freeze, if we got BTRFS_NEED_TRUNCATE_BLOCK then we
7959 	 * know we've truncated everything except the last little bit, and can
7960 	 * do btrfs_truncate_block and then update the disk_i_size.
7961 	 */
7962 	if (ret == BTRFS_NEED_TRUNCATE_BLOCK) {
7963 		btrfs_end_transaction(trans);
7964 		btrfs_btree_balance_dirty(fs_info);
7965 
7966 		ret = btrfs_truncate_block(inode, inode->vfs_inode.i_size,
7967 					   inode->vfs_inode.i_size, (u64)-1);
7968 		if (ret)
7969 			goto out;
7970 		trans = btrfs_start_transaction(root, 1);
7971 		if (IS_ERR(trans)) {
7972 			ret = PTR_ERR(trans);
7973 			goto out;
7974 		}
7975 		btrfs_inode_safe_disk_i_size_write(inode, 0);
7976 	}
7977 
7978 	if (trans) {
7979 		int ret2;
7980 
7981 		trans->block_rsv = &fs_info->trans_block_rsv;
7982 		ret2 = btrfs_update_inode(trans, inode);
7983 		if (ret2 && !ret)
7984 			ret = ret2;
7985 
7986 		ret2 = btrfs_end_transaction(trans);
7987 		if (ret2 && !ret)
7988 			ret = ret2;
7989 		btrfs_btree_balance_dirty(fs_info);
7990 	}
7991 out:
7992 	btrfs_block_rsv_release(fs_info, &rsv, (u64)-1, NULL);
7993 	/*
7994 	 * So if we truncate and then write and fsync we normally would just
7995 	 * write the extents that changed, which is a problem if we need to
7996 	 * first truncate that entire inode.  So set this flag so we write out
7997 	 * all of the extents in the inode to the sync log so we're completely
7998 	 * safe.
7999 	 *
8000 	 * If no extents were dropped or trimmed we don't need to force the next
8001 	 * fsync to truncate all the inode's items from the log and re-log them
8002 	 * all. This means the truncate operation did not change the file size,
8003 	 * or changed it to a smaller size but there was only an implicit hole
8004 	 * between the old i_size and the new i_size, and there were no prealloc
8005 	 * extents beyond i_size to drop.
8006 	 */
8007 	if (control.extents_found > 0)
8008 		btrfs_set_inode_full_sync(inode);
8009 
8010 	return ret;
8011 }
8012 
8013 struct inode *btrfs_new_subvol_inode(struct mnt_idmap *idmap,
8014 				     struct inode *dir)
8015 {
8016 	struct inode *inode;
8017 
8018 	inode = new_inode(dir->i_sb);
8019 	if (inode) {
8020 		/*
8021 		 * Subvolumes don't inherit the sgid bit or the parent's gid if
8022 		 * the parent's sgid bit is set. This is probably a bug.
8023 		 */
8024 		inode_init_owner(idmap, inode, NULL,
8025 				 S_IFDIR | (~current_umask() & S_IRWXUGO));
8026 		inode->i_op = &btrfs_dir_inode_operations;
8027 		inode->i_fop = &btrfs_dir_file_operations;
8028 	}
8029 	return inode;
8030 }
8031 
8032 struct inode *btrfs_alloc_inode(struct super_block *sb)
8033 {
8034 	struct btrfs_fs_info *fs_info = btrfs_sb(sb);
8035 	struct btrfs_inode *ei;
8036 	struct inode *inode;
8037 
8038 	ei = alloc_inode_sb(sb, btrfs_inode_cachep, GFP_KERNEL);
8039 	if (!ei)
8040 		return NULL;
8041 
8042 	ei->root = NULL;
8043 	ei->generation = 0;
8044 	ei->last_trans = 0;
8045 	ei->last_sub_trans = 0;
8046 	ei->logged_trans = 0;
8047 	ei->delalloc_bytes = 0;
8048 	/* new_delalloc_bytes and last_dir_index_offset are in a union. */
8049 	ei->new_delalloc_bytes = 0;
8050 	ei->defrag_bytes = 0;
8051 	ei->disk_i_size = 0;
8052 	ei->flags = 0;
8053 	ei->ro_flags = 0;
8054 	/*
8055 	 * ->index_cnt will be properly initialized later when creating a new
8056 	 * inode (btrfs_create_new_inode()) or when reading an existing inode
8057 	 * from disk (btrfs_read_locked_inode()).
8058 	 */
8059 	ei->csum_bytes = 0;
8060 	ei->dir_index = 0;
8061 	ei->last_unlink_trans = 0;
8062 	ei->last_reflink_trans = 0;
8063 	ei->last_log_commit = 0;
8064 
8065 	spin_lock_init(&ei->lock);
8066 	ei->outstanding_extents = 0;
8067 	if (sb->s_magic != BTRFS_TEST_MAGIC)
8068 		btrfs_init_metadata_block_rsv(fs_info, &ei->block_rsv,
8069 					      BTRFS_BLOCK_RSV_DELALLOC);
8070 	ei->runtime_flags = 0;
8071 	ei->prop_compress = BTRFS_COMPRESS_NONE;
8072 	ei->defrag_compress = BTRFS_COMPRESS_NONE;
8073 
8074 	ei->delayed_node = NULL;
8075 
8076 	ei->i_otime_sec = 0;
8077 	ei->i_otime_nsec = 0;
8078 
8079 	inode = &ei->vfs_inode;
8080 	btrfs_extent_map_tree_init(&ei->extent_tree);
8081 
8082 	/* This io tree sets the valid inode. */
8083 	btrfs_extent_io_tree_init(fs_info, &ei->io_tree, IO_TREE_INODE_IO);
8084 	ei->io_tree.inode = ei;
8085 
8086 	ei->file_extent_tree = NULL;
8087 
8088 	mutex_init(&ei->log_mutex);
8089 	spin_lock_init(&ei->ordered_tree_lock);
8090 	ei->ordered_tree = RB_ROOT;
8091 	ei->ordered_tree_last = NULL;
8092 	INIT_LIST_HEAD(&ei->delalloc_inodes);
8093 	INIT_LIST_HEAD(&ei->delayed_iput);
8094 	init_rwsem(&ei->i_mmap_lock);
8095 
8096 	return inode;
8097 }
8098 
8099 #ifdef CONFIG_BTRFS_FS_RUN_SANITY_TESTS
8100 void btrfs_test_destroy_inode(struct inode *inode)
8101 {
8102 	btrfs_drop_extent_map_range(BTRFS_I(inode), 0, (u64)-1, false);
8103 	kfree(BTRFS_I(inode)->file_extent_tree);
8104 	kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8105 }
8106 #endif
8107 
8108 void btrfs_free_inode(struct inode *inode)
8109 {
8110 	kfree(BTRFS_I(inode)->file_extent_tree);
8111 	kmem_cache_free(btrfs_inode_cachep, BTRFS_I(inode));
8112 }
8113 
8114 void btrfs_destroy_inode(struct inode *vfs_inode)
8115 {
8116 	struct btrfs_ordered_extent *ordered;
8117 	struct btrfs_inode *inode = BTRFS_I(vfs_inode);
8118 	struct btrfs_root *root = inode->root;
8119 	bool freespace_inode;
8120 
8121 	WARN_ON(!hlist_empty(&vfs_inode->i_dentry));
8122 	WARN_ON(vfs_inode->i_data.nrpages);
8123 	WARN_ON(inode->block_rsv.reserved);
8124 	WARN_ON(inode->block_rsv.size);
8125 	WARN_ON(inode->outstanding_extents);
8126 	if (!S_ISDIR(vfs_inode->i_mode)) {
8127 		WARN_ON(inode->delalloc_bytes);
8128 		WARN_ON(inode->new_delalloc_bytes);
8129 		WARN_ON(inode->csum_bytes);
8130 	}
8131 	if (!root || !btrfs_is_data_reloc_root(root))
8132 		WARN_ON(inode->defrag_bytes);
8133 
8134 	/*
8135 	 * This can happen where we create an inode, but somebody else also
8136 	 * created the same inode and we need to destroy the one we already
8137 	 * created.
8138 	 */
8139 	if (!root)
8140 		return;
8141 
8142 	/*
8143 	 * If this is a free space inode do not take the ordered extents lockdep
8144 	 * map.
8145 	 */
8146 	freespace_inode = btrfs_is_free_space_inode(inode);
8147 
8148 	while (1) {
8149 		ordered = btrfs_lookup_first_ordered_extent(inode, (u64)-1);
8150 		if (!ordered)
8151 			break;
8152 		else {
8153 			btrfs_err(root->fs_info,
8154 				  "found ordered extent %llu %llu on inode cleanup",
8155 				  ordered->file_offset, ordered->num_bytes);
8156 
8157 			if (!freespace_inode)
8158 				btrfs_lockdep_acquire(root->fs_info, btrfs_ordered_extent);
8159 
8160 			btrfs_remove_ordered_extent(ordered);
8161 			btrfs_put_ordered_extent(ordered);
8162 			btrfs_put_ordered_extent(ordered);
8163 		}
8164 	}
8165 	btrfs_qgroup_check_reserved_leak(inode);
8166 	btrfs_del_inode_from_root(inode);
8167 	btrfs_drop_extent_map_range(inode, 0, (u64)-1, false);
8168 	btrfs_inode_clear_file_extent_range(inode, 0, (u64)-1);
8169 	btrfs_put_root(inode->root);
8170 }
8171 
8172 int btrfs_drop_inode(struct inode *inode)
8173 {
8174 	struct btrfs_root *root = BTRFS_I(inode)->root;
8175 
8176 	if (root == NULL)
8177 		return 1;
8178 
8179 	/* the snap/subvol tree is on deleting */
8180 	if (btrfs_root_refs(&root->root_item) == 0)
8181 		return 1;
8182 	else
8183 		return inode_generic_drop(inode);
8184 }
8185 
8186 static void init_once(void *foo)
8187 {
8188 	struct btrfs_inode *ei = foo;
8189 
8190 	inode_init_once(&ei->vfs_inode);
8191 }
8192 
8193 void __cold btrfs_destroy_cachep(void)
8194 {
8195 	/*
8196 	 * Make sure all delayed rcu free inodes are flushed before we
8197 	 * destroy cache.
8198 	 */
8199 	rcu_barrier();
8200 	kmem_cache_destroy(btrfs_inode_cachep);
8201 }
8202 
8203 int __init btrfs_init_cachep(void)
8204 {
8205 	btrfs_inode_cachep = kmem_cache_create("btrfs_inode",
8206 			sizeof(struct btrfs_inode), 0,
8207 			SLAB_RECLAIM_ACCOUNT | SLAB_ACCOUNT,
8208 			init_once);
8209 	if (!btrfs_inode_cachep)
8210 		return -ENOMEM;
8211 
8212 	return 0;
8213 }
8214 
8215 static int btrfs_getattr(struct mnt_idmap *idmap,
8216 			 const struct path *path, struct kstat *stat,
8217 			 u32 request_mask, unsigned int flags)
8218 {
8219 	u64 delalloc_bytes;
8220 	u64 inode_bytes;
8221 	struct inode *inode = d_inode(path->dentry);
8222 	u32 blocksize = btrfs_sb(inode->i_sb)->sectorsize;
8223 	u32 bi_flags = BTRFS_I(inode)->flags;
8224 	u32 bi_ro_flags = BTRFS_I(inode)->ro_flags;
8225 
8226 	stat->result_mask |= STATX_BTIME;
8227 	stat->btime.tv_sec = BTRFS_I(inode)->i_otime_sec;
8228 	stat->btime.tv_nsec = BTRFS_I(inode)->i_otime_nsec;
8229 	if (bi_flags & BTRFS_INODE_APPEND)
8230 		stat->attributes |= STATX_ATTR_APPEND;
8231 	if (bi_flags & BTRFS_INODE_COMPRESS)
8232 		stat->attributes |= STATX_ATTR_COMPRESSED;
8233 	if (bi_flags & BTRFS_INODE_IMMUTABLE)
8234 		stat->attributes |= STATX_ATTR_IMMUTABLE;
8235 	if (bi_flags & BTRFS_INODE_NODUMP)
8236 		stat->attributes |= STATX_ATTR_NODUMP;
8237 	if (bi_ro_flags & BTRFS_INODE_RO_VERITY)
8238 		stat->attributes |= STATX_ATTR_VERITY;
8239 
8240 	stat->attributes_mask |= (STATX_ATTR_APPEND |
8241 				  STATX_ATTR_COMPRESSED |
8242 				  STATX_ATTR_IMMUTABLE |
8243 				  STATX_ATTR_NODUMP);
8244 
8245 	generic_fillattr(idmap, request_mask, inode, stat);
8246 	stat->dev = BTRFS_I(inode)->root->anon_dev;
8247 
8248 	stat->subvol = btrfs_root_id(BTRFS_I(inode)->root);
8249 	stat->result_mask |= STATX_SUBVOL;
8250 
8251 	spin_lock(&BTRFS_I(inode)->lock);
8252 	delalloc_bytes = S_ISREG(inode->i_mode) ?
8253 			 BTRFS_I(inode)->new_delalloc_bytes : 0;
8254 	inode_bytes = inode_get_bytes(inode);
8255 	spin_unlock(&BTRFS_I(inode)->lock);
8256 	stat->blocks = (ALIGN(inode_bytes, blocksize) +
8257 			ALIGN(delalloc_bytes, blocksize)) >> SECTOR_SHIFT;
8258 	return 0;
8259 }
8260 
8261 static int btrfs_rename_exchange(struct inode *old_dir,
8262 			      struct dentry *old_dentry,
8263 			      struct inode *new_dir,
8264 			      struct dentry *new_dentry)
8265 {
8266 	struct btrfs_fs_info *fs_info = inode_to_fs_info(old_dir);
8267 	struct btrfs_trans_handle *trans;
8268 	unsigned int trans_num_items;
8269 	struct btrfs_root *root = BTRFS_I(old_dir)->root;
8270 	struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8271 	struct inode *new_inode = new_dentry->d_inode;
8272 	struct inode *old_inode = old_dentry->d_inode;
8273 	struct btrfs_rename_ctx old_rename_ctx;
8274 	struct btrfs_rename_ctx new_rename_ctx;
8275 	u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
8276 	u64 new_ino = btrfs_ino(BTRFS_I(new_inode));
8277 	u64 old_idx = 0;
8278 	u64 new_idx = 0;
8279 	int ret;
8280 	int ret2;
8281 	bool need_abort = false;
8282 	bool logs_pinned = false;
8283 	struct fscrypt_name old_fname, new_fname;
8284 	struct fscrypt_str *old_name, *new_name;
8285 
8286 	/*
8287 	 * For non-subvolumes allow exchange only within one subvolume, in the
8288 	 * same inode namespace. Two subvolumes (represented as directory) can
8289 	 * be exchanged as they're a logical link and have a fixed inode number.
8290 	 */
8291 	if (root != dest &&
8292 	    (old_ino != BTRFS_FIRST_FREE_OBJECTID ||
8293 	     new_ino != BTRFS_FIRST_FREE_OBJECTID))
8294 		return -EXDEV;
8295 
8296 	ret = fscrypt_setup_filename(old_dir, &old_dentry->d_name, 0, &old_fname);
8297 	if (ret)
8298 		return ret;
8299 
8300 	ret = fscrypt_setup_filename(new_dir, &new_dentry->d_name, 0, &new_fname);
8301 	if (ret) {
8302 		fscrypt_free_filename(&old_fname);
8303 		return ret;
8304 	}
8305 
8306 	old_name = &old_fname.disk_name;
8307 	new_name = &new_fname.disk_name;
8308 
8309 	/* close the race window with snapshot create/destroy ioctl */
8310 	if (old_ino == BTRFS_FIRST_FREE_OBJECTID ||
8311 	    new_ino == BTRFS_FIRST_FREE_OBJECTID)
8312 		down_read(&fs_info->subvol_sem);
8313 
8314 	/*
8315 	 * For each inode:
8316 	 * 1 to remove old dir item
8317 	 * 1 to remove old dir index
8318 	 * 1 to add new dir item
8319 	 * 1 to add new dir index
8320 	 * 1 to update parent inode
8321 	 *
8322 	 * If the parents are the same, we only need to account for one
8323 	 */
8324 	trans_num_items = (old_dir == new_dir ? 9 : 10);
8325 	if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8326 		/*
8327 		 * 1 to remove old root ref
8328 		 * 1 to remove old root backref
8329 		 * 1 to add new root ref
8330 		 * 1 to add new root backref
8331 		 */
8332 		trans_num_items += 4;
8333 	} else {
8334 		/*
8335 		 * 1 to update inode item
8336 		 * 1 to remove old inode ref
8337 		 * 1 to add new inode ref
8338 		 */
8339 		trans_num_items += 3;
8340 	}
8341 	if (new_ino == BTRFS_FIRST_FREE_OBJECTID)
8342 		trans_num_items += 4;
8343 	else
8344 		trans_num_items += 3;
8345 	trans = btrfs_start_transaction(root, trans_num_items);
8346 	if (IS_ERR(trans)) {
8347 		ret = PTR_ERR(trans);
8348 		goto out_notrans;
8349 	}
8350 
8351 	if (dest != root) {
8352 		ret = btrfs_record_root_in_trans(trans, dest);
8353 		if (ret)
8354 			goto out_fail;
8355 	}
8356 
8357 	/*
8358 	 * We need to find a free sequence number both in the source and
8359 	 * in the destination directory for the exchange.
8360 	 */
8361 	ret = btrfs_set_inode_index(BTRFS_I(new_dir), &old_idx);
8362 	if (ret)
8363 		goto out_fail;
8364 	ret = btrfs_set_inode_index(BTRFS_I(old_dir), &new_idx);
8365 	if (ret)
8366 		goto out_fail;
8367 
8368 	BTRFS_I(old_inode)->dir_index = 0ULL;
8369 	BTRFS_I(new_inode)->dir_index = 0ULL;
8370 
8371 	/* Reference for the source. */
8372 	if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8373 		/* force full log commit if subvolume involved. */
8374 		btrfs_set_log_full_commit(trans);
8375 	} else {
8376 		ret = btrfs_insert_inode_ref(trans, dest, new_name, old_ino,
8377 					     btrfs_ino(BTRFS_I(new_dir)),
8378 					     old_idx);
8379 		if (ret)
8380 			goto out_fail;
8381 		need_abort = true;
8382 	}
8383 
8384 	/* And now for the dest. */
8385 	if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
8386 		/* force full log commit if subvolume involved. */
8387 		btrfs_set_log_full_commit(trans);
8388 	} else {
8389 		ret = btrfs_insert_inode_ref(trans, root, old_name, new_ino,
8390 					     btrfs_ino(BTRFS_I(old_dir)),
8391 					     new_idx);
8392 		if (ret) {
8393 			if (unlikely(need_abort))
8394 				btrfs_abort_transaction(trans, ret);
8395 			goto out_fail;
8396 		}
8397 	}
8398 
8399 	/* Update inode version and ctime/mtime. */
8400 	inode_inc_iversion(old_dir);
8401 	inode_inc_iversion(new_dir);
8402 	inode_inc_iversion(old_inode);
8403 	inode_inc_iversion(new_inode);
8404 	simple_rename_timestamp(old_dir, old_dentry, new_dir, new_dentry);
8405 
8406 	if (old_ino != BTRFS_FIRST_FREE_OBJECTID &&
8407 	    new_ino != BTRFS_FIRST_FREE_OBJECTID) {
8408 		/*
8409 		 * If we are renaming in the same directory (and it's not for
8410 		 * root entries) pin the log early to prevent any concurrent
8411 		 * task from logging the directory after we removed the old
8412 		 * entries and before we add the new entries, otherwise that
8413 		 * task can sync a log without any entry for the inodes we are
8414 		 * renaming and therefore replaying that log, if a power failure
8415 		 * happens after syncing the log, would result in deleting the
8416 		 * inodes.
8417 		 *
8418 		 * If the rename affects two different directories, we want to
8419 		 * make sure the that there's no log commit that contains
8420 		 * updates for only one of the directories but not for the
8421 		 * other.
8422 		 *
8423 		 * If we are renaming an entry for a root, we don't care about
8424 		 * log updates since we called btrfs_set_log_full_commit().
8425 		 */
8426 		btrfs_pin_log_trans(root);
8427 		btrfs_pin_log_trans(dest);
8428 		logs_pinned = true;
8429 	}
8430 
8431 	if (old_dentry->d_parent != new_dentry->d_parent) {
8432 		btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
8433 					BTRFS_I(old_inode), true);
8434 		btrfs_record_unlink_dir(trans, BTRFS_I(new_dir),
8435 					BTRFS_I(new_inode), true);
8436 	}
8437 
8438 	/* src is a subvolume */
8439 	if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8440 		ret = btrfs_unlink_subvol(trans, BTRFS_I(old_dir), old_dentry);
8441 		if (unlikely(ret)) {
8442 			btrfs_abort_transaction(trans, ret);
8443 			goto out_fail;
8444 		}
8445 	} else { /* src is an inode */
8446 		ret = __btrfs_unlink_inode(trans, BTRFS_I(old_dir),
8447 					   BTRFS_I(old_dentry->d_inode),
8448 					   old_name, &old_rename_ctx);
8449 		if (unlikely(ret)) {
8450 			btrfs_abort_transaction(trans, ret);
8451 			goto out_fail;
8452 		}
8453 		ret = btrfs_update_inode(trans, BTRFS_I(old_inode));
8454 		if (unlikely(ret)) {
8455 			btrfs_abort_transaction(trans, ret);
8456 			goto out_fail;
8457 		}
8458 	}
8459 
8460 	/* dest is a subvolume */
8461 	if (new_ino == BTRFS_FIRST_FREE_OBJECTID) {
8462 		ret = btrfs_unlink_subvol(trans, BTRFS_I(new_dir), new_dentry);
8463 		if (unlikely(ret)) {
8464 			btrfs_abort_transaction(trans, ret);
8465 			goto out_fail;
8466 		}
8467 	} else { /* dest is an inode */
8468 		ret = __btrfs_unlink_inode(trans, BTRFS_I(new_dir),
8469 					   BTRFS_I(new_dentry->d_inode),
8470 					   new_name, &new_rename_ctx);
8471 		if (unlikely(ret)) {
8472 			btrfs_abort_transaction(trans, ret);
8473 			goto out_fail;
8474 		}
8475 		ret = btrfs_update_inode(trans, BTRFS_I(new_inode));
8476 		if (unlikely(ret)) {
8477 			btrfs_abort_transaction(trans, ret);
8478 			goto out_fail;
8479 		}
8480 	}
8481 
8482 	ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
8483 			     new_name, false, old_idx);
8484 	if (unlikely(ret)) {
8485 		btrfs_abort_transaction(trans, ret);
8486 		goto out_fail;
8487 	}
8488 
8489 	ret = btrfs_add_link(trans, BTRFS_I(old_dir), BTRFS_I(new_inode),
8490 			     old_name, false, new_idx);
8491 	if (unlikely(ret)) {
8492 		btrfs_abort_transaction(trans, ret);
8493 		goto out_fail;
8494 	}
8495 
8496 	if (old_inode->i_nlink == 1)
8497 		BTRFS_I(old_inode)->dir_index = old_idx;
8498 	if (new_inode->i_nlink == 1)
8499 		BTRFS_I(new_inode)->dir_index = new_idx;
8500 
8501 	/*
8502 	 * Do the log updates for all inodes.
8503 	 *
8504 	 * If either entry is for a root we don't need to update the logs since
8505 	 * we've called btrfs_set_log_full_commit() before.
8506 	 */
8507 	if (logs_pinned) {
8508 		btrfs_log_new_name(trans, old_dentry, BTRFS_I(old_dir),
8509 				   old_rename_ctx.index, new_dentry->d_parent);
8510 		btrfs_log_new_name(trans, new_dentry, BTRFS_I(new_dir),
8511 				   new_rename_ctx.index, old_dentry->d_parent);
8512 	}
8513 
8514 out_fail:
8515 	if (logs_pinned) {
8516 		btrfs_end_log_trans(root);
8517 		btrfs_end_log_trans(dest);
8518 	}
8519 	ret2 = btrfs_end_transaction(trans);
8520 	ret = ret ? ret : ret2;
8521 out_notrans:
8522 	if (new_ino == BTRFS_FIRST_FREE_OBJECTID ||
8523 	    old_ino == BTRFS_FIRST_FREE_OBJECTID)
8524 		up_read(&fs_info->subvol_sem);
8525 
8526 	fscrypt_free_filename(&new_fname);
8527 	fscrypt_free_filename(&old_fname);
8528 	return ret;
8529 }
8530 
8531 static struct inode *new_whiteout_inode(struct mnt_idmap *idmap,
8532 					struct inode *dir)
8533 {
8534 	struct inode *inode;
8535 
8536 	inode = new_inode(dir->i_sb);
8537 	if (inode) {
8538 		inode_init_owner(idmap, inode, dir,
8539 				 S_IFCHR | WHITEOUT_MODE);
8540 		inode->i_op = &btrfs_special_inode_operations;
8541 		init_special_inode(inode, inode->i_mode, WHITEOUT_DEV);
8542 	}
8543 	return inode;
8544 }
8545 
8546 static int btrfs_rename(struct mnt_idmap *idmap,
8547 			struct inode *old_dir, struct dentry *old_dentry,
8548 			struct inode *new_dir, struct dentry *new_dentry,
8549 			unsigned int flags)
8550 {
8551 	struct btrfs_fs_info *fs_info = inode_to_fs_info(old_dir);
8552 	struct btrfs_new_inode_args whiteout_args = {
8553 		.dir = old_dir,
8554 		.dentry = old_dentry,
8555 	};
8556 	struct btrfs_trans_handle *trans;
8557 	unsigned int trans_num_items;
8558 	struct btrfs_root *root = BTRFS_I(old_dir)->root;
8559 	struct btrfs_root *dest = BTRFS_I(new_dir)->root;
8560 	struct inode *new_inode = d_inode(new_dentry);
8561 	struct inode *old_inode = d_inode(old_dentry);
8562 	struct btrfs_rename_ctx rename_ctx;
8563 	u64 index = 0;
8564 	int ret;
8565 	int ret2;
8566 	u64 old_ino = btrfs_ino(BTRFS_I(old_inode));
8567 	struct fscrypt_name old_fname, new_fname;
8568 	bool logs_pinned = false;
8569 
8570 	if (btrfs_ino(BTRFS_I(new_dir)) == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)
8571 		return -EPERM;
8572 
8573 	/* we only allow rename subvolume link between subvolumes */
8574 	if (old_ino != BTRFS_FIRST_FREE_OBJECTID && root != dest)
8575 		return -EXDEV;
8576 
8577 	if (old_ino == BTRFS_EMPTY_SUBVOL_DIR_OBJECTID ||
8578 	    (new_inode && btrfs_ino(BTRFS_I(new_inode)) == BTRFS_FIRST_FREE_OBJECTID))
8579 		return -ENOTEMPTY;
8580 
8581 	if (S_ISDIR(old_inode->i_mode) && new_inode &&
8582 	    new_inode->i_size > BTRFS_EMPTY_DIR_SIZE)
8583 		return -ENOTEMPTY;
8584 
8585 	ret = fscrypt_setup_filename(old_dir, &old_dentry->d_name, 0, &old_fname);
8586 	if (ret)
8587 		return ret;
8588 
8589 	ret = fscrypt_setup_filename(new_dir, &new_dentry->d_name, 0, &new_fname);
8590 	if (ret) {
8591 		fscrypt_free_filename(&old_fname);
8592 		return ret;
8593 	}
8594 
8595 	/* check for collisions, even if the  name isn't there */
8596 	ret = btrfs_check_dir_item_collision(dest, new_dir->i_ino, &new_fname.disk_name);
8597 	if (ret) {
8598 		if (ret == -EEXIST) {
8599 			/* we shouldn't get
8600 			 * eexist without a new_inode */
8601 			if (WARN_ON(!new_inode)) {
8602 				goto out_fscrypt_names;
8603 			}
8604 		} else {
8605 			/* maybe -EOVERFLOW */
8606 			goto out_fscrypt_names;
8607 		}
8608 	}
8609 	ret = 0;
8610 
8611 	/*
8612 	 * we're using rename to replace one file with another.  Start IO on it
8613 	 * now so  we don't add too much work to the end of the transaction
8614 	 */
8615 	if (new_inode && S_ISREG(old_inode->i_mode) && new_inode->i_size)
8616 		filemap_flush(old_inode->i_mapping);
8617 
8618 	if (flags & RENAME_WHITEOUT) {
8619 		whiteout_args.inode = new_whiteout_inode(idmap, old_dir);
8620 		if (!whiteout_args.inode) {
8621 			ret = -ENOMEM;
8622 			goto out_fscrypt_names;
8623 		}
8624 		ret = btrfs_new_inode_prepare(&whiteout_args, &trans_num_items);
8625 		if (ret)
8626 			goto out_whiteout_inode;
8627 	} else {
8628 		/* 1 to update the old parent inode. */
8629 		trans_num_items = 1;
8630 	}
8631 
8632 	if (old_ino == BTRFS_FIRST_FREE_OBJECTID) {
8633 		/* Close the race window with snapshot create/destroy ioctl */
8634 		down_read(&fs_info->subvol_sem);
8635 		/*
8636 		 * 1 to remove old root ref
8637 		 * 1 to remove old root backref
8638 		 * 1 to add new root ref
8639 		 * 1 to add new root backref
8640 		 */
8641 		trans_num_items += 4;
8642 	} else {
8643 		/*
8644 		 * 1 to update inode
8645 		 * 1 to remove old inode ref
8646 		 * 1 to add new inode ref
8647 		 */
8648 		trans_num_items += 3;
8649 	}
8650 	/*
8651 	 * 1 to remove old dir item
8652 	 * 1 to remove old dir index
8653 	 * 1 to add new dir item
8654 	 * 1 to add new dir index
8655 	 */
8656 	trans_num_items += 4;
8657 	/* 1 to update new parent inode if it's not the same as the old parent */
8658 	if (new_dir != old_dir)
8659 		trans_num_items++;
8660 	if (new_inode) {
8661 		/*
8662 		 * 1 to update inode
8663 		 * 1 to remove inode ref
8664 		 * 1 to remove dir item
8665 		 * 1 to remove dir index
8666 		 * 1 to possibly add orphan item
8667 		 */
8668 		trans_num_items += 5;
8669 	}
8670 	trans = btrfs_start_transaction(root, trans_num_items);
8671 	if (IS_ERR(trans)) {
8672 		ret = PTR_ERR(trans);
8673 		goto out_notrans;
8674 	}
8675 
8676 	if (dest != root) {
8677 		ret = btrfs_record_root_in_trans(trans, dest);
8678 		if (ret)
8679 			goto out_fail;
8680 	}
8681 
8682 	ret = btrfs_set_inode_index(BTRFS_I(new_dir), &index);
8683 	if (ret)
8684 		goto out_fail;
8685 
8686 	BTRFS_I(old_inode)->dir_index = 0ULL;
8687 	if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8688 		/* force full log commit if subvolume involved. */
8689 		btrfs_set_log_full_commit(trans);
8690 	} else {
8691 		ret = btrfs_insert_inode_ref(trans, dest, &new_fname.disk_name,
8692 					     old_ino, btrfs_ino(BTRFS_I(new_dir)),
8693 					     index);
8694 		if (ret)
8695 			goto out_fail;
8696 	}
8697 
8698 	inode_inc_iversion(old_dir);
8699 	inode_inc_iversion(new_dir);
8700 	inode_inc_iversion(old_inode);
8701 	simple_rename_timestamp(old_dir, old_dentry, new_dir, new_dentry);
8702 
8703 	if (old_ino != BTRFS_FIRST_FREE_OBJECTID) {
8704 		/*
8705 		 * If we are renaming in the same directory (and it's not a
8706 		 * root entry) pin the log to prevent any concurrent task from
8707 		 * logging the directory after we removed the old entry and
8708 		 * before we add the new entry, otherwise that task can sync
8709 		 * a log without any entry for the inode we are renaming and
8710 		 * therefore replaying that log, if a power failure happens
8711 		 * after syncing the log, would result in deleting the inode.
8712 		 *
8713 		 * If the rename affects two different directories, we want to
8714 		 * make sure the that there's no log commit that contains
8715 		 * updates for only one of the directories but not for the
8716 		 * other.
8717 		 *
8718 		 * If we are renaming an entry for a root, we don't care about
8719 		 * log updates since we called btrfs_set_log_full_commit().
8720 		 */
8721 		btrfs_pin_log_trans(root);
8722 		btrfs_pin_log_trans(dest);
8723 		logs_pinned = true;
8724 	}
8725 
8726 	if (old_dentry->d_parent != new_dentry->d_parent)
8727 		btrfs_record_unlink_dir(trans, BTRFS_I(old_dir),
8728 					BTRFS_I(old_inode), true);
8729 
8730 	if (unlikely(old_ino == BTRFS_FIRST_FREE_OBJECTID)) {
8731 		ret = btrfs_unlink_subvol(trans, BTRFS_I(old_dir), old_dentry);
8732 		if (unlikely(ret)) {
8733 			btrfs_abort_transaction(trans, ret);
8734 			goto out_fail;
8735 		}
8736 	} else {
8737 		ret = __btrfs_unlink_inode(trans, BTRFS_I(old_dir),
8738 					   BTRFS_I(d_inode(old_dentry)),
8739 					   &old_fname.disk_name, &rename_ctx);
8740 		if (unlikely(ret)) {
8741 			btrfs_abort_transaction(trans, ret);
8742 			goto out_fail;
8743 		}
8744 		ret = btrfs_update_inode(trans, BTRFS_I(old_inode));
8745 		if (unlikely(ret)) {
8746 			btrfs_abort_transaction(trans, ret);
8747 			goto out_fail;
8748 		}
8749 	}
8750 
8751 	if (new_inode) {
8752 		inode_inc_iversion(new_inode);
8753 		if (unlikely(btrfs_ino(BTRFS_I(new_inode)) ==
8754 			     BTRFS_EMPTY_SUBVOL_DIR_OBJECTID)) {
8755 			ret = btrfs_unlink_subvol(trans, BTRFS_I(new_dir), new_dentry);
8756 			if (unlikely(ret)) {
8757 				btrfs_abort_transaction(trans, ret);
8758 				goto out_fail;
8759 			}
8760 			BUG_ON(new_inode->i_nlink == 0);
8761 		} else {
8762 			ret = btrfs_unlink_inode(trans, BTRFS_I(new_dir),
8763 						 BTRFS_I(d_inode(new_dentry)),
8764 						 &new_fname.disk_name);
8765 			if (unlikely(ret)) {
8766 				btrfs_abort_transaction(trans, ret);
8767 				goto out_fail;
8768 			}
8769 		}
8770 		if (new_inode->i_nlink == 0) {
8771 			ret = btrfs_orphan_add(trans,
8772 					BTRFS_I(d_inode(new_dentry)));
8773 			if (unlikely(ret)) {
8774 				btrfs_abort_transaction(trans, ret);
8775 				goto out_fail;
8776 			}
8777 		}
8778 	}
8779 
8780 	ret = btrfs_add_link(trans, BTRFS_I(new_dir), BTRFS_I(old_inode),
8781 			     &new_fname.disk_name, false, index);
8782 	if (unlikely(ret)) {
8783 		btrfs_abort_transaction(trans, ret);
8784 		goto out_fail;
8785 	}
8786 
8787 	if (old_inode->i_nlink == 1)
8788 		BTRFS_I(old_inode)->dir_index = index;
8789 
8790 	if (logs_pinned)
8791 		btrfs_log_new_name(trans, old_dentry, BTRFS_I(old_dir),
8792 				   rename_ctx.index, new_dentry->d_parent);
8793 
8794 	if (flags & RENAME_WHITEOUT) {
8795 		ret = btrfs_create_new_inode(trans, &whiteout_args);
8796 		if (unlikely(ret)) {
8797 			btrfs_abort_transaction(trans, ret);
8798 			goto out_fail;
8799 		} else {
8800 			unlock_new_inode(whiteout_args.inode);
8801 			iput(whiteout_args.inode);
8802 			whiteout_args.inode = NULL;
8803 		}
8804 	}
8805 out_fail:
8806 	if (logs_pinned) {
8807 		btrfs_end_log_trans(root);
8808 		btrfs_end_log_trans(dest);
8809 	}
8810 	ret2 = btrfs_end_transaction(trans);
8811 	ret = ret ? ret : ret2;
8812 out_notrans:
8813 	if (old_ino == BTRFS_FIRST_FREE_OBJECTID)
8814 		up_read(&fs_info->subvol_sem);
8815 	if (flags & RENAME_WHITEOUT)
8816 		btrfs_new_inode_args_destroy(&whiteout_args);
8817 out_whiteout_inode:
8818 	if (flags & RENAME_WHITEOUT)
8819 		iput(whiteout_args.inode);
8820 out_fscrypt_names:
8821 	fscrypt_free_filename(&old_fname);
8822 	fscrypt_free_filename(&new_fname);
8823 	return ret;
8824 }
8825 
8826 static int btrfs_rename2(struct mnt_idmap *idmap, struct inode *old_dir,
8827 			 struct dentry *old_dentry, struct inode *new_dir,
8828 			 struct dentry *new_dentry, unsigned int flags)
8829 {
8830 	int ret;
8831 
8832 	if (flags & ~(RENAME_NOREPLACE | RENAME_EXCHANGE | RENAME_WHITEOUT))
8833 		return -EINVAL;
8834 
8835 	if (flags & RENAME_EXCHANGE)
8836 		ret = btrfs_rename_exchange(old_dir, old_dentry, new_dir,
8837 					    new_dentry);
8838 	else
8839 		ret = btrfs_rename(idmap, old_dir, old_dentry, new_dir,
8840 				   new_dentry, flags);
8841 
8842 	btrfs_btree_balance_dirty(BTRFS_I(new_dir)->root->fs_info);
8843 
8844 	return ret;
8845 }
8846 
8847 struct btrfs_delalloc_work {
8848 	struct inode *inode;
8849 	struct completion completion;
8850 	struct list_head list;
8851 	struct btrfs_work work;
8852 };
8853 
8854 static void btrfs_run_delalloc_work(struct btrfs_work *work)
8855 {
8856 	struct btrfs_delalloc_work *delalloc_work;
8857 	struct inode *inode;
8858 
8859 	delalloc_work = container_of(work, struct btrfs_delalloc_work,
8860 				     work);
8861 	inode = delalloc_work->inode;
8862 	filemap_flush(inode->i_mapping);
8863 	if (test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
8864 				&BTRFS_I(inode)->runtime_flags))
8865 		filemap_flush(inode->i_mapping);
8866 
8867 	iput(inode);
8868 	complete(&delalloc_work->completion);
8869 }
8870 
8871 static struct btrfs_delalloc_work *btrfs_alloc_delalloc_work(struct inode *inode)
8872 {
8873 	struct btrfs_delalloc_work *work;
8874 
8875 	work = kmalloc_obj(*work, GFP_NOFS);
8876 	if (!work)
8877 		return NULL;
8878 
8879 	init_completion(&work->completion);
8880 	INIT_LIST_HEAD(&work->list);
8881 	work->inode = inode;
8882 	btrfs_init_work(&work->work, btrfs_run_delalloc_work, NULL);
8883 
8884 	return work;
8885 }
8886 
8887 /*
8888  * some fairly slow code that needs optimization. This walks the list
8889  * of all the inodes with pending delalloc and forces them to disk.
8890  */
8891 static int start_delalloc_inodes(struct btrfs_root *root, long *nr_to_write,
8892 				 bool snapshot, bool in_reclaim_context)
8893 {
8894 	struct btrfs_delalloc_work *work, *next;
8895 	LIST_HEAD(works);
8896 	LIST_HEAD(splice);
8897 	int ret = 0;
8898 
8899 	mutex_lock(&root->delalloc_mutex);
8900 	spin_lock(&root->delalloc_lock);
8901 	list_splice_init(&root->delalloc_inodes, &splice);
8902 	while (!list_empty(&splice)) {
8903 		struct btrfs_inode *inode;
8904 		struct inode *tmp_inode;
8905 
8906 		inode = list_first_entry(&splice, struct btrfs_inode, delalloc_inodes);
8907 
8908 		list_move_tail(&inode->delalloc_inodes, &root->delalloc_inodes);
8909 
8910 		if (in_reclaim_context &&
8911 		    test_bit(BTRFS_INODE_NO_DELALLOC_FLUSH, &inode->runtime_flags))
8912 			continue;
8913 
8914 		tmp_inode = igrab(&inode->vfs_inode);
8915 		if (!tmp_inode) {
8916 			cond_resched_lock(&root->delalloc_lock);
8917 			continue;
8918 		}
8919 		spin_unlock(&root->delalloc_lock);
8920 
8921 		if (snapshot)
8922 			set_bit(BTRFS_INODE_SNAPSHOT_FLUSH, &inode->runtime_flags);
8923 		if (nr_to_write == NULL) {
8924 			work = btrfs_alloc_delalloc_work(tmp_inode);
8925 			if (!work) {
8926 				iput(tmp_inode);
8927 				ret = -ENOMEM;
8928 				goto out;
8929 			}
8930 			list_add_tail(&work->list, &works);
8931 			btrfs_queue_work(root->fs_info->flush_workers,
8932 					 &work->work);
8933 		} else {
8934 			ret = filemap_flush_nr(tmp_inode->i_mapping,
8935 					nr_to_write);
8936 			btrfs_add_delayed_iput(inode);
8937 
8938 			if (ret || *nr_to_write <= 0)
8939 				goto out;
8940 		}
8941 		cond_resched();
8942 		spin_lock(&root->delalloc_lock);
8943 	}
8944 	spin_unlock(&root->delalloc_lock);
8945 
8946 out:
8947 	list_for_each_entry_safe(work, next, &works, list) {
8948 		list_del_init(&work->list);
8949 		wait_for_completion(&work->completion);
8950 		kfree(work);
8951 	}
8952 
8953 	if (!list_empty(&splice)) {
8954 		spin_lock(&root->delalloc_lock);
8955 		list_splice_tail(&splice, &root->delalloc_inodes);
8956 		spin_unlock(&root->delalloc_lock);
8957 	}
8958 	mutex_unlock(&root->delalloc_mutex);
8959 	return ret;
8960 }
8961 
8962 int btrfs_start_delalloc_snapshot(struct btrfs_root *root, bool in_reclaim_context)
8963 {
8964 	struct btrfs_fs_info *fs_info = root->fs_info;
8965 
8966 	if (unlikely(BTRFS_FS_ERROR(fs_info)))
8967 		return -EROFS;
8968 	return start_delalloc_inodes(root, NULL, true, in_reclaim_context);
8969 }
8970 
8971 int btrfs_start_delalloc_roots(struct btrfs_fs_info *fs_info, long nr,
8972 			       bool in_reclaim_context)
8973 {
8974 	long *nr_to_write = nr == LONG_MAX ? NULL : &nr;
8975 	struct btrfs_root *root;
8976 	LIST_HEAD(splice);
8977 	int ret;
8978 
8979 	if (unlikely(BTRFS_FS_ERROR(fs_info)))
8980 		return -EROFS;
8981 
8982 	mutex_lock(&fs_info->delalloc_root_mutex);
8983 	spin_lock(&fs_info->delalloc_root_lock);
8984 	list_splice_init(&fs_info->delalloc_roots, &splice);
8985 	while (!list_empty(&splice)) {
8986 		root = list_first_entry(&splice, struct btrfs_root,
8987 					delalloc_root);
8988 		root = btrfs_grab_root(root);
8989 		BUG_ON(!root);
8990 		list_move_tail(&root->delalloc_root,
8991 			       &fs_info->delalloc_roots);
8992 		spin_unlock(&fs_info->delalloc_root_lock);
8993 
8994 		ret = start_delalloc_inodes(root, nr_to_write, false,
8995 				in_reclaim_context);
8996 		btrfs_put_root(root);
8997 		if (ret < 0 || nr <= 0)
8998 			goto out;
8999 		spin_lock(&fs_info->delalloc_root_lock);
9000 	}
9001 	spin_unlock(&fs_info->delalloc_root_lock);
9002 
9003 	ret = 0;
9004 out:
9005 	if (!list_empty(&splice)) {
9006 		spin_lock(&fs_info->delalloc_root_lock);
9007 		list_splice_tail(&splice, &fs_info->delalloc_roots);
9008 		spin_unlock(&fs_info->delalloc_root_lock);
9009 	}
9010 	mutex_unlock(&fs_info->delalloc_root_mutex);
9011 	return ret;
9012 }
9013 
9014 static int btrfs_symlink(struct mnt_idmap *idmap, struct inode *dir,
9015 			 struct dentry *dentry, const char *symname)
9016 {
9017 	struct btrfs_fs_info *fs_info = inode_to_fs_info(dir);
9018 	struct btrfs_trans_handle *trans;
9019 	struct btrfs_root *root = BTRFS_I(dir)->root;
9020 	struct btrfs_path *path;
9021 	struct btrfs_key key;
9022 	struct inode *inode;
9023 	struct btrfs_new_inode_args new_inode_args = {
9024 		.dir = dir,
9025 		.dentry = dentry,
9026 	};
9027 	unsigned int trans_num_items;
9028 	int ret;
9029 	int name_len;
9030 	int datasize;
9031 	unsigned long ptr;
9032 	struct btrfs_file_extent_item *ei;
9033 	struct extent_buffer *leaf;
9034 
9035 	name_len = strlen(symname);
9036 	/*
9037 	 * Symlinks utilize uncompressed inline extent data, which should not
9038 	 * reach block size.
9039 	 */
9040 	if (name_len > BTRFS_MAX_INLINE_DATA_SIZE(fs_info) ||
9041 	    name_len >= fs_info->sectorsize)
9042 		return -ENAMETOOLONG;
9043 
9044 	inode = new_inode(dir->i_sb);
9045 	if (!inode)
9046 		return -ENOMEM;
9047 	inode_init_owner(idmap, inode, dir, S_IFLNK | S_IRWXUGO);
9048 	inode->i_op = &btrfs_symlink_inode_operations;
9049 	inode_nohighmem(inode);
9050 	inode->i_mapping->a_ops = &btrfs_aops;
9051 	btrfs_i_size_write(BTRFS_I(inode), name_len);
9052 	inode_set_bytes(inode, name_len);
9053 
9054 	new_inode_args.inode = inode;
9055 	ret = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
9056 	if (ret)
9057 		goto out_inode;
9058 	/* 1 additional item for the inline extent */
9059 	trans_num_items++;
9060 
9061 	trans = btrfs_start_transaction(root, trans_num_items);
9062 	if (IS_ERR(trans)) {
9063 		ret = PTR_ERR(trans);
9064 		goto out_new_inode_args;
9065 	}
9066 
9067 	ret = btrfs_create_new_inode(trans, &new_inode_args);
9068 	if (ret)
9069 		goto out;
9070 
9071 	path = btrfs_alloc_path();
9072 	if (unlikely(!path)) {
9073 		ret = -ENOMEM;
9074 		btrfs_abort_transaction(trans, ret);
9075 		discard_new_inode(inode);
9076 		inode = NULL;
9077 		goto out;
9078 	}
9079 	key.objectid = btrfs_ino(BTRFS_I(inode));
9080 	key.type = BTRFS_EXTENT_DATA_KEY;
9081 	key.offset = 0;
9082 	datasize = btrfs_file_extent_calc_inline_size(name_len);
9083 	ret = btrfs_insert_empty_item(trans, root, path, &key, datasize);
9084 	if (unlikely(ret)) {
9085 		btrfs_abort_transaction(trans, ret);
9086 		btrfs_free_path(path);
9087 		discard_new_inode(inode);
9088 		inode = NULL;
9089 		goto out;
9090 	}
9091 	leaf = path->nodes[0];
9092 	ei = btrfs_item_ptr(leaf, path->slots[0],
9093 			    struct btrfs_file_extent_item);
9094 	btrfs_set_file_extent_generation(leaf, ei, trans->transid);
9095 	btrfs_set_file_extent_type(leaf, ei,
9096 				   BTRFS_FILE_EXTENT_INLINE);
9097 	btrfs_set_file_extent_encryption(leaf, ei, 0);
9098 	btrfs_set_file_extent_compression(leaf, ei, 0);
9099 	btrfs_set_file_extent_other_encoding(leaf, ei, 0);
9100 	btrfs_set_file_extent_ram_bytes(leaf, ei, name_len);
9101 
9102 	ptr = btrfs_file_extent_inline_start(ei);
9103 	write_extent_buffer(leaf, symname, ptr, name_len);
9104 	btrfs_free_path(path);
9105 
9106 	d_instantiate_new(dentry, inode);
9107 	ret = 0;
9108 out:
9109 	btrfs_end_transaction(trans);
9110 	btrfs_btree_balance_dirty(fs_info);
9111 out_new_inode_args:
9112 	btrfs_new_inode_args_destroy(&new_inode_args);
9113 out_inode:
9114 	if (ret)
9115 		iput(inode);
9116 	return ret;
9117 }
9118 
9119 static struct btrfs_trans_handle *insert_prealloc_file_extent(
9120 				       struct btrfs_trans_handle *trans_in,
9121 				       struct btrfs_inode *inode,
9122 				       struct btrfs_key *ins,
9123 				       u64 file_offset)
9124 {
9125 	struct btrfs_file_extent_item stack_fi;
9126 	struct btrfs_replace_extent_info extent_info;
9127 	struct btrfs_trans_handle *trans = trans_in;
9128 	struct btrfs_path *path;
9129 	u64 start = ins->objectid;
9130 	u64 len = ins->offset;
9131 	u64 qgroup_released = 0;
9132 	int ret;
9133 
9134 	memset(&stack_fi, 0, sizeof(stack_fi));
9135 
9136 	btrfs_set_stack_file_extent_type(&stack_fi, BTRFS_FILE_EXTENT_PREALLOC);
9137 	btrfs_set_stack_file_extent_disk_bytenr(&stack_fi, start);
9138 	btrfs_set_stack_file_extent_disk_num_bytes(&stack_fi, len);
9139 	btrfs_set_stack_file_extent_num_bytes(&stack_fi, len);
9140 	btrfs_set_stack_file_extent_ram_bytes(&stack_fi, len);
9141 	btrfs_set_stack_file_extent_compression(&stack_fi, BTRFS_COMPRESS_NONE);
9142 	/* Encryption and other encoding is reserved and all 0 */
9143 
9144 	ret = btrfs_qgroup_release_data(inode, file_offset, len, &qgroup_released);
9145 	if (ret < 0)
9146 		return ERR_PTR(ret);
9147 
9148 	if (trans) {
9149 		ret = insert_reserved_file_extent(trans, inode,
9150 						  file_offset, &stack_fi,
9151 						  true, qgroup_released);
9152 		if (ret)
9153 			goto free_qgroup;
9154 		return trans;
9155 	}
9156 
9157 	extent_info.disk_offset = start;
9158 	extent_info.disk_len = len;
9159 	extent_info.data_offset = 0;
9160 	extent_info.data_len = len;
9161 	extent_info.file_offset = file_offset;
9162 	extent_info.extent_buf = (char *)&stack_fi;
9163 	extent_info.is_new_extent = true;
9164 	extent_info.update_times = true;
9165 	extent_info.qgroup_reserved = qgroup_released;
9166 	extent_info.insertions = 0;
9167 
9168 	path = btrfs_alloc_path();
9169 	if (!path) {
9170 		ret = -ENOMEM;
9171 		goto free_qgroup;
9172 	}
9173 
9174 	ret = btrfs_replace_file_extents(inode, path, file_offset,
9175 				     file_offset + len - 1, &extent_info,
9176 				     &trans);
9177 	btrfs_free_path(path);
9178 	if (ret)
9179 		goto free_qgroup;
9180 	return trans;
9181 
9182 free_qgroup:
9183 	/*
9184 	 * We have released qgroup data range at the beginning of the function,
9185 	 * and normally qgroup_released bytes will be freed when committing
9186 	 * transaction.
9187 	 * But if we error out early, we have to free what we have released
9188 	 * or we leak qgroup data reservation.
9189 	 */
9190 	btrfs_qgroup_free_refroot(inode->root->fs_info,
9191 			btrfs_root_id(inode->root), qgroup_released,
9192 			BTRFS_QGROUP_RSV_DATA);
9193 	return ERR_PTR(ret);
9194 }
9195 
9196 static int __btrfs_prealloc_file_range(struct inode *inode, int mode,
9197 				       u64 start, u64 num_bytes, u64 min_size,
9198 				       loff_t actual_len, u64 *alloc_hint,
9199 				       struct btrfs_trans_handle *trans)
9200 {
9201 	struct btrfs_fs_info *fs_info = inode_to_fs_info(inode);
9202 	struct extent_map *em;
9203 	struct btrfs_root *root = BTRFS_I(inode)->root;
9204 	struct btrfs_key ins;
9205 	u64 cur_offset = start;
9206 	u64 clear_offset = start;
9207 	u64 i_size;
9208 	u64 cur_bytes;
9209 	u64 last_alloc = (u64)-1;
9210 	int ret = 0;
9211 	bool own_trans = true;
9212 	u64 end = start + num_bytes - 1;
9213 
9214 	if (trans)
9215 		own_trans = false;
9216 	while (num_bytes > 0) {
9217 		cur_bytes = min_t(u64, num_bytes, SZ_256M);
9218 		cur_bytes = max(cur_bytes, min_size);
9219 		/*
9220 		 * If we are severely fragmented we could end up with really
9221 		 * small allocations, so if the allocator is returning small
9222 		 * chunks lets make its job easier by only searching for those
9223 		 * sized chunks.
9224 		 */
9225 		cur_bytes = min(cur_bytes, last_alloc);
9226 		ret = btrfs_reserve_extent(root, cur_bytes, cur_bytes,
9227 				min_size, 0, *alloc_hint, &ins, true, false);
9228 		if (ret)
9229 			break;
9230 
9231 		/*
9232 		 * We've reserved this space, and thus converted it from
9233 		 * ->bytes_may_use to ->bytes_reserved.  Any error that happens
9234 		 * from here on out we will only need to clear our reservation
9235 		 * for the remaining unreserved area, so advance our
9236 		 * clear_offset by our extent size.
9237 		 */
9238 		clear_offset += ins.offset;
9239 
9240 		last_alloc = ins.offset;
9241 		trans = insert_prealloc_file_extent(trans, BTRFS_I(inode),
9242 						    &ins, cur_offset);
9243 		/*
9244 		 * Now that we inserted the prealloc extent we can finally
9245 		 * decrement the number of reservations in the block group.
9246 		 * If we did it before, we could race with relocation and have
9247 		 * relocation miss the reserved extent, making it fail later.
9248 		 */
9249 		btrfs_dec_block_group_reservations(fs_info, ins.objectid);
9250 		if (IS_ERR(trans)) {
9251 			ret = PTR_ERR(trans);
9252 			btrfs_free_reserved_extent(fs_info, ins.objectid,
9253 						   ins.offset, false);
9254 			break;
9255 		}
9256 
9257 		em = btrfs_alloc_extent_map();
9258 		if (!em) {
9259 			btrfs_drop_extent_map_range(BTRFS_I(inode), cur_offset,
9260 					    cur_offset + ins.offset - 1, false);
9261 			btrfs_set_inode_full_sync(BTRFS_I(inode));
9262 			goto next;
9263 		}
9264 
9265 		em->start = cur_offset;
9266 		em->len = ins.offset;
9267 		em->disk_bytenr = ins.objectid;
9268 		em->offset = 0;
9269 		em->disk_num_bytes = ins.offset;
9270 		em->ram_bytes = ins.offset;
9271 		em->flags |= EXTENT_FLAG_PREALLOC;
9272 		em->generation = trans->transid;
9273 
9274 		ret = btrfs_replace_extent_map_range(BTRFS_I(inode), em, true);
9275 		btrfs_free_extent_map(em);
9276 next:
9277 		num_bytes -= ins.offset;
9278 		cur_offset += ins.offset;
9279 		*alloc_hint = ins.objectid + ins.offset;
9280 
9281 		inode_inc_iversion(inode);
9282 		inode_set_ctime_current(inode);
9283 		BTRFS_I(inode)->flags |= BTRFS_INODE_PREALLOC;
9284 		if (!(mode & FALLOC_FL_KEEP_SIZE) &&
9285 		    (actual_len > inode->i_size) &&
9286 		    (cur_offset > inode->i_size)) {
9287 			u64 range_start;
9288 			u64 range_end;
9289 
9290 			if (cur_offset > actual_len)
9291 				i_size = actual_len;
9292 			else
9293 				i_size = cur_offset;
9294 
9295 			/*
9296 			 * Make sure the file_extent_tree covers the entire
9297 			 * range [old_i_size, new_i_size) before we update
9298 			 * disk_i_size. Without this, a previous KEEP_SIZE
9299 			 * prealloc that extended past i_size (and was lost
9300 			 * across umount/mount because file_extent_tree is
9301 			 * only populated up to round_up(i_size) on inode
9302 			 * load) can leave a gap inside this range. That gap
9303 			 * would cause btrfs_inode_safe_disk_i_size_write()
9304 			 * (via find_contiguous_extent_bit() starting at 0)
9305 			 * to truncate disk_i_size to the start of the gap,
9306 			 * making the persisted size smaller than i_size.
9307 			 */
9308 			range_start = round_down(inode->i_size, fs_info->sectorsize);
9309 			range_end = round_up(i_size, fs_info->sectorsize);
9310 			ret = btrfs_inode_set_file_extent_range(BTRFS_I(inode),
9311 					range_start, range_end - range_start);
9312 			if (ret) {
9313 				btrfs_abort_transaction(trans, ret);
9314 				if (own_trans)
9315 					btrfs_end_transaction(trans);
9316 				break;
9317 			}
9318 
9319 			i_size_write(inode, i_size);
9320 			btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
9321 		}
9322 
9323 		ret = btrfs_update_inode(trans, BTRFS_I(inode));
9324 
9325 		if (unlikely(ret)) {
9326 			btrfs_abort_transaction(trans, ret);
9327 			if (own_trans)
9328 				btrfs_end_transaction(trans);
9329 			break;
9330 		}
9331 
9332 		if (own_trans) {
9333 			btrfs_end_transaction(trans);
9334 			trans = NULL;
9335 		}
9336 	}
9337 	if (clear_offset < end)
9338 		btrfs_free_reserved_data_space(BTRFS_I(inode), NULL, clear_offset,
9339 			end - clear_offset + 1);
9340 	return ret;
9341 }
9342 
9343 int btrfs_prealloc_file_range(struct inode *inode, int mode,
9344 			      u64 start, u64 num_bytes, u64 min_size,
9345 			      loff_t actual_len, u64 *alloc_hint)
9346 {
9347 	return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9348 					   min_size, actual_len, alloc_hint,
9349 					   NULL);
9350 }
9351 
9352 int btrfs_prealloc_file_range_trans(struct inode *inode,
9353 				    struct btrfs_trans_handle *trans, int mode,
9354 				    u64 start, u64 num_bytes, u64 min_size,
9355 				    loff_t actual_len, u64 *alloc_hint)
9356 {
9357 	return __btrfs_prealloc_file_range(inode, mode, start, num_bytes,
9358 					   min_size, actual_len, alloc_hint, trans);
9359 }
9360 
9361 /*
9362  * NOTE: in case you are adding MAY_EXEC check for directories:
9363  * we are marking them with IOP_FASTPERM_MAY_EXEC, allowing path lookup to
9364  * elide calls here.
9365  */
9366 static int btrfs_permission(struct mnt_idmap *idmap,
9367 			    struct inode *inode, int mask)
9368 {
9369 	struct btrfs_root *root = BTRFS_I(inode)->root;
9370 	umode_t mode = inode->i_mode;
9371 
9372 	if (mask & MAY_WRITE &&
9373 	    (S_ISREG(mode) || S_ISDIR(mode) || S_ISLNK(mode))) {
9374 		if (btrfs_root_readonly(root))
9375 			return -EROFS;
9376 		if (BTRFS_I(inode)->flags & BTRFS_INODE_READONLY)
9377 			return -EACCES;
9378 	}
9379 	return generic_permission(idmap, inode, mask);
9380 }
9381 
9382 static int btrfs_tmpfile(struct mnt_idmap *idmap, struct inode *dir,
9383 			 struct file *file, umode_t mode)
9384 {
9385 	struct btrfs_fs_info *fs_info = inode_to_fs_info(dir);
9386 	struct btrfs_trans_handle *trans;
9387 	struct btrfs_root *root = BTRFS_I(dir)->root;
9388 	struct inode *inode;
9389 	struct btrfs_new_inode_args new_inode_args = {
9390 		.dir = dir,
9391 		.dentry = file->f_path.dentry,
9392 		.orphan = true,
9393 	};
9394 	unsigned int trans_num_items;
9395 	int ret;
9396 
9397 	inode = new_inode(dir->i_sb);
9398 	if (!inode)
9399 		return -ENOMEM;
9400 	inode_init_owner(idmap, inode, dir, mode);
9401 	inode->i_fop = &btrfs_file_operations;
9402 	inode->i_op = &btrfs_file_inode_operations;
9403 	inode->i_mapping->a_ops = &btrfs_aops;
9404 
9405 	new_inode_args.inode = inode;
9406 	ret = btrfs_new_inode_prepare(&new_inode_args, &trans_num_items);
9407 	if (ret)
9408 		goto out_inode;
9409 
9410 	trans = btrfs_start_transaction(root, trans_num_items);
9411 	if (IS_ERR(trans)) {
9412 		ret = PTR_ERR(trans);
9413 		goto out_new_inode_args;
9414 	}
9415 
9416 	ret = btrfs_create_new_inode(trans, &new_inode_args);
9417 
9418 	/*
9419 	 * We set number of links to 0 in btrfs_create_new_inode(), and here we
9420 	 * set it to 1 because d_tmpfile() will issue a warning if the count is
9421 	 * 0, through:
9422 	 *
9423 	 *    d_tmpfile() -> inode_dec_link_count() -> drop_nlink()
9424 	 */
9425 	set_nlink(inode, 1);
9426 
9427 	if (!ret) {
9428 		d_tmpfile(file, inode);
9429 		unlock_new_inode(inode);
9430 		mark_inode_dirty(inode);
9431 	}
9432 
9433 	btrfs_end_transaction(trans);
9434 	btrfs_btree_balance_dirty(fs_info);
9435 out_new_inode_args:
9436 	btrfs_new_inode_args_destroy(&new_inode_args);
9437 out_inode:
9438 	if (ret)
9439 		iput(inode);
9440 	return finish_open_simple(file, ret);
9441 }
9442 
9443 int btrfs_encoded_io_compression_from_extent(struct btrfs_fs_info *fs_info,
9444 					     int compress_type)
9445 {
9446 	switch (compress_type) {
9447 	case BTRFS_COMPRESS_NONE:
9448 		return BTRFS_ENCODED_IO_COMPRESSION_NONE;
9449 	case BTRFS_COMPRESS_ZLIB:
9450 		return BTRFS_ENCODED_IO_COMPRESSION_ZLIB;
9451 	case BTRFS_COMPRESS_LZO:
9452 		/*
9453 		 * The LZO format depends on the sector size. 64K is the maximum
9454 		 * sector size that we support.
9455 		 */
9456 		if (fs_info->sectorsize < SZ_4K || fs_info->sectorsize > SZ_64K)
9457 			return -EINVAL;
9458 		return BTRFS_ENCODED_IO_COMPRESSION_LZO_4K +
9459 		       (fs_info->sectorsize_bits - 12);
9460 	case BTRFS_COMPRESS_ZSTD:
9461 		return BTRFS_ENCODED_IO_COMPRESSION_ZSTD;
9462 	default:
9463 		return -EUCLEAN;
9464 	}
9465 }
9466 
9467 static ssize_t btrfs_encoded_read_inline(
9468 				struct kiocb *iocb,
9469 				struct iov_iter *iter, u64 start,
9470 				u64 lockend,
9471 				struct extent_state **cached_state,
9472 				u64 extent_start, size_t count,
9473 				struct btrfs_ioctl_encoded_io_args *encoded,
9474 				bool *unlocked)
9475 {
9476 	struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
9477 	struct btrfs_root *root = inode->root;
9478 	struct btrfs_fs_info *fs_info = root->fs_info;
9479 	struct extent_io_tree *io_tree = &inode->io_tree;
9480 	BTRFS_PATH_AUTO_FREE(path);
9481 	struct extent_buffer *leaf;
9482 	struct btrfs_file_extent_item *item;
9483 	u64 ram_bytes;
9484 	unsigned long ptr;
9485 	void *tmp;
9486 	ssize_t ret;
9487 	const bool nowait = (iocb->ki_flags & IOCB_NOWAIT);
9488 
9489 	path = btrfs_alloc_path();
9490 	if (!path)
9491 		return -ENOMEM;
9492 
9493 	path->nowait = nowait;
9494 
9495 	ret = btrfs_lookup_file_extent(NULL, root, path, btrfs_ino(inode),
9496 				       extent_start, 0);
9497 	if (ret) {
9498 		if (unlikely(ret > 0)) {
9499 			/* The extent item disappeared? */
9500 			return -EIO;
9501 		}
9502 		return ret;
9503 	}
9504 	leaf = path->nodes[0];
9505 	item = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
9506 
9507 	ram_bytes = btrfs_file_extent_ram_bytes(leaf, item);
9508 	ptr = btrfs_file_extent_inline_start(item);
9509 
9510 	encoded->len = min_t(u64, extent_start + ram_bytes,
9511 			     inode->vfs_inode.i_size) - iocb->ki_pos;
9512 	ret = btrfs_encoded_io_compression_from_extent(fs_info,
9513 				 btrfs_file_extent_compression(leaf, item));
9514 	if (ret < 0)
9515 		return ret;
9516 	encoded->compression = ret;
9517 	if (encoded->compression) {
9518 		size_t inline_size;
9519 
9520 		inline_size = btrfs_file_extent_inline_item_len(leaf,
9521 								path->slots[0]);
9522 		if (inline_size > count)
9523 			return -ENOBUFS;
9524 
9525 		count = inline_size;
9526 		encoded->unencoded_len = ram_bytes;
9527 		encoded->unencoded_offset = iocb->ki_pos - extent_start;
9528 	} else {
9529 		count = min_t(u64, count, encoded->len);
9530 		encoded->len = count;
9531 		encoded->unencoded_len = count;
9532 		ptr += iocb->ki_pos - extent_start;
9533 	}
9534 
9535 	tmp = kmalloc(count, GFP_NOFS);
9536 	if (!tmp)
9537 		return -ENOMEM;
9538 
9539 	read_extent_buffer(leaf, tmp, ptr, count);
9540 	btrfs_release_path(path);
9541 	btrfs_unlock_extent(io_tree, start, lockend, cached_state);
9542 	btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
9543 	*unlocked = true;
9544 
9545 	ret = copy_to_iter(tmp, count, iter);
9546 	if (ret != count)
9547 		ret = -EFAULT;
9548 	kfree(tmp);
9549 
9550 	return ret;
9551 }
9552 
9553 struct btrfs_encoded_read_private {
9554 	struct completion *sync_reads;
9555 	void *uring_ctx;
9556 	refcount_t pending_refs;
9557 	blk_status_t status;
9558 };
9559 
9560 static void btrfs_encoded_read_endio(struct btrfs_bio *bbio)
9561 {
9562 	struct btrfs_encoded_read_private *priv = bbio->private;
9563 
9564 	if (bbio->bio.bi_status) {
9565 		/*
9566 		 * The memory barrier implied by the refcount_dec_and_test() here
9567 		 * pairs with the memory barrier implied by the refcount_dec_and_test()
9568 		 * in btrfs_encoded_read_regular_fill_pages() to ensure that
9569 		 * this write is observed before the load of status in
9570 		 * btrfs_encoded_read_regular_fill_pages().
9571 		 */
9572 		WRITE_ONCE(priv->status, bbio->bio.bi_status);
9573 	}
9574 	if (refcount_dec_and_test(&priv->pending_refs)) {
9575 		int err = blk_status_to_errno(READ_ONCE(priv->status));
9576 
9577 		if (priv->uring_ctx) {
9578 			btrfs_uring_read_extent_endio(priv->uring_ctx, err);
9579 			kfree(priv);
9580 		} else {
9581 			complete(priv->sync_reads);
9582 		}
9583 	}
9584 	bio_put(&bbio->bio);
9585 }
9586 
9587 int btrfs_encoded_read_regular_fill_pages(struct btrfs_inode *inode,
9588 					  u64 disk_bytenr, u64 disk_io_size,
9589 					  struct page **pages, void *uring_ctx)
9590 {
9591 	struct btrfs_encoded_read_private *priv, sync_priv;
9592 	struct completion sync_reads;
9593 	unsigned long i = 0;
9594 	struct btrfs_bio *bbio;
9595 	int ret;
9596 
9597 	/*
9598 	 * Fast path for synchronous reads which completes in this call, io_uring
9599 	 * needs longer time span.
9600 	 */
9601 	if (uring_ctx) {
9602 		priv = kmalloc_obj(struct btrfs_encoded_read_private, GFP_NOFS);
9603 		if (!priv)
9604 			return -ENOMEM;
9605 	} else {
9606 		priv = &sync_priv;
9607 		init_completion(&sync_reads);
9608 		priv->sync_reads = &sync_reads;
9609 	}
9610 
9611 	refcount_set(&priv->pending_refs, 1);
9612 	priv->status = 0;
9613 	priv->uring_ctx = uring_ctx;
9614 
9615 	bbio = btrfs_bio_alloc(BIO_MAX_VECS, REQ_OP_READ, inode, 0,
9616 			       btrfs_encoded_read_endio, priv);
9617 	bbio->bio.bi_iter.bi_sector = disk_bytenr >> SECTOR_SHIFT;
9618 
9619 	do {
9620 		size_t bytes = min_t(u64, disk_io_size, PAGE_SIZE);
9621 
9622 		if (bio_add_page(&bbio->bio, pages[i], bytes, 0) < bytes) {
9623 			refcount_inc(&priv->pending_refs);
9624 			btrfs_submit_bbio(bbio, 0);
9625 
9626 			bbio = btrfs_bio_alloc(BIO_MAX_VECS, REQ_OP_READ, inode, 0,
9627 					       btrfs_encoded_read_endio, priv);
9628 			bbio->bio.bi_iter.bi_sector = disk_bytenr >> SECTOR_SHIFT;
9629 			continue;
9630 		}
9631 
9632 		i++;
9633 		disk_bytenr += bytes;
9634 		disk_io_size -= bytes;
9635 	} while (disk_io_size);
9636 
9637 	refcount_inc(&priv->pending_refs);
9638 	btrfs_submit_bbio(bbio, 0);
9639 
9640 	if (uring_ctx) {
9641 		if (refcount_dec_and_test(&priv->pending_refs)) {
9642 			ret = blk_status_to_errno(READ_ONCE(priv->status));
9643 			btrfs_uring_read_extent_endio(uring_ctx, ret);
9644 			kfree(priv);
9645 			return ret;
9646 		}
9647 
9648 		return -EIOCBQUEUED;
9649 	} else {
9650 		if (!refcount_dec_and_test(&priv->pending_refs))
9651 			wait_for_completion_io(&sync_reads);
9652 		/* See btrfs_encoded_read_endio() for ordering. */
9653 		return blk_status_to_errno(READ_ONCE(priv->status));
9654 	}
9655 }
9656 
9657 ssize_t btrfs_encoded_read_regular(struct kiocb *iocb, struct iov_iter *iter,
9658 				   u64 start, u64 lockend,
9659 				   struct extent_state **cached_state,
9660 				   u64 disk_bytenr, u64 disk_io_size,
9661 				   size_t count, bool compressed, bool *unlocked)
9662 {
9663 	struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
9664 	struct extent_io_tree *io_tree = &inode->io_tree;
9665 	struct page **pages;
9666 	unsigned long nr_pages, i;
9667 	u64 cur;
9668 	size_t page_offset;
9669 	ssize_t ret;
9670 
9671 	nr_pages = DIV_ROUND_UP(disk_io_size, PAGE_SIZE);
9672 	pages = kzalloc_objs(struct page *, nr_pages, GFP_NOFS);
9673 	if (!pages)
9674 		return -ENOMEM;
9675 	ret = btrfs_alloc_page_array(nr_pages, pages, GFP_NOFS);
9676 	if (ret) {
9677 		ret = -ENOMEM;
9678 		goto out;
9679 		}
9680 
9681 	ret = btrfs_encoded_read_regular_fill_pages(inode, disk_bytenr,
9682 						    disk_io_size, pages, NULL);
9683 	if (ret)
9684 		goto out;
9685 
9686 	btrfs_unlock_extent(io_tree, start, lockend, cached_state);
9687 	btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
9688 	*unlocked = true;
9689 
9690 	if (compressed) {
9691 		i = 0;
9692 		page_offset = 0;
9693 	} else {
9694 		i = (iocb->ki_pos - start) >> PAGE_SHIFT;
9695 		page_offset = (iocb->ki_pos - start) & (PAGE_SIZE - 1);
9696 	}
9697 	cur = 0;
9698 	while (cur < count) {
9699 		size_t bytes = min_t(size_t, count - cur,
9700 				     PAGE_SIZE - page_offset);
9701 
9702 		if (copy_page_to_iter(pages[i], page_offset, bytes,
9703 				      iter) != bytes) {
9704 			ret = -EFAULT;
9705 			goto out;
9706 		}
9707 		i++;
9708 		cur += bytes;
9709 		page_offset = 0;
9710 	}
9711 	ret = count;
9712 out:
9713 	for (i = 0; i < nr_pages; i++) {
9714 		if (pages[i])
9715 			__free_page(pages[i]);
9716 	}
9717 	kfree(pages);
9718 	return ret;
9719 }
9720 
9721 ssize_t btrfs_encoded_read(struct kiocb *iocb, struct iov_iter *iter,
9722 			   struct btrfs_ioctl_encoded_io_args *encoded,
9723 			   struct extent_state **cached_state,
9724 			   u64 *disk_bytenr, u64 *disk_io_size)
9725 {
9726 	struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
9727 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
9728 	struct extent_io_tree *io_tree = &inode->io_tree;
9729 	ssize_t ret;
9730 	size_t count = iov_iter_count(iter);
9731 	u64 start, lockend;
9732 	struct extent_map *em;
9733 	const bool nowait = (iocb->ki_flags & IOCB_NOWAIT);
9734 	bool unlocked = false;
9735 
9736 	file_accessed(iocb->ki_filp);
9737 
9738 	ret = btrfs_inode_lock(inode,
9739 			       BTRFS_ILOCK_SHARED | (nowait ? BTRFS_ILOCK_TRY : 0));
9740 	if (ret)
9741 		return ret;
9742 
9743 	if (iocb->ki_pos >= inode->vfs_inode.i_size) {
9744 		btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
9745 		return 0;
9746 	}
9747 	start = ALIGN_DOWN(iocb->ki_pos, fs_info->sectorsize);
9748 	/*
9749 	 * We don't know how long the extent containing iocb->ki_pos is, but if
9750 	 * it's compressed we know that it won't be longer than this.
9751 	 */
9752 	lockend = start + BTRFS_MAX_UNCOMPRESSED - 1;
9753 
9754 	if (nowait) {
9755 		struct btrfs_ordered_extent *ordered;
9756 
9757 		if (filemap_range_needs_writeback(inode->vfs_inode.i_mapping,
9758 						  start, lockend)) {
9759 			ret = -EAGAIN;
9760 			goto out_unlock_inode;
9761 		}
9762 
9763 		if (!btrfs_try_lock_extent(io_tree, start, lockend, cached_state)) {
9764 			ret = -EAGAIN;
9765 			goto out_unlock_inode;
9766 		}
9767 
9768 		ordered = btrfs_lookup_ordered_range(inode, start,
9769 						     lockend - start + 1);
9770 		if (ordered) {
9771 			btrfs_put_ordered_extent(ordered);
9772 			btrfs_unlock_extent(io_tree, start, lockend, cached_state);
9773 			ret = -EAGAIN;
9774 			goto out_unlock_inode;
9775 		}
9776 	} else {
9777 		for (;;) {
9778 			struct btrfs_ordered_extent *ordered;
9779 
9780 			ret = btrfs_wait_ordered_range(inode, start,
9781 						       lockend - start + 1);
9782 			if (ret)
9783 				goto out_unlock_inode;
9784 
9785 			btrfs_lock_extent(io_tree, start, lockend, cached_state);
9786 			ordered = btrfs_lookup_ordered_range(inode, start,
9787 							     lockend - start + 1);
9788 			if (!ordered)
9789 				break;
9790 			btrfs_put_ordered_extent(ordered);
9791 			btrfs_unlock_extent(io_tree, start, lockend, cached_state);
9792 			cond_resched();
9793 		}
9794 	}
9795 
9796 	em = btrfs_get_extent(inode, NULL, start, lockend - start + 1);
9797 	if (IS_ERR(em)) {
9798 		ret = PTR_ERR(em);
9799 		goto out_unlock_extent;
9800 	}
9801 
9802 	if (em->disk_bytenr == EXTENT_MAP_INLINE) {
9803 		u64 extent_start = em->start;
9804 
9805 		/*
9806 		 * For inline extents we get everything we need out of the
9807 		 * extent item.
9808 		 */
9809 		btrfs_free_extent_map(em);
9810 		em = NULL;
9811 		ret = btrfs_encoded_read_inline(iocb, iter, start, lockend,
9812 						cached_state, extent_start,
9813 						count, encoded, &unlocked);
9814 		goto out_unlock_extent;
9815 	}
9816 
9817 	/*
9818 	 * We only want to return up to EOF even if the extent extends beyond
9819 	 * that.
9820 	 */
9821 	encoded->len = min_t(u64, btrfs_extent_map_end(em),
9822 			     inode->vfs_inode.i_size) - iocb->ki_pos;
9823 	if (em->disk_bytenr == EXTENT_MAP_HOLE ||
9824 	    (em->flags & EXTENT_FLAG_PREALLOC)) {
9825 		*disk_bytenr = EXTENT_MAP_HOLE;
9826 		count = min_t(u64, count, encoded->len);
9827 		encoded->len = count;
9828 		encoded->unencoded_len = count;
9829 	} else if (btrfs_extent_map_is_compressed(em)) {
9830 		*disk_bytenr = em->disk_bytenr;
9831 		/*
9832 		 * Bail if the buffer isn't large enough to return the whole
9833 		 * compressed extent.
9834 		 */
9835 		if (em->disk_num_bytes > count) {
9836 			ret = -ENOBUFS;
9837 			goto out_em;
9838 		}
9839 		*disk_io_size = em->disk_num_bytes;
9840 		count = em->disk_num_bytes;
9841 		encoded->unencoded_len = em->ram_bytes;
9842 		encoded->unencoded_offset = iocb->ki_pos - (em->start - em->offset);
9843 		ret = btrfs_encoded_io_compression_from_extent(fs_info,
9844 					       btrfs_extent_map_compression(em));
9845 		if (ret < 0)
9846 			goto out_em;
9847 		encoded->compression = ret;
9848 	} else {
9849 		*disk_bytenr = btrfs_extent_map_block_start(em) + (start - em->start);
9850 		if (encoded->len > count)
9851 			encoded->len = count;
9852 		/*
9853 		 * Don't read beyond what we locked. This also limits the page
9854 		 * allocations that we'll do.
9855 		 */
9856 		*disk_io_size = min(lockend + 1, iocb->ki_pos + encoded->len) - start;
9857 		count = start + *disk_io_size - iocb->ki_pos;
9858 		encoded->len = count;
9859 		encoded->unencoded_len = count;
9860 		*disk_io_size = ALIGN(*disk_io_size, fs_info->sectorsize);
9861 	}
9862 	btrfs_free_extent_map(em);
9863 	em = NULL;
9864 
9865 	if (*disk_bytenr == EXTENT_MAP_HOLE) {
9866 		btrfs_unlock_extent(io_tree, start, lockend, cached_state);
9867 		btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
9868 		unlocked = true;
9869 		ret = iov_iter_zero(count, iter);
9870 		if (ret != count)
9871 			ret = -EFAULT;
9872 	} else {
9873 		ret = -EIOCBQUEUED;
9874 		goto out_unlock_extent;
9875 	}
9876 
9877 out_em:
9878 	btrfs_free_extent_map(em);
9879 out_unlock_extent:
9880 	/* Leave inode and extent locked if we need to do a read. */
9881 	if (!unlocked && ret != -EIOCBQUEUED)
9882 		btrfs_unlock_extent(io_tree, start, lockend, cached_state);
9883 out_unlock_inode:
9884 	if (!unlocked && ret != -EIOCBQUEUED)
9885 		btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
9886 	return ret;
9887 }
9888 
9889 ssize_t btrfs_do_encoded_write(struct kiocb *iocb, struct iov_iter *from,
9890 			       const struct btrfs_ioctl_encoded_io_args *encoded)
9891 {
9892 	struct btrfs_inode *inode = BTRFS_I(file_inode(iocb->ki_filp));
9893 	struct btrfs_root *root = inode->root;
9894 	struct btrfs_fs_info *fs_info = root->fs_info;
9895 	struct extent_io_tree *io_tree = &inode->io_tree;
9896 	struct extent_changeset *data_reserved = NULL;
9897 	struct extent_state *cached_state = NULL;
9898 	struct btrfs_ordered_extent *ordered;
9899 	struct btrfs_file_extent file_extent;
9900 	struct compressed_bio *cb = NULL;
9901 	int compression;
9902 	size_t orig_count;
9903 	const u32 min_folio_size = btrfs_min_folio_size(fs_info);
9904 	const u32 blocksize = fs_info->sectorsize;
9905 	u64 start, end;
9906 	u64 num_bytes, ram_bytes, disk_num_bytes;
9907 	struct btrfs_key ins;
9908 	bool extent_reserved = false;
9909 	struct extent_map *em;
9910 	ssize_t ret;
9911 
9912 	switch (encoded->compression) {
9913 	case BTRFS_ENCODED_IO_COMPRESSION_ZLIB:
9914 		compression = BTRFS_COMPRESS_ZLIB;
9915 		break;
9916 	case BTRFS_ENCODED_IO_COMPRESSION_ZSTD:
9917 		compression = BTRFS_COMPRESS_ZSTD;
9918 		break;
9919 	case BTRFS_ENCODED_IO_COMPRESSION_LZO_4K:
9920 	case BTRFS_ENCODED_IO_COMPRESSION_LZO_8K:
9921 	case BTRFS_ENCODED_IO_COMPRESSION_LZO_16K:
9922 	case BTRFS_ENCODED_IO_COMPRESSION_LZO_32K:
9923 	case BTRFS_ENCODED_IO_COMPRESSION_LZO_64K:
9924 		/* The sector size must match for LZO. */
9925 		if (encoded->compression -
9926 		    BTRFS_ENCODED_IO_COMPRESSION_LZO_4K + 12 !=
9927 		    fs_info->sectorsize_bits)
9928 			return -EINVAL;
9929 		compression = BTRFS_COMPRESS_LZO;
9930 		break;
9931 	default:
9932 		return -EINVAL;
9933 	}
9934 	if (encoded->encryption != BTRFS_ENCODED_IO_ENCRYPTION_NONE)
9935 		return -EINVAL;
9936 
9937 	/*
9938 	 * Compressed extents should always have checksums, so error out if we
9939 	 * have a NOCOW file or inode was created while mounted with NODATASUM.
9940 	 */
9941 	if (inode->flags & BTRFS_INODE_NODATASUM)
9942 		return -EINVAL;
9943 
9944 	orig_count = iov_iter_count(from);
9945 
9946 	/* The extent size must be sane. */
9947 	if (encoded->unencoded_len > BTRFS_MAX_UNCOMPRESSED ||
9948 	    orig_count > BTRFS_MAX_COMPRESSED || orig_count == 0)
9949 		return -EINVAL;
9950 
9951 	/*
9952 	 * The compressed data must be smaller than the decompressed data.
9953 	 *
9954 	 * It's of course possible for data to compress to larger or the same
9955 	 * size, but the buffered I/O path falls back to no compression for such
9956 	 * data, and we don't want to break any assumptions by creating these
9957 	 * extents.
9958 	 *
9959 	 * Note that this is less strict than the current check we have that the
9960 	 * compressed data must be at least one sector smaller than the
9961 	 * decompressed data. We only want to enforce the weaker requirement
9962 	 * from old kernels that it is at least one byte smaller.
9963 	 */
9964 	if (orig_count >= encoded->unencoded_len)
9965 		return -EINVAL;
9966 
9967 	/* The extent must start on a sector boundary. */
9968 	start = iocb->ki_pos;
9969 	if (!IS_ALIGNED(start, fs_info->sectorsize))
9970 		return -EINVAL;
9971 
9972 	/*
9973 	 * The extent must end on a sector boundary. However, we allow a write
9974 	 * which ends at or extends i_size to have an unaligned length; we round
9975 	 * up the extent size and set i_size to the unaligned end.
9976 	 */
9977 	if (start + encoded->len < inode->vfs_inode.i_size &&
9978 	    !IS_ALIGNED(start + encoded->len, fs_info->sectorsize))
9979 		return -EINVAL;
9980 
9981 	/* Finally, the offset in the unencoded data must be sector-aligned. */
9982 	if (!IS_ALIGNED(encoded->unencoded_offset, fs_info->sectorsize))
9983 		return -EINVAL;
9984 
9985 	num_bytes = ALIGN(encoded->len, fs_info->sectorsize);
9986 	ram_bytes = ALIGN(encoded->unencoded_len, fs_info->sectorsize);
9987 	end = start + num_bytes - 1;
9988 
9989 	/*
9990 	 * If the extent cannot be inline, the compressed data on disk must be
9991 	 * sector-aligned. For convenience, we extend it with zeroes if it
9992 	 * isn't.
9993 	 */
9994 	disk_num_bytes = ALIGN(orig_count, fs_info->sectorsize);
9995 
9996 	cb = btrfs_alloc_compressed_write(inode, start, num_bytes);
9997 	for (int i = 0; i * min_folio_size < disk_num_bytes; i++) {
9998 		struct folio *folio;
9999 		size_t bytes = min(min_folio_size, iov_iter_count(from));
10000 		char *kaddr;
10001 
10002 		folio = btrfs_alloc_compr_folio(fs_info, GFP_NOFS);
10003 		if (!folio) {
10004 			ret = -ENOMEM;
10005 			goto out_cb;
10006 		}
10007 		kaddr = kmap_local_folio(folio, 0);
10008 		ret = copy_from_iter(kaddr, bytes, from);
10009 		kunmap_local(kaddr);
10010 		if (ret != bytes) {
10011 			folio_put(folio);
10012 			ret = -EFAULT;
10013 			goto out_cb;
10014 		}
10015 		if (!IS_ALIGNED(bytes, blocksize))
10016 			folio_zero_range(folio, bytes, round_up(bytes, blocksize) - bytes);
10017 		ret = bio_add_folio(&cb->bbio.bio, folio, round_up(bytes, blocksize), 0);
10018 		if (unlikely(!ret)) {
10019 			folio_put(folio);
10020 			ret = -EINVAL;
10021 			goto out_cb;
10022 		}
10023 	}
10024 	ASSERT(cb->bbio.bio.bi_iter.bi_size == disk_num_bytes);
10025 
10026 	for (;;) {
10027 		ret = btrfs_wait_ordered_range(inode, start, num_bytes);
10028 		if (ret)
10029 			goto out_cb;
10030 		ret = invalidate_inode_pages2_range(inode->vfs_inode.i_mapping,
10031 						    start >> PAGE_SHIFT,
10032 						    end >> PAGE_SHIFT);
10033 		if (ret)
10034 			goto out_cb;
10035 		btrfs_lock_extent(io_tree, start, end, &cached_state);
10036 		ordered = btrfs_lookup_ordered_range(inode, start, num_bytes);
10037 		if (!ordered &&
10038 		    !filemap_range_has_page(inode->vfs_inode.i_mapping, start, end))
10039 			break;
10040 		if (ordered)
10041 			btrfs_put_ordered_extent(ordered);
10042 		btrfs_unlock_extent(io_tree, start, end, &cached_state);
10043 		cond_resched();
10044 	}
10045 
10046 	/*
10047 	 * We don't use the higher-level delalloc space functions because our
10048 	 * num_bytes and disk_num_bytes are different.
10049 	 */
10050 	ret = btrfs_alloc_data_chunk_ondemand(inode, disk_num_bytes);
10051 	if (ret)
10052 		goto out_unlock;
10053 	ret = btrfs_qgroup_reserve_data(inode, &data_reserved, start, num_bytes);
10054 	if (ret)
10055 		goto out_free_data_space;
10056 	ret = btrfs_delalloc_reserve_metadata(inode, num_bytes, disk_num_bytes,
10057 					      false);
10058 	if (ret)
10059 		goto out_qgroup_free_data;
10060 
10061 	/* Try an inline extent first. */
10062 	if (encoded->unencoded_len == encoded->len &&
10063 	    encoded->unencoded_offset == 0 &&
10064 	    can_cow_file_range_inline(inode, start, encoded->len, orig_count)) {
10065 		ret = __cow_file_range_inline(inode, encoded->len,
10066 					      orig_count, compression,
10067 					      bio_first_folio_all(&cb->bbio.bio),
10068 					      true);
10069 		if (ret <= 0) {
10070 			if (ret == 0)
10071 				ret = orig_count;
10072 			goto out_delalloc_release;
10073 		}
10074 	}
10075 
10076 	ret = btrfs_reserve_extent(root, disk_num_bytes, disk_num_bytes,
10077 				   disk_num_bytes, 0, 0, &ins, true, true);
10078 	if (ret)
10079 		goto out_delalloc_release;
10080 	extent_reserved = true;
10081 
10082 	file_extent.disk_bytenr = ins.objectid;
10083 	file_extent.disk_num_bytes = ins.offset;
10084 	file_extent.num_bytes = num_bytes;
10085 	file_extent.ram_bytes = ram_bytes;
10086 	file_extent.offset = encoded->unencoded_offset;
10087 	file_extent.compression = compression;
10088 	em = btrfs_create_io_em(inode, start, &file_extent, BTRFS_ORDERED_COMPRESSED);
10089 	if (IS_ERR(em)) {
10090 		ret = PTR_ERR(em);
10091 		goto out_free_reserved;
10092 	}
10093 	btrfs_free_extent_map(em);
10094 
10095 	ordered = btrfs_alloc_ordered_extent(inode, start, &file_extent,
10096 				       (1U << BTRFS_ORDERED_ENCODED) |
10097 				       (1U << BTRFS_ORDERED_COMPRESSED));
10098 	if (IS_ERR(ordered)) {
10099 		btrfs_drop_extent_map_range(inode, start, end, false);
10100 		ret = PTR_ERR(ordered);
10101 		goto out_free_reserved;
10102 	}
10103 	btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10104 
10105 	if (start + encoded->len > inode->vfs_inode.i_size)
10106 		i_size_write(&inode->vfs_inode, start + encoded->len);
10107 
10108 	btrfs_unlock_extent(io_tree, start, end, &cached_state);
10109 
10110 	btrfs_delalloc_release_extents(inode, num_bytes);
10111 
10112 	btrfs_submit_compressed_write(ordered, cb);
10113 	ret = orig_count;
10114 	goto out;
10115 
10116 out_free_reserved:
10117 	btrfs_dec_block_group_reservations(fs_info, ins.objectid);
10118 	btrfs_free_reserved_extent(fs_info, ins.objectid, ins.offset, true);
10119 out_delalloc_release:
10120 	btrfs_delalloc_release_extents(inode, num_bytes);
10121 	btrfs_delalloc_release_metadata(inode, disk_num_bytes, ret < 0);
10122 out_qgroup_free_data:
10123 	if (ret < 0)
10124 		btrfs_qgroup_free_data(inode, data_reserved, start, num_bytes, NULL);
10125 out_free_data_space:
10126 	/*
10127 	 * If btrfs_reserve_extent() succeeded, then we already decremented
10128 	 * bytes_may_use.
10129 	 */
10130 	if (!extent_reserved)
10131 		btrfs_free_reserved_data_space_noquota(inode, disk_num_bytes);
10132 out_unlock:
10133 	btrfs_unlock_extent(io_tree, start, end, &cached_state);
10134 out_cb:
10135 	if (cb)
10136 		cleanup_compressed_bio(cb);
10137 out:
10138 	extent_changeset_free(data_reserved);
10139 	if (ret >= 0)
10140 		iocb->ki_pos += encoded->len;
10141 	return ret;
10142 }
10143 
10144 #ifdef CONFIG_SWAP
10145 /*
10146  * Add an entry indicating a block group or device which is pinned by a
10147  * swapfile. Returns 0 on success, 1 if there is already an entry for it, or a
10148  * negative errno on failure.
10149  */
10150 static int btrfs_add_swapfile_pin(struct inode *inode, void *ptr,
10151 				  bool is_block_group)
10152 {
10153 	struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10154 	struct btrfs_swapfile_pin *sp, *entry;
10155 	struct rb_node **p;
10156 	struct rb_node *parent = NULL;
10157 
10158 	sp = kmalloc_obj(*sp, GFP_NOFS);
10159 	if (!sp)
10160 		return -ENOMEM;
10161 	sp->ptr = ptr;
10162 	sp->inode = inode;
10163 	sp->is_block_group = is_block_group;
10164 	sp->bg_extent_count = 1;
10165 
10166 	spin_lock(&fs_info->swapfile_pins_lock);
10167 	p = &fs_info->swapfile_pins.rb_node;
10168 	while (*p) {
10169 		parent = *p;
10170 		entry = rb_entry(parent, struct btrfs_swapfile_pin, node);
10171 		if (sp->ptr < entry->ptr ||
10172 		    (sp->ptr == entry->ptr && sp->inode < entry->inode)) {
10173 			p = &(*p)->rb_left;
10174 		} else if (sp->ptr > entry->ptr ||
10175 			   (sp->ptr == entry->ptr && sp->inode > entry->inode)) {
10176 			p = &(*p)->rb_right;
10177 		} else {
10178 			if (is_block_group)
10179 				entry->bg_extent_count++;
10180 			spin_unlock(&fs_info->swapfile_pins_lock);
10181 			kfree(sp);
10182 			return 1;
10183 		}
10184 	}
10185 	rb_link_node(&sp->node, parent, p);
10186 	rb_insert_color(&sp->node, &fs_info->swapfile_pins);
10187 	spin_unlock(&fs_info->swapfile_pins_lock);
10188 	return 0;
10189 }
10190 
10191 /* Free all of the entries pinned by this swapfile. */
10192 static void btrfs_free_swapfile_pins(struct inode *inode)
10193 {
10194 	struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
10195 	struct btrfs_swapfile_pin *sp;
10196 	struct rb_node *node, *next;
10197 
10198 	spin_lock(&fs_info->swapfile_pins_lock);
10199 	node = rb_first(&fs_info->swapfile_pins);
10200 	while (node) {
10201 		next = rb_next(node);
10202 		sp = rb_entry(node, struct btrfs_swapfile_pin, node);
10203 		if (sp->inode == inode) {
10204 			rb_erase(&sp->node, &fs_info->swapfile_pins);
10205 			if (sp->is_block_group) {
10206 				btrfs_dec_block_group_swap_extents(sp->ptr,
10207 							   sp->bg_extent_count);
10208 				btrfs_put_block_group(sp->ptr);
10209 			}
10210 			kfree(sp);
10211 		}
10212 		node = next;
10213 	}
10214 	spin_unlock(&fs_info->swapfile_pins_lock);
10215 }
10216 
10217 struct btrfs_swap_info {
10218 	u64 start;
10219 	u64 block_start;
10220 	u64 block_len;
10221 	u64 lowest_ppage;
10222 	u64 highest_ppage;
10223 	unsigned long nr_pages;
10224 	int nr_extents;
10225 };
10226 
10227 static int btrfs_add_swap_extent(struct swap_info_struct *sis,
10228 				 struct btrfs_swap_info *bsi)
10229 {
10230 	unsigned long nr_pages;
10231 	unsigned long max_pages;
10232 	u64 first_ppage, first_ppage_reported, next_ppage;
10233 	int ret;
10234 
10235 	/*
10236 	 * Our swapfile may have had its size extended after the swap header was
10237 	 * written. In that case activating the swapfile should not go beyond
10238 	 * the max size set in the swap header.
10239 	 */
10240 	if (bsi->nr_pages >= sis->max)
10241 		return 0;
10242 
10243 	max_pages = sis->max - bsi->nr_pages;
10244 	first_ppage = PAGE_ALIGN(bsi->block_start) >> PAGE_SHIFT;
10245 	next_ppage = PAGE_ALIGN_DOWN(bsi->block_start + bsi->block_len) >> PAGE_SHIFT;
10246 
10247 	if (first_ppage >= next_ppage)
10248 		return 0;
10249 	nr_pages = next_ppage - first_ppage;
10250 	nr_pages = min(nr_pages, max_pages);
10251 
10252 	first_ppage_reported = first_ppage;
10253 	if (bsi->start == 0)
10254 		first_ppage_reported++;
10255 	if (bsi->lowest_ppage > first_ppage_reported)
10256 		bsi->lowest_ppage = first_ppage_reported;
10257 	if (bsi->highest_ppage < (next_ppage - 1))
10258 		bsi->highest_ppage = next_ppage - 1;
10259 
10260 	ret = add_swap_extent(sis, bsi->nr_pages, nr_pages, first_ppage);
10261 	if (ret < 0)
10262 		return ret;
10263 	bsi->nr_extents += ret;
10264 	bsi->nr_pages += nr_pages;
10265 	return 0;
10266 }
10267 
10268 static void btrfs_swap_deactivate(struct file *file)
10269 {
10270 	struct inode *inode = file_inode(file);
10271 
10272 	btrfs_free_swapfile_pins(inode);
10273 	atomic_dec(&BTRFS_I(inode)->root->nr_swapfiles);
10274 }
10275 
10276 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10277 			       sector_t *span)
10278 {
10279 	struct inode *inode = file_inode(file);
10280 	struct btrfs_root *root = BTRFS_I(inode)->root;
10281 	struct btrfs_fs_info *fs_info = root->fs_info;
10282 	struct extent_io_tree *io_tree = &BTRFS_I(inode)->io_tree;
10283 	struct extent_state *cached_state = NULL;
10284 	struct btrfs_chunk_map *map = NULL;
10285 	struct btrfs_device *device = NULL;
10286 	struct btrfs_swap_info bsi = {
10287 		.lowest_ppage = (sector_t)-1ULL,
10288 	};
10289 	struct btrfs_backref_share_check_ctx *backref_ctx = NULL;
10290 	struct btrfs_path *path = NULL;
10291 	int ret = 0;
10292 	u64 isize;
10293 	u64 prev_extent_end = 0;
10294 
10295 	/*
10296 	 * Acquire the inode's mmap lock to prevent races with memory mapped
10297 	 * writes, as they could happen after we flush delalloc below and before
10298 	 * we lock the extent range further below. The inode was already locked
10299 	 * up in the call chain.
10300 	 */
10301 	btrfs_assert_inode_locked(BTRFS_I(inode));
10302 	down_write(&BTRFS_I(inode)->i_mmap_lock);
10303 
10304 	/*
10305 	 * If the swap file was just created, make sure delalloc is done. If the
10306 	 * file changes again after this, the user is doing something stupid and
10307 	 * we don't really care.
10308 	 */
10309 	ret = btrfs_wait_ordered_range(BTRFS_I(inode), 0, (u64)-1);
10310 	if (ret)
10311 		goto out_unlock_mmap;
10312 
10313 	/*
10314 	 * The inode is locked, so these flags won't change after we check them.
10315 	 */
10316 	if (BTRFS_I(inode)->flags & BTRFS_INODE_COMPRESS) {
10317 		btrfs_warn(fs_info, "swapfile must not be compressed");
10318 		ret = -EINVAL;
10319 		goto out_unlock_mmap;
10320 	}
10321 	if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATACOW)) {
10322 		btrfs_warn(fs_info, "swapfile must not be copy-on-write");
10323 		ret = -EINVAL;
10324 		goto out_unlock_mmap;
10325 	}
10326 	if (!(BTRFS_I(inode)->flags & BTRFS_INODE_NODATASUM)) {
10327 		btrfs_warn(fs_info, "swapfile must not be checksummed");
10328 		ret = -EINVAL;
10329 		goto out_unlock_mmap;
10330 	}
10331 
10332 	path = btrfs_alloc_path();
10333 	backref_ctx = btrfs_alloc_backref_share_check_ctx();
10334 	if (!path || !backref_ctx) {
10335 		ret = -ENOMEM;
10336 		goto out_unlock_mmap;
10337 	}
10338 
10339 	/*
10340 	 * Balance or device remove/replace/resize can move stuff around from
10341 	 * under us. The exclop protection makes sure they aren't running/won't
10342 	 * run concurrently while we are mapping the swap extents, and
10343 	 * fs_info->swapfile_pins prevents them from running while the swap
10344 	 * file is active and moving the extents. Note that this also prevents
10345 	 * a concurrent device add which isn't actually necessary, but it's not
10346 	 * really worth the trouble to allow it.
10347 	 */
10348 	if (!btrfs_exclop_start(fs_info, BTRFS_EXCLOP_SWAP_ACTIVATE)) {
10349 		btrfs_warn(fs_info,
10350 	   "cannot activate swapfile while exclusive operation is running");
10351 		ret = -EBUSY;
10352 		goto out_unlock_mmap;
10353 	}
10354 
10355 	/*
10356 	 * Prevent snapshot creation while we are activating the swap file.
10357 	 * We do not want to race with snapshot creation. If snapshot creation
10358 	 * already started before we bumped nr_swapfiles from 0 to 1 and
10359 	 * completes before the first write into the swap file after it is
10360 	 * activated, than that write would fallback to COW.
10361 	 */
10362 	if (!btrfs_drew_try_write_lock(&root->snapshot_lock)) {
10363 		btrfs_exclop_finish(fs_info);
10364 		btrfs_warn(fs_info,
10365 	   "cannot activate swapfile because snapshot creation is in progress");
10366 		ret = -EINVAL;
10367 		goto out_unlock_mmap;
10368 	}
10369 	/*
10370 	 * Snapshots can create extents which require COW even if NODATACOW is
10371 	 * set. We use this counter to prevent snapshots. We must increment it
10372 	 * before walking the extents because we don't want a concurrent
10373 	 * snapshot to run after we've already checked the extents.
10374 	 *
10375 	 * It is possible that subvolume is marked for deletion but still not
10376 	 * removed yet. To prevent this race, we check the root status before
10377 	 * activating the swapfile.
10378 	 */
10379 	spin_lock(&root->root_item_lock);
10380 	if (btrfs_root_dead(root)) {
10381 		spin_unlock(&root->root_item_lock);
10382 
10383 		btrfs_drew_write_unlock(&root->snapshot_lock);
10384 		btrfs_exclop_finish(fs_info);
10385 		btrfs_warn(fs_info,
10386 		"cannot activate swapfile because subvolume %llu is being deleted",
10387 			btrfs_root_id(root));
10388 		ret = -EPERM;
10389 		goto out_unlock_mmap;
10390 	}
10391 	atomic_inc(&root->nr_swapfiles);
10392 	spin_unlock(&root->root_item_lock);
10393 
10394 	isize = ALIGN_DOWN(inode->i_size, fs_info->sectorsize);
10395 
10396 	btrfs_lock_extent(io_tree, 0, isize - 1, &cached_state);
10397 	while (prev_extent_end < isize) {
10398 		struct btrfs_key key;
10399 		struct extent_buffer *leaf;
10400 		struct btrfs_file_extent_item *ei;
10401 		struct btrfs_block_group *bg;
10402 		u64 logical_block_start;
10403 		u64 physical_block_start;
10404 		u64 extent_gen;
10405 		u64 disk_bytenr;
10406 		u64 len;
10407 
10408 		key.objectid = btrfs_ino(BTRFS_I(inode));
10409 		key.type = BTRFS_EXTENT_DATA_KEY;
10410 		key.offset = prev_extent_end;
10411 
10412 		ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
10413 		if (ret < 0)
10414 			goto out;
10415 
10416 		/*
10417 		 * If key not found it means we have an implicit hole (NO_HOLES
10418 		 * is enabled).
10419 		 */
10420 		if (ret > 0) {
10421 			btrfs_warn(fs_info, "swapfile must not have holes");
10422 			ret = -EINVAL;
10423 			goto out;
10424 		}
10425 
10426 		leaf = path->nodes[0];
10427 		ei = btrfs_item_ptr(leaf, path->slots[0], struct btrfs_file_extent_item);
10428 
10429 		if (btrfs_file_extent_type(leaf, ei) == BTRFS_FILE_EXTENT_INLINE) {
10430 			/*
10431 			 * It's unlikely we'll ever actually find ourselves
10432 			 * here, as a file small enough to fit inline won't be
10433 			 * big enough to store more than the swap header, but in
10434 			 * case something changes in the future, let's catch it
10435 			 * here rather than later.
10436 			 */
10437 			btrfs_warn(fs_info, "swapfile must not be inline");
10438 			ret = -EINVAL;
10439 			goto out;
10440 		}
10441 
10442 		if (btrfs_file_extent_compression(leaf, ei) != BTRFS_COMPRESS_NONE) {
10443 			btrfs_warn(fs_info, "swapfile must not be compressed");
10444 			ret = -EINVAL;
10445 			goto out;
10446 		}
10447 
10448 		disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, ei);
10449 		if (disk_bytenr == 0) {
10450 			btrfs_warn(fs_info, "swapfile must not have holes");
10451 			ret = -EINVAL;
10452 			goto out;
10453 		}
10454 
10455 		logical_block_start = disk_bytenr + btrfs_file_extent_offset(leaf, ei);
10456 		extent_gen = btrfs_file_extent_generation(leaf, ei);
10457 		prev_extent_end = btrfs_file_extent_end(path);
10458 
10459 		if (prev_extent_end > isize)
10460 			len = isize - key.offset;
10461 		else
10462 			len = btrfs_file_extent_num_bytes(leaf, ei);
10463 
10464 		backref_ctx->curr_leaf_bytenr = leaf->start;
10465 
10466 		/*
10467 		 * Don't need the path anymore, release to avoid deadlocks when
10468 		 * calling btrfs_is_data_extent_shared() because when joining a
10469 		 * transaction it can block waiting for the current one's commit
10470 		 * which in turn may be trying to lock the same leaf to flush
10471 		 * delayed items for example.
10472 		 */
10473 		btrfs_release_path(path);
10474 
10475 		ret = btrfs_is_data_extent_shared(BTRFS_I(inode), disk_bytenr,
10476 						  extent_gen, backref_ctx);
10477 		if (ret < 0) {
10478 			goto out;
10479 		} else if (ret > 0) {
10480 			btrfs_warn(fs_info,
10481 				   "swapfile must not be copy-on-write");
10482 			ret = -EINVAL;
10483 			goto out;
10484 		}
10485 
10486 		map = btrfs_get_chunk_map(fs_info, logical_block_start, len);
10487 		if (IS_ERR(map)) {
10488 			ret = PTR_ERR(map);
10489 			goto out;
10490 		}
10491 
10492 		if (map->type & BTRFS_BLOCK_GROUP_PROFILE_MASK) {
10493 			btrfs_warn(fs_info,
10494 				   "swapfile must have single data profile");
10495 			ret = -EINVAL;
10496 			goto out;
10497 		}
10498 
10499 		if (device == NULL) {
10500 			device = map->stripes[0].dev;
10501 			ret = btrfs_add_swapfile_pin(inode, device, false);
10502 			if (ret == 1)
10503 				ret = 0;
10504 			else if (ret)
10505 				goto out;
10506 		} else if (device != map->stripes[0].dev) {
10507 			btrfs_warn(fs_info, "swapfile must be on one device");
10508 			ret = -EINVAL;
10509 			goto out;
10510 		}
10511 
10512 		physical_block_start = (map->stripes[0].physical +
10513 					(logical_block_start - map->start));
10514 		btrfs_free_chunk_map(map);
10515 		map = NULL;
10516 
10517 		bg = btrfs_lookup_block_group(fs_info, logical_block_start);
10518 		if (!bg) {
10519 			btrfs_warn(fs_info,
10520 			   "could not find block group containing swapfile");
10521 			ret = -EINVAL;
10522 			goto out;
10523 		}
10524 
10525 		if (!btrfs_inc_block_group_swap_extents(bg)) {
10526 			btrfs_warn(fs_info,
10527 			   "block group for swapfile at %llu is read-only%s",
10528 			   bg->start,
10529 			   atomic_read(&fs_info->scrubs_running) ?
10530 				       " (scrub running)" : "");
10531 			btrfs_put_block_group(bg);
10532 			ret = -EINVAL;
10533 			goto out;
10534 		}
10535 
10536 		ret = btrfs_add_swapfile_pin(inode, bg, true);
10537 		if (ret) {
10538 			btrfs_put_block_group(bg);
10539 			if (ret == 1)
10540 				ret = 0;
10541 			else
10542 				goto out;
10543 		}
10544 
10545 		if (bsi.block_len &&
10546 		    bsi.block_start + bsi.block_len == physical_block_start) {
10547 			bsi.block_len += len;
10548 		} else {
10549 			if (bsi.block_len) {
10550 				ret = btrfs_add_swap_extent(sis, &bsi);
10551 				if (ret)
10552 					goto out;
10553 			}
10554 			bsi.start = key.offset;
10555 			bsi.block_start = physical_block_start;
10556 			bsi.block_len = len;
10557 		}
10558 
10559 		if (fatal_signal_pending(current)) {
10560 			ret = -EINTR;
10561 			goto out;
10562 		}
10563 
10564 		cond_resched();
10565 	}
10566 
10567 	if (bsi.block_len)
10568 		ret = btrfs_add_swap_extent(sis, &bsi);
10569 
10570 out:
10571 	if (!IS_ERR_OR_NULL(map))
10572 		btrfs_free_chunk_map(map);
10573 
10574 	btrfs_unlock_extent(io_tree, 0, isize - 1, &cached_state);
10575 
10576 	if (ret)
10577 		btrfs_swap_deactivate(file);
10578 
10579 	btrfs_drew_write_unlock(&root->snapshot_lock);
10580 
10581 	btrfs_exclop_finish(fs_info);
10582 
10583 out_unlock_mmap:
10584 	up_write(&BTRFS_I(inode)->i_mmap_lock);
10585 	btrfs_free_backref_share_ctx(backref_ctx);
10586 	btrfs_free_path(path);
10587 	if (ret)
10588 		return ret;
10589 
10590 	if (device)
10591 		sis->bdev = device->bdev;
10592 	*span = bsi.highest_ppage - bsi.lowest_ppage + 1;
10593 	sis->max = bsi.nr_pages;
10594 	sis->pages = bsi.nr_pages - 1;
10595 	return bsi.nr_extents;
10596 }
10597 #else
10598 static void btrfs_swap_deactivate(struct file *file)
10599 {
10600 }
10601 
10602 static int btrfs_swap_activate(struct swap_info_struct *sis, struct file *file,
10603 			       sector_t *span)
10604 {
10605 	return -EOPNOTSUPP;
10606 }
10607 #endif
10608 
10609 /*
10610  * Update the number of bytes used in the VFS' inode. When we replace extents in
10611  * a range (clone, dedupe, fallocate's zero range), we must update the number of
10612  * bytes used by the inode in an atomic manner, so that concurrent stat(2) calls
10613  * always get a correct value.
10614  */
10615 void btrfs_update_inode_bytes(struct btrfs_inode *inode,
10616 			      const u64 add_bytes,
10617 			      const u64 del_bytes)
10618 {
10619 	if (add_bytes == del_bytes)
10620 		return;
10621 
10622 	spin_lock(&inode->lock);
10623 	if (del_bytes > 0)
10624 		inode_sub_bytes(&inode->vfs_inode, del_bytes);
10625 	if (add_bytes > 0)
10626 		inode_add_bytes(&inode->vfs_inode, add_bytes);
10627 	spin_unlock(&inode->lock);
10628 }
10629 
10630 /*
10631  * Verify that there are no ordered extents for a given file range.
10632  *
10633  * @inode:   The target inode.
10634  * @start:   Start offset of the file range, should be sector size aligned.
10635  * @end:     End offset (inclusive) of the file range, its value +1 should be
10636  *           sector size aligned.
10637  *
10638  * This should typically be used for cases where we locked an inode's VFS lock in
10639  * exclusive mode, we have also locked the inode's i_mmap_lock in exclusive mode,
10640  * we have flushed all delalloc in the range, we have waited for all ordered
10641  * extents in the range to complete and finally we have locked the file range in
10642  * the inode's io_tree.
10643  */
10644 void btrfs_assert_inode_range_clean(struct btrfs_inode *inode, u64 start, u64 end)
10645 {
10646 	struct btrfs_root *root = inode->root;
10647 	struct btrfs_ordered_extent *ordered;
10648 
10649 	if (!IS_ENABLED(CONFIG_BTRFS_ASSERT))
10650 		return;
10651 
10652 	ordered = btrfs_lookup_first_ordered_range(inode, start, end + 1 - start);
10653 	if (ordered) {
10654 		btrfs_err(root->fs_info,
10655 "found unexpected ordered extent in file range [%llu, %llu] for inode %llu root %llu (ordered range [%llu, %llu])",
10656 			  start, end, btrfs_ino(inode), btrfs_root_id(root),
10657 			  ordered->file_offset,
10658 			  ordered->file_offset + ordered->num_bytes - 1);
10659 		btrfs_put_ordered_extent(ordered);
10660 	}
10661 
10662 	ASSERT(ordered == NULL);
10663 }
10664 
10665 /*
10666  * Find the first inode with a minimum number.
10667  *
10668  * @root:	The root to search for.
10669  * @min_ino:	The minimum inode number.
10670  *
10671  * Find the first inode in the @root with a number >= @min_ino and return it.
10672  * Returns NULL if no such inode found.
10673  */
10674 struct btrfs_inode *btrfs_find_first_inode(struct btrfs_root *root, u64 min_ino)
10675 {
10676 	struct btrfs_inode *inode;
10677 	unsigned long from = min_ino;
10678 
10679 	xa_lock(&root->inodes);
10680 	while (true) {
10681 		inode = xa_find(&root->inodes, &from, ULONG_MAX, XA_PRESENT);
10682 		if (!inode)
10683 			break;
10684 		if (igrab(&inode->vfs_inode))
10685 			break;
10686 
10687 		from = btrfs_ino(inode) + 1;
10688 		xa_unlock(&root->inodes);
10689 		cond_resched();
10690 		xa_lock(&root->inodes);
10691 	}
10692 	xa_unlock(&root->inodes);
10693 
10694 	return inode;
10695 }
10696 
10697 static const struct inode_operations btrfs_dir_inode_operations = {
10698 	.getattr	= btrfs_getattr,
10699 	.lookup		= btrfs_lookup,
10700 	.create		= btrfs_create,
10701 	.unlink		= btrfs_unlink,
10702 	.link		= btrfs_link,
10703 	.mkdir		= btrfs_mkdir,
10704 	.rmdir		= btrfs_rmdir,
10705 	.rename		= btrfs_rename2,
10706 	.symlink	= btrfs_symlink,
10707 	.setattr	= btrfs_setattr,
10708 	.mknod		= btrfs_mknod,
10709 	.listxattr	= btrfs_listxattr,
10710 	.permission	= btrfs_permission,
10711 	.get_inode_acl	= btrfs_get_acl,
10712 	.set_acl	= btrfs_set_acl,
10713 	.update_time	= btrfs_update_time,
10714 	.tmpfile        = btrfs_tmpfile,
10715 	.fileattr_get	= btrfs_fileattr_get,
10716 	.fileattr_set	= btrfs_fileattr_set,
10717 };
10718 
10719 static const struct file_operations btrfs_dir_file_operations = {
10720 	.llseek		= btrfs_dir_llseek,
10721 	.read		= generic_read_dir,
10722 	.iterate_shared	= btrfs_real_readdir,
10723 	.open		= btrfs_opendir,
10724 	.unlocked_ioctl	= btrfs_ioctl,
10725 #ifdef CONFIG_COMPAT
10726 	.compat_ioctl	= btrfs_compat_ioctl,
10727 #endif
10728 	.release        = btrfs_release_file,
10729 	.fsync		= btrfs_sync_file,
10730 	.setlease	= generic_setlease,
10731 };
10732 
10733 /*
10734  * The folio is going dirty without a btrfs delalloc space reservation.
10735  * This requires a fixup before writeback which we might sleep so cannot
10736  * run in this context, so we merely set state on the folio indicating it
10737  * needs fixup before writeback.
10738  *
10739  * Note that there is no range in the input, so the whole folio is marked
10740  * dirty and fixup.
10741  *
10742  * We believe that all callers of dirty_folio either:
10743  * - take the folio lock (e.g. pinned folio release notification).
10744  * - take the pte lock but must be running on a dirty pte which means
10745  *   page_mkwrite() ran on it and reserved the space. zap_pte_range() cannot
10746  *   race with writeback cleaning the folio because writeback runs
10747  *   folio_mkclean() which also uses the pte lock and revokes outstanding
10748  *   writable mappings.
10749  * Therefore, an additional folio private lock (a la bfs->lock for all cases,
10750  * not just subpage) is not necessary.
10751  */
10752 static bool btrfs_data_dirty_folio(struct address_space *mapping,
10753 				   struct folio *folio)
10754 {
10755 	struct btrfs_inode *inode = BTRFS_I(mapping->host);
10756 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
10757 	const u64 page_start = folio_pos(folio);
10758 	const u64 range_end = min_t(u64, folio_next_pos(folio),
10759 				    round_up(i_size_read(&inode->vfs_inode),
10760 					     fs_info->sectorsize));
10761 
10762 	if (range_end > page_start)
10763 		btrfs_folio_set_fixup_dirty(fs_info, folio, page_start,
10764 					    range_end - page_start);
10765 	return filemap_dirty_folio(mapping, folio);
10766 }
10767 
10768 /*
10769  * btrfs doesn't support the bmap operation because swapfiles
10770  * use bmap to make a mapping of extents in the file.  They assume
10771  * these extents won't change over the life of the file and they
10772  * use the bmap result to do IO directly to the drive.
10773  *
10774  * the btrfs bmap call would return logical addresses that aren't
10775  * suitable for IO and they also will change frequently as COW
10776  * operations happen.  So, swapfile + btrfs == corruption.
10777  *
10778  * For now we're avoiding this by dropping bmap.
10779  */
10780 static const struct address_space_operations btrfs_aops = {
10781 	.read_folio	= btrfs_read_folio,
10782 	.writepages	= btrfs_writepages,
10783 	.readahead	= btrfs_readahead,
10784 	.invalidate_folio = btrfs_invalidate_folio,
10785 	.launder_folio	= btrfs_launder_folio,
10786 	.release_folio	= btrfs_release_folio,
10787 	.migrate_folio	= btrfs_migrate_folio,
10788 	.dirty_folio	= btrfs_data_dirty_folio,
10789 	.error_remove_folio = generic_error_remove_folio,
10790 	.swap_activate	= btrfs_swap_activate,
10791 	.swap_deactivate = btrfs_swap_deactivate,
10792 };
10793 
10794 static const struct inode_operations btrfs_file_inode_operations = {
10795 	.getattr	= btrfs_getattr,
10796 	.setattr	= btrfs_setattr,
10797 	.listxattr      = btrfs_listxattr,
10798 	.permission	= btrfs_permission,
10799 	.fiemap		= btrfs_fiemap,
10800 	.get_inode_acl	= btrfs_get_acl,
10801 	.set_acl	= btrfs_set_acl,
10802 	.update_time	= btrfs_update_time,
10803 	.fileattr_get	= btrfs_fileattr_get,
10804 	.fileattr_set	= btrfs_fileattr_set,
10805 };
10806 static const struct inode_operations btrfs_special_inode_operations = {
10807 	.getattr	= btrfs_getattr,
10808 	.setattr	= btrfs_setattr,
10809 	.permission	= btrfs_permission,
10810 	.listxattr	= btrfs_listxattr,
10811 	.get_inode_acl	= btrfs_get_acl,
10812 	.set_acl	= btrfs_set_acl,
10813 	.update_time	= btrfs_update_time,
10814 };
10815 static const struct inode_operations btrfs_symlink_inode_operations = {
10816 	.get_link	= page_get_link,
10817 	.getattr	= btrfs_getattr,
10818 	.setattr	= btrfs_setattr,
10819 	.permission	= btrfs_permission,
10820 	.listxattr	= btrfs_listxattr,
10821 	.update_time	= btrfs_update_time,
10822 };
10823 
10824 const struct dentry_operations btrfs_dentry_operations = {
10825 	.d_delete	= btrfs_dentry_delete,
10826 };
10827