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