]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/btree_cache.c
Update bcachefs sources to eab3b355cf bcachefs: trace transaction restarts
[bcachefs-tools-debian] / libbcachefs / btree_cache.c
1
2 #include "bcachefs.h"
3 #include "btree_cache.h"
4 #include "btree_io.h"
5 #include "btree_iter.h"
6 #include "btree_locking.h"
7 #include "debug.h"
8 #include "extents.h"
9
10 #include <linux/prefetch.h>
11 #include <trace/events/bcachefs.h>
12
13 #define DEF_BTREE_ID(kwd, val, name) name,
14
15 const char * const bch2_btree_ids[] = {
16         DEFINE_BCH_BTREE_IDS()
17         NULL
18 };
19
20 #undef DEF_BTREE_ID
21
22 void bch2_recalc_btree_reserve(struct bch_fs *c)
23 {
24         unsigned i, reserve = 16;
25
26         if (!c->btree_roots[0].b)
27                 reserve += 8;
28
29         for (i = 0; i < BTREE_ID_NR; i++)
30                 if (c->btree_roots[i].b)
31                         reserve += min_t(unsigned, 1,
32                                          c->btree_roots[i].b->level) * 8;
33
34         c->btree_cache.reserve = reserve;
35 }
36
37 static inline unsigned btree_cache_can_free(struct btree_cache *bc)
38 {
39         return max_t(int, 0, bc->used - bc->reserve);
40 }
41
42 static void __btree_node_data_free(struct bch_fs *c, struct btree *b)
43 {
44         EBUG_ON(btree_node_write_in_flight(b));
45
46         kvpfree(b->data, btree_bytes(c));
47         b->data = NULL;
48         bch2_btree_keys_free(b);
49 }
50
51 static void btree_node_data_free(struct bch_fs *c, struct btree *b)
52 {
53         struct btree_cache *bc = &c->btree_cache;
54
55         __btree_node_data_free(c, b);
56         bc->used--;
57         list_move(&b->list, &bc->freed);
58 }
59
60 static int bch2_btree_cache_cmp_fn(struct rhashtable_compare_arg *arg,
61                                    const void *obj)
62 {
63         const struct btree *b = obj;
64         const u64 *v = arg->key;
65
66         return PTR_HASH(&b->key) == *v ? 0 : 1;
67 }
68
69 static const struct rhashtable_params bch_btree_cache_params = {
70         .head_offset    = offsetof(struct btree, hash),
71         .key_offset     = offsetof(struct btree, key.v),
72         .key_len        = sizeof(struct bch_extent_ptr),
73         .obj_cmpfn      = bch2_btree_cache_cmp_fn,
74 };
75
76 static void btree_node_data_alloc(struct bch_fs *c, struct btree *b, gfp_t gfp)
77 {
78         struct btree_cache *bc = &c->btree_cache;
79
80         b->data = kvpmalloc(btree_bytes(c), gfp);
81         if (!b->data)
82                 goto err;
83
84         if (bch2_btree_keys_alloc(b, btree_page_order(c), gfp))
85                 goto err;
86
87         bc->used++;
88         list_move(&b->list, &bc->freeable);
89         return;
90 err:
91         kvpfree(b->data, btree_bytes(c));
92         b->data = NULL;
93         list_move(&b->list, &bc->freed);
94 }
95
96 static struct btree *btree_node_mem_alloc(struct bch_fs *c, gfp_t gfp)
97 {
98         struct btree *b = kzalloc(sizeof(struct btree), gfp);
99         if (!b)
100                 return NULL;
101
102         bkey_extent_init(&b->key);
103         six_lock_init(&b->lock);
104         INIT_LIST_HEAD(&b->list);
105         INIT_LIST_HEAD(&b->write_blocked);
106
107         btree_node_data_alloc(c, b, gfp);
108         return b->data ? b : NULL;
109 }
110
111 /* Btree in memory cache - hash table */
112
113 void bch2_btree_node_hash_remove(struct btree_cache *bc, struct btree *b)
114 {
115         rhashtable_remove_fast(&bc->table, &b->hash, bch_btree_cache_params);
116
117         /* Cause future lookups for this node to fail: */
118         bkey_i_to_extent(&b->key)->v._data[0] = 0;
119 }
120
121 int __bch2_btree_node_hash_insert(struct btree_cache *bc, struct btree *b)
122 {
123         return rhashtable_lookup_insert_fast(&bc->table, &b->hash,
124                                              bch_btree_cache_params);
125 }
126
127 int bch2_btree_node_hash_insert(struct btree_cache *bc, struct btree *b,
128                                 unsigned level, enum btree_id id)
129 {
130         int ret;
131
132         b->level        = level;
133         b->btree_id     = id;
134
135         mutex_lock(&bc->lock);
136         ret = __bch2_btree_node_hash_insert(bc, b);
137         if (!ret)
138                 list_add(&b->list, &bc->live);
139         mutex_unlock(&bc->lock);
140
141         return ret;
142 }
143
144 __flatten
145 static inline struct btree *btree_cache_find(struct btree_cache *bc,
146                                      const struct bkey_i *k)
147 {
148         return rhashtable_lookup_fast(&bc->table, &PTR_HASH(k),
149                                       bch_btree_cache_params);
150 }
151
152 /*
153  * this version is for btree nodes that have already been freed (we're not
154  * reaping a real btree node)
155  */
156 static int __btree_node_reclaim(struct bch_fs *c, struct btree *b, bool flush)
157 {
158         struct btree_cache *bc = &c->btree_cache;
159         int ret = 0;
160
161         lockdep_assert_held(&bc->lock);
162
163         if (!six_trylock_intent(&b->lock))
164                 return -ENOMEM;
165
166         if (!six_trylock_write(&b->lock))
167                 goto out_unlock_intent;
168
169         if (btree_node_noevict(b))
170                 goto out_unlock;
171
172         if (!btree_node_may_write(b))
173                 goto out_unlock;
174
175         if (btree_node_dirty(b) ||
176             btree_node_write_in_flight(b) ||
177             btree_node_read_in_flight(b)) {
178                 if (!flush)
179                         goto out_unlock;
180
181                 wait_on_bit_io(&b->flags, BTREE_NODE_read_in_flight,
182                                TASK_UNINTERRUPTIBLE);
183
184                 /*
185                  * Using the underscore version because we don't want to compact
186                  * bsets after the write, since this node is about to be evicted
187                  * - unless btree verify mode is enabled, since it runs out of
188                  * the post write cleanup:
189                  */
190                 if (verify_btree_ondisk(c))
191                         bch2_btree_node_write(c, b, SIX_LOCK_intent);
192                 else
193                         __bch2_btree_node_write(c, b, SIX_LOCK_read);
194
195                 /* wait for any in flight btree write */
196                 btree_node_wait_on_io(b);
197         }
198 out:
199         if (PTR_HASH(&b->key) && !ret)
200                 trace_btree_node_reap(c, b);
201         return ret;
202 out_unlock:
203         six_unlock_write(&b->lock);
204 out_unlock_intent:
205         six_unlock_intent(&b->lock);
206         ret = -ENOMEM;
207         goto out;
208 }
209
210 static int btree_node_reclaim(struct bch_fs *c, struct btree *b)
211 {
212         return __btree_node_reclaim(c, b, false);
213 }
214
215 static int btree_node_write_and_reclaim(struct bch_fs *c, struct btree *b)
216 {
217         return __btree_node_reclaim(c, b, true);
218 }
219
220 static unsigned long bch2_btree_cache_scan(struct shrinker *shrink,
221                                            struct shrink_control *sc)
222 {
223         struct bch_fs *c = container_of(shrink, struct bch_fs,
224                                         btree_cache.shrink);
225         struct btree_cache *bc = &c->btree_cache;
226         struct btree *b, *t;
227         unsigned long nr = sc->nr_to_scan;
228         unsigned long can_free;
229         unsigned long touched = 0;
230         unsigned long freed = 0;
231         unsigned i;
232
233         if (btree_shrinker_disabled(c))
234                 return SHRINK_STOP;
235
236         /* Return -1 if we can't do anything right now */
237         if (sc->gfp_mask & __GFP_IO)
238                 mutex_lock(&bc->lock);
239         else if (!mutex_trylock(&bc->lock))
240                 return -1;
241
242         /*
243          * It's _really_ critical that we don't free too many btree nodes - we
244          * have to always leave ourselves a reserve. The reserve is how we
245          * guarantee that allocating memory for a new btree node can always
246          * succeed, so that inserting keys into the btree can always succeed and
247          * IO can always make forward progress:
248          */
249         nr /= btree_pages(c);
250         can_free = btree_cache_can_free(bc);
251         nr = min_t(unsigned long, nr, can_free);
252
253         i = 0;
254         list_for_each_entry_safe(b, t, &bc->freeable, list) {
255                 touched++;
256
257                 if (freed >= nr)
258                         break;
259
260                 if (++i > 3 &&
261                     !btree_node_reclaim(c, b)) {
262                         btree_node_data_free(c, b);
263                         six_unlock_write(&b->lock);
264                         six_unlock_intent(&b->lock);
265                         freed++;
266                 }
267         }
268 restart:
269         list_for_each_entry_safe(b, t, &bc->live, list) {
270                 touched++;
271
272                 if (freed >= nr) {
273                         /* Save position */
274                         if (&t->list != &bc->live)
275                                 list_move_tail(&bc->live, &t->list);
276                         break;
277                 }
278
279                 if (!btree_node_accessed(b) &&
280                     !btree_node_reclaim(c, b)) {
281                         /* can't call bch2_btree_node_hash_remove under lock  */
282                         freed++;
283                         if (&t->list != &bc->live)
284                                 list_move_tail(&bc->live, &t->list);
285
286                         btree_node_data_free(c, b);
287                         mutex_unlock(&bc->lock);
288
289                         bch2_btree_node_hash_remove(bc, b);
290                         six_unlock_write(&b->lock);
291                         six_unlock_intent(&b->lock);
292
293                         if (freed >= nr)
294                                 goto out;
295
296                         if (sc->gfp_mask & __GFP_IO)
297                                 mutex_lock(&bc->lock);
298                         else if (!mutex_trylock(&bc->lock))
299                                 goto out;
300                         goto restart;
301                 } else
302                         clear_btree_node_accessed(b);
303         }
304
305         mutex_unlock(&bc->lock);
306 out:
307         return (unsigned long) freed * btree_pages(c);
308 }
309
310 static unsigned long bch2_btree_cache_count(struct shrinker *shrink,
311                                             struct shrink_control *sc)
312 {
313         struct bch_fs *c = container_of(shrink, struct bch_fs,
314                                         btree_cache.shrink);
315         struct btree_cache *bc = &c->btree_cache;
316
317         if (btree_shrinker_disabled(c))
318                 return 0;
319
320         return btree_cache_can_free(bc) * btree_pages(c);
321 }
322
323 void bch2_fs_btree_cache_exit(struct bch_fs *c)
324 {
325         struct btree_cache *bc = &c->btree_cache;
326         struct btree *b;
327         unsigned i;
328
329         if (bc->shrink.list.next)
330                 unregister_shrinker(&bc->shrink);
331
332         mutex_lock(&bc->lock);
333
334 #ifdef CONFIG_BCACHEFS_DEBUG
335         if (c->verify_data)
336                 list_move(&c->verify_data->list, &bc->live);
337
338         kvpfree(c->verify_ondisk, btree_bytes(c));
339 #endif
340
341         for (i = 0; i < BTREE_ID_NR; i++)
342                 if (c->btree_roots[i].b)
343                         list_add(&c->btree_roots[i].b->list, &bc->live);
344
345         list_splice(&bc->freeable, &bc->live);
346
347         while (!list_empty(&bc->live)) {
348                 b = list_first_entry(&bc->live, struct btree, list);
349
350                 BUG_ON(btree_node_read_in_flight(b) ||
351                        btree_node_write_in_flight(b));
352
353                 if (btree_node_dirty(b))
354                         bch2_btree_complete_write(c, b, btree_current_write(b));
355                 clear_btree_node_dirty(b);
356
357                 btree_node_data_free(c, b);
358         }
359
360         while (!list_empty(&bc->freed)) {
361                 b = list_first_entry(&bc->freed, struct btree, list);
362                 list_del(&b->list);
363                 kfree(b);
364         }
365
366         mutex_unlock(&bc->lock);
367
368         if (bc->table_init_done)
369                 rhashtable_destroy(&bc->table);
370 }
371
372 int bch2_fs_btree_cache_init(struct bch_fs *c)
373 {
374         struct btree_cache *bc = &c->btree_cache;
375         unsigned i;
376         int ret = 0;
377
378         pr_verbose_init(c->opts, "");
379
380         ret = rhashtable_init(&bc->table, &bch_btree_cache_params);
381         if (ret)
382                 goto out;
383
384         bc->table_init_done = true;
385
386         bch2_recalc_btree_reserve(c);
387
388         for (i = 0; i < bc->reserve; i++)
389                 if (!btree_node_mem_alloc(c, GFP_KERNEL)) {
390                         ret = -ENOMEM;
391                         goto out;
392                 }
393
394         list_splice_init(&bc->live, &bc->freeable);
395
396 #ifdef CONFIG_BCACHEFS_DEBUG
397         mutex_init(&c->verify_lock);
398
399         c->verify_ondisk = kvpmalloc(btree_bytes(c), GFP_KERNEL);
400         if (!c->verify_ondisk) {
401                 ret = -ENOMEM;
402                 goto out;
403         }
404
405         c->verify_data = btree_node_mem_alloc(c, GFP_KERNEL);
406         if (!c->verify_data) {
407                 ret = -ENOMEM;
408                 goto out;
409         }
410
411         list_del_init(&c->verify_data->list);
412 #endif
413
414         bc->shrink.count_objects        = bch2_btree_cache_count;
415         bc->shrink.scan_objects         = bch2_btree_cache_scan;
416         bc->shrink.seeks                = 4;
417         bc->shrink.batch                = btree_pages(c) * 2;
418         register_shrinker(&bc->shrink);
419 out:
420         pr_verbose_init(c->opts, "ret %i", ret);
421         return ret;
422 }
423
424 void bch2_fs_btree_cache_init_early(struct btree_cache *bc)
425 {
426         mutex_init(&bc->lock);
427         INIT_LIST_HEAD(&bc->live);
428         INIT_LIST_HEAD(&bc->freeable);
429         INIT_LIST_HEAD(&bc->freed);
430 }
431
432 /*
433  * We can only have one thread cannibalizing other cached btree nodes at a time,
434  * or we'll deadlock. We use an open coded mutex to ensure that, which a
435  * cannibalize_bucket() will take. This means every time we unlock the root of
436  * the btree, we need to release this lock if we have it held.
437  */
438 void bch2_btree_cache_cannibalize_unlock(struct bch_fs *c)
439 {
440         struct btree_cache *bc = &c->btree_cache;
441
442         if (bc->alloc_lock == current) {
443                 trace_btree_node_cannibalize_unlock(c);
444                 bc->alloc_lock = NULL;
445                 closure_wake_up(&bc->alloc_wait);
446         }
447 }
448
449 int bch2_btree_cache_cannibalize_lock(struct bch_fs *c, struct closure *cl)
450 {
451         struct btree_cache *bc = &c->btree_cache;
452         struct task_struct *old;
453
454         old = cmpxchg(&bc->alloc_lock, NULL, current);
455         if (old == NULL || old == current)
456                 goto success;
457
458         if (!cl) {
459                 trace_btree_node_cannibalize_lock_fail(c);
460                 return -ENOMEM;
461         }
462
463         closure_wait(&bc->alloc_wait, cl);
464
465         /* Try again, after adding ourselves to waitlist */
466         old = cmpxchg(&bc->alloc_lock, NULL, current);
467         if (old == NULL || old == current) {
468                 /* We raced */
469                 closure_wake_up(&bc->alloc_wait);
470                 goto success;
471         }
472
473         trace_btree_node_cannibalize_lock_fail(c);
474         return -EAGAIN;
475
476 success:
477         trace_btree_node_cannibalize_lock(c);
478         return 0;
479 }
480
481 static struct btree *btree_node_cannibalize(struct bch_fs *c)
482 {
483         struct btree_cache *bc = &c->btree_cache;
484         struct btree *b;
485
486         list_for_each_entry_reverse(b, &bc->live, list)
487                 if (!btree_node_reclaim(c, b))
488                         return b;
489
490         while (1) {
491                 list_for_each_entry_reverse(b, &bc->live, list)
492                         if (!btree_node_write_and_reclaim(c, b))
493                                 return b;
494
495                 /*
496                  * Rare case: all nodes were intent-locked.
497                  * Just busy-wait.
498                  */
499                 WARN_ONCE(1, "btree cache cannibalize failed\n");
500                 cond_resched();
501         }
502 }
503
504 struct btree *bch2_btree_node_mem_alloc(struct bch_fs *c)
505 {
506         struct btree_cache *bc = &c->btree_cache;
507         struct btree *b;
508         u64 start_time = local_clock();
509
510         mutex_lock(&bc->lock);
511
512         /*
513          * btree_free() doesn't free memory; it sticks the node on the end of
514          * the list. Check if there's any freed nodes there:
515          */
516         list_for_each_entry(b, &bc->freeable, list)
517                 if (!btree_node_reclaim(c, b))
518                         goto out_unlock;
519
520         /*
521          * We never free struct btree itself, just the memory that holds the on
522          * disk node. Check the freed list before allocating a new one:
523          */
524         list_for_each_entry(b, &bc->freed, list)
525                 if (!btree_node_reclaim(c, b)) {
526                         btree_node_data_alloc(c, b, __GFP_NOWARN|GFP_NOIO);
527                         if (b->data)
528                                 goto out_unlock;
529
530                         six_unlock_write(&b->lock);
531                         six_unlock_intent(&b->lock);
532                         goto err;
533                 }
534
535         b = btree_node_mem_alloc(c, __GFP_NOWARN|GFP_NOIO);
536         if (!b)
537                 goto err;
538
539         BUG_ON(!six_trylock_intent(&b->lock));
540         BUG_ON(!six_trylock_write(&b->lock));
541 out_unlock:
542         BUG_ON(btree_node_hashed(b));
543         BUG_ON(btree_node_write_in_flight(b));
544
545         list_del_init(&b->list);
546         mutex_unlock(&bc->lock);
547 out:
548         b->flags                = 0;
549         b->written              = 0;
550         b->nsets                = 0;
551         b->sib_u64s[0]          = 0;
552         b->sib_u64s[1]          = 0;
553         b->whiteout_u64s        = 0;
554         b->uncompacted_whiteout_u64s = 0;
555         bch2_btree_keys_init(b, &c->expensive_debug_checks);
556
557         bch2_time_stats_update(&c->times[BCH_TIME_btree_node_mem_alloc],
558                                start_time);
559
560         return b;
561 err:
562         /* Try to cannibalize another cached btree node: */
563         if (bc->alloc_lock == current) {
564                 b = btree_node_cannibalize(c);
565                 list_del_init(&b->list);
566                 mutex_unlock(&bc->lock);
567
568                 bch2_btree_node_hash_remove(bc, b);
569
570                 trace_btree_node_cannibalize(c);
571                 goto out;
572         }
573
574         mutex_unlock(&bc->lock);
575         return ERR_PTR(-ENOMEM);
576 }
577
578 /* Slowpath, don't want it inlined into btree_iter_traverse() */
579 static noinline struct btree *bch2_btree_node_fill(struct bch_fs *c,
580                                 struct btree_iter *iter,
581                                 const struct bkey_i *k,
582                                 unsigned level,
583                                 enum six_lock_type lock_type,
584                                 bool sync)
585 {
586         struct btree_cache *bc = &c->btree_cache;
587         struct btree *b;
588
589         /*
590          * Parent node must be locked, else we could read in a btree node that's
591          * been freed:
592          */
593         BUG_ON(!btree_node_locked(iter, level + 1));
594         BUG_ON(level >= BTREE_MAX_DEPTH);
595
596         b = bch2_btree_node_mem_alloc(c);
597         if (IS_ERR(b))
598                 return b;
599
600         bkey_copy(&b->key, k);
601         if (bch2_btree_node_hash_insert(bc, b, level, iter->btree_id)) {
602                 /* raced with another fill: */
603
604                 /* mark as unhashed... */
605                 bkey_i_to_extent(&b->key)->v._data[0] = 0;
606
607                 mutex_lock(&bc->lock);
608                 list_add(&b->list, &bc->freeable);
609                 mutex_unlock(&bc->lock);
610
611                 six_unlock_write(&b->lock);
612                 six_unlock_intent(&b->lock);
613                 return NULL;
614         }
615
616         /*
617          * If the btree node wasn't cached, we can't drop our lock on
618          * the parent until after it's added to the cache - because
619          * otherwise we could race with a btree_split() freeing the node
620          * we're trying to lock.
621          *
622          * But the deadlock described below doesn't exist in this case,
623          * so it's safe to not drop the parent lock until here:
624          */
625         if (btree_node_read_locked(iter, level + 1))
626                 btree_node_unlock(iter, level + 1);
627
628         bch2_btree_node_read(c, b, sync);
629
630         six_unlock_write(&b->lock);
631
632         if (!sync) {
633                 six_unlock_intent(&b->lock);
634                 return NULL;
635         }
636
637         if (lock_type == SIX_LOCK_read)
638                 six_lock_downgrade(&b->lock);
639
640         return b;
641 }
642
643 /**
644  * bch_btree_node_get - find a btree node in the cache and lock it, reading it
645  * in from disk if necessary.
646  *
647  * If IO is necessary and running under generic_make_request, returns -EAGAIN.
648  *
649  * The btree node will have either a read or a write lock held, depending on
650  * the @write parameter.
651  */
652 struct btree *bch2_btree_node_get(struct bch_fs *c, struct btree_iter *iter,
653                                   const struct bkey_i *k, unsigned level,
654                                   enum six_lock_type lock_type,
655                                   bool may_drop_locks)
656 {
657         struct btree_cache *bc = &c->btree_cache;
658         struct btree *b;
659         struct bset_tree *t;
660
661         /*
662          * XXX: locking optimization
663          *
664          * we can make the locking looser here - caller can drop lock on parent
665          * node before locking child node (and potentially blocking): we just
666          * have to have bch2_btree_node_fill() call relock on the parent and
667          * return -EINTR if that fails
668          */
669         EBUG_ON(!btree_node_locked(iter, level + 1));
670         EBUG_ON(level >= BTREE_MAX_DEPTH);
671 retry:
672         rcu_read_lock();
673         b = btree_cache_find(bc, k);
674         rcu_read_unlock();
675
676         if (unlikely(!b)) {
677                 /*
678                  * We must have the parent locked to call bch2_btree_node_fill(),
679                  * else we could read in a btree node from disk that's been
680                  * freed:
681                  */
682                 b = bch2_btree_node_fill(c, iter, k, level, lock_type, true);
683
684                 /* We raced and found the btree node in the cache */
685                 if (!b)
686                         goto retry;
687
688                 if (IS_ERR(b))
689                         return b;
690         } else {
691                 /*
692                  * There's a potential deadlock with splits and insertions into
693                  * interior nodes we have to avoid:
694                  *
695                  * The other thread might be holding an intent lock on the node
696                  * we want, and they want to update its parent node so they're
697                  * going to upgrade their intent lock on the parent node to a
698                  * write lock.
699                  *
700                  * But if we're holding a read lock on the parent, and we're
701                  * trying to get the intent lock they're holding, we deadlock.
702                  *
703                  * So to avoid this we drop the read locks on parent nodes when
704                  * we're starting to take intent locks - and handle the race.
705                  *
706                  * The race is that they might be about to free the node we
707                  * want, and dropping our read lock on the parent node lets them
708                  * update the parent marking the node we want as freed, and then
709                  * free it:
710                  *
711                  * To guard against this, btree nodes are evicted from the cache
712                  * when they're freed - and PTR_HASH() is zeroed out, which we
713                  * check for after we lock the node.
714                  *
715                  * Then, bch2_btree_node_relock() on the parent will fail - because
716                  * the parent was modified, when the pointer to the node we want
717                  * was removed - and we'll bail out:
718                  */
719                 if (btree_node_read_locked(iter, level + 1))
720                         btree_node_unlock(iter, level + 1);
721
722                 if (!btree_node_lock(b, k->k.p, level, iter,
723                                      lock_type, may_drop_locks))
724                         return ERR_PTR(-EINTR);
725
726                 if (unlikely(PTR_HASH(&b->key) != PTR_HASH(k) ||
727                              b->level != level ||
728                              race_fault())) {
729                         six_unlock_type(&b->lock, lock_type);
730                         if (bch2_btree_node_relock(iter, level + 1))
731                                 goto retry;
732
733                         trans_restart();
734                         return ERR_PTR(-EINTR);
735                 }
736         }
737
738         wait_on_bit_io(&b->flags, BTREE_NODE_read_in_flight,
739                        TASK_UNINTERRUPTIBLE);
740
741         prefetch(b->aux_data);
742
743         for_each_bset(b, t) {
744                 void *p = (u64 *) b->aux_data + t->aux_data_offset;
745
746                 prefetch(p + L1_CACHE_BYTES * 0);
747                 prefetch(p + L1_CACHE_BYTES * 1);
748                 prefetch(p + L1_CACHE_BYTES * 2);
749         }
750
751         /* avoid atomic set bit if it's not needed: */
752         if (btree_node_accessed(b))
753                 set_btree_node_accessed(b);
754
755         if (unlikely(btree_node_read_error(b))) {
756                 six_unlock_type(&b->lock, lock_type);
757                 return ERR_PTR(-EIO);
758         }
759
760         EBUG_ON(b->btree_id != iter->btree_id ||
761                 BTREE_NODE_LEVEL(b->data) != level ||
762                 bkey_cmp(b->data->max_key, k->k.p));
763
764         return b;
765 }
766
767 struct btree *bch2_btree_node_get_sibling(struct bch_fs *c,
768                                           struct btree_iter *iter,
769                                           struct btree *b,
770                                           bool may_drop_locks,
771                                           enum btree_node_sibling sib)
772 {
773         struct btree *parent;
774         struct btree_node_iter node_iter;
775         struct bkey_packed *k;
776         BKEY_PADDED(k) tmp;
777         struct btree *ret = NULL;
778         unsigned level = b->level;
779
780         parent = btree_iter_node(iter, level + 1);
781         if (!parent)
782                 return NULL;
783
784         if (!bch2_btree_node_relock(iter, level + 1))
785                 goto out_upgrade;
786
787         node_iter = iter->l[parent->level].iter;
788
789         k = bch2_btree_node_iter_peek_all(&node_iter, parent);
790         BUG_ON(bkey_cmp_left_packed(parent, k, &b->key.k.p));
791
792         k = sib == btree_prev_sib
793                 ? bch2_btree_node_iter_prev(&node_iter, parent)
794                 : (bch2_btree_node_iter_advance(&node_iter, parent),
795                    bch2_btree_node_iter_peek(&node_iter, parent));
796         if (!k)
797                 goto out;
798
799         bch2_bkey_unpack(parent, &tmp.k, k);
800
801         ret = bch2_btree_node_get(c, iter, &tmp.k, level,
802                                   SIX_LOCK_intent, may_drop_locks);
803
804         if (PTR_ERR_OR_ZERO(ret) == -EINTR && may_drop_locks) {
805                 struct btree_iter *linked;
806
807                 if (!bch2_btree_node_relock(iter, level + 1))
808                         goto out_upgrade;
809
810                 /*
811                  * We might have got -EINTR because trylock failed, and we're
812                  * holding other locks that would cause us to deadlock:
813                  */
814                 for_each_linked_btree_iter(iter, linked)
815                         if (btree_iter_cmp(iter, linked) < 0)
816                                 __bch2_btree_iter_unlock(linked);
817
818                 if (sib == btree_prev_sib)
819                         btree_node_unlock(iter, level);
820
821                 ret = bch2_btree_node_get(c, iter, &tmp.k, level,
822                                           SIX_LOCK_intent, may_drop_locks);
823
824                 /*
825                  * before btree_iter_relock() calls btree_iter_verify_locks():
826                  */
827                 if (btree_lock_want(iter, level + 1) == BTREE_NODE_UNLOCKED)
828                         btree_node_unlock(iter, level + 1);
829
830                 if (!bch2_btree_node_relock(iter, level)) {
831                         btree_iter_set_dirty(iter, BTREE_ITER_NEED_RELOCK);
832
833                         if (!IS_ERR(ret)) {
834                                 six_unlock_intent(&ret->lock);
835                                 ret = ERR_PTR(-EINTR);
836                         }
837                 }
838
839                 bch2_btree_iter_relock(iter);
840         }
841 out:
842         if (btree_lock_want(iter, level + 1) == BTREE_NODE_UNLOCKED)
843                 btree_node_unlock(iter, level + 1);
844
845         bch2_btree_iter_verify_locks(iter);
846
847         BUG_ON((!may_drop_locks || !IS_ERR(ret)) &&
848                (iter->uptodate >= BTREE_ITER_NEED_RELOCK ||
849                 !btree_node_locked(iter, level)));
850
851         if (!IS_ERR_OR_NULL(ret)) {
852                 struct btree *n1 = ret, *n2 = b;
853
854                 if (sib != btree_prev_sib)
855                         swap(n1, n2);
856
857                 BUG_ON(bkey_cmp(btree_type_successor(n1->btree_id,
858                                                      n1->key.k.p),
859                                 n2->data->min_key));
860         }
861
862         return ret;
863 out_upgrade:
864         if (may_drop_locks)
865                 bch2_btree_iter_upgrade(iter, level + 2, true);
866         ret = ERR_PTR(-EINTR);
867         goto out;
868 }
869
870 void bch2_btree_node_prefetch(struct bch_fs *c, struct btree_iter *iter,
871                               const struct bkey_i *k, unsigned level)
872 {
873         struct btree_cache *bc = &c->btree_cache;
874         struct btree *b;
875
876         BUG_ON(!btree_node_locked(iter, level + 1));
877         BUG_ON(level >= BTREE_MAX_DEPTH);
878
879         rcu_read_lock();
880         b = btree_cache_find(bc, k);
881         rcu_read_unlock();
882
883         if (b)
884                 return;
885
886         bch2_btree_node_fill(c, iter, k, level, SIX_LOCK_read, false);
887 }
888
889 int bch2_print_btree_node(struct bch_fs *c, struct btree *b,
890                           char *buf, size_t len)
891 {
892         const struct bkey_format *f = &b->format;
893         struct bset_stats stats;
894         char ptrs[100];
895
896         memset(&stats, 0, sizeof(stats));
897
898         bch2_val_to_text(c, BKEY_TYPE_BTREE, ptrs, sizeof(ptrs),
899                         bkey_i_to_s_c(&b->key));
900         bch2_btree_keys_stats(b, &stats);
901
902         return scnprintf(buf, len,
903                          "l %u %llu:%llu - %llu:%llu:\n"
904                          "    ptrs: %s\n"
905                          "    format: u64s %u fields %u %u %u %u %u\n"
906                          "    unpack fn len: %u\n"
907                          "    bytes used %zu/%zu (%zu%% full)\n"
908                          "    sib u64s: %u, %u (merge threshold %zu)\n"
909                          "    nr packed keys %u\n"
910                          "    nr unpacked keys %u\n"
911                          "    floats %zu\n"
912                          "    failed unpacked %zu\n"
913                          "    failed prev %zu\n"
914                          "    failed overflow %zu\n",
915                          b->level,
916                          b->data->min_key.inode,
917                          b->data->min_key.offset,
918                          b->data->max_key.inode,
919                          b->data->max_key.offset,
920                          ptrs,
921                          f->key_u64s,
922                          f->bits_per_field[0],
923                          f->bits_per_field[1],
924                          f->bits_per_field[2],
925                          f->bits_per_field[3],
926                          f->bits_per_field[4],
927                          b->unpack_fn_len,
928                          b->nr.live_u64s * sizeof(u64),
929                          btree_bytes(c) - sizeof(struct btree_node),
930                          b->nr.live_u64s * 100 / btree_max_u64s(c),
931                          b->sib_u64s[0],
932                          b->sib_u64s[1],
933                          BTREE_FOREGROUND_MERGE_THRESHOLD(c),
934                          b->nr.packed_keys,
935                          b->nr.unpacked_keys,
936                          stats.floats,
937                          stats.failed_unpacked,
938                          stats.failed_prev,
939                          stats.failed_overflow);
940 }