Brian Silverman | a1652f3 | 2020-01-29 20:41:44 -0800 | [diff] [blame] | 1 | #ifndef AOS_IPC_LIB_DATA_ALIGNMENT_H_ |
| 2 | #define AOS_IPC_LIB_DATA_ALIGNMENT_H_ |
| 3 | |
Austin Schuh | 99f7c6a | 2024-06-25 22:07:44 -0700 | [diff] [blame^] | 4 | #include "absl/log/check.h" |
| 5 | #include "absl/log/log.h" |
Brian Silverman | a1652f3 | 2020-01-29 20:41:44 -0800 | [diff] [blame] | 6 | |
| 7 | namespace aos { |
| 8 | |
| 9 | // All data buffers sent over or received from a channel will guarantee this |
| 10 | // alignment for their end. Flatbuffers aligns from the end, so this is what |
| 11 | // matters. |
| 12 | // |
Austin Schuh | e8d44ff | 2022-12-25 22:20:02 -0800 | [diff] [blame] | 13 | // 128 is a reasonable choice for now: |
Brian Silverman | a1652f3 | 2020-01-29 20:41:44 -0800 | [diff] [blame] | 14 | // Cortex-A72 (Raspberry Pi 4) and Cortex-A53 (Xavier AGX) both have 64 byte |
| 15 | // cache lines. |
| 16 | // V4L2 requires 64 byte alignment for USERPTR buffers. |
Austin Schuh | e8d44ff | 2022-12-25 22:20:02 -0800 | [diff] [blame] | 17 | // |
| 18 | // rockpi v4l2 requires 128 byte alignment for USERPTR buffers. |
| 19 | static constexpr size_t kChannelDataAlignment = 128; |
Brian Silverman | a1652f3 | 2020-01-29 20:41:44 -0800 | [diff] [blame] | 20 | |
| 21 | template <typename T> |
| 22 | inline void CheckChannelDataAlignment(T *data, size_t size) { |
| 23 | CHECK_EQ((reinterpret_cast<uintptr_t>(data) + size) % kChannelDataAlignment, |
| 24 | 0u) |
| 25 | << ": data pointer is not end aligned as it should be: " << data << " + " |
| 26 | << size; |
| 27 | } |
| 28 | |
| 29 | // Aligns the beginning of a channel data buffer. There must be |
| 30 | // kChannelDataAlignment-1 extra bytes beyond the end to potentially use after |
| 31 | // aligning it. |
| 32 | inline char *RoundChannelData(char *data, size_t size) { |
| 33 | const uintptr_t data_value = reinterpret_cast<uintptr_t>(data); |
| 34 | const uintptr_t data_end = data_value + size; |
| 35 | const uintptr_t data_end_max = data_end + (kChannelDataAlignment - 1); |
| 36 | const uintptr_t rounded_data_end = |
| 37 | data_end_max - (data_end_max % kChannelDataAlignment); |
| 38 | const uintptr_t rounded_data = rounded_data_end - size; |
| 39 | return reinterpret_cast<char *>(rounded_data); |
| 40 | } |
| 41 | |
Brian Silverman | 0eaa1da | 2020-08-12 20:03:52 -0700 | [diff] [blame] | 42 | // The size of the redzone we maintain outside each message's data to help |
| 43 | // detect out-of-bounds writes. |
| 44 | static constexpr size_t kChannelDataRedzone = 32; |
| 45 | |
Brian Silverman | a1652f3 | 2020-01-29 20:41:44 -0800 | [diff] [blame] | 46 | } // namespace aos |
| 47 | |
| 48 | #endif // AOS_IPC_LIB_DATA_ALIGNMENT_H_ |