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