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