alloc_cache.c 945 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344
  1. // SPDX-License-Identifier: GPL-2.0
  2. #include "alloc_cache.h"
  3. void io_alloc_cache_free(struct io_alloc_cache *cache,
  4. void (*free)(const void *))
  5. {
  6. void *entry;
  7. if (!cache->entries)
  8. return;
  9. while ((entry = io_alloc_cache_get(cache)) != NULL)
  10. free(entry);
  11. kvfree(cache->entries);
  12. cache->entries = NULL;
  13. }
  14. /* returns false if the cache was initialized properly */
  15. bool io_alloc_cache_init(struct io_alloc_cache *cache,
  16. unsigned max_nr, unsigned int size,
  17. unsigned int init_bytes)
  18. {
  19. cache->entries = kvmalloc_array(max_nr, sizeof(void *), GFP_KERNEL);
  20. if (!cache->entries)
  21. return true;
  22. cache->nr_cached = 0;
  23. cache->max_cached = max_nr;
  24. cache->elem_size = size;
  25. cache->init_clear = init_bytes;
  26. return false;
  27. }
  28. void *io_cache_alloc_new(struct io_alloc_cache *cache, gfp_t gfp)
  29. {
  30. void *obj;
  31. obj = kmalloc(cache->elem_size, gfp);
  32. if (obj && cache->init_clear)
  33. memset(obj, 0, cache->init_clear);
  34. return obj;
  35. }