]> git.ipfire.org Git - thirdparty/systemd.git/blob - src/basic/mempool.c
tree-wide: be more careful with the type of array sizes
[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
9 #include <stdint.h>
10 #include <stdlib.h>
11
12 #include "macro.h"
13 #include "mempool.h"
14 #include "util.h"
15
16 struct pool {
17 struct pool *next;
18 size_t n_tiles;
19 size_t n_used;
20 };
21
22 void* mempool_alloc_tile(struct mempool *mp) {
23 size_t i;
24
25 /* When a tile is released we add it to the list and simply
26 * place the next pointer at its offset 0. */
27
28 assert(mp->tile_size >= sizeof(void*));
29 assert(mp->at_least > 0);
30
31 if (mp->freelist) {
32 void *r;
33
34 r = mp->freelist;
35 mp->freelist = * (void**) mp->freelist;
36 return r;
37 }
38
39 if (_unlikely_(!mp->first_pool) ||
40 _unlikely_(mp->first_pool->n_used >= mp->first_pool->n_tiles)) {
41 size_t size, n;
42 struct pool *p;
43
44 n = mp->first_pool ? mp->first_pool->n_tiles : 0;
45 n = MAX(mp->at_least, n * 2);
46 size = PAGE_ALIGN(ALIGN(sizeof(struct pool)) + n*mp->tile_size);
47 n = (size - ALIGN(sizeof(struct pool))) / mp->tile_size;
48
49 p = malloc(size);
50 if (!p)
51 return NULL;
52
53 p->next = mp->first_pool;
54 p->n_tiles = n;
55 p->n_used = 0;
56
57 mp->first_pool = p;
58 }
59
60 i = mp->first_pool->n_used++;
61
62 return ((uint8_t*) mp->first_pool) + ALIGN(sizeof(struct pool)) + i*mp->tile_size;
63 }
64
65 void* mempool_alloc0_tile(struct mempool *mp) {
66 void *p;
67
68 p = mempool_alloc_tile(mp);
69 if (p)
70 memzero(p, mp->tile_size);
71 return p;
72 }
73
74 void mempool_free_tile(struct mempool *mp, void *p) {
75 * (void**) p = mp->freelist;
76 mp->freelist = p;
77 }
78
79 #ifdef VALGRIND
80
81 void mempool_drop(struct mempool *mp) {
82 struct pool *p = mp->first_pool;
83 while (p) {
84 struct pool *n;
85 n = p->next;
86 free(p);
87 p = n;
88 }
89 }
90
91 #endif