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