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