nfscache.c 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602
  1. // SPDX-License-Identifier: GPL-2.0
  2. /*
  3. * Request reply cache. This is currently a global cache, but this may
  4. * change in the future and be a per-client cache.
  5. *
  6. * This code is heavily inspired by the 44BSD implementation, although
  7. * it does things a bit differently.
  8. *
  9. * Copyright (C) 1995, 1996 Olaf Kirch <okir@monad.swb.de>
  10. */
  11. #include <linux/slab.h>
  12. #include <linux/vmalloc.h>
  13. #include <linux/sunrpc/addr.h>
  14. #include <linux/highmem.h>
  15. #include <linux/log2.h>
  16. #include <linux/hash.h>
  17. #include <net/checksum.h>
  18. #include "nfsd.h"
  19. #include "cache.h"
  20. #define NFSDDBG_FACILITY NFSDDBG_REPCACHE
  21. /*
  22. * We use this value to determine the number of hash buckets from the max
  23. * cache size, the idea being that when the cache is at its maximum number
  24. * of entries, then this should be the average number of entries per bucket.
  25. */
  26. #define TARGET_BUCKET_SIZE 64
  27. struct nfsd_drc_bucket {
  28. struct rb_root rb_head;
  29. struct list_head lru_head;
  30. spinlock_t cache_lock;
  31. };
  32. static struct nfsd_drc_bucket *drc_hashtbl;
  33. static struct kmem_cache *drc_slab;
  34. /* max number of entries allowed in the cache */
  35. static unsigned int max_drc_entries;
  36. /* number of significant bits in the hash value */
  37. static unsigned int maskbits;
  38. static unsigned int drc_hashsize;
  39. /*
  40. * Stats and other tracking of on the duplicate reply cache. All of these and
  41. * the "rc" fields in nfsdstats are protected by the cache_lock
  42. */
  43. /* total number of entries */
  44. static atomic_t num_drc_entries;
  45. /* cache misses due only to checksum comparison failures */
  46. static unsigned int payload_misses;
  47. /* amount of memory (in bytes) currently consumed by the DRC */
  48. static unsigned int drc_mem_usage;
  49. /* longest hash chain seen */
  50. static unsigned int longest_chain;
  51. /* size of cache when we saw the longest hash chain */
  52. static unsigned int longest_chain_cachesize;
  53. static int nfsd_cache_append(struct svc_rqst *rqstp, struct kvec *vec);
  54. static unsigned long nfsd_reply_cache_count(struct shrinker *shrink,
  55. struct shrink_control *sc);
  56. static unsigned long nfsd_reply_cache_scan(struct shrinker *shrink,
  57. struct shrink_control *sc);
  58. static struct shrinker nfsd_reply_cache_shrinker = {
  59. .scan_objects = nfsd_reply_cache_scan,
  60. .count_objects = nfsd_reply_cache_count,
  61. .seeks = 1,
  62. };
  63. /*
  64. * Put a cap on the size of the DRC based on the amount of available
  65. * low memory in the machine.
  66. *
  67. * 64MB: 8192
  68. * 128MB: 11585
  69. * 256MB: 16384
  70. * 512MB: 23170
  71. * 1GB: 32768
  72. * 2GB: 46340
  73. * 4GB: 65536
  74. * 8GB: 92681
  75. * 16GB: 131072
  76. *
  77. * ...with a hard cap of 256k entries. In the worst case, each entry will be
  78. * ~1k, so the above numbers should give a rough max of the amount of memory
  79. * used in k.
  80. */
  81. static unsigned int
  82. nfsd_cache_size_limit(void)
  83. {
  84. unsigned int limit;
  85. unsigned long low_pages = totalram_pages - totalhigh_pages;
  86. limit = (16 * int_sqrt(low_pages)) << (PAGE_SHIFT-10);
  87. return min_t(unsigned int, limit, 256*1024);
  88. }
  89. /*
  90. * Compute the number of hash buckets we need. Divide the max cachesize by
  91. * the "target" max bucket size, and round up to next power of two.
  92. */
  93. static unsigned int
  94. nfsd_hashsize(unsigned int limit)
  95. {
  96. return roundup_pow_of_two(limit / TARGET_BUCKET_SIZE);
  97. }
  98. static u32
  99. nfsd_cache_hash(__be32 xid)
  100. {
  101. return hash_32(be32_to_cpu(xid), maskbits);
  102. }
  103. static struct svc_cacherep *
  104. nfsd_reply_cache_alloc(struct svc_rqst *rqstp, __wsum csum)
  105. {
  106. struct svc_cacherep *rp;
  107. rp = kmem_cache_alloc(drc_slab, GFP_KERNEL);
  108. if (rp) {
  109. rp->c_state = RC_UNUSED;
  110. rp->c_type = RC_NOCACHE;
  111. RB_CLEAR_NODE(&rp->c_node);
  112. INIT_LIST_HEAD(&rp->c_lru);
  113. memset(&rp->c_key, 0, sizeof(rp->c_key));
  114. rp->c_key.k_xid = rqstp->rq_xid;
  115. rp->c_key.k_proc = rqstp->rq_proc;
  116. rpc_copy_addr((struct sockaddr *)&rp->c_key.k_addr, svc_addr(rqstp));
  117. rpc_set_port((struct sockaddr *)&rp->c_key.k_addr, rpc_get_port(svc_addr(rqstp)));
  118. rp->c_key.k_prot = rqstp->rq_prot;
  119. rp->c_key.k_vers = rqstp->rq_vers;
  120. rp->c_key.k_len = rqstp->rq_arg.len;
  121. rp->c_key.k_csum = csum;
  122. }
  123. return rp;
  124. }
  125. static void
  126. nfsd_reply_cache_free_locked(struct nfsd_drc_bucket *b, struct svc_cacherep *rp)
  127. {
  128. if (rp->c_type == RC_REPLBUFF && rp->c_replvec.iov_base) {
  129. drc_mem_usage -= rp->c_replvec.iov_len;
  130. kfree(rp->c_replvec.iov_base);
  131. }
  132. if (rp->c_state != RC_UNUSED) {
  133. rb_erase(&rp->c_node, &b->rb_head);
  134. list_del(&rp->c_lru);
  135. atomic_dec(&num_drc_entries);
  136. drc_mem_usage -= sizeof(*rp);
  137. }
  138. kmem_cache_free(drc_slab, rp);
  139. }
  140. static void
  141. nfsd_reply_cache_free(struct nfsd_drc_bucket *b, struct svc_cacherep *rp)
  142. {
  143. spin_lock(&b->cache_lock);
  144. nfsd_reply_cache_free_locked(b, rp);
  145. spin_unlock(&b->cache_lock);
  146. }
  147. int nfsd_reply_cache_init(void)
  148. {
  149. unsigned int hashsize;
  150. unsigned int i;
  151. int status = 0;
  152. max_drc_entries = nfsd_cache_size_limit();
  153. atomic_set(&num_drc_entries, 0);
  154. hashsize = nfsd_hashsize(max_drc_entries);
  155. maskbits = ilog2(hashsize);
  156. status = register_shrinker(&nfsd_reply_cache_shrinker);
  157. if (status)
  158. return status;
  159. drc_slab = kmem_cache_create("nfsd_drc", sizeof(struct svc_cacherep),
  160. 0, 0, NULL);
  161. if (!drc_slab)
  162. goto out_nomem;
  163. drc_hashtbl = kcalloc(hashsize, sizeof(*drc_hashtbl), GFP_KERNEL);
  164. if (!drc_hashtbl) {
  165. drc_hashtbl = vzalloc(array_size(hashsize,
  166. sizeof(*drc_hashtbl)));
  167. if (!drc_hashtbl)
  168. goto out_nomem;
  169. }
  170. for (i = 0; i < hashsize; i++) {
  171. INIT_LIST_HEAD(&drc_hashtbl[i].lru_head);
  172. spin_lock_init(&drc_hashtbl[i].cache_lock);
  173. }
  174. drc_hashsize = hashsize;
  175. return 0;
  176. out_nomem:
  177. printk(KERN_ERR "nfsd: failed to allocate reply cache\n");
  178. nfsd_reply_cache_shutdown();
  179. return -ENOMEM;
  180. }
  181. void nfsd_reply_cache_shutdown(void)
  182. {
  183. struct svc_cacherep *rp;
  184. unsigned int i;
  185. unregister_shrinker(&nfsd_reply_cache_shrinker);
  186. for (i = 0; i < drc_hashsize; i++) {
  187. struct list_head *head = &drc_hashtbl[i].lru_head;
  188. while (!list_empty(head)) {
  189. rp = list_first_entry(head, struct svc_cacherep, c_lru);
  190. nfsd_reply_cache_free_locked(&drc_hashtbl[i], rp);
  191. }
  192. }
  193. kvfree(drc_hashtbl);
  194. drc_hashtbl = NULL;
  195. drc_hashsize = 0;
  196. kmem_cache_destroy(drc_slab);
  197. drc_slab = NULL;
  198. }
  199. /*
  200. * Move cache entry to end of LRU list, and queue the cleaner to run if it's
  201. * not already scheduled.
  202. */
  203. static void
  204. lru_put_end(struct nfsd_drc_bucket *b, struct svc_cacherep *rp)
  205. {
  206. rp->c_timestamp = jiffies;
  207. list_move_tail(&rp->c_lru, &b->lru_head);
  208. }
  209. static long
  210. prune_bucket(struct nfsd_drc_bucket *b)
  211. {
  212. struct svc_cacherep *rp, *tmp;
  213. long freed = 0;
  214. list_for_each_entry_safe(rp, tmp, &b->lru_head, c_lru) {
  215. /*
  216. * Don't free entries attached to calls that are still
  217. * in-progress, but do keep scanning the list.
  218. */
  219. if (rp->c_state == RC_INPROG)
  220. continue;
  221. if (atomic_read(&num_drc_entries) <= max_drc_entries &&
  222. time_before(jiffies, rp->c_timestamp + RC_EXPIRE))
  223. break;
  224. nfsd_reply_cache_free_locked(b, rp);
  225. freed++;
  226. }
  227. return freed;
  228. }
  229. /*
  230. * Walk the LRU list and prune off entries that are older than RC_EXPIRE.
  231. * Also prune the oldest ones when the total exceeds the max number of entries.
  232. */
  233. static long
  234. prune_cache_entries(void)
  235. {
  236. unsigned int i;
  237. long freed = 0;
  238. for (i = 0; i < drc_hashsize; i++) {
  239. struct nfsd_drc_bucket *b = &drc_hashtbl[i];
  240. if (list_empty(&b->lru_head))
  241. continue;
  242. spin_lock(&b->cache_lock);
  243. freed += prune_bucket(b);
  244. spin_unlock(&b->cache_lock);
  245. }
  246. return freed;
  247. }
  248. static unsigned long
  249. nfsd_reply_cache_count(struct shrinker *shrink, struct shrink_control *sc)
  250. {
  251. return atomic_read(&num_drc_entries);
  252. }
  253. static unsigned long
  254. nfsd_reply_cache_scan(struct shrinker *shrink, struct shrink_control *sc)
  255. {
  256. return prune_cache_entries();
  257. }
  258. /*
  259. * Walk an xdr_buf and get a CRC for at most the first RC_CSUMLEN bytes
  260. */
  261. static __wsum
  262. nfsd_cache_csum(struct svc_rqst *rqstp)
  263. {
  264. int idx;
  265. unsigned int base;
  266. __wsum csum;
  267. struct xdr_buf *buf = &rqstp->rq_arg;
  268. const unsigned char *p = buf->head[0].iov_base;
  269. size_t csum_len = min_t(size_t, buf->head[0].iov_len + buf->page_len,
  270. RC_CSUMLEN);
  271. size_t len = min(buf->head[0].iov_len, csum_len);
  272. /* rq_arg.head first */
  273. csum = csum_partial(p, len, 0);
  274. csum_len -= len;
  275. /* Continue into page array */
  276. idx = buf->page_base / PAGE_SIZE;
  277. base = buf->page_base & ~PAGE_MASK;
  278. while (csum_len) {
  279. p = page_address(buf->pages[idx]) + base;
  280. len = min_t(size_t, PAGE_SIZE - base, csum_len);
  281. csum = csum_partial(p, len, csum);
  282. csum_len -= len;
  283. base = 0;
  284. ++idx;
  285. }
  286. return csum;
  287. }
  288. static int
  289. nfsd_cache_key_cmp(const struct svc_cacherep *key, const struct svc_cacherep *rp)
  290. {
  291. if (key->c_key.k_xid == rp->c_key.k_xid &&
  292. key->c_key.k_csum != rp->c_key.k_csum)
  293. ++payload_misses;
  294. return memcmp(&key->c_key, &rp->c_key, sizeof(key->c_key));
  295. }
  296. /*
  297. * Search the request hash for an entry that matches the given rqstp.
  298. * Must be called with cache_lock held. Returns the found entry or
  299. * inserts an empty key on failure.
  300. */
  301. static struct svc_cacherep *
  302. nfsd_cache_insert(struct nfsd_drc_bucket *b, struct svc_cacherep *key)
  303. {
  304. struct svc_cacherep *rp, *ret = key;
  305. struct rb_node **p = &b->rb_head.rb_node,
  306. *parent = NULL;
  307. unsigned int entries = 0;
  308. int cmp;
  309. while (*p != NULL) {
  310. ++entries;
  311. parent = *p;
  312. rp = rb_entry(parent, struct svc_cacherep, c_node);
  313. cmp = nfsd_cache_key_cmp(key, rp);
  314. if (cmp < 0)
  315. p = &parent->rb_left;
  316. else if (cmp > 0)
  317. p = &parent->rb_right;
  318. else {
  319. ret = rp;
  320. goto out;
  321. }
  322. }
  323. rb_link_node(&key->c_node, parent, p);
  324. rb_insert_color(&key->c_node, &b->rb_head);
  325. out:
  326. /* tally hash chain length stats */
  327. if (entries > longest_chain) {
  328. longest_chain = entries;
  329. longest_chain_cachesize = atomic_read(&num_drc_entries);
  330. } else if (entries == longest_chain) {
  331. /* prefer to keep the smallest cachesize possible here */
  332. longest_chain_cachesize = min_t(unsigned int,
  333. longest_chain_cachesize,
  334. atomic_read(&num_drc_entries));
  335. }
  336. lru_put_end(b, ret);
  337. return ret;
  338. }
  339. /*
  340. * Try to find an entry matching the current call in the cache. When none
  341. * is found, we try to grab the oldest expired entry off the LRU list. If
  342. * a suitable one isn't there, then drop the cache_lock and allocate a
  343. * new one, then search again in case one got inserted while this thread
  344. * didn't hold the lock.
  345. */
  346. int
  347. nfsd_cache_lookup(struct svc_rqst *rqstp)
  348. {
  349. struct svc_cacherep *rp, *found;
  350. __be32 xid = rqstp->rq_xid;
  351. __wsum csum;
  352. u32 hash = nfsd_cache_hash(xid);
  353. struct nfsd_drc_bucket *b = &drc_hashtbl[hash];
  354. int type = rqstp->rq_cachetype;
  355. int rtn = RC_DOIT;
  356. rqstp->rq_cacherep = NULL;
  357. if (type == RC_NOCACHE) {
  358. nfsdstats.rcnocache++;
  359. return rtn;
  360. }
  361. csum = nfsd_cache_csum(rqstp);
  362. /*
  363. * Since the common case is a cache miss followed by an insert,
  364. * preallocate an entry.
  365. */
  366. rp = nfsd_reply_cache_alloc(rqstp, csum);
  367. if (!rp) {
  368. dprintk("nfsd: unable to allocate DRC entry!\n");
  369. return rtn;
  370. }
  371. spin_lock(&b->cache_lock);
  372. found = nfsd_cache_insert(b, rp);
  373. if (found != rp) {
  374. nfsd_reply_cache_free_locked(NULL, rp);
  375. rp = found;
  376. goto found_entry;
  377. }
  378. nfsdstats.rcmisses++;
  379. rqstp->rq_cacherep = rp;
  380. rp->c_state = RC_INPROG;
  381. atomic_inc(&num_drc_entries);
  382. drc_mem_usage += sizeof(*rp);
  383. /* go ahead and prune the cache */
  384. prune_bucket(b);
  385. out:
  386. spin_unlock(&b->cache_lock);
  387. return rtn;
  388. found_entry:
  389. /* We found a matching entry which is either in progress or done. */
  390. nfsdstats.rchits++;
  391. rtn = RC_DROPIT;
  392. /* Request being processed */
  393. if (rp->c_state == RC_INPROG)
  394. goto out;
  395. /* From the hall of fame of impractical attacks:
  396. * Is this a user who tries to snoop on the cache? */
  397. rtn = RC_DOIT;
  398. if (!test_bit(RQ_SECURE, &rqstp->rq_flags) && rp->c_secure)
  399. goto out;
  400. /* Compose RPC reply header */
  401. switch (rp->c_type) {
  402. case RC_NOCACHE:
  403. break;
  404. case RC_REPLSTAT:
  405. svc_putu32(&rqstp->rq_res.head[0], rp->c_replstat);
  406. rtn = RC_REPLY;
  407. break;
  408. case RC_REPLBUFF:
  409. if (!nfsd_cache_append(rqstp, &rp->c_replvec))
  410. goto out; /* should not happen */
  411. rtn = RC_REPLY;
  412. break;
  413. default:
  414. printk(KERN_WARNING "nfsd: bad repcache type %d\n", rp->c_type);
  415. nfsd_reply_cache_free_locked(b, rp);
  416. }
  417. goto out;
  418. }
  419. /*
  420. * Update a cache entry. This is called from nfsd_dispatch when
  421. * the procedure has been executed and the complete reply is in
  422. * rqstp->rq_res.
  423. *
  424. * We're copying around data here rather than swapping buffers because
  425. * the toplevel loop requires max-sized buffers, which would be a waste
  426. * of memory for a cache with a max reply size of 100 bytes (diropokres).
  427. *
  428. * If we should start to use different types of cache entries tailored
  429. * specifically for attrstat and fh's, we may save even more space.
  430. *
  431. * Also note that a cachetype of RC_NOCACHE can legally be passed when
  432. * nfsd failed to encode a reply that otherwise would have been cached.
  433. * In this case, nfsd_cache_update is called with statp == NULL.
  434. */
  435. void
  436. nfsd_cache_update(struct svc_rqst *rqstp, int cachetype, __be32 *statp)
  437. {
  438. struct svc_cacherep *rp = rqstp->rq_cacherep;
  439. struct kvec *resv = &rqstp->rq_res.head[0], *cachv;
  440. u32 hash;
  441. struct nfsd_drc_bucket *b;
  442. int len;
  443. size_t bufsize = 0;
  444. if (!rp)
  445. return;
  446. hash = nfsd_cache_hash(rp->c_key.k_xid);
  447. b = &drc_hashtbl[hash];
  448. len = resv->iov_len - ((char*)statp - (char*)resv->iov_base);
  449. len >>= 2;
  450. /* Don't cache excessive amounts of data and XDR failures */
  451. if (!statp || len > (256 >> 2)) {
  452. nfsd_reply_cache_free(b, rp);
  453. return;
  454. }
  455. switch (cachetype) {
  456. case RC_REPLSTAT:
  457. if (len != 1)
  458. printk("nfsd: RC_REPLSTAT/reply len %d!\n",len);
  459. rp->c_replstat = *statp;
  460. break;
  461. case RC_REPLBUFF:
  462. cachv = &rp->c_replvec;
  463. bufsize = len << 2;
  464. cachv->iov_base = kmalloc(bufsize, GFP_KERNEL);
  465. if (!cachv->iov_base) {
  466. nfsd_reply_cache_free(b, rp);
  467. return;
  468. }
  469. cachv->iov_len = bufsize;
  470. memcpy(cachv->iov_base, statp, bufsize);
  471. break;
  472. case RC_NOCACHE:
  473. nfsd_reply_cache_free(b, rp);
  474. return;
  475. }
  476. spin_lock(&b->cache_lock);
  477. drc_mem_usage += bufsize;
  478. lru_put_end(b, rp);
  479. rp->c_secure = test_bit(RQ_SECURE, &rqstp->rq_flags);
  480. rp->c_type = cachetype;
  481. rp->c_state = RC_DONE;
  482. spin_unlock(&b->cache_lock);
  483. return;
  484. }
  485. /*
  486. * Copy cached reply to current reply buffer. Should always fit.
  487. * FIXME as reply is in a page, we should just attach the page, and
  488. * keep a refcount....
  489. */
  490. static int
  491. nfsd_cache_append(struct svc_rqst *rqstp, struct kvec *data)
  492. {
  493. struct kvec *vec = &rqstp->rq_res.head[0];
  494. if (vec->iov_len + data->iov_len > PAGE_SIZE) {
  495. printk(KERN_WARNING "nfsd: cached reply too large (%zd).\n",
  496. data->iov_len);
  497. return 0;
  498. }
  499. memcpy((char*)vec->iov_base + vec->iov_len, data->iov_base, data->iov_len);
  500. vec->iov_len += data->iov_len;
  501. return 1;
  502. }
  503. /*
  504. * Note that fields may be added, removed or reordered in the future. Programs
  505. * scraping this file for info should test the labels to ensure they're
  506. * getting the correct field.
  507. */
  508. static int nfsd_reply_cache_stats_show(struct seq_file *m, void *v)
  509. {
  510. seq_printf(m, "max entries: %u\n", max_drc_entries);
  511. seq_printf(m, "num entries: %u\n",
  512. atomic_read(&num_drc_entries));
  513. seq_printf(m, "hash buckets: %u\n", 1 << maskbits);
  514. seq_printf(m, "mem usage: %u\n", drc_mem_usage);
  515. seq_printf(m, "cache hits: %u\n", nfsdstats.rchits);
  516. seq_printf(m, "cache misses: %u\n", nfsdstats.rcmisses);
  517. seq_printf(m, "not cached: %u\n", nfsdstats.rcnocache);
  518. seq_printf(m, "payload misses: %u\n", payload_misses);
  519. seq_printf(m, "longest chain len: %u\n", longest_chain);
  520. seq_printf(m, "cachesize at longest: %u\n", longest_chain_cachesize);
  521. return 0;
  522. }
  523. int nfsd_reply_cache_stats_open(struct inode *inode, struct file *file)
  524. {
  525. return single_open(file, nfsd_reply_cache_stats_show, NULL);
  526. }