nfscache.c 15 KB

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