blob: 165f6174b75c87f90498c8de9365b779f0412198 [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 Schuh20b2b082019-09-11 20:42:56 -070012#include "aos/ipc_lib/lockless_queue_memory.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070013#include "aos/realtime.h"
Austin Schuh20b2b082019-09-11 20:42:56 -070014#include "aos/util/compiler_memory_barrier.h"
Austin Schuhf257f3c2019-10-27 21:00:43 -070015#include "glog/logging.h"
Austin Schuh20b2b082019-09-11 20:42:56 -070016
17namespace aos {
18namespace ipc_lib {
Austin Schuh20b2b082019-09-11 20:42:56 -070019namespace {
20
Brian Silvermanfafe1fa2019-12-18 21:42:18 -080021class GrabQueueSetupLockOrDie {
22 public:
23 GrabQueueSetupLockOrDie(LocklessQueueMemory *memory) : memory_(memory) {
24 const int result = mutex_grab(&(memory->queue_setup_lock));
25 CHECK(result == 0 || result == 1) << ": " << result;
26 }
Austin Schuh20b2b082019-09-11 20:42:56 -070027
Brian Silvermanfafe1fa2019-12-18 21:42:18 -080028 ~GrabQueueSetupLockOrDie() { mutex_unlock(&(memory_->queue_setup_lock)); }
29
30 GrabQueueSetupLockOrDie(const GrabQueueSetupLockOrDie &) = delete;
31 GrabQueueSetupLockOrDie &operator=(const GrabQueueSetupLockOrDie &) = delete;
32
33 private:
34 LocklessQueueMemory *const memory_;
35};
36
Brian Silvermand5ca8c62020-08-12 19:51:03 -070037// Returns true if it succeeded. Returns false if another sender died in the
38// middle.
39bool DoCleanup(LocklessQueueMemory *memory, const GrabQueueSetupLockOrDie &) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -080040 // Make sure we start looking at shared memory fresh right now. We'll handle
41 // people dying partway through by either cleaning up after them or not, but
42 // we want to ensure we clean up after anybody who has already died when we
43 // start.
44 aos_compiler_memory_barrier();
45
Austin Schuh20b2b082019-09-11 20:42:56 -070046 const size_t num_senders = memory->num_senders();
47 const size_t queue_size = memory->queue_size();
48 const size_t num_messages = memory->num_messages();
49
50 // There are a large number of crazy cases here for how things can go wrong
51 // and how we have to recover. They either require us to keep extra track of
52 // what is going on, slowing down the send path, or require a large number of
53 // cases.
54 //
55 // The solution here is to not over-think it. This is running while not real
56 // time during construction. It is allowed to be slow. It will also very
57 // rarely trigger. There is a small uS window where process death is
58 // ambiguous.
59 //
60 // So, build up a list N long, where N is the number of messages. Search
61 // through the entire queue and the sender list (ignoring any dead senders),
62 // and mark down which ones we have seen. Once we have seen all the messages
63 // except the N dead senders, we know which messages are dead. Because the
64 // queue is active while we do this, it may take a couple of go arounds to see
65 // everything.
66
Brian Silvermand5ca8c62020-08-12 19:51:03 -070067 ::std::vector<bool> need_recovery(num_senders, false);
68
Austin Schuh20b2b082019-09-11 20:42:56 -070069 // Do the easy case. Find all senders who have died. See if they are either
70 // consistent already, or if they have copied over to_replace to the scratch
71 // index, but haven't cleared to_replace. Count them.
72 size_t valid_senders = 0;
73 for (size_t i = 0; i < num_senders; ++i) {
74 Sender *sender = memory->GetSender(i);
75 const uint32_t tid =
Brian Silvermanfafe1fa2019-12-18 21:42:18 -080076 __atomic_load_n(&(sender->tid.futex), __ATOMIC_ACQUIRE);
Brian Silvermand5ca8c62020-08-12 19:51:03 -070077 if (!(tid & FUTEX_OWNER_DIED)) {
Austin Schuh20b2b082019-09-11 20:42:56 -070078 // Not dead.
79 ++valid_senders;
Brian Silvermand5ca8c62020-08-12 19:51:03 -070080 continue;
Austin Schuh20b2b082019-09-11 20:42:56 -070081 }
Brian Silvermand5ca8c62020-08-12 19:51:03 -070082 VLOG(3) << "Found an easy death for sender " << i;
83 // We can do a relaxed load here because we're the only person touching
84 // this sender at this point.
85 const Index to_replace = sender->to_replace.RelaxedLoad();
86 const Index scratch_index = sender->scratch_index.Load();
87
88 // I find it easiest to think about this in terms of the set of observable
89 // states. The main code progresses through the following states:
90
91 // 1) scratch_index = xxx
92 // to_replace = invalid
93 // This is unambiguous. Already good.
94
95 // 2) scratch_index = xxx
96 // to_replace = yyy
97 // Very ambiguous. Is xxx or yyy the correct one? Need to either roll
98 // this forwards or backwards.
99
100 // 3) scratch_index = yyy
101 // to_replace = yyy
102 // We are in the act of moving to_replace to scratch_index, but didn't
103 // finish. Easy.
104
105 // 4) scratch_index = yyy
106 // to_replace = invalid
107 // Finished, but died. Looks like 1)
108
109 // Any cleanup code needs to follow the same set of states to be robust to
110 // death, so death can be restarted.
111
112 if (!to_replace.valid()) {
113 // 1) or 4). Make sure we aren't corrupted and declare victory.
114 CHECK(scratch_index.valid());
115
116 __atomic_store_n(&(sender->tid.futex), 0, __ATOMIC_RELEASE);
117 ++valid_senders;
118 continue;
119 }
120
121 // Could be 2) or 3) at this point.
122
123 if (to_replace == scratch_index) {
124 // 3) for sure.
125 // Just need to invalidate to_replace to finish.
126 sender->to_replace.Invalidate();
127
128 // And mark that we succeeded.
129 __atomic_store_n(&(sender->tid.futex), 0, __ATOMIC_RELEASE);
130 ++valid_senders;
131 continue;
132 }
133
134 // Must be 2). Mark it for later.
135 need_recovery[i] = true;
Austin Schuh20b2b082019-09-11 20:42:56 -0700136 }
137
138 // If all the senders are (or were made) good, there is no need to do the hard
139 // case.
140 if (valid_senders == num_senders) {
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700141 return true;
Austin Schuh20b2b082019-09-11 20:42:56 -0700142 }
143
Alex Perrycb7da4b2019-08-28 19:35:56 -0700144 VLOG(3) << "Starting hard cleanup";
Austin Schuh20b2b082019-09-11 20:42:56 -0700145
146 size_t num_accounted_for = 0;
147 size_t num_missing = 0;
148 ::std::vector<bool> accounted_for(num_messages, false);
149
150 while ((num_accounted_for + num_missing) != num_messages) {
151 num_missing = 0;
152 for (size_t i = 0; i < num_senders; ++i) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800153 Sender *const sender = memory->GetSender(i);
Austin Schuh20b2b082019-09-11 20:42:56 -0700154 const uint32_t tid =
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800155 __atomic_load_n(&(sender->tid.futex), __ATOMIC_ACQUIRE);
Austin Schuh20b2b082019-09-11 20:42:56 -0700156 if (tid & FUTEX_OWNER_DIED) {
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700157 if (!need_recovery[i]) {
158 return false;
159 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700160 ++num_missing;
161 } else {
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700162 CHECK(!need_recovery[i]) << ": Somebody else recovered a sender: " << i;
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800163 // We can do a relaxed load here because we're the only person touching
164 // this sender at this point, if it matters. If it's not a dead sender,
165 // then any message it every has will already be accounted for, so this
166 // will always be a NOP.
Austin Schuh20b2b082019-09-11 20:42:56 -0700167 const Index scratch_index = sender->scratch_index.RelaxedLoad();
168 if (!accounted_for[scratch_index.message_index()]) {
169 ++num_accounted_for;
170 }
171 accounted_for[scratch_index.message_index()] = true;
172 }
173 }
174
175 for (size_t i = 0; i < queue_size; ++i) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800176 // Same logic as above for scratch_index applies here too.
Austin Schuh20b2b082019-09-11 20:42:56 -0700177 const Index index = memory->GetQueue(i)->RelaxedLoad();
178 if (!accounted_for[index.message_index()]) {
179 ++num_accounted_for;
180 }
181 accounted_for[index.message_index()] = true;
182 }
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700183
184 CHECK_LE(num_accounted_for + num_missing, num_messages);
Austin Schuh20b2b082019-09-11 20:42:56 -0700185 }
186
187 while (num_missing != 0) {
188 const size_t starting_num_missing = num_missing;
189 for (size_t i = 0; i < num_senders; ++i) {
190 Sender *sender = memory->GetSender(i);
191 const uint32_t tid =
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800192 __atomic_load_n(&(sender->tid.futex), __ATOMIC_ACQUIRE);
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700193 if (!(tid & FUTEX_OWNER_DIED)) {
194 CHECK(!need_recovery[i]) << ": Somebody else recovered a sender: " << i;
195 continue;
196 }
197 if (!need_recovery[i]) {
198 return false;
199 }
200 // We can do relaxed loads here because we're the only person touching
201 // this sender at this point.
202 const Index scratch_index = sender->scratch_index.RelaxedLoad();
203 const Index to_replace = sender->to_replace.RelaxedLoad();
Austin Schuh20b2b082019-09-11 20:42:56 -0700204
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700205 // Candidate.
206 if (to_replace.valid()) {
207 CHECK_LE(to_replace.message_index(), accounted_for.size());
208 }
209 if (scratch_index.valid()) {
210 CHECK_LE(scratch_index.message_index(), accounted_for.size());
211 }
212 if (!to_replace.valid() || accounted_for[to_replace.message_index()]) {
213 CHECK(scratch_index.valid());
214 VLOG(3) << "Sender " << i
215 << " died, to_replace is already accounted for";
216 // If both are accounted for, we are corrupt...
217 CHECK(!accounted_for[scratch_index.message_index()]);
Austin Schuh20b2b082019-09-11 20:42:56 -0700218
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700219 // to_replace is already accounted for. This means that we didn't
220 // atomically insert scratch_index into the queue yet. So
221 // invalidate to_replace.
222 sender->to_replace.Invalidate();
Austin Schuh20b2b082019-09-11 20:42:56 -0700223
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700224 // And then mark this sender clean.
225 __atomic_store_n(&(sender->tid.futex), 0, __ATOMIC_RELEASE);
226 need_recovery[i] = false;
Austin Schuh20b2b082019-09-11 20:42:56 -0700227
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700228 // And account for scratch_index.
229 accounted_for[scratch_index.message_index()] = true;
230 --num_missing;
231 ++num_accounted_for;
232 } else if (!scratch_index.valid() ||
233 accounted_for[scratch_index.message_index()]) {
234 VLOG(3) << "Sender " << i
235 << " died, scratch_index is already accounted for";
236 // scratch_index is accounted for. That means we did the insert,
237 // but didn't record it.
238 CHECK(to_replace.valid());
239 // Finish the transaction. Copy to_replace, then clear it.
Austin Schuh20b2b082019-09-11 20:42:56 -0700240
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700241 sender->scratch_index.Store(to_replace);
242 sender->to_replace.Invalidate();
Austin Schuh20b2b082019-09-11 20:42:56 -0700243
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700244 // And then mark this sender clean.
245 __atomic_store_n(&(sender->tid.futex), 0, __ATOMIC_RELEASE);
246 need_recovery[i] = false;
Austin Schuh20b2b082019-09-11 20:42:56 -0700247
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700248 // And account for to_replace.
249 accounted_for[to_replace.message_index()] = true;
250 --num_missing;
251 ++num_accounted_for;
252 } else {
253 VLOG(3) << "Sender " << i << " died, neither is accounted for";
254 // Ambiguous. There will be an unambiguous one somewhere that we
255 // can do first.
Austin Schuh20b2b082019-09-11 20:42:56 -0700256 }
257 }
258 // CHECK that we are making progress.
259 CHECK_NE(num_missing, starting_num_missing);
260 }
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700261 return true;
262}
263
264void Cleanup(LocklessQueueMemory *memory, const GrabQueueSetupLockOrDie &lock) {
265 // The number of iterations is bounded here because there are only a finite
266 // number of senders in existence which could die, and no new ones can be
267 // created while we're in here holding the lock.
268 while (!DoCleanup(memory, lock)) {
269 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700270}
271
272// Exposes rt_tgsigqueueinfo so we can send the signal *just* to the target
273// thread.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800274// TODO(Brian): Do directly in assembly for armhf at least for efficiency.
Austin Schuh20b2b082019-09-11 20:42:56 -0700275int rt_tgsigqueueinfo(pid_t tgid, pid_t tid, int sig, siginfo_t *si) {
276 return syscall(SYS_rt_tgsigqueueinfo, tgid, tid, sig, si);
277}
278
279} // namespace
280
Austin Schuh4bc4f902019-12-23 18:04:51 -0800281size_t LocklessQueueConfiguration::message_size() const {
282 // Round up the message size so following data is aligned appropriately.
Brian Silvermana1652f32020-01-29 20:41:44 -0800283 return LocklessQueueMemory::AlignmentRoundUp(message_data_size +
284 (kChannelDataAlignment - 1)) +
Austin Schuh4bc4f902019-12-23 18:04:51 -0800285 sizeof(Message);
286}
287
Austin Schuh20b2b082019-09-11 20:42:56 -0700288size_t LocklessQueueMemorySize(LocklessQueueConfiguration config) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800289 // Round up the message size so following data is aligned appropriately.
290 config.message_data_size =
291 LocklessQueueMemory::AlignmentRoundUp(config.message_data_size);
Austin Schuh20b2b082019-09-11 20:42:56 -0700292
293 // As we build up the size, confirm that everything is aligned to the
294 // alignment requirements of the type.
295 size_t size = sizeof(LocklessQueueMemory);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800296 CHECK_EQ(size % alignof(LocklessQueueMemory), 0u);
Austin Schuh20b2b082019-09-11 20:42:56 -0700297
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800298 CHECK_EQ(size % alignof(AtomicIndex), 0u);
Austin Schuh20b2b082019-09-11 20:42:56 -0700299 size += LocklessQueueMemory::SizeOfQueue(config);
300
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800301 CHECK_EQ(size % alignof(Message), 0u);
Austin Schuh20b2b082019-09-11 20:42:56 -0700302 size += LocklessQueueMemory::SizeOfMessages(config);
303
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800304 CHECK_EQ(size % alignof(Watcher), 0u);
Austin Schuh20b2b082019-09-11 20:42:56 -0700305 size += LocklessQueueMemory::SizeOfWatchers(config);
306
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800307 CHECK_EQ(size % alignof(Sender), 0u);
Austin Schuh20b2b082019-09-11 20:42:56 -0700308 size += LocklessQueueMemory::SizeOfSenders(config);
309
310 return size;
311}
312
313LocklessQueueMemory *InitializeLocklessQueueMemory(
314 LocklessQueueMemory *memory, LocklessQueueConfiguration config) {
315 // Everything should be zero initialized already. So we just need to fill
316 // everything out properly.
317
Brian Silvermanc57ff0a2020-04-28 16:45:13 -0700318 // This is the UID we will use for checking signal-sending permission
319 // compatibility.
320 //
321 // The manpage says:
322 // For a process to have permission to send a signal, it must either be
323 // privileged [...], or the real or effective user ID of the sending process
324 // must equal the real or saved set-user-ID of the target process.
325 //
326 // Processes typically initialize a queue in random order as they start up.
327 // This means we need an algorithm for verifying all processes have
328 // permissions to send each other signals which gives the same answer no
329 // matter what order they attach in. We would also like to avoid maintaining a
330 // shared list of the UIDs of all processes.
331 //
332 // To do this while still giving sufficient flexibility for all current use
333 // cases, we track a single UID for the queue. All processes with a matching
334 // euid+suid must have this UID. Any processes with distinct euid/suid must
335 // instead have a matching ruid. This guarantees signals can be sent between
336 // all processes attached to the queue.
337 //
338 // In particular, this allows a process to change only its euid (to interact
339 // with a queue) while still maintaining privileges via its ruid. However, it
340 // can only use privileges in ways that do not require changing the euid back,
341 // because while the euid is different it will not be able to receive signals.
342 // We can't actually verify that, but we can sanity check that things are
343 // valid when the queue is initialized.
344
345 uid_t uid;
346 {
347 uid_t ruid, euid, suid;
348 PCHECK(getresuid(&ruid, &euid, &suid) == 0);
349 // If these are equal, then use them, even if that's different from the real
350 // UID. This allows processes to keep a real UID of 0 (to have permissions
351 // to perform system-level changes) while still being able to communicate
352 // with processes running unprivileged as a distinct user.
353 if (euid == suid) {
354 uid = euid;
355 VLOG(1) << "Using euid==suid " << uid;
356 } else {
357 uid = ruid;
358 VLOG(1) << "Using ruid " << ruid;
359 }
360 }
361
Austin Schuh20b2b082019-09-11 20:42:56 -0700362 // Grab the mutex. We don't care if the previous reader died. We are going
363 // to check everything anyways.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800364 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory);
Austin Schuh20b2b082019-09-11 20:42:56 -0700365
366 if (!memory->initialized) {
367 // TODO(austin): Check these for out of bounds.
368 memory->config.num_watchers = config.num_watchers;
369 memory->config.num_senders = config.num_senders;
370 memory->config.queue_size = config.queue_size;
Austin Schuh4bc4f902019-12-23 18:04:51 -0800371 memory->config.message_data_size = config.message_data_size;
Austin Schuh20b2b082019-09-11 20:42:56 -0700372
373 const size_t num_messages = memory->num_messages();
374 // There need to be at most MaxMessages() messages allocated.
375 CHECK_LE(num_messages, Index::MaxMessages());
376
377 for (size_t i = 0; i < num_messages; ++i) {
378 memory->GetMessage(Index(QueueIndex::Zero(memory->queue_size()), i))
379 ->header.queue_index.Invalidate();
380 }
381
382 for (size_t i = 0; i < memory->queue_size(); ++i) {
383 // Make the initial counter be the furthest away number. That means that
384 // index 0 should be 0xffff, 1 should be 0, etc.
385 memory->GetQueue(i)->Store(Index(QueueIndex::Zero(memory->queue_size())
386 .IncrementBy(i)
387 .DecrementBy(memory->queue_size()),
388 i));
389 }
390
391 memory->next_queue_index.Invalidate();
Brian Silvermanc57ff0a2020-04-28 16:45:13 -0700392 memory->uid = uid;
Austin Schuh20b2b082019-09-11 20:42:56 -0700393
394 for (size_t i = 0; i < memory->num_senders(); ++i) {
395 ::aos::ipc_lib::Sender *s = memory->GetSender(i);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800396 // Nobody else can possibly be touching these because we haven't set
397 // initialized to true yet.
398 s->scratch_index.RelaxedStore(Index(0xffff, i + memory->queue_size()));
Austin Schuh20b2b082019-09-11 20:42:56 -0700399 s->to_replace.RelaxedInvalidate();
400 }
401
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800402 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -0700403 // Signal everything is done. This needs to be done last, so if we die, we
404 // redo initialization.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800405 memory->initialized = true;
Austin Schuh3328d132020-02-28 13:54:57 -0800406 } else {
Brian Silvermanc57ff0a2020-04-28 16:45:13 -0700407 CHECK_EQ(uid, memory->uid) << ": UIDs must match for all processes";
Austin Schuh20b2b082019-09-11 20:42:56 -0700408 }
409
Austin Schuh20b2b082019-09-11 20:42:56 -0700410 return memory;
411}
412
413LocklessQueue::LocklessQueue(LocklessQueueMemory *memory,
414 LocklessQueueConfiguration config)
415 : memory_(InitializeLocklessQueueMemory(memory, config)),
416 watcher_copy_(memory_->num_watchers()),
417 pid_(getpid()),
418 uid_(getuid()) {}
419
420LocklessQueue::~LocklessQueue() {
421 CHECK_EQ(watcher_index_, -1);
422
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800423 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory_);
Austin Schuh20b2b082019-09-11 20:42:56 -0700424 const int num_watchers = memory_->num_watchers();
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800425 // Cleanup is cheap. The next user will do it anyways, so no need for us to do
426 // anything right now.
Austin Schuh20b2b082019-09-11 20:42:56 -0700427
428 // And confirm that nothing is owned by us.
429 for (int i = 0; i < num_watchers; ++i) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800430 CHECK(!death_notification_is_held(&(memory_->GetWatcher(i)->tid)));
Austin Schuh20b2b082019-09-11 20:42:56 -0700431 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700432}
433
434size_t LocklessQueue::QueueSize() const { return memory_->queue_size(); }
435
436bool LocklessQueue::RegisterWakeup(int priority) {
437 // TODO(austin): Make sure signal coalescing is turned on. We don't need
438 // duplicates. That will improve performance under high load.
439
440 // Since everything is self consistent, all we need to do is make sure nobody
441 // else is running. Someone dying will get caught in the generic consistency
442 // check.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800443 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory_);
Austin Schuh20b2b082019-09-11 20:42:56 -0700444 const int num_watchers = memory_->num_watchers();
445
446 // Now, find the first empty watcher and grab it.
447 CHECK_EQ(watcher_index_, -1);
448 for (int i = 0; i < num_watchers; ++i) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800449 // If we see a slot the kernel has marked as dead, everything we do reusing
450 // it needs to happen-after whatever that process did before dying.
Brian Silverman2484eea2019-12-21 16:48:46 -0800451 auto *const futex = &(memory_->GetWatcher(i)->tid.futex);
452 const uint32_t tid = __atomic_load_n(futex, __ATOMIC_ACQUIRE);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800453 if (tid == 0 || (tid & FUTEX_OWNER_DIED)) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700454 watcher_index_ = i;
Brian Silverman2484eea2019-12-21 16:48:46 -0800455 // Relaxed is OK here because we're the only task going to touch it
456 // between here and the write in death_notification_init below (other
457 // recovery is blocked by us holding the setup lock).
458 __atomic_store_n(futex, 0, __ATOMIC_RELAXED);
Austin Schuh20b2b082019-09-11 20:42:56 -0700459 break;
460 }
461 }
462
463 // Bail if we failed to find an open slot.
464 if (watcher_index_ == -1) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700465 return false;
466 }
467
468 Watcher *w = memory_->GetWatcher(watcher_index_);
469
470 w->pid = getpid();
471 w->priority = priority;
472
473 // Grabbing a mutex is a compiler and memory barrier, so nothing before will
474 // get rearranged afterwords.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800475 death_notification_init(&(w->tid));
476 return true;
Austin Schuh20b2b082019-09-11 20:42:56 -0700477}
478
479void LocklessQueue::UnregisterWakeup() {
480 // Since everything is self consistent, all we need to do is make sure nobody
481 // else is running. Someone dying will get caught in the generic consistency
482 // check.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800483 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory_);
Austin Schuh20b2b082019-09-11 20:42:56 -0700484
485 // Make sure we are registered.
486 CHECK_NE(watcher_index_, -1);
487
488 // Make sure we still own the slot we are supposed to.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800489 CHECK(
490 death_notification_is_held(&(memory_->GetWatcher(watcher_index_)->tid)));
Austin Schuh20b2b082019-09-11 20:42:56 -0700491
492 // The act of unlocking invalidates the entry. Invalidate it.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800493 death_notification_release(&(memory_->GetWatcher(watcher_index_)->tid));
Austin Schuh20b2b082019-09-11 20:42:56 -0700494 // And internally forget the slot.
495 watcher_index_ = -1;
Austin Schuh20b2b082019-09-11 20:42:56 -0700496}
497
498int LocklessQueue::Wakeup(const int current_priority) {
499 const size_t num_watchers = memory_->num_watchers();
500
501 CHECK_EQ(watcher_copy_.size(), num_watchers);
502
503 // Grab a copy so it won't change out from underneath us, and we can sort it
504 // nicely in C++.
505 // Do note that there is still a window where the process can die *after* we
506 // read everything. We will still PI boost and send a signal to the thread in
507 // question. There is no way without pidfd's to close this window, and
508 // creating a pidfd is likely not RT.
509 for (size_t i = 0; i < num_watchers; ++i) {
510 Watcher *w = memory_->GetWatcher(i);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800511 watcher_copy_[i].tid = __atomic_load_n(&(w->tid.futex), __ATOMIC_RELAXED);
512 // Force the load of the TID to come first.
513 aos_compiler_memory_barrier();
514 watcher_copy_[i].pid = w->pid.load(std::memory_order_relaxed);
515 watcher_copy_[i].priority = w->priority.load(std::memory_order_relaxed);
Austin Schuh20b2b082019-09-11 20:42:56 -0700516
517 // Use a priority of -1 to mean an invalid entry to make sorting easier.
518 if (watcher_copy_[i].tid & FUTEX_OWNER_DIED || watcher_copy_[i].tid == 0) {
519 watcher_copy_[i].priority = -1;
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800520 } else {
521 // Ensure all of this happens after we're done looking at the pid+priority
522 // in shared memory.
523 aos_compiler_memory_barrier();
524 if (watcher_copy_[i].tid != static_cast<pid_t>(__atomic_load_n(
525 &(w->tid.futex), __ATOMIC_RELAXED))) {
526 // Confirm that the watcher hasn't been re-used and modified while we
527 // read it. If it has, mark it invalid again.
528 watcher_copy_[i].priority = -1;
529 watcher_copy_[i].tid = 0;
530 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700531 }
532 }
533
534 // Now sort.
535 ::std::sort(watcher_copy_.begin(), watcher_copy_.end(),
536 [](const WatcherCopy &a, const WatcherCopy &b) {
537 return a.priority > b.priority;
538 });
539
540 int count = 0;
541 if (watcher_copy_[0].priority != -1) {
542 const int max_priority =
543 ::std::max(current_priority, watcher_copy_[0].priority);
544 // Boost if we are RT and there is a higher priority sender out there.
545 // Otherwise we might run into priority inversions.
546 if (max_priority > current_priority && current_priority > 0) {
547 SetCurrentThreadRealtimePriority(max_priority);
548 }
549
550 // Build up the siginfo to send.
551 siginfo_t uinfo;
552 memset(&uinfo, 0, sizeof(uinfo));
553
554 uinfo.si_code = SI_QUEUE;
555 uinfo.si_pid = pid_;
556 uinfo.si_uid = uid_;
557 uinfo.si_value.sival_int = 0;
558
559 for (const WatcherCopy &watcher_copy : watcher_copy_) {
560 // The first -1 priority means we are at the end of the valid list.
561 if (watcher_copy.priority == -1) {
562 break;
563 }
564
565 // Send the signal. Target just the thread that sent it so that we can
566 // support multiple watchers in a process (when someone creates multiple
567 // event loops in different threads).
568 rt_tgsigqueueinfo(watcher_copy.pid, watcher_copy.tid, kWakeupSignal,
569 &uinfo);
570
571 ++count;
572 }
573
574 // Drop back down if we were boosted.
575 if (max_priority > current_priority && current_priority > 0) {
576 SetCurrentThreadRealtimePriority(current_priority);
577 }
578 }
579
580 return count;
581}
582
583LocklessQueue::Sender::Sender(LocklessQueueMemory *memory) : memory_(memory) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800584 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory_);
Austin Schuh20b2b082019-09-11 20:42:56 -0700585
586 // Since we already have the lock, go ahead and try cleaning up.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800587 Cleanup(memory_, grab_queue_setup_lock);
Austin Schuh20b2b082019-09-11 20:42:56 -0700588
589 const int num_senders = memory_->num_senders();
590
591 for (int i = 0; i < num_senders; ++i) {
592 ::aos::ipc_lib::Sender *s = memory->GetSender(i);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800593 // This doesn't need synchronization because we're the only process doing
594 // initialization right now, and nobody else will be touching senders which
595 // we're interested in.
Austin Schuh20b2b082019-09-11 20:42:56 -0700596 const uint32_t tid = __atomic_load_n(&(s->tid.futex), __ATOMIC_RELAXED);
597 if (tid == 0) {
598 sender_index_ = i;
599 break;
600 }
601 }
602
603 if (sender_index_ == -1) {
Austin Schuhe516ab02020-05-06 21:37:04 -0700604 VLOG(1) << "Too many senders, starting to bail.";
605 return;
Austin Schuh20b2b082019-09-11 20:42:56 -0700606 }
607
608 ::aos::ipc_lib::Sender *s = memory_->GetSender(sender_index_);
609
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800610 // Indicate that we are now alive by taking over the slot. If the previous
611 // owner died, we still want to do this.
612 death_notification_init(&(s->tid));
Austin Schuh20b2b082019-09-11 20:42:56 -0700613}
614
615LocklessQueue::Sender::~Sender() {
Austin Schuhe516ab02020-05-06 21:37:04 -0700616 if (valid()) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800617 death_notification_release(&(memory_->GetSender(sender_index_)->tid));
Austin Schuh20b2b082019-09-11 20:42:56 -0700618 }
619}
620
Austin Schuhe516ab02020-05-06 21:37:04 -0700621std::optional<LocklessQueue::Sender> LocklessQueue::MakeSender() {
622 LocklessQueue::Sender result = LocklessQueue::Sender(memory_);
623 if (result.valid()) {
624 return std::move(result);
625 } else {
626 return std::nullopt;
627 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700628}
629
630QueueIndex ZeroOrValid(QueueIndex index) {
631 if (!index.valid()) {
632 return index.Clear();
633 }
634 return index;
635}
636
Alex Perrycb7da4b2019-08-28 19:35:56 -0700637size_t LocklessQueue::Sender::size() { return memory_->message_data_size(); }
638
639void *LocklessQueue::Sender::Data() {
640 ::aos::ipc_lib::Sender *sender = memory_->GetSender(sender_index_);
641 Index scratch_index = sender->scratch_index.RelaxedLoad();
642 Message *message = memory_->GetMessage(scratch_index);
643 message->header.queue_index.Invalidate();
644
Brian Silvermana1652f32020-01-29 20:41:44 -0800645 return message->data(memory_->message_data_size());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700646}
647
Austin Schuhad154822019-12-27 15:45:13 -0800648void LocklessQueue::Sender::Send(
649 const char *data, size_t length,
650 aos::monotonic_clock::time_point monotonic_remote_time,
651 aos::realtime_clock::time_point realtime_remote_time,
652 uint32_t remote_queue_index,
653 aos::monotonic_clock::time_point *monotonic_sent_time,
654 aos::realtime_clock::time_point *realtime_sent_time,
655 uint32_t *queue_index) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700656 CHECK_LE(length, size());
Austin Schuh67420a42019-12-21 21:55:04 -0800657 // Flatbuffers write from the back of the buffer to the front. If we are
658 // going to write an explicit chunk of memory into the buffer, we need to
659 // adhere to this convention and place it at the end.
660 memcpy((reinterpret_cast<char *>(Data()) + size() - length), data, length);
Austin Schuhad154822019-12-27 15:45:13 -0800661 Send(length, monotonic_remote_time, realtime_remote_time, remote_queue_index,
662 monotonic_sent_time, realtime_sent_time, queue_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700663}
664
Austin Schuhad154822019-12-27 15:45:13 -0800665void LocklessQueue::Sender::Send(
666 size_t length, aos::monotonic_clock::time_point monotonic_remote_time,
667 aos::realtime_clock::time_point realtime_remote_time,
668 uint32_t remote_queue_index,
669 aos::monotonic_clock::time_point *monotonic_sent_time,
670 aos::realtime_clock::time_point *realtime_sent_time,
671 uint32_t *queue_index) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700672 const size_t queue_size = memory_->queue_size();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700673 CHECK_LE(length, size());
Austin Schuh20b2b082019-09-11 20:42:56 -0700674
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800675 ::aos::ipc_lib::Sender *const sender = memory_->GetSender(sender_index_);
676 // We can do a relaxed load on our sender because we're the only person
677 // modifying it right now.
678 const Index scratch_index = sender->scratch_index.RelaxedLoad();
679 Message *const message = memory_->GetMessage(scratch_index);
Austin Schuh20b2b082019-09-11 20:42:56 -0700680
Austin Schuh20b2b082019-09-11 20:42:56 -0700681 message->header.length = length;
Austin Schuhad154822019-12-27 15:45:13 -0800682 // Pass these through. Any alternative behavior can be implemented out a
683 // layer.
684 message->header.remote_queue_index = remote_queue_index;
685 message->header.monotonic_remote_time = monotonic_remote_time;
686 message->header.realtime_remote_time = realtime_remote_time;
Austin Schuh20b2b082019-09-11 20:42:56 -0700687
688 while (true) {
689 const QueueIndex actual_next_queue_index =
690 memory_->next_queue_index.Load(queue_size);
691 const QueueIndex next_queue_index = ZeroOrValid(actual_next_queue_index);
692
693 const QueueIndex incremented_queue_index = next_queue_index.Increment();
694
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800695 // This needs to synchronize with whoever the previous writer at this
696 // location was.
Austin Schuh20b2b082019-09-11 20:42:56 -0700697 const Index to_replace = memory_->LoadIndex(next_queue_index);
698
699 const QueueIndex decremented_queue_index =
700 next_queue_index.DecrementBy(queue_size);
701
702 // See if we got beat. If we did, try to atomically update
703 // next_queue_index in case the previous writer failed and retry.
704 if (!to_replace.IsPlausible(decremented_queue_index)) {
705 // We don't care about the result. It will either succeed, or we got
706 // beat in fixing it and just need to give up and try again. If we got
707 // beat multiple times, the only way progress can be made is if the queue
708 // is updated as well. This means that if we retry reading
709 // next_queue_index, we will be at most off by one and can retry.
710 //
711 // Both require no further action from us.
712 //
713 // TODO(austin): If we are having fairness issues under contention, we
714 // could have a mode bit in next_queue_index, and could use a lock or some
715 // other form of PI boosting to let the higher priority task win.
716 memory_->next_queue_index.CompareAndExchangeStrong(
717 actual_next_queue_index, incremented_queue_index);
718
Alex Perrycb7da4b2019-08-28 19:35:56 -0700719 VLOG(3) << "We were beat. Try again. Was " << std::hex
720 << to_replace.get() << ", is " << decremented_queue_index.index();
Austin Schuh20b2b082019-09-11 20:42:56 -0700721 continue;
722 }
723
724 // Confirm that the message is what it should be.
725 {
Austin Schuh20b2b082019-09-11 20:42:56 -0700726 const QueueIndex previous_index =
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800727 memory_->GetMessage(to_replace)->header.queue_index.Load(queue_size);
Austin Schuh20b2b082019-09-11 20:42:56 -0700728 if (previous_index != decremented_queue_index && previous_index.valid()) {
729 // Retry.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700730 VLOG(3) << "Something fishy happened, queue index doesn't match. "
731 "Retrying. Previous index was "
732 << std::hex << previous_index.index() << ", should be "
733 << decremented_queue_index.index();
Austin Schuh20b2b082019-09-11 20:42:56 -0700734 continue;
735 }
736 }
737
738 message->header.monotonic_sent_time = ::aos::monotonic_clock::now();
739 message->header.realtime_sent_time = ::aos::realtime_clock::now();
Austin Schuhad154822019-12-27 15:45:13 -0800740 if (monotonic_sent_time != nullptr) {
741 *monotonic_sent_time = message->header.monotonic_sent_time;
742 }
743 if (realtime_sent_time != nullptr) {
744 *realtime_sent_time = message->header.realtime_sent_time;
745 }
746 if (queue_index != nullptr) {
747 *queue_index = next_queue_index.index();
748 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700749
750 // Before we are fully done filling out the message, update the Sender state
751 // with the new index to write. This re-uses the barrier for the
752 // queue_index store.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700753 const Index index_to_write(next_queue_index, scratch_index.message_index());
Austin Schuh20b2b082019-09-11 20:42:56 -0700754
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800755 aos_compiler_memory_barrier();
756 // We're the only person who cares about our scratch index, besides somebody
757 // cleaning up after us.
Austin Schuh20b2b082019-09-11 20:42:56 -0700758 sender->scratch_index.RelaxedStore(index_to_write);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800759 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -0700760
761 message->header.queue_index.Store(next_queue_index);
762
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800763 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -0700764 // The message is now filled out, and we have a confirmed slot to store
765 // into.
766 //
767 // Start by writing down what we are going to pull out of the queue. This
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800768 // was Invalid before now. Only person who will read this is whoever cleans
769 // up after us, so no synchronization necessary.
Austin Schuh20b2b082019-09-11 20:42:56 -0700770 sender->to_replace.RelaxedStore(to_replace);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800771 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -0700772
773 // Then exchange the next index into the queue.
774 if (!memory_->GetQueue(next_queue_index.Wrapped())
775 ->CompareAndExchangeStrong(to_replace, index_to_write)) {
776 // Aw, didn't succeed. Retry.
777 sender->to_replace.RelaxedInvalidate();
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800778 aos_compiler_memory_barrier();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700779 VLOG(3) << "Failed to wrap into queue";
Austin Schuh20b2b082019-09-11 20:42:56 -0700780 continue;
781 }
782
783 // Then update next_queue_index to save the next user some computation time.
784 memory_->next_queue_index.CompareAndExchangeStrong(actual_next_queue_index,
785 incremented_queue_index);
786
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800787 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -0700788 // Now update the scratch space and record that we succeeded.
789 sender->scratch_index.Store(to_replace);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800790 aos_compiler_memory_barrier();
791 // And then record that we succeeded, but definitely after the above store.
Austin Schuh20b2b082019-09-11 20:42:56 -0700792 sender->to_replace.RelaxedInvalidate();
793 break;
794 }
795}
796
797LocklessQueue::ReadResult LocklessQueue::Read(
798 uint32_t uint32_queue_index,
799 ::aos::monotonic_clock::time_point *monotonic_sent_time,
Austin Schuhad154822019-12-27 15:45:13 -0800800 ::aos::realtime_clock::time_point *realtime_sent_time,
801 ::aos::monotonic_clock::time_point *monotonic_remote_time,
802 ::aos::realtime_clock::time_point *realtime_remote_time,
803 uint32_t *remote_queue_index, size_t *length, char *data) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700804 const size_t queue_size = memory_->queue_size();
805
806 // Build up the QueueIndex.
807 const QueueIndex queue_index =
808 QueueIndex::Zero(queue_size).IncrementBy(uint32_queue_index);
809
810 // Read the message stored at the requested location.
811 Index mi = memory_->LoadIndex(queue_index);
812 Message *m = memory_->GetMessage(mi);
813
814 while (true) {
815 // We need to confirm that the data doesn't change while we are reading it.
816 // Do that by first confirming that the message points to the queue index we
817 // want.
818 const QueueIndex starting_queue_index =
819 m->header.queue_index.Load(queue_size);
820 if (starting_queue_index != queue_index) {
821 // If we found a message that is exactly 1 loop old, we just wrapped.
822 if (starting_queue_index == queue_index.DecrementBy(queue_size)) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700823 VLOG(3) << "Matches: " << std::hex << starting_queue_index.index()
824 << ", " << queue_index.DecrementBy(queue_size).index();
Austin Schuh20b2b082019-09-11 20:42:56 -0700825 return ReadResult::NOTHING_NEW;
826 } else {
827 // Someone has re-used this message between when we pulled it out of the
828 // queue and when we grabbed its index. It is pretty hard to deduce
829 // what happened. Just try again.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800830 Message *const new_m = memory_->GetMessage(queue_index);
Austin Schuh20b2b082019-09-11 20:42:56 -0700831 if (m != new_m) {
832 m = new_m;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700833 VLOG(3) << "Retrying, m doesn't match";
Austin Schuh20b2b082019-09-11 20:42:56 -0700834 continue;
835 }
836
837 // We have confirmed that message still points to the same message. This
838 // means that the message didn't get swapped out from under us, so
839 // starting_queue_index is correct.
840 //
841 // Either we got too far behind (signaled by this being a valid
842 // message), or this is one of the initial messages which are invalid.
843 if (starting_queue_index.valid()) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700844 VLOG(3) << "Too old. Tried for " << std::hex << queue_index.index()
845 << ", got " << starting_queue_index.index() << ", behind by "
846 << std::dec
847 << (starting_queue_index.index() - queue_index.index());
Austin Schuh20b2b082019-09-11 20:42:56 -0700848 return ReadResult::TOO_OLD;
849 }
850
Alex Perrycb7da4b2019-08-28 19:35:56 -0700851 VLOG(3) << "Initial";
Austin Schuh20b2b082019-09-11 20:42:56 -0700852
853 // There isn't a valid message at this location.
854 //
855 // If someone asks for one of the messages within the first go around,
856 // then they need to wait. They got ahead. Otherwise, they are
857 // asking for something crazy, like something before the beginning of
858 // the queue. Tell them that they are behind.
859 if (uint32_queue_index < memory_->queue_size()) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700860 VLOG(3) << "Near zero, " << std::hex << uint32_queue_index;
Austin Schuh20b2b082019-09-11 20:42:56 -0700861 return ReadResult::NOTHING_NEW;
862 } else {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800863 VLOG(3) << "Not near zero, " << std::hex << uint32_queue_index;
Austin Schuh20b2b082019-09-11 20:42:56 -0700864 return ReadResult::TOO_OLD;
865 }
866 }
867 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700868 VLOG(3) << "Eq: " << std::hex << starting_queue_index.index() << ", "
869 << queue_index.index();
Austin Schuh20b2b082019-09-11 20:42:56 -0700870 break;
871 }
872
Alex Perrycb7da4b2019-08-28 19:35:56 -0700873 // Then read the data out. Copy it all out to be deterministic and so we can
874 // make length be from either end.
Austin Schuh20b2b082019-09-11 20:42:56 -0700875 *monotonic_sent_time = m->header.monotonic_sent_time;
876 *realtime_sent_time = m->header.realtime_sent_time;
Austin Schuhad154822019-12-27 15:45:13 -0800877 if (m->header.remote_queue_index == 0xffffffffu) {
878 *remote_queue_index = queue_index.index();
879 } else {
880 *remote_queue_index = m->header.remote_queue_index;
881 }
882 *monotonic_remote_time = m->header.monotonic_remote_time;
883 *realtime_remote_time = m->header.realtime_remote_time;
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800884 if (data) {
885 memcpy(data, m->data(memory_->message_data_size()), message_data_size());
886 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700887 *length = m->header.length;
888
889 // And finally, confirm that the message *still* points to the queue index we
890 // want. This means it didn't change out from under us.
891 // If something changed out from under us, we were reading it much too late in
892 // it's lifetime.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800893 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -0700894 const QueueIndex final_queue_index = m->header.queue_index.Load(queue_size);
895 if (final_queue_index != queue_index) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700896 VLOG(3) << "Changed out from under us. Reading " << std::hex
897 << queue_index.index() << ", finished with "
898 << final_queue_index.index() << ", delta: " << std::dec
899 << (final_queue_index.index() - queue_index.index());
900 return ReadResult::OVERWROTE;
Austin Schuh20b2b082019-09-11 20:42:56 -0700901 }
902
903 return ReadResult::GOOD;
904}
905
Alex Perrycb7da4b2019-08-28 19:35:56 -0700906size_t LocklessQueue::queue_size() const { return memory_->queue_size(); }
907size_t LocklessQueue::message_data_size() const {
908 return memory_->message_data_size();
909}
910
911QueueIndex LocklessQueue::LatestQueueIndex() {
Austin Schuh20b2b082019-09-11 20:42:56 -0700912 const size_t queue_size = memory_->queue_size();
913
914 // There is only one interesting case. We need to know if the queue is empty.
915 // That is done with a sentinel value. At worst, this will be off by one.
916 const QueueIndex next_queue_index =
917 memory_->next_queue_index.Load(queue_size);
918 if (next_queue_index.valid()) {
919 const QueueIndex current_queue_index = next_queue_index.DecrementBy(1u);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700920 return current_queue_index;
Austin Schuh20b2b082019-09-11 20:42:56 -0700921 } else {
922 return empty_queue_index();
923 }
924}
925
926namespace {
927
928// Prints out the mutex state. Not safe to use while the mutex is being
929// changed.
930::std::string PrintMutex(aos_mutex *mutex) {
931 ::std::stringstream s;
932 s << "aos_mutex(" << ::std::hex << mutex->futex;
933
934 if (mutex->futex != 0) {
935 s << ":";
936 if (mutex->futex & FUTEX_OWNER_DIED) {
937 s << "FUTEX_OWNER_DIED|";
938 }
939 s << "tid=" << (mutex->futex & FUTEX_TID_MASK);
940 }
941
942 s << ")";
943 return s.str();
944}
945
946} // namespace
947
948void PrintLocklessQueueMemory(LocklessQueueMemory *memory) {
949 const size_t queue_size = memory->queue_size();
950 ::std::cout << "LocklessQueueMemory (" << memory << ") {" << ::std::endl;
951 ::std::cout << " aos_mutex queue_setup_lock = "
952 << PrintMutex(&memory->queue_setup_lock) << ::std::endl;
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800953 ::std::cout << " bool initialized = " << memory->initialized << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -0700954 ::std::cout << " config {" << ::std::endl;
955 ::std::cout << " size_t num_watchers = " << memory->config.num_watchers
956 << ::std::endl;
957 ::std::cout << " size_t num_senders = " << memory->config.num_senders
958 << ::std::endl;
959 ::std::cout << " size_t queue_size = " << memory->config.queue_size
960 << ::std::endl;
961 ::std::cout << " size_t message_data_size = "
962 << memory->config.message_data_size << ::std::endl;
963
964 ::std::cout << " AtomicQueueIndex next_queue_index = "
965 << memory->next_queue_index.Load(queue_size).DebugString()
966 << ::std::endl;
967
Austin Schuh3328d132020-02-28 13:54:57 -0800968 ::std::cout << " uid_t uid = " << memory->uid << ::std::endl;
969
Austin Schuh20b2b082019-09-11 20:42:56 -0700970 ::std::cout << " }" << ::std::endl;
971 ::std::cout << " AtomicIndex queue[" << queue_size << "] {" << ::std::endl;
972 for (size_t i = 0; i < queue_size; ++i) {
973 ::std::cout << " [" << i << "] -> "
974 << memory->GetQueue(i)->Load().DebugString() << ::std::endl;
975 }
976 ::std::cout << " }" << ::std::endl;
977 ::std::cout << " Message messages[" << memory->num_messages() << "] {"
978 << ::std::endl;
979 for (size_t i = 0; i < memory->num_messages(); ++i) {
980 Message *m = memory->GetMessage(Index(i, i));
981 ::std::cout << " [" << i << "] -> Message {" << ::std::endl;
982 ::std::cout << " Header {" << ::std::endl;
983 ::std::cout << " AtomicQueueIndex queue_index = "
984 << m->header.queue_index.Load(queue_size).DebugString()
985 << ::std::endl;
986 ::std::cout << " size_t length = " << m->header.length
987 << ::std::endl;
988 ::std::cout << " }" << ::std::endl;
989 ::std::cout << " data: {";
990
Brian Silvermana1652f32020-01-29 20:41:44 -0800991 const char *const m_data = m->data(memory->message_data_size());
Austin Schuh20b2b082019-09-11 20:42:56 -0700992 for (size_t j = 0; j < m->header.length; ++j) {
Brian Silvermana1652f32020-01-29 20:41:44 -0800993 char data = m_data[j];
Austin Schuh20b2b082019-09-11 20:42:56 -0700994 if (j != 0) {
995 ::std::cout << " ";
996 }
997 if (::std::isprint(data)) {
998 ::std::cout << ::std::setfill(' ') << ::std::setw(2) << ::std::hex
999 << data;
1000 } else {
1001 ::std::cout << "0x" << ::std::setfill('0') << ::std::setw(2)
1002 << ::std::hex << (static_cast<unsigned>(data) & 0xff);
1003 }
1004 }
1005 ::std::cout << ::std::setfill(' ') << ::std::dec << "}" << ::std::endl;
1006 ::std::cout << " }," << ::std::endl;
1007 }
1008 ::std::cout << " }" << ::std::endl;
1009
Alex Perrycb7da4b2019-08-28 19:35:56 -07001010 ::std::cout << " Sender senders[" << memory->num_senders() << "] {"
1011 << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001012 for (size_t i = 0; i < memory->num_senders(); ++i) {
1013 Sender *s = memory->GetSender(i);
1014 ::std::cout << " [" << i << "] -> Sender {" << ::std::endl;
1015 ::std::cout << " aos_mutex tid = " << PrintMutex(&s->tid)
1016 << ::std::endl;
1017 ::std::cout << " AtomicIndex scratch_index = "
1018 << s->scratch_index.Load().DebugString() << ::std::endl;
1019 ::std::cout << " AtomicIndex to_replace = "
1020 << s->to_replace.Load().DebugString() << ::std::endl;
1021 ::std::cout << " }" << ::std::endl;
1022 }
1023 ::std::cout << " }" << ::std::endl;
1024
1025 ::std::cout << " Watcher watchers[" << memory->num_watchers() << "] {"
1026 << ::std::endl;
1027 for (size_t i = 0; i < memory->num_watchers(); ++i) {
1028 Watcher *w = memory->GetWatcher(i);
1029 ::std::cout << " [" << i << "] -> Watcher {" << ::std::endl;
1030 ::std::cout << " aos_mutex tid = " << PrintMutex(&w->tid)
1031 << ::std::endl;
1032 ::std::cout << " pid_t pid = " << w->pid << ::std::endl;
1033 ::std::cout << " int priority = " << w->priority << ::std::endl;
1034 ::std::cout << " }" << ::std::endl;
1035 }
1036 ::std::cout << " }" << ::std::endl;
1037
1038 ::std::cout << "}" << ::std::endl;
1039}
1040
1041} // namespace ipc_lib
1042} // namespace aos