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  * Memory pool for large temporary memory allocations that must not fail.
13  * With the first allocation from an unused (idle or free) pool the pool
14  * becomes reserved for that particular thread, until all allocations are
15  * freed again. In order to avoid dead-lock and ease code review it is good
16  * practise to free everything allocated by a certain function before
17  * returning.
18  */
19 
20 /*
21  * struct mempool_item - internal struct to keep track of an item
22  */
23 struct mempool_item {
24 	size_t size;
25 	ssize_t prev_item_offset;
26 	ssize_t next_item_offset;
27 };
28 
29 struct mempool;
30 
31 #define MEMPOOL_ALIGN	__alignof__(long)
32 
33 #if defined(__KERNEL__)
34 /*
35  * System wide memory pool for large temporary memory allocation.
36  */
37 extern struct mempool *mempool_default;
38 #endif
39 
40 /*
41  * mempool_alloc_pool() - Allocate a new memory pool
42  * @data:		a block of memory to carve out items from, must
43  *			have an alignment of MEMPOOL_ALIGN.
44  * @size:		size fo the block of memory
45  * @release_mem:	function to call when the pool has been emptied,
46  *			ignored if NULL.
47  * returns a pointer to a valid pool on success or NULL on failure.
48  */
49 struct mempool *mempool_alloc_pool(void *data, size_t size,
50 				   void (*release_mem)(void *ptr, size_t size));
51 
52 /*
53  * mempool_alloc() - Allocate an item from a memory pool
54  * @pool:		A memory pool created with mempool_alloc_pool()
55  * @size:		Size in bytes of the item to allocate
56  * return a valid pointer on success or NULL on failure.
57  */
58 void *mempool_alloc(struct mempool *pool, size_t size);
59 
60 /*
61  * mempool_calloc() - Allocate and zero initialize an array of elements from a
62  *		      memory pool
63  * @pool:		A memory pool created with mempool_alloc_pool()
64  * @nmemb:		Number of elements in the array
65  * @size:		Size in bytes of each element in the array
66  * return a valid pointer on success or NULL on failure.
67  */
68 void *mempool_calloc(struct mempool *pool, size_t nmemb, size_t size);
69 
70 /*
71  * mempool_free() - Frees a previously allocated item
72  * @pool:		A memory pool create with mempool_alloc_pool()
73  * @ptr:		A pointer to a previously allocated item
74  */
75 void mempool_free(struct mempool *pool, void *ptr);
76 
77 #endif /*__MEMPOOL_H*/
78