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