]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/btree_cache.c
Update bcachefs sources to 3f3f969859 bcachefs: Fix some compiler warnings
[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 (freed >= 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 (freed >= 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                 if (b)
774                         goto lock_node;
775         }
776 retry:
777         b = btree_cache_find(bc, k);
778         if (unlikely(!b)) {
779                 /*
780                  * We must have the parent locked to call bch2_btree_node_fill(),
781                  * else we could read in a btree node from disk that's been
782                  * freed:
783                  */
784                 b = bch2_btree_node_fill(c, trans, path, k, path->btree_id,
785                                          level, lock_type, true);
786
787                 /* We raced and found the btree node in the cache */
788                 if (!b)
789                         goto retry;
790
791                 if (IS_ERR(b))
792                         return b;
793         } else {
794 lock_node:
795                 /*
796                  * There's a potential deadlock with splits and insertions into
797                  * interior nodes we have to avoid:
798                  *
799                  * The other thread might be holding an intent lock on the node
800                  * we want, and they want to update its parent node so they're
801                  * going to upgrade their intent lock on the parent node to a
802                  * write lock.
803                  *
804                  * But if we're holding a read lock on the parent, and we're
805                  * trying to get the intent lock they're holding, we deadlock.
806                  *
807                  * So to avoid this we drop the read locks on parent nodes when
808                  * we're starting to take intent locks - and handle the race.
809                  *
810                  * The race is that they might be about to free the node we
811                  * want, and dropping our read lock on the parent node lets them
812                  * update the parent marking the node we want as freed, and then
813                  * free it:
814                  *
815                  * To guard against this, btree nodes are evicted from the cache
816                  * when they're freed - and b->hash_val is zeroed out, which we
817                  * check for after we lock the node.
818                  *
819                  * Then, bch2_btree_node_relock() on the parent will fail - because
820                  * the parent was modified, when the pointer to the node we want
821                  * was removed - and we'll bail out:
822                  */
823                 if (btree_node_read_locked(path, level + 1))
824                         btree_node_unlock(path, level + 1);
825
826                 if (!btree_node_lock(trans, path, b, k->k.p, level, lock_type,
827                                      lock_node_check_fn, (void *) k, trace_ip)) {
828                         if (!trans->restarted)
829                                 goto retry;
830                         return ERR_PTR(-EINTR);
831                 }
832
833                 if (unlikely(b->hash_val != btree_ptr_hash_val(k) ||
834                              b->c.level != level ||
835                              race_fault())) {
836                         six_unlock_type(&b->c.lock, lock_type);
837                         if (bch2_btree_node_relock(trans, path, level + 1))
838                                 goto retry;
839
840                         trace_trans_restart_btree_node_reused(trans->ip,
841                                                               trace_ip,
842                                                               path->btree_id,
843                                                               &path->pos);
844                         btree_trans_restart(trans);
845                         return ERR_PTR(-EINTR);
846                 }
847         }
848
849         if (unlikely(btree_node_read_in_flight(b))) {
850                 u32 seq = b->c.lock.state.seq;
851
852                 six_unlock_type(&b->c.lock, lock_type);
853                 bch2_trans_unlock(trans);
854
855                 bch2_btree_node_wait_on_read(b);
856
857                 /*
858                  * should_be_locked is not set on this path yet, so we need to
859                  * relock it specifically:
860                  */
861                 if (trans &&
862                     (!bch2_trans_relock(trans) ||
863                      !bch2_btree_path_relock_intent(trans, path))) {
864                         BUG_ON(!trans->restarted);
865                         return ERR_PTR(-EINTR);
866                 }
867
868                 if (!six_relock_type(&b->c.lock, lock_type, seq))
869                         goto retry;
870         }
871
872         prefetch(b->aux_data);
873
874         for_each_bset(b, t) {
875                 void *p = (u64 *) b->aux_data + t->aux_data_offset;
876
877                 prefetch(p + L1_CACHE_BYTES * 0);
878                 prefetch(p + L1_CACHE_BYTES * 1);
879                 prefetch(p + L1_CACHE_BYTES * 2);
880         }
881
882         /* avoid atomic set bit if it's not needed: */
883         if (!btree_node_accessed(b))
884                 set_btree_node_accessed(b);
885
886         if (unlikely(btree_node_read_error(b))) {
887                 six_unlock_type(&b->c.lock, lock_type);
888                 return ERR_PTR(-EIO);
889         }
890
891         EBUG_ON(b->c.btree_id != path->btree_id);
892         EBUG_ON(BTREE_NODE_LEVEL(b->data) != level);
893         btree_check_header(c, b);
894
895         return b;
896 }
897
898 struct btree *bch2_btree_node_get_noiter(struct bch_fs *c,
899                                          const struct bkey_i *k,
900                                          enum btree_id btree_id,
901                                          unsigned level,
902                                          bool nofill)
903 {
904         struct btree_cache *bc = &c->btree_cache;
905         struct btree *b;
906         struct bset_tree *t;
907         int ret;
908
909         EBUG_ON(level >= BTREE_MAX_DEPTH);
910
911         if (c->opts.btree_node_mem_ptr_optimization) {
912                 b = btree_node_mem_ptr(k);
913                 if (b)
914                         goto lock_node;
915         }
916 retry:
917         b = btree_cache_find(bc, k);
918         if (unlikely(!b)) {
919                 if (nofill)
920                         goto out;
921
922                 b = bch2_btree_node_fill(c, NULL, NULL, k, btree_id,
923                                          level, SIX_LOCK_read, true);
924
925                 /* We raced and found the btree node in the cache */
926                 if (!b)
927                         goto retry;
928
929                 if (IS_ERR(b) &&
930                     !bch2_btree_cache_cannibalize_lock(c, NULL))
931                         goto retry;
932
933                 if (IS_ERR(b))
934                         goto out;
935         } else {
936 lock_node:
937                 ret = six_lock_read(&b->c.lock, lock_node_check_fn, (void *) k);
938                 if (ret)
939                         goto retry;
940
941                 if (unlikely(b->hash_val != btree_ptr_hash_val(k) ||
942                              b->c.btree_id != btree_id ||
943                              b->c.level != level)) {
944                         six_unlock_read(&b->c.lock);
945                         goto retry;
946                 }
947         }
948
949         /* XXX: waiting on IO with btree locks held: */
950         __bch2_btree_node_wait_on_read(b);
951
952         prefetch(b->aux_data);
953
954         for_each_bset(b, t) {
955                 void *p = (u64 *) b->aux_data + t->aux_data_offset;
956
957                 prefetch(p + L1_CACHE_BYTES * 0);
958                 prefetch(p + L1_CACHE_BYTES * 1);
959                 prefetch(p + L1_CACHE_BYTES * 2);
960         }
961
962         /* avoid atomic set bit if it's not needed: */
963         if (!btree_node_accessed(b))
964                 set_btree_node_accessed(b);
965
966         if (unlikely(btree_node_read_error(b))) {
967                 six_unlock_read(&b->c.lock);
968                 b = ERR_PTR(-EIO);
969                 goto out;
970         }
971
972         EBUG_ON(b->c.btree_id != btree_id);
973         EBUG_ON(BTREE_NODE_LEVEL(b->data) != level);
974         btree_check_header(c, b);
975 out:
976         bch2_btree_cache_cannibalize_unlock(c);
977         return b;
978 }
979
980 int bch2_btree_node_prefetch(struct bch_fs *c,
981                              struct btree_trans *trans,
982                              struct btree_path *path,
983                              const struct bkey_i *k,
984                              enum btree_id btree_id, unsigned level)
985 {
986         struct btree_cache *bc = &c->btree_cache;
987         struct btree *b;
988
989         BUG_ON(trans && !btree_node_locked(path, level + 1));
990         BUG_ON(level >= BTREE_MAX_DEPTH);
991
992         b = btree_cache_find(bc, k);
993         if (b)
994                 return 0;
995
996         b = bch2_btree_node_fill(c, trans, path, k, btree_id,
997                                  level, SIX_LOCK_read, false);
998         return PTR_ERR_OR_ZERO(b);
999 }
1000
1001 void bch2_btree_node_evict(struct bch_fs *c, const struct bkey_i *k)
1002 {
1003         struct btree_cache *bc = &c->btree_cache;
1004         struct btree *b;
1005
1006         b = btree_cache_find(bc, k);
1007         if (!b)
1008                 return;
1009 wait_on_io:
1010         /* not allowed to wait on io with btree locks held: */
1011
1012         /* XXX we're called from btree_gc which will be holding other btree
1013          * nodes locked
1014          * */
1015         __bch2_btree_node_wait_on_read(b);
1016         __bch2_btree_node_wait_on_write(b);
1017
1018         six_lock_intent(&b->c.lock, NULL, NULL);
1019         six_lock_write(&b->c.lock, NULL, NULL);
1020
1021         if (btree_node_dirty(b)) {
1022                 __bch2_btree_node_write(c, b, false);
1023                 six_unlock_write(&b->c.lock);
1024                 six_unlock_intent(&b->c.lock);
1025                 goto wait_on_io;
1026         }
1027
1028         BUG_ON(btree_node_dirty(b));
1029
1030         mutex_lock(&bc->lock);
1031         btree_node_data_free(c, b);
1032         bch2_btree_node_hash_remove(bc, b);
1033         mutex_unlock(&bc->lock);
1034
1035         six_unlock_write(&b->c.lock);
1036         six_unlock_intent(&b->c.lock);
1037 }
1038
1039 void bch2_btree_node_to_text(struct printbuf *out, struct bch_fs *c,
1040                              struct btree *b)
1041 {
1042         const struct bkey_format *f = &b->format;
1043         struct bset_stats stats;
1044
1045         memset(&stats, 0, sizeof(stats));
1046
1047         bch2_btree_keys_stats(b, &stats);
1048
1049         pr_buf(out, "l %u ", b->c.level);
1050         bch2_bpos_to_text(out, b->data->min_key);
1051         pr_buf(out, " - ");
1052         bch2_bpos_to_text(out, b->data->max_key);
1053         pr_buf(out, ":\n"
1054                "    ptrs: ");
1055         bch2_val_to_text(out, c, bkey_i_to_s_c(&b->key));
1056
1057         pr_buf(out, "\n"
1058                "    format: u64s %u fields %u %u %u %u %u\n"
1059                "    unpack fn len: %u\n"
1060                "    bytes used %zu/%zu (%zu%% full)\n"
1061                "    sib u64s: %u, %u (merge threshold %u)\n"
1062                "    nr packed keys %u\n"
1063                "    nr unpacked keys %u\n"
1064                "    floats %zu\n"
1065                "    failed unpacked %zu\n",
1066                f->key_u64s,
1067                f->bits_per_field[0],
1068                f->bits_per_field[1],
1069                f->bits_per_field[2],
1070                f->bits_per_field[3],
1071                f->bits_per_field[4],
1072                b->unpack_fn_len,
1073                b->nr.live_u64s * sizeof(u64),
1074                btree_bytes(c) - sizeof(struct btree_node),
1075                b->nr.live_u64s * 100 / btree_max_u64s(c),
1076                b->sib_u64s[0],
1077                b->sib_u64s[1],
1078                c->btree_foreground_merge_threshold,
1079                b->nr.packed_keys,
1080                b->nr.unpacked_keys,
1081                stats.floats,
1082                stats.failed);
1083 }
1084
1085 void bch2_btree_cache_to_text(struct printbuf *out, struct bch_fs *c)
1086 {
1087         pr_buf(out, "nr nodes:\t\t%u\n", c->btree_cache.used);
1088         pr_buf(out, "nr dirty:\t\t%u\n", atomic_read(&c->btree_cache.dirty));
1089         pr_buf(out, "cannibalize lock:\t%p\n", c->btree_cache.alloc_lock);
1090 }