-
Notifications
You must be signed in to change notification settings - Fork 2
/
slab.c
64 lines (50 loc) · 1.09 KB
/
slab.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
/*
* Copyright (c) 2020-2021 Siddharth Chandrasekaran <[email protected]>
*
* SPDX-License-Identifier: Apache-2.0
*
*/
#include <string.h>
#include <stdbool.h>
#include "slab.h"
struct slab_unit {
uint32_t leased;
uint32_t canary;
uint8_t data[0];
} __packed;
int slab_init(slab_t *slab, size_t slab_size,
uint8_t *blob, size_t blob_size)
{
slab->size = ROUND_UP(slab_size, sizeof(void *)) +
sizeof(struct slab_unit);
if (slab->size > blob_size)
return -1;
slab->count = blob_size / slab->size;
memset(blob, 0, blob_size);
slab->blob = blob;
return (int)slab->count;
}
int slab_alloc(slab_t *slab, void **block)
{
size_t i;
struct slab_unit *p;
for (i = 0; i < slab->count; i++) {
p = (struct slab_unit *)(slab->blob + (i * slab->size));
if (!p->leased) {
p->leased = true;
p->canary = 0xdeadbeaf;
*block = p->data;
return 0;
}
}
return -1;
}
int slab_free(slab_t *slab, void *block)
{
ARG_UNUSED(slab);
struct slab_unit *p = CONTAINER_OF(block, struct slab_unit, data);
if (p->canary != 0xdeadbeaf)
return -1;
p->leased = false;
return 0;
}