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