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