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