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