xref: /openbmc/linux/fs/btrfs/ordered-data.c (revision 7d545e77)
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Copyright (C) 2007 Oracle.  All rights reserved.
4  */
5 
6 #include <linux/slab.h>
7 #include <linux/blkdev.h>
8 #include <linux/writeback.h>
9 #include <linux/sched/mm.h>
10 #include "ctree.h"
11 #include "transaction.h"
12 #include "btrfs_inode.h"
13 #include "extent_io.h"
14 #include "disk-io.h"
15 #include "compression.h"
16 #include "delalloc-space.h"
17 
18 static struct kmem_cache *btrfs_ordered_extent_cache;
19 
20 static u64 entry_end(struct btrfs_ordered_extent *entry)
21 {
22 	if (entry->file_offset + entry->len < entry->file_offset)
23 		return (u64)-1;
24 	return entry->file_offset + entry->len;
25 }
26 
27 /* returns NULL if the insertion worked, or it returns the node it did find
28  * in the tree
29  */
30 static struct rb_node *tree_insert(struct rb_root *root, u64 file_offset,
31 				   struct rb_node *node)
32 {
33 	struct rb_node **p = &root->rb_node;
34 	struct rb_node *parent = NULL;
35 	struct btrfs_ordered_extent *entry;
36 
37 	while (*p) {
38 		parent = *p;
39 		entry = rb_entry(parent, struct btrfs_ordered_extent, rb_node);
40 
41 		if (file_offset < entry->file_offset)
42 			p = &(*p)->rb_left;
43 		else if (file_offset >= entry_end(entry))
44 			p = &(*p)->rb_right;
45 		else
46 			return parent;
47 	}
48 
49 	rb_link_node(node, parent, p);
50 	rb_insert_color(node, root);
51 	return NULL;
52 }
53 
54 static void ordered_data_tree_panic(struct inode *inode, int errno,
55 					       u64 offset)
56 {
57 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
58 	btrfs_panic(fs_info, errno,
59 		    "Inconsistency in ordered tree at offset %llu", offset);
60 }
61 
62 /*
63  * look for a given offset in the tree, and if it can't be found return the
64  * first lesser offset
65  */
66 static struct rb_node *__tree_search(struct rb_root *root, u64 file_offset,
67 				     struct rb_node **prev_ret)
68 {
69 	struct rb_node *n = root->rb_node;
70 	struct rb_node *prev = NULL;
71 	struct rb_node *test;
72 	struct btrfs_ordered_extent *entry;
73 	struct btrfs_ordered_extent *prev_entry = NULL;
74 
75 	while (n) {
76 		entry = rb_entry(n, struct btrfs_ordered_extent, rb_node);
77 		prev = n;
78 		prev_entry = entry;
79 
80 		if (file_offset < entry->file_offset)
81 			n = n->rb_left;
82 		else if (file_offset >= entry_end(entry))
83 			n = n->rb_right;
84 		else
85 			return n;
86 	}
87 	if (!prev_ret)
88 		return NULL;
89 
90 	while (prev && file_offset >= entry_end(prev_entry)) {
91 		test = rb_next(prev);
92 		if (!test)
93 			break;
94 		prev_entry = rb_entry(test, struct btrfs_ordered_extent,
95 				      rb_node);
96 		if (file_offset < entry_end(prev_entry))
97 			break;
98 
99 		prev = test;
100 	}
101 	if (prev)
102 		prev_entry = rb_entry(prev, struct btrfs_ordered_extent,
103 				      rb_node);
104 	while (prev && file_offset < entry_end(prev_entry)) {
105 		test = rb_prev(prev);
106 		if (!test)
107 			break;
108 		prev_entry = rb_entry(test, struct btrfs_ordered_extent,
109 				      rb_node);
110 		prev = test;
111 	}
112 	*prev_ret = prev;
113 	return NULL;
114 }
115 
116 /*
117  * helper to check if a given offset is inside a given entry
118  */
119 static int offset_in_entry(struct btrfs_ordered_extent *entry, u64 file_offset)
120 {
121 	if (file_offset < entry->file_offset ||
122 	    entry->file_offset + entry->len <= file_offset)
123 		return 0;
124 	return 1;
125 }
126 
127 static int range_overlaps(struct btrfs_ordered_extent *entry, u64 file_offset,
128 			  u64 len)
129 {
130 	if (file_offset + len <= entry->file_offset ||
131 	    entry->file_offset + entry->len <= file_offset)
132 		return 0;
133 	return 1;
134 }
135 
136 /*
137  * look find the first ordered struct that has this offset, otherwise
138  * the first one less than this offset
139  */
140 static inline struct rb_node *tree_search(struct btrfs_ordered_inode_tree *tree,
141 					  u64 file_offset)
142 {
143 	struct rb_root *root = &tree->tree;
144 	struct rb_node *prev = NULL;
145 	struct rb_node *ret;
146 	struct btrfs_ordered_extent *entry;
147 
148 	if (tree->last) {
149 		entry = rb_entry(tree->last, struct btrfs_ordered_extent,
150 				 rb_node);
151 		if (offset_in_entry(entry, file_offset))
152 			return tree->last;
153 	}
154 	ret = __tree_search(root, file_offset, &prev);
155 	if (!ret)
156 		ret = prev;
157 	if (ret)
158 		tree->last = ret;
159 	return ret;
160 }
161 
162 /* allocate and add a new ordered_extent into the per-inode tree.
163  * file_offset is the logical offset in the file
164  *
165  * start is the disk block number of an extent already reserved in the
166  * extent allocation tree
167  *
168  * len is the length of the extent
169  *
170  * The tree is given a single reference on the ordered extent that was
171  * inserted.
172  */
173 static int __btrfs_add_ordered_extent(struct inode *inode, u64 file_offset,
174 				      u64 start, u64 len, u64 disk_len,
175 				      int type, int dio, int compress_type)
176 {
177 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
178 	struct btrfs_root *root = BTRFS_I(inode)->root;
179 	struct btrfs_ordered_inode_tree *tree;
180 	struct rb_node *node;
181 	struct btrfs_ordered_extent *entry;
182 
183 	tree = &BTRFS_I(inode)->ordered_tree;
184 	entry = kmem_cache_zalloc(btrfs_ordered_extent_cache, GFP_NOFS);
185 	if (!entry)
186 		return -ENOMEM;
187 
188 	entry->file_offset = file_offset;
189 	entry->start = start;
190 	entry->len = len;
191 	entry->disk_len = disk_len;
192 	entry->bytes_left = len;
193 	entry->inode = igrab(inode);
194 	entry->compress_type = compress_type;
195 	entry->truncated_len = (u64)-1;
196 	if (type != BTRFS_ORDERED_IO_DONE && type != BTRFS_ORDERED_COMPLETE)
197 		set_bit(type, &entry->flags);
198 
199 	if (dio) {
200 		percpu_counter_add_batch(&fs_info->dio_bytes, len,
201 					 fs_info->delalloc_batch);
202 		set_bit(BTRFS_ORDERED_DIRECT, &entry->flags);
203 	}
204 
205 	/* one ref for the tree */
206 	refcount_set(&entry->refs, 1);
207 	init_waitqueue_head(&entry->wait);
208 	INIT_LIST_HEAD(&entry->list);
209 	INIT_LIST_HEAD(&entry->root_extent_list);
210 	INIT_LIST_HEAD(&entry->work_list);
211 	init_completion(&entry->completion);
212 	INIT_LIST_HEAD(&entry->log_list);
213 	INIT_LIST_HEAD(&entry->trans_list);
214 
215 	trace_btrfs_ordered_extent_add(inode, entry);
216 
217 	spin_lock_irq(&tree->lock);
218 	node = tree_insert(&tree->tree, file_offset,
219 			   &entry->rb_node);
220 	if (node)
221 		ordered_data_tree_panic(inode, -EEXIST, file_offset);
222 	spin_unlock_irq(&tree->lock);
223 
224 	spin_lock(&root->ordered_extent_lock);
225 	list_add_tail(&entry->root_extent_list,
226 		      &root->ordered_extents);
227 	root->nr_ordered_extents++;
228 	if (root->nr_ordered_extents == 1) {
229 		spin_lock(&fs_info->ordered_root_lock);
230 		BUG_ON(!list_empty(&root->ordered_root));
231 		list_add_tail(&root->ordered_root, &fs_info->ordered_roots);
232 		spin_unlock(&fs_info->ordered_root_lock);
233 	}
234 	spin_unlock(&root->ordered_extent_lock);
235 
236 	/*
237 	 * We don't need the count_max_extents here, we can assume that all of
238 	 * that work has been done at higher layers, so this is truly the
239 	 * smallest the extent is going to get.
240 	 */
241 	spin_lock(&BTRFS_I(inode)->lock);
242 	btrfs_mod_outstanding_extents(BTRFS_I(inode), 1);
243 	spin_unlock(&BTRFS_I(inode)->lock);
244 
245 	return 0;
246 }
247 
248 int btrfs_add_ordered_extent(struct inode *inode, u64 file_offset,
249 			     u64 start, u64 len, u64 disk_len, int type)
250 {
251 	return __btrfs_add_ordered_extent(inode, file_offset, start, len,
252 					  disk_len, type, 0,
253 					  BTRFS_COMPRESS_NONE);
254 }
255 
256 int btrfs_add_ordered_extent_dio(struct inode *inode, u64 file_offset,
257 				 u64 start, u64 len, u64 disk_len, int type)
258 {
259 	return __btrfs_add_ordered_extent(inode, file_offset, start, len,
260 					  disk_len, type, 1,
261 					  BTRFS_COMPRESS_NONE);
262 }
263 
264 int btrfs_add_ordered_extent_compress(struct inode *inode, u64 file_offset,
265 				      u64 start, u64 len, u64 disk_len,
266 				      int type, int compress_type)
267 {
268 	return __btrfs_add_ordered_extent(inode, file_offset, start, len,
269 					  disk_len, type, 0,
270 					  compress_type);
271 }
272 
273 /*
274  * Add a struct btrfs_ordered_sum into the list of checksums to be inserted
275  * when an ordered extent is finished.  If the list covers more than one
276  * ordered extent, it is split across multiples.
277  */
278 void btrfs_add_ordered_sum(struct btrfs_ordered_extent *entry,
279 			   struct btrfs_ordered_sum *sum)
280 {
281 	struct btrfs_ordered_inode_tree *tree;
282 
283 	tree = &BTRFS_I(entry->inode)->ordered_tree;
284 	spin_lock_irq(&tree->lock);
285 	list_add_tail(&sum->list, &entry->list);
286 	spin_unlock_irq(&tree->lock);
287 }
288 
289 /*
290  * this is used to account for finished IO across a given range
291  * of the file.  The IO may span ordered extents.  If
292  * a given ordered_extent is completely done, 1 is returned, otherwise
293  * 0.
294  *
295  * test_and_set_bit on a flag in the struct btrfs_ordered_extent is used
296  * to make sure this function only returns 1 once for a given ordered extent.
297  *
298  * file_offset is updated to one byte past the range that is recorded as
299  * complete.  This allows you to walk forward in the file.
300  */
301 int btrfs_dec_test_first_ordered_pending(struct inode *inode,
302 				   struct btrfs_ordered_extent **cached,
303 				   u64 *file_offset, u64 io_size, int uptodate)
304 {
305 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
306 	struct btrfs_ordered_inode_tree *tree;
307 	struct rb_node *node;
308 	struct btrfs_ordered_extent *entry = NULL;
309 	int ret;
310 	unsigned long flags;
311 	u64 dec_end;
312 	u64 dec_start;
313 	u64 to_dec;
314 
315 	tree = &BTRFS_I(inode)->ordered_tree;
316 	spin_lock_irqsave(&tree->lock, flags);
317 	node = tree_search(tree, *file_offset);
318 	if (!node) {
319 		ret = 1;
320 		goto out;
321 	}
322 
323 	entry = rb_entry(node, struct btrfs_ordered_extent, rb_node);
324 	if (!offset_in_entry(entry, *file_offset)) {
325 		ret = 1;
326 		goto out;
327 	}
328 
329 	dec_start = max(*file_offset, entry->file_offset);
330 	dec_end = min(*file_offset + io_size, entry->file_offset +
331 		      entry->len);
332 	*file_offset = dec_end;
333 	if (dec_start > dec_end) {
334 		btrfs_crit(fs_info, "bad ordering dec_start %llu end %llu",
335 			   dec_start, dec_end);
336 	}
337 	to_dec = dec_end - dec_start;
338 	if (to_dec > entry->bytes_left) {
339 		btrfs_crit(fs_info,
340 			   "bad ordered accounting left %llu size %llu",
341 			   entry->bytes_left, to_dec);
342 	}
343 	entry->bytes_left -= to_dec;
344 	if (!uptodate)
345 		set_bit(BTRFS_ORDERED_IOERR, &entry->flags);
346 
347 	if (entry->bytes_left == 0) {
348 		ret = test_and_set_bit(BTRFS_ORDERED_IO_DONE, &entry->flags);
349 		/* test_and_set_bit implies a barrier */
350 		cond_wake_up_nomb(&entry->wait);
351 	} else {
352 		ret = 1;
353 	}
354 out:
355 	if (!ret && cached && entry) {
356 		*cached = entry;
357 		refcount_inc(&entry->refs);
358 	}
359 	spin_unlock_irqrestore(&tree->lock, flags);
360 	return ret == 0;
361 }
362 
363 /*
364  * this is used to account for finished IO across a given range
365  * of the file.  The IO should not span ordered extents.  If
366  * a given ordered_extent is completely done, 1 is returned, otherwise
367  * 0.
368  *
369  * test_and_set_bit on a flag in the struct btrfs_ordered_extent is used
370  * to make sure this function only returns 1 once for a given ordered extent.
371  */
372 int btrfs_dec_test_ordered_pending(struct inode *inode,
373 				   struct btrfs_ordered_extent **cached,
374 				   u64 file_offset, u64 io_size, int uptodate)
375 {
376 	struct btrfs_ordered_inode_tree *tree;
377 	struct rb_node *node;
378 	struct btrfs_ordered_extent *entry = NULL;
379 	unsigned long flags;
380 	int ret;
381 
382 	tree = &BTRFS_I(inode)->ordered_tree;
383 	spin_lock_irqsave(&tree->lock, flags);
384 	if (cached && *cached) {
385 		entry = *cached;
386 		goto have_entry;
387 	}
388 
389 	node = tree_search(tree, file_offset);
390 	if (!node) {
391 		ret = 1;
392 		goto out;
393 	}
394 
395 	entry = rb_entry(node, struct btrfs_ordered_extent, rb_node);
396 have_entry:
397 	if (!offset_in_entry(entry, file_offset)) {
398 		ret = 1;
399 		goto out;
400 	}
401 
402 	if (io_size > entry->bytes_left) {
403 		btrfs_crit(BTRFS_I(inode)->root->fs_info,
404 			   "bad ordered accounting left %llu size %llu",
405 		       entry->bytes_left, io_size);
406 	}
407 	entry->bytes_left -= io_size;
408 	if (!uptodate)
409 		set_bit(BTRFS_ORDERED_IOERR, &entry->flags);
410 
411 	if (entry->bytes_left == 0) {
412 		ret = test_and_set_bit(BTRFS_ORDERED_IO_DONE, &entry->flags);
413 		/* test_and_set_bit implies a barrier */
414 		cond_wake_up_nomb(&entry->wait);
415 	} else {
416 		ret = 1;
417 	}
418 out:
419 	if (!ret && cached && entry) {
420 		*cached = entry;
421 		refcount_inc(&entry->refs);
422 	}
423 	spin_unlock_irqrestore(&tree->lock, flags);
424 	return ret == 0;
425 }
426 
427 /*
428  * used to drop a reference on an ordered extent.  This will free
429  * the extent if the last reference is dropped
430  */
431 void btrfs_put_ordered_extent(struct btrfs_ordered_extent *entry)
432 {
433 	struct list_head *cur;
434 	struct btrfs_ordered_sum *sum;
435 
436 	trace_btrfs_ordered_extent_put(entry->inode, entry);
437 
438 	if (refcount_dec_and_test(&entry->refs)) {
439 		ASSERT(list_empty(&entry->log_list));
440 		ASSERT(list_empty(&entry->trans_list));
441 		ASSERT(list_empty(&entry->root_extent_list));
442 		ASSERT(RB_EMPTY_NODE(&entry->rb_node));
443 		if (entry->inode)
444 			btrfs_add_delayed_iput(entry->inode);
445 		while (!list_empty(&entry->list)) {
446 			cur = entry->list.next;
447 			sum = list_entry(cur, struct btrfs_ordered_sum, list);
448 			list_del(&sum->list);
449 			kvfree(sum);
450 		}
451 		kmem_cache_free(btrfs_ordered_extent_cache, entry);
452 	}
453 }
454 
455 /*
456  * remove an ordered extent from the tree.  No references are dropped
457  * and waiters are woken up.
458  */
459 void btrfs_remove_ordered_extent(struct inode *inode,
460 				 struct btrfs_ordered_extent *entry)
461 {
462 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
463 	struct btrfs_ordered_inode_tree *tree;
464 	struct btrfs_inode *btrfs_inode = BTRFS_I(inode);
465 	struct btrfs_root *root = btrfs_inode->root;
466 	struct rb_node *node;
467 
468 	/* This is paired with btrfs_add_ordered_extent. */
469 	spin_lock(&btrfs_inode->lock);
470 	btrfs_mod_outstanding_extents(btrfs_inode, -1);
471 	spin_unlock(&btrfs_inode->lock);
472 	if (root != fs_info->tree_root)
473 		btrfs_delalloc_release_metadata(btrfs_inode, entry->len, false);
474 
475 	if (test_bit(BTRFS_ORDERED_DIRECT, &entry->flags))
476 		percpu_counter_add_batch(&fs_info->dio_bytes, -entry->len,
477 					 fs_info->delalloc_batch);
478 
479 	tree = &btrfs_inode->ordered_tree;
480 	spin_lock_irq(&tree->lock);
481 	node = &entry->rb_node;
482 	rb_erase(node, &tree->tree);
483 	RB_CLEAR_NODE(node);
484 	if (tree->last == node)
485 		tree->last = NULL;
486 	set_bit(BTRFS_ORDERED_COMPLETE, &entry->flags);
487 	spin_unlock_irq(&tree->lock);
488 
489 	spin_lock(&root->ordered_extent_lock);
490 	list_del_init(&entry->root_extent_list);
491 	root->nr_ordered_extents--;
492 
493 	trace_btrfs_ordered_extent_remove(inode, entry);
494 
495 	if (!root->nr_ordered_extents) {
496 		spin_lock(&fs_info->ordered_root_lock);
497 		BUG_ON(list_empty(&root->ordered_root));
498 		list_del_init(&root->ordered_root);
499 		spin_unlock(&fs_info->ordered_root_lock);
500 	}
501 	spin_unlock(&root->ordered_extent_lock);
502 	wake_up(&entry->wait);
503 }
504 
505 static void btrfs_run_ordered_extent_work(struct btrfs_work *work)
506 {
507 	struct btrfs_ordered_extent *ordered;
508 
509 	ordered = container_of(work, struct btrfs_ordered_extent, flush_work);
510 	btrfs_start_ordered_extent(ordered->inode, ordered, 1);
511 	complete(&ordered->completion);
512 }
513 
514 /*
515  * wait for all the ordered extents in a root.  This is done when balancing
516  * space between drives.
517  */
518 u64 btrfs_wait_ordered_extents(struct btrfs_root *root, u64 nr,
519 			       const u64 range_start, const u64 range_len)
520 {
521 	struct btrfs_fs_info *fs_info = root->fs_info;
522 	LIST_HEAD(splice);
523 	LIST_HEAD(skipped);
524 	LIST_HEAD(works);
525 	struct btrfs_ordered_extent *ordered, *next;
526 	u64 count = 0;
527 	const u64 range_end = range_start + range_len;
528 
529 	mutex_lock(&root->ordered_extent_mutex);
530 	spin_lock(&root->ordered_extent_lock);
531 	list_splice_init(&root->ordered_extents, &splice);
532 	while (!list_empty(&splice) && nr) {
533 		ordered = list_first_entry(&splice, struct btrfs_ordered_extent,
534 					   root_extent_list);
535 
536 		if (range_end <= ordered->start ||
537 		    ordered->start + ordered->disk_len <= range_start) {
538 			list_move_tail(&ordered->root_extent_list, &skipped);
539 			cond_resched_lock(&root->ordered_extent_lock);
540 			continue;
541 		}
542 
543 		list_move_tail(&ordered->root_extent_list,
544 			       &root->ordered_extents);
545 		refcount_inc(&ordered->refs);
546 		spin_unlock(&root->ordered_extent_lock);
547 
548 		btrfs_init_work(&ordered->flush_work,
549 				btrfs_flush_delalloc_helper,
550 				btrfs_run_ordered_extent_work, NULL, NULL);
551 		list_add_tail(&ordered->work_list, &works);
552 		btrfs_queue_work(fs_info->flush_workers, &ordered->flush_work);
553 
554 		cond_resched();
555 		spin_lock(&root->ordered_extent_lock);
556 		if (nr != U64_MAX)
557 			nr--;
558 		count++;
559 	}
560 	list_splice_tail(&skipped, &root->ordered_extents);
561 	list_splice_tail(&splice, &root->ordered_extents);
562 	spin_unlock(&root->ordered_extent_lock);
563 
564 	list_for_each_entry_safe(ordered, next, &works, work_list) {
565 		list_del_init(&ordered->work_list);
566 		wait_for_completion(&ordered->completion);
567 		btrfs_put_ordered_extent(ordered);
568 		cond_resched();
569 	}
570 	mutex_unlock(&root->ordered_extent_mutex);
571 
572 	return count;
573 }
574 
575 u64 btrfs_wait_ordered_roots(struct btrfs_fs_info *fs_info, u64 nr,
576 			     const u64 range_start, const u64 range_len)
577 {
578 	struct btrfs_root *root;
579 	struct list_head splice;
580 	u64 total_done = 0;
581 	u64 done;
582 
583 	INIT_LIST_HEAD(&splice);
584 
585 	mutex_lock(&fs_info->ordered_operations_mutex);
586 	spin_lock(&fs_info->ordered_root_lock);
587 	list_splice_init(&fs_info->ordered_roots, &splice);
588 	while (!list_empty(&splice) && nr) {
589 		root = list_first_entry(&splice, struct btrfs_root,
590 					ordered_root);
591 		root = btrfs_grab_fs_root(root);
592 		BUG_ON(!root);
593 		list_move_tail(&root->ordered_root,
594 			       &fs_info->ordered_roots);
595 		spin_unlock(&fs_info->ordered_root_lock);
596 
597 		done = btrfs_wait_ordered_extents(root, nr,
598 						  range_start, range_len);
599 		btrfs_put_fs_root(root);
600 		total_done += done;
601 
602 		spin_lock(&fs_info->ordered_root_lock);
603 		if (nr != U64_MAX) {
604 			nr -= done;
605 		}
606 	}
607 	list_splice_tail(&splice, &fs_info->ordered_roots);
608 	spin_unlock(&fs_info->ordered_root_lock);
609 	mutex_unlock(&fs_info->ordered_operations_mutex);
610 
611 	return total_done;
612 }
613 
614 /*
615  * Used to start IO or wait for a given ordered extent to finish.
616  *
617  * If wait is one, this effectively waits on page writeback for all the pages
618  * in the extent, and it waits on the io completion code to insert
619  * metadata into the btree corresponding to the extent
620  */
621 void btrfs_start_ordered_extent(struct inode *inode,
622 				       struct btrfs_ordered_extent *entry,
623 				       int wait)
624 {
625 	u64 start = entry->file_offset;
626 	u64 end = start + entry->len - 1;
627 
628 	trace_btrfs_ordered_extent_start(inode, entry);
629 
630 	/*
631 	 * pages in the range can be dirty, clean or writeback.  We
632 	 * start IO on any dirty ones so the wait doesn't stall waiting
633 	 * for the flusher thread to find them
634 	 */
635 	if (!test_bit(BTRFS_ORDERED_DIRECT, &entry->flags))
636 		filemap_fdatawrite_range(inode->i_mapping, start, end);
637 	if (wait) {
638 		wait_event(entry->wait, test_bit(BTRFS_ORDERED_COMPLETE,
639 						 &entry->flags));
640 	}
641 }
642 
643 /*
644  * Used to wait on ordered extents across a large range of bytes.
645  */
646 int btrfs_wait_ordered_range(struct inode *inode, u64 start, u64 len)
647 {
648 	int ret = 0;
649 	int ret_wb = 0;
650 	u64 end;
651 	u64 orig_end;
652 	struct btrfs_ordered_extent *ordered;
653 
654 	if (start + len < start) {
655 		orig_end = INT_LIMIT(loff_t);
656 	} else {
657 		orig_end = start + len - 1;
658 		if (orig_end > INT_LIMIT(loff_t))
659 			orig_end = INT_LIMIT(loff_t);
660 	}
661 
662 	/* start IO across the range first to instantiate any delalloc
663 	 * extents
664 	 */
665 	ret = btrfs_fdatawrite_range(inode, start, orig_end);
666 	if (ret)
667 		return ret;
668 
669 	/*
670 	 * If we have a writeback error don't return immediately. Wait first
671 	 * for any ordered extents that haven't completed yet. This is to make
672 	 * sure no one can dirty the same page ranges and call writepages()
673 	 * before the ordered extents complete - to avoid failures (-EEXIST)
674 	 * when adding the new ordered extents to the ordered tree.
675 	 */
676 	ret_wb = filemap_fdatawait_range(inode->i_mapping, start, orig_end);
677 
678 	end = orig_end;
679 	while (1) {
680 		ordered = btrfs_lookup_first_ordered_extent(inode, end);
681 		if (!ordered)
682 			break;
683 		if (ordered->file_offset > orig_end) {
684 			btrfs_put_ordered_extent(ordered);
685 			break;
686 		}
687 		if (ordered->file_offset + ordered->len <= start) {
688 			btrfs_put_ordered_extent(ordered);
689 			break;
690 		}
691 		btrfs_start_ordered_extent(inode, ordered, 1);
692 		end = ordered->file_offset;
693 		if (test_bit(BTRFS_ORDERED_IOERR, &ordered->flags))
694 			ret = -EIO;
695 		btrfs_put_ordered_extent(ordered);
696 		if (ret || end == 0 || end == start)
697 			break;
698 		end--;
699 	}
700 	return ret_wb ? ret_wb : ret;
701 }
702 
703 /*
704  * find an ordered extent corresponding to file_offset.  return NULL if
705  * nothing is found, otherwise take a reference on the extent and return it
706  */
707 struct btrfs_ordered_extent *btrfs_lookup_ordered_extent(struct inode *inode,
708 							 u64 file_offset)
709 {
710 	struct btrfs_ordered_inode_tree *tree;
711 	struct rb_node *node;
712 	struct btrfs_ordered_extent *entry = NULL;
713 
714 	tree = &BTRFS_I(inode)->ordered_tree;
715 	spin_lock_irq(&tree->lock);
716 	node = tree_search(tree, file_offset);
717 	if (!node)
718 		goto out;
719 
720 	entry = rb_entry(node, struct btrfs_ordered_extent, rb_node);
721 	if (!offset_in_entry(entry, file_offset))
722 		entry = NULL;
723 	if (entry)
724 		refcount_inc(&entry->refs);
725 out:
726 	spin_unlock_irq(&tree->lock);
727 	return entry;
728 }
729 
730 /* Since the DIO code tries to lock a wide area we need to look for any ordered
731  * extents that exist in the range, rather than just the start of the range.
732  */
733 struct btrfs_ordered_extent *btrfs_lookup_ordered_range(
734 		struct btrfs_inode *inode, u64 file_offset, u64 len)
735 {
736 	struct btrfs_ordered_inode_tree *tree;
737 	struct rb_node *node;
738 	struct btrfs_ordered_extent *entry = NULL;
739 
740 	tree = &inode->ordered_tree;
741 	spin_lock_irq(&tree->lock);
742 	node = tree_search(tree, file_offset);
743 	if (!node) {
744 		node = tree_search(tree, file_offset + len);
745 		if (!node)
746 			goto out;
747 	}
748 
749 	while (1) {
750 		entry = rb_entry(node, struct btrfs_ordered_extent, rb_node);
751 		if (range_overlaps(entry, file_offset, len))
752 			break;
753 
754 		if (entry->file_offset >= file_offset + len) {
755 			entry = NULL;
756 			break;
757 		}
758 		entry = NULL;
759 		node = rb_next(node);
760 		if (!node)
761 			break;
762 	}
763 out:
764 	if (entry)
765 		refcount_inc(&entry->refs);
766 	spin_unlock_irq(&tree->lock);
767 	return entry;
768 }
769 
770 /*
771  * lookup and return any extent before 'file_offset'.  NULL is returned
772  * if none is found
773  */
774 struct btrfs_ordered_extent *
775 btrfs_lookup_first_ordered_extent(struct inode *inode, u64 file_offset)
776 {
777 	struct btrfs_ordered_inode_tree *tree;
778 	struct rb_node *node;
779 	struct btrfs_ordered_extent *entry = NULL;
780 
781 	tree = &BTRFS_I(inode)->ordered_tree;
782 	spin_lock_irq(&tree->lock);
783 	node = tree_search(tree, file_offset);
784 	if (!node)
785 		goto out;
786 
787 	entry = rb_entry(node, struct btrfs_ordered_extent, rb_node);
788 	refcount_inc(&entry->refs);
789 out:
790 	spin_unlock_irq(&tree->lock);
791 	return entry;
792 }
793 
794 /*
795  * After an extent is done, call this to conditionally update the on disk
796  * i_size.  i_size is updated to cover any fully written part of the file.
797  */
798 int btrfs_ordered_update_i_size(struct inode *inode, u64 offset,
799 				struct btrfs_ordered_extent *ordered)
800 {
801 	struct btrfs_ordered_inode_tree *tree = &BTRFS_I(inode)->ordered_tree;
802 	u64 disk_i_size;
803 	u64 new_i_size;
804 	u64 i_size = i_size_read(inode);
805 	struct rb_node *node;
806 	struct rb_node *prev = NULL;
807 	struct btrfs_ordered_extent *test;
808 	int ret = 1;
809 	u64 orig_offset = offset;
810 
811 	spin_lock_irq(&tree->lock);
812 	if (ordered) {
813 		offset = entry_end(ordered);
814 		if (test_bit(BTRFS_ORDERED_TRUNCATED, &ordered->flags))
815 			offset = min(offset,
816 				     ordered->file_offset +
817 				     ordered->truncated_len);
818 	} else {
819 		offset = ALIGN(offset, btrfs_inode_sectorsize(inode));
820 	}
821 	disk_i_size = BTRFS_I(inode)->disk_i_size;
822 
823 	/*
824 	 * truncate file.
825 	 * If ordered is not NULL, then this is called from endio and
826 	 * disk_i_size will be updated by either truncate itself or any
827 	 * in-flight IOs which are inside the disk_i_size.
828 	 *
829 	 * Because btrfs_setsize() may set i_size with disk_i_size if truncate
830 	 * fails somehow, we need to make sure we have a precise disk_i_size by
831 	 * updating it as usual.
832 	 *
833 	 */
834 	if (!ordered && disk_i_size > i_size) {
835 		BTRFS_I(inode)->disk_i_size = orig_offset;
836 		ret = 0;
837 		goto out;
838 	}
839 
840 	/*
841 	 * if the disk i_size is already at the inode->i_size, or
842 	 * this ordered extent is inside the disk i_size, we're done
843 	 */
844 	if (disk_i_size == i_size)
845 		goto out;
846 
847 	/*
848 	 * We still need to update disk_i_size if outstanding_isize is greater
849 	 * than disk_i_size.
850 	 */
851 	if (offset <= disk_i_size &&
852 	    (!ordered || ordered->outstanding_isize <= disk_i_size))
853 		goto out;
854 
855 	/*
856 	 * walk backward from this ordered extent to disk_i_size.
857 	 * if we find an ordered extent then we can't update disk i_size
858 	 * yet
859 	 */
860 	if (ordered) {
861 		node = rb_prev(&ordered->rb_node);
862 	} else {
863 		prev = tree_search(tree, offset);
864 		/*
865 		 * we insert file extents without involving ordered struct,
866 		 * so there should be no ordered struct cover this offset
867 		 */
868 		if (prev) {
869 			test = rb_entry(prev, struct btrfs_ordered_extent,
870 					rb_node);
871 			BUG_ON(offset_in_entry(test, offset));
872 		}
873 		node = prev;
874 	}
875 	for (; node; node = rb_prev(node)) {
876 		test = rb_entry(node, struct btrfs_ordered_extent, rb_node);
877 
878 		/* We treat this entry as if it doesn't exist */
879 		if (test_bit(BTRFS_ORDERED_UPDATED_ISIZE, &test->flags))
880 			continue;
881 
882 		if (entry_end(test) <= disk_i_size)
883 			break;
884 		if (test->file_offset >= i_size)
885 			break;
886 
887 		/*
888 		 * We don't update disk_i_size now, so record this undealt
889 		 * i_size. Or we will not know the real i_size.
890 		 */
891 		if (test->outstanding_isize < offset)
892 			test->outstanding_isize = offset;
893 		if (ordered &&
894 		    ordered->outstanding_isize > test->outstanding_isize)
895 			test->outstanding_isize = ordered->outstanding_isize;
896 		goto out;
897 	}
898 	new_i_size = min_t(u64, offset, i_size);
899 
900 	/*
901 	 * Some ordered extents may completed before the current one, and
902 	 * we hold the real i_size in ->outstanding_isize.
903 	 */
904 	if (ordered && ordered->outstanding_isize > new_i_size)
905 		new_i_size = min_t(u64, ordered->outstanding_isize, i_size);
906 	BTRFS_I(inode)->disk_i_size = new_i_size;
907 	ret = 0;
908 out:
909 	/*
910 	 * We need to do this because we can't remove ordered extents until
911 	 * after the i_disk_size has been updated and then the inode has been
912 	 * updated to reflect the change, so we need to tell anybody who finds
913 	 * this ordered extent that we've already done all the real work, we
914 	 * just haven't completed all the other work.
915 	 */
916 	if (ordered)
917 		set_bit(BTRFS_ORDERED_UPDATED_ISIZE, &ordered->flags);
918 	spin_unlock_irq(&tree->lock);
919 	return ret;
920 }
921 
922 /*
923  * search the ordered extents for one corresponding to 'offset' and
924  * try to find a checksum.  This is used because we allow pages to
925  * be reclaimed before their checksum is actually put into the btree
926  */
927 int btrfs_find_ordered_sum(struct inode *inode, u64 offset, u64 disk_bytenr,
928 			   u8 *sum, int len)
929 {
930 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
931 	struct btrfs_ordered_sum *ordered_sum;
932 	struct btrfs_ordered_extent *ordered;
933 	struct btrfs_ordered_inode_tree *tree = &BTRFS_I(inode)->ordered_tree;
934 	unsigned long num_sectors;
935 	unsigned long i;
936 	u32 sectorsize = btrfs_inode_sectorsize(inode);
937 	const u16 csum_size = btrfs_super_csum_size(fs_info->super_copy);
938 	int index = 0;
939 
940 	ordered = btrfs_lookup_ordered_extent(inode, offset);
941 	if (!ordered)
942 		return 0;
943 
944 	spin_lock_irq(&tree->lock);
945 	list_for_each_entry_reverse(ordered_sum, &ordered->list, list) {
946 		if (disk_bytenr >= ordered_sum->bytenr &&
947 		    disk_bytenr < ordered_sum->bytenr + ordered_sum->len) {
948 			i = (disk_bytenr - ordered_sum->bytenr) >>
949 			    inode->i_sb->s_blocksize_bits;
950 			num_sectors = ordered_sum->len >>
951 				      inode->i_sb->s_blocksize_bits;
952 			num_sectors = min_t(int, len - index, num_sectors - i);
953 			memcpy(sum + index, ordered_sum->sums + i * csum_size,
954 			       num_sectors * csum_size);
955 
956 			index += (int)num_sectors * csum_size;
957 			if (index == len)
958 				goto out;
959 			disk_bytenr += num_sectors * sectorsize;
960 		}
961 	}
962 out:
963 	spin_unlock_irq(&tree->lock);
964 	btrfs_put_ordered_extent(ordered);
965 	return index;
966 }
967 
968 /*
969  * btrfs_flush_ordered_range - Lock the passed range and ensures all pending
970  * ordered extents in it are run to completion.
971  *
972  * @tree:         IO tree used for locking out other users of the range
973  * @inode:        Inode whose ordered tree is to be searched
974  * @start:        Beginning of range to flush
975  * @end:          Last byte of range to lock
976  * @cached_state: If passed, will return the extent state responsible for the
977  * locked range. It's the caller's responsibility to free the cached state.
978  *
979  * This function always returns with the given range locked, ensuring after it's
980  * called no order extent can be pending.
981  */
982 void btrfs_lock_and_flush_ordered_range(struct extent_io_tree *tree,
983 					struct btrfs_inode *inode, u64 start,
984 					u64 end,
985 					struct extent_state **cached_state)
986 {
987 	struct btrfs_ordered_extent *ordered;
988 	struct extent_state *cache = NULL;
989 	struct extent_state **cachedp = &cache;
990 
991 	if (cached_state)
992 		cachedp = cached_state;
993 
994 	while (1) {
995 		lock_extent_bits(tree, start, end, cachedp);
996 		ordered = btrfs_lookup_ordered_range(inode, start,
997 						     end - start + 1);
998 		if (!ordered) {
999 			/*
1000 			 * If no external cached_state has been passed then
1001 			 * decrement the extra ref taken for cachedp since we
1002 			 * aren't exposing it outside of this function
1003 			 */
1004 			if (!cached_state)
1005 				refcount_dec(&cache->refs);
1006 			break;
1007 		}
1008 		unlock_extent_cached(tree, start, end, cachedp);
1009 		btrfs_start_ordered_extent(&inode->vfs_inode, ordered, 1);
1010 		btrfs_put_ordered_extent(ordered);
1011 	}
1012 }
1013 
1014 int __init ordered_data_init(void)
1015 {
1016 	btrfs_ordered_extent_cache = kmem_cache_create("btrfs_ordered_extent",
1017 				     sizeof(struct btrfs_ordered_extent), 0,
1018 				     SLAB_MEM_SPREAD,
1019 				     NULL);
1020 	if (!btrfs_ordered_extent_cache)
1021 		return -ENOMEM;
1022 
1023 	return 0;
1024 }
1025 
1026 void __cold ordered_data_exit(void)
1027 {
1028 	kmem_cache_destroy(btrfs_ordered_extent_cache);
1029 }
1030