]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/btree_gc.c
Update bcachefs sources to d83b992f65 bcachefs: Rewrite journal_seq_blacklist machinery
[bcachefs-tools-debian] / libbcachefs / btree_gc.c
1 /*
2  * Copyright (C) 2010 Kent Overstreet <kent.overstreet@gmail.com>
3  * Copyright (C) 2014 Datera Inc.
4  */
5
6 #include "bcachefs.h"
7 #include "alloc_background.h"
8 #include "alloc_foreground.h"
9 #include "bkey_methods.h"
10 #include "btree_locking.h"
11 #include "btree_update_interior.h"
12 #include "btree_io.h"
13 #include "btree_gc.h"
14 #include "buckets.h"
15 #include "clock.h"
16 #include "debug.h"
17 #include "ec.h"
18 #include "error.h"
19 #include "extents.h"
20 #include "journal.h"
21 #include "journal_io.h"
22 #include "keylist.h"
23 #include "move.h"
24 #include "replicas.h"
25 #include "super-io.h"
26
27 #include <linux/slab.h>
28 #include <linux/bitops.h>
29 #include <linux/freezer.h>
30 #include <linux/kthread.h>
31 #include <linux/preempt.h>
32 #include <linux/rcupdate.h>
33 #include <linux/sched/task.h>
34 #include <trace/events/bcachefs.h>
35
36 static inline void __gc_pos_set(struct bch_fs *c, struct gc_pos new_pos)
37 {
38         write_seqcount_begin(&c->gc_pos_lock);
39         c->gc_pos = new_pos;
40         write_seqcount_end(&c->gc_pos_lock);
41 }
42
43 static inline void gc_pos_set(struct bch_fs *c, struct gc_pos new_pos)
44 {
45         BUG_ON(gc_pos_cmp(new_pos, c->gc_pos) <= 0);
46         __gc_pos_set(c, new_pos);
47 }
48
49 /* range_checks - for validating min/max pos of each btree node: */
50
51 struct range_checks {
52         struct range_level {
53                 struct bpos     min;
54                 struct bpos     max;
55         }                       l[BTREE_MAX_DEPTH];
56         unsigned                depth;
57 };
58
59 static void btree_node_range_checks_init(struct range_checks *r, unsigned depth)
60 {
61         unsigned i;
62
63         for (i = 0; i < BTREE_MAX_DEPTH; i++)
64                 r->l[i].min = r->l[i].max = POS_MIN;
65         r->depth = depth;
66 }
67
68 static void btree_node_range_checks(struct bch_fs *c, struct btree *b,
69                                     struct range_checks *r)
70 {
71         struct range_level *l = &r->l[b->level];
72
73         struct bpos expected_min = bkey_cmp(l->min, l->max)
74                 ? btree_type_successor(b->btree_id, l->max)
75                 : l->max;
76
77         bch2_fs_inconsistent_on(bkey_cmp(b->data->min_key, expected_min), c,
78                 "btree node has incorrect min key: %llu:%llu != %llu:%llu",
79                 b->data->min_key.inode,
80                 b->data->min_key.offset,
81                 expected_min.inode,
82                 expected_min.offset);
83
84         l->max = b->data->max_key;
85
86         if (b->level > r->depth) {
87                 l = &r->l[b->level - 1];
88
89                 bch2_fs_inconsistent_on(bkey_cmp(b->data->min_key, l->min), c,
90                         "btree node min doesn't match min of child nodes: %llu:%llu != %llu:%llu",
91                         b->data->min_key.inode,
92                         b->data->min_key.offset,
93                         l->min.inode,
94                         l->min.offset);
95
96                 bch2_fs_inconsistent_on(bkey_cmp(b->data->max_key, l->max), c,
97                         "btree node max doesn't match max of child nodes: %llu:%llu != %llu:%llu",
98                         b->data->max_key.inode,
99                         b->data->max_key.offset,
100                         l->max.inode,
101                         l->max.offset);
102
103                 if (bkey_cmp(b->data->max_key, POS_MAX))
104                         l->min = l->max =
105                                 btree_type_successor(b->btree_id,
106                                                      b->data->max_key);
107         }
108 }
109
110 /* marking of btree keys/nodes: */
111
112 static int bch2_gc_mark_key(struct bch_fs *c, struct bkey_s_c k,
113                             u8 *max_stale, bool initial)
114 {
115         struct bkey_ptrs_c ptrs = bch2_bkey_ptrs_c(k);
116         const struct bch_extent_ptr *ptr;
117         unsigned flags =
118                 BCH_BUCKET_MARK_GC|
119                 (initial ? BCH_BUCKET_MARK_NOATOMIC : 0);
120         int ret = 0;
121
122         if (initial) {
123                 BUG_ON(journal_seq_verify(c) &&
124                        k.k->version.lo > journal_cur_seq(&c->journal));
125
126                 if (k.k->version.lo > atomic64_read(&c->key_version))
127                         atomic64_set(&c->key_version, k.k->version.lo);
128
129                 if (test_bit(BCH_FS_REBUILD_REPLICAS, &c->flags) ||
130                     fsck_err_on(!bch2_bkey_replicas_marked(c, k, false), c,
131                                 "superblock not marked as containing replicas (type %u)",
132                                 k.k->type)) {
133                         ret = bch2_mark_bkey_replicas(c, k);
134                         if (ret)
135                                 return ret;
136                 }
137
138                 bkey_for_each_ptr(ptrs, ptr) {
139                         struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
140                         struct bucket *g = PTR_BUCKET(ca, ptr, true);
141                         struct bucket *g2 = PTR_BUCKET(ca, ptr, false);
142
143                         if (mustfix_fsck_err_on(!g->gen_valid, c,
144                                         "found ptr with missing gen in alloc btree,\n"
145                                         "type %u gen %u",
146                                         k.k->type, ptr->gen)) {
147                                 g2->_mark.gen   = g->_mark.gen          = ptr->gen;
148                                 g2->_mark.dirty = g->_mark.dirty        = true;
149                                 g2->gen_valid   = g->gen_valid          = true;
150                         }
151
152                         if (mustfix_fsck_err_on(gen_cmp(ptr->gen, g->mark.gen) > 0, c,
153                                         "%u ptr gen in the future: %u > %u",
154                                         k.k->type, ptr->gen, g->mark.gen)) {
155                                 g2->_mark.gen   = g->_mark.gen          = ptr->gen;
156                                 g2->_mark.dirty = g->_mark.dirty        = true;
157                                 g2->gen_valid   = g->gen_valid          = true;
158                                 set_bit(BCH_FS_FIXED_GENS, &c->flags);
159                         }
160                 }
161         }
162
163         bkey_for_each_ptr(ptrs, ptr) {
164                 struct bch_dev *ca = bch_dev_bkey_exists(c, ptr->dev);
165                 struct bucket *g = PTR_BUCKET(ca, ptr, true);
166
167                 if (gen_after(g->oldest_gen, ptr->gen))
168                         g->oldest_gen = ptr->gen;
169
170                 *max_stale = max(*max_stale, ptr_stale(ca, ptr));
171         }
172
173         bch2_mark_key(c, k, true, k.k->size, NULL, 0, flags);
174 fsck_err:
175         return ret;
176 }
177
178 static int btree_gc_mark_node(struct bch_fs *c, struct btree *b,
179                               u8 *max_stale, bool initial)
180 {
181         struct btree_node_iter iter;
182         struct bkey unpacked;
183         struct bkey_s_c k;
184         int ret = 0;
185
186         *max_stale = 0;
187
188         if (!btree_node_type_needs_gc(btree_node_type(b)))
189                 return 0;
190
191         for_each_btree_node_key_unpack(b, k, &iter,
192                                        &unpacked) {
193                 bch2_bkey_debugcheck(c, b, k);
194
195                 ret = bch2_gc_mark_key(c, k, max_stale, initial);
196                 if (ret)
197                         break;
198         }
199
200         return ret;
201 }
202
203 static int bch2_gc_btree(struct bch_fs *c, enum btree_id btree_id,
204                          bool initial, bool metadata_only)
205 {
206         struct btree_trans trans;
207         struct btree_iter *iter;
208         struct btree *b;
209         struct range_checks r;
210         unsigned depth = btree_node_type_needs_gc(btree_id) ? 0 : 1;
211         u8 max_stale;
212         int ret = 0;
213
214         bch2_trans_init(&trans, c);
215
216         gc_pos_set(c, gc_pos_btree(btree_id, POS_MIN, 0));
217
218         /*
219          * if expensive_debug_checks is on, run range_checks on all leaf nodes:
220          *
221          * and on startup, we have to read every btree node (XXX: only if it was
222          * an unclean shutdown)
223          */
224         if (metadata_only)
225                 depth = 1;
226         else if (initial || expensive_debug_checks(c))
227                 depth = 0;
228
229         btree_node_range_checks_init(&r, depth);
230
231         __for_each_btree_node(&trans, iter, btree_id, POS_MIN,
232                               0, depth, BTREE_ITER_PREFETCH, b) {
233                 btree_node_range_checks(c, b, &r);
234
235                 bch2_verify_btree_nr_keys(b);
236
237                 gc_pos_set(c, gc_pos_btree_node(b));
238
239                 ret = btree_gc_mark_node(c, b, &max_stale, initial);
240                 if (ret)
241                         break;
242
243                 if (!initial) {
244                         if (max_stale > 64)
245                                 bch2_btree_node_rewrite(c, iter,
246                                                 b->data->keys.seq,
247                                                 BTREE_INSERT_USE_RESERVE|
248                                                 BTREE_INSERT_NOWAIT|
249                                                 BTREE_INSERT_GC_LOCK_HELD);
250                         else if (!btree_gc_rewrite_disabled(c) &&
251                                  (btree_gc_always_rewrite(c) || max_stale > 16))
252                                 bch2_btree_node_rewrite(c, iter,
253                                                 b->data->keys.seq,
254                                                 BTREE_INSERT_NOWAIT|
255                                                 BTREE_INSERT_GC_LOCK_HELD);
256                 }
257
258                 bch2_trans_cond_resched(&trans);
259         }
260         ret = bch2_trans_exit(&trans) ?: ret;
261         if (ret)
262                 return ret;
263
264         mutex_lock(&c->btree_root_lock);
265         b = c->btree_roots[btree_id].b;
266         if (!btree_node_fake(b))
267                 ret = bch2_gc_mark_key(c, bkey_i_to_s_c(&b->key),
268                                        &max_stale, initial);
269         gc_pos_set(c, gc_pos_btree_root(b->btree_id));
270         mutex_unlock(&c->btree_root_lock);
271
272         return ret;
273 }
274
275 static inline int btree_id_gc_phase_cmp(enum btree_id l, enum btree_id r)
276 {
277         return  (int) btree_id_to_gc_phase(l) -
278                 (int) btree_id_to_gc_phase(r);
279 }
280
281 static int bch2_gc_btrees(struct bch_fs *c, struct list_head *journal,
282                           bool initial, bool metadata_only)
283 {
284         enum btree_id ids[BTREE_ID_NR];
285         u8 max_stale;
286         unsigned i;
287
288         for (i = 0; i < BTREE_ID_NR; i++)
289                 ids[i] = i;
290         bubble_sort(ids, BTREE_ID_NR, btree_id_gc_phase_cmp);
291
292         for (i = 0; i < BTREE_ID_NR; i++) {
293                 enum btree_id id = ids[i];
294                 enum btree_node_type type = __btree_node_type(0, id);
295
296                 int ret = bch2_gc_btree(c, id, initial, metadata_only);
297                 if (ret)
298                         return ret;
299
300                 if (journal && !metadata_only &&
301                     btree_node_type_needs_gc(type)) {
302                         struct bkey_i *k, *n;
303                         struct jset_entry *j;
304                         struct journal_replay *r;
305                         int ret;
306
307                         list_for_each_entry(r, journal, list)
308                                 for_each_jset_key(k, n, j, &r->j) {
309                                         if (type == __btree_node_type(j->level, j->btree_id)) {
310                                                 ret = bch2_gc_mark_key(c,
311                                                         bkey_i_to_s_c(k),
312                                                         &max_stale, initial);
313                                                 if (ret)
314                                                         return ret;
315                                         }
316                                 }
317                 }
318         }
319
320         return 0;
321 }
322
323 static void mark_metadata_sectors(struct bch_fs *c, struct bch_dev *ca,
324                                   u64 start, u64 end,
325                                   enum bch_data_type type,
326                                   unsigned flags)
327 {
328         u64 b = sector_to_bucket(ca, start);
329
330         do {
331                 unsigned sectors =
332                         min_t(u64, bucket_to_sector(ca, b + 1), end) - start;
333
334                 bch2_mark_metadata_bucket(c, ca, b, type, sectors,
335                                           gc_phase(GC_PHASE_SB), flags);
336                 b++;
337                 start += sectors;
338         } while (start < end);
339 }
340
341 void bch2_mark_dev_superblock(struct bch_fs *c, struct bch_dev *ca,
342                               unsigned flags)
343 {
344         struct bch_sb_layout *layout = &ca->disk_sb.sb->layout;
345         unsigned i;
346         u64 b;
347
348         /*
349          * This conditional is kind of gross, but we may be called from the
350          * device add path, before the new device has actually been added to the
351          * running filesystem:
352          */
353         if (c) {
354                 lockdep_assert_held(&c->sb_lock);
355                 percpu_down_read_preempt_disable(&c->mark_lock);
356         } else {
357                 preempt_disable();
358         }
359
360         for (i = 0; i < layout->nr_superblocks; i++) {
361                 u64 offset = le64_to_cpu(layout->sb_offset[i]);
362
363                 if (offset == BCH_SB_SECTOR)
364                         mark_metadata_sectors(c, ca, 0, BCH_SB_SECTOR,
365                                               BCH_DATA_SB, flags);
366
367                 mark_metadata_sectors(c, ca, offset,
368                                       offset + (1 << layout->sb_max_size_bits),
369                                       BCH_DATA_SB, flags);
370         }
371
372         for (i = 0; i < ca->journal.nr; i++) {
373                 b = ca->journal.buckets[i];
374                 bch2_mark_metadata_bucket(c, ca, b, BCH_DATA_JOURNAL,
375                                           ca->mi.bucket_size,
376                                           gc_phase(GC_PHASE_SB), flags);
377         }
378
379         if (c) {
380                 percpu_up_read_preempt_enable(&c->mark_lock);
381         } else {
382                 preempt_enable();
383         }
384 }
385
386 static void bch2_mark_superblocks(struct bch_fs *c)
387 {
388         struct bch_dev *ca;
389         unsigned i;
390
391         mutex_lock(&c->sb_lock);
392         gc_pos_set(c, gc_phase(GC_PHASE_SB));
393
394         for_each_online_member(ca, c, i)
395                 bch2_mark_dev_superblock(c, ca, BCH_BUCKET_MARK_GC);
396         mutex_unlock(&c->sb_lock);
397 }
398
399 /* Also see bch2_pending_btree_node_free_insert_done() */
400 static void bch2_mark_pending_btree_node_frees(struct bch_fs *c)
401 {
402         struct btree_update *as;
403         struct pending_btree_node_free *d;
404
405         mutex_lock(&c->btree_interior_update_lock);
406         gc_pos_set(c, gc_phase(GC_PHASE_PENDING_DELETE));
407
408         for_each_pending_btree_node_free(c, as, d)
409                 if (d->index_update_done)
410                         bch2_mark_key(c, bkey_i_to_s_c(&d->key),
411                                       true, 0, NULL, 0,
412                                       BCH_BUCKET_MARK_GC);
413
414         mutex_unlock(&c->btree_interior_update_lock);
415 }
416
417 static void bch2_mark_allocator_buckets(struct bch_fs *c)
418 {
419         struct bch_dev *ca;
420         struct open_bucket *ob;
421         size_t i, j, iter;
422         unsigned ci;
423
424         percpu_down_read_preempt_disable(&c->mark_lock);
425
426         spin_lock(&c->freelist_lock);
427         gc_pos_set(c, gc_pos_alloc(c, NULL));
428
429         for_each_member_device(ca, c, ci) {
430                 fifo_for_each_entry(i, &ca->free_inc, iter)
431                         bch2_mark_alloc_bucket(c, ca, i, true,
432                                                gc_pos_alloc(c, NULL),
433                                                BCH_BUCKET_MARK_GC);
434
435
436
437                 for (j = 0; j < RESERVE_NR; j++)
438                         fifo_for_each_entry(i, &ca->free[j], iter)
439                                 bch2_mark_alloc_bucket(c, ca, i, true,
440                                                        gc_pos_alloc(c, NULL),
441                                                        BCH_BUCKET_MARK_GC);
442         }
443
444         spin_unlock(&c->freelist_lock);
445
446         for (ob = c->open_buckets;
447              ob < c->open_buckets + ARRAY_SIZE(c->open_buckets);
448              ob++) {
449                 spin_lock(&ob->lock);
450                 if (ob->valid) {
451                         gc_pos_set(c, gc_pos_alloc(c, ob));
452                         ca = bch_dev_bkey_exists(c, ob->ptr.dev);
453                         bch2_mark_alloc_bucket(c, ca, PTR_BUCKET_NR(ca, &ob->ptr), true,
454                                                gc_pos_alloc(c, ob),
455                                                BCH_BUCKET_MARK_GC);
456                 }
457                 spin_unlock(&ob->lock);
458         }
459
460         percpu_up_read_preempt_enable(&c->mark_lock);
461 }
462
463 static void bch2_gc_free(struct bch_fs *c)
464 {
465         struct bch_dev *ca;
466         unsigned i;
467
468         genradix_free(&c->stripes[1]);
469
470         for_each_member_device(ca, c, i) {
471                 kvpfree(rcu_dereference_protected(ca->buckets[1], 1),
472                         sizeof(struct bucket_array) +
473                         ca->mi.nbuckets * sizeof(struct bucket));
474                 ca->buckets[1] = NULL;
475
476                 free_percpu(ca->usage[1]);
477                 ca->usage[1] = NULL;
478         }
479
480         free_percpu(c->usage[1]);
481         c->usage[1] = NULL;
482 }
483
484 static int bch2_gc_done(struct bch_fs *c,
485                         bool initial, bool metadata_only)
486 {
487         struct bch_dev *ca;
488         bool verify = !metadata_only &&
489                 (!initial ||
490                  (c->sb.compat & (1ULL << BCH_COMPAT_FEAT_ALLOC_INFO)));
491         unsigned i;
492         int ret = 0;
493
494 #define copy_field(_f, _msg, ...)                                       \
495         if (dst->_f != src->_f) {                                       \
496                 if (verify)                                             \
497                         fsck_err(c, _msg ": got %llu, should be %llu"   \
498                                 , ##__VA_ARGS__, dst->_f, src->_f);     \
499                 dst->_f = src->_f;                                      \
500         }
501 #define copy_stripe_field(_f, _msg, ...)                                \
502         if (dst->_f != src->_f) {                                       \
503                 if (verify)                                             \
504                         fsck_err(c, "stripe %zu has wrong "_msg         \
505                                 ": got %u, should be %u",               \
506                                 dst_iter.pos, ##__VA_ARGS__,            \
507                                 dst->_f, src->_f);                      \
508                 dst->_f = src->_f;                                      \
509                 dst->dirty = true;                                      \
510         }
511 #define copy_bucket_field(_f)                                           \
512         if (dst->b[b].mark._f != src->b[b].mark._f) {                   \
513                 if (verify)                                             \
514                         fsck_err(c, "dev %u bucket %zu has wrong " #_f  \
515                                 ": got %u, should be %u", i, b,         \
516                                 dst->b[b].mark._f, src->b[b].mark._f);  \
517                 dst->b[b]._mark._f = src->b[b].mark._f;                 \
518                 dst->b[b]._mark.dirty = true;                           \
519         }
520 #define copy_dev_field(_f, _msg, ...)                                   \
521         copy_field(_f, "dev %u has wrong " _msg, i, ##__VA_ARGS__)
522 #define copy_fs_field(_f, _msg, ...)                                    \
523         copy_field(_f, "fs has wrong " _msg, ##__VA_ARGS__)
524
525         if (!metadata_only) {
526                 struct genradix_iter dst_iter = genradix_iter_init(&c->stripes[0], 0);
527                 struct genradix_iter src_iter = genradix_iter_init(&c->stripes[1], 0);
528                 struct stripe *dst, *src;
529                 unsigned i;
530
531                 c->ec_stripes_heap.used = 0;
532
533                 while ((dst = genradix_iter_peek(&dst_iter, &c->stripes[0])) &&
534                        (src = genradix_iter_peek(&src_iter, &c->stripes[1]))) {
535                         BUG_ON(src_iter.pos != dst_iter.pos);
536
537                         copy_stripe_field(alive,        "alive");
538                         copy_stripe_field(sectors,      "sectors");
539                         copy_stripe_field(algorithm,    "algorithm");
540                         copy_stripe_field(nr_blocks,    "nr_blocks");
541                         copy_stripe_field(nr_redundant, "nr_redundant");
542                         copy_stripe_field(blocks_nonempty,
543                                           "blocks_nonempty");
544
545                         for (i = 0; i < ARRAY_SIZE(dst->block_sectors); i++)
546                                 copy_stripe_field(block_sectors[i],
547                                                   "block_sectors[%u]", i);
548
549                         if (dst->alive)
550                                 bch2_stripes_heap_insert(c, dst, dst_iter.pos);
551
552                         genradix_iter_advance(&dst_iter, &c->stripes[0]);
553                         genradix_iter_advance(&src_iter, &c->stripes[1]);
554                 }
555         }
556
557         for_each_member_device(ca, c, i) {
558                 struct bucket_array *dst = __bucket_array(ca, 0);
559                 struct bucket_array *src = __bucket_array(ca, 1);
560                 size_t b;
561
562                 for (b = 0; b < src->nbuckets; b++) {
563                         copy_bucket_field(gen);
564                         copy_bucket_field(data_type);
565                         copy_bucket_field(owned_by_allocator);
566                         copy_bucket_field(stripe);
567                         copy_bucket_field(dirty_sectors);
568                         copy_bucket_field(cached_sectors);
569
570                         if (dst->b[b].oldest_gen != src->b[b].oldest_gen) {
571                                 dst->b[b].oldest_gen = src->b[b].oldest_gen;
572                                 dst->b[b]._mark.dirty = true;
573                         }
574                 }
575         };
576
577         bch2_dev_usage_from_buckets(c);
578
579         {
580                 unsigned nr = fs_usage_u64s(c);
581                 struct bch_fs_usage *dst = (void *)
582                         bch2_acc_percpu_u64s((void *) c->usage[0], nr);
583                 struct bch_fs_usage *src = (void *)
584                         bch2_acc_percpu_u64s((void *) c->usage[1], nr);
585
586                 copy_fs_field(hidden,           "hidden");
587                 copy_fs_field(btree,            "btree");
588
589                 if (!metadata_only) {
590                         copy_fs_field(data,     "data");
591                         copy_fs_field(cached,   "cached");
592                         copy_fs_field(reserved, "reserved");
593                         copy_fs_field(nr_inodes,"nr_inodes");
594
595                         for (i = 0; i < BCH_REPLICAS_MAX; i++)
596                                 copy_fs_field(persistent_reserved[i],
597                                               "persistent_reserved[%i]", i);
598                 }
599
600                 for (i = 0; i < c->replicas.nr; i++) {
601                         struct bch_replicas_entry *e =
602                                 cpu_replicas_entry(&c->replicas, i);
603                         char buf[80];
604
605                         if (metadata_only &&
606                             (e->data_type == BCH_DATA_USER ||
607                              e->data_type == BCH_DATA_CACHED))
608                                 continue;
609
610                         bch2_replicas_entry_to_text(&PBUF(buf), e);
611
612                         copy_fs_field(replicas[i], "%s", buf);
613                 }
614         }
615
616 #undef copy_fs_field
617 #undef copy_dev_field
618 #undef copy_bucket_field
619 #undef copy_stripe_field
620 #undef copy_field
621 fsck_err:
622         return ret;
623 }
624
625 static int bch2_gc_start(struct bch_fs *c,
626                          bool metadata_only)
627 {
628         struct bch_dev *ca;
629         unsigned i;
630
631         /*
632          * indicate to stripe code that we need to allocate for the gc stripes
633          * radix tree, too
634          */
635         gc_pos_set(c, gc_phase(GC_PHASE_START));
636
637         BUG_ON(c->usage[1]);
638
639         c->usage[1] = __alloc_percpu_gfp(fs_usage_u64s(c) * sizeof(u64),
640                                          sizeof(u64), GFP_KERNEL);
641         if (!c->usage[1])
642                 return -ENOMEM;
643
644         for_each_member_device(ca, c, i) {
645                 BUG_ON(ca->buckets[1]);
646                 BUG_ON(ca->usage[1]);
647
648                 ca->buckets[1] = kvpmalloc(sizeof(struct bucket_array) +
649                                 ca->mi.nbuckets * sizeof(struct bucket),
650                                 GFP_KERNEL|__GFP_ZERO);
651                 if (!ca->buckets[1]) {
652                         percpu_ref_put(&ca->ref);
653                         return -ENOMEM;
654                 }
655
656                 ca->usage[1] = alloc_percpu(struct bch_dev_usage);
657                 if (!ca->usage[1]) {
658                         percpu_ref_put(&ca->ref);
659                         return -ENOMEM;
660                 }
661         }
662
663         for_each_member_device(ca, c, i) {
664                 struct bucket_array *dst = __bucket_array(ca, 1);
665                 struct bucket_array *src = __bucket_array(ca, 0);
666                 size_t b;
667
668                 dst->first_bucket       = src->first_bucket;
669                 dst->nbuckets           = src->nbuckets;
670
671                 for (b = 0; b < src->nbuckets; b++) {
672                         struct bucket *d = &dst->b[b];
673                         struct bucket *s = &src->b[b];
674
675                         d->_mark.gen = dst->b[b].oldest_gen = s->mark.gen;
676                         d->gen_valid = s->gen_valid;
677
678                         if (metadata_only &&
679                             (s->mark.data_type == BCH_DATA_USER ||
680                              s->mark.data_type == BCH_DATA_CACHED)) {
681                                 d->_mark = s->mark;
682                                 d->_mark.owned_by_allocator = 0;
683                         }
684                 }
685         };
686
687         return bch2_ec_mem_alloc(c, true);
688 }
689
690 /**
691  * bch2_gc - walk _all_ references to buckets, and recompute them:
692  *
693  * Order matters here:
694  *  - Concurrent GC relies on the fact that we have a total ordering for
695  *    everything that GC walks - see  gc_will_visit_node(),
696  *    gc_will_visit_root()
697  *
698  *  - also, references move around in the course of index updates and
699  *    various other crap: everything needs to agree on the ordering
700  *    references are allowed to move around in - e.g., we're allowed to
701  *    start with a reference owned by an open_bucket (the allocator) and
702  *    move it to the btree, but not the reverse.
703  *
704  *    This is necessary to ensure that gc doesn't miss references that
705  *    move around - if references move backwards in the ordering GC
706  *    uses, GC could skip past them
707  */
708 int bch2_gc(struct bch_fs *c, struct list_head *journal,
709             bool initial, bool metadata_only)
710 {
711         struct bch_dev *ca;
712         u64 start_time = local_clock();
713         unsigned i, iter = 0;
714         int ret;
715
716         trace_gc_start(c);
717
718         down_write(&c->gc_lock);
719 again:
720         percpu_down_write(&c->mark_lock);
721         ret = bch2_gc_start(c, metadata_only);
722         percpu_up_write(&c->mark_lock);
723
724         if (ret)
725                 goto out;
726
727         bch2_mark_superblocks(c);
728
729         ret = bch2_gc_btrees(c, journal, initial, metadata_only);
730         if (ret)
731                 goto out;
732
733         bch2_mark_pending_btree_node_frees(c);
734         bch2_mark_allocator_buckets(c);
735
736         c->gc_count++;
737 out:
738         if (!ret &&
739             (test_bit(BCH_FS_FIXED_GENS, &c->flags) ||
740              (!iter && test_restart_gc(c)))) {
741                 /*
742                  * XXX: make sure gens we fixed got saved
743                  */
744                 if (iter++ <= 2) {
745                         bch_info(c, "Fixed gens, restarting mark and sweep:");
746                         clear_bit(BCH_FS_FIXED_GENS, &c->flags);
747                         __gc_pos_set(c, gc_phase(GC_PHASE_NOT_RUNNING));
748
749                         percpu_down_write(&c->mark_lock);
750                         bch2_gc_free(c);
751                         percpu_up_write(&c->mark_lock);
752
753                         goto again;
754                 }
755
756                 bch_info(c, "Unable to fix bucket gens, looping");
757                 ret = -EINVAL;
758         }
759
760         percpu_down_write(&c->mark_lock);
761
762         if (!ret)
763                 ret = bch2_gc_done(c, initial, metadata_only);
764
765         /* Indicates that gc is no longer in progress: */
766         __gc_pos_set(c, gc_phase(GC_PHASE_NOT_RUNNING));
767
768         bch2_gc_free(c);
769         percpu_up_write(&c->mark_lock);
770
771         up_write(&c->gc_lock);
772
773         trace_gc_end(c);
774         bch2_time_stats_update(&c->times[BCH_TIME_btree_gc], start_time);
775
776         /*
777          * Wake up allocator in case it was waiting for buckets
778          * because of not being able to inc gens
779          */
780         for_each_member_device(ca, c, i)
781                 bch2_wake_allocator(ca);
782
783         /*
784          * At startup, allocations can happen directly instead of via the
785          * allocator thread - issue wakeup in case they blocked on gc_lock:
786          */
787         closure_wake_up(&c->freelist_wait);
788         return ret;
789 }
790
791 /* Btree coalescing */
792
793 static void recalc_packed_keys(struct btree *b)
794 {
795         struct bset *i = btree_bset_first(b);
796         struct bkey_packed *k;
797
798         memset(&b->nr, 0, sizeof(b->nr));
799
800         BUG_ON(b->nsets != 1);
801
802         vstruct_for_each(i, k)
803                 btree_keys_account_key_add(&b->nr, 0, k);
804 }
805
806 static void bch2_coalesce_nodes(struct bch_fs *c, struct btree_iter *iter,
807                                 struct btree *old_nodes[GC_MERGE_NODES])
808 {
809         struct btree *parent = btree_node_parent(iter, old_nodes[0]);
810         unsigned i, nr_old_nodes, nr_new_nodes, u64s = 0;
811         unsigned blocks = btree_blocks(c) * 2 / 3;
812         struct btree *new_nodes[GC_MERGE_NODES];
813         struct btree_update *as;
814         struct keylist keylist;
815         struct bkey_format_state format_state;
816         struct bkey_format new_format;
817
818         memset(new_nodes, 0, sizeof(new_nodes));
819         bch2_keylist_init(&keylist, NULL);
820
821         /* Count keys that are not deleted */
822         for (i = 0; i < GC_MERGE_NODES && old_nodes[i]; i++)
823                 u64s += old_nodes[i]->nr.live_u64s;
824
825         nr_old_nodes = nr_new_nodes = i;
826
827         /* Check if all keys in @old_nodes could fit in one fewer node */
828         if (nr_old_nodes <= 1 ||
829             __vstruct_blocks(struct btree_node, c->block_bits,
830                              DIV_ROUND_UP(u64s, nr_old_nodes - 1)) > blocks)
831                 return;
832
833         /* Find a format that all keys in @old_nodes can pack into */
834         bch2_bkey_format_init(&format_state);
835
836         for (i = 0; i < nr_old_nodes; i++)
837                 __bch2_btree_calc_format(&format_state, old_nodes[i]);
838
839         new_format = bch2_bkey_format_done(&format_state);
840
841         /* Check if repacking would make any nodes too big to fit */
842         for (i = 0; i < nr_old_nodes; i++)
843                 if (!bch2_btree_node_format_fits(c, old_nodes[i], &new_format)) {
844                         trace_btree_gc_coalesce_fail(c,
845                                         BTREE_GC_COALESCE_FAIL_FORMAT_FITS);
846                         return;
847                 }
848
849         if (bch2_keylist_realloc(&keylist, NULL, 0,
850                         (BKEY_U64s + BKEY_EXTENT_U64s_MAX) * nr_old_nodes)) {
851                 trace_btree_gc_coalesce_fail(c,
852                                 BTREE_GC_COALESCE_FAIL_KEYLIST_REALLOC);
853                 return;
854         }
855
856         as = bch2_btree_update_start(c, iter->btree_id,
857                         btree_update_reserve_required(c, parent) + nr_old_nodes,
858                         BTREE_INSERT_NOFAIL|
859                         BTREE_INSERT_USE_RESERVE,
860                         NULL);
861         if (IS_ERR(as)) {
862                 trace_btree_gc_coalesce_fail(c,
863                                 BTREE_GC_COALESCE_FAIL_RESERVE_GET);
864                 bch2_keylist_free(&keylist, NULL);
865                 return;
866         }
867
868         trace_btree_gc_coalesce(c, old_nodes[0]);
869
870         for (i = 0; i < nr_old_nodes; i++)
871                 bch2_btree_interior_update_will_free_node(as, old_nodes[i]);
872
873         /* Repack everything with @new_format and sort down to one bset */
874         for (i = 0; i < nr_old_nodes; i++)
875                 new_nodes[i] =
876                         __bch2_btree_node_alloc_replacement(as, old_nodes[i],
877                                                             new_format);
878
879         /*
880          * Conceptually we concatenate the nodes together and slice them
881          * up at different boundaries.
882          */
883         for (i = nr_new_nodes - 1; i > 0; --i) {
884                 struct btree *n1 = new_nodes[i];
885                 struct btree *n2 = new_nodes[i - 1];
886
887                 struct bset *s1 = btree_bset_first(n1);
888                 struct bset *s2 = btree_bset_first(n2);
889                 struct bkey_packed *k, *last = NULL;
890
891                 /* Calculate how many keys from @n2 we could fit inside @n1 */
892                 u64s = 0;
893
894                 for (k = s2->start;
895                      k < vstruct_last(s2) &&
896                      vstruct_blocks_plus(n1->data, c->block_bits,
897                                          u64s + k->u64s) <= blocks;
898                      k = bkey_next(k)) {
899                         last = k;
900                         u64s += k->u64s;
901                 }
902
903                 if (u64s == le16_to_cpu(s2->u64s)) {
904                         /* n2 fits entirely in n1 */
905                         n1->key.k.p = n1->data->max_key = n2->data->max_key;
906
907                         memcpy_u64s(vstruct_last(s1),
908                                     s2->start,
909                                     le16_to_cpu(s2->u64s));
910                         le16_add_cpu(&s1->u64s, le16_to_cpu(s2->u64s));
911
912                         set_btree_bset_end(n1, n1->set);
913
914                         six_unlock_write(&n2->lock);
915                         bch2_btree_node_free_never_inserted(c, n2);
916                         six_unlock_intent(&n2->lock);
917
918                         memmove(new_nodes + i - 1,
919                                 new_nodes + i,
920                                 sizeof(new_nodes[0]) * (nr_new_nodes - i));
921                         new_nodes[--nr_new_nodes] = NULL;
922                 } else if (u64s) {
923                         /* move part of n2 into n1 */
924                         n1->key.k.p = n1->data->max_key =
925                                 bkey_unpack_pos(n1, last);
926
927                         n2->data->min_key =
928                                 btree_type_successor(iter->btree_id,
929                                                      n1->data->max_key);
930
931                         memcpy_u64s(vstruct_last(s1),
932                                     s2->start, u64s);
933                         le16_add_cpu(&s1->u64s, u64s);
934
935                         memmove(s2->start,
936                                 vstruct_idx(s2, u64s),
937                                 (le16_to_cpu(s2->u64s) - u64s) * sizeof(u64));
938                         s2->u64s = cpu_to_le16(le16_to_cpu(s2->u64s) - u64s);
939
940                         set_btree_bset_end(n1, n1->set);
941                         set_btree_bset_end(n2, n2->set);
942                 }
943         }
944
945         for (i = 0; i < nr_new_nodes; i++) {
946                 struct btree *n = new_nodes[i];
947
948                 recalc_packed_keys(n);
949                 btree_node_reset_sib_u64s(n);
950
951                 bch2_btree_build_aux_trees(n);
952                 six_unlock_write(&n->lock);
953
954                 bch2_btree_node_write(c, n, SIX_LOCK_intent);
955         }
956
957         /*
958          * The keys for the old nodes get deleted. We don't want to insert keys
959          * that compare equal to the keys for the new nodes we'll also be
960          * inserting - we can't because keys on a keylist must be strictly
961          * greater than the previous keys, and we also don't need to since the
962          * key for the new node will serve the same purpose (overwriting the key
963          * for the old node).
964          */
965         for (i = 0; i < nr_old_nodes; i++) {
966                 struct bkey_i delete;
967                 unsigned j;
968
969                 for (j = 0; j < nr_new_nodes; j++)
970                         if (!bkey_cmp(old_nodes[i]->key.k.p,
971                                       new_nodes[j]->key.k.p))
972                                 goto next;
973
974                 bkey_init(&delete.k);
975                 delete.k.p = old_nodes[i]->key.k.p;
976                 bch2_keylist_add_in_order(&keylist, &delete);
977 next:
978                 i = i;
979         }
980
981         /*
982          * Keys for the new nodes get inserted: bch2_btree_insert_keys() only
983          * does the lookup once and thus expects the keys to be in sorted order
984          * so we have to make sure the new keys are correctly ordered with
985          * respect to the deleted keys added in the previous loop
986          */
987         for (i = 0; i < nr_new_nodes; i++)
988                 bch2_keylist_add_in_order(&keylist, &new_nodes[i]->key);
989
990         /* Insert the newly coalesced nodes */
991         bch2_btree_insert_node(as, parent, iter, &keylist, 0);
992
993         BUG_ON(!bch2_keylist_empty(&keylist));
994
995         BUG_ON(iter->l[old_nodes[0]->level].b != old_nodes[0]);
996
997         bch2_btree_iter_node_replace(iter, new_nodes[0]);
998
999         for (i = 0; i < nr_new_nodes; i++)
1000                 bch2_open_buckets_put(c, &new_nodes[i]->ob);
1001
1002         /* Free the old nodes and update our sliding window */
1003         for (i = 0; i < nr_old_nodes; i++) {
1004                 bch2_btree_node_free_inmem(c, old_nodes[i], iter);
1005
1006                 /*
1007                  * the index update might have triggered a split, in which case
1008                  * the nodes we coalesced - the new nodes we just created -
1009                  * might not be sibling nodes anymore - don't add them to the
1010                  * sliding window (except the first):
1011                  */
1012                 if (!i) {
1013                         old_nodes[i] = new_nodes[i];
1014                 } else {
1015                         old_nodes[i] = NULL;
1016                         if (new_nodes[i])
1017                                 six_unlock_intent(&new_nodes[i]->lock);
1018                 }
1019         }
1020
1021         bch2_btree_update_done(as);
1022         bch2_keylist_free(&keylist, NULL);
1023 }
1024
1025 static int bch2_coalesce_btree(struct bch_fs *c, enum btree_id btree_id)
1026 {
1027         struct btree_trans trans;
1028         struct btree_iter *iter;
1029         struct btree *b;
1030         bool kthread = (current->flags & PF_KTHREAD) != 0;
1031         unsigned i;
1032
1033         /* Sliding window of adjacent btree nodes */
1034         struct btree *merge[GC_MERGE_NODES];
1035         u32 lock_seq[GC_MERGE_NODES];
1036
1037         bch2_trans_init(&trans, c);
1038
1039         /*
1040          * XXX: We don't have a good way of positively matching on sibling nodes
1041          * that have the same parent - this code works by handling the cases
1042          * where they might not have the same parent, and is thus fragile. Ugh.
1043          *
1044          * Perhaps redo this to use multiple linked iterators?
1045          */
1046         memset(merge, 0, sizeof(merge));
1047
1048         __for_each_btree_node(&trans, iter, btree_id, POS_MIN,
1049                               BTREE_MAX_DEPTH, 0,
1050                               BTREE_ITER_PREFETCH, b) {
1051                 memmove(merge + 1, merge,
1052                         sizeof(merge) - sizeof(merge[0]));
1053                 memmove(lock_seq + 1, lock_seq,
1054                         sizeof(lock_seq) - sizeof(lock_seq[0]));
1055
1056                 merge[0] = b;
1057
1058                 for (i = 1; i < GC_MERGE_NODES; i++) {
1059                         if (!merge[i] ||
1060                             !six_relock_intent(&merge[i]->lock, lock_seq[i]))
1061                                 break;
1062
1063                         if (merge[i]->level != merge[0]->level) {
1064                                 six_unlock_intent(&merge[i]->lock);
1065                                 break;
1066                         }
1067                 }
1068                 memset(merge + i, 0, (GC_MERGE_NODES - i) * sizeof(merge[0]));
1069
1070                 bch2_coalesce_nodes(c, iter, merge);
1071
1072                 for (i = 1; i < GC_MERGE_NODES && merge[i]; i++) {
1073                         lock_seq[i] = merge[i]->lock.state.seq;
1074                         six_unlock_intent(&merge[i]->lock);
1075                 }
1076
1077                 lock_seq[0] = merge[0]->lock.state.seq;
1078
1079                 if (kthread && kthread_should_stop()) {
1080                         bch2_trans_exit(&trans);
1081                         return -ESHUTDOWN;
1082                 }
1083
1084                 bch2_trans_cond_resched(&trans);
1085
1086                 /*
1087                  * If the parent node wasn't relocked, it might have been split
1088                  * and the nodes in our sliding window might not have the same
1089                  * parent anymore - blow away the sliding window:
1090                  */
1091                 if (btree_iter_node(iter, iter->level + 1) &&
1092                     !btree_node_intent_locked(iter, iter->level + 1))
1093                         memset(merge + 1, 0,
1094                                (GC_MERGE_NODES - 1) * sizeof(merge[0]));
1095         }
1096         return bch2_trans_exit(&trans);
1097 }
1098
1099 /**
1100  * bch_coalesce - coalesce adjacent nodes with low occupancy
1101  */
1102 void bch2_coalesce(struct bch_fs *c)
1103 {
1104         enum btree_id id;
1105
1106         down_read(&c->gc_lock);
1107         trace_gc_coalesce_start(c);
1108
1109         for (id = 0; id < BTREE_ID_NR; id++) {
1110                 int ret = c->btree_roots[id].b
1111                         ? bch2_coalesce_btree(c, id)
1112                         : 0;
1113
1114                 if (ret) {
1115                         if (ret != -ESHUTDOWN)
1116                                 bch_err(c, "btree coalescing failed: %d", ret);
1117                         return;
1118                 }
1119         }
1120
1121         trace_gc_coalesce_end(c);
1122         up_read(&c->gc_lock);
1123 }
1124
1125 static int bch2_gc_thread(void *arg)
1126 {
1127         struct bch_fs *c = arg;
1128         struct io_clock *clock = &c->io_clock[WRITE];
1129         unsigned long last = atomic_long_read(&clock->now);
1130         unsigned last_kick = atomic_read(&c->kick_gc);
1131         int ret;
1132
1133         set_freezable();
1134
1135         while (1) {
1136                 while (1) {
1137                         set_current_state(TASK_INTERRUPTIBLE);
1138
1139                         if (kthread_should_stop()) {
1140                                 __set_current_state(TASK_RUNNING);
1141                                 return 0;
1142                         }
1143
1144                         if (atomic_read(&c->kick_gc) != last_kick)
1145                                 break;
1146
1147                         if (c->btree_gc_periodic) {
1148                                 unsigned long next = last + c->capacity / 16;
1149
1150                                 if (atomic_long_read(&clock->now) >= next)
1151                                         break;
1152
1153                                 bch2_io_clock_schedule_timeout(clock, next);
1154                         } else {
1155                                 schedule();
1156                         }
1157
1158                         try_to_freeze();
1159                 }
1160                 __set_current_state(TASK_RUNNING);
1161
1162                 last = atomic_long_read(&clock->now);
1163                 last_kick = atomic_read(&c->kick_gc);
1164
1165                 ret = bch2_gc(c, NULL, false, false);
1166                 if (ret)
1167                         bch_err(c, "btree gc failed: %i", ret);
1168
1169                 debug_check_no_locks_held();
1170         }
1171
1172         return 0;
1173 }
1174
1175 void bch2_gc_thread_stop(struct bch_fs *c)
1176 {
1177         struct task_struct *p;
1178
1179         p = c->gc_thread;
1180         c->gc_thread = NULL;
1181
1182         if (p) {
1183                 kthread_stop(p);
1184                 put_task_struct(p);
1185         }
1186 }
1187
1188 int bch2_gc_thread_start(struct bch_fs *c)
1189 {
1190         struct task_struct *p;
1191
1192         BUG_ON(c->gc_thread);
1193
1194         p = kthread_create(bch2_gc_thread, c, "bch_gc");
1195         if (IS_ERR(p))
1196                 return PTR_ERR(p);
1197
1198         get_task_struct(p);
1199         c->gc_thread = p;
1200         wake_up_process(p);
1201         return 0;
1202 }