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