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