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