]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/movinggc.c
e9cb2304576fdf3db2559c04d137e8e5df00efda
[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 "extents.h"
16 #include "eytzinger.h"
17 #include "io.h"
18 #include "keylist.h"
19 #include "move.h"
20 #include "movinggc.h"
21 #include "super-io.h"
22
23 #include <trace/events/bcachefs.h>
24 #include <linux/freezer.h>
25 #include <linux/kthread.h>
26 #include <linux/math64.h>
27 #include <linux/sched/task.h>
28 #include <linux/sort.h>
29 #include <linux/wait.h>
30
31 /*
32  * We can't use the entire copygc reserve in one iteration of copygc: we may
33  * need the buckets we're freeing up to go back into the copygc reserve to make
34  * forward progress, but if the copygc reserve is full they'll be available for
35  * any allocation - and it's possible that in a given iteration, we free up most
36  * of the buckets we're going to free before we allocate most of the buckets
37  * we're going to allocate.
38  *
39  * If we only use half of the reserve per iteration, then in steady state we'll
40  * always have room in the reserve for the buckets we're going to need in the
41  * next iteration:
42  */
43 #define COPYGC_BUCKETS_PER_ITER(ca)                                     \
44         ((ca)->free[RESERVE_MOVINGGC].size / 2)
45
46 /*
47  * Max sectors to move per iteration: Have to take into account internal
48  * fragmentation from the multiple write points for each generation:
49  */
50 #define COPYGC_SECTORS_PER_ITER(ca)                                     \
51         ((ca)->mi.bucket_size * COPYGC_BUCKETS_PER_ITER(ca))
52
53 static inline int sectors_used_cmp(copygc_heap *heap,
54                                    struct copygc_heap_entry l,
55                                    struct copygc_heap_entry r)
56 {
57         return cmp_int(l.sectors, r.sectors);
58 }
59
60 static int bucket_offset_cmp(const void *_l, const void *_r, size_t size)
61 {
62         const struct copygc_heap_entry *l = _l;
63         const struct copygc_heap_entry *r = _r;
64
65         return cmp_int(l->offset, r->offset);
66 }
67
68 static bool __copygc_pred(struct bch_dev *ca,
69                           struct bkey_s_c k)
70 {
71         copygc_heap *h = &ca->copygc_heap;
72         const struct bch_extent_ptr *ptr =
73                 bch2_bkey_has_device(k, ca->dev_idx);
74
75         if (ptr) {
76                 struct copygc_heap_entry search = { .offset = ptr->offset };
77
78                 ssize_t i = eytzinger0_find_le(h->data, h->used,
79                                                sizeof(h->data[0]),
80                                                bucket_offset_cmp, &search);
81
82                 return (i >= 0 &&
83                         ptr->offset < h->data[i].offset + ca->mi.bucket_size &&
84                         ptr->gen == h->data[i].gen);
85         }
86
87         return false;
88 }
89
90 static enum data_cmd copygc_pred(struct bch_fs *c, void *arg,
91                                  struct bkey_s_c k,
92                                  struct bch_io_opts *io_opts,
93                                  struct data_opts *data_opts)
94 {
95         struct bch_dev *ca = arg;
96
97         if (!__copygc_pred(ca, k))
98                 return DATA_SKIP;
99
100         data_opts->target               = dev_to_target(ca->dev_idx);
101         data_opts->btree_insert_flags   = BTREE_INSERT_USE_RESERVE;
102         data_opts->rewrite_dev          = ca->dev_idx;
103         return DATA_REWRITE;
104 }
105
106 static bool have_copygc_reserve(struct bch_dev *ca)
107 {
108         bool ret;
109
110         spin_lock(&ca->fs->freelist_lock);
111         ret = fifo_full(&ca->free[RESERVE_MOVINGGC]) ||
112                 ca->allocator_state != ALLOCATOR_RUNNING;
113         spin_unlock(&ca->fs->freelist_lock);
114
115         return ret;
116 }
117
118 static void bch2_copygc(struct bch_fs *c, struct bch_dev *ca)
119 {
120         copygc_heap *h = &ca->copygc_heap;
121         struct copygc_heap_entry e, *i;
122         struct bucket_array *buckets;
123         struct bch_move_stats move_stats;
124         u64 sectors_to_move = 0, sectors_not_moved = 0;
125         u64 buckets_to_move, buckets_not_moved = 0;
126         size_t b;
127         int ret;
128
129         memset(&move_stats, 0, sizeof(move_stats));
130         closure_wait_event(&c->freelist_wait, have_copygc_reserve(ca));
131
132         /*
133          * Find buckets with lowest sector counts, skipping completely
134          * empty buckets, by building a maxheap sorted by sector count,
135          * and repeatedly replacing the maximum element until all
136          * buckets have been visited.
137          */
138         h->used = 0;
139
140         /*
141          * We need bucket marks to be up to date - gc can't be recalculating
142          * them:
143          */
144         down_read(&c->gc_lock);
145         down_read(&ca->bucket_lock);
146         buckets = bucket_array(ca);
147
148         for (b = buckets->first_bucket; b < buckets->nbuckets; b++) {
149                 struct bucket_mark m = READ_ONCE(buckets->b[b].mark);
150                 struct copygc_heap_entry e;
151
152                 if (m.owned_by_allocator ||
153                     m.data_type != BCH_DATA_USER ||
154                     !bucket_sectors_used(m) ||
155                     bucket_sectors_used(m) >= ca->mi.bucket_size)
156                         continue;
157
158                 e = (struct copygc_heap_entry) {
159                         .gen            = m.gen,
160                         .sectors        = bucket_sectors_used(m),
161                         .offset         = bucket_to_sector(ca, b),
162                 };
163                 heap_add_or_replace(h, e, -sectors_used_cmp, NULL);
164         }
165         up_read(&ca->bucket_lock);
166         up_read(&c->gc_lock);
167
168         for (i = h->data; i < h->data + h->used; i++)
169                 sectors_to_move += i->sectors;
170
171         while (sectors_to_move > COPYGC_SECTORS_PER_ITER(ca)) {
172                 BUG_ON(!heap_pop(h, e, -sectors_used_cmp, NULL));
173                 sectors_to_move -= e.sectors;
174         }
175
176         buckets_to_move = h->used;
177
178         if (!buckets_to_move)
179                 return;
180
181         eytzinger0_sort(h->data, h->used,
182                         sizeof(h->data[0]),
183                         bucket_offset_cmp, NULL);
184
185         ret = bch2_move_data(c, &ca->copygc_pd.rate,
186                              writepoint_ptr(&ca->copygc_write_point),
187                              POS_MIN, POS_MAX,
188                              copygc_pred, ca,
189                              &move_stats);
190
191         down_read(&ca->bucket_lock);
192         buckets = bucket_array(ca);
193         for (i = h->data; i < h->data + h->used; i++) {
194                 size_t b = sector_to_bucket(ca, i->offset);
195                 struct bucket_mark m = READ_ONCE(buckets->b[b].mark);
196
197                 if (i->gen == m.gen && bucket_sectors_used(m)) {
198                         sectors_not_moved += bucket_sectors_used(m);
199                         buckets_not_moved++;
200                 }
201         }
202         up_read(&ca->bucket_lock);
203
204         if (sectors_not_moved && !ret)
205                 bch_warn_ratelimited(c,
206                         "copygc finished but %llu/%llu sectors, %llu/%llu buckets not moved",
207                          sectors_not_moved, sectors_to_move,
208                          buckets_not_moved, buckets_to_move);
209
210         trace_copygc(ca,
211                      atomic64_read(&move_stats.sectors_moved), sectors_not_moved,
212                      buckets_to_move, buckets_not_moved);
213 }
214
215 /*
216  * Copygc runs when the amount of fragmented data is above some arbitrary
217  * threshold:
218  *
219  * The threshold at the limit - when the device is full - is the amount of space
220  * we reserved in bch2_recalc_capacity; we can't have more than that amount of
221  * disk space stranded due to fragmentation and store everything we have
222  * promised to store.
223  *
224  * But we don't want to be running copygc unnecessarily when the device still
225  * has plenty of free space - rather, we want copygc to smoothly run every so
226  * often and continually reduce the amount of fragmented space as the device
227  * fills up. So, we increase the threshold by half the current free space.
228  */
229 unsigned long bch2_copygc_wait_amount(struct bch_dev *ca)
230 {
231         struct bch_fs *c = ca->fs;
232         struct bch_dev_usage usage = bch2_dev_usage_read(c, ca);
233         u64 fragmented_allowed = ca->copygc_threshold +
234                 ((__dev_buckets_available(ca, usage) * ca->mi.bucket_size) >> 1);
235
236         return max_t(s64, 0, fragmented_allowed - usage.sectors_fragmented);
237 }
238
239 static int bch2_copygc_thread(void *arg)
240 {
241         struct bch_dev *ca = arg;
242         struct bch_fs *c = ca->fs;
243         struct io_clock *clock = &c->io_clock[WRITE];
244         unsigned long last, wait;
245
246         set_freezable();
247
248         while (!kthread_should_stop()) {
249                 if (kthread_wait_freezable(c->copy_gc_enabled))
250                         break;
251
252                 last = atomic_long_read(&clock->now);
253                 wait = bch2_copygc_wait_amount(ca);
254
255                 if (wait > clock->max_slop) {
256                         bch2_kthread_io_clock_wait(clock, last + wait,
257                                         MAX_SCHEDULE_TIMEOUT);
258                         continue;
259                 }
260
261                 bch2_copygc(c, ca);
262         }
263
264         return 0;
265 }
266
267 void bch2_copygc_stop(struct bch_dev *ca)
268 {
269         ca->copygc_pd.rate.rate = UINT_MAX;
270         bch2_ratelimit_reset(&ca->copygc_pd.rate);
271
272         if (ca->copygc_thread) {
273                 kthread_stop(ca->copygc_thread);
274                 put_task_struct(ca->copygc_thread);
275         }
276         ca->copygc_thread = NULL;
277 }
278
279 int bch2_copygc_start(struct bch_fs *c, struct bch_dev *ca)
280 {
281         struct task_struct *t;
282
283         if (ca->copygc_thread)
284                 return 0;
285
286         if (c->opts.nochanges)
287                 return 0;
288
289         if (bch2_fs_init_fault("copygc_start"))
290                 return -ENOMEM;
291
292         t = kthread_create(bch2_copygc_thread, ca,
293                            "bch_copygc[%s]", ca->name);
294         if (IS_ERR(t))
295                 return PTR_ERR(t);
296
297         get_task_struct(t);
298
299         ca->copygc_thread = t;
300         wake_up_process(ca->copygc_thread);
301
302         return 0;
303 }
304
305 void bch2_dev_copygc_init(struct bch_dev *ca)
306 {
307         bch2_pd_controller_init(&ca->copygc_pd);
308         ca->copygc_pd.d_term = 0;
309 }