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