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