]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/alloc_background.c
Update bcachefs sources to ef60854e99 bcachefs: More allocator startup improvements
[bcachefs-tools-debian] / libbcachefs / alloc_background.c
1 #include "bcachefs.h"
2 #include "alloc_background.h"
3 #include "alloc_foreground.h"
4 #include "btree_cache.h"
5 #include "btree_io.h"
6 #include "btree_update.h"
7 #include "btree_update_interior.h"
8 #include "btree_gc.h"
9 #include "buckets.h"
10 #include "clock.h"
11 #include "debug.h"
12 #include "ec.h"
13 #include "error.h"
14 #include "journal_io.h"
15
16 #include <linux/kthread.h>
17 #include <linux/math64.h>
18 #include <linux/random.h>
19 #include <linux/rculist.h>
20 #include <linux/rcupdate.h>
21 #include <linux/sched/task.h>
22 #include <linux/sort.h>
23 #include <trace/events/bcachefs.h>
24
25 static const char * const bch2_alloc_field_names[] = {
26 #define x(name, bytes) #name,
27         BCH_ALLOC_FIELDS()
28 #undef x
29         NULL
30 };
31
32 static void bch2_recalc_oldest_io(struct bch_fs *, struct bch_dev *, int);
33
34 /* Ratelimiting/PD controllers */
35
36 static void pd_controllers_update(struct work_struct *work)
37 {
38         struct bch_fs *c = container_of(to_delayed_work(work),
39                                            struct bch_fs,
40                                            pd_controllers_update);
41         struct bch_dev *ca;
42         unsigned i;
43
44         for_each_member_device(ca, c, i) {
45                 struct bch_dev_usage stats = bch2_dev_usage_read(c, ca);
46
47                 u64 free = bucket_to_sector(ca,
48                                 __dev_buckets_free(ca, stats)) << 9;
49                 /*
50                  * Bytes of internal fragmentation, which can be
51                  * reclaimed by copy GC
52                  */
53                 s64 fragmented = (bucket_to_sector(ca,
54                                         stats.buckets[BCH_DATA_USER] +
55                                         stats.buckets[BCH_DATA_CACHED]) -
56                                   (stats.sectors[BCH_DATA_USER] +
57                                    stats.sectors[BCH_DATA_CACHED])) << 9;
58
59                 fragmented = max(0LL, fragmented);
60
61                 bch2_pd_controller_update(&ca->copygc_pd,
62                                          free, fragmented, -1);
63         }
64
65         schedule_delayed_work(&c->pd_controllers_update,
66                               c->pd_controllers_update_seconds * HZ);
67 }
68
69 /* Persistent alloc info: */
70
71 static inline u64 get_alloc_field(const struct bch_alloc *a,
72                                   const void **p, unsigned field)
73 {
74         unsigned bytes = BCH_ALLOC_FIELD_BYTES[field];
75         u64 v;
76
77         if (!(a->fields & (1 << field)))
78                 return 0;
79
80         switch (bytes) {
81         case 1:
82                 v = *((const u8 *) *p);
83                 break;
84         case 2:
85                 v = le16_to_cpup(*p);
86                 break;
87         case 4:
88                 v = le32_to_cpup(*p);
89                 break;
90         case 8:
91                 v = le64_to_cpup(*p);
92                 break;
93         default:
94                 BUG();
95         }
96
97         *p += bytes;
98         return v;
99 }
100
101 static inline void put_alloc_field(struct bkey_i_alloc *a, void **p,
102                                    unsigned field, u64 v)
103 {
104         unsigned bytes = BCH_ALLOC_FIELD_BYTES[field];
105
106         if (!v)
107                 return;
108
109         a->v.fields |= 1 << field;
110
111         switch (bytes) {
112         case 1:
113                 *((u8 *) *p) = v;
114                 break;
115         case 2:
116                 *((__le16 *) *p) = cpu_to_le16(v);
117                 break;
118         case 4:
119                 *((__le32 *) *p) = cpu_to_le32(v);
120                 break;
121         case 8:
122                 *((__le64 *) *p) = cpu_to_le64(v);
123                 break;
124         default:
125                 BUG();
126         }
127
128         *p += bytes;
129 }
130
131 static unsigned bch_alloc_val_u64s(const struct bch_alloc *a)
132 {
133         unsigned i, bytes = offsetof(struct bch_alloc, data);
134
135         for (i = 0; i < ARRAY_SIZE(BCH_ALLOC_FIELD_BYTES); i++)
136                 if (a->fields & (1 << i))
137                         bytes += BCH_ALLOC_FIELD_BYTES[i];
138
139         return DIV_ROUND_UP(bytes, sizeof(u64));
140 }
141
142 const char *bch2_alloc_invalid(const struct bch_fs *c, struct bkey_s_c k)
143 {
144         struct bkey_s_c_alloc a = bkey_s_c_to_alloc(k);
145
146         if (k.k->p.inode >= c->sb.nr_devices ||
147             !c->devs[k.k->p.inode])
148                 return "invalid device";
149
150         /* allow for unknown fields */
151         if (bkey_val_u64s(a.k) < bch_alloc_val_u64s(a.v))
152                 return "incorrect value size";
153
154         return NULL;
155 }
156
157 void bch2_alloc_to_text(struct printbuf *out, struct bch_fs *c,
158                         struct bkey_s_c k)
159 {
160         struct bkey_s_c_alloc a = bkey_s_c_to_alloc(k);
161         const void *d = a.v->data;
162         unsigned i;
163
164         pr_buf(out, "gen %u", a.v->gen);
165
166         for (i = 0; i < BCH_ALLOC_FIELD_NR; i++)
167                 if (a.v->fields & (1 << i))
168                         pr_buf(out, " %s %llu",
169                                bch2_alloc_field_names[i],
170                                get_alloc_field(a.v, &d, i));
171 }
172
173 static void __alloc_read_key(struct bucket *g, const struct bch_alloc *a)
174 {
175         const void *d = a->data;
176         unsigned idx = 0;
177
178         g->_mark.gen            = a->gen;
179         g->gen_valid            = 1;
180         g->io_time[READ]        = get_alloc_field(a, &d, idx++);
181         g->io_time[WRITE]       = get_alloc_field(a, &d, idx++);
182         g->_mark.data_type      = get_alloc_field(a, &d, idx++);
183         g->_mark.dirty_sectors  = get_alloc_field(a, &d, idx++);
184         g->_mark.cached_sectors = get_alloc_field(a, &d, idx++);
185 }
186
187 static void __alloc_write_key(struct bkey_i_alloc *a, struct bucket *g,
188                               struct bucket_mark m)
189 {
190         unsigned idx = 0;
191         void *d = a->v.data;
192
193         a->v.fields     = 0;
194         a->v.gen        = m.gen;
195
196         d = a->v.data;
197         put_alloc_field(a, &d, idx++, g->io_time[READ]);
198         put_alloc_field(a, &d, idx++, g->io_time[WRITE]);
199         put_alloc_field(a, &d, idx++, m.data_type);
200         put_alloc_field(a, &d, idx++, m.dirty_sectors);
201         put_alloc_field(a, &d, idx++, m.cached_sectors);
202
203         set_bkey_val_bytes(&a->k, (void *) d - (void *) &a->v);
204 }
205
206 static void bch2_alloc_read_key(struct bch_fs *c, struct bkey_s_c k)
207 {
208         struct bch_dev *ca;
209         struct bkey_s_c_alloc a;
210
211         if (k.k->type != KEY_TYPE_alloc)
212                 return;
213
214         a = bkey_s_c_to_alloc(k);
215         ca = bch_dev_bkey_exists(c, a.k->p.inode);
216
217         if (a.k->p.offset >= ca->mi.nbuckets)
218                 return;
219
220         percpu_down_read_preempt_disable(&c->mark_lock);
221         __alloc_read_key(bucket(ca, a.k->p.offset), a.v);
222         percpu_up_read_preempt_enable(&c->mark_lock);
223 }
224
225 int bch2_alloc_read(struct bch_fs *c, struct list_head *journal_replay_list)
226 {
227         struct journal_replay *r;
228         struct btree_iter iter;
229         struct bkey_s_c k;
230         struct bch_dev *ca;
231         unsigned i;
232         int ret;
233
234         for_each_btree_key(&iter, c, BTREE_ID_ALLOC, POS_MIN, 0, k) {
235                 bch2_alloc_read_key(c, k);
236                 bch2_btree_iter_cond_resched(&iter);
237         }
238
239         ret = bch2_btree_iter_unlock(&iter);
240         if (ret)
241                 return ret;
242
243         list_for_each_entry(r, journal_replay_list, list) {
244                 struct bkey_i *k, *n;
245                 struct jset_entry *entry;
246
247                 for_each_jset_key(k, n, entry, &r->j)
248                         if (entry->btree_id == BTREE_ID_ALLOC)
249                                 bch2_alloc_read_key(c, bkey_i_to_s_c(k));
250         }
251
252         mutex_lock(&c->bucket_clock[READ].lock);
253         for_each_member_device(ca, c, i) {
254                 down_read(&ca->bucket_lock);
255                 bch2_recalc_oldest_io(c, ca, READ);
256                 up_read(&ca->bucket_lock);
257         }
258         mutex_unlock(&c->bucket_clock[READ].lock);
259
260         mutex_lock(&c->bucket_clock[WRITE].lock);
261         for_each_member_device(ca, c, i) {
262                 down_read(&ca->bucket_lock);
263                 bch2_recalc_oldest_io(c, ca, WRITE);
264                 up_read(&ca->bucket_lock);
265         }
266         mutex_unlock(&c->bucket_clock[WRITE].lock);
267
268         return 0;
269 }
270
271 static int __bch2_alloc_write_key(struct bch_fs *c, struct bch_dev *ca,
272                                   size_t b, struct btree_iter *iter,
273                                   u64 *journal_seq, unsigned flags)
274 {
275 #if 0
276         __BKEY_PADDED(k, BKEY_ALLOC_VAL_U64s_MAX) alloc_key;
277 #else
278         /* hack: */
279         __BKEY_PADDED(k, 8) alloc_key;
280 #endif
281         struct bkey_i_alloc *a = bkey_alloc_init(&alloc_key.k);
282         struct bucket *g;
283         struct bucket_mark m;
284         int ret;
285
286         BUG_ON(BKEY_ALLOC_VAL_U64s_MAX > 8);
287
288         a->k.p = POS(ca->dev_idx, b);
289
290         percpu_down_read_preempt_disable(&c->mark_lock);
291         g = bucket(ca, b);
292         m = bucket_cmpxchg(g, m, m.dirty = false);
293
294         __alloc_write_key(a, g, m);
295         percpu_up_read_preempt_enable(&c->mark_lock);
296
297         bch2_btree_iter_cond_resched(iter);
298
299         bch2_btree_iter_set_pos(iter, a->k.p);
300
301         ret = bch2_btree_insert_at(c, NULL, journal_seq,
302                                    BTREE_INSERT_NOFAIL|
303                                    BTREE_INSERT_USE_RESERVE|
304                                    BTREE_INSERT_USE_ALLOC_RESERVE|
305                                    flags,
306                                    BTREE_INSERT_ENTRY(iter, &a->k_i));
307
308         if (!ret && ca->buckets_written)
309                 set_bit(b, ca->buckets_written);
310
311         return ret;
312 }
313
314 int bch2_alloc_replay_key(struct bch_fs *c, struct bkey_i *k)
315 {
316         struct bch_dev *ca;
317         struct btree_iter iter;
318         int ret;
319
320         if (k->k.p.inode >= c->sb.nr_devices ||
321             !c->devs[k->k.p.inode])
322                 return 0;
323
324         ca = bch_dev_bkey_exists(c, k->k.p.inode);
325
326         if (k->k.p.offset >= ca->mi.nbuckets)
327                 return 0;
328
329         bch2_btree_iter_init(&iter, c, BTREE_ID_ALLOC, k->k.p,
330                              BTREE_ITER_INTENT);
331
332         ret = bch2_btree_iter_traverse(&iter);
333         if (ret)
334                 goto err;
335
336         /* check buckets_written with btree node locked: */
337
338         ret = test_bit(k->k.p.offset, ca->buckets_written)
339                 ? 0
340                 : bch2_btree_insert_at(c, NULL, NULL,
341                                        BTREE_INSERT_NOFAIL|
342                                        BTREE_INSERT_JOURNAL_REPLAY,
343                                        BTREE_INSERT_ENTRY(&iter, k));
344 err:
345         bch2_btree_iter_unlock(&iter);
346         return ret;
347 }
348
349 int bch2_alloc_write(struct bch_fs *c, bool nowait, bool *wrote)
350 {
351         struct bch_dev *ca;
352         unsigned i;
353         int ret = 0;
354
355         *wrote = false;
356
357         for_each_rw_member(ca, c, i) {
358                 struct btree_iter iter;
359                 struct bucket_array *buckets;
360                 size_t b;
361
362                 bch2_btree_iter_init(&iter, c, BTREE_ID_ALLOC, POS_MIN,
363                                      BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
364
365                 down_read(&ca->bucket_lock);
366                 buckets = bucket_array(ca);
367
368                 for (b = buckets->first_bucket;
369                      b < buckets->nbuckets;
370                      b++) {
371                         if (!buckets->b[b].mark.dirty)
372                                 continue;
373
374                         ret = __bch2_alloc_write_key(c, ca, b, &iter, NULL,
375                                                      nowait
376                                                      ? BTREE_INSERT_NOWAIT
377                                                      : 0);
378                         if (ret)
379                                 break;
380
381                         *wrote = true;
382                 }
383                 up_read(&ca->bucket_lock);
384                 bch2_btree_iter_unlock(&iter);
385
386                 if (ret) {
387                         percpu_ref_put(&ca->io_ref);
388                         break;
389                 }
390         }
391
392         return ret;
393 }
394
395 /* Bucket IO clocks: */
396
397 static void bch2_recalc_oldest_io(struct bch_fs *c, struct bch_dev *ca, int rw)
398 {
399         struct bucket_clock *clock = &c->bucket_clock[rw];
400         struct bucket_array *buckets = bucket_array(ca);
401         struct bucket *g;
402         u16 max_last_io = 0;
403         unsigned i;
404
405         lockdep_assert_held(&c->bucket_clock[rw].lock);
406
407         /* Recalculate max_last_io for this device: */
408         for_each_bucket(g, buckets)
409                 max_last_io = max(max_last_io, bucket_last_io(c, g, rw));
410
411         ca->max_last_bucket_io[rw] = max_last_io;
412
413         /* Recalculate global max_last_io: */
414         max_last_io = 0;
415
416         for_each_member_device(ca, c, i)
417                 max_last_io = max(max_last_io, ca->max_last_bucket_io[rw]);
418
419         clock->max_last_io = max_last_io;
420 }
421
422 static void bch2_rescale_bucket_io_times(struct bch_fs *c, int rw)
423 {
424         struct bucket_clock *clock = &c->bucket_clock[rw];
425         struct bucket_array *buckets;
426         struct bch_dev *ca;
427         struct bucket *g;
428         unsigned i;
429
430         trace_rescale_prios(c);
431
432         for_each_member_device(ca, c, i) {
433                 down_read(&ca->bucket_lock);
434                 buckets = bucket_array(ca);
435
436                 for_each_bucket(g, buckets)
437                         g->io_time[rw] = clock->hand -
438                         bucket_last_io(c, g, rw) / 2;
439
440                 bch2_recalc_oldest_io(c, ca, rw);
441
442                 up_read(&ca->bucket_lock);
443         }
444 }
445
446 static inline u64 bucket_clock_freq(u64 capacity)
447 {
448         return max(capacity >> 10, 2028ULL);
449 }
450
451 static void bch2_inc_clock_hand(struct io_timer *timer)
452 {
453         struct bucket_clock *clock = container_of(timer,
454                                                 struct bucket_clock, rescale);
455         struct bch_fs *c = container_of(clock,
456                                         struct bch_fs, bucket_clock[clock->rw]);
457         struct bch_dev *ca;
458         u64 capacity;
459         unsigned i;
460
461         mutex_lock(&clock->lock);
462
463         /* if clock cannot be advanced more, rescale prio */
464         if (clock->max_last_io >= U16_MAX - 2)
465                 bch2_rescale_bucket_io_times(c, clock->rw);
466
467         BUG_ON(clock->max_last_io >= U16_MAX - 2);
468
469         for_each_member_device(ca, c, i)
470                 ca->max_last_bucket_io[clock->rw]++;
471         clock->max_last_io++;
472         clock->hand++;
473
474         mutex_unlock(&clock->lock);
475
476         capacity = READ_ONCE(c->capacity);
477
478         if (!capacity)
479                 return;
480
481         /*
482          * we only increment when 0.1% of the filesystem capacity has been read
483          * or written too, this determines if it's time
484          *
485          * XXX: we shouldn't really be going off of the capacity of devices in
486          * RW mode (that will be 0 when we're RO, yet we can still service
487          * reads)
488          */
489         timer->expire += bucket_clock_freq(capacity);
490
491         bch2_io_timer_add(&c->io_clock[clock->rw], timer);
492 }
493
494 static void bch2_bucket_clock_init(struct bch_fs *c, int rw)
495 {
496         struct bucket_clock *clock = &c->bucket_clock[rw];
497
498         clock->hand             = 1;
499         clock->rw               = rw;
500         clock->rescale.fn       = bch2_inc_clock_hand;
501         clock->rescale.expire   = bucket_clock_freq(c->capacity);
502         mutex_init(&clock->lock);
503 }
504
505 /* Background allocator thread: */
506
507 /*
508  * Scans for buckets to be invalidated, invalidates them, rewrites prios/gens
509  * (marking them as invalidated on disk), then optionally issues discard
510  * commands to the newly free buckets, then puts them on the various freelists.
511  */
512
513 #define BUCKET_GC_GEN_MAX       96U
514
515 /**
516  * wait_buckets_available - wait on reclaimable buckets
517  *
518  * If there aren't enough available buckets to fill up free_inc, wait until
519  * there are.
520  */
521 static int wait_buckets_available(struct bch_fs *c, struct bch_dev *ca)
522 {
523         unsigned long gc_count = c->gc_count;
524         int ret = 0;
525
526         while (1) {
527                 set_current_state(TASK_INTERRUPTIBLE);
528                 if (kthread_should_stop()) {
529                         ret = 1;
530                         break;
531                 }
532
533                 if (gc_count != c->gc_count)
534                         ca->inc_gen_really_needs_gc = 0;
535
536                 if ((ssize_t) (dev_buckets_available(c, ca) -
537                                ca->inc_gen_really_needs_gc) >=
538                     (ssize_t) fifo_free(&ca->free_inc))
539                         break;
540
541                 up_read(&c->gc_lock);
542                 schedule();
543                 try_to_freeze();
544                 down_read(&c->gc_lock);
545         }
546
547         __set_current_state(TASK_RUNNING);
548         return ret;
549 }
550
551 static bool bch2_can_invalidate_bucket(struct bch_dev *ca,
552                                        size_t bucket,
553                                        struct bucket_mark mark)
554 {
555         u8 gc_gen;
556
557         if (!is_available_bucket(mark))
558                 return false;
559
560         if (ca->buckets_nouse &&
561             test_bit(bucket, ca->buckets_nouse))
562                 return false;
563
564         gc_gen = bucket_gc_gen(ca, bucket);
565
566         if (gc_gen >= BUCKET_GC_GEN_MAX / 2)
567                 ca->inc_gen_needs_gc++;
568
569         if (gc_gen >= BUCKET_GC_GEN_MAX)
570                 ca->inc_gen_really_needs_gc++;
571
572         return gc_gen < BUCKET_GC_GEN_MAX;
573 }
574
575 /*
576  * Determines what order we're going to reuse buckets, smallest bucket_key()
577  * first.
578  *
579  *
580  * - We take into account the read prio of the bucket, which gives us an
581  *   indication of how hot the data is -- we scale the prio so that the prio
582  *   farthest from the clock is worth 1/8th of the closest.
583  *
584  * - The number of sectors of cached data in the bucket, which gives us an
585  *   indication of the cost in cache misses this eviction will cause.
586  *
587  * - If hotness * sectors used compares equal, we pick the bucket with the
588  *   smallest bucket_gc_gen() - since incrementing the same bucket's generation
589  *   number repeatedly forces us to run mark and sweep gc to avoid generation
590  *   number wraparound.
591  */
592
593 static unsigned long bucket_sort_key(struct bch_fs *c, struct bch_dev *ca,
594                                      size_t b, struct bucket_mark m)
595 {
596         unsigned last_io = bucket_last_io(c, bucket(ca, b), READ);
597         unsigned max_last_io = ca->max_last_bucket_io[READ];
598
599         /*
600          * Time since last read, scaled to [0, 8) where larger value indicates
601          * more recently read data:
602          */
603         unsigned long hotness = (max_last_io - last_io) * 7 / max_last_io;
604
605         /* How much we want to keep the data in this bucket: */
606         unsigned long data_wantness =
607                 (hotness + 1) * bucket_sectors_used(m);
608
609         unsigned long needs_journal_commit =
610                 bucket_needs_journal_commit(m, c->journal.last_seq_ondisk);
611
612         return  (data_wantness << 9) |
613                 (needs_journal_commit << 8) |
614                 (bucket_gc_gen(ca, b) / 16);
615 }
616
617 static inline int bucket_alloc_cmp(alloc_heap *h,
618                                    struct alloc_heap_entry l,
619                                    struct alloc_heap_entry r)
620 {
621         return (l.key > r.key) - (l.key < r.key) ?:
622                 (l.nr < r.nr)  - (l.nr  > r.nr) ?:
623                 (l.bucket > r.bucket) - (l.bucket < r.bucket);
624 }
625
626 static inline int bucket_idx_cmp(const void *_l, const void *_r)
627 {
628         const struct alloc_heap_entry *l = _l, *r = _r;
629
630         return (l->bucket > r->bucket) - (l->bucket < r->bucket);
631 }
632
633 static void find_reclaimable_buckets_lru(struct bch_fs *c, struct bch_dev *ca)
634 {
635         struct bucket_array *buckets;
636         struct alloc_heap_entry e = { 0 };
637         size_t b, i, nr = 0;
638
639         ca->alloc_heap.used = 0;
640
641         mutex_lock(&c->bucket_clock[READ].lock);
642         down_read(&ca->bucket_lock);
643
644         buckets = bucket_array(ca);
645
646         bch2_recalc_oldest_io(c, ca, READ);
647
648         /*
649          * Find buckets with lowest read priority, by building a maxheap sorted
650          * by read priority and repeatedly replacing the maximum element until
651          * all buckets have been visited.
652          */
653         for (b = ca->mi.first_bucket; b < ca->mi.nbuckets; b++) {
654                 struct bucket_mark m = READ_ONCE(buckets->b[b].mark);
655                 unsigned long key = bucket_sort_key(c, ca, b, m);
656
657                 if (!bch2_can_invalidate_bucket(ca, b, m))
658                         continue;
659
660                 if (e.nr && e.bucket + e.nr == b && e.key == key) {
661                         e.nr++;
662                 } else {
663                         if (e.nr)
664                                 heap_add_or_replace(&ca->alloc_heap, e,
665                                         -bucket_alloc_cmp, NULL);
666
667                         e = (struct alloc_heap_entry) {
668                                 .bucket = b,
669                                 .nr     = 1,
670                                 .key    = key,
671                         };
672                 }
673
674                 cond_resched();
675         }
676
677         if (e.nr)
678                 heap_add_or_replace(&ca->alloc_heap, e,
679                                 -bucket_alloc_cmp, NULL);
680
681         for (i = 0; i < ca->alloc_heap.used; i++)
682                 nr += ca->alloc_heap.data[i].nr;
683
684         while (nr - ca->alloc_heap.data[0].nr >= ALLOC_SCAN_BATCH(ca)) {
685                 nr -= ca->alloc_heap.data[0].nr;
686                 heap_pop(&ca->alloc_heap, e, -bucket_alloc_cmp, NULL);
687         }
688
689         up_read(&ca->bucket_lock);
690         mutex_unlock(&c->bucket_clock[READ].lock);
691 }
692
693 static void find_reclaimable_buckets_fifo(struct bch_fs *c, struct bch_dev *ca)
694 {
695         struct bucket_array *buckets = bucket_array(ca);
696         struct bucket_mark m;
697         size_t b, start;
698
699         if (ca->fifo_last_bucket <  ca->mi.first_bucket ||
700             ca->fifo_last_bucket >= ca->mi.nbuckets)
701                 ca->fifo_last_bucket = ca->mi.first_bucket;
702
703         start = ca->fifo_last_bucket;
704
705         do {
706                 ca->fifo_last_bucket++;
707                 if (ca->fifo_last_bucket == ca->mi.nbuckets)
708                         ca->fifo_last_bucket = ca->mi.first_bucket;
709
710                 b = ca->fifo_last_bucket;
711                 m = READ_ONCE(buckets->b[b].mark);
712
713                 if (bch2_can_invalidate_bucket(ca, b, m)) {
714                         struct alloc_heap_entry e = { .bucket = b, .nr = 1, };
715
716                         heap_add(&ca->alloc_heap, e, bucket_alloc_cmp, NULL);
717                         if (heap_full(&ca->alloc_heap))
718                                 break;
719                 }
720
721                 cond_resched();
722         } while (ca->fifo_last_bucket != start);
723 }
724
725 static void find_reclaimable_buckets_random(struct bch_fs *c, struct bch_dev *ca)
726 {
727         struct bucket_array *buckets = bucket_array(ca);
728         struct bucket_mark m;
729         size_t checked, i;
730
731         for (checked = 0;
732              checked < ca->mi.nbuckets / 2;
733              checked++) {
734                 size_t b = bch2_rand_range(ca->mi.nbuckets -
735                                            ca->mi.first_bucket) +
736                         ca->mi.first_bucket;
737
738                 m = READ_ONCE(buckets->b[b].mark);
739
740                 if (bch2_can_invalidate_bucket(ca, b, m)) {
741                         struct alloc_heap_entry e = { .bucket = b, .nr = 1, };
742
743                         heap_add(&ca->alloc_heap, e, bucket_alloc_cmp, NULL);
744                         if (heap_full(&ca->alloc_heap))
745                                 break;
746                 }
747
748                 cond_resched();
749         }
750
751         sort(ca->alloc_heap.data,
752              ca->alloc_heap.used,
753              sizeof(ca->alloc_heap.data[0]),
754              bucket_idx_cmp, NULL);
755
756         /* remove duplicates: */
757         for (i = 0; i + 1 < ca->alloc_heap.used; i++)
758                 if (ca->alloc_heap.data[i].bucket ==
759                     ca->alloc_heap.data[i + 1].bucket)
760                         ca->alloc_heap.data[i].nr = 0;
761 }
762
763 static size_t find_reclaimable_buckets(struct bch_fs *c, struct bch_dev *ca)
764 {
765         size_t i, nr = 0;
766
767         ca->inc_gen_needs_gc                    = 0;
768
769         switch (ca->mi.replacement) {
770         case CACHE_REPLACEMENT_LRU:
771                 find_reclaimable_buckets_lru(c, ca);
772                 break;
773         case CACHE_REPLACEMENT_FIFO:
774                 find_reclaimable_buckets_fifo(c, ca);
775                 break;
776         case CACHE_REPLACEMENT_RANDOM:
777                 find_reclaimable_buckets_random(c, ca);
778                 break;
779         }
780
781         heap_resort(&ca->alloc_heap, bucket_alloc_cmp, NULL);
782
783         for (i = 0; i < ca->alloc_heap.used; i++)
784                 nr += ca->alloc_heap.data[i].nr;
785
786         return nr;
787 }
788
789 static inline long next_alloc_bucket(struct bch_dev *ca)
790 {
791         struct alloc_heap_entry e, *top = ca->alloc_heap.data;
792
793         while (ca->alloc_heap.used) {
794                 if (top->nr) {
795                         size_t b = top->bucket;
796
797                         top->bucket++;
798                         top->nr--;
799                         return b;
800                 }
801
802                 heap_pop(&ca->alloc_heap, e, bucket_alloc_cmp, NULL);
803         }
804
805         return -1;
806 }
807
808 static bool bch2_invalidate_one_bucket(struct bch_fs *c, struct bch_dev *ca,
809                                        size_t bucket, u64 *flush_seq)
810 {
811         struct bucket_mark m;
812
813         percpu_down_read_preempt_disable(&c->mark_lock);
814         spin_lock(&c->freelist_lock);
815
816         bch2_invalidate_bucket(c, ca, bucket, &m);
817
818         verify_not_on_freelist(c, ca, bucket);
819         BUG_ON(!fifo_push(&ca->free_inc, bucket));
820
821         spin_unlock(&c->freelist_lock);
822
823         bucket_io_clock_reset(c, ca, bucket, READ);
824         bucket_io_clock_reset(c, ca, bucket, WRITE);
825
826         percpu_up_read_preempt_enable(&c->mark_lock);
827
828         if (m.journal_seq_valid) {
829                 u64 journal_seq = atomic64_read(&c->journal.seq);
830                 u64 bucket_seq  = journal_seq;
831
832                 bucket_seq &= ~((u64) U16_MAX);
833                 bucket_seq |= m.journal_seq;
834
835                 if (bucket_seq > journal_seq)
836                         bucket_seq -= 1 << 16;
837
838                 *flush_seq = max(*flush_seq, bucket_seq);
839         }
840
841         return m.cached_sectors != 0;
842 }
843
844 /*
845  * Pull buckets off ca->alloc_heap, invalidate them, move them to ca->free_inc:
846  */
847 static int bch2_invalidate_buckets(struct bch_fs *c, struct bch_dev *ca)
848 {
849         struct btree_iter iter;
850         u64 journal_seq = 0;
851         int ret = 0;
852         long b;
853
854         bch2_btree_iter_init(&iter, c, BTREE_ID_ALLOC, POS(ca->dev_idx, 0),
855                              BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
856
857         /* Only use nowait if we've already invalidated at least one bucket: */
858         while (!ret &&
859                !fifo_full(&ca->free_inc) &&
860                (b = next_alloc_bucket(ca)) >= 0) {
861                 bool must_flush =
862                         bch2_invalidate_one_bucket(c, ca, b, &journal_seq);
863
864                 ret = __bch2_alloc_write_key(c, ca, b, &iter,
865                                 must_flush ? &journal_seq : NULL,
866                                 !fifo_empty(&ca->free_inc) ? BTREE_INSERT_NOWAIT : 0);
867         }
868
869         bch2_btree_iter_unlock(&iter);
870
871         /* If we used NOWAIT, don't return the error: */
872         if (!fifo_empty(&ca->free_inc))
873                 ret = 0;
874         if (ret) {
875                 bch_err(ca, "error invalidating buckets: %i", ret);
876                 return ret;
877         }
878
879         if (journal_seq)
880                 ret = bch2_journal_flush_seq(&c->journal, journal_seq);
881         if (ret) {
882                 bch_err(ca, "journal error: %i", ret);
883                 return ret;
884         }
885
886         return 0;
887 }
888
889 static int push_invalidated_bucket(struct bch_fs *c, struct bch_dev *ca, size_t bucket)
890 {
891         unsigned i;
892         int ret = 0;
893
894         while (1) {
895                 set_current_state(TASK_INTERRUPTIBLE);
896
897                 spin_lock(&c->freelist_lock);
898                 for (i = 0; i < RESERVE_NR; i++)
899                         if (fifo_push(&ca->free[i], bucket)) {
900                                 fifo_pop(&ca->free_inc, bucket);
901                                 closure_wake_up(&c->freelist_wait);
902                                 spin_unlock(&c->freelist_lock);
903                                 goto out;
904                         }
905                 spin_unlock(&c->freelist_lock);
906
907                 if ((current->flags & PF_KTHREAD) &&
908                     kthread_should_stop()) {
909                         ret = 1;
910                         break;
911                 }
912
913                 schedule();
914                 try_to_freeze();
915         }
916 out:
917         __set_current_state(TASK_RUNNING);
918         return ret;
919 }
920
921 /*
922  * Pulls buckets off free_inc, discards them (if enabled), then adds them to
923  * freelists, waiting until there's room if necessary:
924  */
925 static int discard_invalidated_buckets(struct bch_fs *c, struct bch_dev *ca)
926 {
927         while (!fifo_empty(&ca->free_inc)) {
928                 size_t bucket = fifo_peek(&ca->free_inc);
929
930                 if (ca->mi.discard &&
931                     blk_queue_discard(bdev_get_queue(ca->disk_sb.bdev)))
932                         blkdev_issue_discard(ca->disk_sb.bdev,
933                                              bucket_to_sector(ca, bucket),
934                                              ca->mi.bucket_size, GFP_NOIO, 0);
935
936                 if (push_invalidated_bucket(c, ca, bucket))
937                         return 1;
938         }
939
940         return 0;
941 }
942
943 /**
944  * bch_allocator_thread - move buckets from free_inc to reserves
945  *
946  * The free_inc FIFO is populated by find_reclaimable_buckets(), and
947  * the reserves are depleted by bucket allocation. When we run out
948  * of free_inc, try to invalidate some buckets and write out
949  * prios and gens.
950  */
951 static int bch2_allocator_thread(void *arg)
952 {
953         struct bch_dev *ca = arg;
954         struct bch_fs *c = ca->fs;
955         size_t nr;
956         int ret;
957
958         set_freezable();
959
960         while (1) {
961                 cond_resched();
962
963                 pr_debug("discarding %zu invalidated buckets",
964                          fifo_used(&ca->free_inc));
965
966                 ret = discard_invalidated_buckets(c, ca);
967                 if (ret)
968                         goto stop;
969
970                 down_read(&c->gc_lock);
971
972                 ret = bch2_invalidate_buckets(c, ca);
973                 if (ret) {
974                         up_read(&c->gc_lock);
975                         goto stop;
976                 }
977
978                 if (!fifo_empty(&ca->free_inc)) {
979                         up_read(&c->gc_lock);
980                         continue;
981                 }
982
983                 pr_debug("free_inc now empty");
984
985                 do {
986                         /*
987                          * Find some buckets that we can invalidate, either
988                          * they're completely unused, or only contain clean data
989                          * that's been written back to the backing device or
990                          * another cache tier
991                          */
992
993                         pr_debug("scanning for reclaimable buckets");
994
995                         nr = find_reclaimable_buckets(c, ca);
996
997                         pr_debug("found %zu buckets", nr);
998
999                         trace_alloc_batch(ca, nr, ca->alloc_heap.size);
1000
1001                         if ((ca->inc_gen_needs_gc >= ALLOC_SCAN_BATCH(ca) ||
1002                              ca->inc_gen_really_needs_gc) &&
1003                             c->gc_thread) {
1004                                 atomic_inc(&c->kick_gc);
1005                                 wake_up_process(c->gc_thread);
1006                         }
1007
1008                         /*
1009                          * If we found any buckets, we have to invalidate them
1010                          * before we scan for more - but if we didn't find very
1011                          * many we may want to wait on more buckets being
1012                          * available so we don't spin:
1013                          */
1014                         if (!nr ||
1015                             (nr < ALLOC_SCAN_BATCH(ca) &&
1016                              !fifo_full(&ca->free[RESERVE_MOVINGGC]))) {
1017                                 ca->allocator_blocked = true;
1018                                 closure_wake_up(&c->freelist_wait);
1019
1020                                 ret = wait_buckets_available(c, ca);
1021                                 if (ret) {
1022                                         up_read(&c->gc_lock);
1023                                         goto stop;
1024                                 }
1025                         }
1026                 } while (!nr);
1027
1028                 ca->allocator_blocked = false;
1029                 up_read(&c->gc_lock);
1030
1031                 pr_debug("%zu buckets to invalidate", nr);
1032
1033                 /*
1034                  * alloc_heap is now full of newly-invalidated buckets: next,
1035                  * write out the new bucket gens:
1036                  */
1037         }
1038
1039 stop:
1040         pr_debug("alloc thread stopping (ret %i)", ret);
1041         return 0;
1042 }
1043
1044 /* Startup/shutdown (ro/rw): */
1045
1046 void bch2_recalc_capacity(struct bch_fs *c)
1047 {
1048         struct bch_dev *ca;
1049         u64 capacity = 0, reserved_sectors = 0, gc_reserve;
1050         unsigned bucket_size_max = 0;
1051         unsigned long ra_pages = 0;
1052         unsigned i, j;
1053
1054         lockdep_assert_held(&c->state_lock);
1055
1056         for_each_online_member(ca, c, i) {
1057                 struct backing_dev_info *bdi = ca->disk_sb.bdev->bd_bdi;
1058
1059                 ra_pages += bdi->ra_pages;
1060         }
1061
1062         bch2_set_ra_pages(c, ra_pages);
1063
1064         for_each_rw_member(ca, c, i) {
1065                 u64 dev_reserve = 0;
1066
1067                 /*
1068                  * We need to reserve buckets (from the number
1069                  * of currently available buckets) against
1070                  * foreground writes so that mainly copygc can
1071                  * make forward progress.
1072                  *
1073                  * We need enough to refill the various reserves
1074                  * from scratch - copygc will use its entire
1075                  * reserve all at once, then run against when
1076                  * its reserve is refilled (from the formerly
1077                  * available buckets).
1078                  *
1079                  * This reserve is just used when considering if
1080                  * allocations for foreground writes must wait -
1081                  * not -ENOSPC calculations.
1082                  */
1083                 for (j = 0; j < RESERVE_NONE; j++)
1084                         dev_reserve += ca->free[j].size;
1085
1086                 dev_reserve += 1;       /* btree write point */
1087                 dev_reserve += 1;       /* copygc write point */
1088                 dev_reserve += 1;       /* rebalance write point */
1089
1090                 dev_reserve *= ca->mi.bucket_size;
1091
1092                 ca->copygc_threshold = dev_reserve;
1093
1094                 capacity += bucket_to_sector(ca, ca->mi.nbuckets -
1095                                              ca->mi.first_bucket);
1096
1097                 reserved_sectors += dev_reserve * 2;
1098
1099                 bucket_size_max = max_t(unsigned, bucket_size_max,
1100                                         ca->mi.bucket_size);
1101         }
1102
1103         gc_reserve = c->opts.gc_reserve_bytes
1104                 ? c->opts.gc_reserve_bytes >> 9
1105                 : div64_u64(capacity * c->opts.gc_reserve_percent, 100);
1106
1107         reserved_sectors = max(gc_reserve, reserved_sectors);
1108
1109         reserved_sectors = min(reserved_sectors, capacity);
1110
1111         c->capacity = capacity - reserved_sectors;
1112
1113         c->bucket_size_max = bucket_size_max;
1114
1115         if (c->capacity) {
1116                 bch2_io_timer_add(&c->io_clock[READ],
1117                                  &c->bucket_clock[READ].rescale);
1118                 bch2_io_timer_add(&c->io_clock[WRITE],
1119                                  &c->bucket_clock[WRITE].rescale);
1120         } else {
1121                 bch2_io_timer_del(&c->io_clock[READ],
1122                                  &c->bucket_clock[READ].rescale);
1123                 bch2_io_timer_del(&c->io_clock[WRITE],
1124                                  &c->bucket_clock[WRITE].rescale);
1125         }
1126
1127         /* Wake up case someone was waiting for buckets */
1128         closure_wake_up(&c->freelist_wait);
1129 }
1130
1131 static bool bch2_dev_has_open_write_point(struct bch_fs *c, struct bch_dev *ca)
1132 {
1133         struct open_bucket *ob;
1134         bool ret = false;
1135
1136         for (ob = c->open_buckets;
1137              ob < c->open_buckets + ARRAY_SIZE(c->open_buckets);
1138              ob++) {
1139                 spin_lock(&ob->lock);
1140                 if (ob->valid && !ob->on_partial_list &&
1141                     ob->ptr.dev == ca->dev_idx)
1142                         ret = true;
1143                 spin_unlock(&ob->lock);
1144         }
1145
1146         return ret;
1147 }
1148
1149 /* device goes ro: */
1150 void bch2_dev_allocator_remove(struct bch_fs *c, struct bch_dev *ca)
1151 {
1152         unsigned i;
1153
1154         BUG_ON(ca->alloc_thread);
1155
1156         /* First, remove device from allocation groups: */
1157
1158         for (i = 0; i < ARRAY_SIZE(c->rw_devs); i++)
1159                 clear_bit(ca->dev_idx, c->rw_devs[i].d);
1160
1161         /*
1162          * Capacity is calculated based off of devices in allocation groups:
1163          */
1164         bch2_recalc_capacity(c);
1165
1166         /* Next, close write points that point to this device... */
1167         for (i = 0; i < ARRAY_SIZE(c->write_points); i++)
1168                 bch2_writepoint_stop(c, ca, &c->write_points[i]);
1169
1170         bch2_writepoint_stop(c, ca, &ca->copygc_write_point);
1171         bch2_writepoint_stop(c, ca, &c->rebalance_write_point);
1172         bch2_writepoint_stop(c, ca, &c->btree_write_point);
1173
1174         mutex_lock(&c->btree_reserve_cache_lock);
1175         while (c->btree_reserve_cache_nr) {
1176                 struct btree_alloc *a =
1177                         &c->btree_reserve_cache[--c->btree_reserve_cache_nr];
1178
1179                 bch2_open_buckets_put(c, &a->ob);
1180         }
1181         mutex_unlock(&c->btree_reserve_cache_lock);
1182
1183         while (1) {
1184                 struct open_bucket *ob;
1185
1186                 spin_lock(&c->freelist_lock);
1187                 if (!ca->open_buckets_partial_nr) {
1188                         spin_unlock(&c->freelist_lock);
1189                         break;
1190                 }
1191                 ob = c->open_buckets +
1192                         ca->open_buckets_partial[--ca->open_buckets_partial_nr];
1193                 ob->on_partial_list = false;
1194                 spin_unlock(&c->freelist_lock);
1195
1196                 bch2_open_bucket_put(c, ob);
1197         }
1198
1199         bch2_ec_stop_dev(c, ca);
1200
1201         /*
1202          * Wake up threads that were blocked on allocation, so they can notice
1203          * the device can no longer be removed and the capacity has changed:
1204          */
1205         closure_wake_up(&c->freelist_wait);
1206
1207         /*
1208          * journal_res_get() can block waiting for free space in the journal -
1209          * it needs to notice there may not be devices to allocate from anymore:
1210          */
1211         wake_up(&c->journal.wait);
1212
1213         /* Now wait for any in flight writes: */
1214
1215         closure_wait_event(&c->open_buckets_wait,
1216                            !bch2_dev_has_open_write_point(c, ca));
1217 }
1218
1219 /* device goes rw: */
1220 void bch2_dev_allocator_add(struct bch_fs *c, struct bch_dev *ca)
1221 {
1222         unsigned i;
1223
1224         for (i = 0; i < ARRAY_SIZE(c->rw_devs); i++)
1225                 if (ca->mi.data_allowed & (1 << i))
1226                         set_bit(ca->dev_idx, c->rw_devs[i].d);
1227 }
1228
1229 /* stop allocator thread: */
1230 void bch2_dev_allocator_stop(struct bch_dev *ca)
1231 {
1232         struct task_struct *p;
1233
1234         p = rcu_dereference_protected(ca->alloc_thread, 1);
1235         ca->alloc_thread = NULL;
1236
1237         /*
1238          * We need an rcu barrier between setting ca->alloc_thread = NULL and
1239          * the thread shutting down to avoid bch2_wake_allocator() racing:
1240          *
1241          * XXX: it would be better to have the rcu barrier be asynchronous
1242          * instead of blocking us here
1243          */
1244         synchronize_rcu();
1245
1246         if (p) {
1247                 kthread_stop(p);
1248                 put_task_struct(p);
1249         }
1250 }
1251
1252 /* start allocator thread: */
1253 int bch2_dev_allocator_start(struct bch_dev *ca)
1254 {
1255         struct task_struct *p;
1256
1257         /*
1258          * allocator thread already started?
1259          */
1260         if (ca->alloc_thread)
1261                 return 0;
1262
1263         p = kthread_create(bch2_allocator_thread, ca,
1264                            "bch_alloc[%s]", ca->name);
1265         if (IS_ERR(p))
1266                 return PTR_ERR(p);
1267
1268         get_task_struct(p);
1269         rcu_assign_pointer(ca->alloc_thread, p);
1270         wake_up_process(p);
1271         return 0;
1272 }
1273
1274 static void flush_held_btree_writes(struct bch_fs *c)
1275 {
1276         struct bucket_table *tbl;
1277         struct rhash_head *pos;
1278         struct btree *b;
1279         bool nodes_blocked;
1280         size_t i;
1281         struct closure cl;
1282
1283         closure_init_stack(&cl);
1284
1285         clear_bit(BCH_FS_HOLD_BTREE_WRITES, &c->flags);
1286 again:
1287         pr_debug("flushing dirty btree nodes");
1288         cond_resched();
1289         closure_wait(&c->btree_interior_update_wait, &cl);
1290
1291         nodes_blocked = false;
1292
1293         rcu_read_lock();
1294         for_each_cached_btree(b, c, tbl, i, pos)
1295                 if (btree_node_need_write(b)) {
1296                         if (btree_node_may_write(b)) {
1297                                 rcu_read_unlock();
1298                                 btree_node_lock_type(c, b, SIX_LOCK_read);
1299                                 bch2_btree_node_write(c, b, SIX_LOCK_read);
1300                                 six_unlock_read(&b->lock);
1301                                 goto again;
1302                         } else {
1303                                 nodes_blocked = true;
1304                         }
1305                 }
1306         rcu_read_unlock();
1307
1308         if (c->btree_roots_dirty)
1309                 bch2_journal_meta(&c->journal);
1310
1311         if (nodes_blocked) {
1312                 closure_sync(&cl);
1313                 goto again;
1314         }
1315
1316         closure_wake_up(&c->btree_interior_update_wait);
1317         closure_sync(&cl);
1318
1319         closure_wait_event(&c->btree_interior_update_wait,
1320                            !bch2_btree_interior_updates_nr_pending(c));
1321 }
1322
1323 static void allocator_start_issue_discards(struct bch_fs *c)
1324 {
1325         struct bch_dev *ca;
1326         unsigned dev_iter;
1327         size_t bu;
1328
1329         for_each_rw_member(ca, c, dev_iter)
1330                 while (fifo_pop(&ca->free_inc, bu))
1331                         blkdev_issue_discard(ca->disk_sb.bdev,
1332                                              bucket_to_sector(ca, bu),
1333                                              ca->mi.bucket_size, GFP_NOIO, 0);
1334 }
1335
1336 static int __bch2_fs_allocator_start(struct bch_fs *c)
1337 {
1338         struct bch_dev *ca;
1339         unsigned dev_iter;
1340         u64 journal_seq = 0;
1341         long bu;
1342         int ret = 0;
1343
1344         if (test_alloc_startup(c))
1345                 goto not_enough;
1346
1347         /* Scan for buckets that are already invalidated: */
1348         for_each_rw_member(ca, c, dev_iter) {
1349                 struct bucket_array *buckets;
1350                 struct bucket_mark m;
1351
1352                 down_read(&ca->bucket_lock);
1353                 percpu_down_read_preempt_disable(&c->mark_lock);
1354
1355                 buckets = bucket_array(ca);
1356
1357                 for (bu = buckets->first_bucket;
1358                      bu < buckets->nbuckets; bu++) {
1359                         m = READ_ONCE(buckets->b[bu].mark);
1360
1361                         if (!buckets->b[bu].gen_valid ||
1362                             !test_bit(bu, ca->buckets_nouse) ||
1363                             !is_available_bucket(m) ||
1364                             m.cached_sectors)
1365                                 continue;
1366
1367                         bch2_mark_alloc_bucket(c, ca, bu, true,
1368                                         gc_pos_alloc(c, NULL), 0);
1369
1370                         fifo_push(&ca->free_inc, bu);
1371
1372                         discard_invalidated_buckets(c, ca);
1373
1374                         if (fifo_full(&ca->free[RESERVE_BTREE]))
1375                                 break;
1376                 }
1377                 percpu_up_read_preempt_enable(&c->mark_lock);
1378                 up_read(&ca->bucket_lock);
1379         }
1380
1381         /* did we find enough buckets? */
1382         for_each_rw_member(ca, c, dev_iter)
1383                 if (!fifo_full(&ca->free[RESERVE_BTREE])) {
1384                         percpu_ref_put(&ca->io_ref);
1385                         goto not_enough;
1386                 }
1387
1388         return 0;
1389 not_enough:
1390         pr_debug("not enough empty buckets; scanning for reclaimable buckets");
1391
1392         /*
1393          * We're moving buckets to freelists _before_ they've been marked as
1394          * invalidated on disk - we have to so that we can allocate new btree
1395          * nodes to mark them as invalidated on disk.
1396          *
1397          * However, we can't _write_ to any of these buckets yet - they might
1398          * have cached data in them, which is live until they're marked as
1399          * invalidated on disk:
1400          */
1401         set_bit(BCH_FS_HOLD_BTREE_WRITES, &c->flags);
1402
1403         while (1) {
1404                 bool wrote = false;
1405
1406                 for_each_rw_member(ca, c, dev_iter) {
1407                         find_reclaimable_buckets(c, ca);
1408
1409                         while (!fifo_full(&ca->free[RESERVE_BTREE]) &&
1410                                (bu = next_alloc_bucket(ca)) >= 0) {
1411                                 bch2_invalidate_one_bucket(c, ca, bu,
1412                                                            &journal_seq);
1413
1414                                 fifo_push(&ca->free[RESERVE_BTREE], bu);
1415                                 bucket_set_dirty(ca, bu);
1416                         }
1417                 }
1418
1419                 pr_debug("done scanning for reclaimable buckets");
1420
1421                 /*
1422                  * XXX: it's possible for this to deadlock waiting on journal reclaim,
1423                  * since we're holding btree writes. What then?
1424                  */
1425                 ret = bch2_alloc_write(c, true, &wrote);
1426
1427                 /*
1428                  * If bch2_alloc_write() did anything, it may have used some
1429                  * buckets, and we need the RESERVE_BTREE freelist full - so we
1430                  * need to loop and scan again.
1431                  * And if it errored, it may have been because there weren't
1432                  * enough buckets, so just scan and loop again as long as it
1433                  * made some progress:
1434                  */
1435                 if (!wrote && ret)
1436                         return ret;
1437                 if (!wrote && !ret)
1438                         break;
1439         }
1440
1441         pr_debug("flushing journal");
1442
1443         ret = bch2_journal_flush(&c->journal);
1444         if (ret)
1445                 return ret;
1446
1447         pr_debug("issuing discards");
1448         allocator_start_issue_discards(c);
1449
1450         set_bit(BCH_FS_ALLOCATOR_STARTED, &c->flags);
1451
1452         /* now flush dirty btree nodes: */
1453         flush_held_btree_writes(c);
1454
1455         return 0;
1456 }
1457
1458 int bch2_fs_allocator_start(struct bch_fs *c)
1459 {
1460         struct bch_dev *ca;
1461         unsigned i;
1462         bool wrote;
1463         int ret;
1464
1465         down_read(&c->gc_lock);
1466         ret = __bch2_fs_allocator_start(c);
1467         up_read(&c->gc_lock);
1468
1469         if (ret)
1470                 return ret;
1471
1472         for_each_rw_member(ca, c, i) {
1473                 ret = bch2_dev_allocator_start(ca);
1474                 if (ret) {
1475                         percpu_ref_put(&ca->io_ref);
1476                         return ret;
1477                 }
1478         }
1479
1480         return bch2_alloc_write(c, false, &wrote);
1481 }
1482
1483 void bch2_fs_allocator_background_init(struct bch_fs *c)
1484 {
1485         spin_lock_init(&c->freelist_lock);
1486         bch2_bucket_clock_init(c, READ);
1487         bch2_bucket_clock_init(c, WRITE);
1488
1489         c->pd_controllers_update_seconds = 5;
1490         INIT_DELAYED_WORK(&c->pd_controllers_update, pd_controllers_update);
1491 }