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