Zth (libzth)
Loading...
Searching...
No Matches
regs.h
Go to the documentation of this file.
1#ifndef ZTH_REGS_H
2#define ZTH_REGS_H
3/*
4 * SPDX-FileCopyrightText: 2019-2026 Jochem Rutgers
5 *
6 * SPDX-License-Identifier: MPL-2.0
7 */
8
9#include <libzth/macros.h>
10
11#ifdef __cplusplus
12# include <libzth/util.h>
13
19namespace zth {
20
30template <typename T, uintptr_t Addr, typename Fields>
31struct Register {
32 typedef T type;
33
34 Register() noexcept
35 {
36 static_assert(sizeof(Fields) == sizeof(type), "");
37 read();
38 }
39
40 constexpr explicit Register(type v) noexcept
41 : value(v)
42 {}
43
44 union {
46 Fields field;
47 };
48
49 static type volatile* r() noexcept
50 {
51 return (type volatile*)Addr;
52 }
53
54 type read() const noexcept
55 {
56 return *r();
57 }
58
59 type read() noexcept
60 {
61 return value = *r();
62 }
63
64 void write() const noexcept
65 {
66 *r() = value;
67 }
68
69 void write(type v) const noexcept
70 {
71 *r() = v;
72 }
73
74 void write(type v) noexcept
75 {
76 *r() = value = v;
77 }
78
79 operator type() const noexcept
80 {
81 return value;
82 }
83};
84
85# if defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
86// In case of little-endian, gcc puts the last field at the highest bits.
87// This is counter intuitive for registers. Reverse them.
88# define ZTH_REG_BITFIELDS(...) REVERSE(__VA_ARGS__)
89# else
90# define ZTH_REG_BITFIELDS(...) __VA_ARGS__
91# endif
92
116# define ZTH_REG_DEFINE(T, name, addr, fields...) \
117 struct name##__type { \
118 T ZTH_REG_BITFIELDS(fields); \
119 } __attribute__((packed)); \
120 struct name : public zth::Register<T, addr, name##__type> { \
121 typedef zth::Register<T, addr, name##__type> base; \
122 using typename base::type; \
123 name() noexcept \
124 : base() \
125 {} \
126 constexpr explicit name(type v) noexcept \
127 : base(v) \
128 {} \
129 };
130
131} // namespace zth
132#endif // __cplusplus
133#endif // ZTH_REGS_H
Helper class to read/write (bitfields in) hardware registers.
Definition regs.h:31
static type volatile * r() noexcept
Definition regs.h:49
constexpr Register(type v) noexcept
Definition regs.h:40
type read() noexcept
Definition regs.h:59
void write(type v) noexcept
Definition regs.h:74
Fields field
Definition regs.h:46
type read() const noexcept
Definition regs.h:54
Register() noexcept
Definition regs.h:34
void write(type v) const noexcept
Definition regs.h:69
void write() const noexcept
Definition regs.h:64
type value
Definition regs.h:45