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