]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/btree_cache.c
Update bcachefs sources to bf340e68c7 bcachefs: Ignore cached data when calculating...
[bcachefs-tools-debian] / libbcachefs / btree_cache.c
1 // SPDX-License-Identifier: GPL-2.0
2
3 #include "bcachefs.h"
4 #include "bkey_buf.h"
5 #include "btree_cache.h"
6 #include "btree_io.h"
7 #include "btree_iter.h"
8 #include "btree_locking.h"
9 #include "debug.h"
10 #include "error.h"
11
12 #include <linux/prefetch.h>
13 #include <linux/sched/mm.h>
14 #include <trace/events/bcachefs.h>
15
16 struct lock_class_key bch2_btree_node_lock_key;
17
18 void bch2_recalc_btree_reserve(struct bch_fs *c)
19 {
20         unsigned i, reserve = 16;
21
22         if (!c->btree_roots[0].b)
23                 reserve += 8;
24
25         for (i = 0; i < BTREE_ID_NR; i++)
26                 if (c->btree_roots[i].b)
27                         reserve += min_t(unsigned, 1,
28                                          c->btree_roots[i].b->c.level) * 8;
29
30         c->btree_cache.reserve = reserve;
31 }
32
33 static inline unsigned btree_cache_can_free(struct btree_cache *bc)
34 {
35         return max_t(int, 0, bc->used - bc->reserve);
36 }
37
38 static void btree_node_data_free(struct bch_fs *c, struct btree *b)
39 {
40         struct btree_cache *bc = &c->btree_cache;
41
42         EBUG_ON(btree_node_write_in_flight(b));
43
44         kvpfree(b->data, btree_bytes(c));
45         b->data = NULL;
46 #ifdef __KERNEL__
47         vfree(b->aux_data);
48 #else
49         munmap(b->aux_data, btree_aux_data_bytes(b));
50 #endif
51         b->aux_data = NULL;
52
53         bc->used--;
54         list_move(&b->list, &bc->freed);
55 }
56
57 static int bch2_btree_cache_cmp_fn(struct rhashtable_compare_arg *arg,
58                                    const void *obj)
59 {
60         const struct btree *b = obj;
61         const u64 *v = arg->key;
62
63         return b->hash_val == *v ? 0 : 1;
64 }
65
66 static const struct rhashtable_params bch_btree_cache_params = {
67         .head_offset    = offsetof(struct btree, hash),
68         .key_offset     = offsetof(struct btree, hash_val),
69         .key_len        = sizeof(u64),
70         .obj_cmpfn      = bch2_btree_cache_cmp_fn,
71 };
72
73 static int btree_node_data_alloc(struct bch_fs *c, struct btree *b, gfp_t gfp)
74 {
75         BUG_ON(b->data || b->aux_data);
76
77         b->data = kvpmalloc(btree_bytes(c), gfp);
78         if (!b->data)
79                 return -ENOMEM;
80 #ifdef __KERNEL__
81         b->aux_data = vmalloc_exec(btree_aux_data_bytes(b), gfp);
82 #else
83         b->aux_data = mmap(NULL, btree_aux_data_bytes(b),
84                            PROT_READ|PROT_WRITE|PROT_EXEC,
85                            MAP_PRIVATE|MAP_ANONYMOUS, 0, 0);
86         if (b->aux_data == MAP_FAILED)
87                 b->aux_data = NULL;
88 #endif
89         if (!b->aux_data) {
90                 kvpfree(b->data, btree_bytes(c));
91                 b->data = NULL;
92                 return -ENOMEM;
93         }
94
95         return 0;
96 }
97
98 static struct btree *__btree_node_mem_alloc(struct bch_fs *c)
99 {
100         struct btree *b = kzalloc(sizeof(struct btree), GFP_KERNEL);
101         if (!b)
102                 return NULL;
103
104         bkey_btree_ptr_init(&b->key);
105         __six_lock_init(&b->c.lock, "b->c.lock", &bch2_btree_node_lock_key);
106         INIT_LIST_HEAD(&b->list);
107         INIT_LIST_HEAD(&b->write_blocked);
108         b->byte_order = ilog2(btree_bytes(c));
109         return b;
110 }
111
112 struct btree *__bch2_btree_node_mem_alloc(struct bch_fs *c)
113 {
114         struct btree_cache *bc = &c->btree_cache;
115         struct btree *b = __btree_node_mem_alloc(c);
116         if (!b)
117                 return NULL;
118
119         if (btree_node_data_alloc(c, b, GFP_KERNEL)) {
120                 kfree(b);
121                 return NULL;
122         }
123
124         bc->used++;
125         list_add(&b->list, &bc->freeable);
126         return b;
127 }
128
129 /* Btree in memory cache - hash table */
130
131 void bch2_btree_node_hash_remove(struct btree_cache *bc, struct btree *b)
132 {
133         int ret = rhashtable_remove_fast(&bc->table, &b->hash, bch_btree_cache_params);
134         BUG_ON(ret);
135
136         /* Cause future lookups for this node to fail: */
137         b->hash_val = 0;
138
139         six_lock_wakeup_all(&b->c.lock);
140 }
141
142 int __bch2_btree_node_hash_insert(struct btree_cache *bc, struct btree *b)
143 {
144         BUG_ON(b->hash_val);
145         b->hash_val = btree_ptr_hash_val(&b->key);
146
147         return rhashtable_lookup_insert_fast(&bc->table, &b->hash,
148                                              bch_btree_cache_params);
149 }
150
151 int bch2_btree_node_hash_insert(struct btree_cache *bc, struct btree *b,
152                                 unsigned level, enum btree_id id)
153 {
154         int ret;
155
156         b->c.level      = level;
157         b->c.btree_id   = id;
158
159         if (level)
160                 six_lock_pcpu_alloc(&b->c.lock);
161         else
162                 six_lock_pcpu_free_rcu(&b->c.lock);
163
164         mutex_lock(&bc->lock);
165         ret = __bch2_btree_node_hash_insert(bc, b);
166         if (!ret)
167                 list_add(&b->list, &bc->live);
168         mutex_unlock(&bc->lock);
169
170         return ret;
171 }
172
173 __flatten
174 static inline struct btree *btree_cache_find(struct btree_cache *bc,
175                                      const struct bkey_i *k)
176 {
177         u64 v = btree_ptr_hash_val(k);
178
179         return rhashtable_lookup_fast(&bc->table, &v, bch_btree_cache_params);
180 }
181
182 /*
183  * this version is for btree nodes that have already been freed (we're not
184  * reaping a real btree node)
185  */
186 static int __btree_node_reclaim(struct bch_fs *c, struct btree *b, bool flush)
187 {
188         struct btree_cache *bc = &c->btree_cache;
189         int ret = 0;
190
191         lockdep_assert_held(&bc->lock);
192 wait_on_io:
193         if (b->flags & ((1U << BTREE_NODE_dirty)|
194                         (1U << BTREE_NODE_read_in_flight)|
195                         (1U << BTREE_NODE_write_in_flight))) {
196                 if (!flush)
197                         return -ENOMEM;
198
199                 /* XXX: waiting on IO with btree cache lock held */
200                 bch2_btree_node_wait_on_read(b);
201                 bch2_btree_node_wait_on_write(b);
202         }
203
204         if (!six_trylock_intent(&b->c.lock))
205                 return -ENOMEM;
206
207         if (!six_trylock_write(&b->c.lock))
208                 goto out_unlock_intent;
209
210         /* recheck under lock */
211         if (b->flags & ((1U << BTREE_NODE_read_in_flight)|
212                         (1U << BTREE_NODE_write_in_flight))) {
213                 if (!flush)
214                         goto out_unlock;
215                 six_unlock_write(&b->c.lock);
216                 six_unlock_intent(&b->c.lock);
217                 goto wait_on_io;
218         }
219
220         if (btree_node_noevict(b))
221                 goto out_unlock;
222
223         if (!btree_node_may_write(b))
224                 goto out_unlock;
225
226         if (btree_node_dirty(b)) {
227                 if (!flush ||
228                     test_bit(BCH_FS_HOLD_BTREE_WRITES, &c->flags))
229                         goto out_unlock;
230                 /*
231                  * Using the underscore version because we don't want to compact
232                  * bsets after the write, since this node is about to be evicted
233                  * - unless btree verify mode is enabled, since it runs out of
234                  * the post write cleanup:
235                  */
236                 if (bch2_verify_btree_ondisk)
237                         bch2_btree_node_write(c, b, SIX_LOCK_intent);
238                 else
239                         __bch2_btree_node_write(c, b, false);
240
241                 six_unlock_write(&b->c.lock);
242                 six_unlock_intent(&b->c.lock);
243                 goto wait_on_io;
244         }
245 out:
246         if (b->hash_val && !ret)
247                 trace_btree_node_reap(c, b);
248         return ret;
249 out_unlock:
250         six_unlock_write(&b->c.lock);
251 out_unlock_intent:
252         six_unlock_intent(&b->c.lock);
253         ret = -ENOMEM;
254         goto out;
255 }
256
257 static int btree_node_reclaim(struct bch_fs *c, struct btree *b)
258 {
259         return __btree_node_reclaim(c, b, false);
260 }
261
262 static int btree_node_write_and_reclaim(struct bch_fs *c, struct btree *b)
263 {
264         return __btree_node_reclaim(c, b, true);
265 }
266
267 static unsigned long bch2_btree_cache_scan(struct shrinker *shrink,
268                                            struct shrink_control *sc)
269 {
270         struct bch_fs *c = container_of(shrink, struct bch_fs,
271                                         btree_cache.shrink);
272         struct btree_cache *bc = &c->btree_cache;
273         struct btree *b, *t;
274         unsigned long nr = sc->nr_to_scan;
275         unsigned long can_free;
276         unsigned long touched = 0;
277         unsigned long freed = 0;
278         unsigned i, flags;
279         unsigned long ret = SHRINK_STOP;
280
281         if (bch2_btree_shrinker_disabled)
282                 return SHRINK_STOP;
283
284         /* Return -1 if we can't do anything right now */
285         if (sc->gfp_mask & __GFP_FS)
286                 mutex_lock(&bc->lock);
287         else if (!mutex_trylock(&bc->lock))
288                 goto out_norestore;
289
290         flags = memalloc_nofs_save();
291
292         /*
293          * It's _really_ critical that we don't free too many btree nodes - we
294          * have to always leave ourselves a reserve. The reserve is how we
295          * guarantee that allocating memory for a new btree node can always
296          * succeed, so that inserting keys into the btree can always succeed and
297          * IO can always make forward progress:
298          */
299         nr /= btree_pages(c);
300         can_free = btree_cache_can_free(bc);
301         nr = min_t(unsigned long, nr, can_free);
302
303         i = 0;
304         list_for_each_entry_safe(b, t, &bc->freeable, list) {
305                 /*
306                  * Leave a few nodes on the freeable list, so that a btree split
307                  * won't have to hit the system allocator:
308                  */
309                 if (++i <= 3)
310                         continue;
311
312                 touched++;
313
314                 if (touched >= nr)
315                         break;
316
317                 if (!btree_node_reclaim(c, b)) {
318                         btree_node_data_free(c, b);
319                         six_unlock_write(&b->c.lock);
320                         six_unlock_intent(&b->c.lock);
321                         freed++;
322                 }
323         }
324 restart:
325         list_for_each_entry_safe(b, t, &bc->live, list) {
326                 touched++;
327
328                 if (touched >= nr) {
329                         /* Save position */
330                         if (&t->list != &bc->live)
331                                 list_move_tail(&bc->live, &t->list);
332                         break;
333                 }
334
335                 if (!btree_node_accessed(b) &&
336                     !btree_node_reclaim(c, b)) {
337                         /* can't call bch2_btree_node_hash_remove under lock  */
338                         freed++;
339                         if (&t->list != &bc->live)
340                                 list_move_tail(&bc->live, &t->list);
341
342                         btree_node_data_free(c, b);
343                         mutex_unlock(&bc->lock);
344
345                         bch2_btree_node_hash_remove(bc, b);
346                         six_unlock_write(&b->c.lock);
347                         six_unlock_intent(&b->c.lock);
348
349                         if (freed >= nr)
350                                 goto out;
351
352                         if (sc->gfp_mask & __GFP_FS)
353                                 mutex_lock(&bc->lock);
354                         else if (!mutex_trylock(&bc->lock))
355                                 goto out;
356                         goto restart;
357                 } else
358                         clear_btree_node_accessed(b);
359         }
360
361         mutex_unlock(&bc->lock);
362 out:
363         ret = (unsigned long) freed * btree_pages(c);
364         memalloc_nofs_restore(flags);
365 out_norestore:
366         trace_btree_cache_scan(sc->nr_to_scan,
367                                sc->nr_to_scan / btree_pages(c),
368                                btree_cache_can_free(bc),
369                                ret);
370         return ret;
371 }
372
373 static unsigned long bch2_btree_cache_count(struct shrinker *shrink,
374                                             struct shrink_control *sc)
375 {
376         struct bch_fs *c = container_of(shrink, struct bch_fs,
377                                         btree_cache.shrink);
378         struct btree_cache *bc = &c->btree_cache;
379
380         if (bch2_btree_shrinker_disabled)
381                 return 0;
382
383         return btree_cache_can_free(bc) * btree_pages(c);
384 }
385
386 void bch2_fs_btree_cache_exit(struct bch_fs *c)
387 {
388         struct btree_cache *bc = &c->btree_cache;
389         struct btree *b;
390         unsigned i, flags;
391
392         if (bc->shrink.list.next)
393                 unregister_shrinker(&bc->shrink);
394
395         /* vfree() can allocate memory: */
396         flags = memalloc_nofs_save();
397         mutex_lock(&bc->lock);
398
399         if (c->verify_data)
400                 list_move(&c->verify_data->list, &bc->live);
401
402         kvpfree(c->verify_ondisk, btree_bytes(c));
403
404         for (i = 0; i < BTREE_ID_NR; i++)
405                 if (c->btree_roots[i].b)
406                         list_add(&c->btree_roots[i].b->list, &bc->live);
407
408         list_splice(&bc->freeable, &bc->live);
409
410         while (!list_empty(&bc->live)) {
411                 b = list_first_entry(&bc->live, struct btree, list);
412
413                 BUG_ON(btree_node_read_in_flight(b) ||
414                        btree_node_write_in_flight(b));
415
416                 if (btree_node_dirty(b))
417                         bch2_btree_complete_write(c, b, btree_current_write(b));
418                 clear_btree_node_dirty(c, b);
419
420                 btree_node_data_free(c, b);
421         }
422
423         BUG_ON(atomic_read(&c->btree_cache.dirty));
424
425         while (!list_empty(&bc->freed)) {
426                 b = list_first_entry(&bc->freed, struct btree, list);
427                 list_del(&b->list);
428                 six_lock_pcpu_free(&b->c.lock);
429                 kfree(b);
430         }
431
432         mutex_unlock(&bc->lock);
433         memalloc_nofs_restore(flags);
434
435         if (bc->table_init_done)
436                 rhashtable_destroy(&bc->table);
437 }
438
439 int bch2_fs_btree_cache_init(struct bch_fs *c)
440 {
441         struct btree_cache *bc = &c->btree_cache;
442         unsigned i;
443         int ret = 0;
444
445         pr_verbose_init(c->opts, "");
446
447         ret = rhashtable_init(&bc->table, &bch_btree_cache_params);
448         if (ret)
449                 goto out;
450
451         bc->table_init_done = true;
452
453         bch2_recalc_btree_reserve(c);
454
455         for (i = 0; i < bc->reserve; i++)
456                 if (!__bch2_btree_node_mem_alloc(c)) {
457                         ret = -ENOMEM;
458                         goto out;
459                 }
460
461         list_splice_init(&bc->live, &bc->freeable);
462
463         mutex_init(&c->verify_lock);
464
465         bc->shrink.count_objects        = bch2_btree_cache_count;
466         bc->shrink.scan_objects         = bch2_btree_cache_scan;
467         bc->shrink.seeks                = 4;
468         bc->shrink.batch                = btree_pages(c) * 2;
469         ret = register_shrinker(&bc->shrink);
470 out:
471         pr_verbose_init(c->opts, "ret %i", ret);
472         return ret;
473 }
474
475 void bch2_fs_btree_cache_init_early(struct btree_cache *bc)
476 {
477         mutex_init(&bc->lock);
478         INIT_LIST_HEAD(&bc->live);
479         INIT_LIST_HEAD(&bc->freeable);
480         INIT_LIST_HEAD(&bc->freed);
481 }
482
483 /*
484  * We can only have one thread cannibalizing other cached btree nodes at a time,
485  * or we'll deadlock. We use an open coded mutex to ensure that, which a
486  * cannibalize_bucket() will take. This means every time we unlock the root of
487  * the btree, we need to release this lock if we have it held.
488  */
489 void bch2_btree_cache_cannibalize_unlock(struct bch_fs *c)
490 {
491         struct btree_cache *bc = &c->btree_cache;
492
493         if (bc->alloc_lock == current) {
494                 trace_btree_node_cannibalize_unlock(c);
495                 bc->alloc_lock = NULL;
496                 closure_wake_up(&bc->alloc_wait);
497         }
498 }
499
500 int bch2_btree_cache_cannibalize_lock(struct bch_fs *c, struct closure *cl)
501 {
502         struct btree_cache *bc = &c->btree_cache;
503         struct task_struct *old;
504
505         old = cmpxchg(&bc->alloc_lock, NULL, current);
506         if (old == NULL || old == current)
507                 goto success;
508
509         if (!cl) {
510                 trace_btree_node_cannibalize_lock_fail(c);
511                 return -ENOMEM;
512         }
513
514         closure_wait(&bc->alloc_wait, cl);
515
516         /* Try again, after adding ourselves to waitlist */
517         old = cmpxchg(&bc->alloc_lock, NULL, current);
518         if (old == NULL || old == current) {
519                 /* We raced */
520                 closure_wake_up(&bc->alloc_wait);
521                 goto success;
522         }
523
524         trace_btree_node_cannibalize_lock_fail(c);
525         return -EAGAIN;
526
527 success:
528         trace_btree_node_cannibalize_lock(c);
529         return 0;
530 }
531
532 static struct btree *btree_node_cannibalize(struct bch_fs *c)
533 {
534         struct btree_cache *bc = &c->btree_cache;
535         struct btree *b;
536
537         list_for_each_entry_reverse(b, &bc->live, list)
538                 if (!btree_node_reclaim(c, b))
539                         return b;
540
541         while (1) {
542                 list_for_each_entry_reverse(b, &bc->live, list)
543                         if (!btree_node_write_and_reclaim(c, b))
544                                 return b;
545
546                 /*
547                  * Rare case: all nodes were intent-locked.
548                  * Just busy-wait.
549                  */
550                 WARN_ONCE(1, "btree cache cannibalize failed\n");
551                 cond_resched();
552         }
553 }
554
555 struct btree *bch2_btree_node_mem_alloc(struct bch_fs *c)
556 {
557         struct btree_cache *bc = &c->btree_cache;
558         struct btree *b;
559         u64 start_time = local_clock();
560         unsigned flags;
561
562         flags = memalloc_nofs_save();
563         mutex_lock(&bc->lock);
564
565         /*
566          * btree_free() doesn't free memory; it sticks the node on the end of
567          * the list. Check if there's any freed nodes there:
568          */
569         list_for_each_entry(b, &bc->freeable, list)
570                 if (!btree_node_reclaim(c, b))
571                         goto got_node;
572
573         /*
574          * We never free struct btree itself, just the memory that holds the on
575          * disk node. Check the freed list before allocating a new one:
576          */
577         list_for_each_entry(b, &bc->freed, list)
578                 if (!btree_node_reclaim(c, b))
579                         goto got_node;
580
581         b = NULL;
582 got_node:
583         if (b)
584                 list_del_init(&b->list);
585         mutex_unlock(&bc->lock);
586
587         if (!b) {
588                 b = __btree_node_mem_alloc(c);
589                 if (!b)
590                         goto err;
591
592                 BUG_ON(!six_trylock_intent(&b->c.lock));
593                 BUG_ON(!six_trylock_write(&b->c.lock));
594         }
595
596         if (!b->data) {
597                 if (btree_node_data_alloc(c, b, __GFP_NOWARN|GFP_KERNEL))
598                         goto err;
599
600                 mutex_lock(&bc->lock);
601                 bc->used++;
602                 mutex_unlock(&bc->lock);
603         }
604
605         BUG_ON(btree_node_hashed(b));
606         BUG_ON(btree_node_dirty(b));
607         BUG_ON(btree_node_write_in_flight(b));
608 out:
609         b->flags                = 0;
610         b->written              = 0;
611         b->nsets                = 0;
612         b->sib_u64s[0]          = 0;
613         b->sib_u64s[1]          = 0;
614         b->whiteout_u64s        = 0;
615         bch2_btree_keys_init(b);
616         set_btree_node_accessed(b);
617
618         bch2_time_stats_update(&c->times[BCH_TIME_btree_node_mem_alloc],
619                                start_time);
620
621         memalloc_nofs_restore(flags);
622         return b;
623 err:
624         mutex_lock(&bc->lock);
625
626         if (b) {
627                 list_add(&b->list, &bc->freed);
628                 six_unlock_write(&b->c.lock);
629                 six_unlock_intent(&b->c.lock);
630         }
631
632         /* Try to cannibalize another cached btree node: */
633         if (bc->alloc_lock == current) {
634                 b = btree_node_cannibalize(c);
635                 list_del_init(&b->list);
636                 mutex_unlock(&bc->lock);
637
638                 bch2_btree_node_hash_remove(bc, b);
639
640                 trace_btree_node_cannibalize(c);
641                 goto out;
642         }
643
644         mutex_unlock(&bc->lock);
645         memalloc_nofs_restore(flags);
646         return ERR_PTR(-ENOMEM);
647 }
648
649 /* Slowpath, don't want it inlined into btree_iter_traverse() */
650 static noinline struct btree *bch2_btree_node_fill(struct bch_fs *c,
651                                 struct btree_trans *trans,
652                                 struct btree_path *path,
653                                 const struct bkey_i *k,
654                                 enum btree_id btree_id,
655                                 unsigned level,
656                                 enum six_lock_type lock_type,
657                                 bool sync)
658 {
659         struct btree_cache *bc = &c->btree_cache;
660         struct btree *b;
661         u32 seq;
662
663         BUG_ON(level + 1 >= BTREE_MAX_DEPTH);
664         /*
665          * Parent node must be locked, else we could read in a btree node that's
666          * been freed:
667          */
668         if (trans && !bch2_btree_node_relock(trans, path, level + 1)) {
669                 trace_trans_restart_relock_parent_for_fill(trans->fn,
670                                         _THIS_IP_, btree_id, &path->pos);
671                 btree_trans_restart(trans);
672                 return ERR_PTR(-EINTR);
673         }
674
675         b = bch2_btree_node_mem_alloc(c);
676         if (IS_ERR(b))
677                 return b;
678
679         bkey_copy(&b->key, k);
680         if (bch2_btree_node_hash_insert(bc, b, level, btree_id)) {
681                 /* raced with another fill: */
682
683                 /* mark as unhashed... */
684                 b->hash_val = 0;
685
686                 mutex_lock(&bc->lock);
687                 list_add(&b->list, &bc->freeable);
688                 mutex_unlock(&bc->lock);
689
690                 six_unlock_write(&b->c.lock);
691                 six_unlock_intent(&b->c.lock);
692                 return NULL;
693         }
694
695         set_btree_node_read_in_flight(b);
696
697         six_unlock_write(&b->c.lock);
698         seq = b->c.lock.state.seq;
699         six_unlock_intent(&b->c.lock);
700
701         /* Unlock before doing IO: */
702         if (trans && sync)
703                 bch2_trans_unlock(trans);
704
705         bch2_btree_node_read(c, b, sync);
706
707         if (!sync)
708                 return NULL;
709
710         if (trans &&
711             (!bch2_trans_relock(trans) ||
712              !bch2_btree_path_relock_intent(trans, path))) {
713                 BUG_ON(!trans->restarted);
714                 return ERR_PTR(-EINTR);
715         }
716
717         if (!six_relock_type(&b->c.lock, lock_type, seq)) {
718                 trace_trans_restart_relock_after_fill(trans->fn, _THIS_IP_,
719                                            btree_id, &path->pos);
720                 btree_trans_restart(trans);
721                 return ERR_PTR(-EINTR);
722         }
723
724         return b;
725 }
726
727 static int lock_node_check_fn(struct six_lock *lock, void *p)
728 {
729         struct btree *b = container_of(lock, struct btree, c.lock);
730         const struct bkey_i *k = p;
731
732         return b->hash_val == btree_ptr_hash_val(k) ? 0 : -1;
733 }
734
735 static noinline void btree_bad_header(struct bch_fs *c, struct btree *b)
736 {
737         char buf1[200], buf2[100], buf3[100];
738
739         if (!test_bit(BCH_FS_INITIAL_GC_DONE, &c->flags))
740                 return;
741
742         bch2_bkey_val_to_text(&PBUF(buf1), c, bkey_i_to_s_c(&b->key));
743         bch2_bpos_to_text(&PBUF(buf2), b->data->min_key);
744         bch2_bpos_to_text(&PBUF(buf3), b->data->max_key);
745
746         bch2_fs_inconsistent(c, "btree node header doesn't match ptr\n"
747                              "btree %s level %u\n"
748                              "ptr: %s\n"
749                              "header: btree %s level %llu\n"
750                              "min %s max %s\n",
751                              bch2_btree_ids[b->c.btree_id], b->c.level,
752                              buf1,
753                              bch2_btree_ids[BTREE_NODE_ID(b->data)],
754                              BTREE_NODE_LEVEL(b->data),
755                              buf2, buf3);
756 }
757
758 static inline void btree_check_header(struct bch_fs *c, struct btree *b)
759 {
760         if (b->c.btree_id != BTREE_NODE_ID(b->data) ||
761             b->c.level != BTREE_NODE_LEVEL(b->data) ||
762             bpos_cmp(b->data->max_key, b->key.k.p) ||
763             (b->key.k.type == KEY_TYPE_btree_ptr_v2 &&
764              bpos_cmp(b->data->min_key,
765                       bkey_i_to_btree_ptr_v2(&b->key)->v.min_key)))
766                 btree_bad_header(c, b);
767 }
768
769 /**
770  * bch_btree_node_get - find a btree node in the cache and lock it, reading it
771  * in from disk if necessary.
772  *
773  * If IO is necessary and running under generic_make_request, returns -EAGAIN.
774  *
775  * The btree node will have either a read or a write lock held, depending on
776  * the @write parameter.
777  */
778 struct btree *bch2_btree_node_get(struct btree_trans *trans, struct btree_path *path,
779                                   const struct bkey_i *k, unsigned level,
780                                   enum six_lock_type lock_type,
781                                   unsigned long trace_ip)
782 {
783         struct bch_fs *c = trans->c;
784         struct btree_cache *bc = &c->btree_cache;
785         struct btree *b;
786         struct bset_tree *t;
787
788         EBUG_ON(level >= BTREE_MAX_DEPTH);
789
790         b = btree_node_mem_ptr(k);
791
792         /*
793          * Check b->hash_val _before_ calling btree_node_lock() - this might not
794          * be the node we want anymore, and trying to lock the wrong node could
795          * cause an unneccessary transaction restart:
796          */
797         if (likely(c->opts.btree_node_mem_ptr_optimization &&
798                    b &&
799                    b->hash_val == btree_ptr_hash_val(k)))
800                         goto lock_node;
801 retry:
802         b = btree_cache_find(bc, k);
803         if (unlikely(!b)) {
804                 /*
805                  * We must have the parent locked to call bch2_btree_node_fill(),
806                  * else we could read in a btree node from disk that's been
807                  * freed:
808                  */
809                 b = bch2_btree_node_fill(c, trans, path, k, path->btree_id,
810                                          level, lock_type, true);
811
812                 /* We raced and found the btree node in the cache */
813                 if (!b)
814                         goto retry;
815
816                 if (IS_ERR(b))
817                         return b;
818         } else {
819 lock_node:
820                 /*
821                  * There's a potential deadlock with splits and insertions into
822                  * interior nodes we have to avoid:
823                  *
824                  * The other thread might be holding an intent lock on the node
825                  * we want, and they want to update its parent node so they're
826                  * going to upgrade their intent lock on the parent node to a
827                  * write lock.
828                  *
829                  * But if we're holding a read lock on the parent, and we're
830                  * trying to get the intent lock they're holding, we deadlock.
831                  *
832                  * So to avoid this we drop the read locks on parent nodes when
833                  * we're starting to take intent locks - and handle the race.
834                  *
835                  * The race is that they might be about to free the node we
836                  * want, and dropping our read lock on the parent node lets them
837                  * update the parent marking the node we want as freed, and then
838                  * free it:
839                  *
840                  * To guard against this, btree nodes are evicted from the cache
841                  * when they're freed - and b->hash_val is zeroed out, which we
842                  * check for after we lock the node.
843                  *
844                  * Then, bch2_btree_node_relock() on the parent will fail - because
845                  * the parent was modified, when the pointer to the node we want
846                  * was removed - and we'll bail out:
847                  */
848                 if (btree_node_read_locked(path, level + 1))
849                         btree_node_unlock(path, level + 1);
850
851                 if (!btree_node_lock(trans, path, b, k->k.p, level, lock_type,
852                                      lock_node_check_fn, (void *) k, trace_ip)) {
853                         if (!trans->restarted)
854                                 goto retry;
855                         return ERR_PTR(-EINTR);
856                 }
857
858                 if (unlikely(b->hash_val != btree_ptr_hash_val(k) ||
859                              b->c.level != level ||
860                              race_fault())) {
861                         six_unlock_type(&b->c.lock, lock_type);
862                         if (bch2_btree_node_relock(trans, path, level + 1))
863                                 goto retry;
864
865                         trace_trans_restart_btree_node_reused(trans->fn,
866                                                               trace_ip,
867                                                               path->btree_id,
868                                                               &path->pos);
869                         btree_trans_restart(trans);
870                         return ERR_PTR(-EINTR);
871                 }
872         }
873
874         if (unlikely(btree_node_read_in_flight(b))) {
875                 u32 seq = b->c.lock.state.seq;
876
877                 six_unlock_type(&b->c.lock, lock_type);
878                 bch2_trans_unlock(trans);
879
880                 bch2_btree_node_wait_on_read(b);
881
882                 /*
883                  * should_be_locked is not set on this path yet, so we need to
884                  * relock it specifically:
885                  */
886                 if (trans &&
887                     (!bch2_trans_relock(trans) ||
888                      !bch2_btree_path_relock_intent(trans, path))) {
889                         BUG_ON(!trans->restarted);
890                         return ERR_PTR(-EINTR);
891                 }
892
893                 if (!six_relock_type(&b->c.lock, lock_type, seq))
894                         goto retry;
895         }
896
897         prefetch(b->aux_data);
898
899         for_each_bset(b, t) {
900                 void *p = (u64 *) b->aux_data + t->aux_data_offset;
901
902                 prefetch(p + L1_CACHE_BYTES * 0);
903                 prefetch(p + L1_CACHE_BYTES * 1);
904                 prefetch(p + L1_CACHE_BYTES * 2);
905         }
906
907         /* avoid atomic set bit if it's not needed: */
908         if (!btree_node_accessed(b))
909                 set_btree_node_accessed(b);
910
911         if (unlikely(btree_node_read_error(b))) {
912                 six_unlock_type(&b->c.lock, lock_type);
913                 return ERR_PTR(-EIO);
914         }
915
916         EBUG_ON(b->c.btree_id != path->btree_id);
917         EBUG_ON(BTREE_NODE_LEVEL(b->data) != level);
918         btree_check_header(c, b);
919
920         return b;
921 }
922
923 struct btree *bch2_btree_node_get_noiter(struct bch_fs *c,
924                                          const struct bkey_i *k,
925                                          enum btree_id btree_id,
926                                          unsigned level,
927                                          bool nofill)
928 {
929         struct btree_cache *bc = &c->btree_cache;
930         struct btree *b;
931         struct bset_tree *t;
932         int ret;
933
934         EBUG_ON(level >= BTREE_MAX_DEPTH);
935
936         if (c->opts.btree_node_mem_ptr_optimization) {
937                 b = btree_node_mem_ptr(k);
938                 if (b)
939                         goto lock_node;
940         }
941 retry:
942         b = btree_cache_find(bc, k);
943         if (unlikely(!b)) {
944                 if (nofill)
945                         goto out;
946
947                 b = bch2_btree_node_fill(c, NULL, NULL, k, btree_id,
948                                          level, SIX_LOCK_read, true);
949
950                 /* We raced and found the btree node in the cache */
951                 if (!b)
952                         goto retry;
953
954                 if (IS_ERR(b) &&
955                     !bch2_btree_cache_cannibalize_lock(c, NULL))
956                         goto retry;
957
958                 if (IS_ERR(b))
959                         goto out;
960         } else {
961 lock_node:
962                 ret = six_lock_read(&b->c.lock, lock_node_check_fn, (void *) k);
963                 if (ret)
964                         goto retry;
965
966                 if (unlikely(b->hash_val != btree_ptr_hash_val(k) ||
967                              b->c.btree_id != btree_id ||
968                              b->c.level != level)) {
969                         six_unlock_read(&b->c.lock);
970                         goto retry;
971                 }
972         }
973
974         /* XXX: waiting on IO with btree locks held: */
975         __bch2_btree_node_wait_on_read(b);
976
977         prefetch(b->aux_data);
978
979         for_each_bset(b, t) {
980                 void *p = (u64 *) b->aux_data + t->aux_data_offset;
981
982                 prefetch(p + L1_CACHE_BYTES * 0);
983                 prefetch(p + L1_CACHE_BYTES * 1);
984                 prefetch(p + L1_CACHE_BYTES * 2);
985         }
986
987         /* avoid atomic set bit if it's not needed: */
988         if (!btree_node_accessed(b))
989                 set_btree_node_accessed(b);
990
991         if (unlikely(btree_node_read_error(b))) {
992                 six_unlock_read(&b->c.lock);
993                 b = ERR_PTR(-EIO);
994                 goto out;
995         }
996
997         EBUG_ON(b->c.btree_id != btree_id);
998         EBUG_ON(BTREE_NODE_LEVEL(b->data) != level);
999         btree_check_header(c, b);
1000 out:
1001         bch2_btree_cache_cannibalize_unlock(c);
1002         return b;
1003 }
1004
1005 int bch2_btree_node_prefetch(struct bch_fs *c,
1006                              struct btree_trans *trans,
1007                              struct btree_path *path,
1008                              const struct bkey_i *k,
1009                              enum btree_id btree_id, unsigned level)
1010 {
1011         struct btree_cache *bc = &c->btree_cache;
1012         struct btree *b;
1013
1014         BUG_ON(trans && !btree_node_locked(path, level + 1));
1015         BUG_ON(level >= BTREE_MAX_DEPTH);
1016
1017         b = btree_cache_find(bc, k);
1018         if (b)
1019                 return 0;
1020
1021         b = bch2_btree_node_fill(c, trans, path, k, btree_id,
1022                                  level, SIX_LOCK_read, false);
1023         return PTR_ERR_OR_ZERO(b);
1024 }
1025
1026 void bch2_btree_node_evict(struct bch_fs *c, const struct bkey_i *k)
1027 {
1028         struct btree_cache *bc = &c->btree_cache;
1029         struct btree *b;
1030
1031         b = btree_cache_find(bc, k);
1032         if (!b)
1033                 return;
1034 wait_on_io:
1035         /* not allowed to wait on io with btree locks held: */
1036
1037         /* XXX we're called from btree_gc which will be holding other btree
1038          * nodes locked
1039          * */
1040         __bch2_btree_node_wait_on_read(b);
1041         __bch2_btree_node_wait_on_write(b);
1042
1043         six_lock_intent(&b->c.lock, NULL, NULL);
1044         six_lock_write(&b->c.lock, NULL, NULL);
1045
1046         if (btree_node_dirty(b)) {
1047                 __bch2_btree_node_write(c, b, false);
1048                 six_unlock_write(&b->c.lock);
1049                 six_unlock_intent(&b->c.lock);
1050                 goto wait_on_io;
1051         }
1052
1053         BUG_ON(btree_node_dirty(b));
1054
1055         mutex_lock(&bc->lock);
1056         btree_node_data_free(c, b);
1057         bch2_btree_node_hash_remove(bc, b);
1058         mutex_unlock(&bc->lock);
1059
1060         six_unlock_write(&b->c.lock);
1061         six_unlock_intent(&b->c.lock);
1062 }
1063
1064 void bch2_btree_node_to_text(struct printbuf *out, struct bch_fs *c,
1065                              struct btree *b)
1066 {
1067         const struct bkey_format *f = &b->format;
1068         struct bset_stats stats;
1069
1070         memset(&stats, 0, sizeof(stats));
1071
1072         bch2_btree_keys_stats(b, &stats);
1073
1074         pr_buf(out, "l %u ", b->c.level);
1075         bch2_bpos_to_text(out, b->data->min_key);
1076         pr_buf(out, " - ");
1077         bch2_bpos_to_text(out, b->data->max_key);
1078         pr_buf(out, ":\n"
1079                "    ptrs: ");
1080         bch2_val_to_text(out, c, bkey_i_to_s_c(&b->key));
1081
1082         pr_buf(out, "\n"
1083                "    format: u64s %u fields %u %u %u %u %u\n"
1084                "    unpack fn len: %u\n"
1085                "    bytes used %zu/%zu (%zu%% full)\n"
1086                "    sib u64s: %u, %u (merge threshold %u)\n"
1087                "    nr packed keys %u\n"
1088                "    nr unpacked keys %u\n"
1089                "    floats %zu\n"
1090                "    failed unpacked %zu\n",
1091                f->key_u64s,
1092                f->bits_per_field[0],
1093                f->bits_per_field[1],
1094                f->bits_per_field[2],
1095                f->bits_per_field[3],
1096                f->bits_per_field[4],
1097                b->unpack_fn_len,
1098                b->nr.live_u64s * sizeof(u64),
1099                btree_bytes(c) - sizeof(struct btree_node),
1100                b->nr.live_u64s * 100 / btree_max_u64s(c),
1101                b->sib_u64s[0],
1102                b->sib_u64s[1],
1103                c->btree_foreground_merge_threshold,
1104                b->nr.packed_keys,
1105                b->nr.unpacked_keys,
1106                stats.floats,
1107                stats.failed);
1108 }
1109
1110 void bch2_btree_cache_to_text(struct printbuf *out, struct bch_fs *c)
1111 {
1112         pr_buf(out, "nr nodes:\t\t%u\n", c->btree_cache.used);
1113         pr_buf(out, "nr dirty:\t\t%u\n", atomic_read(&c->btree_cache.dirty));
1114         pr_buf(out, "cannibalize lock:\t%p\n", c->btree_cache.alloc_lock);
1115 }