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(hashsize * sizeof(*drc_hashtbl));
  152. if (!drc_hashtbl)
  153. goto out_nomem;
  154. }
  155. for (i = 0; i < hashsize; i++) {
  156. INIT_LIST_HEAD(&drc_hashtbl[i].lru_head);
  157. spin_lock_init(&drc_hashtbl[i].cache_lock);
  158. }
  159. drc_hashsize = hashsize;
  160. return 0;
  161. out_nomem:
  162. printk(KERN_ERR "nfsd: failed to allocate reply cache\n");
  163. nfsd_reply_cache_shutdown();
  164. return -ENOMEM;
  165. }
  166. void nfsd_reply_cache_shutdown(void)
  167. {
  168. struct svc_cacherep *rp;
  169. unsigned int i;
  170. unregister_shrinker(&nfsd_reply_cache_shrinker);
  171. for (i = 0; i < drc_hashsize; i++) {
  172. struct list_head *head = &drc_hashtbl[i].lru_head;
  173. while (!list_empty(head)) {
  174. rp = list_first_entry(head, struct svc_cacherep, c_lru);
  175. nfsd_reply_cache_free_locked(rp);
  176. }
  177. }
  178. kvfree(drc_hashtbl);
  179. drc_hashtbl = NULL;
  180. drc_hashsize = 0;
  181. kmem_cache_destroy(drc_slab);
  182. drc_slab = NULL;
  183. }
  184. /*
  185. * Move cache entry to end of LRU list, and queue the cleaner to run if it's
  186. * not already scheduled.
  187. */
  188. static void
  189. lru_put_end(struct nfsd_drc_bucket *b, struct svc_cacherep *rp)
  190. {
  191. rp->c_timestamp = jiffies;
  192. list_move_tail(&rp->c_lru, &b->lru_head);
  193. }
  194. static long
  195. prune_bucket(struct nfsd_drc_bucket *b)
  196. {
  197. struct svc_cacherep *rp, *tmp;
  198. long freed = 0;
  199. list_for_each_entry_safe(rp, tmp, &b->lru_head, c_lru) {
  200. /*
  201. * Don't free entries attached to calls that are still
  202. * in-progress, but do keep scanning the list.
  203. */
  204. if (rp->c_state == RC_INPROG)
  205. continue;
  206. if (atomic_read(&num_drc_entries) <= max_drc_entries &&
  207. time_before(jiffies, rp->c_timestamp + RC_EXPIRE))
  208. break;
  209. nfsd_reply_cache_free_locked(rp);
  210. freed++;
  211. }
  212. return freed;
  213. }
  214. /*
  215. * Walk the LRU list and prune off entries that are older than RC_EXPIRE.
  216. * Also prune the oldest ones when the total exceeds the max number of entries.
  217. */
  218. static long
  219. prune_cache_entries(void)
  220. {
  221. unsigned int i;
  222. long freed = 0;
  223. for (i = 0; i < drc_hashsize; i++) {
  224. struct nfsd_drc_bucket *b = &drc_hashtbl[i];
  225. if (list_empty(&b->lru_head))
  226. continue;
  227. spin_lock(&b->cache_lock);
  228. freed += prune_bucket(b);
  229. spin_unlock(&b->cache_lock);
  230. }
  231. return freed;
  232. }
  233. static unsigned long
  234. nfsd_reply_cache_count(struct shrinker *shrink, struct shrink_control *sc)
  235. {
  236. return atomic_read(&num_drc_entries);
  237. }
  238. static unsigned long
  239. nfsd_reply_cache_scan(struct shrinker *shrink, struct shrink_control *sc)
  240. {
  241. return prune_cache_entries();
  242. }
  243. /*
  244. * Walk an xdr_buf and get a CRC for at most the first RC_CSUMLEN bytes
  245. */
  246. static __wsum
  247. nfsd_cache_csum(struct svc_rqst *rqstp)
  248. {
  249. int idx;
  250. unsigned int base;
  251. __wsum csum;
  252. struct xdr_buf *buf = &rqstp->rq_arg;
  253. const unsigned char *p = buf->head[0].iov_base;
  254. size_t csum_len = min_t(size_t, buf->head[0].iov_len + buf->page_len,
  255. RC_CSUMLEN);
  256. size_t len = min(buf->head[0].iov_len, csum_len);
  257. /* rq_arg.head first */
  258. csum = csum_partial(p, len, 0);
  259. csum_len -= len;
  260. /* Continue into page array */
  261. idx = buf->page_base / PAGE_SIZE;
  262. base = buf->page_base & ~PAGE_MASK;
  263. while (csum_len) {
  264. p = page_address(buf->pages[idx]) + base;
  265. len = min_t(size_t, PAGE_SIZE - base, csum_len);
  266. csum = csum_partial(p, len, csum);
  267. csum_len -= len;
  268. base = 0;
  269. ++idx;
  270. }
  271. return csum;
  272. }
  273. static bool
  274. nfsd_cache_match(struct svc_rqst *rqstp, __wsum csum, struct svc_cacherep *rp)
  275. {
  276. /* Check RPC XID first */
  277. if (rqstp->rq_xid != rp->c_xid)
  278. return false;
  279. /* compare checksum of NFS data */
  280. if (csum != rp->c_csum) {
  281. ++payload_misses;
  282. return false;
  283. }
  284. /* Other discriminators */
  285. if (rqstp->rq_proc != rp->c_proc ||
  286. rqstp->rq_prot != rp->c_prot ||
  287. rqstp->rq_vers != rp->c_vers ||
  288. rqstp->rq_arg.len != rp->c_len ||
  289. !rpc_cmp_addr(svc_addr(rqstp), (struct sockaddr *)&rp->c_addr) ||
  290. rpc_get_port(svc_addr(rqstp)) != rpc_get_port((struct sockaddr *)&rp->c_addr))
  291. return false;
  292. return true;
  293. }
  294. /*
  295. * Search the request hash for an entry that matches the given rqstp.
  296. * Must be called with cache_lock held. Returns the found entry or
  297. * NULL on failure.
  298. */
  299. static struct svc_cacherep *
  300. nfsd_cache_search(struct nfsd_drc_bucket *b, struct svc_rqst *rqstp,
  301. __wsum csum)
  302. {
  303. struct svc_cacherep *rp, *ret = NULL;
  304. struct list_head *rh = &b->lru_head;
  305. unsigned int entries = 0;
  306. list_for_each_entry(rp, rh, c_lru) {
  307. ++entries;
  308. if (nfsd_cache_match(rqstp, csum, rp)) {
  309. ret = rp;
  310. break;
  311. }
  312. }
  313. /* tally hash chain length stats */
  314. if (entries > longest_chain) {
  315. longest_chain = entries;
  316. longest_chain_cachesize = atomic_read(&num_drc_entries);
  317. } else if (entries == longest_chain) {
  318. /* prefer to keep the smallest cachesize possible here */
  319. longest_chain_cachesize = min_t(unsigned int,
  320. longest_chain_cachesize,
  321. atomic_read(&num_drc_entries));
  322. }
  323. return ret;
  324. }
  325. /*
  326. * Try to find an entry matching the current call in the cache. When none
  327. * is found, we try to grab the oldest expired entry off the LRU list. If
  328. * a suitable one isn't there, then drop the cache_lock and allocate a
  329. * new one, then search again in case one got inserted while this thread
  330. * didn't hold the lock.
  331. */
  332. int
  333. nfsd_cache_lookup(struct svc_rqst *rqstp)
  334. {
  335. struct svc_cacherep *rp, *found;
  336. __be32 xid = rqstp->rq_xid;
  337. u32 proto = rqstp->rq_prot,
  338. vers = rqstp->rq_vers,
  339. proc = rqstp->rq_proc;
  340. __wsum csum;
  341. u32 hash = nfsd_cache_hash(xid);
  342. struct nfsd_drc_bucket *b = &drc_hashtbl[hash];
  343. unsigned long age;
  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. age = jiffies - rp->c_timestamp;
  401. lru_put_end(b, rp);
  402. rtn = RC_DROPIT;
  403. /* Request being processed or excessive rexmits */
  404. if (rp->c_state == RC_INPROG || age < RC_DELAY)
  405. goto out;
  406. /* From the hall of fame of impractical attacks:
  407. * Is this a user who tries to snoop on the cache? */
  408. rtn = RC_DOIT;
  409. if (!test_bit(RQ_SECURE, &rqstp->rq_flags) && rp->c_secure)
  410. goto out;
  411. /* Compose RPC reply header */
  412. switch (rp->c_type) {
  413. case RC_NOCACHE:
  414. break;
  415. case RC_REPLSTAT:
  416. svc_putu32(&rqstp->rq_res.head[0], rp->c_replstat);
  417. rtn = RC_REPLY;
  418. break;
  419. case RC_REPLBUFF:
  420. if (!nfsd_cache_append(rqstp, &rp->c_replvec))
  421. goto out; /* should not happen */
  422. rtn = RC_REPLY;
  423. break;
  424. default:
  425. printk(KERN_WARNING "nfsd: bad repcache type %d\n", rp->c_type);
  426. nfsd_reply_cache_free_locked(rp);
  427. }
  428. goto out;
  429. }
  430. /*
  431. * Update a cache entry. This is called from nfsd_dispatch when
  432. * the procedure has been executed and the complete reply is in
  433. * rqstp->rq_res.
  434. *
  435. * We're copying around data here rather than swapping buffers because
  436. * the toplevel loop requires max-sized buffers, which would be a waste
  437. * of memory for a cache with a max reply size of 100 bytes (diropokres).
  438. *
  439. * If we should start to use different types of cache entries tailored
  440. * specifically for attrstat and fh's, we may save even more space.
  441. *
  442. * Also note that a cachetype of RC_NOCACHE can legally be passed when
  443. * nfsd failed to encode a reply that otherwise would have been cached.
  444. * In this case, nfsd_cache_update is called with statp == NULL.
  445. */
  446. void
  447. nfsd_cache_update(struct svc_rqst *rqstp, int cachetype, __be32 *statp)
  448. {
  449. struct svc_cacherep *rp = rqstp->rq_cacherep;
  450. struct kvec *resv = &rqstp->rq_res.head[0], *cachv;
  451. u32 hash;
  452. struct nfsd_drc_bucket *b;
  453. int len;
  454. size_t bufsize = 0;
  455. if (!rp)
  456. return;
  457. hash = nfsd_cache_hash(rp->c_xid);
  458. b = &drc_hashtbl[hash];
  459. len = resv->iov_len - ((char*)statp - (char*)resv->iov_base);
  460. len >>= 2;
  461. /* Don't cache excessive amounts of data and XDR failures */
  462. if (!statp || len > (256 >> 2)) {
  463. nfsd_reply_cache_free(b, rp);
  464. return;
  465. }
  466. switch (cachetype) {
  467. case RC_REPLSTAT:
  468. if (len != 1)
  469. printk("nfsd: RC_REPLSTAT/reply len %d!\n",len);
  470. rp->c_replstat = *statp;
  471. break;
  472. case RC_REPLBUFF:
  473. cachv = &rp->c_replvec;
  474. bufsize = len << 2;
  475. cachv->iov_base = kmalloc(bufsize, GFP_KERNEL);
  476. if (!cachv->iov_base) {
  477. nfsd_reply_cache_free(b, rp);
  478. return;
  479. }
  480. cachv->iov_len = bufsize;
  481. memcpy(cachv->iov_base, statp, bufsize);
  482. break;
  483. case RC_NOCACHE:
  484. nfsd_reply_cache_free(b, rp);
  485. return;
  486. }
  487. spin_lock(&b->cache_lock);
  488. drc_mem_usage += bufsize;
  489. lru_put_end(b, rp);
  490. rp->c_secure = test_bit(RQ_SECURE, &rqstp->rq_flags);
  491. rp->c_type = cachetype;
  492. rp->c_state = RC_DONE;
  493. spin_unlock(&b->cache_lock);
  494. return;
  495. }
  496. /*
  497. * Copy cached reply to current reply buffer. Should always fit.
  498. * FIXME as reply is in a page, we should just attach the page, and
  499. * keep a refcount....
  500. */
  501. static int
  502. nfsd_cache_append(struct svc_rqst *rqstp, struct kvec *data)
  503. {
  504. struct kvec *vec = &rqstp->rq_res.head[0];
  505. if (vec->iov_len + data->iov_len > PAGE_SIZE) {
  506. printk(KERN_WARNING "nfsd: cached reply too large (%zd).\n",
  507. data->iov_len);
  508. return 0;
  509. }
  510. memcpy((char*)vec->iov_base + vec->iov_len, data->iov_base, data->iov_len);
  511. vec->iov_len += data->iov_len;
  512. return 1;
  513. }
  514. /*
  515. * Note that fields may be added, removed or reordered in the future. Programs
  516. * scraping this file for info should test the labels to ensure they're
  517. * getting the correct field.
  518. */
  519. static int nfsd_reply_cache_stats_show(struct seq_file *m, void *v)
  520. {
  521. seq_printf(m, "max entries: %u\n", max_drc_entries);
  522. seq_printf(m, "num entries: %u\n",
  523. atomic_read(&num_drc_entries));
  524. seq_printf(m, "hash buckets: %u\n", 1 << maskbits);
  525. seq_printf(m, "mem usage: %u\n", drc_mem_usage);
  526. seq_printf(m, "cache hits: %u\n", nfsdstats.rchits);
  527. seq_printf(m, "cache misses: %u\n", nfsdstats.rcmisses);
  528. seq_printf(m, "not cached: %u\n", nfsdstats.rcnocache);
  529. seq_printf(m, "payload misses: %u\n", payload_misses);
  530. seq_printf(m, "longest chain len: %u\n", longest_chain);
  531. seq_printf(m, "cachesize at longest: %u\n", longest_chain_cachesize);
  532. return 0;
  533. }
  534. int nfsd_reply_cache_stats_open(struct inode *inode, struct file *file)
  535. {
  536. return single_open(file, nfsd_reply_cache_stats_show, NULL);
  537. }