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