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