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