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