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