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