| 1 | /* |
| 2 | * Copyright (C) 2010-2011 Mathieu Desnoyers <mathieu.desnoyers@efficios.com> |
| 3 | * |
| 4 | * SPDX-License-Identifier: MIT |
| 5 | * |
| 6 | */ |
| 7 | |
| 8 | #ifndef _LTTNG_ALIGN_H |
| 9 | #define _LTTNG_ALIGN_H |
| 10 | |
| 11 | #include "bug.h" |
| 12 | #include <unistd.h> |
| 13 | #include <limits.h> |
| 14 | |
| 15 | #ifndef PAGE_SIZE /* Cygwin limits.h defines its own PAGE_SIZE. */ |
| 16 | #define PAGE_SIZE sysconf(_SC_PAGE_SIZE) |
| 17 | #endif |
| 18 | |
| 19 | #ifndef PAGE_MASK /* macOS defines its own PAGE_MASK. */ |
| 20 | #define PAGE_MASK (~(PAGE_SIZE - 1)) |
| 21 | #endif |
| 22 | |
| 23 | #define __ALIGN_MASK(v, mask) (((v) + (mask)) & ~(mask)) |
| 24 | |
| 25 | #ifndef ALIGN /* macOS defines its own ALIGN. */ |
| 26 | #define ALIGN(v, align) __ALIGN_MASK(v, (__typeof__(v)) (align) - 1) |
| 27 | #endif |
| 28 | |
| 29 | #define __ALIGN_FLOOR_MASK(v, mask) ((v) & ~(mask)) |
| 30 | |
| 31 | #ifndef ALIGN_FLOOR |
| 32 | #define ALIGN_FLOOR(v, align) __ALIGN_FLOOR_MASK(v, (__typeof__(v)) (align) - 1) |
| 33 | #endif |
| 34 | |
| 35 | #define PAGE_ALIGN(addr) ALIGN(addr, PAGE_SIZE) |
| 36 | |
| 37 | /** |
| 38 | * offset_align - Calculate the offset needed to align an object on its natural |
| 39 | * alignment towards higher addresses. |
| 40 | * @align_drift: object offset from an "alignment"-aligned address. |
| 41 | * @alignment: natural object alignment. Must be non-zero, power of 2. |
| 42 | * |
| 43 | * Returns the offset that must be added to align towards higher |
| 44 | * addresses. |
| 45 | */ |
| 46 | #define offset_align(align_drift, alignment) \ |
| 47 | ({ \ |
| 48 | LTTNG_BUILD_RUNTIME_BUG_ON((alignment) == 0 \ |
| 49 | || ((alignment) & ((alignment) - 1))); \ |
| 50 | (((alignment) - (align_drift)) & ((alignment) - 1)); \ |
| 51 | }) |
| 52 | |
| 53 | /** |
| 54 | * offset_align_floor - Calculate the offset needed to align an object |
| 55 | * on its natural alignment towards lower addresses. |
| 56 | * @align_drift: object offset from an "alignment"-aligned address. |
| 57 | * @alignment: natural object alignment. Must be non-zero, power of 2. |
| 58 | * |
| 59 | * Returns the offset that must be substracted to align towards lower addresses. |
| 60 | */ |
| 61 | #define offset_align_floor(align_drift, alignment) \ |
| 62 | ({ \ |
| 63 | LTTNG_BUILD_RUNTIME_BUG_ON((alignment) == 0 \ |
| 64 | || ((alignment) & ((alignment) - 1))); \ |
| 65 | (((align_drift) - (alignment)) & ((alignment) - 1)); \ |
| 66 | }) |
| 67 | |
| 68 | #endif /* _LTTNG_ALIGN_H */ |