]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/btree_key_cache.c
Update bcachefs sources to 8fd009dd76 bcachefs: Rip out code for storing backpointers...
[bcachefs-tools-debian] / libbcachefs / btree_key_cache.c
1 // SPDX-License-Identifier: GPL-2.0
2
3 #include "bcachefs.h"
4 #include "btree_cache.h"
5 #include "btree_iter.h"
6 #include "btree_key_cache.h"
7 #include "btree_locking.h"
8 #include "btree_update.h"
9 #include "errcode.h"
10 #include "error.h"
11 #include "journal.h"
12 #include "journal_reclaim.h"
13
14 #include <linux/sched/mm.h>
15 #include <linux/seq_buf.h>
16 #include <trace/events/bcachefs.h>
17
18 static inline bool btree_uses_pcpu_readers(enum btree_id id)
19 {
20         return id == BTREE_ID_subvolumes;
21 }
22
23 static struct kmem_cache *bch2_key_cache;
24
25 static int bch2_btree_key_cache_cmp_fn(struct rhashtable_compare_arg *arg,
26                                        const void *obj)
27 {
28         const struct bkey_cached *ck = obj;
29         const struct bkey_cached_key *key = arg->key;
30
31         return ck->key.btree_id != key->btree_id ||
32                 !bpos_eq(ck->key.pos, key->pos);
33 }
34
35 static const struct rhashtable_params bch2_btree_key_cache_params = {
36         .head_offset    = offsetof(struct bkey_cached, hash),
37         .key_offset     = offsetof(struct bkey_cached, key),
38         .key_len        = sizeof(struct bkey_cached_key),
39         .obj_cmpfn      = bch2_btree_key_cache_cmp_fn,
40 };
41
42 __flatten
43 inline struct bkey_cached *
44 bch2_btree_key_cache_find(struct bch_fs *c, enum btree_id btree_id, struct bpos pos)
45 {
46         struct bkey_cached_key key = {
47                 .btree_id       = btree_id,
48                 .pos            = pos,
49         };
50
51         return rhashtable_lookup_fast(&c->btree_key_cache.table, &key,
52                                       bch2_btree_key_cache_params);
53 }
54
55 static bool bkey_cached_lock_for_evict(struct bkey_cached *ck)
56 {
57         if (!six_trylock_intent(&ck->c.lock))
58                 return false;
59
60         if (test_bit(BKEY_CACHED_DIRTY, &ck->flags)) {
61                 six_unlock_intent(&ck->c.lock);
62                 return false;
63         }
64
65         if (!six_trylock_write(&ck->c.lock)) {
66                 six_unlock_intent(&ck->c.lock);
67                 return false;
68         }
69
70         return true;
71 }
72
73 static void bkey_cached_evict(struct btree_key_cache *c,
74                               struct bkey_cached *ck)
75 {
76         BUG_ON(rhashtable_remove_fast(&c->table, &ck->hash,
77                                       bch2_btree_key_cache_params));
78         memset(&ck->key, ~0, sizeof(ck->key));
79
80         atomic_long_dec(&c->nr_keys);
81 }
82
83 static void bkey_cached_free(struct btree_key_cache *bc,
84                              struct bkey_cached *ck)
85 {
86         struct bch_fs *c = container_of(bc, struct bch_fs, btree_key_cache);
87
88         BUG_ON(test_bit(BKEY_CACHED_DIRTY, &ck->flags));
89
90         ck->btree_trans_barrier_seq =
91                 start_poll_synchronize_srcu(&c->btree_trans_barrier);
92
93         if (ck->c.lock.readers)
94                 list_move_tail(&ck->list, &bc->freed_pcpu);
95         else
96                 list_move_tail(&ck->list, &bc->freed_nonpcpu);
97         atomic_long_inc(&bc->nr_freed);
98
99         kfree(ck->k);
100         ck->k           = NULL;
101         ck->u64s        = 0;
102
103         six_unlock_write(&ck->c.lock);
104         six_unlock_intent(&ck->c.lock);
105 }
106
107 #ifdef __KERNEL__
108 static void __bkey_cached_move_to_freelist_ordered(struct btree_key_cache *bc,
109                                                    struct bkey_cached *ck)
110 {
111         struct bkey_cached *pos;
112
113         list_for_each_entry_reverse(pos, &bc->freed_nonpcpu, list) {
114                 if (ULONG_CMP_GE(ck->btree_trans_barrier_seq,
115                                  pos->btree_trans_barrier_seq)) {
116                         list_move(&ck->list, &pos->list);
117                         return;
118                 }
119         }
120
121         list_move(&ck->list, &bc->freed_nonpcpu);
122 }
123 #endif
124
125 static void bkey_cached_move_to_freelist(struct btree_key_cache *bc,
126                                          struct bkey_cached *ck)
127 {
128         BUG_ON(test_bit(BKEY_CACHED_DIRTY, &ck->flags));
129
130         if (!ck->c.lock.readers) {
131 #ifdef __KERNEL__
132                 struct btree_key_cache_freelist *f;
133                 bool freed = false;
134
135                 preempt_disable();
136                 f = this_cpu_ptr(bc->pcpu_freed);
137
138                 if (f->nr < ARRAY_SIZE(f->objs)) {
139                         f->objs[f->nr++] = ck;
140                         freed = true;
141                 }
142                 preempt_enable();
143
144                 if (!freed) {
145                         mutex_lock(&bc->lock);
146                         preempt_disable();
147                         f = this_cpu_ptr(bc->pcpu_freed);
148
149                         while (f->nr > ARRAY_SIZE(f->objs) / 2) {
150                                 struct bkey_cached *ck2 = f->objs[--f->nr];
151
152                                 __bkey_cached_move_to_freelist_ordered(bc, ck2);
153                         }
154                         preempt_enable();
155
156                         __bkey_cached_move_to_freelist_ordered(bc, ck);
157                         mutex_unlock(&bc->lock);
158                 }
159 #else
160                 mutex_lock(&bc->lock);
161                 list_move_tail(&ck->list, &bc->freed_nonpcpu);
162                 mutex_unlock(&bc->lock);
163 #endif
164         } else {
165                 mutex_lock(&bc->lock);
166                 list_move_tail(&ck->list, &bc->freed_pcpu);
167                 mutex_unlock(&bc->lock);
168         }
169 }
170
171 static void bkey_cached_free_fast(struct btree_key_cache *bc,
172                                   struct bkey_cached *ck)
173 {
174         struct bch_fs *c = container_of(bc, struct bch_fs, btree_key_cache);
175
176         ck->btree_trans_barrier_seq =
177                 start_poll_synchronize_srcu(&c->btree_trans_barrier);
178
179         list_del_init(&ck->list);
180         atomic_long_inc(&bc->nr_freed);
181
182         kfree(ck->k);
183         ck->k           = NULL;
184         ck->u64s        = 0;
185
186         bkey_cached_move_to_freelist(bc, ck);
187
188         six_unlock_write(&ck->c.lock);
189         six_unlock_intent(&ck->c.lock);
190 }
191
192 static struct bkey_cached *
193 bkey_cached_alloc(struct btree_trans *trans, struct btree_path *path,
194                   bool *was_new)
195 {
196         struct bch_fs *c = trans->c;
197         struct btree_key_cache *bc = &c->btree_key_cache;
198         struct bkey_cached *ck = NULL;
199         bool pcpu_readers = btree_uses_pcpu_readers(path->btree_id);
200         int ret;
201
202         if (!pcpu_readers) {
203 #ifdef __KERNEL__
204                 struct btree_key_cache_freelist *f;
205
206                 preempt_disable();
207                 f = this_cpu_ptr(bc->pcpu_freed);
208                 if (f->nr)
209                         ck = f->objs[--f->nr];
210                 preempt_enable();
211
212                 if (!ck) {
213                         mutex_lock(&bc->lock);
214                         preempt_disable();
215                         f = this_cpu_ptr(bc->pcpu_freed);
216
217                         while (!list_empty(&bc->freed_nonpcpu) &&
218                                f->nr < ARRAY_SIZE(f->objs) / 2) {
219                                 ck = list_last_entry(&bc->freed_nonpcpu, struct bkey_cached, list);
220                                 list_del_init(&ck->list);
221                                 f->objs[f->nr++] = ck;
222                         }
223
224                         ck = f->nr ? f->objs[--f->nr] : NULL;
225                         preempt_enable();
226                         mutex_unlock(&bc->lock);
227                 }
228 #else
229                 mutex_lock(&bc->lock);
230                 if (!list_empty(&bc->freed_nonpcpu)) {
231                         ck = list_last_entry(&bc->freed_nonpcpu, struct bkey_cached, list);
232                         list_del_init(&ck->list);
233                 }
234                 mutex_unlock(&bc->lock);
235 #endif
236         } else {
237                 mutex_lock(&bc->lock);
238                 if (!list_empty(&bc->freed_pcpu)) {
239                         ck = list_last_entry(&bc->freed_pcpu, struct bkey_cached, list);
240                         list_del_init(&ck->list);
241                 }
242                 mutex_unlock(&bc->lock);
243         }
244
245         if (ck) {
246                 int ret;
247
248                 ret = btree_node_lock_nopath(trans, &ck->c, SIX_LOCK_intent, _THIS_IP_);
249                 if (unlikely(ret)) {
250                         bkey_cached_move_to_freelist(bc, ck);
251                         return ERR_PTR(ret);
252                 }
253
254                 path->l[0].b = (void *) ck;
255                 path->l[0].lock_seq = ck->c.lock.state.seq;
256                 mark_btree_node_locked(trans, path, 0, SIX_LOCK_intent);
257
258                 ret = bch2_btree_node_lock_write(trans, path, &ck->c);
259                 if (unlikely(ret)) {
260                         btree_node_unlock(trans, path, 0);
261                         bkey_cached_move_to_freelist(bc, ck);
262                         return ERR_PTR(ret);
263                 }
264
265                 return ck;
266         }
267
268         ck = kmem_cache_zalloc(bch2_key_cache, GFP_NOWAIT|__GFP_NOWARN);
269         if (likely(ck))
270                 goto init;
271
272         bch2_trans_unlock(trans);
273
274         ck = kmem_cache_zalloc(bch2_key_cache, GFP_KERNEL);
275
276         ret = bch2_trans_relock(trans);
277         if (ret) {
278                 kmem_cache_free(bch2_key_cache, ck);
279                 return ERR_PTR(ret);
280         }
281
282         if (!ck)
283                 return NULL;
284 init:
285         INIT_LIST_HEAD(&ck->list);
286         bch2_btree_lock_init(&ck->c);
287         if (pcpu_readers)
288                 six_lock_pcpu_alloc(&ck->c.lock);
289
290         ck->c.cached = true;
291         BUG_ON(!six_trylock_intent(&ck->c.lock));
292         BUG_ON(!six_trylock_write(&ck->c.lock));
293         *was_new = true;
294         return ck;
295 }
296
297 static struct bkey_cached *
298 bkey_cached_reuse(struct btree_key_cache *c)
299 {
300         struct bucket_table *tbl;
301         struct rhash_head *pos;
302         struct bkey_cached *ck;
303         unsigned i;
304
305         mutex_lock(&c->lock);
306         rcu_read_lock();
307         tbl = rht_dereference_rcu(c->table.tbl, &c->table);
308         for (i = 0; i < tbl->size; i++)
309                 rht_for_each_entry_rcu(ck, pos, tbl, i, hash) {
310                         if (!test_bit(BKEY_CACHED_DIRTY, &ck->flags) &&
311                             bkey_cached_lock_for_evict(ck)) {
312                                 bkey_cached_evict(c, ck);
313                                 goto out;
314                         }
315                 }
316         ck = NULL;
317 out:
318         rcu_read_unlock();
319         mutex_unlock(&c->lock);
320         return ck;
321 }
322
323 static struct bkey_cached *
324 btree_key_cache_create(struct btree_trans *trans, struct btree_path *path)
325 {
326         struct bch_fs *c = trans->c;
327         struct btree_key_cache *bc = &c->btree_key_cache;
328         struct bkey_cached *ck;
329         bool was_new = false;
330
331         ck = bkey_cached_alloc(trans, path, &was_new);
332         if (IS_ERR(ck))
333                 return ck;
334
335         if (unlikely(!ck)) {
336                 ck = bkey_cached_reuse(bc);
337                 if (unlikely(!ck)) {
338                         bch_err(c, "error allocating memory for key cache item, btree %s",
339                                 bch2_btree_ids[path->btree_id]);
340                         return ERR_PTR(-BCH_ERR_ENOMEM_btree_key_cache_create);
341                 }
342
343                 mark_btree_node_locked(trans, path, 0, SIX_LOCK_intent);
344         } else {
345                 if (path->btree_id == BTREE_ID_subvolumes)
346                         six_lock_pcpu_alloc(&ck->c.lock);
347         }
348
349         ck->c.level             = 0;
350         ck->c.btree_id          = path->btree_id;
351         ck->key.btree_id        = path->btree_id;
352         ck->key.pos             = path->pos;
353         ck->valid               = false;
354         ck->flags               = 1U << BKEY_CACHED_ACCESSED;
355
356         if (unlikely(rhashtable_lookup_insert_fast(&bc->table,
357                                           &ck->hash,
358                                           bch2_btree_key_cache_params))) {
359                 /* We raced with another fill: */
360
361                 if (likely(was_new)) {
362                         six_unlock_write(&ck->c.lock);
363                         six_unlock_intent(&ck->c.lock);
364                         kfree(ck);
365                 } else {
366                         bkey_cached_free_fast(bc, ck);
367                 }
368
369                 mark_btree_node_locked(trans, path, 0, BTREE_NODE_UNLOCKED);
370                 return NULL;
371         }
372
373         atomic_long_inc(&bc->nr_keys);
374
375         six_unlock_write(&ck->c.lock);
376
377         return ck;
378 }
379
380 static int btree_key_cache_fill(struct btree_trans *trans,
381                                 struct btree_path *ck_path,
382                                 struct bkey_cached *ck)
383 {
384         struct btree_iter iter;
385         struct bkey_s_c k;
386         unsigned new_u64s = 0;
387         struct bkey_i *new_k = NULL;
388         int ret;
389
390         bch2_trans_iter_init(trans, &iter, ck->key.btree_id, ck->key.pos,
391                              BTREE_ITER_KEY_CACHE_FILL|
392                              BTREE_ITER_CACHED_NOFILL);
393         k = bch2_btree_iter_peek_slot(&iter);
394         ret = bkey_err(k);
395         if (ret)
396                 goto err;
397
398         if (!bch2_btree_node_relock(trans, ck_path, 0)) {
399                 trace_and_count(trans->c, trans_restart_relock_key_cache_fill, trans, _THIS_IP_, ck_path);
400                 ret = btree_trans_restart(trans, BCH_ERR_transaction_restart_key_cache_fill);
401                 goto err;
402         }
403
404         /*
405          * bch2_varint_decode can read past the end of the buffer by at
406          * most 7 bytes (it won't be used):
407          */
408         new_u64s = k.k->u64s + 1;
409
410         /*
411          * Allocate some extra space so that the transaction commit path is less
412          * likely to have to reallocate, since that requires a transaction
413          * restart:
414          */
415         new_u64s = min(256U, (new_u64s * 3) / 2);
416
417         if (new_u64s > ck->u64s) {
418                 new_u64s = roundup_pow_of_two(new_u64s);
419                 new_k = kmalloc(new_u64s * sizeof(u64), GFP_NOWAIT|__GFP_NOWARN);
420                 if (!new_k) {
421                         bch2_trans_unlock(trans);
422
423                         new_k = kmalloc(new_u64s * sizeof(u64), GFP_KERNEL);
424                         if (!new_k) {
425                                 bch_err(trans->c, "error allocating memory for key cache key, btree %s u64s %u",
426                                         bch2_btree_ids[ck->key.btree_id], new_u64s);
427                                 ret = -BCH_ERR_ENOMEM_btree_key_cache_fill;
428                                 goto err;
429                         }
430
431                         if (!bch2_btree_node_relock(trans, ck_path, 0)) {
432                                 kfree(new_k);
433                                 trace_and_count(trans->c, trans_restart_relock_key_cache_fill, trans, _THIS_IP_, ck_path);
434                                 ret = btree_trans_restart(trans, BCH_ERR_transaction_restart_key_cache_fill);
435                                 goto err;
436                         }
437
438                         ret = bch2_trans_relock(trans);
439                         if (ret) {
440                                 kfree(new_k);
441                                 goto err;
442                         }
443                 }
444         }
445
446         ret = bch2_btree_node_lock_write(trans, ck_path, &ck_path->l[0].b->c);
447         if (ret) {
448                 kfree(new_k);
449                 goto err;
450         }
451
452         if (new_k) {
453                 kfree(ck->k);
454                 ck->u64s = new_u64s;
455                 ck->k = new_k;
456         }
457
458         bkey_reassemble(ck->k, k);
459         ck->valid = true;
460         bch2_btree_node_unlock_write(trans, ck_path, ck_path->l[0].b);
461
462         /* We're not likely to need this iterator again: */
463         set_btree_iter_dontneed(&iter);
464 err:
465         bch2_trans_iter_exit(trans, &iter);
466         return ret;
467 }
468
469 static noinline int
470 bch2_btree_path_traverse_cached_slowpath(struct btree_trans *trans, struct btree_path *path,
471                                          unsigned flags)
472 {
473         struct bch_fs *c = trans->c;
474         struct bkey_cached *ck;
475         int ret = 0;
476
477         BUG_ON(path->level);
478
479         path->l[1].b = NULL;
480
481         if (bch2_btree_node_relock_notrace(trans, path, 0)) {
482                 ck = (void *) path->l[0].b;
483                 goto fill;
484         }
485 retry:
486         ck = bch2_btree_key_cache_find(c, path->btree_id, path->pos);
487         if (!ck) {
488                 ck = btree_key_cache_create(trans, path);
489                 ret = PTR_ERR_OR_ZERO(ck);
490                 if (ret)
491                         goto err;
492                 if (!ck)
493                         goto retry;
494
495                 mark_btree_node_locked(trans, path, 0, SIX_LOCK_intent);
496                 path->locks_want = 1;
497         } else {
498                 enum six_lock_type lock_want = __btree_lock_want(path, 0);
499
500                 ret = btree_node_lock(trans, path, (void *) ck, 0,
501                                       lock_want, _THIS_IP_);
502                 if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
503                         goto err;
504
505                 BUG_ON(ret);
506
507                 if (ck->key.btree_id != path->btree_id ||
508                     !bpos_eq(ck->key.pos, path->pos)) {
509                         six_unlock_type(&ck->c.lock, lock_want);
510                         goto retry;
511                 }
512
513                 mark_btree_node_locked(trans, path, 0, lock_want);
514         }
515
516         path->l[0].lock_seq     = ck->c.lock.state.seq;
517         path->l[0].b            = (void *) ck;
518 fill:
519         path->uptodate = BTREE_ITER_UPTODATE;
520
521         if (!ck->valid && !(flags & BTREE_ITER_CACHED_NOFILL)) {
522                 /*
523                  * Using the underscore version because we haven't set
524                  * path->uptodate yet:
525                  */
526                 if (!path->locks_want &&
527                     !__bch2_btree_path_upgrade(trans, path, 1)) {
528                         trace_and_count(trans->c, trans_restart_key_cache_upgrade, trans, _THIS_IP_);
529                         ret = btree_trans_restart(trans, BCH_ERR_transaction_restart_key_cache_upgrade);
530                         goto err;
531                 }
532
533                 ret = btree_key_cache_fill(trans, path, ck);
534                 if (ret)
535                         goto err;
536
537                 ret = bch2_btree_path_relock(trans, path, _THIS_IP_);
538                 if (ret)
539                         goto err;
540
541                 path->uptodate = BTREE_ITER_UPTODATE;
542         }
543
544         if (!test_bit(BKEY_CACHED_ACCESSED, &ck->flags))
545                 set_bit(BKEY_CACHED_ACCESSED, &ck->flags);
546
547         BUG_ON(btree_node_locked_type(path, 0) != btree_lock_want(path, 0));
548         BUG_ON(path->uptodate);
549
550         return ret;
551 err:
552         path->uptodate = BTREE_ITER_NEED_TRAVERSE;
553         if (!bch2_err_matches(ret, BCH_ERR_transaction_restart)) {
554                 btree_node_unlock(trans, path, 0);
555                 path->l[0].b = ERR_PTR(ret);
556         }
557         return ret;
558 }
559
560 int bch2_btree_path_traverse_cached(struct btree_trans *trans, struct btree_path *path,
561                                     unsigned flags)
562 {
563         struct bch_fs *c = trans->c;
564         struct bkey_cached *ck;
565         int ret = 0;
566
567         EBUG_ON(path->level);
568
569         path->l[1].b = NULL;
570
571         if (bch2_btree_node_relock_notrace(trans, path, 0)) {
572                 ck = (void *) path->l[0].b;
573                 goto fill;
574         }
575 retry:
576         ck = bch2_btree_key_cache_find(c, path->btree_id, path->pos);
577         if (!ck) {
578                 return bch2_btree_path_traverse_cached_slowpath(trans, path, flags);
579         } else {
580                 enum six_lock_type lock_want = __btree_lock_want(path, 0);
581
582                 ret = btree_node_lock(trans, path, (void *) ck, 0,
583                                       lock_want, _THIS_IP_);
584                 EBUG_ON(ret && !bch2_err_matches(ret, BCH_ERR_transaction_restart));
585
586                 if (ret)
587                         return ret;
588
589                 if (ck->key.btree_id != path->btree_id ||
590                     !bpos_eq(ck->key.pos, path->pos)) {
591                         six_unlock_type(&ck->c.lock, lock_want);
592                         goto retry;
593                 }
594
595                 mark_btree_node_locked(trans, path, 0, lock_want);
596         }
597
598         path->l[0].lock_seq     = ck->c.lock.state.seq;
599         path->l[0].b            = (void *) ck;
600 fill:
601         if (!ck->valid)
602                 return bch2_btree_path_traverse_cached_slowpath(trans, path, flags);
603
604         if (!test_bit(BKEY_CACHED_ACCESSED, &ck->flags))
605                 set_bit(BKEY_CACHED_ACCESSED, &ck->flags);
606
607         path->uptodate = BTREE_ITER_UPTODATE;
608         EBUG_ON(!ck->valid);
609         EBUG_ON(btree_node_locked_type(path, 0) != btree_lock_want(path, 0));
610
611         return ret;
612 }
613
614 static int btree_key_cache_flush_pos(struct btree_trans *trans,
615                                      struct bkey_cached_key key,
616                                      u64 journal_seq,
617                                      unsigned commit_flags,
618                                      bool evict)
619 {
620         struct bch_fs *c = trans->c;
621         struct journal *j = &c->journal;
622         struct btree_iter c_iter, b_iter;
623         struct bkey_cached *ck = NULL;
624         int ret;
625
626         bch2_trans_iter_init(trans, &b_iter, key.btree_id, key.pos,
627                              BTREE_ITER_SLOTS|
628                              BTREE_ITER_INTENT|
629                              BTREE_ITER_ALL_SNAPSHOTS);
630         bch2_trans_iter_init(trans, &c_iter, key.btree_id, key.pos,
631                              BTREE_ITER_CACHED|
632                              BTREE_ITER_INTENT);
633         b_iter.flags &= ~BTREE_ITER_WITH_KEY_CACHE;
634
635         ret = bch2_btree_iter_traverse(&c_iter);
636         if (ret)
637                 goto out;
638
639         ck = (void *) c_iter.path->l[0].b;
640         if (!ck)
641                 goto out;
642
643         if (!test_bit(BKEY_CACHED_DIRTY, &ck->flags)) {
644                 if (evict)
645                         goto evict;
646                 goto out;
647         }
648
649         BUG_ON(!ck->valid);
650
651         if (journal_seq && ck->journal.seq != journal_seq)
652                 goto out;
653
654         /*
655          * Since journal reclaim depends on us making progress here, and the
656          * allocator/copygc depend on journal reclaim making progress, we need
657          * to be using alloc reserves:
658          */
659         ret   = bch2_btree_iter_traverse(&b_iter) ?:
660                 bch2_trans_update(trans, &b_iter, ck->k,
661                                   BTREE_UPDATE_KEY_CACHE_RECLAIM|
662                                   BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE|
663                                   BTREE_TRIGGER_NORUN) ?:
664                 bch2_trans_commit(trans, NULL, NULL,
665                                   BTREE_INSERT_NOCHECK_RW|
666                                   BTREE_INSERT_NOFAIL|
667                                   BTREE_INSERT_USE_RESERVE|
668                                   (ck->journal.seq == journal_last_seq(j)
669                                    ? JOURNAL_WATERMARK_reserved
670                                    : 0)|
671                                   commit_flags);
672
673         bch2_fs_fatal_err_on(ret &&
674                              !bch2_err_matches(ret, BCH_ERR_transaction_restart) &&
675                              !bch2_err_matches(ret, BCH_ERR_journal_reclaim_would_deadlock) &&
676                              !bch2_journal_error(j), c,
677                              "error flushing key cache: %s", bch2_err_str(ret));
678         if (ret)
679                 goto out;
680
681         bch2_journal_pin_drop(j, &ck->journal);
682         bch2_journal_preres_put(j, &ck->res);
683
684         BUG_ON(!btree_node_locked(c_iter.path, 0));
685
686         if (!evict) {
687                 if (test_bit(BKEY_CACHED_DIRTY, &ck->flags)) {
688                         clear_bit(BKEY_CACHED_DIRTY, &ck->flags);
689                         atomic_long_dec(&c->btree_key_cache.nr_dirty);
690                 }
691         } else {
692                 struct btree_path *path2;
693 evict:
694                 trans_for_each_path(trans, path2)
695                         if (path2 != c_iter.path)
696                                 __bch2_btree_path_unlock(trans, path2);
697
698                 bch2_btree_node_lock_write_nofail(trans, c_iter.path, &ck->c);
699
700                 if (test_bit(BKEY_CACHED_DIRTY, &ck->flags)) {
701                         clear_bit(BKEY_CACHED_DIRTY, &ck->flags);
702                         atomic_long_dec(&c->btree_key_cache.nr_dirty);
703                 }
704
705                 mark_btree_node_locked_noreset(c_iter.path, 0, BTREE_NODE_UNLOCKED);
706                 bkey_cached_evict(&c->btree_key_cache, ck);
707                 bkey_cached_free_fast(&c->btree_key_cache, ck);
708         }
709 out:
710         bch2_trans_iter_exit(trans, &b_iter);
711         bch2_trans_iter_exit(trans, &c_iter);
712         return ret;
713 }
714
715 int bch2_btree_key_cache_journal_flush(struct journal *j,
716                                 struct journal_entry_pin *pin, u64 seq)
717 {
718         struct bch_fs *c = container_of(j, struct bch_fs, journal);
719         struct bkey_cached *ck =
720                 container_of(pin, struct bkey_cached, journal);
721         struct bkey_cached_key key;
722         struct btree_trans trans;
723         int srcu_idx = srcu_read_lock(&c->btree_trans_barrier);
724         int ret = 0;
725
726         bch2_trans_init(&trans, c, 0, 0);
727
728         btree_node_lock_nopath_nofail(&trans, &ck->c, SIX_LOCK_read);
729         key = ck->key;
730
731         if (ck->journal.seq != seq ||
732             !test_bit(BKEY_CACHED_DIRTY, &ck->flags)) {
733                 six_unlock_read(&ck->c.lock);
734                 goto unlock;
735         }
736
737         if (ck->seq != seq) {
738                 bch2_journal_pin_update(&c->journal, ck->seq, &ck->journal,
739                                         bch2_btree_key_cache_journal_flush);
740                 six_unlock_read(&ck->c.lock);
741                 goto unlock;
742         }
743         six_unlock_read(&ck->c.lock);
744
745         ret = commit_do(&trans, NULL, NULL, 0,
746                 btree_key_cache_flush_pos(&trans, key, seq,
747                                 BTREE_INSERT_JOURNAL_RECLAIM, false));
748 unlock:
749         srcu_read_unlock(&c->btree_trans_barrier, srcu_idx);
750
751         bch2_trans_exit(&trans);
752         return ret;
753 }
754
755 /*
756  * Flush and evict a key from the key cache:
757  */
758 int bch2_btree_key_cache_flush(struct btree_trans *trans,
759                                enum btree_id id, struct bpos pos)
760 {
761         struct bch_fs *c = trans->c;
762         struct bkey_cached_key key = { id, pos };
763
764         /* Fastpath - assume it won't be found: */
765         if (!bch2_btree_key_cache_find(c, id, pos))
766                 return 0;
767
768         return btree_key_cache_flush_pos(trans, key, 0, 0, true);
769 }
770
771 bool bch2_btree_insert_key_cached(struct btree_trans *trans,
772                                   unsigned flags,
773                                   struct btree_insert_entry *insert_entry)
774 {
775         struct bch_fs *c = trans->c;
776         struct bkey_cached *ck = (void *) insert_entry->path->l[0].b;
777         struct bkey_i *insert = insert_entry->k;
778         bool kick_reclaim = false;
779
780         BUG_ON(insert->k.u64s > ck->u64s);
781
782         if (likely(!(flags & BTREE_INSERT_JOURNAL_REPLAY))) {
783                 int difference;
784
785                 BUG_ON(jset_u64s(insert->k.u64s) > trans->journal_preres.u64s);
786
787                 difference = jset_u64s(insert->k.u64s) - ck->res.u64s;
788                 if (difference > 0) {
789                         trans->journal_preres.u64s      -= difference;
790                         ck->res.u64s                    += difference;
791                 }
792         }
793
794         bkey_copy(ck->k, insert);
795         ck->valid = true;
796
797         if (!test_bit(BKEY_CACHED_DIRTY, &ck->flags)) {
798                 set_bit(BKEY_CACHED_DIRTY, &ck->flags);
799                 atomic_long_inc(&c->btree_key_cache.nr_dirty);
800
801                 if (bch2_nr_btree_keys_need_flush(c))
802                         kick_reclaim = true;
803         }
804
805         /*
806          * To minimize lock contention, we only add the journal pin here and
807          * defer pin updates to the flush callback via ->seq. Be careful not to
808          * update ->seq on nojournal commits because we don't want to update the
809          * pin to a seq that doesn't include journal updates on disk. Otherwise
810          * we risk losing the update after a crash.
811          *
812          * The only exception is if the pin is not active in the first place. We
813          * have to add the pin because journal reclaim drives key cache
814          * flushing. The flush callback will not proceed unless ->seq matches
815          * the latest pin, so make sure it starts with a consistent value.
816          */
817         if (!(insert_entry->flags & BTREE_UPDATE_NOJOURNAL) ||
818             !journal_pin_active(&ck->journal)) {
819                 ck->seq = trans->journal_res.seq;
820         }
821         bch2_journal_pin_add(&c->journal, trans->journal_res.seq,
822                              &ck->journal, bch2_btree_key_cache_journal_flush);
823
824         if (kick_reclaim)
825                 journal_reclaim_kick(&c->journal);
826         return true;
827 }
828
829 void bch2_btree_key_cache_drop(struct btree_trans *trans,
830                                struct btree_path *path)
831 {
832         struct bch_fs *c = trans->c;
833         struct bkey_cached *ck = (void *) path->l[0].b;
834
835         BUG_ON(!ck->valid);
836
837         /*
838          * We just did an update to the btree, bypassing the key cache: the key
839          * cache key is now stale and must be dropped, even if dirty:
840          */
841         if (test_bit(BKEY_CACHED_DIRTY, &ck->flags)) {
842                 clear_bit(BKEY_CACHED_DIRTY, &ck->flags);
843                 atomic_long_dec(&c->btree_key_cache.nr_dirty);
844                 bch2_journal_pin_drop(&c->journal, &ck->journal);
845         }
846
847         ck->valid = false;
848 }
849
850 static unsigned long bch2_btree_key_cache_scan(struct shrinker *shrink,
851                                            struct shrink_control *sc)
852 {
853         struct bch_fs *c = container_of(shrink, struct bch_fs,
854                                         btree_key_cache.shrink);
855         struct btree_key_cache *bc = &c->btree_key_cache;
856         struct bucket_table *tbl;
857         struct bkey_cached *ck, *t;
858         size_t scanned = 0, freed = 0, nr = sc->nr_to_scan;
859         unsigned start, flags;
860         int srcu_idx;
861
862         mutex_lock(&bc->lock);
863         srcu_idx = srcu_read_lock(&c->btree_trans_barrier);
864         flags = memalloc_nofs_save();
865
866         /*
867          * Newest freed entries are at the end of the list - once we hit one
868          * that's too new to be freed, we can bail out:
869          */
870         list_for_each_entry_safe(ck, t, &bc->freed_nonpcpu, list) {
871                 if (!poll_state_synchronize_srcu(&c->btree_trans_barrier,
872                                                  ck->btree_trans_barrier_seq))
873                         break;
874
875                 list_del(&ck->list);
876                 six_lock_pcpu_free(&ck->c.lock);
877                 kmem_cache_free(bch2_key_cache, ck);
878                 atomic_long_dec(&bc->nr_freed);
879                 scanned++;
880                 freed++;
881         }
882
883         if (scanned >= nr)
884                 goto out;
885
886         list_for_each_entry_safe(ck, t, &bc->freed_pcpu, list) {
887                 if (!poll_state_synchronize_srcu(&c->btree_trans_barrier,
888                                                  ck->btree_trans_barrier_seq))
889                         break;
890
891                 list_del(&ck->list);
892                 six_lock_pcpu_free(&ck->c.lock);
893                 kmem_cache_free(bch2_key_cache, ck);
894                 atomic_long_dec(&bc->nr_freed);
895                 scanned++;
896                 freed++;
897         }
898
899         if (scanned >= nr)
900                 goto out;
901
902         rcu_read_lock();
903         tbl = rht_dereference_rcu(bc->table.tbl, &bc->table);
904         if (bc->shrink_iter >= tbl->size)
905                 bc->shrink_iter = 0;
906         start = bc->shrink_iter;
907
908         do {
909                 struct rhash_head *pos, *next;
910
911                 pos = rht_ptr_rcu(rht_bucket(tbl, bc->shrink_iter));
912
913                 while (!rht_is_a_nulls(pos)) {
914                         next = rht_dereference_bucket_rcu(pos->next, tbl, bc->shrink_iter);
915                         ck = container_of(pos, struct bkey_cached, hash);
916
917                         if (test_bit(BKEY_CACHED_DIRTY, &ck->flags))
918                                 goto next;
919
920                         if (test_bit(BKEY_CACHED_ACCESSED, &ck->flags))
921                                 clear_bit(BKEY_CACHED_ACCESSED, &ck->flags);
922                         else if (bkey_cached_lock_for_evict(ck)) {
923                                 bkey_cached_evict(bc, ck);
924                                 bkey_cached_free(bc, ck);
925                         }
926
927                         scanned++;
928                         if (scanned >= nr)
929                                 break;
930 next:
931                         pos = next;
932                 }
933
934                 bc->shrink_iter++;
935                 if (bc->shrink_iter >= tbl->size)
936                         bc->shrink_iter = 0;
937         } while (scanned < nr && bc->shrink_iter != start);
938
939         rcu_read_unlock();
940 out:
941         memalloc_nofs_restore(flags);
942         srcu_read_unlock(&c->btree_trans_barrier, srcu_idx);
943         mutex_unlock(&bc->lock);
944
945         return freed;
946 }
947
948 static unsigned long bch2_btree_key_cache_count(struct shrinker *shrink,
949                                             struct shrink_control *sc)
950 {
951         struct bch_fs *c = container_of(shrink, struct bch_fs,
952                                         btree_key_cache.shrink);
953         struct btree_key_cache *bc = &c->btree_key_cache;
954         long nr = atomic_long_read(&bc->nr_keys) -
955                 atomic_long_read(&bc->nr_dirty);
956
957         return max(0L, nr);
958 }
959
960 void bch2_fs_btree_key_cache_exit(struct btree_key_cache *bc)
961 {
962         struct bch_fs *c = container_of(bc, struct bch_fs, btree_key_cache);
963         struct bucket_table *tbl;
964         struct bkey_cached *ck, *n;
965         struct rhash_head *pos;
966         LIST_HEAD(items);
967         unsigned i;
968 #ifdef __KERNEL__
969         int cpu;
970 #endif
971
972         if (bc->shrink.list.next)
973                 unregister_shrinker(&bc->shrink);
974
975         mutex_lock(&bc->lock);
976
977         /*
978          * The loop is needed to guard against racing with rehash:
979          */
980         while (atomic_long_read(&bc->nr_keys)) {
981                 rcu_read_lock();
982                 tbl = rht_dereference_rcu(bc->table.tbl, &bc->table);
983                 if (tbl)
984                         for (i = 0; i < tbl->size; i++)
985                                 rht_for_each_entry_rcu(ck, pos, tbl, i, hash) {
986                                         bkey_cached_evict(bc, ck);
987                                         list_add(&ck->list, &items);
988                                 }
989                 rcu_read_unlock();
990         }
991
992 #ifdef __KERNEL__
993         for_each_possible_cpu(cpu) {
994                 struct btree_key_cache_freelist *f =
995                         per_cpu_ptr(bc->pcpu_freed, cpu);
996
997                 for (i = 0; i < f->nr; i++) {
998                         ck = f->objs[i];
999                         list_add(&ck->list, &items);
1000                 }
1001         }
1002 #endif
1003
1004         list_splice(&bc->freed_pcpu,    &items);
1005         list_splice(&bc->freed_nonpcpu, &items);
1006
1007         mutex_unlock(&bc->lock);
1008
1009         list_for_each_entry_safe(ck, n, &items, list) {
1010                 cond_resched();
1011
1012                 bch2_journal_pin_drop(&c->journal, &ck->journal);
1013                 bch2_journal_preres_put(&c->journal, &ck->res);
1014
1015                 list_del(&ck->list);
1016                 kfree(ck->k);
1017                 six_lock_pcpu_free(&ck->c.lock);
1018                 kmem_cache_free(bch2_key_cache, ck);
1019         }
1020
1021         if (atomic_long_read(&bc->nr_dirty) &&
1022             !bch2_journal_error(&c->journal) &&
1023             test_bit(BCH_FS_WAS_RW, &c->flags))
1024                 panic("btree key cache shutdown error: nr_dirty nonzero (%li)\n",
1025                       atomic_long_read(&bc->nr_dirty));
1026
1027         if (atomic_long_read(&bc->nr_keys))
1028                 panic("btree key cache shutdown error: nr_keys nonzero (%li)\n",
1029                       atomic_long_read(&bc->nr_keys));
1030
1031         if (bc->table_init_done)
1032                 rhashtable_destroy(&bc->table);
1033
1034         free_percpu(bc->pcpu_freed);
1035 }
1036
1037 void bch2_fs_btree_key_cache_init_early(struct btree_key_cache *c)
1038 {
1039         mutex_init(&c->lock);
1040         INIT_LIST_HEAD(&c->freed_pcpu);
1041         INIT_LIST_HEAD(&c->freed_nonpcpu);
1042 }
1043
1044 static void bch2_btree_key_cache_shrinker_to_text(struct seq_buf *s, struct shrinker *shrink)
1045 {
1046         struct btree_key_cache *bc =
1047                 container_of(shrink, struct btree_key_cache, shrink);
1048         char *cbuf;
1049         size_t buflen = seq_buf_get_buf(s, &cbuf);
1050         struct printbuf out = PRINTBUF_EXTERN(cbuf, buflen);
1051
1052         bch2_btree_key_cache_to_text(&out, bc);
1053         seq_buf_commit(s, out.pos);
1054 }
1055
1056 int bch2_fs_btree_key_cache_init(struct btree_key_cache *bc)
1057 {
1058         struct bch_fs *c = container_of(bc, struct bch_fs, btree_key_cache);
1059
1060 #ifdef __KERNEL__
1061         bc->pcpu_freed = alloc_percpu(struct btree_key_cache_freelist);
1062         if (!bc->pcpu_freed)
1063                 return -BCH_ERR_ENOMEM_fs_btree_cache_init;
1064 #endif
1065
1066         if (rhashtable_init(&bc->table, &bch2_btree_key_cache_params))
1067                 return -BCH_ERR_ENOMEM_fs_btree_cache_init;
1068
1069         bc->table_init_done = true;
1070
1071         bc->shrink.seeks                = 0;
1072         bc->shrink.count_objects        = bch2_btree_key_cache_count;
1073         bc->shrink.scan_objects         = bch2_btree_key_cache_scan;
1074         bc->shrink.to_text              = bch2_btree_key_cache_shrinker_to_text;
1075         if (register_shrinker(&bc->shrink, "%s/btree_key_cache", c->name))
1076                 return -BCH_ERR_ENOMEM_fs_btree_cache_init;
1077         return 0;
1078 }
1079
1080 void bch2_btree_key_cache_to_text(struct printbuf *out, struct btree_key_cache *c)
1081 {
1082         prt_printf(out, "nr_freed:\t%zu",       atomic_long_read(&c->nr_freed));
1083         prt_newline(out);
1084         prt_printf(out, "nr_keys:\t%lu",        atomic_long_read(&c->nr_keys));
1085         prt_newline(out);
1086         prt_printf(out, "nr_dirty:\t%lu",       atomic_long_read(&c->nr_dirty));
1087         prt_newline(out);
1088 }
1089
1090 void bch2_btree_key_cache_exit(void)
1091 {
1092         kmem_cache_destroy(bch2_key_cache);
1093 }
1094
1095 int __init bch2_btree_key_cache_init(void)
1096 {
1097         bch2_key_cache = KMEM_CACHE(bkey_cached, 0);
1098         if (!bch2_key_cache)
1099                 return -ENOMEM;
1100
1101         return 0;
1102 }