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