blob: f380848c388a60711ca1176a555e2399992f6756 [file] [log] [blame]
Austin Schuh20b2b082019-09-11 20:42:56 -07001#include "aos/ipc_lib/lockless_queue.h"
2
3#include <linux/futex.h>
4#include <sys/types.h>
5#include <syscall.h>
6#include <unistd.h>
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07007
Austin Schuh20b2b082019-09-11 20:42:56 -07008#include <algorithm>
9#include <iomanip>
10#include <iostream>
11#include <sstream>
12
Austin Schuhbe416742020-10-03 17:24:26 -070013#include "absl/strings/escaping.h"
Austin Schuh20b2b082019-09-11 20:42:56 -070014#include "aos/ipc_lib/lockless_queue_memory.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070015#include "aos/realtime.h"
Austin Schuh20b2b082019-09-11 20:42:56 -070016#include "aos/util/compiler_memory_barrier.h"
Brian Silverman001f24d2020-08-12 19:33:20 -070017#include "gflags/gflags.h"
Austin Schuhf257f3c2019-10-27 21:00:43 -070018#include "glog/logging.h"
Austin Schuh20b2b082019-09-11 20:42:56 -070019
Brian Silverman001f24d2020-08-12 19:33:20 -070020DEFINE_bool(dump_lockless_queue_data, false,
21 "If true, print the data out when dumping the queue.");
22
Austin Schuh20b2b082019-09-11 20:42:56 -070023namespace aos {
24namespace ipc_lib {
Austin Schuh20b2b082019-09-11 20:42:56 -070025namespace {
26
Brian Silvermanfafe1fa2019-12-18 21:42:18 -080027class GrabQueueSetupLockOrDie {
28 public:
29 GrabQueueSetupLockOrDie(LocklessQueueMemory *memory) : memory_(memory) {
30 const int result = mutex_grab(&(memory->queue_setup_lock));
31 CHECK(result == 0 || result == 1) << ": " << result;
32 }
Austin Schuh20b2b082019-09-11 20:42:56 -070033
Brian Silvermanfafe1fa2019-12-18 21:42:18 -080034 ~GrabQueueSetupLockOrDie() { mutex_unlock(&(memory_->queue_setup_lock)); }
35
36 GrabQueueSetupLockOrDie(const GrabQueueSetupLockOrDie &) = delete;
37 GrabQueueSetupLockOrDie &operator=(const GrabQueueSetupLockOrDie &) = delete;
38
39 private:
40 LocklessQueueMemory *const memory_;
41};
42
Brian Silverman177567e2020-08-12 19:51:33 -070043bool IsPinned(LocklessQueueMemory *memory, Index index) {
44 DCHECK(index.valid());
45 const size_t queue_size = memory->queue_size();
46 const QueueIndex message_index =
47 memory->GetMessage(index)->header.queue_index.Load(queue_size);
48 if (!message_index.valid()) {
49 return false;
50 }
51 DCHECK(memory->GetQueue(message_index.Wrapped())->Load() != index)
52 << ": Message is in the queue";
53 for (int pinner_index = 0;
54 pinner_index < static_cast<int>(memory->config.num_pinners);
55 ++pinner_index) {
56 ipc_lib::Pinner *const pinner = memory->GetPinner(pinner_index);
57
58 if (pinner->pinned.RelaxedLoad(queue_size) == message_index) {
59 return true;
60 }
61 }
62 return false;
63}
64
65// Ensures sender->scratch_index (which must contain to_replace) is not pinned.
66//
67// Returns the new scratch_index value.
68Index SwapPinnedSenderScratch(LocklessQueueMemory *const memory,
69 ipc_lib::Sender *const sender,
70 const Index to_replace) {
71 // If anybody's trying to pin this message, then grab a message from a pinner
72 // to write into instead, and leave the message we pulled out of the queue
73 // (currently in our scratch_index) with a pinner.
74 //
75 // This loop will terminate in at most one iteration through the pinners in
76 // any steady-state configuration of the memory. There are only as many
77 // Pinner::pinned values to worry about as there are Pinner::scratch_index
78 // values to check against, plus to_replace, which means there will always be
79 // a free one. We might have to make multiple passes if things are being
80 // changed concurrently though, but nobody dying can make this loop fail to
81 // terminate (because the number of processes that can die is bounded, because
82 // no new ones can start while we've got the lock).
83 for (int pinner_index = 0; true;
84 pinner_index = (pinner_index + 1) % memory->config.num_pinners) {
85 if (!IsPinned(memory, to_replace)) {
86 // No pinners on our current scratch_index, so we're fine now.
87 VLOG(3) << "No pinners: " << to_replace.DebugString();
88 return to_replace;
89 }
90
91 ipc_lib::Pinner *const pinner = memory->GetPinner(pinner_index);
92
93 const Index pinner_scratch = pinner->scratch_index.RelaxedLoad();
94 CHECK(pinner_scratch.valid())
95 << ": Pinner scratch_index should always be valid";
96 if (IsPinned(memory, pinner_scratch)) {
97 // Wouldn't do us any good to swap with this one, so don't bother, and
98 // move onto the next one.
99 VLOG(3) << "Also pinned: " << pinner_scratch.DebugString();
100 continue;
101 }
102
103 sender->to_replace.RelaxedStore(pinner_scratch);
104 aos_compiler_memory_barrier();
105 // Give the pinner the message (which is currently in
106 // sender->scratch_index).
107 if (!pinner->scratch_index.CompareAndExchangeStrong(pinner_scratch,
108 to_replace)) {
109 // Somebody swapped into this pinner before us. The new value is probably
110 // pinned, so we don't want to look at it again immediately.
111 VLOG(3) << "Pinner " << pinner_index
112 << " scratch_index changed: " << pinner_scratch.DebugString()
113 << ", " << to_replace.DebugString();
114 sender->to_replace.RelaxedInvalidate();
115 continue;
116 }
117 aos_compiler_memory_barrier();
118 // Now update the sender's scratch space and record that we succeeded.
119 sender->scratch_index.Store(pinner_scratch);
120 aos_compiler_memory_barrier();
121 // And then record that we succeeded, but definitely after the above
122 // store.
123 sender->to_replace.RelaxedInvalidate();
124 VLOG(3) << "Got new scratch message: " << pinner_scratch.DebugString();
125
126 // If it's in a pinner's scratch_index, it should not be in the queue, which
127 // means nobody new can pin it for real. However, they can still attempt to
128 // pin it, which means we can't verify !IsPinned down here.
129
130 return pinner_scratch;
131 }
132}
133
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700134// Returns true if it succeeded. Returns false if another sender died in the
135// middle.
136bool DoCleanup(LocklessQueueMemory *memory, const GrabQueueSetupLockOrDie &) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800137 // Make sure we start looking at shared memory fresh right now. We'll handle
138 // people dying partway through by either cleaning up after them or not, but
139 // we want to ensure we clean up after anybody who has already died when we
140 // start.
141 aos_compiler_memory_barrier();
142
Austin Schuh20b2b082019-09-11 20:42:56 -0700143 const size_t num_senders = memory->num_senders();
Brian Silverman177567e2020-08-12 19:51:33 -0700144 const size_t num_pinners = memory->num_pinners();
Austin Schuh20b2b082019-09-11 20:42:56 -0700145 const size_t queue_size = memory->queue_size();
146 const size_t num_messages = memory->num_messages();
147
148 // There are a large number of crazy cases here for how things can go wrong
149 // and how we have to recover. They either require us to keep extra track of
150 // what is going on, slowing down the send path, or require a large number of
151 // cases.
152 //
153 // The solution here is to not over-think it. This is running while not real
154 // time during construction. It is allowed to be slow. It will also very
155 // rarely trigger. There is a small uS window where process death is
156 // ambiguous.
157 //
158 // So, build up a list N long, where N is the number of messages. Search
159 // through the entire queue and the sender list (ignoring any dead senders),
160 // and mark down which ones we have seen. Once we have seen all the messages
161 // except the N dead senders, we know which messages are dead. Because the
162 // queue is active while we do this, it may take a couple of go arounds to see
163 // everything.
164
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700165 ::std::vector<bool> need_recovery(num_senders, false);
166
Austin Schuh20b2b082019-09-11 20:42:56 -0700167 // Do the easy case. Find all senders who have died. See if they are either
168 // consistent already, or if they have copied over to_replace to the scratch
169 // index, but haven't cleared to_replace. Count them.
170 size_t valid_senders = 0;
171 for (size_t i = 0; i < num_senders; ++i) {
172 Sender *sender = memory->GetSender(i);
173 const uint32_t tid =
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800174 __atomic_load_n(&(sender->tid.futex), __ATOMIC_ACQUIRE);
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700175 if (!(tid & FUTEX_OWNER_DIED)) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700176 // Not dead.
177 ++valid_senders;
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700178 continue;
Austin Schuh20b2b082019-09-11 20:42:56 -0700179 }
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700180 VLOG(3) << "Found an easy death for sender " << i;
181 // We can do a relaxed load here because we're the only person touching
182 // this sender at this point.
183 const Index to_replace = sender->to_replace.RelaxedLoad();
184 const Index scratch_index = sender->scratch_index.Load();
185
186 // I find it easiest to think about this in terms of the set of observable
187 // states. The main code progresses through the following states:
188
189 // 1) scratch_index = xxx
190 // to_replace = invalid
191 // This is unambiguous. Already good.
192
193 // 2) scratch_index = xxx
194 // to_replace = yyy
195 // Very ambiguous. Is xxx or yyy the correct one? Need to either roll
196 // this forwards or backwards.
197
198 // 3) scratch_index = yyy
199 // to_replace = yyy
200 // We are in the act of moving to_replace to scratch_index, but didn't
201 // finish. Easy.
Brian Silverman177567e2020-08-12 19:51:33 -0700202 //
203 // If doing a pinner swap, we've definitely done it.
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700204
205 // 4) scratch_index = yyy
206 // to_replace = invalid
207 // Finished, but died. Looks like 1)
208
Brian Silverman177567e2020-08-12 19:51:33 -0700209 // Swapping with a pinner's scratch_index passes through the same states.
210 // We just need to ensure the message that ends up in the senders's
211 // scratch_index isn't pinned, using the same code as sending does.
212
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700213 // Any cleanup code needs to follow the same set of states to be robust to
214 // death, so death can be restarted.
215
216 if (!to_replace.valid()) {
217 // 1) or 4). Make sure we aren't corrupted and declare victory.
218 CHECK(scratch_index.valid());
219
Brian Silverman177567e2020-08-12 19:51:33 -0700220 // If it's in 1) with a pinner, the sender might have a pinned message,
221 // so fix that.
222 SwapPinnedSenderScratch(memory, sender, scratch_index);
223
224 // If it's in 4), it may not have completed this step yet. This will
225 // always be a NOP if it's in 1), verified by a DCHECK.
226 memory->GetMessage(scratch_index)->header.queue_index.RelaxedInvalidate();
227
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700228 __atomic_store_n(&(sender->tid.futex), 0, __ATOMIC_RELEASE);
229 ++valid_senders;
230 continue;
231 }
232
233 // Could be 2) or 3) at this point.
234
235 if (to_replace == scratch_index) {
236 // 3) for sure.
237 // Just need to invalidate to_replace to finish.
238 sender->to_replace.Invalidate();
239
Brian Silverman177567e2020-08-12 19:51:33 -0700240 // Make sure to indicate it's an unused message before a sender gets its
241 // hands on it.
242 memory->GetMessage(scratch_index)->header.queue_index.RelaxedInvalidate();
243 aos_compiler_memory_barrier();
244
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700245 // And mark that we succeeded.
246 __atomic_store_n(&(sender->tid.futex), 0, __ATOMIC_RELEASE);
247 ++valid_senders;
248 continue;
249 }
250
251 // Must be 2). Mark it for later.
252 need_recovery[i] = true;
Austin Schuh20b2b082019-09-11 20:42:56 -0700253 }
254
Brian Silverman177567e2020-08-12 19:51:33 -0700255 // Cleaning up pinners is easy. We don't actually have to do anything, but
256 // invalidating its pinned field might help catch bugs elsewhere trying to
257 // read it before it's set.
258 for (size_t i = 0; i < num_pinners; ++i) {
259 Pinner *const pinner = memory->GetPinner(i);
260 const uint32_t tid =
261 __atomic_load_n(&(pinner->tid.futex), __ATOMIC_ACQUIRE);
262 if (!(tid & FUTEX_OWNER_DIED)) {
263 continue;
264 }
265 pinner->pinned.Invalidate();
266 __atomic_store_n(&(pinner->tid.futex), 0, __ATOMIC_RELEASE);
267 }
268
Austin Schuh20b2b082019-09-11 20:42:56 -0700269 // If all the senders are (or were made) good, there is no need to do the hard
270 // case.
271 if (valid_senders == num_senders) {
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700272 return true;
Austin Schuh20b2b082019-09-11 20:42:56 -0700273 }
274
Alex Perrycb7da4b2019-08-28 19:35:56 -0700275 VLOG(3) << "Starting hard cleanup";
Austin Schuh20b2b082019-09-11 20:42:56 -0700276
277 size_t num_accounted_for = 0;
278 size_t num_missing = 0;
279 ::std::vector<bool> accounted_for(num_messages, false);
280
281 while ((num_accounted_for + num_missing) != num_messages) {
282 num_missing = 0;
283 for (size_t i = 0; i < num_senders; ++i) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800284 Sender *const sender = memory->GetSender(i);
Austin Schuh20b2b082019-09-11 20:42:56 -0700285 const uint32_t tid =
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800286 __atomic_load_n(&(sender->tid.futex), __ATOMIC_ACQUIRE);
Austin Schuh20b2b082019-09-11 20:42:56 -0700287 if (tid & FUTEX_OWNER_DIED) {
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700288 if (!need_recovery[i]) {
289 return false;
290 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700291 ++num_missing;
Brian Silverman177567e2020-08-12 19:51:33 -0700292 continue;
Austin Schuh20b2b082019-09-11 20:42:56 -0700293 }
Brian Silverman177567e2020-08-12 19:51:33 -0700294 CHECK(!need_recovery[i]) << ": Somebody else recovered a sender: " << i;
295 // We can do a relaxed load here because we're the only person touching
296 // this sender at this point, if it matters. If it's not a dead sender,
297 // then any message it ever has will eventually be accounted for if we
298 // make enough tries through the outer loop.
299 const Index scratch_index = sender->scratch_index.RelaxedLoad();
300 if (!accounted_for[scratch_index.message_index()]) {
301 ++num_accounted_for;
302 }
303 accounted_for[scratch_index.message_index()] = true;
Austin Schuh20b2b082019-09-11 20:42:56 -0700304 }
305
306 for (size_t i = 0; i < queue_size; ++i) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800307 // Same logic as above for scratch_index applies here too.
Austin Schuh20b2b082019-09-11 20:42:56 -0700308 const Index index = memory->GetQueue(i)->RelaxedLoad();
309 if (!accounted_for[index.message_index()]) {
310 ++num_accounted_for;
311 }
312 accounted_for[index.message_index()] = true;
313 }
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700314
Brian Silverman177567e2020-08-12 19:51:33 -0700315 for (size_t pinner_index = 0; pinner_index < num_pinners; ++pinner_index) {
316 // Same logic as above for scratch_index applies here too.
317 const Index index =
318 memory->GetPinner(pinner_index)->scratch_index.RelaxedLoad();
319 if (!accounted_for[index.message_index()]) {
320 ++num_accounted_for;
321 }
322 accounted_for[index.message_index()] = true;
323 }
324
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700325 CHECK_LE(num_accounted_for + num_missing, num_messages);
Austin Schuh20b2b082019-09-11 20:42:56 -0700326 }
327
328 while (num_missing != 0) {
329 const size_t starting_num_missing = num_missing;
330 for (size_t i = 0; i < num_senders; ++i) {
331 Sender *sender = memory->GetSender(i);
332 const uint32_t tid =
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800333 __atomic_load_n(&(sender->tid.futex), __ATOMIC_ACQUIRE);
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700334 if (!(tid & FUTEX_OWNER_DIED)) {
335 CHECK(!need_recovery[i]) << ": Somebody else recovered a sender: " << i;
336 continue;
337 }
338 if (!need_recovery[i]) {
339 return false;
340 }
341 // We can do relaxed loads here because we're the only person touching
342 // this sender at this point.
343 const Index scratch_index = sender->scratch_index.RelaxedLoad();
344 const Index to_replace = sender->to_replace.RelaxedLoad();
Austin Schuh20b2b082019-09-11 20:42:56 -0700345
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700346 // Candidate.
347 if (to_replace.valid()) {
348 CHECK_LE(to_replace.message_index(), accounted_for.size());
349 }
350 if (scratch_index.valid()) {
351 CHECK_LE(scratch_index.message_index(), accounted_for.size());
352 }
353 if (!to_replace.valid() || accounted_for[to_replace.message_index()]) {
354 CHECK(scratch_index.valid());
355 VLOG(3) << "Sender " << i
356 << " died, to_replace is already accounted for";
357 // If both are accounted for, we are corrupt...
358 CHECK(!accounted_for[scratch_index.message_index()]);
Austin Schuh20b2b082019-09-11 20:42:56 -0700359
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700360 // to_replace is already accounted for. This means that we didn't
361 // atomically insert scratch_index into the queue yet. So
362 // invalidate to_replace.
363 sender->to_replace.Invalidate();
Brian Silverman177567e2020-08-12 19:51:33 -0700364 // Sender definitely will not have gotten here, so finish for it.
365 memory->GetMessage(scratch_index)
366 ->header.queue_index.RelaxedInvalidate();
Austin Schuh20b2b082019-09-11 20:42:56 -0700367
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700368 // And then mark this sender clean.
369 __atomic_store_n(&(sender->tid.futex), 0, __ATOMIC_RELEASE);
370 need_recovery[i] = false;
Austin Schuh20b2b082019-09-11 20:42:56 -0700371
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700372 // And account for scratch_index.
373 accounted_for[scratch_index.message_index()] = true;
374 --num_missing;
375 ++num_accounted_for;
376 } else if (!scratch_index.valid() ||
377 accounted_for[scratch_index.message_index()]) {
378 VLOG(3) << "Sender " << i
379 << " died, scratch_index is already accounted for";
380 // scratch_index is accounted for. That means we did the insert,
381 // but didn't record it.
382 CHECK(to_replace.valid());
Brian Silverman177567e2020-08-12 19:51:33 -0700383
384 // Make sure to indicate it's an unused message before a sender gets its
385 // hands on it.
386 memory->GetMessage(to_replace)->header.queue_index.RelaxedInvalidate();
387 aos_compiler_memory_barrier();
388
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700389 // Finish the transaction. Copy to_replace, then clear it.
Austin Schuh20b2b082019-09-11 20:42:56 -0700390
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700391 sender->scratch_index.Store(to_replace);
392 sender->to_replace.Invalidate();
Austin Schuh20b2b082019-09-11 20:42:56 -0700393
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700394 // And then mark this sender clean.
395 __atomic_store_n(&(sender->tid.futex), 0, __ATOMIC_RELEASE);
396 need_recovery[i] = false;
Austin Schuh20b2b082019-09-11 20:42:56 -0700397
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700398 // And account for to_replace.
399 accounted_for[to_replace.message_index()] = true;
400 --num_missing;
401 ++num_accounted_for;
402 } else {
403 VLOG(3) << "Sender " << i << " died, neither is accounted for";
404 // Ambiguous. There will be an unambiguous one somewhere that we
405 // can do first.
Austin Schuh20b2b082019-09-11 20:42:56 -0700406 }
407 }
408 // CHECK that we are making progress.
409 CHECK_NE(num_missing, starting_num_missing);
410 }
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700411 return true;
412}
413
414void Cleanup(LocklessQueueMemory *memory, const GrabQueueSetupLockOrDie &lock) {
415 // The number of iterations is bounded here because there are only a finite
416 // number of senders in existence which could die, and no new ones can be
417 // created while we're in here holding the lock.
418 while (!DoCleanup(memory, lock)) {
419 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700420}
421
422// Exposes rt_tgsigqueueinfo so we can send the signal *just* to the target
423// thread.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800424// TODO(Brian): Do directly in assembly for armhf at least for efficiency.
Austin Schuh20b2b082019-09-11 20:42:56 -0700425int rt_tgsigqueueinfo(pid_t tgid, pid_t tid, int sig, siginfo_t *si) {
426 return syscall(SYS_rt_tgsigqueueinfo, tgid, tid, sig, si);
427}
428
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700429QueueIndex ZeroOrValid(QueueIndex index) {
430 if (!index.valid()) {
431 return index.Clear();
432 }
433 return index;
434}
435
Austin Schuh20b2b082019-09-11 20:42:56 -0700436} // namespace
437
Austin Schuh4bc4f902019-12-23 18:04:51 -0800438size_t LocklessQueueConfiguration::message_size() const {
439 // Round up the message size so following data is aligned appropriately.
Brian Silverman0eaa1da2020-08-12 20:03:52 -0700440 // Make sure to leave space to align the message data. It will be aligned
441 // relative to the start of the shared memory region, but that might not be
442 // aligned for some use cases.
Brian Silvermana1652f32020-01-29 20:41:44 -0800443 return LocklessQueueMemory::AlignmentRoundUp(message_data_size +
Brian Silverman0eaa1da2020-08-12 20:03:52 -0700444 kChannelDataRedzone * 2 +
Brian Silvermana1652f32020-01-29 20:41:44 -0800445 (kChannelDataAlignment - 1)) +
Austin Schuh4bc4f902019-12-23 18:04:51 -0800446 sizeof(Message);
447}
448
Austin Schuh20b2b082019-09-11 20:42:56 -0700449size_t LocklessQueueMemorySize(LocklessQueueConfiguration config) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800450 // Round up the message size so following data is aligned appropriately.
451 config.message_data_size =
452 LocklessQueueMemory::AlignmentRoundUp(config.message_data_size);
Austin Schuh20b2b082019-09-11 20:42:56 -0700453
454 // As we build up the size, confirm that everything is aligned to the
455 // alignment requirements of the type.
456 size_t size = sizeof(LocklessQueueMemory);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800457 CHECK_EQ(size % alignof(LocklessQueueMemory), 0u);
Austin Schuh20b2b082019-09-11 20:42:56 -0700458
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800459 CHECK_EQ(size % alignof(AtomicIndex), 0u);
Austin Schuh20b2b082019-09-11 20:42:56 -0700460 size += LocklessQueueMemory::SizeOfQueue(config);
461
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800462 CHECK_EQ(size % alignof(Message), 0u);
Austin Schuh20b2b082019-09-11 20:42:56 -0700463 size += LocklessQueueMemory::SizeOfMessages(config);
464
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800465 CHECK_EQ(size % alignof(Watcher), 0u);
Austin Schuh20b2b082019-09-11 20:42:56 -0700466 size += LocklessQueueMemory::SizeOfWatchers(config);
467
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800468 CHECK_EQ(size % alignof(Sender), 0u);
Austin Schuh20b2b082019-09-11 20:42:56 -0700469 size += LocklessQueueMemory::SizeOfSenders(config);
470
Brian Silverman177567e2020-08-12 19:51:33 -0700471 CHECK_EQ(size % alignof(Pinner), 0u);
472 size += LocklessQueueMemory::SizeOfPinners(config);
473
Austin Schuh20b2b082019-09-11 20:42:56 -0700474 return size;
475}
476
Brian Silverman0eaa1da2020-08-12 20:03:52 -0700477// Calculates the starting byte for a redzone in shared memory. This starting
478// value is simply incremented for subsequent bytes.
479//
480// The result is based on the offset of the region in shared memor, to ensure it
481// is the same for each region when we generate and verify, but different for
482// each region to help catch forms of corruption like copying out-of-bounds data
483// from one place to another.
484//
485// memory is the base pointer to the shared memory. It is used to calculated
486// offsets. starting_data is the start of the redzone's data. Each one will
487// get a unique pattern.
488uint8_t RedzoneStart(const LocklessQueueMemory *memory,
489 const char *starting_data) {
490 const auto memory_int = reinterpret_cast<uintptr_t>(memory);
491 const auto starting_int = reinterpret_cast<uintptr_t>(starting_data);
492 DCHECK(starting_int >= memory_int);
493 DCHECK(starting_int < memory_int + LocklessQueueMemorySize(memory->config));
494 const uintptr_t starting_offset = starting_int - memory_int;
495 // Just XOR the lower 2 bytes. They higher-order bytes are probably 0
496 // anyways.
497 return (starting_offset & 0xFF) ^ ((starting_offset >> 8) & 0xFF);
498}
499
500// Returns true if the given redzone has invalid data.
501bool CheckRedzone(const LocklessQueueMemory *memory,
502 absl::Span<const char> redzone) {
503 uint8_t redzone_value = RedzoneStart(memory, redzone.data());
504
505 bool bad = false;
506
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700507 for (size_t i = 0; i < redzone.size() && !bad; ++i) {
Brian Silverman0eaa1da2020-08-12 20:03:52 -0700508 if (memcmp(&redzone[i], &redzone_value, 1)) {
509 bad = true;
510 }
511 ++redzone_value;
512 }
513
514 return bad;
515}
516
517// Returns true if either of message's redzones has invalid data.
518bool CheckBothRedzones(const LocklessQueueMemory *memory,
519 const Message *message) {
520 return CheckRedzone(memory,
521 message->PreRedzone(memory->message_data_size())) ||
522 CheckRedzone(memory, message->PostRedzone(memory->message_data_size(),
523 memory->message_size()));
524}
525
526// Fills the given redzone with the expected data.
527void FillRedzone(LocklessQueueMemory *memory, absl::Span<char> redzone) {
528 uint8_t redzone_value = RedzoneStart(memory, redzone.data());
529 for (size_t i = 0; i < redzone.size(); ++i) {
530 memcpy(&redzone[i], &redzone_value, 1);
531 ++redzone_value;
532 }
533
534 // Just double check that the implementations match.
535 CHECK(!CheckRedzone(memory, redzone));
536}
537
Austin Schuh20b2b082019-09-11 20:42:56 -0700538LocklessQueueMemory *InitializeLocklessQueueMemory(
539 LocklessQueueMemory *memory, LocklessQueueConfiguration config) {
540 // Everything should be zero initialized already. So we just need to fill
541 // everything out properly.
542
Brian Silvermanc57ff0a2020-04-28 16:45:13 -0700543 // This is the UID we will use for checking signal-sending permission
544 // compatibility.
545 //
546 // The manpage says:
547 // For a process to have permission to send a signal, it must either be
548 // privileged [...], or the real or effective user ID of the sending process
549 // must equal the real or saved set-user-ID of the target process.
550 //
551 // Processes typically initialize a queue in random order as they start up.
552 // This means we need an algorithm for verifying all processes have
553 // permissions to send each other signals which gives the same answer no
554 // matter what order they attach in. We would also like to avoid maintaining a
555 // shared list of the UIDs of all processes.
556 //
557 // To do this while still giving sufficient flexibility for all current use
558 // cases, we track a single UID for the queue. All processes with a matching
559 // euid+suid must have this UID. Any processes with distinct euid/suid must
560 // instead have a matching ruid. This guarantees signals can be sent between
561 // all processes attached to the queue.
562 //
563 // In particular, this allows a process to change only its euid (to interact
564 // with a queue) while still maintaining privileges via its ruid. However, it
565 // can only use privileges in ways that do not require changing the euid back,
566 // because while the euid is different it will not be able to receive signals.
567 // We can't actually verify that, but we can sanity check that things are
568 // valid when the queue is initialized.
569
570 uid_t uid;
571 {
572 uid_t ruid, euid, suid;
573 PCHECK(getresuid(&ruid, &euid, &suid) == 0);
574 // If these are equal, then use them, even if that's different from the real
575 // UID. This allows processes to keep a real UID of 0 (to have permissions
576 // to perform system-level changes) while still being able to communicate
577 // with processes running unprivileged as a distinct user.
578 if (euid == suid) {
579 uid = euid;
580 VLOG(1) << "Using euid==suid " << uid;
581 } else {
582 uid = ruid;
583 VLOG(1) << "Using ruid " << ruid;
584 }
585 }
586
Austin Schuh20b2b082019-09-11 20:42:56 -0700587 // Grab the mutex. We don't care if the previous reader died. We are going
588 // to check everything anyways.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800589 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory);
Austin Schuh20b2b082019-09-11 20:42:56 -0700590
591 if (!memory->initialized) {
592 // TODO(austin): Check these for out of bounds.
593 memory->config.num_watchers = config.num_watchers;
594 memory->config.num_senders = config.num_senders;
Brian Silverman177567e2020-08-12 19:51:33 -0700595 memory->config.num_pinners = config.num_pinners;
Austin Schuh20b2b082019-09-11 20:42:56 -0700596 memory->config.queue_size = config.queue_size;
Austin Schuh4bc4f902019-12-23 18:04:51 -0800597 memory->config.message_data_size = config.message_data_size;
Austin Schuh20b2b082019-09-11 20:42:56 -0700598
599 const size_t num_messages = memory->num_messages();
600 // There need to be at most MaxMessages() messages allocated.
601 CHECK_LE(num_messages, Index::MaxMessages());
602
603 for (size_t i = 0; i < num_messages; ++i) {
Brian Silverman0eaa1da2020-08-12 20:03:52 -0700604 Message *const message =
605 memory->GetMessage(Index(QueueIndex::Zero(memory->queue_size()), i));
606 message->header.queue_index.Invalidate();
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700607 message->header.monotonic_sent_time = monotonic_clock::min_time;
Brian Silverman0eaa1da2020-08-12 20:03:52 -0700608 FillRedzone(memory, message->PreRedzone(memory->message_data_size()));
609 FillRedzone(memory, message->PostRedzone(memory->message_data_size(),
610 memory->message_size()));
Austin Schuh20b2b082019-09-11 20:42:56 -0700611 }
612
613 for (size_t i = 0; i < memory->queue_size(); ++i) {
614 // Make the initial counter be the furthest away number. That means that
615 // index 0 should be 0xffff, 1 should be 0, etc.
616 memory->GetQueue(i)->Store(Index(QueueIndex::Zero(memory->queue_size())
617 .IncrementBy(i)
618 .DecrementBy(memory->queue_size()),
619 i));
620 }
621
622 memory->next_queue_index.Invalidate();
Brian Silvermanc57ff0a2020-04-28 16:45:13 -0700623 memory->uid = uid;
Austin Schuh20b2b082019-09-11 20:42:56 -0700624
625 for (size_t i = 0; i < memory->num_senders(); ++i) {
626 ::aos::ipc_lib::Sender *s = memory->GetSender(i);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800627 // Nobody else can possibly be touching these because we haven't set
628 // initialized to true yet.
629 s->scratch_index.RelaxedStore(Index(0xffff, i + memory->queue_size()));
Austin Schuh20b2b082019-09-11 20:42:56 -0700630 s->to_replace.RelaxedInvalidate();
631 }
632
Brian Silverman177567e2020-08-12 19:51:33 -0700633 for (size_t i = 0; i < memory->num_pinners(); ++i) {
634 ::aos::ipc_lib::Pinner *pinner = memory->GetPinner(i);
635 // Nobody else can possibly be touching these because we haven't set
636 // initialized to true yet.
637 pinner->scratch_index.RelaxedStore(
638 Index(0xffff, i + memory->num_senders() + memory->queue_size()));
639 pinner->pinned.Invalidate();
640 }
641
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800642 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -0700643 // Signal everything is done. This needs to be done last, so if we die, we
644 // redo initialization.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800645 memory->initialized = true;
Austin Schuh3328d132020-02-28 13:54:57 -0800646 } else {
Brian Silvermanc57ff0a2020-04-28 16:45:13 -0700647 CHECK_EQ(uid, memory->uid) << ": UIDs must match for all processes";
Austin Schuh20b2b082019-09-11 20:42:56 -0700648 }
649
Austin Schuh20b2b082019-09-11 20:42:56 -0700650 return memory;
651}
652
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700653void LocklessQueue::Initialize() {
654 InitializeLocklessQueueMemory(memory_, config_);
655}
Austin Schuh20b2b082019-09-11 20:42:56 -0700656
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700657LocklessQueueWatcher::~LocklessQueueWatcher() {
658 if (watcher_index_ == -1) {
659 return;
660 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700661
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700662 // Since everything is self consistent, all we need to do is make sure nobody
663 // else is running. Someone dying will get caught in the generic consistency
664 // check.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800665 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory_);
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700666
667 // Make sure we are registered.
668 CHECK_NE(watcher_index_, -1);
669
670 // Make sure we still own the slot we are supposed to.
671 CHECK(
672 death_notification_is_held(&(memory_->GetWatcher(watcher_index_)->tid)));
673
674 // The act of unlocking invalidates the entry. Invalidate it.
675 death_notification_release(&(memory_->GetWatcher(watcher_index_)->tid));
676 // And internally forget the slot.
677 watcher_index_ = -1;
678
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800679 // Cleanup is cheap. The next user will do it anyways, so no need for us to do
680 // anything right now.
Austin Schuh20b2b082019-09-11 20:42:56 -0700681
682 // And confirm that nothing is owned by us.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700683 const int num_watchers = memory_->num_watchers();
Austin Schuh20b2b082019-09-11 20:42:56 -0700684 for (int i = 0; i < num_watchers; ++i) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700685 CHECK(!death_notification_is_held(&(memory_->GetWatcher(i)->tid)))
686 << ": " << i;
Austin Schuh20b2b082019-09-11 20:42:56 -0700687 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700688}
689
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700690std::optional<LocklessQueueWatcher> LocklessQueueWatcher::Make(
691 LocklessQueue queue, int priority) {
692 queue.Initialize();
693 LocklessQueueWatcher result(queue.memory(), priority);
694 if (result.watcher_index_ != -1) {
James Kuszmaul9776b392023-01-14 14:08:08 -0800695 return result;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700696 } else {
697 return std::nullopt;
698 }
699}
Austin Schuh20b2b082019-09-11 20:42:56 -0700700
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700701LocklessQueueWatcher::LocklessQueueWatcher(LocklessQueueMemory *memory,
702 int priority)
703 : memory_(memory) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700704 // TODO(austin): Make sure signal coalescing is turned on. We don't need
705 // duplicates. That will improve performance under high load.
706
707 // Since everything is self consistent, all we need to do is make sure nobody
708 // else is running. Someone dying will get caught in the generic consistency
709 // check.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800710 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory_);
Austin Schuh20b2b082019-09-11 20:42:56 -0700711 const int num_watchers = memory_->num_watchers();
712
713 // Now, find the first empty watcher and grab it.
714 CHECK_EQ(watcher_index_, -1);
715 for (int i = 0; i < num_watchers; ++i) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800716 // If we see a slot the kernel has marked as dead, everything we do reusing
717 // it needs to happen-after whatever that process did before dying.
Brian Silverman2484eea2019-12-21 16:48:46 -0800718 auto *const futex = &(memory_->GetWatcher(i)->tid.futex);
719 const uint32_t tid = __atomic_load_n(futex, __ATOMIC_ACQUIRE);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800720 if (tid == 0 || (tid & FUTEX_OWNER_DIED)) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700721 watcher_index_ = i;
Brian Silverman2484eea2019-12-21 16:48:46 -0800722 // Relaxed is OK here because we're the only task going to touch it
723 // between here and the write in death_notification_init below (other
724 // recovery is blocked by us holding the setup lock).
725 __atomic_store_n(futex, 0, __ATOMIC_RELAXED);
Austin Schuh20b2b082019-09-11 20:42:56 -0700726 break;
727 }
728 }
729
730 // Bail if we failed to find an open slot.
731 if (watcher_index_ == -1) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700732 return;
Austin Schuh20b2b082019-09-11 20:42:56 -0700733 }
734
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700735 Watcher *const w = memory_->GetWatcher(watcher_index_);
Austin Schuh20b2b082019-09-11 20:42:56 -0700736
737 w->pid = getpid();
738 w->priority = priority;
739
740 // Grabbing a mutex is a compiler and memory barrier, so nothing before will
741 // get rearranged afterwords.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800742 death_notification_init(&(w->tid));
Austin Schuh20b2b082019-09-11 20:42:56 -0700743}
744
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700745LocklessQueueWakeUpper::LocklessQueueWakeUpper(LocklessQueue queue)
746 : memory_(queue.const_memory()), pid_(getpid()), uid_(getuid()) {
747 queue.Initialize();
748 watcher_copy_.resize(memory_->num_watchers());
Austin Schuh20b2b082019-09-11 20:42:56 -0700749}
750
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700751int LocklessQueueWakeUpper::Wakeup(const int current_priority) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700752 const size_t num_watchers = memory_->num_watchers();
753
754 CHECK_EQ(watcher_copy_.size(), num_watchers);
755
756 // Grab a copy so it won't change out from underneath us, and we can sort it
757 // nicely in C++.
758 // Do note that there is still a window where the process can die *after* we
759 // read everything. We will still PI boost and send a signal to the thread in
760 // question. There is no way without pidfd's to close this window, and
761 // creating a pidfd is likely not RT.
762 for (size_t i = 0; i < num_watchers; ++i) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700763 const Watcher *w = memory_->GetWatcher(i);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800764 watcher_copy_[i].tid = __atomic_load_n(&(w->tid.futex), __ATOMIC_RELAXED);
765 // Force the load of the TID to come first.
766 aos_compiler_memory_barrier();
767 watcher_copy_[i].pid = w->pid.load(std::memory_order_relaxed);
768 watcher_copy_[i].priority = w->priority.load(std::memory_order_relaxed);
Austin Schuh20b2b082019-09-11 20:42:56 -0700769
770 // Use a priority of -1 to mean an invalid entry to make sorting easier.
771 if (watcher_copy_[i].tid & FUTEX_OWNER_DIED || watcher_copy_[i].tid == 0) {
772 watcher_copy_[i].priority = -1;
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800773 } else {
774 // Ensure all of this happens after we're done looking at the pid+priority
775 // in shared memory.
776 aos_compiler_memory_barrier();
777 if (watcher_copy_[i].tid != static_cast<pid_t>(__atomic_load_n(
778 &(w->tid.futex), __ATOMIC_RELAXED))) {
779 // Confirm that the watcher hasn't been re-used and modified while we
780 // read it. If it has, mark it invalid again.
781 watcher_copy_[i].priority = -1;
782 watcher_copy_[i].tid = 0;
783 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700784 }
785 }
786
787 // Now sort.
788 ::std::sort(watcher_copy_.begin(), watcher_copy_.end(),
789 [](const WatcherCopy &a, const WatcherCopy &b) {
790 return a.priority > b.priority;
791 });
792
793 int count = 0;
794 if (watcher_copy_[0].priority != -1) {
795 const int max_priority =
796 ::std::max(current_priority, watcher_copy_[0].priority);
797 // Boost if we are RT and there is a higher priority sender out there.
798 // Otherwise we might run into priority inversions.
799 if (max_priority > current_priority && current_priority > 0) {
800 SetCurrentThreadRealtimePriority(max_priority);
801 }
802
803 // Build up the siginfo to send.
804 siginfo_t uinfo;
805 memset(&uinfo, 0, sizeof(uinfo));
806
807 uinfo.si_code = SI_QUEUE;
808 uinfo.si_pid = pid_;
809 uinfo.si_uid = uid_;
810 uinfo.si_value.sival_int = 0;
811
812 for (const WatcherCopy &watcher_copy : watcher_copy_) {
813 // The first -1 priority means we are at the end of the valid list.
814 if (watcher_copy.priority == -1) {
815 break;
816 }
817
818 // Send the signal. Target just the thread that sent it so that we can
819 // support multiple watchers in a process (when someone creates multiple
820 // event loops in different threads).
821 rt_tgsigqueueinfo(watcher_copy.pid, watcher_copy.tid, kWakeupSignal,
822 &uinfo);
823
824 ++count;
825 }
826
827 // Drop back down if we were boosted.
828 if (max_priority > current_priority && current_priority > 0) {
829 SetCurrentThreadRealtimePriority(current_priority);
830 }
831 }
832
833 return count;
834}
835
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700836std::ostream &operator<<(std::ostream &os,
837 const LocklessQueueSender::Result r) {
838 os << static_cast<int>(r);
839 return os;
840}
841
842LocklessQueueSender::LocklessQueueSender(
843 LocklessQueueMemory *memory,
844 monotonic_clock::duration channel_storage_duration)
845 : memory_(memory), channel_storage_duration_(channel_storage_duration) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800846 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory_);
Austin Schuh20b2b082019-09-11 20:42:56 -0700847
848 // Since we already have the lock, go ahead and try cleaning up.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800849 Cleanup(memory_, grab_queue_setup_lock);
Austin Schuh20b2b082019-09-11 20:42:56 -0700850
851 const int num_senders = memory_->num_senders();
852
853 for (int i = 0; i < num_senders; ++i) {
854 ::aos::ipc_lib::Sender *s = memory->GetSender(i);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800855 // This doesn't need synchronization because we're the only process doing
856 // initialization right now, and nobody else will be touching senders which
857 // we're interested in.
Austin Schuh20b2b082019-09-11 20:42:56 -0700858 const uint32_t tid = __atomic_load_n(&(s->tid.futex), __ATOMIC_RELAXED);
859 if (tid == 0) {
860 sender_index_ = i;
861 break;
862 }
863 }
864
865 if (sender_index_ == -1) {
Austin Schuhe516ab02020-05-06 21:37:04 -0700866 VLOG(1) << "Too many senders, starting to bail.";
867 return;
Austin Schuh20b2b082019-09-11 20:42:56 -0700868 }
869
Brian Silverman177567e2020-08-12 19:51:33 -0700870 ::aos::ipc_lib::Sender *const sender = memory_->GetSender(sender_index_);
Austin Schuh20b2b082019-09-11 20:42:56 -0700871
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800872 // Indicate that we are now alive by taking over the slot. If the previous
873 // owner died, we still want to do this.
Brian Silverman177567e2020-08-12 19:51:33 -0700874 death_notification_init(&(sender->tid));
875
876 const Index scratch_index = sender->scratch_index.RelaxedLoad();
877 Message *const message = memory_->GetMessage(scratch_index);
878 CHECK(!message->header.queue_index.RelaxedLoad(memory_->queue_size()).valid())
879 << ": " << std::hex << scratch_index.get();
Austin Schuh20b2b082019-09-11 20:42:56 -0700880}
881
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700882LocklessQueueSender::~LocklessQueueSender() {
883 if (sender_index_ != -1) {
884 CHECK(memory_ != nullptr);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800885 death_notification_release(&(memory_->GetSender(sender_index_)->tid));
Austin Schuh20b2b082019-09-11 20:42:56 -0700886 }
887}
888
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700889std::optional<LocklessQueueSender> LocklessQueueSender::Make(
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700890 LocklessQueue queue, monotonic_clock::duration channel_storage_duration) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700891 queue.Initialize();
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700892 LocklessQueueSender result(queue.memory(), channel_storage_duration);
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700893 if (result.sender_index_ != -1) {
James Kuszmaul9776b392023-01-14 14:08:08 -0800894 return result;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700895 } else {
896 return std::nullopt;
897 }
898}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700899
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700900size_t LocklessQueueSender::size() const {
901 return memory_->message_data_size();
902}
903
904void *LocklessQueueSender::Data() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700905 ::aos::ipc_lib::Sender *sender = memory_->GetSender(sender_index_);
Brian Silverman177567e2020-08-12 19:51:33 -0700906 const Index scratch_index = sender->scratch_index.RelaxedLoad();
907 Message *const message = memory_->GetMessage(scratch_index);
908 // We should have invalidated this when we first got the buffer. Verify that
909 // in debug mode.
910 DCHECK(
911 !message->header.queue_index.RelaxedLoad(memory_->queue_size()).valid())
912 << ": " << std::hex << scratch_index.get();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700913
Brian Silvermana1652f32020-01-29 20:41:44 -0800914 return message->data(memory_->message_data_size());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700915}
916
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700917LocklessQueueSender::Result LocklessQueueSender::Send(
Austin Schuhad154822019-12-27 15:45:13 -0800918 const char *data, size_t length,
Austin Schuhb5c6f972021-03-14 21:53:07 -0700919 monotonic_clock::time_point monotonic_remote_time,
920 realtime_clock::time_point realtime_remote_time,
Austin Schuha9012be2021-07-21 15:19:11 -0700921 uint32_t remote_queue_index, const UUID &source_boot_uuid,
Austin Schuhb5c6f972021-03-14 21:53:07 -0700922 monotonic_clock::time_point *monotonic_sent_time,
923 realtime_clock::time_point *realtime_sent_time, uint32_t *queue_index) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700924 CHECK_LE(length, size());
Austin Schuh67420a42019-12-21 21:55:04 -0800925 // Flatbuffers write from the back of the buffer to the front. If we are
926 // going to write an explicit chunk of memory into the buffer, we need to
927 // adhere to this convention and place it at the end.
928 memcpy((reinterpret_cast<char *>(Data()) + size() - length), data, length);
Austin Schuh91ba6392020-10-03 13:27:47 -0700929 return Send(length, monotonic_remote_time, realtime_remote_time,
Austin Schuha9012be2021-07-21 15:19:11 -0700930 remote_queue_index, source_boot_uuid, monotonic_sent_time,
Austin Schuhb5c6f972021-03-14 21:53:07 -0700931 realtime_sent_time, queue_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700932}
933
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700934LocklessQueueSender::Result LocklessQueueSender::Send(
Austin Schuhb5c6f972021-03-14 21:53:07 -0700935 size_t length, monotonic_clock::time_point monotonic_remote_time,
936 realtime_clock::time_point realtime_remote_time,
Austin Schuha9012be2021-07-21 15:19:11 -0700937 uint32_t remote_queue_index, const UUID &source_boot_uuid,
Austin Schuhb5c6f972021-03-14 21:53:07 -0700938 monotonic_clock::time_point *monotonic_sent_time,
939 realtime_clock::time_point *realtime_sent_time, uint32_t *queue_index) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700940 const size_t queue_size = memory_->queue_size();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700941 CHECK_LE(length, size());
Austin Schuh20b2b082019-09-11 20:42:56 -0700942
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800943 ::aos::ipc_lib::Sender *const sender = memory_->GetSender(sender_index_);
944 // We can do a relaxed load on our sender because we're the only person
945 // modifying it right now.
946 const Index scratch_index = sender->scratch_index.RelaxedLoad();
947 Message *const message = memory_->GetMessage(scratch_index);
Austin Schuh91ba6392020-10-03 13:27:47 -0700948 if (CheckBothRedzones(memory_, message)) {
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700949 return Result::INVALID_REDZONE;
Austin Schuh91ba6392020-10-03 13:27:47 -0700950 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700951
Brian Silverman177567e2020-08-12 19:51:33 -0700952 // We should have invalidated this when we first got the buffer. Verify that
953 // in debug mode.
954 DCHECK(
955 !message->header.queue_index.RelaxedLoad(memory_->queue_size()).valid())
956 << ": " << std::hex << scratch_index.get();
957
Austin Schuh20b2b082019-09-11 20:42:56 -0700958 message->header.length = length;
Austin Schuhad154822019-12-27 15:45:13 -0800959 // Pass these through. Any alternative behavior can be implemented out a
960 // layer.
961 message->header.remote_queue_index = remote_queue_index;
Austin Schuha9012be2021-07-21 15:19:11 -0700962 message->header.source_boot_uuid = source_boot_uuid;
Austin Schuhad154822019-12-27 15:45:13 -0800963 message->header.monotonic_remote_time = monotonic_remote_time;
964 message->header.realtime_remote_time = realtime_remote_time;
Austin Schuh20b2b082019-09-11 20:42:56 -0700965
Brian Silverman177567e2020-08-12 19:51:33 -0700966 Index to_replace = Index::Invalid();
Austin Schuh20b2b082019-09-11 20:42:56 -0700967 while (true) {
968 const QueueIndex actual_next_queue_index =
969 memory_->next_queue_index.Load(queue_size);
970 const QueueIndex next_queue_index = ZeroOrValid(actual_next_queue_index);
971
972 const QueueIndex incremented_queue_index = next_queue_index.Increment();
973
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800974 // This needs to synchronize with whoever the previous writer at this
975 // location was.
Brian Silverman177567e2020-08-12 19:51:33 -0700976 to_replace = memory_->LoadIndex(next_queue_index);
Austin Schuh20b2b082019-09-11 20:42:56 -0700977
978 const QueueIndex decremented_queue_index =
979 next_queue_index.DecrementBy(queue_size);
980
981 // See if we got beat. If we did, try to atomically update
982 // next_queue_index in case the previous writer failed and retry.
983 if (!to_replace.IsPlausible(decremented_queue_index)) {
984 // We don't care about the result. It will either succeed, or we got
985 // beat in fixing it and just need to give up and try again. If we got
986 // beat multiple times, the only way progress can be made is if the queue
987 // is updated as well. This means that if we retry reading
988 // next_queue_index, we will be at most off by one and can retry.
989 //
990 // Both require no further action from us.
991 //
992 // TODO(austin): If we are having fairness issues under contention, we
993 // could have a mode bit in next_queue_index, and could use a lock or some
994 // other form of PI boosting to let the higher priority task win.
995 memory_->next_queue_index.CompareAndExchangeStrong(
996 actual_next_queue_index, incremented_queue_index);
997
Alex Perrycb7da4b2019-08-28 19:35:56 -0700998 VLOG(3) << "We were beat. Try again. Was " << std::hex
999 << to_replace.get() << ", is " << decremented_queue_index.index();
Austin Schuh20b2b082019-09-11 20:42:56 -07001000 continue;
1001 }
1002
1003 // Confirm that the message is what it should be.
Brian Silverman177567e2020-08-12 19:51:33 -07001004 //
1005 // This is just a best-effort check to skip reading the clocks if possible.
1006 // If this fails, then the compare-exchange below definitely would, so we
1007 // can bail out now.
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001008 const Message *message_to_replace = memory_->GetMessage(to_replace);
1009 bool is_previous_index_valid = false;
Austin Schuh20b2b082019-09-11 20:42:56 -07001010 {
Austin Schuh20b2b082019-09-11 20:42:56 -07001011 const QueueIndex previous_index =
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001012 message_to_replace->header.queue_index.RelaxedLoad(queue_size);
1013 is_previous_index_valid = previous_index.valid();
1014 if (previous_index != decremented_queue_index &&
1015 is_previous_index_valid) {
Austin Schuh20b2b082019-09-11 20:42:56 -07001016 // Retry.
Alex Perrycb7da4b2019-08-28 19:35:56 -07001017 VLOG(3) << "Something fishy happened, queue index doesn't match. "
1018 "Retrying. Previous index was "
1019 << std::hex << previous_index.index() << ", should be "
1020 << decremented_queue_index.index();
Austin Schuh20b2b082019-09-11 20:42:56 -07001021 continue;
1022 }
1023 }
1024
1025 message->header.monotonic_sent_time = ::aos::monotonic_clock::now();
1026 message->header.realtime_sent_time = ::aos::realtime_clock::now();
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001027
Austin Schuhad154822019-12-27 15:45:13 -08001028 if (monotonic_sent_time != nullptr) {
1029 *monotonic_sent_time = message->header.monotonic_sent_time;
1030 }
1031 if (realtime_sent_time != nullptr) {
1032 *realtime_sent_time = message->header.realtime_sent_time;
1033 }
1034 if (queue_index != nullptr) {
1035 *queue_index = next_queue_index.index();
1036 }
Austin Schuh20b2b082019-09-11 20:42:56 -07001037
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001038 const auto to_replace_monotonic_sent_time =
1039 message_to_replace->header.monotonic_sent_time;
1040
1041 // If we are overwriting a message sent in the last
1042 // channel_storage_duration_, that means that we would be sending more than
1043 // queue_size messages and would therefore be sending too fast. If the
1044 // previous index is not valid then the message hasn't been filled out yet
1045 // so we aren't sending too fast. And, if it is not less than the sent time
1046 // of the message that we are going to write, someone else beat us and the
1047 // compare and exchange below will fail.
1048 if (is_previous_index_valid &&
1049 (to_replace_monotonic_sent_time <
1050 message->header.monotonic_sent_time) &&
1051 (message->header.monotonic_sent_time - to_replace_monotonic_sent_time <
1052 channel_storage_duration_)) {
1053 // There is a possibility that another context beat us to writing out the
1054 // message in the queue, but we beat that context to acquiring the sent
1055 // time. In this case our sent time is *greater than* the other context's
1056 // sent time. Therefore, we can check if we got beat filling out this
1057 // message *after* doing the above check to determine if we hit this edge
1058 // case. Otherwise, messages are being sent too fast.
1059 const QueueIndex previous_index =
1060 message_to_replace->header.queue_index.Load(queue_size);
1061 if (previous_index != decremented_queue_index && previous_index.valid()) {
1062 VLOG(3) << "Got beat during check for messages being sent too fast"
1063 "Retrying.";
1064 continue;
1065 } else {
1066 VLOG(3) << "Messages sent too fast. Returning. Attempted index: "
1067 << decremented_queue_index.index()
1068 << " message sent time: " << message->header.monotonic_sent_time
1069 << " message to replace sent time: "
1070 << to_replace_monotonic_sent_time;
1071 // Since we are not using the message obtained from scratch_index
1072 // and we are not retrying, we need to invalidate its queue_index.
1073 message->header.queue_index.Invalidate();
1074 return Result::MESSAGES_SENT_TOO_FAST;
1075 }
1076 }
1077
Austin Schuh20b2b082019-09-11 20:42:56 -07001078 // Before we are fully done filling out the message, update the Sender state
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001079 // with the new index to write. This re-uses the barrier for the
Austin Schuh20b2b082019-09-11 20:42:56 -07001080 // queue_index store.
Alex Perrycb7da4b2019-08-28 19:35:56 -07001081 const Index index_to_write(next_queue_index, scratch_index.message_index());
Austin Schuh20b2b082019-09-11 20:42:56 -07001082
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001083 aos_compiler_memory_barrier();
1084 // We're the only person who cares about our scratch index, besides somebody
1085 // cleaning up after us.
Austin Schuh20b2b082019-09-11 20:42:56 -07001086 sender->scratch_index.RelaxedStore(index_to_write);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001087 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -07001088
1089 message->header.queue_index.Store(next_queue_index);
1090
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001091 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -07001092 // The message is now filled out, and we have a confirmed slot to store
1093 // into.
1094 //
1095 // Start by writing down what we are going to pull out of the queue. This
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001096 // was Invalid before now. Only person who will read this is whoever cleans
1097 // up after us, so no synchronization necessary.
Austin Schuh20b2b082019-09-11 20:42:56 -07001098 sender->to_replace.RelaxedStore(to_replace);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001099 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -07001100
1101 // Then exchange the next index into the queue.
1102 if (!memory_->GetQueue(next_queue_index.Wrapped())
1103 ->CompareAndExchangeStrong(to_replace, index_to_write)) {
1104 // Aw, didn't succeed. Retry.
1105 sender->to_replace.RelaxedInvalidate();
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001106 aos_compiler_memory_barrier();
Alex Perrycb7da4b2019-08-28 19:35:56 -07001107 VLOG(3) << "Failed to wrap into queue";
Austin Schuh20b2b082019-09-11 20:42:56 -07001108 continue;
1109 }
1110
1111 // Then update next_queue_index to save the next user some computation time.
1112 memory_->next_queue_index.CompareAndExchangeStrong(actual_next_queue_index,
1113 incremented_queue_index);
1114
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001115 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -07001116 // Now update the scratch space and record that we succeeded.
1117 sender->scratch_index.Store(to_replace);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001118 aos_compiler_memory_barrier();
1119 // And then record that we succeeded, but definitely after the above store.
Austin Schuh20b2b082019-09-11 20:42:56 -07001120 sender->to_replace.RelaxedInvalidate();
Brian Silverman177567e2020-08-12 19:51:33 -07001121
Austin Schuh20b2b082019-09-11 20:42:56 -07001122 break;
1123 }
Brian Silverman177567e2020-08-12 19:51:33 -07001124
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001125 DCHECK(!CheckBothRedzones(memory_, memory_->GetMessage(to_replace)))
1126 << ": Invalid message found in shared memory";
Brian Silverman177567e2020-08-12 19:51:33 -07001127 // to_replace is our current scratch_index. It isn't in the queue, which means
1128 // nobody new can pin it. They can set their `pinned` to it, but they will
1129 // back it out, so they don't count. This means that we just need to find a
1130 // message for which no pinner had it in `pinned`, and then we know this
1131 // message will never be pinned. We'll start with to_replace, and if that is
1132 // pinned then we'll look for a new one to use instead.
1133 const Index new_scratch =
1134 SwapPinnedSenderScratch(memory_, sender, to_replace);
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001135 DCHECK(!CheckBothRedzones(
1136 memory_, memory_->GetMessage(sender->scratch_index.RelaxedLoad())))
1137 << ": Invalid message found in shared memory";
Brian Silverman177567e2020-08-12 19:51:33 -07001138
1139 // If anybody is looking at this message (they shouldn't be), then try telling
1140 // them about it (best-effort).
1141 memory_->GetMessage(new_scratch)->header.queue_index.RelaxedInvalidate();
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001142 return Result::GOOD;
Austin Schuh20b2b082019-09-11 20:42:56 -07001143}
1144
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001145int LocklessQueueSender::buffer_index() const {
Brian Silverman4f4e0612020-08-12 19:54:41 -07001146 ::aos::ipc_lib::Sender *const sender = memory_->GetSender(sender_index_);
1147 // We can do a relaxed load on our sender because we're the only person
1148 // modifying it right now.
1149 const Index scratch_index = sender->scratch_index.RelaxedLoad();
1150 return scratch_index.message_index();
1151}
1152
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001153LocklessQueuePinner::LocklessQueuePinner(
1154 LocklessQueueMemory *memory, const LocklessQueueMemory *const_memory)
1155 : memory_(memory), const_memory_(const_memory) {
1156 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory_);
1157
1158 // Since we already have the lock, go ahead and try cleaning up.
1159 Cleanup(memory_, grab_queue_setup_lock);
1160
1161 const int num_pinners = memory_->num_pinners();
1162
1163 for (int i = 0; i < num_pinners; ++i) {
1164 ::aos::ipc_lib::Pinner *p = memory->GetPinner(i);
1165 // This doesn't need synchronization because we're the only process doing
1166 // initialization right now, and nobody else will be touching pinners which
1167 // we're interested in.
1168 const uint32_t tid = __atomic_load_n(&(p->tid.futex), __ATOMIC_RELAXED);
1169 if (tid == 0) {
1170 pinner_index_ = i;
1171 break;
1172 }
1173 }
1174
1175 if (pinner_index_ == -1) {
1176 VLOG(1) << "Too many pinners, starting to bail.";
1177 return;
1178 }
1179
1180 ::aos::ipc_lib::Pinner *p = memory_->GetPinner(pinner_index_);
1181 p->pinned.Invalidate();
1182
1183 // Indicate that we are now alive by taking over the slot. If the previous
1184 // owner died, we still want to do this.
1185 death_notification_init(&(p->tid));
1186}
1187
1188LocklessQueuePinner::~LocklessQueuePinner() {
1189 if (pinner_index_ != -1) {
1190 CHECK(memory_ != nullptr);
1191 memory_->GetPinner(pinner_index_)->pinned.Invalidate();
1192 aos_compiler_memory_barrier();
1193 death_notification_release(&(memory_->GetPinner(pinner_index_)->tid));
1194 }
1195}
1196
1197std::optional<LocklessQueuePinner> LocklessQueuePinner::Make(
1198 LocklessQueue queue) {
1199 queue.Initialize();
1200 LocklessQueuePinner result(queue.memory(), queue.const_memory());
1201 if (result.pinner_index_ != -1) {
James Kuszmaul9776b392023-01-14 14:08:08 -08001202 return result;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001203 } else {
1204 return std::nullopt;
1205 }
1206}
1207
1208// This method doesn't mess with any scratch_index, so it doesn't have to worry
1209// about message ownership.
1210int LocklessQueuePinner::PinIndex(uint32_t uint32_queue_index) {
1211 const size_t queue_size = memory_->queue_size();
1212 const QueueIndex queue_index =
1213 QueueIndex::Zero(queue_size).IncrementBy(uint32_queue_index);
1214 ipc_lib::Pinner *const pinner = memory_->GetPinner(pinner_index_);
1215
1216 AtomicIndex *const queue_slot = memory_->GetQueue(queue_index.Wrapped());
1217
1218 // Indicate that we want to pin this message.
1219 pinner->pinned.Store(queue_index);
1220 aos_compiler_memory_barrier();
1221
1222 {
1223 const Index message_index = queue_slot->Load();
1224 Message *const message = memory_->GetMessage(message_index);
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001225 DCHECK(!CheckBothRedzones(memory_, message))
1226 << ": Invalid message found in shared memory";
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001227
1228 const QueueIndex message_queue_index =
1229 message->header.queue_index.Load(queue_size);
1230 if (message_queue_index == queue_index) {
1231 VLOG(3) << "Eq: " << std::hex << message_queue_index.index();
1232 aos_compiler_memory_barrier();
1233 return message_index.message_index();
1234 }
1235 VLOG(3) << "Message reused: " << std::hex << message_queue_index.index()
1236 << ", " << queue_index.index();
1237 }
1238
1239 // Being down here means we asked to pin a message before realizing it's no
1240 // longer in the queue, so back that out now.
1241 pinner->pinned.Invalidate();
1242 VLOG(3) << "Unpinned: " << std::hex << queue_index.index();
1243 return -1;
1244}
1245
1246size_t LocklessQueuePinner::size() const {
1247 return const_memory_->message_data_size();
1248}
1249
1250const void *LocklessQueuePinner::Data() const {
1251 const size_t queue_size = const_memory_->queue_size();
1252 const ::aos::ipc_lib::Pinner *const pinner =
1253 const_memory_->GetPinner(pinner_index_);
1254 QueueIndex pinned = pinner->pinned.RelaxedLoad(queue_size);
1255 CHECK(pinned.valid());
1256 const Message *message = const_memory_->GetMessage(pinned);
1257
1258 return message->data(const_memory_->message_data_size());
1259}
1260
1261LocklessQueueReader::Result LocklessQueueReader::Read(
Austin Schuh20b2b082019-09-11 20:42:56 -07001262 uint32_t uint32_queue_index,
Austin Schuhb5c6f972021-03-14 21:53:07 -07001263 monotonic_clock::time_point *monotonic_sent_time,
1264 realtime_clock::time_point *realtime_sent_time,
1265 monotonic_clock::time_point *monotonic_remote_time,
1266 realtime_clock::time_point *realtime_remote_time,
Austin Schuha9012be2021-07-21 15:19:11 -07001267 uint32_t *remote_queue_index, UUID *source_boot_uuid, size_t *length,
Austin Schuhb5c6f972021-03-14 21:53:07 -07001268 char *data) const {
Austin Schuh20b2b082019-09-11 20:42:56 -07001269 const size_t queue_size = memory_->queue_size();
1270
1271 // Build up the QueueIndex.
1272 const QueueIndex queue_index =
1273 QueueIndex::Zero(queue_size).IncrementBy(uint32_queue_index);
1274
1275 // Read the message stored at the requested location.
1276 Index mi = memory_->LoadIndex(queue_index);
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001277 const Message *m = memory_->GetMessage(mi);
Austin Schuh20b2b082019-09-11 20:42:56 -07001278
1279 while (true) {
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001280 DCHECK(!CheckBothRedzones(memory_, m))
1281 << ": Invalid message found in shared memory";
Austin Schuh20b2b082019-09-11 20:42:56 -07001282 // We need to confirm that the data doesn't change while we are reading it.
1283 // Do that by first confirming that the message points to the queue index we
1284 // want.
1285 const QueueIndex starting_queue_index =
1286 m->header.queue_index.Load(queue_size);
1287 if (starting_queue_index != queue_index) {
1288 // If we found a message that is exactly 1 loop old, we just wrapped.
1289 if (starting_queue_index == queue_index.DecrementBy(queue_size)) {
Alex Perrycb7da4b2019-08-28 19:35:56 -07001290 VLOG(3) << "Matches: " << std::hex << starting_queue_index.index()
1291 << ", " << queue_index.DecrementBy(queue_size).index();
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001292 return Result::NOTHING_NEW;
Brian Silverman177567e2020-08-12 19:51:33 -07001293 }
1294
1295 // Someone has re-used this message between when we pulled it out of the
1296 // queue and when we grabbed its index. It is pretty hard to deduce
1297 // what happened. Just try again.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001298 const Message *const new_m = memory_->GetMessage(queue_index);
Brian Silverman177567e2020-08-12 19:51:33 -07001299 if (m != new_m) {
1300 m = new_m;
1301 VLOG(3) << "Retrying, m doesn't match";
1302 continue;
1303 }
1304
1305 // We have confirmed that message still points to the same message. This
1306 // means that the message didn't get swapped out from under us, so
1307 // starting_queue_index is correct.
1308 //
1309 // Either we got too far behind (signaled by this being a valid
1310 // message), or this is one of the initial messages which are invalid.
1311 if (starting_queue_index.valid()) {
1312 VLOG(3) << "Too old. Tried for " << std::hex << queue_index.index()
1313 << ", got " << starting_queue_index.index() << ", behind by "
1314 << std::dec
1315 << (starting_queue_index.index() - queue_index.index());
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001316 return Result::TOO_OLD;
Brian Silverman177567e2020-08-12 19:51:33 -07001317 }
1318
1319 VLOG(3) << "Initial";
1320
1321 // There isn't a valid message at this location.
1322 //
1323 // If someone asks for one of the messages within the first go around,
1324 // then they need to wait. They got ahead. Otherwise, they are
1325 // asking for something crazy, like something before the beginning of
1326 // the queue. Tell them that they are behind.
1327 if (uint32_queue_index < memory_->queue_size()) {
1328 VLOG(3) << "Near zero, " << std::hex << uint32_queue_index;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001329 return Result::NOTHING_NEW;
Austin Schuh20b2b082019-09-11 20:42:56 -07001330 } else {
Brian Silverman177567e2020-08-12 19:51:33 -07001331 VLOG(3) << "Not near zero, " << std::hex << uint32_queue_index;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001332 return Result::TOO_OLD;
Austin Schuh20b2b082019-09-11 20:42:56 -07001333 }
1334 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001335 VLOG(3) << "Eq: " << std::hex << starting_queue_index.index() << ", "
1336 << queue_index.index();
Austin Schuh20b2b082019-09-11 20:42:56 -07001337 break;
1338 }
1339
Alex Perrycb7da4b2019-08-28 19:35:56 -07001340 // Then read the data out. Copy it all out to be deterministic and so we can
1341 // make length be from either end.
Austin Schuh20b2b082019-09-11 20:42:56 -07001342 *monotonic_sent_time = m->header.monotonic_sent_time;
1343 *realtime_sent_time = m->header.realtime_sent_time;
Austin Schuhad154822019-12-27 15:45:13 -08001344 if (m->header.remote_queue_index == 0xffffffffu) {
1345 *remote_queue_index = queue_index.index();
1346 } else {
1347 *remote_queue_index = m->header.remote_queue_index;
1348 }
1349 *monotonic_remote_time = m->header.monotonic_remote_time;
1350 *realtime_remote_time = m->header.realtime_remote_time;
Austin Schuha9012be2021-07-21 15:19:11 -07001351 *source_boot_uuid = m->header.source_boot_uuid;
Brian Silverman6b8a3c32020-03-06 11:26:14 -08001352 if (data) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001353 memcpy(data, m->data(memory_->message_data_size()),
1354 memory_->message_data_size());
Brian Silverman6b8a3c32020-03-06 11:26:14 -08001355 }
Austin Schuh20b2b082019-09-11 20:42:56 -07001356 *length = m->header.length;
1357
1358 // And finally, confirm that the message *still* points to the queue index we
1359 // want. This means it didn't change out from under us.
1360 // If something changed out from under us, we were reading it much too late in
1361 // it's lifetime.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001362 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -07001363 const QueueIndex final_queue_index = m->header.queue_index.Load(queue_size);
1364 if (final_queue_index != queue_index) {
Alex Perrycb7da4b2019-08-28 19:35:56 -07001365 VLOG(3) << "Changed out from under us. Reading " << std::hex
1366 << queue_index.index() << ", finished with "
1367 << final_queue_index.index() << ", delta: " << std::dec
1368 << (final_queue_index.index() - queue_index.index());
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001369 return Result::OVERWROTE;
Austin Schuh20b2b082019-09-11 20:42:56 -07001370 }
1371
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001372 return Result::GOOD;
Austin Schuh20b2b082019-09-11 20:42:56 -07001373}
1374
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001375QueueIndex LocklessQueueReader::LatestIndex() const {
Austin Schuh20b2b082019-09-11 20:42:56 -07001376 const size_t queue_size = memory_->queue_size();
1377
1378 // There is only one interesting case. We need to know if the queue is empty.
1379 // That is done with a sentinel value. At worst, this will be off by one.
1380 const QueueIndex next_queue_index =
1381 memory_->next_queue_index.Load(queue_size);
1382 if (next_queue_index.valid()) {
1383 const QueueIndex current_queue_index = next_queue_index.DecrementBy(1u);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001384 return current_queue_index;
Austin Schuh20b2b082019-09-11 20:42:56 -07001385 }
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001386 return QueueIndex::Invalid();
1387}
1388
1389size_t LocklessQueueSize(const LocklessQueueMemory *memory) {
1390 return memory->queue_size();
1391}
1392
1393size_t LocklessQueueMessageDataSize(const LocklessQueueMemory *memory) {
1394 return memory->message_data_size();
Austin Schuh20b2b082019-09-11 20:42:56 -07001395}
1396
1397namespace {
1398
1399// Prints out the mutex state. Not safe to use while the mutex is being
1400// changed.
1401::std::string PrintMutex(aos_mutex *mutex) {
1402 ::std::stringstream s;
1403 s << "aos_mutex(" << ::std::hex << mutex->futex;
1404
1405 if (mutex->futex != 0) {
1406 s << ":";
1407 if (mutex->futex & FUTEX_OWNER_DIED) {
1408 s << "FUTEX_OWNER_DIED|";
1409 }
1410 s << "tid=" << (mutex->futex & FUTEX_TID_MASK);
1411 }
1412
1413 s << ")";
1414 return s.str();
1415}
1416
1417} // namespace
1418
1419void PrintLocklessQueueMemory(LocklessQueueMemory *memory) {
1420 const size_t queue_size = memory->queue_size();
1421 ::std::cout << "LocklessQueueMemory (" << memory << ") {" << ::std::endl;
1422 ::std::cout << " aos_mutex queue_setup_lock = "
1423 << PrintMutex(&memory->queue_setup_lock) << ::std::endl;
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001424 ::std::cout << " bool initialized = " << memory->initialized << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001425 ::std::cout << " config {" << ::std::endl;
1426 ::std::cout << " size_t num_watchers = " << memory->config.num_watchers
1427 << ::std::endl;
1428 ::std::cout << " size_t num_senders = " << memory->config.num_senders
1429 << ::std::endl;
Brian Silverman177567e2020-08-12 19:51:33 -07001430 ::std::cout << " size_t num_pinners = " << memory->config.num_pinners
1431 << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001432 ::std::cout << " size_t queue_size = " << memory->config.queue_size
1433 << ::std::endl;
1434 ::std::cout << " size_t message_data_size = "
1435 << memory->config.message_data_size << ::std::endl;
1436
1437 ::std::cout << " AtomicQueueIndex next_queue_index = "
1438 << memory->next_queue_index.Load(queue_size).DebugString()
1439 << ::std::endl;
1440
Austin Schuh3328d132020-02-28 13:54:57 -08001441 ::std::cout << " uid_t uid = " << memory->uid << ::std::endl;
1442
Austin Schuh20b2b082019-09-11 20:42:56 -07001443 ::std::cout << " }" << ::std::endl;
1444 ::std::cout << " AtomicIndex queue[" << queue_size << "] {" << ::std::endl;
1445 for (size_t i = 0; i < queue_size; ++i) {
1446 ::std::cout << " [" << i << "] -> "
1447 << memory->GetQueue(i)->Load().DebugString() << ::std::endl;
1448 }
1449 ::std::cout << " }" << ::std::endl;
1450 ::std::cout << " Message messages[" << memory->num_messages() << "] {"
1451 << ::std::endl;
1452 for (size_t i = 0; i < memory->num_messages(); ++i) {
1453 Message *m = memory->GetMessage(Index(i, i));
Brian Silverman001f24d2020-08-12 19:33:20 -07001454 ::std::cout << " [" << i << "] -> Message 0x" << std::hex
1455 << (reinterpret_cast<uintptr_t>(
1456 memory->GetMessage(Index(i, i))) -
1457 reinterpret_cast<uintptr_t>(memory))
1458 << std::dec << " {" << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001459 ::std::cout << " Header {" << ::std::endl;
1460 ::std::cout << " AtomicQueueIndex queue_index = "
1461 << m->header.queue_index.Load(queue_size).DebugString()
1462 << ::std::endl;
Brian Silverman001f24d2020-08-12 19:33:20 -07001463 ::std::cout << " monotonic_clock::time_point monotonic_sent_time = "
1464 << m->header.monotonic_sent_time << " 0x" << std::hex
1465 << m->header.monotonic_sent_time.time_since_epoch().count()
1466 << std::dec << ::std::endl;
1467 ::std::cout << " realtime_clock::time_point realtime_sent_time = "
1468 << m->header.realtime_sent_time << " 0x" << std::hex
1469 << m->header.realtime_sent_time.time_since_epoch().count()
1470 << std::dec << ::std::endl;
1471 ::std::cout
1472 << " monotonic_clock::time_point monotonic_remote_time = "
1473 << m->header.monotonic_remote_time << " 0x" << std::hex
1474 << m->header.monotonic_remote_time.time_since_epoch().count()
1475 << std::dec << ::std::endl;
1476 ::std::cout << " realtime_clock::time_point realtime_remote_time = "
1477 << m->header.realtime_remote_time << " 0x" << std::hex
1478 << m->header.realtime_remote_time.time_since_epoch().count()
1479 << std::dec << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001480 ::std::cout << " size_t length = " << m->header.length
1481 << ::std::endl;
1482 ::std::cout << " }" << ::std::endl;
Austin Schuhbe416742020-10-03 17:24:26 -07001483 const bool corrupt = CheckBothRedzones(memory, m);
1484 if (corrupt) {
1485 absl::Span<char> pre_redzone = m->PreRedzone(memory->message_data_size());
1486 absl::Span<char> post_redzone =
1487 m->PostRedzone(memory->message_data_size(), memory->message_size());
1488
1489 ::std::cout << " pre-redzone: \""
1490 << absl::BytesToHexString(std::string_view(
1491 pre_redzone.data(), pre_redzone.size()))
1492 << std::endl;
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001493 ::std::cout << " // *** DATA REDZONES ARE CORRUPTED ***"
1494 << ::std::endl;
Austin Schuhbe416742020-10-03 17:24:26 -07001495 ::std::cout << " post-redzone: \""
1496 << absl::BytesToHexString(std::string_view(
1497 post_redzone.data(), post_redzone.size()))
1498 << std::endl;
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001499 }
Austin Schuh20b2b082019-09-11 20:42:56 -07001500 ::std::cout << " data: {";
1501
Brian Silverman001f24d2020-08-12 19:33:20 -07001502 if (FLAGS_dump_lockless_queue_data) {
1503 const char *const m_data = m->data(memory->message_data_size());
Austin Schuhbe416742020-10-03 17:24:26 -07001504 std::cout << absl::BytesToHexString(std::string_view(
1505 m_data, corrupt ? memory->message_data_size() : m->header.length));
Austin Schuh20b2b082019-09-11 20:42:56 -07001506 }
1507 ::std::cout << ::std::setfill(' ') << ::std::dec << "}" << ::std::endl;
1508 ::std::cout << " }," << ::std::endl;
1509 }
1510 ::std::cout << " }" << ::std::endl;
1511
Alex Perrycb7da4b2019-08-28 19:35:56 -07001512 ::std::cout << " Sender senders[" << memory->num_senders() << "] {"
1513 << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001514 for (size_t i = 0; i < memory->num_senders(); ++i) {
1515 Sender *s = memory->GetSender(i);
1516 ::std::cout << " [" << i << "] -> Sender {" << ::std::endl;
1517 ::std::cout << " aos_mutex tid = " << PrintMutex(&s->tid)
1518 << ::std::endl;
1519 ::std::cout << " AtomicIndex scratch_index = "
1520 << s->scratch_index.Load().DebugString() << ::std::endl;
1521 ::std::cout << " AtomicIndex to_replace = "
1522 << s->to_replace.Load().DebugString() << ::std::endl;
1523 ::std::cout << " }" << ::std::endl;
1524 }
1525 ::std::cout << " }" << ::std::endl;
1526
Brian Silverman177567e2020-08-12 19:51:33 -07001527 ::std::cout << " Pinner pinners[" << memory->num_pinners() << "] {"
1528 << ::std::endl;
1529 for (size_t i = 0; i < memory->num_pinners(); ++i) {
1530 Pinner *p = memory->GetPinner(i);
1531 ::std::cout << " [" << i << "] -> Pinner {" << ::std::endl;
1532 ::std::cout << " aos_mutex tid = " << PrintMutex(&p->tid)
1533 << ::std::endl;
1534 ::std::cout << " AtomicIndex scratch_index = "
1535 << p->scratch_index.Load().DebugString() << ::std::endl;
1536 ::std::cout << " AtomicIndex pinned = "
1537 << p->pinned.Load(memory->queue_size()).DebugString()
1538 << ::std::endl;
1539 ::std::cout << " }" << ::std::endl;
1540 }
1541 ::std::cout << " }" << ::std::endl;
1542
Austin Schuh20b2b082019-09-11 20:42:56 -07001543 ::std::cout << " Watcher watchers[" << memory->num_watchers() << "] {"
1544 << ::std::endl;
1545 for (size_t i = 0; i < memory->num_watchers(); ++i) {
1546 Watcher *w = memory->GetWatcher(i);
1547 ::std::cout << " [" << i << "] -> Watcher {" << ::std::endl;
1548 ::std::cout << " aos_mutex tid = " << PrintMutex(&w->tid)
1549 << ::std::endl;
1550 ::std::cout << " pid_t pid = " << w->pid << ::std::endl;
1551 ::std::cout << " int priority = " << w->priority << ::std::endl;
1552 ::std::cout << " }" << ::std::endl;
1553 }
1554 ::std::cout << " }" << ::std::endl;
1555
1556 ::std::cout << "}" << ::std::endl;
1557}
1558
1559} // namespace ipc_lib
1560} // namespace aos