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