]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/movinggc.c
Update bcachefs sources to 5e392aed7a bcachefs: Kill bch2_alloc_write()
[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_background.h"
10 #include "alloc_foreground.h"
11 #include "btree_iter.h"
12 #include "btree_update.h"
13 #include "buckets.h"
14 #include "clock.h"
15 #include "disk_groups.h"
16 #include "error.h"
17 #include "extents.h"
18 #include "eytzinger.h"
19 #include "io.h"
20 #include "keylist.h"
21 #include "move.h"
22 #include "movinggc.h"
23 #include "super-io.h"
24
25 #include <trace/events/bcachefs.h>
26 #include <linux/freezer.h>
27 #include <linux/kthread.h>
28 #include <linux/math64.h>
29 #include <linux/sched/task.h>
30 #include <linux/sort.h>
31 #include <linux/wait.h>
32
33 static int bucket_offset_cmp(const void *_l, const void *_r, size_t size)
34 {
35         const struct copygc_heap_entry *l = _l;
36         const struct copygc_heap_entry *r = _r;
37
38         return  cmp_int(l->dev,    r->dev) ?:
39                 cmp_int(l->offset, r->offset);
40 }
41
42 static enum data_cmd copygc_pred(struct bch_fs *c, void *arg,
43                                  struct bkey_s_c k,
44                                  struct bch_io_opts *io_opts,
45                                  struct data_opts *data_opts)
46 {
47         copygc_heap *h = &c->copygc_heap;
48         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
49         const union bch_extent_entry *entry;
50         struct extent_ptr_decoded p = { 0 };
51
52         bkey_for_each_ptr_decode(k.k, ptrs, p, entry) {
53                 struct bch_dev *ca = bch_dev_bkey_exists(c, p.ptr.dev);
54                 struct copygc_heap_entry search = {
55                         .dev    = p.ptr.dev,
56                         .offset = p.ptr.offset,
57                 };
58                 ssize_t i;
59
60                 if (p.ptr.cached)
61                         continue;
62
63                 i = eytzinger0_find_le(h->data, h->used,
64                                        sizeof(h->data[0]),
65                                        bucket_offset_cmp, &search);
66 #if 0
67                 /* eytzinger search verify code: */
68                 ssize_t j = -1, k;
69
70                 for (k = 0; k < h->used; k++)
71                         if (h->data[k].offset <= ptr->offset &&
72                             (j < 0 || h->data[k].offset > h->data[j].offset))
73                                 j = k;
74
75                 BUG_ON(i != j);
76 #endif
77                 if (i >= 0 &&
78                     p.ptr.dev == h->data[i].dev &&
79                     p.ptr.offset < h->data[i].offset + ca->mi.bucket_size &&
80                     p.ptr.gen == h->data[i].gen) {
81                         /*
82                          * We need to use the journal reserve here, because
83                          *  - journal reclaim depends on btree key cache
84                          *    flushing to make forward progress,
85                          *  - which has to make forward progress when the
86                          *    journal is pre-reservation full,
87                          *  - and depends on allocation - meaning allocator and
88                          *    copygc
89                          */
90
91                         data_opts->target               = io_opts->background_target;
92                         data_opts->nr_replicas          = 1;
93                         data_opts->btree_insert_flags   = BTREE_INSERT_USE_RESERVE|
94                                 JOURNAL_WATERMARK_copygc;
95                         data_opts->rewrite_dev          = p.ptr.dev;
96
97                         if (p.has_ec)
98                                 data_opts->nr_replicas += p.ec.redundancy;
99
100                         return DATA_REWRITE;
101                 }
102         }
103
104         return DATA_SKIP;
105 }
106
107 static inline int fragmentation_cmp(copygc_heap *heap,
108                                    struct copygc_heap_entry l,
109                                    struct copygc_heap_entry r)
110 {
111         return cmp_int(l.fragmentation, r.fragmentation);
112 }
113
114 static int walk_buckets_to_copygc(struct bch_fs *c)
115 {
116         copygc_heap *h = &c->copygc_heap;
117         struct btree_trans trans;
118         struct btree_iter iter;
119         struct bkey_s_c k;
120         struct bch_alloc_v4 a;
121         int ret;
122
123         bch2_trans_init(&trans, c, 0, 0);
124
125         for_each_btree_key(&trans, iter, BTREE_ID_alloc, POS_MIN,
126                            BTREE_ITER_PREFETCH, k, ret) {
127                 struct bch_dev *ca = bch_dev_bkey_exists(c, iter.pos.inode);
128                 struct copygc_heap_entry e;
129
130                 bch2_alloc_to_v4(k, &a);
131
132                 if (a.data_type != BCH_DATA_user ||
133                     a.dirty_sectors >= ca->mi.bucket_size ||
134                     bch2_bucket_is_open(c, iter.pos.inode, iter.pos.offset))
135                         continue;
136
137                 e = (struct copygc_heap_entry) {
138                         .dev            = iter.pos.inode,
139                         .gen            = a.gen,
140                         .replicas       = 1 + a.stripe_redundancy,
141                         .fragmentation  = (u64) a.dirty_sectors * (1ULL << 31)
142                                 / ca->mi.bucket_size,
143                         .sectors        = a.dirty_sectors,
144                         .offset         = bucket_to_sector(ca, iter.pos.offset),
145                 };
146                 heap_add_or_replace(h, e, -fragmentation_cmp, NULL);
147
148         }
149         bch2_trans_iter_exit(&trans, &iter);
150
151         bch2_trans_exit(&trans);
152         return ret;
153 }
154
155 static int bucket_inorder_cmp(const void *_l, const void *_r)
156 {
157         const struct copygc_heap_entry *l = _l;
158         const struct copygc_heap_entry *r = _r;
159
160         return cmp_int(l->dev, r->dev) ?: cmp_int(l->offset, r->offset);
161 }
162
163 static int check_copygc_was_done(struct bch_fs *c,
164                                  u64 *sectors_not_moved,
165                                  u64 *buckets_not_moved)
166 {
167         copygc_heap *h = &c->copygc_heap;
168         struct btree_trans trans;
169         struct btree_iter iter;
170         struct bkey_s_c k;
171         struct bch_alloc_v4 a;
172         struct copygc_heap_entry *i;
173         int ret = 0;
174
175         sort(h->data, h->used, sizeof(h->data[0]), bucket_inorder_cmp, NULL);
176
177         bch2_trans_init(&trans, c, 0, 0);
178         bch2_trans_iter_init(&trans, &iter, BTREE_ID_alloc, POS_MIN, 0);
179
180         for (i = h->data; i < h->data + h->used; i++) {
181                 struct bch_dev *ca = bch_dev_bkey_exists(c, i->dev);
182
183                 bch2_btree_iter_set_pos(&iter, POS(i->dev, sector_to_bucket(ca, i->offset)));
184
185                 ret = lockrestart_do(&trans,
186                                 bkey_err(k = bch2_btree_iter_peek_slot(&iter)));
187                 if (ret)
188                         break;
189
190                 bch2_alloc_to_v4(k, &a);
191
192                 if (a.gen == i->gen && a.dirty_sectors) {
193                         *sectors_not_moved += a.dirty_sectors;
194                         *buckets_not_moved += 1;
195                 }
196         }
197         bch2_trans_iter_exit(&trans, &iter);
198
199         bch2_trans_exit(&trans);
200         return ret;
201 }
202
203 static int bch2_copygc(struct bch_fs *c)
204 {
205         copygc_heap *h = &c->copygc_heap;
206         struct copygc_heap_entry e, *i;
207         struct bch_move_stats move_stats;
208         u64 sectors_to_move = 0, sectors_to_write = 0, sectors_not_moved = 0;
209         u64 sectors_reserved = 0;
210         u64 buckets_to_move, buckets_not_moved = 0;
211         struct bch_dev *ca;
212         unsigned dev_idx;
213         size_t heap_size = 0;
214         int ret;
215
216         bch_move_stats_init(&move_stats, "copygc");
217
218         /*
219          * Find buckets with lowest sector counts, skipping completely
220          * empty buckets, by building a maxheap sorted by sector count,
221          * and repeatedly replacing the maximum element until all
222          * buckets have been visited.
223          */
224         h->used = 0;
225
226         for_each_rw_member(ca, c, dev_idx)
227                 heap_size += ca->mi.nbuckets >> 7;
228
229         if (h->size < heap_size) {
230                 free_heap(&c->copygc_heap);
231                 if (!init_heap(&c->copygc_heap, heap_size, GFP_KERNEL)) {
232                         bch_err(c, "error allocating copygc heap");
233                         return 0;
234                 }
235         }
236
237         for_each_rw_member(ca, c, dev_idx) {
238                 s64 avail = min(dev_buckets_available(ca, RESERVE_movinggc),
239                                 ca->mi.nbuckets >> 6);
240
241                 sectors_reserved += avail * ca->mi.bucket_size;
242         }
243
244         ret = walk_buckets_to_copygc(c);
245         if (ret) {
246                 bch2_fs_fatal_error(c, "error walking buckets to copygc!");
247                 return ret;
248         }
249
250         if (!h->used) {
251                 bch_err_ratelimited(c, "copygc requested to run but found no buckets to move!");
252                 return 0;
253         }
254
255         /*
256          * Our btree node allocations also come out of RESERVE_movingc:
257          */
258         sectors_reserved = (sectors_reserved * 3) / 4;
259         if (!sectors_reserved) {
260                 bch2_fs_fatal_error(c, "stuck, ran out of copygc reserve!");
261                 return -1;
262         }
263
264         for (i = h->data; i < h->data + h->used; i++) {
265                 sectors_to_move += i->sectors;
266                 sectors_to_write += i->sectors * i->replicas;
267         }
268
269         while (sectors_to_write > sectors_reserved) {
270                 BUG_ON(!heap_pop(h, e, -fragmentation_cmp, NULL));
271                 sectors_to_write -= e.sectors * e.replicas;
272         }
273
274         buckets_to_move = h->used;
275
276         if (!buckets_to_move) {
277                 bch_err_ratelimited(c, "copygc cannot run - sectors_reserved %llu!",
278                                     sectors_reserved);
279                 return 0;
280         }
281
282         eytzinger0_sort(h->data, h->used,
283                         sizeof(h->data[0]),
284                         bucket_offset_cmp, NULL);
285
286         ret = bch2_move_data(c,
287                              0,                 POS_MIN,
288                              BTREE_ID_NR,       POS_MAX,
289                              NULL,
290                              writepoint_ptr(&c->copygc_write_point),
291                              copygc_pred, NULL,
292                              &move_stats);
293         if (ret) {
294                 bch_err(c, "error %i from bch2_move_data() in copygc", ret);
295                 return ret;
296         }
297
298         ret = check_copygc_was_done(c, &sectors_not_moved, &buckets_not_moved);
299         if (ret) {
300                 bch_err(c, "error %i from check_copygc_was_done()", ret);
301                 return ret;
302         }
303
304         if (sectors_not_moved)
305                 bch_warn_ratelimited(c,
306                         "copygc finished but %llu/%llu sectors, %llu/%llu buckets not moved (move stats: moved %llu sectors, raced %llu keys, %llu sectors)",
307                          sectors_not_moved, sectors_to_move,
308                          buckets_not_moved, buckets_to_move,
309                          atomic64_read(&move_stats.sectors_moved),
310                          atomic64_read(&move_stats.keys_raced),
311                          atomic64_read(&move_stats.sectors_raced));
312
313         trace_copygc(c,
314                      atomic64_read(&move_stats.sectors_moved), sectors_not_moved,
315                      buckets_to_move, buckets_not_moved);
316         return 0;
317 }
318
319 /*
320  * Copygc runs when the amount of fragmented data is above some arbitrary
321  * threshold:
322  *
323  * The threshold at the limit - when the device is full - is the amount of space
324  * we reserved in bch2_recalc_capacity; we can't have more than that amount of
325  * disk space stranded due to fragmentation and store everything we have
326  * promised to store.
327  *
328  * But we don't want to be running copygc unnecessarily when the device still
329  * has plenty of free space - rather, we want copygc to smoothly run every so
330  * often and continually reduce the amount of fragmented space as the device
331  * fills up. So, we increase the threshold by half the current free space.
332  */
333 unsigned long bch2_copygc_wait_amount(struct bch_fs *c)
334 {
335         struct bch_dev *ca;
336         unsigned dev_idx;
337         s64 wait = S64_MAX, fragmented_allowed, fragmented;
338
339         for_each_rw_member(ca, c, dev_idx) {
340                 struct bch_dev_usage usage = bch2_dev_usage_read(ca);
341
342                 fragmented_allowed = ((__dev_buckets_available(ca, usage, RESERVE_none) *
343                                        ca->mi.bucket_size) >> 1);
344                 fragmented = usage.d[BCH_DATA_user].fragmented;
345
346                 wait = min(wait, max(0LL, fragmented_allowed - fragmented));
347         }
348
349         return wait;
350 }
351
352 static int bch2_copygc_thread(void *arg)
353 {
354         struct bch_fs *c = arg;
355         struct io_clock *clock = &c->io_clock[WRITE];
356         u64 last, wait;
357
358         set_freezable();
359
360         while (!kthread_should_stop()) {
361                 cond_resched();
362
363                 if (kthread_wait_freezable(c->copy_gc_enabled))
364                         break;
365
366                 last = atomic64_read(&clock->now);
367                 wait = bch2_copygc_wait_amount(c);
368
369                 if (wait > clock->max_slop) {
370                         trace_copygc_wait(c, wait, last + wait);
371                         c->copygc_wait = last + wait;
372                         bch2_kthread_io_clock_wait(clock, last + wait,
373                                         MAX_SCHEDULE_TIMEOUT);
374                         continue;
375                 }
376
377                 c->copygc_wait = 0;
378
379                 if (bch2_copygc(c))
380                         break;
381         }
382
383         return 0;
384 }
385
386 void bch2_copygc_stop(struct bch_fs *c)
387 {
388         if (c->copygc_thread) {
389                 kthread_stop(c->copygc_thread);
390                 put_task_struct(c->copygc_thread);
391         }
392         c->copygc_thread = NULL;
393 }
394
395 int bch2_copygc_start(struct bch_fs *c)
396 {
397         struct task_struct *t;
398
399         if (c->copygc_thread)
400                 return 0;
401
402         if (c->opts.nochanges)
403                 return 0;
404
405         if (bch2_fs_init_fault("copygc_start"))
406                 return -ENOMEM;
407
408         t = kthread_create(bch2_copygc_thread, c, "bch-copygc/%s", c->name);
409         if (IS_ERR(t)) {
410                 bch_err(c, "error creating copygc thread: %li", PTR_ERR(t));
411                 return PTR_ERR(t);
412         }
413
414         get_task_struct(t);
415
416         c->copygc_thread = t;
417         wake_up_process(c->copygc_thread);
418
419         return 0;
420 }
421
422 void bch2_fs_copygc_init(struct bch_fs *c)
423 {
424 }