d5d326c674b1a77e3894eb944677307b04879ad7
[platform/kernel/linux-rpi.git] / fs / btrfs / ordered-data.c
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
20 static struct kmem_cache *btrfs_ordered_extent_cache;
21
22 static u64 entry_end(struct btrfs_ordered_extent *entry)
23 {
24         if (entry->file_offset + entry->num_bytes < entry->file_offset)
25                 return (u64)-1;
26         return entry->file_offset + entry->num_bytes;
27 }
28
29 /* returns NULL if the insertion worked, or it returns the node it did find
30  * in the tree
31  */
32 static struct rb_node *tree_insert(struct rb_root *root, u64 file_offset,
33                                    struct rb_node *node)
34 {
35         struct rb_node **p = &root->rb_node;
36         struct rb_node *parent = NULL;
37         struct btrfs_ordered_extent *entry;
38
39         while (*p) {
40                 parent = *p;
41                 entry = rb_entry(parent, struct btrfs_ordered_extent, rb_node);
42
43                 if (file_offset < entry->file_offset)
44                         p = &(*p)->rb_left;
45                 else if (file_offset >= entry_end(entry))
46                         p = &(*p)->rb_right;
47                 else
48                         return parent;
49         }
50
51         rb_link_node(node, parent, p);
52         rb_insert_color(node, root);
53         return NULL;
54 }
55
56 /*
57  * look for a given offset in the tree, and if it can't be found return the
58  * first lesser offset
59  */
60 static struct rb_node *__tree_search(struct rb_root *root, u64 file_offset,
61                                      struct rb_node **prev_ret)
62 {
63         struct rb_node *n = root->rb_node;
64         struct rb_node *prev = NULL;
65         struct rb_node *test;
66         struct btrfs_ordered_extent *entry;
67         struct btrfs_ordered_extent *prev_entry = NULL;
68
69         while (n) {
70                 entry = rb_entry(n, struct btrfs_ordered_extent, rb_node);
71                 prev = n;
72                 prev_entry = entry;
73
74                 if (file_offset < entry->file_offset)
75                         n = n->rb_left;
76                 else if (file_offset >= entry_end(entry))
77                         n = n->rb_right;
78                 else
79                         return n;
80         }
81         if (!prev_ret)
82                 return NULL;
83
84         while (prev && file_offset >= entry_end(prev_entry)) {
85                 test = rb_next(prev);
86                 if (!test)
87                         break;
88                 prev_entry = rb_entry(test, struct btrfs_ordered_extent,
89                                       rb_node);
90                 if (file_offset < entry_end(prev_entry))
91                         break;
92
93                 prev = test;
94         }
95         if (prev)
96                 prev_entry = rb_entry(prev, struct btrfs_ordered_extent,
97                                       rb_node);
98         while (prev && file_offset < entry_end(prev_entry)) {
99                 test = rb_prev(prev);
100                 if (!test)
101                         break;
102                 prev_entry = rb_entry(test, struct btrfs_ordered_extent,
103                                       rb_node);
104                 prev = test;
105         }
106         *prev_ret = prev;
107         return NULL;
108 }
109
110 /*
111  * helper to check if a given offset is inside a given entry
112  */
113 static int offset_in_entry(struct btrfs_ordered_extent *entry, u64 file_offset)
114 {
115         if (file_offset < entry->file_offset ||
116             entry->file_offset + entry->num_bytes <= file_offset)
117                 return 0;
118         return 1;
119 }
120
121 static int range_overlaps(struct btrfs_ordered_extent *entry, u64 file_offset,
122                           u64 len)
123 {
124         if (file_offset + len <= entry->file_offset ||
125             entry->file_offset + entry->num_bytes <= file_offset)
126                 return 0;
127         return 1;
128 }
129
130 /*
131  * look find the first ordered struct that has this offset, otherwise
132  * the first one less than this offset
133  */
134 static inline struct rb_node *tree_search(struct btrfs_ordered_inode_tree *tree,
135                                           u64 file_offset)
136 {
137         struct rb_root *root = &tree->tree;
138         struct rb_node *prev = NULL;
139         struct rb_node *ret;
140         struct btrfs_ordered_extent *entry;
141
142         if (tree->last) {
143                 entry = rb_entry(tree->last, struct btrfs_ordered_extent,
144                                  rb_node);
145                 if (offset_in_entry(entry, file_offset))
146                         return tree->last;
147         }
148         ret = __tree_search(root, file_offset, &prev);
149         if (!ret)
150                 ret = prev;
151         if (ret)
152                 tree->last = ret;
153         return ret;
154 }
155
156 /*
157  * Allocate and add a new ordered_extent into the per-inode tree.
158  *
159  * The tree is given a single reference on the ordered extent that was
160  * inserted.
161  */
162 static int __btrfs_add_ordered_extent(struct btrfs_inode *inode, u64 file_offset,
163                                       u64 disk_bytenr, u64 num_bytes,
164                                       u64 disk_num_bytes, int type, int dio,
165                                       int compress_type)
166 {
167         struct btrfs_root *root = inode->root;
168         struct btrfs_fs_info *fs_info = root->fs_info;
169         struct btrfs_ordered_inode_tree *tree = &inode->ordered_tree;
170         struct rb_node *node;
171         struct btrfs_ordered_extent *entry;
172         int ret;
173
174         if (type == BTRFS_ORDERED_NOCOW || type == BTRFS_ORDERED_PREALLOC) {
175                 /* For nocow write, we can release the qgroup rsv right now */
176                 ret = btrfs_qgroup_free_data(inode, NULL, file_offset, num_bytes);
177                 if (ret < 0)
178                         return ret;
179                 ret = 0;
180         } else {
181                 /*
182                  * The ordered extent has reserved qgroup space, release now
183                  * and pass the reserved number for qgroup_record to free.
184                  */
185                 ret = btrfs_qgroup_release_data(inode, file_offset, num_bytes);
186                 if (ret < 0)
187                         return ret;
188         }
189         entry = kmem_cache_zalloc(btrfs_ordered_extent_cache, GFP_NOFS);
190         if (!entry)
191                 return -ENOMEM;
192
193         entry->file_offset = file_offset;
194         entry->disk_bytenr = disk_bytenr;
195         entry->num_bytes = num_bytes;
196         entry->disk_num_bytes = disk_num_bytes;
197         entry->bytes_left = num_bytes;
198         entry->inode = igrab(&inode->vfs_inode);
199         entry->compress_type = compress_type;
200         entry->truncated_len = (u64)-1;
201         entry->qgroup_rsv = ret;
202         if (type != BTRFS_ORDERED_IO_DONE && type != BTRFS_ORDERED_COMPLETE)
203                 set_bit(type, &entry->flags);
204
205         if (dio) {
206                 percpu_counter_add_batch(&fs_info->dio_bytes, num_bytes,
207                                          fs_info->delalloc_batch);
208                 set_bit(BTRFS_ORDERED_DIRECT, &entry->flags);
209         }
210
211         /* one ref for the tree */
212         refcount_set(&entry->refs, 1);
213         init_waitqueue_head(&entry->wait);
214         INIT_LIST_HEAD(&entry->list);
215         INIT_LIST_HEAD(&entry->log_list);
216         INIT_LIST_HEAD(&entry->root_extent_list);
217         INIT_LIST_HEAD(&entry->work_list);
218         init_completion(&entry->completion);
219
220         trace_btrfs_ordered_extent_add(inode, entry);
221
222         spin_lock_irq(&tree->lock);
223         node = tree_insert(&tree->tree, file_offset,
224                            &entry->rb_node);
225         if (node)
226                 btrfs_panic(fs_info, -EEXIST,
227                                 "inconsistency in ordered tree at offset %llu",
228                                 file_offset);
229         spin_unlock_irq(&tree->lock);
230
231         spin_lock(&root->ordered_extent_lock);
232         list_add_tail(&entry->root_extent_list,
233                       &root->ordered_extents);
234         root->nr_ordered_extents++;
235         if (root->nr_ordered_extents == 1) {
236                 spin_lock(&fs_info->ordered_root_lock);
237                 BUG_ON(!list_empty(&root->ordered_root));
238                 list_add_tail(&root->ordered_root, &fs_info->ordered_roots);
239                 spin_unlock(&fs_info->ordered_root_lock);
240         }
241         spin_unlock(&root->ordered_extent_lock);
242
243         /*
244          * We don't need the count_max_extents here, we can assume that all of
245          * that work has been done at higher layers, so this is truly the
246          * smallest the extent is going to get.
247          */
248         spin_lock(&inode->lock);
249         btrfs_mod_outstanding_extents(inode, 1);
250         spin_unlock(&inode->lock);
251
252         return 0;
253 }
254
255 int btrfs_add_ordered_extent(struct btrfs_inode *inode, u64 file_offset,
256                              u64 disk_bytenr, u64 num_bytes, u64 disk_num_bytes,
257                              int type)
258 {
259         return __btrfs_add_ordered_extent(inode, file_offset, disk_bytenr,
260                                           num_bytes, disk_num_bytes, type, 0,
261                                           BTRFS_COMPRESS_NONE);
262 }
263
264 int btrfs_add_ordered_extent_dio(struct btrfs_inode *inode, u64 file_offset,
265                                  u64 disk_bytenr, u64 num_bytes,
266                                  u64 disk_num_bytes, int type)
267 {
268         return __btrfs_add_ordered_extent(inode, file_offset, disk_bytenr,
269                                           num_bytes, disk_num_bytes, type, 1,
270                                           BTRFS_COMPRESS_NONE);
271 }
272
273 int btrfs_add_ordered_extent_compress(struct btrfs_inode *inode, u64 file_offset,
274                                       u64 disk_bytenr, u64 num_bytes,
275                                       u64 disk_num_bytes, int type,
276                                       int compress_type)
277 {
278         return __btrfs_add_ordered_extent(inode, file_offset, disk_bytenr,
279                                           num_bytes, disk_num_bytes, type, 0,
280                                           compress_type);
281 }
282
283 /*
284  * Add a struct btrfs_ordered_sum into the list of checksums to be inserted
285  * when an ordered extent is finished.  If the list covers more than one
286  * ordered extent, it is split across multiples.
287  */
288 void btrfs_add_ordered_sum(struct btrfs_ordered_extent *entry,
289                            struct btrfs_ordered_sum *sum)
290 {
291         struct btrfs_ordered_inode_tree *tree;
292
293         tree = &BTRFS_I(entry->inode)->ordered_tree;
294         spin_lock_irq(&tree->lock);
295         list_add_tail(&sum->list, &entry->list);
296         spin_unlock_irq(&tree->lock);
297 }
298
299 /*
300  * Finish IO for one ordered extent across a given range.  The range can
301  * contain several ordered extents.
302  *
303  * @found_ret:   Return the finished ordered extent
304  * @file_offset: File offset for the finished IO
305  *               Will also be updated to one byte past the range that is
306  *               recordered as finished. This allows caller to walk forward.
307  * @io_size:     Length of the finish IO range
308  * @uptodate:    If the IO finished without problem
309  *
310  * Return true if any ordered extent is finished in the range, and update
311  * @found_ret and @file_offset.
312  * Return false otherwise.
313  *
314  * NOTE: Although The range can cross multiple ordered extents, only one
315  * ordered extent will be updated during one call. The caller is responsible to
316  * iterate all ordered extents in the range.
317  */
318 bool btrfs_dec_test_first_ordered_pending(struct btrfs_inode *inode,
319                                    struct btrfs_ordered_extent **finished_ret,
320                                    u64 *file_offset, u64 io_size, int uptodate)
321 {
322         struct btrfs_fs_info *fs_info = inode->root->fs_info;
323         struct btrfs_ordered_inode_tree *tree = &inode->ordered_tree;
324         struct rb_node *node;
325         struct btrfs_ordered_extent *entry = NULL;
326         bool finished = false;
327         unsigned long flags;
328         u64 dec_end;
329         u64 dec_start;
330         u64 to_dec;
331
332         spin_lock_irqsave(&tree->lock, flags);
333         node = tree_search(tree, *file_offset);
334         if (!node)
335                 goto out;
336
337         entry = rb_entry(node, struct btrfs_ordered_extent, rb_node);
338         if (!offset_in_entry(entry, *file_offset))
339                 goto out;
340
341         dec_start = max(*file_offset, entry->file_offset);
342         dec_end = min(*file_offset + io_size,
343                       entry->file_offset + entry->num_bytes);
344         *file_offset = dec_end;
345         if (dec_start > dec_end) {
346                 btrfs_crit(fs_info, "bad ordering dec_start %llu end %llu",
347                            dec_start, dec_end);
348         }
349         to_dec = dec_end - dec_start;
350         if (to_dec > entry->bytes_left) {
351                 btrfs_crit(fs_info,
352                            "bad ordered accounting left %llu size %llu",
353                            entry->bytes_left, to_dec);
354         }
355         entry->bytes_left -= to_dec;
356         if (!uptodate)
357                 set_bit(BTRFS_ORDERED_IOERR, &entry->flags);
358
359         if (entry->bytes_left == 0) {
360                 /*
361                  * Ensure only one caller can set the flag and finished_ret
362                  * accordingly
363                  */
364                 finished = !test_and_set_bit(BTRFS_ORDERED_IO_DONE, &entry->flags);
365                 /* test_and_set_bit implies a barrier */
366                 cond_wake_up_nomb(&entry->wait);
367         }
368 out:
369         if (finished && finished_ret && entry) {
370                 *finished_ret = entry;
371                 refcount_inc(&entry->refs);
372         }
373         spin_unlock_irqrestore(&tree->lock, flags);
374         return finished;
375 }
376
377 /*
378  * Finish IO for one ordered extent across a given range.  The range can only
379  * contain one ordered extent.
380  *
381  * @cached:      The cached ordered extent. If not NULL, we can skip the tree
382  *               search and use the ordered extent directly.
383  *               Will be also used to store the finished ordered extent.
384  * @file_offset: File offset for the finished IO
385  * @io_size:     Length of the finish IO range
386  * @uptodate:    If the IO finishes without problem
387  *
388  * Return true if the ordered extent is finished in the range, and update
389  * @cached.
390  * Return false otherwise.
391  *
392  * NOTE: The range can NOT cross multiple ordered extents.
393  * Thus caller should ensure the range doesn't cross ordered extents.
394  */
395 bool btrfs_dec_test_ordered_pending(struct btrfs_inode *inode,
396                                     struct btrfs_ordered_extent **cached,
397                                     u64 file_offset, u64 io_size, int uptodate)
398 {
399         struct btrfs_ordered_inode_tree *tree = &inode->ordered_tree;
400         struct rb_node *node;
401         struct btrfs_ordered_extent *entry = NULL;
402         unsigned long flags;
403         bool finished = false;
404
405         spin_lock_irqsave(&tree->lock, flags);
406         if (cached && *cached) {
407                 entry = *cached;
408                 goto have_entry;
409         }
410
411         node = tree_search(tree, file_offset);
412         if (!node)
413                 goto out;
414
415         entry = rb_entry(node, struct btrfs_ordered_extent, rb_node);
416 have_entry:
417         if (!offset_in_entry(entry, file_offset))
418                 goto out;
419
420         if (io_size > entry->bytes_left)
421                 btrfs_crit(inode->root->fs_info,
422                            "bad ordered accounting left %llu size %llu",
423                        entry->bytes_left, io_size);
424
425         entry->bytes_left -= io_size;
426         if (!uptodate)
427                 set_bit(BTRFS_ORDERED_IOERR, &entry->flags);
428
429         if (entry->bytes_left == 0) {
430                 /*
431                  * Ensure only one caller can set the flag and finished_ret
432                  * accordingly
433                  */
434                 finished = !test_and_set_bit(BTRFS_ORDERED_IO_DONE, &entry->flags);
435                 /* test_and_set_bit implies a barrier */
436                 cond_wake_up_nomb(&entry->wait);
437         }
438 out:
439         if (finished && cached && entry) {
440                 *cached = entry;
441                 refcount_inc(&entry->refs);
442         }
443         spin_unlock_irqrestore(&tree->lock, flags);
444         return finished;
445 }
446
447 /*
448  * used to drop a reference on an ordered extent.  This will free
449  * the extent if the last reference is dropped
450  */
451 void btrfs_put_ordered_extent(struct btrfs_ordered_extent *entry)
452 {
453         struct list_head *cur;
454         struct btrfs_ordered_sum *sum;
455
456         trace_btrfs_ordered_extent_put(BTRFS_I(entry->inode), entry);
457
458         if (refcount_dec_and_test(&entry->refs)) {
459                 ASSERT(list_empty(&entry->root_extent_list));
460                 ASSERT(list_empty(&entry->log_list));
461                 ASSERT(RB_EMPTY_NODE(&entry->rb_node));
462                 if (entry->inode)
463                         btrfs_add_delayed_iput(entry->inode);
464                 while (!list_empty(&entry->list)) {
465                         cur = entry->list.next;
466                         sum = list_entry(cur, struct btrfs_ordered_sum, list);
467                         list_del(&sum->list);
468                         kvfree(sum);
469                 }
470                 kmem_cache_free(btrfs_ordered_extent_cache, entry);
471         }
472 }
473
474 /*
475  * remove an ordered extent from the tree.  No references are dropped
476  * and waiters are woken up.
477  */
478 void btrfs_remove_ordered_extent(struct btrfs_inode *btrfs_inode,
479                                  struct btrfs_ordered_extent *entry)
480 {
481         struct btrfs_ordered_inode_tree *tree;
482         struct btrfs_root *root = btrfs_inode->root;
483         struct btrfs_fs_info *fs_info = root->fs_info;
484         struct rb_node *node;
485         bool pending;
486
487         /* This is paired with btrfs_add_ordered_extent. */
488         spin_lock(&btrfs_inode->lock);
489         btrfs_mod_outstanding_extents(btrfs_inode, -1);
490         spin_unlock(&btrfs_inode->lock);
491         if (root != fs_info->tree_root)
492                 btrfs_delalloc_release_metadata(btrfs_inode, entry->num_bytes,
493                                                 false);
494
495         if (test_bit(BTRFS_ORDERED_DIRECT, &entry->flags))
496                 percpu_counter_add_batch(&fs_info->dio_bytes, -entry->num_bytes,
497                                          fs_info->delalloc_batch);
498
499         tree = &btrfs_inode->ordered_tree;
500         spin_lock_irq(&tree->lock);
501         node = &entry->rb_node;
502         rb_erase(node, &tree->tree);
503         RB_CLEAR_NODE(node);
504         if (tree->last == node)
505                 tree->last = NULL;
506         set_bit(BTRFS_ORDERED_COMPLETE, &entry->flags);
507         pending = test_and_clear_bit(BTRFS_ORDERED_PENDING, &entry->flags);
508         spin_unlock_irq(&tree->lock);
509
510         /*
511          * The current running transaction is waiting on us, we need to let it
512          * know that we're complete and wake it up.
513          */
514         if (pending) {
515                 struct btrfs_transaction *trans;
516
517                 /*
518                  * The checks for trans are just a formality, it should be set,
519                  * but if it isn't we don't want to deref/assert under the spin
520                  * lock, so be nice and check if trans is set, but ASSERT() so
521                  * if it isn't set a developer will notice.
522                  */
523                 spin_lock(&fs_info->trans_lock);
524                 trans = fs_info->running_transaction;
525                 if (trans)
526                         refcount_inc(&trans->use_count);
527                 spin_unlock(&fs_info->trans_lock);
528
529                 ASSERT(trans);
530                 if (trans) {
531                         if (atomic_dec_and_test(&trans->pending_ordered))
532                                 wake_up(&trans->pending_wait);
533                         btrfs_put_transaction(trans);
534                 }
535         }
536
537         spin_lock(&root->ordered_extent_lock);
538         list_del_init(&entry->root_extent_list);
539         root->nr_ordered_extents--;
540
541         trace_btrfs_ordered_extent_remove(btrfs_inode, entry);
542
543         if (!root->nr_ordered_extents) {
544                 spin_lock(&fs_info->ordered_root_lock);
545                 BUG_ON(list_empty(&root->ordered_root));
546                 list_del_init(&root->ordered_root);
547                 spin_unlock(&fs_info->ordered_root_lock);
548         }
549         spin_unlock(&root->ordered_extent_lock);
550         wake_up(&entry->wait);
551 }
552
553 static void btrfs_run_ordered_extent_work(struct btrfs_work *work)
554 {
555         struct btrfs_ordered_extent *ordered;
556
557         ordered = container_of(work, struct btrfs_ordered_extent, flush_work);
558         btrfs_start_ordered_extent(ordered, 1);
559         complete(&ordered->completion);
560 }
561
562 /*
563  * wait for all the ordered extents in a root.  This is done when balancing
564  * space between drives.
565  */
566 u64 btrfs_wait_ordered_extents(struct btrfs_root *root, u64 nr,
567                                const u64 range_start, const u64 range_len)
568 {
569         struct btrfs_fs_info *fs_info = root->fs_info;
570         LIST_HEAD(splice);
571         LIST_HEAD(skipped);
572         LIST_HEAD(works);
573         struct btrfs_ordered_extent *ordered, *next;
574         u64 count = 0;
575         const u64 range_end = range_start + range_len;
576
577         mutex_lock(&root->ordered_extent_mutex);
578         spin_lock(&root->ordered_extent_lock);
579         list_splice_init(&root->ordered_extents, &splice);
580         while (!list_empty(&splice) && nr) {
581                 ordered = list_first_entry(&splice, struct btrfs_ordered_extent,
582                                            root_extent_list);
583
584                 if (range_end <= ordered->disk_bytenr ||
585                     ordered->disk_bytenr + ordered->disk_num_bytes <= range_start) {
586                         list_move_tail(&ordered->root_extent_list, &skipped);
587                         cond_resched_lock(&root->ordered_extent_lock);
588                         continue;
589                 }
590
591                 list_move_tail(&ordered->root_extent_list,
592                                &root->ordered_extents);
593                 refcount_inc(&ordered->refs);
594                 spin_unlock(&root->ordered_extent_lock);
595
596                 btrfs_init_work(&ordered->flush_work,
597                                 btrfs_run_ordered_extent_work, NULL, NULL);
598                 list_add_tail(&ordered->work_list, &works);
599                 btrfs_queue_work(fs_info->flush_workers, &ordered->flush_work);
600
601                 cond_resched();
602                 spin_lock(&root->ordered_extent_lock);
603                 if (nr != U64_MAX)
604                         nr--;
605                 count++;
606         }
607         list_splice_tail(&skipped, &root->ordered_extents);
608         list_splice_tail(&splice, &root->ordered_extents);
609         spin_unlock(&root->ordered_extent_lock);
610
611         list_for_each_entry_safe(ordered, next, &works, work_list) {
612                 list_del_init(&ordered->work_list);
613                 wait_for_completion(&ordered->completion);
614                 btrfs_put_ordered_extent(ordered);
615                 cond_resched();
616         }
617         mutex_unlock(&root->ordered_extent_mutex);
618
619         return count;
620 }
621
622 void btrfs_wait_ordered_roots(struct btrfs_fs_info *fs_info, u64 nr,
623                              const u64 range_start, const u64 range_len)
624 {
625         struct btrfs_root *root;
626         struct list_head splice;
627         u64 done;
628
629         INIT_LIST_HEAD(&splice);
630
631         mutex_lock(&fs_info->ordered_operations_mutex);
632         spin_lock(&fs_info->ordered_root_lock);
633         list_splice_init(&fs_info->ordered_roots, &splice);
634         while (!list_empty(&splice) && nr) {
635                 root = list_first_entry(&splice, struct btrfs_root,
636                                         ordered_root);
637                 root = btrfs_grab_root(root);
638                 BUG_ON(!root);
639                 list_move_tail(&root->ordered_root,
640                                &fs_info->ordered_roots);
641                 spin_unlock(&fs_info->ordered_root_lock);
642
643                 done = btrfs_wait_ordered_extents(root, nr,
644                                                   range_start, range_len);
645                 btrfs_put_root(root);
646
647                 spin_lock(&fs_info->ordered_root_lock);
648                 if (nr != U64_MAX) {
649                         nr -= done;
650                 }
651         }
652         list_splice_tail(&splice, &fs_info->ordered_roots);
653         spin_unlock(&fs_info->ordered_root_lock);
654         mutex_unlock(&fs_info->ordered_operations_mutex);
655 }
656
657 /*
658  * Used to start IO or wait for a given ordered extent to finish.
659  *
660  * If wait is one, this effectively waits on page writeback for all the pages
661  * in the extent, and it waits on the io completion code to insert
662  * metadata into the btree corresponding to the extent
663  */
664 void btrfs_start_ordered_extent(struct btrfs_ordered_extent *entry, int wait)
665 {
666         u64 start = entry->file_offset;
667         u64 end = start + entry->num_bytes - 1;
668         struct btrfs_inode *inode = BTRFS_I(entry->inode);
669
670         trace_btrfs_ordered_extent_start(inode, entry);
671
672         /*
673          * pages in the range can be dirty, clean or writeback.  We
674          * start IO on any dirty ones so the wait doesn't stall waiting
675          * for the flusher thread to find them
676          */
677         if (!test_bit(BTRFS_ORDERED_DIRECT, &entry->flags))
678                 filemap_fdatawrite_range(inode->vfs_inode.i_mapping, start, end);
679         if (wait) {
680                 wait_event(entry->wait, test_bit(BTRFS_ORDERED_COMPLETE,
681                                                  &entry->flags));
682         }
683 }
684
685 /*
686  * Used to wait on ordered extents across a large range of bytes.
687  */
688 int btrfs_wait_ordered_range(struct inode *inode, u64 start, u64 len)
689 {
690         int ret = 0;
691         int ret_wb = 0;
692         u64 end;
693         u64 orig_end;
694         struct btrfs_ordered_extent *ordered;
695
696         if (start + len < start) {
697                 orig_end = INT_LIMIT(loff_t);
698         } else {
699                 orig_end = start + len - 1;
700                 if (orig_end > INT_LIMIT(loff_t))
701                         orig_end = INT_LIMIT(loff_t);
702         }
703
704         /* start IO across the range first to instantiate any delalloc
705          * extents
706          */
707         ret = btrfs_fdatawrite_range(inode, start, orig_end);
708         if (ret)
709                 return ret;
710
711         /*
712          * If we have a writeback error don't return immediately. Wait first
713          * for any ordered extents that haven't completed yet. This is to make
714          * sure no one can dirty the same page ranges and call writepages()
715          * before the ordered extents complete - to avoid failures (-EEXIST)
716          * when adding the new ordered extents to the ordered tree.
717          */
718         ret_wb = filemap_fdatawait_range(inode->i_mapping, start, orig_end);
719
720         end = orig_end;
721         while (1) {
722                 ordered = btrfs_lookup_first_ordered_extent(BTRFS_I(inode), end);
723                 if (!ordered)
724                         break;
725                 if (ordered->file_offset > orig_end) {
726                         btrfs_put_ordered_extent(ordered);
727                         break;
728                 }
729                 if (ordered->file_offset + ordered->num_bytes <= start) {
730                         btrfs_put_ordered_extent(ordered);
731                         break;
732                 }
733                 btrfs_start_ordered_extent(ordered, 1);
734                 end = ordered->file_offset;
735                 /*
736                  * If the ordered extent had an error save the error but don't
737                  * exit without waiting first for all other ordered extents in
738                  * the range to complete.
739                  */
740                 if (test_bit(BTRFS_ORDERED_IOERR, &ordered->flags))
741                         ret = -EIO;
742                 btrfs_put_ordered_extent(ordered);
743                 if (end == 0 || end == start)
744                         break;
745                 end--;
746         }
747         return ret_wb ? ret_wb : ret;
748 }
749
750 /*
751  * find an ordered extent corresponding to file_offset.  return NULL if
752  * nothing is found, otherwise take a reference on the extent and return it
753  */
754 struct btrfs_ordered_extent *btrfs_lookup_ordered_extent(struct btrfs_inode *inode,
755                                                          u64 file_offset)
756 {
757         struct btrfs_ordered_inode_tree *tree;
758         struct rb_node *node;
759         struct btrfs_ordered_extent *entry = NULL;
760
761         tree = &inode->ordered_tree;
762         spin_lock_irq(&tree->lock);
763         node = tree_search(tree, file_offset);
764         if (!node)
765                 goto out;
766
767         entry = rb_entry(node, struct btrfs_ordered_extent, rb_node);
768         if (!offset_in_entry(entry, file_offset))
769                 entry = NULL;
770         if (entry)
771                 refcount_inc(&entry->refs);
772 out:
773         spin_unlock_irq(&tree->lock);
774         return entry;
775 }
776
777 /* Since the DIO code tries to lock a wide area we need to look for any ordered
778  * extents that exist in the range, rather than just the start of the range.
779  */
780 struct btrfs_ordered_extent *btrfs_lookup_ordered_range(
781                 struct btrfs_inode *inode, u64 file_offset, u64 len)
782 {
783         struct btrfs_ordered_inode_tree *tree;
784         struct rb_node *node;
785         struct btrfs_ordered_extent *entry = NULL;
786
787         tree = &inode->ordered_tree;
788         spin_lock_irq(&tree->lock);
789         node = tree_search(tree, file_offset);
790         if (!node) {
791                 node = tree_search(tree, file_offset + len);
792                 if (!node)
793                         goto out;
794         }
795
796         while (1) {
797                 entry = rb_entry(node, struct btrfs_ordered_extent, rb_node);
798                 if (range_overlaps(entry, file_offset, len))
799                         break;
800
801                 if (entry->file_offset >= file_offset + len) {
802                         entry = NULL;
803                         break;
804                 }
805                 entry = NULL;
806                 node = rb_next(node);
807                 if (!node)
808                         break;
809         }
810 out:
811         if (entry)
812                 refcount_inc(&entry->refs);
813         spin_unlock_irq(&tree->lock);
814         return entry;
815 }
816
817 /*
818  * Adds all ordered extents to the given list. The list ends up sorted by the
819  * file_offset of the ordered extents.
820  */
821 void btrfs_get_ordered_extents_for_logging(struct btrfs_inode *inode,
822                                            struct list_head *list)
823 {
824         struct btrfs_ordered_inode_tree *tree = &inode->ordered_tree;
825         struct rb_node *n;
826
827         ASSERT(inode_is_locked(&inode->vfs_inode));
828
829         spin_lock_irq(&tree->lock);
830         for (n = rb_first(&tree->tree); n; n = rb_next(n)) {
831                 struct btrfs_ordered_extent *ordered;
832
833                 ordered = rb_entry(n, struct btrfs_ordered_extent, rb_node);
834
835                 if (test_bit(BTRFS_ORDERED_LOGGED, &ordered->flags))
836                         continue;
837
838                 ASSERT(list_empty(&ordered->log_list));
839                 list_add_tail(&ordered->log_list, list);
840                 refcount_inc(&ordered->refs);
841         }
842         spin_unlock_irq(&tree->lock);
843 }
844
845 /*
846  * lookup and return any extent before 'file_offset'.  NULL is returned
847  * if none is found
848  */
849 struct btrfs_ordered_extent *
850 btrfs_lookup_first_ordered_extent(struct btrfs_inode *inode, u64 file_offset)
851 {
852         struct btrfs_ordered_inode_tree *tree;
853         struct rb_node *node;
854         struct btrfs_ordered_extent *entry = NULL;
855
856         tree = &inode->ordered_tree;
857         spin_lock_irq(&tree->lock);
858         node = tree_search(tree, file_offset);
859         if (!node)
860                 goto out;
861
862         entry = rb_entry(node, struct btrfs_ordered_extent, rb_node);
863         refcount_inc(&entry->refs);
864 out:
865         spin_unlock_irq(&tree->lock);
866         return entry;
867 }
868
869 /*
870  * btrfs_flush_ordered_range - Lock the passed range and ensures all pending
871  * ordered extents in it are run to completion.
872  *
873  * @inode:        Inode whose ordered tree is to be searched
874  * @start:        Beginning of range to flush
875  * @end:          Last byte of range to lock
876  * @cached_state: If passed, will return the extent state responsible for the
877  * locked range. It's the caller's responsibility to free the cached state.
878  *
879  * This function always returns with the given range locked, ensuring after it's
880  * called no order extent can be pending.
881  */
882 void btrfs_lock_and_flush_ordered_range(struct btrfs_inode *inode, u64 start,
883                                         u64 end,
884                                         struct extent_state **cached_state)
885 {
886         struct btrfs_ordered_extent *ordered;
887         struct extent_state *cache = NULL;
888         struct extent_state **cachedp = &cache;
889
890         if (cached_state)
891                 cachedp = cached_state;
892
893         while (1) {
894                 lock_extent_bits(&inode->io_tree, start, end, cachedp);
895                 ordered = btrfs_lookup_ordered_range(inode, start,
896                                                      end - start + 1);
897                 if (!ordered) {
898                         /*
899                          * If no external cached_state has been passed then
900                          * decrement the extra ref taken for cachedp since we
901                          * aren't exposing it outside of this function
902                          */
903                         if (!cached_state)
904                                 refcount_dec(&cache->refs);
905                         break;
906                 }
907                 unlock_extent_cached(&inode->io_tree, start, end, cachedp);
908                 btrfs_start_ordered_extent(ordered, 1);
909                 btrfs_put_ordered_extent(ordered);
910         }
911 }
912
913 int __init ordered_data_init(void)
914 {
915         btrfs_ordered_extent_cache = kmem_cache_create("btrfs_ordered_extent",
916                                      sizeof(struct btrfs_ordered_extent), 0,
917                                      SLAB_MEM_SPREAD,
918                                      NULL);
919         if (!btrfs_ordered_extent_cache)
920                 return -ENOMEM;
921
922         return 0;
923 }
924
925 void __cold ordered_data_exit(void)
926 {
927         kmem_cache_destroy(btrfs_ordered_extent_cache);
928 }