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