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