Merge branch 'dev' of https://github.com/smartxworks/fio
[fio.git] / lib / memalign.c
CommitLineData
91aea6ec 1#include <assert.h>
3d2d14bc 2#include <stdlib.h>
91aea6ec
JA
3
4#include "memalign.h"
3114b675 5#include "smalloc.h"
087c0cba
TK
6
7#define PTR_ALIGN(ptr, mask) \
8 (char *)((uintptr_t)((ptr) + (mask)) & ~(mask))
91aea6ec
JA
9
10struct align_footer {
11 unsigned int offset;
12};
13
3114b675 14void *fio_memalign(size_t alignment, size_t size, bool shared)
91aea6ec
JA
15{
16 struct align_footer *f;
17 void *ptr, *ret = NULL;
18
19 assert(!(alignment & (alignment - 1)));
20
3114b675
VF
21 if (shared)
22 ptr = smalloc(size + alignment + sizeof(*f) - 1);
23 else
24 ptr = malloc(size + alignment + sizeof(*f) - 1);
25
91aea6ec 26 if (ptr) {
5fb55c77 27 ret = PTR_ALIGN(ptr, alignment - 1);
91aea6ec 28 f = ret + size;
e43606c2 29 f->offset = (uintptr_t) ret - (uintptr_t) ptr;
91aea6ec
JA
30 }
31
32 return ret;
33}
34
3114b675 35void fio_memfree(void *ptr, size_t size, bool shared)
91aea6ec
JA
36{
37 struct align_footer *f = ptr + size;
38
3114b675
VF
39 if (shared)
40 sfree(ptr - f->offset);
41 else
42 free(ptr - f->offset);
91aea6ec 43}