bcachefs: Use separate new stripes for copygc and non-copygc
[linux-block.git] / fs / bcachefs / btree_gc.c
CommitLineData
1c6fdbd8
KO
1// SPDX-License-Identifier: GPL-2.0
2/*
3 * Copyright (C) 2010 Kent Overstreet <kent.overstreet@gmail.com>
4 * Copyright (C) 2014 Datera Inc.
5 */
6
7#include "bcachefs.h"
7b3f84ea 8#include "alloc_background.h"
ef337c54 9#include "alloc_foreground.h"
1c6fdbd8 10#include "bkey_methods.h"
c47c50f8 11#include "bkey_on_stack.h"
1c6fdbd8
KO
12#include "btree_locking.h"
13#include "btree_update_interior.h"
14#include "btree_io.h"
15#include "btree_gc.h"
16#include "buckets.h"
17#include "clock.h"
18#include "debug.h"
cd575ddf 19#include "ec.h"
1c6fdbd8
KO
20#include "error.h"
21#include "extents.h"
22#include "journal.h"
23#include "keylist.h"
24#include "move.h"
d0734356 25#include "recovery.h"
1c6fdbd8
KO
26#include "replicas.h"
27#include "super-io.h"
28#include "trace.h"
29
30#include <linux/slab.h>
31#include <linux/bitops.h>
32#include <linux/freezer.h>
33#include <linux/kthread.h>
34#include <linux/preempt.h>
35#include <linux/rcupdate.h>
36#include <linux/sched/task.h>
37
2252aa27
KO
38static inline void __gc_pos_set(struct bch_fs *c, struct gc_pos new_pos)
39{
40 preempt_disable();
41 write_seqcount_begin(&c->gc_pos_lock);
42 c->gc_pos = new_pos;
43 write_seqcount_end(&c->gc_pos_lock);
44 preempt_enable();
45}
46
47static inline void gc_pos_set(struct bch_fs *c, struct gc_pos new_pos)
48{
49 BUG_ON(gc_pos_cmp(new_pos, c->gc_pos) <= 0);
50 __gc_pos_set(c, new_pos);
51}
52
d06c1a0c
KO
53static int bch2_gc_check_topology(struct bch_fs *c,
54 struct bkey_s_c k,
55 struct bpos *expected_start,
56 struct bpos expected_end,
57 bool is_last)
1c6fdbd8 58{
d06c1a0c 59 int ret = 0;
1c6fdbd8 60
d06c1a0c
KO
61 if (k.k->type == KEY_TYPE_btree_ptr_v2) {
62 struct bkey_s_c_btree_ptr_v2 bp = bkey_s_c_to_btree_ptr_v2(k);
1c6fdbd8 63
d06c1a0c
KO
64 if (fsck_err_on(bkey_cmp(*expected_start, bp.v->min_key), c,
65 "btree node with incorrect min_key: got %llu:%llu, should be %llu:%llu",
66 bp.v->min_key.inode,
67 bp.v->min_key.offset,
68 expected_start->inode,
69 expected_start->offset)) {
70 BUG();
71 }
72 }
1c6fdbd8 73
d06c1a0c
KO
74 *expected_start = bkey_cmp(k.k->p, POS_MAX)
75 ? bkey_successor(k.k->p)
76 : k.k->p;
77
78 if (fsck_err_on(is_last &&
79 bkey_cmp(k.k->p, expected_end), c,
80 "btree node with incorrect max_key: got %llu:%llu, should be %llu:%llu",
81 k.k->p.inode,
82 k.k->p.offset,
83 expected_end.inode,
84 expected_end.offset)) {
85 BUG();
1c6fdbd8 86 }
d06c1a0c
KO
87fsck_err:
88 return ret;
1c6fdbd8
KO
89}
90
2252aa27
KO
91/* marking of btree keys/nodes: */
92
26609b61 93static int bch2_gc_mark_key(struct bch_fs *c, struct bkey_s_c k,
d034c09b 94 u8 *max_stale, bool initial)
2252aa27 95{
26609b61
KO
96 struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
97 const struct bch_extent_ptr *ptr;
47799326 98 unsigned flags =
2d594dfb
KO
99 BTREE_TRIGGER_GC|
100 (initial ? BTREE_TRIGGER_NOATOMIC : 0);
2252aa27
KO
101 int ret = 0;
102
91f8b567 103 if (initial) {
29364f34 104 BUG_ON(bch2_journal_seq_verify &&
91f8b567
KO
105 k.k->version.lo > journal_cur_seq(&c->journal));
106
a9bc0a51
KO
107 /* XXX change to fsck check */
108 if (fsck_err_on(k.k->version.lo > atomic64_read(&c->key_version), c,
109 "key version number higher than recorded: %llu > %llu",
110 k.k->version.lo,
111 atomic64_read(&c->key_version)))
91f8b567
KO
112 atomic64_set(&c->key_version, k.k->version.lo);
113
114 if (test_bit(BCH_FS_REBUILD_REPLICAS, &c->flags) ||
988e98cf 115 fsck_err_on(!bch2_bkey_replicas_marked(c, k), c,
91f8b567 116 "superblock not marked as containing replicas (type %u)",
26609b61
KO
117 k.k->type)) {
118 ret = bch2_mark_bkey_replicas(c, k);
91f8b567 119 if (ret)
2252aa27
KO
120 return ret;
121 }
47799326 122
26609b61
KO
123 bkey_for_each_ptr(ptrs, ptr) {
124 struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
39fbc5a4 125 struct bucket *g = PTR_BUCKET(ca, ptr, true);
28062d32 126 struct bucket *g2 = PTR_BUCKET(ca, ptr, false);
26609b61 127
90541a74 128 if (mustfix_fsck_err_on(!g->gen_valid, c,
06ab329c
KO
129 "bucket %u:%zu data type %s ptr gen %u missing in alloc btree",
130 ptr->dev, PTR_BUCKET_NR(ca, ptr),
131 bch2_data_types[ptr_data_type(k.k, ptr)],
132 ptr->gen)) {
28062d32 133 g2->_mark.gen = g->_mark.gen = ptr->gen;
28062d32 134 g2->gen_valid = g->gen_valid = true;
26609b61
KO
135 }
136
137 if (mustfix_fsck_err_on(gen_cmp(ptr->gen, g->mark.gen) > 0, c,
06ab329c
KO
138 "bucket %u:%zu data type %s ptr gen in the future: %u > %u",
139 ptr->dev, PTR_BUCKET_NR(ca, ptr),
140 bch2_data_types[ptr_data_type(k.k, ptr)],
141 ptr->gen, g->mark.gen)) {
28062d32 142 g2->_mark.gen = g->_mark.gen = ptr->gen;
28062d32 143 g2->gen_valid = g->gen_valid = true;
06ab329c
KO
144 g2->_mark.data_type = 0;
145 g2->_mark.dirty_sectors = 0;
146 g2->_mark.cached_sectors = 0;
26609b61
KO
147 set_bit(BCH_FS_FIXED_GENS, &c->flags);
148 }
149 }
2252aa27
KO
150 }
151
26609b61
KO
152 bkey_for_each_ptr(ptrs, ptr) {
153 struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
39fbc5a4 154 struct bucket *g = PTR_BUCKET(ca, ptr, true);
26609b61 155
76f4c7b0
KO
156 if (gen_after(g->oldest_gen, ptr->gen))
157 g->oldest_gen = ptr->gen;
26609b61
KO
158
159 *max_stale = max(*max_stale, ptr_stale(ca, ptr));
160 }
91f8b567 161
2cbe5cfe 162 bch2_mark_key(c, k, 0, k.k->size, NULL, 0, flags);
91f8b567 163fsck_err:
2252aa27
KO
164 return ret;
165}
166
e3e464ac 167static int btree_gc_mark_node(struct bch_fs *c, struct btree *b, u8 *max_stale,
e62d65f2 168 bool initial)
1c6fdbd8 169{
d06c1a0c 170 struct bpos next_node_start = b->data->min_key;
1c6fdbd8
KO
171 struct btree_node_iter iter;
172 struct bkey unpacked;
173 struct bkey_s_c k;
d034c09b
KO
174 int ret = 0;
175
176 *max_stale = 0;
1c6fdbd8 177
26609b61 178 if (!btree_node_type_needs_gc(btree_node_type(b)))
2252aa27 179 return 0;
1c6fdbd8 180
d06c1a0c
KO
181 bch2_btree_node_iter_init_from_start(&iter, b);
182
183 while ((k = bch2_btree_node_iter_peek_unpack(&iter, b, &unpacked)).k) {
2252aa27 184 bch2_bkey_debugcheck(c, b, k);
1c6fdbd8 185
26609b61 186 ret = bch2_gc_mark_key(c, k, max_stale, initial);
d034c09b
KO
187 if (ret)
188 break;
d06c1a0c
KO
189
190 bch2_btree_node_iter_advance(&iter, b);
191
192 if (b->c.level) {
193 ret = bch2_gc_check_topology(c, k,
194 &next_node_start,
195 b->data->max_key,
196 bch2_btree_node_iter_end(&iter));
197 if (ret)
198 break;
199 }
2252aa27
KO
200 }
201
d034c09b 202 return ret;
1c6fdbd8
KO
203}
204
2252aa27 205static int bch2_gc_btree(struct bch_fs *c, enum btree_id btree_id,
a1d58243 206 bool initial, bool metadata_only)
1c6fdbd8 207{
424eb881
KO
208 struct btree_trans trans;
209 struct btree_iter *iter;
1c6fdbd8 210 struct btree *b;
4881fdb7 211 unsigned depth = metadata_only ? 1
29364f34 212 : bch2_expensive_debug_checks ? 0
4881fdb7
KO
213 : !btree_node_type_needs_gc(btree_id) ? 1
214 : 0;
f7c0fcdd 215 u8 max_stale = 0;
1c6fdbd8
KO
216 int ret = 0;
217
20bceecb 218 bch2_trans_init(&trans, c, 0, 0);
424eb881 219
1c6fdbd8
KO
220 gc_pos_set(c, gc_pos_btree(btree_id, POS_MIN, 0));
221
424eb881 222 __for_each_btree_node(&trans, iter, btree_id, POS_MIN,
1c6fdbd8 223 0, depth, BTREE_ITER_PREFETCH, b) {
1c6fdbd8
KO
224 bch2_verify_btree_nr_keys(b);
225
8777210b
KO
226 gc_pos_set(c, gc_pos_btree_node(b));
227
e62d65f2 228 ret = btree_gc_mark_node(c, b, &max_stale, initial);
d034c09b
KO
229 if (ret)
230 break;
1c6fdbd8 231
2252aa27
KO
232 if (!initial) {
233 if (max_stale > 64)
424eb881 234 bch2_btree_node_rewrite(c, iter,
2252aa27 235 b->data->keys.seq,
2252aa27
KO
236 BTREE_INSERT_NOWAIT|
237 BTREE_INSERT_GC_LOCK_HELD);
29364f34
KO
238 else if (!bch2_btree_gc_rewrite_disabled &&
239 (bch2_btree_gc_always_rewrite || max_stale > 16))
424eb881 240 bch2_btree_node_rewrite(c, iter,
2252aa27
KO
241 b->data->keys.seq,
242 BTREE_INSERT_NOWAIT|
243 BTREE_INSERT_GC_LOCK_HELD);
244 }
1c6fdbd8 245
424eb881 246 bch2_trans_cond_resched(&trans);
1c6fdbd8 247 }
424eb881 248 ret = bch2_trans_exit(&trans) ?: ret;
1c6fdbd8
KO
249 if (ret)
250 return ret;
251
252 mutex_lock(&c->btree_root_lock);
1c6fdbd8
KO
253 b = c->btree_roots[btree_id].b;
254 if (!btree_node_fake(b))
8b2b9d11
KO
255 ret = bch2_gc_mark_key(c, bkey_i_to_s_c(&b->key),
256 &max_stale, initial);
c43a6ef9 257 gc_pos_set(c, gc_pos_btree_root(b->c.btree_id));
1c6fdbd8 258 mutex_unlock(&c->btree_root_lock);
8b2b9d11
KO
259
260 return ret;
1c6fdbd8
KO
261}
262
e62d65f2 263static int bch2_gc_btree_init_recurse(struct bch_fs *c, struct btree *b,
d06c1a0c
KO
264 struct journal_keys *journal_keys,
265 unsigned target_depth)
e62d65f2
KO
266{
267 struct btree_and_journal_iter iter;
268 struct bkey_s_c k;
d06c1a0c 269 struct bpos next_node_start = b->data->min_key;
e62d65f2
KO
270 u8 max_stale = 0;
271 int ret = 0;
272
273 bch2_btree_and_journal_iter_init_node_iter(&iter, journal_keys, b);
274
275 while ((k = bch2_btree_and_journal_iter_peek(&iter)).k) {
276 bch2_bkey_debugcheck(c, b, k);
277
d06c1a0c
KO
278 BUG_ON(bkey_cmp(k.k->p, b->data->min_key) < 0);
279 BUG_ON(bkey_cmp(k.k->p, b->data->max_key) > 0);
280
e62d65f2
KO
281 ret = bch2_gc_mark_key(c, k, &max_stale, true);
282 if (ret)
283 break;
284
d06c1a0c 285 if (b->c.level) {
e62d65f2
KO
286 struct btree *child;
287 BKEY_PADDED(k) tmp;
288
289 bkey_reassemble(&tmp.k, k);
d06c1a0c
KO
290 k = bkey_i_to_s_c(&tmp.k);
291
292 bch2_btree_and_journal_iter_advance(&iter);
e62d65f2 293
d06c1a0c
KO
294 ret = bch2_gc_check_topology(c, k,
295 &next_node_start,
296 b->data->max_key,
297 !bch2_btree_and_journal_iter_peek(&iter).k);
e62d65f2
KO
298 if (ret)
299 break;
300
d06c1a0c
KO
301 if (b->c.level > target_depth) {
302 child = bch2_btree_node_get_noiter(c, &tmp.k,
303 b->c.btree_id, b->c.level - 1);
304 ret = PTR_ERR_OR_ZERO(child);
305 if (ret)
306 break;
e62d65f2 307
d06c1a0c
KO
308 ret = bch2_gc_btree_init_recurse(c, child,
309 journal_keys, target_depth);
310 six_unlock_read(&child->c.lock);
311
312 if (ret)
313 break;
314 }
315 } else {
316 bch2_btree_and_journal_iter_advance(&iter);
317 }
e62d65f2
KO
318 }
319
320 return ret;
321}
322
323static int bch2_gc_btree_init(struct bch_fs *c,
324 struct journal_keys *journal_keys,
325 enum btree_id btree_id,
326 bool metadata_only)
327{
328 struct btree *b;
329 unsigned target_depth = metadata_only ? 1
29364f34 330 : bch2_expensive_debug_checks ? 0
e62d65f2
KO
331 : !btree_node_type_needs_gc(btree_id) ? 1
332 : 0;
333 u8 max_stale = 0;
334 int ret = 0;
335
336 b = c->btree_roots[btree_id].b;
337
338 if (btree_node_fake(b))
339 return 0;
340
341 six_lock_read(&b->c.lock, NULL, NULL);
d06c1a0c
KO
342 if (fsck_err_on(bkey_cmp(b->data->min_key, POS_MIN), c,
343 "btree root with incorrect min_key: %llu:%llu",
344 b->data->min_key.inode,
345 b->data->min_key.offset)) {
346 BUG();
347 }
348
349 if (fsck_err_on(bkey_cmp(b->data->max_key, POS_MAX), c,
350 "btree root with incorrect min_key: %llu:%llu",
351 b->data->max_key.inode,
352 b->data->max_key.offset)) {
353 BUG();
354 }
355
e62d65f2
KO
356 if (b->c.level >= target_depth)
357 ret = bch2_gc_btree_init_recurse(c, b,
358 journal_keys, target_depth);
359
360 if (!ret)
361 ret = bch2_gc_mark_key(c, bkey_i_to_s_c(&b->key),
362 &max_stale, true);
d06c1a0c 363fsck_err:
e62d65f2
KO
364 six_unlock_read(&b->c.lock);
365
366 return ret;
367}
368
cd575ddf
KO
369static inline int btree_id_gc_phase_cmp(enum btree_id l, enum btree_id r)
370{
371 return (int) btree_id_to_gc_phase(l) -
372 (int) btree_id_to_gc_phase(r);
373}
374
d0734356 375static int bch2_gc_btrees(struct bch_fs *c, struct journal_keys *journal_keys,
a1d58243 376 bool initial, bool metadata_only)
2252aa27 377{
cd575ddf 378 enum btree_id ids[BTREE_ID_NR];
2252aa27
KO
379 unsigned i;
380
cd575ddf
KO
381 for (i = 0; i < BTREE_ID_NR; i++)
382 ids[i] = i;
383 bubble_sort(ids, BTREE_ID_NR, btree_id_gc_phase_cmp);
384
2252aa27 385 for (i = 0; i < BTREE_ID_NR; i++) {
cd575ddf 386 enum btree_id id = ids[i];
e62d65f2
KO
387 int ret = initial
388 ? bch2_gc_btree_init(c, journal_keys,
389 id, metadata_only)
390 : bch2_gc_btree(c, id, initial, metadata_only);
2252aa27
KO
391 if (ret)
392 return ret;
2252aa27
KO
393 }
394
395 return 0;
396}
397
1c6fdbd8
KO
398static void mark_metadata_sectors(struct bch_fs *c, struct bch_dev *ca,
399 u64 start, u64 end,
400 enum bch_data_type type,
401 unsigned flags)
402{
403 u64 b = sector_to_bucket(ca, start);
404
405 do {
406 unsigned sectors =
407 min_t(u64, bucket_to_sector(ca, b + 1), end) - start;
408
409 bch2_mark_metadata_bucket(c, ca, b, type, sectors,
410 gc_phase(GC_PHASE_SB), flags);
411 b++;
412 start += sectors;
413 } while (start < end);
414}
415
416void bch2_mark_dev_superblock(struct bch_fs *c, struct bch_dev *ca,
417 unsigned flags)
418{
419 struct bch_sb_layout *layout = &ca->disk_sb.sb->layout;
420 unsigned i;
421 u64 b;
422
97446a24
KO
423 /*
424 * This conditional is kind of gross, but we may be called from the
425 * device add path, before the new device has actually been added to the
426 * running filesystem:
427 */
1c6fdbd8
KO
428 if (c) {
429 lockdep_assert_held(&c->sb_lock);
9166b41d 430 percpu_down_read(&c->mark_lock);
1c6fdbd8
KO
431 }
432
433 for (i = 0; i < layout->nr_superblocks; i++) {
434 u64 offset = le64_to_cpu(layout->sb_offset[i]);
435
436 if (offset == BCH_SB_SECTOR)
437 mark_metadata_sectors(c, ca, 0, BCH_SB_SECTOR,
89fd25be 438 BCH_DATA_sb, flags);
1c6fdbd8
KO
439
440 mark_metadata_sectors(c, ca, offset,
441 offset + (1 << layout->sb_max_size_bits),
89fd25be 442 BCH_DATA_sb, flags);
1c6fdbd8
KO
443 }
444
1c6fdbd8
KO
445 for (i = 0; i < ca->journal.nr; i++) {
446 b = ca->journal.buckets[i];
89fd25be 447 bch2_mark_metadata_bucket(c, ca, b, BCH_DATA_journal,
1c6fdbd8
KO
448 ca->mi.bucket_size,
449 gc_phase(GC_PHASE_SB), flags);
450 }
451
3a0e06db 452 if (c)
9166b41d 453 percpu_up_read(&c->mark_lock);
1c6fdbd8
KO
454}
455
456static void bch2_mark_superblocks(struct bch_fs *c)
457{
458 struct bch_dev *ca;
459 unsigned i;
460
461 mutex_lock(&c->sb_lock);
462 gc_pos_set(c, gc_phase(GC_PHASE_SB));
463
464 for_each_online_member(ca, c, i)
2d594dfb 465 bch2_mark_dev_superblock(c, ca, BTREE_TRIGGER_GC);
1c6fdbd8
KO
466 mutex_unlock(&c->sb_lock);
467}
468
00b8ccf7 469#if 0
1c6fdbd8
KO
470/* Also see bch2_pending_btree_node_free_insert_done() */
471static void bch2_mark_pending_btree_node_frees(struct bch_fs *c)
472{
1c6fdbd8
KO
473 struct btree_update *as;
474 struct pending_btree_node_free *d;
475
476 mutex_lock(&c->btree_interior_update_lock);
477 gc_pos_set(c, gc_phase(GC_PHASE_PENDING_DELETE));
478
479 for_each_pending_btree_node_free(c, as, d)
480 if (d->index_update_done)
2cbe5cfe
KO
481 bch2_mark_key(c, bkey_i_to_s_c(&d->key),
482 0, 0, NULL, 0,
2d594dfb 483 BTREE_TRIGGER_GC);
1c6fdbd8
KO
484
485 mutex_unlock(&c->btree_interior_update_lock);
486}
00b8ccf7 487#endif
1c6fdbd8
KO
488
489static void bch2_mark_allocator_buckets(struct bch_fs *c)
490{
491 struct bch_dev *ca;
492 struct open_bucket *ob;
493 size_t i, j, iter;
494 unsigned ci;
495
9166b41d 496 percpu_down_read(&c->mark_lock);
1c6fdbd8
KO
497
498 spin_lock(&c->freelist_lock);
499 gc_pos_set(c, gc_pos_alloc(c, NULL));
500
501 for_each_member_device(ca, c, ci) {
502 fifo_for_each_entry(i, &ca->free_inc, iter)
503 bch2_mark_alloc_bucket(c, ca, i, true,
504 gc_pos_alloc(c, NULL),
2d594dfb 505 BTREE_TRIGGER_GC);
1c6fdbd8
KO
506
507
508
509 for (j = 0; j < RESERVE_NR; j++)
510 fifo_for_each_entry(i, &ca->free[j], iter)
511 bch2_mark_alloc_bucket(c, ca, i, true,
512 gc_pos_alloc(c, NULL),
2d594dfb 513 BTREE_TRIGGER_GC);
1c6fdbd8
KO
514 }
515
516 spin_unlock(&c->freelist_lock);
517
518 for (ob = c->open_buckets;
519 ob < c->open_buckets + ARRAY_SIZE(c->open_buckets);
520 ob++) {
521 spin_lock(&ob->lock);
522 if (ob->valid) {
523 gc_pos_set(c, gc_pos_alloc(c, ob));
524 ca = bch_dev_bkey_exists(c, ob->ptr.dev);
525 bch2_mark_alloc_bucket(c, ca, PTR_BUCKET_NR(ca, &ob->ptr), true,
526 gc_pos_alloc(c, ob),
2d594dfb 527 BTREE_TRIGGER_GC);
1c6fdbd8
KO
528 }
529 spin_unlock(&ob->lock);
530 }
531
9166b41d 532 percpu_up_read(&c->mark_lock);
1c6fdbd8
KO
533}
534
9ca53b55
KO
535static void bch2_gc_free(struct bch_fs *c)
536{
537 struct bch_dev *ca;
538 unsigned i;
539
dfe9bfb3
KO
540 genradix_free(&c->stripes[1]);
541
9ca53b55
KO
542 for_each_member_device(ca, c, i) {
543 kvpfree(rcu_dereference_protected(ca->buckets[1], 1),
544 sizeof(struct bucket_array) +
545 ca->mi.nbuckets * sizeof(struct bucket));
546 ca->buckets[1] = NULL;
547
548 free_percpu(ca->usage[1]);
549 ca->usage[1] = NULL;
550 }
551
5e82a9a1
KO
552 free_percpu(c->usage_gc);
553 c->usage_gc = NULL;
06b7345c
KO
554}
555
a1d58243
KO
556static int bch2_gc_done(struct bch_fs *c,
557 bool initial, bool metadata_only)
9ca53b55
KO
558{
559 struct bch_dev *ca;
a1d58243
KO
560 bool verify = !metadata_only &&
561 (!initial ||
562 (c->sb.compat & (1ULL << BCH_COMPAT_FEAT_ALLOC_INFO)));
9ca53b55 563 unsigned i;
cccf4e6d 564 int ret = 0;
9ca53b55
KO
565
566#define copy_field(_f, _msg, ...) \
23f80d2b 567 if (dst->_f != src->_f) { \
76f4c7b0 568 if (verify) \
cccf4e6d 569 fsck_err(c, _msg ": got %llu, should be %llu" \
76f4c7b0 570 , ##__VA_ARGS__, dst->_f, src->_f); \
23f80d2b 571 dst->_f = src->_f; \
8d6b6222 572 ret = 1; \
9ca53b55 573 }
dfe9bfb3
KO
574#define copy_stripe_field(_f, _msg, ...) \
575 if (dst->_f != src->_f) { \
76f4c7b0 576 if (verify) \
cccf4e6d
KO
577 fsck_err(c, "stripe %zu has wrong "_msg \
578 ": got %u, should be %u", \
76f4c7b0
KO
579 dst_iter.pos, ##__VA_ARGS__, \
580 dst->_f, src->_f); \
dfe9bfb3 581 dst->_f = src->_f; \
61c8d7c8 582 dst->dirty = true; \
8d6b6222 583 ret = 1; \
dfe9bfb3 584 }
9ca53b55
KO
585#define copy_bucket_field(_f) \
586 if (dst->b[b].mark._f != src->b[b].mark._f) { \
76f4c7b0 587 if (verify) \
aafcf9bc 588 fsck_err(c, "bucket %u:%zu gen %u data type %s has wrong " #_f \
cccf4e6d 589 ": got %u, should be %u", i, b, \
aafcf9bc
KO
590 dst->b[b].mark.gen, \
591 bch2_data_types[dst->b[b].mark.data_type],\
76f4c7b0 592 dst->b[b].mark._f, src->b[b].mark._f); \
9ca53b55 593 dst->b[b]._mark._f = src->b[b].mark._f; \
8d6b6222 594 ret = 1; \
9ca53b55
KO
595 }
596#define copy_dev_field(_f, _msg, ...) \
597 copy_field(_f, "dev %u has wrong " _msg, i, ##__VA_ARGS__)
598#define copy_fs_field(_f, _msg, ...) \
599 copy_field(_f, "fs has wrong " _msg, ##__VA_ARGS__)
600
a1d58243 601 if (!metadata_only) {
dfe9bfb3
KO
602 struct genradix_iter dst_iter = genradix_iter_init(&c->stripes[0], 0);
603 struct genradix_iter src_iter = genradix_iter_init(&c->stripes[1], 0);
604 struct stripe *dst, *src;
dfe9bfb3
KO
605
606 c->ec_stripes_heap.used = 0;
607
608 while ((dst = genradix_iter_peek(&dst_iter, &c->stripes[0])) &&
609 (src = genradix_iter_peek(&src_iter, &c->stripes[1]))) {
61c8d7c8
KO
610 BUG_ON(src_iter.pos != dst_iter.pos);
611
dfe9bfb3
KO
612 copy_stripe_field(alive, "alive");
613 copy_stripe_field(sectors, "sectors");
614 copy_stripe_field(algorithm, "algorithm");
615 copy_stripe_field(nr_blocks, "nr_blocks");
616 copy_stripe_field(nr_redundant, "nr_redundant");
61c8d7c8 617 copy_stripe_field(blocks_nonempty,
dfe9bfb3
KO
618 "blocks_nonempty");
619
620 for (i = 0; i < ARRAY_SIZE(dst->block_sectors); i++)
61c8d7c8 621 copy_stripe_field(block_sectors[i],
dfe9bfb3
KO
622 "block_sectors[%u]", i);
623
ba6dd1dd
KO
624 if (dst->alive) {
625 spin_lock(&c->ec_stripes_heap_lock);
dfe9bfb3 626 bch2_stripes_heap_insert(c, dst, dst_iter.pos);
ba6dd1dd
KO
627 spin_unlock(&c->ec_stripes_heap_lock);
628 }
dfe9bfb3
KO
629
630 genradix_iter_advance(&dst_iter, &c->stripes[0]);
631 genradix_iter_advance(&src_iter, &c->stripes[1]);
632 }
633 }
634
9ca53b55
KO
635 for_each_member_device(ca, c, i) {
636 struct bucket_array *dst = __bucket_array(ca, 0);
637 struct bucket_array *src = __bucket_array(ca, 1);
638 size_t b;
639
9ca53b55
KO
640 for (b = 0; b < src->nbuckets; b++) {
641 copy_bucket_field(gen);
642 copy_bucket_field(data_type);
643 copy_bucket_field(owned_by_allocator);
644 copy_bucket_field(stripe);
645 copy_bucket_field(dirty_sectors);
646 copy_bucket_field(cached_sectors);
76f4c7b0 647
6671a708 648 dst->b[b].oldest_gen = src->b[b].oldest_gen;
9ca53b55
KO
649 }
650 };
651
5e82a9a1
KO
652 for (i = 0; i < ARRAY_SIZE(c->usage); i++)
653 bch2_fs_usage_acc_to_base(c, i);
654
a1d58243 655 bch2_dev_usage_from_buckets(c);
9ca53b55
KO
656
657 {
ecf37a4a 658 unsigned nr = fs_usage_u64s(c);
5e82a9a1 659 struct bch_fs_usage *dst = c->usage_base;
23f80d2b 660 struct bch_fs_usage *src = (void *)
5e82a9a1 661 bch2_acc_percpu_u64s((void *) c->usage_gc, nr);
9ca53b55 662
768ac639 663 copy_fs_field(hidden, "hidden");
a1d58243 664 copy_fs_field(btree, "btree");
06b7345c 665
a1d58243
KO
666 if (!metadata_only) {
667 copy_fs_field(data, "data");
668 copy_fs_field(cached, "cached");
669 copy_fs_field(reserved, "reserved");
670 copy_fs_field(nr_inodes,"nr_inodes");
671
672 for (i = 0; i < BCH_REPLICAS_MAX; i++)
673 copy_fs_field(persistent_reserved[i],
674 "persistent_reserved[%i]", i);
675 }
9ca53b55 676
7ef2a73a 677 for (i = 0; i < c->replicas.nr; i++) {
8777210b
KO
678 struct bch_replicas_entry *e =
679 cpu_replicas_entry(&c->replicas, i);
680 char buf[80];
681
a1d58243 682 if (metadata_only &&
89fd25be
KO
683 (e->data_type == BCH_DATA_user ||
684 e->data_type == BCH_DATA_cached))
a1d58243
KO
685 continue;
686
8777210b
KO
687 bch2_replicas_entry_to_text(&PBUF(buf), e);
688
768ac639 689 copy_fs_field(replicas[i], "%s", buf);
7ef2a73a 690 }
9ca53b55 691 }
76f4c7b0 692
9ca53b55
KO
693#undef copy_fs_field
694#undef copy_dev_field
695#undef copy_bucket_field
dfe9bfb3
KO
696#undef copy_stripe_field
697#undef copy_field
cccf4e6d
KO
698fsck_err:
699 return ret;
9ca53b55
KO
700}
701
a1d58243
KO
702static int bch2_gc_start(struct bch_fs *c,
703 bool metadata_only)
9ca53b55
KO
704{
705 struct bch_dev *ca;
706 unsigned i;
0741d378 707 int ret;
dfe9bfb3 708
5e82a9a1 709 BUG_ON(c->usage_gc);
9ca53b55 710
5e82a9a1 711 c->usage_gc = __alloc_percpu_gfp(fs_usage_u64s(c) * sizeof(u64),
ecf37a4a 712 sizeof(u64), GFP_KERNEL);
1e1a31c4
KO
713 if (!c->usage_gc) {
714 bch_err(c, "error allocating c->usage_gc");
9ca53b55 715 return -ENOMEM;
1e1a31c4 716 }
9ca53b55 717
1c6fdbd8 718 for_each_member_device(ca, c, i) {
9ca53b55
KO
719 BUG_ON(ca->buckets[1]);
720 BUG_ON(ca->usage[1]);
721
722 ca->buckets[1] = kvpmalloc(sizeof(struct bucket_array) +
723 ca->mi.nbuckets * sizeof(struct bucket),
724 GFP_KERNEL|__GFP_ZERO);
725 if (!ca->buckets[1]) {
726 percpu_ref_put(&ca->ref);
1e1a31c4 727 bch_err(c, "error allocating ca->buckets[gc]");
9ca53b55
KO
728 return -ENOMEM;
729 }
730
731 ca->usage[1] = alloc_percpu(struct bch_dev_usage);
732 if (!ca->usage[1]) {
1e1a31c4 733 bch_err(c, "error allocating ca->usage[gc]");
9ca53b55
KO
734 percpu_ref_put(&ca->ref);
735 return -ENOMEM;
1c6fdbd8 736 }
1c6fdbd8 737 }
9ca53b55 738
0741d378 739 ret = bch2_ec_mem_alloc(c, true);
1e1a31c4
KO
740 if (ret) {
741 bch_err(c, "error allocating ec gc mem");
0741d378 742 return ret;
1e1a31c4 743 }
0741d378
KO
744
745 percpu_down_write(&c->mark_lock);
746
747 /*
748 * indicate to stripe code that we need to allocate for the gc stripes
749 * radix tree, too
750 */
751 gc_pos_set(c, gc_phase(GC_PHASE_START));
752
9ca53b55
KO
753 for_each_member_device(ca, c, i) {
754 struct bucket_array *dst = __bucket_array(ca, 1);
755 struct bucket_array *src = __bucket_array(ca, 0);
756 size_t b;
757
758 dst->first_bucket = src->first_bucket;
759 dst->nbuckets = src->nbuckets;
760
28062d32 761 for (b = 0; b < src->nbuckets; b++) {
a1d58243
KO
762 struct bucket *d = &dst->b[b];
763 struct bucket *s = &src->b[b];
764
765 d->_mark.gen = dst->b[b].oldest_gen = s->mark.gen;
766 d->gen_valid = s->gen_valid;
767
768 if (metadata_only &&
89fd25be
KO
769 (s->mark.data_type == BCH_DATA_user ||
770 s->mark.data_type == BCH_DATA_cached)) {
a1d58243
KO
771 d->_mark = s->mark;
772 d->_mark.owned_by_allocator = 0;
773 }
28062d32 774 }
9ca53b55
KO
775 };
776
0741d378
KO
777 percpu_up_write(&c->mark_lock);
778
779 return 0;
1c6fdbd8
KO
780}
781
782/**
9ca53b55
KO
783 * bch2_gc - walk _all_ references to buckets, and recompute them:
784 *
785 * Order matters here:
786 * - Concurrent GC relies on the fact that we have a total ordering for
787 * everything that GC walks - see gc_will_visit_node(),
788 * gc_will_visit_root()
789 *
790 * - also, references move around in the course of index updates and
791 * various other crap: everything needs to agree on the ordering
792 * references are allowed to move around in - e.g., we're allowed to
793 * start with a reference owned by an open_bucket (the allocator) and
794 * move it to the btree, but not the reverse.
795 *
796 * This is necessary to ensure that gc doesn't miss references that
797 * move around - if references move backwards in the ordering GC
798 * uses, GC could skip past them
1c6fdbd8 799 */
d0734356 800int bch2_gc(struct bch_fs *c, struct journal_keys *journal_keys,
a1d58243 801 bool initial, bool metadata_only)
1c6fdbd8
KO
802{
803 struct bch_dev *ca;
804 u64 start_time = local_clock();
9ca53b55 805 unsigned i, iter = 0;
2252aa27 806 int ret;
1c6fdbd8 807
1ada1606 808 lockdep_assert_held(&c->state_lock);
1c6fdbd8
KO
809 trace_gc_start(c);
810
1c6fdbd8 811 down_write(&c->gc_lock);
00b8ccf7
KO
812
813 /* flush interior btree updates: */
814 closure_wait_event(&c->btree_interior_update_wait,
815 !bch2_btree_interior_updates_nr_pending(c));
9ca53b55 816again:
a1d58243 817 ret = bch2_gc_start(c, metadata_only);
9ca53b55 818 if (ret)
1c6fdbd8
KO
819 goto out;
820
1c6fdbd8
KO
821 bch2_mark_superblocks(c);
822
d0734356 823 ret = bch2_gc_btrees(c, journal_keys, initial, metadata_only);
9ca53b55 824 if (ret)
2252aa27 825 goto out;
1c6fdbd8 826
00b8ccf7 827#if 0
1c6fdbd8 828 bch2_mark_pending_btree_node_frees(c);
00b8ccf7 829#endif
1c6fdbd8
KO
830 bch2_mark_allocator_buckets(c);
831
1c6fdbd8
KO
832 c->gc_count++;
833out:
6122ab63
KO
834 if (!ret &&
835 (test_bit(BCH_FS_FIXED_GENS, &c->flags) ||
29364f34 836 (!iter && bch2_test_restart_gc))) {
9ca53b55
KO
837 /*
838 * XXX: make sure gens we fixed got saved
839 */
840 if (iter++ <= 2) {
841 bch_info(c, "Fixed gens, restarting mark and sweep:");
842 clear_bit(BCH_FS_FIXED_GENS, &c->flags);
28062d32 843 __gc_pos_set(c, gc_phase(GC_PHASE_NOT_RUNNING));
05b3d5ac
KO
844
845 percpu_down_write(&c->mark_lock);
28062d32 846 bch2_gc_free(c);
05b3d5ac 847 percpu_up_write(&c->mark_lock);
89b05118
KO
848 /* flush fsck errors, reset counters */
849 bch2_flush_fsck_errs(c);
05b3d5ac 850
9ca53b55
KO
851 goto again;
852 }
853
854 bch_info(c, "Unable to fix bucket gens, looping");
855 ret = -EINVAL;
856 }
857
5e82a9a1
KO
858 if (!ret) {
859 bch2_journal_block(&c->journal);
05b3d5ac 860
5e82a9a1 861 percpu_down_write(&c->mark_lock);
a1d58243 862 ret = bch2_gc_done(c, initial, metadata_only);
9ca53b55 863
5e82a9a1
KO
864 bch2_journal_unblock(&c->journal);
865 } else {
866 percpu_down_write(&c->mark_lock);
867 }
868
9ca53b55 869 /* Indicates that gc is no longer in progress: */
dfe9bfb3 870 __gc_pos_set(c, gc_phase(GC_PHASE_NOT_RUNNING));
9ca53b55
KO
871
872 bch2_gc_free(c);
05b3d5ac
KO
873 percpu_up_write(&c->mark_lock);
874
1c6fdbd8 875 up_write(&c->gc_lock);
9ca53b55 876
1c6fdbd8
KO
877 trace_gc_end(c);
878 bch2_time_stats_update(&c->times[BCH_TIME_btree_gc], start_time);
879
880 /*
881 * Wake up allocator in case it was waiting for buckets
882 * because of not being able to inc gens
883 */
884 for_each_member_device(ca, c, i)
885 bch2_wake_allocator(ca);
886
887 /*
888 * At startup, allocations can happen directly instead of via the
889 * allocator thread - issue wakeup in case they blocked on gc_lock:
890 */
891 closure_wake_up(&c->freelist_wait);
9ca53b55 892 return ret;
1c6fdbd8
KO
893}
894
c47c50f8
KO
895static bool gc_btree_gens_key(struct bch_fs *c, struct bkey_s_c k)
896{
897 struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
898 const struct bch_extent_ptr *ptr;
899
900 percpu_down_read(&c->mark_lock);
901 bkey_for_each_ptr(ptrs, ptr) {
902 struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
903 struct bucket *g = PTR_BUCKET(ca, ptr, false);
904
905 if (gen_after(g->mark.gen, ptr->gen) > 16) {
906 percpu_up_read(&c->mark_lock);
907 return true;
908 }
909 }
910
911 bkey_for_each_ptr(ptrs, ptr) {
912 struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
913 struct bucket *g = PTR_BUCKET(ca, ptr, false);
914
915 if (gen_after(g->gc_gen, ptr->gen))
916 g->gc_gen = ptr->gen;
917 }
918 percpu_up_read(&c->mark_lock);
919
920 return false;
921}
922
451570a5
KO
923/*
924 * For recalculating oldest gen, we only need to walk keys in leaf nodes; btree
925 * node pointers currently never have cached pointers that can become stale:
926 */
c47c50f8 927static int bch2_gc_btree_gens(struct bch_fs *c, enum btree_id btree_id)
451570a5
KO
928{
929 struct btree_trans trans;
930 struct btree_iter *iter;
931 struct bkey_s_c k;
c47c50f8
KO
932 struct bkey_on_stack sk;
933 int ret = 0;
451570a5 934
c47c50f8 935 bkey_on_stack_init(&sk);
451570a5
KO
936 bch2_trans_init(&trans, c, 0, 0);
937
c47c50f8
KO
938 iter = bch2_trans_get_iter(&trans, btree_id, POS_MIN,
939 BTREE_ITER_PREFETCH);
451570a5 940
c47c50f8
KO
941 while ((k = bch2_btree_iter_peek(iter)).k &&
942 !(ret = bkey_err(k))) {
943 if (gc_btree_gens_key(c, k)) {
944 bkey_on_stack_reassemble(&sk, c, k);
945 bch2_extent_normalize(c, bkey_i_to_s(sk.k));
451570a5 946
c47c50f8 947 bch2_btree_iter_set_pos(iter, bkey_start_pos(&sk.k->k));
451570a5 948
c47c50f8 949 bch2_trans_update(&trans, iter, sk.k, 0);
451570a5 950
c47c50f8
KO
951 ret = bch2_trans_commit(&trans, NULL, NULL,
952 BTREE_INSERT_NOFAIL);
953 if (ret == -EINTR)
954 continue;
955 if (ret) {
956 break;
451570a5
KO
957 }
958 }
c47c50f8
KO
959
960 bch2_btree_iter_next(iter);
451570a5
KO
961 }
962
963 bch2_trans_exit(&trans);
c47c50f8
KO
964 bkey_on_stack_exit(&sk, c);
965
451570a5
KO
966 return ret;
967}
968
969int bch2_gc_gens(struct bch_fs *c)
970{
971 struct bch_dev *ca;
972 struct bucket_array *buckets;
973 struct bucket *g;
974 unsigned i;
975 int ret;
976
b9c3d139
KO
977 /*
978 * Ideally we would be using state_lock and not gc_lock here, but that
979 * introduces a deadlock in the RO path - we currently take the state
980 * lock at the start of going RO, thus the gc thread may get stuck:
981 */
982 down_read(&c->gc_lock);
451570a5
KO
983
984 for_each_member_device(ca, c, i) {
985 down_read(&ca->bucket_lock);
986 buckets = bucket_array(ca);
987
988 for_each_bucket(g, buckets)
989 g->gc_gen = g->mark.gen;
990 up_read(&ca->bucket_lock);
991 }
992
993 for (i = 0; i < BTREE_ID_NR; i++)
994 if (btree_node_type_needs_gc(i)) {
995 ret = bch2_gc_btree_gens(c, i);
74ed7e56
KO
996 if (ret) {
997 bch_err(c, "error recalculating oldest_gen: %i", ret);
451570a5 998 goto err;
74ed7e56 999 }
451570a5
KO
1000 }
1001
1002 for_each_member_device(ca, c, i) {
1003 down_read(&ca->bucket_lock);
1004 buckets = bucket_array(ca);
1005
1006 for_each_bucket(g, buckets)
1007 g->oldest_gen = g->gc_gen;
1008 up_read(&ca->bucket_lock);
1009 }
74ed7e56
KO
1010
1011 c->gc_count++;
451570a5 1012err:
b9c3d139 1013 up_read(&c->gc_lock);
451570a5
KO
1014 return ret;
1015}
1016
1c6fdbd8
KO
1017/* Btree coalescing */
1018
1019static void recalc_packed_keys(struct btree *b)
1020{
216c9fac 1021 struct bset *i = btree_bset_first(b);
1c6fdbd8
KO
1022 struct bkey_packed *k;
1023
1024 memset(&b->nr, 0, sizeof(b->nr));
1025
1026 BUG_ON(b->nsets != 1);
1027
216c9fac 1028 vstruct_for_each(i, k)
1c6fdbd8
KO
1029 btree_keys_account_key_add(&b->nr, 0, k);
1030}
1031
1032static void bch2_coalesce_nodes(struct bch_fs *c, struct btree_iter *iter,
1033 struct btree *old_nodes[GC_MERGE_NODES])
1034{
1035 struct btree *parent = btree_node_parent(iter, old_nodes[0]);
1036 unsigned i, nr_old_nodes, nr_new_nodes, u64s = 0;
1037 unsigned blocks = btree_blocks(c) * 2 / 3;
1038 struct btree *new_nodes[GC_MERGE_NODES];
1039 struct btree_update *as;
1040 struct keylist keylist;
1041 struct bkey_format_state format_state;
1042 struct bkey_format new_format;
1043
1044 memset(new_nodes, 0, sizeof(new_nodes));
1045 bch2_keylist_init(&keylist, NULL);
1046
1047 /* Count keys that are not deleted */
1048 for (i = 0; i < GC_MERGE_NODES && old_nodes[i]; i++)
1049 u64s += old_nodes[i]->nr.live_u64s;
1050
1051 nr_old_nodes = nr_new_nodes = i;
1052
1053 /* Check if all keys in @old_nodes could fit in one fewer node */
1054 if (nr_old_nodes <= 1 ||
1055 __vstruct_blocks(struct btree_node, c->block_bits,
1056 DIV_ROUND_UP(u64s, nr_old_nodes - 1)) > blocks)
1057 return;
1058
1059 /* Find a format that all keys in @old_nodes can pack into */
1060 bch2_bkey_format_init(&format_state);
1061
1062 for (i = 0; i < nr_old_nodes; i++)
1063 __bch2_btree_calc_format(&format_state, old_nodes[i]);
1064
1065 new_format = bch2_bkey_format_done(&format_state);
1066
1067 /* Check if repacking would make any nodes too big to fit */
1068 for (i = 0; i < nr_old_nodes; i++)
1069 if (!bch2_btree_node_format_fits(c, old_nodes[i], &new_format)) {
1070 trace_btree_gc_coalesce_fail(c,
1071 BTREE_GC_COALESCE_FAIL_FORMAT_FITS);
1072 return;
1073 }
1074
1075 if (bch2_keylist_realloc(&keylist, NULL, 0,
1076 (BKEY_U64s + BKEY_EXTENT_U64s_MAX) * nr_old_nodes)) {
1077 trace_btree_gc_coalesce_fail(c,
1078 BTREE_GC_COALESCE_FAIL_KEYLIST_REALLOC);
1079 return;
1080 }
1081
0f9dda47 1082 as = bch2_btree_update_start(iter->trans, iter->btree_id,
1c6fdbd8
KO
1083 btree_update_reserve_required(c, parent) + nr_old_nodes,
1084 BTREE_INSERT_NOFAIL|
1085 BTREE_INSERT_USE_RESERVE,
1086 NULL);
1087 if (IS_ERR(as)) {
1088 trace_btree_gc_coalesce_fail(c,
1089 BTREE_GC_COALESCE_FAIL_RESERVE_GET);
1090 bch2_keylist_free(&keylist, NULL);
1091 return;
1092 }
1093
1094 trace_btree_gc_coalesce(c, old_nodes[0]);
1095
1096 for (i = 0; i < nr_old_nodes; i++)
1097 bch2_btree_interior_update_will_free_node(as, old_nodes[i]);
1098
1099 /* Repack everything with @new_format and sort down to one bset */
1100 for (i = 0; i < nr_old_nodes; i++)
1101 new_nodes[i] =
1102 __bch2_btree_node_alloc_replacement(as, old_nodes[i],
1103 new_format);
1104
1105 /*
1106 * Conceptually we concatenate the nodes together and slice them
1107 * up at different boundaries.
1108 */
1109 for (i = nr_new_nodes - 1; i > 0; --i) {
1110 struct btree *n1 = new_nodes[i];
1111 struct btree *n2 = new_nodes[i - 1];
1112
1113 struct bset *s1 = btree_bset_first(n1);
1114 struct bset *s2 = btree_bset_first(n2);
1115 struct bkey_packed *k, *last = NULL;
1116
1117 /* Calculate how many keys from @n2 we could fit inside @n1 */
1118 u64s = 0;
1119
1120 for (k = s2->start;
1121 k < vstruct_last(s2) &&
1122 vstruct_blocks_plus(n1->data, c->block_bits,
1123 u64s + k->u64s) <= blocks;
ad44bdc3 1124 k = bkey_next_skip_noops(k, vstruct_last(s2))) {
1c6fdbd8
KO
1125 last = k;
1126 u64s += k->u64s;
1127 }
1128
1129 if (u64s == le16_to_cpu(s2->u64s)) {
1130 /* n2 fits entirely in n1 */
1131 n1->key.k.p = n1->data->max_key = n2->data->max_key;
1132
1133 memcpy_u64s(vstruct_last(s1),
1134 s2->start,
1135 le16_to_cpu(s2->u64s));
1136 le16_add_cpu(&s1->u64s, le16_to_cpu(s2->u64s));
1137
1138 set_btree_bset_end(n1, n1->set);
1139
c43a6ef9 1140 six_unlock_write(&n2->c.lock);
1c6fdbd8 1141 bch2_btree_node_free_never_inserted(c, n2);
c43a6ef9 1142 six_unlock_intent(&n2->c.lock);
1c6fdbd8
KO
1143
1144 memmove(new_nodes + i - 1,
1145 new_nodes + i,
1146 sizeof(new_nodes[0]) * (nr_new_nodes - i));
1147 new_nodes[--nr_new_nodes] = NULL;
1148 } else if (u64s) {
1149 /* move part of n2 into n1 */
1150 n1->key.k.p = n1->data->max_key =
1151 bkey_unpack_pos(n1, last);
1152
39fb2983 1153 n2->data->min_key = bkey_successor(n1->data->max_key);
1c6fdbd8
KO
1154
1155 memcpy_u64s(vstruct_last(s1),
1156 s2->start, u64s);
1157 le16_add_cpu(&s1->u64s, u64s);
1158
1159 memmove(s2->start,
1160 vstruct_idx(s2, u64s),
1161 (le16_to_cpu(s2->u64s) - u64s) * sizeof(u64));
1162 s2->u64s = cpu_to_le16(le16_to_cpu(s2->u64s) - u64s);
1163
1164 set_btree_bset_end(n1, n1->set);
1165 set_btree_bset_end(n2, n2->set);
1166 }
1167 }
1168
1169 for (i = 0; i < nr_new_nodes; i++) {
1170 struct btree *n = new_nodes[i];
1171
1172 recalc_packed_keys(n);
1173 btree_node_reset_sib_u64s(n);
1174
1175 bch2_btree_build_aux_trees(n);
00b8ccf7
KO
1176
1177 bch2_btree_update_add_new_node(as, n);
c43a6ef9 1178 six_unlock_write(&n->c.lock);
1c6fdbd8
KO
1179
1180 bch2_btree_node_write(c, n, SIX_LOCK_intent);
1181 }
1182
1183 /*
1184 * The keys for the old nodes get deleted. We don't want to insert keys
1185 * that compare equal to the keys for the new nodes we'll also be
1186 * inserting - we can't because keys on a keylist must be strictly
1187 * greater than the previous keys, and we also don't need to since the
1188 * key for the new node will serve the same purpose (overwriting the key
1189 * for the old node).
1190 */
1191 for (i = 0; i < nr_old_nodes; i++) {
1192 struct bkey_i delete;
1193 unsigned j;
1194
1195 for (j = 0; j < nr_new_nodes; j++)
1196 if (!bkey_cmp(old_nodes[i]->key.k.p,
1197 new_nodes[j]->key.k.p))
1198 goto next;
1199
1200 bkey_init(&delete.k);
1201 delete.k.p = old_nodes[i]->key.k.p;
1202 bch2_keylist_add_in_order(&keylist, &delete);
1203next:
1204 i = i;
1205 }
1206
1207 /*
1208 * Keys for the new nodes get inserted: bch2_btree_insert_keys() only
1209 * does the lookup once and thus expects the keys to be in sorted order
1210 * so we have to make sure the new keys are correctly ordered with
1211 * respect to the deleted keys added in the previous loop
1212 */
1213 for (i = 0; i < nr_new_nodes; i++)
1214 bch2_keylist_add_in_order(&keylist, &new_nodes[i]->key);
1215
1216 /* Insert the newly coalesced nodes */
1217 bch2_btree_insert_node(as, parent, iter, &keylist, 0);
1218
1219 BUG_ON(!bch2_keylist_empty(&keylist));
1220
c43a6ef9 1221 BUG_ON(iter->l[old_nodes[0]->c.level].b != old_nodes[0]);
1c6fdbd8
KO
1222
1223 bch2_btree_iter_node_replace(iter, new_nodes[0]);
1224
1225 for (i = 0; i < nr_new_nodes; i++)
00b8ccf7 1226 bch2_btree_update_get_open_buckets(as, new_nodes[i]);
1c6fdbd8
KO
1227
1228 /* Free the old nodes and update our sliding window */
1229 for (i = 0; i < nr_old_nodes; i++) {
1230 bch2_btree_node_free_inmem(c, old_nodes[i], iter);
1c6fdbd8
KO
1231
1232 /*
1233 * the index update might have triggered a split, in which case
1234 * the nodes we coalesced - the new nodes we just created -
1235 * might not be sibling nodes anymore - don't add them to the
1236 * sliding window (except the first):
1237 */
1238 if (!i) {
1239 old_nodes[i] = new_nodes[i];
1240 } else {
1241 old_nodes[i] = NULL;
1c6fdbd8
KO
1242 }
1243 }
1244
ea3532cb
KO
1245 for (i = 0; i < nr_new_nodes; i++)
1246 six_unlock_intent(&new_nodes[i]->c.lock);
1247
1c6fdbd8
KO
1248 bch2_btree_update_done(as);
1249 bch2_keylist_free(&keylist, NULL);
1250}
1251
1252static int bch2_coalesce_btree(struct bch_fs *c, enum btree_id btree_id)
1253{
424eb881
KO
1254 struct btree_trans trans;
1255 struct btree_iter *iter;
1c6fdbd8
KO
1256 struct btree *b;
1257 bool kthread = (current->flags & PF_KTHREAD) != 0;
1258 unsigned i;
1259
1260 /* Sliding window of adjacent btree nodes */
1261 struct btree *merge[GC_MERGE_NODES];
1262 u32 lock_seq[GC_MERGE_NODES];
1263
20bceecb 1264 bch2_trans_init(&trans, c, 0, 0);
424eb881 1265
1c6fdbd8
KO
1266 /*
1267 * XXX: We don't have a good way of positively matching on sibling nodes
1268 * that have the same parent - this code works by handling the cases
1269 * where they might not have the same parent, and is thus fragile. Ugh.
1270 *
1271 * Perhaps redo this to use multiple linked iterators?
1272 */
1273 memset(merge, 0, sizeof(merge));
1274
424eb881 1275 __for_each_btree_node(&trans, iter, btree_id, POS_MIN,
1c6fdbd8
KO
1276 BTREE_MAX_DEPTH, 0,
1277 BTREE_ITER_PREFETCH, b) {
1278 memmove(merge + 1, merge,
1279 sizeof(merge) - sizeof(merge[0]));
1280 memmove(lock_seq + 1, lock_seq,
1281 sizeof(lock_seq) - sizeof(lock_seq[0]));
1282
1283 merge[0] = b;
1284
1285 for (i = 1; i < GC_MERGE_NODES; i++) {
1286 if (!merge[i] ||
c43a6ef9 1287 !six_relock_intent(&merge[i]->c.lock, lock_seq[i]))
1c6fdbd8
KO
1288 break;
1289
c43a6ef9
KO
1290 if (merge[i]->c.level != merge[0]->c.level) {
1291 six_unlock_intent(&merge[i]->c.lock);
1c6fdbd8
KO
1292 break;
1293 }
1294 }
1295 memset(merge + i, 0, (GC_MERGE_NODES - i) * sizeof(merge[0]));
1296
424eb881 1297 bch2_coalesce_nodes(c, iter, merge);
1c6fdbd8
KO
1298
1299 for (i = 1; i < GC_MERGE_NODES && merge[i]; i++) {
c43a6ef9
KO
1300 lock_seq[i] = merge[i]->c.lock.state.seq;
1301 six_unlock_intent(&merge[i]->c.lock);
1c6fdbd8
KO
1302 }
1303
c43a6ef9 1304 lock_seq[0] = merge[0]->c.lock.state.seq;
1c6fdbd8
KO
1305
1306 if (kthread && kthread_should_stop()) {
424eb881 1307 bch2_trans_exit(&trans);
1c6fdbd8
KO
1308 return -ESHUTDOWN;
1309 }
1310
424eb881 1311 bch2_trans_cond_resched(&trans);
1c6fdbd8
KO
1312
1313 /*
1314 * If the parent node wasn't relocked, it might have been split
1315 * and the nodes in our sliding window might not have the same
1316 * parent anymore - blow away the sliding window:
1317 */
424eb881
KO
1318 if (btree_iter_node(iter, iter->level + 1) &&
1319 !btree_node_intent_locked(iter, iter->level + 1))
1c6fdbd8
KO
1320 memset(merge + 1, 0,
1321 (GC_MERGE_NODES - 1) * sizeof(merge[0]));
1322 }
424eb881 1323 return bch2_trans_exit(&trans);
1c6fdbd8
KO
1324}
1325
1326/**
1327 * bch_coalesce - coalesce adjacent nodes with low occupancy
1328 */
1329void bch2_coalesce(struct bch_fs *c)
1330{
1331 enum btree_id id;
1332
1c6fdbd8
KO
1333 down_read(&c->gc_lock);
1334 trace_gc_coalesce_start(c);
1335
1336 for (id = 0; id < BTREE_ID_NR; id++) {
1337 int ret = c->btree_roots[id].b
1338 ? bch2_coalesce_btree(c, id)
1339 : 0;
1340
1341 if (ret) {
1342 if (ret != -ESHUTDOWN)
1343 bch_err(c, "btree coalescing failed: %d", ret);
1c6fdbd8
KO
1344 return;
1345 }
1346 }
1347
1348 trace_gc_coalesce_end(c);
1349 up_read(&c->gc_lock);
1350}
1351
1352static int bch2_gc_thread(void *arg)
1353{
1354 struct bch_fs *c = arg;
1355 struct io_clock *clock = &c->io_clock[WRITE];
1356 unsigned long last = atomic_long_read(&clock->now);
1357 unsigned last_kick = atomic_read(&c->kick_gc);
9ca53b55 1358 int ret;
1c6fdbd8
KO
1359
1360 set_freezable();
1361
1362 while (1) {
1363 while (1) {
1364 set_current_state(TASK_INTERRUPTIBLE);
1365
1366 if (kthread_should_stop()) {
1367 __set_current_state(TASK_RUNNING);
1368 return 0;
1369 }
1370
1371 if (atomic_read(&c->kick_gc) != last_kick)
1372 break;
1373
1374 if (c->btree_gc_periodic) {
1375 unsigned long next = last + c->capacity / 16;
1376
1377 if (atomic_long_read(&clock->now) >= next)
1378 break;
1379
1380 bch2_io_clock_schedule_timeout(clock, next);
1381 } else {
1382 schedule();
1383 }
1384
1385 try_to_freeze();
1386 }
1387 __set_current_state(TASK_RUNNING);
1388
1389 last = atomic_long_read(&clock->now);
1390 last_kick = atomic_read(&c->kick_gc);
1391
451570a5
KO
1392 /*
1393 * Full gc is currently incompatible with btree key cache:
1394 */
1395#if 0
a1d58243 1396 ret = bch2_gc(c, NULL, false, false);
451570a5
KO
1397#else
1398 ret = bch2_gc_gens(c);
1399#endif
8d6b6222 1400 if (ret < 0)
9ca53b55 1401 bch_err(c, "btree gc failed: %i", ret);
1c6fdbd8
KO
1402
1403 debug_check_no_locks_held();
1404 }
1405
1406 return 0;
1407}
1408
1409void bch2_gc_thread_stop(struct bch_fs *c)
1410{
1411 struct task_struct *p;
1412
1413 p = c->gc_thread;
1414 c->gc_thread = NULL;
1415
1416 if (p) {
1417 kthread_stop(p);
1418 put_task_struct(p);
1419 }
1420}
1421
1422int bch2_gc_thread_start(struct bch_fs *c)
1423{
1424 struct task_struct *p;
1425
1426 BUG_ON(c->gc_thread);
1427
b7a9bbfc 1428 p = kthread_create(bch2_gc_thread, c, "bch-gc/%s", c->name);
1c6fdbd8
KO
1429 if (IS_ERR(p))
1430 return PTR_ERR(p);
1431
1432 get_task_struct(p);
1433 c->gc_thread = p;
1434 wake_up_process(p);
1435 return 0;
1436}