blob: c21fa0e8aaca65644ef3fe9f968ed3d587d4a4e0 [file] [log] [blame]
Aaron Durbin127525c2015-03-26 12:29:12 -05001/*
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 Durbin127525c2015-03-26 12:29:12 -050014 */
15
16#ifndef _MEM_POOL_H_
17#define _MEM_POOL_H_
18
19#include <stddef.h>
20#include <stdint.h>
21
22/*
23 * The memory pool allows one to allocate memory from a fixed size buffer
24 * that also allows freeing semantics for reuse. However, the current
25 * limitation is that the most recent allocation is the only one that
26 * can be freed. If one tries to free any allocation that isn't the
27 * most recently allocated it will result in a leak within the memory pool.
28 *
29 * The memory returned by allocations are at least 8 byte aligned. Note
30 * that this requires the backing buffer to start on at least an 8 byte
31 * alignment.
32 */
33
34struct mem_pool {
35 uint8_t *buf;
36 size_t size;
37 uint8_t *last_alloc;
38 size_t free_offset;
39};
40
41#define MEM_POOL_INIT(buf_, size_) \
42 { \
43 .buf = (buf_), \
44 .size = (size_), \
45 .last_alloc = NULL, \
46 .free_offset = 0, \
47 }
48
49static inline void mem_pool_reset(struct mem_pool *mp)
50{
51 mp->last_alloc = NULL;
52 mp->free_offset = 0;
53}
54
55/* Initialize a memory pool. */
56static inline void mem_pool_init(struct mem_pool *mp, void *buf, size_t sz)
57{
58 mp->buf = buf;
59 mp->size = sz;
60 mem_pool_reset(mp);
61}
62
63/* Allocate requested size from the memory pool. NULL returned on error. */
64void *mem_pool_alloc(struct mem_pool *mp, size_t sz);
65
66/* Free allocation from memory pool. */
67void mem_pool_free(struct mem_pool *mp, void *alloc);
68
69#endif /* _MEM_POOL_H_ */