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