blob: d82ab18bd79688aca3cc51678e3ab3f28bc25bc2 [file] [log] [blame]
Angel Ponsebda03e2020-04-02 23:48:05 +02001/* SPDX-License-Identifier: GPL-2.0-only */
Aaron Durbin127525c2015-03-26 12:29:12 -05002
Aaron Durbinca0a6762015-12-15 17:49:12 -06003#include <commonlib/helpers.h>
Aaron Durbindc9f5cd2015-09-08 13:34:43 -05004#include <commonlib/mem_pool.h>
Aaron Durbin127525c2015-03-26 12:29:12 -05005
6void *mem_pool_alloc(struct mem_pool *mp, size_t sz)
7{
8 void *p;
9
Raul E Rangel5ac82dc2021-07-23 16:43:18 -060010 if (mp->alignment == 0)
11 return NULL;
12
13 /* We assume that mp->buf started mp->alignment aligned */
14 sz = ALIGN_UP(sz, mp->alignment);
Aaron Durbin127525c2015-03-26 12:29:12 -050015
16 /* Determine if any space available. */
17 if ((mp->size - mp->free_offset) < sz)
18 return NULL;
19
20 p = &mp->buf[mp->free_offset];
21
22 mp->free_offset += sz;
Julius Werner6482c222021-04-02 17:45:03 -070023 mp->second_to_last_alloc = mp->last_alloc;
Aaron Durbin127525c2015-03-26 12:29:12 -050024 mp->last_alloc = p;
25
26 return p;
27}
28
29void mem_pool_free(struct mem_pool *mp, void *p)
30{
31 /* Determine if p was the most recent allocation. */
32 if (p == NULL || mp->last_alloc != p)
33 return;
34
35 mp->free_offset = mp->last_alloc - mp->buf;
Julius Werner6482c222021-04-02 17:45:03 -070036 mp->last_alloc = mp->second_to_last_alloc;
Aaron Durbin127525c2015-03-26 12:29:12 -050037 /* No way to track allocation before this one. */
Julius Werner6482c222021-04-02 17:45:03 -070038 mp->second_to_last_alloc = NULL;
Aaron Durbin127525c2015-03-26 12:29:12 -050039}