xref: /openbmc/linux/fs/btrfs/ordered-data.c (revision 944441d8)
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 "misc.h"
11 #include "ctree.h"
12 #include "transaction.h"
13 #include "btrfs_inode.h"
14 #include "extent_io.h"
15 #include "disk-io.h"
16 #include "compression.h"
17 #include "delalloc-space.h"
18 #include "qgroup.h"
19 #include "subpage.h"
20 
21 static struct kmem_cache *btrfs_ordered_extent_cache;
22 
23 static u64 entry_end(struct btrfs_ordered_extent *entry)
24 {
25 	if (entry->file_offset + entry->num_bytes < entry->file_offset)
26 		return (u64)-1;
27 	return entry->file_offset + entry->num_bytes;
28 }
29 
30 /* returns NULL if the insertion worked, or it returns the node it did find
31  * in the tree
32  */
33 static struct rb_node *tree_insert(struct rb_root *root, u64 file_offset,
34 				   struct rb_node *node)
35 {
36 	struct rb_node **p = &root->rb_node;
37 	struct rb_node *parent = NULL;
38 	struct btrfs_ordered_extent *entry;
39 
40 	while (*p) {
41 		parent = *p;
42 		entry = rb_entry(parent, struct btrfs_ordered_extent, rb_node);
43 
44 		if (file_offset < entry->file_offset)
45 			p = &(*p)->rb_left;
46 		else if (file_offset >= entry_end(entry))
47 			p = &(*p)->rb_right;
48 		else
49 			return parent;
50 	}
51 
52 	rb_link_node(node, parent, p);
53 	rb_insert_color(node, root);
54 	return NULL;
55 }
56 
57 /*
58  * look for a given offset in the tree, and if it can't be found return the
59  * first lesser offset
60  */
61 static struct rb_node *__tree_search(struct rb_root *root, u64 file_offset,
62 				     struct rb_node **prev_ret)
63 {
64 	struct rb_node *n = root->rb_node;
65 	struct rb_node *prev = NULL;
66 	struct rb_node *test;
67 	struct btrfs_ordered_extent *entry;
68 	struct btrfs_ordered_extent *prev_entry = NULL;
69 
70 	while (n) {
71 		entry = rb_entry(n, struct btrfs_ordered_extent, rb_node);
72 		prev = n;
73 		prev_entry = entry;
74 
75 		if (file_offset < entry->file_offset)
76 			n = n->rb_left;
77 		else if (file_offset >= entry_end(entry))
78 			n = n->rb_right;
79 		else
80 			return n;
81 	}
82 	if (!prev_ret)
83 		return NULL;
84 
85 	while (prev && file_offset >= entry_end(prev_entry)) {
86 		test = rb_next(prev);
87 		if (!test)
88 			break;
89 		prev_entry = rb_entry(test, struct btrfs_ordered_extent,
90 				      rb_node);
91 		if (file_offset < entry_end(prev_entry))
92 			break;
93 
94 		prev = test;
95 	}
96 	if (prev)
97 		prev_entry = rb_entry(prev, struct btrfs_ordered_extent,
98 				      rb_node);
99 	while (prev && file_offset < entry_end(prev_entry)) {
100 		test = rb_prev(prev);
101 		if (!test)
102 			break;
103 		prev_entry = rb_entry(test, struct btrfs_ordered_extent,
104 				      rb_node);
105 		prev = test;
106 	}
107 	*prev_ret = prev;
108 	return NULL;
109 }
110 
111 static int range_overlaps(struct btrfs_ordered_extent *entry, u64 file_offset,
112 			  u64 len)
113 {
114 	if (file_offset + len <= entry->file_offset ||
115 	    entry->file_offset + entry->num_bytes <= file_offset)
116 		return 0;
117 	return 1;
118 }
119 
120 /*
121  * look find the first ordered struct that has this offset, otherwise
122  * the first one less than this offset
123  */
124 static inline struct rb_node *tree_search(struct btrfs_ordered_inode_tree *tree,
125 					  u64 file_offset)
126 {
127 	struct rb_root *root = &tree->tree;
128 	struct rb_node *prev = NULL;
129 	struct rb_node *ret;
130 	struct btrfs_ordered_extent *entry;
131 
132 	if (tree->last) {
133 		entry = rb_entry(tree->last, struct btrfs_ordered_extent,
134 				 rb_node);
135 		if (in_range(file_offset, entry->file_offset, entry->num_bytes))
136 			return tree->last;
137 	}
138 	ret = __tree_search(root, file_offset, &prev);
139 	if (!ret)
140 		ret = prev;
141 	if (ret)
142 		tree->last = ret;
143 	return ret;
144 }
145 
146 /**
147  * Add an ordered extent to the per-inode tree.
148  *
149  * @inode:           Inode that this extent is for.
150  * @file_offset:     Logical offset in file where the extent starts.
151  * @num_bytes:       Logical length of extent in file.
152  * @ram_bytes:       Full length of unencoded data.
153  * @disk_bytenr:     Offset of extent on disk.
154  * @disk_num_bytes:  Size of extent on disk.
155  * @offset:          Offset into unencoded data where file data starts.
156  * @flags:           Flags specifying type of extent (1 << BTRFS_ORDERED_*).
157  * @compress_type:   Compression algorithm used for data.
158  *
159  * Most of these parameters correspond to &struct btrfs_file_extent_item. The
160  * tree is given a single reference on the ordered extent that was inserted.
161  *
162  * Return: 0 or -ENOMEM.
163  */
164 int btrfs_add_ordered_extent(struct btrfs_inode *inode, u64 file_offset,
165 			     u64 num_bytes, u64 ram_bytes, u64 disk_bytenr,
166 			     u64 disk_num_bytes, u64 offset, unsigned flags,
167 			     int compress_type)
168 {
169 	struct btrfs_root *root = inode->root;
170 	struct btrfs_fs_info *fs_info = root->fs_info;
171 	struct btrfs_ordered_inode_tree *tree = &inode->ordered_tree;
172 	struct rb_node *node;
173 	struct btrfs_ordered_extent *entry;
174 	int ret;
175 
176 	if (flags &
177 	    ((1 << BTRFS_ORDERED_NOCOW) | (1 << BTRFS_ORDERED_PREALLOC))) {
178 		/* For nocow write, we can release the qgroup rsv right now */
179 		ret = btrfs_qgroup_free_data(inode, NULL, file_offset, num_bytes);
180 		if (ret < 0)
181 			return ret;
182 		ret = 0;
183 	} else {
184 		/*
185 		 * The ordered extent has reserved qgroup space, release now
186 		 * and pass the reserved number for qgroup_record to free.
187 		 */
188 		ret = btrfs_qgroup_release_data(inode, file_offset, num_bytes);
189 		if (ret < 0)
190 			return ret;
191 	}
192 	entry = kmem_cache_zalloc(btrfs_ordered_extent_cache, GFP_NOFS);
193 	if (!entry)
194 		return -ENOMEM;
195 
196 	entry->file_offset = file_offset;
197 	entry->num_bytes = num_bytes;
198 	entry->ram_bytes = ram_bytes;
199 	entry->disk_bytenr = disk_bytenr;
200 	entry->disk_num_bytes = disk_num_bytes;
201 	entry->offset = offset;
202 	entry->bytes_left = num_bytes;
203 	entry->inode = igrab(&inode->vfs_inode);
204 	entry->compress_type = compress_type;
205 	entry->truncated_len = (u64)-1;
206 	entry->qgroup_rsv = ret;
207 	entry->physical = (u64)-1;
208 
209 	ASSERT((flags & ~BTRFS_ORDERED_TYPE_FLAGS) == 0);
210 	entry->flags = flags;
211 
212 	percpu_counter_add_batch(&fs_info->ordered_bytes, num_bytes,
213 				 fs_info->delalloc_batch);
214 
215 	/* one ref for the tree */
216 	refcount_set(&entry->refs, 1);
217 	init_waitqueue_head(&entry->wait);
218 	INIT_LIST_HEAD(&entry->list);
219 	INIT_LIST_HEAD(&entry->log_list);
220 	INIT_LIST_HEAD(&entry->root_extent_list);
221 	INIT_LIST_HEAD(&entry->work_list);
222 	init_completion(&entry->completion);
223 
224 	trace_btrfs_ordered_extent_add(inode, entry);
225 
226 	spin_lock_irq(&tree->lock);
227 	node = tree_insert(&tree->tree, file_offset,
228 			   &entry->rb_node);
229 	if (node)
230 		btrfs_panic(fs_info, -EEXIST,
231 				"inconsistency in ordered tree at offset %llu",
232 				file_offset);
233 	spin_unlock_irq(&tree->lock);
234 
235 	spin_lock(&root->ordered_extent_lock);
236 	list_add_tail(&entry->root_extent_list,
237 		      &root->ordered_extents);
238 	root->nr_ordered_extents++;
239 	if (root->nr_ordered_extents == 1) {
240 		spin_lock(&fs_info->ordered_root_lock);
241 		BUG_ON(!list_empty(&root->ordered_root));
242 		list_add_tail(&root->ordered_root, &fs_info->ordered_roots);
243 		spin_unlock(&fs_info->ordered_root_lock);
244 	}
245 	spin_unlock(&root->ordered_extent_lock);
246 
247 	/*
248 	 * We don't need the count_max_extents here, we can assume that all of
249 	 * that work has been done at higher layers, so this is truly the
250 	 * smallest the extent is going to get.
251 	 */
252 	spin_lock(&inode->lock);
253 	btrfs_mod_outstanding_extents(inode, 1);
254 	spin_unlock(&inode->lock);
255 
256 	return 0;
257 }
258 
259 /*
260  * Add a struct btrfs_ordered_sum into the list of checksums to be inserted
261  * when an ordered extent is finished.  If the list covers more than one
262  * ordered extent, it is split across multiples.
263  */
264 void btrfs_add_ordered_sum(struct btrfs_ordered_extent *entry,
265 			   struct btrfs_ordered_sum *sum)
266 {
267 	struct btrfs_ordered_inode_tree *tree;
268 
269 	tree = &BTRFS_I(entry->inode)->ordered_tree;
270 	spin_lock_irq(&tree->lock);
271 	list_add_tail(&sum->list, &entry->list);
272 	spin_unlock_irq(&tree->lock);
273 }
274 
275 static void finish_ordered_fn(struct btrfs_work *work)
276 {
277 	struct btrfs_ordered_extent *ordered_extent;
278 
279 	ordered_extent = container_of(work, struct btrfs_ordered_extent, work);
280 	btrfs_finish_ordered_io(ordered_extent);
281 }
282 
283 /*
284  * Mark all ordered extents io inside the specified range finished.
285  *
286  * @page:	 The involved page for the operation.
287  *		 For uncompressed buffered IO, the page status also needs to be
288  *		 updated to indicate whether the pending ordered io is finished.
289  *		 Can be NULL for direct IO and compressed write.
290  *		 For these cases, callers are ensured they won't execute the
291  *		 endio function twice.
292  *
293  * This function is called for endio, thus the range must have ordered
294  * extent(s) covering it.
295  */
296 void btrfs_mark_ordered_io_finished(struct btrfs_inode *inode,
297 				    struct page *page, u64 file_offset,
298 				    u64 num_bytes, bool uptodate)
299 {
300 	struct btrfs_ordered_inode_tree *tree = &inode->ordered_tree;
301 	struct btrfs_fs_info *fs_info = inode->root->fs_info;
302 	struct btrfs_workqueue *wq;
303 	struct rb_node *node;
304 	struct btrfs_ordered_extent *entry = NULL;
305 	unsigned long flags;
306 	u64 cur = file_offset;
307 
308 	if (btrfs_is_free_space_inode(inode))
309 		wq = fs_info->endio_freespace_worker;
310 	else
311 		wq = fs_info->endio_write_workers;
312 
313 	if (page)
314 		ASSERT(page->mapping && page_offset(page) <= file_offset &&
315 		       file_offset + num_bytes <= page_offset(page) + PAGE_SIZE);
316 
317 	spin_lock_irqsave(&tree->lock, flags);
318 	while (cur < file_offset + num_bytes) {
319 		u64 entry_end;
320 		u64 end;
321 		u32 len;
322 
323 		node = tree_search(tree, cur);
324 		/* No ordered extents at all */
325 		if (!node)
326 			break;
327 
328 		entry = rb_entry(node, struct btrfs_ordered_extent, rb_node);
329 		entry_end = entry->file_offset + entry->num_bytes;
330 		/*
331 		 * |<-- OE --->|  |
332 		 *		  cur
333 		 * Go to next OE.
334 		 */
335 		if (cur >= entry_end) {
336 			node = rb_next(node);
337 			/* No more ordered extents, exit */
338 			if (!node)
339 				break;
340 			entry = rb_entry(node, struct btrfs_ordered_extent,
341 					 rb_node);
342 
343 			/* Go to next ordered extent and continue */
344 			cur = entry->file_offset;
345 			continue;
346 		}
347 		/*
348 		 * |	|<--- OE --->|
349 		 * cur
350 		 * Go to the start of OE.
351 		 */
352 		if (cur < entry->file_offset) {
353 			cur = entry->file_offset;
354 			continue;
355 		}
356 
357 		/*
358 		 * Now we are definitely inside one ordered extent.
359 		 *
360 		 * |<--- OE --->|
361 		 *	|
362 		 *	cur
363 		 */
364 		end = min(entry->file_offset + entry->num_bytes,
365 			  file_offset + num_bytes) - 1;
366 		ASSERT(end + 1 - cur < U32_MAX);
367 		len = end + 1 - cur;
368 
369 		if (page) {
370 			/*
371 			 * Ordered (Private2) bit indicates whether we still
372 			 * have pending io unfinished for the ordered extent.
373 			 *
374 			 * If there's no such bit, we need to skip to next range.
375 			 */
376 			if (!btrfs_page_test_ordered(fs_info, page, cur, len)) {
377 				cur += len;
378 				continue;
379 			}
380 			btrfs_page_clear_ordered(fs_info, page, cur, len);
381 		}
382 
383 		/* Now we're fine to update the accounting */
384 		if (unlikely(len > entry->bytes_left)) {
385 			WARN_ON(1);
386 			btrfs_crit(fs_info,
387 "bad ordered extent accounting, root=%llu ino=%llu OE offset=%llu OE len=%llu to_dec=%u left=%llu",
388 				   inode->root->root_key.objectid,
389 				   btrfs_ino(inode),
390 				   entry->file_offset,
391 				   entry->num_bytes,
392 				   len, entry->bytes_left);
393 			entry->bytes_left = 0;
394 		} else {
395 			entry->bytes_left -= len;
396 		}
397 
398 		if (!uptodate)
399 			set_bit(BTRFS_ORDERED_IOERR, &entry->flags);
400 
401 		/*
402 		 * All the IO of the ordered extent is finished, we need to queue
403 		 * the finish_func to be executed.
404 		 */
405 		if (entry->bytes_left == 0) {
406 			set_bit(BTRFS_ORDERED_IO_DONE, &entry->flags);
407 			cond_wake_up(&entry->wait);
408 			refcount_inc(&entry->refs);
409 			trace_btrfs_ordered_extent_mark_finished(inode, entry);
410 			spin_unlock_irqrestore(&tree->lock, flags);
411 			btrfs_init_work(&entry->work, finish_ordered_fn, NULL, NULL);
412 			btrfs_queue_work(wq, &entry->work);
413 			spin_lock_irqsave(&tree->lock, flags);
414 		}
415 		cur += len;
416 	}
417 	spin_unlock_irqrestore(&tree->lock, flags);
418 }
419 
420 /*
421  * Finish IO for one ordered extent across a given range.  The range can only
422  * contain one ordered extent.
423  *
424  * @cached:	 The cached ordered extent. If not NULL, we can skip the tree
425  *               search and use the ordered extent directly.
426  * 		 Will be also used to store the finished ordered extent.
427  * @file_offset: File offset for the finished IO
428  * @io_size:	 Length of the finish IO range
429  *
430  * Return true if the ordered extent is finished in the range, and update
431  * @cached.
432  * Return false otherwise.
433  *
434  * NOTE: The range can NOT cross multiple ordered extents.
435  * Thus caller should ensure the range doesn't cross ordered extents.
436  */
437 bool btrfs_dec_test_ordered_pending(struct btrfs_inode *inode,
438 				    struct btrfs_ordered_extent **cached,
439 				    u64 file_offset, u64 io_size)
440 {
441 	struct btrfs_ordered_inode_tree *tree = &inode->ordered_tree;
442 	struct rb_node *node;
443 	struct btrfs_ordered_extent *entry = NULL;
444 	unsigned long flags;
445 	bool finished = false;
446 
447 	spin_lock_irqsave(&tree->lock, flags);
448 	if (cached && *cached) {
449 		entry = *cached;
450 		goto have_entry;
451 	}
452 
453 	node = tree_search(tree, file_offset);
454 	if (!node)
455 		goto out;
456 
457 	entry = rb_entry(node, struct btrfs_ordered_extent, rb_node);
458 have_entry:
459 	if (!in_range(file_offset, entry->file_offset, entry->num_bytes))
460 		goto out;
461 
462 	if (io_size > entry->bytes_left)
463 		btrfs_crit(inode->root->fs_info,
464 			   "bad ordered accounting left %llu size %llu",
465 		       entry->bytes_left, io_size);
466 
467 	entry->bytes_left -= io_size;
468 
469 	if (entry->bytes_left == 0) {
470 		/*
471 		 * Ensure only one caller can set the flag and finished_ret
472 		 * accordingly
473 		 */
474 		finished = !test_and_set_bit(BTRFS_ORDERED_IO_DONE, &entry->flags);
475 		/* test_and_set_bit implies a barrier */
476 		cond_wake_up_nomb(&entry->wait);
477 	}
478 out:
479 	if (finished && cached && entry) {
480 		*cached = entry;
481 		refcount_inc(&entry->refs);
482 		trace_btrfs_ordered_extent_dec_test_pending(inode, entry);
483 	}
484 	spin_unlock_irqrestore(&tree->lock, flags);
485 	return finished;
486 }
487 
488 /*
489  * used to drop a reference on an ordered extent.  This will free
490  * the extent if the last reference is dropped
491  */
492 void btrfs_put_ordered_extent(struct btrfs_ordered_extent *entry)
493 {
494 	struct list_head *cur;
495 	struct btrfs_ordered_sum *sum;
496 
497 	trace_btrfs_ordered_extent_put(BTRFS_I(entry->inode), entry);
498 
499 	if (refcount_dec_and_test(&entry->refs)) {
500 		ASSERT(list_empty(&entry->root_extent_list));
501 		ASSERT(list_empty(&entry->log_list));
502 		ASSERT(RB_EMPTY_NODE(&entry->rb_node));
503 		if (entry->inode)
504 			btrfs_add_delayed_iput(entry->inode);
505 		while (!list_empty(&entry->list)) {
506 			cur = entry->list.next;
507 			sum = list_entry(cur, struct btrfs_ordered_sum, list);
508 			list_del(&sum->list);
509 			kvfree(sum);
510 		}
511 		kmem_cache_free(btrfs_ordered_extent_cache, entry);
512 	}
513 }
514 
515 /*
516  * remove an ordered extent from the tree.  No references are dropped
517  * and waiters are woken up.
518  */
519 void btrfs_remove_ordered_extent(struct btrfs_inode *btrfs_inode,
520 				 struct btrfs_ordered_extent *entry)
521 {
522 	struct btrfs_ordered_inode_tree *tree;
523 	struct btrfs_root *root = btrfs_inode->root;
524 	struct btrfs_fs_info *fs_info = root->fs_info;
525 	struct rb_node *node;
526 	bool pending;
527 
528 	/* This is paired with btrfs_add_ordered_extent. */
529 	spin_lock(&btrfs_inode->lock);
530 	btrfs_mod_outstanding_extents(btrfs_inode, -1);
531 	spin_unlock(&btrfs_inode->lock);
532 	if (root != fs_info->tree_root) {
533 		u64 release;
534 
535 		if (test_bit(BTRFS_ORDERED_ENCODED, &entry->flags))
536 			release = entry->disk_num_bytes;
537 		else
538 			release = entry->num_bytes;
539 		btrfs_delalloc_release_metadata(btrfs_inode, release, false);
540 	}
541 
542 	percpu_counter_add_batch(&fs_info->ordered_bytes, -entry->num_bytes,
543 				 fs_info->delalloc_batch);
544 
545 	tree = &btrfs_inode->ordered_tree;
546 	spin_lock_irq(&tree->lock);
547 	node = &entry->rb_node;
548 	rb_erase(node, &tree->tree);
549 	RB_CLEAR_NODE(node);
550 	if (tree->last == node)
551 		tree->last = NULL;
552 	set_bit(BTRFS_ORDERED_COMPLETE, &entry->flags);
553 	pending = test_and_clear_bit(BTRFS_ORDERED_PENDING, &entry->flags);
554 	spin_unlock_irq(&tree->lock);
555 
556 	/*
557 	 * The current running transaction is waiting on us, we need to let it
558 	 * know that we're complete and wake it up.
559 	 */
560 	if (pending) {
561 		struct btrfs_transaction *trans;
562 
563 		/*
564 		 * The checks for trans are just a formality, it should be set,
565 		 * but if it isn't we don't want to deref/assert under the spin
566 		 * lock, so be nice and check if trans is set, but ASSERT() so
567 		 * if it isn't set a developer will notice.
568 		 */
569 		spin_lock(&fs_info->trans_lock);
570 		trans = fs_info->running_transaction;
571 		if (trans)
572 			refcount_inc(&trans->use_count);
573 		spin_unlock(&fs_info->trans_lock);
574 
575 		ASSERT(trans);
576 		if (trans) {
577 			if (atomic_dec_and_test(&trans->pending_ordered))
578 				wake_up(&trans->pending_wait);
579 			btrfs_put_transaction(trans);
580 		}
581 	}
582 
583 	spin_lock(&root->ordered_extent_lock);
584 	list_del_init(&entry->root_extent_list);
585 	root->nr_ordered_extents--;
586 
587 	trace_btrfs_ordered_extent_remove(btrfs_inode, entry);
588 
589 	if (!root->nr_ordered_extents) {
590 		spin_lock(&fs_info->ordered_root_lock);
591 		BUG_ON(list_empty(&root->ordered_root));
592 		list_del_init(&root->ordered_root);
593 		spin_unlock(&fs_info->ordered_root_lock);
594 	}
595 	spin_unlock(&root->ordered_extent_lock);
596 	wake_up(&entry->wait);
597 }
598 
599 static void btrfs_run_ordered_extent_work(struct btrfs_work *work)
600 {
601 	struct btrfs_ordered_extent *ordered;
602 
603 	ordered = container_of(work, struct btrfs_ordered_extent, flush_work);
604 	btrfs_start_ordered_extent(ordered, 1);
605 	complete(&ordered->completion);
606 }
607 
608 /*
609  * wait for all the ordered extents in a root.  This is done when balancing
610  * space between drives.
611  */
612 u64 btrfs_wait_ordered_extents(struct btrfs_root *root, u64 nr,
613 			       const u64 range_start, const u64 range_len)
614 {
615 	struct btrfs_fs_info *fs_info = root->fs_info;
616 	LIST_HEAD(splice);
617 	LIST_HEAD(skipped);
618 	LIST_HEAD(works);
619 	struct btrfs_ordered_extent *ordered, *next;
620 	u64 count = 0;
621 	const u64 range_end = range_start + range_len;
622 
623 	mutex_lock(&root->ordered_extent_mutex);
624 	spin_lock(&root->ordered_extent_lock);
625 	list_splice_init(&root->ordered_extents, &splice);
626 	while (!list_empty(&splice) && nr) {
627 		ordered = list_first_entry(&splice, struct btrfs_ordered_extent,
628 					   root_extent_list);
629 
630 		if (range_end <= ordered->disk_bytenr ||
631 		    ordered->disk_bytenr + ordered->disk_num_bytes <= range_start) {
632 			list_move_tail(&ordered->root_extent_list, &skipped);
633 			cond_resched_lock(&root->ordered_extent_lock);
634 			continue;
635 		}
636 
637 		list_move_tail(&ordered->root_extent_list,
638 			       &root->ordered_extents);
639 		refcount_inc(&ordered->refs);
640 		spin_unlock(&root->ordered_extent_lock);
641 
642 		btrfs_init_work(&ordered->flush_work,
643 				btrfs_run_ordered_extent_work, NULL, NULL);
644 		list_add_tail(&ordered->work_list, &works);
645 		btrfs_queue_work(fs_info->flush_workers, &ordered->flush_work);
646 
647 		cond_resched();
648 		spin_lock(&root->ordered_extent_lock);
649 		if (nr != U64_MAX)
650 			nr--;
651 		count++;
652 	}
653 	list_splice_tail(&skipped, &root->ordered_extents);
654 	list_splice_tail(&splice, &root->ordered_extents);
655 	spin_unlock(&root->ordered_extent_lock);
656 
657 	list_for_each_entry_safe(ordered, next, &works, work_list) {
658 		list_del_init(&ordered->work_list);
659 		wait_for_completion(&ordered->completion);
660 		btrfs_put_ordered_extent(ordered);
661 		cond_resched();
662 	}
663 	mutex_unlock(&root->ordered_extent_mutex);
664 
665 	return count;
666 }
667 
668 void btrfs_wait_ordered_roots(struct btrfs_fs_info *fs_info, u64 nr,
669 			     const u64 range_start, const u64 range_len)
670 {
671 	struct btrfs_root *root;
672 	struct list_head splice;
673 	u64 done;
674 
675 	INIT_LIST_HEAD(&splice);
676 
677 	mutex_lock(&fs_info->ordered_operations_mutex);
678 	spin_lock(&fs_info->ordered_root_lock);
679 	list_splice_init(&fs_info->ordered_roots, &splice);
680 	while (!list_empty(&splice) && nr) {
681 		root = list_first_entry(&splice, struct btrfs_root,
682 					ordered_root);
683 		root = btrfs_grab_root(root);
684 		BUG_ON(!root);
685 		list_move_tail(&root->ordered_root,
686 			       &fs_info->ordered_roots);
687 		spin_unlock(&fs_info->ordered_root_lock);
688 
689 		done = btrfs_wait_ordered_extents(root, nr,
690 						  range_start, range_len);
691 		btrfs_put_root(root);
692 
693 		spin_lock(&fs_info->ordered_root_lock);
694 		if (nr != U64_MAX) {
695 			nr -= done;
696 		}
697 	}
698 	list_splice_tail(&splice, &fs_info->ordered_roots);
699 	spin_unlock(&fs_info->ordered_root_lock);
700 	mutex_unlock(&fs_info->ordered_operations_mutex);
701 }
702 
703 /*
704  * Used to start IO or wait for a given ordered extent to finish.
705  *
706  * If wait is one, this effectively waits on page writeback for all the pages
707  * in the extent, and it waits on the io completion code to insert
708  * metadata into the btree corresponding to the extent
709  */
710 void btrfs_start_ordered_extent(struct btrfs_ordered_extent *entry, int wait)
711 {
712 	u64 start = entry->file_offset;
713 	u64 end = start + entry->num_bytes - 1;
714 	struct btrfs_inode *inode = BTRFS_I(entry->inode);
715 
716 	trace_btrfs_ordered_extent_start(inode, entry);
717 
718 	/*
719 	 * pages in the range can be dirty, clean or writeback.  We
720 	 * start IO on any dirty ones so the wait doesn't stall waiting
721 	 * for the flusher thread to find them
722 	 */
723 	if (!test_bit(BTRFS_ORDERED_DIRECT, &entry->flags))
724 		filemap_fdatawrite_range(inode->vfs_inode.i_mapping, start, end);
725 	if (wait) {
726 		wait_event(entry->wait, test_bit(BTRFS_ORDERED_COMPLETE,
727 						 &entry->flags));
728 	}
729 }
730 
731 /*
732  * Used to wait on ordered extents across a large range of bytes.
733  */
734 int btrfs_wait_ordered_range(struct inode *inode, u64 start, u64 len)
735 {
736 	int ret = 0;
737 	int ret_wb = 0;
738 	u64 end;
739 	u64 orig_end;
740 	struct btrfs_ordered_extent *ordered;
741 
742 	if (start + len < start) {
743 		orig_end = INT_LIMIT(loff_t);
744 	} else {
745 		orig_end = start + len - 1;
746 		if (orig_end > INT_LIMIT(loff_t))
747 			orig_end = INT_LIMIT(loff_t);
748 	}
749 
750 	/* start IO across the range first to instantiate any delalloc
751 	 * extents
752 	 */
753 	ret = btrfs_fdatawrite_range(inode, start, orig_end);
754 	if (ret)
755 		return ret;
756 
757 	/*
758 	 * If we have a writeback error don't return immediately. Wait first
759 	 * for any ordered extents that haven't completed yet. This is to make
760 	 * sure no one can dirty the same page ranges and call writepages()
761 	 * before the ordered extents complete - to avoid failures (-EEXIST)
762 	 * when adding the new ordered extents to the ordered tree.
763 	 */
764 	ret_wb = filemap_fdatawait_range(inode->i_mapping, start, orig_end);
765 
766 	end = orig_end;
767 	while (1) {
768 		ordered = btrfs_lookup_first_ordered_extent(BTRFS_I(inode), end);
769 		if (!ordered)
770 			break;
771 		if (ordered->file_offset > orig_end) {
772 			btrfs_put_ordered_extent(ordered);
773 			break;
774 		}
775 		if (ordered->file_offset + ordered->num_bytes <= start) {
776 			btrfs_put_ordered_extent(ordered);
777 			break;
778 		}
779 		btrfs_start_ordered_extent(ordered, 1);
780 		end = ordered->file_offset;
781 		/*
782 		 * If the ordered extent had an error save the error but don't
783 		 * exit without waiting first for all other ordered extents in
784 		 * the range to complete.
785 		 */
786 		if (test_bit(BTRFS_ORDERED_IOERR, &ordered->flags))
787 			ret = -EIO;
788 		btrfs_put_ordered_extent(ordered);
789 		if (end == 0 || end == start)
790 			break;
791 		end--;
792 	}
793 	return ret_wb ? ret_wb : ret;
794 }
795 
796 /*
797  * find an ordered extent corresponding to file_offset.  return NULL if
798  * nothing is found, otherwise take a reference on the extent and return it
799  */
800 struct btrfs_ordered_extent *btrfs_lookup_ordered_extent(struct btrfs_inode *inode,
801 							 u64 file_offset)
802 {
803 	struct btrfs_ordered_inode_tree *tree;
804 	struct rb_node *node;
805 	struct btrfs_ordered_extent *entry = NULL;
806 	unsigned long flags;
807 
808 	tree = &inode->ordered_tree;
809 	spin_lock_irqsave(&tree->lock, flags);
810 	node = tree_search(tree, file_offset);
811 	if (!node)
812 		goto out;
813 
814 	entry = rb_entry(node, struct btrfs_ordered_extent, rb_node);
815 	if (!in_range(file_offset, entry->file_offset, entry->num_bytes))
816 		entry = NULL;
817 	if (entry) {
818 		refcount_inc(&entry->refs);
819 		trace_btrfs_ordered_extent_lookup(inode, entry);
820 	}
821 out:
822 	spin_unlock_irqrestore(&tree->lock, flags);
823 	return entry;
824 }
825 
826 /* Since the DIO code tries to lock a wide area we need to look for any ordered
827  * extents that exist in the range, rather than just the start of the range.
828  */
829 struct btrfs_ordered_extent *btrfs_lookup_ordered_range(
830 		struct btrfs_inode *inode, u64 file_offset, u64 len)
831 {
832 	struct btrfs_ordered_inode_tree *tree;
833 	struct rb_node *node;
834 	struct btrfs_ordered_extent *entry = NULL;
835 
836 	tree = &inode->ordered_tree;
837 	spin_lock_irq(&tree->lock);
838 	node = tree_search(tree, file_offset);
839 	if (!node) {
840 		node = tree_search(tree, file_offset + len);
841 		if (!node)
842 			goto out;
843 	}
844 
845 	while (1) {
846 		entry = rb_entry(node, struct btrfs_ordered_extent, rb_node);
847 		if (range_overlaps(entry, file_offset, len))
848 			break;
849 
850 		if (entry->file_offset >= file_offset + len) {
851 			entry = NULL;
852 			break;
853 		}
854 		entry = NULL;
855 		node = rb_next(node);
856 		if (!node)
857 			break;
858 	}
859 out:
860 	if (entry) {
861 		refcount_inc(&entry->refs);
862 		trace_btrfs_ordered_extent_lookup_range(inode, entry);
863 	}
864 	spin_unlock_irq(&tree->lock);
865 	return entry;
866 }
867 
868 /*
869  * Adds all ordered extents to the given list. The list ends up sorted by the
870  * file_offset of the ordered extents.
871  */
872 void btrfs_get_ordered_extents_for_logging(struct btrfs_inode *inode,
873 					   struct list_head *list)
874 {
875 	struct btrfs_ordered_inode_tree *tree = &inode->ordered_tree;
876 	struct rb_node *n;
877 
878 	ASSERT(inode_is_locked(&inode->vfs_inode));
879 
880 	spin_lock_irq(&tree->lock);
881 	for (n = rb_first(&tree->tree); n; n = rb_next(n)) {
882 		struct btrfs_ordered_extent *ordered;
883 
884 		ordered = rb_entry(n, struct btrfs_ordered_extent, rb_node);
885 
886 		if (test_bit(BTRFS_ORDERED_LOGGED, &ordered->flags))
887 			continue;
888 
889 		ASSERT(list_empty(&ordered->log_list));
890 		list_add_tail(&ordered->log_list, list);
891 		refcount_inc(&ordered->refs);
892 		trace_btrfs_ordered_extent_lookup_for_logging(inode, ordered);
893 	}
894 	spin_unlock_irq(&tree->lock);
895 }
896 
897 /*
898  * lookup and return any extent before 'file_offset'.  NULL is returned
899  * if none is found
900  */
901 struct btrfs_ordered_extent *
902 btrfs_lookup_first_ordered_extent(struct btrfs_inode *inode, u64 file_offset)
903 {
904 	struct btrfs_ordered_inode_tree *tree;
905 	struct rb_node *node;
906 	struct btrfs_ordered_extent *entry = NULL;
907 
908 	tree = &inode->ordered_tree;
909 	spin_lock_irq(&tree->lock);
910 	node = tree_search(tree, file_offset);
911 	if (!node)
912 		goto out;
913 
914 	entry = rb_entry(node, struct btrfs_ordered_extent, rb_node);
915 	refcount_inc(&entry->refs);
916 	trace_btrfs_ordered_extent_lookup_first(inode, entry);
917 out:
918 	spin_unlock_irq(&tree->lock);
919 	return entry;
920 }
921 
922 /*
923  * Lookup the first ordered extent that overlaps the range
924  * [@file_offset, @file_offset + @len).
925  *
926  * The difference between this and btrfs_lookup_first_ordered_extent() is
927  * that this one won't return any ordered extent that does not overlap the range.
928  * And the difference against btrfs_lookup_ordered_extent() is, this function
929  * ensures the first ordered extent gets returned.
930  */
931 struct btrfs_ordered_extent *btrfs_lookup_first_ordered_range(
932 			struct btrfs_inode *inode, u64 file_offset, u64 len)
933 {
934 	struct btrfs_ordered_inode_tree *tree = &inode->ordered_tree;
935 	struct rb_node *node;
936 	struct rb_node *cur;
937 	struct rb_node *prev;
938 	struct rb_node *next;
939 	struct btrfs_ordered_extent *entry = NULL;
940 
941 	spin_lock_irq(&tree->lock);
942 	node = tree->tree.rb_node;
943 	/*
944 	 * Here we don't want to use tree_search() which will use tree->last
945 	 * and screw up the search order.
946 	 * And __tree_search() can't return the adjacent ordered extents
947 	 * either, thus here we do our own search.
948 	 */
949 	while (node) {
950 		entry = rb_entry(node, struct btrfs_ordered_extent, rb_node);
951 
952 		if (file_offset < entry->file_offset) {
953 			node = node->rb_left;
954 		} else if (file_offset >= entry_end(entry)) {
955 			node = node->rb_right;
956 		} else {
957 			/*
958 			 * Direct hit, got an ordered extent that starts at
959 			 * @file_offset
960 			 */
961 			goto out;
962 		}
963 	}
964 	if (!entry) {
965 		/* Empty tree */
966 		goto out;
967 	}
968 
969 	cur = &entry->rb_node;
970 	/* We got an entry around @file_offset, check adjacent entries */
971 	if (entry->file_offset < file_offset) {
972 		prev = cur;
973 		next = rb_next(cur);
974 	} else {
975 		prev = rb_prev(cur);
976 		next = cur;
977 	}
978 	if (prev) {
979 		entry = rb_entry(prev, struct btrfs_ordered_extent, rb_node);
980 		if (range_overlaps(entry, file_offset, len))
981 			goto out;
982 	}
983 	if (next) {
984 		entry = rb_entry(next, struct btrfs_ordered_extent, rb_node);
985 		if (range_overlaps(entry, file_offset, len))
986 			goto out;
987 	}
988 	/* No ordered extent in the range */
989 	entry = NULL;
990 out:
991 	if (entry) {
992 		refcount_inc(&entry->refs);
993 		trace_btrfs_ordered_extent_lookup_first_range(inode, entry);
994 	}
995 
996 	spin_unlock_irq(&tree->lock);
997 	return entry;
998 }
999 
1000 /*
1001  * btrfs_flush_ordered_range - Lock the passed range and ensures all pending
1002  * ordered extents in it are run to completion.
1003  *
1004  * @inode:        Inode whose ordered tree is to be searched
1005  * @start:        Beginning of range to flush
1006  * @end:          Last byte of range to lock
1007  * @cached_state: If passed, will return the extent state responsible for the
1008  * locked range. It's the caller's responsibility to free the cached state.
1009  *
1010  * This function always returns with the given range locked, ensuring after it's
1011  * called no order extent can be pending.
1012  */
1013 void btrfs_lock_and_flush_ordered_range(struct btrfs_inode *inode, u64 start,
1014 					u64 end,
1015 					struct extent_state **cached_state)
1016 {
1017 	struct btrfs_ordered_extent *ordered;
1018 	struct extent_state *cache = NULL;
1019 	struct extent_state **cachedp = &cache;
1020 
1021 	if (cached_state)
1022 		cachedp = cached_state;
1023 
1024 	while (1) {
1025 		lock_extent_bits(&inode->io_tree, start, end, cachedp);
1026 		ordered = btrfs_lookup_ordered_range(inode, start,
1027 						     end - start + 1);
1028 		if (!ordered) {
1029 			/*
1030 			 * If no external cached_state has been passed then
1031 			 * decrement the extra ref taken for cachedp since we
1032 			 * aren't exposing it outside of this function
1033 			 */
1034 			if (!cached_state)
1035 				refcount_dec(&cache->refs);
1036 			break;
1037 		}
1038 		unlock_extent_cached(&inode->io_tree, start, end, cachedp);
1039 		btrfs_start_ordered_extent(ordered, 1);
1040 		btrfs_put_ordered_extent(ordered);
1041 	}
1042 }
1043 
1044 static int clone_ordered_extent(struct btrfs_ordered_extent *ordered, u64 pos,
1045 				u64 len)
1046 {
1047 	struct inode *inode = ordered->inode;
1048 	struct btrfs_fs_info *fs_info = BTRFS_I(inode)->root->fs_info;
1049 	u64 file_offset = ordered->file_offset + pos;
1050 	u64 disk_bytenr = ordered->disk_bytenr + pos;
1051 	unsigned long flags = ordered->flags & BTRFS_ORDERED_TYPE_FLAGS;
1052 
1053 	/*
1054 	 * The splitting extent is already counted and will be added again in
1055 	 * btrfs_add_ordered_extent_*(). Subtract len to avoid double counting.
1056 	 */
1057 	percpu_counter_add_batch(&fs_info->ordered_bytes, -len,
1058 				 fs_info->delalloc_batch);
1059 	WARN_ON_ONCE(flags & (1 << BTRFS_ORDERED_COMPRESSED));
1060 	return btrfs_add_ordered_extent(BTRFS_I(inode), file_offset, len, len,
1061 					disk_bytenr, len, 0, flags,
1062 					ordered->compress_type);
1063 }
1064 
1065 int btrfs_split_ordered_extent(struct btrfs_ordered_extent *ordered, u64 pre,
1066 				u64 post)
1067 {
1068 	struct inode *inode = ordered->inode;
1069 	struct btrfs_ordered_inode_tree *tree = &BTRFS_I(inode)->ordered_tree;
1070 	struct rb_node *node;
1071 	struct btrfs_fs_info *fs_info = btrfs_sb(inode->i_sb);
1072 	int ret = 0;
1073 
1074 	trace_btrfs_ordered_extent_split(BTRFS_I(inode), ordered);
1075 
1076 	spin_lock_irq(&tree->lock);
1077 	/* Remove from tree once */
1078 	node = &ordered->rb_node;
1079 	rb_erase(node, &tree->tree);
1080 	RB_CLEAR_NODE(node);
1081 	if (tree->last == node)
1082 		tree->last = NULL;
1083 
1084 	ordered->file_offset += pre;
1085 	ordered->disk_bytenr += pre;
1086 	ordered->num_bytes -= (pre + post);
1087 	ordered->disk_num_bytes -= (pre + post);
1088 	ordered->bytes_left -= (pre + post);
1089 
1090 	/* Re-insert the node */
1091 	node = tree_insert(&tree->tree, ordered->file_offset, &ordered->rb_node);
1092 	if (node)
1093 		btrfs_panic(fs_info, -EEXIST,
1094 			"zoned: inconsistency in ordered tree at offset %llu",
1095 			    ordered->file_offset);
1096 
1097 	spin_unlock_irq(&tree->lock);
1098 
1099 	if (pre)
1100 		ret = clone_ordered_extent(ordered, 0, pre);
1101 	if (ret == 0 && post)
1102 		ret = clone_ordered_extent(ordered, pre + ordered->disk_num_bytes,
1103 					   post);
1104 
1105 	return ret;
1106 }
1107 
1108 int __init ordered_data_init(void)
1109 {
1110 	btrfs_ordered_extent_cache = kmem_cache_create("btrfs_ordered_extent",
1111 				     sizeof(struct btrfs_ordered_extent), 0,
1112 				     SLAB_MEM_SPREAD,
1113 				     NULL);
1114 	if (!btrfs_ordered_extent_cache)
1115 		return -ENOMEM;
1116 
1117 	return 0;
1118 }
1119 
1120 void __cold ordered_data_exit(void)
1121 {
1122 	kmem_cache_destroy(btrfs_ordered_extent_cache);
1123 }
1124