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