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