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