xfs_mru_cache.c 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608
  1. /*
  2. * Copyright (c) 2006-2007 Silicon Graphics, Inc.
  3. * All Rights Reserved.
  4. *
  5. * This program is free software; you can redistribute it and/or
  6. * modify it under the terms of the GNU General Public License as
  7. * published by the Free Software Foundation.
  8. *
  9. * This program is distributed in the hope that it would be useful,
  10. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. * GNU General Public License for more details.
  13. *
  14. * You should have received a copy of the GNU General Public License
  15. * along with this program; if not, write the Free Software Foundation,
  16. * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  17. */
  18. #include "xfs.h"
  19. #include "xfs_mru_cache.h"
  20. /*
  21. * The MRU Cache data structure consists of a data store, an array of lists and
  22. * a lock to protect its internal state. At initialisation time, the client
  23. * supplies an element lifetime in milliseconds and a group count, as well as a
  24. * function pointer to call when deleting elements. A data structure for
  25. * queueing up work in the form of timed callbacks is also included.
  26. *
  27. * The group count controls how many lists are created, and thereby how finely
  28. * the elements are grouped in time. When reaping occurs, all the elements in
  29. * all the lists whose time has expired are deleted.
  30. *
  31. * To give an example of how this works in practice, consider a client that
  32. * initialises an MRU Cache with a lifetime of ten seconds and a group count of
  33. * five. Five internal lists will be created, each representing a two second
  34. * period in time. When the first element is added, time zero for the data
  35. * structure is initialised to the current time.
  36. *
  37. * All the elements added in the first two seconds are appended to the first
  38. * list. Elements added in the third second go into the second list, and so on.
  39. * If an element is accessed at any point, it is removed from its list and
  40. * inserted at the head of the current most-recently-used list.
  41. *
  42. * The reaper function will have nothing to do until at least twelve seconds
  43. * have elapsed since the first element was added. The reason for this is that
  44. * if it were called at t=11s, there could be elements in the first list that
  45. * have only been inactive for nine seconds, so it still does nothing. If it is
  46. * called anywhere between t=12 and t=14 seconds, it will delete all the
  47. * elements that remain in the first list. It's therefore possible for elements
  48. * to remain in the data store even after they've been inactive for up to
  49. * (t + t/g) seconds, where t is the inactive element lifetime and g is the
  50. * number of groups.
  51. *
  52. * The above example assumes that the reaper function gets called at least once
  53. * every (t/g) seconds. If it is called less frequently, unused elements will
  54. * accumulate in the reap list until the reaper function is eventually called.
  55. * The current implementation uses work queue callbacks to carefully time the
  56. * reaper function calls, so this should happen rarely, if at all.
  57. *
  58. * From a design perspective, the primary reason for the choice of a list array
  59. * representing discrete time intervals is that it's only practical to reap
  60. * expired elements in groups of some appreciable size. This automatically
  61. * introduces a granularity to element lifetimes, so there's no point storing an
  62. * individual timeout with each element that specifies a more precise reap time.
  63. * The bonus is a saving of sizeof(long) bytes of memory per element stored.
  64. *
  65. * The elements could have been stored in just one list, but an array of
  66. * counters or pointers would need to be maintained to allow them to be divided
  67. * up into discrete time groups. More critically, the process of touching or
  68. * removing an element would involve walking large portions of the entire list,
  69. * which would have a detrimental effect on performance. The additional memory
  70. * requirement for the array of list heads is minimal.
  71. *
  72. * When an element is touched or deleted, it needs to be removed from its
  73. * current list. Doubly linked lists are used to make the list maintenance
  74. * portion of these operations O(1). Since reaper timing can be imprecise,
  75. * inserts and lookups can occur when there are no free lists available. When
  76. * this happens, all the elements on the LRU list need to be migrated to the end
  77. * of the reap list. To keep the list maintenance portion of these operations
  78. * O(1) also, list tails need to be accessible without walking the entire list.
  79. * This is the reason why doubly linked list heads are used.
  80. */
  81. /*
  82. * An MRU Cache is a dynamic data structure that stores its elements in a way
  83. * that allows efficient lookups, but also groups them into discrete time
  84. * intervals based on insertion time. This allows elements to be efficiently
  85. * and automatically reaped after a fixed period of inactivity.
  86. *
  87. * When a client data pointer is stored in the MRU Cache it needs to be added to
  88. * both the data store and to one of the lists. It must also be possible to
  89. * access each of these entries via the other, i.e. to:
  90. *
  91. * a) Walk a list, removing the corresponding data store entry for each item.
  92. * b) Look up a data store entry, then access its list entry directly.
  93. *
  94. * To achieve both of these goals, each entry must contain both a list entry and
  95. * a key, in addition to the user's data pointer. Note that it's not a good
  96. * idea to have the client embed one of these structures at the top of their own
  97. * data structure, because inserting the same item more than once would most
  98. * likely result in a loop in one of the lists. That's a sure-fire recipe for
  99. * an infinite loop in the code.
  100. */
  101. typedef struct xfs_mru_cache_elem
  102. {
  103. struct list_head list_node;
  104. unsigned long key;
  105. void *value;
  106. } xfs_mru_cache_elem_t;
  107. static kmem_zone_t *xfs_mru_elem_zone;
  108. static struct workqueue_struct *xfs_mru_reap_wq;
  109. /*
  110. * When inserting, destroying or reaping, it's first necessary to update the
  111. * lists relative to a particular time. In the case of destroying, that time
  112. * will be well in the future to ensure that all items are moved to the reap
  113. * list. In all other cases though, the time will be the current time.
  114. *
  115. * This function enters a loop, moving the contents of the LRU list to the reap
  116. * list again and again until either a) the lists are all empty, or b) time zero
  117. * has been advanced sufficiently to be within the immediate element lifetime.
  118. *
  119. * Case a) above is detected by counting how many groups are migrated and
  120. * stopping when they've all been moved. Case b) is detected by monitoring the
  121. * time_zero field, which is updated as each group is migrated.
  122. *
  123. * The return value is the earliest time that more migration could be needed, or
  124. * zero if there's no need to schedule more work because the lists are empty.
  125. */
  126. STATIC unsigned long
  127. _xfs_mru_cache_migrate(
  128. xfs_mru_cache_t *mru,
  129. unsigned long now)
  130. {
  131. unsigned int grp;
  132. unsigned int migrated = 0;
  133. struct list_head *lru_list;
  134. /* Nothing to do if the data store is empty. */
  135. if (!mru->time_zero)
  136. return 0;
  137. /* While time zero is older than the time spanned by all the lists. */
  138. while (mru->time_zero <= now - mru->grp_count * mru->grp_time) {
  139. /*
  140. * If the LRU list isn't empty, migrate its elements to the tail
  141. * of the reap list.
  142. */
  143. lru_list = mru->lists + mru->lru_grp;
  144. if (!list_empty(lru_list))
  145. list_splice_init(lru_list, mru->reap_list.prev);
  146. /*
  147. * Advance the LRU group number, freeing the old LRU list to
  148. * become the new MRU list; advance time zero accordingly.
  149. */
  150. mru->lru_grp = (mru->lru_grp + 1) % mru->grp_count;
  151. mru->time_zero += mru->grp_time;
  152. /*
  153. * If reaping is so far behind that all the elements on all the
  154. * lists have been migrated to the reap list, it's now empty.
  155. */
  156. if (++migrated == mru->grp_count) {
  157. mru->lru_grp = 0;
  158. mru->time_zero = 0;
  159. return 0;
  160. }
  161. }
  162. /* Find the first non-empty list from the LRU end. */
  163. for (grp = 0; grp < mru->grp_count; grp++) {
  164. /* Check the grp'th list from the LRU end. */
  165. lru_list = mru->lists + ((mru->lru_grp + grp) % mru->grp_count);
  166. if (!list_empty(lru_list))
  167. return mru->time_zero +
  168. (mru->grp_count + grp) * mru->grp_time;
  169. }
  170. /* All the lists must be empty. */
  171. mru->lru_grp = 0;
  172. mru->time_zero = 0;
  173. return 0;
  174. }
  175. /*
  176. * When inserting or doing a lookup, an element needs to be inserted into the
  177. * MRU list. The lists must be migrated first to ensure that they're
  178. * up-to-date, otherwise the new element could be given a shorter lifetime in
  179. * the cache than it should.
  180. */
  181. STATIC void
  182. _xfs_mru_cache_list_insert(
  183. xfs_mru_cache_t *mru,
  184. xfs_mru_cache_elem_t *elem)
  185. {
  186. unsigned int grp = 0;
  187. unsigned long now = jiffies;
  188. /*
  189. * If the data store is empty, initialise time zero, leave grp set to
  190. * zero and start the work queue timer if necessary. Otherwise, set grp
  191. * to the number of group times that have elapsed since time zero.
  192. */
  193. if (!_xfs_mru_cache_migrate(mru, now)) {
  194. mru->time_zero = now;
  195. if (!mru->next_reap)
  196. mru->next_reap = mru->grp_count * mru->grp_time;
  197. } else {
  198. grp = (now - mru->time_zero) / mru->grp_time;
  199. grp = (mru->lru_grp + grp) % mru->grp_count;
  200. }
  201. /* Insert the element at the tail of the corresponding list. */
  202. list_add_tail(&elem->list_node, mru->lists + grp);
  203. }
  204. /*
  205. * When destroying or reaping, all the elements that were migrated to the reap
  206. * list need to be deleted. For each element this involves removing it from the
  207. * data store, removing it from the reap list, calling the client's free
  208. * function and deleting the element from the element zone.
  209. */
  210. STATIC void
  211. _xfs_mru_cache_clear_reap_list(
  212. xfs_mru_cache_t *mru)
  213. {
  214. xfs_mru_cache_elem_t *elem, *next;
  215. struct list_head tmp;
  216. INIT_LIST_HEAD(&tmp);
  217. list_for_each_entry_safe(elem, next, &mru->reap_list, list_node) {
  218. /* Remove the element from the data store. */
  219. radix_tree_delete(&mru->store, elem->key);
  220. /*
  221. * remove to temp list so it can be freed without
  222. * needing to hold the lock
  223. */
  224. list_move(&elem->list_node, &tmp);
  225. }
  226. mutex_spinunlock(&mru->lock, 0);
  227. list_for_each_entry_safe(elem, next, &tmp, list_node) {
  228. /* Remove the element from the reap list. */
  229. list_del_init(&elem->list_node);
  230. /* Call the client's free function with the key and value pointer. */
  231. mru->free_func(elem->key, elem->value);
  232. /* Free the element structure. */
  233. kmem_zone_free(xfs_mru_elem_zone, elem);
  234. }
  235. mutex_spinlock(&mru->lock);
  236. }
  237. /*
  238. * We fire the reap timer every group expiry interval so
  239. * we always have a reaper ready to run. This makes shutdown
  240. * and flushing of the reaper easy to do. Hence we need to
  241. * keep when the next reap must occur so we can determine
  242. * at each interval whether there is anything we need to do.
  243. */
  244. STATIC void
  245. _xfs_mru_cache_reap(
  246. struct work_struct *work)
  247. {
  248. xfs_mru_cache_t *mru = container_of(work, xfs_mru_cache_t, work.work);
  249. unsigned long now;
  250. ASSERT(mru && mru->lists);
  251. if (!mru || !mru->lists)
  252. return;
  253. mutex_spinlock(&mru->lock);
  254. now = jiffies;
  255. if (mru->reap_all ||
  256. (mru->next_reap && time_after(now, mru->next_reap))) {
  257. if (mru->reap_all)
  258. now += mru->grp_count * mru->grp_time * 2;
  259. mru->next_reap = _xfs_mru_cache_migrate(mru, now);
  260. _xfs_mru_cache_clear_reap_list(mru);
  261. }
  262. /*
  263. * the process that triggered the reap_all is responsible
  264. * for restating the periodic reap if it is required.
  265. */
  266. if (!mru->reap_all)
  267. queue_delayed_work(xfs_mru_reap_wq, &mru->work, mru->grp_time);
  268. mru->reap_all = 0;
  269. mutex_spinunlock(&mru->lock, 0);
  270. }
  271. int
  272. xfs_mru_cache_init(void)
  273. {
  274. xfs_mru_elem_zone = kmem_zone_init(sizeof(xfs_mru_cache_elem_t),
  275. "xfs_mru_cache_elem");
  276. if (!xfs_mru_elem_zone)
  277. return ENOMEM;
  278. xfs_mru_reap_wq = create_singlethread_workqueue("xfs_mru_cache");
  279. if (!xfs_mru_reap_wq) {
  280. kmem_zone_destroy(xfs_mru_elem_zone);
  281. return ENOMEM;
  282. }
  283. return 0;
  284. }
  285. void
  286. xfs_mru_cache_uninit(void)
  287. {
  288. destroy_workqueue(xfs_mru_reap_wq);
  289. kmem_zone_destroy(xfs_mru_elem_zone);
  290. }
  291. /*
  292. * To initialise a struct xfs_mru_cache pointer, call xfs_mru_cache_create()
  293. * with the address of the pointer, a lifetime value in milliseconds, a group
  294. * count and a free function to use when deleting elements. This function
  295. * returns 0 if the initialisation was successful.
  296. */
  297. int
  298. xfs_mru_cache_create(
  299. xfs_mru_cache_t **mrup,
  300. unsigned int lifetime_ms,
  301. unsigned int grp_count,
  302. xfs_mru_cache_free_func_t free_func)
  303. {
  304. xfs_mru_cache_t *mru = NULL;
  305. int err = 0, grp;
  306. unsigned int grp_time;
  307. if (mrup)
  308. *mrup = NULL;
  309. if (!mrup || !grp_count || !lifetime_ms || !free_func)
  310. return EINVAL;
  311. if (!(grp_time = msecs_to_jiffies(lifetime_ms) / grp_count))
  312. return EINVAL;
  313. if (!(mru = kmem_zalloc(sizeof(*mru), KM_SLEEP)))
  314. return ENOMEM;
  315. /* An extra list is needed to avoid reaping up to a grp_time early. */
  316. mru->grp_count = grp_count + 1;
  317. mru->lists = kmem_alloc(mru->grp_count * sizeof(*mru->lists), KM_SLEEP);
  318. if (!mru->lists) {
  319. err = ENOMEM;
  320. goto exit;
  321. }
  322. for (grp = 0; grp < mru->grp_count; grp++)
  323. INIT_LIST_HEAD(mru->lists + grp);
  324. /*
  325. * We use GFP_KERNEL radix tree preload and do inserts under a
  326. * spinlock so GFP_ATOMIC is appropriate for the radix tree itself.
  327. */
  328. INIT_RADIX_TREE(&mru->store, GFP_ATOMIC);
  329. INIT_LIST_HEAD(&mru->reap_list);
  330. spinlock_init(&mru->lock, "xfs_mru_cache");
  331. INIT_DELAYED_WORK(&mru->work, _xfs_mru_cache_reap);
  332. mru->grp_time = grp_time;
  333. mru->free_func = free_func;
  334. /* start up the reaper event */
  335. mru->next_reap = 0;
  336. mru->reap_all = 0;
  337. queue_delayed_work(xfs_mru_reap_wq, &mru->work, mru->grp_time);
  338. *mrup = mru;
  339. exit:
  340. if (err && mru && mru->lists)
  341. kmem_free(mru->lists, mru->grp_count * sizeof(*mru->lists));
  342. if (err && mru)
  343. kmem_free(mru, sizeof(*mru));
  344. return err;
  345. }
  346. /*
  347. * Call xfs_mru_cache_flush() to flush out all cached entries, calling their
  348. * free functions as they're deleted. When this function returns, the caller is
  349. * guaranteed that all the free functions for all the elements have finished
  350. * executing.
  351. *
  352. * While we are flushing, we stop the periodic reaper event from triggering.
  353. * Normally, we want to restart this periodic event, but if we are shutting
  354. * down the cache we do not want it restarted. hence the restart parameter
  355. * where 0 = do not restart reaper and 1 = restart reaper.
  356. */
  357. void
  358. xfs_mru_cache_flush(
  359. xfs_mru_cache_t *mru,
  360. int restart)
  361. {
  362. if (!mru || !mru->lists)
  363. return;
  364. cancel_rearming_delayed_workqueue(xfs_mru_reap_wq, &mru->work);
  365. mutex_spinlock(&mru->lock);
  366. mru->reap_all = 1;
  367. mutex_spinunlock(&mru->lock, 0);
  368. queue_work(xfs_mru_reap_wq, &mru->work.work);
  369. flush_workqueue(xfs_mru_reap_wq);
  370. mutex_spinlock(&mru->lock);
  371. WARN_ON_ONCE(mru->reap_all != 0);
  372. mru->reap_all = 0;
  373. if (restart)
  374. queue_delayed_work(xfs_mru_reap_wq, &mru->work, mru->grp_time);
  375. mutex_spinunlock(&mru->lock, 0);
  376. }
  377. void
  378. xfs_mru_cache_destroy(
  379. xfs_mru_cache_t *mru)
  380. {
  381. if (!mru || !mru->lists)
  382. return;
  383. /* we don't want the reaper to restart here */
  384. xfs_mru_cache_flush(mru, 0);
  385. kmem_free(mru->lists, mru->grp_count * sizeof(*mru->lists));
  386. kmem_free(mru, sizeof(*mru));
  387. }
  388. /*
  389. * To insert an element, call xfs_mru_cache_insert() with the data store, the
  390. * element's key and the client data pointer. This function returns 0 on
  391. * success or ENOMEM if memory for the data element couldn't be allocated.
  392. */
  393. int
  394. xfs_mru_cache_insert(
  395. xfs_mru_cache_t *mru,
  396. unsigned long key,
  397. void *value)
  398. {
  399. xfs_mru_cache_elem_t *elem;
  400. ASSERT(mru && mru->lists);
  401. if (!mru || !mru->lists)
  402. return EINVAL;
  403. elem = kmem_zone_zalloc(xfs_mru_elem_zone, KM_SLEEP);
  404. if (!elem)
  405. return ENOMEM;
  406. if (radix_tree_preload(GFP_KERNEL)) {
  407. kmem_zone_free(xfs_mru_elem_zone, elem);
  408. return ENOMEM;
  409. }
  410. INIT_LIST_HEAD(&elem->list_node);
  411. elem->key = key;
  412. elem->value = value;
  413. mutex_spinlock(&mru->lock);
  414. radix_tree_insert(&mru->store, key, elem);
  415. radix_tree_preload_end();
  416. _xfs_mru_cache_list_insert(mru, elem);
  417. mutex_spinunlock(&mru->lock, 0);
  418. return 0;
  419. }
  420. /*
  421. * To remove an element without calling the free function, call
  422. * xfs_mru_cache_remove() with the data store and the element's key. On success
  423. * the client data pointer for the removed element is returned, otherwise this
  424. * function will return a NULL pointer.
  425. */
  426. void *
  427. xfs_mru_cache_remove(
  428. xfs_mru_cache_t *mru,
  429. unsigned long key)
  430. {
  431. xfs_mru_cache_elem_t *elem;
  432. void *value = NULL;
  433. ASSERT(mru && mru->lists);
  434. if (!mru || !mru->lists)
  435. return NULL;
  436. mutex_spinlock(&mru->lock);
  437. elem = radix_tree_delete(&mru->store, key);
  438. if (elem) {
  439. value = elem->value;
  440. list_del(&elem->list_node);
  441. }
  442. mutex_spinunlock(&mru->lock, 0);
  443. if (elem)
  444. kmem_zone_free(xfs_mru_elem_zone, elem);
  445. return value;
  446. }
  447. /*
  448. * To remove and element and call the free function, call xfs_mru_cache_delete()
  449. * with the data store and the element's key.
  450. */
  451. void
  452. xfs_mru_cache_delete(
  453. xfs_mru_cache_t *mru,
  454. unsigned long key)
  455. {
  456. void *value = xfs_mru_cache_remove(mru, key);
  457. if (value)
  458. mru->free_func(key, value);
  459. }
  460. /*
  461. * To look up an element using its key, call xfs_mru_cache_lookup() with the
  462. * data store and the element's key. If found, the element will be moved to the
  463. * head of the MRU list to indicate that it's been touched.
  464. *
  465. * The internal data structures are protected by a spinlock that is STILL HELD
  466. * when this function returns. Call xfs_mru_cache_done() to release it. Note
  467. * that it is not safe to call any function that might sleep in the interim.
  468. *
  469. * The implementation could have used reference counting to avoid this
  470. * restriction, but since most clients simply want to get, set or test a member
  471. * of the returned data structure, the extra per-element memory isn't warranted.
  472. *
  473. * If the element isn't found, this function returns NULL and the spinlock is
  474. * released. xfs_mru_cache_done() should NOT be called when this occurs.
  475. */
  476. void *
  477. xfs_mru_cache_lookup(
  478. xfs_mru_cache_t *mru,
  479. unsigned long key)
  480. {
  481. xfs_mru_cache_elem_t *elem;
  482. ASSERT(mru && mru->lists);
  483. if (!mru || !mru->lists)
  484. return NULL;
  485. mutex_spinlock(&mru->lock);
  486. elem = radix_tree_lookup(&mru->store, key);
  487. if (elem) {
  488. list_del(&elem->list_node);
  489. _xfs_mru_cache_list_insert(mru, elem);
  490. }
  491. else
  492. mutex_spinunlock(&mru->lock, 0);
  493. return elem ? elem->value : NULL;
  494. }
  495. /*
  496. * To look up an element using its key, but leave its location in the internal
  497. * lists alone, call xfs_mru_cache_peek(). If the element isn't found, this
  498. * function returns NULL.
  499. *
  500. * See the comments above the declaration of the xfs_mru_cache_lookup() function
  501. * for important locking information pertaining to this call.
  502. */
  503. void *
  504. xfs_mru_cache_peek(
  505. xfs_mru_cache_t *mru,
  506. unsigned long key)
  507. {
  508. xfs_mru_cache_elem_t *elem;
  509. ASSERT(mru && mru->lists);
  510. if (!mru || !mru->lists)
  511. return NULL;
  512. mutex_spinlock(&mru->lock);
  513. elem = radix_tree_lookup(&mru->store, key);
  514. if (!elem)
  515. mutex_spinunlock(&mru->lock, 0);
  516. return elem ? elem->value : NULL;
  517. }
  518. /*
  519. * To release the internal data structure spinlock after having performed an
  520. * xfs_mru_cache_lookup() or an xfs_mru_cache_peek(), call xfs_mru_cache_done()
  521. * with the data store pointer.
  522. */
  523. void
  524. xfs_mru_cache_done(
  525. xfs_mru_cache_t *mru)
  526. {
  527. mutex_spinunlock(&mru->lock, 0);
  528. }