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