alloc_cache.h 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #ifndef IOU_ALLOC_CACHE_H
  2. #define IOU_ALLOC_CACHE_H
  3. /*
  4. * Don't allow the cache to grow beyond this size.
  5. */
  6. #define IO_ALLOC_CACHE_MAX 128
  7. static inline bool io_alloc_cache_put(struct io_alloc_cache *cache,
  8. void *entry)
  9. {
  10. if (cache->nr_cached < cache->max_cached) {
  11. if (!kasan_mempool_poison_object(entry))
  12. return false;
  13. cache->entries[cache->nr_cached++] = entry;
  14. return true;
  15. }
  16. return false;
  17. }
  18. static inline void *io_alloc_cache_get(struct io_alloc_cache *cache)
  19. {
  20. if (cache->nr_cached) {
  21. void *entry = cache->entries[--cache->nr_cached];
  22. kasan_mempool_unpoison_object(entry, cache->elem_size);
  23. return entry;
  24. }
  25. return NULL;
  26. }
  27. /* returns false if the cache was initialized properly */
  28. static inline bool io_alloc_cache_init(struct io_alloc_cache *cache,
  29. unsigned max_nr, size_t size)
  30. {
  31. cache->entries = kvmalloc_array(max_nr, sizeof(void *), GFP_KERNEL);
  32. if (cache->entries) {
  33. cache->nr_cached = 0;
  34. cache->max_cached = max_nr;
  35. cache->elem_size = size;
  36. return false;
  37. }
  38. return true;
  39. }
  40. static inline void io_alloc_cache_free(struct io_alloc_cache *cache,
  41. void (*free)(const void *))
  42. {
  43. void *entry;
  44. if (!cache->entries)
  45. return;
  46. while ((entry = io_alloc_cache_get(cache)) != NULL)
  47. free(entry);
  48. kvfree(cache->entries);
  49. cache->entries = NULL;
  50. }
  51. #endif