blob: 45d9e163438973f806ed7148eee5d6de29bf7b9f [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"
Brian Silverman001f24d2020-08-12 19:33:20 -070015#include "gflags/gflags.h"
Austin Schuhf257f3c2019-10-27 21:00:43 -070016#include "glog/logging.h"
Austin Schuh20b2b082019-09-11 20:42:56 -070017
Brian Silverman001f24d2020-08-12 19:33:20 -070018DEFINE_bool(dump_lockless_queue_data, false,
19 "If true, print the data out when dumping the queue.");
20
Austin Schuh20b2b082019-09-11 20:42:56 -070021namespace aos {
22namespace ipc_lib {
Austin Schuh20b2b082019-09-11 20:42:56 -070023namespace {
24
Brian Silvermanfafe1fa2019-12-18 21:42:18 -080025class GrabQueueSetupLockOrDie {
26 public:
27 GrabQueueSetupLockOrDie(LocklessQueueMemory *memory) : memory_(memory) {
28 const int result = mutex_grab(&(memory->queue_setup_lock));
29 CHECK(result == 0 || result == 1) << ": " << result;
30 }
Austin Schuh20b2b082019-09-11 20:42:56 -070031
Brian Silvermanfafe1fa2019-12-18 21:42:18 -080032 ~GrabQueueSetupLockOrDie() { mutex_unlock(&(memory_->queue_setup_lock)); }
33
34 GrabQueueSetupLockOrDie(const GrabQueueSetupLockOrDie &) = delete;
35 GrabQueueSetupLockOrDie &operator=(const GrabQueueSetupLockOrDie &) = delete;
36
37 private:
38 LocklessQueueMemory *const memory_;
39};
40
Brian Silverman177567e2020-08-12 19:51:33 -070041bool IsPinned(LocklessQueueMemory *memory, Index index) {
42 DCHECK(index.valid());
43 const size_t queue_size = memory->queue_size();
44 const QueueIndex message_index =
45 memory->GetMessage(index)->header.queue_index.Load(queue_size);
46 if (!message_index.valid()) {
47 return false;
48 }
49 DCHECK(memory->GetQueue(message_index.Wrapped())->Load() != index)
50 << ": Message is in the queue";
51 for (int pinner_index = 0;
52 pinner_index < static_cast<int>(memory->config.num_pinners);
53 ++pinner_index) {
54 ipc_lib::Pinner *const pinner = memory->GetPinner(pinner_index);
55
56 if (pinner->pinned.RelaxedLoad(queue_size) == message_index) {
57 return true;
58 }
59 }
60 return false;
61}
62
63// Ensures sender->scratch_index (which must contain to_replace) is not pinned.
64//
65// Returns the new scratch_index value.
66Index SwapPinnedSenderScratch(LocklessQueueMemory *const memory,
67 ipc_lib::Sender *const sender,
68 const Index to_replace) {
69 // If anybody's trying to pin this message, then grab a message from a pinner
70 // to write into instead, and leave the message we pulled out of the queue
71 // (currently in our scratch_index) with a pinner.
72 //
73 // This loop will terminate in at most one iteration through the pinners in
74 // any steady-state configuration of the memory. There are only as many
75 // Pinner::pinned values to worry about as there are Pinner::scratch_index
76 // values to check against, plus to_replace, which means there will always be
77 // a free one. We might have to make multiple passes if things are being
78 // changed concurrently though, but nobody dying can make this loop fail to
79 // terminate (because the number of processes that can die is bounded, because
80 // no new ones can start while we've got the lock).
81 for (int pinner_index = 0; true;
82 pinner_index = (pinner_index + 1) % memory->config.num_pinners) {
83 if (!IsPinned(memory, to_replace)) {
84 // No pinners on our current scratch_index, so we're fine now.
85 VLOG(3) << "No pinners: " << to_replace.DebugString();
86 return to_replace;
87 }
88
89 ipc_lib::Pinner *const pinner = memory->GetPinner(pinner_index);
90
91 const Index pinner_scratch = pinner->scratch_index.RelaxedLoad();
92 CHECK(pinner_scratch.valid())
93 << ": Pinner scratch_index should always be valid";
94 if (IsPinned(memory, pinner_scratch)) {
95 // Wouldn't do us any good to swap with this one, so don't bother, and
96 // move onto the next one.
97 VLOG(3) << "Also pinned: " << pinner_scratch.DebugString();
98 continue;
99 }
100
101 sender->to_replace.RelaxedStore(pinner_scratch);
102 aos_compiler_memory_barrier();
103 // Give the pinner the message (which is currently in
104 // sender->scratch_index).
105 if (!pinner->scratch_index.CompareAndExchangeStrong(pinner_scratch,
106 to_replace)) {
107 // Somebody swapped into this pinner before us. The new value is probably
108 // pinned, so we don't want to look at it again immediately.
109 VLOG(3) << "Pinner " << pinner_index
110 << " scratch_index changed: " << pinner_scratch.DebugString()
111 << ", " << to_replace.DebugString();
112 sender->to_replace.RelaxedInvalidate();
113 continue;
114 }
115 aos_compiler_memory_barrier();
116 // Now update the sender's scratch space and record that we succeeded.
117 sender->scratch_index.Store(pinner_scratch);
118 aos_compiler_memory_barrier();
119 // And then record that we succeeded, but definitely after the above
120 // store.
121 sender->to_replace.RelaxedInvalidate();
122 VLOG(3) << "Got new scratch message: " << pinner_scratch.DebugString();
123
124 // If it's in a pinner's scratch_index, it should not be in the queue, which
125 // means nobody new can pin it for real. However, they can still attempt to
126 // pin it, which means we can't verify !IsPinned down here.
127
128 return pinner_scratch;
129 }
130}
131
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700132// Returns true if it succeeded. Returns false if another sender died in the
133// middle.
134bool DoCleanup(LocklessQueueMemory *memory, const GrabQueueSetupLockOrDie &) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800135 // Make sure we start looking at shared memory fresh right now. We'll handle
136 // people dying partway through by either cleaning up after them or not, but
137 // we want to ensure we clean up after anybody who has already died when we
138 // start.
139 aos_compiler_memory_barrier();
140
Austin Schuh20b2b082019-09-11 20:42:56 -0700141 const size_t num_senders = memory->num_senders();
Brian Silverman177567e2020-08-12 19:51:33 -0700142 const size_t num_pinners = memory->num_pinners();
Austin Schuh20b2b082019-09-11 20:42:56 -0700143 const size_t queue_size = memory->queue_size();
144 const size_t num_messages = memory->num_messages();
145
146 // There are a large number of crazy cases here for how things can go wrong
147 // and how we have to recover. They either require us to keep extra track of
148 // what is going on, slowing down the send path, or require a large number of
149 // cases.
150 //
151 // The solution here is to not over-think it. This is running while not real
152 // time during construction. It is allowed to be slow. It will also very
153 // rarely trigger. There is a small uS window where process death is
154 // ambiguous.
155 //
156 // So, build up a list N long, where N is the number of messages. Search
157 // through the entire queue and the sender list (ignoring any dead senders),
158 // and mark down which ones we have seen. Once we have seen all the messages
159 // except the N dead senders, we know which messages are dead. Because the
160 // queue is active while we do this, it may take a couple of go arounds to see
161 // everything.
162
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700163 ::std::vector<bool> need_recovery(num_senders, false);
164
Austin Schuh20b2b082019-09-11 20:42:56 -0700165 // Do the easy case. Find all senders who have died. See if they are either
166 // consistent already, or if they have copied over to_replace to the scratch
167 // index, but haven't cleared to_replace. Count them.
168 size_t valid_senders = 0;
169 for (size_t i = 0; i < num_senders; ++i) {
170 Sender *sender = memory->GetSender(i);
171 const uint32_t tid =
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800172 __atomic_load_n(&(sender->tid.futex), __ATOMIC_ACQUIRE);
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700173 if (!(tid & FUTEX_OWNER_DIED)) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700174 // Not dead.
175 ++valid_senders;
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700176 continue;
Austin Schuh20b2b082019-09-11 20:42:56 -0700177 }
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700178 VLOG(3) << "Found an easy death for sender " << i;
179 // We can do a relaxed load here because we're the only person touching
180 // this sender at this point.
181 const Index to_replace = sender->to_replace.RelaxedLoad();
182 const Index scratch_index = sender->scratch_index.Load();
183
184 // I find it easiest to think about this in terms of the set of observable
185 // states. The main code progresses through the following states:
186
187 // 1) scratch_index = xxx
188 // to_replace = invalid
189 // This is unambiguous. Already good.
190
191 // 2) scratch_index = xxx
192 // to_replace = yyy
193 // Very ambiguous. Is xxx or yyy the correct one? Need to either roll
194 // this forwards or backwards.
195
196 // 3) scratch_index = yyy
197 // to_replace = yyy
198 // We are in the act of moving to_replace to scratch_index, but didn't
199 // finish. Easy.
Brian Silverman177567e2020-08-12 19:51:33 -0700200 //
201 // If doing a pinner swap, we've definitely done it.
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700202
203 // 4) scratch_index = yyy
204 // to_replace = invalid
205 // Finished, but died. Looks like 1)
206
Brian Silverman177567e2020-08-12 19:51:33 -0700207 // Swapping with a pinner's scratch_index passes through the same states.
208 // We just need to ensure the message that ends up in the senders's
209 // scratch_index isn't pinned, using the same code as sending does.
210
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700211 // Any cleanup code needs to follow the same set of states to be robust to
212 // death, so death can be restarted.
213
214 if (!to_replace.valid()) {
215 // 1) or 4). Make sure we aren't corrupted and declare victory.
216 CHECK(scratch_index.valid());
217
Brian Silverman177567e2020-08-12 19:51:33 -0700218 // If it's in 1) with a pinner, the sender might have a pinned message,
219 // so fix that.
220 SwapPinnedSenderScratch(memory, sender, scratch_index);
221
222 // If it's in 4), it may not have completed this step yet. This will
223 // always be a NOP if it's in 1), verified by a DCHECK.
224 memory->GetMessage(scratch_index)->header.queue_index.RelaxedInvalidate();
225
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700226 __atomic_store_n(&(sender->tid.futex), 0, __ATOMIC_RELEASE);
227 ++valid_senders;
228 continue;
229 }
230
231 // Could be 2) or 3) at this point.
232
233 if (to_replace == scratch_index) {
234 // 3) for sure.
235 // Just need to invalidate to_replace to finish.
236 sender->to_replace.Invalidate();
237
Brian Silverman177567e2020-08-12 19:51:33 -0700238 // Make sure to indicate it's an unused message before a sender gets its
239 // hands on it.
240 memory->GetMessage(scratch_index)->header.queue_index.RelaxedInvalidate();
241 aos_compiler_memory_barrier();
242
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700243 // And mark that we succeeded.
244 __atomic_store_n(&(sender->tid.futex), 0, __ATOMIC_RELEASE);
245 ++valid_senders;
246 continue;
247 }
248
249 // Must be 2). Mark it for later.
250 need_recovery[i] = true;
Austin Schuh20b2b082019-09-11 20:42:56 -0700251 }
252
Brian Silverman177567e2020-08-12 19:51:33 -0700253 // Cleaning up pinners is easy. We don't actually have to do anything, but
254 // invalidating its pinned field might help catch bugs elsewhere trying to
255 // read it before it's set.
256 for (size_t i = 0; i < num_pinners; ++i) {
257 Pinner *const pinner = memory->GetPinner(i);
258 const uint32_t tid =
259 __atomic_load_n(&(pinner->tid.futex), __ATOMIC_ACQUIRE);
260 if (!(tid & FUTEX_OWNER_DIED)) {
261 continue;
262 }
263 pinner->pinned.Invalidate();
264 __atomic_store_n(&(pinner->tid.futex), 0, __ATOMIC_RELEASE);
265 }
266
Austin Schuh20b2b082019-09-11 20:42:56 -0700267 // If all the senders are (or were made) good, there is no need to do the hard
268 // case.
269 if (valid_senders == num_senders) {
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700270 return true;
Austin Schuh20b2b082019-09-11 20:42:56 -0700271 }
272
Alex Perrycb7da4b2019-08-28 19:35:56 -0700273 VLOG(3) << "Starting hard cleanup";
Austin Schuh20b2b082019-09-11 20:42:56 -0700274
275 size_t num_accounted_for = 0;
276 size_t num_missing = 0;
277 ::std::vector<bool> accounted_for(num_messages, false);
278
279 while ((num_accounted_for + num_missing) != num_messages) {
280 num_missing = 0;
281 for (size_t i = 0; i < num_senders; ++i) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800282 Sender *const sender = memory->GetSender(i);
Austin Schuh20b2b082019-09-11 20:42:56 -0700283 const uint32_t tid =
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800284 __atomic_load_n(&(sender->tid.futex), __ATOMIC_ACQUIRE);
Austin Schuh20b2b082019-09-11 20:42:56 -0700285 if (tid & FUTEX_OWNER_DIED) {
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700286 if (!need_recovery[i]) {
287 return false;
288 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700289 ++num_missing;
Brian Silverman177567e2020-08-12 19:51:33 -0700290 continue;
Austin Schuh20b2b082019-09-11 20:42:56 -0700291 }
Brian Silverman177567e2020-08-12 19:51:33 -0700292 CHECK(!need_recovery[i]) << ": Somebody else recovered a sender: " << i;
293 // We can do a relaxed load here because we're the only person touching
294 // this sender at this point, if it matters. If it's not a dead sender,
295 // then any message it ever has will eventually be accounted for if we
296 // make enough tries through the outer loop.
297 const Index scratch_index = sender->scratch_index.RelaxedLoad();
298 if (!accounted_for[scratch_index.message_index()]) {
299 ++num_accounted_for;
300 }
301 accounted_for[scratch_index.message_index()] = true;
Austin Schuh20b2b082019-09-11 20:42:56 -0700302 }
303
304 for (size_t i = 0; i < queue_size; ++i) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800305 // Same logic as above for scratch_index applies here too.
Austin Schuh20b2b082019-09-11 20:42:56 -0700306 const Index index = memory->GetQueue(i)->RelaxedLoad();
307 if (!accounted_for[index.message_index()]) {
308 ++num_accounted_for;
309 }
310 accounted_for[index.message_index()] = true;
311 }
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700312
Brian Silverman177567e2020-08-12 19:51:33 -0700313 for (size_t pinner_index = 0; pinner_index < num_pinners; ++pinner_index) {
314 // Same logic as above for scratch_index applies here too.
315 const Index index =
316 memory->GetPinner(pinner_index)->scratch_index.RelaxedLoad();
317 if (!accounted_for[index.message_index()]) {
318 ++num_accounted_for;
319 }
320 accounted_for[index.message_index()] = true;
321 }
322
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700323 CHECK_LE(num_accounted_for + num_missing, num_messages);
Austin Schuh20b2b082019-09-11 20:42:56 -0700324 }
325
326 while (num_missing != 0) {
327 const size_t starting_num_missing = num_missing;
328 for (size_t i = 0; i < num_senders; ++i) {
329 Sender *sender = memory->GetSender(i);
330 const uint32_t tid =
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800331 __atomic_load_n(&(sender->tid.futex), __ATOMIC_ACQUIRE);
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700332 if (!(tid & FUTEX_OWNER_DIED)) {
333 CHECK(!need_recovery[i]) << ": Somebody else recovered a sender: " << i;
334 continue;
335 }
336 if (!need_recovery[i]) {
337 return false;
338 }
339 // We can do relaxed loads here because we're the only person touching
340 // this sender at this point.
341 const Index scratch_index = sender->scratch_index.RelaxedLoad();
342 const Index to_replace = sender->to_replace.RelaxedLoad();
Austin Schuh20b2b082019-09-11 20:42:56 -0700343
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700344 // Candidate.
345 if (to_replace.valid()) {
346 CHECK_LE(to_replace.message_index(), accounted_for.size());
347 }
348 if (scratch_index.valid()) {
349 CHECK_LE(scratch_index.message_index(), accounted_for.size());
350 }
351 if (!to_replace.valid() || accounted_for[to_replace.message_index()]) {
352 CHECK(scratch_index.valid());
353 VLOG(3) << "Sender " << i
354 << " died, to_replace is already accounted for";
355 // If both are accounted for, we are corrupt...
356 CHECK(!accounted_for[scratch_index.message_index()]);
Austin Schuh20b2b082019-09-11 20:42:56 -0700357
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700358 // to_replace is already accounted for. This means that we didn't
359 // atomically insert scratch_index into the queue yet. So
360 // invalidate to_replace.
361 sender->to_replace.Invalidate();
Brian Silverman177567e2020-08-12 19:51:33 -0700362 // Sender definitely will not have gotten here, so finish for it.
363 memory->GetMessage(scratch_index)
364 ->header.queue_index.RelaxedInvalidate();
Austin Schuh20b2b082019-09-11 20:42:56 -0700365
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700366 // And then mark this sender clean.
367 __atomic_store_n(&(sender->tid.futex), 0, __ATOMIC_RELEASE);
368 need_recovery[i] = false;
Austin Schuh20b2b082019-09-11 20:42:56 -0700369
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700370 // And account for scratch_index.
371 accounted_for[scratch_index.message_index()] = true;
372 --num_missing;
373 ++num_accounted_for;
374 } else if (!scratch_index.valid() ||
375 accounted_for[scratch_index.message_index()]) {
376 VLOG(3) << "Sender " << i
377 << " died, scratch_index is already accounted for";
378 // scratch_index is accounted for. That means we did the insert,
379 // but didn't record it.
380 CHECK(to_replace.valid());
Brian Silverman177567e2020-08-12 19:51:33 -0700381
382 // Make sure to indicate it's an unused message before a sender gets its
383 // hands on it.
384 memory->GetMessage(to_replace)->header.queue_index.RelaxedInvalidate();
385 aos_compiler_memory_barrier();
386
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700387 // Finish the transaction. Copy to_replace, then clear it.
Austin Schuh20b2b082019-09-11 20:42:56 -0700388
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700389 sender->scratch_index.Store(to_replace);
390 sender->to_replace.Invalidate();
Austin Schuh20b2b082019-09-11 20:42:56 -0700391
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700392 // And then mark this sender clean.
393 __atomic_store_n(&(sender->tid.futex), 0, __ATOMIC_RELEASE);
394 need_recovery[i] = false;
Austin Schuh20b2b082019-09-11 20:42:56 -0700395
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700396 // And account for to_replace.
397 accounted_for[to_replace.message_index()] = true;
398 --num_missing;
399 ++num_accounted_for;
400 } else {
401 VLOG(3) << "Sender " << i << " died, neither is accounted for";
402 // Ambiguous. There will be an unambiguous one somewhere that we
403 // can do first.
Austin Schuh20b2b082019-09-11 20:42:56 -0700404 }
405 }
406 // CHECK that we are making progress.
407 CHECK_NE(num_missing, starting_num_missing);
408 }
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700409 return true;
410}
411
412void Cleanup(LocklessQueueMemory *memory, const GrabQueueSetupLockOrDie &lock) {
413 // The number of iterations is bounded here because there are only a finite
414 // number of senders in existence which could die, and no new ones can be
415 // created while we're in here holding the lock.
416 while (!DoCleanup(memory, lock)) {
417 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700418}
419
420// Exposes rt_tgsigqueueinfo so we can send the signal *just* to the target
421// thread.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800422// TODO(Brian): Do directly in assembly for armhf at least for efficiency.
Austin Schuh20b2b082019-09-11 20:42:56 -0700423int rt_tgsigqueueinfo(pid_t tgid, pid_t tid, int sig, siginfo_t *si) {
424 return syscall(SYS_rt_tgsigqueueinfo, tgid, tid, sig, si);
425}
426
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700427QueueIndex ZeroOrValid(QueueIndex index) {
428 if (!index.valid()) {
429 return index.Clear();
430 }
431 return index;
432}
433
Austin Schuh20b2b082019-09-11 20:42:56 -0700434} // namespace
435
Austin Schuh4bc4f902019-12-23 18:04:51 -0800436size_t LocklessQueueConfiguration::message_size() const {
437 // Round up the message size so following data is aligned appropriately.
Brian Silverman0eaa1da2020-08-12 20:03:52 -0700438 // Make sure to leave space to align the message data. It will be aligned
439 // relative to the start of the shared memory region, but that might not be
440 // aligned for some use cases.
Brian Silvermana1652f32020-01-29 20:41:44 -0800441 return LocklessQueueMemory::AlignmentRoundUp(message_data_size +
Brian Silverman0eaa1da2020-08-12 20:03:52 -0700442 kChannelDataRedzone * 2 +
Brian Silvermana1652f32020-01-29 20:41:44 -0800443 (kChannelDataAlignment - 1)) +
Austin Schuh4bc4f902019-12-23 18:04:51 -0800444 sizeof(Message);
445}
446
Austin Schuh20b2b082019-09-11 20:42:56 -0700447size_t LocklessQueueMemorySize(LocklessQueueConfiguration config) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800448 // Round up the message size so following data is aligned appropriately.
449 config.message_data_size =
450 LocklessQueueMemory::AlignmentRoundUp(config.message_data_size);
Austin Schuh20b2b082019-09-11 20:42:56 -0700451
452 // As we build up the size, confirm that everything is aligned to the
453 // alignment requirements of the type.
454 size_t size = sizeof(LocklessQueueMemory);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800455 CHECK_EQ(size % alignof(LocklessQueueMemory), 0u);
Austin Schuh20b2b082019-09-11 20:42:56 -0700456
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800457 CHECK_EQ(size % alignof(AtomicIndex), 0u);
Austin Schuh20b2b082019-09-11 20:42:56 -0700458 size += LocklessQueueMemory::SizeOfQueue(config);
459
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800460 CHECK_EQ(size % alignof(Message), 0u);
Austin Schuh20b2b082019-09-11 20:42:56 -0700461 size += LocklessQueueMemory::SizeOfMessages(config);
462
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800463 CHECK_EQ(size % alignof(Watcher), 0u);
Austin Schuh20b2b082019-09-11 20:42:56 -0700464 size += LocklessQueueMemory::SizeOfWatchers(config);
465
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800466 CHECK_EQ(size % alignof(Sender), 0u);
Austin Schuh20b2b082019-09-11 20:42:56 -0700467 size += LocklessQueueMemory::SizeOfSenders(config);
468
Brian Silverman177567e2020-08-12 19:51:33 -0700469 CHECK_EQ(size % alignof(Pinner), 0u);
470 size += LocklessQueueMemory::SizeOfPinners(config);
471
Austin Schuh20b2b082019-09-11 20:42:56 -0700472 return size;
473}
474
Brian Silverman0eaa1da2020-08-12 20:03:52 -0700475// Calculates the starting byte for a redzone in shared memory. This starting
476// value is simply incremented for subsequent bytes.
477//
478// The result is based on the offset of the region in shared memor, to ensure it
479// is the same for each region when we generate and verify, but different for
480// each region to help catch forms of corruption like copying out-of-bounds data
481// from one place to another.
482//
483// memory is the base pointer to the shared memory. It is used to calculated
484// offsets. starting_data is the start of the redzone's data. Each one will
485// get a unique pattern.
486uint8_t RedzoneStart(const LocklessQueueMemory *memory,
487 const char *starting_data) {
488 const auto memory_int = reinterpret_cast<uintptr_t>(memory);
489 const auto starting_int = reinterpret_cast<uintptr_t>(starting_data);
490 DCHECK(starting_int >= memory_int);
491 DCHECK(starting_int < memory_int + LocklessQueueMemorySize(memory->config));
492 const uintptr_t starting_offset = starting_int - memory_int;
493 // Just XOR the lower 2 bytes. They higher-order bytes are probably 0
494 // anyways.
495 return (starting_offset & 0xFF) ^ ((starting_offset >> 8) & 0xFF);
496}
497
498// Returns true if the given redzone has invalid data.
499bool CheckRedzone(const LocklessQueueMemory *memory,
500 absl::Span<const char> redzone) {
501 uint8_t redzone_value = RedzoneStart(memory, redzone.data());
502
503 bool bad = false;
504
505 for (size_t i = 0; i < redzone.size(); ++i) {
506 if (memcmp(&redzone[i], &redzone_value, 1)) {
507 bad = true;
508 }
509 ++redzone_value;
510 }
511
512 return bad;
513}
514
515// Returns true if either of message's redzones has invalid data.
516bool CheckBothRedzones(const LocklessQueueMemory *memory,
517 const Message *message) {
518 return CheckRedzone(memory,
519 message->PreRedzone(memory->message_data_size())) ||
520 CheckRedzone(memory, message->PostRedzone(memory->message_data_size(),
521 memory->message_size()));
522}
523
524// Fills the given redzone with the expected data.
525void FillRedzone(LocklessQueueMemory *memory, absl::Span<char> redzone) {
526 uint8_t redzone_value = RedzoneStart(memory, redzone.data());
527 for (size_t i = 0; i < redzone.size(); ++i) {
528 memcpy(&redzone[i], &redzone_value, 1);
529 ++redzone_value;
530 }
531
532 // Just double check that the implementations match.
533 CHECK(!CheckRedzone(memory, redzone));
534}
535
Austin Schuh20b2b082019-09-11 20:42:56 -0700536LocklessQueueMemory *InitializeLocklessQueueMemory(
537 LocklessQueueMemory *memory, LocklessQueueConfiguration config) {
538 // Everything should be zero initialized already. So we just need to fill
539 // everything out properly.
540
Brian Silvermanc57ff0a2020-04-28 16:45:13 -0700541 // This is the UID we will use for checking signal-sending permission
542 // compatibility.
543 //
544 // The manpage says:
545 // For a process to have permission to send a signal, it must either be
546 // privileged [...], or the real or effective user ID of the sending process
547 // must equal the real or saved set-user-ID of the target process.
548 //
549 // Processes typically initialize a queue in random order as they start up.
550 // This means we need an algorithm for verifying all processes have
551 // permissions to send each other signals which gives the same answer no
552 // matter what order they attach in. We would also like to avoid maintaining a
553 // shared list of the UIDs of all processes.
554 //
555 // To do this while still giving sufficient flexibility for all current use
556 // cases, we track a single UID for the queue. All processes with a matching
557 // euid+suid must have this UID. Any processes with distinct euid/suid must
558 // instead have a matching ruid. This guarantees signals can be sent between
559 // all processes attached to the queue.
560 //
561 // In particular, this allows a process to change only its euid (to interact
562 // with a queue) while still maintaining privileges via its ruid. However, it
563 // can only use privileges in ways that do not require changing the euid back,
564 // because while the euid is different it will not be able to receive signals.
565 // We can't actually verify that, but we can sanity check that things are
566 // valid when the queue is initialized.
567
568 uid_t uid;
569 {
570 uid_t ruid, euid, suid;
571 PCHECK(getresuid(&ruid, &euid, &suid) == 0);
572 // If these are equal, then use them, even if that's different from the real
573 // UID. This allows processes to keep a real UID of 0 (to have permissions
574 // to perform system-level changes) while still being able to communicate
575 // with processes running unprivileged as a distinct user.
576 if (euid == suid) {
577 uid = euid;
578 VLOG(1) << "Using euid==suid " << uid;
579 } else {
580 uid = ruid;
581 VLOG(1) << "Using ruid " << ruid;
582 }
583 }
584
Austin Schuh20b2b082019-09-11 20:42:56 -0700585 // Grab the mutex. We don't care if the previous reader died. We are going
586 // to check everything anyways.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800587 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory);
Austin Schuh20b2b082019-09-11 20:42:56 -0700588
589 if (!memory->initialized) {
590 // TODO(austin): Check these for out of bounds.
591 memory->config.num_watchers = config.num_watchers;
592 memory->config.num_senders = config.num_senders;
Brian Silverman177567e2020-08-12 19:51:33 -0700593 memory->config.num_pinners = config.num_pinners;
Austin Schuh20b2b082019-09-11 20:42:56 -0700594 memory->config.queue_size = config.queue_size;
Austin Schuh4bc4f902019-12-23 18:04:51 -0800595 memory->config.message_data_size = config.message_data_size;
Austin Schuh20b2b082019-09-11 20:42:56 -0700596
597 const size_t num_messages = memory->num_messages();
598 // There need to be at most MaxMessages() messages allocated.
599 CHECK_LE(num_messages, Index::MaxMessages());
600
601 for (size_t i = 0; i < num_messages; ++i) {
Brian Silverman0eaa1da2020-08-12 20:03:52 -0700602 Message *const message =
603 memory->GetMessage(Index(QueueIndex::Zero(memory->queue_size()), i));
604 message->header.queue_index.Invalidate();
605 FillRedzone(memory, message->PreRedzone(memory->message_data_size()));
606 FillRedzone(memory, message->PostRedzone(memory->message_data_size(),
607 memory->message_size()));
Austin Schuh20b2b082019-09-11 20:42:56 -0700608 }
609
610 for (size_t i = 0; i < memory->queue_size(); ++i) {
611 // Make the initial counter be the furthest away number. That means that
612 // index 0 should be 0xffff, 1 should be 0, etc.
613 memory->GetQueue(i)->Store(Index(QueueIndex::Zero(memory->queue_size())
614 .IncrementBy(i)
615 .DecrementBy(memory->queue_size()),
616 i));
617 }
618
619 memory->next_queue_index.Invalidate();
Brian Silvermanc57ff0a2020-04-28 16:45:13 -0700620 memory->uid = uid;
Austin Schuh20b2b082019-09-11 20:42:56 -0700621
622 for (size_t i = 0; i < memory->num_senders(); ++i) {
623 ::aos::ipc_lib::Sender *s = memory->GetSender(i);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800624 // Nobody else can possibly be touching these because we haven't set
625 // initialized to true yet.
626 s->scratch_index.RelaxedStore(Index(0xffff, i + memory->queue_size()));
Austin Schuh20b2b082019-09-11 20:42:56 -0700627 s->to_replace.RelaxedInvalidate();
628 }
629
Brian Silverman177567e2020-08-12 19:51:33 -0700630 for (size_t i = 0; i < memory->num_pinners(); ++i) {
631 ::aos::ipc_lib::Pinner *pinner = memory->GetPinner(i);
632 // Nobody else can possibly be touching these because we haven't set
633 // initialized to true yet.
634 pinner->scratch_index.RelaxedStore(
635 Index(0xffff, i + memory->num_senders() + memory->queue_size()));
636 pinner->pinned.Invalidate();
637 }
638
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800639 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -0700640 // Signal everything is done. This needs to be done last, so if we die, we
641 // redo initialization.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800642 memory->initialized = true;
Austin Schuh3328d132020-02-28 13:54:57 -0800643 } else {
Brian Silvermanc57ff0a2020-04-28 16:45:13 -0700644 CHECK_EQ(uid, memory->uid) << ": UIDs must match for all processes";
Austin Schuh20b2b082019-09-11 20:42:56 -0700645 }
646
Austin Schuh20b2b082019-09-11 20:42:56 -0700647 return memory;
648}
649
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700650void LocklessQueue::Initialize() {
651 InitializeLocklessQueueMemory(memory_, config_);
652}
Austin Schuh20b2b082019-09-11 20:42:56 -0700653
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700654LocklessQueueWatcher::~LocklessQueueWatcher() {
655 if (watcher_index_ == -1) {
656 return;
657 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700658
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700659 // Since everything is self consistent, all we need to do is make sure nobody
660 // else is running. Someone dying will get caught in the generic consistency
661 // check.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800662 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory_);
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700663
664 // Make sure we are registered.
665 CHECK_NE(watcher_index_, -1);
666
667 // Make sure we still own the slot we are supposed to.
668 CHECK(
669 death_notification_is_held(&(memory_->GetWatcher(watcher_index_)->tid)));
670
671 // The act of unlocking invalidates the entry. Invalidate it.
672 death_notification_release(&(memory_->GetWatcher(watcher_index_)->tid));
673 // And internally forget the slot.
674 watcher_index_ = -1;
675
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800676 // Cleanup is cheap. The next user will do it anyways, so no need for us to do
677 // anything right now.
Austin Schuh20b2b082019-09-11 20:42:56 -0700678
679 // And confirm that nothing is owned by us.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700680 const int num_watchers = memory_->num_watchers();
Austin Schuh20b2b082019-09-11 20:42:56 -0700681 for (int i = 0; i < num_watchers; ++i) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700682 CHECK(!death_notification_is_held(&(memory_->GetWatcher(i)->tid)))
683 << ": " << i;
Austin Schuh20b2b082019-09-11 20:42:56 -0700684 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700685}
686
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700687std::optional<LocklessQueueWatcher> LocklessQueueWatcher::Make(
688 LocklessQueue queue, int priority) {
689 queue.Initialize();
690 LocklessQueueWatcher result(queue.memory(), priority);
691 if (result.watcher_index_ != -1) {
692 return std::move(result);
693 } else {
694 return std::nullopt;
695 }
696}
Austin Schuh20b2b082019-09-11 20:42:56 -0700697
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700698LocklessQueueWatcher::LocklessQueueWatcher(LocklessQueueMemory *memory,
699 int priority)
700 : memory_(memory) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700701 // TODO(austin): Make sure signal coalescing is turned on. We don't need
702 // duplicates. That will improve performance under high load.
703
704 // Since everything is self consistent, all we need to do is make sure nobody
705 // else is running. Someone dying will get caught in the generic consistency
706 // check.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800707 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory_);
Austin Schuh20b2b082019-09-11 20:42:56 -0700708 const int num_watchers = memory_->num_watchers();
709
710 // Now, find the first empty watcher and grab it.
711 CHECK_EQ(watcher_index_, -1);
712 for (int i = 0; i < num_watchers; ++i) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800713 // If we see a slot the kernel has marked as dead, everything we do reusing
714 // it needs to happen-after whatever that process did before dying.
Brian Silverman2484eea2019-12-21 16:48:46 -0800715 auto *const futex = &(memory_->GetWatcher(i)->tid.futex);
716 const uint32_t tid = __atomic_load_n(futex, __ATOMIC_ACQUIRE);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800717 if (tid == 0 || (tid & FUTEX_OWNER_DIED)) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700718 watcher_index_ = i;
Brian Silverman2484eea2019-12-21 16:48:46 -0800719 // Relaxed is OK here because we're the only task going to touch it
720 // between here and the write in death_notification_init below (other
721 // recovery is blocked by us holding the setup lock).
722 __atomic_store_n(futex, 0, __ATOMIC_RELAXED);
Austin Schuh20b2b082019-09-11 20:42:56 -0700723 break;
724 }
725 }
726
727 // Bail if we failed to find an open slot.
728 if (watcher_index_ == -1) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700729 return;
Austin Schuh20b2b082019-09-11 20:42:56 -0700730 }
731
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700732 Watcher *const w = memory_->GetWatcher(watcher_index_);
Austin Schuh20b2b082019-09-11 20:42:56 -0700733
734 w->pid = getpid();
735 w->priority = priority;
736
737 // Grabbing a mutex is a compiler and memory barrier, so nothing before will
738 // get rearranged afterwords.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800739 death_notification_init(&(w->tid));
Austin Schuh20b2b082019-09-11 20:42:56 -0700740}
741
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700742LocklessQueueWakeUpper::LocklessQueueWakeUpper(LocklessQueue queue)
743 : memory_(queue.const_memory()), pid_(getpid()), uid_(getuid()) {
744 queue.Initialize();
745 watcher_copy_.resize(memory_->num_watchers());
Austin Schuh20b2b082019-09-11 20:42:56 -0700746}
747
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700748int LocklessQueueWakeUpper::Wakeup(const int current_priority) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700749 const size_t num_watchers = memory_->num_watchers();
750
751 CHECK_EQ(watcher_copy_.size(), num_watchers);
752
753 // Grab a copy so it won't change out from underneath us, and we can sort it
754 // nicely in C++.
755 // Do note that there is still a window where the process can die *after* we
756 // read everything. We will still PI boost and send a signal to the thread in
757 // question. There is no way without pidfd's to close this window, and
758 // creating a pidfd is likely not RT.
759 for (size_t i = 0; i < num_watchers; ++i) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700760 const Watcher *w = memory_->GetWatcher(i);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800761 watcher_copy_[i].tid = __atomic_load_n(&(w->tid.futex), __ATOMIC_RELAXED);
762 // Force the load of the TID to come first.
763 aos_compiler_memory_barrier();
764 watcher_copy_[i].pid = w->pid.load(std::memory_order_relaxed);
765 watcher_copy_[i].priority = w->priority.load(std::memory_order_relaxed);
Austin Schuh20b2b082019-09-11 20:42:56 -0700766
767 // Use a priority of -1 to mean an invalid entry to make sorting easier.
768 if (watcher_copy_[i].tid & FUTEX_OWNER_DIED || watcher_copy_[i].tid == 0) {
769 watcher_copy_[i].priority = -1;
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800770 } else {
771 // Ensure all of this happens after we're done looking at the pid+priority
772 // in shared memory.
773 aos_compiler_memory_barrier();
774 if (watcher_copy_[i].tid != static_cast<pid_t>(__atomic_load_n(
775 &(w->tid.futex), __ATOMIC_RELAXED))) {
776 // Confirm that the watcher hasn't been re-used and modified while we
777 // read it. If it has, mark it invalid again.
778 watcher_copy_[i].priority = -1;
779 watcher_copy_[i].tid = 0;
780 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700781 }
782 }
783
784 // Now sort.
785 ::std::sort(watcher_copy_.begin(), watcher_copy_.end(),
786 [](const WatcherCopy &a, const WatcherCopy &b) {
787 return a.priority > b.priority;
788 });
789
790 int count = 0;
791 if (watcher_copy_[0].priority != -1) {
792 const int max_priority =
793 ::std::max(current_priority, watcher_copy_[0].priority);
794 // Boost if we are RT and there is a higher priority sender out there.
795 // Otherwise we might run into priority inversions.
796 if (max_priority > current_priority && current_priority > 0) {
797 SetCurrentThreadRealtimePriority(max_priority);
798 }
799
800 // Build up the siginfo to send.
801 siginfo_t uinfo;
802 memset(&uinfo, 0, sizeof(uinfo));
803
804 uinfo.si_code = SI_QUEUE;
805 uinfo.si_pid = pid_;
806 uinfo.si_uid = uid_;
807 uinfo.si_value.sival_int = 0;
808
809 for (const WatcherCopy &watcher_copy : watcher_copy_) {
810 // The first -1 priority means we are at the end of the valid list.
811 if (watcher_copy.priority == -1) {
812 break;
813 }
814
815 // Send the signal. Target just the thread that sent it so that we can
816 // support multiple watchers in a process (when someone creates multiple
817 // event loops in different threads).
818 rt_tgsigqueueinfo(watcher_copy.pid, watcher_copy.tid, kWakeupSignal,
819 &uinfo);
820
821 ++count;
822 }
823
824 // Drop back down if we were boosted.
825 if (max_priority > current_priority && current_priority > 0) {
826 SetCurrentThreadRealtimePriority(current_priority);
827 }
828 }
829
830 return count;
831}
832
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700833LocklessQueueSender::LocklessQueueSender(LocklessQueueMemory *memory)
834 : memory_(memory) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800835 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory_);
Austin Schuh20b2b082019-09-11 20:42:56 -0700836
837 // Since we already have the lock, go ahead and try cleaning up.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800838 Cleanup(memory_, grab_queue_setup_lock);
Austin Schuh20b2b082019-09-11 20:42:56 -0700839
840 const int num_senders = memory_->num_senders();
841
842 for (int i = 0; i < num_senders; ++i) {
843 ::aos::ipc_lib::Sender *s = memory->GetSender(i);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800844 // This doesn't need synchronization because we're the only process doing
845 // initialization right now, and nobody else will be touching senders which
846 // we're interested in.
Austin Schuh20b2b082019-09-11 20:42:56 -0700847 const uint32_t tid = __atomic_load_n(&(s->tid.futex), __ATOMIC_RELAXED);
848 if (tid == 0) {
849 sender_index_ = i;
850 break;
851 }
852 }
853
854 if (sender_index_ == -1) {
Austin Schuhe516ab02020-05-06 21:37:04 -0700855 VLOG(1) << "Too many senders, starting to bail.";
856 return;
Austin Schuh20b2b082019-09-11 20:42:56 -0700857 }
858
Brian Silverman177567e2020-08-12 19:51:33 -0700859 ::aos::ipc_lib::Sender *const sender = memory_->GetSender(sender_index_);
Austin Schuh20b2b082019-09-11 20:42:56 -0700860
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800861 // Indicate that we are now alive by taking over the slot. If the previous
862 // owner died, we still want to do this.
Brian Silverman177567e2020-08-12 19:51:33 -0700863 death_notification_init(&(sender->tid));
864
865 const Index scratch_index = sender->scratch_index.RelaxedLoad();
866 Message *const message = memory_->GetMessage(scratch_index);
867 CHECK(!message->header.queue_index.RelaxedLoad(memory_->queue_size()).valid())
868 << ": " << std::hex << scratch_index.get();
Austin Schuh20b2b082019-09-11 20:42:56 -0700869}
870
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700871LocklessQueueSender::~LocklessQueueSender() {
872 if (sender_index_ != -1) {
873 CHECK(memory_ != nullptr);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800874 death_notification_release(&(memory_->GetSender(sender_index_)->tid));
Austin Schuh20b2b082019-09-11 20:42:56 -0700875 }
876}
877
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700878std::optional<LocklessQueueSender> LocklessQueueSender::Make(
879 LocklessQueue queue) {
880 queue.Initialize();
881 LocklessQueueSender result(queue.memory());
882 if (result.sender_index_ != -1) {
883 return std::move(result);
884 } else {
885 return std::nullopt;
886 }
887}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700888
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700889size_t LocklessQueueSender::size() const {
890 return memory_->message_data_size();
891}
892
893void *LocklessQueueSender::Data() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700894 ::aos::ipc_lib::Sender *sender = memory_->GetSender(sender_index_);
Brian Silverman177567e2020-08-12 19:51:33 -0700895 const Index scratch_index = sender->scratch_index.RelaxedLoad();
896 Message *const message = memory_->GetMessage(scratch_index);
897 // We should have invalidated this when we first got the buffer. Verify that
898 // in debug mode.
899 DCHECK(
900 !message->header.queue_index.RelaxedLoad(memory_->queue_size()).valid())
901 << ": " << std::hex << scratch_index.get();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700902
Brian Silvermana1652f32020-01-29 20:41:44 -0800903 return message->data(memory_->message_data_size());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700904}
905
Austin Schuh91ba6392020-10-03 13:27:47 -0700906bool LocklessQueueSender::Send(
Austin Schuhad154822019-12-27 15:45:13 -0800907 const char *data, size_t length,
908 aos::monotonic_clock::time_point monotonic_remote_time,
909 aos::realtime_clock::time_point realtime_remote_time,
910 uint32_t remote_queue_index,
911 aos::monotonic_clock::time_point *monotonic_sent_time,
912 aos::realtime_clock::time_point *realtime_sent_time,
913 uint32_t *queue_index) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700914 CHECK_LE(length, size());
Austin Schuh67420a42019-12-21 21:55:04 -0800915 // Flatbuffers write from the back of the buffer to the front. If we are
916 // going to write an explicit chunk of memory into the buffer, we need to
917 // adhere to this convention and place it at the end.
918 memcpy((reinterpret_cast<char *>(Data()) + size() - length), data, length);
Austin Schuh91ba6392020-10-03 13:27:47 -0700919 return Send(length, monotonic_remote_time, realtime_remote_time,
920 remote_queue_index, monotonic_sent_time, realtime_sent_time,
921 queue_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700922}
923
Austin Schuh91ba6392020-10-03 13:27:47 -0700924bool LocklessQueueSender::Send(
Austin Schuhad154822019-12-27 15:45:13 -0800925 size_t length, aos::monotonic_clock::time_point monotonic_remote_time,
926 aos::realtime_clock::time_point realtime_remote_time,
927 uint32_t remote_queue_index,
928 aos::monotonic_clock::time_point *monotonic_sent_time,
929 aos::realtime_clock::time_point *realtime_sent_time,
930 uint32_t *queue_index) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700931 const size_t queue_size = memory_->queue_size();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700932 CHECK_LE(length, size());
Austin Schuh20b2b082019-09-11 20:42:56 -0700933
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800934 ::aos::ipc_lib::Sender *const sender = memory_->GetSender(sender_index_);
935 // We can do a relaxed load on our sender because we're the only person
936 // modifying it right now.
937 const Index scratch_index = sender->scratch_index.RelaxedLoad();
938 Message *const message = memory_->GetMessage(scratch_index);
Austin Schuh91ba6392020-10-03 13:27:47 -0700939 if (CheckBothRedzones(memory_, message)) {
940 return false;
941 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700942
Brian Silverman177567e2020-08-12 19:51:33 -0700943 // We should have invalidated this when we first got the buffer. Verify that
944 // in debug mode.
945 DCHECK(
946 !message->header.queue_index.RelaxedLoad(memory_->queue_size()).valid())
947 << ": " << std::hex << scratch_index.get();
948
Austin Schuh20b2b082019-09-11 20:42:56 -0700949 message->header.length = length;
Austin Schuhad154822019-12-27 15:45:13 -0800950 // Pass these through. Any alternative behavior can be implemented out a
951 // layer.
952 message->header.remote_queue_index = remote_queue_index;
953 message->header.monotonic_remote_time = monotonic_remote_time;
954 message->header.realtime_remote_time = realtime_remote_time;
Austin Schuh20b2b082019-09-11 20:42:56 -0700955
Brian Silverman177567e2020-08-12 19:51:33 -0700956 Index to_replace = Index::Invalid();
Austin Schuh20b2b082019-09-11 20:42:56 -0700957 while (true) {
958 const QueueIndex actual_next_queue_index =
959 memory_->next_queue_index.Load(queue_size);
960 const QueueIndex next_queue_index = ZeroOrValid(actual_next_queue_index);
961
962 const QueueIndex incremented_queue_index = next_queue_index.Increment();
963
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800964 // This needs to synchronize with whoever the previous writer at this
965 // location was.
Brian Silverman177567e2020-08-12 19:51:33 -0700966 to_replace = memory_->LoadIndex(next_queue_index);
Austin Schuh20b2b082019-09-11 20:42:56 -0700967
968 const QueueIndex decremented_queue_index =
969 next_queue_index.DecrementBy(queue_size);
970
971 // See if we got beat. If we did, try to atomically update
972 // next_queue_index in case the previous writer failed and retry.
973 if (!to_replace.IsPlausible(decremented_queue_index)) {
974 // We don't care about the result. It will either succeed, or we got
975 // beat in fixing it and just need to give up and try again. If we got
976 // beat multiple times, the only way progress can be made is if the queue
977 // is updated as well. This means that if we retry reading
978 // next_queue_index, we will be at most off by one and can retry.
979 //
980 // Both require no further action from us.
981 //
982 // TODO(austin): If we are having fairness issues under contention, we
983 // could have a mode bit in next_queue_index, and could use a lock or some
984 // other form of PI boosting to let the higher priority task win.
985 memory_->next_queue_index.CompareAndExchangeStrong(
986 actual_next_queue_index, incremented_queue_index);
987
Alex Perrycb7da4b2019-08-28 19:35:56 -0700988 VLOG(3) << "We were beat. Try again. Was " << std::hex
989 << to_replace.get() << ", is " << decremented_queue_index.index();
Austin Schuh20b2b082019-09-11 20:42:56 -0700990 continue;
991 }
992
993 // Confirm that the message is what it should be.
Brian Silverman177567e2020-08-12 19:51:33 -0700994 //
995 // This is just a best-effort check to skip reading the clocks if possible.
996 // If this fails, then the compare-exchange below definitely would, so we
997 // can bail out now.
Austin Schuh20b2b082019-09-11 20:42:56 -0700998 {
Austin Schuh20b2b082019-09-11 20:42:56 -0700999 const QueueIndex previous_index =
Brian Silverman177567e2020-08-12 19:51:33 -07001000 memory_->GetMessage(to_replace)
1001 ->header.queue_index.RelaxedLoad(queue_size);
Austin Schuh20b2b082019-09-11 20:42:56 -07001002 if (previous_index != decremented_queue_index && previous_index.valid()) {
1003 // Retry.
Alex Perrycb7da4b2019-08-28 19:35:56 -07001004 VLOG(3) << "Something fishy happened, queue index doesn't match. "
1005 "Retrying. Previous index was "
1006 << std::hex << previous_index.index() << ", should be "
1007 << decremented_queue_index.index();
Austin Schuh20b2b082019-09-11 20:42:56 -07001008 continue;
1009 }
1010 }
1011
1012 message->header.monotonic_sent_time = ::aos::monotonic_clock::now();
1013 message->header.realtime_sent_time = ::aos::realtime_clock::now();
Austin Schuhad154822019-12-27 15:45:13 -08001014 if (monotonic_sent_time != nullptr) {
1015 *monotonic_sent_time = message->header.monotonic_sent_time;
1016 }
1017 if (realtime_sent_time != nullptr) {
1018 *realtime_sent_time = message->header.realtime_sent_time;
1019 }
1020 if (queue_index != nullptr) {
1021 *queue_index = next_queue_index.index();
1022 }
Austin Schuh20b2b082019-09-11 20:42:56 -07001023
1024 // Before we are fully done filling out the message, update the Sender state
1025 // with the new index to write. This re-uses the barrier for the
1026 // queue_index store.
Alex Perrycb7da4b2019-08-28 19:35:56 -07001027 const Index index_to_write(next_queue_index, scratch_index.message_index());
Austin Schuh20b2b082019-09-11 20:42:56 -07001028
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001029 aos_compiler_memory_barrier();
1030 // We're the only person who cares about our scratch index, besides somebody
1031 // cleaning up after us.
Austin Schuh20b2b082019-09-11 20:42:56 -07001032 sender->scratch_index.RelaxedStore(index_to_write);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001033 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -07001034
1035 message->header.queue_index.Store(next_queue_index);
1036
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001037 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -07001038 // The message is now filled out, and we have a confirmed slot to store
1039 // into.
1040 //
1041 // Start by writing down what we are going to pull out of the queue. This
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001042 // was Invalid before now. Only person who will read this is whoever cleans
1043 // up after us, so no synchronization necessary.
Austin Schuh20b2b082019-09-11 20:42:56 -07001044 sender->to_replace.RelaxedStore(to_replace);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001045 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -07001046
1047 // Then exchange the next index into the queue.
1048 if (!memory_->GetQueue(next_queue_index.Wrapped())
1049 ->CompareAndExchangeStrong(to_replace, index_to_write)) {
1050 // Aw, didn't succeed. Retry.
1051 sender->to_replace.RelaxedInvalidate();
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001052 aos_compiler_memory_barrier();
Alex Perrycb7da4b2019-08-28 19:35:56 -07001053 VLOG(3) << "Failed to wrap into queue";
Austin Schuh20b2b082019-09-11 20:42:56 -07001054 continue;
1055 }
1056
1057 // Then update next_queue_index to save the next user some computation time.
1058 memory_->next_queue_index.CompareAndExchangeStrong(actual_next_queue_index,
1059 incremented_queue_index);
1060
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001061 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -07001062 // Now update the scratch space and record that we succeeded.
1063 sender->scratch_index.Store(to_replace);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001064 aos_compiler_memory_barrier();
1065 // And then record that we succeeded, but definitely after the above store.
Austin Schuh20b2b082019-09-11 20:42:56 -07001066 sender->to_replace.RelaxedInvalidate();
Brian Silverman177567e2020-08-12 19:51:33 -07001067
Austin Schuh20b2b082019-09-11 20:42:56 -07001068 break;
1069 }
Brian Silverman177567e2020-08-12 19:51:33 -07001070
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001071 DCHECK(!CheckBothRedzones(memory_, memory_->GetMessage(to_replace)))
1072 << ": Invalid message found in shared memory";
Brian Silverman177567e2020-08-12 19:51:33 -07001073 // to_replace is our current scratch_index. It isn't in the queue, which means
1074 // nobody new can pin it. They can set their `pinned` to it, but they will
1075 // back it out, so they don't count. This means that we just need to find a
1076 // message for which no pinner had it in `pinned`, and then we know this
1077 // message will never be pinned. We'll start with to_replace, and if that is
1078 // pinned then we'll look for a new one to use instead.
1079 const Index new_scratch =
1080 SwapPinnedSenderScratch(memory_, sender, to_replace);
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001081 DCHECK(!CheckBothRedzones(
1082 memory_, memory_->GetMessage(sender->scratch_index.RelaxedLoad())))
1083 << ": Invalid message found in shared memory";
Brian Silverman177567e2020-08-12 19:51:33 -07001084
1085 // If anybody is looking at this message (they shouldn't be), then try telling
1086 // them about it (best-effort).
1087 memory_->GetMessage(new_scratch)->header.queue_index.RelaxedInvalidate();
Austin Schuh91ba6392020-10-03 13:27:47 -07001088 return true;
Austin Schuh20b2b082019-09-11 20:42:56 -07001089}
1090
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001091int LocklessQueueSender::buffer_index() const {
Brian Silverman4f4e0612020-08-12 19:54:41 -07001092 ::aos::ipc_lib::Sender *const sender = memory_->GetSender(sender_index_);
1093 // We can do a relaxed load on our sender because we're the only person
1094 // modifying it right now.
1095 const Index scratch_index = sender->scratch_index.RelaxedLoad();
1096 return scratch_index.message_index();
1097}
1098
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001099LocklessQueuePinner::LocklessQueuePinner(
1100 LocklessQueueMemory *memory, const LocklessQueueMemory *const_memory)
1101 : memory_(memory), const_memory_(const_memory) {
1102 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory_);
1103
1104 // Since we already have the lock, go ahead and try cleaning up.
1105 Cleanup(memory_, grab_queue_setup_lock);
1106
1107 const int num_pinners = memory_->num_pinners();
1108
1109 for (int i = 0; i < num_pinners; ++i) {
1110 ::aos::ipc_lib::Pinner *p = memory->GetPinner(i);
1111 // This doesn't need synchronization because we're the only process doing
1112 // initialization right now, and nobody else will be touching pinners which
1113 // we're interested in.
1114 const uint32_t tid = __atomic_load_n(&(p->tid.futex), __ATOMIC_RELAXED);
1115 if (tid == 0) {
1116 pinner_index_ = i;
1117 break;
1118 }
1119 }
1120
1121 if (pinner_index_ == -1) {
1122 VLOG(1) << "Too many pinners, starting to bail.";
1123 return;
1124 }
1125
1126 ::aos::ipc_lib::Pinner *p = memory_->GetPinner(pinner_index_);
1127 p->pinned.Invalidate();
1128
1129 // Indicate that we are now alive by taking over the slot. If the previous
1130 // owner died, we still want to do this.
1131 death_notification_init(&(p->tid));
1132}
1133
1134LocklessQueuePinner::~LocklessQueuePinner() {
1135 if (pinner_index_ != -1) {
1136 CHECK(memory_ != nullptr);
1137 memory_->GetPinner(pinner_index_)->pinned.Invalidate();
1138 aos_compiler_memory_barrier();
1139 death_notification_release(&(memory_->GetPinner(pinner_index_)->tid));
1140 }
1141}
1142
1143std::optional<LocklessQueuePinner> LocklessQueuePinner::Make(
1144 LocklessQueue queue) {
1145 queue.Initialize();
1146 LocklessQueuePinner result(queue.memory(), queue.const_memory());
1147 if (result.pinner_index_ != -1) {
1148 return std::move(result);
1149 } else {
1150 return std::nullopt;
1151 }
1152}
1153
1154// This method doesn't mess with any scratch_index, so it doesn't have to worry
1155// about message ownership.
1156int LocklessQueuePinner::PinIndex(uint32_t uint32_queue_index) {
1157 const size_t queue_size = memory_->queue_size();
1158 const QueueIndex queue_index =
1159 QueueIndex::Zero(queue_size).IncrementBy(uint32_queue_index);
1160 ipc_lib::Pinner *const pinner = memory_->GetPinner(pinner_index_);
1161
1162 AtomicIndex *const queue_slot = memory_->GetQueue(queue_index.Wrapped());
1163
1164 // Indicate that we want to pin this message.
1165 pinner->pinned.Store(queue_index);
1166 aos_compiler_memory_barrier();
1167
1168 {
1169 const Index message_index = queue_slot->Load();
1170 Message *const message = memory_->GetMessage(message_index);
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001171 DCHECK(!CheckBothRedzones(memory_, message))
1172 << ": Invalid message found in shared memory";
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001173
1174 const QueueIndex message_queue_index =
1175 message->header.queue_index.Load(queue_size);
1176 if (message_queue_index == queue_index) {
1177 VLOG(3) << "Eq: " << std::hex << message_queue_index.index();
1178 aos_compiler_memory_barrier();
1179 return message_index.message_index();
1180 }
1181 VLOG(3) << "Message reused: " << std::hex << message_queue_index.index()
1182 << ", " << queue_index.index();
1183 }
1184
1185 // Being down here means we asked to pin a message before realizing it's no
1186 // longer in the queue, so back that out now.
1187 pinner->pinned.Invalidate();
1188 VLOG(3) << "Unpinned: " << std::hex << queue_index.index();
1189 return -1;
1190}
1191
1192size_t LocklessQueuePinner::size() const {
1193 return const_memory_->message_data_size();
1194}
1195
1196const void *LocklessQueuePinner::Data() const {
1197 const size_t queue_size = const_memory_->queue_size();
1198 const ::aos::ipc_lib::Pinner *const pinner =
1199 const_memory_->GetPinner(pinner_index_);
1200 QueueIndex pinned = pinner->pinned.RelaxedLoad(queue_size);
1201 CHECK(pinned.valid());
1202 const Message *message = const_memory_->GetMessage(pinned);
1203
1204 return message->data(const_memory_->message_data_size());
1205}
1206
1207LocklessQueueReader::Result LocklessQueueReader::Read(
Austin Schuh20b2b082019-09-11 20:42:56 -07001208 uint32_t uint32_queue_index,
1209 ::aos::monotonic_clock::time_point *monotonic_sent_time,
Austin Schuhad154822019-12-27 15:45:13 -08001210 ::aos::realtime_clock::time_point *realtime_sent_time,
1211 ::aos::monotonic_clock::time_point *monotonic_remote_time,
1212 ::aos::realtime_clock::time_point *realtime_remote_time,
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001213 uint32_t *remote_queue_index, size_t *length, char *data) const {
Austin Schuh20b2b082019-09-11 20:42:56 -07001214 const size_t queue_size = memory_->queue_size();
1215
1216 // Build up the QueueIndex.
1217 const QueueIndex queue_index =
1218 QueueIndex::Zero(queue_size).IncrementBy(uint32_queue_index);
1219
1220 // Read the message stored at the requested location.
1221 Index mi = memory_->LoadIndex(queue_index);
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001222 const Message *m = memory_->GetMessage(mi);
Austin Schuh20b2b082019-09-11 20:42:56 -07001223
1224 while (true) {
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001225 DCHECK(!CheckBothRedzones(memory_, m))
1226 << ": Invalid message found in shared memory";
Austin Schuh20b2b082019-09-11 20:42:56 -07001227 // We need to confirm that the data doesn't change while we are reading it.
1228 // Do that by first confirming that the message points to the queue index we
1229 // want.
1230 const QueueIndex starting_queue_index =
1231 m->header.queue_index.Load(queue_size);
1232 if (starting_queue_index != queue_index) {
1233 // If we found a message that is exactly 1 loop old, we just wrapped.
1234 if (starting_queue_index == queue_index.DecrementBy(queue_size)) {
Alex Perrycb7da4b2019-08-28 19:35:56 -07001235 VLOG(3) << "Matches: " << std::hex << starting_queue_index.index()
1236 << ", " << queue_index.DecrementBy(queue_size).index();
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001237 return Result::NOTHING_NEW;
Brian Silverman177567e2020-08-12 19:51:33 -07001238 }
1239
1240 // Someone has re-used this message between when we pulled it out of the
1241 // queue and when we grabbed its index. It is pretty hard to deduce
1242 // what happened. Just try again.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001243 const Message *const new_m = memory_->GetMessage(queue_index);
Brian Silverman177567e2020-08-12 19:51:33 -07001244 if (m != new_m) {
1245 m = new_m;
1246 VLOG(3) << "Retrying, m doesn't match";
1247 continue;
1248 }
1249
1250 // We have confirmed that message still points to the same message. This
1251 // means that the message didn't get swapped out from under us, so
1252 // starting_queue_index is correct.
1253 //
1254 // Either we got too far behind (signaled by this being a valid
1255 // message), or this is one of the initial messages which are invalid.
1256 if (starting_queue_index.valid()) {
1257 VLOG(3) << "Too old. Tried for " << std::hex << queue_index.index()
1258 << ", got " << starting_queue_index.index() << ", behind by "
1259 << std::dec
1260 << (starting_queue_index.index() - queue_index.index());
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001261 return Result::TOO_OLD;
Brian Silverman177567e2020-08-12 19:51:33 -07001262 }
1263
1264 VLOG(3) << "Initial";
1265
1266 // There isn't a valid message at this location.
1267 //
1268 // If someone asks for one of the messages within the first go around,
1269 // then they need to wait. They got ahead. Otherwise, they are
1270 // asking for something crazy, like something before the beginning of
1271 // the queue. Tell them that they are behind.
1272 if (uint32_queue_index < memory_->queue_size()) {
1273 VLOG(3) << "Near zero, " << std::hex << uint32_queue_index;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001274 return Result::NOTHING_NEW;
Austin Schuh20b2b082019-09-11 20:42:56 -07001275 } else {
Brian Silverman177567e2020-08-12 19:51:33 -07001276 VLOG(3) << "Not near zero, " << std::hex << uint32_queue_index;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001277 return Result::TOO_OLD;
Austin Schuh20b2b082019-09-11 20:42:56 -07001278 }
1279 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001280 VLOG(3) << "Eq: " << std::hex << starting_queue_index.index() << ", "
1281 << queue_index.index();
Austin Schuh20b2b082019-09-11 20:42:56 -07001282 break;
1283 }
1284
Alex Perrycb7da4b2019-08-28 19:35:56 -07001285 // Then read the data out. Copy it all out to be deterministic and so we can
1286 // make length be from either end.
Austin Schuh20b2b082019-09-11 20:42:56 -07001287 *monotonic_sent_time = m->header.monotonic_sent_time;
1288 *realtime_sent_time = m->header.realtime_sent_time;
Austin Schuhad154822019-12-27 15:45:13 -08001289 if (m->header.remote_queue_index == 0xffffffffu) {
1290 *remote_queue_index = queue_index.index();
1291 } else {
1292 *remote_queue_index = m->header.remote_queue_index;
1293 }
1294 *monotonic_remote_time = m->header.monotonic_remote_time;
1295 *realtime_remote_time = m->header.realtime_remote_time;
Brian Silverman6b8a3c32020-03-06 11:26:14 -08001296 if (data) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001297 memcpy(data, m->data(memory_->message_data_size()),
1298 memory_->message_data_size());
Brian Silverman6b8a3c32020-03-06 11:26:14 -08001299 }
Austin Schuh20b2b082019-09-11 20:42:56 -07001300 *length = m->header.length;
1301
1302 // And finally, confirm that the message *still* points to the queue index we
1303 // want. This means it didn't change out from under us.
1304 // If something changed out from under us, we were reading it much too late in
1305 // it's lifetime.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001306 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -07001307 const QueueIndex final_queue_index = m->header.queue_index.Load(queue_size);
1308 if (final_queue_index != queue_index) {
Alex Perrycb7da4b2019-08-28 19:35:56 -07001309 VLOG(3) << "Changed out from under us. Reading " << std::hex
1310 << queue_index.index() << ", finished with "
1311 << final_queue_index.index() << ", delta: " << std::dec
1312 << (final_queue_index.index() - queue_index.index());
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001313 return Result::OVERWROTE;
Austin Schuh20b2b082019-09-11 20:42:56 -07001314 }
1315
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001316 return Result::GOOD;
Austin Schuh20b2b082019-09-11 20:42:56 -07001317}
1318
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001319QueueIndex LocklessQueueReader::LatestIndex() const {
Austin Schuh20b2b082019-09-11 20:42:56 -07001320 const size_t queue_size = memory_->queue_size();
1321
1322 // There is only one interesting case. We need to know if the queue is empty.
1323 // That is done with a sentinel value. At worst, this will be off by one.
1324 const QueueIndex next_queue_index =
1325 memory_->next_queue_index.Load(queue_size);
1326 if (next_queue_index.valid()) {
1327 const QueueIndex current_queue_index = next_queue_index.DecrementBy(1u);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001328 return current_queue_index;
Austin Schuh20b2b082019-09-11 20:42:56 -07001329 }
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001330 return QueueIndex::Invalid();
1331}
1332
1333size_t LocklessQueueSize(const LocklessQueueMemory *memory) {
1334 return memory->queue_size();
1335}
1336
1337size_t LocklessQueueMessageDataSize(const LocklessQueueMemory *memory) {
1338 return memory->message_data_size();
Austin Schuh20b2b082019-09-11 20:42:56 -07001339}
1340
1341namespace {
1342
1343// Prints out the mutex state. Not safe to use while the mutex is being
1344// changed.
1345::std::string PrintMutex(aos_mutex *mutex) {
1346 ::std::stringstream s;
1347 s << "aos_mutex(" << ::std::hex << mutex->futex;
1348
1349 if (mutex->futex != 0) {
1350 s << ":";
1351 if (mutex->futex & FUTEX_OWNER_DIED) {
1352 s << "FUTEX_OWNER_DIED|";
1353 }
1354 s << "tid=" << (mutex->futex & FUTEX_TID_MASK);
1355 }
1356
1357 s << ")";
1358 return s.str();
1359}
1360
1361} // namespace
1362
1363void PrintLocklessQueueMemory(LocklessQueueMemory *memory) {
1364 const size_t queue_size = memory->queue_size();
1365 ::std::cout << "LocklessQueueMemory (" << memory << ") {" << ::std::endl;
1366 ::std::cout << " aos_mutex queue_setup_lock = "
1367 << PrintMutex(&memory->queue_setup_lock) << ::std::endl;
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001368 ::std::cout << " bool initialized = " << memory->initialized << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001369 ::std::cout << " config {" << ::std::endl;
1370 ::std::cout << " size_t num_watchers = " << memory->config.num_watchers
1371 << ::std::endl;
1372 ::std::cout << " size_t num_senders = " << memory->config.num_senders
1373 << ::std::endl;
Brian Silverman177567e2020-08-12 19:51:33 -07001374 ::std::cout << " size_t num_pinners = " << memory->config.num_pinners
1375 << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001376 ::std::cout << " size_t queue_size = " << memory->config.queue_size
1377 << ::std::endl;
1378 ::std::cout << " size_t message_data_size = "
1379 << memory->config.message_data_size << ::std::endl;
1380
1381 ::std::cout << " AtomicQueueIndex next_queue_index = "
1382 << memory->next_queue_index.Load(queue_size).DebugString()
1383 << ::std::endl;
1384
Austin Schuh3328d132020-02-28 13:54:57 -08001385 ::std::cout << " uid_t uid = " << memory->uid << ::std::endl;
1386
Austin Schuh20b2b082019-09-11 20:42:56 -07001387 ::std::cout << " }" << ::std::endl;
1388 ::std::cout << " AtomicIndex queue[" << queue_size << "] {" << ::std::endl;
1389 for (size_t i = 0; i < queue_size; ++i) {
1390 ::std::cout << " [" << i << "] -> "
1391 << memory->GetQueue(i)->Load().DebugString() << ::std::endl;
1392 }
1393 ::std::cout << " }" << ::std::endl;
1394 ::std::cout << " Message messages[" << memory->num_messages() << "] {"
1395 << ::std::endl;
1396 for (size_t i = 0; i < memory->num_messages(); ++i) {
1397 Message *m = memory->GetMessage(Index(i, i));
Brian Silverman001f24d2020-08-12 19:33:20 -07001398 ::std::cout << " [" << i << "] -> Message 0x" << std::hex
1399 << (reinterpret_cast<uintptr_t>(
1400 memory->GetMessage(Index(i, i))) -
1401 reinterpret_cast<uintptr_t>(memory))
1402 << std::dec << " {" << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001403 ::std::cout << " Header {" << ::std::endl;
1404 ::std::cout << " AtomicQueueIndex queue_index = "
1405 << m->header.queue_index.Load(queue_size).DebugString()
1406 << ::std::endl;
Brian Silverman001f24d2020-08-12 19:33:20 -07001407 ::std::cout << " monotonic_clock::time_point monotonic_sent_time = "
1408 << m->header.monotonic_sent_time << " 0x" << std::hex
1409 << m->header.monotonic_sent_time.time_since_epoch().count()
1410 << std::dec << ::std::endl;
1411 ::std::cout << " realtime_clock::time_point realtime_sent_time = "
1412 << m->header.realtime_sent_time << " 0x" << std::hex
1413 << m->header.realtime_sent_time.time_since_epoch().count()
1414 << std::dec << ::std::endl;
1415 ::std::cout
1416 << " monotonic_clock::time_point monotonic_remote_time = "
1417 << m->header.monotonic_remote_time << " 0x" << std::hex
1418 << m->header.monotonic_remote_time.time_since_epoch().count()
1419 << std::dec << ::std::endl;
1420 ::std::cout << " realtime_clock::time_point realtime_remote_time = "
1421 << m->header.realtime_remote_time << " 0x" << std::hex
1422 << m->header.realtime_remote_time.time_since_epoch().count()
1423 << std::dec << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001424 ::std::cout << " size_t length = " << m->header.length
1425 << ::std::endl;
1426 ::std::cout << " }" << ::std::endl;
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001427 if (!CheckBothRedzones(memory, m)) {
1428 ::std::cout << " // *** DATA REDZONES ARE CORRUPTED ***"
1429 << ::std::endl;
1430 }
Austin Schuh20b2b082019-09-11 20:42:56 -07001431 ::std::cout << " data: {";
1432
Brian Silverman001f24d2020-08-12 19:33:20 -07001433 if (FLAGS_dump_lockless_queue_data) {
1434 const char *const m_data = m->data(memory->message_data_size());
1435 for (size_t j = 0; j < m->header.length; ++j) {
1436 char data = m_data[j];
1437 if (j != 0) {
1438 ::std::cout << " ";
1439 }
1440 if (::std::isprint(data)) {
1441 ::std::cout << ::std::setfill(' ') << ::std::setw(2) << ::std::hex
1442 << data;
1443 } else {
1444 ::std::cout << "0x" << ::std::setfill('0') << ::std::setw(2)
1445 << ::std::hex << (static_cast<unsigned>(data) & 0xff);
1446 }
Austin Schuh20b2b082019-09-11 20:42:56 -07001447 }
1448 }
1449 ::std::cout << ::std::setfill(' ') << ::std::dec << "}" << ::std::endl;
1450 ::std::cout << " }," << ::std::endl;
1451 }
1452 ::std::cout << " }" << ::std::endl;
1453
Alex Perrycb7da4b2019-08-28 19:35:56 -07001454 ::std::cout << " Sender senders[" << memory->num_senders() << "] {"
1455 << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001456 for (size_t i = 0; i < memory->num_senders(); ++i) {
1457 Sender *s = memory->GetSender(i);
1458 ::std::cout << " [" << i << "] -> Sender {" << ::std::endl;
1459 ::std::cout << " aos_mutex tid = " << PrintMutex(&s->tid)
1460 << ::std::endl;
1461 ::std::cout << " AtomicIndex scratch_index = "
1462 << s->scratch_index.Load().DebugString() << ::std::endl;
1463 ::std::cout << " AtomicIndex to_replace = "
1464 << s->to_replace.Load().DebugString() << ::std::endl;
1465 ::std::cout << " }" << ::std::endl;
1466 }
1467 ::std::cout << " }" << ::std::endl;
1468
Brian Silverman177567e2020-08-12 19:51:33 -07001469 ::std::cout << " Pinner pinners[" << memory->num_pinners() << "] {"
1470 << ::std::endl;
1471 for (size_t i = 0; i < memory->num_pinners(); ++i) {
1472 Pinner *p = memory->GetPinner(i);
1473 ::std::cout << " [" << i << "] -> Pinner {" << ::std::endl;
1474 ::std::cout << " aos_mutex tid = " << PrintMutex(&p->tid)
1475 << ::std::endl;
1476 ::std::cout << " AtomicIndex scratch_index = "
1477 << p->scratch_index.Load().DebugString() << ::std::endl;
1478 ::std::cout << " AtomicIndex pinned = "
1479 << p->pinned.Load(memory->queue_size()).DebugString()
1480 << ::std::endl;
1481 ::std::cout << " }" << ::std::endl;
1482 }
1483 ::std::cout << " }" << ::std::endl;
1484
Austin Schuh20b2b082019-09-11 20:42:56 -07001485 ::std::cout << " Watcher watchers[" << memory->num_watchers() << "] {"
1486 << ::std::endl;
1487 for (size_t i = 0; i < memory->num_watchers(); ++i) {
1488 Watcher *w = memory->GetWatcher(i);
1489 ::std::cout << " [" << i << "] -> Watcher {" << ::std::endl;
1490 ::std::cout << " aos_mutex tid = " << PrintMutex(&w->tid)
1491 << ::std::endl;
1492 ::std::cout << " pid_t pid = " << w->pid << ::std::endl;
1493 ::std::cout << " int priority = " << w->priority << ::std::endl;
1494 ::std::cout << " }" << ::std::endl;
1495 }
1496 ::std::cout << " }" << ::std::endl;
1497
1498 ::std::cout << "}" << ::std::endl;
1499}
1500
1501} // namespace ipc_lib
1502} // namespace aos