]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/movinggc.c
4834f41f48edd4d5ba54a43e573155bcc4bed379
[bcachefs-tools-debian] / libbcachefs / movinggc.c
1 // SPDX-License-Identifier: GPL-2.0
2 /*
3  * Moving/copying garbage collector
4  *
5  * Copyright 2012 Google, Inc.
6  */
7
8 #include "bcachefs.h"
9 #include "alloc_foreground.h"
10 #include "btree_iter.h"
11 #include "btree_update.h"
12 #include "buckets.h"
13 #include "clock.h"
14 #include "disk_groups.h"
15 #include "error.h"
16 #include "extents.h"
17 #include "eytzinger.h"
18 #include "io.h"
19 #include "keylist.h"
20 #include "move.h"
21 #include "movinggc.h"
22 #include "super-io.h"
23
24 #include <trace/events/bcachefs.h>
25 #include <linux/freezer.h>
26 #include <linux/kthread.h>
27 #include <linux/math64.h>
28 #include <linux/sched/task.h>
29 #include <linux/sort.h>
30 #include <linux/wait.h>
31
32 /*
33  * We can't use the entire copygc reserve in one iteration of copygc: we may
34  * need the buckets we're freeing up to go back into the copygc reserve to make
35  * forward progress, but if the copygc reserve is full they'll be available for
36  * any allocation - and it's possible that in a given iteration, we free up most
37  * of the buckets we're going to free before we allocate most of the buckets
38  * we're going to allocate.
39  *
40  * If we only use half of the reserve per iteration, then in steady state we'll
41  * always have room in the reserve for the buckets we're going to need in the
42  * next iteration:
43  */
44 #define COPYGC_BUCKETS_PER_ITER(ca)                                     \
45         ((ca)->free[RESERVE_MOVINGGC].size / 2)
46
47 static int bucket_offset_cmp(const void *_l, const void *_r, size_t size)
48 {
49         const struct copygc_heap_entry *l = _l;
50         const struct copygc_heap_entry *r = _r;
51
52         return  cmp_int(l->dev,    r->dev) ?:
53                 cmp_int(l->offset, r->offset);
54 }
55
56 static enum data_cmd copygc_pred(struct bch_fs *c, void *arg,
57                                  struct bkey_s_c k,
58                                  struct bch_io_opts *io_opts,
59                                  struct data_opts *data_opts)
60 {
61         copygc_heap *h = &c->copygc_heap;
62         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
63         const union bch_extent_entry *entry;
64         struct extent_ptr_decoded p;
65
66         bkey_for_each_ptr_decode(k.k, ptrs, p, entry) {
67                 struct bch_dev *ca = bch_dev_bkey_exists(c, p.ptr.dev);
68                 struct copygc_heap_entry search = {
69                         .dev    = p.ptr.dev,
70                         .offset = p.ptr.offset,
71                 };
72
73                 ssize_t i = eytzinger0_find_le(h->data, h->used,
74                                                sizeof(h->data[0]),
75                                                bucket_offset_cmp, &search);
76 #if 0
77                 /* eytzinger search verify code: */
78                 ssize_t j = -1, k;
79
80                 for (k = 0; k < h->used; k++)
81                         if (h->data[k].offset <= ptr->offset &&
82                             (j < 0 || h->data[k].offset > h->data[j].offset))
83                                 j = k;
84
85                 BUG_ON(i != j);
86 #endif
87                 if (i >= 0 &&
88                     p.ptr.offset < h->data[i].offset + ca->mi.bucket_size &&
89                     p.ptr.gen == h->data[i].gen) {
90                         data_opts->target               = io_opts->background_target;
91                         data_opts->nr_replicas          = 1;
92                         data_opts->btree_insert_flags   = BTREE_INSERT_USE_RESERVE;
93                         data_opts->rewrite_dev          = p.ptr.dev;
94
95                         if (p.has_ec) {
96                                 struct stripe *m = genradix_ptr(&c->stripes[0], p.ec.idx);
97
98                                 data_opts->nr_replicas += m->nr_redundant;
99                         }
100
101                         return DATA_REWRITE;
102                 }
103         }
104
105         return DATA_SKIP;
106 }
107
108 static bool have_copygc_reserve(struct bch_dev *ca)
109 {
110         bool ret;
111
112         spin_lock(&ca->fs->freelist_lock);
113         ret = fifo_full(&ca->free[RESERVE_MOVINGGC]) ||
114                 ca->allocator_state != ALLOCATOR_RUNNING;
115         spin_unlock(&ca->fs->freelist_lock);
116
117         return ret;
118 }
119
120 static inline int fragmentation_cmp(copygc_heap *heap,
121                                    struct copygc_heap_entry l,
122                                    struct copygc_heap_entry r)
123 {
124         return cmp_int(l.fragmentation, r.fragmentation);
125 }
126
127 static int bch2_copygc(struct bch_fs *c)
128 {
129         copygc_heap *h = &c->copygc_heap;
130         struct copygc_heap_entry e, *i;
131         struct bucket_array *buckets;
132         struct bch_move_stats move_stats;
133         u64 sectors_to_move = 0, sectors_not_moved = 0;
134         u64 sectors_reserved = 0;
135         u64 buckets_to_move, buckets_not_moved = 0;
136         struct bch_dev *ca;
137         unsigned dev_idx;
138         size_t b, heap_size = 0;
139         int ret;
140
141         memset(&move_stats, 0, sizeof(move_stats));
142         /*
143          * Find buckets with lowest sector counts, skipping completely
144          * empty buckets, by building a maxheap sorted by sector count,
145          * and repeatedly replacing the maximum element until all
146          * buckets have been visited.
147          */
148         h->used = 0;
149
150         for_each_rw_member(ca, c, dev_idx)
151                 heap_size += ca->mi.nbuckets >> 7;
152
153         if (h->size < heap_size) {
154                 free_heap(&c->copygc_heap);
155                 if (!init_heap(&c->copygc_heap, heap_size, GFP_KERNEL)) {
156                         bch_err(c, "error allocating copygc heap");
157                         return 0;
158                 }
159         }
160
161         for_each_rw_member(ca, c, dev_idx) {
162                 closure_wait_event(&c->freelist_wait, have_copygc_reserve(ca));
163
164                 spin_lock(&ca->fs->freelist_lock);
165                 sectors_reserved += fifo_used(&ca->free[RESERVE_MOVINGGC]) * ca->mi.bucket_size;
166                 spin_unlock(&ca->fs->freelist_lock);
167
168                 down_read(&ca->bucket_lock);
169                 buckets = bucket_array(ca);
170
171                 for (b = buckets->first_bucket; b < buckets->nbuckets; b++) {
172                         struct bucket *g = buckets->b + b;
173                         struct bucket_mark m = READ_ONCE(g->mark);
174                         struct copygc_heap_entry e;
175
176                         if (m.owned_by_allocator ||
177                             m.data_type != BCH_DATA_user ||
178                             !bucket_sectors_used(m) ||
179                             bucket_sectors_used(m) >= ca->mi.bucket_size)
180                                 continue;
181
182                         WARN_ON(m.stripe && !g->ec_redundancy);
183
184                         e = (struct copygc_heap_entry) {
185                                 .dev            = dev_idx,
186                                 .gen            = m.gen,
187                                 .replicas       = 1 + g->ec_redundancy,
188                                 .fragmentation  = bucket_sectors_used(m) * (1U << 15)
189                                         / ca->mi.bucket_size,
190                                 .sectors        = bucket_sectors_used(m),
191                                 .offset         = bucket_to_sector(ca, b),
192                         };
193                         heap_add_or_replace(h, e, -fragmentation_cmp, NULL);
194                 }
195                 up_read(&ca->bucket_lock);
196         }
197
198         if (!sectors_reserved) {
199                 bch2_fs_fatal_error(c, "stuck, ran out of copygc reserve!");
200                 return -1;
201         }
202
203         for (i = h->data; i < h->data + h->used; i++)
204                 sectors_to_move += i->sectors * i->replicas;
205
206         while (sectors_to_move > sectors_reserved) {
207                 BUG_ON(!heap_pop(h, e, -fragmentation_cmp, NULL));
208                 sectors_to_move -= e.sectors * e.replicas;
209         }
210
211         buckets_to_move = h->used;
212
213         if (!buckets_to_move)
214                 return 0;
215
216         eytzinger0_sort(h->data, h->used,
217                         sizeof(h->data[0]),
218                         bucket_offset_cmp, NULL);
219
220         ret = bch2_move_data(c, &c->copygc_pd.rate,
221                              writepoint_ptr(&c->copygc_write_point),
222                              POS_MIN, POS_MAX,
223                              copygc_pred, NULL,
224                              &move_stats);
225
226         for_each_rw_member(ca, c, dev_idx) {
227                 down_read(&ca->bucket_lock);
228                 buckets = bucket_array(ca);
229                 for (i = h->data; i < h->data + h->used; i++) {
230                         struct bucket_mark m;
231                         size_t b;
232
233                         if (i->dev != dev_idx)
234                                 continue;
235
236                         b = sector_to_bucket(ca, i->offset);
237                         m = READ_ONCE(buckets->b[b].mark);
238
239                         if (i->gen == m.gen &&
240                             bucket_sectors_used(m)) {
241                                 sectors_not_moved += bucket_sectors_used(m);
242                                 buckets_not_moved++;
243                         }
244                 }
245                 up_read(&ca->bucket_lock);
246         }
247
248         if (sectors_not_moved && !ret)
249                 bch_warn_ratelimited(c,
250                         "copygc finished but %llu/%llu sectors, %llu/%llu buckets not moved (move stats: moved %llu sectors, raced %llu keys, %llu sectors)",
251                          sectors_not_moved, sectors_to_move,
252                          buckets_not_moved, buckets_to_move,
253                          atomic64_read(&move_stats.sectors_moved),
254                          atomic64_read(&move_stats.keys_raced),
255                          atomic64_read(&move_stats.sectors_raced));
256
257         trace_copygc(c,
258                      atomic64_read(&move_stats.sectors_moved), sectors_not_moved,
259                      buckets_to_move, buckets_not_moved);
260         return 0;
261 }
262
263 /*
264  * Copygc runs when the amount of fragmented data is above some arbitrary
265  * threshold:
266  *
267  * The threshold at the limit - when the device is full - is the amount of space
268  * we reserved in bch2_recalc_capacity; we can't have more than that amount of
269  * disk space stranded due to fragmentation and store everything we have
270  * promised to store.
271  *
272  * But we don't want to be running copygc unnecessarily when the device still
273  * has plenty of free space - rather, we want copygc to smoothly run every so
274  * often and continually reduce the amount of fragmented space as the device
275  * fills up. So, we increase the threshold by half the current free space.
276  */
277 unsigned long bch2_copygc_wait_amount(struct bch_fs *c)
278 {
279         struct bch_dev *ca;
280         unsigned dev_idx;
281         u64 fragmented_allowed = c->copygc_threshold;
282         u64 fragmented = 0;
283
284         for_each_rw_member(ca, c, dev_idx) {
285                 struct bch_dev_usage usage = bch2_dev_usage_read(ca);
286
287                 fragmented_allowed += ((__dev_buckets_available(ca, usage) *
288                                         ca->mi.bucket_size) >> 1);
289                 fragmented += usage.sectors_fragmented;
290         }
291
292         return max_t(s64, 0, fragmented_allowed - fragmented);
293 }
294
295 static int bch2_copygc_thread(void *arg)
296 {
297         struct bch_fs *c = arg;
298         struct io_clock *clock = &c->io_clock[WRITE];
299         unsigned long last, wait;
300
301         set_freezable();
302
303         while (!kthread_should_stop()) {
304                 if (kthread_wait_freezable(c->copy_gc_enabled))
305                         break;
306
307                 last = atomic_long_read(&clock->now);
308                 wait = bch2_copygc_wait_amount(c);
309
310                 if (wait > clock->max_slop) {
311                         bch2_kthread_io_clock_wait(clock, last + wait,
312                                         MAX_SCHEDULE_TIMEOUT);
313                         continue;
314                 }
315
316                 if (bch2_copygc(c))
317                         break;
318         }
319
320         return 0;
321 }
322
323 void bch2_copygc_stop(struct bch_fs *c)
324 {
325         c->copygc_pd.rate.rate = UINT_MAX;
326         bch2_ratelimit_reset(&c->copygc_pd.rate);
327
328         if (c->copygc_thread) {
329                 kthread_stop(c->copygc_thread);
330                 put_task_struct(c->copygc_thread);
331         }
332         c->copygc_thread = NULL;
333 }
334
335 int bch2_copygc_start(struct bch_fs *c)
336 {
337         struct task_struct *t;
338
339         if (c->copygc_thread)
340                 return 0;
341
342         if (c->opts.nochanges)
343                 return 0;
344
345         if (bch2_fs_init_fault("copygc_start"))
346                 return -ENOMEM;
347
348         t = kthread_create(bch2_copygc_thread, c, "bch-copygc/%s", c->name);
349         if (IS_ERR(t))
350                 return PTR_ERR(t);
351
352         get_task_struct(t);
353
354         c->copygc_thread = t;
355         wake_up_process(c->copygc_thread);
356
357         return 0;
358 }
359
360 void bch2_fs_copygc_init(struct bch_fs *c)
361 {
362         bch2_pd_controller_init(&c->copygc_pd);
363         c->copygc_pd.d_term = 0;
364 }