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