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