This repository has been archived by the owner on Mar 1, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 4
/
mem.c
88 lines (69 loc) · 1.66 KB
/
mem.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
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#ifdef HAVE_CONFIG_H
#include <config.h>
#endif
#include "ggaoed.h"
#include <stdlib.h>
#include <unistd.h>
#include <glib.h>
/**********************************************************************
* Global variables
*/
/* Physical page size */
static long page_size;
/* Exponent of the page size */
static unsigned page_shift;
/* Valid packet sizes are between 1 (MTU=1500) and 4 (MTU=9000) pages */
static GTrashStack *caches[4];
/**********************************************************************
* Functions
*/
void *alloc_packet(unsigned size)
{
unsigned cache;
void *ptr;
int ret;
cache = (size + page_size - 1) >> page_shift;
size = cache-- << page_shift;
if (G_UNLIKELY(cache >= G_N_ELEMENTS(caches)))
{
/* Should not happen */
logit(LOG_ERR, "Unexpected memory allocation size %u", size);
return NULL;
}
ptr = g_trash_stack_pop(&caches[cache]);
if (G_LIKELY(ptr))
return ptr;
ret = posix_memalign(&ptr, page_size, size);
if (ret)
{
logit(LOG_ERR, "Memory allocation failed: %s", strerror(ret));
return NULL;
}
return ptr;
}
void free_packet(void *buf, unsigned size)
{
unsigned cache;
cache = ((size + page_size - 1) >> page_shift) - 1;
if (G_UNLIKELY(cache >= G_N_ELEMENTS(caches)))
{
/* Should not happen */
logit(LOG_ERR, "Unexpected memory de-allocation size %u", size);
return;
}
g_trash_stack_push(&caches[cache], buf);
}
void mem_init(void)
{
page_size = sysconf(_SC_PAGESIZE);
for (page_shift = 0; 1l << page_shift < page_size; page_shift++)
/* Nothing */;
}
void mem_done(void)
{
unsigned i;
void *p;
for (i = 0; i < G_N_ELEMENTS(caches); i++)
while ((p = g_trash_stack_pop(&caches[i])))
free(p);
}