]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/movinggc.c
Update bcachefs sources to eb83f1f842bb mean and variance: Promote to lib/math
[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 "btree_write_buffer.h"
14 #include "buckets.h"
15 #include "clock.h"
16 #include "errcode.h"
17 #include "error.h"
18 #include "lru.h"
19 #include "move.h"
20 #include "movinggc.h"
21 #include "trace.h"
22
23 #include <linux/freezer.h>
24 #include <linux/kthread.h>
25 #include <linux/math64.h>
26 #include <linux/sched/task.h>
27 #include <linux/wait.h>
28
29 struct buckets_in_flight {
30         struct rhashtable               table;
31         struct move_bucket_in_flight    *first;
32         struct move_bucket_in_flight    *last;
33         size_t                          nr;
34         size_t                          sectors;
35 };
36
37 static const struct rhashtable_params bch_move_bucket_params = {
38         .head_offset    = offsetof(struct move_bucket_in_flight, hash),
39         .key_offset     = offsetof(struct move_bucket_in_flight, bucket.k),
40         .key_len        = sizeof(struct move_bucket_key),
41 };
42
43 static struct move_bucket_in_flight *
44 move_bucket_in_flight_add(struct buckets_in_flight *list, struct move_bucket b)
45 {
46         struct move_bucket_in_flight *new = kzalloc(sizeof(*new), GFP_KERNEL);
47         int ret;
48
49         if (!new)
50                 return ERR_PTR(-ENOMEM);
51
52         new->bucket = b;
53
54         ret = rhashtable_lookup_insert_fast(&list->table, &new->hash,
55                                             bch_move_bucket_params);
56         if (ret) {
57                 kfree(new);
58                 return ERR_PTR(ret);
59         }
60
61         if (!list->first)
62                 list->first = new;
63         else
64                 list->last->next = new;
65
66         list->last = new;
67         list->nr++;
68         list->sectors += b.sectors;
69         return new;
70 }
71
72 static int bch2_bucket_is_movable(struct btree_trans *trans,
73                                   struct move_bucket *b, u64 time)
74 {
75         struct btree_iter iter;
76         struct bkey_s_c k;
77         struct bch_alloc_v4 _a;
78         const struct bch_alloc_v4 *a;
79         int ret;
80
81         if (bch2_bucket_is_open(trans->c,
82                                 b->k.bucket.inode,
83                                 b->k.bucket.offset))
84                 return 0;
85
86         k = bch2_bkey_get_iter(trans, &iter, BTREE_ID_alloc,
87                                b->k.bucket, BTREE_ITER_CACHED);
88         ret = bkey_err(k);
89         if (ret)
90                 return ret;
91
92         a = bch2_alloc_to_v4(k, &_a);
93         b->k.gen        = a->gen;
94         b->sectors      = bch2_bucket_sectors_dirty(*a);
95
96         ret = data_type_movable(a->data_type) &&
97                 a->fragmentation_lru &&
98                 a->fragmentation_lru <= time;
99
100         bch2_trans_iter_exit(trans, &iter);
101         return ret;
102 }
103
104 static void move_buckets_wait(struct moving_context *ctxt,
105                               struct buckets_in_flight *list,
106                               bool flush)
107 {
108         struct move_bucket_in_flight *i;
109         int ret;
110
111         while ((i = list->first)) {
112                 if (flush)
113                         move_ctxt_wait_event(ctxt, !atomic_read(&i->count));
114
115                 if (atomic_read(&i->count))
116                         break;
117
118                 list->first = i->next;
119                 if (!list->first)
120                         list->last = NULL;
121
122                 list->nr--;
123                 list->sectors -= i->bucket.sectors;
124
125                 ret = rhashtable_remove_fast(&list->table, &i->hash,
126                                              bch_move_bucket_params);
127                 BUG_ON(ret);
128                 kfree(i);
129         }
130
131         bch2_trans_unlock_long(ctxt->trans);
132 }
133
134 static bool bucket_in_flight(struct buckets_in_flight *list,
135                              struct move_bucket_key k)
136 {
137         return rhashtable_lookup_fast(&list->table, &k, bch_move_bucket_params);
138 }
139
140 typedef DARRAY(struct move_bucket) move_buckets;
141
142 static int bch2_copygc_get_buckets(struct moving_context *ctxt,
143                         struct buckets_in_flight *buckets_in_flight,
144                         move_buckets *buckets)
145 {
146         struct btree_trans *trans = ctxt->trans;
147         struct bch_fs *c = trans->c;
148         struct btree_iter iter;
149         struct bkey_s_c k;
150         size_t nr_to_get = max_t(size_t, 16U, buckets_in_flight->nr / 4);
151         size_t saw = 0, in_flight = 0, not_movable = 0, sectors = 0;
152         int ret;
153
154         move_buckets_wait(ctxt, buckets_in_flight, false);
155
156         ret = bch2_btree_write_buffer_tryflush(trans);
157         if (bch2_err_matches(ret, EROFS))
158                 return ret;
159
160         if (bch2_fs_fatal_err_on(ret, c, "%s: error %s from bch2_btree_write_buffer_tryflush()",
161                                  __func__, bch2_err_str(ret)))
162                 return ret;
163
164         ret = for_each_btree_key2_upto(trans, iter, BTREE_ID_lru,
165                                   lru_pos(BCH_LRU_FRAGMENTATION_START, 0, 0),
166                                   lru_pos(BCH_LRU_FRAGMENTATION_START, U64_MAX, LRU_TIME_MAX),
167                                   0, k, ({
168                 struct move_bucket b = { .k.bucket = u64_to_bucket(k.k->p.offset) };
169                 int ret2 = 0;
170
171                 saw++;
172
173                 if (!bch2_bucket_is_movable(trans, &b, lru_pos_time(k.k->p)))
174                         not_movable++;
175                 else if (bucket_in_flight(buckets_in_flight, b.k))
176                         in_flight++;
177                 else {
178                         ret2 = darray_push(buckets, b) ?: buckets->nr >= nr_to_get;
179                         if (ret2 >= 0)
180                                 sectors += b.sectors;
181                 }
182                 ret2;
183         }));
184
185         pr_debug("have: %zu (%zu) saw %zu in flight %zu not movable %zu got %zu (%zu)/%zu buckets ret %i",
186                  buckets_in_flight->nr, buckets_in_flight->sectors,
187                  saw, in_flight, not_movable, buckets->nr, sectors, nr_to_get, ret);
188
189         return ret < 0 ? ret : 0;
190 }
191
192 noinline
193 static int bch2_copygc(struct moving_context *ctxt,
194                        struct buckets_in_flight *buckets_in_flight,
195                        bool *did_work)
196 {
197         struct btree_trans *trans = ctxt->trans;
198         struct bch_fs *c = trans->c;
199         struct data_update_opts data_opts = {
200                 .btree_insert_flags = BCH_WATERMARK_copygc,
201         };
202         move_buckets buckets = { 0 };
203         struct move_bucket_in_flight *f;
204         struct move_bucket *i;
205         u64 moved = atomic64_read(&ctxt->stats->sectors_moved);
206         int ret = 0;
207
208         ret = bch2_copygc_get_buckets(ctxt, buckets_in_flight, &buckets);
209         if (ret)
210                 goto err;
211
212         darray_for_each(buckets, i) {
213                 if (kthread_should_stop() || freezing(current))
214                         break;
215
216                 f = move_bucket_in_flight_add(buckets_in_flight, *i);
217                 ret = PTR_ERR_OR_ZERO(f);
218                 if (ret == -EEXIST) { /* rare race: copygc_get_buckets returned same bucket more than once */
219                         ret = 0;
220                         continue;
221                 }
222                 if (ret == -ENOMEM) { /* flush IO, continue later */
223                         ret = 0;
224                         break;
225                 }
226
227                 ret = bch2_evacuate_bucket(ctxt, f, f->bucket.k.bucket,
228                                              f->bucket.k.gen, data_opts);
229                 if (ret)
230                         goto err;
231
232                 *did_work = true;
233         }
234 err:
235         darray_exit(&buckets);
236
237         /* no entries in LRU btree found, or got to end: */
238         if (bch2_err_matches(ret, ENOENT))
239                 ret = 0;
240
241         if (ret < 0 && !bch2_err_matches(ret, EROFS))
242                 bch_err_msg(c, ret, "from bch2_move_data()");
243
244         moved = atomic64_read(&ctxt->stats->sectors_moved) - moved;
245         trace_and_count(c, copygc, c, moved, 0, 0, 0);
246         return ret;
247 }
248
249 /*
250  * Copygc runs when the amount of fragmented data is above some arbitrary
251  * threshold:
252  *
253  * The threshold at the limit - when the device is full - is the amount of space
254  * we reserved in bch2_recalc_capacity; we can't have more than that amount of
255  * disk space stranded due to fragmentation and store everything we have
256  * promised to store.
257  *
258  * But we don't want to be running copygc unnecessarily when the device still
259  * has plenty of free space - rather, we want copygc to smoothly run every so
260  * often and continually reduce the amount of fragmented space as the device
261  * fills up. So, we increase the threshold by half the current free space.
262  */
263 unsigned long bch2_copygc_wait_amount(struct bch_fs *c)
264 {
265         struct bch_dev *ca;
266         unsigned dev_idx;
267         s64 wait = S64_MAX, fragmented_allowed, fragmented;
268         unsigned i;
269
270         for_each_rw_member(ca, c, dev_idx) {
271                 struct bch_dev_usage usage = bch2_dev_usage_read(ca);
272
273                 fragmented_allowed = ((__dev_buckets_available(ca, usage, BCH_WATERMARK_stripe) *
274                                        ca->mi.bucket_size) >> 1);
275                 fragmented = 0;
276
277                 for (i = 0; i < BCH_DATA_NR; i++)
278                         if (data_type_movable(i))
279                                 fragmented += usage.d[i].fragmented;
280
281                 wait = min(wait, max(0LL, fragmented_allowed - fragmented));
282         }
283
284         return wait;
285 }
286
287 void bch2_copygc_wait_to_text(struct printbuf *out, struct bch_fs *c)
288 {
289         prt_printf(out, "Currently waiting for:     ");
290         prt_human_readable_u64(out, max(0LL, c->copygc_wait -
291                                         atomic64_read(&c->io_clock[WRITE].now)) << 9);
292         prt_newline(out);
293
294         prt_printf(out, "Currently waiting since:   ");
295         prt_human_readable_u64(out, max(0LL,
296                                         atomic64_read(&c->io_clock[WRITE].now) -
297                                         c->copygc_wait_at) << 9);
298         prt_newline(out);
299
300         prt_printf(out, "Currently calculated wait: ");
301         prt_human_readable_u64(out, bch2_copygc_wait_amount(c));
302         prt_newline(out);
303 }
304
305 static int bch2_copygc_thread(void *arg)
306 {
307         struct bch_fs *c = arg;
308         struct moving_context ctxt;
309         struct bch_move_stats move_stats;
310         struct io_clock *clock = &c->io_clock[WRITE];
311         struct buckets_in_flight *buckets;
312         u64 last, wait;
313         int ret = 0;
314
315         buckets = kzalloc(sizeof(struct buckets_in_flight), GFP_KERNEL);
316         if (!buckets)
317                 return -ENOMEM;
318         ret = rhashtable_init(&buckets->table, &bch_move_bucket_params);
319         if (ret) {
320                 kfree(buckets);
321                 bch_err_msg(c, ret, "allocating copygc buckets in flight");
322                 return ret;
323         }
324
325         set_freezable();
326
327         bch2_move_stats_init(&move_stats, "copygc");
328         bch2_moving_ctxt_init(&ctxt, c, NULL, &move_stats,
329                               writepoint_ptr(&c->copygc_write_point),
330                               false);
331
332         while (!ret && !kthread_should_stop()) {
333                 bool did_work = false;
334
335                 bch2_trans_unlock_long(ctxt.trans);
336                 cond_resched();
337
338                 if (!c->copy_gc_enabled) {
339                         move_buckets_wait(&ctxt, buckets, true);
340                         kthread_wait_freezable(c->copy_gc_enabled ||
341                                                kthread_should_stop());
342                 }
343
344                 if (unlikely(freezing(current))) {
345                         move_buckets_wait(&ctxt, buckets, true);
346                         __refrigerator(false);
347                         continue;
348                 }
349
350                 last = atomic64_read(&clock->now);
351                 wait = bch2_copygc_wait_amount(c);
352
353                 if (wait > clock->max_slop) {
354                         c->copygc_wait_at = last;
355                         c->copygc_wait = last + wait;
356                         move_buckets_wait(&ctxt, buckets, true);
357                         trace_and_count(c, copygc_wait, c, wait, last + wait);
358                         bch2_kthread_io_clock_wait(clock, last + wait,
359                                         MAX_SCHEDULE_TIMEOUT);
360                         continue;
361                 }
362
363                 c->copygc_wait = 0;
364
365                 c->copygc_running = true;
366                 ret = bch2_copygc(&ctxt, buckets, &did_work);
367                 c->copygc_running = false;
368
369                 wake_up(&c->copygc_running_wq);
370
371                 if (!wait && !did_work) {
372                         u64 min_member_capacity = bch2_min_rw_member_capacity(c);
373
374                         if (min_member_capacity == U64_MAX)
375                                 min_member_capacity = 128 * 2048;
376
377                         bch2_trans_unlock_long(ctxt.trans);
378                         bch2_kthread_io_clock_wait(clock, last + (min_member_capacity >> 6),
379                                         MAX_SCHEDULE_TIMEOUT);
380                 }
381         }
382
383         move_buckets_wait(&ctxt, buckets, true);
384
385         rhashtable_destroy(&buckets->table);
386         kfree(buckets);
387         bch2_moving_ctxt_exit(&ctxt);
388         bch2_move_stats_exit(&move_stats, c);
389
390         return 0;
391 }
392
393 void bch2_copygc_stop(struct bch_fs *c)
394 {
395         if (c->copygc_thread) {
396                 kthread_stop(c->copygc_thread);
397                 put_task_struct(c->copygc_thread);
398         }
399         c->copygc_thread = NULL;
400 }
401
402 int bch2_copygc_start(struct bch_fs *c)
403 {
404         struct task_struct *t;
405         int ret;
406
407         if (c->copygc_thread)
408                 return 0;
409
410         if (c->opts.nochanges)
411                 return 0;
412
413         if (bch2_fs_init_fault("copygc_start"))
414                 return -ENOMEM;
415
416         t = kthread_create(bch2_copygc_thread, c, "bch-copygc/%s", c->name);
417         ret = PTR_ERR_OR_ZERO(t);
418         if (ret) {
419                 bch_err_msg(c, ret, "creating copygc thread");
420                 return ret;
421         }
422
423         get_task_struct(t);
424
425         c->copygc_thread = t;
426         wake_up_process(c->copygc_thread);
427
428         return 0;
429 }
430
431 void bch2_fs_copygc_init(struct bch_fs *c)
432 {
433         init_waitqueue_head(&c->copygc_running_wq);
434         c->copygc_running = false;
435 }