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