blob: 9cbfa23b8aa13f2b961d4e131ce7ff61bef15351 [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
Austin Schuh99f7c6a2024-06-25 22:07:44 -07004#include "absl/log/check.h"
5#include "absl/log/log.h"
Brian Silvermana1652f32020-01-29 20:41:44 -08006
7namespace 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 Schuhe8d44ff2022-12-25 22:20:02 -080013// 128 is a reasonable choice for now:
Brian Silvermana1652f32020-01-29 20:41:44 -080014// 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 Schuhe8d44ff2022-12-25 22:20:02 -080017//
18// rockpi v4l2 requires 128 byte alignment for USERPTR buffers.
19static constexpr size_t kChannelDataAlignment = 128;
Brian Silvermana1652f32020-01-29 20:41:44 -080020
21template <typename T>
22inline 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.
32inline 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 Silverman0eaa1da2020-08-12 20:03:52 -070042// The size of the redzone we maintain outside each message's data to help
43// detect out-of-bounds writes.
44static constexpr size_t kChannelDataRedzone = 32;
45
Brian Silvermana1652f32020-01-29 20:41:44 -080046} // namespace aos
47
48#endif // AOS_IPC_LIB_DATA_ALIGNMENT_H_