xref: /optee_os/lib/libutils/ext/include/mempool.h (revision 12941fdcbaa31bd0c6ab241022a7eba66c801467)
1 /* SPDX-License-Identifier: BSD-2-Clause */
2 /*
3  * Copyright (c) 2018, Linaro Limited
4  */
5 
6 #ifndef __MEMPOOL_H
7 #define __MEMPOOL_H
8 
9 #include <types_ext.h>
10 
11 /*
12  * struct mempool_item - internal struct to keep track of an item
13  */
14 struct mempool_item {
15 	size_t size;
16 	ssize_t prev_item_offset;
17 	ssize_t next_item_offset;
18 };
19 
20 struct mempool;
21 
22 /*
23  * mempool_alloc_pool() - Allocate a new memory pool
24  * @data:		a block of memory to carve out items from
25  * @size:		size fo the block of memory
26  * @release_mem:	function to call when the pool has been emptied,
27  *			ignored if NULL.
28  * returns a pointer to a valid pool on success or NULL on failure.
29  */
30 struct mempool *mempool_alloc_pool(void *data, size_t size,
31 				   void (*release_mem)(void *ptr, size_t size));
32 
33 /*
34  * mempool_alloc() - Allocate an item from a memory pool
35  * @pool:		A memory pool created with mempool_alloc_pool()
36  * @size:		Size in bytes of the item to allocate
37  * return a valid pointer on success or NULL on failure.
38  */
39 void *mempool_alloc(struct mempool *pool, size_t size);
40 
41 /*
42  * mempool_calloc() - Allocate and zero initialize an array of elements from a
43  *		      memory pool
44  * @pool:		A memory pool created with mempool_alloc_pool()
45  * @nmemb:		Number of elements in the array
46  * @size:		Size in bytes of each element in the array
47  * return a valid pointer on success or NULL on failure.
48  */
49 void *mempool_calloc(struct mempool *pool, size_t nmemb, size_t size);
50 
51 /*
52  * mempool_free() - Frees a previously allocated item
53  * @pool:		A memory pool create with mempool_alloc_pool()
54  * @ptr:		A pointer to a previously allocated item
55  */
56 void mempool_free(struct mempool *pool, void *ptr);
57 
58 #endif /*__MEMPOOL_H*/
59