| 1 | #include <assert.h> |
| 2 | #include <stdlib.h> |
| 3 | |
| 4 | #include "memalign.h" |
| 5 | #include "smalloc.h" |
| 6 | |
| 7 | #define PTR_ALIGN(ptr, mask) \ |
| 8 | (char *)((uintptr_t)((ptr) + (mask)) & ~(mask)) |
| 9 | |
| 10 | struct align_footer { |
| 11 | unsigned int offset; |
| 12 | }; |
| 13 | |
| 14 | void *__fio_memalign(size_t alignment, size_t size, malloc_fn fn) |
| 15 | { |
| 16 | struct align_footer *f; |
| 17 | void *ptr, *ret = NULL; |
| 18 | |
| 19 | assert(!(alignment & (alignment - 1))); |
| 20 | |
| 21 | ptr = fn(size + alignment + sizeof(*f) - 1); |
| 22 | if (ptr) { |
| 23 | ret = PTR_ALIGN(ptr, alignment - 1); |
| 24 | f = ret + size; |
| 25 | f->offset = (uintptr_t) ret - (uintptr_t) ptr; |
| 26 | } |
| 27 | |
| 28 | return ret; |
| 29 | } |
| 30 | |
| 31 | void __fio_memfree(void *ptr, size_t size, free_fn fn) |
| 32 | { |
| 33 | struct align_footer *f = ptr + size; |
| 34 | |
| 35 | fn(ptr - f->offset); |
| 36 | } |