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