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