]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/alloc_background.c
Update bcachefs sources to e1f6739c4a bcachefs: Fix another iterator counting bug
[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         unsigned bytes;
156
157         dst->v.fields   = 0;
158         dst->v.gen      = src.gen;
159
160 #define x(_name, _bits) put_alloc_field(dst, &d, idx++, src._name);
161         BCH_ALLOC_FIELDS()
162 #undef  x
163
164         bytes = (void *) d - (void *) &dst->v;
165         set_bkey_val_bytes(&dst->k, bytes);
166         memset_u64s_tail(&dst->v, 0, bytes);
167 }
168
169 static unsigned bch_alloc_val_u64s(const struct bch_alloc *a)
170 {
171         unsigned i, bytes = offsetof(struct bch_alloc, data);
172
173         for (i = 0; i < ARRAY_SIZE(BCH_ALLOC_FIELD_BYTES); i++)
174                 if (a->fields & (1 << i))
175                         bytes += BCH_ALLOC_FIELD_BYTES[i];
176
177         return DIV_ROUND_UP(bytes, sizeof(u64));
178 }
179
180 const char *bch2_alloc_invalid(const struct bch_fs *c, struct bkey_s_c k)
181 {
182         struct bkey_s_c_alloc a = bkey_s_c_to_alloc(k);
183
184         if (k.k->p.inode >= c->sb.nr_devices ||
185             !c->devs[k.k->p.inode])
186                 return "invalid device";
187
188         /* allow for unknown fields */
189         if (bkey_val_u64s(a.k) < bch_alloc_val_u64s(a.v))
190                 return "incorrect value size";
191
192         return NULL;
193 }
194
195 void bch2_alloc_to_text(struct printbuf *out, struct bch_fs *c,
196                         struct bkey_s_c k)
197 {
198         struct bkey_s_c_alloc a = bkey_s_c_to_alloc(k);
199         const void *d = a.v->data;
200         unsigned i;
201
202         pr_buf(out, "gen %u", a.v->gen);
203
204         for (i = 0; i < BCH_ALLOC_FIELD_NR; i++)
205                 if (a.v->fields & (1 << i))
206                         pr_buf(out, " %s %llu",
207                                bch2_alloc_field_names[i],
208                                get_alloc_field(a.v, &d, i));
209 }
210
211 int bch2_alloc_read(struct bch_fs *c, struct journal_keys *journal_keys)
212 {
213         struct btree_trans trans;
214         struct btree_and_journal_iter iter;
215         struct bkey_s_c k;
216         struct bch_dev *ca;
217         unsigned i;
218         int ret = 0;
219
220         bch2_trans_init(&trans, c, 0, 0);
221
222         bch2_btree_and_journal_iter_init(&iter, &trans, journal_keys,
223                                          BTREE_ID_ALLOC, POS_MIN);
224
225         while ((k = bch2_btree_and_journal_iter_peek(&iter)).k) {
226                 bch2_mark_key(c, k, 0, 0, NULL, 0,
227                               BTREE_TRIGGER_ALLOC_READ|
228                               BTREE_TRIGGER_NOATOMIC);
229
230                 bch2_btree_and_journal_iter_advance(&iter);
231         }
232
233         ret = bch2_trans_exit(&trans) ?: ret;
234         if (ret) {
235                 bch_err(c, "error reading alloc info: %i", ret);
236                 return ret;
237         }
238
239         percpu_down_write(&c->mark_lock);
240         bch2_dev_usage_from_buckets(c);
241         percpu_up_write(&c->mark_lock);
242
243         mutex_lock(&c->bucket_clock[READ].lock);
244         for_each_member_device(ca, c, i) {
245                 down_read(&ca->bucket_lock);
246                 bch2_recalc_oldest_io(c, ca, READ);
247                 up_read(&ca->bucket_lock);
248         }
249         mutex_unlock(&c->bucket_clock[READ].lock);
250
251         mutex_lock(&c->bucket_clock[WRITE].lock);
252         for_each_member_device(ca, c, i) {
253                 down_read(&ca->bucket_lock);
254                 bch2_recalc_oldest_io(c, ca, WRITE);
255                 up_read(&ca->bucket_lock);
256         }
257         mutex_unlock(&c->bucket_clock[WRITE].lock);
258
259         return 0;
260 }
261
262 enum alloc_write_ret {
263         ALLOC_WROTE,
264         ALLOC_NOWROTE,
265         ALLOC_END,
266 };
267
268 static int bch2_alloc_write_key(struct btree_trans *trans,
269                                 struct btree_iter *iter,
270                                 unsigned flags)
271 {
272         struct bch_fs *c = trans->c;
273         struct bkey_s_c k;
274         struct bch_dev *ca;
275         struct bucket_array *ba;
276         struct bucket *g;
277         struct bucket_mark m;
278         struct bkey_alloc_unpacked old_u, new_u;
279         __BKEY_PADDED(k, 8) alloc_key; /* hack: */
280         struct bkey_i_alloc *a;
281         int ret;
282 retry:
283         k = bch2_btree_iter_peek_slot(iter);
284         ret = bkey_err(k);
285         if (ret)
286                 goto err;
287
288         old_u = bch2_alloc_unpack(k);
289
290         if (iter->pos.inode >= c->sb.nr_devices ||
291             !c->devs[iter->pos.inode])
292                 return ALLOC_END;
293
294         percpu_down_read(&c->mark_lock);
295         ca      = bch_dev_bkey_exists(c, iter->pos.inode);
296         ba      = bucket_array(ca);
297
298         if (iter->pos.offset >= ba->nbuckets) {
299                 percpu_up_read(&c->mark_lock);
300                 return ALLOC_END;
301         }
302
303         g       = &ba->b[iter->pos.offset];
304         m       = READ_ONCE(g->mark);
305         new_u   = alloc_mem_to_key(g, m);
306         percpu_up_read(&c->mark_lock);
307
308         if (!bkey_alloc_unpacked_cmp(old_u, new_u))
309                 return ALLOC_NOWROTE;
310
311         a = bkey_alloc_init(&alloc_key.k);
312         a->k.p = iter->pos;
313         bch2_alloc_pack(a, new_u);
314
315         bch2_trans_update(trans, iter, &a->k_i,
316                           BTREE_TRIGGER_NORUN);
317         ret = bch2_trans_commit(trans, NULL, NULL,
318                                 BTREE_INSERT_NOFAIL|
319                                 BTREE_INSERT_USE_RESERVE|
320                                 flags);
321 err:
322         if (ret == -EINTR)
323                 goto retry;
324         return ret;
325 }
326
327 int bch2_alloc_write(struct bch_fs *c, unsigned flags, bool *wrote)
328 {
329         struct btree_trans trans;
330         struct btree_iter *iter;
331         struct bch_dev *ca;
332         unsigned i;
333         int ret = 0;
334
335         BUG_ON(BKEY_ALLOC_VAL_U64s_MAX > 8);
336
337         bch2_trans_init(&trans, c, 0, 0);
338
339         iter = bch2_trans_get_iter(&trans, BTREE_ID_ALLOC, POS_MIN,
340                                    BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
341
342         for_each_rw_member(ca, c, i) {
343                 unsigned first_bucket;
344
345                 percpu_down_read(&c->mark_lock);
346                 first_bucket = bucket_array(ca)->first_bucket;
347                 percpu_up_read(&c->mark_lock);
348
349                 bch2_btree_iter_set_pos(iter, POS(i, first_bucket));
350
351                 while (1) {
352                         ret = bch2_alloc_write_key(&trans, iter, flags);
353                         if (ret < 0 || ret == ALLOC_END)
354                                 break;
355                         if (ret == ALLOC_WROTE)
356                                 *wrote = true;
357                         bch2_btree_iter_next_slot(iter);
358                 }
359
360                 if (ret < 0) {
361                         percpu_ref_put(&ca->io_ref);
362                         break;
363                 }
364         }
365
366         bch2_trans_exit(&trans);
367
368         return ret < 0 ? ret : 0;
369 }
370
371 int bch2_alloc_replay_key(struct bch_fs *c, struct bkey_i *k)
372 {
373         struct btree_trans trans;
374         struct btree_iter *iter;
375         int ret;
376
377         bch2_trans_init(&trans, c, 0, 0);
378
379         iter = bch2_trans_get_iter(&trans, BTREE_ID_ALLOC, k->k.p,
380                                    BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
381
382         ret = bch2_alloc_write_key(&trans, iter,
383                                    BTREE_INSERT_NOFAIL|
384                                    BTREE_INSERT_LAZY_RW|
385                                    BTREE_INSERT_JOURNAL_REPLAY);
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, iter, &a->k_i,
903                           BTREE_TRIGGER_BUCKET_INVALIDATE);
904
905         /*
906          * XXX:
907          * when using deferred btree updates, we have journal reclaim doing
908          * btree updates and thus requiring the allocator to make forward
909          * progress, and here the allocator is requiring space in the journal -
910          * so we need a journal pre-reservation:
911          */
912         ret = bch2_trans_commit(trans, NULL,
913                                 invalidating_cached_data ? journal_seq : NULL,
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                                 flags);
920         if (ret == -EINTR)
921                 goto retry;
922
923         if (!ret) {
924                 /* remove from alloc_heap: */
925                 struct alloc_heap_entry e, *top = ca->alloc_heap.data;
926
927                 top->bucket++;
928                 top->nr--;
929
930                 if (!top->nr)
931                         heap_pop(&ca->alloc_heap, e, bucket_alloc_cmp, NULL);
932
933                 /*
934                  * Make sure we flush the last journal entry that updated this
935                  * bucket (i.e. deleting the last reference) before writing to
936                  * this bucket again:
937                  */
938                 *journal_seq = max(*journal_seq, bucket_journal_seq(c, m));
939         } else {
940                 size_t b2;
941
942                 /* remove from free_inc: */
943                 percpu_down_read(&c->mark_lock);
944                 spin_lock(&c->freelist_lock);
945
946                 bch2_mark_alloc_bucket(c, ca, b, false,
947                                        gc_pos_alloc(c, NULL), 0);
948
949                 BUG_ON(!fifo_pop_back(&ca->free_inc, b2));
950                 BUG_ON(b != b2);
951
952                 spin_unlock(&c->freelist_lock);
953                 percpu_up_read(&c->mark_lock);
954         }
955
956         return ret;
957 }
958
959 static bool bch2_invalidate_one_bucket(struct bch_fs *c, struct bch_dev *ca,
960                                        size_t bucket, u64 *flush_seq)
961 {
962         struct bucket_mark m;
963
964         percpu_down_read(&c->mark_lock);
965         spin_lock(&c->freelist_lock);
966
967         bch2_invalidate_bucket(c, ca, bucket, &m);
968
969         verify_not_on_freelist(c, ca, bucket);
970         BUG_ON(!fifo_push(&ca->free_inc, bucket));
971
972         spin_unlock(&c->freelist_lock);
973
974         bucket_io_clock_reset(c, ca, bucket, READ);
975         bucket_io_clock_reset(c, ca, bucket, WRITE);
976
977         percpu_up_read(&c->mark_lock);
978
979         *flush_seq = max(*flush_seq, bucket_journal_seq(c, m));
980
981         return m.cached_sectors != 0;
982 }
983
984 /*
985  * Pull buckets off ca->alloc_heap, invalidate them, move them to ca->free_inc:
986  */
987 static int bch2_invalidate_buckets(struct bch_fs *c, struct bch_dev *ca)
988 {
989         struct btree_trans trans;
990         struct btree_iter *iter;
991         u64 journal_seq = 0;
992         int ret = 0;
993
994         bch2_trans_init(&trans, c, 0, 0);
995
996         iter = bch2_trans_get_iter(&trans, BTREE_ID_ALLOC,
997                                    POS(ca->dev_idx, 0),
998                                    BTREE_ITER_SLOTS|BTREE_ITER_INTENT);
999
1000         /* Only use nowait if we've already invalidated at least one bucket: */
1001         while (!ret &&
1002                !fifo_full(&ca->free_inc) &&
1003                ca->alloc_heap.used)
1004                 ret = bch2_invalidate_one_bucket2(&trans, ca, iter, &journal_seq,
1005                                 BTREE_INSERT_GC_LOCK_HELD|
1006                                 (!fifo_empty(&ca->free_inc)
1007                                  ? BTREE_INSERT_NOWAIT : 0));
1008
1009         bch2_trans_exit(&trans);
1010
1011         /* If we used NOWAIT, don't return the error: */
1012         if (!fifo_empty(&ca->free_inc))
1013                 ret = 0;
1014         if (ret) {
1015                 bch_err(ca, "error invalidating buckets: %i", ret);
1016                 return ret;
1017         }
1018
1019         if (journal_seq)
1020                 ret = bch2_journal_flush_seq(&c->journal, journal_seq);
1021         if (ret) {
1022                 bch_err(ca, "journal error: %i", ret);
1023                 return ret;
1024         }
1025
1026         return 0;
1027 }
1028
1029 static int push_invalidated_bucket(struct bch_fs *c, struct bch_dev *ca, size_t bucket)
1030 {
1031         unsigned i;
1032         int ret = 0;
1033
1034         while (1) {
1035                 set_current_state(TASK_INTERRUPTIBLE);
1036
1037                 spin_lock(&c->freelist_lock);
1038                 for (i = 0; i < RESERVE_NR; i++) {
1039
1040                         /*
1041                          * Don't strand buckets on the copygc freelist until
1042                          * after recovery is finished:
1043                          */
1044                         if (!test_bit(BCH_FS_STARTED, &c->flags) &&
1045                             i == RESERVE_MOVINGGC)
1046                                 continue;
1047
1048                         if (fifo_push(&ca->free[i], bucket)) {
1049                                 fifo_pop(&ca->free_inc, bucket);
1050
1051                                 closure_wake_up(&c->freelist_wait);
1052                                 ca->allocator_state = ALLOCATOR_RUNNING;
1053
1054                                 spin_unlock(&c->freelist_lock);
1055                                 goto out;
1056                         }
1057                 }
1058
1059                 if (ca->allocator_state != ALLOCATOR_BLOCKED_FULL) {
1060                         ca->allocator_state = ALLOCATOR_BLOCKED_FULL;
1061                         closure_wake_up(&c->freelist_wait);
1062                 }
1063
1064                 spin_unlock(&c->freelist_lock);
1065
1066                 if ((current->flags & PF_KTHREAD) &&
1067                     kthread_should_stop()) {
1068                         ret = 1;
1069                         break;
1070                 }
1071
1072                 schedule();
1073                 try_to_freeze();
1074         }
1075 out:
1076         __set_current_state(TASK_RUNNING);
1077         return ret;
1078 }
1079
1080 /*
1081  * Pulls buckets off free_inc, discards them (if enabled), then adds them to
1082  * freelists, waiting until there's room if necessary:
1083  */
1084 static int discard_invalidated_buckets(struct bch_fs *c, struct bch_dev *ca)
1085 {
1086         while (!fifo_empty(&ca->free_inc)) {
1087                 size_t bucket = fifo_peek(&ca->free_inc);
1088
1089                 if (ca->mi.discard &&
1090                     blk_queue_discard(bdev_get_queue(ca->disk_sb.bdev)))
1091                         blkdev_issue_discard(ca->disk_sb.bdev,
1092                                              bucket_to_sector(ca, bucket),
1093                                              ca->mi.bucket_size, GFP_NOIO, 0);
1094
1095                 if (push_invalidated_bucket(c, ca, bucket))
1096                         return 1;
1097         }
1098
1099         return 0;
1100 }
1101
1102 /**
1103  * bch_allocator_thread - move buckets from free_inc to reserves
1104  *
1105  * The free_inc FIFO is populated by find_reclaimable_buckets(), and
1106  * the reserves are depleted by bucket allocation. When we run out
1107  * of free_inc, try to invalidate some buckets and write out
1108  * prios and gens.
1109  */
1110 static int bch2_allocator_thread(void *arg)
1111 {
1112         struct bch_dev *ca = arg;
1113         struct bch_fs *c = ca->fs;
1114         size_t nr;
1115         int ret;
1116
1117         set_freezable();
1118         ca->allocator_state = ALLOCATOR_RUNNING;
1119
1120         while (1) {
1121                 cond_resched();
1122
1123                 pr_debug("discarding %zu invalidated buckets",
1124                          fifo_used(&ca->free_inc));
1125
1126                 ret = discard_invalidated_buckets(c, ca);
1127                 if (ret)
1128                         goto stop;
1129
1130                 down_read(&c->gc_lock);
1131
1132                 ret = bch2_invalidate_buckets(c, ca);
1133                 if (ret) {
1134                         up_read(&c->gc_lock);
1135                         goto stop;
1136                 }
1137
1138                 if (!fifo_empty(&ca->free_inc)) {
1139                         up_read(&c->gc_lock);
1140                         continue;
1141                 }
1142
1143                 pr_debug("free_inc now empty");
1144
1145                 do {
1146                         /*
1147                          * Find some buckets that we can invalidate, either
1148                          * they're completely unused, or only contain clean data
1149                          * that's been written back to the backing device or
1150                          * another cache tier
1151                          */
1152
1153                         pr_debug("scanning for reclaimable buckets");
1154
1155                         nr = find_reclaimable_buckets(c, ca);
1156
1157                         pr_debug("found %zu buckets", nr);
1158
1159                         trace_alloc_batch(ca, nr, ca->alloc_heap.size);
1160
1161                         if ((ca->inc_gen_needs_gc >= ALLOC_SCAN_BATCH(ca) ||
1162                              ca->inc_gen_really_needs_gc) &&
1163                             c->gc_thread) {
1164                                 atomic_inc(&c->kick_gc);
1165                                 wake_up_process(c->gc_thread);
1166                         }
1167
1168                         /*
1169                          * If we found any buckets, we have to invalidate them
1170                          * before we scan for more - but if we didn't find very
1171                          * many we may want to wait on more buckets being
1172                          * available so we don't spin:
1173                          */
1174                         if (!nr ||
1175                             (nr < ALLOC_SCAN_BATCH(ca) &&
1176                              !fifo_empty(&ca->free[RESERVE_NONE]))) {
1177                                 ret = wait_buckets_available(c, ca);
1178                                 if (ret) {
1179                                         up_read(&c->gc_lock);
1180                                         goto stop;
1181                                 }
1182                         }
1183                 } while (!nr);
1184
1185                 up_read(&c->gc_lock);
1186
1187                 pr_debug("%zu buckets to invalidate", nr);
1188
1189                 /*
1190                  * alloc_heap is now full of newly-invalidated buckets: next,
1191                  * write out the new bucket gens:
1192                  */
1193         }
1194
1195 stop:
1196         pr_debug("alloc thread stopping (ret %i)", ret);
1197         ca->allocator_state = ALLOCATOR_STOPPED;
1198         closure_wake_up(&c->freelist_wait);
1199         return 0;
1200 }
1201
1202 /* Startup/shutdown (ro/rw): */
1203
1204 void bch2_recalc_capacity(struct bch_fs *c)
1205 {
1206         struct bch_dev *ca;
1207         u64 capacity = 0, reserved_sectors = 0, gc_reserve;
1208         unsigned bucket_size_max = 0;
1209         unsigned long ra_pages = 0;
1210         unsigned i, j;
1211
1212         lockdep_assert_held(&c->state_lock);
1213
1214         for_each_online_member(ca, c, i) {
1215                 struct backing_dev_info *bdi = ca->disk_sb.bdev->bd_bdi;
1216
1217                 ra_pages += bdi->ra_pages;
1218         }
1219
1220         bch2_set_ra_pages(c, ra_pages);
1221
1222         for_each_rw_member(ca, c, i) {
1223                 u64 dev_reserve = 0;
1224
1225                 /*
1226                  * We need to reserve buckets (from the number
1227                  * of currently available buckets) against
1228                  * foreground writes so that mainly copygc can
1229                  * make forward progress.
1230                  *
1231                  * We need enough to refill the various reserves
1232                  * from scratch - copygc will use its entire
1233                  * reserve all at once, then run against when
1234                  * its reserve is refilled (from the formerly
1235                  * available buckets).
1236                  *
1237                  * This reserve is just used when considering if
1238                  * allocations for foreground writes must wait -
1239                  * not -ENOSPC calculations.
1240                  */
1241                 for (j = 0; j < RESERVE_NONE; j++)
1242                         dev_reserve += ca->free[j].size;
1243
1244                 dev_reserve += 1;       /* btree write point */
1245                 dev_reserve += 1;       /* copygc write point */
1246                 dev_reserve += 1;       /* rebalance write point */
1247
1248                 dev_reserve *= ca->mi.bucket_size;
1249
1250                 ca->copygc_threshold = dev_reserve;
1251
1252                 capacity += bucket_to_sector(ca, ca->mi.nbuckets -
1253                                              ca->mi.first_bucket);
1254
1255                 reserved_sectors += dev_reserve * 2;
1256
1257                 bucket_size_max = max_t(unsigned, bucket_size_max,
1258                                         ca->mi.bucket_size);
1259         }
1260
1261         gc_reserve = c->opts.gc_reserve_bytes
1262                 ? c->opts.gc_reserve_bytes >> 9
1263                 : div64_u64(capacity * c->opts.gc_reserve_percent, 100);
1264
1265         reserved_sectors = max(gc_reserve, reserved_sectors);
1266
1267         reserved_sectors = min(reserved_sectors, capacity);
1268
1269         c->capacity = capacity - reserved_sectors;
1270
1271         c->bucket_size_max = bucket_size_max;
1272
1273         if (c->capacity) {
1274                 bch2_io_timer_add(&c->io_clock[READ],
1275                                  &c->bucket_clock[READ].rescale);
1276                 bch2_io_timer_add(&c->io_clock[WRITE],
1277                                  &c->bucket_clock[WRITE].rescale);
1278         } else {
1279                 bch2_io_timer_del(&c->io_clock[READ],
1280                                  &c->bucket_clock[READ].rescale);
1281                 bch2_io_timer_del(&c->io_clock[WRITE],
1282                                  &c->bucket_clock[WRITE].rescale);
1283         }
1284
1285         /* Wake up case someone was waiting for buckets */
1286         closure_wake_up(&c->freelist_wait);
1287 }
1288
1289 static bool bch2_dev_has_open_write_point(struct bch_fs *c, struct bch_dev *ca)
1290 {
1291         struct open_bucket *ob;
1292         bool ret = false;
1293
1294         for (ob = c->open_buckets;
1295              ob < c->open_buckets + ARRAY_SIZE(c->open_buckets);
1296              ob++) {
1297                 spin_lock(&ob->lock);
1298                 if (ob->valid && !ob->on_partial_list &&
1299                     ob->ptr.dev == ca->dev_idx)
1300                         ret = true;
1301                 spin_unlock(&ob->lock);
1302         }
1303
1304         return ret;
1305 }
1306
1307 /* device goes ro: */
1308 void bch2_dev_allocator_remove(struct bch_fs *c, struct bch_dev *ca)
1309 {
1310         unsigned i;
1311
1312         BUG_ON(ca->alloc_thread);
1313
1314         /* First, remove device from allocation groups: */
1315
1316         for (i = 0; i < ARRAY_SIZE(c->rw_devs); i++)
1317                 clear_bit(ca->dev_idx, c->rw_devs[i].d);
1318
1319         /*
1320          * Capacity is calculated based off of devices in allocation groups:
1321          */
1322         bch2_recalc_capacity(c);
1323
1324         /* Next, close write points that point to this device... */
1325         for (i = 0; i < ARRAY_SIZE(c->write_points); i++)
1326                 bch2_writepoint_stop(c, ca, &c->write_points[i]);
1327
1328         bch2_writepoint_stop(c, ca, &ca->copygc_write_point);
1329         bch2_writepoint_stop(c, ca, &c->rebalance_write_point);
1330         bch2_writepoint_stop(c, ca, &c->btree_write_point);
1331
1332         mutex_lock(&c->btree_reserve_cache_lock);
1333         while (c->btree_reserve_cache_nr) {
1334                 struct btree_alloc *a =
1335                         &c->btree_reserve_cache[--c->btree_reserve_cache_nr];
1336
1337                 bch2_open_buckets_put(c, &a->ob);
1338         }
1339         mutex_unlock(&c->btree_reserve_cache_lock);
1340
1341         while (1) {
1342                 struct open_bucket *ob;
1343
1344                 spin_lock(&c->freelist_lock);
1345                 if (!ca->open_buckets_partial_nr) {
1346                         spin_unlock(&c->freelist_lock);
1347                         break;
1348                 }
1349                 ob = c->open_buckets +
1350                         ca->open_buckets_partial[--ca->open_buckets_partial_nr];
1351                 ob->on_partial_list = false;
1352                 spin_unlock(&c->freelist_lock);
1353
1354                 bch2_open_bucket_put(c, ob);
1355         }
1356
1357         bch2_ec_stop_dev(c, ca);
1358
1359         /*
1360          * Wake up threads that were blocked on allocation, so they can notice
1361          * the device can no longer be removed and the capacity has changed:
1362          */
1363         closure_wake_up(&c->freelist_wait);
1364
1365         /*
1366          * journal_res_get() can block waiting for free space in the journal -
1367          * it needs to notice there may not be devices to allocate from anymore:
1368          */
1369         wake_up(&c->journal.wait);
1370
1371         /* Now wait for any in flight writes: */
1372
1373         closure_wait_event(&c->open_buckets_wait,
1374                            !bch2_dev_has_open_write_point(c, ca));
1375 }
1376
1377 /* device goes rw: */
1378 void bch2_dev_allocator_add(struct bch_fs *c, struct bch_dev *ca)
1379 {
1380         unsigned i;
1381
1382         for (i = 0; i < ARRAY_SIZE(c->rw_devs); i++)
1383                 if (ca->mi.data_allowed & (1 << i))
1384                         set_bit(ca->dev_idx, c->rw_devs[i].d);
1385 }
1386
1387 void bch2_dev_allocator_quiesce(struct bch_fs *c, struct bch_dev *ca)
1388 {
1389         if (ca->alloc_thread)
1390                 closure_wait_event(&c->freelist_wait,
1391                                    ca->allocator_state != ALLOCATOR_RUNNING);
1392 }
1393
1394 /* stop allocator thread: */
1395 void bch2_dev_allocator_stop(struct bch_dev *ca)
1396 {
1397         struct task_struct *p;
1398
1399         p = rcu_dereference_protected(ca->alloc_thread, 1);
1400         ca->alloc_thread = NULL;
1401
1402         /*
1403          * We need an rcu barrier between setting ca->alloc_thread = NULL and
1404          * the thread shutting down to avoid bch2_wake_allocator() racing:
1405          *
1406          * XXX: it would be better to have the rcu barrier be asynchronous
1407          * instead of blocking us here
1408          */
1409         synchronize_rcu();
1410
1411         if (p) {
1412                 kthread_stop(p);
1413                 put_task_struct(p);
1414         }
1415 }
1416
1417 /* start allocator thread: */
1418 int bch2_dev_allocator_start(struct bch_dev *ca)
1419 {
1420         struct task_struct *p;
1421
1422         /*
1423          * allocator thread already started?
1424          */
1425         if (ca->alloc_thread)
1426                 return 0;
1427
1428         p = kthread_create(bch2_allocator_thread, ca,
1429                            "bch_alloc[%s]", ca->name);
1430         if (IS_ERR(p))
1431                 return PTR_ERR(p);
1432
1433         get_task_struct(p);
1434         rcu_assign_pointer(ca->alloc_thread, p);
1435         wake_up_process(p);
1436         return 0;
1437 }
1438
1439 static bool flush_held_btree_writes(struct bch_fs *c)
1440 {
1441         struct bucket_table *tbl;
1442         struct rhash_head *pos;
1443         struct btree *b;
1444         bool nodes_unwritten;
1445         size_t i;
1446 again:
1447         cond_resched();
1448         nodes_unwritten = false;
1449
1450         if (bch2_journal_error(&c->journal))
1451                 return true;
1452
1453         rcu_read_lock();
1454         for_each_cached_btree(b, c, tbl, i, pos)
1455                 if (btree_node_need_write(b)) {
1456                         if (btree_node_may_write(b)) {
1457                                 rcu_read_unlock();
1458                                 btree_node_lock_type(c, b, SIX_LOCK_read);
1459                                 bch2_btree_node_write(c, b, SIX_LOCK_read);
1460                                 six_unlock_read(&b->lock);
1461                                 goto again;
1462                         } else {
1463                                 nodes_unwritten = true;
1464                         }
1465                 }
1466         rcu_read_unlock();
1467
1468         if (c->btree_roots_dirty) {
1469                 bch2_journal_meta(&c->journal);
1470                 goto again;
1471         }
1472
1473         return !nodes_unwritten &&
1474                 !bch2_btree_interior_updates_nr_pending(c);
1475 }
1476
1477 static void allocator_start_issue_discards(struct bch_fs *c)
1478 {
1479         struct bch_dev *ca;
1480         unsigned dev_iter;
1481         size_t bu;
1482
1483         for_each_rw_member(ca, c, dev_iter)
1484                 while (fifo_pop(&ca->free_inc, bu))
1485                         blkdev_issue_discard(ca->disk_sb.bdev,
1486                                              bucket_to_sector(ca, bu),
1487                                              ca->mi.bucket_size, GFP_NOIO, 0);
1488 }
1489
1490 static int resize_free_inc(struct bch_dev *ca)
1491 {
1492         alloc_fifo free_inc;
1493
1494         if (!fifo_full(&ca->free_inc))
1495                 return 0;
1496
1497         if (!init_fifo(&free_inc,
1498                        ca->free_inc.size * 2,
1499                        GFP_KERNEL))
1500                 return -ENOMEM;
1501
1502         fifo_move(&free_inc, &ca->free_inc);
1503         swap(free_inc, ca->free_inc);
1504         free_fifo(&free_inc);
1505         return 0;
1506 }
1507
1508 static bool bch2_fs_allocator_start_fast(struct bch_fs *c)
1509 {
1510         struct bch_dev *ca;
1511         unsigned dev_iter;
1512         bool ret = true;
1513
1514         if (test_alloc_startup(c))
1515                 return false;
1516
1517         down_read(&c->gc_lock);
1518
1519         /* Scan for buckets that are already invalidated: */
1520         for_each_rw_member(ca, c, dev_iter) {
1521                 struct bucket_array *buckets;
1522                 struct bucket_mark m;
1523                 long bu;
1524
1525                 down_read(&ca->bucket_lock);
1526                 buckets = bucket_array(ca);
1527
1528                 for (bu = buckets->first_bucket;
1529                      bu < buckets->nbuckets; bu++) {
1530                         m = READ_ONCE(buckets->b[bu].mark);
1531
1532                         if (!buckets->b[bu].gen_valid ||
1533                             !is_available_bucket(m) ||
1534                             m.cached_sectors ||
1535                             (ca->buckets_nouse &&
1536                              test_bit(bu, ca->buckets_nouse)))
1537                                 continue;
1538
1539                         percpu_down_read(&c->mark_lock);
1540                         bch2_mark_alloc_bucket(c, ca, bu, true,
1541                                         gc_pos_alloc(c, NULL), 0);
1542                         percpu_up_read(&c->mark_lock);
1543
1544                         fifo_push(&ca->free_inc, bu);
1545
1546                         discard_invalidated_buckets(c, ca);
1547
1548                         if (fifo_full(&ca->free[RESERVE_BTREE]))
1549                                 break;
1550                 }
1551                 up_read(&ca->bucket_lock);
1552         }
1553
1554         up_read(&c->gc_lock);
1555
1556         /* did we find enough buckets? */
1557         for_each_rw_member(ca, c, dev_iter)
1558                 if (!fifo_full(&ca->free[RESERVE_BTREE]))
1559                         ret = false;
1560
1561         return ret;
1562 }
1563
1564 int bch2_fs_allocator_start(struct bch_fs *c)
1565 {
1566         struct bch_dev *ca;
1567         unsigned dev_iter;
1568         u64 journal_seq = 0;
1569         bool wrote;
1570         long bu;
1571         int ret = 0;
1572
1573         if (!test_alloc_startup(c) &&
1574             bch2_fs_allocator_start_fast(c))
1575                 return 0;
1576
1577         pr_debug("not enough empty buckets; scanning for reclaimable buckets");
1578
1579         /*
1580          * We're moving buckets to freelists _before_ they've been marked as
1581          * invalidated on disk - we have to so that we can allocate new btree
1582          * nodes to mark them as invalidated on disk.
1583          *
1584          * However, we can't _write_ to any of these buckets yet - they might
1585          * have cached data in them, which is live until they're marked as
1586          * invalidated on disk:
1587          */
1588         set_bit(BCH_FS_HOLD_BTREE_WRITES, &c->flags);
1589
1590         down_read(&c->gc_lock);
1591         do {
1592                 wrote = false;
1593
1594                 for_each_rw_member(ca, c, dev_iter) {
1595                         find_reclaimable_buckets(c, ca);
1596
1597                         while (!fifo_full(&ca->free[RESERVE_BTREE]) &&
1598                                (bu = next_alloc_bucket(ca)) >= 0) {
1599                                 ret = resize_free_inc(ca);
1600                                 if (ret) {
1601                                         percpu_ref_put(&ca->io_ref);
1602                                         up_read(&c->gc_lock);
1603                                         goto err;
1604                                 }
1605
1606                                 bch2_invalidate_one_bucket(c, ca, bu,
1607                                                            &journal_seq);
1608
1609                                 fifo_push(&ca->free[RESERVE_BTREE], bu);
1610                         }
1611                 }
1612
1613                 pr_debug("done scanning for reclaimable buckets");
1614
1615                 /*
1616                  * XXX: it's possible for this to deadlock waiting on journal reclaim,
1617                  * since we're holding btree writes. What then?
1618                  */
1619                 ret = bch2_alloc_write(c,
1620                                        BTREE_INSERT_NOCHECK_RW|
1621                                        BTREE_INSERT_USE_ALLOC_RESERVE|
1622                                        BTREE_INSERT_NOWAIT, &wrote);
1623
1624                 /*
1625                  * If bch2_alloc_write() did anything, it may have used some
1626                  * buckets, and we need the RESERVE_BTREE freelist full - so we
1627                  * need to loop and scan again.
1628                  * And if it errored, it may have been because there weren't
1629                  * enough buckets, so just scan and loop again as long as it
1630                  * made some progress:
1631                  */
1632         } while (wrote);
1633         up_read(&c->gc_lock);
1634
1635         if (ret)
1636                 goto err;
1637
1638         pr_debug("flushing journal");
1639
1640         ret = bch2_journal_flush(&c->journal);
1641         if (ret)
1642                 goto err;
1643
1644         pr_debug("issuing discards");
1645         allocator_start_issue_discards(c);
1646 err:
1647         clear_bit(BCH_FS_HOLD_BTREE_WRITES, &c->flags);
1648         closure_wait_event(&c->btree_interior_update_wait,
1649                            flush_held_btree_writes(c));
1650
1651         return ret;
1652 }
1653
1654 void bch2_fs_allocator_background_init(struct bch_fs *c)
1655 {
1656         spin_lock_init(&c->freelist_lock);
1657         bch2_bucket_clock_init(c, READ);
1658         bch2_bucket_clock_init(c, WRITE);
1659
1660         c->pd_controllers_update_seconds = 5;
1661         INIT_DELAYED_WORK(&c->pd_controllers_update, pd_controllers_update);
1662 }