blob: b1afdc857f5ebf5f1dcf0731470f0fbd629a642a [file] [log] [blame]
Austin Schuh25356e22019-09-11 19:27:07 -07001#ifndef AOS_IPC_LIB_INDEX_H_
2#define AOS_IPC_LIB_INDEX_H_
3
4#include <sys/types.h>
5#include <atomic>
Austin Schuh20b2b082019-09-11 20:42:56 -07006#include <string>
Austin Schuh25356e22019-09-11 19:27:07 -07007
8namespace aos {
9namespace ipc_lib {
10
11struct AtomicQueueIndex;
12class AtomicIndex;
13class Index;
14
15namespace testing {
16class QueueIndexTest;
17} // namespace testing
18
19// There are 2 types of indices in the queue. 1 is the index into the overall
20// queue. If we have sent 1,000,005 messages, this is that number.
21//
22// The other is the index into the message list. This is essentially a message
23// pointer. It has some of the lower bits of the queue index encoded into it as
24// a safeguard to detect if someone re-used a message out from under us and we
25// couldn't tell otherwise. It is used to map a queue index to a message index.
26//
27// Each of these index types has an atomic version and a non-atomic. The atomic
28// version is a wrapper around a uint32_t to hang helper functions off of.
29// The non-atomic version contains all the logic. These are all in the header
30// file to encourage the compiler to inline aggressively.
31//
32// The user should very infrequently be manipulating the values of these
33// directly. Use the classes instead to do the heavy lifting.
34
35// Structure for holding the index into the queue.
36class QueueIndex {
37 public:
38 // Returns an invalid queue element which uses a reserved value.
39 static QueueIndex Invalid() { return QueueIndex(0xffffffff, 0); }
40 // Returns a queue element pointing to 0.
41 static QueueIndex Zero(uint32_t count) { return QueueIndex(0, count); }
42
43 // Returns true if the index is valid.
44 bool valid() const { return index_ != 0xffffffff; }
45
46 // Returns the modulo base used to wrap to avoid overlapping with the reserved
47 // number.
48 // max_value is one more than the max value we can store.
49 // count is the the number of elements in the queue.
50 static constexpr uint32_t MaxIndex(uint32_t max_value, uint32_t count) {
51 return (max_value / count) * count;
52 }
53
54 // Gets the next index.
55 QueueIndex Increment() const {
56 return IncrementBy(1u);
57 }
58
59 // Gets the nth next element.
60 QueueIndex IncrementBy(uint32_t amount) const {
61 uint32_t index = index_ + amount;
62 uint32_t max_index = MaxIndex(sentinal_value(), count_);
63
64 if (index < index_) {
65 // We wrapped. We are shifting up by 0x100000000 - MaxIndex(...).
66 // Which is equivalent to subtracting MaxIndex since everything is modular
67 // with a uint32_t.
68 index -= max_index;
69 }
70
71 // Now, wrap the remainder.
72 index = index % max_index;
73 return QueueIndex(index, count_);
74 }
75
76 // Gets the nth previous element.
77 QueueIndex DecrementBy(uint32_t amount) const {
78 uint32_t index = index_ - amount;
79 if (index > index_) {
80 // We wrapped. We are shifting down by 0x100000000 - MaxIndex(...).
81 // Which is equivalent to adding MaxIndex since everything is modular with
82 // a uint32_t.
83 index += MaxIndex(sentinal_value(), count_);
84 }
85 return QueueIndex(index, count_);
86 }
87
88 // Returns true if the lowest 16 bits of the queue index from the Index could
89 // plausibly match this queue index.
90 bool IsPlausible(uint16_t queue_index) const {
91 return valid() && (queue_index == static_cast<uint16_t>(index_ & 0xffff));
92 }
93
94 bool operator==(const QueueIndex other) const {
95 return other.index_ == index_;
96 }
97
98 bool operator!=(const QueueIndex other) const {
99 return other.index_ != index_;
100 }
101
102 // Returns the wrapped index into the queue.
103 uint32_t Wrapped() const { return index_ % count_; }
104
105 // Returns the raw index. This should be used very sparingly.
106 uint32_t index() const { return index_; }
107
Austin Schuh20b2b082019-09-11 20:42:56 -0700108 QueueIndex Clear() const { return QueueIndex(0, count_); }
109
110 // Returns a string representing the index.
111 ::std::string DebugString() const;
112
Austin Schuh25356e22019-09-11 19:27:07 -0700113 private:
114 QueueIndex(uint32_t index, uint32_t count) : index_(index), count_(count) {}
115
116 static constexpr uint32_t sentinal_value() { return 0xffffffffu; }
117
118 friend struct AtomicQueueIndex;
119 friend class Index;
120 // For testing.
121 friend class testing::QueueIndexTest;
122
123 // Index and number of elements in the queue.
124 uint32_t index_;
125 // Count is stored here rather than passed in everywhere in the hopes that the
126 // compiler completely optimizes out this class and this variable if it isn't
127 // used.
128 uint32_t count_;
129};
130
131// Atomic storage for setting and getting QueueIndex objects.
132// Count is the number of messages in the queue.
133struct AtomicQueueIndex {
134 public:
135 // Atomically reads the index without any ordering constraints.
136 QueueIndex RelaxedLoad(uint32_t count) {
137 return QueueIndex(index_.load(::std::memory_order_relaxed), count);
138 }
139
140 // Full bidirectional barriers here.
141 QueueIndex Load(uint32_t count) { return QueueIndex(index_.load(), count); }
142 inline void Store(QueueIndex value) { index_.store(value.index_); }
143
144 // Invalidates the element unconditionally.
145 inline void Invalidate() { Store(QueueIndex::Invalid()); }
146
147 // Swaps expected for index atomically. Returns true on success, false
148 // otherwise.
149 inline bool CompareAndExchangeStrong(QueueIndex expected, QueueIndex index) {
150 return index_.compare_exchange_strong(expected.index_, index.index_);
151 }
152
153 private:
154 ::std::atomic<uint32_t> index_;
155};
156
157// Structure holding the queue index and the index into the message list.
158class Index {
159 public:
160 // Constructs an Index. queue_index is the QueueIndex of this message, and
161 // message_index is the index into the messages structure.
162 Index(QueueIndex queue_index, uint16_t message_index)
163 : Index(queue_index.index_, message_index) {}
164 Index(uint32_t queue_index, uint16_t message_index)
165 : index_((queue_index & 0xffff) |
166 (static_cast<uint32_t>(message_index) << 16)) {}
167
168 // Index of this message in the message array.
169 uint16_t message_index() const { return (index_ >> 16) & 0xffff; }
170
171 // Lowest 16 bits of the queue index of this message in the queue.
172 uint16_t queue_index() const { return index_ & 0xffff; }
173
174 // Returns true if the provided queue index plausibly represents this Index.
175 bool IsPlausible(QueueIndex queue_index) const {
176 return queue_index.IsPlausible(this->queue_index());
177 }
178
179 // Returns an invalid Index.
180 static Index Invalid() { return Index(sentinal_value()); }
181 // Checks if this Index is valid or not.
182 bool valid() const { return index_ != sentinal_value(); }
183
184 // Returns the raw Index. This should only be used for debug.
185 uint32_t get() const { return index_; }
186
187 // Returns the maximum number of messages we can store before overflowing.
188 static constexpr uint16_t MaxMessages() { return 0xfffe; }
189
190 bool operator==(const Index other) const { return other.index_ == index_; }
191
Austin Schuh20b2b082019-09-11 20:42:56 -0700192 // Returns a string representing the index.
193 ::std::string DebugString() const;
194
Austin Schuh25356e22019-09-11 19:27:07 -0700195 private:
196 Index(uint32_t index)
197 : index_(index) {}
198
199 friend class AtomicIndex;
200
201 static constexpr uint32_t sentinal_value() { return 0xffffffffu; }
202
203 // Note: a value of 0xffffffff is a sentinal to represent an invalid entry.
204 // This works because we would need to have a queue index of 0x*ffff, *and*
205 // have 0xffff messages in the message list. That constraint is easy to
206 // enforce by limiting the max messages.
207 uint32_t index_;
208};
209
210// Atomic storage for setting and getting Index objects.
211class AtomicIndex {
212 public:
213 // Stores and loads atomically without ordering constraints.
214 Index RelaxedLoad() {
215 return Index(index_.load(::std::memory_order_relaxed));
216 }
217 void RelaxedStore(Index index) {
218 index_.store(index.index_, ::std::memory_order_relaxed);
219 }
220
221 // Invalidates the index atomically, but without any ordering constraints.
222 void RelaxedInvalidate() { RelaxedStore(Index::Invalid()); }
223
224 // Full bidirectional barriers here.
Austin Schuh20b2b082019-09-11 20:42:56 -0700225 void Invalidate() { Store(Index::Invalid()); }
Austin Schuh25356e22019-09-11 19:27:07 -0700226 void Store(Index index) { index_.store(index.index_); }
227 Index Load() { return Index(index_.load()); }
228
229
230 // Swaps expected for index atomically. Returns true on success, false
231 // otherwise.
232 inline bool CompareAndExchangeStrong(Index expected, Index index) {
233 return index_.compare_exchange_strong(expected.index_, index.index_);
234 }
235
236 private:
237 ::std::atomic<uint32_t> index_;
238};
239
240} // namespace ipc_lib
241} // namespace aos
242
243#endif // AOS_IPC_LIB_INDEX_H_