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