blob: 7d979eafb30f6a89c873383140365985c0d7306f [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.
Brian Silverman2035de72019-12-18 21:39:14 -0800141 QueueIndex Load(uint32_t count) {
142 return QueueIndex(index_.load(::std::memory_order_acquire), count);
143 }
144 inline void Store(QueueIndex value) {
145 index_.store(value.index_, ::std::memory_order_release);
146 }
Austin Schuh25356e22019-09-11 19:27:07 -0700147
148 // Invalidates the element unconditionally.
149 inline void Invalidate() { Store(QueueIndex::Invalid()); }
150
151 // Swaps expected for index atomically. Returns true on success, false
152 // otherwise.
153 inline bool CompareAndExchangeStrong(QueueIndex expected, QueueIndex index) {
Brian Silverman2035de72019-12-18 21:39:14 -0800154 return index_.compare_exchange_strong(expected.index_, index.index_,
155 ::std::memory_order_acq_rel);
Austin Schuh25356e22019-09-11 19:27:07 -0700156 }
157
158 private:
159 ::std::atomic<uint32_t> index_;
160};
161
162// Structure holding the queue index and the index into the message list.
163class Index {
164 public:
165 // Constructs an Index. queue_index is the QueueIndex of this message, and
166 // message_index is the index into the messages structure.
167 Index(QueueIndex queue_index, uint16_t message_index)
168 : Index(queue_index.index_, message_index) {}
169 Index(uint32_t queue_index, uint16_t message_index)
170 : index_((queue_index & 0xffff) |
171 (static_cast<uint32_t>(message_index) << 16)) {}
172
173 // Index of this message in the message array.
174 uint16_t message_index() const { return (index_ >> 16) & 0xffff; }
175
176 // Lowest 16 bits of the queue index of this message in the queue.
177 uint16_t queue_index() const { return index_ & 0xffff; }
178
179 // Returns true if the provided queue index plausibly represents this Index.
180 bool IsPlausible(QueueIndex queue_index) const {
181 return queue_index.IsPlausible(this->queue_index());
182 }
183
184 // Returns an invalid Index.
185 static Index Invalid() { return Index(sentinal_value()); }
186 // Checks if this Index is valid or not.
187 bool valid() const { return index_ != sentinal_value(); }
188
189 // Returns the raw Index. This should only be used for debug.
190 uint32_t get() const { return index_; }
191
192 // Returns the maximum number of messages we can store before overflowing.
193 static constexpr uint16_t MaxMessages() { return 0xfffe; }
194
195 bool operator==(const Index other) const { return other.index_ == index_; }
196
Austin Schuh20b2b082019-09-11 20:42:56 -0700197 // Returns a string representing the index.
198 ::std::string DebugString() const;
199
Austin Schuh25356e22019-09-11 19:27:07 -0700200 private:
201 Index(uint32_t index)
202 : index_(index) {}
203
204 friend class AtomicIndex;
205
206 static constexpr uint32_t sentinal_value() { return 0xffffffffu; }
207
208 // Note: a value of 0xffffffff is a sentinal to represent an invalid entry.
209 // This works because we would need to have a queue index of 0x*ffff, *and*
210 // have 0xffff messages in the message list. That constraint is easy to
211 // enforce by limiting the max messages.
212 uint32_t index_;
213};
214
215// Atomic storage for setting and getting Index objects.
216class AtomicIndex {
217 public:
218 // Stores and loads atomically without ordering constraints.
219 Index RelaxedLoad() {
220 return Index(index_.load(::std::memory_order_relaxed));
221 }
222 void RelaxedStore(Index index) {
223 index_.store(index.index_, ::std::memory_order_relaxed);
224 }
225
226 // Invalidates the index atomically, but without any ordering constraints.
227 void RelaxedInvalidate() { RelaxedStore(Index::Invalid()); }
228
Brian Silverman2035de72019-12-18 21:39:14 -0800229 // Full barriers here.
Austin Schuh20b2b082019-09-11 20:42:56 -0700230 void Invalidate() { Store(Index::Invalid()); }
Brian Silverman2035de72019-12-18 21:39:14 -0800231 void Store(Index index) {
232 index_.store(index.index_, ::std::memory_order_release);
233 }
234 Index Load() { return Index(index_.load(::std::memory_order_acquire)); }
Austin Schuh25356e22019-09-11 19:27:07 -0700235
236 // Swaps expected for index atomically. Returns true on success, false
237 // otherwise.
238 inline bool CompareAndExchangeStrong(Index expected, Index index) {
Brian Silverman2035de72019-12-18 21:39:14 -0800239 return index_.compare_exchange_strong(expected.index_, index.index_,
240 ::std::memory_order_acq_rel);
Austin Schuh25356e22019-09-11 19:27:07 -0700241 }
242
243 private:
244 ::std::atomic<uint32_t> index_;
245};
246
247} // namespace ipc_lib
248} // namespace aos
249
250#endif // AOS_IPC_LIB_INDEX_H_