xref: /linux/fs/btrfs/file.c (revision dbbf49928f2eb118036766fae503be1314620cce)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2007 Oracle.  All rights reserved.
4  */
5 
6 #include <linux/fs.h>
7 #include <linux/pagemap.h>
8 #include <linux/time.h>
9 #include <linux/init.h>
10 #include <linux/string.h>
11 #include <linux/backing-dev.h>
12 #include <linux/falloc.h>
13 #include <linux/writeback.h>
14 #include <linux/compat.h>
15 #include <linux/slab.h>
16 #include <linux/btrfs.h>
17 #include <linux/uio.h>
18 #include <linux/iversion.h>
19 #include <linux/fsverity.h>
20 #include "ctree.h"
21 #include "disk-io.h"
22 #include "transaction.h"
23 #include "btrfs_inode.h"
24 #include "print-tree.h"
25 #include "tree-log.h"
26 #include "locking.h"
27 #include "volumes.h"
28 #include "qgroup.h"
29 #include "compression.h"
30 #include "delalloc-space.h"
31 #include "reflink.h"
32 #include "subpage.h"
33 
34 static struct kmem_cache *btrfs_inode_defrag_cachep;
35 /*
36  * when auto defrag is enabled we
37  * queue up these defrag structs to remember which
38  * inodes need defragging passes
39  */
40 struct inode_defrag {
41 	struct rb_node rb_node;
42 	/* objectid */
43 	u64 ino;
44 	/*
45 	 * transid where the defrag was added, we search for
46 	 * extents newer than this
47 	 */
48 	u64 transid;
49 
50 	/* root objectid */
51 	u64 root;
52 
53 	/*
54 	 * The extent size threshold for autodefrag.
55 	 *
56 	 * This value is different for compressed/non-compressed extents,
57 	 * thus needs to be passed from higher layer.
58 	 * (aka, inode_should_defrag())
59 	 */
60 	u32 extent_thresh;
61 };
62 
63 static int __compare_inode_defrag(struct inode_defrag *defrag1,
64 				  struct inode_defrag *defrag2)
65 {
66 	if (defrag1->root > defrag2->root)
67 		return 1;
68 	else if (defrag1->root < defrag2->root)
69 		return -1;
70 	else if (defrag1->ino > defrag2->ino)
71 		return 1;
72 	else if (defrag1->ino < defrag2->ino)
73 		return -1;
74 	else
75 		return 0;
76 }
77 
78 /* pop a record for an inode into the defrag tree.  The lock
79  * must be held already
80  *
81  * If you're inserting a record for an older transid than an
82  * existing record, the transid already in the tree is lowered
83  *
84  * If an existing record is found the defrag item you
85  * pass in is freed
86  */
87 static int __btrfs_add_inode_defrag(struct btrfs_inode *inode,
88 				    struct inode_defrag *defrag)
89 {
90 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
91 	struct inode_defrag *entry;
92 	struct rb_node **p;
93 	struct rb_node *parent = NULL;
94 	int ret;
95 
96 	p = &fs_info->defrag_inodes.rb_node;
97 	while (*p) {
98 		parent = *p;
99 		entry = rb_entry(parent, struct inode_defrag, rb_node);
100 
101 		ret = __compare_inode_defrag(defrag, entry);
102 		if (ret < 0)
103 			p = &parent->rb_left;
104 		else if (ret > 0)
105 			p = &parent->rb_right;
106 		else {
107 			/* if we're reinserting an entry for
108 			 * an old defrag run, make sure to
109 			 * lower the transid of our existing record
110 			 */
111 			if (defrag->transid < entry->transid)
112 				entry->transid = defrag->transid;
113 			entry->extent_thresh = min(defrag->extent_thresh,
114 						   entry->extent_thresh);
115 			return -EEXIST;
116 		}
117 	}
118 	set_bit(BTRFS_INODE_IN_DEFRAG, &inode->runtime_flags);
119 	rb_link_node(&defrag->rb_node, parent, p);
120 	rb_insert_color(&defrag->rb_node, &fs_info->defrag_inodes);
121 	return 0;
122 }
123 
124 static inline int __need_auto_defrag(struct btrfs_fs_info *fs_info)
125 {
126 	if (!btrfs_test_opt(fs_info, AUTO_DEFRAG))
127 		return 0;
128 
129 	if (btrfs_fs_closing(fs_info))
130 		return 0;
131 
132 	return 1;
133 }
134 
135 /*
136  * insert a defrag record for this inode if auto defrag is
137  * enabled
138  */
139 int btrfs_add_inode_defrag(struct btrfs_trans_handle *trans,
140 			   struct btrfs_inode *inode, u32 extent_thresh)
141 {
142 	struct btrfs_root *root = inode->root;
143 	struct btrfs_fs_info *fs_info = root->fs_info;
144 	struct inode_defrag *defrag;
145 	u64 transid;
146 	int ret;
147 
148 	if (!__need_auto_defrag(fs_info))
149 		return 0;
150 
151 	if (test_bit(BTRFS_INODE_IN_DEFRAG, &inode->runtime_flags))
152 		return 0;
153 
154 	if (trans)
155 		transid = trans->transid;
156 	else
157 		transid = inode->root->last_trans;
158 
159 	defrag = kmem_cache_zalloc(btrfs_inode_defrag_cachep, GFP_NOFS);
160 	if (!defrag)
161 		return -ENOMEM;
162 
163 	defrag->ino = btrfs_ino(inode);
164 	defrag->transid = transid;
165 	defrag->root = root->root_key.objectid;
166 	defrag->extent_thresh = extent_thresh;
167 
168 	spin_lock(&fs_info->defrag_inodes_lock);
169 	if (!test_bit(BTRFS_INODE_IN_DEFRAG, &inode->runtime_flags)) {
170 		/*
171 		 * If we set IN_DEFRAG flag and evict the inode from memory,
172 		 * and then re-read this inode, this new inode doesn't have
173 		 * IN_DEFRAG flag. At the case, we may find the existed defrag.
174 		 */
175 		ret = __btrfs_add_inode_defrag(inode, defrag);
176 		if (ret)
177 			kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
178 	} else {
179 		kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
180 	}
181 	spin_unlock(&fs_info->defrag_inodes_lock);
182 	return 0;
183 }
184 
185 /*
186  * pick the defragable inode that we want, if it doesn't exist, we will get
187  * the next one.
188  */
189 static struct inode_defrag *
190 btrfs_pick_defrag_inode(struct btrfs_fs_info *fs_info, u64 root, u64 ino)
191 {
192 	struct inode_defrag *entry = NULL;
193 	struct inode_defrag tmp;
194 	struct rb_node *p;
195 	struct rb_node *parent = NULL;
196 	int ret;
197 
198 	tmp.ino = ino;
199 	tmp.root = root;
200 
201 	spin_lock(&fs_info->defrag_inodes_lock);
202 	p = fs_info->defrag_inodes.rb_node;
203 	while (p) {
204 		parent = p;
205 		entry = rb_entry(parent, struct inode_defrag, rb_node);
206 
207 		ret = __compare_inode_defrag(&tmp, entry);
208 		if (ret < 0)
209 			p = parent->rb_left;
210 		else if (ret > 0)
211 			p = parent->rb_right;
212 		else
213 			goto out;
214 	}
215 
216 	if (parent && __compare_inode_defrag(&tmp, entry) > 0) {
217 		parent = rb_next(parent);
218 		if (parent)
219 			entry = rb_entry(parent, struct inode_defrag, rb_node);
220 		else
221 			entry = NULL;
222 	}
223 out:
224 	if (entry)
225 		rb_erase(parent, &fs_info->defrag_inodes);
226 	spin_unlock(&fs_info->defrag_inodes_lock);
227 	return entry;
228 }
229 
230 void btrfs_cleanup_defrag_inodes(struct btrfs_fs_info *fs_info)
231 {
232 	struct inode_defrag *defrag;
233 	struct rb_node *node;
234 
235 	spin_lock(&fs_info->defrag_inodes_lock);
236 	node = rb_first(&fs_info->defrag_inodes);
237 	while (node) {
238 		rb_erase(node, &fs_info->defrag_inodes);
239 		defrag = rb_entry(node, struct inode_defrag, rb_node);
240 		kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
241 
242 		cond_resched_lock(&fs_info->defrag_inodes_lock);
243 
244 		node = rb_first(&fs_info->defrag_inodes);
245 	}
246 	spin_unlock(&fs_info->defrag_inodes_lock);
247 }
248 
249 #define BTRFS_DEFRAG_BATCH	1024
250 
251 static int __btrfs_run_defrag_inode(struct btrfs_fs_info *fs_info,
252 				    struct inode_defrag *defrag)
253 {
254 	struct btrfs_root *inode_root;
255 	struct inode *inode;
256 	struct btrfs_ioctl_defrag_range_args range;
257 	int ret = 0;
258 	u64 cur = 0;
259 
260 again:
261 	if (test_bit(BTRFS_FS_STATE_REMOUNTING, &fs_info->fs_state))
262 		goto cleanup;
263 	if (!__need_auto_defrag(fs_info))
264 		goto cleanup;
265 
266 	/* get the inode */
267 	inode_root = btrfs_get_fs_root(fs_info, defrag->root, true);
268 	if (IS_ERR(inode_root)) {
269 		ret = PTR_ERR(inode_root);
270 		goto cleanup;
271 	}
272 
273 	inode = btrfs_iget(fs_info->sb, defrag->ino, inode_root);
274 	btrfs_put_root(inode_root);
275 	if (IS_ERR(inode)) {
276 		ret = PTR_ERR(inode);
277 		goto cleanup;
278 	}
279 
280 	if (cur >= i_size_read(inode)) {
281 		iput(inode);
282 		goto cleanup;
283 	}
284 
285 	/* do a chunk of defrag */
286 	clear_bit(BTRFS_INODE_IN_DEFRAG, &BTRFS_I(inode)->runtime_flags);
287 	memset(&range, 0, sizeof(range));
288 	range.len = (u64)-1;
289 	range.start = cur;
290 	range.extent_thresh = defrag->extent_thresh;
291 
292 	sb_start_write(fs_info->sb);
293 	ret = btrfs_defrag_file(inode, NULL, &range, defrag->transid,
294 				       BTRFS_DEFRAG_BATCH);
295 	sb_end_write(fs_info->sb);
296 	iput(inode);
297 
298 	if (ret < 0)
299 		goto cleanup;
300 
301 	cur = max(cur + fs_info->sectorsize, range.start);
302 	goto again;
303 
304 cleanup:
305 	kmem_cache_free(btrfs_inode_defrag_cachep, defrag);
306 	return ret;
307 }
308 
309 /*
310  * run through the list of inodes in the FS that need
311  * defragging
312  */
313 int btrfs_run_defrag_inodes(struct btrfs_fs_info *fs_info)
314 {
315 	struct inode_defrag *defrag;
316 	u64 first_ino = 0;
317 	u64 root_objectid = 0;
318 
319 	atomic_inc(&fs_info->defrag_running);
320 	while (1) {
321 		/* Pause the auto defragger. */
322 		if (test_bit(BTRFS_FS_STATE_REMOUNTING,
323 			     &fs_info->fs_state))
324 			break;
325 
326 		if (!__need_auto_defrag(fs_info))
327 			break;
328 
329 		/* find an inode to defrag */
330 		defrag = btrfs_pick_defrag_inode(fs_info, root_objectid,
331 						 first_ino);
332 		if (!defrag) {
333 			if (root_objectid || first_ino) {
334 				root_objectid = 0;
335 				first_ino = 0;
336 				continue;
337 			} else {
338 				break;
339 			}
340 		}
341 
342 		first_ino = defrag->ino + 1;
343 		root_objectid = defrag->root;
344 
345 		__btrfs_run_defrag_inode(fs_info, defrag);
346 	}
347 	atomic_dec(&fs_info->defrag_running);
348 
349 	/*
350 	 * during unmount, we use the transaction_wait queue to
351 	 * wait for the defragger to stop
352 	 */
353 	wake_up(&fs_info->transaction_wait);
354 	return 0;
355 }
356 
357 /* simple helper to fault in pages and copy.  This should go away
358  * and be replaced with calls into generic code.
359  */
360 static noinline int btrfs_copy_from_user(loff_t pos, size_t write_bytes,
361 					 struct page **prepared_pages,
362 					 struct iov_iter *i)
363 {
364 	size_t copied = 0;
365 	size_t total_copied = 0;
366 	int pg = 0;
367 	int offset = offset_in_page(pos);
368 
369 	while (write_bytes > 0) {
370 		size_t count = min_t(size_t,
371 				     PAGE_SIZE - offset, write_bytes);
372 		struct page *page = prepared_pages[pg];
373 		/*
374 		 * Copy data from userspace to the current page
375 		 */
376 		copied = copy_page_from_iter_atomic(page, offset, count, i);
377 
378 		/* Flush processor's dcache for this page */
379 		flush_dcache_page(page);
380 
381 		/*
382 		 * if we get a partial write, we can end up with
383 		 * partially up to date pages.  These add
384 		 * a lot of complexity, so make sure they don't
385 		 * happen by forcing this copy to be retried.
386 		 *
387 		 * The rest of the btrfs_file_write code will fall
388 		 * back to page at a time copies after we return 0.
389 		 */
390 		if (unlikely(copied < count)) {
391 			if (!PageUptodate(page)) {
392 				iov_iter_revert(i, copied);
393 				copied = 0;
394 			}
395 			if (!copied)
396 				break;
397 		}
398 
399 		write_bytes -= copied;
400 		total_copied += copied;
401 		offset += copied;
402 		if (offset == PAGE_SIZE) {
403 			pg++;
404 			offset = 0;
405 		}
406 	}
407 	return total_copied;
408 }
409 
410 /*
411  * unlocks pages after btrfs_file_write is done with them
412  */
413 static void btrfs_drop_pages(struct btrfs_fs_info *fs_info,
414 			     struct page **pages, size_t num_pages,
415 			     u64 pos, u64 copied)
416 {
417 	size_t i;
418 	u64 block_start = round_down(pos, fs_info->sectorsize);
419 	u64 block_len = round_up(pos + copied, fs_info->sectorsize) - block_start;
420 
421 	ASSERT(block_len <= U32_MAX);
422 	for (i = 0; i < num_pages; i++) {
423 		/* page checked is some magic around finding pages that
424 		 * have been modified without going through btrfs_set_page_dirty
425 		 * clear it here. There should be no need to mark the pages
426 		 * accessed as prepare_pages should have marked them accessed
427 		 * in prepare_pages via find_or_create_page()
428 		 */
429 		btrfs_page_clamp_clear_checked(fs_info, pages[i], block_start,
430 					       block_len);
431 		unlock_page(pages[i]);
432 		put_page(pages[i]);
433 	}
434 }
435 
436 /*
437  * After btrfs_copy_from_user(), update the following things for delalloc:
438  * - Mark newly dirtied pages as DELALLOC in the io tree.
439  *   Used to advise which range is to be written back.
440  * - Mark modified pages as Uptodate/Dirty and not needing COW fixup
441  * - Update inode size for past EOF write
442  */
443 int btrfs_dirty_pages(struct btrfs_inode *inode, struct page **pages,
444 		      size_t num_pages, loff_t pos, size_t write_bytes,
445 		      struct extent_state **cached, bool noreserve)
446 {
447 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
448 	int err = 0;
449 	int i;
450 	u64 num_bytes;
451 	u64 start_pos;
452 	u64 end_of_last_block;
453 	u64 end_pos = pos + write_bytes;
454 	loff_t isize = i_size_read(&inode->vfs_inode);
455 	unsigned int extra_bits = 0;
456 
457 	if (write_bytes == 0)
458 		return 0;
459 
460 	if (noreserve)
461 		extra_bits |= EXTENT_NORESERVE;
462 
463 	start_pos = round_down(pos, fs_info->sectorsize);
464 	num_bytes = round_up(write_bytes + pos - start_pos,
465 			     fs_info->sectorsize);
466 	ASSERT(num_bytes <= U32_MAX);
467 
468 	end_of_last_block = start_pos + num_bytes - 1;
469 
470 	/*
471 	 * The pages may have already been dirty, clear out old accounting so
472 	 * we can set things up properly
473 	 */
474 	clear_extent_bit(&inode->io_tree, start_pos, end_of_last_block,
475 			 EXTENT_DELALLOC | EXTENT_DO_ACCOUNTING | EXTENT_DEFRAG,
476 			 0, cached);
477 
478 	err = btrfs_set_extent_delalloc(inode, start_pos, end_of_last_block,
479 					extra_bits, cached);
480 	if (err)
481 		return err;
482 
483 	for (i = 0; i < num_pages; i++) {
484 		struct page *p = pages[i];
485 
486 		btrfs_page_clamp_set_uptodate(fs_info, p, start_pos, num_bytes);
487 		btrfs_page_clamp_clear_checked(fs_info, p, start_pos, num_bytes);
488 		btrfs_page_clamp_set_dirty(fs_info, p, start_pos, num_bytes);
489 	}
490 
491 	/*
492 	 * we've only changed i_size in ram, and we haven't updated
493 	 * the disk i_size.  There is no need to log the inode
494 	 * at this time.
495 	 */
496 	if (end_pos > isize)
497 		i_size_write(&inode->vfs_inode, end_pos);
498 	return 0;
499 }
500 
501 /*
502  * this drops all the extents in the cache that intersect the range
503  * [start, end].  Existing extents are split as required.
504  */
505 void btrfs_drop_extent_cache(struct btrfs_inode *inode, u64 start, u64 end,
506 			     int skip_pinned)
507 {
508 	struct extent_map *em;
509 	struct extent_map *split = NULL;
510 	struct extent_map *split2 = NULL;
511 	struct extent_map_tree *em_tree = &inode->extent_tree;
512 	u64 len = end - start + 1;
513 	u64 gen;
514 	int ret;
515 	int testend = 1;
516 	unsigned long flags;
517 	int compressed = 0;
518 	bool modified;
519 
520 	WARN_ON(end < start);
521 	if (end == (u64)-1) {
522 		len = (u64)-1;
523 		testend = 0;
524 	}
525 	while (1) {
526 		int no_splits = 0;
527 
528 		modified = false;
529 		if (!split)
530 			split = alloc_extent_map();
531 		if (!split2)
532 			split2 = alloc_extent_map();
533 		if (!split || !split2)
534 			no_splits = 1;
535 
536 		write_lock(&em_tree->lock);
537 		em = lookup_extent_mapping(em_tree, start, len);
538 		if (!em) {
539 			write_unlock(&em_tree->lock);
540 			break;
541 		}
542 		flags = em->flags;
543 		gen = em->generation;
544 		if (skip_pinned && test_bit(EXTENT_FLAG_PINNED, &em->flags)) {
545 			if (testend && em->start + em->len >= start + len) {
546 				free_extent_map(em);
547 				write_unlock(&em_tree->lock);
548 				break;
549 			}
550 			start = em->start + em->len;
551 			if (testend)
552 				len = start + len - (em->start + em->len);
553 			free_extent_map(em);
554 			write_unlock(&em_tree->lock);
555 			continue;
556 		}
557 		compressed = test_bit(EXTENT_FLAG_COMPRESSED, &em->flags);
558 		clear_bit(EXTENT_FLAG_PINNED, &em->flags);
559 		clear_bit(EXTENT_FLAG_LOGGING, &flags);
560 		modified = !list_empty(&em->list);
561 		if (no_splits)
562 			goto next;
563 
564 		if (em->start < start) {
565 			split->start = em->start;
566 			split->len = start - em->start;
567 
568 			if (em->block_start < EXTENT_MAP_LAST_BYTE) {
569 				split->orig_start = em->orig_start;
570 				split->block_start = em->block_start;
571 
572 				if (compressed)
573 					split->block_len = em->block_len;
574 				else
575 					split->block_len = split->len;
576 				split->orig_block_len = max(split->block_len,
577 						em->orig_block_len);
578 				split->ram_bytes = em->ram_bytes;
579 			} else {
580 				split->orig_start = split->start;
581 				split->block_len = 0;
582 				split->block_start = em->block_start;
583 				split->orig_block_len = 0;
584 				split->ram_bytes = split->len;
585 			}
586 
587 			split->generation = gen;
588 			split->flags = flags;
589 			split->compress_type = em->compress_type;
590 			replace_extent_mapping(em_tree, em, split, modified);
591 			free_extent_map(split);
592 			split = split2;
593 			split2 = NULL;
594 		}
595 		if (testend && em->start + em->len > start + len) {
596 			u64 diff = start + len - em->start;
597 
598 			split->start = start + len;
599 			split->len = em->start + em->len - (start + len);
600 			split->flags = flags;
601 			split->compress_type = em->compress_type;
602 			split->generation = gen;
603 
604 			if (em->block_start < EXTENT_MAP_LAST_BYTE) {
605 				split->orig_block_len = max(em->block_len,
606 						    em->orig_block_len);
607 
608 				split->ram_bytes = em->ram_bytes;
609 				if (compressed) {
610 					split->block_len = em->block_len;
611 					split->block_start = em->block_start;
612 					split->orig_start = em->orig_start;
613 				} else {
614 					split->block_len = split->len;
615 					split->block_start = em->block_start
616 						+ diff;
617 					split->orig_start = em->orig_start;
618 				}
619 			} else {
620 				split->ram_bytes = split->len;
621 				split->orig_start = split->start;
622 				split->block_len = 0;
623 				split->block_start = em->block_start;
624 				split->orig_block_len = 0;
625 			}
626 
627 			if (extent_map_in_tree(em)) {
628 				replace_extent_mapping(em_tree, em, split,
629 						       modified);
630 			} else {
631 				ret = add_extent_mapping(em_tree, split,
632 							 modified);
633 				ASSERT(ret == 0); /* Logic error */
634 			}
635 			free_extent_map(split);
636 			split = NULL;
637 		}
638 next:
639 		if (extent_map_in_tree(em))
640 			remove_extent_mapping(em_tree, em);
641 		write_unlock(&em_tree->lock);
642 
643 		/* once for us */
644 		free_extent_map(em);
645 		/* once for the tree*/
646 		free_extent_map(em);
647 	}
648 	if (split)
649 		free_extent_map(split);
650 	if (split2)
651 		free_extent_map(split2);
652 }
653 
654 /*
655  * this is very complex, but the basic idea is to drop all extents
656  * in the range start - end.  hint_block is filled in with a block number
657  * that would be a good hint to the block allocator for this file.
658  *
659  * If an extent intersects the range but is not entirely inside the range
660  * it is either truncated or split.  Anything entirely inside the range
661  * is deleted from the tree.
662  *
663  * Note: the VFS' inode number of bytes is not updated, it's up to the caller
664  * to deal with that. We set the field 'bytes_found' of the arguments structure
665  * with the number of allocated bytes found in the target range, so that the
666  * caller can update the inode's number of bytes in an atomic way when
667  * replacing extents in a range to avoid races with stat(2).
668  */
669 int btrfs_drop_extents(struct btrfs_trans_handle *trans,
670 		       struct btrfs_root *root, struct btrfs_inode *inode,
671 		       struct btrfs_drop_extents_args *args)
672 {
673 	struct btrfs_fs_info *fs_info = root->fs_info;
674 	struct extent_buffer *leaf;
675 	struct btrfs_file_extent_item *fi;
676 	struct btrfs_ref ref = { 0 };
677 	struct btrfs_key key;
678 	struct btrfs_key new_key;
679 	u64 ino = btrfs_ino(inode);
680 	u64 search_start = args->start;
681 	u64 disk_bytenr = 0;
682 	u64 num_bytes = 0;
683 	u64 extent_offset = 0;
684 	u64 extent_end = 0;
685 	u64 last_end = args->start;
686 	int del_nr = 0;
687 	int del_slot = 0;
688 	int extent_type;
689 	int recow;
690 	int ret;
691 	int modify_tree = -1;
692 	int update_refs;
693 	int found = 0;
694 	struct btrfs_path *path = args->path;
695 
696 	args->bytes_found = 0;
697 	args->extent_inserted = false;
698 
699 	/* Must always have a path if ->replace_extent is true */
700 	ASSERT(!(args->replace_extent && !args->path));
701 
702 	if (!path) {
703 		path = btrfs_alloc_path();
704 		if (!path) {
705 			ret = -ENOMEM;
706 			goto out;
707 		}
708 	}
709 
710 	if (args->drop_cache)
711 		btrfs_drop_extent_cache(inode, args->start, args->end - 1, 0);
712 
713 	if (args->start >= inode->disk_i_size && !args->replace_extent)
714 		modify_tree = 0;
715 
716 	update_refs = (root->root_key.objectid != BTRFS_TREE_LOG_OBJECTID);
717 	while (1) {
718 		recow = 0;
719 		ret = btrfs_lookup_file_extent(trans, root, path, ino,
720 					       search_start, modify_tree);
721 		if (ret < 0)
722 			break;
723 		if (ret > 0 && path->slots[0] > 0 && search_start == args->start) {
724 			leaf = path->nodes[0];
725 			btrfs_item_key_to_cpu(leaf, &key, path->slots[0] - 1);
726 			if (key.objectid == ino &&
727 			    key.type == BTRFS_EXTENT_DATA_KEY)
728 				path->slots[0]--;
729 		}
730 		ret = 0;
731 next_slot:
732 		leaf = path->nodes[0];
733 		if (path->slots[0] >= btrfs_header_nritems(leaf)) {
734 			BUG_ON(del_nr > 0);
735 			ret = btrfs_next_leaf(root, path);
736 			if (ret < 0)
737 				break;
738 			if (ret > 0) {
739 				ret = 0;
740 				break;
741 			}
742 			leaf = path->nodes[0];
743 			recow = 1;
744 		}
745 
746 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
747 
748 		if (key.objectid > ino)
749 			break;
750 		if (WARN_ON_ONCE(key.objectid < ino) ||
751 		    key.type < BTRFS_EXTENT_DATA_KEY) {
752 			ASSERT(del_nr == 0);
753 			path->slots[0]++;
754 			goto next_slot;
755 		}
756 		if (key.type > BTRFS_EXTENT_DATA_KEY || key.offset >= args->end)
757 			break;
758 
759 		fi = btrfs_item_ptr(leaf, path->slots[0],
760 				    struct btrfs_file_extent_item);
761 		extent_type = btrfs_file_extent_type(leaf, fi);
762 
763 		if (extent_type == BTRFS_FILE_EXTENT_REG ||
764 		    extent_type == BTRFS_FILE_EXTENT_PREALLOC) {
765 			disk_bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
766 			num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
767 			extent_offset = btrfs_file_extent_offset(leaf, fi);
768 			extent_end = key.offset +
769 				btrfs_file_extent_num_bytes(leaf, fi);
770 		} else if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
771 			extent_end = key.offset +
772 				btrfs_file_extent_ram_bytes(leaf, fi);
773 		} else {
774 			/* can't happen */
775 			BUG();
776 		}
777 
778 		/*
779 		 * Don't skip extent items representing 0 byte lengths. They
780 		 * used to be created (bug) if while punching holes we hit
781 		 * -ENOSPC condition. So if we find one here, just ensure we
782 		 * delete it, otherwise we would insert a new file extent item
783 		 * with the same key (offset) as that 0 bytes length file
784 		 * extent item in the call to setup_items_for_insert() later
785 		 * in this function.
786 		 */
787 		if (extent_end == key.offset && extent_end >= search_start) {
788 			last_end = extent_end;
789 			goto delete_extent_item;
790 		}
791 
792 		if (extent_end <= search_start) {
793 			path->slots[0]++;
794 			goto next_slot;
795 		}
796 
797 		found = 1;
798 		search_start = max(key.offset, args->start);
799 		if (recow || !modify_tree) {
800 			modify_tree = -1;
801 			btrfs_release_path(path);
802 			continue;
803 		}
804 
805 		/*
806 		 *     | - range to drop - |
807 		 *  | -------- extent -------- |
808 		 */
809 		if (args->start > key.offset && args->end < extent_end) {
810 			BUG_ON(del_nr > 0);
811 			if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
812 				ret = -EOPNOTSUPP;
813 				break;
814 			}
815 
816 			memcpy(&new_key, &key, sizeof(new_key));
817 			new_key.offset = args->start;
818 			ret = btrfs_duplicate_item(trans, root, path,
819 						   &new_key);
820 			if (ret == -EAGAIN) {
821 				btrfs_release_path(path);
822 				continue;
823 			}
824 			if (ret < 0)
825 				break;
826 
827 			leaf = path->nodes[0];
828 			fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
829 					    struct btrfs_file_extent_item);
830 			btrfs_set_file_extent_num_bytes(leaf, fi,
831 							args->start - key.offset);
832 
833 			fi = btrfs_item_ptr(leaf, path->slots[0],
834 					    struct btrfs_file_extent_item);
835 
836 			extent_offset += args->start - key.offset;
837 			btrfs_set_file_extent_offset(leaf, fi, extent_offset);
838 			btrfs_set_file_extent_num_bytes(leaf, fi,
839 							extent_end - args->start);
840 			btrfs_mark_buffer_dirty(leaf);
841 
842 			if (update_refs && disk_bytenr > 0) {
843 				btrfs_init_generic_ref(&ref,
844 						BTRFS_ADD_DELAYED_REF,
845 						disk_bytenr, num_bytes, 0);
846 				btrfs_init_data_ref(&ref,
847 						root->root_key.objectid,
848 						new_key.objectid,
849 						args->start - extent_offset,
850 						0, false);
851 				ret = btrfs_inc_extent_ref(trans, &ref);
852 				BUG_ON(ret); /* -ENOMEM */
853 			}
854 			key.offset = args->start;
855 		}
856 		/*
857 		 * From here on out we will have actually dropped something, so
858 		 * last_end can be updated.
859 		 */
860 		last_end = extent_end;
861 
862 		/*
863 		 *  | ---- range to drop ----- |
864 		 *      | -------- extent -------- |
865 		 */
866 		if (args->start <= key.offset && args->end < extent_end) {
867 			if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
868 				ret = -EOPNOTSUPP;
869 				break;
870 			}
871 
872 			memcpy(&new_key, &key, sizeof(new_key));
873 			new_key.offset = args->end;
874 			btrfs_set_item_key_safe(fs_info, path, &new_key);
875 
876 			extent_offset += args->end - key.offset;
877 			btrfs_set_file_extent_offset(leaf, fi, extent_offset);
878 			btrfs_set_file_extent_num_bytes(leaf, fi,
879 							extent_end - args->end);
880 			btrfs_mark_buffer_dirty(leaf);
881 			if (update_refs && disk_bytenr > 0)
882 				args->bytes_found += args->end - key.offset;
883 			break;
884 		}
885 
886 		search_start = extent_end;
887 		/*
888 		 *       | ---- range to drop ----- |
889 		 *  | -------- extent -------- |
890 		 */
891 		if (args->start > key.offset && args->end >= extent_end) {
892 			BUG_ON(del_nr > 0);
893 			if (extent_type == BTRFS_FILE_EXTENT_INLINE) {
894 				ret = -EOPNOTSUPP;
895 				break;
896 			}
897 
898 			btrfs_set_file_extent_num_bytes(leaf, fi,
899 							args->start - key.offset);
900 			btrfs_mark_buffer_dirty(leaf);
901 			if (update_refs && disk_bytenr > 0)
902 				args->bytes_found += extent_end - args->start;
903 			if (args->end == extent_end)
904 				break;
905 
906 			path->slots[0]++;
907 			goto next_slot;
908 		}
909 
910 		/*
911 		 *  | ---- range to drop ----- |
912 		 *    | ------ extent ------ |
913 		 */
914 		if (args->start <= key.offset && args->end >= extent_end) {
915 delete_extent_item:
916 			if (del_nr == 0) {
917 				del_slot = path->slots[0];
918 				del_nr = 1;
919 			} else {
920 				BUG_ON(del_slot + del_nr != path->slots[0]);
921 				del_nr++;
922 			}
923 
924 			if (update_refs &&
925 			    extent_type == BTRFS_FILE_EXTENT_INLINE) {
926 				args->bytes_found += extent_end - key.offset;
927 				extent_end = ALIGN(extent_end,
928 						   fs_info->sectorsize);
929 			} else if (update_refs && disk_bytenr > 0) {
930 				btrfs_init_generic_ref(&ref,
931 						BTRFS_DROP_DELAYED_REF,
932 						disk_bytenr, num_bytes, 0);
933 				btrfs_init_data_ref(&ref,
934 						root->root_key.objectid,
935 						key.objectid,
936 						key.offset - extent_offset, 0,
937 						false);
938 				ret = btrfs_free_extent(trans, &ref);
939 				BUG_ON(ret); /* -ENOMEM */
940 				args->bytes_found += extent_end - key.offset;
941 			}
942 
943 			if (args->end == extent_end)
944 				break;
945 
946 			if (path->slots[0] + 1 < btrfs_header_nritems(leaf)) {
947 				path->slots[0]++;
948 				goto next_slot;
949 			}
950 
951 			ret = btrfs_del_items(trans, root, path, del_slot,
952 					      del_nr);
953 			if (ret) {
954 				btrfs_abort_transaction(trans, ret);
955 				break;
956 			}
957 
958 			del_nr = 0;
959 			del_slot = 0;
960 
961 			btrfs_release_path(path);
962 			continue;
963 		}
964 
965 		BUG();
966 	}
967 
968 	if (!ret && del_nr > 0) {
969 		/*
970 		 * Set path->slots[0] to first slot, so that after the delete
971 		 * if items are move off from our leaf to its immediate left or
972 		 * right neighbor leafs, we end up with a correct and adjusted
973 		 * path->slots[0] for our insertion (if args->replace_extent).
974 		 */
975 		path->slots[0] = del_slot;
976 		ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
977 		if (ret)
978 			btrfs_abort_transaction(trans, ret);
979 	}
980 
981 	leaf = path->nodes[0];
982 	/*
983 	 * If btrfs_del_items() was called, it might have deleted a leaf, in
984 	 * which case it unlocked our path, so check path->locks[0] matches a
985 	 * write lock.
986 	 */
987 	if (!ret && args->replace_extent &&
988 	    path->locks[0] == BTRFS_WRITE_LOCK &&
989 	    btrfs_leaf_free_space(leaf) >=
990 	    sizeof(struct btrfs_item) + args->extent_item_size) {
991 
992 		key.objectid = ino;
993 		key.type = BTRFS_EXTENT_DATA_KEY;
994 		key.offset = args->start;
995 		if (!del_nr && path->slots[0] < btrfs_header_nritems(leaf)) {
996 			struct btrfs_key slot_key;
997 
998 			btrfs_item_key_to_cpu(leaf, &slot_key, path->slots[0]);
999 			if (btrfs_comp_cpu_keys(&key, &slot_key) > 0)
1000 				path->slots[0]++;
1001 		}
1002 		btrfs_setup_item_for_insert(root, path, &key, args->extent_item_size);
1003 		args->extent_inserted = true;
1004 	}
1005 
1006 	if (!args->path)
1007 		btrfs_free_path(path);
1008 	else if (!args->extent_inserted)
1009 		btrfs_release_path(path);
1010 out:
1011 	args->drop_end = found ? min(args->end, last_end) : args->end;
1012 
1013 	return ret;
1014 }
1015 
1016 static int extent_mergeable(struct extent_buffer *leaf, int slot,
1017 			    u64 objectid, u64 bytenr, u64 orig_offset,
1018 			    u64 *start, u64 *end)
1019 {
1020 	struct btrfs_file_extent_item *fi;
1021 	struct btrfs_key key;
1022 	u64 extent_end;
1023 
1024 	if (slot < 0 || slot >= btrfs_header_nritems(leaf))
1025 		return 0;
1026 
1027 	btrfs_item_key_to_cpu(leaf, &key, slot);
1028 	if (key.objectid != objectid || key.type != BTRFS_EXTENT_DATA_KEY)
1029 		return 0;
1030 
1031 	fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
1032 	if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG ||
1033 	    btrfs_file_extent_disk_bytenr(leaf, fi) != bytenr ||
1034 	    btrfs_file_extent_offset(leaf, fi) != key.offset - orig_offset ||
1035 	    btrfs_file_extent_compression(leaf, fi) ||
1036 	    btrfs_file_extent_encryption(leaf, fi) ||
1037 	    btrfs_file_extent_other_encoding(leaf, fi))
1038 		return 0;
1039 
1040 	extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
1041 	if ((*start && *start != key.offset) || (*end && *end != extent_end))
1042 		return 0;
1043 
1044 	*start = key.offset;
1045 	*end = extent_end;
1046 	return 1;
1047 }
1048 
1049 /*
1050  * Mark extent in the range start - end as written.
1051  *
1052  * This changes extent type from 'pre-allocated' to 'regular'. If only
1053  * part of extent is marked as written, the extent will be split into
1054  * two or three.
1055  */
1056 int btrfs_mark_extent_written(struct btrfs_trans_handle *trans,
1057 			      struct btrfs_inode *inode, u64 start, u64 end)
1058 {
1059 	struct btrfs_fs_info *fs_info = trans->fs_info;
1060 	struct btrfs_root *root = inode->root;
1061 	struct extent_buffer *leaf;
1062 	struct btrfs_path *path;
1063 	struct btrfs_file_extent_item *fi;
1064 	struct btrfs_ref ref = { 0 };
1065 	struct btrfs_key key;
1066 	struct btrfs_key new_key;
1067 	u64 bytenr;
1068 	u64 num_bytes;
1069 	u64 extent_end;
1070 	u64 orig_offset;
1071 	u64 other_start;
1072 	u64 other_end;
1073 	u64 split;
1074 	int del_nr = 0;
1075 	int del_slot = 0;
1076 	int recow;
1077 	int ret = 0;
1078 	u64 ino = btrfs_ino(inode);
1079 
1080 	path = btrfs_alloc_path();
1081 	if (!path)
1082 		return -ENOMEM;
1083 again:
1084 	recow = 0;
1085 	split = start;
1086 	key.objectid = ino;
1087 	key.type = BTRFS_EXTENT_DATA_KEY;
1088 	key.offset = split;
1089 
1090 	ret = btrfs_search_slot(trans, root, &key, path, -1, 1);
1091 	if (ret < 0)
1092 		goto out;
1093 	if (ret > 0 && path->slots[0] > 0)
1094 		path->slots[0]--;
1095 
1096 	leaf = path->nodes[0];
1097 	btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
1098 	if (key.objectid != ino ||
1099 	    key.type != BTRFS_EXTENT_DATA_KEY) {
1100 		ret = -EINVAL;
1101 		btrfs_abort_transaction(trans, ret);
1102 		goto out;
1103 	}
1104 	fi = btrfs_item_ptr(leaf, path->slots[0],
1105 			    struct btrfs_file_extent_item);
1106 	if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_PREALLOC) {
1107 		ret = -EINVAL;
1108 		btrfs_abort_transaction(trans, ret);
1109 		goto out;
1110 	}
1111 	extent_end = key.offset + btrfs_file_extent_num_bytes(leaf, fi);
1112 	if (key.offset > start || extent_end < end) {
1113 		ret = -EINVAL;
1114 		btrfs_abort_transaction(trans, ret);
1115 		goto out;
1116 	}
1117 
1118 	bytenr = btrfs_file_extent_disk_bytenr(leaf, fi);
1119 	num_bytes = btrfs_file_extent_disk_num_bytes(leaf, fi);
1120 	orig_offset = key.offset - btrfs_file_extent_offset(leaf, fi);
1121 	memcpy(&new_key, &key, sizeof(new_key));
1122 
1123 	if (start == key.offset && end < extent_end) {
1124 		other_start = 0;
1125 		other_end = start;
1126 		if (extent_mergeable(leaf, path->slots[0] - 1,
1127 				     ino, bytenr, orig_offset,
1128 				     &other_start, &other_end)) {
1129 			new_key.offset = end;
1130 			btrfs_set_item_key_safe(fs_info, path, &new_key);
1131 			fi = btrfs_item_ptr(leaf, path->slots[0],
1132 					    struct btrfs_file_extent_item);
1133 			btrfs_set_file_extent_generation(leaf, fi,
1134 							 trans->transid);
1135 			btrfs_set_file_extent_num_bytes(leaf, fi,
1136 							extent_end - end);
1137 			btrfs_set_file_extent_offset(leaf, fi,
1138 						     end - orig_offset);
1139 			fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
1140 					    struct btrfs_file_extent_item);
1141 			btrfs_set_file_extent_generation(leaf, fi,
1142 							 trans->transid);
1143 			btrfs_set_file_extent_num_bytes(leaf, fi,
1144 							end - other_start);
1145 			btrfs_mark_buffer_dirty(leaf);
1146 			goto out;
1147 		}
1148 	}
1149 
1150 	if (start > key.offset && end == extent_end) {
1151 		other_start = end;
1152 		other_end = 0;
1153 		if (extent_mergeable(leaf, path->slots[0] + 1,
1154 				     ino, bytenr, orig_offset,
1155 				     &other_start, &other_end)) {
1156 			fi = btrfs_item_ptr(leaf, path->slots[0],
1157 					    struct btrfs_file_extent_item);
1158 			btrfs_set_file_extent_num_bytes(leaf, fi,
1159 							start - key.offset);
1160 			btrfs_set_file_extent_generation(leaf, fi,
1161 							 trans->transid);
1162 			path->slots[0]++;
1163 			new_key.offset = start;
1164 			btrfs_set_item_key_safe(fs_info, path, &new_key);
1165 
1166 			fi = btrfs_item_ptr(leaf, path->slots[0],
1167 					    struct btrfs_file_extent_item);
1168 			btrfs_set_file_extent_generation(leaf, fi,
1169 							 trans->transid);
1170 			btrfs_set_file_extent_num_bytes(leaf, fi,
1171 							other_end - start);
1172 			btrfs_set_file_extent_offset(leaf, fi,
1173 						     start - orig_offset);
1174 			btrfs_mark_buffer_dirty(leaf);
1175 			goto out;
1176 		}
1177 	}
1178 
1179 	while (start > key.offset || end < extent_end) {
1180 		if (key.offset == start)
1181 			split = end;
1182 
1183 		new_key.offset = split;
1184 		ret = btrfs_duplicate_item(trans, root, path, &new_key);
1185 		if (ret == -EAGAIN) {
1186 			btrfs_release_path(path);
1187 			goto again;
1188 		}
1189 		if (ret < 0) {
1190 			btrfs_abort_transaction(trans, ret);
1191 			goto out;
1192 		}
1193 
1194 		leaf = path->nodes[0];
1195 		fi = btrfs_item_ptr(leaf, path->slots[0] - 1,
1196 				    struct btrfs_file_extent_item);
1197 		btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1198 		btrfs_set_file_extent_num_bytes(leaf, fi,
1199 						split - key.offset);
1200 
1201 		fi = btrfs_item_ptr(leaf, path->slots[0],
1202 				    struct btrfs_file_extent_item);
1203 
1204 		btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1205 		btrfs_set_file_extent_offset(leaf, fi, split - orig_offset);
1206 		btrfs_set_file_extent_num_bytes(leaf, fi,
1207 						extent_end - split);
1208 		btrfs_mark_buffer_dirty(leaf);
1209 
1210 		btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF, bytenr,
1211 				       num_bytes, 0);
1212 		btrfs_init_data_ref(&ref, root->root_key.objectid, ino,
1213 				    orig_offset, 0, false);
1214 		ret = btrfs_inc_extent_ref(trans, &ref);
1215 		if (ret) {
1216 			btrfs_abort_transaction(trans, ret);
1217 			goto out;
1218 		}
1219 
1220 		if (split == start) {
1221 			key.offset = start;
1222 		} else {
1223 			if (start != key.offset) {
1224 				ret = -EINVAL;
1225 				btrfs_abort_transaction(trans, ret);
1226 				goto out;
1227 			}
1228 			path->slots[0]--;
1229 			extent_end = end;
1230 		}
1231 		recow = 1;
1232 	}
1233 
1234 	other_start = end;
1235 	other_end = 0;
1236 	btrfs_init_generic_ref(&ref, BTRFS_DROP_DELAYED_REF, bytenr,
1237 			       num_bytes, 0);
1238 	btrfs_init_data_ref(&ref, root->root_key.objectid, ino, orig_offset,
1239 			    0, false);
1240 	if (extent_mergeable(leaf, path->slots[0] + 1,
1241 			     ino, bytenr, orig_offset,
1242 			     &other_start, &other_end)) {
1243 		if (recow) {
1244 			btrfs_release_path(path);
1245 			goto again;
1246 		}
1247 		extent_end = other_end;
1248 		del_slot = path->slots[0] + 1;
1249 		del_nr++;
1250 		ret = btrfs_free_extent(trans, &ref);
1251 		if (ret) {
1252 			btrfs_abort_transaction(trans, ret);
1253 			goto out;
1254 		}
1255 	}
1256 	other_start = 0;
1257 	other_end = start;
1258 	if (extent_mergeable(leaf, path->slots[0] - 1,
1259 			     ino, bytenr, orig_offset,
1260 			     &other_start, &other_end)) {
1261 		if (recow) {
1262 			btrfs_release_path(path);
1263 			goto again;
1264 		}
1265 		key.offset = other_start;
1266 		del_slot = path->slots[0];
1267 		del_nr++;
1268 		ret = btrfs_free_extent(trans, &ref);
1269 		if (ret) {
1270 			btrfs_abort_transaction(trans, ret);
1271 			goto out;
1272 		}
1273 	}
1274 	if (del_nr == 0) {
1275 		fi = btrfs_item_ptr(leaf, path->slots[0],
1276 			   struct btrfs_file_extent_item);
1277 		btrfs_set_file_extent_type(leaf, fi,
1278 					   BTRFS_FILE_EXTENT_REG);
1279 		btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1280 		btrfs_mark_buffer_dirty(leaf);
1281 	} else {
1282 		fi = btrfs_item_ptr(leaf, del_slot - 1,
1283 			   struct btrfs_file_extent_item);
1284 		btrfs_set_file_extent_type(leaf, fi,
1285 					   BTRFS_FILE_EXTENT_REG);
1286 		btrfs_set_file_extent_generation(leaf, fi, trans->transid);
1287 		btrfs_set_file_extent_num_bytes(leaf, fi,
1288 						extent_end - key.offset);
1289 		btrfs_mark_buffer_dirty(leaf);
1290 
1291 		ret = btrfs_del_items(trans, root, path, del_slot, del_nr);
1292 		if (ret < 0) {
1293 			btrfs_abort_transaction(trans, ret);
1294 			goto out;
1295 		}
1296 	}
1297 out:
1298 	btrfs_free_path(path);
1299 	return ret;
1300 }
1301 
1302 /*
1303  * on error we return an unlocked page and the error value
1304  * on success we return a locked page and 0
1305  */
1306 static int prepare_uptodate_page(struct inode *inode,
1307 				 struct page *page, u64 pos,
1308 				 bool force_uptodate)
1309 {
1310 	struct folio *folio = page_folio(page);
1311 	int ret = 0;
1312 
1313 	if (((pos & (PAGE_SIZE - 1)) || force_uptodate) &&
1314 	    !PageUptodate(page)) {
1315 		ret = btrfs_read_folio(NULL, folio);
1316 		if (ret)
1317 			return ret;
1318 		lock_page(page);
1319 		if (!PageUptodate(page)) {
1320 			unlock_page(page);
1321 			return -EIO;
1322 		}
1323 
1324 		/*
1325 		 * Since btrfs_read_folio() will unlock the folio before it
1326 		 * returns, there is a window where btrfs_release_folio() can be
1327 		 * called to release the page.  Here we check both inode
1328 		 * mapping and PagePrivate() to make sure the page was not
1329 		 * released.
1330 		 *
1331 		 * The private flag check is essential for subpage as we need
1332 		 * to store extra bitmap using page->private.
1333 		 */
1334 		if (page->mapping != inode->i_mapping || !PagePrivate(page)) {
1335 			unlock_page(page);
1336 			return -EAGAIN;
1337 		}
1338 	}
1339 	return 0;
1340 }
1341 
1342 /*
1343  * this just gets pages into the page cache and locks them down.
1344  */
1345 static noinline int prepare_pages(struct inode *inode, struct page **pages,
1346 				  size_t num_pages, loff_t pos,
1347 				  size_t write_bytes, bool force_uptodate)
1348 {
1349 	int i;
1350 	unsigned long index = pos >> PAGE_SHIFT;
1351 	gfp_t mask = btrfs_alloc_write_mask(inode->i_mapping);
1352 	int err = 0;
1353 	int faili;
1354 
1355 	for (i = 0; i < num_pages; i++) {
1356 again:
1357 		pages[i] = find_or_create_page(inode->i_mapping, index + i,
1358 					       mask | __GFP_WRITE);
1359 		if (!pages[i]) {
1360 			faili = i - 1;
1361 			err = -ENOMEM;
1362 			goto fail;
1363 		}
1364 
1365 		err = set_page_extent_mapped(pages[i]);
1366 		if (err < 0) {
1367 			faili = i;
1368 			goto fail;
1369 		}
1370 
1371 		if (i == 0)
1372 			err = prepare_uptodate_page(inode, pages[i], pos,
1373 						    force_uptodate);
1374 		if (!err && i == num_pages - 1)
1375 			err = prepare_uptodate_page(inode, pages[i],
1376 						    pos + write_bytes, false);
1377 		if (err) {
1378 			put_page(pages[i]);
1379 			if (err == -EAGAIN) {
1380 				err = 0;
1381 				goto again;
1382 			}
1383 			faili = i - 1;
1384 			goto fail;
1385 		}
1386 		wait_on_page_writeback(pages[i]);
1387 	}
1388 
1389 	return 0;
1390 fail:
1391 	while (faili >= 0) {
1392 		unlock_page(pages[faili]);
1393 		put_page(pages[faili]);
1394 		faili--;
1395 	}
1396 	return err;
1397 
1398 }
1399 
1400 /*
1401  * This function locks the extent and properly waits for data=ordered extents
1402  * to finish before allowing the pages to be modified if need.
1403  *
1404  * The return value:
1405  * 1 - the extent is locked
1406  * 0 - the extent is not locked, and everything is OK
1407  * -EAGAIN - need re-prepare the pages
1408  * the other < 0 number - Something wrong happens
1409  */
1410 static noinline int
1411 lock_and_cleanup_extent_if_need(struct btrfs_inode *inode, struct page **pages,
1412 				size_t num_pages, loff_t pos,
1413 				size_t write_bytes,
1414 				u64 *lockstart, u64 *lockend,
1415 				struct extent_state **cached_state)
1416 {
1417 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
1418 	u64 start_pos;
1419 	u64 last_pos;
1420 	int i;
1421 	int ret = 0;
1422 
1423 	start_pos = round_down(pos, fs_info->sectorsize);
1424 	last_pos = round_up(pos + write_bytes, fs_info->sectorsize) - 1;
1425 
1426 	if (start_pos < inode->vfs_inode.i_size) {
1427 		struct btrfs_ordered_extent *ordered;
1428 
1429 		lock_extent_bits(&inode->io_tree, start_pos, last_pos,
1430 				cached_state);
1431 		ordered = btrfs_lookup_ordered_range(inode, start_pos,
1432 						     last_pos - start_pos + 1);
1433 		if (ordered &&
1434 		    ordered->file_offset + ordered->num_bytes > start_pos &&
1435 		    ordered->file_offset <= last_pos) {
1436 			unlock_extent_cached(&inode->io_tree, start_pos,
1437 					last_pos, cached_state);
1438 			for (i = 0; i < num_pages; i++) {
1439 				unlock_page(pages[i]);
1440 				put_page(pages[i]);
1441 			}
1442 			btrfs_start_ordered_extent(ordered, 1);
1443 			btrfs_put_ordered_extent(ordered);
1444 			return -EAGAIN;
1445 		}
1446 		if (ordered)
1447 			btrfs_put_ordered_extent(ordered);
1448 
1449 		*lockstart = start_pos;
1450 		*lockend = last_pos;
1451 		ret = 1;
1452 	}
1453 
1454 	/*
1455 	 * We should be called after prepare_pages() which should have locked
1456 	 * all pages in the range.
1457 	 */
1458 	for (i = 0; i < num_pages; i++)
1459 		WARN_ON(!PageLocked(pages[i]));
1460 
1461 	return ret;
1462 }
1463 
1464 /*
1465  * Check if we can do nocow write into the range [@pos, @pos + @write_bytes)
1466  *
1467  * @pos:         File offset.
1468  * @write_bytes: The length to write, will be updated to the nocow writeable
1469  *               range.
1470  *
1471  * This function will flush ordered extents in the range to ensure proper
1472  * nocow checks.
1473  *
1474  * Return:
1475  * > 0          If we can nocow, and updates @write_bytes.
1476  *  0           If we can't do a nocow write.
1477  * -EAGAIN      If we can't do a nocow write because snapshoting of the inode's
1478  *              root is in progress.
1479  * < 0          If an error happened.
1480  *
1481  * NOTE: Callers need to call btrfs_check_nocow_unlock() if we return > 0.
1482  */
1483 int btrfs_check_nocow_lock(struct btrfs_inode *inode, loff_t pos,
1484 			   size_t *write_bytes)
1485 {
1486 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
1487 	struct btrfs_root *root = inode->root;
1488 	u64 lockstart, lockend;
1489 	u64 num_bytes;
1490 	int ret;
1491 
1492 	if (!(inode->flags & (BTRFS_INODE_NODATACOW | BTRFS_INODE_PREALLOC)))
1493 		return 0;
1494 
1495 	if (!btrfs_drew_try_write_lock(&root->snapshot_lock))
1496 		return -EAGAIN;
1497 
1498 	lockstart = round_down(pos, fs_info->sectorsize);
1499 	lockend = round_up(pos + *write_bytes,
1500 			   fs_info->sectorsize) - 1;
1501 	num_bytes = lockend - lockstart + 1;
1502 
1503 	btrfs_lock_and_flush_ordered_range(inode, lockstart, lockend, NULL);
1504 	ret = can_nocow_extent(&inode->vfs_inode, lockstart, &num_bytes,
1505 			NULL, NULL, NULL, false);
1506 	if (ret <= 0) {
1507 		ret = 0;
1508 		btrfs_drew_write_unlock(&root->snapshot_lock);
1509 	} else {
1510 		*write_bytes = min_t(size_t, *write_bytes ,
1511 				     num_bytes - pos + lockstart);
1512 	}
1513 	unlock_extent(&inode->io_tree, lockstart, lockend);
1514 
1515 	return ret;
1516 }
1517 
1518 void btrfs_check_nocow_unlock(struct btrfs_inode *inode)
1519 {
1520 	btrfs_drew_write_unlock(&inode->root->snapshot_lock);
1521 }
1522 
1523 static void update_time_for_write(struct inode *inode)
1524 {
1525 	struct timespec64 now;
1526 
1527 	if (IS_NOCMTIME(inode))
1528 		return;
1529 
1530 	now = current_time(inode);
1531 	if (!timespec64_equal(&inode->i_mtime, &now))
1532 		inode->i_mtime = now;
1533 
1534 	if (!timespec64_equal(&inode->i_ctime, &now))
1535 		inode->i_ctime = now;
1536 
1537 	if (IS_I_VERSION(inode))
1538 		inode_inc_iversion(inode);
1539 }
1540 
1541 static int btrfs_write_check(struct kiocb *iocb, struct iov_iter *from,
1542 			     size_t count)
1543 {
1544 	struct file *file = iocb->ki_filp;
1545 	struct inode *inode = file_inode(file);
1546 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1547 	loff_t pos = iocb->ki_pos;
1548 	int ret;
1549 	loff_t oldsize;
1550 	loff_t start_pos;
1551 
1552 	/*
1553 	 * Quickly bail out on NOWAIT writes if we don't have the nodatacow or
1554 	 * prealloc flags, as without those flags we always have to COW. We will
1555 	 * later check if we can really COW into the target range (using
1556 	 * can_nocow_extent() at btrfs_get_blocks_direct_write()).
1557 	 */
1558 	if ((iocb->ki_flags & IOCB_NOWAIT) &&
1559 	    !(BTRFS_I(inode)->flags & (BTRFS_INODE_NODATACOW | BTRFS_INODE_PREALLOC)))
1560 		return -EAGAIN;
1561 
1562 	current->backing_dev_info = inode_to_bdi(inode);
1563 	ret = file_remove_privs(file);
1564 	if (ret)
1565 		return ret;
1566 
1567 	/*
1568 	 * We reserve space for updating the inode when we reserve space for the
1569 	 * extent we are going to write, so we will enospc out there.  We don't
1570 	 * need to start yet another transaction to update the inode as we will
1571 	 * update the inode when we finish writing whatever data we write.
1572 	 */
1573 	update_time_for_write(inode);
1574 
1575 	start_pos = round_down(pos, fs_info->sectorsize);
1576 	oldsize = i_size_read(inode);
1577 	if (start_pos > oldsize) {
1578 		/* Expand hole size to cover write data, preventing empty gap */
1579 		loff_t end_pos = round_up(pos + count, fs_info->sectorsize);
1580 
1581 		ret = btrfs_cont_expand(BTRFS_I(inode), oldsize, end_pos);
1582 		if (ret) {
1583 			current->backing_dev_info = NULL;
1584 			return ret;
1585 		}
1586 	}
1587 
1588 	return 0;
1589 }
1590 
1591 static noinline ssize_t btrfs_buffered_write(struct kiocb *iocb,
1592 					       struct iov_iter *i)
1593 {
1594 	struct file *file = iocb->ki_filp;
1595 	loff_t pos;
1596 	struct inode *inode = file_inode(file);
1597 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1598 	struct page **pages = NULL;
1599 	struct extent_changeset *data_reserved = NULL;
1600 	u64 release_bytes = 0;
1601 	u64 lockstart;
1602 	u64 lockend;
1603 	size_t num_written = 0;
1604 	int nrptrs;
1605 	ssize_t ret;
1606 	bool only_release_metadata = false;
1607 	bool force_page_uptodate = false;
1608 	loff_t old_isize = i_size_read(inode);
1609 	unsigned int ilock_flags = 0;
1610 
1611 	if (iocb->ki_flags & IOCB_NOWAIT)
1612 		ilock_flags |= BTRFS_ILOCK_TRY;
1613 
1614 	ret = btrfs_inode_lock(inode, ilock_flags);
1615 	if (ret < 0)
1616 		return ret;
1617 
1618 	ret = generic_write_checks(iocb, i);
1619 	if (ret <= 0)
1620 		goto out;
1621 
1622 	ret = btrfs_write_check(iocb, i, ret);
1623 	if (ret < 0)
1624 		goto out;
1625 
1626 	pos = iocb->ki_pos;
1627 	nrptrs = min(DIV_ROUND_UP(iov_iter_count(i), PAGE_SIZE),
1628 			PAGE_SIZE / (sizeof(struct page *)));
1629 	nrptrs = min(nrptrs, current->nr_dirtied_pause - current->nr_dirtied);
1630 	nrptrs = max(nrptrs, 8);
1631 	pages = kmalloc_array(nrptrs, sizeof(struct page *), GFP_KERNEL);
1632 	if (!pages) {
1633 		ret = -ENOMEM;
1634 		goto out;
1635 	}
1636 
1637 	while (iov_iter_count(i) > 0) {
1638 		struct extent_state *cached_state = NULL;
1639 		size_t offset = offset_in_page(pos);
1640 		size_t sector_offset;
1641 		size_t write_bytes = min(iov_iter_count(i),
1642 					 nrptrs * (size_t)PAGE_SIZE -
1643 					 offset);
1644 		size_t num_pages;
1645 		size_t reserve_bytes;
1646 		size_t dirty_pages;
1647 		size_t copied;
1648 		size_t dirty_sectors;
1649 		size_t num_sectors;
1650 		int extents_locked;
1651 
1652 		/*
1653 		 * Fault pages before locking them in prepare_pages
1654 		 * to avoid recursive lock
1655 		 */
1656 		if (unlikely(fault_in_iov_iter_readable(i, write_bytes))) {
1657 			ret = -EFAULT;
1658 			break;
1659 		}
1660 
1661 		only_release_metadata = false;
1662 		sector_offset = pos & (fs_info->sectorsize - 1);
1663 
1664 		extent_changeset_release(data_reserved);
1665 		ret = btrfs_check_data_free_space(BTRFS_I(inode),
1666 						  &data_reserved, pos,
1667 						  write_bytes);
1668 		if (ret < 0) {
1669 			/*
1670 			 * If we don't have to COW at the offset, reserve
1671 			 * metadata only. write_bytes may get smaller than
1672 			 * requested here.
1673 			 */
1674 			if (btrfs_check_nocow_lock(BTRFS_I(inode), pos,
1675 						   &write_bytes) > 0)
1676 				only_release_metadata = true;
1677 			else
1678 				break;
1679 		}
1680 
1681 		num_pages = DIV_ROUND_UP(write_bytes + offset, PAGE_SIZE);
1682 		WARN_ON(num_pages > nrptrs);
1683 		reserve_bytes = round_up(write_bytes + sector_offset,
1684 					 fs_info->sectorsize);
1685 		WARN_ON(reserve_bytes == 0);
1686 		ret = btrfs_delalloc_reserve_metadata(BTRFS_I(inode),
1687 						      reserve_bytes,
1688 						      reserve_bytes, false);
1689 		if (ret) {
1690 			if (!only_release_metadata)
1691 				btrfs_free_reserved_data_space(BTRFS_I(inode),
1692 						data_reserved, pos,
1693 						write_bytes);
1694 			else
1695 				btrfs_check_nocow_unlock(BTRFS_I(inode));
1696 			break;
1697 		}
1698 
1699 		release_bytes = reserve_bytes;
1700 again:
1701 		/*
1702 		 * This is going to setup the pages array with the number of
1703 		 * pages we want, so we don't really need to worry about the
1704 		 * contents of pages from loop to loop
1705 		 */
1706 		ret = prepare_pages(inode, pages, num_pages,
1707 				    pos, write_bytes,
1708 				    force_page_uptodate);
1709 		if (ret) {
1710 			btrfs_delalloc_release_extents(BTRFS_I(inode),
1711 						       reserve_bytes);
1712 			break;
1713 		}
1714 
1715 		extents_locked = lock_and_cleanup_extent_if_need(
1716 				BTRFS_I(inode), pages,
1717 				num_pages, pos, write_bytes, &lockstart,
1718 				&lockend, &cached_state);
1719 		if (extents_locked < 0) {
1720 			if (extents_locked == -EAGAIN)
1721 				goto again;
1722 			btrfs_delalloc_release_extents(BTRFS_I(inode),
1723 						       reserve_bytes);
1724 			ret = extents_locked;
1725 			break;
1726 		}
1727 
1728 		copied = btrfs_copy_from_user(pos, write_bytes, pages, i);
1729 
1730 		num_sectors = BTRFS_BYTES_TO_BLKS(fs_info, reserve_bytes);
1731 		dirty_sectors = round_up(copied + sector_offset,
1732 					fs_info->sectorsize);
1733 		dirty_sectors = BTRFS_BYTES_TO_BLKS(fs_info, dirty_sectors);
1734 
1735 		/*
1736 		 * if we have trouble faulting in the pages, fall
1737 		 * back to one page at a time
1738 		 */
1739 		if (copied < write_bytes)
1740 			nrptrs = 1;
1741 
1742 		if (copied == 0) {
1743 			force_page_uptodate = true;
1744 			dirty_sectors = 0;
1745 			dirty_pages = 0;
1746 		} else {
1747 			force_page_uptodate = false;
1748 			dirty_pages = DIV_ROUND_UP(copied + offset,
1749 						   PAGE_SIZE);
1750 		}
1751 
1752 		if (num_sectors > dirty_sectors) {
1753 			/* release everything except the sectors we dirtied */
1754 			release_bytes -= dirty_sectors << fs_info->sectorsize_bits;
1755 			if (only_release_metadata) {
1756 				btrfs_delalloc_release_metadata(BTRFS_I(inode),
1757 							release_bytes, true);
1758 			} else {
1759 				u64 __pos;
1760 
1761 				__pos = round_down(pos,
1762 						   fs_info->sectorsize) +
1763 					(dirty_pages << PAGE_SHIFT);
1764 				btrfs_delalloc_release_space(BTRFS_I(inode),
1765 						data_reserved, __pos,
1766 						release_bytes, true);
1767 			}
1768 		}
1769 
1770 		release_bytes = round_up(copied + sector_offset,
1771 					fs_info->sectorsize);
1772 
1773 		ret = btrfs_dirty_pages(BTRFS_I(inode), pages,
1774 					dirty_pages, pos, copied,
1775 					&cached_state, only_release_metadata);
1776 
1777 		/*
1778 		 * If we have not locked the extent range, because the range's
1779 		 * start offset is >= i_size, we might still have a non-NULL
1780 		 * cached extent state, acquired while marking the extent range
1781 		 * as delalloc through btrfs_dirty_pages(). Therefore free any
1782 		 * possible cached extent state to avoid a memory leak.
1783 		 */
1784 		if (extents_locked)
1785 			unlock_extent_cached(&BTRFS_I(inode)->io_tree,
1786 					     lockstart, lockend, &cached_state);
1787 		else
1788 			free_extent_state(cached_state);
1789 
1790 		btrfs_delalloc_release_extents(BTRFS_I(inode), reserve_bytes);
1791 		if (ret) {
1792 			btrfs_drop_pages(fs_info, pages, num_pages, pos, copied);
1793 			break;
1794 		}
1795 
1796 		release_bytes = 0;
1797 		if (only_release_metadata)
1798 			btrfs_check_nocow_unlock(BTRFS_I(inode));
1799 
1800 		btrfs_drop_pages(fs_info, pages, num_pages, pos, copied);
1801 
1802 		cond_resched();
1803 
1804 		balance_dirty_pages_ratelimited(inode->i_mapping);
1805 
1806 		pos += copied;
1807 		num_written += copied;
1808 	}
1809 
1810 	kfree(pages);
1811 
1812 	if (release_bytes) {
1813 		if (only_release_metadata) {
1814 			btrfs_check_nocow_unlock(BTRFS_I(inode));
1815 			btrfs_delalloc_release_metadata(BTRFS_I(inode),
1816 					release_bytes, true);
1817 		} else {
1818 			btrfs_delalloc_release_space(BTRFS_I(inode),
1819 					data_reserved,
1820 					round_down(pos, fs_info->sectorsize),
1821 					release_bytes, true);
1822 		}
1823 	}
1824 
1825 	extent_changeset_free(data_reserved);
1826 	if (num_written > 0) {
1827 		pagecache_isize_extended(inode, old_isize, iocb->ki_pos);
1828 		iocb->ki_pos += num_written;
1829 	}
1830 out:
1831 	btrfs_inode_unlock(inode, ilock_flags);
1832 	return num_written ? num_written : ret;
1833 }
1834 
1835 static ssize_t check_direct_IO(struct btrfs_fs_info *fs_info,
1836 			       const struct iov_iter *iter, loff_t offset)
1837 {
1838 	const u32 blocksize_mask = fs_info->sectorsize - 1;
1839 
1840 	if (offset & blocksize_mask)
1841 		return -EINVAL;
1842 
1843 	if (iov_iter_alignment(iter) & blocksize_mask)
1844 		return -EINVAL;
1845 
1846 	return 0;
1847 }
1848 
1849 static ssize_t btrfs_direct_write(struct kiocb *iocb, struct iov_iter *from)
1850 {
1851 	struct file *file = iocb->ki_filp;
1852 	struct inode *inode = file_inode(file);
1853 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1854 	loff_t pos;
1855 	ssize_t written = 0;
1856 	ssize_t written_buffered;
1857 	size_t prev_left = 0;
1858 	loff_t endbyte;
1859 	ssize_t err;
1860 	unsigned int ilock_flags = 0;
1861 
1862 	if (iocb->ki_flags & IOCB_NOWAIT)
1863 		ilock_flags |= BTRFS_ILOCK_TRY;
1864 
1865 	/* If the write DIO is within EOF, use a shared lock */
1866 	if (iocb->ki_pos + iov_iter_count(from) <= i_size_read(inode))
1867 		ilock_flags |= BTRFS_ILOCK_SHARED;
1868 
1869 relock:
1870 	err = btrfs_inode_lock(inode, ilock_flags);
1871 	if (err < 0)
1872 		return err;
1873 
1874 	err = generic_write_checks(iocb, from);
1875 	if (err <= 0) {
1876 		btrfs_inode_unlock(inode, ilock_flags);
1877 		return err;
1878 	}
1879 
1880 	err = btrfs_write_check(iocb, from, err);
1881 	if (err < 0) {
1882 		btrfs_inode_unlock(inode, ilock_flags);
1883 		goto out;
1884 	}
1885 
1886 	pos = iocb->ki_pos;
1887 	/*
1888 	 * Re-check since file size may have changed just before taking the
1889 	 * lock or pos may have changed because of O_APPEND in generic_write_check()
1890 	 */
1891 	if ((ilock_flags & BTRFS_ILOCK_SHARED) &&
1892 	    pos + iov_iter_count(from) > i_size_read(inode)) {
1893 		btrfs_inode_unlock(inode, ilock_flags);
1894 		ilock_flags &= ~BTRFS_ILOCK_SHARED;
1895 		goto relock;
1896 	}
1897 
1898 	if (check_direct_IO(fs_info, from, pos)) {
1899 		btrfs_inode_unlock(inode, ilock_flags);
1900 		goto buffered;
1901 	}
1902 
1903 	/*
1904 	 * The iov_iter can be mapped to the same file range we are writing to.
1905 	 * If that's the case, then we will deadlock in the iomap code, because
1906 	 * it first calls our callback btrfs_dio_iomap_begin(), which will create
1907 	 * an ordered extent, and after that it will fault in the pages that the
1908 	 * iov_iter refers to. During the fault in we end up in the readahead
1909 	 * pages code (starting at btrfs_readahead()), which will lock the range,
1910 	 * find that ordered extent and then wait for it to complete (at
1911 	 * btrfs_lock_and_flush_ordered_range()), resulting in a deadlock since
1912 	 * obviously the ordered extent can never complete as we didn't submit
1913 	 * yet the respective bio(s). This always happens when the buffer is
1914 	 * memory mapped to the same file range, since the iomap DIO code always
1915 	 * invalidates pages in the target file range (after starting and waiting
1916 	 * for any writeback).
1917 	 *
1918 	 * So here we disable page faults in the iov_iter and then retry if we
1919 	 * got -EFAULT, faulting in the pages before the retry.
1920 	 */
1921 again:
1922 	from->nofault = true;
1923 	err = btrfs_dio_rw(iocb, from, written);
1924 	from->nofault = false;
1925 
1926 	/* No increment (+=) because iomap returns a cumulative value. */
1927 	if (err > 0)
1928 		written = err;
1929 
1930 	if (iov_iter_count(from) > 0 && (err == -EFAULT || err > 0)) {
1931 		const size_t left = iov_iter_count(from);
1932 		/*
1933 		 * We have more data left to write. Try to fault in as many as
1934 		 * possible of the remainder pages and retry. We do this without
1935 		 * releasing and locking again the inode, to prevent races with
1936 		 * truncate.
1937 		 *
1938 		 * Also, in case the iov refers to pages in the file range of the
1939 		 * file we want to write to (due to a mmap), we could enter an
1940 		 * infinite loop if we retry after faulting the pages in, since
1941 		 * iomap will invalidate any pages in the range early on, before
1942 		 * it tries to fault in the pages of the iov. So we keep track of
1943 		 * how much was left of iov in the previous EFAULT and fallback
1944 		 * to buffered IO in case we haven't made any progress.
1945 		 */
1946 		if (left == prev_left) {
1947 			err = -ENOTBLK;
1948 		} else {
1949 			fault_in_iov_iter_readable(from, left);
1950 			prev_left = left;
1951 			goto again;
1952 		}
1953 	}
1954 
1955 	btrfs_inode_unlock(inode, ilock_flags);
1956 
1957 	/*
1958 	 * If 'err' is -ENOTBLK or we have not written all data, then it means
1959 	 * we must fallback to buffered IO.
1960 	 */
1961 	if ((err < 0 && err != -ENOTBLK) || !iov_iter_count(from))
1962 		goto out;
1963 
1964 buffered:
1965 	/*
1966 	 * If we are in a NOWAIT context, then return -EAGAIN to signal the caller
1967 	 * it must retry the operation in a context where blocking is acceptable,
1968 	 * since we currently don't have NOWAIT semantics support for buffered IO
1969 	 * and may block there for many reasons (reserving space for example).
1970 	 */
1971 	if (iocb->ki_flags & IOCB_NOWAIT) {
1972 		err = -EAGAIN;
1973 		goto out;
1974 	}
1975 
1976 	pos = iocb->ki_pos;
1977 	written_buffered = btrfs_buffered_write(iocb, from);
1978 	if (written_buffered < 0) {
1979 		err = written_buffered;
1980 		goto out;
1981 	}
1982 	/*
1983 	 * Ensure all data is persisted. We want the next direct IO read to be
1984 	 * able to read what was just written.
1985 	 */
1986 	endbyte = pos + written_buffered - 1;
1987 	err = btrfs_fdatawrite_range(inode, pos, endbyte);
1988 	if (err)
1989 		goto out;
1990 	err = filemap_fdatawait_range(inode->i_mapping, pos, endbyte);
1991 	if (err)
1992 		goto out;
1993 	written += written_buffered;
1994 	iocb->ki_pos = pos + written_buffered;
1995 	invalidate_mapping_pages(file->f_mapping, pos >> PAGE_SHIFT,
1996 				 endbyte >> PAGE_SHIFT);
1997 out:
1998 	return err < 0 ? err : written;
1999 }
2000 
2001 static ssize_t btrfs_encoded_write(struct kiocb *iocb, struct iov_iter *from,
2002 			const struct btrfs_ioctl_encoded_io_args *encoded)
2003 {
2004 	struct file *file = iocb->ki_filp;
2005 	struct inode *inode = file_inode(file);
2006 	loff_t count;
2007 	ssize_t ret;
2008 
2009 	btrfs_inode_lock(inode, 0);
2010 	count = encoded->len;
2011 	ret = generic_write_checks_count(iocb, &count);
2012 	if (ret == 0 && count != encoded->len) {
2013 		/*
2014 		 * The write got truncated by generic_write_checks_count(). We
2015 		 * can't do a partial encoded write.
2016 		 */
2017 		ret = -EFBIG;
2018 	}
2019 	if (ret || encoded->len == 0)
2020 		goto out;
2021 
2022 	ret = btrfs_write_check(iocb, from, encoded->len);
2023 	if (ret < 0)
2024 		goto out;
2025 
2026 	ret = btrfs_do_encoded_write(iocb, from, encoded);
2027 out:
2028 	btrfs_inode_unlock(inode, 0);
2029 	return ret;
2030 }
2031 
2032 ssize_t btrfs_do_write_iter(struct kiocb *iocb, struct iov_iter *from,
2033 			    const struct btrfs_ioctl_encoded_io_args *encoded)
2034 {
2035 	struct file *file = iocb->ki_filp;
2036 	struct btrfs_inode *inode = BTRFS_I(file_inode(file));
2037 	ssize_t num_written, num_sync;
2038 	const bool sync = iocb_is_dsync(iocb);
2039 
2040 	/*
2041 	 * If the fs flips readonly due to some impossible error, although we
2042 	 * have opened a file as writable, we have to stop this write operation
2043 	 * to ensure consistency.
2044 	 */
2045 	if (BTRFS_FS_ERROR(inode->root->fs_info))
2046 		return -EROFS;
2047 
2048 	if ((iocb->ki_flags & IOCB_NOWAIT) && !(iocb->ki_flags & IOCB_DIRECT))
2049 		return -EOPNOTSUPP;
2050 
2051 	if (sync)
2052 		atomic_inc(&inode->sync_writers);
2053 
2054 	if (encoded) {
2055 		num_written = btrfs_encoded_write(iocb, from, encoded);
2056 		num_sync = encoded->len;
2057 	} else if (iocb->ki_flags & IOCB_DIRECT) {
2058 		num_written = btrfs_direct_write(iocb, from);
2059 		num_sync = num_written;
2060 	} else {
2061 		num_written = btrfs_buffered_write(iocb, from);
2062 		num_sync = num_written;
2063 	}
2064 
2065 	btrfs_set_inode_last_sub_trans(inode);
2066 
2067 	if (num_sync > 0) {
2068 		num_sync = generic_write_sync(iocb, num_sync);
2069 		if (num_sync < 0)
2070 			num_written = num_sync;
2071 	}
2072 
2073 	if (sync)
2074 		atomic_dec(&inode->sync_writers);
2075 
2076 	current->backing_dev_info = NULL;
2077 	return num_written;
2078 }
2079 
2080 static ssize_t btrfs_file_write_iter(struct kiocb *iocb, struct iov_iter *from)
2081 {
2082 	return btrfs_do_write_iter(iocb, from, NULL);
2083 }
2084 
2085 int btrfs_release_file(struct inode *inode, struct file *filp)
2086 {
2087 	struct btrfs_file_private *private = filp->private_data;
2088 
2089 	if (private && private->filldir_buf)
2090 		kfree(private->filldir_buf);
2091 	kfree(private);
2092 	filp->private_data = NULL;
2093 
2094 	/*
2095 	 * Set by setattr when we are about to truncate a file from a non-zero
2096 	 * size to a zero size.  This tries to flush down new bytes that may
2097 	 * have been written if the application were using truncate to replace
2098 	 * a file in place.
2099 	 */
2100 	if (test_and_clear_bit(BTRFS_INODE_FLUSH_ON_CLOSE,
2101 			       &BTRFS_I(inode)->runtime_flags))
2102 			filemap_flush(inode->i_mapping);
2103 	return 0;
2104 }
2105 
2106 static int start_ordered_ops(struct inode *inode, loff_t start, loff_t end)
2107 {
2108 	int ret;
2109 	struct blk_plug plug;
2110 
2111 	/*
2112 	 * This is only called in fsync, which would do synchronous writes, so
2113 	 * a plug can merge adjacent IOs as much as possible.  Esp. in case of
2114 	 * multiple disks using raid profile, a large IO can be split to
2115 	 * several segments of stripe length (currently 64K).
2116 	 */
2117 	blk_start_plug(&plug);
2118 	atomic_inc(&BTRFS_I(inode)->sync_writers);
2119 	ret = btrfs_fdatawrite_range(inode, start, end);
2120 	atomic_dec(&BTRFS_I(inode)->sync_writers);
2121 	blk_finish_plug(&plug);
2122 
2123 	return ret;
2124 }
2125 
2126 static inline bool skip_inode_logging(const struct btrfs_log_ctx *ctx)
2127 {
2128 	struct btrfs_inode *inode = BTRFS_I(ctx->inode);
2129 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
2130 
2131 	if (btrfs_inode_in_log(inode, fs_info->generation) &&
2132 	    list_empty(&ctx->ordered_extents))
2133 		return true;
2134 
2135 	/*
2136 	 * If we are doing a fast fsync we can not bail out if the inode's
2137 	 * last_trans is <= then the last committed transaction, because we only
2138 	 * update the last_trans of the inode during ordered extent completion,
2139 	 * and for a fast fsync we don't wait for that, we only wait for the
2140 	 * writeback to complete.
2141 	 */
2142 	if (inode->last_trans <= fs_info->last_trans_committed &&
2143 	    (test_bit(BTRFS_INODE_NEEDS_FULL_SYNC, &inode->runtime_flags) ||
2144 	     list_empty(&ctx->ordered_extents)))
2145 		return true;
2146 
2147 	return false;
2148 }
2149 
2150 /*
2151  * fsync call for both files and directories.  This logs the inode into
2152  * the tree log instead of forcing full commits whenever possible.
2153  *
2154  * It needs to call filemap_fdatawait so that all ordered extent updates are
2155  * in the metadata btree are up to date for copying to the log.
2156  *
2157  * It drops the inode mutex before doing the tree log commit.  This is an
2158  * important optimization for directories because holding the mutex prevents
2159  * new operations on the dir while we write to disk.
2160  */
2161 int btrfs_sync_file(struct file *file, loff_t start, loff_t end, int datasync)
2162 {
2163 	struct dentry *dentry = file_dentry(file);
2164 	struct inode *inode = d_inode(dentry);
2165 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2166 	struct btrfs_root *root = BTRFS_I(inode)->root;
2167 	struct btrfs_trans_handle *trans;
2168 	struct btrfs_log_ctx ctx;
2169 	int ret = 0, err;
2170 	u64 len;
2171 	bool full_sync;
2172 
2173 	trace_btrfs_sync_file(file, datasync);
2174 
2175 	btrfs_init_log_ctx(&ctx, inode);
2176 
2177 	/*
2178 	 * Always set the range to a full range, otherwise we can get into
2179 	 * several problems, from missing file extent items to represent holes
2180 	 * when not using the NO_HOLES feature, to log tree corruption due to
2181 	 * races between hole detection during logging and completion of ordered
2182 	 * extents outside the range, to missing checksums due to ordered extents
2183 	 * for which we flushed only a subset of their pages.
2184 	 */
2185 	start = 0;
2186 	end = LLONG_MAX;
2187 	len = (u64)LLONG_MAX + 1;
2188 
2189 	/*
2190 	 * We write the dirty pages in the range and wait until they complete
2191 	 * out of the ->i_mutex. If so, we can flush the dirty pages by
2192 	 * multi-task, and make the performance up.  See
2193 	 * btrfs_wait_ordered_range for an explanation of the ASYNC check.
2194 	 */
2195 	ret = start_ordered_ops(inode, start, end);
2196 	if (ret)
2197 		goto out;
2198 
2199 	btrfs_inode_lock(inode, BTRFS_ILOCK_MMAP);
2200 
2201 	atomic_inc(&root->log_batch);
2202 
2203 	/*
2204 	 * Always check for the full sync flag while holding the inode's lock,
2205 	 * to avoid races with other tasks. The flag must be either set all the
2206 	 * time during logging or always off all the time while logging.
2207 	 */
2208 	full_sync = test_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
2209 			     &BTRFS_I(inode)->runtime_flags);
2210 
2211 	/*
2212 	 * Before we acquired the inode's lock and the mmap lock, someone may
2213 	 * have dirtied more pages in the target range. We need to make sure
2214 	 * that writeback for any such pages does not start while we are logging
2215 	 * the inode, because if it does, any of the following might happen when
2216 	 * we are not doing a full inode sync:
2217 	 *
2218 	 * 1) We log an extent after its writeback finishes but before its
2219 	 *    checksums are added to the csum tree, leading to -EIO errors
2220 	 *    when attempting to read the extent after a log replay.
2221 	 *
2222 	 * 2) We can end up logging an extent before its writeback finishes.
2223 	 *    Therefore after the log replay we will have a file extent item
2224 	 *    pointing to an unwritten extent (and no data checksums as well).
2225 	 *
2226 	 * So trigger writeback for any eventual new dirty pages and then we
2227 	 * wait for all ordered extents to complete below.
2228 	 */
2229 	ret = start_ordered_ops(inode, start, end);
2230 	if (ret) {
2231 		btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP);
2232 		goto out;
2233 	}
2234 
2235 	/*
2236 	 * We have to do this here to avoid the priority inversion of waiting on
2237 	 * IO of a lower priority task while holding a transaction open.
2238 	 *
2239 	 * For a full fsync we wait for the ordered extents to complete while
2240 	 * for a fast fsync we wait just for writeback to complete, and then
2241 	 * attach the ordered extents to the transaction so that a transaction
2242 	 * commit waits for their completion, to avoid data loss if we fsync,
2243 	 * the current transaction commits before the ordered extents complete
2244 	 * and a power failure happens right after that.
2245 	 *
2246 	 * For zoned filesystem, if a write IO uses a ZONE_APPEND command, the
2247 	 * logical address recorded in the ordered extent may change. We need
2248 	 * to wait for the IO to stabilize the logical address.
2249 	 */
2250 	if (full_sync || btrfs_is_zoned(fs_info)) {
2251 		ret = btrfs_wait_ordered_range(inode, start, len);
2252 	} else {
2253 		/*
2254 		 * Get our ordered extents as soon as possible to avoid doing
2255 		 * checksum lookups in the csum tree, and use instead the
2256 		 * checksums attached to the ordered extents.
2257 		 */
2258 		btrfs_get_ordered_extents_for_logging(BTRFS_I(inode),
2259 						      &ctx.ordered_extents);
2260 		ret = filemap_fdatawait_range(inode->i_mapping, start, end);
2261 	}
2262 
2263 	if (ret)
2264 		goto out_release_extents;
2265 
2266 	atomic_inc(&root->log_batch);
2267 
2268 	smp_mb();
2269 	if (skip_inode_logging(&ctx)) {
2270 		/*
2271 		 * We've had everything committed since the last time we were
2272 		 * modified so clear this flag in case it was set for whatever
2273 		 * reason, it's no longer relevant.
2274 		 */
2275 		clear_bit(BTRFS_INODE_NEEDS_FULL_SYNC,
2276 			  &BTRFS_I(inode)->runtime_flags);
2277 		/*
2278 		 * An ordered extent might have started before and completed
2279 		 * already with io errors, in which case the inode was not
2280 		 * updated and we end up here. So check the inode's mapping
2281 		 * for any errors that might have happened since we last
2282 		 * checked called fsync.
2283 		 */
2284 		ret = filemap_check_wb_err(inode->i_mapping, file->f_wb_err);
2285 		goto out_release_extents;
2286 	}
2287 
2288 	/*
2289 	 * We use start here because we will need to wait on the IO to complete
2290 	 * in btrfs_sync_log, which could require joining a transaction (for
2291 	 * example checking cross references in the nocow path).  If we use join
2292 	 * here we could get into a situation where we're waiting on IO to
2293 	 * happen that is blocked on a transaction trying to commit.  With start
2294 	 * we inc the extwriter counter, so we wait for all extwriters to exit
2295 	 * before we start blocking joiners.  This comment is to keep somebody
2296 	 * from thinking they are super smart and changing this to
2297 	 * btrfs_join_transaction *cough*Josef*cough*.
2298 	 */
2299 	trans = btrfs_start_transaction(root, 0);
2300 	if (IS_ERR(trans)) {
2301 		ret = PTR_ERR(trans);
2302 		goto out_release_extents;
2303 	}
2304 	trans->in_fsync = true;
2305 
2306 	ret = btrfs_log_dentry_safe(trans, dentry, &ctx);
2307 	btrfs_release_log_ctx_extents(&ctx);
2308 	if (ret < 0) {
2309 		/* Fallthrough and commit/free transaction. */
2310 		ret = BTRFS_LOG_FORCE_COMMIT;
2311 	}
2312 
2313 	/* we've logged all the items and now have a consistent
2314 	 * version of the file in the log.  It is possible that
2315 	 * someone will come in and modify the file, but that's
2316 	 * fine because the log is consistent on disk, and we
2317 	 * have references to all of the file's extents
2318 	 *
2319 	 * It is possible that someone will come in and log the
2320 	 * file again, but that will end up using the synchronization
2321 	 * inside btrfs_sync_log to keep things safe.
2322 	 */
2323 	btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP);
2324 
2325 	if (ret == BTRFS_NO_LOG_SYNC) {
2326 		ret = btrfs_end_transaction(trans);
2327 		goto out;
2328 	}
2329 
2330 	/* We successfully logged the inode, attempt to sync the log. */
2331 	if (!ret) {
2332 		ret = btrfs_sync_log(trans, root, &ctx);
2333 		if (!ret) {
2334 			ret = btrfs_end_transaction(trans);
2335 			goto out;
2336 		}
2337 	}
2338 
2339 	/*
2340 	 * At this point we need to commit the transaction because we had
2341 	 * btrfs_need_log_full_commit() or some other error.
2342 	 *
2343 	 * If we didn't do a full sync we have to stop the trans handle, wait on
2344 	 * the ordered extents, start it again and commit the transaction.  If
2345 	 * we attempt to wait on the ordered extents here we could deadlock with
2346 	 * something like fallocate() that is holding the extent lock trying to
2347 	 * start a transaction while some other thread is trying to commit the
2348 	 * transaction while we (fsync) are currently holding the transaction
2349 	 * open.
2350 	 */
2351 	if (!full_sync) {
2352 		ret = btrfs_end_transaction(trans);
2353 		if (ret)
2354 			goto out;
2355 		ret = btrfs_wait_ordered_range(inode, start, len);
2356 		if (ret)
2357 			goto out;
2358 
2359 		/*
2360 		 * This is safe to use here because we're only interested in
2361 		 * making sure the transaction that had the ordered extents is
2362 		 * committed.  We aren't waiting on anything past this point,
2363 		 * we're purely getting the transaction and committing it.
2364 		 */
2365 		trans = btrfs_attach_transaction_barrier(root);
2366 		if (IS_ERR(trans)) {
2367 			ret = PTR_ERR(trans);
2368 
2369 			/*
2370 			 * We committed the transaction and there's no currently
2371 			 * running transaction, this means everything we care
2372 			 * about made it to disk and we are done.
2373 			 */
2374 			if (ret == -ENOENT)
2375 				ret = 0;
2376 			goto out;
2377 		}
2378 	}
2379 
2380 	ret = btrfs_commit_transaction(trans);
2381 out:
2382 	ASSERT(list_empty(&ctx.list));
2383 	ASSERT(list_empty(&ctx.conflict_inodes));
2384 	err = file_check_and_advance_wb_err(file);
2385 	if (!ret)
2386 		ret = err;
2387 	return ret > 0 ? -EIO : ret;
2388 
2389 out_release_extents:
2390 	btrfs_release_log_ctx_extents(&ctx);
2391 	btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP);
2392 	goto out;
2393 }
2394 
2395 static const struct vm_operations_struct btrfs_file_vm_ops = {
2396 	.fault		= filemap_fault,
2397 	.map_pages	= filemap_map_pages,
2398 	.page_mkwrite	= btrfs_page_mkwrite,
2399 };
2400 
2401 static int btrfs_file_mmap(struct file	*filp, struct vm_area_struct *vma)
2402 {
2403 	struct address_space *mapping = filp->f_mapping;
2404 
2405 	if (!mapping->a_ops->read_folio)
2406 		return -ENOEXEC;
2407 
2408 	file_accessed(filp);
2409 	vma->vm_ops = &btrfs_file_vm_ops;
2410 
2411 	return 0;
2412 }
2413 
2414 static int hole_mergeable(struct btrfs_inode *inode, struct extent_buffer *leaf,
2415 			  int slot, u64 start, u64 end)
2416 {
2417 	struct btrfs_file_extent_item *fi;
2418 	struct btrfs_key key;
2419 
2420 	if (slot < 0 || slot >= btrfs_header_nritems(leaf))
2421 		return 0;
2422 
2423 	btrfs_item_key_to_cpu(leaf, &key, slot);
2424 	if (key.objectid != btrfs_ino(inode) ||
2425 	    key.type != BTRFS_EXTENT_DATA_KEY)
2426 		return 0;
2427 
2428 	fi = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
2429 
2430 	if (btrfs_file_extent_type(leaf, fi) != BTRFS_FILE_EXTENT_REG)
2431 		return 0;
2432 
2433 	if (btrfs_file_extent_disk_bytenr(leaf, fi))
2434 		return 0;
2435 
2436 	if (key.offset == end)
2437 		return 1;
2438 	if (key.offset + btrfs_file_extent_num_bytes(leaf, fi) == start)
2439 		return 1;
2440 	return 0;
2441 }
2442 
2443 static int fill_holes(struct btrfs_trans_handle *trans,
2444 		struct btrfs_inode *inode,
2445 		struct btrfs_path *path, u64 offset, u64 end)
2446 {
2447 	struct btrfs_fs_info *fs_info = trans->fs_info;
2448 	struct btrfs_root *root = inode->root;
2449 	struct extent_buffer *leaf;
2450 	struct btrfs_file_extent_item *fi;
2451 	struct extent_map *hole_em;
2452 	struct extent_map_tree *em_tree = &inode->extent_tree;
2453 	struct btrfs_key key;
2454 	int ret;
2455 
2456 	if (btrfs_fs_incompat(fs_info, NO_HOLES))
2457 		goto out;
2458 
2459 	key.objectid = btrfs_ino(inode);
2460 	key.type = BTRFS_EXTENT_DATA_KEY;
2461 	key.offset = offset;
2462 
2463 	ret = btrfs_search_slot(trans, root, &key, path, 0, 1);
2464 	if (ret <= 0) {
2465 		/*
2466 		 * We should have dropped this offset, so if we find it then
2467 		 * something has gone horribly wrong.
2468 		 */
2469 		if (ret == 0)
2470 			ret = -EINVAL;
2471 		return ret;
2472 	}
2473 
2474 	leaf = path->nodes[0];
2475 	if (hole_mergeable(inode, leaf, path->slots[0] - 1, offset, end)) {
2476 		u64 num_bytes;
2477 
2478 		path->slots[0]--;
2479 		fi = btrfs_item_ptr(leaf, path->slots[0],
2480 				    struct btrfs_file_extent_item);
2481 		num_bytes = btrfs_file_extent_num_bytes(leaf, fi) +
2482 			end - offset;
2483 		btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2484 		btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes);
2485 		btrfs_set_file_extent_offset(leaf, fi, 0);
2486 		btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2487 		btrfs_mark_buffer_dirty(leaf);
2488 		goto out;
2489 	}
2490 
2491 	if (hole_mergeable(inode, leaf, path->slots[0], offset, end)) {
2492 		u64 num_bytes;
2493 
2494 		key.offset = offset;
2495 		btrfs_set_item_key_safe(fs_info, path, &key);
2496 		fi = btrfs_item_ptr(leaf, path->slots[0],
2497 				    struct btrfs_file_extent_item);
2498 		num_bytes = btrfs_file_extent_num_bytes(leaf, fi) + end -
2499 			offset;
2500 		btrfs_set_file_extent_num_bytes(leaf, fi, num_bytes);
2501 		btrfs_set_file_extent_ram_bytes(leaf, fi, num_bytes);
2502 		btrfs_set_file_extent_offset(leaf, fi, 0);
2503 		btrfs_set_file_extent_generation(leaf, fi, trans->transid);
2504 		btrfs_mark_buffer_dirty(leaf);
2505 		goto out;
2506 	}
2507 	btrfs_release_path(path);
2508 
2509 	ret = btrfs_insert_hole_extent(trans, root, btrfs_ino(inode), offset,
2510 				       end - offset);
2511 	if (ret)
2512 		return ret;
2513 
2514 out:
2515 	btrfs_release_path(path);
2516 
2517 	hole_em = alloc_extent_map();
2518 	if (!hole_em) {
2519 		btrfs_drop_extent_cache(inode, offset, end - 1, 0);
2520 		btrfs_set_inode_full_sync(inode);
2521 	} else {
2522 		hole_em->start = offset;
2523 		hole_em->len = end - offset;
2524 		hole_em->ram_bytes = hole_em->len;
2525 		hole_em->orig_start = offset;
2526 
2527 		hole_em->block_start = EXTENT_MAP_HOLE;
2528 		hole_em->block_len = 0;
2529 		hole_em->orig_block_len = 0;
2530 		hole_em->compress_type = BTRFS_COMPRESS_NONE;
2531 		hole_em->generation = trans->transid;
2532 
2533 		do {
2534 			btrfs_drop_extent_cache(inode, offset, end - 1, 0);
2535 			write_lock(&em_tree->lock);
2536 			ret = add_extent_mapping(em_tree, hole_em, 1);
2537 			write_unlock(&em_tree->lock);
2538 		} while (ret == -EEXIST);
2539 		free_extent_map(hole_em);
2540 		if (ret)
2541 			btrfs_set_inode_full_sync(inode);
2542 	}
2543 
2544 	return 0;
2545 }
2546 
2547 /*
2548  * Find a hole extent on given inode and change start/len to the end of hole
2549  * extent.(hole/vacuum extent whose em->start <= start &&
2550  *	   em->start + em->len > start)
2551  * When a hole extent is found, return 1 and modify start/len.
2552  */
2553 static int find_first_non_hole(struct btrfs_inode *inode, u64 *start, u64 *len)
2554 {
2555 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
2556 	struct extent_map *em;
2557 	int ret = 0;
2558 
2559 	em = btrfs_get_extent(inode, NULL, 0,
2560 			      round_down(*start, fs_info->sectorsize),
2561 			      round_up(*len, fs_info->sectorsize));
2562 	if (IS_ERR(em))
2563 		return PTR_ERR(em);
2564 
2565 	/* Hole or vacuum extent(only exists in no-hole mode) */
2566 	if (em->block_start == EXTENT_MAP_HOLE) {
2567 		ret = 1;
2568 		*len = em->start + em->len > *start + *len ?
2569 		       0 : *start + *len - em->start - em->len;
2570 		*start = em->start + em->len;
2571 	}
2572 	free_extent_map(em);
2573 	return ret;
2574 }
2575 
2576 static void btrfs_punch_hole_lock_range(struct inode *inode,
2577 					const u64 lockstart,
2578 					const u64 lockend,
2579 					struct extent_state **cached_state)
2580 {
2581 	/*
2582 	 * For subpage case, if the range is not at page boundary, we could
2583 	 * have pages at the leading/tailing part of the range.
2584 	 * This could lead to dead loop since filemap_range_has_page()
2585 	 * will always return true.
2586 	 * So here we need to do extra page alignment for
2587 	 * filemap_range_has_page().
2588 	 */
2589 	const u64 page_lockstart = round_up(lockstart, PAGE_SIZE);
2590 	const u64 page_lockend = round_down(lockend + 1, PAGE_SIZE) - 1;
2591 
2592 	while (1) {
2593 		truncate_pagecache_range(inode, lockstart, lockend);
2594 
2595 		lock_extent_bits(&BTRFS_I(inode)->io_tree, lockstart, lockend,
2596 				 cached_state);
2597 		/*
2598 		 * We can't have ordered extents in the range, nor dirty/writeback
2599 		 * pages, because we have locked the inode's VFS lock in exclusive
2600 		 * mode, we have locked the inode's i_mmap_lock in exclusive mode,
2601 		 * we have flushed all delalloc in the range and we have waited
2602 		 * for any ordered extents in the range to complete.
2603 		 * We can race with anyone reading pages from this range, so after
2604 		 * locking the range check if we have pages in the range, and if
2605 		 * we do, unlock the range and retry.
2606 		 */
2607 		if (!filemap_range_has_page(inode->i_mapping, page_lockstart,
2608 					    page_lockend))
2609 			break;
2610 
2611 		unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart,
2612 				     lockend, cached_state);
2613 	}
2614 
2615 	btrfs_assert_inode_range_clean(BTRFS_I(inode), lockstart, lockend);
2616 }
2617 
2618 static int btrfs_insert_replace_extent(struct btrfs_trans_handle *trans,
2619 				     struct btrfs_inode *inode,
2620 				     struct btrfs_path *path,
2621 				     struct btrfs_replace_extent_info *extent_info,
2622 				     const u64 replace_len,
2623 				     const u64 bytes_to_drop)
2624 {
2625 	struct btrfs_fs_info *fs_info = trans->fs_info;
2626 	struct btrfs_root *root = inode->root;
2627 	struct btrfs_file_extent_item *extent;
2628 	struct extent_buffer *leaf;
2629 	struct btrfs_key key;
2630 	int slot;
2631 	struct btrfs_ref ref = { 0 };
2632 	int ret;
2633 
2634 	if (replace_len == 0)
2635 		return 0;
2636 
2637 	if (extent_info->disk_offset == 0 &&
2638 	    btrfs_fs_incompat(fs_info, NO_HOLES)) {
2639 		btrfs_update_inode_bytes(inode, 0, bytes_to_drop);
2640 		return 0;
2641 	}
2642 
2643 	key.objectid = btrfs_ino(inode);
2644 	key.type = BTRFS_EXTENT_DATA_KEY;
2645 	key.offset = extent_info->file_offset;
2646 	ret = btrfs_insert_empty_item(trans, root, path, &key,
2647 				      sizeof(struct btrfs_file_extent_item));
2648 	if (ret)
2649 		return ret;
2650 	leaf = path->nodes[0];
2651 	slot = path->slots[0];
2652 	write_extent_buffer(leaf, extent_info->extent_buf,
2653 			    btrfs_item_ptr_offset(leaf, slot),
2654 			    sizeof(struct btrfs_file_extent_item));
2655 	extent = btrfs_item_ptr(leaf, slot, struct btrfs_file_extent_item);
2656 	ASSERT(btrfs_file_extent_type(leaf, extent) != BTRFS_FILE_EXTENT_INLINE);
2657 	btrfs_set_file_extent_offset(leaf, extent, extent_info->data_offset);
2658 	btrfs_set_file_extent_num_bytes(leaf, extent, replace_len);
2659 	if (extent_info->is_new_extent)
2660 		btrfs_set_file_extent_generation(leaf, extent, trans->transid);
2661 	btrfs_mark_buffer_dirty(leaf);
2662 	btrfs_release_path(path);
2663 
2664 	ret = btrfs_inode_set_file_extent_range(inode, extent_info->file_offset,
2665 						replace_len);
2666 	if (ret)
2667 		return ret;
2668 
2669 	/* If it's a hole, nothing more needs to be done. */
2670 	if (extent_info->disk_offset == 0) {
2671 		btrfs_update_inode_bytes(inode, 0, bytes_to_drop);
2672 		return 0;
2673 	}
2674 
2675 	btrfs_update_inode_bytes(inode, replace_len, bytes_to_drop);
2676 
2677 	if (extent_info->is_new_extent && extent_info->insertions == 0) {
2678 		key.objectid = extent_info->disk_offset;
2679 		key.type = BTRFS_EXTENT_ITEM_KEY;
2680 		key.offset = extent_info->disk_len;
2681 		ret = btrfs_alloc_reserved_file_extent(trans, root,
2682 						       btrfs_ino(inode),
2683 						       extent_info->file_offset,
2684 						       extent_info->qgroup_reserved,
2685 						       &key);
2686 	} else {
2687 		u64 ref_offset;
2688 
2689 		btrfs_init_generic_ref(&ref, BTRFS_ADD_DELAYED_REF,
2690 				       extent_info->disk_offset,
2691 				       extent_info->disk_len, 0);
2692 		ref_offset = extent_info->file_offset - extent_info->data_offset;
2693 		btrfs_init_data_ref(&ref, root->root_key.objectid,
2694 				    btrfs_ino(inode), ref_offset, 0, false);
2695 		ret = btrfs_inc_extent_ref(trans, &ref);
2696 	}
2697 
2698 	extent_info->insertions++;
2699 
2700 	return ret;
2701 }
2702 
2703 /*
2704  * The respective range must have been previously locked, as well as the inode.
2705  * The end offset is inclusive (last byte of the range).
2706  * @extent_info is NULL for fallocate's hole punching and non-NULL when replacing
2707  * the file range with an extent.
2708  * When not punching a hole, we don't want to end up in a state where we dropped
2709  * extents without inserting a new one, so we must abort the transaction to avoid
2710  * a corruption.
2711  */
2712 int btrfs_replace_file_extents(struct btrfs_inode *inode,
2713 			       struct btrfs_path *path, const u64 start,
2714 			       const u64 end,
2715 			       struct btrfs_replace_extent_info *extent_info,
2716 			       struct btrfs_trans_handle **trans_out)
2717 {
2718 	struct btrfs_drop_extents_args drop_args = { 0 };
2719 	struct btrfs_root *root = inode->root;
2720 	struct btrfs_fs_info *fs_info = root->fs_info;
2721 	u64 min_size = btrfs_calc_insert_metadata_size(fs_info, 1);
2722 	u64 ino_size = round_up(inode->vfs_inode.i_size, fs_info->sectorsize);
2723 	struct btrfs_trans_handle *trans = NULL;
2724 	struct btrfs_block_rsv *rsv;
2725 	unsigned int rsv_count;
2726 	u64 cur_offset;
2727 	u64 len = end - start;
2728 	int ret = 0;
2729 
2730 	if (end <= start)
2731 		return -EINVAL;
2732 
2733 	rsv = btrfs_alloc_block_rsv(fs_info, BTRFS_BLOCK_RSV_TEMP);
2734 	if (!rsv) {
2735 		ret = -ENOMEM;
2736 		goto out;
2737 	}
2738 	rsv->size = btrfs_calc_insert_metadata_size(fs_info, 1);
2739 	rsv->failfast = true;
2740 
2741 	/*
2742 	 * 1 - update the inode
2743 	 * 1 - removing the extents in the range
2744 	 * 1 - adding the hole extent if no_holes isn't set or if we are
2745 	 *     replacing the range with a new extent
2746 	 */
2747 	if (!btrfs_fs_incompat(fs_info, NO_HOLES) || extent_info)
2748 		rsv_count = 3;
2749 	else
2750 		rsv_count = 2;
2751 
2752 	trans = btrfs_start_transaction(root, rsv_count);
2753 	if (IS_ERR(trans)) {
2754 		ret = PTR_ERR(trans);
2755 		trans = NULL;
2756 		goto out_free;
2757 	}
2758 
2759 	ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv, rsv,
2760 				      min_size, false);
2761 	if (WARN_ON(ret))
2762 		goto out_trans;
2763 	trans->block_rsv = rsv;
2764 
2765 	cur_offset = start;
2766 	drop_args.path = path;
2767 	drop_args.end = end + 1;
2768 	drop_args.drop_cache = true;
2769 	while (cur_offset < end) {
2770 		drop_args.start = cur_offset;
2771 		ret = btrfs_drop_extents(trans, root, inode, &drop_args);
2772 		/* If we are punching a hole decrement the inode's byte count */
2773 		if (!extent_info)
2774 			btrfs_update_inode_bytes(inode, 0,
2775 						 drop_args.bytes_found);
2776 		if (ret != -ENOSPC) {
2777 			/*
2778 			 * The only time we don't want to abort is if we are
2779 			 * attempting to clone a partial inline extent, in which
2780 			 * case we'll get EOPNOTSUPP.  However if we aren't
2781 			 * clone we need to abort no matter what, because if we
2782 			 * got EOPNOTSUPP via prealloc then we messed up and
2783 			 * need to abort.
2784 			 */
2785 			if (ret &&
2786 			    (ret != -EOPNOTSUPP ||
2787 			     (extent_info && extent_info->is_new_extent)))
2788 				btrfs_abort_transaction(trans, ret);
2789 			break;
2790 		}
2791 
2792 		trans->block_rsv = &fs_info->trans_block_rsv;
2793 
2794 		if (!extent_info && cur_offset < drop_args.drop_end &&
2795 		    cur_offset < ino_size) {
2796 			ret = fill_holes(trans, inode, path, cur_offset,
2797 					 drop_args.drop_end);
2798 			if (ret) {
2799 				/*
2800 				 * If we failed then we didn't insert our hole
2801 				 * entries for the area we dropped, so now the
2802 				 * fs is corrupted, so we must abort the
2803 				 * transaction.
2804 				 */
2805 				btrfs_abort_transaction(trans, ret);
2806 				break;
2807 			}
2808 		} else if (!extent_info && cur_offset < drop_args.drop_end) {
2809 			/*
2810 			 * We are past the i_size here, but since we didn't
2811 			 * insert holes we need to clear the mapped area so we
2812 			 * know to not set disk_i_size in this area until a new
2813 			 * file extent is inserted here.
2814 			 */
2815 			ret = btrfs_inode_clear_file_extent_range(inode,
2816 					cur_offset,
2817 					drop_args.drop_end - cur_offset);
2818 			if (ret) {
2819 				/*
2820 				 * We couldn't clear our area, so we could
2821 				 * presumably adjust up and corrupt the fs, so
2822 				 * we need to abort.
2823 				 */
2824 				btrfs_abort_transaction(trans, ret);
2825 				break;
2826 			}
2827 		}
2828 
2829 		if (extent_info &&
2830 		    drop_args.drop_end > extent_info->file_offset) {
2831 			u64 replace_len = drop_args.drop_end -
2832 					  extent_info->file_offset;
2833 
2834 			ret = btrfs_insert_replace_extent(trans, inode,	path,
2835 					extent_info, replace_len,
2836 					drop_args.bytes_found);
2837 			if (ret) {
2838 				btrfs_abort_transaction(trans, ret);
2839 				break;
2840 			}
2841 			extent_info->data_len -= replace_len;
2842 			extent_info->data_offset += replace_len;
2843 			extent_info->file_offset += replace_len;
2844 		}
2845 
2846 		/*
2847 		 * We are releasing our handle on the transaction, balance the
2848 		 * dirty pages of the btree inode and flush delayed items, and
2849 		 * then get a new transaction handle, which may now point to a
2850 		 * new transaction in case someone else may have committed the
2851 		 * transaction we used to replace/drop file extent items. So
2852 		 * bump the inode's iversion and update mtime and ctime except
2853 		 * if we are called from a dedupe context. This is because a
2854 		 * power failure/crash may happen after the transaction is
2855 		 * committed and before we finish replacing/dropping all the
2856 		 * file extent items we need.
2857 		 */
2858 		inode_inc_iversion(&inode->vfs_inode);
2859 
2860 		if (!extent_info || extent_info->update_times) {
2861 			inode->vfs_inode.i_mtime = current_time(&inode->vfs_inode);
2862 			inode->vfs_inode.i_ctime = inode->vfs_inode.i_mtime;
2863 		}
2864 
2865 		ret = btrfs_update_inode(trans, root, inode);
2866 		if (ret)
2867 			break;
2868 
2869 		btrfs_end_transaction(trans);
2870 		btrfs_btree_balance_dirty(fs_info);
2871 
2872 		trans = btrfs_start_transaction(root, rsv_count);
2873 		if (IS_ERR(trans)) {
2874 			ret = PTR_ERR(trans);
2875 			trans = NULL;
2876 			break;
2877 		}
2878 
2879 		ret = btrfs_block_rsv_migrate(&fs_info->trans_block_rsv,
2880 					      rsv, min_size, false);
2881 		if (WARN_ON(ret))
2882 			break;
2883 		trans->block_rsv = rsv;
2884 
2885 		cur_offset = drop_args.drop_end;
2886 		len = end - cur_offset;
2887 		if (!extent_info && len) {
2888 			ret = find_first_non_hole(inode, &cur_offset, &len);
2889 			if (unlikely(ret < 0))
2890 				break;
2891 			if (ret && !len) {
2892 				ret = 0;
2893 				break;
2894 			}
2895 		}
2896 	}
2897 
2898 	/*
2899 	 * If we were cloning, force the next fsync to be a full one since we
2900 	 * we replaced (or just dropped in the case of cloning holes when
2901 	 * NO_HOLES is enabled) file extent items and did not setup new extent
2902 	 * maps for the replacement extents (or holes).
2903 	 */
2904 	if (extent_info && !extent_info->is_new_extent)
2905 		btrfs_set_inode_full_sync(inode);
2906 
2907 	if (ret)
2908 		goto out_trans;
2909 
2910 	trans->block_rsv = &fs_info->trans_block_rsv;
2911 	/*
2912 	 * If we are using the NO_HOLES feature we might have had already an
2913 	 * hole that overlaps a part of the region [lockstart, lockend] and
2914 	 * ends at (or beyond) lockend. Since we have no file extent items to
2915 	 * represent holes, drop_end can be less than lockend and so we must
2916 	 * make sure we have an extent map representing the existing hole (the
2917 	 * call to __btrfs_drop_extents() might have dropped the existing extent
2918 	 * map representing the existing hole), otherwise the fast fsync path
2919 	 * will not record the existence of the hole region
2920 	 * [existing_hole_start, lockend].
2921 	 */
2922 	if (drop_args.drop_end <= end)
2923 		drop_args.drop_end = end + 1;
2924 	/*
2925 	 * Don't insert file hole extent item if it's for a range beyond eof
2926 	 * (because it's useless) or if it represents a 0 bytes range (when
2927 	 * cur_offset == drop_end).
2928 	 */
2929 	if (!extent_info && cur_offset < ino_size &&
2930 	    cur_offset < drop_args.drop_end) {
2931 		ret = fill_holes(trans, inode, path, cur_offset,
2932 				 drop_args.drop_end);
2933 		if (ret) {
2934 			/* Same comment as above. */
2935 			btrfs_abort_transaction(trans, ret);
2936 			goto out_trans;
2937 		}
2938 	} else if (!extent_info && cur_offset < drop_args.drop_end) {
2939 		/* See the comment in the loop above for the reasoning here. */
2940 		ret = btrfs_inode_clear_file_extent_range(inode, cur_offset,
2941 					drop_args.drop_end - cur_offset);
2942 		if (ret) {
2943 			btrfs_abort_transaction(trans, ret);
2944 			goto out_trans;
2945 		}
2946 
2947 	}
2948 	if (extent_info) {
2949 		ret = btrfs_insert_replace_extent(trans, inode, path,
2950 				extent_info, extent_info->data_len,
2951 				drop_args.bytes_found);
2952 		if (ret) {
2953 			btrfs_abort_transaction(trans, ret);
2954 			goto out_trans;
2955 		}
2956 	}
2957 
2958 out_trans:
2959 	if (!trans)
2960 		goto out_free;
2961 
2962 	trans->block_rsv = &fs_info->trans_block_rsv;
2963 	if (ret)
2964 		btrfs_end_transaction(trans);
2965 	else
2966 		*trans_out = trans;
2967 out_free:
2968 	btrfs_free_block_rsv(fs_info, rsv);
2969 out:
2970 	return ret;
2971 }
2972 
2973 static int btrfs_punch_hole(struct file *file, loff_t offset, loff_t len)
2974 {
2975 	struct inode *inode = file_inode(file);
2976 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
2977 	struct btrfs_root *root = BTRFS_I(inode)->root;
2978 	struct extent_state *cached_state = NULL;
2979 	struct btrfs_path *path;
2980 	struct btrfs_trans_handle *trans = NULL;
2981 	u64 lockstart;
2982 	u64 lockend;
2983 	u64 tail_start;
2984 	u64 tail_len;
2985 	u64 orig_start = offset;
2986 	int ret = 0;
2987 	bool same_block;
2988 	u64 ino_size;
2989 	bool truncated_block = false;
2990 	bool updated_inode = false;
2991 
2992 	btrfs_inode_lock(inode, BTRFS_ILOCK_MMAP);
2993 
2994 	ret = btrfs_wait_ordered_range(inode, offset, len);
2995 	if (ret)
2996 		goto out_only_mutex;
2997 
2998 	ino_size = round_up(inode->i_size, fs_info->sectorsize);
2999 	ret = find_first_non_hole(BTRFS_I(inode), &offset, &len);
3000 	if (ret < 0)
3001 		goto out_only_mutex;
3002 	if (ret && !len) {
3003 		/* Already in a large hole */
3004 		ret = 0;
3005 		goto out_only_mutex;
3006 	}
3007 
3008 	ret = file_modified(file);
3009 	if (ret)
3010 		goto out_only_mutex;
3011 
3012 	lockstart = round_up(offset, btrfs_inode_sectorsize(BTRFS_I(inode)));
3013 	lockend = round_down(offset + len,
3014 			     btrfs_inode_sectorsize(BTRFS_I(inode))) - 1;
3015 	same_block = (BTRFS_BYTES_TO_BLKS(fs_info, offset))
3016 		== (BTRFS_BYTES_TO_BLKS(fs_info, offset + len - 1));
3017 	/*
3018 	 * We needn't truncate any block which is beyond the end of the file
3019 	 * because we are sure there is no data there.
3020 	 */
3021 	/*
3022 	 * Only do this if we are in the same block and we aren't doing the
3023 	 * entire block.
3024 	 */
3025 	if (same_block && len < fs_info->sectorsize) {
3026 		if (offset < ino_size) {
3027 			truncated_block = true;
3028 			ret = btrfs_truncate_block(BTRFS_I(inode), offset, len,
3029 						   0);
3030 		} else {
3031 			ret = 0;
3032 		}
3033 		goto out_only_mutex;
3034 	}
3035 
3036 	/* zero back part of the first block */
3037 	if (offset < ino_size) {
3038 		truncated_block = true;
3039 		ret = btrfs_truncate_block(BTRFS_I(inode), offset, 0, 0);
3040 		if (ret) {
3041 			btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP);
3042 			return ret;
3043 		}
3044 	}
3045 
3046 	/* Check the aligned pages after the first unaligned page,
3047 	 * if offset != orig_start, which means the first unaligned page
3048 	 * including several following pages are already in holes,
3049 	 * the extra check can be skipped */
3050 	if (offset == orig_start) {
3051 		/* after truncate page, check hole again */
3052 		len = offset + len - lockstart;
3053 		offset = lockstart;
3054 		ret = find_first_non_hole(BTRFS_I(inode), &offset, &len);
3055 		if (ret < 0)
3056 			goto out_only_mutex;
3057 		if (ret && !len) {
3058 			ret = 0;
3059 			goto out_only_mutex;
3060 		}
3061 		lockstart = offset;
3062 	}
3063 
3064 	/* Check the tail unaligned part is in a hole */
3065 	tail_start = lockend + 1;
3066 	tail_len = offset + len - tail_start;
3067 	if (tail_len) {
3068 		ret = find_first_non_hole(BTRFS_I(inode), &tail_start, &tail_len);
3069 		if (unlikely(ret < 0))
3070 			goto out_only_mutex;
3071 		if (!ret) {
3072 			/* zero the front end of the last page */
3073 			if (tail_start + tail_len < ino_size) {
3074 				truncated_block = true;
3075 				ret = btrfs_truncate_block(BTRFS_I(inode),
3076 							tail_start + tail_len,
3077 							0, 1);
3078 				if (ret)
3079 					goto out_only_mutex;
3080 			}
3081 		}
3082 	}
3083 
3084 	if (lockend < lockstart) {
3085 		ret = 0;
3086 		goto out_only_mutex;
3087 	}
3088 
3089 	btrfs_punch_hole_lock_range(inode, lockstart, lockend, &cached_state);
3090 
3091 	path = btrfs_alloc_path();
3092 	if (!path) {
3093 		ret = -ENOMEM;
3094 		goto out;
3095 	}
3096 
3097 	ret = btrfs_replace_file_extents(BTRFS_I(inode), path, lockstart,
3098 					 lockend, NULL, &trans);
3099 	btrfs_free_path(path);
3100 	if (ret)
3101 		goto out;
3102 
3103 	ASSERT(trans != NULL);
3104 	inode_inc_iversion(inode);
3105 	inode->i_mtime = current_time(inode);
3106 	inode->i_ctime = inode->i_mtime;
3107 	ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
3108 	updated_inode = true;
3109 	btrfs_end_transaction(trans);
3110 	btrfs_btree_balance_dirty(fs_info);
3111 out:
3112 	unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart, lockend,
3113 			     &cached_state);
3114 out_only_mutex:
3115 	if (!updated_inode && truncated_block && !ret) {
3116 		/*
3117 		 * If we only end up zeroing part of a page, we still need to
3118 		 * update the inode item, so that all the time fields are
3119 		 * updated as well as the necessary btrfs inode in memory fields
3120 		 * for detecting, at fsync time, if the inode isn't yet in the
3121 		 * log tree or it's there but not up to date.
3122 		 */
3123 		struct timespec64 now = current_time(inode);
3124 
3125 		inode_inc_iversion(inode);
3126 		inode->i_mtime = now;
3127 		inode->i_ctime = now;
3128 		trans = btrfs_start_transaction(root, 1);
3129 		if (IS_ERR(trans)) {
3130 			ret = PTR_ERR(trans);
3131 		} else {
3132 			int ret2;
3133 
3134 			ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
3135 			ret2 = btrfs_end_transaction(trans);
3136 			if (!ret)
3137 				ret = ret2;
3138 		}
3139 	}
3140 	btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP);
3141 	return ret;
3142 }
3143 
3144 /* Helper structure to record which range is already reserved */
3145 struct falloc_range {
3146 	struct list_head list;
3147 	u64 start;
3148 	u64 len;
3149 };
3150 
3151 /*
3152  * Helper function to add falloc range
3153  *
3154  * Caller should have locked the larger range of extent containing
3155  * [start, len)
3156  */
3157 static int add_falloc_range(struct list_head *head, u64 start, u64 len)
3158 {
3159 	struct falloc_range *range = NULL;
3160 
3161 	if (!list_empty(head)) {
3162 		/*
3163 		 * As fallocate iterates by bytenr order, we only need to check
3164 		 * the last range.
3165 		 */
3166 		range = list_last_entry(head, struct falloc_range, list);
3167 		if (range->start + range->len == start) {
3168 			range->len += len;
3169 			return 0;
3170 		}
3171 	}
3172 
3173 	range = kmalloc(sizeof(*range), GFP_KERNEL);
3174 	if (!range)
3175 		return -ENOMEM;
3176 	range->start = start;
3177 	range->len = len;
3178 	list_add_tail(&range->list, head);
3179 	return 0;
3180 }
3181 
3182 static int btrfs_fallocate_update_isize(struct inode *inode,
3183 					const u64 end,
3184 					const int mode)
3185 {
3186 	struct btrfs_trans_handle *trans;
3187 	struct btrfs_root *root = BTRFS_I(inode)->root;
3188 	int ret;
3189 	int ret2;
3190 
3191 	if (mode & FALLOC_FL_KEEP_SIZE || end <= i_size_read(inode))
3192 		return 0;
3193 
3194 	trans = btrfs_start_transaction(root, 1);
3195 	if (IS_ERR(trans))
3196 		return PTR_ERR(trans);
3197 
3198 	inode->i_ctime = current_time(inode);
3199 	i_size_write(inode, end);
3200 	btrfs_inode_safe_disk_i_size_write(BTRFS_I(inode), 0);
3201 	ret = btrfs_update_inode(trans, root, BTRFS_I(inode));
3202 	ret2 = btrfs_end_transaction(trans);
3203 
3204 	return ret ? ret : ret2;
3205 }
3206 
3207 enum {
3208 	RANGE_BOUNDARY_WRITTEN_EXTENT,
3209 	RANGE_BOUNDARY_PREALLOC_EXTENT,
3210 	RANGE_BOUNDARY_HOLE,
3211 };
3212 
3213 static int btrfs_zero_range_check_range_boundary(struct btrfs_inode *inode,
3214 						 u64 offset)
3215 {
3216 	const u64 sectorsize = btrfs_inode_sectorsize(inode);
3217 	struct extent_map *em;
3218 	int ret;
3219 
3220 	offset = round_down(offset, sectorsize);
3221 	em = btrfs_get_extent(inode, NULL, 0, offset, sectorsize);
3222 	if (IS_ERR(em))
3223 		return PTR_ERR(em);
3224 
3225 	if (em->block_start == EXTENT_MAP_HOLE)
3226 		ret = RANGE_BOUNDARY_HOLE;
3227 	else if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags))
3228 		ret = RANGE_BOUNDARY_PREALLOC_EXTENT;
3229 	else
3230 		ret = RANGE_BOUNDARY_WRITTEN_EXTENT;
3231 
3232 	free_extent_map(em);
3233 	return ret;
3234 }
3235 
3236 static int btrfs_zero_range(struct inode *inode,
3237 			    loff_t offset,
3238 			    loff_t len,
3239 			    const int mode)
3240 {
3241 	struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
3242 	struct extent_map *em;
3243 	struct extent_changeset *data_reserved = NULL;
3244 	int ret;
3245 	u64 alloc_hint = 0;
3246 	const u64 sectorsize = btrfs_inode_sectorsize(BTRFS_I(inode));
3247 	u64 alloc_start = round_down(offset, sectorsize);
3248 	u64 alloc_end = round_up(offset + len, sectorsize);
3249 	u64 bytes_to_reserve = 0;
3250 	bool space_reserved = false;
3251 
3252 	em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, alloc_start,
3253 			      alloc_end - alloc_start);
3254 	if (IS_ERR(em)) {
3255 		ret = PTR_ERR(em);
3256 		goto out;
3257 	}
3258 
3259 	/*
3260 	 * Avoid hole punching and extent allocation for some cases. More cases
3261 	 * could be considered, but these are unlikely common and we keep things
3262 	 * as simple as possible for now. Also, intentionally, if the target
3263 	 * range contains one or more prealloc extents together with regular
3264 	 * extents and holes, we drop all the existing extents and allocate a
3265 	 * new prealloc extent, so that we get a larger contiguous disk extent.
3266 	 */
3267 	if (em->start <= alloc_start &&
3268 	    test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
3269 		const u64 em_end = em->start + em->len;
3270 
3271 		if (em_end >= offset + len) {
3272 			/*
3273 			 * The whole range is already a prealloc extent,
3274 			 * do nothing except updating the inode's i_size if
3275 			 * needed.
3276 			 */
3277 			free_extent_map(em);
3278 			ret = btrfs_fallocate_update_isize(inode, offset + len,
3279 							   mode);
3280 			goto out;
3281 		}
3282 		/*
3283 		 * Part of the range is already a prealloc extent, so operate
3284 		 * only on the remaining part of the range.
3285 		 */
3286 		alloc_start = em_end;
3287 		ASSERT(IS_ALIGNED(alloc_start, sectorsize));
3288 		len = offset + len - alloc_start;
3289 		offset = alloc_start;
3290 		alloc_hint = em->block_start + em->len;
3291 	}
3292 	free_extent_map(em);
3293 
3294 	if (BTRFS_BYTES_TO_BLKS(fs_info, offset) ==
3295 	    BTRFS_BYTES_TO_BLKS(fs_info, offset + len - 1)) {
3296 		em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, alloc_start,
3297 				      sectorsize);
3298 		if (IS_ERR(em)) {
3299 			ret = PTR_ERR(em);
3300 			goto out;
3301 		}
3302 
3303 		if (test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) {
3304 			free_extent_map(em);
3305 			ret = btrfs_fallocate_update_isize(inode, offset + len,
3306 							   mode);
3307 			goto out;
3308 		}
3309 		if (len < sectorsize && em->block_start != EXTENT_MAP_HOLE) {
3310 			free_extent_map(em);
3311 			ret = btrfs_truncate_block(BTRFS_I(inode), offset, len,
3312 						   0);
3313 			if (!ret)
3314 				ret = btrfs_fallocate_update_isize(inode,
3315 								   offset + len,
3316 								   mode);
3317 			return ret;
3318 		}
3319 		free_extent_map(em);
3320 		alloc_start = round_down(offset, sectorsize);
3321 		alloc_end = alloc_start + sectorsize;
3322 		goto reserve_space;
3323 	}
3324 
3325 	alloc_start = round_up(offset, sectorsize);
3326 	alloc_end = round_down(offset + len, sectorsize);
3327 
3328 	/*
3329 	 * For unaligned ranges, check the pages at the boundaries, they might
3330 	 * map to an extent, in which case we need to partially zero them, or
3331 	 * they might map to a hole, in which case we need our allocation range
3332 	 * to cover them.
3333 	 */
3334 	if (!IS_ALIGNED(offset, sectorsize)) {
3335 		ret = btrfs_zero_range_check_range_boundary(BTRFS_I(inode),
3336 							    offset);
3337 		if (ret < 0)
3338 			goto out;
3339 		if (ret == RANGE_BOUNDARY_HOLE) {
3340 			alloc_start = round_down(offset, sectorsize);
3341 			ret = 0;
3342 		} else if (ret == RANGE_BOUNDARY_WRITTEN_EXTENT) {
3343 			ret = btrfs_truncate_block(BTRFS_I(inode), offset, 0, 0);
3344 			if (ret)
3345 				goto out;
3346 		} else {
3347 			ret = 0;
3348 		}
3349 	}
3350 
3351 	if (!IS_ALIGNED(offset + len, sectorsize)) {
3352 		ret = btrfs_zero_range_check_range_boundary(BTRFS_I(inode),
3353 							    offset + len);
3354 		if (ret < 0)
3355 			goto out;
3356 		if (ret == RANGE_BOUNDARY_HOLE) {
3357 			alloc_end = round_up(offset + len, sectorsize);
3358 			ret = 0;
3359 		} else if (ret == RANGE_BOUNDARY_WRITTEN_EXTENT) {
3360 			ret = btrfs_truncate_block(BTRFS_I(inode), offset + len,
3361 						   0, 1);
3362 			if (ret)
3363 				goto out;
3364 		} else {
3365 			ret = 0;
3366 		}
3367 	}
3368 
3369 reserve_space:
3370 	if (alloc_start < alloc_end) {
3371 		struct extent_state *cached_state = NULL;
3372 		const u64 lockstart = alloc_start;
3373 		const u64 lockend = alloc_end - 1;
3374 
3375 		bytes_to_reserve = alloc_end - alloc_start;
3376 		ret = btrfs_alloc_data_chunk_ondemand(BTRFS_I(inode),
3377 						      bytes_to_reserve);
3378 		if (ret < 0)
3379 			goto out;
3380 		space_reserved = true;
3381 		btrfs_punch_hole_lock_range(inode, lockstart, lockend,
3382 					    &cached_state);
3383 		ret = btrfs_qgroup_reserve_data(BTRFS_I(inode), &data_reserved,
3384 						alloc_start, bytes_to_reserve);
3385 		if (ret) {
3386 			unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart,
3387 					     lockend, &cached_state);
3388 			goto out;
3389 		}
3390 		ret = btrfs_prealloc_file_range(inode, mode, alloc_start,
3391 						alloc_end - alloc_start,
3392 						i_blocksize(inode),
3393 						offset + len, &alloc_hint);
3394 		unlock_extent_cached(&BTRFS_I(inode)->io_tree, lockstart,
3395 				     lockend, &cached_state);
3396 		/* btrfs_prealloc_file_range releases reserved space on error */
3397 		if (ret) {
3398 			space_reserved = false;
3399 			goto out;
3400 		}
3401 	}
3402 	ret = btrfs_fallocate_update_isize(inode, offset + len, mode);
3403  out:
3404 	if (ret && space_reserved)
3405 		btrfs_free_reserved_data_space(BTRFS_I(inode), data_reserved,
3406 					       alloc_start, bytes_to_reserve);
3407 	extent_changeset_free(data_reserved);
3408 
3409 	return ret;
3410 }
3411 
3412 static long btrfs_fallocate(struct file *file, int mode,
3413 			    loff_t offset, loff_t len)
3414 {
3415 	struct inode *inode = file_inode(file);
3416 	struct extent_state *cached_state = NULL;
3417 	struct extent_changeset *data_reserved = NULL;
3418 	struct falloc_range *range;
3419 	struct falloc_range *tmp;
3420 	struct list_head reserve_list;
3421 	u64 cur_offset;
3422 	u64 last_byte;
3423 	u64 alloc_start;
3424 	u64 alloc_end;
3425 	u64 alloc_hint = 0;
3426 	u64 locked_end;
3427 	u64 actual_end = 0;
3428 	u64 data_space_needed = 0;
3429 	u64 data_space_reserved = 0;
3430 	u64 qgroup_reserved = 0;
3431 	struct extent_map *em;
3432 	int blocksize = btrfs_inode_sectorsize(BTRFS_I(inode));
3433 	int ret;
3434 
3435 	/* Do not allow fallocate in ZONED mode */
3436 	if (btrfs_is_zoned(btrfs_sb(inode->i_sb)))
3437 		return -EOPNOTSUPP;
3438 
3439 	alloc_start = round_down(offset, blocksize);
3440 	alloc_end = round_up(offset + len, blocksize);
3441 	cur_offset = alloc_start;
3442 
3443 	/* Make sure we aren't being give some crap mode */
3444 	if (mode & ~(FALLOC_FL_KEEP_SIZE | FALLOC_FL_PUNCH_HOLE |
3445 		     FALLOC_FL_ZERO_RANGE))
3446 		return -EOPNOTSUPP;
3447 
3448 	if (mode & FALLOC_FL_PUNCH_HOLE)
3449 		return btrfs_punch_hole(file, offset, len);
3450 
3451 	btrfs_inode_lock(inode, BTRFS_ILOCK_MMAP);
3452 
3453 	if (!(mode & FALLOC_FL_KEEP_SIZE) && offset + len > inode->i_size) {
3454 		ret = inode_newsize_ok(inode, offset + len);
3455 		if (ret)
3456 			goto out;
3457 	}
3458 
3459 	ret = file_modified(file);
3460 	if (ret)
3461 		goto out;
3462 
3463 	/*
3464 	 * TODO: Move these two operations after we have checked
3465 	 * accurate reserved space, or fallocate can still fail but
3466 	 * with page truncated or size expanded.
3467 	 *
3468 	 * But that's a minor problem and won't do much harm BTW.
3469 	 */
3470 	if (alloc_start > inode->i_size) {
3471 		ret = btrfs_cont_expand(BTRFS_I(inode), i_size_read(inode),
3472 					alloc_start);
3473 		if (ret)
3474 			goto out;
3475 	} else if (offset + len > inode->i_size) {
3476 		/*
3477 		 * If we are fallocating from the end of the file onward we
3478 		 * need to zero out the end of the block if i_size lands in the
3479 		 * middle of a block.
3480 		 */
3481 		ret = btrfs_truncate_block(BTRFS_I(inode), inode->i_size, 0, 0);
3482 		if (ret)
3483 			goto out;
3484 	}
3485 
3486 	/*
3487 	 * We have locked the inode at the VFS level (in exclusive mode) and we
3488 	 * have locked the i_mmap_lock lock (in exclusive mode). Now before
3489 	 * locking the file range, flush all dealloc in the range and wait for
3490 	 * all ordered extents in the range to complete. After this we can lock
3491 	 * the file range and, due to the previous locking we did, we know there
3492 	 * can't be more delalloc or ordered extents in the range.
3493 	 */
3494 	ret = btrfs_wait_ordered_range(inode, alloc_start,
3495 				       alloc_end - alloc_start);
3496 	if (ret)
3497 		goto out;
3498 
3499 	if (mode & FALLOC_FL_ZERO_RANGE) {
3500 		ret = btrfs_zero_range(inode, offset, len, mode);
3501 		btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP);
3502 		return ret;
3503 	}
3504 
3505 	locked_end = alloc_end - 1;
3506 	lock_extent_bits(&BTRFS_I(inode)->io_tree, alloc_start, locked_end,
3507 			 &cached_state);
3508 
3509 	btrfs_assert_inode_range_clean(BTRFS_I(inode), alloc_start, locked_end);
3510 
3511 	/* First, check if we exceed the qgroup limit */
3512 	INIT_LIST_HEAD(&reserve_list);
3513 	while (cur_offset < alloc_end) {
3514 		em = btrfs_get_extent(BTRFS_I(inode), NULL, 0, cur_offset,
3515 				      alloc_end - cur_offset);
3516 		if (IS_ERR(em)) {
3517 			ret = PTR_ERR(em);
3518 			break;
3519 		}
3520 		last_byte = min(extent_map_end(em), alloc_end);
3521 		actual_end = min_t(u64, extent_map_end(em), offset + len);
3522 		last_byte = ALIGN(last_byte, blocksize);
3523 		if (em->block_start == EXTENT_MAP_HOLE ||
3524 		    (cur_offset >= inode->i_size &&
3525 		     !test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
3526 			const u64 range_len = last_byte - cur_offset;
3527 
3528 			ret = add_falloc_range(&reserve_list, cur_offset, range_len);
3529 			if (ret < 0) {
3530 				free_extent_map(em);
3531 				break;
3532 			}
3533 			ret = btrfs_qgroup_reserve_data(BTRFS_I(inode),
3534 					&data_reserved, cur_offset, range_len);
3535 			if (ret < 0) {
3536 				free_extent_map(em);
3537 				break;
3538 			}
3539 			qgroup_reserved += range_len;
3540 			data_space_needed += range_len;
3541 		}
3542 		free_extent_map(em);
3543 		cur_offset = last_byte;
3544 	}
3545 
3546 	if (!ret && data_space_needed > 0) {
3547 		/*
3548 		 * We are safe to reserve space here as we can't have delalloc
3549 		 * in the range, see above.
3550 		 */
3551 		ret = btrfs_alloc_data_chunk_ondemand(BTRFS_I(inode),
3552 						      data_space_needed);
3553 		if (!ret)
3554 			data_space_reserved = data_space_needed;
3555 	}
3556 
3557 	/*
3558 	 * If ret is still 0, means we're OK to fallocate.
3559 	 * Or just cleanup the list and exit.
3560 	 */
3561 	list_for_each_entry_safe(range, tmp, &reserve_list, list) {
3562 		if (!ret) {
3563 			ret = btrfs_prealloc_file_range(inode, mode,
3564 					range->start,
3565 					range->len, i_blocksize(inode),
3566 					offset + len, &alloc_hint);
3567 			/*
3568 			 * btrfs_prealloc_file_range() releases space even
3569 			 * if it returns an error.
3570 			 */
3571 			data_space_reserved -= range->len;
3572 			qgroup_reserved -= range->len;
3573 		} else if (data_space_reserved > 0) {
3574 			btrfs_free_reserved_data_space(BTRFS_I(inode),
3575 					       data_reserved, range->start,
3576 					       range->len);
3577 			data_space_reserved -= range->len;
3578 			qgroup_reserved -= range->len;
3579 		} else if (qgroup_reserved > 0) {
3580 			btrfs_qgroup_free_data(BTRFS_I(inode), data_reserved,
3581 					       range->start, range->len);
3582 			qgroup_reserved -= range->len;
3583 		}
3584 		list_del(&range->list);
3585 		kfree(range);
3586 	}
3587 	if (ret < 0)
3588 		goto out_unlock;
3589 
3590 	/*
3591 	 * We didn't need to allocate any more space, but we still extended the
3592 	 * size of the file so we need to update i_size and the inode item.
3593 	 */
3594 	ret = btrfs_fallocate_update_isize(inode, actual_end, mode);
3595 out_unlock:
3596 	unlock_extent_cached(&BTRFS_I(inode)->io_tree, alloc_start, locked_end,
3597 			     &cached_state);
3598 out:
3599 	btrfs_inode_unlock(inode, BTRFS_ILOCK_MMAP);
3600 	extent_changeset_free(data_reserved);
3601 	return ret;
3602 }
3603 
3604 /*
3605  * Helper for btrfs_find_delalloc_in_range(). Find a subrange in a given range
3606  * that has unflushed and/or flushing delalloc. There might be other adjacent
3607  * subranges after the one it found, so btrfs_find_delalloc_in_range() keeps
3608  * looping while it gets adjacent subranges, and merging them together.
3609  */
3610 static bool find_delalloc_subrange(struct btrfs_inode *inode, u64 start, u64 end,
3611 				   u64 *delalloc_start_ret, u64 *delalloc_end_ret)
3612 {
3613 	const u64 len = end + 1 - start;
3614 	struct extent_map_tree *em_tree = &inode->extent_tree;
3615 	struct extent_map *em;
3616 	u64 em_end;
3617 	u64 delalloc_len;
3618 
3619 	/*
3620 	 * Search the io tree first for EXTENT_DELALLOC. If we find any, it
3621 	 * means we have delalloc (dirty pages) for which writeback has not
3622 	 * started yet.
3623 	 */
3624 	*delalloc_start_ret = start;
3625 	delalloc_len = count_range_bits(&inode->io_tree, delalloc_start_ret, end,
3626 					len, EXTENT_DELALLOC, 1);
3627 	/*
3628 	 * If delalloc was found then *delalloc_start_ret has a sector size
3629 	 * aligned value (rounded down).
3630 	 */
3631 	if (delalloc_len > 0)
3632 		*delalloc_end_ret = *delalloc_start_ret + delalloc_len - 1;
3633 
3634 	/*
3635 	 * Now also check if there's any extent map in the range that does not
3636 	 * map to a hole or prealloc extent. We do this because:
3637 	 *
3638 	 * 1) When delalloc is flushed, the file range is locked, we clear the
3639 	 *    EXTENT_DELALLOC bit from the io tree and create an extent map for
3640 	 *    an allocated extent. So we might just have been called after
3641 	 *    delalloc is flushed and before the ordered extent completes and
3642 	 *    inserts the new file extent item in the subvolume's btree;
3643 	 *
3644 	 * 2) We may have an extent map created by flushing delalloc for a
3645 	 *    subrange that starts before the subrange we found marked with
3646 	 *    EXTENT_DELALLOC in the io tree.
3647 	 */
3648 	read_lock(&em_tree->lock);
3649 	em = lookup_extent_mapping(em_tree, start, len);
3650 	read_unlock(&em_tree->lock);
3651 
3652 	/* extent_map_end() returns a non-inclusive end offset. */
3653 	em_end = em ? extent_map_end(em) : 0;
3654 
3655 	/*
3656 	 * If we have a hole/prealloc extent map, check the next one if this one
3657 	 * ends before our range's end.
3658 	 */
3659 	if (em && (em->block_start == EXTENT_MAP_HOLE ||
3660 		   test_bit(EXTENT_FLAG_PREALLOC, &em->flags)) && em_end < end) {
3661 		struct extent_map *next_em;
3662 
3663 		read_lock(&em_tree->lock);
3664 		next_em = lookup_extent_mapping(em_tree, em_end, len - em_end);
3665 		read_unlock(&em_tree->lock);
3666 
3667 		free_extent_map(em);
3668 		em_end = next_em ? extent_map_end(next_em) : 0;
3669 		em = next_em;
3670 	}
3671 
3672 	if (em && (em->block_start == EXTENT_MAP_HOLE ||
3673 		   test_bit(EXTENT_FLAG_PREALLOC, &em->flags))) {
3674 		free_extent_map(em);
3675 		em = NULL;
3676 	}
3677 
3678 	/*
3679 	 * No extent map or one for a hole or prealloc extent. Use the delalloc
3680 	 * range we found in the io tree if we have one.
3681 	 */
3682 	if (!em)
3683 		return (delalloc_len > 0);
3684 
3685 	/*
3686 	 * We don't have any range as EXTENT_DELALLOC in the io tree, so the
3687 	 * extent map is the only subrange representing delalloc.
3688 	 */
3689 	if (delalloc_len == 0) {
3690 		*delalloc_start_ret = em->start;
3691 		*delalloc_end_ret = min(end, em_end - 1);
3692 		free_extent_map(em);
3693 		return true;
3694 	}
3695 
3696 	/*
3697 	 * The extent map represents a delalloc range that starts before the
3698 	 * delalloc range we found in the io tree.
3699 	 */
3700 	if (em->start < *delalloc_start_ret) {
3701 		*delalloc_start_ret = em->start;
3702 		/*
3703 		 * If the ranges are adjacent, return a combined range.
3704 		 * Otherwise return the extent map's range.
3705 		 */
3706 		if (em_end < *delalloc_start_ret)
3707 			*delalloc_end_ret = min(end, em_end - 1);
3708 
3709 		free_extent_map(em);
3710 		return true;
3711 	}
3712 
3713 	/*
3714 	 * The extent map starts after the delalloc range we found in the io
3715 	 * tree. If it's adjacent, return a combined range, otherwise return
3716 	 * the range found in the io tree.
3717 	 */
3718 	if (*delalloc_end_ret + 1 == em->start)
3719 		*delalloc_end_ret = min(end, em_end - 1);
3720 
3721 	free_extent_map(em);
3722 	return true;
3723 }
3724 
3725 /*
3726  * Check if there's delalloc in a given range.
3727  *
3728  * @inode:               The inode.
3729  * @start:               The start offset of the range. It does not need to be
3730  *                       sector size aligned.
3731  * @end:                 The end offset (inclusive value) of the search range.
3732  *                       It does not need to be sector size aligned.
3733  * @delalloc_start_ret:  Output argument, set to the start offset of the
3734  *                       subrange found with delalloc (may not be sector size
3735  *                       aligned).
3736  * @delalloc_end_ret:    Output argument, set to he end offset (inclusive value)
3737  *                       of the subrange found with delalloc.
3738  *
3739  * Returns true if a subrange with delalloc is found within the given range, and
3740  * if so it sets @delalloc_start_ret and @delalloc_end_ret with the start and
3741  * end offsets of the subrange.
3742  */
3743 bool btrfs_find_delalloc_in_range(struct btrfs_inode *inode, u64 start, u64 end,
3744 				  u64 *delalloc_start_ret, u64 *delalloc_end_ret)
3745 {
3746 	u64 cur_offset = round_down(start, inode->root->fs_info->sectorsize);
3747 	u64 prev_delalloc_end = 0;
3748 	bool ret = false;
3749 
3750 	while (cur_offset < end) {
3751 		u64 delalloc_start;
3752 		u64 delalloc_end;
3753 		bool delalloc;
3754 
3755 		delalloc = find_delalloc_subrange(inode, cur_offset, end,
3756 						  &delalloc_start,
3757 						  &delalloc_end);
3758 		if (!delalloc)
3759 			break;
3760 
3761 		if (prev_delalloc_end == 0) {
3762 			/* First subrange found. */
3763 			*delalloc_start_ret = max(delalloc_start, start);
3764 			*delalloc_end_ret = delalloc_end;
3765 			ret = true;
3766 		} else if (delalloc_start == prev_delalloc_end + 1) {
3767 			/* Subrange adjacent to the previous one, merge them. */
3768 			*delalloc_end_ret = delalloc_end;
3769 		} else {
3770 			/* Subrange not adjacent to the previous one, exit. */
3771 			break;
3772 		}
3773 
3774 		prev_delalloc_end = delalloc_end;
3775 		cur_offset = delalloc_end + 1;
3776 		cond_resched();
3777 	}
3778 
3779 	return ret;
3780 }
3781 
3782 /*
3783  * Check if there's a hole or delalloc range in a range representing a hole (or
3784  * prealloc extent) found in the inode's subvolume btree.
3785  *
3786  * @inode:      The inode.
3787  * @whence:     Seek mode (SEEK_DATA or SEEK_HOLE).
3788  * @start:      Start offset of the hole region. It does not need to be sector
3789  *              size aligned.
3790  * @end:        End offset (inclusive value) of the hole region. It does not
3791  *              need to be sector size aligned.
3792  * @start_ret:  Return parameter, used to set the start of the subrange in the
3793  *              hole that matches the search criteria (seek mode), if such
3794  *              subrange is found (return value of the function is true).
3795  *              The value returned here may not be sector size aligned.
3796  *
3797  * Returns true if a subrange matching the given seek mode is found, and if one
3798  * is found, it updates @start_ret with the start of the subrange.
3799  */
3800 static bool find_desired_extent_in_hole(struct btrfs_inode *inode, int whence,
3801 					u64 start, u64 end, u64 *start_ret)
3802 {
3803 	u64 delalloc_start;
3804 	u64 delalloc_end;
3805 	bool delalloc;
3806 
3807 	delalloc = btrfs_find_delalloc_in_range(inode, start, end,
3808 						&delalloc_start, &delalloc_end);
3809 	if (delalloc && whence == SEEK_DATA) {
3810 		*start_ret = delalloc_start;
3811 		return true;
3812 	}
3813 
3814 	if (delalloc && whence == SEEK_HOLE) {
3815 		/*
3816 		 * We found delalloc but it starts after out start offset. So we
3817 		 * have a hole between our start offset and the delalloc start.
3818 		 */
3819 		if (start < delalloc_start) {
3820 			*start_ret = start;
3821 			return true;
3822 		}
3823 		/*
3824 		 * Delalloc range starts at our start offset.
3825 		 * If the delalloc range's length is smaller than our range,
3826 		 * then it means we have a hole that starts where the delalloc
3827 		 * subrange ends.
3828 		 */
3829 		if (delalloc_end < end) {
3830 			*start_ret = delalloc_end + 1;
3831 			return true;
3832 		}
3833 
3834 		/* There's delalloc for the whole range. */
3835 		return false;
3836 	}
3837 
3838 	if (!delalloc && whence == SEEK_HOLE) {
3839 		*start_ret = start;
3840 		return true;
3841 	}
3842 
3843 	/*
3844 	 * No delalloc in the range and we are seeking for data. The caller has
3845 	 * to iterate to the next extent item in the subvolume btree.
3846 	 */
3847 	return false;
3848 }
3849 
3850 static loff_t find_desired_extent(struct btrfs_inode *inode, loff_t offset,
3851 				  int whence)
3852 {
3853 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
3854 	struct extent_state *cached_state = NULL;
3855 	const loff_t i_size = i_size_read(&inode->vfs_inode);
3856 	const u64 ino = btrfs_ino(inode);
3857 	struct btrfs_root *root = inode->root;
3858 	struct btrfs_path *path;
3859 	struct btrfs_key key;
3860 	u64 last_extent_end;
3861 	u64 lockstart;
3862 	u64 lockend;
3863 	u64 start;
3864 	int ret;
3865 	bool found = false;
3866 
3867 	if (i_size == 0 || offset >= i_size)
3868 		return -ENXIO;
3869 
3870 	/*
3871 	 * Quick path. If the inode has no prealloc extents and its number of
3872 	 * bytes used matches its i_size, then it can not have holes.
3873 	 */
3874 	if (whence == SEEK_HOLE &&
3875 	    !(inode->flags & BTRFS_INODE_PREALLOC) &&
3876 	    inode_get_bytes(&inode->vfs_inode) == i_size)
3877 		return i_size;
3878 
3879 	/*
3880 	 * offset can be negative, in this case we start finding DATA/HOLE from
3881 	 * the very start of the file.
3882 	 */
3883 	start = max_t(loff_t, 0, offset);
3884 
3885 	lockstart = round_down(start, fs_info->sectorsize);
3886 	lockend = round_up(i_size, fs_info->sectorsize);
3887 	if (lockend <= lockstart)
3888 		lockend = lockstart + fs_info->sectorsize;
3889 	lockend--;
3890 
3891 	path = btrfs_alloc_path();
3892 	if (!path)
3893 		return -ENOMEM;
3894 	path->reada = READA_FORWARD;
3895 
3896 	key.objectid = ino;
3897 	key.type = BTRFS_EXTENT_DATA_KEY;
3898 	key.offset = start;
3899 
3900 	last_extent_end = lockstart;
3901 
3902 	lock_extent_bits(&inode->io_tree, lockstart, lockend, &cached_state);
3903 
3904 	ret = btrfs_search_slot(NULL, root, &key, path, 0, 0);
3905 	if (ret < 0) {
3906 		goto out;
3907 	} else if (ret > 0 && path->slots[0] > 0) {
3908 		btrfs_item_key_to_cpu(path->nodes[0], &key, path->slots[0] - 1);
3909 		if (key.objectid == ino && key.type == BTRFS_EXTENT_DATA_KEY)
3910 			path->slots[0]--;
3911 	}
3912 
3913 	while (start < i_size) {
3914 		struct extent_buffer *leaf = path->nodes[0];
3915 		struct btrfs_file_extent_item *extent;
3916 		u64 extent_end;
3917 
3918 		if (path->slots[0] >= btrfs_header_nritems(leaf)) {
3919 			ret = btrfs_next_leaf(root, path);
3920 			if (ret < 0)
3921 				goto out;
3922 			else if (ret > 0)
3923 				break;
3924 
3925 			leaf = path->nodes[0];
3926 		}
3927 
3928 		btrfs_item_key_to_cpu(leaf, &key, path->slots[0]);
3929 		if (key.objectid != ino || key.type != BTRFS_EXTENT_DATA_KEY)
3930 			break;
3931 
3932 		extent_end = btrfs_file_extent_end(path);
3933 
3934 		/*
3935 		 * In the first iteration we may have a slot that points to an
3936 		 * extent that ends before our start offset, so skip it.
3937 		 */
3938 		if (extent_end <= start) {
3939 			path->slots[0]++;
3940 			continue;
3941 		}
3942 
3943 		/* We have an implicit hole, NO_HOLES feature is likely set. */
3944 		if (last_extent_end < key.offset) {
3945 			u64 search_start = last_extent_end;
3946 			u64 found_start;
3947 
3948 			/*
3949 			 * First iteration, @start matches @offset and it's
3950 			 * within the hole.
3951 			 */
3952 			if (start == offset)
3953 				search_start = offset;
3954 
3955 			found = find_desired_extent_in_hole(inode, whence,
3956 							    search_start,
3957 							    key.offset - 1,
3958 							    &found_start);
3959 			if (found) {
3960 				start = found_start;
3961 				break;
3962 			}
3963 			/*
3964 			 * Didn't find data or a hole (due to delalloc) in the
3965 			 * implicit hole range, so need to analyze the extent.
3966 			 */
3967 		}
3968 
3969 		extent = btrfs_item_ptr(leaf, path->slots[0],
3970 					struct btrfs_file_extent_item);
3971 
3972 		if (btrfs_file_extent_disk_bytenr(leaf, extent) == 0 ||
3973 		    btrfs_file_extent_type(leaf, extent) ==
3974 		    BTRFS_FILE_EXTENT_PREALLOC) {
3975 			/*
3976 			 * Explicit hole or prealloc extent, search for delalloc.
3977 			 * A prealloc extent is treated like a hole.
3978 			 */
3979 			u64 search_start = key.offset;
3980 			u64 found_start;
3981 
3982 			/*
3983 			 * First iteration, @start matches @offset and it's
3984 			 * within the hole.
3985 			 */
3986 			if (start == offset)
3987 				search_start = offset;
3988 
3989 			found = find_desired_extent_in_hole(inode, whence,
3990 							    search_start,
3991 							    extent_end - 1,
3992 							    &found_start);
3993 			if (found) {
3994 				start = found_start;
3995 				break;
3996 			}
3997 			/*
3998 			 * Didn't find data or a hole (due to delalloc) in the
3999 			 * implicit hole range, so need to analyze the next
4000 			 * extent item.
4001 			 */
4002 		} else {
4003 			/*
4004 			 * Found a regular or inline extent.
4005 			 * If we are seeking for data, adjust the start offset
4006 			 * and stop, we're done.
4007 			 */
4008 			if (whence == SEEK_DATA) {
4009 				start = max_t(u64, key.offset, offset);
4010 				found = true;
4011 				break;
4012 			}
4013 			/*
4014 			 * Else, we are seeking for a hole, check the next file
4015 			 * extent item.
4016 			 */
4017 		}
4018 
4019 		start = extent_end;
4020 		last_extent_end = extent_end;
4021 		path->slots[0]++;
4022 		if (fatal_signal_pending(current)) {
4023 			ret = -EINTR;
4024 			goto out;
4025 		}
4026 		cond_resched();
4027 	}
4028 
4029 	/* We have an implicit hole from the last extent found up to i_size. */
4030 	if (!found && start < i_size) {
4031 		found = find_desired_extent_in_hole(inode, whence, start,
4032 						    i_size - 1, &start);
4033 		if (!found)
4034 			start = i_size;
4035 	}
4036 
4037 out:
4038 	unlock_extent_cached(&inode->io_tree, lockstart, lockend,
4039 			     &cached_state);
4040 	btrfs_free_path(path);
4041 
4042 	if (ret < 0)
4043 		return ret;
4044 
4045 	if (whence == SEEK_DATA && start >= i_size)
4046 		return -ENXIO;
4047 
4048 	return min_t(loff_t, start, i_size);
4049 }
4050 
4051 static loff_t btrfs_file_llseek(struct file *file, loff_t offset, int whence)
4052 {
4053 	struct inode *inode = file->f_mapping->host;
4054 
4055 	switch (whence) {
4056 	default:
4057 		return generic_file_llseek(file, offset, whence);
4058 	case SEEK_DATA:
4059 	case SEEK_HOLE:
4060 		btrfs_inode_lock(inode, BTRFS_ILOCK_SHARED);
4061 		offset = find_desired_extent(BTRFS_I(inode), offset, whence);
4062 		btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
4063 		break;
4064 	}
4065 
4066 	if (offset < 0)
4067 		return offset;
4068 
4069 	return vfs_setpos(file, offset, inode->i_sb->s_maxbytes);
4070 }
4071 
4072 static int btrfs_file_open(struct inode *inode, struct file *filp)
4073 {
4074 	int ret;
4075 
4076 	filp->f_mode |= FMODE_NOWAIT | FMODE_BUF_RASYNC;
4077 
4078 	ret = fsverity_file_open(inode, filp);
4079 	if (ret)
4080 		return ret;
4081 	return generic_file_open(inode, filp);
4082 }
4083 
4084 static int check_direct_read(struct btrfs_fs_info *fs_info,
4085 			     const struct iov_iter *iter, loff_t offset)
4086 {
4087 	int ret;
4088 	int i, seg;
4089 
4090 	ret = check_direct_IO(fs_info, iter, offset);
4091 	if (ret < 0)
4092 		return ret;
4093 
4094 	if (!iter_is_iovec(iter))
4095 		return 0;
4096 
4097 	for (seg = 0; seg < iter->nr_segs; seg++)
4098 		for (i = seg + 1; i < iter->nr_segs; i++)
4099 			if (iter->iov[seg].iov_base == iter->iov[i].iov_base)
4100 				return -EINVAL;
4101 	return 0;
4102 }
4103 
4104 static ssize_t btrfs_direct_read(struct kiocb *iocb, struct iov_iter *to)
4105 {
4106 	struct inode *inode = file_inode(iocb->ki_filp);
4107 	size_t prev_left = 0;
4108 	ssize_t read = 0;
4109 	ssize_t ret;
4110 
4111 	if (fsverity_active(inode))
4112 		return 0;
4113 
4114 	if (check_direct_read(btrfs_sb(inode->i_sb), to, iocb->ki_pos))
4115 		return 0;
4116 
4117 	btrfs_inode_lock(inode, BTRFS_ILOCK_SHARED);
4118 again:
4119 	/*
4120 	 * This is similar to what we do for direct IO writes, see the comment
4121 	 * at btrfs_direct_write(), but we also disable page faults in addition
4122 	 * to disabling them only at the iov_iter level. This is because when
4123 	 * reading from a hole or prealloc extent, iomap calls iov_iter_zero(),
4124 	 * which can still trigger page fault ins despite having set ->nofault
4125 	 * to true of our 'to' iov_iter.
4126 	 *
4127 	 * The difference to direct IO writes is that we deadlock when trying
4128 	 * to lock the extent range in the inode's tree during he page reads
4129 	 * triggered by the fault in (while for writes it is due to waiting for
4130 	 * our own ordered extent). This is because for direct IO reads,
4131 	 * btrfs_dio_iomap_begin() returns with the extent range locked, which
4132 	 * is only unlocked in the endio callback (end_bio_extent_readpage()).
4133 	 */
4134 	pagefault_disable();
4135 	to->nofault = true;
4136 	ret = btrfs_dio_rw(iocb, to, read);
4137 	to->nofault = false;
4138 	pagefault_enable();
4139 
4140 	/* No increment (+=) because iomap returns a cumulative value. */
4141 	if (ret > 0)
4142 		read = ret;
4143 
4144 	if (iov_iter_count(to) > 0 && (ret == -EFAULT || ret > 0)) {
4145 		const size_t left = iov_iter_count(to);
4146 
4147 		if (left == prev_left) {
4148 			/*
4149 			 * We didn't make any progress since the last attempt,
4150 			 * fallback to a buffered read for the remainder of the
4151 			 * range. This is just to avoid any possibility of looping
4152 			 * for too long.
4153 			 */
4154 			ret = read;
4155 		} else {
4156 			/*
4157 			 * We made some progress since the last retry or this is
4158 			 * the first time we are retrying. Fault in as many pages
4159 			 * as possible and retry.
4160 			 */
4161 			fault_in_iov_iter_writeable(to, left);
4162 			prev_left = left;
4163 			goto again;
4164 		}
4165 	}
4166 	btrfs_inode_unlock(inode, BTRFS_ILOCK_SHARED);
4167 	return ret < 0 ? ret : read;
4168 }
4169 
4170 static ssize_t btrfs_file_read_iter(struct kiocb *iocb, struct iov_iter *to)
4171 {
4172 	ssize_t ret = 0;
4173 
4174 	if (iocb->ki_flags & IOCB_DIRECT) {
4175 		ret = btrfs_direct_read(iocb, to);
4176 		if (ret < 0 || !iov_iter_count(to) ||
4177 		    iocb->ki_pos >= i_size_read(file_inode(iocb->ki_filp)))
4178 			return ret;
4179 	}
4180 
4181 	return filemap_read(iocb, to, ret);
4182 }
4183 
4184 const struct file_operations btrfs_file_operations = {
4185 	.llseek		= btrfs_file_llseek,
4186 	.read_iter      = btrfs_file_read_iter,
4187 	.splice_read	= generic_file_splice_read,
4188 	.write_iter	= btrfs_file_write_iter,
4189 	.splice_write	= iter_file_splice_write,
4190 	.mmap		= btrfs_file_mmap,
4191 	.open		= btrfs_file_open,
4192 	.release	= btrfs_release_file,
4193 	.get_unmapped_area = thp_get_unmapped_area,
4194 	.fsync		= btrfs_sync_file,
4195 	.fallocate	= btrfs_fallocate,
4196 	.unlocked_ioctl	= btrfs_ioctl,
4197 #ifdef CONFIG_COMPAT
4198 	.compat_ioctl	= btrfs_compat_ioctl,
4199 #endif
4200 	.remap_file_range = btrfs_remap_file_range,
4201 };
4202 
4203 void __cold btrfs_auto_defrag_exit(void)
4204 {
4205 	kmem_cache_destroy(btrfs_inode_defrag_cachep);
4206 }
4207 
4208 int __init btrfs_auto_defrag_init(void)
4209 {
4210 	btrfs_inode_defrag_cachep = kmem_cache_create("btrfs_inode_defrag",
4211 					sizeof(struct inode_defrag), 0,
4212 					SLAB_MEM_SPREAD,
4213 					NULL);
4214 	if (!btrfs_inode_defrag_cachep)
4215 		return -ENOMEM;
4216 
4217 	return 0;
4218 }
4219 
4220 int btrfs_fdatawrite_range(struct inode *inode, loff_t start, loff_t end)
4221 {
4222 	int ret;
4223 
4224 	/*
4225 	 * So with compression we will find and lock a dirty page and clear the
4226 	 * first one as dirty, setup an async extent, and immediately return
4227 	 * with the entire range locked but with nobody actually marked with
4228 	 * writeback.  So we can't just filemap_write_and_wait_range() and
4229 	 * expect it to work since it will just kick off a thread to do the
4230 	 * actual work.  So we need to call filemap_fdatawrite_range _again_
4231 	 * since it will wait on the page lock, which won't be unlocked until
4232 	 * after the pages have been marked as writeback and so we're good to go
4233 	 * from there.  We have to do this otherwise we'll miss the ordered
4234 	 * extents and that results in badness.  Please Josef, do not think you
4235 	 * know better and pull this out at some point in the future, it is
4236 	 * right and you are wrong.
4237 	 */
4238 	ret = filemap_fdatawrite_range(inode->i_mapping, start, end);
4239 	if (!ret && test_bit(BTRFS_INODE_HAS_ASYNC_EXTENT,
4240 			     &BTRFS_I(inode)->runtime_flags))
4241 		ret = filemap_fdatawrite_range(inode->i_mapping, start, end);
4242 
4243 	return ret;
4244 }
4245