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