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