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