blob: 2b704ef84f9bccb3d83054b05ea7c4d56b7511a1 [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>
7#include <algorithm>
8#include <iomanip>
9#include <iostream>
10#include <sstream>
11
Austin Schuhbe416742020-10-03 17:24:26 -070012#include "absl/strings/escaping.h"
Austin Schuh20b2b082019-09-11 20:42:56 -070013#include "aos/ipc_lib/lockless_queue_memory.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070014#include "aos/realtime.h"
Austin Schuh20b2b082019-09-11 20:42:56 -070015#include "aos/util/compiler_memory_barrier.h"
Brian Silverman001f24d2020-08-12 19:33:20 -070016#include "gflags/gflags.h"
Austin Schuhf257f3c2019-10-27 21:00:43 -070017#include "glog/logging.h"
Austin Schuh20b2b082019-09-11 20:42:56 -070018
Brian Silverman001f24d2020-08-12 19:33:20 -070019DEFINE_bool(dump_lockless_queue_data, false,
20 "If true, print the data out when dumping the queue.");
21
Austin Schuh20b2b082019-09-11 20:42:56 -070022namespace aos {
23namespace ipc_lib {
Austin Schuh20b2b082019-09-11 20:42:56 -070024namespace {
25
Brian Silvermanfafe1fa2019-12-18 21:42:18 -080026class GrabQueueSetupLockOrDie {
27 public:
28 GrabQueueSetupLockOrDie(LocklessQueueMemory *memory) : memory_(memory) {
29 const int result = mutex_grab(&(memory->queue_setup_lock));
30 CHECK(result == 0 || result == 1) << ": " << result;
31 }
Austin Schuh20b2b082019-09-11 20:42:56 -070032
Brian Silvermanfafe1fa2019-12-18 21:42:18 -080033 ~GrabQueueSetupLockOrDie() { mutex_unlock(&(memory_->queue_setup_lock)); }
34
35 GrabQueueSetupLockOrDie(const GrabQueueSetupLockOrDie &) = delete;
36 GrabQueueSetupLockOrDie &operator=(const GrabQueueSetupLockOrDie &) = delete;
37
38 private:
39 LocklessQueueMemory *const memory_;
40};
41
Brian Silverman177567e2020-08-12 19:51:33 -070042bool IsPinned(LocklessQueueMemory *memory, Index index) {
43 DCHECK(index.valid());
44 const size_t queue_size = memory->queue_size();
45 const QueueIndex message_index =
46 memory->GetMessage(index)->header.queue_index.Load(queue_size);
47 if (!message_index.valid()) {
48 return false;
49 }
50 DCHECK(memory->GetQueue(message_index.Wrapped())->Load() != index)
51 << ": Message is in the queue";
52 for (int pinner_index = 0;
53 pinner_index < static_cast<int>(memory->config.num_pinners);
54 ++pinner_index) {
55 ipc_lib::Pinner *const pinner = memory->GetPinner(pinner_index);
56
57 if (pinner->pinned.RelaxedLoad(queue_size) == message_index) {
58 return true;
59 }
60 }
61 return false;
62}
63
64// Ensures sender->scratch_index (which must contain to_replace) is not pinned.
65//
66// Returns the new scratch_index value.
67Index SwapPinnedSenderScratch(LocklessQueueMemory *const memory,
68 ipc_lib::Sender *const sender,
69 const Index to_replace) {
70 // If anybody's trying to pin this message, then grab a message from a pinner
71 // to write into instead, and leave the message we pulled out of the queue
72 // (currently in our scratch_index) with a pinner.
73 //
74 // This loop will terminate in at most one iteration through the pinners in
75 // any steady-state configuration of the memory. There are only as many
76 // Pinner::pinned values to worry about as there are Pinner::scratch_index
77 // values to check against, plus to_replace, which means there will always be
78 // a free one. We might have to make multiple passes if things are being
79 // changed concurrently though, but nobody dying can make this loop fail to
80 // terminate (because the number of processes that can die is bounded, because
81 // no new ones can start while we've got the lock).
82 for (int pinner_index = 0; true;
83 pinner_index = (pinner_index + 1) % memory->config.num_pinners) {
84 if (!IsPinned(memory, to_replace)) {
85 // No pinners on our current scratch_index, so we're fine now.
86 VLOG(3) << "No pinners: " << to_replace.DebugString();
87 return to_replace;
88 }
89
90 ipc_lib::Pinner *const pinner = memory->GetPinner(pinner_index);
91
92 const Index pinner_scratch = pinner->scratch_index.RelaxedLoad();
93 CHECK(pinner_scratch.valid())
94 << ": Pinner scratch_index should always be valid";
95 if (IsPinned(memory, pinner_scratch)) {
96 // Wouldn't do us any good to swap with this one, so don't bother, and
97 // move onto the next one.
98 VLOG(3) << "Also pinned: " << pinner_scratch.DebugString();
99 continue;
100 }
101
102 sender->to_replace.RelaxedStore(pinner_scratch);
103 aos_compiler_memory_barrier();
104 // Give the pinner the message (which is currently in
105 // sender->scratch_index).
106 if (!pinner->scratch_index.CompareAndExchangeStrong(pinner_scratch,
107 to_replace)) {
108 // Somebody swapped into this pinner before us. The new value is probably
109 // pinned, so we don't want to look at it again immediately.
110 VLOG(3) << "Pinner " << pinner_index
111 << " scratch_index changed: " << pinner_scratch.DebugString()
112 << ", " << to_replace.DebugString();
113 sender->to_replace.RelaxedInvalidate();
114 continue;
115 }
116 aos_compiler_memory_barrier();
117 // Now update the sender's scratch space and record that we succeeded.
118 sender->scratch_index.Store(pinner_scratch);
119 aos_compiler_memory_barrier();
120 // And then record that we succeeded, but definitely after the above
121 // store.
122 sender->to_replace.RelaxedInvalidate();
123 VLOG(3) << "Got new scratch message: " << pinner_scratch.DebugString();
124
125 // If it's in a pinner's scratch_index, it should not be in the queue, which
126 // means nobody new can pin it for real. However, they can still attempt to
127 // pin it, which means we can't verify !IsPinned down here.
128
129 return pinner_scratch;
130 }
131}
132
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700133// Returns true if it succeeded. Returns false if another sender died in the
134// middle.
135bool DoCleanup(LocklessQueueMemory *memory, const GrabQueueSetupLockOrDie &) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800136 // Make sure we start looking at shared memory fresh right now. We'll handle
137 // people dying partway through by either cleaning up after them or not, but
138 // we want to ensure we clean up after anybody who has already died when we
139 // start.
140 aos_compiler_memory_barrier();
141
Austin Schuh20b2b082019-09-11 20:42:56 -0700142 const size_t num_senders = memory->num_senders();
Brian Silverman177567e2020-08-12 19:51:33 -0700143 const size_t num_pinners = memory->num_pinners();
Austin Schuh20b2b082019-09-11 20:42:56 -0700144 const size_t queue_size = memory->queue_size();
145 const size_t num_messages = memory->num_messages();
146
147 // There are a large number of crazy cases here for how things can go wrong
148 // and how we have to recover. They either require us to keep extra track of
149 // what is going on, slowing down the send path, or require a large number of
150 // cases.
151 //
152 // The solution here is to not over-think it. This is running while not real
153 // time during construction. It is allowed to be slow. It will also very
154 // rarely trigger. There is a small uS window where process death is
155 // ambiguous.
156 //
157 // So, build up a list N long, where N is the number of messages. Search
158 // through the entire queue and the sender list (ignoring any dead senders),
159 // and mark down which ones we have seen. Once we have seen all the messages
160 // except the N dead senders, we know which messages are dead. Because the
161 // queue is active while we do this, it may take a couple of go arounds to see
162 // everything.
163
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700164 ::std::vector<bool> need_recovery(num_senders, false);
165
Austin Schuh20b2b082019-09-11 20:42:56 -0700166 // Do the easy case. Find all senders who have died. See if they are either
167 // consistent already, or if they have copied over to_replace to the scratch
168 // index, but haven't cleared to_replace. Count them.
169 size_t valid_senders = 0;
170 for (size_t i = 0; i < num_senders; ++i) {
171 Sender *sender = memory->GetSender(i);
172 const uint32_t tid =
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800173 __atomic_load_n(&(sender->tid.futex), __ATOMIC_ACQUIRE);
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700174 if (!(tid & FUTEX_OWNER_DIED)) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700175 // Not dead.
176 ++valid_senders;
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700177 continue;
Austin Schuh20b2b082019-09-11 20:42:56 -0700178 }
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700179 VLOG(3) << "Found an easy death for sender " << i;
180 // We can do a relaxed load here because we're the only person touching
181 // this sender at this point.
182 const Index to_replace = sender->to_replace.RelaxedLoad();
183 const Index scratch_index = sender->scratch_index.Load();
184
185 // I find it easiest to think about this in terms of the set of observable
186 // states. The main code progresses through the following states:
187
188 // 1) scratch_index = xxx
189 // to_replace = invalid
190 // This is unambiguous. Already good.
191
192 // 2) scratch_index = xxx
193 // to_replace = yyy
194 // Very ambiguous. Is xxx or yyy the correct one? Need to either roll
195 // this forwards or backwards.
196
197 // 3) scratch_index = yyy
198 // to_replace = yyy
199 // We are in the act of moving to_replace to scratch_index, but didn't
200 // finish. Easy.
Brian Silverman177567e2020-08-12 19:51:33 -0700201 //
202 // If doing a pinner swap, we've definitely done it.
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700203
204 // 4) scratch_index = yyy
205 // to_replace = invalid
206 // Finished, but died. Looks like 1)
207
Brian Silverman177567e2020-08-12 19:51:33 -0700208 // Swapping with a pinner's scratch_index passes through the same states.
209 // We just need to ensure the message that ends up in the senders's
210 // scratch_index isn't pinned, using the same code as sending does.
211
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700212 // Any cleanup code needs to follow the same set of states to be robust to
213 // death, so death can be restarted.
214
215 if (!to_replace.valid()) {
216 // 1) or 4). Make sure we aren't corrupted and declare victory.
217 CHECK(scratch_index.valid());
218
Brian Silverman177567e2020-08-12 19:51:33 -0700219 // If it's in 1) with a pinner, the sender might have a pinned message,
220 // so fix that.
221 SwapPinnedSenderScratch(memory, sender, scratch_index);
222
223 // If it's in 4), it may not have completed this step yet. This will
224 // always be a NOP if it's in 1), verified by a DCHECK.
225 memory->GetMessage(scratch_index)->header.queue_index.RelaxedInvalidate();
226
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700227 __atomic_store_n(&(sender->tid.futex), 0, __ATOMIC_RELEASE);
228 ++valid_senders;
229 continue;
230 }
231
232 // Could be 2) or 3) at this point.
233
234 if (to_replace == scratch_index) {
235 // 3) for sure.
236 // Just need to invalidate to_replace to finish.
237 sender->to_replace.Invalidate();
238
Brian Silverman177567e2020-08-12 19:51:33 -0700239 // Make sure to indicate it's an unused message before a sender gets its
240 // hands on it.
241 memory->GetMessage(scratch_index)->header.queue_index.RelaxedInvalidate();
242 aos_compiler_memory_barrier();
243
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700244 // And mark that we succeeded.
245 __atomic_store_n(&(sender->tid.futex), 0, __ATOMIC_RELEASE);
246 ++valid_senders;
247 continue;
248 }
249
250 // Must be 2). Mark it for later.
251 need_recovery[i] = true;
Austin Schuh20b2b082019-09-11 20:42:56 -0700252 }
253
Brian Silverman177567e2020-08-12 19:51:33 -0700254 // Cleaning up pinners is easy. We don't actually have to do anything, but
255 // invalidating its pinned field might help catch bugs elsewhere trying to
256 // read it before it's set.
257 for (size_t i = 0; i < num_pinners; ++i) {
258 Pinner *const pinner = memory->GetPinner(i);
259 const uint32_t tid =
260 __atomic_load_n(&(pinner->tid.futex), __ATOMIC_ACQUIRE);
261 if (!(tid & FUTEX_OWNER_DIED)) {
262 continue;
263 }
264 pinner->pinned.Invalidate();
265 __atomic_store_n(&(pinner->tid.futex), 0, __ATOMIC_RELEASE);
266 }
267
Austin Schuh20b2b082019-09-11 20:42:56 -0700268 // If all the senders are (or were made) good, there is no need to do the hard
269 // case.
270 if (valid_senders == num_senders) {
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700271 return true;
Austin Schuh20b2b082019-09-11 20:42:56 -0700272 }
273
Alex Perrycb7da4b2019-08-28 19:35:56 -0700274 VLOG(3) << "Starting hard cleanup";
Austin Schuh20b2b082019-09-11 20:42:56 -0700275
276 size_t num_accounted_for = 0;
277 size_t num_missing = 0;
278 ::std::vector<bool> accounted_for(num_messages, false);
279
280 while ((num_accounted_for + num_missing) != num_messages) {
281 num_missing = 0;
282 for (size_t i = 0; i < num_senders; ++i) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800283 Sender *const sender = memory->GetSender(i);
Austin Schuh20b2b082019-09-11 20:42:56 -0700284 const uint32_t tid =
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800285 __atomic_load_n(&(sender->tid.futex), __ATOMIC_ACQUIRE);
Austin Schuh20b2b082019-09-11 20:42:56 -0700286 if (tid & FUTEX_OWNER_DIED) {
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700287 if (!need_recovery[i]) {
288 return false;
289 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700290 ++num_missing;
Brian Silverman177567e2020-08-12 19:51:33 -0700291 continue;
Austin Schuh20b2b082019-09-11 20:42:56 -0700292 }
Brian Silverman177567e2020-08-12 19:51:33 -0700293 CHECK(!need_recovery[i]) << ": Somebody else recovered a sender: " << i;
294 // We can do a relaxed load here because we're the only person touching
295 // this sender at this point, if it matters. If it's not a dead sender,
296 // then any message it ever has will eventually be accounted for if we
297 // make enough tries through the outer loop.
298 const Index scratch_index = sender->scratch_index.RelaxedLoad();
299 if (!accounted_for[scratch_index.message_index()]) {
300 ++num_accounted_for;
301 }
302 accounted_for[scratch_index.message_index()] = true;
Austin Schuh20b2b082019-09-11 20:42:56 -0700303 }
304
305 for (size_t i = 0; i < queue_size; ++i) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800306 // Same logic as above for scratch_index applies here too.
Austin Schuh20b2b082019-09-11 20:42:56 -0700307 const Index index = memory->GetQueue(i)->RelaxedLoad();
308 if (!accounted_for[index.message_index()]) {
309 ++num_accounted_for;
310 }
311 accounted_for[index.message_index()] = true;
312 }
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700313
Brian Silverman177567e2020-08-12 19:51:33 -0700314 for (size_t pinner_index = 0; pinner_index < num_pinners; ++pinner_index) {
315 // Same logic as above for scratch_index applies here too.
316 const Index index =
317 memory->GetPinner(pinner_index)->scratch_index.RelaxedLoad();
318 if (!accounted_for[index.message_index()]) {
319 ++num_accounted_for;
320 }
321 accounted_for[index.message_index()] = true;
322 }
323
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700324 CHECK_LE(num_accounted_for + num_missing, num_messages);
Austin Schuh20b2b082019-09-11 20:42:56 -0700325 }
326
327 while (num_missing != 0) {
328 const size_t starting_num_missing = num_missing;
329 for (size_t i = 0; i < num_senders; ++i) {
330 Sender *sender = memory->GetSender(i);
331 const uint32_t tid =
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800332 __atomic_load_n(&(sender->tid.futex), __ATOMIC_ACQUIRE);
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700333 if (!(tid & FUTEX_OWNER_DIED)) {
334 CHECK(!need_recovery[i]) << ": Somebody else recovered a sender: " << i;
335 continue;
336 }
337 if (!need_recovery[i]) {
338 return false;
339 }
340 // We can do relaxed loads here because we're the only person touching
341 // this sender at this point.
342 const Index scratch_index = sender->scratch_index.RelaxedLoad();
343 const Index to_replace = sender->to_replace.RelaxedLoad();
Austin Schuh20b2b082019-09-11 20:42:56 -0700344
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700345 // Candidate.
346 if (to_replace.valid()) {
347 CHECK_LE(to_replace.message_index(), accounted_for.size());
348 }
349 if (scratch_index.valid()) {
350 CHECK_LE(scratch_index.message_index(), accounted_for.size());
351 }
352 if (!to_replace.valid() || accounted_for[to_replace.message_index()]) {
353 CHECK(scratch_index.valid());
354 VLOG(3) << "Sender " << i
355 << " died, to_replace is already accounted for";
356 // If both are accounted for, we are corrupt...
357 CHECK(!accounted_for[scratch_index.message_index()]);
Austin Schuh20b2b082019-09-11 20:42:56 -0700358
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700359 // to_replace is already accounted for. This means that we didn't
360 // atomically insert scratch_index into the queue yet. So
361 // invalidate to_replace.
362 sender->to_replace.Invalidate();
Brian Silverman177567e2020-08-12 19:51:33 -0700363 // Sender definitely will not have gotten here, so finish for it.
364 memory->GetMessage(scratch_index)
365 ->header.queue_index.RelaxedInvalidate();
Austin Schuh20b2b082019-09-11 20:42:56 -0700366
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700367 // And then mark this sender clean.
368 __atomic_store_n(&(sender->tid.futex), 0, __ATOMIC_RELEASE);
369 need_recovery[i] = false;
Austin Schuh20b2b082019-09-11 20:42:56 -0700370
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700371 // And account for scratch_index.
372 accounted_for[scratch_index.message_index()] = true;
373 --num_missing;
374 ++num_accounted_for;
375 } else if (!scratch_index.valid() ||
376 accounted_for[scratch_index.message_index()]) {
377 VLOG(3) << "Sender " << i
378 << " died, scratch_index is already accounted for";
379 // scratch_index is accounted for. That means we did the insert,
380 // but didn't record it.
381 CHECK(to_replace.valid());
Brian Silverman177567e2020-08-12 19:51:33 -0700382
383 // Make sure to indicate it's an unused message before a sender gets its
384 // hands on it.
385 memory->GetMessage(to_replace)->header.queue_index.RelaxedInvalidate();
386 aos_compiler_memory_barrier();
387
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700388 // Finish the transaction. Copy to_replace, then clear it.
Austin Schuh20b2b082019-09-11 20:42:56 -0700389
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700390 sender->scratch_index.Store(to_replace);
391 sender->to_replace.Invalidate();
Austin Schuh20b2b082019-09-11 20:42:56 -0700392
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700393 // And then mark this sender clean.
394 __atomic_store_n(&(sender->tid.futex), 0, __ATOMIC_RELEASE);
395 need_recovery[i] = false;
Austin Schuh20b2b082019-09-11 20:42:56 -0700396
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700397 // And account for to_replace.
398 accounted_for[to_replace.message_index()] = true;
399 --num_missing;
400 ++num_accounted_for;
401 } else {
402 VLOG(3) << "Sender " << i << " died, neither is accounted for";
403 // Ambiguous. There will be an unambiguous one somewhere that we
404 // can do first.
Austin Schuh20b2b082019-09-11 20:42:56 -0700405 }
406 }
407 // CHECK that we are making progress.
408 CHECK_NE(num_missing, starting_num_missing);
409 }
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700410 return true;
411}
412
413void Cleanup(LocklessQueueMemory *memory, const GrabQueueSetupLockOrDie &lock) {
414 // The number of iterations is bounded here because there are only a finite
415 // number of senders in existence which could die, and no new ones can be
416 // created while we're in here holding the lock.
417 while (!DoCleanup(memory, lock)) {
418 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700419}
420
421// Exposes rt_tgsigqueueinfo so we can send the signal *just* to the target
422// thread.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800423// TODO(Brian): Do directly in assembly for armhf at least for efficiency.
Austin Schuh20b2b082019-09-11 20:42:56 -0700424int rt_tgsigqueueinfo(pid_t tgid, pid_t tid, int sig, siginfo_t *si) {
425 return syscall(SYS_rt_tgsigqueueinfo, tgid, tid, sig, si);
426}
427
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700428QueueIndex ZeroOrValid(QueueIndex index) {
429 if (!index.valid()) {
430 return index.Clear();
431 }
432 return index;
433}
434
Austin Schuh20b2b082019-09-11 20:42:56 -0700435} // namespace
436
Austin Schuh4bc4f902019-12-23 18:04:51 -0800437size_t LocklessQueueConfiguration::message_size() const {
438 // Round up the message size so following data is aligned appropriately.
Brian Silverman0eaa1da2020-08-12 20:03:52 -0700439 // Make sure to leave space to align the message data. It will be aligned
440 // relative to the start of the shared memory region, but that might not be
441 // aligned for some use cases.
Brian Silvermana1652f32020-01-29 20:41:44 -0800442 return LocklessQueueMemory::AlignmentRoundUp(message_data_size +
Brian Silverman0eaa1da2020-08-12 20:03:52 -0700443 kChannelDataRedzone * 2 +
Brian Silvermana1652f32020-01-29 20:41:44 -0800444 (kChannelDataAlignment - 1)) +
Austin Schuh4bc4f902019-12-23 18:04:51 -0800445 sizeof(Message);
446}
447
Austin Schuh20b2b082019-09-11 20:42:56 -0700448size_t LocklessQueueMemorySize(LocklessQueueConfiguration config) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800449 // Round up the message size so following data is aligned appropriately.
450 config.message_data_size =
451 LocklessQueueMemory::AlignmentRoundUp(config.message_data_size);
Austin Schuh20b2b082019-09-11 20:42:56 -0700452
453 // As we build up the size, confirm that everything is aligned to the
454 // alignment requirements of the type.
455 size_t size = sizeof(LocklessQueueMemory);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800456 CHECK_EQ(size % alignof(LocklessQueueMemory), 0u);
Austin Schuh20b2b082019-09-11 20:42:56 -0700457
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800458 CHECK_EQ(size % alignof(AtomicIndex), 0u);
Austin Schuh20b2b082019-09-11 20:42:56 -0700459 size += LocklessQueueMemory::SizeOfQueue(config);
460
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800461 CHECK_EQ(size % alignof(Message), 0u);
Austin Schuh20b2b082019-09-11 20:42:56 -0700462 size += LocklessQueueMemory::SizeOfMessages(config);
463
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800464 CHECK_EQ(size % alignof(Watcher), 0u);
Austin Schuh20b2b082019-09-11 20:42:56 -0700465 size += LocklessQueueMemory::SizeOfWatchers(config);
466
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800467 CHECK_EQ(size % alignof(Sender), 0u);
Austin Schuh20b2b082019-09-11 20:42:56 -0700468 size += LocklessQueueMemory::SizeOfSenders(config);
469
Brian Silverman177567e2020-08-12 19:51:33 -0700470 CHECK_EQ(size % alignof(Pinner), 0u);
471 size += LocklessQueueMemory::SizeOfPinners(config);
472
Austin Schuh20b2b082019-09-11 20:42:56 -0700473 return size;
474}
475
Brian Silverman0eaa1da2020-08-12 20:03:52 -0700476// Calculates the starting byte for a redzone in shared memory. This starting
477// value is simply incremented for subsequent bytes.
478//
479// The result is based on the offset of the region in shared memor, to ensure it
480// is the same for each region when we generate and verify, but different for
481// each region to help catch forms of corruption like copying out-of-bounds data
482// from one place to another.
483//
484// memory is the base pointer to the shared memory. It is used to calculated
485// offsets. starting_data is the start of the redzone's data. Each one will
486// get a unique pattern.
487uint8_t RedzoneStart(const LocklessQueueMemory *memory,
488 const char *starting_data) {
489 const auto memory_int = reinterpret_cast<uintptr_t>(memory);
490 const auto starting_int = reinterpret_cast<uintptr_t>(starting_data);
491 DCHECK(starting_int >= memory_int);
492 DCHECK(starting_int < memory_int + LocklessQueueMemorySize(memory->config));
493 const uintptr_t starting_offset = starting_int - memory_int;
494 // Just XOR the lower 2 bytes. They higher-order bytes are probably 0
495 // anyways.
496 return (starting_offset & 0xFF) ^ ((starting_offset >> 8) & 0xFF);
497}
498
499// Returns true if the given redzone has invalid data.
500bool CheckRedzone(const LocklessQueueMemory *memory,
501 absl::Span<const char> redzone) {
502 uint8_t redzone_value = RedzoneStart(memory, redzone.data());
503
504 bool bad = false;
505
506 for (size_t i = 0; i < redzone.size(); ++i) {
507 if (memcmp(&redzone[i], &redzone_value, 1)) {
508 bad = true;
509 }
510 ++redzone_value;
511 }
512
513 return bad;
514}
515
516// Returns true if either of message's redzones has invalid data.
517bool CheckBothRedzones(const LocklessQueueMemory *memory,
518 const Message *message) {
519 return CheckRedzone(memory,
520 message->PreRedzone(memory->message_data_size())) ||
521 CheckRedzone(memory, message->PostRedzone(memory->message_data_size(),
522 memory->message_size()));
523}
524
525// Fills the given redzone with the expected data.
526void FillRedzone(LocklessQueueMemory *memory, absl::Span<char> redzone) {
527 uint8_t redzone_value = RedzoneStart(memory, redzone.data());
528 for (size_t i = 0; i < redzone.size(); ++i) {
529 memcpy(&redzone[i], &redzone_value, 1);
530 ++redzone_value;
531 }
532
533 // Just double check that the implementations match.
534 CHECK(!CheckRedzone(memory, redzone));
535}
536
Austin Schuh20b2b082019-09-11 20:42:56 -0700537LocklessQueueMemory *InitializeLocklessQueueMemory(
538 LocklessQueueMemory *memory, LocklessQueueConfiguration config) {
539 // Everything should be zero initialized already. So we just need to fill
540 // everything out properly.
541
Brian Silvermanc57ff0a2020-04-28 16:45:13 -0700542 // This is the UID we will use for checking signal-sending permission
543 // compatibility.
544 //
545 // The manpage says:
546 // For a process to have permission to send a signal, it must either be
547 // privileged [...], or the real or effective user ID of the sending process
548 // must equal the real or saved set-user-ID of the target process.
549 //
550 // Processes typically initialize a queue in random order as they start up.
551 // This means we need an algorithm for verifying all processes have
552 // permissions to send each other signals which gives the same answer no
553 // matter what order they attach in. We would also like to avoid maintaining a
554 // shared list of the UIDs of all processes.
555 //
556 // To do this while still giving sufficient flexibility for all current use
557 // cases, we track a single UID for the queue. All processes with a matching
558 // euid+suid must have this UID. Any processes with distinct euid/suid must
559 // instead have a matching ruid. This guarantees signals can be sent between
560 // all processes attached to the queue.
561 //
562 // In particular, this allows a process to change only its euid (to interact
563 // with a queue) while still maintaining privileges via its ruid. However, it
564 // can only use privileges in ways that do not require changing the euid back,
565 // because while the euid is different it will not be able to receive signals.
566 // We can't actually verify that, but we can sanity check that things are
567 // valid when the queue is initialized.
568
569 uid_t uid;
570 {
571 uid_t ruid, euid, suid;
572 PCHECK(getresuid(&ruid, &euid, &suid) == 0);
573 // If these are equal, then use them, even if that's different from the real
574 // UID. This allows processes to keep a real UID of 0 (to have permissions
575 // to perform system-level changes) while still being able to communicate
576 // with processes running unprivileged as a distinct user.
577 if (euid == suid) {
578 uid = euid;
579 VLOG(1) << "Using euid==suid " << uid;
580 } else {
581 uid = ruid;
582 VLOG(1) << "Using ruid " << ruid;
583 }
584 }
585
Austin Schuh20b2b082019-09-11 20:42:56 -0700586 // Grab the mutex. We don't care if the previous reader died. We are going
587 // to check everything anyways.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800588 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory);
Austin Schuh20b2b082019-09-11 20:42:56 -0700589
590 if (!memory->initialized) {
591 // TODO(austin): Check these for out of bounds.
592 memory->config.num_watchers = config.num_watchers;
593 memory->config.num_senders = config.num_senders;
Brian Silverman177567e2020-08-12 19:51:33 -0700594 memory->config.num_pinners = config.num_pinners;
Austin Schuh20b2b082019-09-11 20:42:56 -0700595 memory->config.queue_size = config.queue_size;
Austin Schuh4bc4f902019-12-23 18:04:51 -0800596 memory->config.message_data_size = config.message_data_size;
Austin Schuh20b2b082019-09-11 20:42:56 -0700597
598 const size_t num_messages = memory->num_messages();
599 // There need to be at most MaxMessages() messages allocated.
600 CHECK_LE(num_messages, Index::MaxMessages());
601
602 for (size_t i = 0; i < num_messages; ++i) {
Brian Silverman0eaa1da2020-08-12 20:03:52 -0700603 Message *const message =
604 memory->GetMessage(Index(QueueIndex::Zero(memory->queue_size()), i));
605 message->header.queue_index.Invalidate();
606 FillRedzone(memory, message->PreRedzone(memory->message_data_size()));
607 FillRedzone(memory, message->PostRedzone(memory->message_data_size(),
608 memory->message_size()));
Austin Schuh20b2b082019-09-11 20:42:56 -0700609 }
610
611 for (size_t i = 0; i < memory->queue_size(); ++i) {
612 // Make the initial counter be the furthest away number. That means that
613 // index 0 should be 0xffff, 1 should be 0, etc.
614 memory->GetQueue(i)->Store(Index(QueueIndex::Zero(memory->queue_size())
615 .IncrementBy(i)
616 .DecrementBy(memory->queue_size()),
617 i));
618 }
619
620 memory->next_queue_index.Invalidate();
Brian Silvermanc57ff0a2020-04-28 16:45:13 -0700621 memory->uid = uid;
Austin Schuh20b2b082019-09-11 20:42:56 -0700622
623 for (size_t i = 0; i < memory->num_senders(); ++i) {
624 ::aos::ipc_lib::Sender *s = memory->GetSender(i);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800625 // Nobody else can possibly be touching these because we haven't set
626 // initialized to true yet.
627 s->scratch_index.RelaxedStore(Index(0xffff, i + memory->queue_size()));
Austin Schuh20b2b082019-09-11 20:42:56 -0700628 s->to_replace.RelaxedInvalidate();
629 }
630
Brian Silverman177567e2020-08-12 19:51:33 -0700631 for (size_t i = 0; i < memory->num_pinners(); ++i) {
632 ::aos::ipc_lib::Pinner *pinner = memory->GetPinner(i);
633 // Nobody else can possibly be touching these because we haven't set
634 // initialized to true yet.
635 pinner->scratch_index.RelaxedStore(
636 Index(0xffff, i + memory->num_senders() + memory->queue_size()));
637 pinner->pinned.Invalidate();
638 }
639
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800640 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -0700641 // Signal everything is done. This needs to be done last, so if we die, we
642 // redo initialization.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800643 memory->initialized = true;
Austin Schuh3328d132020-02-28 13:54:57 -0800644 } else {
Brian Silvermanc57ff0a2020-04-28 16:45:13 -0700645 CHECK_EQ(uid, memory->uid) << ": UIDs must match for all processes";
Austin Schuh20b2b082019-09-11 20:42:56 -0700646 }
647
Austin Schuh20b2b082019-09-11 20:42:56 -0700648 return memory;
649}
650
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700651void LocklessQueue::Initialize() {
652 InitializeLocklessQueueMemory(memory_, config_);
653}
Austin Schuh20b2b082019-09-11 20:42:56 -0700654
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700655LocklessQueueWatcher::~LocklessQueueWatcher() {
656 if (watcher_index_ == -1) {
657 return;
658 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700659
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700660 // Since everything is self consistent, all we need to do is make sure nobody
661 // else is running. Someone dying will get caught in the generic consistency
662 // check.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800663 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory_);
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700664
665 // Make sure we are registered.
666 CHECK_NE(watcher_index_, -1);
667
668 // Make sure we still own the slot we are supposed to.
669 CHECK(
670 death_notification_is_held(&(memory_->GetWatcher(watcher_index_)->tid)));
671
672 // The act of unlocking invalidates the entry. Invalidate it.
673 death_notification_release(&(memory_->GetWatcher(watcher_index_)->tid));
674 // And internally forget the slot.
675 watcher_index_ = -1;
676
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800677 // Cleanup is cheap. The next user will do it anyways, so no need for us to do
678 // anything right now.
Austin Schuh20b2b082019-09-11 20:42:56 -0700679
680 // And confirm that nothing is owned by us.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700681 const int num_watchers = memory_->num_watchers();
Austin Schuh20b2b082019-09-11 20:42:56 -0700682 for (int i = 0; i < num_watchers; ++i) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700683 CHECK(!death_notification_is_held(&(memory_->GetWatcher(i)->tid)))
684 << ": " << i;
Austin Schuh20b2b082019-09-11 20:42:56 -0700685 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700686}
687
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700688std::optional<LocklessQueueWatcher> LocklessQueueWatcher::Make(
689 LocklessQueue queue, int priority) {
690 queue.Initialize();
691 LocklessQueueWatcher result(queue.memory(), priority);
692 if (result.watcher_index_ != -1) {
693 return std::move(result);
694 } else {
695 return std::nullopt;
696 }
697}
Austin Schuh20b2b082019-09-11 20:42:56 -0700698
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700699LocklessQueueWatcher::LocklessQueueWatcher(LocklessQueueMemory *memory,
700 int priority)
701 : memory_(memory) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700702 // TODO(austin): Make sure signal coalescing is turned on. We don't need
703 // duplicates. That will improve performance under high load.
704
705 // Since everything is self consistent, all we need to do is make sure nobody
706 // else is running. Someone dying will get caught in the generic consistency
707 // check.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800708 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory_);
Austin Schuh20b2b082019-09-11 20:42:56 -0700709 const int num_watchers = memory_->num_watchers();
710
711 // Now, find the first empty watcher and grab it.
712 CHECK_EQ(watcher_index_, -1);
713 for (int i = 0; i < num_watchers; ++i) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800714 // If we see a slot the kernel has marked as dead, everything we do reusing
715 // it needs to happen-after whatever that process did before dying.
Brian Silverman2484eea2019-12-21 16:48:46 -0800716 auto *const futex = &(memory_->GetWatcher(i)->tid.futex);
717 const uint32_t tid = __atomic_load_n(futex, __ATOMIC_ACQUIRE);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800718 if (tid == 0 || (tid & FUTEX_OWNER_DIED)) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700719 watcher_index_ = i;
Brian Silverman2484eea2019-12-21 16:48:46 -0800720 // Relaxed is OK here because we're the only task going to touch it
721 // between here and the write in death_notification_init below (other
722 // recovery is blocked by us holding the setup lock).
723 __atomic_store_n(futex, 0, __ATOMIC_RELAXED);
Austin Schuh20b2b082019-09-11 20:42:56 -0700724 break;
725 }
726 }
727
728 // Bail if we failed to find an open slot.
729 if (watcher_index_ == -1) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700730 return;
Austin Schuh20b2b082019-09-11 20:42:56 -0700731 }
732
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700733 Watcher *const w = memory_->GetWatcher(watcher_index_);
Austin Schuh20b2b082019-09-11 20:42:56 -0700734
735 w->pid = getpid();
736 w->priority = priority;
737
738 // Grabbing a mutex is a compiler and memory barrier, so nothing before will
739 // get rearranged afterwords.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800740 death_notification_init(&(w->tid));
Austin Schuh20b2b082019-09-11 20:42:56 -0700741}
742
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700743LocklessQueueWakeUpper::LocklessQueueWakeUpper(LocklessQueue queue)
744 : memory_(queue.const_memory()), pid_(getpid()), uid_(getuid()) {
745 queue.Initialize();
746 watcher_copy_.resize(memory_->num_watchers());
Austin Schuh20b2b082019-09-11 20:42:56 -0700747}
748
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700749int LocklessQueueWakeUpper::Wakeup(const int current_priority) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700750 const size_t num_watchers = memory_->num_watchers();
751
752 CHECK_EQ(watcher_copy_.size(), num_watchers);
753
754 // Grab a copy so it won't change out from underneath us, and we can sort it
755 // nicely in C++.
756 // Do note that there is still a window where the process can die *after* we
757 // read everything. We will still PI boost and send a signal to the thread in
758 // question. There is no way without pidfd's to close this window, and
759 // creating a pidfd is likely not RT.
760 for (size_t i = 0; i < num_watchers; ++i) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700761 const Watcher *w = memory_->GetWatcher(i);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800762 watcher_copy_[i].tid = __atomic_load_n(&(w->tid.futex), __ATOMIC_RELAXED);
763 // Force the load of the TID to come first.
764 aos_compiler_memory_barrier();
765 watcher_copy_[i].pid = w->pid.load(std::memory_order_relaxed);
766 watcher_copy_[i].priority = w->priority.load(std::memory_order_relaxed);
Austin Schuh20b2b082019-09-11 20:42:56 -0700767
768 // Use a priority of -1 to mean an invalid entry to make sorting easier.
769 if (watcher_copy_[i].tid & FUTEX_OWNER_DIED || watcher_copy_[i].tid == 0) {
770 watcher_copy_[i].priority = -1;
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800771 } else {
772 // Ensure all of this happens after we're done looking at the pid+priority
773 // in shared memory.
774 aos_compiler_memory_barrier();
775 if (watcher_copy_[i].tid != static_cast<pid_t>(__atomic_load_n(
776 &(w->tid.futex), __ATOMIC_RELAXED))) {
777 // Confirm that the watcher hasn't been re-used and modified while we
778 // read it. If it has, mark it invalid again.
779 watcher_copy_[i].priority = -1;
780 watcher_copy_[i].tid = 0;
781 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700782 }
783 }
784
785 // Now sort.
786 ::std::sort(watcher_copy_.begin(), watcher_copy_.end(),
787 [](const WatcherCopy &a, const WatcherCopy &b) {
788 return a.priority > b.priority;
789 });
790
791 int count = 0;
792 if (watcher_copy_[0].priority != -1) {
793 const int max_priority =
794 ::std::max(current_priority, watcher_copy_[0].priority);
795 // Boost if we are RT and there is a higher priority sender out there.
796 // Otherwise we might run into priority inversions.
797 if (max_priority > current_priority && current_priority > 0) {
798 SetCurrentThreadRealtimePriority(max_priority);
799 }
800
801 // Build up the siginfo to send.
802 siginfo_t uinfo;
803 memset(&uinfo, 0, sizeof(uinfo));
804
805 uinfo.si_code = SI_QUEUE;
806 uinfo.si_pid = pid_;
807 uinfo.si_uid = uid_;
808 uinfo.si_value.sival_int = 0;
809
810 for (const WatcherCopy &watcher_copy : watcher_copy_) {
811 // The first -1 priority means we are at the end of the valid list.
812 if (watcher_copy.priority == -1) {
813 break;
814 }
815
816 // Send the signal. Target just the thread that sent it so that we can
817 // support multiple watchers in a process (when someone creates multiple
818 // event loops in different threads).
819 rt_tgsigqueueinfo(watcher_copy.pid, watcher_copy.tid, kWakeupSignal,
820 &uinfo);
821
822 ++count;
823 }
824
825 // Drop back down if we were boosted.
826 if (max_priority > current_priority && current_priority > 0) {
827 SetCurrentThreadRealtimePriority(current_priority);
828 }
829 }
830
831 return count;
832}
833
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700834LocklessQueueSender::LocklessQueueSender(LocklessQueueMemory *memory)
835 : memory_(memory) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800836 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory_);
Austin Schuh20b2b082019-09-11 20:42:56 -0700837
838 // Since we already have the lock, go ahead and try cleaning up.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800839 Cleanup(memory_, grab_queue_setup_lock);
Austin Schuh20b2b082019-09-11 20:42:56 -0700840
841 const int num_senders = memory_->num_senders();
842
843 for (int i = 0; i < num_senders; ++i) {
844 ::aos::ipc_lib::Sender *s = memory->GetSender(i);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800845 // This doesn't need synchronization because we're the only process doing
846 // initialization right now, and nobody else will be touching senders which
847 // we're interested in.
Austin Schuh20b2b082019-09-11 20:42:56 -0700848 const uint32_t tid = __atomic_load_n(&(s->tid.futex), __ATOMIC_RELAXED);
849 if (tid == 0) {
850 sender_index_ = i;
851 break;
852 }
853 }
854
855 if (sender_index_ == -1) {
Austin Schuhe516ab02020-05-06 21:37:04 -0700856 VLOG(1) << "Too many senders, starting to bail.";
857 return;
Austin Schuh20b2b082019-09-11 20:42:56 -0700858 }
859
Brian Silverman177567e2020-08-12 19:51:33 -0700860 ::aos::ipc_lib::Sender *const sender = memory_->GetSender(sender_index_);
Austin Schuh20b2b082019-09-11 20:42:56 -0700861
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800862 // Indicate that we are now alive by taking over the slot. If the previous
863 // owner died, we still want to do this.
Brian Silverman177567e2020-08-12 19:51:33 -0700864 death_notification_init(&(sender->tid));
865
866 const Index scratch_index = sender->scratch_index.RelaxedLoad();
867 Message *const message = memory_->GetMessage(scratch_index);
868 CHECK(!message->header.queue_index.RelaxedLoad(memory_->queue_size()).valid())
869 << ": " << std::hex << scratch_index.get();
Austin Schuh20b2b082019-09-11 20:42:56 -0700870}
871
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700872LocklessQueueSender::~LocklessQueueSender() {
873 if (sender_index_ != -1) {
874 CHECK(memory_ != nullptr);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800875 death_notification_release(&(memory_->GetSender(sender_index_)->tid));
Austin Schuh20b2b082019-09-11 20:42:56 -0700876 }
877}
878
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700879std::optional<LocklessQueueSender> LocklessQueueSender::Make(
880 LocklessQueue queue) {
881 queue.Initialize();
882 LocklessQueueSender result(queue.memory());
883 if (result.sender_index_ != -1) {
884 return std::move(result);
885 } else {
886 return std::nullopt;
887 }
888}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700889
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700890size_t LocklessQueueSender::size() const {
891 return memory_->message_data_size();
892}
893
894void *LocklessQueueSender::Data() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700895 ::aos::ipc_lib::Sender *sender = memory_->GetSender(sender_index_);
Brian Silverman177567e2020-08-12 19:51:33 -0700896 const Index scratch_index = sender->scratch_index.RelaxedLoad();
897 Message *const message = memory_->GetMessage(scratch_index);
898 // We should have invalidated this when we first got the buffer. Verify that
899 // in debug mode.
900 DCHECK(
901 !message->header.queue_index.RelaxedLoad(memory_->queue_size()).valid())
902 << ": " << std::hex << scratch_index.get();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700903
Brian Silvermana1652f32020-01-29 20:41:44 -0800904 return message->data(memory_->message_data_size());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700905}
906
Austin Schuh91ba6392020-10-03 13:27:47 -0700907bool LocklessQueueSender::Send(
Austin Schuhad154822019-12-27 15:45:13 -0800908 const char *data, size_t length,
909 aos::monotonic_clock::time_point monotonic_remote_time,
910 aos::realtime_clock::time_point realtime_remote_time,
911 uint32_t remote_queue_index,
912 aos::monotonic_clock::time_point *monotonic_sent_time,
913 aos::realtime_clock::time_point *realtime_sent_time,
914 uint32_t *queue_index) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700915 CHECK_LE(length, size());
Austin Schuh67420a42019-12-21 21:55:04 -0800916 // Flatbuffers write from the back of the buffer to the front. If we are
917 // going to write an explicit chunk of memory into the buffer, we need to
918 // adhere to this convention and place it at the end.
919 memcpy((reinterpret_cast<char *>(Data()) + size() - length), data, length);
Austin Schuh91ba6392020-10-03 13:27:47 -0700920 return Send(length, monotonic_remote_time, realtime_remote_time,
921 remote_queue_index, monotonic_sent_time, realtime_sent_time,
922 queue_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700923}
924
Austin Schuh91ba6392020-10-03 13:27:47 -0700925bool LocklessQueueSender::Send(
Austin Schuhad154822019-12-27 15:45:13 -0800926 size_t length, aos::monotonic_clock::time_point monotonic_remote_time,
927 aos::realtime_clock::time_point realtime_remote_time,
928 uint32_t remote_queue_index,
929 aos::monotonic_clock::time_point *monotonic_sent_time,
930 aos::realtime_clock::time_point *realtime_sent_time,
931 uint32_t *queue_index) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700932 const size_t queue_size = memory_->queue_size();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700933 CHECK_LE(length, size());
Austin Schuh20b2b082019-09-11 20:42:56 -0700934
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800935 ::aos::ipc_lib::Sender *const sender = memory_->GetSender(sender_index_);
936 // We can do a relaxed load on our sender because we're the only person
937 // modifying it right now.
938 const Index scratch_index = sender->scratch_index.RelaxedLoad();
939 Message *const message = memory_->GetMessage(scratch_index);
Austin Schuh91ba6392020-10-03 13:27:47 -0700940 if (CheckBothRedzones(memory_, message)) {
941 return false;
942 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700943
Brian Silverman177567e2020-08-12 19:51:33 -0700944 // We should have invalidated this when we first got the buffer. Verify that
945 // in debug mode.
946 DCHECK(
947 !message->header.queue_index.RelaxedLoad(memory_->queue_size()).valid())
948 << ": " << std::hex << scratch_index.get();
949
Austin Schuh20b2b082019-09-11 20:42:56 -0700950 message->header.length = length;
Austin Schuhad154822019-12-27 15:45:13 -0800951 // Pass these through. Any alternative behavior can be implemented out a
952 // layer.
953 message->header.remote_queue_index = remote_queue_index;
954 message->header.monotonic_remote_time = monotonic_remote_time;
955 message->header.realtime_remote_time = realtime_remote_time;
Austin Schuh20b2b082019-09-11 20:42:56 -0700956
Brian Silverman177567e2020-08-12 19:51:33 -0700957 Index to_replace = Index::Invalid();
Austin Schuh20b2b082019-09-11 20:42:56 -0700958 while (true) {
959 const QueueIndex actual_next_queue_index =
960 memory_->next_queue_index.Load(queue_size);
961 const QueueIndex next_queue_index = ZeroOrValid(actual_next_queue_index);
962
963 const QueueIndex incremented_queue_index = next_queue_index.Increment();
964
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800965 // This needs to synchronize with whoever the previous writer at this
966 // location was.
Brian Silverman177567e2020-08-12 19:51:33 -0700967 to_replace = memory_->LoadIndex(next_queue_index);
Austin Schuh20b2b082019-09-11 20:42:56 -0700968
969 const QueueIndex decremented_queue_index =
970 next_queue_index.DecrementBy(queue_size);
971
972 // See if we got beat. If we did, try to atomically update
973 // next_queue_index in case the previous writer failed and retry.
974 if (!to_replace.IsPlausible(decremented_queue_index)) {
975 // We don't care about the result. It will either succeed, or we got
976 // beat in fixing it and just need to give up and try again. If we got
977 // beat multiple times, the only way progress can be made is if the queue
978 // is updated as well. This means that if we retry reading
979 // next_queue_index, we will be at most off by one and can retry.
980 //
981 // Both require no further action from us.
982 //
983 // TODO(austin): If we are having fairness issues under contention, we
984 // could have a mode bit in next_queue_index, and could use a lock or some
985 // other form of PI boosting to let the higher priority task win.
986 memory_->next_queue_index.CompareAndExchangeStrong(
987 actual_next_queue_index, incremented_queue_index);
988
Alex Perrycb7da4b2019-08-28 19:35:56 -0700989 VLOG(3) << "We were beat. Try again. Was " << std::hex
990 << to_replace.get() << ", is " << decremented_queue_index.index();
Austin Schuh20b2b082019-09-11 20:42:56 -0700991 continue;
992 }
993
994 // Confirm that the message is what it should be.
Brian Silverman177567e2020-08-12 19:51:33 -0700995 //
996 // This is just a best-effort check to skip reading the clocks if possible.
997 // If this fails, then the compare-exchange below definitely would, so we
998 // can bail out now.
Austin Schuh20b2b082019-09-11 20:42:56 -0700999 {
Austin Schuh20b2b082019-09-11 20:42:56 -07001000 const QueueIndex previous_index =
Brian Silverman177567e2020-08-12 19:51:33 -07001001 memory_->GetMessage(to_replace)
1002 ->header.queue_index.RelaxedLoad(queue_size);
Austin Schuh20b2b082019-09-11 20:42:56 -07001003 if (previous_index != decremented_queue_index && previous_index.valid()) {
1004 // Retry.
Alex Perrycb7da4b2019-08-28 19:35:56 -07001005 VLOG(3) << "Something fishy happened, queue index doesn't match. "
1006 "Retrying. Previous index was "
1007 << std::hex << previous_index.index() << ", should be "
1008 << decremented_queue_index.index();
Austin Schuh20b2b082019-09-11 20:42:56 -07001009 continue;
1010 }
1011 }
1012
1013 message->header.monotonic_sent_time = ::aos::monotonic_clock::now();
1014 message->header.realtime_sent_time = ::aos::realtime_clock::now();
Austin Schuhad154822019-12-27 15:45:13 -08001015 if (monotonic_sent_time != nullptr) {
1016 *monotonic_sent_time = message->header.monotonic_sent_time;
1017 }
1018 if (realtime_sent_time != nullptr) {
1019 *realtime_sent_time = message->header.realtime_sent_time;
1020 }
1021 if (queue_index != nullptr) {
1022 *queue_index = next_queue_index.index();
1023 }
Austin Schuh20b2b082019-09-11 20:42:56 -07001024
1025 // Before we are fully done filling out the message, update the Sender state
1026 // with the new index to write. This re-uses the barrier for the
1027 // queue_index store.
Alex Perrycb7da4b2019-08-28 19:35:56 -07001028 const Index index_to_write(next_queue_index, scratch_index.message_index());
Austin Schuh20b2b082019-09-11 20:42:56 -07001029
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001030 aos_compiler_memory_barrier();
1031 // We're the only person who cares about our scratch index, besides somebody
1032 // cleaning up after us.
Austin Schuh20b2b082019-09-11 20:42:56 -07001033 sender->scratch_index.RelaxedStore(index_to_write);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001034 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -07001035
1036 message->header.queue_index.Store(next_queue_index);
1037
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001038 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -07001039 // The message is now filled out, and we have a confirmed slot to store
1040 // into.
1041 //
1042 // Start by writing down what we are going to pull out of the queue. This
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001043 // was Invalid before now. Only person who will read this is whoever cleans
1044 // up after us, so no synchronization necessary.
Austin Schuh20b2b082019-09-11 20:42:56 -07001045 sender->to_replace.RelaxedStore(to_replace);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001046 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -07001047
1048 // Then exchange the next index into the queue.
1049 if (!memory_->GetQueue(next_queue_index.Wrapped())
1050 ->CompareAndExchangeStrong(to_replace, index_to_write)) {
1051 // Aw, didn't succeed. Retry.
1052 sender->to_replace.RelaxedInvalidate();
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001053 aos_compiler_memory_barrier();
Alex Perrycb7da4b2019-08-28 19:35:56 -07001054 VLOG(3) << "Failed to wrap into queue";
Austin Schuh20b2b082019-09-11 20:42:56 -07001055 continue;
1056 }
1057
1058 // Then update next_queue_index to save the next user some computation time.
1059 memory_->next_queue_index.CompareAndExchangeStrong(actual_next_queue_index,
1060 incremented_queue_index);
1061
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001062 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -07001063 // Now update the scratch space and record that we succeeded.
1064 sender->scratch_index.Store(to_replace);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001065 aos_compiler_memory_barrier();
1066 // And then record that we succeeded, but definitely after the above store.
Austin Schuh20b2b082019-09-11 20:42:56 -07001067 sender->to_replace.RelaxedInvalidate();
Brian Silverman177567e2020-08-12 19:51:33 -07001068
Austin Schuh20b2b082019-09-11 20:42:56 -07001069 break;
1070 }
Brian Silverman177567e2020-08-12 19:51:33 -07001071
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001072 DCHECK(!CheckBothRedzones(memory_, memory_->GetMessage(to_replace)))
1073 << ": Invalid message found in shared memory";
Brian Silverman177567e2020-08-12 19:51:33 -07001074 // to_replace is our current scratch_index. It isn't in the queue, which means
1075 // nobody new can pin it. They can set their `pinned` to it, but they will
1076 // back it out, so they don't count. This means that we just need to find a
1077 // message for which no pinner had it in `pinned`, and then we know this
1078 // message will never be pinned. We'll start with to_replace, and if that is
1079 // pinned then we'll look for a new one to use instead.
1080 const Index new_scratch =
1081 SwapPinnedSenderScratch(memory_, sender, to_replace);
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001082 DCHECK(!CheckBothRedzones(
1083 memory_, memory_->GetMessage(sender->scratch_index.RelaxedLoad())))
1084 << ": Invalid message found in shared memory";
Brian Silverman177567e2020-08-12 19:51:33 -07001085
1086 // If anybody is looking at this message (they shouldn't be), then try telling
1087 // them about it (best-effort).
1088 memory_->GetMessage(new_scratch)->header.queue_index.RelaxedInvalidate();
Austin Schuh91ba6392020-10-03 13:27:47 -07001089 return true;
Austin Schuh20b2b082019-09-11 20:42:56 -07001090}
1091
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001092int LocklessQueueSender::buffer_index() const {
Brian Silverman4f4e0612020-08-12 19:54:41 -07001093 ::aos::ipc_lib::Sender *const sender = memory_->GetSender(sender_index_);
1094 // We can do a relaxed load on our sender because we're the only person
1095 // modifying it right now.
1096 const Index scratch_index = sender->scratch_index.RelaxedLoad();
1097 return scratch_index.message_index();
1098}
1099
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001100LocklessQueuePinner::LocklessQueuePinner(
1101 LocklessQueueMemory *memory, const LocklessQueueMemory *const_memory)
1102 : memory_(memory), const_memory_(const_memory) {
1103 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory_);
1104
1105 // Since we already have the lock, go ahead and try cleaning up.
1106 Cleanup(memory_, grab_queue_setup_lock);
1107
1108 const int num_pinners = memory_->num_pinners();
1109
1110 for (int i = 0; i < num_pinners; ++i) {
1111 ::aos::ipc_lib::Pinner *p = memory->GetPinner(i);
1112 // This doesn't need synchronization because we're the only process doing
1113 // initialization right now, and nobody else will be touching pinners which
1114 // we're interested in.
1115 const uint32_t tid = __atomic_load_n(&(p->tid.futex), __ATOMIC_RELAXED);
1116 if (tid == 0) {
1117 pinner_index_ = i;
1118 break;
1119 }
1120 }
1121
1122 if (pinner_index_ == -1) {
1123 VLOG(1) << "Too many pinners, starting to bail.";
1124 return;
1125 }
1126
1127 ::aos::ipc_lib::Pinner *p = memory_->GetPinner(pinner_index_);
1128 p->pinned.Invalidate();
1129
1130 // Indicate that we are now alive by taking over the slot. If the previous
1131 // owner died, we still want to do this.
1132 death_notification_init(&(p->tid));
1133}
1134
1135LocklessQueuePinner::~LocklessQueuePinner() {
1136 if (pinner_index_ != -1) {
1137 CHECK(memory_ != nullptr);
1138 memory_->GetPinner(pinner_index_)->pinned.Invalidate();
1139 aos_compiler_memory_barrier();
1140 death_notification_release(&(memory_->GetPinner(pinner_index_)->tid));
1141 }
1142}
1143
1144std::optional<LocklessQueuePinner> LocklessQueuePinner::Make(
1145 LocklessQueue queue) {
1146 queue.Initialize();
1147 LocklessQueuePinner result(queue.memory(), queue.const_memory());
1148 if (result.pinner_index_ != -1) {
1149 return std::move(result);
1150 } else {
1151 return std::nullopt;
1152 }
1153}
1154
1155// This method doesn't mess with any scratch_index, so it doesn't have to worry
1156// about message ownership.
1157int LocklessQueuePinner::PinIndex(uint32_t uint32_queue_index) {
1158 const size_t queue_size = memory_->queue_size();
1159 const QueueIndex queue_index =
1160 QueueIndex::Zero(queue_size).IncrementBy(uint32_queue_index);
1161 ipc_lib::Pinner *const pinner = memory_->GetPinner(pinner_index_);
1162
1163 AtomicIndex *const queue_slot = memory_->GetQueue(queue_index.Wrapped());
1164
1165 // Indicate that we want to pin this message.
1166 pinner->pinned.Store(queue_index);
1167 aos_compiler_memory_barrier();
1168
1169 {
1170 const Index message_index = queue_slot->Load();
1171 Message *const message = memory_->GetMessage(message_index);
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001172 DCHECK(!CheckBothRedzones(memory_, message))
1173 << ": Invalid message found in shared memory";
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001174
1175 const QueueIndex message_queue_index =
1176 message->header.queue_index.Load(queue_size);
1177 if (message_queue_index == queue_index) {
1178 VLOG(3) << "Eq: " << std::hex << message_queue_index.index();
1179 aos_compiler_memory_barrier();
1180 return message_index.message_index();
1181 }
1182 VLOG(3) << "Message reused: " << std::hex << message_queue_index.index()
1183 << ", " << queue_index.index();
1184 }
1185
1186 // Being down here means we asked to pin a message before realizing it's no
1187 // longer in the queue, so back that out now.
1188 pinner->pinned.Invalidate();
1189 VLOG(3) << "Unpinned: " << std::hex << queue_index.index();
1190 return -1;
1191}
1192
1193size_t LocklessQueuePinner::size() const {
1194 return const_memory_->message_data_size();
1195}
1196
1197const void *LocklessQueuePinner::Data() const {
1198 const size_t queue_size = const_memory_->queue_size();
1199 const ::aos::ipc_lib::Pinner *const pinner =
1200 const_memory_->GetPinner(pinner_index_);
1201 QueueIndex pinned = pinner->pinned.RelaxedLoad(queue_size);
1202 CHECK(pinned.valid());
1203 const Message *message = const_memory_->GetMessage(pinned);
1204
1205 return message->data(const_memory_->message_data_size());
1206}
1207
1208LocklessQueueReader::Result LocklessQueueReader::Read(
Austin Schuh20b2b082019-09-11 20:42:56 -07001209 uint32_t uint32_queue_index,
1210 ::aos::monotonic_clock::time_point *monotonic_sent_time,
Austin Schuhad154822019-12-27 15:45:13 -08001211 ::aos::realtime_clock::time_point *realtime_sent_time,
1212 ::aos::monotonic_clock::time_point *monotonic_remote_time,
1213 ::aos::realtime_clock::time_point *realtime_remote_time,
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001214 uint32_t *remote_queue_index, size_t *length, char *data) const {
Austin Schuh20b2b082019-09-11 20:42:56 -07001215 const size_t queue_size = memory_->queue_size();
1216
1217 // Build up the QueueIndex.
1218 const QueueIndex queue_index =
1219 QueueIndex::Zero(queue_size).IncrementBy(uint32_queue_index);
1220
1221 // Read the message stored at the requested location.
1222 Index mi = memory_->LoadIndex(queue_index);
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001223 const Message *m = memory_->GetMessage(mi);
Austin Schuh20b2b082019-09-11 20:42:56 -07001224
1225 while (true) {
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001226 DCHECK(!CheckBothRedzones(memory_, m))
1227 << ": Invalid message found in shared memory";
Austin Schuh20b2b082019-09-11 20:42:56 -07001228 // We need to confirm that the data doesn't change while we are reading it.
1229 // Do that by first confirming that the message points to the queue index we
1230 // want.
1231 const QueueIndex starting_queue_index =
1232 m->header.queue_index.Load(queue_size);
1233 if (starting_queue_index != queue_index) {
1234 // If we found a message that is exactly 1 loop old, we just wrapped.
1235 if (starting_queue_index == queue_index.DecrementBy(queue_size)) {
Alex Perrycb7da4b2019-08-28 19:35:56 -07001236 VLOG(3) << "Matches: " << std::hex << starting_queue_index.index()
1237 << ", " << queue_index.DecrementBy(queue_size).index();
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001238 return Result::NOTHING_NEW;
Brian Silverman177567e2020-08-12 19:51:33 -07001239 }
1240
1241 // Someone has re-used this message between when we pulled it out of the
1242 // queue and when we grabbed its index. It is pretty hard to deduce
1243 // what happened. Just try again.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001244 const Message *const new_m = memory_->GetMessage(queue_index);
Brian Silverman177567e2020-08-12 19:51:33 -07001245 if (m != new_m) {
1246 m = new_m;
1247 VLOG(3) << "Retrying, m doesn't match";
1248 continue;
1249 }
1250
1251 // We have confirmed that message still points to the same message. This
1252 // means that the message didn't get swapped out from under us, so
1253 // starting_queue_index is correct.
1254 //
1255 // Either we got too far behind (signaled by this being a valid
1256 // message), or this is one of the initial messages which are invalid.
1257 if (starting_queue_index.valid()) {
1258 VLOG(3) << "Too old. Tried for " << std::hex << queue_index.index()
1259 << ", got " << starting_queue_index.index() << ", behind by "
1260 << std::dec
1261 << (starting_queue_index.index() - queue_index.index());
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001262 return Result::TOO_OLD;
Brian Silverman177567e2020-08-12 19:51:33 -07001263 }
1264
1265 VLOG(3) << "Initial";
1266
1267 // There isn't a valid message at this location.
1268 //
1269 // If someone asks for one of the messages within the first go around,
1270 // then they need to wait. They got ahead. Otherwise, they are
1271 // asking for something crazy, like something before the beginning of
1272 // the queue. Tell them that they are behind.
1273 if (uint32_queue_index < memory_->queue_size()) {
1274 VLOG(3) << "Near zero, " << std::hex << uint32_queue_index;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001275 return Result::NOTHING_NEW;
Austin Schuh20b2b082019-09-11 20:42:56 -07001276 } else {
Brian Silverman177567e2020-08-12 19:51:33 -07001277 VLOG(3) << "Not near zero, " << std::hex << uint32_queue_index;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001278 return Result::TOO_OLD;
Austin Schuh20b2b082019-09-11 20:42:56 -07001279 }
1280 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001281 VLOG(3) << "Eq: " << std::hex << starting_queue_index.index() << ", "
1282 << queue_index.index();
Austin Schuh20b2b082019-09-11 20:42:56 -07001283 break;
1284 }
1285
Alex Perrycb7da4b2019-08-28 19:35:56 -07001286 // Then read the data out. Copy it all out to be deterministic and so we can
1287 // make length be from either end.
Austin Schuh20b2b082019-09-11 20:42:56 -07001288 *monotonic_sent_time = m->header.monotonic_sent_time;
1289 *realtime_sent_time = m->header.realtime_sent_time;
Austin Schuhad154822019-12-27 15:45:13 -08001290 if (m->header.remote_queue_index == 0xffffffffu) {
1291 *remote_queue_index = queue_index.index();
1292 } else {
1293 *remote_queue_index = m->header.remote_queue_index;
1294 }
1295 *monotonic_remote_time = m->header.monotonic_remote_time;
1296 *realtime_remote_time = m->header.realtime_remote_time;
Brian Silverman6b8a3c32020-03-06 11:26:14 -08001297 if (data) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001298 memcpy(data, m->data(memory_->message_data_size()),
1299 memory_->message_data_size());
Brian Silverman6b8a3c32020-03-06 11:26:14 -08001300 }
Austin Schuh20b2b082019-09-11 20:42:56 -07001301 *length = m->header.length;
1302
1303 // And finally, confirm that the message *still* points to the queue index we
1304 // want. This means it didn't change out from under us.
1305 // If something changed out from under us, we were reading it much too late in
1306 // it's lifetime.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001307 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -07001308 const QueueIndex final_queue_index = m->header.queue_index.Load(queue_size);
1309 if (final_queue_index != queue_index) {
Alex Perrycb7da4b2019-08-28 19:35:56 -07001310 VLOG(3) << "Changed out from under us. Reading " << std::hex
1311 << queue_index.index() << ", finished with "
1312 << final_queue_index.index() << ", delta: " << std::dec
1313 << (final_queue_index.index() - queue_index.index());
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001314 return Result::OVERWROTE;
Austin Schuh20b2b082019-09-11 20:42:56 -07001315 }
1316
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001317 return Result::GOOD;
Austin Schuh20b2b082019-09-11 20:42:56 -07001318}
1319
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001320QueueIndex LocklessQueueReader::LatestIndex() const {
Austin Schuh20b2b082019-09-11 20:42:56 -07001321 const size_t queue_size = memory_->queue_size();
1322
1323 // There is only one interesting case. We need to know if the queue is empty.
1324 // That is done with a sentinel value. At worst, this will be off by one.
1325 const QueueIndex next_queue_index =
1326 memory_->next_queue_index.Load(queue_size);
1327 if (next_queue_index.valid()) {
1328 const QueueIndex current_queue_index = next_queue_index.DecrementBy(1u);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001329 return current_queue_index;
Austin Schuh20b2b082019-09-11 20:42:56 -07001330 }
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001331 return QueueIndex::Invalid();
1332}
1333
1334size_t LocklessQueueSize(const LocklessQueueMemory *memory) {
1335 return memory->queue_size();
1336}
1337
1338size_t LocklessQueueMessageDataSize(const LocklessQueueMemory *memory) {
1339 return memory->message_data_size();
Austin Schuh20b2b082019-09-11 20:42:56 -07001340}
1341
1342namespace {
1343
1344// Prints out the mutex state. Not safe to use while the mutex is being
1345// changed.
1346::std::string PrintMutex(aos_mutex *mutex) {
1347 ::std::stringstream s;
1348 s << "aos_mutex(" << ::std::hex << mutex->futex;
1349
1350 if (mutex->futex != 0) {
1351 s << ":";
1352 if (mutex->futex & FUTEX_OWNER_DIED) {
1353 s << "FUTEX_OWNER_DIED|";
1354 }
1355 s << "tid=" << (mutex->futex & FUTEX_TID_MASK);
1356 }
1357
1358 s << ")";
1359 return s.str();
1360}
1361
1362} // namespace
1363
1364void PrintLocklessQueueMemory(LocklessQueueMemory *memory) {
1365 const size_t queue_size = memory->queue_size();
1366 ::std::cout << "LocklessQueueMemory (" << memory << ") {" << ::std::endl;
1367 ::std::cout << " aos_mutex queue_setup_lock = "
1368 << PrintMutex(&memory->queue_setup_lock) << ::std::endl;
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001369 ::std::cout << " bool initialized = " << memory->initialized << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001370 ::std::cout << " config {" << ::std::endl;
1371 ::std::cout << " size_t num_watchers = " << memory->config.num_watchers
1372 << ::std::endl;
1373 ::std::cout << " size_t num_senders = " << memory->config.num_senders
1374 << ::std::endl;
Brian Silverman177567e2020-08-12 19:51:33 -07001375 ::std::cout << " size_t num_pinners = " << memory->config.num_pinners
1376 << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001377 ::std::cout << " size_t queue_size = " << memory->config.queue_size
1378 << ::std::endl;
1379 ::std::cout << " size_t message_data_size = "
1380 << memory->config.message_data_size << ::std::endl;
1381
1382 ::std::cout << " AtomicQueueIndex next_queue_index = "
1383 << memory->next_queue_index.Load(queue_size).DebugString()
1384 << ::std::endl;
1385
Austin Schuh3328d132020-02-28 13:54:57 -08001386 ::std::cout << " uid_t uid = " << memory->uid << ::std::endl;
1387
Austin Schuh20b2b082019-09-11 20:42:56 -07001388 ::std::cout << " }" << ::std::endl;
1389 ::std::cout << " AtomicIndex queue[" << queue_size << "] {" << ::std::endl;
1390 for (size_t i = 0; i < queue_size; ++i) {
1391 ::std::cout << " [" << i << "] -> "
1392 << memory->GetQueue(i)->Load().DebugString() << ::std::endl;
1393 }
1394 ::std::cout << " }" << ::std::endl;
1395 ::std::cout << " Message messages[" << memory->num_messages() << "] {"
1396 << ::std::endl;
1397 for (size_t i = 0; i < memory->num_messages(); ++i) {
1398 Message *m = memory->GetMessage(Index(i, i));
Brian Silverman001f24d2020-08-12 19:33:20 -07001399 ::std::cout << " [" << i << "] -> Message 0x" << std::hex
1400 << (reinterpret_cast<uintptr_t>(
1401 memory->GetMessage(Index(i, i))) -
1402 reinterpret_cast<uintptr_t>(memory))
1403 << std::dec << " {" << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001404 ::std::cout << " Header {" << ::std::endl;
1405 ::std::cout << " AtomicQueueIndex queue_index = "
1406 << m->header.queue_index.Load(queue_size).DebugString()
1407 << ::std::endl;
Brian Silverman001f24d2020-08-12 19:33:20 -07001408 ::std::cout << " monotonic_clock::time_point monotonic_sent_time = "
1409 << m->header.monotonic_sent_time << " 0x" << std::hex
1410 << m->header.monotonic_sent_time.time_since_epoch().count()
1411 << std::dec << ::std::endl;
1412 ::std::cout << " realtime_clock::time_point realtime_sent_time = "
1413 << m->header.realtime_sent_time << " 0x" << std::hex
1414 << m->header.realtime_sent_time.time_since_epoch().count()
1415 << std::dec << ::std::endl;
1416 ::std::cout
1417 << " monotonic_clock::time_point monotonic_remote_time = "
1418 << m->header.monotonic_remote_time << " 0x" << std::hex
1419 << m->header.monotonic_remote_time.time_since_epoch().count()
1420 << std::dec << ::std::endl;
1421 ::std::cout << " realtime_clock::time_point realtime_remote_time = "
1422 << m->header.realtime_remote_time << " 0x" << std::hex
1423 << m->header.realtime_remote_time.time_since_epoch().count()
1424 << std::dec << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001425 ::std::cout << " size_t length = " << m->header.length
1426 << ::std::endl;
1427 ::std::cout << " }" << ::std::endl;
Austin Schuhbe416742020-10-03 17:24:26 -07001428 const bool corrupt = CheckBothRedzones(memory, m);
1429 if (corrupt) {
1430 absl::Span<char> pre_redzone = m->PreRedzone(memory->message_data_size());
1431 absl::Span<char> post_redzone =
1432 m->PostRedzone(memory->message_data_size(), memory->message_size());
1433
1434 ::std::cout << " pre-redzone: \""
1435 << absl::BytesToHexString(std::string_view(
1436 pre_redzone.data(), pre_redzone.size()))
1437 << std::endl;
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001438 ::std::cout << " // *** DATA REDZONES ARE CORRUPTED ***"
1439 << ::std::endl;
Austin Schuhbe416742020-10-03 17:24:26 -07001440 ::std::cout << " post-redzone: \""
1441 << absl::BytesToHexString(std::string_view(
1442 post_redzone.data(), post_redzone.size()))
1443 << std::endl;
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001444 }
Austin Schuh20b2b082019-09-11 20:42:56 -07001445 ::std::cout << " data: {";
1446
Brian Silverman001f24d2020-08-12 19:33:20 -07001447 if (FLAGS_dump_lockless_queue_data) {
1448 const char *const m_data = m->data(memory->message_data_size());
Austin Schuhbe416742020-10-03 17:24:26 -07001449 std::cout << absl::BytesToHexString(std::string_view(
1450 m_data, corrupt ? memory->message_data_size() : m->header.length));
Austin Schuh20b2b082019-09-11 20:42:56 -07001451 }
1452 ::std::cout << ::std::setfill(' ') << ::std::dec << "}" << ::std::endl;
1453 ::std::cout << " }," << ::std::endl;
1454 }
1455 ::std::cout << " }" << ::std::endl;
1456
Alex Perrycb7da4b2019-08-28 19:35:56 -07001457 ::std::cout << " Sender senders[" << memory->num_senders() << "] {"
1458 << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001459 for (size_t i = 0; i < memory->num_senders(); ++i) {
1460 Sender *s = memory->GetSender(i);
1461 ::std::cout << " [" << i << "] -> Sender {" << ::std::endl;
1462 ::std::cout << " aos_mutex tid = " << PrintMutex(&s->tid)
1463 << ::std::endl;
1464 ::std::cout << " AtomicIndex scratch_index = "
1465 << s->scratch_index.Load().DebugString() << ::std::endl;
1466 ::std::cout << " AtomicIndex to_replace = "
1467 << s->to_replace.Load().DebugString() << ::std::endl;
1468 ::std::cout << " }" << ::std::endl;
1469 }
1470 ::std::cout << " }" << ::std::endl;
1471
Brian Silverman177567e2020-08-12 19:51:33 -07001472 ::std::cout << " Pinner pinners[" << memory->num_pinners() << "] {"
1473 << ::std::endl;
1474 for (size_t i = 0; i < memory->num_pinners(); ++i) {
1475 Pinner *p = memory->GetPinner(i);
1476 ::std::cout << " [" << i << "] -> Pinner {" << ::std::endl;
1477 ::std::cout << " aos_mutex tid = " << PrintMutex(&p->tid)
1478 << ::std::endl;
1479 ::std::cout << " AtomicIndex scratch_index = "
1480 << p->scratch_index.Load().DebugString() << ::std::endl;
1481 ::std::cout << " AtomicIndex pinned = "
1482 << p->pinned.Load(memory->queue_size()).DebugString()
1483 << ::std::endl;
1484 ::std::cout << " }" << ::std::endl;
1485 }
1486 ::std::cout << " }" << ::std::endl;
1487
Austin Schuh20b2b082019-09-11 20:42:56 -07001488 ::std::cout << " Watcher watchers[" << memory->num_watchers() << "] {"
1489 << ::std::endl;
1490 for (size_t i = 0; i < memory->num_watchers(); ++i) {
1491 Watcher *w = memory->GetWatcher(i);
1492 ::std::cout << " [" << i << "] -> Watcher {" << ::std::endl;
1493 ::std::cout << " aos_mutex tid = " << PrintMutex(&w->tid)
1494 << ::std::endl;
1495 ::std::cout << " pid_t pid = " << w->pid << ::std::endl;
1496 ::std::cout << " int priority = " << w->priority << ::std::endl;
1497 ::std::cout << " }" << ::std::endl;
1498 }
1499 ::std::cout << " }" << ::std::endl;
1500
1501 ::std::cout << "}" << ::std::endl;
1502}
1503
1504} // namespace ipc_lib
1505} // namespace aos