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