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