Angel Pons | ebda03e | 2020-04-02 23:48:05 +0200 | [diff] [blame] | 1 | /* SPDX-License-Identifier: GPL-2.0-only */ |
Aaron Durbin | 127525c | 2015-03-26 12:29:12 -0500 | [diff] [blame] | 2 | |
Aaron Durbin | ca0a676 | 2015-12-15 17:49:12 -0600 | [diff] [blame] | 3 | #include <commonlib/helpers.h> |
Aaron Durbin | dc9f5cd | 2015-09-08 13:34:43 -0500 | [diff] [blame] | 4 | #include <commonlib/mem_pool.h> |
Aaron Durbin | 127525c | 2015-03-26 12:29:12 -0500 | [diff] [blame] | 5 | |
| 6 | void *mem_pool_alloc(struct mem_pool *mp, size_t sz) |
| 7 | { |
| 8 | void *p; |
| 9 | |
Raul E Rangel | 5ac82dc | 2021-07-23 16:43:18 -0600 | [diff] [blame] | 10 | 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 Durbin | 127525c | 2015-03-26 12:29:12 -0500 | [diff] [blame] | 15 | |
| 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 Werner | 6482c22 | 2021-04-02 17:45:03 -0700 | [diff] [blame] | 23 | mp->second_to_last_alloc = mp->last_alloc; |
Aaron Durbin | 127525c | 2015-03-26 12:29:12 -0500 | [diff] [blame] | 24 | mp->last_alloc = p; |
| 25 | |
| 26 | return p; |
| 27 | } |
| 28 | |
| 29 | void 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 Werner | 6482c22 | 2021-04-02 17:45:03 -0700 | [diff] [blame] | 36 | mp->last_alloc = mp->second_to_last_alloc; |
Aaron Durbin | 127525c | 2015-03-26 12:29:12 -0500 | [diff] [blame] | 37 | /* No way to track allocation before this one. */ |
Julius Werner | 6482c22 | 2021-04-02 17:45:03 -0700 | [diff] [blame] | 38 | mp->second_to_last_alloc = NULL; |
Aaron Durbin | 127525c | 2015-03-26 12:29:12 -0500 | [diff] [blame] | 39 | } |