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