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