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