]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/mempool.c
Add SPDX license identifiers to source files under the LGPL
[thirdparty/systemd.git] / src / basic / mempool.c
1 /* SPDX-License-Identifier: LGPL-2.1+ */
2 /***
3 This file is part of systemd.
4
5 Copyright 2010-2014 Lennart Poettering
6 Copyright 2014 Michal Schmidt
7
8 systemd is free software; you can redistribute it and/or modify it
9 under the terms of the GNU Lesser General Public License as published by
10 the Free Software Foundation; either version 2.1 of the License, or
11 (at your option) any later version.
12
13 systemd is distributed in the hope that it will be useful, but
14 WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 Lesser General Public License for more details.
17
18 You should have received a copy of the GNU Lesser General Public License
19 along with systemd; If not, see <http://www.gnu.org/licenses/>.
20 ***/
21
22 #include <stdint.h>
23 #include <stdlib.h>
24
25 #include "macro.h"
26 #include "mempool.h"
27 #include "util.h"
28
29 struct pool {
30 struct pool *next;
31 unsigned n_tiles;
32 unsigned n_used;
33 };
34
35 void* mempool_alloc_tile(struct mempool *mp) {
36 unsigned i;
37
38 /* When a tile is released we add it to the list and simply
39 * place the next pointer at its offset 0. */
40
41 assert(mp->tile_size >= sizeof(void*));
42 assert(mp->at_least > 0);
43
44 if (mp->freelist) {
45 void *r;
46
47 r = mp->freelist;
48 mp->freelist = * (void**) mp->freelist;
49 return r;
50 }
51
52 if (_unlikely_(!mp->first_pool) ||
53 _unlikely_(mp->first_pool->n_used >= mp->first_pool->n_tiles)) {
54 unsigned n;
55 size_t size;
56 struct pool *p;
57
58 n = mp->first_pool ? mp->first_pool->n_tiles : 0;
59 n = MAX(mp->at_least, n * 2);
60 size = PAGE_ALIGN(ALIGN(sizeof(struct pool)) + n*mp->tile_size);
61 n = (size - ALIGN(sizeof(struct pool))) / mp->tile_size;
62
63 p = malloc(size);
64 if (!p)
65 return NULL;
66
67 p->next = mp->first_pool;
68 p->n_tiles = n;
69 p->n_used = 0;
70
71 mp->first_pool = p;
72 }
73
74 i = mp->first_pool->n_used++;
75
76 return ((uint8_t*) mp->first_pool) + ALIGN(sizeof(struct pool)) + i*mp->tile_size;
77 }
78
79 void* mempool_alloc0_tile(struct mempool *mp) {
80 void *p;
81
82 p = mempool_alloc_tile(mp);
83 if (p)
84 memzero(p, mp->tile_size);
85 return p;
86 }
87
88 void mempool_free_tile(struct mempool *mp, void *p) {
89 * (void**) p = mp->freelist;
90 mp->freelist = p;
91 }
92
93 #ifdef VALGRIND
94
95 void mempool_drop(struct mempool *mp) {
96 struct pool *p = mp->first_pool;
97 while (p) {
98 struct pool *n;
99 n = p->next;
100 free(p);
101 p = n;
102 }
103 }
104
105 #endif