nfscache.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  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. hlist_add_head(&rp->c_hash, cache_hash + hash_32(rp->c_xid, maskbits));
  190. }
  191. static inline bool
  192. nfsd_cache_entry_expired(struct svc_cacherep *rp)
  193. {
  194. return rp->c_state != RC_INPROG &&
  195. time_after(jiffies, rp->c_timestamp + RC_EXPIRE);
  196. }
  197. /*
  198. * Walk the LRU list and prune off entries that are older than RC_EXPIRE.
  199. * Also prune the oldest ones when the total exceeds the max number of entries.
  200. */
  201. static long
  202. prune_cache_entries(void)
  203. {
  204. struct svc_cacherep *rp, *tmp;
  205. long freed = 0;
  206. list_for_each_entry_safe(rp, tmp, &lru_head, c_lru) {
  207. if (!nfsd_cache_entry_expired(rp) &&
  208. num_drc_entries <= max_drc_entries)
  209. break;
  210. nfsd_reply_cache_free_locked(rp);
  211. freed++;
  212. }
  213. /*
  214. * Conditionally rearm the job. If we cleaned out the list, then
  215. * cancel any pending run (since there won't be any work to do).
  216. * Otherwise, we rearm the job or modify the existing one to run in
  217. * RC_EXPIRE since we just ran the pruner.
  218. */
  219. if (list_empty(&lru_head))
  220. cancel_delayed_work(&cache_cleaner);
  221. else
  222. mod_delayed_work(system_wq, &cache_cleaner, RC_EXPIRE);
  223. return freed;
  224. }
  225. static void
  226. cache_cleaner_func(struct work_struct *unused)
  227. {
  228. spin_lock(&cache_lock);
  229. prune_cache_entries();
  230. spin_unlock(&cache_lock);
  231. }
  232. static unsigned long
  233. nfsd_reply_cache_count(struct shrinker *shrink, struct shrink_control *sc)
  234. {
  235. unsigned long num;
  236. spin_lock(&cache_lock);
  237. num = num_drc_entries;
  238. spin_unlock(&cache_lock);
  239. return num;
  240. }
  241. static unsigned long
  242. nfsd_reply_cache_scan(struct shrinker *shrink, struct shrink_control *sc)
  243. {
  244. unsigned long freed;
  245. spin_lock(&cache_lock);
  246. freed = prune_cache_entries();
  247. spin_unlock(&cache_lock);
  248. return freed;
  249. }
  250. /*
  251. * Walk an xdr_buf and get a CRC for at most the first RC_CSUMLEN bytes
  252. */
  253. static __wsum
  254. nfsd_cache_csum(struct svc_rqst *rqstp)
  255. {
  256. int idx;
  257. unsigned int base;
  258. __wsum csum;
  259. struct xdr_buf *buf = &rqstp->rq_arg;
  260. const unsigned char *p = buf->head[0].iov_base;
  261. size_t csum_len = min_t(size_t, buf->head[0].iov_len + buf->page_len,
  262. RC_CSUMLEN);
  263. size_t len = min(buf->head[0].iov_len, csum_len);
  264. /* rq_arg.head first */
  265. csum = csum_partial(p, len, 0);
  266. csum_len -= len;
  267. /* Continue into page array */
  268. idx = buf->page_base / PAGE_SIZE;
  269. base = buf->page_base & ~PAGE_MASK;
  270. while (csum_len) {
  271. p = page_address(buf->pages[idx]) + base;
  272. len = min_t(size_t, PAGE_SIZE - base, csum_len);
  273. csum = csum_partial(p, len, csum);
  274. csum_len -= len;
  275. base = 0;
  276. ++idx;
  277. }
  278. return csum;
  279. }
  280. static bool
  281. nfsd_cache_match(struct svc_rqst *rqstp, __wsum csum, struct svc_cacherep *rp)
  282. {
  283. /* Check RPC header info first */
  284. if (rqstp->rq_xid != rp->c_xid || rqstp->rq_proc != rp->c_proc ||
  285. rqstp->rq_prot != rp->c_prot || rqstp->rq_vers != rp->c_vers ||
  286. rqstp->rq_arg.len != rp->c_len ||
  287. !rpc_cmp_addr(svc_addr(rqstp), (struct sockaddr *)&rp->c_addr) ||
  288. rpc_get_port(svc_addr(rqstp)) != rpc_get_port((struct sockaddr *)&rp->c_addr))
  289. return false;
  290. /* compare checksum of NFS data */
  291. if (csum != rp->c_csum) {
  292. ++payload_misses;
  293. return false;
  294. }
  295. return true;
  296. }
  297. /*
  298. * Search the request hash for an entry that matches the given rqstp.
  299. * Must be called with cache_lock held. Returns the found entry or
  300. * NULL on failure.
  301. */
  302. static struct svc_cacherep *
  303. nfsd_cache_search(struct svc_rqst *rqstp, __wsum csum)
  304. {
  305. struct svc_cacherep *rp, *ret = NULL;
  306. struct hlist_head *rh;
  307. unsigned int entries = 0;
  308. rh = &cache_hash[hash_32(rqstp->rq_xid, maskbits)];
  309. hlist_for_each_entry(rp, rh, c_hash) {
  310. ++entries;
  311. if (nfsd_cache_match(rqstp, csum, rp)) {
  312. ret = rp;
  313. break;
  314. }
  315. }
  316. /* tally hash chain length stats */
  317. if (entries > longest_chain) {
  318. longest_chain = entries;
  319. longest_chain_cachesize = num_drc_entries;
  320. } else if (entries == longest_chain) {
  321. /* prefer to keep the smallest cachesize possible here */
  322. longest_chain_cachesize = min(longest_chain_cachesize,
  323. num_drc_entries);
  324. }
  325. return ret;
  326. }
  327. /*
  328. * Try to find an entry matching the current call in the cache. When none
  329. * is found, we try to grab the oldest expired entry off the LRU list. If
  330. * a suitable one isn't there, then drop the cache_lock and allocate a
  331. * new one, then search again in case one got inserted while this thread
  332. * didn't hold the lock.
  333. */
  334. int
  335. nfsd_cache_lookup(struct svc_rqst *rqstp)
  336. {
  337. struct svc_cacherep *rp, *found;
  338. __be32 xid = rqstp->rq_xid;
  339. u32 proto = rqstp->rq_prot,
  340. vers = rqstp->rq_vers,
  341. proc = rqstp->rq_proc;
  342. __wsum csum;
  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. First, try to reuse the first entry on the LRU
  355. * if it works, then go ahead and prune the LRU list.
  356. */
  357. spin_lock(&cache_lock);
  358. if (!list_empty(&lru_head)) {
  359. rp = list_first_entry(&lru_head, struct svc_cacherep, c_lru);
  360. if (nfsd_cache_entry_expired(rp) ||
  361. num_drc_entries >= max_drc_entries) {
  362. lru_put_end(rp);
  363. prune_cache_entries();
  364. goto search_cache;
  365. }
  366. }
  367. /* No expired ones available, allocate a new one. */
  368. spin_unlock(&cache_lock);
  369. rp = nfsd_reply_cache_alloc();
  370. spin_lock(&cache_lock);
  371. if (likely(rp)) {
  372. ++num_drc_entries;
  373. drc_mem_usage += sizeof(*rp);
  374. }
  375. search_cache:
  376. found = nfsd_cache_search(rqstp, csum);
  377. if (found) {
  378. if (likely(rp))
  379. nfsd_reply_cache_free_locked(rp);
  380. rp = found;
  381. goto found_entry;
  382. }
  383. if (!rp) {
  384. dprintk("nfsd: unable to allocate DRC entry!\n");
  385. goto out;
  386. }
  387. /*
  388. * We're keeping the one we just allocated. Are we now over the
  389. * limit? Prune one off the tip of the LRU in trade for the one we
  390. * just allocated if so.
  391. */
  392. if (num_drc_entries >= max_drc_entries)
  393. nfsd_reply_cache_free_locked(list_first_entry(&lru_head,
  394. struct svc_cacherep, c_lru));
  395. nfsdstats.rcmisses++;
  396. rqstp->rq_cacherep = rp;
  397. rp->c_state = RC_INPROG;
  398. rp->c_xid = xid;
  399. rp->c_proc = proc;
  400. rpc_copy_addr((struct sockaddr *)&rp->c_addr, svc_addr(rqstp));
  401. rpc_set_port((struct sockaddr *)&rp->c_addr, rpc_get_port(svc_addr(rqstp)));
  402. rp->c_prot = proto;
  403. rp->c_vers = vers;
  404. rp->c_len = rqstp->rq_arg.len;
  405. rp->c_csum = csum;
  406. hash_refile(rp);
  407. lru_put_end(rp);
  408. /* release any buffer */
  409. if (rp->c_type == RC_REPLBUFF) {
  410. drc_mem_usage -= rp->c_replvec.iov_len;
  411. kfree(rp->c_replvec.iov_base);
  412. rp->c_replvec.iov_base = NULL;
  413. }
  414. rp->c_type = RC_NOCACHE;
  415. out:
  416. spin_unlock(&cache_lock);
  417. return rtn;
  418. found_entry:
  419. nfsdstats.rchits++;
  420. /* We found a matching entry which is either in progress or done. */
  421. age = jiffies - rp->c_timestamp;
  422. lru_put_end(rp);
  423. rtn = RC_DROPIT;
  424. /* Request being processed or excessive rexmits */
  425. if (rp->c_state == RC_INPROG || age < RC_DELAY)
  426. goto out;
  427. /* From the hall of fame of impractical attacks:
  428. * Is this a user who tries to snoop on the cache? */
  429. rtn = RC_DOIT;
  430. if (!rqstp->rq_secure && rp->c_secure)
  431. goto out;
  432. /* Compose RPC reply header */
  433. switch (rp->c_type) {
  434. case RC_NOCACHE:
  435. break;
  436. case RC_REPLSTAT:
  437. svc_putu32(&rqstp->rq_res.head[0], rp->c_replstat);
  438. rtn = RC_REPLY;
  439. break;
  440. case RC_REPLBUFF:
  441. if (!nfsd_cache_append(rqstp, &rp->c_replvec))
  442. goto out; /* should not happen */
  443. rtn = RC_REPLY;
  444. break;
  445. default:
  446. printk(KERN_WARNING "nfsd: bad repcache type %d\n", rp->c_type);
  447. nfsd_reply_cache_free_locked(rp);
  448. }
  449. goto out;
  450. }
  451. /*
  452. * Update a cache entry. This is called from nfsd_dispatch when
  453. * the procedure has been executed and the complete reply is in
  454. * rqstp->rq_res.
  455. *
  456. * We're copying around data here rather than swapping buffers because
  457. * the toplevel loop requires max-sized buffers, which would be a waste
  458. * of memory for a cache with a max reply size of 100 bytes (diropokres).
  459. *
  460. * If we should start to use different types of cache entries tailored
  461. * specifically for attrstat and fh's, we may save even more space.
  462. *
  463. * Also note that a cachetype of RC_NOCACHE can legally be passed when
  464. * nfsd failed to encode a reply that otherwise would have been cached.
  465. * In this case, nfsd_cache_update is called with statp == NULL.
  466. */
  467. void
  468. nfsd_cache_update(struct svc_rqst *rqstp, int cachetype, __be32 *statp)
  469. {
  470. struct svc_cacherep *rp = rqstp->rq_cacherep;
  471. struct kvec *resv = &rqstp->rq_res.head[0], *cachv;
  472. int len;
  473. size_t bufsize = 0;
  474. if (!rp)
  475. return;
  476. len = resv->iov_len - ((char*)statp - (char*)resv->iov_base);
  477. len >>= 2;
  478. /* Don't cache excessive amounts of data and XDR failures */
  479. if (!statp || len > (256 >> 2)) {
  480. nfsd_reply_cache_free(rp);
  481. return;
  482. }
  483. switch (cachetype) {
  484. case RC_REPLSTAT:
  485. if (len != 1)
  486. printk("nfsd: RC_REPLSTAT/reply len %d!\n",len);
  487. rp->c_replstat = *statp;
  488. break;
  489. case RC_REPLBUFF:
  490. cachv = &rp->c_replvec;
  491. bufsize = len << 2;
  492. cachv->iov_base = kmalloc(bufsize, GFP_KERNEL);
  493. if (!cachv->iov_base) {
  494. nfsd_reply_cache_free(rp);
  495. return;
  496. }
  497. cachv->iov_len = bufsize;
  498. memcpy(cachv->iov_base, statp, bufsize);
  499. break;
  500. case RC_NOCACHE:
  501. nfsd_reply_cache_free(rp);
  502. return;
  503. }
  504. spin_lock(&cache_lock);
  505. drc_mem_usage += bufsize;
  506. lru_put_end(rp);
  507. rp->c_secure = rqstp->rq_secure;
  508. rp->c_type = cachetype;
  509. rp->c_state = RC_DONE;
  510. spin_unlock(&cache_lock);
  511. return;
  512. }
  513. /*
  514. * Copy cached reply to current reply buffer. Should always fit.
  515. * FIXME as reply is in a page, we should just attach the page, and
  516. * keep a refcount....
  517. */
  518. static int
  519. nfsd_cache_append(struct svc_rqst *rqstp, struct kvec *data)
  520. {
  521. struct kvec *vec = &rqstp->rq_res.head[0];
  522. if (vec->iov_len + data->iov_len > PAGE_SIZE) {
  523. printk(KERN_WARNING "nfsd: cached reply too large (%Zd).\n",
  524. data->iov_len);
  525. return 0;
  526. }
  527. memcpy((char*)vec->iov_base + vec->iov_len, data->iov_base, data->iov_len);
  528. vec->iov_len += data->iov_len;
  529. return 1;
  530. }
  531. /*
  532. * Note that fields may be added, removed or reordered in the future. Programs
  533. * scraping this file for info should test the labels to ensure they're
  534. * getting the correct field.
  535. */
  536. static int nfsd_reply_cache_stats_show(struct seq_file *m, void *v)
  537. {
  538. spin_lock(&cache_lock);
  539. seq_printf(m, "max entries: %u\n", max_drc_entries);
  540. seq_printf(m, "num entries: %u\n", num_drc_entries);
  541. seq_printf(m, "hash buckets: %u\n", 1 << maskbits);
  542. seq_printf(m, "mem usage: %u\n", drc_mem_usage);
  543. seq_printf(m, "cache hits: %u\n", nfsdstats.rchits);
  544. seq_printf(m, "cache misses: %u\n", nfsdstats.rcmisses);
  545. seq_printf(m, "not cached: %u\n", nfsdstats.rcnocache);
  546. seq_printf(m, "payload misses: %u\n", payload_misses);
  547. seq_printf(m, "longest chain len: %u\n", longest_chain);
  548. seq_printf(m, "cachesize at longest: %u\n", longest_chain_cachesize);
  549. spin_unlock(&cache_lock);
  550. return 0;
  551. }
  552. int nfsd_reply_cache_stats_open(struct inode *inode, struct file *file)
  553. {
  554. return single_open(file, nfsd_reply_cache_stats_show, NULL);
  555. }