xref: /optee_os/lib/libutils/ext/mempool.c (revision 3d3b05918ec9052ba13de82fbcaba204766eb636)
1 // SPDX-License-Identifier: BSD-2-Clause
2 /*
3  * Copyright (c) 2014, STMicroelectronics International N.V.
4  * Copyright (c) 2018-2019, Linaro Limited
5  */
6 
7 
8 #include <assert.h>
9 #include <compiler.h>
10 #include <malloc.h>
11 #include <mempool.h>
12 #include <string.h>
13 #include <util.h>
14 
15 #if defined(__KERNEL__)
16 #include <kernel/mutex.h>
17 #include <kernel/panic.h>
18 #include <kernel/thread.h>
19 #include <kernel/refcount.h>
20 #endif
21 
22 /*
23  * Allocation of temporary memory buffers which are used in a stack like
24  * fashion. One exmaple is when a Big Number is needed for a temporary
25  * variable in a Big Number computation: Big Number operations (add,...),
26  * crypto algorithms (rsa, ecc,,...).
27  *
28  *  The allocation algorithm takes memory buffers from a pool,
29  *  characterized by (cf. struct mempool):
30  * - the total size (in bytes) of the pool
31  * - the offset of the last item allocated in the pool (struct
32  *   mempool_item). This offset is -1 is nothing is allocated yet.
33  *
34  * Each item consists of (struct mempool_item)
35  * - the size of the item
36  * - the offsets, in the pool, of the previous and next items
37  *
38  * The allocation allocates an item for a given size.
39  * The allocation is performed in the pool after the last
40  * allocated items. This means:
41  * - the heap is never used.
42  * - there is no assumption on the size of the allocated memory buffers. Only
43  *   the size of the pool will limit the allocation.
44  * - a constant time allocation and free as there is no list scan
45  * - but a potentially fragmented memory as the allocation does not take into
46  *   account "holes" in the pool (allocation is performed after the last
47  *   allocated variable). Indeed, this interface is supposed to be used
48  *   with stack like allocations to avoid this issue. This means that
49  *   allocated items:
50  *   - should have a short life cycle
51  *   - if an item A is allocated before another item B, then A should be
52  *     released after B.
53  *   So the potential fragmentation is mitigated.
54  */
55 
56 
57 struct mempool {
58 	size_t size;  /* size of the memory pool, in bytes */
59 	ssize_t last_offset;   /* offset to the last one */
60 	vaddr_t data;
61 #ifdef CFG_MEMPOOL_REPORT_LAST_OFFSET
62 	ssize_t max_last_offset;
63 #endif
64 #if defined(__KERNEL__)
65 	void (*release_mem)(void *ptr, size_t size);
66 	struct mutex mu;
67 	struct condvar cv;
68 	struct refcount refc;
69 	int owner;
70 #endif
71 };
72 
73 static void get_pool(struct mempool *pool __maybe_unused)
74 {
75 #if defined(__KERNEL__)
76 	/*
77 	 * Owner matches our thread it cannot be changed. If it doesn't
78 	 * match it can change any at time we're not holding the mutex to
79 	 * any value but our thread id.
80 	 */
81 	if (atomic_load_int(&pool->owner) == thread_get_id()) {
82 		if (!refcount_inc(&pool->refc))
83 			panic();
84 		return;
85 	}
86 
87 	mutex_lock(&pool->mu);
88 
89 	/* Wait until the pool is available */
90 	while (pool->owner != THREAD_ID_INVALID)
91 		condvar_wait(&pool->cv, &pool->mu);
92 
93 	pool->owner = thread_get_id();
94 	refcount_set(&pool->refc, 1);
95 
96 	mutex_unlock(&pool->mu);
97 #endif
98 }
99 
100 static void put_pool(struct mempool *pool __maybe_unused)
101 {
102 #if defined(__KERNEL__)
103 	assert(atomic_load_int(&pool->owner) == thread_get_id());
104 
105 	if (refcount_dec(&pool->refc)) {
106 		mutex_lock(&pool->mu);
107 
108 		/*
109 		 * Do an atomic store to match the atomic load in
110 		 * get_pool() above.
111 		 */
112 		atomic_store_int(&pool->owner, THREAD_ID_INVALID);
113 		condvar_signal(&pool->cv);
114 
115 		/* As the refcount is 0 there should be no items left */
116 		if (pool->last_offset >= 0)
117 			panic();
118 		if (pool->release_mem)
119 			pool->release_mem((void *)pool->data, pool->size);
120 
121 		mutex_unlock(&pool->mu);
122 	}
123 #endif
124 }
125 
126 struct mempool *
127 mempool_alloc_pool(void *data, size_t size,
128 		   void (*release_mem)(void *ptr, size_t size) __maybe_unused)
129 {
130 	struct mempool *pool = calloc(1, sizeof(*pool));
131 
132 	COMPILE_TIME_ASSERT(MEMPOOL_ALIGN >= __alignof__(struct mempool_item));
133 	assert(!((vaddr_t)data & (MEMPOOL_ALIGN - 1)));
134 
135 	if (pool) {
136 		pool->size = size;
137 		pool->data = (vaddr_t)data;
138 		pool->last_offset = -1;
139 #if defined(__KERNEL__)
140 		pool->release_mem = release_mem;
141 		mutex_init(&pool->mu);
142 		condvar_init(&pool->cv);
143 		pool->owner = THREAD_ID_INVALID;
144 #endif
145 	}
146 
147 	return pool;
148 }
149 
150 void *mempool_alloc(struct mempool *pool, size_t size)
151 {
152 	size_t offset;
153 	struct mempool_item *new_item;
154 	struct mempool_item *last_item = NULL;
155 
156 	get_pool(pool);
157 
158 	if (pool->last_offset < 0) {
159 		offset = 0;
160 	} else {
161 		last_item = (struct mempool_item *)(pool->data +
162 						    pool->last_offset);
163 		offset = pool->last_offset + last_item->size;
164 
165 		offset = ROUNDUP(offset, MEMPOOL_ALIGN);
166 		if (offset > pool->size)
167 			goto error;
168 	}
169 
170 	size = sizeof(struct mempool_item) + size;
171 	size = ROUNDUP(size, MEMPOOL_ALIGN);
172 	if (offset + size > pool->size)
173 		goto error;
174 
175 	new_item = (struct mempool_item *)(pool->data + offset);
176 	new_item->size = size;
177 	new_item->prev_item_offset = pool->last_offset;
178 	if (last_item)
179 		last_item->next_item_offset = offset;
180 	new_item->next_item_offset = -1;
181 	pool->last_offset = offset;
182 #ifdef CFG_MEMPOOL_REPORT_LAST_OFFSET
183 	if (pool->last_offset > pool->max_last_offset) {
184 		pool->max_last_offset = pool->last_offset;
185 		DMSG("Max memory usage increased to %zu",
186 		     (size_t)pool->max_last_offset);
187 	}
188 #endif
189 
190 	return new_item + 1;
191 
192 error:
193 	EMSG("Failed to allocate %zu bytes, please tune the pool size", size);
194 	put_pool(pool);
195 	return NULL;
196 }
197 
198 void *mempool_calloc(struct mempool *pool, size_t nmemb, size_t size)
199 {
200 	size_t sz;
201 	void *p;
202 
203 	if (MUL_OVERFLOW(nmemb, size, &sz))
204 		return NULL;
205 
206 	p = mempool_alloc(pool, sz);
207 	if (p)
208 		memset(p, 0, sz);
209 
210 	return p;
211 }
212 
213 void mempool_free(struct mempool *pool, void *ptr)
214 {
215 	struct mempool_item *item;
216 	struct mempool_item *prev_item;
217 	struct mempool_item *next_item;
218 	ssize_t last_offset = -1;
219 
220 	if (!ptr)
221 		return;
222 
223 	item = (struct mempool_item *)((vaddr_t)ptr -
224 				       sizeof(struct mempool_item));
225 	if (item->prev_item_offset >= 0) {
226 		prev_item = (struct mempool_item *)(pool->data +
227 						    item->prev_item_offset);
228 		prev_item->next_item_offset = item->next_item_offset;
229 		last_offset = item->prev_item_offset;
230 	}
231 
232 	if (item->next_item_offset >= 0) {
233 		next_item = (struct mempool_item *)(pool->data +
234 						    item->next_item_offset);
235 		next_item->prev_item_offset = item->prev_item_offset;
236 		last_offset = pool->last_offset;
237 	}
238 
239 	pool->last_offset = last_offset;
240 	put_pool(pool);
241 }
242