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