nfscache.c 16 KB

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