]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/btree_cache.c
Update bcachefs sources to 938f680845d1 fixup! rename and export __kern_path_locked()
[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 = container_of(shrink, struct bch_fs,
322                                         btree_cache.shrink);
323         struct btree_cache *bc = &c->btree_cache;
324         struct btree *b, *t;
325         unsigned long nr = sc->nr_to_scan;
326         unsigned long can_free = 0;
327         unsigned long freed = 0;
328         unsigned long touched = 0;
329         unsigned i, flags;
330         unsigned long ret = SHRINK_STOP;
331         bool trigger_writes = atomic_read(&bc->dirty) + nr >=
332                 bc->used * 3 / 4;
333
334         if (bch2_btree_shrinker_disabled)
335                 return SHRINK_STOP;
336
337         mutex_lock(&bc->lock);
338         flags = memalloc_nofs_save();
339
340         /*
341          * It's _really_ critical that we don't free too many btree nodes - we
342          * have to always leave ourselves a reserve. The reserve is how we
343          * guarantee that allocating memory for a new btree node can always
344          * succeed, so that inserting keys into the btree can always succeed and
345          * IO can always make forward progress:
346          */
347         can_free = btree_cache_can_free(bc);
348         nr = min_t(unsigned long, nr, can_free);
349
350         i = 0;
351         list_for_each_entry_safe(b, t, &bc->freeable, list) {
352                 /*
353                  * Leave a few nodes on the freeable list, so that a btree split
354                  * won't have to hit the system allocator:
355                  */
356                 if (++i <= 3)
357                         continue;
358
359                 touched++;
360
361                 if (touched >= nr)
362                         goto out;
363
364                 if (!btree_node_reclaim(c, b, true)) {
365                         btree_node_data_free(c, b);
366                         six_unlock_write(&b->c.lock);
367                         six_unlock_intent(&b->c.lock);
368                         freed++;
369                         bc->freed++;
370                 }
371         }
372 restart:
373         list_for_each_entry_safe(b, t, &bc->live, list) {
374                 touched++;
375
376                 if (btree_node_accessed(b)) {
377                         clear_btree_node_accessed(b);
378                         bc->not_freed_access_bit++;
379                 } else if (!btree_node_reclaim(c, b, true)) {
380                         freed++;
381                         btree_node_data_free(c, b);
382                         bc->freed++;
383
384                         bch2_btree_node_hash_remove(bc, b);
385                         six_unlock_write(&b->c.lock);
386                         six_unlock_intent(&b->c.lock);
387
388                         if (freed == nr)
389                                 goto out_rotate;
390                 } else if (trigger_writes &&
391                            btree_node_dirty(b) &&
392                            !btree_node_will_make_reachable(b) &&
393                            !btree_node_write_blocked(b) &&
394                            six_trylock_read(&b->c.lock)) {
395                         list_move(&bc->live, &b->list);
396                         mutex_unlock(&bc->lock);
397                         __bch2_btree_node_write(c, b, BTREE_WRITE_cache_reclaim);
398                         six_unlock_read(&b->c.lock);
399                         if (touched >= nr)
400                                 goto out_nounlock;
401                         mutex_lock(&bc->lock);
402                         goto restart;
403                 }
404
405                 if (touched >= nr)
406                         break;
407         }
408 out_rotate:
409         if (&t->list != &bc->live)
410                 list_move_tail(&bc->live, &t->list);
411 out:
412         mutex_unlock(&bc->lock);
413 out_nounlock:
414         ret = freed;
415         memalloc_nofs_restore(flags);
416         trace_and_count(c, btree_cache_scan, sc->nr_to_scan, can_free, ret);
417         return ret;
418 }
419
420 static unsigned long bch2_btree_cache_count(struct shrinker *shrink,
421                                             struct shrink_control *sc)
422 {
423         struct bch_fs *c = container_of(shrink, struct bch_fs,
424                                         btree_cache.shrink);
425         struct btree_cache *bc = &c->btree_cache;
426
427         if (bch2_btree_shrinker_disabled)
428                 return 0;
429
430         return btree_cache_can_free(bc);
431 }
432
433 static void bch2_btree_cache_shrinker_to_text(struct seq_buf *s, struct shrinker *shrink)
434 {
435         struct bch_fs *c = container_of(shrink, struct bch_fs,
436                                         btree_cache.shrink);
437         char *cbuf;
438         size_t buflen = seq_buf_get_buf(s, &cbuf);
439         struct printbuf out = PRINTBUF_EXTERN(cbuf, buflen);
440
441         bch2_btree_cache_to_text(&out, &c->btree_cache);
442         seq_buf_commit(s, out.pos);
443 }
444
445 void bch2_fs_btree_cache_exit(struct bch_fs *c)
446 {
447         struct btree_cache *bc = &c->btree_cache;
448         struct btree *b;
449         unsigned i, flags;
450
451         unregister_shrinker(&bc->shrink);
452
453         /* vfree() can allocate memory: */
454         flags = memalloc_nofs_save();
455         mutex_lock(&bc->lock);
456
457         if (c->verify_data)
458                 list_move(&c->verify_data->list, &bc->live);
459
460         kvpfree(c->verify_ondisk, btree_bytes(c));
461
462         for (i = 0; i < btree_id_nr_alive(c); i++) {
463                 struct btree_root *r = bch2_btree_id_root(c, i);
464
465                 if (r->b)
466                         list_add(&r->b->list, &bc->live);
467         }
468
469         list_splice(&bc->freeable, &bc->live);
470
471         while (!list_empty(&bc->live)) {
472                 b = list_first_entry(&bc->live, struct btree, list);
473
474                 BUG_ON(btree_node_read_in_flight(b) ||
475                        btree_node_write_in_flight(b));
476
477                 if (btree_node_dirty(b))
478                         bch2_btree_complete_write(c, b, btree_current_write(b));
479                 clear_btree_node_dirty_acct(c, b);
480
481                 btree_node_data_free(c, b);
482         }
483
484         BUG_ON(atomic_read(&c->btree_cache.dirty));
485
486         list_splice(&bc->freed_pcpu, &bc->freed_nonpcpu);
487
488         while (!list_empty(&bc->freed_nonpcpu)) {
489                 b = list_first_entry(&bc->freed_nonpcpu, struct btree, list);
490                 list_del(&b->list);
491                 six_lock_exit(&b->c.lock);
492                 kfree(b);
493         }
494
495         mutex_unlock(&bc->lock);
496         memalloc_nofs_restore(flags);
497
498         if (bc->table_init_done)
499                 rhashtable_destroy(&bc->table);
500 }
501
502 int bch2_fs_btree_cache_init(struct bch_fs *c)
503 {
504         struct btree_cache *bc = &c->btree_cache;
505         unsigned i;
506         int ret = 0;
507
508         ret = rhashtable_init(&bc->table, &bch_btree_cache_params);
509         if (ret)
510                 goto err;
511
512         bc->table_init_done = true;
513
514         bch2_recalc_btree_reserve(c);
515
516         for (i = 0; i < bc->reserve; i++)
517                 if (!__bch2_btree_node_mem_alloc(c))
518                         goto err;
519
520         list_splice_init(&bc->live, &bc->freeable);
521
522         mutex_init(&c->verify_lock);
523
524         bc->shrink.count_objects        = bch2_btree_cache_count;
525         bc->shrink.scan_objects         = bch2_btree_cache_scan;
526         bc->shrink.to_text              = bch2_btree_cache_shrinker_to_text;
527         bc->shrink.seeks                = 4;
528         ret = register_shrinker(&bc->shrink, "%s-btree_cache", c->name);
529         if (ret)
530                 goto err;
531
532         return 0;
533 err:
534         return -BCH_ERR_ENOMEM_fs_btree_cache_init;
535 }
536
537 void bch2_fs_btree_cache_init_early(struct btree_cache *bc)
538 {
539         mutex_init(&bc->lock);
540         INIT_LIST_HEAD(&bc->live);
541         INIT_LIST_HEAD(&bc->freeable);
542         INIT_LIST_HEAD(&bc->freed_pcpu);
543         INIT_LIST_HEAD(&bc->freed_nonpcpu);
544 }
545
546 /*
547  * We can only have one thread cannibalizing other cached btree nodes at a time,
548  * or we'll deadlock. We use an open coded mutex to ensure that, which a
549  * cannibalize_bucket() will take. This means every time we unlock the root of
550  * the btree, we need to release this lock if we have it held.
551  */
552 void bch2_btree_cache_cannibalize_unlock(struct bch_fs *c)
553 {
554         struct btree_cache *bc = &c->btree_cache;
555
556         if (bc->alloc_lock == current) {
557                 trace_and_count(c, btree_cache_cannibalize_unlock, c);
558                 bc->alloc_lock = NULL;
559                 closure_wake_up(&bc->alloc_wait);
560         }
561 }
562
563 int bch2_btree_cache_cannibalize_lock(struct bch_fs *c, struct closure *cl)
564 {
565         struct btree_cache *bc = &c->btree_cache;
566         struct task_struct *old;
567
568         old = cmpxchg(&bc->alloc_lock, NULL, current);
569         if (old == NULL || old == current)
570                 goto success;
571
572         if (!cl) {
573                 trace_and_count(c, btree_cache_cannibalize_lock_fail, c);
574                 return -BCH_ERR_ENOMEM_btree_cache_cannibalize_lock;
575         }
576
577         closure_wait(&bc->alloc_wait, cl);
578
579         /* Try again, after adding ourselves to waitlist */
580         old = cmpxchg(&bc->alloc_lock, NULL, current);
581         if (old == NULL || old == current) {
582                 /* We raced */
583                 closure_wake_up(&bc->alloc_wait);
584                 goto success;
585         }
586
587         trace_and_count(c, btree_cache_cannibalize_lock_fail, c);
588         return -BCH_ERR_btree_cache_cannibalize_lock_blocked;
589
590 success:
591         trace_and_count(c, btree_cache_cannibalize_lock, c);
592         return 0;
593 }
594
595 static struct btree *btree_node_cannibalize(struct bch_fs *c)
596 {
597         struct btree_cache *bc = &c->btree_cache;
598         struct btree *b;
599
600         list_for_each_entry_reverse(b, &bc->live, list)
601                 if (!btree_node_reclaim(c, b, false))
602                         return b;
603
604         while (1) {
605                 list_for_each_entry_reverse(b, &bc->live, list)
606                         if (!btree_node_write_and_reclaim(c, b))
607                                 return b;
608
609                 /*
610                  * Rare case: all nodes were intent-locked.
611                  * Just busy-wait.
612                  */
613                 WARN_ONCE(1, "btree cache cannibalize failed\n");
614                 cond_resched();
615         }
616 }
617
618 struct btree *bch2_btree_node_mem_alloc(struct btree_trans *trans, bool pcpu_read_locks)
619 {
620         struct bch_fs *c = trans->c;
621         struct btree_cache *bc = &c->btree_cache;
622         struct list_head *freed = pcpu_read_locks
623                 ? &bc->freed_pcpu
624                 : &bc->freed_nonpcpu;
625         struct btree *b, *b2;
626         u64 start_time = local_clock();
627         unsigned flags;
628
629         flags = memalloc_nofs_save();
630         mutex_lock(&bc->lock);
631
632         /*
633          * We never free struct btree itself, just the memory that holds the on
634          * disk node. Check the freed list before allocating a new one:
635          */
636         list_for_each_entry(b, freed, list)
637                 if (!btree_node_reclaim(c, b, false)) {
638                         list_del_init(&b->list);
639                         goto got_node;
640                 }
641
642         b = __btree_node_mem_alloc(c, GFP_NOWAIT|__GFP_NOWARN);
643         if (!b) {
644                 mutex_unlock(&bc->lock);
645                 bch2_trans_unlock(trans);
646                 b = __btree_node_mem_alloc(c, GFP_KERNEL);
647                 if (!b)
648                         goto err;
649                 mutex_lock(&bc->lock);
650         }
651
652         bch2_btree_lock_init(&b->c, pcpu_read_locks ? SIX_LOCK_INIT_PCPU : 0);
653
654         BUG_ON(!six_trylock_intent(&b->c.lock));
655         BUG_ON(!six_trylock_write(&b->c.lock));
656 got_node:
657
658         /*
659          * btree_free() doesn't free memory; it sticks the node on the end of
660          * the list. Check if there's any freed nodes there:
661          */
662         list_for_each_entry(b2, &bc->freeable, list)
663                 if (!btree_node_reclaim(c, b2, false)) {
664                         swap(b->data, b2->data);
665                         swap(b->aux_data, b2->aux_data);
666                         btree_node_to_freedlist(bc, b2);
667                         six_unlock_write(&b2->c.lock);
668                         six_unlock_intent(&b2->c.lock);
669                         goto got_mem;
670                 }
671
672         mutex_unlock(&bc->lock);
673
674         if (btree_node_data_alloc(c, b, GFP_NOWAIT|__GFP_NOWARN)) {
675                 bch2_trans_unlock(trans);
676                 if (btree_node_data_alloc(c, b, GFP_KERNEL|__GFP_NOWARN))
677                         goto err;
678         }
679
680         mutex_lock(&bc->lock);
681         bc->used++;
682 got_mem:
683         mutex_unlock(&bc->lock);
684
685         BUG_ON(btree_node_hashed(b));
686         BUG_ON(btree_node_dirty(b));
687         BUG_ON(btree_node_write_in_flight(b));
688 out:
689         b->flags                = 0;
690         b->written              = 0;
691         b->nsets                = 0;
692         b->sib_u64s[0]          = 0;
693         b->sib_u64s[1]          = 0;
694         b->whiteout_u64s        = 0;
695         bch2_btree_keys_init(b);
696         set_btree_node_accessed(b);
697
698         bch2_time_stats_update(&c->times[BCH_TIME_btree_node_mem_alloc],
699                                start_time);
700
701         memalloc_nofs_restore(flags);
702         return b;
703 err:
704         mutex_lock(&bc->lock);
705
706         /* Try to cannibalize another cached btree node: */
707         if (bc->alloc_lock == current) {
708                 b2 = btree_node_cannibalize(c);
709                 clear_btree_node_just_written(b2);
710                 bch2_btree_node_hash_remove(bc, b2);
711
712                 if (b) {
713                         swap(b->data, b2->data);
714                         swap(b->aux_data, b2->aux_data);
715                         btree_node_to_freedlist(bc, b2);
716                         six_unlock_write(&b2->c.lock);
717                         six_unlock_intent(&b2->c.lock);
718                 } else {
719                         b = b2;
720                         list_del_init(&b->list);
721                 }
722
723                 mutex_unlock(&bc->lock);
724
725                 trace_and_count(c, btree_cache_cannibalize, c);
726                 goto out;
727         }
728
729         mutex_unlock(&bc->lock);
730         memalloc_nofs_restore(flags);
731         return ERR_PTR(-BCH_ERR_ENOMEM_btree_node_mem_alloc);
732 }
733
734 /* Slowpath, don't want it inlined into btree_iter_traverse() */
735 static noinline struct btree *bch2_btree_node_fill(struct btree_trans *trans,
736                                 struct btree_path *path,
737                                 const struct bkey_i *k,
738                                 enum btree_id btree_id,
739                                 unsigned level,
740                                 enum six_lock_type lock_type,
741                                 bool sync)
742 {
743         struct bch_fs *c = trans->c;
744         struct btree_cache *bc = &c->btree_cache;
745         struct btree *b;
746         u32 seq;
747
748         BUG_ON(level + 1 >= BTREE_MAX_DEPTH);
749         /*
750          * Parent node must be locked, else we could read in a btree node that's
751          * been freed:
752          */
753         if (path && !bch2_btree_node_relock(trans, path, level + 1)) {
754                 trace_and_count(c, trans_restart_relock_parent_for_fill, trans, _THIS_IP_, path);
755                 return ERR_PTR(btree_trans_restart(trans, BCH_ERR_transaction_restart_fill_relock));
756         }
757
758         b = bch2_btree_node_mem_alloc(trans, level != 0);
759
760         if (bch2_err_matches(PTR_ERR_OR_ZERO(b), ENOMEM)) {
761                 trans->memory_allocation_failure = true;
762                 trace_and_count(c, trans_restart_memory_allocation_failure, trans, _THIS_IP_, path);
763                 return ERR_PTR(btree_trans_restart(trans, BCH_ERR_transaction_restart_fill_mem_alloc_fail));
764         }
765
766         if (IS_ERR(b))
767                 return b;
768
769         /*
770          * Btree nodes read in from disk should not have the accessed bit set
771          * initially, so that linear scans don't thrash the cache:
772          */
773         clear_btree_node_accessed(b);
774
775         bkey_copy(&b->key, k);
776         if (bch2_btree_node_hash_insert(bc, b, level, btree_id)) {
777                 /* raced with another fill: */
778
779                 /* mark as unhashed... */
780                 b->hash_val = 0;
781
782                 mutex_lock(&bc->lock);
783                 list_add(&b->list, &bc->freeable);
784                 mutex_unlock(&bc->lock);
785
786                 six_unlock_write(&b->c.lock);
787                 six_unlock_intent(&b->c.lock);
788                 return NULL;
789         }
790
791         set_btree_node_read_in_flight(b);
792
793         six_unlock_write(&b->c.lock);
794         seq = six_lock_seq(&b->c.lock);
795         six_unlock_intent(&b->c.lock);
796
797         /* Unlock before doing IO: */
798         if (path && sync)
799                 bch2_trans_unlock_noassert(trans);
800
801         bch2_btree_node_read(c, b, sync);
802
803         if (!sync)
804                 return NULL;
805
806         if (path) {
807                 int ret = bch2_trans_relock(trans) ?:
808                         bch2_btree_path_relock_intent(trans, path);
809                 if (ret) {
810                         BUG_ON(!trans->restarted);
811                         return ERR_PTR(ret);
812                 }
813         }
814
815         if (!six_relock_type(&b->c.lock, lock_type, seq)) {
816                 if (path)
817                         trace_and_count(c, trans_restart_relock_after_fill, trans, _THIS_IP_, path);
818                 return ERR_PTR(btree_trans_restart(trans, BCH_ERR_transaction_restart_relock_after_fill));
819         }
820
821         return b;
822 }
823
824 static noinline void btree_bad_header(struct bch_fs *c, struct btree *b)
825 {
826         struct printbuf buf = PRINTBUF;
827
828         if (c->curr_recovery_pass <= BCH_RECOVERY_PASS_check_allocations)
829                 return;
830
831         prt_printf(&buf,
832                "btree node header doesn't match ptr\n"
833                "btree %s level %u\n"
834                "ptr: ",
835                bch2_btree_id_str(b->c.btree_id), b->c.level);
836         bch2_bkey_val_to_text(&buf, c, bkey_i_to_s_c(&b->key));
837
838         prt_printf(&buf, "\nheader: btree %s level %llu\n"
839                "min ",
840                bch2_btree_id_str(BTREE_NODE_ID(b->data)),
841                BTREE_NODE_LEVEL(b->data));
842         bch2_bpos_to_text(&buf, b->data->min_key);
843
844         prt_printf(&buf, "\nmax ");
845         bch2_bpos_to_text(&buf, b->data->max_key);
846
847         bch2_fs_inconsistent(c, "%s", buf.buf);
848         printbuf_exit(&buf);
849 }
850
851 static inline void btree_check_header(struct bch_fs *c, struct btree *b)
852 {
853         if (b->c.btree_id != BTREE_NODE_ID(b->data) ||
854             b->c.level != BTREE_NODE_LEVEL(b->data) ||
855             !bpos_eq(b->data->max_key, b->key.k.p) ||
856             (b->key.k.type == KEY_TYPE_btree_ptr_v2 &&
857              !bpos_eq(b->data->min_key,
858                       bkey_i_to_btree_ptr_v2(&b->key)->v.min_key)))
859                 btree_bad_header(c, b);
860 }
861
862 static struct btree *__bch2_btree_node_get(struct btree_trans *trans, struct btree_path *path,
863                                            const struct bkey_i *k, unsigned level,
864                                            enum six_lock_type lock_type,
865                                            unsigned long trace_ip)
866 {
867         struct bch_fs *c = trans->c;
868         struct btree_cache *bc = &c->btree_cache;
869         struct btree *b;
870         struct bset_tree *t;
871         bool need_relock = false;
872         int ret;
873
874         EBUG_ON(level >= BTREE_MAX_DEPTH);
875 retry:
876         b = btree_cache_find(bc, k);
877         if (unlikely(!b)) {
878                 /*
879                  * We must have the parent locked to call bch2_btree_node_fill(),
880                  * else we could read in a btree node from disk that's been
881                  * freed:
882                  */
883                 b = bch2_btree_node_fill(trans, path, k, path->btree_id,
884                                          level, lock_type, true);
885                 need_relock = true;
886
887                 /* We raced and found the btree node in the cache */
888                 if (!b)
889                         goto retry;
890
891                 if (IS_ERR(b))
892                         return b;
893         } else {
894                 if (btree_node_read_locked(path, level + 1))
895                         btree_node_unlock(trans, path, level + 1);
896
897                 ret = btree_node_lock(trans, path, &b->c, level, lock_type, trace_ip);
898                 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
899                         return ERR_PTR(ret);
900
901                 BUG_ON(ret);
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_and_count(c, trans_restart_btree_node_reused, trans, trace_ip, path);
911                         return ERR_PTR(btree_trans_restart(trans, BCH_ERR_transaction_restart_lock_node_reused));
912                 }
913
914                 /* avoid atomic set bit if it's not needed: */
915                 if (!btree_node_accessed(b))
916                         set_btree_node_accessed(b);
917         }
918
919         if (unlikely(btree_node_read_in_flight(b))) {
920                 u32 seq = six_lock_seq(&b->c.lock);
921
922                 six_unlock_type(&b->c.lock, lock_type);
923                 bch2_trans_unlock(trans);
924                 need_relock = true;
925
926                 bch2_btree_node_wait_on_read(b);
927
928                 /*
929                  * should_be_locked is not set on this path yet, so we need to
930                  * relock it specifically:
931                  */
932                 if (!six_relock_type(&b->c.lock, lock_type, seq))
933                         goto retry;
934         }
935
936         if (unlikely(need_relock)) {
937                 ret = bch2_trans_relock(trans) ?:
938                         bch2_btree_path_relock_intent(trans, path);
939                 if (ret) {
940                         six_unlock_type(&b->c.lock, lock_type);
941                         return ERR_PTR(ret);
942                 }
943         }
944
945         prefetch(b->aux_data);
946
947         for_each_bset(b, t) {
948                 void *p = (u64 *) b->aux_data + t->aux_data_offset;
949
950                 prefetch(p + L1_CACHE_BYTES * 0);
951                 prefetch(p + L1_CACHE_BYTES * 1);
952                 prefetch(p + L1_CACHE_BYTES * 2);
953         }
954
955         if (unlikely(btree_node_read_error(b))) {
956                 six_unlock_type(&b->c.lock, lock_type);
957                 return ERR_PTR(-EIO);
958         }
959
960         EBUG_ON(b->c.btree_id != path->btree_id);
961         EBUG_ON(BTREE_NODE_LEVEL(b->data) != level);
962         btree_check_header(c, b);
963
964         return b;
965 }
966
967 /**
968  * bch2_btree_node_get - find a btree node in the cache and lock it, reading it
969  * in from disk if necessary.
970  *
971  * @trans:      btree transaction object
972  * @path:       btree_path being traversed
973  * @k:          pointer to btree node (generally KEY_TYPE_btree_ptr_v2)
974  * @level:      level of btree node being looked up (0 == leaf node)
975  * @lock_type:  SIX_LOCK_read or SIX_LOCK_intent
976  * @trace_ip:   ip of caller of btree iterator code (i.e. caller of bch2_btree_iter_peek())
977  *
978  * The btree node will have either a read or a write lock held, depending on
979  * the @write parameter.
980  *
981  * Returns: btree node or ERR_PTR()
982  */
983 struct btree *bch2_btree_node_get(struct btree_trans *trans, struct btree_path *path,
984                                   const struct bkey_i *k, unsigned level,
985                                   enum six_lock_type lock_type,
986                                   unsigned long trace_ip)
987 {
988         struct bch_fs *c = trans->c;
989         struct btree *b;
990         struct bset_tree *t;
991         int ret;
992
993         EBUG_ON(level >= BTREE_MAX_DEPTH);
994
995         b = btree_node_mem_ptr(k);
996
997         /*
998          * Check b->hash_val _before_ calling btree_node_lock() - this might not
999          * be the node we want anymore, and trying to lock the wrong node could
1000          * cause an unneccessary transaction restart:
1001          */
1002         if (unlikely(!c->opts.btree_node_mem_ptr_optimization ||
1003                      !b ||
1004                      b->hash_val != btree_ptr_hash_val(k)))
1005                 return __bch2_btree_node_get(trans, path, k, level, lock_type, trace_ip);
1006
1007         if (btree_node_read_locked(path, level + 1))
1008                 btree_node_unlock(trans, path, level + 1);
1009
1010         ret = btree_node_lock(trans, path, &b->c, level, lock_type, trace_ip);
1011         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
1012                 return ERR_PTR(ret);
1013
1014         BUG_ON(ret);
1015
1016         if (unlikely(b->hash_val != btree_ptr_hash_val(k) ||
1017                      b->c.level != level ||
1018                      race_fault())) {
1019                 six_unlock_type(&b->c.lock, lock_type);
1020                 if (bch2_btree_node_relock(trans, path, level + 1))
1021                         return __bch2_btree_node_get(trans, path, k, level, lock_type, trace_ip);
1022
1023                 trace_and_count(c, trans_restart_btree_node_reused, trans, trace_ip, path);
1024                 return ERR_PTR(btree_trans_restart(trans, BCH_ERR_transaction_restart_lock_node_reused));
1025         }
1026
1027         if (unlikely(btree_node_read_in_flight(b))) {
1028                 six_unlock_type(&b->c.lock, lock_type);
1029                 return __bch2_btree_node_get(trans, path, k, level, lock_type, trace_ip);
1030         }
1031
1032         prefetch(b->aux_data);
1033
1034         for_each_bset(b, t) {
1035                 void *p = (u64 *) b->aux_data + t->aux_data_offset;
1036
1037                 prefetch(p + L1_CACHE_BYTES * 0);
1038                 prefetch(p + L1_CACHE_BYTES * 1);
1039                 prefetch(p + L1_CACHE_BYTES * 2);
1040         }
1041
1042         /* avoid atomic set bit if it's not needed: */
1043         if (!btree_node_accessed(b))
1044                 set_btree_node_accessed(b);
1045
1046         if (unlikely(btree_node_read_error(b))) {
1047                 six_unlock_type(&b->c.lock, lock_type);
1048                 return ERR_PTR(-EIO);
1049         }
1050
1051         EBUG_ON(b->c.btree_id != path->btree_id);
1052         EBUG_ON(BTREE_NODE_LEVEL(b->data) != level);
1053         btree_check_header(c, b);
1054
1055         return b;
1056 }
1057
1058 struct btree *bch2_btree_node_get_noiter(struct btree_trans *trans,
1059                                          const struct bkey_i *k,
1060                                          enum btree_id btree_id,
1061                                          unsigned level,
1062                                          bool nofill)
1063 {
1064         struct bch_fs *c = trans->c;
1065         struct btree_cache *bc = &c->btree_cache;
1066         struct btree *b;
1067         struct bset_tree *t;
1068         int ret;
1069
1070         EBUG_ON(level >= BTREE_MAX_DEPTH);
1071
1072         if (c->opts.btree_node_mem_ptr_optimization) {
1073                 b = btree_node_mem_ptr(k);
1074                 if (b)
1075                         goto lock_node;
1076         }
1077 retry:
1078         b = btree_cache_find(bc, k);
1079         if (unlikely(!b)) {
1080                 if (nofill)
1081                         goto out;
1082
1083                 b = bch2_btree_node_fill(trans, NULL, k, btree_id,
1084                                          level, SIX_LOCK_read, true);
1085
1086                 /* We raced and found the btree node in the cache */
1087                 if (!b)
1088                         goto retry;
1089
1090                 if (IS_ERR(b) &&
1091                     !bch2_btree_cache_cannibalize_lock(c, NULL))
1092                         goto retry;
1093
1094                 if (IS_ERR(b))
1095                         goto out;
1096         } else {
1097 lock_node:
1098                 ret = btree_node_lock_nopath(trans, &b->c, SIX_LOCK_read, _THIS_IP_);
1099                 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
1100                         return ERR_PTR(ret);
1101
1102                 BUG_ON(ret);
1103
1104                 if (unlikely(b->hash_val != btree_ptr_hash_val(k) ||
1105                              b->c.btree_id != btree_id ||
1106                              b->c.level != level)) {
1107                         six_unlock_read(&b->c.lock);
1108                         goto retry;
1109                 }
1110         }
1111
1112         /* XXX: waiting on IO with btree locks held: */
1113         __bch2_btree_node_wait_on_read(b);
1114
1115         prefetch(b->aux_data);
1116
1117         for_each_bset(b, t) {
1118                 void *p = (u64 *) b->aux_data + t->aux_data_offset;
1119
1120                 prefetch(p + L1_CACHE_BYTES * 0);
1121                 prefetch(p + L1_CACHE_BYTES * 1);
1122                 prefetch(p + L1_CACHE_BYTES * 2);
1123         }
1124
1125         /* avoid atomic set bit if it's not needed: */
1126         if (!btree_node_accessed(b))
1127                 set_btree_node_accessed(b);
1128
1129         if (unlikely(btree_node_read_error(b))) {
1130                 six_unlock_read(&b->c.lock);
1131                 b = ERR_PTR(-EIO);
1132                 goto out;
1133         }
1134
1135         EBUG_ON(b->c.btree_id != btree_id);
1136         EBUG_ON(BTREE_NODE_LEVEL(b->data) != level);
1137         btree_check_header(c, b);
1138 out:
1139         bch2_btree_cache_cannibalize_unlock(c);
1140         return b;
1141 }
1142
1143 int bch2_btree_node_prefetch(struct btree_trans *trans,
1144                              struct btree_path *path,
1145                              const struct bkey_i *k,
1146                              enum btree_id btree_id, unsigned level)
1147 {
1148         struct bch_fs *c = trans->c;
1149         struct btree_cache *bc = &c->btree_cache;
1150         struct btree *b;
1151
1152         BUG_ON(trans && !btree_node_locked(path, level + 1));
1153         BUG_ON(level >= BTREE_MAX_DEPTH);
1154
1155         b = btree_cache_find(bc, k);
1156         if (b)
1157                 return 0;
1158
1159         b = bch2_btree_node_fill(trans, path, k, btree_id,
1160                                  level, SIX_LOCK_read, false);
1161         return PTR_ERR_OR_ZERO(b);
1162 }
1163
1164 void bch2_btree_node_evict(struct btree_trans *trans, const struct bkey_i *k)
1165 {
1166         struct bch_fs *c = trans->c;
1167         struct btree_cache *bc = &c->btree_cache;
1168         struct btree *b;
1169
1170         b = btree_cache_find(bc, k);
1171         if (!b)
1172                 return;
1173 wait_on_io:
1174         /* not allowed to wait on io with btree locks held: */
1175
1176         /* XXX we're called from btree_gc which will be holding other btree
1177          * nodes locked
1178          */
1179         __bch2_btree_node_wait_on_read(b);
1180         __bch2_btree_node_wait_on_write(b);
1181
1182         btree_node_lock_nopath_nofail(trans, &b->c, SIX_LOCK_intent);
1183         btree_node_lock_nopath_nofail(trans, &b->c, SIX_LOCK_write);
1184
1185         if (btree_node_dirty(b)) {
1186                 __bch2_btree_node_write(c, b, BTREE_WRITE_cache_reclaim);
1187                 six_unlock_write(&b->c.lock);
1188                 six_unlock_intent(&b->c.lock);
1189                 goto wait_on_io;
1190         }
1191
1192         BUG_ON(btree_node_dirty(b));
1193
1194         mutex_lock(&bc->lock);
1195         btree_node_data_free(c, b);
1196         bch2_btree_node_hash_remove(bc, b);
1197         mutex_unlock(&bc->lock);
1198
1199         six_unlock_write(&b->c.lock);
1200         six_unlock_intent(&b->c.lock);
1201 }
1202
1203 const char *bch2_btree_id_str(enum btree_id btree)
1204 {
1205         return btree < BTREE_ID_NR ? __bch2_btree_ids[btree] : "(unknown)";
1206 }
1207
1208 void bch2_btree_pos_to_text(struct printbuf *out, struct bch_fs *c, const struct btree *b)
1209 {
1210         prt_printf(out, "%s level %u/%u\n  ",
1211                bch2_btree_id_str(b->c.btree_id),
1212                b->c.level,
1213                bch2_btree_id_root(c, b->c.btree_id)->level);
1214         bch2_bkey_val_to_text(out, c, bkey_i_to_s_c(&b->key));
1215 }
1216
1217 void bch2_btree_node_to_text(struct printbuf *out, struct bch_fs *c, const struct btree *b)
1218 {
1219         struct bset_stats stats;
1220
1221         memset(&stats, 0, sizeof(stats));
1222
1223         bch2_btree_keys_stats(b, &stats);
1224
1225         prt_printf(out, "l %u ", b->c.level);
1226         bch2_bpos_to_text(out, b->data->min_key);
1227         prt_printf(out, " - ");
1228         bch2_bpos_to_text(out, b->data->max_key);
1229         prt_printf(out, ":\n"
1230                "    ptrs: ");
1231         bch2_val_to_text(out, c, bkey_i_to_s_c(&b->key));
1232         prt_newline(out);
1233
1234         prt_printf(out,
1235                "    format: ");
1236         bch2_bkey_format_to_text(out, &b->format);
1237
1238         prt_printf(out,
1239                "    unpack fn len: %u\n"
1240                "    bytes used %zu/%zu (%zu%% full)\n"
1241                "    sib u64s: %u, %u (merge threshold %u)\n"
1242                "    nr packed keys %u\n"
1243                "    nr unpacked keys %u\n"
1244                "    floats %zu\n"
1245                "    failed unpacked %zu\n",
1246                b->unpack_fn_len,
1247                b->nr.live_u64s * sizeof(u64),
1248                btree_bytes(c) - sizeof(struct btree_node),
1249                b->nr.live_u64s * 100 / btree_max_u64s(c),
1250                b->sib_u64s[0],
1251                b->sib_u64s[1],
1252                c->btree_foreground_merge_threshold,
1253                b->nr.packed_keys,
1254                b->nr.unpacked_keys,
1255                stats.floats,
1256                stats.failed);
1257 }
1258
1259 void bch2_btree_cache_to_text(struct printbuf *out, const struct btree_cache *bc)
1260 {
1261         prt_printf(out, "nr nodes:\t\t%u\n", bc->used);
1262         prt_printf(out, "nr dirty:\t\t%u\n", atomic_read(&bc->dirty));
1263         prt_printf(out, "cannibalize lock:\t%p\n", bc->alloc_lock);
1264
1265         prt_printf(out, "freed:\t\t\t\t%u\n", bc->freed);
1266         prt_printf(out, "not freed, dirty:\t\t%u\n", bc->not_freed_dirty);
1267         prt_printf(out, "not freed, write in flight:\t%u\n", bc->not_freed_write_in_flight);
1268         prt_printf(out, "not freed, read in flight:\t%u\n", bc->not_freed_read_in_flight);
1269         prt_printf(out, "not freed, lock intent failed:\t%u\n", bc->not_freed_lock_intent);
1270         prt_printf(out, "not freed, lock write failed:\t%u\n", bc->not_freed_lock_write);
1271         prt_printf(out, "not freed, access bit:\t\t%u\n", bc->not_freed_access_bit);
1272         prt_printf(out, "not freed, no evict failed:\t%u\n", bc->not_freed_noevict);
1273         prt_printf(out, "not freed, write blocked:\t%u\n", bc->not_freed_write_blocked);
1274         prt_printf(out, "not freed, will make reachable:\t%u\n", bc->not_freed_will_make_reachable);
1275
1276 }