Jens Axboe | 91aea6e | 2011-04-25 20:46:58 +0200 | [diff] [blame] | 1 | #include <stdlib.h> |
| 2 | #include <assert.h> |
Bruce Cran | e43606c | 2012-02-20 09:34:24 +0100 | [diff] [blame] | 3 | #include <inttypes.h> |
Jens Axboe | 91aea6e | 2011-04-25 20:46:58 +0200 | [diff] [blame] | 4 | |
| 5 | #include "memalign.h" |
| 6 | |
| 7 | struct align_footer { |
| 8 | unsigned int offset; |
| 9 | }; |
| 10 | |
| 11 | #define PTR_ALIGN(ptr, mask) \ |
Bruce Cran | e43606c | 2012-02-20 09:34:24 +0100 | [diff] [blame] | 12 | (char *) (((uintptr_t) ((ptr) + (mask)) & ~(mask))) |
Jens Axboe | 91aea6e | 2011-04-25 20:46:58 +0200 | [diff] [blame] | 13 | |
| 14 | void *fio_memalign(size_t alignment, size_t size) |
| 15 | { |
| 16 | struct align_footer *f; |
| 17 | void *ptr, *ret = NULL; |
| 18 | |
| 19 | assert(!(alignment & (alignment - 1))); |
| 20 | |
| 21 | ptr = malloc(size + alignment + size + sizeof(*f) - 1); |
| 22 | if (ptr) { |
| 23 | ret = PTR_ALIGN(ptr, alignment); |
| 24 | f = ret + size; |
Bruce Cran | e43606c | 2012-02-20 09:34:24 +0100 | [diff] [blame] | 25 | f->offset = (uintptr_t) ret - (uintptr_t) ptr; |
Jens Axboe | 91aea6e | 2011-04-25 20:46:58 +0200 | [diff] [blame] | 26 | } |
| 27 | |
| 28 | return ret; |
| 29 | } |
| 30 | |
| 31 | void fio_memfree(void *ptr, size_t size) |
| 32 | { |
| 33 | struct align_footer *f = ptr + size; |
| 34 | |
| 35 | free(ptr - f->offset); |
| 36 | } |