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