]> git.sesse.net Git - bcachefs-tools-debian/blob - libbcachefs/btree_key_cache.c
Update bcachefs sources to 176718966e bcachefs: Re-enable hash_redo_key()
[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 static int bkey_cached_check_fn(struct six_lock *lock, void *p)
402 {
403         struct bkey_cached *ck = container_of(lock, struct bkey_cached, c.lock);
404         const struct btree_path *path = p;
405
406         if (ck->key.btree_id != path->btree_id &&
407             bpos_cmp(ck->key.pos, path->pos))
408                 return BCH_ERR_lock_fail_node_reused;
409         return 0;
410 }
411
412 __flatten
413 int bch2_btree_path_traverse_cached(struct btree_trans *trans, struct btree_path *path,
414                                     unsigned flags)
415 {
416         struct bch_fs *c = trans->c;
417         struct bkey_cached *ck;
418         int ret = 0;
419
420         BUG_ON(path->level);
421
422         path->l[1].b = NULL;
423
424         if (bch2_btree_node_relock(trans, path, 0)) {
425                 ck = (void *) path->l[0].b;
426                 goto fill;
427         }
428 retry:
429         ck = bch2_btree_key_cache_find(c, path->btree_id, path->pos);
430         if (!ck) {
431                 ck = btree_key_cache_create(trans, path);
432                 ret = PTR_ERR_OR_ZERO(ck);
433                 if (ret)
434                         goto err;
435                 if (!ck)
436                         goto retry;
437
438                 mark_btree_node_locked(trans, path, 0, SIX_LOCK_intent);
439                 path->locks_want = 1;
440         } else {
441                 enum six_lock_type lock_want = __btree_lock_want(path, 0);
442
443                 ret = btree_node_lock(trans, path, (void *) ck, path->pos, 0,
444                                       lock_want,
445                                       bkey_cached_check_fn, path, _THIS_IP_);
446                 if (ret) {
447                         if (bch2_err_matches(ret, BCH_ERR_lock_fail_node_reused))
448                                 goto retry;
449                         if (bch2_err_matches(ret, BCH_ERR_transaction_restart))
450                                 goto err;
451                         BUG();
452                 }
453
454                 if (ck->key.btree_id != path->btree_id ||
455                     bpos_cmp(ck->key.pos, path->pos)) {
456                         six_unlock_type(&ck->c.lock, lock_want);
457                         goto retry;
458                 }
459
460                 mark_btree_node_locked(trans, path, 0, lock_want);
461         }
462
463         path->l[0].lock_seq     = ck->c.lock.state.seq;
464         path->l[0].b            = (void *) ck;
465 fill:
466         if (!ck->valid) {
467                 /*
468                  * Using the underscore version because we haven't set
469                  * path->uptodate yet:
470                  */
471                 if (!path->locks_want &&
472                     !__bch2_btree_path_upgrade(trans, path, 1)) {
473                         trace_and_count(trans->c, trans_restart_key_cache_upgrade, trans, _THIS_IP_);
474                         ret = btree_trans_restart(trans, BCH_ERR_transaction_restart_key_cache_upgrade);
475                         goto err;
476                 }
477
478                 ret = btree_key_cache_fill(trans, path, ck);
479                 if (ret)
480                         goto err;
481         }
482
483         if (!test_bit(BKEY_CACHED_ACCESSED, &ck->flags))
484                 set_bit(BKEY_CACHED_ACCESSED, &ck->flags);
485
486         path->uptodate = BTREE_ITER_UPTODATE;
487         BUG_ON(!ck->valid);
488         BUG_ON(btree_node_locked_type(path, 0) != btree_lock_want(path, 0));
489
490         return ret;
491 err:
492         if (!bch2_err_matches(ret, BCH_ERR_transaction_restart)) {
493                 btree_node_unlock(trans, path, 0);
494                 path->l[0].b = ERR_PTR(ret);
495         }
496         return ret;
497 }
498
499 static int btree_key_cache_flush_pos(struct btree_trans *trans,
500                                      struct bkey_cached_key key,
501                                      u64 journal_seq,
502                                      unsigned commit_flags,
503                                      bool evict)
504 {
505         struct bch_fs *c = trans->c;
506         struct journal *j = &c->journal;
507         struct btree_iter c_iter, b_iter;
508         struct bkey_cached *ck = NULL;
509         int ret;
510
511         bch2_trans_iter_init(trans, &b_iter, key.btree_id, key.pos,
512                              BTREE_ITER_SLOTS|
513                              BTREE_ITER_INTENT|
514                              BTREE_ITER_ALL_SNAPSHOTS);
515         bch2_trans_iter_init(trans, &c_iter, key.btree_id, key.pos,
516                              BTREE_ITER_CACHED|
517                              BTREE_ITER_INTENT);
518         b_iter.flags &= ~BTREE_ITER_WITH_KEY_CACHE;
519
520         ret = bch2_btree_iter_traverse(&c_iter);
521         if (ret)
522                 goto out;
523
524         ck = (void *) c_iter.path->l[0].b;
525         if (!ck)
526                 goto out;
527
528         if (!test_bit(BKEY_CACHED_DIRTY, &ck->flags)) {
529                 if (evict)
530                         goto evict;
531                 goto out;
532         }
533
534         BUG_ON(!ck->valid);
535
536         if (journal_seq && ck->journal.seq != journal_seq)
537                 goto out;
538
539         /*
540          * Since journal reclaim depends on us making progress here, and the
541          * allocator/copygc depend on journal reclaim making progress, we need
542          * to be using alloc reserves:
543          * */
544         ret   = bch2_btree_iter_traverse(&b_iter) ?:
545                 bch2_trans_update(trans, &b_iter, ck->k,
546                                   BTREE_UPDATE_KEY_CACHE_RECLAIM|
547                                   BTREE_UPDATE_INTERNAL_SNAPSHOT_NODE|
548                                   BTREE_TRIGGER_NORUN) ?:
549                 bch2_trans_commit(trans, NULL, NULL,
550                                   BTREE_INSERT_NOCHECK_RW|
551                                   BTREE_INSERT_NOFAIL|
552                                   BTREE_INSERT_USE_RESERVE|
553                                   (ck->journal.seq == journal_last_seq(j)
554                                    ? JOURNAL_WATERMARK_reserved
555                                    : 0)|
556                                   commit_flags);
557
558         bch2_fs_fatal_err_on(ret &&
559                              !bch2_err_matches(ret, BCH_ERR_transaction_restart) &&
560                              !bch2_err_matches(ret, BCH_ERR_journal_reclaim_would_deadlock) &&
561                              !bch2_journal_error(j), c,
562                              "error flushing key cache: %s", bch2_err_str(ret));
563         if (ret)
564                 goto out;
565
566         bch2_journal_pin_drop(j, &ck->journal);
567         bch2_journal_preres_put(j, &ck->res);
568
569         BUG_ON(!btree_node_locked(c_iter.path, 0));
570
571         if (!evict) {
572                 if (test_bit(BKEY_CACHED_DIRTY, &ck->flags)) {
573                         clear_bit(BKEY_CACHED_DIRTY, &ck->flags);
574                         atomic_long_dec(&c->btree_key_cache.nr_dirty);
575                 }
576         } else {
577                 struct btree_path *path2;
578 evict:
579                 trans_for_each_path(trans, path2)
580                         if (path2 != c_iter.path)
581                                 __bch2_btree_path_unlock(trans, path2);
582
583                 bch2_btree_node_lock_write_nofail(trans, c_iter.path, &ck->c);
584
585                 if (test_bit(BKEY_CACHED_DIRTY, &ck->flags)) {
586                         clear_bit(BKEY_CACHED_DIRTY, &ck->flags);
587                         atomic_long_dec(&c->btree_key_cache.nr_dirty);
588                 }
589
590                 mark_btree_node_locked_noreset(c_iter.path, 0, BTREE_NODE_UNLOCKED);
591                 bkey_cached_evict(&c->btree_key_cache, ck);
592                 bkey_cached_free_fast(&c->btree_key_cache, ck);
593         }
594 out:
595         bch2_trans_iter_exit(trans, &b_iter);
596         bch2_trans_iter_exit(trans, &c_iter);
597         return ret;
598 }
599
600 int bch2_btree_key_cache_journal_flush(struct journal *j,
601                                 struct journal_entry_pin *pin, u64 seq)
602 {
603         struct bch_fs *c = container_of(j, struct bch_fs, journal);
604         struct bkey_cached *ck =
605                 container_of(pin, struct bkey_cached, journal);
606         struct bkey_cached_key key;
607         struct btree_trans trans;
608         int srcu_idx = srcu_read_lock(&c->btree_trans_barrier);
609         int ret = 0;
610
611         bch2_trans_init(&trans, c, 0, 0);
612
613         btree_node_lock_nopath_nofail(&trans, &ck->c, SIX_LOCK_read);
614         key = ck->key;
615
616         if (ck->journal.seq != seq ||
617             !test_bit(BKEY_CACHED_DIRTY, &ck->flags)) {
618                 six_unlock_read(&ck->c.lock);
619                 goto unlock;
620         }
621         six_unlock_read(&ck->c.lock);
622
623         ret = commit_do(&trans, NULL, NULL, 0,
624                 btree_key_cache_flush_pos(&trans, key, seq,
625                                 BTREE_INSERT_JOURNAL_RECLAIM, false));
626 unlock:
627         srcu_read_unlock(&c->btree_trans_barrier, srcu_idx);
628
629         bch2_trans_exit(&trans);
630         return ret;
631 }
632
633 /*
634  * Flush and evict a key from the key cache:
635  */
636 int bch2_btree_key_cache_flush(struct btree_trans *trans,
637                                enum btree_id id, struct bpos pos)
638 {
639         struct bch_fs *c = trans->c;
640         struct bkey_cached_key key = { id, pos };
641
642         /* Fastpath - assume it won't be found: */
643         if (!bch2_btree_key_cache_find(c, id, pos))
644                 return 0;
645
646         return btree_key_cache_flush_pos(trans, key, 0, 0, true);
647 }
648
649 bool bch2_btree_insert_key_cached(struct btree_trans *trans,
650                                   struct btree_path *path,
651                                   struct bkey_i *insert)
652 {
653         struct bch_fs *c = trans->c;
654         struct bkey_cached *ck = (void *) path->l[0].b;
655         bool kick_reclaim = false;
656
657         BUG_ON(insert->u64s > ck->u64s);
658
659         if (likely(!(trans->flags & BTREE_INSERT_JOURNAL_REPLAY))) {
660                 int difference;
661
662                 BUG_ON(jset_u64s(insert->u64s) > trans->journal_preres.u64s);
663
664                 difference = jset_u64s(insert->u64s) - ck->res.u64s;
665                 if (difference > 0) {
666                         trans->journal_preres.u64s      -= difference;
667                         ck->res.u64s                    += difference;
668                 }
669         }
670
671         bkey_copy(ck->k, insert);
672         ck->valid = true;
673
674         if (!test_bit(BKEY_CACHED_DIRTY, &ck->flags)) {
675                 set_bit(BKEY_CACHED_DIRTY, &ck->flags);
676                 atomic_long_inc(&c->btree_key_cache.nr_dirty);
677
678                 if (bch2_nr_btree_keys_need_flush(c))
679                         kick_reclaim = true;
680         }
681
682         bch2_journal_pin_update(&c->journal, trans->journal_res.seq,
683                                 &ck->journal, bch2_btree_key_cache_journal_flush);
684
685         if (kick_reclaim)
686                 journal_reclaim_kick(&c->journal);
687         return true;
688 }
689
690 void bch2_btree_key_cache_drop(struct btree_trans *trans,
691                                struct btree_path *path)
692 {
693         struct bch_fs *c = trans->c;
694         struct bkey_cached *ck = (void *) path->l[0].b;
695
696         BUG_ON(!ck->valid);
697
698         /*
699          * We just did an update to the btree, bypassing the key cache: the key
700          * cache key is now stale and must be dropped, even if dirty:
701          */
702         if (test_bit(BKEY_CACHED_DIRTY, &ck->flags)) {
703                 clear_bit(BKEY_CACHED_DIRTY, &ck->flags);
704                 atomic_long_dec(&c->btree_key_cache.nr_dirty);
705                 bch2_journal_pin_drop(&c->journal, &ck->journal);
706         }
707
708         ck->valid = false;
709 }
710
711 static unsigned long bch2_btree_key_cache_scan(struct shrinker *shrink,
712                                            struct shrink_control *sc)
713 {
714         struct bch_fs *c = container_of(shrink, struct bch_fs,
715                                         btree_key_cache.shrink);
716         struct btree_key_cache *bc = &c->btree_key_cache;
717         struct bucket_table *tbl;
718         struct bkey_cached *ck, *t;
719         size_t scanned = 0, freed = 0, nr = sc->nr_to_scan;
720         unsigned start, flags;
721         int srcu_idx;
722
723         /* Return -1 if we can't do anything right now */
724         if (sc->gfp_mask & __GFP_FS)
725                 mutex_lock(&bc->lock);
726         else if (!mutex_trylock(&bc->lock))
727                 return -1;
728
729         srcu_idx = srcu_read_lock(&c->btree_trans_barrier);
730         flags = memalloc_nofs_save();
731
732         /*
733          * Newest freed entries are at the end of the list - once we hit one
734          * that's too new to be freed, we can bail out:
735          */
736         list_for_each_entry_safe(ck, t, &bc->freed_nonpcpu, list) {
737                 if (!poll_state_synchronize_srcu(&c->btree_trans_barrier,
738                                                  ck->btree_trans_barrier_seq))
739                         break;
740
741                 list_del(&ck->list);
742                 six_lock_pcpu_free(&ck->c.lock);
743                 kmem_cache_free(bch2_key_cache, ck);
744                 atomic_long_dec(&bc->nr_freed);
745                 scanned++;
746                 freed++;
747         }
748
749         if (scanned >= nr)
750                 goto out;
751
752         list_for_each_entry_safe(ck, t, &bc->freed_pcpu, list) {
753                 if (!poll_state_synchronize_srcu(&c->btree_trans_barrier,
754                                                  ck->btree_trans_barrier_seq))
755                         break;
756
757                 list_del(&ck->list);
758                 six_lock_pcpu_free(&ck->c.lock);
759                 kmem_cache_free(bch2_key_cache, ck);
760                 atomic_long_dec(&bc->nr_freed);
761                 scanned++;
762                 freed++;
763         }
764
765         if (scanned >= nr)
766                 goto out;
767
768         rcu_read_lock();
769         tbl = rht_dereference_rcu(bc->table.tbl, &bc->table);
770         if (bc->shrink_iter >= tbl->size)
771                 bc->shrink_iter = 0;
772         start = bc->shrink_iter;
773
774         do {
775                 struct rhash_head *pos, *next;
776
777                 pos = rht_ptr_rcu(rht_bucket(tbl, bc->shrink_iter));
778
779                 while (!rht_is_a_nulls(pos)) {
780                         next = rht_dereference_bucket_rcu(pos->next, tbl, bc->shrink_iter);
781                         ck = container_of(pos, struct bkey_cached, hash);
782
783                         if (test_bit(BKEY_CACHED_DIRTY, &ck->flags))
784                                 goto next;
785
786                         if (test_bit(BKEY_CACHED_ACCESSED, &ck->flags))
787                                 clear_bit(BKEY_CACHED_ACCESSED, &ck->flags);
788                         else if (bkey_cached_lock_for_evict(ck)) {
789                                 bkey_cached_evict(bc, ck);
790                                 bkey_cached_free(bc, ck);
791                         }
792
793                         scanned++;
794                         if (scanned >= nr)
795                                 break;
796 next:
797                         pos = next;
798                 }
799
800                 bc->shrink_iter++;
801                 if (bc->shrink_iter >= tbl->size)
802                         bc->shrink_iter = 0;
803         } while (scanned < nr && bc->shrink_iter != start);
804
805         rcu_read_unlock();
806 out:
807         memalloc_nofs_restore(flags);
808         srcu_read_unlock(&c->btree_trans_barrier, srcu_idx);
809         mutex_unlock(&bc->lock);
810
811         return freed;
812 }
813
814 static unsigned long bch2_btree_key_cache_count(struct shrinker *shrink,
815                                             struct shrink_control *sc)
816 {
817         struct bch_fs *c = container_of(shrink, struct bch_fs,
818                                         btree_key_cache.shrink);
819         struct btree_key_cache *bc = &c->btree_key_cache;
820         long nr = atomic_long_read(&bc->nr_keys) -
821                 atomic_long_read(&bc->nr_dirty);
822
823         return max(0L, nr);
824 }
825
826 void bch2_fs_btree_key_cache_exit(struct btree_key_cache *bc)
827 {
828         struct bch_fs *c = container_of(bc, struct bch_fs, btree_key_cache);
829         struct bucket_table *tbl;
830         struct bkey_cached *ck, *n;
831         struct rhash_head *pos;
832         unsigned i;
833         int cpu;
834
835         if (bc->shrink.list.next)
836                 unregister_shrinker(&bc->shrink);
837
838         mutex_lock(&bc->lock);
839
840         rcu_read_lock();
841         tbl = rht_dereference_rcu(bc->table.tbl, &bc->table);
842         if (tbl)
843                 for (i = 0; i < tbl->size; i++)
844                         rht_for_each_entry_rcu(ck, pos, tbl, i, hash) {
845                                 bkey_cached_evict(bc, ck);
846                                 list_add(&ck->list, &bc->freed_nonpcpu);
847                         }
848         rcu_read_unlock();
849
850         for_each_possible_cpu(cpu) {
851                 struct btree_key_cache_freelist *f =
852                         per_cpu_ptr(bc->pcpu_freed, cpu);
853
854                 for (i = 0; i < f->nr; i++) {
855                         ck = f->objs[i];
856                         list_add(&ck->list, &bc->freed_nonpcpu);
857                 }
858         }
859
860         list_splice(&bc->freed_pcpu, &bc->freed_nonpcpu);
861
862         list_for_each_entry_safe(ck, n, &bc->freed_nonpcpu, list) {
863                 cond_resched();
864
865                 bch2_journal_pin_drop(&c->journal, &ck->journal);
866                 bch2_journal_preres_put(&c->journal, &ck->res);
867
868                 list_del(&ck->list);
869                 kfree(ck->k);
870                 six_lock_pcpu_free(&ck->c.lock);
871                 kmem_cache_free(bch2_key_cache, ck);
872         }
873
874         BUG_ON(atomic_long_read(&bc->nr_dirty) &&
875                !bch2_journal_error(&c->journal) &&
876                test_bit(BCH_FS_WAS_RW, &c->flags));
877         BUG_ON(atomic_long_read(&bc->nr_keys));
878
879         mutex_unlock(&bc->lock);
880
881         if (bc->table_init_done)
882                 rhashtable_destroy(&bc->table);
883
884         free_percpu(bc->pcpu_freed);
885 }
886
887 void bch2_fs_btree_key_cache_init_early(struct btree_key_cache *c)
888 {
889         mutex_init(&c->lock);
890         INIT_LIST_HEAD(&c->freed_pcpu);
891         INIT_LIST_HEAD(&c->freed_nonpcpu);
892 }
893
894 static void bch2_btree_key_cache_shrinker_to_text(struct printbuf *out, struct shrinker *shrink)
895 {
896         struct btree_key_cache *bc =
897                 container_of(shrink, struct btree_key_cache, shrink);
898
899         bch2_btree_key_cache_to_text(out, bc);
900 }
901
902 int bch2_fs_btree_key_cache_init(struct btree_key_cache *c)
903 {
904         int ret;
905
906         c->pcpu_freed = alloc_percpu(struct btree_key_cache_freelist);
907         if (!c->pcpu_freed)
908                 return -ENOMEM;
909
910         ret = rhashtable_init(&c->table, &bch2_btree_key_cache_params);
911         if (ret)
912                 return ret;
913
914         c->table_init_done = true;
915
916         c->shrink.seeks                 = 1;
917         c->shrink.count_objects         = bch2_btree_key_cache_count;
918         c->shrink.scan_objects          = bch2_btree_key_cache_scan;
919         c->shrink.to_text               = bch2_btree_key_cache_shrinker_to_text;
920         return register_shrinker(&c->shrink);
921 }
922
923 void bch2_btree_key_cache_to_text(struct printbuf *out, struct btree_key_cache *c)
924 {
925         prt_printf(out, "nr_freed:\t%zu\n",     atomic_long_read(&c->nr_freed));
926         prt_printf(out, "nr_keys:\t%lu\n",      atomic_long_read(&c->nr_keys));
927         prt_printf(out, "nr_dirty:\t%lu\n",     atomic_long_read(&c->nr_dirty));
928 }
929
930 void bch2_btree_key_cache_exit(void)
931 {
932         if (bch2_key_cache)
933                 kmem_cache_destroy(bch2_key_cache);
934 }
935
936 int __init bch2_btree_key_cache_init(void)
937 {
938         bch2_key_cache = KMEM_CACHE(bkey_cached, 0);
939         if (!bch2_key_cache)
940                 return -ENOMEM;
941
942         return 0;
943 }