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