1 // SPDX-License-Identifier: GPL-2.0
3 * Request reply cache. This is currently a global cache, but this may
4 * change in the future and be a per-client cache.
6 * This code is heavily inspired by the 44BSD implementation, although
7 * it does things a bit differently.
9 * Copyright (C) 1995, 1996 Olaf Kirch <okir@monad.swb.de>
12 #include <linux/slab.h>
13 #include <linux/vmalloc.h>
14 #include <linux/sunrpc/addr.h>
15 #include <linux/highmem.h>
16 #include <linux/log2.h>
17 #include <linux/hash.h>
18 #include <net/checksum.h>
23 #define NFSDDBG_FACILITY NFSDDBG_REPCACHE
26 * We use this value to determine the number of hash buckets from the max
27 * cache size, the idea being that when the cache is at its maximum number
28 * of entries, then this should be the average number of entries per bucket.
30 #define TARGET_BUCKET_SIZE 64
32 struct nfsd_drc_bucket
{
33 struct rb_root rb_head
;
34 struct list_head lru_head
;
35 spinlock_t cache_lock
;
38 static struct nfsd_drc_bucket
*drc_hashtbl
;
39 static struct kmem_cache
*drc_slab
;
41 /* max number of entries allowed in the cache */
42 static unsigned int max_drc_entries
;
44 /* number of significant bits in the hash value */
45 static unsigned int maskbits
;
46 static unsigned int drc_hashsize
;
49 * Stats and other tracking of on the duplicate reply cache. All of these and
50 * the "rc" fields in nfsdstats are protected by the cache_lock
53 /* total number of entries */
54 static atomic_t num_drc_entries
;
56 /* cache misses due only to checksum comparison failures */
57 static unsigned int payload_misses
;
59 /* amount of memory (in bytes) currently consumed by the DRC */
60 static unsigned int drc_mem_usage
;
62 /* longest hash chain seen */
63 static unsigned int longest_chain
;
65 /* size of cache when we saw the longest hash chain */
66 static unsigned int longest_chain_cachesize
;
68 static int nfsd_cache_append(struct svc_rqst
*rqstp
, struct kvec
*vec
);
69 static unsigned long nfsd_reply_cache_count(struct shrinker
*shrink
,
70 struct shrink_control
*sc
);
71 static unsigned long nfsd_reply_cache_scan(struct shrinker
*shrink
,
72 struct shrink_control
*sc
);
74 static struct shrinker nfsd_reply_cache_shrinker
= {
75 .scan_objects
= nfsd_reply_cache_scan
,
76 .count_objects
= nfsd_reply_cache_count
,
81 * Put a cap on the size of the DRC based on the amount of available
82 * low memory in the machine.
94 * ...with a hard cap of 256k entries. In the worst case, each entry will be
95 * ~1k, so the above numbers should give a rough max of the amount of memory
99 nfsd_cache_size_limit(void)
102 unsigned long low_pages
= totalram_pages() - totalhigh_pages();
104 limit
= (16 * int_sqrt(low_pages
)) << (PAGE_SHIFT
-10);
105 return min_t(unsigned int, limit
, 256*1024);
109 * Compute the number of hash buckets we need. Divide the max cachesize by
110 * the "target" max bucket size, and round up to next power of two.
113 nfsd_hashsize(unsigned int limit
)
115 return roundup_pow_of_two(limit
/ TARGET_BUCKET_SIZE
);
119 nfsd_cache_hash(__be32 xid
)
121 return hash_32(be32_to_cpu(xid
), maskbits
);
124 static struct svc_cacherep
*
125 nfsd_reply_cache_alloc(struct svc_rqst
*rqstp
, __wsum csum
)
127 struct svc_cacherep
*rp
;
129 rp
= kmem_cache_alloc(drc_slab
, GFP_KERNEL
);
131 rp
->c_state
= RC_UNUSED
;
132 rp
->c_type
= RC_NOCACHE
;
133 RB_CLEAR_NODE(&rp
->c_node
);
134 INIT_LIST_HEAD(&rp
->c_lru
);
136 memset(&rp
->c_key
, 0, sizeof(rp
->c_key
));
137 rp
->c_key
.k_xid
= rqstp
->rq_xid
;
138 rp
->c_key
.k_proc
= rqstp
->rq_proc
;
139 rpc_copy_addr((struct sockaddr
*)&rp
->c_key
.k_addr
, svc_addr(rqstp
));
140 rpc_set_port((struct sockaddr
*)&rp
->c_key
.k_addr
, rpc_get_port(svc_addr(rqstp
)));
141 rp
->c_key
.k_prot
= rqstp
->rq_prot
;
142 rp
->c_key
.k_vers
= rqstp
->rq_vers
;
143 rp
->c_key
.k_len
= rqstp
->rq_arg
.len
;
144 rp
->c_key
.k_csum
= csum
;
150 nfsd_reply_cache_free_locked(struct nfsd_drc_bucket
*b
, struct svc_cacherep
*rp
)
152 if (rp
->c_type
== RC_REPLBUFF
&& rp
->c_replvec
.iov_base
) {
153 drc_mem_usage
-= rp
->c_replvec
.iov_len
;
154 kfree(rp
->c_replvec
.iov_base
);
156 if (rp
->c_state
!= RC_UNUSED
) {
157 rb_erase(&rp
->c_node
, &b
->rb_head
);
158 list_del(&rp
->c_lru
);
159 atomic_dec(&num_drc_entries
);
160 drc_mem_usage
-= sizeof(*rp
);
162 kmem_cache_free(drc_slab
, rp
);
166 nfsd_reply_cache_free(struct nfsd_drc_bucket
*b
, struct svc_cacherep
*rp
)
168 spin_lock(&b
->cache_lock
);
169 nfsd_reply_cache_free_locked(b
, rp
);
170 spin_unlock(&b
->cache_lock
);
173 int nfsd_reply_cache_init(void)
175 unsigned int hashsize
;
179 max_drc_entries
= nfsd_cache_size_limit();
180 atomic_set(&num_drc_entries
, 0);
181 hashsize
= nfsd_hashsize(max_drc_entries
);
182 maskbits
= ilog2(hashsize
);
184 status
= register_shrinker(&nfsd_reply_cache_shrinker
);
188 drc_slab
= kmem_cache_create("nfsd_drc", sizeof(struct svc_cacherep
),
193 drc_hashtbl
= kcalloc(hashsize
, sizeof(*drc_hashtbl
), GFP_KERNEL
);
195 drc_hashtbl
= vzalloc(array_size(hashsize
,
196 sizeof(*drc_hashtbl
)));
201 for (i
= 0; i
< hashsize
; i
++) {
202 INIT_LIST_HEAD(&drc_hashtbl
[i
].lru_head
);
203 spin_lock_init(&drc_hashtbl
[i
].cache_lock
);
205 drc_hashsize
= hashsize
;
209 printk(KERN_ERR
"nfsd: failed to allocate reply cache\n");
210 nfsd_reply_cache_shutdown();
214 void nfsd_reply_cache_shutdown(void)
216 struct svc_cacherep
*rp
;
219 unregister_shrinker(&nfsd_reply_cache_shrinker
);
221 for (i
= 0; i
< drc_hashsize
; i
++) {
222 struct list_head
*head
= &drc_hashtbl
[i
].lru_head
;
223 while (!list_empty(head
)) {
224 rp
= list_first_entry(head
, struct svc_cacherep
, c_lru
);
225 nfsd_reply_cache_free_locked(&drc_hashtbl
[i
], rp
);
233 kmem_cache_destroy(drc_slab
);
238 * Move cache entry to end of LRU list, and queue the cleaner to run if it's
239 * not already scheduled.
242 lru_put_end(struct nfsd_drc_bucket
*b
, struct svc_cacherep
*rp
)
244 rp
->c_timestamp
= jiffies
;
245 list_move_tail(&rp
->c_lru
, &b
->lru_head
);
249 prune_bucket(struct nfsd_drc_bucket
*b
)
251 struct svc_cacherep
*rp
, *tmp
;
254 list_for_each_entry_safe(rp
, tmp
, &b
->lru_head
, c_lru
) {
256 * Don't free entries attached to calls that are still
257 * in-progress, but do keep scanning the list.
259 if (rp
->c_state
== RC_INPROG
)
261 if (atomic_read(&num_drc_entries
) <= max_drc_entries
&&
262 time_before(jiffies
, rp
->c_timestamp
+ RC_EXPIRE
))
264 nfsd_reply_cache_free_locked(b
, rp
);
271 * Walk the LRU list and prune off entries that are older than RC_EXPIRE.
272 * Also prune the oldest ones when the total exceeds the max number of entries.
275 prune_cache_entries(void)
280 for (i
= 0; i
< drc_hashsize
; i
++) {
281 struct nfsd_drc_bucket
*b
= &drc_hashtbl
[i
];
283 if (list_empty(&b
->lru_head
))
285 spin_lock(&b
->cache_lock
);
286 freed
+= prune_bucket(b
);
287 spin_unlock(&b
->cache_lock
);
293 nfsd_reply_cache_count(struct shrinker
*shrink
, struct shrink_control
*sc
)
295 return atomic_read(&num_drc_entries
);
299 nfsd_reply_cache_scan(struct shrinker
*shrink
, struct shrink_control
*sc
)
301 return prune_cache_entries();
304 * Walk an xdr_buf and get a CRC for at most the first RC_CSUMLEN bytes
307 nfsd_cache_csum(struct svc_rqst
*rqstp
)
312 struct xdr_buf
*buf
= &rqstp
->rq_arg
;
313 const unsigned char *p
= buf
->head
[0].iov_base
;
314 size_t csum_len
= min_t(size_t, buf
->head
[0].iov_len
+ buf
->page_len
,
316 size_t len
= min(buf
->head
[0].iov_len
, csum_len
);
318 /* rq_arg.head first */
319 csum
= csum_partial(p
, len
, 0);
322 /* Continue into page array */
323 idx
= buf
->page_base
/ PAGE_SIZE
;
324 base
= buf
->page_base
& ~PAGE_MASK
;
326 p
= page_address(buf
->pages
[idx
]) + base
;
327 len
= min_t(size_t, PAGE_SIZE
- base
, csum_len
);
328 csum
= csum_partial(p
, len
, csum
);
337 nfsd_cache_key_cmp(const struct svc_cacherep
*key
, const struct svc_cacherep
*rp
)
339 if (key
->c_key
.k_xid
== rp
->c_key
.k_xid
&&
340 key
->c_key
.k_csum
!= rp
->c_key
.k_csum
)
343 return memcmp(&key
->c_key
, &rp
->c_key
, sizeof(key
->c_key
));
347 * Search the request hash for an entry that matches the given rqstp.
348 * Must be called with cache_lock held. Returns the found entry or
349 * inserts an empty key on failure.
351 static struct svc_cacherep
*
352 nfsd_cache_insert(struct nfsd_drc_bucket
*b
, struct svc_cacherep
*key
)
354 struct svc_cacherep
*rp
, *ret
= key
;
355 struct rb_node
**p
= &b
->rb_head
.rb_node
,
357 unsigned int entries
= 0;
363 rp
= rb_entry(parent
, struct svc_cacherep
, c_node
);
365 cmp
= nfsd_cache_key_cmp(key
, rp
);
367 p
= &parent
->rb_left
;
369 p
= &parent
->rb_right
;
375 rb_link_node(&key
->c_node
, parent
, p
);
376 rb_insert_color(&key
->c_node
, &b
->rb_head
);
378 /* tally hash chain length stats */
379 if (entries
> longest_chain
) {
380 longest_chain
= entries
;
381 longest_chain_cachesize
= atomic_read(&num_drc_entries
);
382 } else if (entries
== longest_chain
) {
383 /* prefer to keep the smallest cachesize possible here */
384 longest_chain_cachesize
= min_t(unsigned int,
385 longest_chain_cachesize
,
386 atomic_read(&num_drc_entries
));
394 * Try to find an entry matching the current call in the cache. When none
395 * is found, we try to grab the oldest expired entry off the LRU list. If
396 * a suitable one isn't there, then drop the cache_lock and allocate a
397 * new one, then search again in case one got inserted while this thread
398 * didn't hold the lock.
401 nfsd_cache_lookup(struct svc_rqst
*rqstp
)
403 struct svc_cacherep
*rp
, *found
;
404 __be32 xid
= rqstp
->rq_xid
;
406 u32 hash
= nfsd_cache_hash(xid
);
407 struct nfsd_drc_bucket
*b
= &drc_hashtbl
[hash
];
408 int type
= rqstp
->rq_cachetype
;
411 rqstp
->rq_cacherep
= NULL
;
412 if (type
== RC_NOCACHE
) {
413 nfsdstats
.rcnocache
++;
417 csum
= nfsd_cache_csum(rqstp
);
420 * Since the common case is a cache miss followed by an insert,
421 * preallocate an entry.
423 rp
= nfsd_reply_cache_alloc(rqstp
, csum
);
425 dprintk("nfsd: unable to allocate DRC entry!\n");
429 spin_lock(&b
->cache_lock
);
430 found
= nfsd_cache_insert(b
, rp
);
432 nfsd_reply_cache_free_locked(NULL
, rp
);
437 nfsdstats
.rcmisses
++;
438 rqstp
->rq_cacherep
= rp
;
439 rp
->c_state
= RC_INPROG
;
441 atomic_inc(&num_drc_entries
);
442 drc_mem_usage
+= sizeof(*rp
);
444 /* go ahead and prune the cache */
447 spin_unlock(&b
->cache_lock
);
451 /* We found a matching entry which is either in progress or done. */
455 /* Request being processed */
456 if (rp
->c_state
== RC_INPROG
)
459 /* From the hall of fame of impractical attacks:
460 * Is this a user who tries to snoop on the cache? */
462 if (!test_bit(RQ_SECURE
, &rqstp
->rq_flags
) && rp
->c_secure
)
465 /* Compose RPC reply header */
466 switch (rp
->c_type
) {
470 svc_putu32(&rqstp
->rq_res
.head
[0], rp
->c_replstat
);
474 if (!nfsd_cache_append(rqstp
, &rp
->c_replvec
))
475 goto out
; /* should not happen */
479 printk(KERN_WARNING
"nfsd: bad repcache type %d\n", rp
->c_type
);
480 nfsd_reply_cache_free_locked(b
, rp
);
487 * Update a cache entry. This is called from nfsd_dispatch when
488 * the procedure has been executed and the complete reply is in
491 * We're copying around data here rather than swapping buffers because
492 * the toplevel loop requires max-sized buffers, which would be a waste
493 * of memory for a cache with a max reply size of 100 bytes (diropokres).
495 * If we should start to use different types of cache entries tailored
496 * specifically for attrstat and fh's, we may save even more space.
498 * Also note that a cachetype of RC_NOCACHE can legally be passed when
499 * nfsd failed to encode a reply that otherwise would have been cached.
500 * In this case, nfsd_cache_update is called with statp == NULL.
503 nfsd_cache_update(struct svc_rqst
*rqstp
, int cachetype
, __be32
*statp
)
505 struct svc_cacherep
*rp
= rqstp
->rq_cacherep
;
506 struct kvec
*resv
= &rqstp
->rq_res
.head
[0], *cachv
;
508 struct nfsd_drc_bucket
*b
;
515 hash
= nfsd_cache_hash(rp
->c_key
.k_xid
);
516 b
= &drc_hashtbl
[hash
];
518 len
= resv
->iov_len
- ((char*)statp
- (char*)resv
->iov_base
);
521 /* Don't cache excessive amounts of data and XDR failures */
522 if (!statp
|| len
> (256 >> 2)) {
523 nfsd_reply_cache_free(b
, rp
);
530 printk("nfsd: RC_REPLSTAT/reply len %d!\n",len
);
531 rp
->c_replstat
= *statp
;
534 cachv
= &rp
->c_replvec
;
536 cachv
->iov_base
= kmalloc(bufsize
, GFP_KERNEL
);
537 if (!cachv
->iov_base
) {
538 nfsd_reply_cache_free(b
, rp
);
541 cachv
->iov_len
= bufsize
;
542 memcpy(cachv
->iov_base
, statp
, bufsize
);
545 nfsd_reply_cache_free(b
, rp
);
548 spin_lock(&b
->cache_lock
);
549 drc_mem_usage
+= bufsize
;
551 rp
->c_secure
= test_bit(RQ_SECURE
, &rqstp
->rq_flags
);
552 rp
->c_type
= cachetype
;
553 rp
->c_state
= RC_DONE
;
554 spin_unlock(&b
->cache_lock
);
559 * Copy cached reply to current reply buffer. Should always fit.
560 * FIXME as reply is in a page, we should just attach the page, and
561 * keep a refcount....
564 nfsd_cache_append(struct svc_rqst
*rqstp
, struct kvec
*data
)
566 struct kvec
*vec
= &rqstp
->rq_res
.head
[0];
568 if (vec
->iov_len
+ data
->iov_len
> PAGE_SIZE
) {
569 printk(KERN_WARNING
"nfsd: cached reply too large (%zd).\n",
573 memcpy((char*)vec
->iov_base
+ vec
->iov_len
, data
->iov_base
, data
->iov_len
);
574 vec
->iov_len
+= data
->iov_len
;
579 * Note that fields may be added, removed or reordered in the future. Programs
580 * scraping this file for info should test the labels to ensure they're
581 * getting the correct field.
583 static int nfsd_reply_cache_stats_show(struct seq_file
*m
, void *v
)
585 seq_printf(m
, "max entries: %u\n", max_drc_entries
);
586 seq_printf(m
, "num entries: %u\n",
587 atomic_read(&num_drc_entries
));
588 seq_printf(m
, "hash buckets: %u\n", 1 << maskbits
);
589 seq_printf(m
, "mem usage: %u\n", drc_mem_usage
);
590 seq_printf(m
, "cache hits: %u\n", nfsdstats
.rchits
);
591 seq_printf(m
, "cache misses: %u\n", nfsdstats
.rcmisses
);
592 seq_printf(m
, "not cached: %u\n", nfsdstats
.rcnocache
);
593 seq_printf(m
, "payload misses: %u\n", payload_misses
);
594 seq_printf(m
, "longest chain len: %u\n", longest_chain
);
595 seq_printf(m
, "cachesize at longest: %u\n", longest_chain_cachesize
);
599 int nfsd_reply_cache_stats_open(struct inode
*inode
, struct file
*file
)
601 return single_open(file
, nfsd_reply_cache_stats_show
, NULL
);