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