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