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