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