blob: 3d2c0d16d3ea042973a5b2238ea4f5cd7213a57f [file] [log] [blame]
Austin Schuh20b2b082019-09-11 20:42:56 -07001#include "aos/ipc_lib/lockless_queue.h"
2
3#include <linux/futex.h>
4#include <sys/types.h>
5#include <syscall.h>
6#include <unistd.h>
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07007
Austin Schuh20b2b082019-09-11 20:42:56 -07008#include <algorithm>
9#include <iomanip>
10#include <iostream>
11#include <sstream>
12
Austin Schuhbe416742020-10-03 17:24:26 -070013#include "absl/strings/escaping.h"
Philipp Schrader790cb542023-07-05 21:06:52 -070014#include "gflags/gflags.h"
15#include "glog/logging.h"
16
Austin Schuh20b2b082019-09-11 20:42:56 -070017#include "aos/ipc_lib/lockless_queue_memory.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070018#include "aos/realtime.h"
Austin Schuh20b2b082019-09-11 20:42:56 -070019#include "aos/util/compiler_memory_barrier.h"
20
Brian Silverman001f24d2020-08-12 19:33:20 -070021DEFINE_bool(dump_lockless_queue_data, false,
22 "If true, print the data out when dumping the queue.");
23
Austin Schuh20b2b082019-09-11 20:42:56 -070024namespace aos {
25namespace ipc_lib {
Austin Schuh20b2b082019-09-11 20:42:56 -070026namespace {
27
Brian Silvermanfafe1fa2019-12-18 21:42:18 -080028class GrabQueueSetupLockOrDie {
29 public:
30 GrabQueueSetupLockOrDie(LocklessQueueMemory *memory) : memory_(memory) {
31 const int result = mutex_grab(&(memory->queue_setup_lock));
32 CHECK(result == 0 || result == 1) << ": " << result;
33 }
Austin Schuh20b2b082019-09-11 20:42:56 -070034
Brian Silvermanfafe1fa2019-12-18 21:42:18 -080035 ~GrabQueueSetupLockOrDie() { mutex_unlock(&(memory_->queue_setup_lock)); }
36
37 GrabQueueSetupLockOrDie(const GrabQueueSetupLockOrDie &) = delete;
38 GrabQueueSetupLockOrDie &operator=(const GrabQueueSetupLockOrDie &) = delete;
39
40 private:
41 LocklessQueueMemory *const memory_;
42};
43
Brian Silverman177567e2020-08-12 19:51:33 -070044bool IsPinned(LocklessQueueMemory *memory, Index index) {
45 DCHECK(index.valid());
46 const size_t queue_size = memory->queue_size();
47 const QueueIndex message_index =
48 memory->GetMessage(index)->header.queue_index.Load(queue_size);
49 if (!message_index.valid()) {
50 return false;
51 }
52 DCHECK(memory->GetQueue(message_index.Wrapped())->Load() != index)
53 << ": Message is in the queue";
54 for (int pinner_index = 0;
55 pinner_index < static_cast<int>(memory->config.num_pinners);
56 ++pinner_index) {
57 ipc_lib::Pinner *const pinner = memory->GetPinner(pinner_index);
58
59 if (pinner->pinned.RelaxedLoad(queue_size) == message_index) {
60 return true;
61 }
62 }
63 return false;
64}
65
66// Ensures sender->scratch_index (which must contain to_replace) is not pinned.
67//
68// Returns the new scratch_index value.
69Index SwapPinnedSenderScratch(LocklessQueueMemory *const memory,
70 ipc_lib::Sender *const sender,
71 const Index to_replace) {
72 // If anybody's trying to pin this message, then grab a message from a pinner
73 // to write into instead, and leave the message we pulled out of the queue
74 // (currently in our scratch_index) with a pinner.
75 //
76 // This loop will terminate in at most one iteration through the pinners in
77 // any steady-state configuration of the memory. There are only as many
78 // Pinner::pinned values to worry about as there are Pinner::scratch_index
79 // values to check against, plus to_replace, which means there will always be
80 // a free one. We might have to make multiple passes if things are being
81 // changed concurrently though, but nobody dying can make this loop fail to
82 // terminate (because the number of processes that can die is bounded, because
83 // no new ones can start while we've got the lock).
84 for (int pinner_index = 0; true;
85 pinner_index = (pinner_index + 1) % memory->config.num_pinners) {
86 if (!IsPinned(memory, to_replace)) {
87 // No pinners on our current scratch_index, so we're fine now.
88 VLOG(3) << "No pinners: " << to_replace.DebugString();
89 return to_replace;
90 }
91
92 ipc_lib::Pinner *const pinner = memory->GetPinner(pinner_index);
93
94 const Index pinner_scratch = pinner->scratch_index.RelaxedLoad();
95 CHECK(pinner_scratch.valid())
96 << ": Pinner scratch_index should always be valid";
97 if (IsPinned(memory, pinner_scratch)) {
98 // Wouldn't do us any good to swap with this one, so don't bother, and
99 // move onto the next one.
100 VLOG(3) << "Also pinned: " << pinner_scratch.DebugString();
101 continue;
102 }
103
104 sender->to_replace.RelaxedStore(pinner_scratch);
105 aos_compiler_memory_barrier();
106 // Give the pinner the message (which is currently in
107 // sender->scratch_index).
108 if (!pinner->scratch_index.CompareAndExchangeStrong(pinner_scratch,
109 to_replace)) {
110 // Somebody swapped into this pinner before us. The new value is probably
111 // pinned, so we don't want to look at it again immediately.
112 VLOG(3) << "Pinner " << pinner_index
113 << " scratch_index changed: " << pinner_scratch.DebugString()
114 << ", " << to_replace.DebugString();
115 sender->to_replace.RelaxedInvalidate();
116 continue;
117 }
118 aos_compiler_memory_barrier();
119 // Now update the sender's scratch space and record that we succeeded.
120 sender->scratch_index.Store(pinner_scratch);
121 aos_compiler_memory_barrier();
122 // And then record that we succeeded, but definitely after the above
123 // store.
124 sender->to_replace.RelaxedInvalidate();
125 VLOG(3) << "Got new scratch message: " << pinner_scratch.DebugString();
126
127 // If it's in a pinner's scratch_index, it should not be in the queue, which
128 // means nobody new can pin it for real. However, they can still attempt to
129 // pin it, which means we can't verify !IsPinned down here.
130
131 return pinner_scratch;
132 }
133}
134
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700135// Returns true if it succeeded. Returns false if another sender died in the
136// middle.
137bool DoCleanup(LocklessQueueMemory *memory, const GrabQueueSetupLockOrDie &) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800138 // Make sure we start looking at shared memory fresh right now. We'll handle
139 // people dying partway through by either cleaning up after them or not, but
140 // we want to ensure we clean up after anybody who has already died when we
141 // start.
142 aos_compiler_memory_barrier();
143
Austin Schuh20b2b082019-09-11 20:42:56 -0700144 const size_t num_senders = memory->num_senders();
Brian Silverman177567e2020-08-12 19:51:33 -0700145 const size_t num_pinners = memory->num_pinners();
Austin Schuh20b2b082019-09-11 20:42:56 -0700146 const size_t queue_size = memory->queue_size();
147 const size_t num_messages = memory->num_messages();
148
149 // There are a large number of crazy cases here for how things can go wrong
150 // and how we have to recover. They either require us to keep extra track of
151 // what is going on, slowing down the send path, or require a large number of
152 // cases.
153 //
154 // The solution here is to not over-think it. This is running while not real
155 // time during construction. It is allowed to be slow. It will also very
156 // rarely trigger. There is a small uS window where process death is
157 // ambiguous.
158 //
159 // So, build up a list N long, where N is the number of messages. Search
160 // through the entire queue and the sender list (ignoring any dead senders),
161 // and mark down which ones we have seen. Once we have seen all the messages
162 // except the N dead senders, we know which messages are dead. Because the
163 // queue is active while we do this, it may take a couple of go arounds to see
164 // everything.
165
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700166 ::std::vector<bool> need_recovery(num_senders, false);
167
Austin Schuh20b2b082019-09-11 20:42:56 -0700168 // Do the easy case. Find all senders who have died. See if they are either
169 // consistent already, or if they have copied over to_replace to the scratch
170 // index, but haven't cleared to_replace. Count them.
171 size_t valid_senders = 0;
172 for (size_t i = 0; i < num_senders; ++i) {
173 Sender *sender = memory->GetSender(i);
174 const uint32_t tid =
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800175 __atomic_load_n(&(sender->tid.futex), __ATOMIC_ACQUIRE);
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700176 if (!(tid & FUTEX_OWNER_DIED)) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700177 // Not dead.
178 ++valid_senders;
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700179 continue;
Austin Schuh20b2b082019-09-11 20:42:56 -0700180 }
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700181 VLOG(3) << "Found an easy death for sender " << i;
182 // We can do a relaxed load here because we're the only person touching
183 // this sender at this point.
184 const Index to_replace = sender->to_replace.RelaxedLoad();
185 const Index scratch_index = sender->scratch_index.Load();
186
187 // I find it easiest to think about this in terms of the set of observable
188 // states. The main code progresses through the following states:
189
190 // 1) scratch_index = xxx
191 // to_replace = invalid
192 // This is unambiguous. Already good.
193
194 // 2) scratch_index = xxx
195 // to_replace = yyy
196 // Very ambiguous. Is xxx or yyy the correct one? Need to either roll
197 // this forwards or backwards.
198
199 // 3) scratch_index = yyy
200 // to_replace = yyy
201 // We are in the act of moving to_replace to scratch_index, but didn't
202 // finish. Easy.
Brian Silverman177567e2020-08-12 19:51:33 -0700203 //
204 // If doing a pinner swap, we've definitely done it.
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700205
206 // 4) scratch_index = yyy
207 // to_replace = invalid
208 // Finished, but died. Looks like 1)
209
Brian Silverman177567e2020-08-12 19:51:33 -0700210 // Swapping with a pinner's scratch_index passes through the same states.
211 // We just need to ensure the message that ends up in the senders's
212 // scratch_index isn't pinned, using the same code as sending does.
213
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700214 // Any cleanup code needs to follow the same set of states to be robust to
215 // death, so death can be restarted.
216
217 if (!to_replace.valid()) {
218 // 1) or 4). Make sure we aren't corrupted and declare victory.
219 CHECK(scratch_index.valid());
220
Brian Silverman177567e2020-08-12 19:51:33 -0700221 // If it's in 1) with a pinner, the sender might have a pinned message,
222 // so fix that.
223 SwapPinnedSenderScratch(memory, sender, scratch_index);
224
225 // If it's in 4), it may not have completed this step yet. This will
226 // always be a NOP if it's in 1), verified by a DCHECK.
227 memory->GetMessage(scratch_index)->header.queue_index.RelaxedInvalidate();
228
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700229 __atomic_store_n(&(sender->tid.futex), 0, __ATOMIC_RELEASE);
230 ++valid_senders;
231 continue;
232 }
233
234 // Could be 2) or 3) at this point.
235
236 if (to_replace == scratch_index) {
237 // 3) for sure.
238 // Just need to invalidate to_replace to finish.
239 sender->to_replace.Invalidate();
240
Brian Silverman177567e2020-08-12 19:51:33 -0700241 // Make sure to indicate it's an unused message before a sender gets its
242 // hands on it.
243 memory->GetMessage(scratch_index)->header.queue_index.RelaxedInvalidate();
244 aos_compiler_memory_barrier();
245
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700246 // And mark that we succeeded.
247 __atomic_store_n(&(sender->tid.futex), 0, __ATOMIC_RELEASE);
248 ++valid_senders;
249 continue;
250 }
251
252 // Must be 2). Mark it for later.
253 need_recovery[i] = true;
Austin Schuh20b2b082019-09-11 20:42:56 -0700254 }
255
Brian Silverman177567e2020-08-12 19:51:33 -0700256 // Cleaning up pinners is easy. We don't actually have to do anything, but
257 // invalidating its pinned field might help catch bugs elsewhere trying to
258 // read it before it's set.
259 for (size_t i = 0; i < num_pinners; ++i) {
260 Pinner *const pinner = memory->GetPinner(i);
261 const uint32_t tid =
262 __atomic_load_n(&(pinner->tid.futex), __ATOMIC_ACQUIRE);
263 if (!(tid & FUTEX_OWNER_DIED)) {
264 continue;
265 }
266 pinner->pinned.Invalidate();
267 __atomic_store_n(&(pinner->tid.futex), 0, __ATOMIC_RELEASE);
268 }
269
Austin Schuh20b2b082019-09-11 20:42:56 -0700270 // If all the senders are (or were made) good, there is no need to do the hard
271 // case.
272 if (valid_senders == num_senders) {
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700273 return true;
Austin Schuh20b2b082019-09-11 20:42:56 -0700274 }
275
Alex Perrycb7da4b2019-08-28 19:35:56 -0700276 VLOG(3) << "Starting hard cleanup";
Austin Schuh20b2b082019-09-11 20:42:56 -0700277
278 size_t num_accounted_for = 0;
279 size_t num_missing = 0;
280 ::std::vector<bool> accounted_for(num_messages, false);
281
282 while ((num_accounted_for + num_missing) != num_messages) {
283 num_missing = 0;
284 for (size_t i = 0; i < num_senders; ++i) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800285 Sender *const sender = memory->GetSender(i);
Austin Schuh20b2b082019-09-11 20:42:56 -0700286 const uint32_t tid =
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800287 __atomic_load_n(&(sender->tid.futex), __ATOMIC_ACQUIRE);
Austin Schuh20b2b082019-09-11 20:42:56 -0700288 if (tid & FUTEX_OWNER_DIED) {
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700289 if (!need_recovery[i]) {
290 return false;
291 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700292 ++num_missing;
Brian Silverman177567e2020-08-12 19:51:33 -0700293 continue;
Austin Schuh20b2b082019-09-11 20:42:56 -0700294 }
Brian Silverman177567e2020-08-12 19:51:33 -0700295 CHECK(!need_recovery[i]) << ": Somebody else recovered a sender: " << i;
296 // We can do a relaxed load here because we're the only person touching
297 // this sender at this point, if it matters. If it's not a dead sender,
298 // then any message it ever has will eventually be accounted for if we
299 // make enough tries through the outer loop.
300 const Index scratch_index = sender->scratch_index.RelaxedLoad();
301 if (!accounted_for[scratch_index.message_index()]) {
302 ++num_accounted_for;
303 }
304 accounted_for[scratch_index.message_index()] = true;
Austin Schuh20b2b082019-09-11 20:42:56 -0700305 }
306
307 for (size_t i = 0; i < queue_size; ++i) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800308 // Same logic as above for scratch_index applies here too.
Austin Schuh20b2b082019-09-11 20:42:56 -0700309 const Index index = memory->GetQueue(i)->RelaxedLoad();
310 if (!accounted_for[index.message_index()]) {
311 ++num_accounted_for;
312 }
313 accounted_for[index.message_index()] = true;
314 }
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700315
Brian Silverman177567e2020-08-12 19:51:33 -0700316 for (size_t pinner_index = 0; pinner_index < num_pinners; ++pinner_index) {
317 // Same logic as above for scratch_index applies here too.
318 const Index index =
319 memory->GetPinner(pinner_index)->scratch_index.RelaxedLoad();
320 if (!accounted_for[index.message_index()]) {
321 ++num_accounted_for;
322 }
323 accounted_for[index.message_index()] = true;
324 }
325
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700326 CHECK_LE(num_accounted_for + num_missing, num_messages);
Austin Schuh20b2b082019-09-11 20:42:56 -0700327 }
328
329 while (num_missing != 0) {
330 const size_t starting_num_missing = num_missing;
331 for (size_t i = 0; i < num_senders; ++i) {
332 Sender *sender = memory->GetSender(i);
333 const uint32_t tid =
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800334 __atomic_load_n(&(sender->tid.futex), __ATOMIC_ACQUIRE);
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700335 if (!(tid & FUTEX_OWNER_DIED)) {
336 CHECK(!need_recovery[i]) << ": Somebody else recovered a sender: " << i;
337 continue;
338 }
339 if (!need_recovery[i]) {
340 return false;
341 }
342 // We can do relaxed loads here because we're the only person touching
343 // this sender at this point.
344 const Index scratch_index = sender->scratch_index.RelaxedLoad();
345 const Index to_replace = sender->to_replace.RelaxedLoad();
Austin Schuh20b2b082019-09-11 20:42:56 -0700346
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700347 // Candidate.
348 if (to_replace.valid()) {
349 CHECK_LE(to_replace.message_index(), accounted_for.size());
350 }
351 if (scratch_index.valid()) {
352 CHECK_LE(scratch_index.message_index(), accounted_for.size());
353 }
354 if (!to_replace.valid() || accounted_for[to_replace.message_index()]) {
355 CHECK(scratch_index.valid());
356 VLOG(3) << "Sender " << i
357 << " died, to_replace is already accounted for";
358 // If both are accounted for, we are corrupt...
359 CHECK(!accounted_for[scratch_index.message_index()]);
Austin Schuh20b2b082019-09-11 20:42:56 -0700360
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700361 // to_replace is already accounted for. This means that we didn't
362 // atomically insert scratch_index into the queue yet. So
363 // invalidate to_replace.
364 sender->to_replace.Invalidate();
Brian Silverman177567e2020-08-12 19:51:33 -0700365 // Sender definitely will not have gotten here, so finish for it.
366 memory->GetMessage(scratch_index)
367 ->header.queue_index.RelaxedInvalidate();
Austin Schuh20b2b082019-09-11 20:42:56 -0700368
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700369 // And then mark this sender clean.
370 __atomic_store_n(&(sender->tid.futex), 0, __ATOMIC_RELEASE);
371 need_recovery[i] = false;
Austin Schuh20b2b082019-09-11 20:42:56 -0700372
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700373 // And account for scratch_index.
374 accounted_for[scratch_index.message_index()] = true;
375 --num_missing;
376 ++num_accounted_for;
377 } else if (!scratch_index.valid() ||
378 accounted_for[scratch_index.message_index()]) {
379 VLOG(3) << "Sender " << i
380 << " died, scratch_index is already accounted for";
381 // scratch_index is accounted for. That means we did the insert,
382 // but didn't record it.
383 CHECK(to_replace.valid());
Brian Silverman177567e2020-08-12 19:51:33 -0700384
385 // Make sure to indicate it's an unused message before a sender gets its
386 // hands on it.
387 memory->GetMessage(to_replace)->header.queue_index.RelaxedInvalidate();
388 aos_compiler_memory_barrier();
389
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700390 // Finish the transaction. Copy to_replace, then clear it.
Austin Schuh20b2b082019-09-11 20:42:56 -0700391
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700392 sender->scratch_index.Store(to_replace);
393 sender->to_replace.Invalidate();
Austin Schuh20b2b082019-09-11 20:42:56 -0700394
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700395 // And then mark this sender clean.
396 __atomic_store_n(&(sender->tid.futex), 0, __ATOMIC_RELEASE);
397 need_recovery[i] = false;
Austin Schuh20b2b082019-09-11 20:42:56 -0700398
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700399 // And account for to_replace.
400 accounted_for[to_replace.message_index()] = true;
401 --num_missing;
402 ++num_accounted_for;
403 } else {
404 VLOG(3) << "Sender " << i << " died, neither is accounted for";
405 // Ambiguous. There will be an unambiguous one somewhere that we
406 // can do first.
Austin Schuh20b2b082019-09-11 20:42:56 -0700407 }
408 }
409 // CHECK that we are making progress.
410 CHECK_NE(num_missing, starting_num_missing);
411 }
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700412 return true;
413}
414
415void Cleanup(LocklessQueueMemory *memory, const GrabQueueSetupLockOrDie &lock) {
416 // The number of iterations is bounded here because there are only a finite
417 // number of senders in existence which could die, and no new ones can be
418 // created while we're in here holding the lock.
419 while (!DoCleanup(memory, lock)) {
420 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700421}
422
423// Exposes rt_tgsigqueueinfo so we can send the signal *just* to the target
424// thread.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800425// TODO(Brian): Do directly in assembly for armhf at least for efficiency.
Austin Schuh20b2b082019-09-11 20:42:56 -0700426int rt_tgsigqueueinfo(pid_t tgid, pid_t tid, int sig, siginfo_t *si) {
427 return syscall(SYS_rt_tgsigqueueinfo, tgid, tid, sig, si);
428}
429
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700430QueueIndex ZeroOrValid(QueueIndex index) {
431 if (!index.valid()) {
432 return index.Clear();
433 }
434 return index;
435}
436
Austin Schuh20b2b082019-09-11 20:42:56 -0700437} // namespace
438
Austin Schuh4bc4f902019-12-23 18:04:51 -0800439size_t LocklessQueueConfiguration::message_size() const {
440 // Round up the message size so following data is aligned appropriately.
Brian Silverman0eaa1da2020-08-12 20:03:52 -0700441 // Make sure to leave space to align the message data. It will be aligned
442 // relative to the start of the shared memory region, but that might not be
443 // aligned for some use cases.
Brian Silvermana1652f32020-01-29 20:41:44 -0800444 return LocklessQueueMemory::AlignmentRoundUp(message_data_size +
Brian Silverman0eaa1da2020-08-12 20:03:52 -0700445 kChannelDataRedzone * 2 +
Brian Silvermana1652f32020-01-29 20:41:44 -0800446 (kChannelDataAlignment - 1)) +
Austin Schuh4bc4f902019-12-23 18:04:51 -0800447 sizeof(Message);
448}
449
Austin Schuh20b2b082019-09-11 20:42:56 -0700450size_t LocklessQueueMemorySize(LocklessQueueConfiguration config) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800451 // Round up the message size so following data is aligned appropriately.
452 config.message_data_size =
453 LocklessQueueMemory::AlignmentRoundUp(config.message_data_size);
Austin Schuh20b2b082019-09-11 20:42:56 -0700454
455 // As we build up the size, confirm that everything is aligned to the
456 // alignment requirements of the type.
457 size_t size = sizeof(LocklessQueueMemory);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800458 CHECK_EQ(size % alignof(LocklessQueueMemory), 0u);
Austin Schuh20b2b082019-09-11 20:42:56 -0700459
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800460 CHECK_EQ(size % alignof(AtomicIndex), 0u);
Austin Schuh20b2b082019-09-11 20:42:56 -0700461 size += LocklessQueueMemory::SizeOfQueue(config);
462
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800463 CHECK_EQ(size % alignof(Message), 0u);
Austin Schuh20b2b082019-09-11 20:42:56 -0700464 size += LocklessQueueMemory::SizeOfMessages(config);
465
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800466 CHECK_EQ(size % alignof(Watcher), 0u);
Austin Schuh20b2b082019-09-11 20:42:56 -0700467 size += LocklessQueueMemory::SizeOfWatchers(config);
468
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800469 CHECK_EQ(size % alignof(Sender), 0u);
Austin Schuh20b2b082019-09-11 20:42:56 -0700470 size += LocklessQueueMemory::SizeOfSenders(config);
471
Brian Silverman177567e2020-08-12 19:51:33 -0700472 CHECK_EQ(size % alignof(Pinner), 0u);
473 size += LocklessQueueMemory::SizeOfPinners(config);
474
Austin Schuh20b2b082019-09-11 20:42:56 -0700475 return size;
476}
477
Brian Silverman0eaa1da2020-08-12 20:03:52 -0700478// Calculates the starting byte for a redzone in shared memory. This starting
479// value is simply incremented for subsequent bytes.
480//
481// The result is based on the offset of the region in shared memor, to ensure it
482// is the same for each region when we generate and verify, but different for
483// each region to help catch forms of corruption like copying out-of-bounds data
484// from one place to another.
485//
486// memory is the base pointer to the shared memory. It is used to calculated
487// offsets. starting_data is the start of the redzone's data. Each one will
488// get a unique pattern.
489uint8_t RedzoneStart(const LocklessQueueMemory *memory,
490 const char *starting_data) {
491 const auto memory_int = reinterpret_cast<uintptr_t>(memory);
492 const auto starting_int = reinterpret_cast<uintptr_t>(starting_data);
493 DCHECK(starting_int >= memory_int);
494 DCHECK(starting_int < memory_int + LocklessQueueMemorySize(memory->config));
495 const uintptr_t starting_offset = starting_int - memory_int;
496 // Just XOR the lower 2 bytes. They higher-order bytes are probably 0
497 // anyways.
498 return (starting_offset & 0xFF) ^ ((starting_offset >> 8) & 0xFF);
499}
500
501// Returns true if the given redzone has invalid data.
502bool CheckRedzone(const LocklessQueueMemory *memory,
503 absl::Span<const char> redzone) {
504 uint8_t redzone_value = RedzoneStart(memory, redzone.data());
505
506 bool bad = false;
507
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700508 for (size_t i = 0; i < redzone.size() && !bad; ++i) {
Brian Silverman0eaa1da2020-08-12 20:03:52 -0700509 if (memcmp(&redzone[i], &redzone_value, 1)) {
510 bad = true;
511 }
512 ++redzone_value;
513 }
514
515 return bad;
516}
517
518// Returns true if either of message's redzones has invalid data.
519bool CheckBothRedzones(const LocklessQueueMemory *memory,
520 const Message *message) {
521 return CheckRedzone(memory,
522 message->PreRedzone(memory->message_data_size())) ||
523 CheckRedzone(memory, message->PostRedzone(memory->message_data_size(),
524 memory->message_size()));
525}
526
527// Fills the given redzone with the expected data.
528void FillRedzone(LocklessQueueMemory *memory, absl::Span<char> redzone) {
529 uint8_t redzone_value = RedzoneStart(memory, redzone.data());
530 for (size_t i = 0; i < redzone.size(); ++i) {
531 memcpy(&redzone[i], &redzone_value, 1);
532 ++redzone_value;
533 }
534
535 // Just double check that the implementations match.
536 CHECK(!CheckRedzone(memory, redzone));
537}
538
Austin Schuh20b2b082019-09-11 20:42:56 -0700539LocklessQueueMemory *InitializeLocklessQueueMemory(
540 LocklessQueueMemory *memory, LocklessQueueConfiguration config) {
541 // Everything should be zero initialized already. So we just need to fill
542 // everything out properly.
543
Brian Silvermanc57ff0a2020-04-28 16:45:13 -0700544 // This is the UID we will use for checking signal-sending permission
545 // compatibility.
546 //
547 // The manpage says:
548 // For a process to have permission to send a signal, it must either be
549 // privileged [...], or the real or effective user ID of the sending process
550 // must equal the real or saved set-user-ID of the target process.
551 //
552 // Processes typically initialize a queue in random order as they start up.
553 // This means we need an algorithm for verifying all processes have
554 // permissions to send each other signals which gives the same answer no
555 // matter what order they attach in. We would also like to avoid maintaining a
556 // shared list of the UIDs of all processes.
557 //
558 // To do this while still giving sufficient flexibility for all current use
559 // cases, we track a single UID for the queue. All processes with a matching
560 // euid+suid must have this UID. Any processes with distinct euid/suid must
561 // instead have a matching ruid. This guarantees signals can be sent between
562 // all processes attached to the queue.
563 //
564 // In particular, this allows a process to change only its euid (to interact
565 // with a queue) while still maintaining privileges via its ruid. However, it
566 // can only use privileges in ways that do not require changing the euid back,
567 // because while the euid is different it will not be able to receive signals.
568 // We can't actually verify that, but we can sanity check that things are
569 // valid when the queue is initialized.
570
571 uid_t uid;
572 {
573 uid_t ruid, euid, suid;
574 PCHECK(getresuid(&ruid, &euid, &suid) == 0);
575 // If these are equal, then use them, even if that's different from the real
576 // UID. This allows processes to keep a real UID of 0 (to have permissions
577 // to perform system-level changes) while still being able to communicate
578 // with processes running unprivileged as a distinct user.
579 if (euid == suid) {
580 uid = euid;
581 VLOG(1) << "Using euid==suid " << uid;
582 } else {
583 uid = ruid;
584 VLOG(1) << "Using ruid " << ruid;
585 }
586 }
587
Austin Schuh20b2b082019-09-11 20:42:56 -0700588 // Grab the mutex. We don't care if the previous reader died. We are going
589 // to check everything anyways.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800590 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory);
Austin Schuh20b2b082019-09-11 20:42:56 -0700591
592 if (!memory->initialized) {
593 // TODO(austin): Check these for out of bounds.
594 memory->config.num_watchers = config.num_watchers;
595 memory->config.num_senders = config.num_senders;
Brian Silverman177567e2020-08-12 19:51:33 -0700596 memory->config.num_pinners = config.num_pinners;
Austin Schuh20b2b082019-09-11 20:42:56 -0700597 memory->config.queue_size = config.queue_size;
Austin Schuh4bc4f902019-12-23 18:04:51 -0800598 memory->config.message_data_size = config.message_data_size;
Austin Schuh20b2b082019-09-11 20:42:56 -0700599
600 const size_t num_messages = memory->num_messages();
601 // There need to be at most MaxMessages() messages allocated.
602 CHECK_LE(num_messages, Index::MaxMessages());
603
604 for (size_t i = 0; i < num_messages; ++i) {
Brian Silverman0eaa1da2020-08-12 20:03:52 -0700605 Message *const message =
606 memory->GetMessage(Index(QueueIndex::Zero(memory->queue_size()), i));
607 message->header.queue_index.Invalidate();
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700608 message->header.monotonic_sent_time = monotonic_clock::min_time;
Brian Silverman0eaa1da2020-08-12 20:03:52 -0700609 FillRedzone(memory, message->PreRedzone(memory->message_data_size()));
610 FillRedzone(memory, message->PostRedzone(memory->message_data_size(),
611 memory->message_size()));
Austin Schuh20b2b082019-09-11 20:42:56 -0700612 }
613
614 for (size_t i = 0; i < memory->queue_size(); ++i) {
615 // Make the initial counter be the furthest away number. That means that
616 // index 0 should be 0xffff, 1 should be 0, etc.
617 memory->GetQueue(i)->Store(Index(QueueIndex::Zero(memory->queue_size())
618 .IncrementBy(i)
619 .DecrementBy(memory->queue_size()),
620 i));
621 }
622
623 memory->next_queue_index.Invalidate();
Brian Silvermanc57ff0a2020-04-28 16:45:13 -0700624 memory->uid = uid;
Austin Schuh20b2b082019-09-11 20:42:56 -0700625
626 for (size_t i = 0; i < memory->num_senders(); ++i) {
627 ::aos::ipc_lib::Sender *s = memory->GetSender(i);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800628 // Nobody else can possibly be touching these because we haven't set
629 // initialized to true yet.
630 s->scratch_index.RelaxedStore(Index(0xffff, i + memory->queue_size()));
Austin Schuh20b2b082019-09-11 20:42:56 -0700631 s->to_replace.RelaxedInvalidate();
632 }
633
Brian Silverman177567e2020-08-12 19:51:33 -0700634 for (size_t i = 0; i < memory->num_pinners(); ++i) {
635 ::aos::ipc_lib::Pinner *pinner = memory->GetPinner(i);
636 // Nobody else can possibly be touching these because we haven't set
637 // initialized to true yet.
638 pinner->scratch_index.RelaxedStore(
639 Index(0xffff, i + memory->num_senders() + memory->queue_size()));
640 pinner->pinned.Invalidate();
641 }
642
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800643 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -0700644 // Signal everything is done. This needs to be done last, so if we die, we
645 // redo initialization.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800646 memory->initialized = true;
Austin Schuh3328d132020-02-28 13:54:57 -0800647 } else {
Brian Silvermanc57ff0a2020-04-28 16:45:13 -0700648 CHECK_EQ(uid, memory->uid) << ": UIDs must match for all processes";
Austin Schuh20b2b082019-09-11 20:42:56 -0700649 }
650
Austin Schuh20b2b082019-09-11 20:42:56 -0700651 return memory;
652}
653
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700654void LocklessQueue::Initialize() {
655 InitializeLocklessQueueMemory(memory_, config_);
656}
Austin Schuh20b2b082019-09-11 20:42:56 -0700657
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700658LocklessQueueWatcher::~LocklessQueueWatcher() {
659 if (watcher_index_ == -1) {
660 return;
661 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700662
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700663 // Since everything is self consistent, all we need to do is make sure nobody
664 // else is running. Someone dying will get caught in the generic consistency
665 // check.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800666 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory_);
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700667
668 // Make sure we are registered.
669 CHECK_NE(watcher_index_, -1);
670
671 // Make sure we still own the slot we are supposed to.
672 CHECK(
673 death_notification_is_held(&(memory_->GetWatcher(watcher_index_)->tid)));
674
675 // The act of unlocking invalidates the entry. Invalidate it.
676 death_notification_release(&(memory_->GetWatcher(watcher_index_)->tid));
677 // And internally forget the slot.
678 watcher_index_ = -1;
679
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800680 // Cleanup is cheap. The next user will do it anyways, so no need for us to do
681 // anything right now.
Austin Schuh20b2b082019-09-11 20:42:56 -0700682
683 // And confirm that nothing is owned by us.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700684 const int num_watchers = memory_->num_watchers();
Austin Schuh20b2b082019-09-11 20:42:56 -0700685 for (int i = 0; i < num_watchers; ++i) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700686 CHECK(!death_notification_is_held(&(memory_->GetWatcher(i)->tid)))
687 << ": " << i;
Austin Schuh20b2b082019-09-11 20:42:56 -0700688 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700689}
690
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700691std::optional<LocklessQueueWatcher> LocklessQueueWatcher::Make(
692 LocklessQueue queue, int priority) {
693 queue.Initialize();
694 LocklessQueueWatcher result(queue.memory(), priority);
695 if (result.watcher_index_ != -1) {
James Kuszmaul9776b392023-01-14 14:08:08 -0800696 return result;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700697 } else {
698 return std::nullopt;
699 }
700}
Austin Schuh20b2b082019-09-11 20:42:56 -0700701
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700702LocklessQueueWatcher::LocklessQueueWatcher(LocklessQueueMemory *memory,
703 int priority)
704 : memory_(memory) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700705 // TODO(austin): Make sure signal coalescing is turned on. We don't need
706 // duplicates. That will improve performance under high load.
707
708 // Since everything is self consistent, all we need to do is make sure nobody
709 // else is running. Someone dying will get caught in the generic consistency
710 // check.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800711 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory_);
Austin Schuh20b2b082019-09-11 20:42:56 -0700712 const int num_watchers = memory_->num_watchers();
713
714 // Now, find the first empty watcher and grab it.
715 CHECK_EQ(watcher_index_, -1);
716 for (int i = 0; i < num_watchers; ++i) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800717 // If we see a slot the kernel has marked as dead, everything we do reusing
718 // it needs to happen-after whatever that process did before dying.
Brian Silverman2484eea2019-12-21 16:48:46 -0800719 auto *const futex = &(memory_->GetWatcher(i)->tid.futex);
720 const uint32_t tid = __atomic_load_n(futex, __ATOMIC_ACQUIRE);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800721 if (tid == 0 || (tid & FUTEX_OWNER_DIED)) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700722 watcher_index_ = i;
Brian Silverman2484eea2019-12-21 16:48:46 -0800723 // Relaxed is OK here because we're the only task going to touch it
724 // between here and the write in death_notification_init below (other
725 // recovery is blocked by us holding the setup lock).
726 __atomic_store_n(futex, 0, __ATOMIC_RELAXED);
Austin Schuh20b2b082019-09-11 20:42:56 -0700727 break;
728 }
729 }
730
731 // Bail if we failed to find an open slot.
732 if (watcher_index_ == -1) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700733 return;
Austin Schuh20b2b082019-09-11 20:42:56 -0700734 }
735
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700736 Watcher *const w = memory_->GetWatcher(watcher_index_);
Austin Schuh20b2b082019-09-11 20:42:56 -0700737
738 w->pid = getpid();
739 w->priority = priority;
740
741 // Grabbing a mutex is a compiler and memory barrier, so nothing before will
742 // get rearranged afterwords.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800743 death_notification_init(&(w->tid));
Austin Schuh20b2b082019-09-11 20:42:56 -0700744}
745
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700746LocklessQueueWakeUpper::LocklessQueueWakeUpper(LocklessQueue queue)
747 : memory_(queue.const_memory()), pid_(getpid()), uid_(getuid()) {
748 queue.Initialize();
749 watcher_copy_.resize(memory_->num_watchers());
Austin Schuh20b2b082019-09-11 20:42:56 -0700750}
751
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700752int LocklessQueueWakeUpper::Wakeup(const int current_priority) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700753 const size_t num_watchers = memory_->num_watchers();
754
755 CHECK_EQ(watcher_copy_.size(), num_watchers);
756
757 // Grab a copy so it won't change out from underneath us, and we can sort it
758 // nicely in C++.
759 // Do note that there is still a window where the process can die *after* we
760 // read everything. We will still PI boost and send a signal to the thread in
761 // question. There is no way without pidfd's to close this window, and
762 // creating a pidfd is likely not RT.
763 for (size_t i = 0; i < num_watchers; ++i) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700764 const Watcher *w = memory_->GetWatcher(i);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800765 watcher_copy_[i].tid = __atomic_load_n(&(w->tid.futex), __ATOMIC_RELAXED);
766 // Force the load of the TID to come first.
767 aos_compiler_memory_barrier();
768 watcher_copy_[i].pid = w->pid.load(std::memory_order_relaxed);
769 watcher_copy_[i].priority = w->priority.load(std::memory_order_relaxed);
Austin Schuh20b2b082019-09-11 20:42:56 -0700770
771 // Use a priority of -1 to mean an invalid entry to make sorting easier.
772 if (watcher_copy_[i].tid & FUTEX_OWNER_DIED || watcher_copy_[i].tid == 0) {
773 watcher_copy_[i].priority = -1;
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800774 } else {
775 // Ensure all of this happens after we're done looking at the pid+priority
776 // in shared memory.
777 aos_compiler_memory_barrier();
778 if (watcher_copy_[i].tid != static_cast<pid_t>(__atomic_load_n(
779 &(w->tid.futex), __ATOMIC_RELAXED))) {
780 // Confirm that the watcher hasn't been re-used and modified while we
781 // read it. If it has, mark it invalid again.
782 watcher_copy_[i].priority = -1;
783 watcher_copy_[i].tid = 0;
784 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700785 }
786 }
787
788 // Now sort.
789 ::std::sort(watcher_copy_.begin(), watcher_copy_.end(),
790 [](const WatcherCopy &a, const WatcherCopy &b) {
791 return a.priority > b.priority;
792 });
793
794 int count = 0;
795 if (watcher_copy_[0].priority != -1) {
796 const int max_priority =
797 ::std::max(current_priority, watcher_copy_[0].priority);
798 // Boost if we are RT and there is a higher priority sender out there.
799 // Otherwise we might run into priority inversions.
800 if (max_priority > current_priority && current_priority > 0) {
801 SetCurrentThreadRealtimePriority(max_priority);
802 }
803
804 // Build up the siginfo to send.
805 siginfo_t uinfo;
806 memset(&uinfo, 0, sizeof(uinfo));
807
808 uinfo.si_code = SI_QUEUE;
809 uinfo.si_pid = pid_;
810 uinfo.si_uid = uid_;
811 uinfo.si_value.sival_int = 0;
812
813 for (const WatcherCopy &watcher_copy : watcher_copy_) {
814 // The first -1 priority means we are at the end of the valid list.
815 if (watcher_copy.priority == -1) {
816 break;
817 }
818
819 // Send the signal. Target just the thread that sent it so that we can
820 // support multiple watchers in a process (when someone creates multiple
821 // event loops in different threads).
822 rt_tgsigqueueinfo(watcher_copy.pid, watcher_copy.tid, kWakeupSignal,
823 &uinfo);
824
825 ++count;
826 }
827
828 // Drop back down if we were boosted.
829 if (max_priority > current_priority && current_priority > 0) {
830 SetCurrentThreadRealtimePriority(current_priority);
831 }
832 }
833
834 return count;
835}
836
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700837std::ostream &operator<<(std::ostream &os,
838 const LocklessQueueSender::Result r) {
839 os << static_cast<int>(r);
840 return os;
841}
842
843LocklessQueueSender::LocklessQueueSender(
844 LocklessQueueMemory *memory,
845 monotonic_clock::duration channel_storage_duration)
846 : memory_(memory), channel_storage_duration_(channel_storage_duration) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800847 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory_);
Austin Schuh20b2b082019-09-11 20:42:56 -0700848
849 // Since we already have the lock, go ahead and try cleaning up.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800850 Cleanup(memory_, grab_queue_setup_lock);
Austin Schuh20b2b082019-09-11 20:42:56 -0700851
852 const int num_senders = memory_->num_senders();
853
854 for (int i = 0; i < num_senders; ++i) {
855 ::aos::ipc_lib::Sender *s = memory->GetSender(i);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800856 // This doesn't need synchronization because we're the only process doing
857 // initialization right now, and nobody else will be touching senders which
858 // we're interested in.
Austin Schuh20b2b082019-09-11 20:42:56 -0700859 const uint32_t tid = __atomic_load_n(&(s->tid.futex), __ATOMIC_RELAXED);
860 if (tid == 0) {
861 sender_index_ = i;
862 break;
863 }
864 }
865
866 if (sender_index_ == -1) {
Austin Schuhe516ab02020-05-06 21:37:04 -0700867 VLOG(1) << "Too many senders, starting to bail.";
868 return;
Austin Schuh20b2b082019-09-11 20:42:56 -0700869 }
870
Brian Silverman177567e2020-08-12 19:51:33 -0700871 ::aos::ipc_lib::Sender *const sender = memory_->GetSender(sender_index_);
Austin Schuh20b2b082019-09-11 20:42:56 -0700872
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800873 // Indicate that we are now alive by taking over the slot. If the previous
874 // owner died, we still want to do this.
Brian Silverman177567e2020-08-12 19:51:33 -0700875 death_notification_init(&(sender->tid));
876
877 const Index scratch_index = sender->scratch_index.RelaxedLoad();
878 Message *const message = memory_->GetMessage(scratch_index);
879 CHECK(!message->header.queue_index.RelaxedLoad(memory_->queue_size()).valid())
880 << ": " << std::hex << scratch_index.get();
Austin Schuh20b2b082019-09-11 20:42:56 -0700881}
882
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700883LocklessQueueSender::~LocklessQueueSender() {
884 if (sender_index_ != -1) {
885 CHECK(memory_ != nullptr);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800886 death_notification_release(&(memory_->GetSender(sender_index_)->tid));
Austin Schuh20b2b082019-09-11 20:42:56 -0700887 }
888}
889
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700890std::optional<LocklessQueueSender> LocklessQueueSender::Make(
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700891 LocklessQueue queue, monotonic_clock::duration channel_storage_duration) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700892 queue.Initialize();
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700893 LocklessQueueSender result(queue.memory(), channel_storage_duration);
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700894 if (result.sender_index_ != -1) {
James Kuszmaul9776b392023-01-14 14:08:08 -0800895 return result;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700896 } else {
897 return std::nullopt;
898 }
899}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700900
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700901size_t LocklessQueueSender::size() const {
902 return memory_->message_data_size();
903}
904
905void *LocklessQueueSender::Data() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700906 ::aos::ipc_lib::Sender *sender = memory_->GetSender(sender_index_);
Brian Silverman177567e2020-08-12 19:51:33 -0700907 const Index scratch_index = sender->scratch_index.RelaxedLoad();
908 Message *const message = memory_->GetMessage(scratch_index);
909 // We should have invalidated this when we first got the buffer. Verify that
910 // in debug mode.
911 DCHECK(
912 !message->header.queue_index.RelaxedLoad(memory_->queue_size()).valid())
913 << ": " << std::hex << scratch_index.get();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700914
Brian Silvermana1652f32020-01-29 20:41:44 -0800915 return message->data(memory_->message_data_size());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700916}
917
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700918LocklessQueueSender::Result LocklessQueueSender::Send(
Austin Schuhad154822019-12-27 15:45:13 -0800919 const char *data, size_t length,
Austin Schuhb5c6f972021-03-14 21:53:07 -0700920 monotonic_clock::time_point monotonic_remote_time,
921 realtime_clock::time_point realtime_remote_time,
Austin Schuha9012be2021-07-21 15:19:11 -0700922 uint32_t remote_queue_index, const UUID &source_boot_uuid,
Austin Schuhb5c6f972021-03-14 21:53:07 -0700923 monotonic_clock::time_point *monotonic_sent_time,
924 realtime_clock::time_point *realtime_sent_time, uint32_t *queue_index) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700925 CHECK_LE(length, size());
Austin Schuh67420a42019-12-21 21:55:04 -0800926 // Flatbuffers write from the back of the buffer to the front. If we are
927 // going to write an explicit chunk of memory into the buffer, we need to
928 // adhere to this convention and place it at the end.
929 memcpy((reinterpret_cast<char *>(Data()) + size() - length), data, length);
Austin Schuh91ba6392020-10-03 13:27:47 -0700930 return Send(length, monotonic_remote_time, realtime_remote_time,
Austin Schuha9012be2021-07-21 15:19:11 -0700931 remote_queue_index, source_boot_uuid, monotonic_sent_time,
Austin Schuhb5c6f972021-03-14 21:53:07 -0700932 realtime_sent_time, queue_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700933}
934
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700935LocklessQueueSender::Result LocklessQueueSender::Send(
Austin Schuhb5c6f972021-03-14 21:53:07 -0700936 size_t length, monotonic_clock::time_point monotonic_remote_time,
937 realtime_clock::time_point realtime_remote_time,
Austin Schuha9012be2021-07-21 15:19:11 -0700938 uint32_t remote_queue_index, const UUID &source_boot_uuid,
Austin Schuhb5c6f972021-03-14 21:53:07 -0700939 monotonic_clock::time_point *monotonic_sent_time,
940 realtime_clock::time_point *realtime_sent_time, uint32_t *queue_index) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700941 const size_t queue_size = memory_->queue_size();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700942 CHECK_LE(length, size());
Austin Schuh20b2b082019-09-11 20:42:56 -0700943
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800944 ::aos::ipc_lib::Sender *const sender = memory_->GetSender(sender_index_);
945 // We can do a relaxed load on our sender because we're the only person
946 // modifying it right now.
947 const Index scratch_index = sender->scratch_index.RelaxedLoad();
948 Message *const message = memory_->GetMessage(scratch_index);
Austin Schuh91ba6392020-10-03 13:27:47 -0700949 if (CheckBothRedzones(memory_, message)) {
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700950 return Result::INVALID_REDZONE;
Austin Schuh91ba6392020-10-03 13:27:47 -0700951 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700952
Brian Silverman177567e2020-08-12 19:51:33 -0700953 // We should have invalidated this when we first got the buffer. Verify that
954 // in debug mode.
955 DCHECK(
956 !message->header.queue_index.RelaxedLoad(memory_->queue_size()).valid())
957 << ": " << std::hex << scratch_index.get();
958
Austin Schuh20b2b082019-09-11 20:42:56 -0700959 message->header.length = length;
Austin Schuhad154822019-12-27 15:45:13 -0800960 // Pass these through. Any alternative behavior can be implemented out a
961 // layer.
962 message->header.remote_queue_index = remote_queue_index;
Austin Schuha9012be2021-07-21 15:19:11 -0700963 message->header.source_boot_uuid = source_boot_uuid;
Austin Schuhad154822019-12-27 15:45:13 -0800964 message->header.monotonic_remote_time = monotonic_remote_time;
965 message->header.realtime_remote_time = realtime_remote_time;
Austin Schuh20b2b082019-09-11 20:42:56 -0700966
Brian Silverman177567e2020-08-12 19:51:33 -0700967 Index to_replace = Index::Invalid();
Austin Schuh20b2b082019-09-11 20:42:56 -0700968 while (true) {
969 const QueueIndex actual_next_queue_index =
970 memory_->next_queue_index.Load(queue_size);
971 const QueueIndex next_queue_index = ZeroOrValid(actual_next_queue_index);
972
973 const QueueIndex incremented_queue_index = next_queue_index.Increment();
974
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800975 // This needs to synchronize with whoever the previous writer at this
976 // location was.
Brian Silverman177567e2020-08-12 19:51:33 -0700977 to_replace = memory_->LoadIndex(next_queue_index);
Austin Schuh20b2b082019-09-11 20:42:56 -0700978
979 const QueueIndex decremented_queue_index =
980 next_queue_index.DecrementBy(queue_size);
981
982 // See if we got beat. If we did, try to atomically update
983 // next_queue_index in case the previous writer failed and retry.
984 if (!to_replace.IsPlausible(decremented_queue_index)) {
985 // We don't care about the result. It will either succeed, or we got
986 // beat in fixing it and just need to give up and try again. If we got
987 // beat multiple times, the only way progress can be made is if the queue
988 // is updated as well. This means that if we retry reading
989 // next_queue_index, we will be at most off by one and can retry.
990 //
991 // Both require no further action from us.
992 //
993 // TODO(austin): If we are having fairness issues under contention, we
994 // could have a mode bit in next_queue_index, and could use a lock or some
995 // other form of PI boosting to let the higher priority task win.
996 memory_->next_queue_index.CompareAndExchangeStrong(
997 actual_next_queue_index, incremented_queue_index);
998
Alex Perrycb7da4b2019-08-28 19:35:56 -0700999 VLOG(3) << "We were beat. Try again. Was " << std::hex
1000 << to_replace.get() << ", is " << decremented_queue_index.index();
Austin Schuh20b2b082019-09-11 20:42:56 -07001001 continue;
1002 }
1003
1004 // Confirm that the message is what it should be.
Brian Silverman177567e2020-08-12 19:51:33 -07001005 //
1006 // This is just a best-effort check to skip reading the clocks if possible.
1007 // If this fails, then the compare-exchange below definitely would, so we
1008 // can bail out now.
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001009 const Message *message_to_replace = memory_->GetMessage(to_replace);
1010 bool is_previous_index_valid = false;
Austin Schuh20b2b082019-09-11 20:42:56 -07001011 {
Austin Schuh20b2b082019-09-11 20:42:56 -07001012 const QueueIndex previous_index =
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001013 message_to_replace->header.queue_index.RelaxedLoad(queue_size);
1014 is_previous_index_valid = previous_index.valid();
1015 if (previous_index != decremented_queue_index &&
1016 is_previous_index_valid) {
Austin Schuh20b2b082019-09-11 20:42:56 -07001017 // Retry.
Alex Perrycb7da4b2019-08-28 19:35:56 -07001018 VLOG(3) << "Something fishy happened, queue index doesn't match. "
1019 "Retrying. Previous index was "
1020 << std::hex << previous_index.index() << ", should be "
1021 << decremented_queue_index.index();
Austin Schuh20b2b082019-09-11 20:42:56 -07001022 continue;
1023 }
1024 }
1025
1026 message->header.monotonic_sent_time = ::aos::monotonic_clock::now();
1027 message->header.realtime_sent_time = ::aos::realtime_clock::now();
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001028
Austin Schuhad154822019-12-27 15:45:13 -08001029 if (monotonic_sent_time != nullptr) {
1030 *monotonic_sent_time = message->header.monotonic_sent_time;
1031 }
1032 if (realtime_sent_time != nullptr) {
1033 *realtime_sent_time = message->header.realtime_sent_time;
1034 }
1035 if (queue_index != nullptr) {
1036 *queue_index = next_queue_index.index();
1037 }
Austin Schuh20b2b082019-09-11 20:42:56 -07001038
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001039 const auto to_replace_monotonic_sent_time =
1040 message_to_replace->header.monotonic_sent_time;
1041
1042 // If we are overwriting a message sent in the last
1043 // channel_storage_duration_, that means that we would be sending more than
1044 // queue_size messages and would therefore be sending too fast. If the
1045 // previous index is not valid then the message hasn't been filled out yet
1046 // so we aren't sending too fast. And, if it is not less than the sent time
1047 // of the message that we are going to write, someone else beat us and the
1048 // compare and exchange below will fail.
1049 if (is_previous_index_valid &&
1050 (to_replace_monotonic_sent_time <
1051 message->header.monotonic_sent_time) &&
1052 (message->header.monotonic_sent_time - to_replace_monotonic_sent_time <
1053 channel_storage_duration_)) {
1054 // There is a possibility that another context beat us to writing out the
1055 // message in the queue, but we beat that context to acquiring the sent
1056 // time. In this case our sent time is *greater than* the other context's
1057 // sent time. Therefore, we can check if we got beat filling out this
1058 // message *after* doing the above check to determine if we hit this edge
1059 // case. Otherwise, messages are being sent too fast.
1060 const QueueIndex previous_index =
1061 message_to_replace->header.queue_index.Load(queue_size);
1062 if (previous_index != decremented_queue_index && previous_index.valid()) {
1063 VLOG(3) << "Got beat during check for messages being sent too fast"
1064 "Retrying.";
1065 continue;
1066 } else {
Austin Schuh71e72142023-05-03 13:10:07 -07001067 VLOG(1) << "Messages sent too fast. Returning. Attempted index: "
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001068 << decremented_queue_index.index()
1069 << " message sent time: " << message->header.monotonic_sent_time
1070 << " message to replace sent time: "
1071 << to_replace_monotonic_sent_time;
Austin Schuh71e72142023-05-03 13:10:07 -07001072
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001073 // Since we are not using the message obtained from scratch_index
1074 // and we are not retrying, we need to invalidate its queue_index.
1075 message->header.queue_index.Invalidate();
1076 return Result::MESSAGES_SENT_TOO_FAST;
1077 }
1078 }
1079
Austin Schuh20b2b082019-09-11 20:42:56 -07001080 // Before we are fully done filling out the message, update the Sender state
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001081 // with the new index to write. This re-uses the barrier for the
Austin Schuh20b2b082019-09-11 20:42:56 -07001082 // queue_index store.
Alex Perrycb7da4b2019-08-28 19:35:56 -07001083 const Index index_to_write(next_queue_index, scratch_index.message_index());
Austin Schuh20b2b082019-09-11 20:42:56 -07001084
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001085 aos_compiler_memory_barrier();
1086 // We're the only person who cares about our scratch index, besides somebody
1087 // cleaning up after us.
Austin Schuh20b2b082019-09-11 20:42:56 -07001088 sender->scratch_index.RelaxedStore(index_to_write);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001089 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -07001090
1091 message->header.queue_index.Store(next_queue_index);
1092
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001093 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -07001094 // The message is now filled out, and we have a confirmed slot to store
1095 // into.
1096 //
1097 // Start by writing down what we are going to pull out of the queue. This
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001098 // was Invalid before now. Only person who will read this is whoever cleans
1099 // up after us, so no synchronization necessary.
Austin Schuh20b2b082019-09-11 20:42:56 -07001100 sender->to_replace.RelaxedStore(to_replace);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001101 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -07001102
1103 // Then exchange the next index into the queue.
1104 if (!memory_->GetQueue(next_queue_index.Wrapped())
1105 ->CompareAndExchangeStrong(to_replace, index_to_write)) {
1106 // Aw, didn't succeed. Retry.
1107 sender->to_replace.RelaxedInvalidate();
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001108 aos_compiler_memory_barrier();
Alex Perrycb7da4b2019-08-28 19:35:56 -07001109 VLOG(3) << "Failed to wrap into queue";
Austin Schuh20b2b082019-09-11 20:42:56 -07001110 continue;
1111 }
1112
1113 // Then update next_queue_index to save the next user some computation time.
1114 memory_->next_queue_index.CompareAndExchangeStrong(actual_next_queue_index,
1115 incremented_queue_index);
1116
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001117 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -07001118 // Now update the scratch space and record that we succeeded.
1119 sender->scratch_index.Store(to_replace);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001120 aos_compiler_memory_barrier();
1121 // And then record that we succeeded, but definitely after the above store.
Austin Schuh20b2b082019-09-11 20:42:56 -07001122 sender->to_replace.RelaxedInvalidate();
Brian Silverman177567e2020-08-12 19:51:33 -07001123
Austin Schuh20b2b082019-09-11 20:42:56 -07001124 break;
1125 }
Brian Silverman177567e2020-08-12 19:51:33 -07001126
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001127 DCHECK(!CheckBothRedzones(memory_, memory_->GetMessage(to_replace)))
1128 << ": Invalid message found in shared memory";
Brian Silverman177567e2020-08-12 19:51:33 -07001129 // to_replace is our current scratch_index. It isn't in the queue, which means
1130 // nobody new can pin it. They can set their `pinned` to it, but they will
1131 // back it out, so they don't count. This means that we just need to find a
1132 // message for which no pinner had it in `pinned`, and then we know this
1133 // message will never be pinned. We'll start with to_replace, and if that is
1134 // pinned then we'll look for a new one to use instead.
1135 const Index new_scratch =
1136 SwapPinnedSenderScratch(memory_, sender, to_replace);
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001137 DCHECK(!CheckBothRedzones(
1138 memory_, memory_->GetMessage(sender->scratch_index.RelaxedLoad())))
1139 << ": Invalid message found in shared memory";
Brian Silverman177567e2020-08-12 19:51:33 -07001140
1141 // If anybody is looking at this message (they shouldn't be), then try telling
1142 // them about it (best-effort).
1143 memory_->GetMessage(new_scratch)->header.queue_index.RelaxedInvalidate();
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001144 return Result::GOOD;
Austin Schuh20b2b082019-09-11 20:42:56 -07001145}
1146
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001147int LocklessQueueSender::buffer_index() const {
Brian Silverman4f4e0612020-08-12 19:54:41 -07001148 ::aos::ipc_lib::Sender *const sender = memory_->GetSender(sender_index_);
1149 // We can do a relaxed load on our sender because we're the only person
1150 // modifying it right now.
1151 const Index scratch_index = sender->scratch_index.RelaxedLoad();
1152 return scratch_index.message_index();
1153}
1154
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001155LocklessQueuePinner::LocklessQueuePinner(
1156 LocklessQueueMemory *memory, const LocklessQueueMemory *const_memory)
1157 : memory_(memory), const_memory_(const_memory) {
1158 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory_);
1159
1160 // Since we already have the lock, go ahead and try cleaning up.
1161 Cleanup(memory_, grab_queue_setup_lock);
1162
1163 const int num_pinners = memory_->num_pinners();
1164
1165 for (int i = 0; i < num_pinners; ++i) {
1166 ::aos::ipc_lib::Pinner *p = memory->GetPinner(i);
1167 // This doesn't need synchronization because we're the only process doing
1168 // initialization right now, and nobody else will be touching pinners which
1169 // we're interested in.
1170 const uint32_t tid = __atomic_load_n(&(p->tid.futex), __ATOMIC_RELAXED);
1171 if (tid == 0) {
1172 pinner_index_ = i;
1173 break;
1174 }
1175 }
1176
1177 if (pinner_index_ == -1) {
1178 VLOG(1) << "Too many pinners, starting to bail.";
1179 return;
1180 }
1181
1182 ::aos::ipc_lib::Pinner *p = memory_->GetPinner(pinner_index_);
1183 p->pinned.Invalidate();
1184
1185 // Indicate that we are now alive by taking over the slot. If the previous
1186 // owner died, we still want to do this.
1187 death_notification_init(&(p->tid));
1188}
1189
1190LocklessQueuePinner::~LocklessQueuePinner() {
1191 if (pinner_index_ != -1) {
1192 CHECK(memory_ != nullptr);
1193 memory_->GetPinner(pinner_index_)->pinned.Invalidate();
1194 aos_compiler_memory_barrier();
1195 death_notification_release(&(memory_->GetPinner(pinner_index_)->tid));
1196 }
1197}
1198
1199std::optional<LocklessQueuePinner> LocklessQueuePinner::Make(
1200 LocklessQueue queue) {
1201 queue.Initialize();
1202 LocklessQueuePinner result(queue.memory(), queue.const_memory());
1203 if (result.pinner_index_ != -1) {
James Kuszmaul9776b392023-01-14 14:08:08 -08001204 return result;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001205 } else {
1206 return std::nullopt;
1207 }
1208}
1209
1210// This method doesn't mess with any scratch_index, so it doesn't have to worry
1211// about message ownership.
1212int LocklessQueuePinner::PinIndex(uint32_t uint32_queue_index) {
1213 const size_t queue_size = memory_->queue_size();
1214 const QueueIndex queue_index =
1215 QueueIndex::Zero(queue_size).IncrementBy(uint32_queue_index);
1216 ipc_lib::Pinner *const pinner = memory_->GetPinner(pinner_index_);
1217
1218 AtomicIndex *const queue_slot = memory_->GetQueue(queue_index.Wrapped());
1219
1220 // Indicate that we want to pin this message.
1221 pinner->pinned.Store(queue_index);
1222 aos_compiler_memory_barrier();
1223
1224 {
1225 const Index message_index = queue_slot->Load();
1226 Message *const message = memory_->GetMessage(message_index);
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001227 DCHECK(!CheckBothRedzones(memory_, message))
1228 << ": Invalid message found in shared memory";
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001229
1230 const QueueIndex message_queue_index =
1231 message->header.queue_index.Load(queue_size);
1232 if (message_queue_index == queue_index) {
1233 VLOG(3) << "Eq: " << std::hex << message_queue_index.index();
1234 aos_compiler_memory_barrier();
1235 return message_index.message_index();
1236 }
1237 VLOG(3) << "Message reused: " << std::hex << message_queue_index.index()
1238 << ", " << queue_index.index();
1239 }
1240
1241 // Being down here means we asked to pin a message before realizing it's no
1242 // longer in the queue, so back that out now.
1243 pinner->pinned.Invalidate();
1244 VLOG(3) << "Unpinned: " << std::hex << queue_index.index();
1245 return -1;
1246}
1247
1248size_t LocklessQueuePinner::size() const {
1249 return const_memory_->message_data_size();
1250}
1251
1252const void *LocklessQueuePinner::Data() const {
1253 const size_t queue_size = const_memory_->queue_size();
1254 const ::aos::ipc_lib::Pinner *const pinner =
1255 const_memory_->GetPinner(pinner_index_);
1256 QueueIndex pinned = pinner->pinned.RelaxedLoad(queue_size);
1257 CHECK(pinned.valid());
1258 const Message *message = const_memory_->GetMessage(pinned);
1259
1260 return message->data(const_memory_->message_data_size());
1261}
1262
1263LocklessQueueReader::Result LocklessQueueReader::Read(
Austin Schuh20b2b082019-09-11 20:42:56 -07001264 uint32_t uint32_queue_index,
Austin Schuhb5c6f972021-03-14 21:53:07 -07001265 monotonic_clock::time_point *monotonic_sent_time,
1266 realtime_clock::time_point *realtime_sent_time,
1267 monotonic_clock::time_point *monotonic_remote_time,
1268 realtime_clock::time_point *realtime_remote_time,
Austin Schuha9012be2021-07-21 15:19:11 -07001269 uint32_t *remote_queue_index, UUID *source_boot_uuid, size_t *length,
Austin Schuhb5c6f972021-03-14 21:53:07 -07001270 char *data) const {
Austin Schuh20b2b082019-09-11 20:42:56 -07001271 const size_t queue_size = memory_->queue_size();
1272
1273 // Build up the QueueIndex.
1274 const QueueIndex queue_index =
1275 QueueIndex::Zero(queue_size).IncrementBy(uint32_queue_index);
1276
1277 // Read the message stored at the requested location.
1278 Index mi = memory_->LoadIndex(queue_index);
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001279 const Message *m = memory_->GetMessage(mi);
Austin Schuh20b2b082019-09-11 20:42:56 -07001280
1281 while (true) {
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001282 DCHECK(!CheckBothRedzones(memory_, m))
1283 << ": Invalid message found in shared memory";
Austin Schuh20b2b082019-09-11 20:42:56 -07001284 // We need to confirm that the data doesn't change while we are reading it.
1285 // Do that by first confirming that the message points to the queue index we
1286 // want.
1287 const QueueIndex starting_queue_index =
1288 m->header.queue_index.Load(queue_size);
1289 if (starting_queue_index != queue_index) {
1290 // If we found a message that is exactly 1 loop old, we just wrapped.
1291 if (starting_queue_index == queue_index.DecrementBy(queue_size)) {
Alex Perrycb7da4b2019-08-28 19:35:56 -07001292 VLOG(3) << "Matches: " << std::hex << starting_queue_index.index()
1293 << ", " << queue_index.DecrementBy(queue_size).index();
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001294 return Result::NOTHING_NEW;
Brian Silverman177567e2020-08-12 19:51:33 -07001295 }
1296
1297 // Someone has re-used this message between when we pulled it out of the
1298 // queue and when we grabbed its index. It is pretty hard to deduce
1299 // what happened. Just try again.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001300 const Message *const new_m = memory_->GetMessage(queue_index);
Brian Silverman177567e2020-08-12 19:51:33 -07001301 if (m != new_m) {
1302 m = new_m;
1303 VLOG(3) << "Retrying, m doesn't match";
1304 continue;
1305 }
1306
1307 // We have confirmed that message still points to the same message. This
1308 // means that the message didn't get swapped out from under us, so
1309 // starting_queue_index is correct.
1310 //
1311 // Either we got too far behind (signaled by this being a valid
1312 // message), or this is one of the initial messages which are invalid.
1313 if (starting_queue_index.valid()) {
1314 VLOG(3) << "Too old. Tried for " << std::hex << queue_index.index()
1315 << ", got " << starting_queue_index.index() << ", behind by "
1316 << std::dec
1317 << (starting_queue_index.index() - queue_index.index());
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001318 return Result::TOO_OLD;
Brian Silverman177567e2020-08-12 19:51:33 -07001319 }
1320
1321 VLOG(3) << "Initial";
1322
1323 // There isn't a valid message at this location.
1324 //
1325 // If someone asks for one of the messages within the first go around,
1326 // then they need to wait. They got ahead. Otherwise, they are
1327 // asking for something crazy, like something before the beginning of
1328 // the queue. Tell them that they are behind.
1329 if (uint32_queue_index < memory_->queue_size()) {
1330 VLOG(3) << "Near zero, " << std::hex << uint32_queue_index;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001331 return Result::NOTHING_NEW;
Austin Schuh20b2b082019-09-11 20:42:56 -07001332 } else {
Brian Silverman177567e2020-08-12 19:51:33 -07001333 VLOG(3) << "Not near zero, " << std::hex << uint32_queue_index;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001334 return Result::TOO_OLD;
Austin Schuh20b2b082019-09-11 20:42:56 -07001335 }
1336 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001337 VLOG(3) << "Eq: " << std::hex << starting_queue_index.index() << ", "
1338 << queue_index.index();
Austin Schuh20b2b082019-09-11 20:42:56 -07001339 break;
1340 }
1341
Alex Perrycb7da4b2019-08-28 19:35:56 -07001342 // Then read the data out. Copy it all out to be deterministic and so we can
1343 // make length be from either end.
Austin Schuh20b2b082019-09-11 20:42:56 -07001344 *monotonic_sent_time = m->header.monotonic_sent_time;
1345 *realtime_sent_time = m->header.realtime_sent_time;
Austin Schuhad154822019-12-27 15:45:13 -08001346 if (m->header.remote_queue_index == 0xffffffffu) {
1347 *remote_queue_index = queue_index.index();
1348 } else {
1349 *remote_queue_index = m->header.remote_queue_index;
1350 }
1351 *monotonic_remote_time = m->header.monotonic_remote_time;
1352 *realtime_remote_time = m->header.realtime_remote_time;
Austin Schuha9012be2021-07-21 15:19:11 -07001353 *source_boot_uuid = m->header.source_boot_uuid;
Brian Silverman6b8a3c32020-03-06 11:26:14 -08001354 if (data) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001355 memcpy(data, m->data(memory_->message_data_size()),
1356 memory_->message_data_size());
Brian Silverman6b8a3c32020-03-06 11:26:14 -08001357 }
Austin Schuh20b2b082019-09-11 20:42:56 -07001358 *length = m->header.length;
1359
1360 // And finally, confirm that the message *still* points to the queue index we
1361 // want. This means it didn't change out from under us.
1362 // If something changed out from under us, we were reading it much too late in
1363 // it's lifetime.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001364 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -07001365 const QueueIndex final_queue_index = m->header.queue_index.Load(queue_size);
1366 if (final_queue_index != queue_index) {
Alex Perrycb7da4b2019-08-28 19:35:56 -07001367 VLOG(3) << "Changed out from under us. Reading " << std::hex
1368 << queue_index.index() << ", finished with "
1369 << final_queue_index.index() << ", delta: " << std::dec
1370 << (final_queue_index.index() - queue_index.index());
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001371 return Result::OVERWROTE;
Austin Schuh20b2b082019-09-11 20:42:56 -07001372 }
1373
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001374 return Result::GOOD;
Austin Schuh20b2b082019-09-11 20:42:56 -07001375}
1376
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001377QueueIndex LocklessQueueReader::LatestIndex() const {
Austin Schuh20b2b082019-09-11 20:42:56 -07001378 const size_t queue_size = memory_->queue_size();
1379
1380 // There is only one interesting case. We need to know if the queue is empty.
1381 // That is done with a sentinel value. At worst, this will be off by one.
1382 const QueueIndex next_queue_index =
1383 memory_->next_queue_index.Load(queue_size);
1384 if (next_queue_index.valid()) {
1385 const QueueIndex current_queue_index = next_queue_index.DecrementBy(1u);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001386 return current_queue_index;
Austin Schuh20b2b082019-09-11 20:42:56 -07001387 }
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001388 return QueueIndex::Invalid();
1389}
1390
1391size_t LocklessQueueSize(const LocklessQueueMemory *memory) {
1392 return memory->queue_size();
1393}
1394
1395size_t LocklessQueueMessageDataSize(const LocklessQueueMemory *memory) {
1396 return memory->message_data_size();
Austin Schuh20b2b082019-09-11 20:42:56 -07001397}
1398
1399namespace {
1400
1401// Prints out the mutex state. Not safe to use while the mutex is being
1402// changed.
1403::std::string PrintMutex(aos_mutex *mutex) {
1404 ::std::stringstream s;
1405 s << "aos_mutex(" << ::std::hex << mutex->futex;
1406
1407 if (mutex->futex != 0) {
1408 s << ":";
1409 if (mutex->futex & FUTEX_OWNER_DIED) {
1410 s << "FUTEX_OWNER_DIED|";
1411 }
1412 s << "tid=" << (mutex->futex & FUTEX_TID_MASK);
1413 }
1414
1415 s << ")";
1416 return s.str();
1417}
1418
1419} // namespace
1420
1421void PrintLocklessQueueMemory(LocklessQueueMemory *memory) {
1422 const size_t queue_size = memory->queue_size();
1423 ::std::cout << "LocklessQueueMemory (" << memory << ") {" << ::std::endl;
1424 ::std::cout << " aos_mutex queue_setup_lock = "
1425 << PrintMutex(&memory->queue_setup_lock) << ::std::endl;
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001426 ::std::cout << " bool initialized = " << memory->initialized << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001427 ::std::cout << " config {" << ::std::endl;
1428 ::std::cout << " size_t num_watchers = " << memory->config.num_watchers
1429 << ::std::endl;
1430 ::std::cout << " size_t num_senders = " << memory->config.num_senders
1431 << ::std::endl;
Brian Silverman177567e2020-08-12 19:51:33 -07001432 ::std::cout << " size_t num_pinners = " << memory->config.num_pinners
1433 << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001434 ::std::cout << " size_t queue_size = " << memory->config.queue_size
1435 << ::std::endl;
1436 ::std::cout << " size_t message_data_size = "
1437 << memory->config.message_data_size << ::std::endl;
1438
1439 ::std::cout << " AtomicQueueIndex next_queue_index = "
1440 << memory->next_queue_index.Load(queue_size).DebugString()
1441 << ::std::endl;
1442
Austin Schuh3328d132020-02-28 13:54:57 -08001443 ::std::cout << " uid_t uid = " << memory->uid << ::std::endl;
1444
Austin Schuh20b2b082019-09-11 20:42:56 -07001445 ::std::cout << " }" << ::std::endl;
1446 ::std::cout << " AtomicIndex queue[" << queue_size << "] {" << ::std::endl;
1447 for (size_t i = 0; i < queue_size; ++i) {
1448 ::std::cout << " [" << i << "] -> "
1449 << memory->GetQueue(i)->Load().DebugString() << ::std::endl;
1450 }
1451 ::std::cout << " }" << ::std::endl;
1452 ::std::cout << " Message messages[" << memory->num_messages() << "] {"
1453 << ::std::endl;
1454 for (size_t i = 0; i < memory->num_messages(); ++i) {
1455 Message *m = memory->GetMessage(Index(i, i));
Brian Silverman001f24d2020-08-12 19:33:20 -07001456 ::std::cout << " [" << i << "] -> Message 0x" << std::hex
1457 << (reinterpret_cast<uintptr_t>(
1458 memory->GetMessage(Index(i, i))) -
1459 reinterpret_cast<uintptr_t>(memory))
1460 << std::dec << " {" << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001461 ::std::cout << " Header {" << ::std::endl;
1462 ::std::cout << " AtomicQueueIndex queue_index = "
1463 << m->header.queue_index.Load(queue_size).DebugString()
1464 << ::std::endl;
Brian Silverman001f24d2020-08-12 19:33:20 -07001465 ::std::cout << " monotonic_clock::time_point monotonic_sent_time = "
1466 << m->header.monotonic_sent_time << " 0x" << std::hex
1467 << m->header.monotonic_sent_time.time_since_epoch().count()
1468 << std::dec << ::std::endl;
1469 ::std::cout << " realtime_clock::time_point realtime_sent_time = "
1470 << m->header.realtime_sent_time << " 0x" << std::hex
1471 << m->header.realtime_sent_time.time_since_epoch().count()
1472 << std::dec << ::std::endl;
1473 ::std::cout
1474 << " monotonic_clock::time_point monotonic_remote_time = "
1475 << m->header.monotonic_remote_time << " 0x" << std::hex
1476 << m->header.monotonic_remote_time.time_since_epoch().count()
1477 << std::dec << ::std::endl;
1478 ::std::cout << " realtime_clock::time_point realtime_remote_time = "
1479 << m->header.realtime_remote_time << " 0x" << std::hex
1480 << m->header.realtime_remote_time.time_since_epoch().count()
1481 << std::dec << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001482 ::std::cout << " size_t length = " << m->header.length
1483 << ::std::endl;
1484 ::std::cout << " }" << ::std::endl;
Austin Schuhbe416742020-10-03 17:24:26 -07001485 const bool corrupt = CheckBothRedzones(memory, m);
1486 if (corrupt) {
1487 absl::Span<char> pre_redzone = m->PreRedzone(memory->message_data_size());
1488 absl::Span<char> post_redzone =
1489 m->PostRedzone(memory->message_data_size(), memory->message_size());
1490
1491 ::std::cout << " pre-redzone: \""
1492 << absl::BytesToHexString(std::string_view(
1493 pre_redzone.data(), pre_redzone.size()))
1494 << std::endl;
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001495 ::std::cout << " // *** DATA REDZONES ARE CORRUPTED ***"
1496 << ::std::endl;
Austin Schuhbe416742020-10-03 17:24:26 -07001497 ::std::cout << " post-redzone: \""
1498 << absl::BytesToHexString(std::string_view(
1499 post_redzone.data(), post_redzone.size()))
1500 << std::endl;
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001501 }
Austin Schuh20b2b082019-09-11 20:42:56 -07001502 ::std::cout << " data: {";
1503
Brian Silverman001f24d2020-08-12 19:33:20 -07001504 if (FLAGS_dump_lockless_queue_data) {
1505 const char *const m_data = m->data(memory->message_data_size());
Austin Schuhbe416742020-10-03 17:24:26 -07001506 std::cout << absl::BytesToHexString(std::string_view(
1507 m_data, corrupt ? memory->message_data_size() : m->header.length));
Austin Schuh20b2b082019-09-11 20:42:56 -07001508 }
1509 ::std::cout << ::std::setfill(' ') << ::std::dec << "}" << ::std::endl;
1510 ::std::cout << " }," << ::std::endl;
1511 }
1512 ::std::cout << " }" << ::std::endl;
1513
Alex Perrycb7da4b2019-08-28 19:35:56 -07001514 ::std::cout << " Sender senders[" << memory->num_senders() << "] {"
1515 << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001516 for (size_t i = 0; i < memory->num_senders(); ++i) {
1517 Sender *s = memory->GetSender(i);
1518 ::std::cout << " [" << i << "] -> Sender {" << ::std::endl;
1519 ::std::cout << " aos_mutex tid = " << PrintMutex(&s->tid)
1520 << ::std::endl;
1521 ::std::cout << " AtomicIndex scratch_index = "
1522 << s->scratch_index.Load().DebugString() << ::std::endl;
1523 ::std::cout << " AtomicIndex to_replace = "
1524 << s->to_replace.Load().DebugString() << ::std::endl;
1525 ::std::cout << " }" << ::std::endl;
1526 }
1527 ::std::cout << " }" << ::std::endl;
1528
Brian Silverman177567e2020-08-12 19:51:33 -07001529 ::std::cout << " Pinner pinners[" << memory->num_pinners() << "] {"
1530 << ::std::endl;
1531 for (size_t i = 0; i < memory->num_pinners(); ++i) {
1532 Pinner *p = memory->GetPinner(i);
1533 ::std::cout << " [" << i << "] -> Pinner {" << ::std::endl;
1534 ::std::cout << " aos_mutex tid = " << PrintMutex(&p->tid)
1535 << ::std::endl;
1536 ::std::cout << " AtomicIndex scratch_index = "
1537 << p->scratch_index.Load().DebugString() << ::std::endl;
1538 ::std::cout << " AtomicIndex pinned = "
1539 << p->pinned.Load(memory->queue_size()).DebugString()
1540 << ::std::endl;
1541 ::std::cout << " }" << ::std::endl;
1542 }
1543 ::std::cout << " }" << ::std::endl;
1544
Austin Schuh20b2b082019-09-11 20:42:56 -07001545 ::std::cout << " Watcher watchers[" << memory->num_watchers() << "] {"
1546 << ::std::endl;
1547 for (size_t i = 0; i < memory->num_watchers(); ++i) {
1548 Watcher *w = memory->GetWatcher(i);
1549 ::std::cout << " [" << i << "] -> Watcher {" << ::std::endl;
1550 ::std::cout << " aos_mutex tid = " << PrintMutex(&w->tid)
1551 << ::std::endl;
1552 ::std::cout << " pid_t pid = " << w->pid << ::std::endl;
1553 ::std::cout << " int priority = " << w->priority << ::std::endl;
1554 ::std::cout << " }" << ::std::endl;
1555 }
1556 ::std::cout << " }" << ::std::endl;
1557
1558 ::std::cout << "}" << ::std::endl;
1559}
1560
1561} // namespace ipc_lib
1562} // namespace aos