nfscache.c 16 KB

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