summaryrefslogtreecommitdiff
path: root/lib/memalign.c
blob: 537bb9fb1b92930e862426156f7b7b46c4cee8f9 (plain)
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
#include <assert.h>
#include <stdlib.h>

#include "memalign.h"
#include "smalloc.h"

#define PTR_ALIGN(ptr, mask)   \
	(char *)((uintptr_t)((ptr) + (mask)) & ~(mask))

struct align_footer {
	unsigned int offset;
};

void *fio_memalign(size_t alignment, size_t size, bool shared)
{
	struct align_footer *f;
	void *ptr, *ret = NULL;

	assert(!(alignment & (alignment - 1)));

	if (shared)
		ptr = smalloc(size + alignment + sizeof(*f) - 1);
	else
		ptr = malloc(size + alignment + sizeof(*f) - 1);

	if (ptr) {
		ret = PTR_ALIGN(ptr, alignment - 1);
		f = ret + size;
		f->offset = (uintptr_t) ret - (uintptr_t) ptr;
	}

	return ret;
}

void fio_memfree(void *ptr, size_t size, bool shared)
{
	struct align_footer *f = ptr + size;

	if (shared)
		sfree(ptr - f->offset);
	else
		free(ptr - f->offset);
}