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