Aaron Durbin | 127525c | 2015-03-26 12:29:12 -0500 | [diff] [blame] | 1 | /* |
| 2 | * This file is part of the coreboot project. |
| 3 | * |
| 4 | * Copyright 2015 Google Inc. |
| 5 | * |
| 6 | * This program is free software; you can redistribute it and/or modify |
| 7 | * it under the terms of the GNU General Public License as published by |
| 8 | * the Free Software Foundation; version 2 of the License. |
| 9 | * |
| 10 | * This program is distributed in the hope that it will be useful, |
| 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 13 | * GNU General Public License for more details. |
Aaron Durbin | 127525c | 2015-03-26 12:29:12 -0500 | [diff] [blame] | 14 | */ |
| 15 | |
Aaron Durbin | dc9f5cd | 2015-09-08 13:34:43 -0500 | [diff] [blame] | 16 | #include <commonlib/mem_pool.h> |
Aaron Durbin | 127525c | 2015-03-26 12:29:12 -0500 | [diff] [blame] | 17 | #include <stdlib.h> |
| 18 | |
| 19 | void *mem_pool_alloc(struct mem_pool *mp, size_t sz) |
| 20 | { |
| 21 | void *p; |
| 22 | |
| 23 | /* Make all allocations be at least 8 byte aligned. */ |
| 24 | sz = ALIGN_UP(sz, 8); |
| 25 | |
| 26 | /* Determine if any space available. */ |
| 27 | if ((mp->size - mp->free_offset) < sz) |
| 28 | return NULL; |
| 29 | |
| 30 | p = &mp->buf[mp->free_offset]; |
| 31 | |
| 32 | mp->free_offset += sz; |
| 33 | mp->last_alloc = p; |
| 34 | |
| 35 | return p; |
| 36 | } |
| 37 | |
| 38 | void mem_pool_free(struct mem_pool *mp, void *p) |
| 39 | { |
| 40 | /* Determine if p was the most recent allocation. */ |
| 41 | if (p == NULL || mp->last_alloc != p) |
| 42 | return; |
| 43 | |
| 44 | mp->free_offset = mp->last_alloc - mp->buf; |
| 45 | /* No way to track allocation before this one. */ |
| 46 | mp->last_alloc = NULL; |
| 47 | } |