blob: 14110d634e452701702bf518830acd78e271b091 [file] [log] [blame]
Austin Schuh20b2b082019-09-11 20:42:56 -07001#include "aos/ipc_lib/lockless_queue.h"
2
3#include <linux/futex.h>
Brennan Coslett6af53bb2023-07-18 15:22:46 -05004#include <pwd.h>
Austin Schuh20b2b082019-09-11 20:42:56 -07005#include <sys/types.h>
6#include <syscall.h>
7#include <unistd.h>
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07008
Austin Schuh20b2b082019-09-11 20:42:56 -07009#include <algorithm>
10#include <iomanip>
11#include <iostream>
12#include <sstream>
13
Austin Schuhbe416742020-10-03 17:24:26 -070014#include "absl/strings/escaping.h"
Philipp Schrader790cb542023-07-05 21:06:52 -070015#include "gflags/gflags.h"
16#include "glog/logging.h"
17
Austin Schuh20b2b082019-09-11 20:42:56 -070018#include "aos/ipc_lib/lockless_queue_memory.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070019#include "aos/realtime.h"
Austin Schuh20b2b082019-09-11 20:42:56 -070020#include "aos/util/compiler_memory_barrier.h"
21
Brian Silverman001f24d2020-08-12 19:33:20 -070022DEFINE_bool(dump_lockless_queue_data, false,
23 "If true, print the data out when dumping the queue.");
24
Austin Schuh20b2b082019-09-11 20:42:56 -070025namespace aos {
26namespace ipc_lib {
Austin Schuh20b2b082019-09-11 20:42:56 -070027namespace {
28
Brian Silvermanfafe1fa2019-12-18 21:42:18 -080029class GrabQueueSetupLockOrDie {
30 public:
31 GrabQueueSetupLockOrDie(LocklessQueueMemory *memory) : memory_(memory) {
32 const int result = mutex_grab(&(memory->queue_setup_lock));
33 CHECK(result == 0 || result == 1) << ": " << result;
34 }
Austin Schuh20b2b082019-09-11 20:42:56 -070035
Brian Silvermanfafe1fa2019-12-18 21:42:18 -080036 ~GrabQueueSetupLockOrDie() { mutex_unlock(&(memory_->queue_setup_lock)); }
37
38 GrabQueueSetupLockOrDie(const GrabQueueSetupLockOrDie &) = delete;
39 GrabQueueSetupLockOrDie &operator=(const GrabQueueSetupLockOrDie &) = delete;
40
41 private:
42 LocklessQueueMemory *const memory_;
43};
44
Brian Silverman177567e2020-08-12 19:51:33 -070045bool IsPinned(LocklessQueueMemory *memory, Index index) {
46 DCHECK(index.valid());
47 const size_t queue_size = memory->queue_size();
48 const QueueIndex message_index =
49 memory->GetMessage(index)->header.queue_index.Load(queue_size);
50 if (!message_index.valid()) {
51 return false;
52 }
53 DCHECK(memory->GetQueue(message_index.Wrapped())->Load() != index)
54 << ": Message is in the queue";
55 for (int pinner_index = 0;
56 pinner_index < static_cast<int>(memory->config.num_pinners);
57 ++pinner_index) {
58 ipc_lib::Pinner *const pinner = memory->GetPinner(pinner_index);
59
60 if (pinner->pinned.RelaxedLoad(queue_size) == message_index) {
61 return true;
62 }
63 }
64 return false;
65}
66
67// Ensures sender->scratch_index (which must contain to_replace) is not pinned.
68//
69// Returns the new scratch_index value.
70Index SwapPinnedSenderScratch(LocklessQueueMemory *const memory,
71 ipc_lib::Sender *const sender,
72 const Index to_replace) {
73 // If anybody's trying to pin this message, then grab a message from a pinner
74 // to write into instead, and leave the message we pulled out of the queue
75 // (currently in our scratch_index) with a pinner.
76 //
77 // This loop will terminate in at most one iteration through the pinners in
78 // any steady-state configuration of the memory. There are only as many
79 // Pinner::pinned values to worry about as there are Pinner::scratch_index
80 // values to check against, plus to_replace, which means there will always be
81 // a free one. We might have to make multiple passes if things are being
82 // changed concurrently though, but nobody dying can make this loop fail to
83 // terminate (because the number of processes that can die is bounded, because
84 // no new ones can start while we've got the lock).
85 for (int pinner_index = 0; true;
86 pinner_index = (pinner_index + 1) % memory->config.num_pinners) {
87 if (!IsPinned(memory, to_replace)) {
88 // No pinners on our current scratch_index, so we're fine now.
89 VLOG(3) << "No pinners: " << to_replace.DebugString();
90 return to_replace;
91 }
92
93 ipc_lib::Pinner *const pinner = memory->GetPinner(pinner_index);
94
95 const Index pinner_scratch = pinner->scratch_index.RelaxedLoad();
96 CHECK(pinner_scratch.valid())
97 << ": Pinner scratch_index should always be valid";
98 if (IsPinned(memory, pinner_scratch)) {
99 // Wouldn't do us any good to swap with this one, so don't bother, and
100 // move onto the next one.
101 VLOG(3) << "Also pinned: " << pinner_scratch.DebugString();
102 continue;
103 }
104
105 sender->to_replace.RelaxedStore(pinner_scratch);
106 aos_compiler_memory_barrier();
107 // Give the pinner the message (which is currently in
108 // sender->scratch_index).
109 if (!pinner->scratch_index.CompareAndExchangeStrong(pinner_scratch,
110 to_replace)) {
111 // Somebody swapped into this pinner before us. The new value is probably
112 // pinned, so we don't want to look at it again immediately.
113 VLOG(3) << "Pinner " << pinner_index
114 << " scratch_index changed: " << pinner_scratch.DebugString()
115 << ", " << to_replace.DebugString();
116 sender->to_replace.RelaxedInvalidate();
117 continue;
118 }
119 aos_compiler_memory_barrier();
120 // Now update the sender's scratch space and record that we succeeded.
121 sender->scratch_index.Store(pinner_scratch);
122 aos_compiler_memory_barrier();
123 // And then record that we succeeded, but definitely after the above
124 // store.
125 sender->to_replace.RelaxedInvalidate();
126 VLOG(3) << "Got new scratch message: " << pinner_scratch.DebugString();
127
128 // If it's in a pinner's scratch_index, it should not be in the queue, which
129 // means nobody new can pin it for real. However, they can still attempt to
130 // pin it, which means we can't verify !IsPinned down here.
131
132 return pinner_scratch;
133 }
134}
135
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700136// Returns true if it succeeded. Returns false if another sender died in the
137// middle.
138bool DoCleanup(LocklessQueueMemory *memory, const GrabQueueSetupLockOrDie &) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800139 // Make sure we start looking at shared memory fresh right now. We'll handle
140 // people dying partway through by either cleaning up after them or not, but
141 // we want to ensure we clean up after anybody who has already died when we
142 // start.
143 aos_compiler_memory_barrier();
144
Austin Schuh20b2b082019-09-11 20:42:56 -0700145 const size_t num_senders = memory->num_senders();
Brian Silverman177567e2020-08-12 19:51:33 -0700146 const size_t num_pinners = memory->num_pinners();
Austin Schuh20b2b082019-09-11 20:42:56 -0700147 const size_t queue_size = memory->queue_size();
148 const size_t num_messages = memory->num_messages();
149
150 // There are a large number of crazy cases here for how things can go wrong
151 // and how we have to recover. They either require us to keep extra track of
152 // what is going on, slowing down the send path, or require a large number of
153 // cases.
154 //
155 // The solution here is to not over-think it. This is running while not real
156 // time during construction. It is allowed to be slow. It will also very
157 // rarely trigger. There is a small uS window where process death is
158 // ambiguous.
159 //
160 // So, build up a list N long, where N is the number of messages. Search
161 // through the entire queue and the sender list (ignoring any dead senders),
162 // and mark down which ones we have seen. Once we have seen all the messages
163 // except the N dead senders, we know which messages are dead. Because the
164 // queue is active while we do this, it may take a couple of go arounds to see
165 // everything.
166
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700167 ::std::vector<bool> need_recovery(num_senders, false);
168
Austin Schuh20b2b082019-09-11 20:42:56 -0700169 // Do the easy case. Find all senders who have died. See if they are either
170 // consistent already, or if they have copied over to_replace to the scratch
171 // index, but haven't cleared to_replace. Count them.
172 size_t valid_senders = 0;
173 for (size_t i = 0; i < num_senders; ++i) {
174 Sender *sender = memory->GetSender(i);
175 const uint32_t tid =
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800176 __atomic_load_n(&(sender->tid.futex), __ATOMIC_ACQUIRE);
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700177 if (!(tid & FUTEX_OWNER_DIED)) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700178 // Not dead.
179 ++valid_senders;
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700180 continue;
Austin Schuh20b2b082019-09-11 20:42:56 -0700181 }
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700182 VLOG(3) << "Found an easy death for sender " << i;
183 // We can do a relaxed load here because we're the only person touching
184 // this sender at this point.
185 const Index to_replace = sender->to_replace.RelaxedLoad();
186 const Index scratch_index = sender->scratch_index.Load();
187
188 // I find it easiest to think about this in terms of the set of observable
189 // states. The main code progresses through the following states:
190
191 // 1) scratch_index = xxx
192 // to_replace = invalid
193 // This is unambiguous. Already good.
194
195 // 2) scratch_index = xxx
196 // to_replace = yyy
197 // Very ambiguous. Is xxx or yyy the correct one? Need to either roll
198 // this forwards or backwards.
199
200 // 3) scratch_index = yyy
201 // to_replace = yyy
202 // We are in the act of moving to_replace to scratch_index, but didn't
203 // finish. Easy.
Brian Silverman177567e2020-08-12 19:51:33 -0700204 //
205 // If doing a pinner swap, we've definitely done it.
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700206
207 // 4) scratch_index = yyy
208 // to_replace = invalid
209 // Finished, but died. Looks like 1)
210
Brian Silverman177567e2020-08-12 19:51:33 -0700211 // Swapping with a pinner's scratch_index passes through the same states.
212 // We just need to ensure the message that ends up in the senders's
213 // scratch_index isn't pinned, using the same code as sending does.
214
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700215 // Any cleanup code needs to follow the same set of states to be robust to
216 // death, so death can be restarted.
217
218 if (!to_replace.valid()) {
219 // 1) or 4). Make sure we aren't corrupted and declare victory.
220 CHECK(scratch_index.valid());
221
Brian Silverman177567e2020-08-12 19:51:33 -0700222 // If it's in 1) with a pinner, the sender might have a pinned message,
223 // so fix that.
224 SwapPinnedSenderScratch(memory, sender, scratch_index);
225
226 // If it's in 4), it may not have completed this step yet. This will
227 // always be a NOP if it's in 1), verified by a DCHECK.
228 memory->GetMessage(scratch_index)->header.queue_index.RelaxedInvalidate();
229
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700230 __atomic_store_n(&(sender->tid.futex), 0, __ATOMIC_RELEASE);
231 ++valid_senders;
232 continue;
233 }
234
235 // Could be 2) or 3) at this point.
236
237 if (to_replace == scratch_index) {
238 // 3) for sure.
239 // Just need to invalidate to_replace to finish.
240 sender->to_replace.Invalidate();
241
Brian Silverman177567e2020-08-12 19:51:33 -0700242 // Make sure to indicate it's an unused message before a sender gets its
243 // hands on it.
244 memory->GetMessage(scratch_index)->header.queue_index.RelaxedInvalidate();
245 aos_compiler_memory_barrier();
246
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700247 // And mark that we succeeded.
248 __atomic_store_n(&(sender->tid.futex), 0, __ATOMIC_RELEASE);
249 ++valid_senders;
250 continue;
251 }
252
253 // Must be 2). Mark it for later.
254 need_recovery[i] = true;
Austin Schuh20b2b082019-09-11 20:42:56 -0700255 }
256
Brian Silverman177567e2020-08-12 19:51:33 -0700257 // Cleaning up pinners is easy. We don't actually have to do anything, but
258 // invalidating its pinned field might help catch bugs elsewhere trying to
259 // read it before it's set.
260 for (size_t i = 0; i < num_pinners; ++i) {
261 Pinner *const pinner = memory->GetPinner(i);
262 const uint32_t tid =
263 __atomic_load_n(&(pinner->tid.futex), __ATOMIC_ACQUIRE);
264 if (!(tid & FUTEX_OWNER_DIED)) {
265 continue;
266 }
267 pinner->pinned.Invalidate();
268 __atomic_store_n(&(pinner->tid.futex), 0, __ATOMIC_RELEASE);
269 }
270
Austin Schuh20b2b082019-09-11 20:42:56 -0700271 // If all the senders are (or were made) good, there is no need to do the hard
272 // case.
273 if (valid_senders == num_senders) {
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700274 return true;
Austin Schuh20b2b082019-09-11 20:42:56 -0700275 }
276
Alex Perrycb7da4b2019-08-28 19:35:56 -0700277 VLOG(3) << "Starting hard cleanup";
Austin Schuh20b2b082019-09-11 20:42:56 -0700278
279 size_t num_accounted_for = 0;
280 size_t num_missing = 0;
281 ::std::vector<bool> accounted_for(num_messages, false);
282
283 while ((num_accounted_for + num_missing) != num_messages) {
284 num_missing = 0;
285 for (size_t i = 0; i < num_senders; ++i) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800286 Sender *const sender = memory->GetSender(i);
Austin Schuh20b2b082019-09-11 20:42:56 -0700287 const uint32_t tid =
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800288 __atomic_load_n(&(sender->tid.futex), __ATOMIC_ACQUIRE);
Austin Schuh20b2b082019-09-11 20:42:56 -0700289 if (tid & FUTEX_OWNER_DIED) {
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700290 if (!need_recovery[i]) {
291 return false;
292 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700293 ++num_missing;
Brian Silverman177567e2020-08-12 19:51:33 -0700294 continue;
Austin Schuh20b2b082019-09-11 20:42:56 -0700295 }
Brian Silverman177567e2020-08-12 19:51:33 -0700296 CHECK(!need_recovery[i]) << ": Somebody else recovered a sender: " << i;
297 // We can do a relaxed load here because we're the only person touching
298 // this sender at this point, if it matters. If it's not a dead sender,
299 // then any message it ever has will eventually be accounted for if we
300 // make enough tries through the outer loop.
301 const Index scratch_index = sender->scratch_index.RelaxedLoad();
302 if (!accounted_for[scratch_index.message_index()]) {
303 ++num_accounted_for;
304 }
305 accounted_for[scratch_index.message_index()] = true;
Austin Schuh20b2b082019-09-11 20:42:56 -0700306 }
307
308 for (size_t i = 0; i < queue_size; ++i) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800309 // Same logic as above for scratch_index applies here too.
Austin Schuh20b2b082019-09-11 20:42:56 -0700310 const Index index = memory->GetQueue(i)->RelaxedLoad();
311 if (!accounted_for[index.message_index()]) {
312 ++num_accounted_for;
313 }
314 accounted_for[index.message_index()] = true;
315 }
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700316
Brian Silverman177567e2020-08-12 19:51:33 -0700317 for (size_t pinner_index = 0; pinner_index < num_pinners; ++pinner_index) {
318 // Same logic as above for scratch_index applies here too.
319 const Index index =
320 memory->GetPinner(pinner_index)->scratch_index.RelaxedLoad();
321 if (!accounted_for[index.message_index()]) {
322 ++num_accounted_for;
323 }
324 accounted_for[index.message_index()] = true;
325 }
326
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700327 CHECK_LE(num_accounted_for + num_missing, num_messages);
Austin Schuh20b2b082019-09-11 20:42:56 -0700328 }
329
330 while (num_missing != 0) {
331 const size_t starting_num_missing = num_missing;
332 for (size_t i = 0; i < num_senders; ++i) {
333 Sender *sender = memory->GetSender(i);
334 const uint32_t tid =
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800335 __atomic_load_n(&(sender->tid.futex), __ATOMIC_ACQUIRE);
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700336 if (!(tid & FUTEX_OWNER_DIED)) {
337 CHECK(!need_recovery[i]) << ": Somebody else recovered a sender: " << i;
338 continue;
339 }
340 if (!need_recovery[i]) {
341 return false;
342 }
343 // We can do relaxed loads here because we're the only person touching
344 // this sender at this point.
345 const Index scratch_index = sender->scratch_index.RelaxedLoad();
346 const Index to_replace = sender->to_replace.RelaxedLoad();
Austin Schuh20b2b082019-09-11 20:42:56 -0700347
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700348 // Candidate.
349 if (to_replace.valid()) {
350 CHECK_LE(to_replace.message_index(), accounted_for.size());
351 }
352 if (scratch_index.valid()) {
353 CHECK_LE(scratch_index.message_index(), accounted_for.size());
354 }
355 if (!to_replace.valid() || accounted_for[to_replace.message_index()]) {
356 CHECK(scratch_index.valid());
357 VLOG(3) << "Sender " << i
358 << " died, to_replace is already accounted for";
359 // If both are accounted for, we are corrupt...
360 CHECK(!accounted_for[scratch_index.message_index()]);
Austin Schuh20b2b082019-09-11 20:42:56 -0700361
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700362 // to_replace is already accounted for. This means that we didn't
363 // atomically insert scratch_index into the queue yet. So
364 // invalidate to_replace.
365 sender->to_replace.Invalidate();
Brian Silverman177567e2020-08-12 19:51:33 -0700366 // Sender definitely will not have gotten here, so finish for it.
367 memory->GetMessage(scratch_index)
368 ->header.queue_index.RelaxedInvalidate();
Austin Schuh20b2b082019-09-11 20:42:56 -0700369
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700370 // And then mark this sender clean.
371 __atomic_store_n(&(sender->tid.futex), 0, __ATOMIC_RELEASE);
372 need_recovery[i] = false;
Austin Schuh20b2b082019-09-11 20:42:56 -0700373
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700374 // And account for scratch_index.
375 accounted_for[scratch_index.message_index()] = true;
376 --num_missing;
377 ++num_accounted_for;
378 } else if (!scratch_index.valid() ||
379 accounted_for[scratch_index.message_index()]) {
380 VLOG(3) << "Sender " << i
381 << " died, scratch_index is already accounted for";
382 // scratch_index is accounted for. That means we did the insert,
383 // but didn't record it.
384 CHECK(to_replace.valid());
Brian Silverman177567e2020-08-12 19:51:33 -0700385
386 // Make sure to indicate it's an unused message before a sender gets its
387 // hands on it.
388 memory->GetMessage(to_replace)->header.queue_index.RelaxedInvalidate();
389 aos_compiler_memory_barrier();
390
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700391 // Finish the transaction. Copy to_replace, then clear it.
Austin Schuh20b2b082019-09-11 20:42:56 -0700392
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700393 sender->scratch_index.Store(to_replace);
394 sender->to_replace.Invalidate();
Austin Schuh20b2b082019-09-11 20:42:56 -0700395
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700396 // And then mark this sender clean.
397 __atomic_store_n(&(sender->tid.futex), 0, __ATOMIC_RELEASE);
398 need_recovery[i] = false;
Austin Schuh20b2b082019-09-11 20:42:56 -0700399
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700400 // And account for to_replace.
401 accounted_for[to_replace.message_index()] = true;
402 --num_missing;
403 ++num_accounted_for;
404 } else {
405 VLOG(3) << "Sender " << i << " died, neither is accounted for";
406 // Ambiguous. There will be an unambiguous one somewhere that we
407 // can do first.
Austin Schuh20b2b082019-09-11 20:42:56 -0700408 }
409 }
410 // CHECK that we are making progress.
411 CHECK_NE(num_missing, starting_num_missing);
412 }
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700413 return true;
414}
415
416void Cleanup(LocklessQueueMemory *memory, const GrabQueueSetupLockOrDie &lock) {
417 // The number of iterations is bounded here because there are only a finite
418 // number of senders in existence which could die, and no new ones can be
419 // created while we're in here holding the lock.
420 while (!DoCleanup(memory, lock)) {
421 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700422}
423
424// Exposes rt_tgsigqueueinfo so we can send the signal *just* to the target
425// thread.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800426// TODO(Brian): Do directly in assembly for armhf at least for efficiency.
Austin Schuh20b2b082019-09-11 20:42:56 -0700427int rt_tgsigqueueinfo(pid_t tgid, pid_t tid, int sig, siginfo_t *si) {
428 return syscall(SYS_rt_tgsigqueueinfo, tgid, tid, sig, si);
429}
430
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700431QueueIndex ZeroOrValid(QueueIndex index) {
432 if (!index.valid()) {
433 return index.Clear();
434 }
435 return index;
436}
437
Austin Schuh20b2b082019-09-11 20:42:56 -0700438} // namespace
439
Austin Schuh4bc4f902019-12-23 18:04:51 -0800440size_t LocklessQueueConfiguration::message_size() const {
441 // Round up the message size so following data is aligned appropriately.
Brian Silverman0eaa1da2020-08-12 20:03:52 -0700442 // Make sure to leave space to align the message data. It will be aligned
443 // relative to the start of the shared memory region, but that might not be
444 // aligned for some use cases.
Brian Silvermana1652f32020-01-29 20:41:44 -0800445 return LocklessQueueMemory::AlignmentRoundUp(message_data_size +
Brian Silverman0eaa1da2020-08-12 20:03:52 -0700446 kChannelDataRedzone * 2 +
Brian Silvermana1652f32020-01-29 20:41:44 -0800447 (kChannelDataAlignment - 1)) +
Austin Schuh4bc4f902019-12-23 18:04:51 -0800448 sizeof(Message);
449}
450
Austin Schuh20b2b082019-09-11 20:42:56 -0700451size_t LocklessQueueMemorySize(LocklessQueueConfiguration config) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800452 // Round up the message size so following data is aligned appropriately.
453 config.message_data_size =
454 LocklessQueueMemory::AlignmentRoundUp(config.message_data_size);
Austin Schuh20b2b082019-09-11 20:42:56 -0700455
456 // As we build up the size, confirm that everything is aligned to the
457 // alignment requirements of the type.
458 size_t size = sizeof(LocklessQueueMemory);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800459 CHECK_EQ(size % alignof(LocklessQueueMemory), 0u);
Austin Schuh20b2b082019-09-11 20:42:56 -0700460
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800461 CHECK_EQ(size % alignof(AtomicIndex), 0u);
Austin Schuh20b2b082019-09-11 20:42:56 -0700462 size += LocklessQueueMemory::SizeOfQueue(config);
463
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800464 CHECK_EQ(size % alignof(Message), 0u);
Austin Schuh20b2b082019-09-11 20:42:56 -0700465 size += LocklessQueueMemory::SizeOfMessages(config);
466
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800467 CHECK_EQ(size % alignof(Watcher), 0u);
Austin Schuh20b2b082019-09-11 20:42:56 -0700468 size += LocklessQueueMemory::SizeOfWatchers(config);
469
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800470 CHECK_EQ(size % alignof(Sender), 0u);
Austin Schuh20b2b082019-09-11 20:42:56 -0700471 size += LocklessQueueMemory::SizeOfSenders(config);
472
Brian Silverman177567e2020-08-12 19:51:33 -0700473 CHECK_EQ(size % alignof(Pinner), 0u);
474 size += LocklessQueueMemory::SizeOfPinners(config);
475
Austin Schuh20b2b082019-09-11 20:42:56 -0700476 return size;
477}
478
Brian Silverman0eaa1da2020-08-12 20:03:52 -0700479// Calculates the starting byte for a redzone in shared memory. This starting
480// value is simply incremented for subsequent bytes.
481//
482// The result is based on the offset of the region in shared memor, to ensure it
483// is the same for each region when we generate and verify, but different for
484// each region to help catch forms of corruption like copying out-of-bounds data
485// from one place to another.
486//
487// memory is the base pointer to the shared memory. It is used to calculated
488// offsets. starting_data is the start of the redzone's data. Each one will
489// get a unique pattern.
490uint8_t RedzoneStart(const LocklessQueueMemory *memory,
491 const char *starting_data) {
492 const auto memory_int = reinterpret_cast<uintptr_t>(memory);
493 const auto starting_int = reinterpret_cast<uintptr_t>(starting_data);
494 DCHECK(starting_int >= memory_int);
495 DCHECK(starting_int < memory_int + LocklessQueueMemorySize(memory->config));
496 const uintptr_t starting_offset = starting_int - memory_int;
497 // Just XOR the lower 2 bytes. They higher-order bytes are probably 0
498 // anyways.
499 return (starting_offset & 0xFF) ^ ((starting_offset >> 8) & 0xFF);
500}
501
502// Returns true if the given redzone has invalid data.
503bool CheckRedzone(const LocklessQueueMemory *memory,
504 absl::Span<const char> redzone) {
505 uint8_t redzone_value = RedzoneStart(memory, redzone.data());
506
507 bool bad = false;
508
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700509 for (size_t i = 0; i < redzone.size() && !bad; ++i) {
Brian Silverman0eaa1da2020-08-12 20:03:52 -0700510 if (memcmp(&redzone[i], &redzone_value, 1)) {
511 bad = true;
512 }
513 ++redzone_value;
514 }
515
516 return bad;
517}
518
519// Returns true if either of message's redzones has invalid data.
520bool CheckBothRedzones(const LocklessQueueMemory *memory,
521 const Message *message) {
522 return CheckRedzone(memory,
523 message->PreRedzone(memory->message_data_size())) ||
524 CheckRedzone(memory, message->PostRedzone(memory->message_data_size(),
525 memory->message_size()));
526}
527
528// Fills the given redzone with the expected data.
529void FillRedzone(LocklessQueueMemory *memory, absl::Span<char> redzone) {
530 uint8_t redzone_value = RedzoneStart(memory, redzone.data());
531 for (size_t i = 0; i < redzone.size(); ++i) {
532 memcpy(&redzone[i], &redzone_value, 1);
533 ++redzone_value;
534 }
535
536 // Just double check that the implementations match.
537 CHECK(!CheckRedzone(memory, redzone));
538}
539
Austin Schuh20b2b082019-09-11 20:42:56 -0700540LocklessQueueMemory *InitializeLocklessQueueMemory(
541 LocklessQueueMemory *memory, LocklessQueueConfiguration config) {
542 // Everything should be zero initialized already. So we just need to fill
543 // everything out properly.
544
Brian Silvermanc57ff0a2020-04-28 16:45:13 -0700545 // This is the UID we will use for checking signal-sending permission
546 // compatibility.
547 //
548 // The manpage says:
549 // For a process to have permission to send a signal, it must either be
550 // privileged [...], or the real or effective user ID of the sending process
551 // must equal the real or saved set-user-ID of the target process.
552 //
553 // Processes typically initialize a queue in random order as they start up.
554 // This means we need an algorithm for verifying all processes have
555 // permissions to send each other signals which gives the same answer no
556 // matter what order they attach in. We would also like to avoid maintaining a
557 // shared list of the UIDs of all processes.
558 //
559 // To do this while still giving sufficient flexibility for all current use
560 // cases, we track a single UID for the queue. All processes with a matching
561 // euid+suid must have this UID. Any processes with distinct euid/suid must
562 // instead have a matching ruid. This guarantees signals can be sent between
563 // all processes attached to the queue.
564 //
565 // In particular, this allows a process to change only its euid (to interact
566 // with a queue) while still maintaining privileges via its ruid. However, it
567 // can only use privileges in ways that do not require changing the euid back,
568 // because while the euid is different it will not be able to receive signals.
569 // We can't actually verify that, but we can sanity check that things are
570 // valid when the queue is initialized.
571
572 uid_t uid;
573 {
574 uid_t ruid, euid, suid;
575 PCHECK(getresuid(&ruid, &euid, &suid) == 0);
576 // If these are equal, then use them, even if that's different from the real
577 // UID. This allows processes to keep a real UID of 0 (to have permissions
578 // to perform system-level changes) while still being able to communicate
579 // with processes running unprivileged as a distinct user.
580 if (euid == suid) {
581 uid = euid;
582 VLOG(1) << "Using euid==suid " << uid;
583 } else {
584 uid = ruid;
585 VLOG(1) << "Using ruid " << ruid;
586 }
587 }
588
Austin Schuh20b2b082019-09-11 20:42:56 -0700589 // Grab the mutex. We don't care if the previous reader died. We are going
590 // to check everything anyways.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800591 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory);
Austin Schuh20b2b082019-09-11 20:42:56 -0700592
593 if (!memory->initialized) {
594 // TODO(austin): Check these for out of bounds.
595 memory->config.num_watchers = config.num_watchers;
596 memory->config.num_senders = config.num_senders;
Brian Silverman177567e2020-08-12 19:51:33 -0700597 memory->config.num_pinners = config.num_pinners;
Austin Schuh20b2b082019-09-11 20:42:56 -0700598 memory->config.queue_size = config.queue_size;
Austin Schuh4bc4f902019-12-23 18:04:51 -0800599 memory->config.message_data_size = config.message_data_size;
Austin Schuh20b2b082019-09-11 20:42:56 -0700600
601 const size_t num_messages = memory->num_messages();
602 // There need to be at most MaxMessages() messages allocated.
603 CHECK_LE(num_messages, Index::MaxMessages());
604
605 for (size_t i = 0; i < num_messages; ++i) {
Brian Silverman0eaa1da2020-08-12 20:03:52 -0700606 Message *const message =
607 memory->GetMessage(Index(QueueIndex::Zero(memory->queue_size()), i));
608 message->header.queue_index.Invalidate();
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700609 message->header.monotonic_sent_time = monotonic_clock::min_time;
Brian Silverman0eaa1da2020-08-12 20:03:52 -0700610 FillRedzone(memory, message->PreRedzone(memory->message_data_size()));
611 FillRedzone(memory, message->PostRedzone(memory->message_data_size(),
612 memory->message_size()));
Austin Schuh20b2b082019-09-11 20:42:56 -0700613 }
614
615 for (size_t i = 0; i < memory->queue_size(); ++i) {
616 // Make the initial counter be the furthest away number. That means that
617 // index 0 should be 0xffff, 1 should be 0, etc.
618 memory->GetQueue(i)->Store(Index(QueueIndex::Zero(memory->queue_size())
619 .IncrementBy(i)
620 .DecrementBy(memory->queue_size()),
621 i));
622 }
623
624 memory->next_queue_index.Invalidate();
Brian Silvermanc57ff0a2020-04-28 16:45:13 -0700625 memory->uid = uid;
Austin Schuh20b2b082019-09-11 20:42:56 -0700626
627 for (size_t i = 0; i < memory->num_senders(); ++i) {
628 ::aos::ipc_lib::Sender *s = memory->GetSender(i);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800629 // Nobody else can possibly be touching these because we haven't set
630 // initialized to true yet.
Austin Schuh83cbb1e2023-06-23 12:59:02 -0700631 s->scratch_index.RelaxedStore(
632 Index(QueueIndex::Invalid(), i + memory->queue_size()));
Austin Schuh20b2b082019-09-11 20:42:56 -0700633 s->to_replace.RelaxedInvalidate();
634 }
635
Brian Silverman177567e2020-08-12 19:51:33 -0700636 for (size_t i = 0; i < memory->num_pinners(); ++i) {
637 ::aos::ipc_lib::Pinner *pinner = memory->GetPinner(i);
638 // Nobody else can possibly be touching these because we haven't set
639 // initialized to true yet.
640 pinner->scratch_index.RelaxedStore(
Austin Schuh83cbb1e2023-06-23 12:59:02 -0700641 Index(QueueIndex::Invalid(),
642 i + memory->num_senders() + memory->queue_size()));
Brian Silverman177567e2020-08-12 19:51:33 -0700643 pinner->pinned.Invalidate();
644 }
645
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800646 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -0700647 // Signal everything is done. This needs to be done last, so if we die, we
648 // redo initialization.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800649 memory->initialized = true;
Austin Schuh3328d132020-02-28 13:54:57 -0800650 } else {
Brennan Coslett6af53bb2023-07-18 15:22:46 -0500651 if (memory->uid != uid) {
652 // Subsequent calls to getpwuid() overwrite this
653 // pointer, pull the thing we care about into a
654 // string.
655 struct passwd const *user_pw = getpwuid(uid);
656 std::string user_username = user_pw->pw_name;
657 struct passwd const *memory_pw = getpwuid(memory->uid);
658 std::string memory_username = memory_pw->pw_name;
659 LOG(FATAL) << "Current user " << user_username << " (uid:" << uid << ") "
660 << "doesn't match shared memory user " << memory_username
661 << " (uid:" << memory->uid << "). "
662 << "Login as " << memory_username
663 << " user to access this channel.";
664 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700665 }
666
Austin Schuh20b2b082019-09-11 20:42:56 -0700667 return memory;
668}
669
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700670void LocklessQueue::Initialize() {
671 InitializeLocklessQueueMemory(memory_, config_);
672}
Austin Schuh20b2b082019-09-11 20:42:56 -0700673
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700674LocklessQueueWatcher::~LocklessQueueWatcher() {
675 if (watcher_index_ == -1) {
676 return;
677 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700678
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700679 // Since everything is self consistent, all we need to do is make sure nobody
680 // else is running. Someone dying will get caught in the generic consistency
681 // check.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800682 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory_);
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700683
684 // Make sure we are registered.
685 CHECK_NE(watcher_index_, -1);
686
687 // Make sure we still own the slot we are supposed to.
688 CHECK(
689 death_notification_is_held(&(memory_->GetWatcher(watcher_index_)->tid)));
690
691 // The act of unlocking invalidates the entry. Invalidate it.
692 death_notification_release(&(memory_->GetWatcher(watcher_index_)->tid));
693 // And internally forget the slot.
694 watcher_index_ = -1;
695
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800696 // Cleanup is cheap. The next user will do it anyways, so no need for us to do
697 // anything right now.
Austin Schuh20b2b082019-09-11 20:42:56 -0700698
699 // And confirm that nothing is owned by us.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700700 const int num_watchers = memory_->num_watchers();
Austin Schuh20b2b082019-09-11 20:42:56 -0700701 for (int i = 0; i < num_watchers; ++i) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700702 CHECK(!death_notification_is_held(&(memory_->GetWatcher(i)->tid)))
703 << ": " << i;
Austin Schuh20b2b082019-09-11 20:42:56 -0700704 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700705}
706
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700707std::optional<LocklessQueueWatcher> LocklessQueueWatcher::Make(
708 LocklessQueue queue, int priority) {
709 queue.Initialize();
710 LocklessQueueWatcher result(queue.memory(), priority);
711 if (result.watcher_index_ != -1) {
James Kuszmaul9776b392023-01-14 14:08:08 -0800712 return result;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700713 } else {
714 return std::nullopt;
715 }
716}
Austin Schuh20b2b082019-09-11 20:42:56 -0700717
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700718LocklessQueueWatcher::LocklessQueueWatcher(LocklessQueueMemory *memory,
719 int priority)
720 : memory_(memory) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700721 // TODO(austin): Make sure signal coalescing is turned on. We don't need
722 // duplicates. That will improve performance under high load.
723
724 // Since everything is self consistent, all we need to do is make sure nobody
725 // else is running. Someone dying will get caught in the generic consistency
726 // check.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800727 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory_);
Austin Schuh20b2b082019-09-11 20:42:56 -0700728 const int num_watchers = memory_->num_watchers();
729
730 // Now, find the first empty watcher and grab it.
731 CHECK_EQ(watcher_index_, -1);
732 for (int i = 0; i < num_watchers; ++i) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800733 // If we see a slot the kernel has marked as dead, everything we do reusing
734 // it needs to happen-after whatever that process did before dying.
Brian Silverman2484eea2019-12-21 16:48:46 -0800735 auto *const futex = &(memory_->GetWatcher(i)->tid.futex);
736 const uint32_t tid = __atomic_load_n(futex, __ATOMIC_ACQUIRE);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800737 if (tid == 0 || (tid & FUTEX_OWNER_DIED)) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700738 watcher_index_ = i;
Brian Silverman2484eea2019-12-21 16:48:46 -0800739 // Relaxed is OK here because we're the only task going to touch it
740 // between here and the write in death_notification_init below (other
741 // recovery is blocked by us holding the setup lock).
742 __atomic_store_n(futex, 0, __ATOMIC_RELAXED);
Austin Schuh20b2b082019-09-11 20:42:56 -0700743 break;
744 }
745 }
746
747 // Bail if we failed to find an open slot.
748 if (watcher_index_ == -1) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700749 return;
Austin Schuh20b2b082019-09-11 20:42:56 -0700750 }
751
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700752 Watcher *const w = memory_->GetWatcher(watcher_index_);
Austin Schuh20b2b082019-09-11 20:42:56 -0700753
754 w->pid = getpid();
755 w->priority = priority;
756
757 // Grabbing a mutex is a compiler and memory barrier, so nothing before will
758 // get rearranged afterwords.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800759 death_notification_init(&(w->tid));
Austin Schuh20b2b082019-09-11 20:42:56 -0700760}
761
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700762LocklessQueueWakeUpper::LocklessQueueWakeUpper(LocklessQueue queue)
763 : memory_(queue.const_memory()), pid_(getpid()), uid_(getuid()) {
764 queue.Initialize();
765 watcher_copy_.resize(memory_->num_watchers());
Austin Schuh20b2b082019-09-11 20:42:56 -0700766}
767
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700768int LocklessQueueWakeUpper::Wakeup(const int current_priority) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700769 const size_t num_watchers = memory_->num_watchers();
770
771 CHECK_EQ(watcher_copy_.size(), num_watchers);
772
773 // Grab a copy so it won't change out from underneath us, and we can sort it
774 // nicely in C++.
775 // Do note that there is still a window where the process can die *after* we
776 // read everything. We will still PI boost and send a signal to the thread in
777 // question. There is no way without pidfd's to close this window, and
778 // creating a pidfd is likely not RT.
779 for (size_t i = 0; i < num_watchers; ++i) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700780 const Watcher *w = memory_->GetWatcher(i);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800781 watcher_copy_[i].tid = __atomic_load_n(&(w->tid.futex), __ATOMIC_RELAXED);
782 // Force the load of the TID to come first.
783 aos_compiler_memory_barrier();
784 watcher_copy_[i].pid = w->pid.load(std::memory_order_relaxed);
785 watcher_copy_[i].priority = w->priority.load(std::memory_order_relaxed);
Austin Schuh20b2b082019-09-11 20:42:56 -0700786
787 // Use a priority of -1 to mean an invalid entry to make sorting easier.
788 if (watcher_copy_[i].tid & FUTEX_OWNER_DIED || watcher_copy_[i].tid == 0) {
789 watcher_copy_[i].priority = -1;
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800790 } else {
791 // Ensure all of this happens after we're done looking at the pid+priority
792 // in shared memory.
793 aos_compiler_memory_barrier();
794 if (watcher_copy_[i].tid != static_cast<pid_t>(__atomic_load_n(
795 &(w->tid.futex), __ATOMIC_RELAXED))) {
796 // Confirm that the watcher hasn't been re-used and modified while we
797 // read it. If it has, mark it invalid again.
798 watcher_copy_[i].priority = -1;
799 watcher_copy_[i].tid = 0;
800 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700801 }
802 }
803
804 // Now sort.
805 ::std::sort(watcher_copy_.begin(), watcher_copy_.end(),
806 [](const WatcherCopy &a, const WatcherCopy &b) {
807 return a.priority > b.priority;
808 });
809
810 int count = 0;
811 if (watcher_copy_[0].priority != -1) {
812 const int max_priority =
813 ::std::max(current_priority, watcher_copy_[0].priority);
814 // Boost if we are RT and there is a higher priority sender out there.
815 // Otherwise we might run into priority inversions.
816 if (max_priority > current_priority && current_priority > 0) {
817 SetCurrentThreadRealtimePriority(max_priority);
818 }
819
820 // Build up the siginfo to send.
821 siginfo_t uinfo;
822 memset(&uinfo, 0, sizeof(uinfo));
823
824 uinfo.si_code = SI_QUEUE;
825 uinfo.si_pid = pid_;
826 uinfo.si_uid = uid_;
827 uinfo.si_value.sival_int = 0;
828
829 for (const WatcherCopy &watcher_copy : watcher_copy_) {
830 // The first -1 priority means we are at the end of the valid list.
831 if (watcher_copy.priority == -1) {
832 break;
833 }
834
835 // Send the signal. Target just the thread that sent it so that we can
836 // support multiple watchers in a process (when someone creates multiple
837 // event loops in different threads).
838 rt_tgsigqueueinfo(watcher_copy.pid, watcher_copy.tid, kWakeupSignal,
839 &uinfo);
840
841 ++count;
842 }
843
844 // Drop back down if we were boosted.
845 if (max_priority > current_priority && current_priority > 0) {
846 SetCurrentThreadRealtimePriority(current_priority);
847 }
848 }
849
850 return count;
851}
852
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700853std::ostream &operator<<(std::ostream &os,
854 const LocklessQueueSender::Result r) {
855 os << static_cast<int>(r);
856 return os;
857}
858
859LocklessQueueSender::LocklessQueueSender(
860 LocklessQueueMemory *memory,
861 monotonic_clock::duration channel_storage_duration)
862 : memory_(memory), channel_storage_duration_(channel_storage_duration) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800863 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory_);
Austin Schuh20b2b082019-09-11 20:42:56 -0700864
865 // Since we already have the lock, go ahead and try cleaning up.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800866 Cleanup(memory_, grab_queue_setup_lock);
Austin Schuh20b2b082019-09-11 20:42:56 -0700867
868 const int num_senders = memory_->num_senders();
869
870 for (int i = 0; i < num_senders; ++i) {
871 ::aos::ipc_lib::Sender *s = memory->GetSender(i);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800872 // This doesn't need synchronization because we're the only process doing
873 // initialization right now, and nobody else will be touching senders which
874 // we're interested in.
Austin Schuh20b2b082019-09-11 20:42:56 -0700875 const uint32_t tid = __atomic_load_n(&(s->tid.futex), __ATOMIC_RELAXED);
876 if (tid == 0) {
877 sender_index_ = i;
878 break;
879 }
880 }
881
882 if (sender_index_ == -1) {
Austin Schuhe516ab02020-05-06 21:37:04 -0700883 VLOG(1) << "Too many senders, starting to bail.";
884 return;
Austin Schuh20b2b082019-09-11 20:42:56 -0700885 }
886
Brian Silverman177567e2020-08-12 19:51:33 -0700887 ::aos::ipc_lib::Sender *const sender = memory_->GetSender(sender_index_);
Austin Schuh20b2b082019-09-11 20:42:56 -0700888
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800889 // Indicate that we are now alive by taking over the slot. If the previous
890 // owner died, we still want to do this.
Brian Silverman177567e2020-08-12 19:51:33 -0700891 death_notification_init(&(sender->tid));
892
893 const Index scratch_index = sender->scratch_index.RelaxedLoad();
894 Message *const message = memory_->GetMessage(scratch_index);
895 CHECK(!message->header.queue_index.RelaxedLoad(memory_->queue_size()).valid())
896 << ": " << std::hex << scratch_index.get();
Austin Schuh20b2b082019-09-11 20:42:56 -0700897}
898
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700899LocklessQueueSender::~LocklessQueueSender() {
900 if (sender_index_ != -1) {
901 CHECK(memory_ != nullptr);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800902 death_notification_release(&(memory_->GetSender(sender_index_)->tid));
Austin Schuh20b2b082019-09-11 20:42:56 -0700903 }
904}
905
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700906std::optional<LocklessQueueSender> LocklessQueueSender::Make(
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700907 LocklessQueue queue, monotonic_clock::duration channel_storage_duration) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700908 queue.Initialize();
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700909 LocklessQueueSender result(queue.memory(), channel_storage_duration);
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700910 if (result.sender_index_ != -1) {
James Kuszmaul9776b392023-01-14 14:08:08 -0800911 return result;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700912 } else {
913 return std::nullopt;
914 }
915}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700916
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700917size_t LocklessQueueSender::size() const {
918 return memory_->message_data_size();
919}
920
921void *LocklessQueueSender::Data() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700922 ::aos::ipc_lib::Sender *sender = memory_->GetSender(sender_index_);
Brian Silverman177567e2020-08-12 19:51:33 -0700923 const Index scratch_index = sender->scratch_index.RelaxedLoad();
924 Message *const message = memory_->GetMessage(scratch_index);
925 // We should have invalidated this when we first got the buffer. Verify that
926 // in debug mode.
927 DCHECK(
928 !message->header.queue_index.RelaxedLoad(memory_->queue_size()).valid())
929 << ": " << std::hex << scratch_index.get();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700930
Brian Silvermana1652f32020-01-29 20:41:44 -0800931 return message->data(memory_->message_data_size());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700932}
933
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700934LocklessQueueSender::Result LocklessQueueSender::Send(
Austin Schuhad154822019-12-27 15:45:13 -0800935 const char *data, size_t length,
Austin Schuhb5c6f972021-03-14 21:53:07 -0700936 monotonic_clock::time_point monotonic_remote_time,
937 realtime_clock::time_point realtime_remote_time,
Austin Schuha9012be2021-07-21 15:19:11 -0700938 uint32_t remote_queue_index, const UUID &source_boot_uuid,
Austin Schuhb5c6f972021-03-14 21:53:07 -0700939 monotonic_clock::time_point *monotonic_sent_time,
940 realtime_clock::time_point *realtime_sent_time, uint32_t *queue_index) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700941 CHECK_LE(length, size());
Austin Schuh67420a42019-12-21 21:55:04 -0800942 // Flatbuffers write from the back of the buffer to the front. If we are
943 // going to write an explicit chunk of memory into the buffer, we need to
944 // adhere to this convention and place it at the end.
945 memcpy((reinterpret_cast<char *>(Data()) + size() - length), data, length);
Austin Schuh91ba6392020-10-03 13:27:47 -0700946 return Send(length, monotonic_remote_time, realtime_remote_time,
Austin Schuha9012be2021-07-21 15:19:11 -0700947 remote_queue_index, source_boot_uuid, monotonic_sent_time,
Austin Schuhb5c6f972021-03-14 21:53:07 -0700948 realtime_sent_time, queue_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700949}
950
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700951LocklessQueueSender::Result LocklessQueueSender::Send(
Austin Schuhb5c6f972021-03-14 21:53:07 -0700952 size_t length, monotonic_clock::time_point monotonic_remote_time,
953 realtime_clock::time_point realtime_remote_time,
Austin Schuha9012be2021-07-21 15:19:11 -0700954 uint32_t remote_queue_index, const UUID &source_boot_uuid,
Austin Schuhb5c6f972021-03-14 21:53:07 -0700955 monotonic_clock::time_point *monotonic_sent_time,
956 realtime_clock::time_point *realtime_sent_time, uint32_t *queue_index) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700957 const size_t queue_size = memory_->queue_size();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700958 CHECK_LE(length, size());
Austin Schuh20b2b082019-09-11 20:42:56 -0700959
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800960 ::aos::ipc_lib::Sender *const sender = memory_->GetSender(sender_index_);
961 // We can do a relaxed load on our sender because we're the only person
962 // modifying it right now.
963 const Index scratch_index = sender->scratch_index.RelaxedLoad();
964 Message *const message = memory_->GetMessage(scratch_index);
Austin Schuh91ba6392020-10-03 13:27:47 -0700965 if (CheckBothRedzones(memory_, message)) {
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700966 return Result::INVALID_REDZONE;
Austin Schuh91ba6392020-10-03 13:27:47 -0700967 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700968
Brian Silverman177567e2020-08-12 19:51:33 -0700969 // We should have invalidated this when we first got the buffer. Verify that
970 // in debug mode.
971 DCHECK(
972 !message->header.queue_index.RelaxedLoad(memory_->queue_size()).valid())
973 << ": " << std::hex << scratch_index.get();
974
Austin Schuh20b2b082019-09-11 20:42:56 -0700975 message->header.length = length;
Austin Schuhad154822019-12-27 15:45:13 -0800976 // Pass these through. Any alternative behavior can be implemented out a
977 // layer.
978 message->header.remote_queue_index = remote_queue_index;
Austin Schuha9012be2021-07-21 15:19:11 -0700979 message->header.source_boot_uuid = source_boot_uuid;
Austin Schuhad154822019-12-27 15:45:13 -0800980 message->header.monotonic_remote_time = monotonic_remote_time;
981 message->header.realtime_remote_time = realtime_remote_time;
Austin Schuh20b2b082019-09-11 20:42:56 -0700982
Brian Silverman177567e2020-08-12 19:51:33 -0700983 Index to_replace = Index::Invalid();
Austin Schuh20b2b082019-09-11 20:42:56 -0700984 while (true) {
985 const QueueIndex actual_next_queue_index =
986 memory_->next_queue_index.Load(queue_size);
987 const QueueIndex next_queue_index = ZeroOrValid(actual_next_queue_index);
988
989 const QueueIndex incremented_queue_index = next_queue_index.Increment();
990
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800991 // This needs to synchronize with whoever the previous writer at this
992 // location was.
Brian Silverman177567e2020-08-12 19:51:33 -0700993 to_replace = memory_->LoadIndex(next_queue_index);
Austin Schuh20b2b082019-09-11 20:42:56 -0700994
995 const QueueIndex decremented_queue_index =
996 next_queue_index.DecrementBy(queue_size);
997
998 // See if we got beat. If we did, try to atomically update
999 // next_queue_index in case the previous writer failed and retry.
1000 if (!to_replace.IsPlausible(decremented_queue_index)) {
1001 // We don't care about the result. It will either succeed, or we got
1002 // beat in fixing it and just need to give up and try again. If we got
1003 // beat multiple times, the only way progress can be made is if the queue
1004 // is updated as well. This means that if we retry reading
1005 // next_queue_index, we will be at most off by one and can retry.
1006 //
1007 // Both require no further action from us.
1008 //
1009 // TODO(austin): If we are having fairness issues under contention, we
1010 // could have a mode bit in next_queue_index, and could use a lock or some
1011 // other form of PI boosting to let the higher priority task win.
1012 memory_->next_queue_index.CompareAndExchangeStrong(
1013 actual_next_queue_index, incremented_queue_index);
1014
Alex Perrycb7da4b2019-08-28 19:35:56 -07001015 VLOG(3) << "We were beat. Try again. Was " << std::hex
1016 << to_replace.get() << ", is " << decremented_queue_index.index();
Austin Schuh20b2b082019-09-11 20:42:56 -07001017 continue;
1018 }
1019
1020 // Confirm that the message is what it should be.
Brian Silverman177567e2020-08-12 19:51:33 -07001021 //
1022 // This is just a best-effort check to skip reading the clocks if possible.
1023 // If this fails, then the compare-exchange below definitely would, so we
1024 // can bail out now.
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001025 const Message *message_to_replace = memory_->GetMessage(to_replace);
1026 bool is_previous_index_valid = false;
Austin Schuh20b2b082019-09-11 20:42:56 -07001027 {
Austin Schuh20b2b082019-09-11 20:42:56 -07001028 const QueueIndex previous_index =
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001029 message_to_replace->header.queue_index.RelaxedLoad(queue_size);
1030 is_previous_index_valid = previous_index.valid();
1031 if (previous_index != decremented_queue_index &&
1032 is_previous_index_valid) {
Austin Schuh20b2b082019-09-11 20:42:56 -07001033 // Retry.
Alex Perrycb7da4b2019-08-28 19:35:56 -07001034 VLOG(3) << "Something fishy happened, queue index doesn't match. "
1035 "Retrying. Previous index was "
1036 << std::hex << previous_index.index() << ", should be "
1037 << decremented_queue_index.index();
Austin Schuh20b2b082019-09-11 20:42:56 -07001038 continue;
1039 }
1040 }
1041
1042 message->header.monotonic_sent_time = ::aos::monotonic_clock::now();
1043 message->header.realtime_sent_time = ::aos::realtime_clock::now();
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001044
Austin Schuhad154822019-12-27 15:45:13 -08001045 if (monotonic_sent_time != nullptr) {
1046 *monotonic_sent_time = message->header.monotonic_sent_time;
1047 }
1048 if (realtime_sent_time != nullptr) {
1049 *realtime_sent_time = message->header.realtime_sent_time;
1050 }
1051 if (queue_index != nullptr) {
1052 *queue_index = next_queue_index.index();
1053 }
Austin Schuh20b2b082019-09-11 20:42:56 -07001054
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001055 const auto to_replace_monotonic_sent_time =
1056 message_to_replace->header.monotonic_sent_time;
1057
1058 // If we are overwriting a message sent in the last
1059 // channel_storage_duration_, that means that we would be sending more than
1060 // queue_size messages and would therefore be sending too fast. If the
1061 // previous index is not valid then the message hasn't been filled out yet
1062 // so we aren't sending too fast. And, if it is not less than the sent time
1063 // of the message that we are going to write, someone else beat us and the
1064 // compare and exchange below will fail.
1065 if (is_previous_index_valid &&
1066 (to_replace_monotonic_sent_time <
1067 message->header.monotonic_sent_time) &&
1068 (message->header.monotonic_sent_time - to_replace_monotonic_sent_time <
1069 channel_storage_duration_)) {
1070 // There is a possibility that another context beat us to writing out the
1071 // message in the queue, but we beat that context to acquiring the sent
1072 // time. In this case our sent time is *greater than* the other context's
1073 // sent time. Therefore, we can check if we got beat filling out this
1074 // message *after* doing the above check to determine if we hit this edge
1075 // case. Otherwise, messages are being sent too fast.
1076 const QueueIndex previous_index =
1077 message_to_replace->header.queue_index.Load(queue_size);
1078 if (previous_index != decremented_queue_index && previous_index.valid()) {
1079 VLOG(3) << "Got beat during check for messages being sent too fast"
1080 "Retrying.";
1081 continue;
1082 } else {
Austin Schuh71e72142023-05-03 13:10:07 -07001083 VLOG(1) << "Messages sent too fast. Returning. Attempted index: "
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001084 << decremented_queue_index.index()
1085 << " message sent time: " << message->header.monotonic_sent_time
1086 << " message to replace sent time: "
1087 << to_replace_monotonic_sent_time;
Austin Schuh71e72142023-05-03 13:10:07 -07001088
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001089 // Since we are not using the message obtained from scratch_index
1090 // and we are not retrying, we need to invalidate its queue_index.
1091 message->header.queue_index.Invalidate();
1092 return Result::MESSAGES_SENT_TOO_FAST;
1093 }
1094 }
1095
Austin Schuh20b2b082019-09-11 20:42:56 -07001096 // Before we are fully done filling out the message, update the Sender state
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001097 // with the new index to write. This re-uses the barrier for the
Austin Schuh20b2b082019-09-11 20:42:56 -07001098 // queue_index store.
Alex Perrycb7da4b2019-08-28 19:35:56 -07001099 const Index index_to_write(next_queue_index, scratch_index.message_index());
Austin Schuh20b2b082019-09-11 20:42:56 -07001100
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001101 aos_compiler_memory_barrier();
1102 // We're the only person who cares about our scratch index, besides somebody
1103 // cleaning up after us.
Austin Schuh20b2b082019-09-11 20:42:56 -07001104 sender->scratch_index.RelaxedStore(index_to_write);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001105 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -07001106
1107 message->header.queue_index.Store(next_queue_index);
1108
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001109 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -07001110 // The message is now filled out, and we have a confirmed slot to store
1111 // into.
1112 //
1113 // Start by writing down what we are going to pull out of the queue. This
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001114 // was Invalid before now. Only person who will read this is whoever cleans
1115 // up after us, so no synchronization necessary.
Austin Schuh20b2b082019-09-11 20:42:56 -07001116 sender->to_replace.RelaxedStore(to_replace);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001117 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -07001118
1119 // Then exchange the next index into the queue.
1120 if (!memory_->GetQueue(next_queue_index.Wrapped())
1121 ->CompareAndExchangeStrong(to_replace, index_to_write)) {
1122 // Aw, didn't succeed. Retry.
1123 sender->to_replace.RelaxedInvalidate();
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001124 aos_compiler_memory_barrier();
Alex Perrycb7da4b2019-08-28 19:35:56 -07001125 VLOG(3) << "Failed to wrap into queue";
Austin Schuh20b2b082019-09-11 20:42:56 -07001126 continue;
1127 }
1128
1129 // Then update next_queue_index to save the next user some computation time.
1130 memory_->next_queue_index.CompareAndExchangeStrong(actual_next_queue_index,
1131 incremented_queue_index);
1132
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001133 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -07001134 // Now update the scratch space and record that we succeeded.
1135 sender->scratch_index.Store(to_replace);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001136 aos_compiler_memory_barrier();
1137 // And then record that we succeeded, but definitely after the above store.
Austin Schuh20b2b082019-09-11 20:42:56 -07001138 sender->to_replace.RelaxedInvalidate();
Brian Silverman177567e2020-08-12 19:51:33 -07001139
Austin Schuh20b2b082019-09-11 20:42:56 -07001140 break;
1141 }
Brian Silverman177567e2020-08-12 19:51:33 -07001142
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001143 DCHECK(!CheckBothRedzones(memory_, memory_->GetMessage(to_replace)))
1144 << ": Invalid message found in shared memory";
Brian Silverman177567e2020-08-12 19:51:33 -07001145 // to_replace is our current scratch_index. It isn't in the queue, which means
1146 // nobody new can pin it. They can set their `pinned` to it, but they will
1147 // back it out, so they don't count. This means that we just need to find a
1148 // message for which no pinner had it in `pinned`, and then we know this
1149 // message will never be pinned. We'll start with to_replace, and if that is
1150 // pinned then we'll look for a new one to use instead.
1151 const Index new_scratch =
1152 SwapPinnedSenderScratch(memory_, sender, to_replace);
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001153 DCHECK(!CheckBothRedzones(
1154 memory_, memory_->GetMessage(sender->scratch_index.RelaxedLoad())))
1155 << ": Invalid message found in shared memory";
Brian Silverman177567e2020-08-12 19:51:33 -07001156
1157 // If anybody is looking at this message (they shouldn't be), then try telling
1158 // them about it (best-effort).
1159 memory_->GetMessage(new_scratch)->header.queue_index.RelaxedInvalidate();
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001160 return Result::GOOD;
Austin Schuh20b2b082019-09-11 20:42:56 -07001161}
1162
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001163int LocklessQueueSender::buffer_index() const {
Brian Silverman4f4e0612020-08-12 19:54:41 -07001164 ::aos::ipc_lib::Sender *const sender = memory_->GetSender(sender_index_);
1165 // We can do a relaxed load on our sender because we're the only person
1166 // modifying it right now.
1167 const Index scratch_index = sender->scratch_index.RelaxedLoad();
1168 return scratch_index.message_index();
1169}
1170
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001171LocklessQueuePinner::LocklessQueuePinner(
1172 LocklessQueueMemory *memory, const LocklessQueueMemory *const_memory)
1173 : memory_(memory), const_memory_(const_memory) {
1174 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory_);
1175
1176 // Since we already have the lock, go ahead and try cleaning up.
1177 Cleanup(memory_, grab_queue_setup_lock);
1178
1179 const int num_pinners = memory_->num_pinners();
1180
1181 for (int i = 0; i < num_pinners; ++i) {
1182 ::aos::ipc_lib::Pinner *p = memory->GetPinner(i);
1183 // This doesn't need synchronization because we're the only process doing
1184 // initialization right now, and nobody else will be touching pinners which
1185 // we're interested in.
1186 const uint32_t tid = __atomic_load_n(&(p->tid.futex), __ATOMIC_RELAXED);
1187 if (tid == 0) {
1188 pinner_index_ = i;
1189 break;
1190 }
1191 }
1192
1193 if (pinner_index_ == -1) {
1194 VLOG(1) << "Too many pinners, starting to bail.";
1195 return;
1196 }
1197
1198 ::aos::ipc_lib::Pinner *p = memory_->GetPinner(pinner_index_);
1199 p->pinned.Invalidate();
1200
1201 // Indicate that we are now alive by taking over the slot. If the previous
1202 // owner died, we still want to do this.
1203 death_notification_init(&(p->tid));
1204}
1205
1206LocklessQueuePinner::~LocklessQueuePinner() {
1207 if (pinner_index_ != -1) {
1208 CHECK(memory_ != nullptr);
1209 memory_->GetPinner(pinner_index_)->pinned.Invalidate();
1210 aos_compiler_memory_barrier();
1211 death_notification_release(&(memory_->GetPinner(pinner_index_)->tid));
1212 }
1213}
1214
1215std::optional<LocklessQueuePinner> LocklessQueuePinner::Make(
1216 LocklessQueue queue) {
1217 queue.Initialize();
1218 LocklessQueuePinner result(queue.memory(), queue.const_memory());
1219 if (result.pinner_index_ != -1) {
James Kuszmaul9776b392023-01-14 14:08:08 -08001220 return result;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001221 } else {
1222 return std::nullopt;
1223 }
1224}
1225
1226// This method doesn't mess with any scratch_index, so it doesn't have to worry
1227// about message ownership.
1228int LocklessQueuePinner::PinIndex(uint32_t uint32_queue_index) {
1229 const size_t queue_size = memory_->queue_size();
1230 const QueueIndex queue_index =
1231 QueueIndex::Zero(queue_size).IncrementBy(uint32_queue_index);
1232 ipc_lib::Pinner *const pinner = memory_->GetPinner(pinner_index_);
1233
1234 AtomicIndex *const queue_slot = memory_->GetQueue(queue_index.Wrapped());
1235
1236 // Indicate that we want to pin this message.
1237 pinner->pinned.Store(queue_index);
1238 aos_compiler_memory_barrier();
1239
1240 {
1241 const Index message_index = queue_slot->Load();
1242 Message *const message = memory_->GetMessage(message_index);
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001243 DCHECK(!CheckBothRedzones(memory_, message))
1244 << ": Invalid message found in shared memory";
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001245
1246 const QueueIndex message_queue_index =
1247 message->header.queue_index.Load(queue_size);
1248 if (message_queue_index == queue_index) {
1249 VLOG(3) << "Eq: " << std::hex << message_queue_index.index();
1250 aos_compiler_memory_barrier();
1251 return message_index.message_index();
1252 }
1253 VLOG(3) << "Message reused: " << std::hex << message_queue_index.index()
1254 << ", " << queue_index.index();
1255 }
1256
1257 // Being down here means we asked to pin a message before realizing it's no
1258 // longer in the queue, so back that out now.
1259 pinner->pinned.Invalidate();
1260 VLOG(3) << "Unpinned: " << std::hex << queue_index.index();
1261 return -1;
1262}
1263
1264size_t LocklessQueuePinner::size() const {
1265 return const_memory_->message_data_size();
1266}
1267
1268const void *LocklessQueuePinner::Data() const {
1269 const size_t queue_size = const_memory_->queue_size();
1270 const ::aos::ipc_lib::Pinner *const pinner =
1271 const_memory_->GetPinner(pinner_index_);
1272 QueueIndex pinned = pinner->pinned.RelaxedLoad(queue_size);
1273 CHECK(pinned.valid());
1274 const Message *message = const_memory_->GetMessage(pinned);
1275
1276 return message->data(const_memory_->message_data_size());
1277}
1278
1279LocklessQueueReader::Result LocklessQueueReader::Read(
Austin Schuh20b2b082019-09-11 20:42:56 -07001280 uint32_t uint32_queue_index,
Austin Schuhb5c6f972021-03-14 21:53:07 -07001281 monotonic_clock::time_point *monotonic_sent_time,
1282 realtime_clock::time_point *realtime_sent_time,
1283 monotonic_clock::time_point *monotonic_remote_time,
1284 realtime_clock::time_point *realtime_remote_time,
Austin Schuha9012be2021-07-21 15:19:11 -07001285 uint32_t *remote_queue_index, UUID *source_boot_uuid, size_t *length,
Austin Schuh82ea7382023-07-14 15:17:34 -07001286 char *data, std::function<bool(const Context &)> should_read) const {
Austin Schuh20b2b082019-09-11 20:42:56 -07001287 const size_t queue_size = memory_->queue_size();
1288
1289 // Build up the QueueIndex.
1290 const QueueIndex queue_index =
1291 QueueIndex::Zero(queue_size).IncrementBy(uint32_queue_index);
1292
1293 // Read the message stored at the requested location.
1294 Index mi = memory_->LoadIndex(queue_index);
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001295 const Message *m = memory_->GetMessage(mi);
Austin Schuh20b2b082019-09-11 20:42:56 -07001296
1297 while (true) {
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001298 DCHECK(!CheckBothRedzones(memory_, m))
1299 << ": Invalid message found in shared memory";
Austin Schuh20b2b082019-09-11 20:42:56 -07001300 // We need to confirm that the data doesn't change while we are reading it.
1301 // Do that by first confirming that the message points to the queue index we
1302 // want.
1303 const QueueIndex starting_queue_index =
1304 m->header.queue_index.Load(queue_size);
1305 if (starting_queue_index != queue_index) {
1306 // If we found a message that is exactly 1 loop old, we just wrapped.
1307 if (starting_queue_index == queue_index.DecrementBy(queue_size)) {
Alex Perrycb7da4b2019-08-28 19:35:56 -07001308 VLOG(3) << "Matches: " << std::hex << starting_queue_index.index()
1309 << ", " << queue_index.DecrementBy(queue_size).index();
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001310 return Result::NOTHING_NEW;
Brian Silverman177567e2020-08-12 19:51:33 -07001311 }
1312
1313 // Someone has re-used this message between when we pulled it out of the
1314 // queue and when we grabbed its index. It is pretty hard to deduce
1315 // what happened. Just try again.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001316 const Message *const new_m = memory_->GetMessage(queue_index);
Brian Silverman177567e2020-08-12 19:51:33 -07001317 if (m != new_m) {
1318 m = new_m;
1319 VLOG(3) << "Retrying, m doesn't match";
1320 continue;
1321 }
1322
1323 // We have confirmed that message still points to the same message. This
1324 // means that the message didn't get swapped out from under us, so
1325 // starting_queue_index is correct.
1326 //
1327 // Either we got too far behind (signaled by this being a valid
1328 // message), or this is one of the initial messages which are invalid.
1329 if (starting_queue_index.valid()) {
1330 VLOG(3) << "Too old. Tried for " << std::hex << queue_index.index()
1331 << ", got " << starting_queue_index.index() << ", behind by "
1332 << std::dec
1333 << (starting_queue_index.index() - queue_index.index());
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001334 return Result::TOO_OLD;
Brian Silverman177567e2020-08-12 19:51:33 -07001335 }
1336
1337 VLOG(3) << "Initial";
1338
1339 // There isn't a valid message at this location.
1340 //
1341 // If someone asks for one of the messages within the first go around,
1342 // then they need to wait. They got ahead. Otherwise, they are
1343 // asking for something crazy, like something before the beginning of
1344 // the queue. Tell them that they are behind.
1345 if (uint32_queue_index < memory_->queue_size()) {
1346 VLOG(3) << "Near zero, " << std::hex << uint32_queue_index;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001347 return Result::NOTHING_NEW;
Austin Schuh20b2b082019-09-11 20:42:56 -07001348 } else {
Brian Silverman177567e2020-08-12 19:51:33 -07001349 VLOG(3) << "Not near zero, " << std::hex << uint32_queue_index;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001350 return Result::TOO_OLD;
Austin Schuh20b2b082019-09-11 20:42:56 -07001351 }
1352 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001353 VLOG(3) << "Eq: " << std::hex << starting_queue_index.index() << ", "
1354 << queue_index.index();
Austin Schuh20b2b082019-09-11 20:42:56 -07001355 break;
1356 }
1357
Alex Perrycb7da4b2019-08-28 19:35:56 -07001358 // Then read the data out. Copy it all out to be deterministic and so we can
1359 // make length be from either end.
Austin Schuh82ea7382023-07-14 15:17:34 -07001360 if (!should_read) {
1361 *monotonic_sent_time = m->header.monotonic_sent_time;
1362 *realtime_sent_time = m->header.realtime_sent_time;
1363 if (m->header.remote_queue_index == 0xffffffffu) {
1364 *remote_queue_index = queue_index.index();
1365 } else {
1366 *remote_queue_index = m->header.remote_queue_index;
1367 }
1368 *monotonic_remote_time = m->header.monotonic_remote_time;
1369 *realtime_remote_time = m->header.realtime_remote_time;
1370 *source_boot_uuid = m->header.source_boot_uuid;
1371 *length = m->header.length;
Austin Schuhad154822019-12-27 15:45:13 -08001372 } else {
Austin Schuh82ea7382023-07-14 15:17:34 -07001373 // Cache the header results so we don't modify the outputs unless the filter
1374 // function says "go".
1375 Context context;
1376 context.monotonic_event_time = m->header.monotonic_sent_time;
1377 context.realtime_event_time = m->header.realtime_sent_time;
1378 context.monotonic_remote_time = m->header.monotonic_remote_time;
1379 context.realtime_remote_time = m->header.realtime_remote_time;
1380 context.queue_index = queue_index.index();
1381 if (m->header.remote_queue_index == 0xffffffffu) {
1382 context.remote_queue_index = context.queue_index;
1383 } else {
1384 context.remote_queue_index = m->header.remote_queue_index;
1385 }
1386 context.source_boot_uuid = m->header.source_boot_uuid;
1387 context.size = m->header.length;
1388 context.data = nullptr;
1389 context.buffer_index = -1;
1390
1391 // And finally, confirm that the message *still* points to the queue index
1392 // we want. This means it didn't change out from under us. If something
1393 // changed out from under us, we were reading it much too late in its
1394 // lifetime.
1395 aos_compiler_memory_barrier();
1396 const QueueIndex final_queue_index = m->header.queue_index.Load(queue_size);
1397 if (final_queue_index != queue_index) {
1398 VLOG(3) << "Changed out from under us. Reading " << std::hex
1399 << queue_index.index() << ", finished with "
1400 << final_queue_index.index() << ", delta: " << std::dec
1401 << (final_queue_index.index() - queue_index.index());
1402 return Result::OVERWROTE;
1403 }
1404
1405 // We now know that the context is safe to use. See if we are supposed to
1406 // take the message or not.
1407 if (!should_read(context)) {
1408 return Result::FILTERED;
1409 }
1410
1411 // And now take it.
1412 *monotonic_sent_time = context.monotonic_event_time;
1413 *realtime_sent_time = context.realtime_event_time;
1414 *remote_queue_index = context.remote_queue_index;
1415 *monotonic_remote_time = context.monotonic_remote_time;
1416 *realtime_remote_time = context.realtime_remote_time;
1417 *source_boot_uuid = context.source_boot_uuid;
1418 *length = context.size;
Austin Schuhad154822019-12-27 15:45:13 -08001419 }
Brian Silverman6b8a3c32020-03-06 11:26:14 -08001420 if (data) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001421 memcpy(data, m->data(memory_->message_data_size()),
1422 memory_->message_data_size());
Austin Schuh20b2b082019-09-11 20:42:56 -07001423
Austin Schuh82ea7382023-07-14 15:17:34 -07001424 // Check again since we touched the message again.
1425 aos_compiler_memory_barrier();
1426 const QueueIndex final_queue_index = m->header.queue_index.Load(queue_size);
1427 if (final_queue_index != queue_index) {
1428 VLOG(3) << "Changed out from under us. Reading " << std::hex
1429 << queue_index.index() << ", finished with "
1430 << final_queue_index.index() << ", delta: " << std::dec
1431 << (final_queue_index.index() - queue_index.index());
1432 return Result::OVERWROTE;
1433 }
Austin Schuh20b2b082019-09-11 20:42:56 -07001434 }
1435
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001436 return Result::GOOD;
Austin Schuh20b2b082019-09-11 20:42:56 -07001437}
1438
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001439QueueIndex LocklessQueueReader::LatestIndex() const {
Austin Schuh20b2b082019-09-11 20:42:56 -07001440 const size_t queue_size = memory_->queue_size();
1441
1442 // There is only one interesting case. We need to know if the queue is empty.
1443 // That is done with a sentinel value. At worst, this will be off by one.
1444 const QueueIndex next_queue_index =
1445 memory_->next_queue_index.Load(queue_size);
1446 if (next_queue_index.valid()) {
1447 const QueueIndex current_queue_index = next_queue_index.DecrementBy(1u);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001448 return current_queue_index;
Austin Schuh20b2b082019-09-11 20:42:56 -07001449 }
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001450 return QueueIndex::Invalid();
1451}
1452
1453size_t LocklessQueueSize(const LocklessQueueMemory *memory) {
1454 return memory->queue_size();
1455}
1456
1457size_t LocklessQueueMessageDataSize(const LocklessQueueMemory *memory) {
1458 return memory->message_data_size();
Austin Schuh20b2b082019-09-11 20:42:56 -07001459}
1460
1461namespace {
1462
1463// Prints out the mutex state. Not safe to use while the mutex is being
1464// changed.
Austin Schuh83cbb1e2023-06-23 12:59:02 -07001465::std::string PrintMutex(const aos_mutex *mutex) {
Austin Schuh20b2b082019-09-11 20:42:56 -07001466 ::std::stringstream s;
1467 s << "aos_mutex(" << ::std::hex << mutex->futex;
1468
1469 if (mutex->futex != 0) {
1470 s << ":";
1471 if (mutex->futex & FUTEX_OWNER_DIED) {
1472 s << "FUTEX_OWNER_DIED|";
1473 }
1474 s << "tid=" << (mutex->futex & FUTEX_TID_MASK);
1475 }
1476
1477 s << ")";
1478 return s.str();
1479}
1480
1481} // namespace
1482
Austin Schuh83cbb1e2023-06-23 12:59:02 -07001483void PrintLocklessQueueMemory(const LocklessQueueMemory *memory) {
Austin Schuh20b2b082019-09-11 20:42:56 -07001484 const size_t queue_size = memory->queue_size();
1485 ::std::cout << "LocklessQueueMemory (" << memory << ") {" << ::std::endl;
1486 ::std::cout << " aos_mutex queue_setup_lock = "
1487 << PrintMutex(&memory->queue_setup_lock) << ::std::endl;
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001488 ::std::cout << " bool initialized = " << memory->initialized << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001489 ::std::cout << " config {" << ::std::endl;
1490 ::std::cout << " size_t num_watchers = " << memory->config.num_watchers
1491 << ::std::endl;
1492 ::std::cout << " size_t num_senders = " << memory->config.num_senders
1493 << ::std::endl;
Brian Silverman177567e2020-08-12 19:51:33 -07001494 ::std::cout << " size_t num_pinners = " << memory->config.num_pinners
1495 << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001496 ::std::cout << " size_t queue_size = " << memory->config.queue_size
1497 << ::std::endl;
1498 ::std::cout << " size_t message_data_size = "
1499 << memory->config.message_data_size << ::std::endl;
1500
1501 ::std::cout << " AtomicQueueIndex next_queue_index = "
1502 << memory->next_queue_index.Load(queue_size).DebugString()
1503 << ::std::endl;
1504
Austin Schuh3328d132020-02-28 13:54:57 -08001505 ::std::cout << " uid_t uid = " << memory->uid << ::std::endl;
1506
Austin Schuh20b2b082019-09-11 20:42:56 -07001507 ::std::cout << " }" << ::std::endl;
1508 ::std::cout << " AtomicIndex queue[" << queue_size << "] {" << ::std::endl;
1509 for (size_t i = 0; i < queue_size; ++i) {
1510 ::std::cout << " [" << i << "] -> "
1511 << memory->GetQueue(i)->Load().DebugString() << ::std::endl;
1512 }
1513 ::std::cout << " }" << ::std::endl;
1514 ::std::cout << " Message messages[" << memory->num_messages() << "] {"
1515 << ::std::endl;
1516 for (size_t i = 0; i < memory->num_messages(); ++i) {
Austin Schuh83cbb1e2023-06-23 12:59:02 -07001517 const Message *m = memory->GetMessage(Index(i, i));
Brian Silverman001f24d2020-08-12 19:33:20 -07001518 ::std::cout << " [" << i << "] -> Message 0x" << std::hex
1519 << (reinterpret_cast<uintptr_t>(
1520 memory->GetMessage(Index(i, i))) -
1521 reinterpret_cast<uintptr_t>(memory))
1522 << std::dec << " {" << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001523 ::std::cout << " Header {" << ::std::endl;
1524 ::std::cout << " AtomicQueueIndex queue_index = "
1525 << m->header.queue_index.Load(queue_size).DebugString()
1526 << ::std::endl;
Brian Silverman001f24d2020-08-12 19:33:20 -07001527 ::std::cout << " monotonic_clock::time_point monotonic_sent_time = "
1528 << m->header.monotonic_sent_time << " 0x" << std::hex
1529 << m->header.monotonic_sent_time.time_since_epoch().count()
1530 << std::dec << ::std::endl;
1531 ::std::cout << " realtime_clock::time_point realtime_sent_time = "
1532 << m->header.realtime_sent_time << " 0x" << std::hex
1533 << m->header.realtime_sent_time.time_since_epoch().count()
1534 << std::dec << ::std::endl;
1535 ::std::cout
1536 << " monotonic_clock::time_point monotonic_remote_time = "
1537 << m->header.monotonic_remote_time << " 0x" << std::hex
1538 << m->header.monotonic_remote_time.time_since_epoch().count()
1539 << std::dec << ::std::endl;
1540 ::std::cout << " realtime_clock::time_point realtime_remote_time = "
1541 << m->header.realtime_remote_time << " 0x" << std::hex
1542 << m->header.realtime_remote_time.time_since_epoch().count()
1543 << std::dec << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001544 ::std::cout << " size_t length = " << m->header.length
1545 << ::std::endl;
1546 ::std::cout << " }" << ::std::endl;
Austin Schuhbe416742020-10-03 17:24:26 -07001547 const bool corrupt = CheckBothRedzones(memory, m);
1548 if (corrupt) {
Austin Schuh83cbb1e2023-06-23 12:59:02 -07001549 absl::Span<const char> pre_redzone =
1550 m->PreRedzone(memory->message_data_size());
1551 absl::Span<const char> post_redzone =
Austin Schuhbe416742020-10-03 17:24:26 -07001552 m->PostRedzone(memory->message_data_size(), memory->message_size());
1553
1554 ::std::cout << " pre-redzone: \""
1555 << absl::BytesToHexString(std::string_view(
1556 pre_redzone.data(), pre_redzone.size()))
1557 << std::endl;
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001558 ::std::cout << " // *** DATA REDZONES ARE CORRUPTED ***"
1559 << ::std::endl;
Austin Schuhbe416742020-10-03 17:24:26 -07001560 ::std::cout << " post-redzone: \""
1561 << absl::BytesToHexString(std::string_view(
1562 post_redzone.data(), post_redzone.size()))
1563 << std::endl;
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001564 }
Austin Schuh20b2b082019-09-11 20:42:56 -07001565 ::std::cout << " data: {";
1566
Brian Silverman001f24d2020-08-12 19:33:20 -07001567 if (FLAGS_dump_lockless_queue_data) {
1568 const char *const m_data = m->data(memory->message_data_size());
Austin Schuhbe416742020-10-03 17:24:26 -07001569 std::cout << absl::BytesToHexString(std::string_view(
1570 m_data, corrupt ? memory->message_data_size() : m->header.length));
Austin Schuh20b2b082019-09-11 20:42:56 -07001571 }
1572 ::std::cout << ::std::setfill(' ') << ::std::dec << "}" << ::std::endl;
1573 ::std::cout << " }," << ::std::endl;
1574 }
1575 ::std::cout << " }" << ::std::endl;
1576
Alex Perrycb7da4b2019-08-28 19:35:56 -07001577 ::std::cout << " Sender senders[" << memory->num_senders() << "] {"
1578 << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001579 for (size_t i = 0; i < memory->num_senders(); ++i) {
Austin Schuh83cbb1e2023-06-23 12:59:02 -07001580 const Sender *s = memory->GetSender(i);
Austin Schuh20b2b082019-09-11 20:42:56 -07001581 ::std::cout << " [" << i << "] -> Sender {" << ::std::endl;
1582 ::std::cout << " aos_mutex tid = " << PrintMutex(&s->tid)
1583 << ::std::endl;
1584 ::std::cout << " AtomicIndex scratch_index = "
1585 << s->scratch_index.Load().DebugString() << ::std::endl;
1586 ::std::cout << " AtomicIndex to_replace = "
1587 << s->to_replace.Load().DebugString() << ::std::endl;
1588 ::std::cout << " }" << ::std::endl;
1589 }
1590 ::std::cout << " }" << ::std::endl;
1591
Brian Silverman177567e2020-08-12 19:51:33 -07001592 ::std::cout << " Pinner pinners[" << memory->num_pinners() << "] {"
1593 << ::std::endl;
1594 for (size_t i = 0; i < memory->num_pinners(); ++i) {
Austin Schuh83cbb1e2023-06-23 12:59:02 -07001595 const Pinner *p = memory->GetPinner(i);
Brian Silverman177567e2020-08-12 19:51:33 -07001596 ::std::cout << " [" << i << "] -> Pinner {" << ::std::endl;
1597 ::std::cout << " aos_mutex tid = " << PrintMutex(&p->tid)
1598 << ::std::endl;
1599 ::std::cout << " AtomicIndex scratch_index = "
1600 << p->scratch_index.Load().DebugString() << ::std::endl;
1601 ::std::cout << " AtomicIndex pinned = "
1602 << p->pinned.Load(memory->queue_size()).DebugString()
1603 << ::std::endl;
1604 ::std::cout << " }" << ::std::endl;
1605 }
1606 ::std::cout << " }" << ::std::endl;
1607
Austin Schuh20b2b082019-09-11 20:42:56 -07001608 ::std::cout << " Watcher watchers[" << memory->num_watchers() << "] {"
1609 << ::std::endl;
1610 for (size_t i = 0; i < memory->num_watchers(); ++i) {
Austin Schuh83cbb1e2023-06-23 12:59:02 -07001611 const Watcher *w = memory->GetWatcher(i);
Austin Schuh20b2b082019-09-11 20:42:56 -07001612 ::std::cout << " [" << i << "] -> Watcher {" << ::std::endl;
1613 ::std::cout << " aos_mutex tid = " << PrintMutex(&w->tid)
1614 << ::std::endl;
1615 ::std::cout << " pid_t pid = " << w->pid << ::std::endl;
1616 ::std::cout << " int priority = " << w->priority << ::std::endl;
1617 ::std::cout << " }" << ::std::endl;
1618 }
1619 ::std::cout << " }" << ::std::endl;
1620
1621 ::std::cout << "}" << ::std::endl;
1622}
1623
1624} // namespace ipc_lib
1625} // namespace aos