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