blob: 9a53eb04cb1596f519701afe17275a935a1beb0e [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.
Austin Schuh83cbb1e2023-06-23 12:59:02 -0700630 s->scratch_index.RelaxedStore(
631 Index(QueueIndex::Invalid(), i + memory->queue_size()));
Austin Schuh20b2b082019-09-11 20:42:56 -0700632 s->to_replace.RelaxedInvalidate();
633 }
634
Brian Silverman177567e2020-08-12 19:51:33 -0700635 for (size_t i = 0; i < memory->num_pinners(); ++i) {
636 ::aos::ipc_lib::Pinner *pinner = memory->GetPinner(i);
637 // Nobody else can possibly be touching these because we haven't set
638 // initialized to true yet.
639 pinner->scratch_index.RelaxedStore(
Austin Schuh83cbb1e2023-06-23 12:59:02 -0700640 Index(QueueIndex::Invalid(),
641 i + memory->num_senders() + memory->queue_size()));
Brian Silverman177567e2020-08-12 19:51:33 -0700642 pinner->pinned.Invalidate();
643 }
644
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800645 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -0700646 // Signal everything is done. This needs to be done last, so if we die, we
647 // redo initialization.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800648 memory->initialized = true;
Austin Schuh3328d132020-02-28 13:54:57 -0800649 } else {
Brian Silvermanc57ff0a2020-04-28 16:45:13 -0700650 CHECK_EQ(uid, memory->uid) << ": UIDs must match for all processes";
Austin Schuh20b2b082019-09-11 20:42:56 -0700651 }
652
Austin Schuh20b2b082019-09-11 20:42:56 -0700653 return memory;
654}
655
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700656void LocklessQueue::Initialize() {
657 InitializeLocklessQueueMemory(memory_, config_);
658}
Austin Schuh20b2b082019-09-11 20:42:56 -0700659
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700660LocklessQueueWatcher::~LocklessQueueWatcher() {
661 if (watcher_index_ == -1) {
662 return;
663 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700664
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700665 // Since everything is self consistent, all we need to do is make sure nobody
666 // else is running. Someone dying will get caught in the generic consistency
667 // check.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800668 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory_);
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700669
670 // Make sure we are registered.
671 CHECK_NE(watcher_index_, -1);
672
673 // Make sure we still own the slot we are supposed to.
674 CHECK(
675 death_notification_is_held(&(memory_->GetWatcher(watcher_index_)->tid)));
676
677 // The act of unlocking invalidates the entry. Invalidate it.
678 death_notification_release(&(memory_->GetWatcher(watcher_index_)->tid));
679 // And internally forget the slot.
680 watcher_index_ = -1;
681
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800682 // Cleanup is cheap. The next user will do it anyways, so no need for us to do
683 // anything right now.
Austin Schuh20b2b082019-09-11 20:42:56 -0700684
685 // And confirm that nothing is owned by us.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700686 const int num_watchers = memory_->num_watchers();
Austin Schuh20b2b082019-09-11 20:42:56 -0700687 for (int i = 0; i < num_watchers; ++i) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700688 CHECK(!death_notification_is_held(&(memory_->GetWatcher(i)->tid)))
689 << ": " << i;
Austin Schuh20b2b082019-09-11 20:42:56 -0700690 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700691}
692
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700693std::optional<LocklessQueueWatcher> LocklessQueueWatcher::Make(
694 LocklessQueue queue, int priority) {
695 queue.Initialize();
696 LocklessQueueWatcher result(queue.memory(), priority);
697 if (result.watcher_index_ != -1) {
James Kuszmaul9776b392023-01-14 14:08:08 -0800698 return result;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700699 } else {
700 return std::nullopt;
701 }
702}
Austin Schuh20b2b082019-09-11 20:42:56 -0700703
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700704LocklessQueueWatcher::LocklessQueueWatcher(LocklessQueueMemory *memory,
705 int priority)
706 : memory_(memory) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700707 // TODO(austin): Make sure signal coalescing is turned on. We don't need
708 // duplicates. That will improve performance under high load.
709
710 // Since everything is self consistent, all we need to do is make sure nobody
711 // else is running. Someone dying will get caught in the generic consistency
712 // check.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800713 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory_);
Austin Schuh20b2b082019-09-11 20:42:56 -0700714 const int num_watchers = memory_->num_watchers();
715
716 // Now, find the first empty watcher and grab it.
717 CHECK_EQ(watcher_index_, -1);
718 for (int i = 0; i < num_watchers; ++i) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800719 // If we see a slot the kernel has marked as dead, everything we do reusing
720 // it needs to happen-after whatever that process did before dying.
Brian Silverman2484eea2019-12-21 16:48:46 -0800721 auto *const futex = &(memory_->GetWatcher(i)->tid.futex);
722 const uint32_t tid = __atomic_load_n(futex, __ATOMIC_ACQUIRE);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800723 if (tid == 0 || (tid & FUTEX_OWNER_DIED)) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700724 watcher_index_ = i;
Brian Silverman2484eea2019-12-21 16:48:46 -0800725 // Relaxed is OK here because we're the only task going to touch it
726 // between here and the write in death_notification_init below (other
727 // recovery is blocked by us holding the setup lock).
728 __atomic_store_n(futex, 0, __ATOMIC_RELAXED);
Austin Schuh20b2b082019-09-11 20:42:56 -0700729 break;
730 }
731 }
732
733 // Bail if we failed to find an open slot.
734 if (watcher_index_ == -1) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700735 return;
Austin Schuh20b2b082019-09-11 20:42:56 -0700736 }
737
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700738 Watcher *const w = memory_->GetWatcher(watcher_index_);
Austin Schuh20b2b082019-09-11 20:42:56 -0700739
740 w->pid = getpid();
741 w->priority = priority;
742
743 // Grabbing a mutex is a compiler and memory barrier, so nothing before will
744 // get rearranged afterwords.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800745 death_notification_init(&(w->tid));
Austin Schuh20b2b082019-09-11 20:42:56 -0700746}
747
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700748LocklessQueueWakeUpper::LocklessQueueWakeUpper(LocklessQueue queue)
749 : memory_(queue.const_memory()), pid_(getpid()), uid_(getuid()) {
750 queue.Initialize();
751 watcher_copy_.resize(memory_->num_watchers());
Austin Schuh20b2b082019-09-11 20:42:56 -0700752}
753
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700754int LocklessQueueWakeUpper::Wakeup(const int current_priority) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700755 const size_t num_watchers = memory_->num_watchers();
756
757 CHECK_EQ(watcher_copy_.size(), num_watchers);
758
759 // Grab a copy so it won't change out from underneath us, and we can sort it
760 // nicely in C++.
761 // Do note that there is still a window where the process can die *after* we
762 // read everything. We will still PI boost and send a signal to the thread in
763 // question. There is no way without pidfd's to close this window, and
764 // creating a pidfd is likely not RT.
765 for (size_t i = 0; i < num_watchers; ++i) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700766 const Watcher *w = memory_->GetWatcher(i);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800767 watcher_copy_[i].tid = __atomic_load_n(&(w->tid.futex), __ATOMIC_RELAXED);
768 // Force the load of the TID to come first.
769 aos_compiler_memory_barrier();
770 watcher_copy_[i].pid = w->pid.load(std::memory_order_relaxed);
771 watcher_copy_[i].priority = w->priority.load(std::memory_order_relaxed);
Austin Schuh20b2b082019-09-11 20:42:56 -0700772
773 // Use a priority of -1 to mean an invalid entry to make sorting easier.
774 if (watcher_copy_[i].tid & FUTEX_OWNER_DIED || watcher_copy_[i].tid == 0) {
775 watcher_copy_[i].priority = -1;
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800776 } else {
777 // Ensure all of this happens after we're done looking at the pid+priority
778 // in shared memory.
779 aos_compiler_memory_barrier();
780 if (watcher_copy_[i].tid != static_cast<pid_t>(__atomic_load_n(
781 &(w->tid.futex), __ATOMIC_RELAXED))) {
782 // Confirm that the watcher hasn't been re-used and modified while we
783 // read it. If it has, mark it invalid again.
784 watcher_copy_[i].priority = -1;
785 watcher_copy_[i].tid = 0;
786 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700787 }
788 }
789
790 // Now sort.
791 ::std::sort(watcher_copy_.begin(), watcher_copy_.end(),
792 [](const WatcherCopy &a, const WatcherCopy &b) {
793 return a.priority > b.priority;
794 });
795
796 int count = 0;
797 if (watcher_copy_[0].priority != -1) {
798 const int max_priority =
799 ::std::max(current_priority, watcher_copy_[0].priority);
800 // Boost if we are RT and there is a higher priority sender out there.
801 // Otherwise we might run into priority inversions.
802 if (max_priority > current_priority && current_priority > 0) {
803 SetCurrentThreadRealtimePriority(max_priority);
804 }
805
806 // Build up the siginfo to send.
807 siginfo_t uinfo;
808 memset(&uinfo, 0, sizeof(uinfo));
809
810 uinfo.si_code = SI_QUEUE;
811 uinfo.si_pid = pid_;
812 uinfo.si_uid = uid_;
813 uinfo.si_value.sival_int = 0;
814
815 for (const WatcherCopy &watcher_copy : watcher_copy_) {
816 // The first -1 priority means we are at the end of the valid list.
817 if (watcher_copy.priority == -1) {
818 break;
819 }
820
821 // Send the signal. Target just the thread that sent it so that we can
822 // support multiple watchers in a process (when someone creates multiple
823 // event loops in different threads).
824 rt_tgsigqueueinfo(watcher_copy.pid, watcher_copy.tid, kWakeupSignal,
825 &uinfo);
826
827 ++count;
828 }
829
830 // Drop back down if we were boosted.
831 if (max_priority > current_priority && current_priority > 0) {
832 SetCurrentThreadRealtimePriority(current_priority);
833 }
834 }
835
836 return count;
837}
838
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700839std::ostream &operator<<(std::ostream &os,
840 const LocklessQueueSender::Result r) {
841 os << static_cast<int>(r);
842 return os;
843}
844
845LocklessQueueSender::LocklessQueueSender(
846 LocklessQueueMemory *memory,
847 monotonic_clock::duration channel_storage_duration)
848 : memory_(memory), channel_storage_duration_(channel_storage_duration) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800849 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory_);
Austin Schuh20b2b082019-09-11 20:42:56 -0700850
851 // Since we already have the lock, go ahead and try cleaning up.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800852 Cleanup(memory_, grab_queue_setup_lock);
Austin Schuh20b2b082019-09-11 20:42:56 -0700853
854 const int num_senders = memory_->num_senders();
855
856 for (int i = 0; i < num_senders; ++i) {
857 ::aos::ipc_lib::Sender *s = memory->GetSender(i);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800858 // This doesn't need synchronization because we're the only process doing
859 // initialization right now, and nobody else will be touching senders which
860 // we're interested in.
Austin Schuh20b2b082019-09-11 20:42:56 -0700861 const uint32_t tid = __atomic_load_n(&(s->tid.futex), __ATOMIC_RELAXED);
862 if (tid == 0) {
863 sender_index_ = i;
864 break;
865 }
866 }
867
868 if (sender_index_ == -1) {
Austin Schuhe516ab02020-05-06 21:37:04 -0700869 VLOG(1) << "Too many senders, starting to bail.";
870 return;
Austin Schuh20b2b082019-09-11 20:42:56 -0700871 }
872
Brian Silverman177567e2020-08-12 19:51:33 -0700873 ::aos::ipc_lib::Sender *const sender = memory_->GetSender(sender_index_);
Austin Schuh20b2b082019-09-11 20:42:56 -0700874
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800875 // Indicate that we are now alive by taking over the slot. If the previous
876 // owner died, we still want to do this.
Brian Silverman177567e2020-08-12 19:51:33 -0700877 death_notification_init(&(sender->tid));
878
879 const Index scratch_index = sender->scratch_index.RelaxedLoad();
880 Message *const message = memory_->GetMessage(scratch_index);
881 CHECK(!message->header.queue_index.RelaxedLoad(memory_->queue_size()).valid())
882 << ": " << std::hex << scratch_index.get();
Austin Schuh20b2b082019-09-11 20:42:56 -0700883}
884
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700885LocklessQueueSender::~LocklessQueueSender() {
886 if (sender_index_ != -1) {
887 CHECK(memory_ != nullptr);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800888 death_notification_release(&(memory_->GetSender(sender_index_)->tid));
Austin Schuh20b2b082019-09-11 20:42:56 -0700889 }
890}
891
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700892std::optional<LocklessQueueSender> LocklessQueueSender::Make(
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700893 LocklessQueue queue, monotonic_clock::duration channel_storage_duration) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700894 queue.Initialize();
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700895 LocklessQueueSender result(queue.memory(), channel_storage_duration);
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700896 if (result.sender_index_ != -1) {
James Kuszmaul9776b392023-01-14 14:08:08 -0800897 return result;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700898 } else {
899 return std::nullopt;
900 }
901}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700902
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700903size_t LocklessQueueSender::size() const {
904 return memory_->message_data_size();
905}
906
907void *LocklessQueueSender::Data() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700908 ::aos::ipc_lib::Sender *sender = memory_->GetSender(sender_index_);
Brian Silverman177567e2020-08-12 19:51:33 -0700909 const Index scratch_index = sender->scratch_index.RelaxedLoad();
910 Message *const message = memory_->GetMessage(scratch_index);
911 // We should have invalidated this when we first got the buffer. Verify that
912 // in debug mode.
913 DCHECK(
914 !message->header.queue_index.RelaxedLoad(memory_->queue_size()).valid())
915 << ": " << std::hex << scratch_index.get();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700916
Brian Silvermana1652f32020-01-29 20:41:44 -0800917 return message->data(memory_->message_data_size());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700918}
919
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700920LocklessQueueSender::Result LocklessQueueSender::Send(
Austin Schuhad154822019-12-27 15:45:13 -0800921 const char *data, size_t length,
Austin Schuhb5c6f972021-03-14 21:53:07 -0700922 monotonic_clock::time_point monotonic_remote_time,
923 realtime_clock::time_point realtime_remote_time,
Austin Schuha9012be2021-07-21 15:19:11 -0700924 uint32_t remote_queue_index, const UUID &source_boot_uuid,
Austin Schuhb5c6f972021-03-14 21:53:07 -0700925 monotonic_clock::time_point *monotonic_sent_time,
926 realtime_clock::time_point *realtime_sent_time, uint32_t *queue_index) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700927 CHECK_LE(length, size());
Austin Schuh67420a42019-12-21 21:55:04 -0800928 // Flatbuffers write from the back of the buffer to the front. If we are
929 // going to write an explicit chunk of memory into the buffer, we need to
930 // adhere to this convention and place it at the end.
931 memcpy((reinterpret_cast<char *>(Data()) + size() - length), data, length);
Austin Schuh91ba6392020-10-03 13:27:47 -0700932 return Send(length, monotonic_remote_time, realtime_remote_time,
Austin Schuha9012be2021-07-21 15:19:11 -0700933 remote_queue_index, source_boot_uuid, monotonic_sent_time,
Austin Schuhb5c6f972021-03-14 21:53:07 -0700934 realtime_sent_time, queue_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700935}
936
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700937LocklessQueueSender::Result LocklessQueueSender::Send(
Austin Schuhb5c6f972021-03-14 21:53:07 -0700938 size_t length, monotonic_clock::time_point monotonic_remote_time,
939 realtime_clock::time_point realtime_remote_time,
Austin Schuha9012be2021-07-21 15:19:11 -0700940 uint32_t remote_queue_index, const UUID &source_boot_uuid,
Austin Schuhb5c6f972021-03-14 21:53:07 -0700941 monotonic_clock::time_point *monotonic_sent_time,
942 realtime_clock::time_point *realtime_sent_time, uint32_t *queue_index) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700943 const size_t queue_size = memory_->queue_size();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700944 CHECK_LE(length, size());
Austin Schuh20b2b082019-09-11 20:42:56 -0700945
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800946 ::aos::ipc_lib::Sender *const sender = memory_->GetSender(sender_index_);
947 // We can do a relaxed load on our sender because we're the only person
948 // modifying it right now.
949 const Index scratch_index = sender->scratch_index.RelaxedLoad();
950 Message *const message = memory_->GetMessage(scratch_index);
Austin Schuh91ba6392020-10-03 13:27:47 -0700951 if (CheckBothRedzones(memory_, message)) {
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700952 return Result::INVALID_REDZONE;
Austin Schuh91ba6392020-10-03 13:27:47 -0700953 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700954
Brian Silverman177567e2020-08-12 19:51:33 -0700955 // We should have invalidated this when we first got the buffer. Verify that
956 // in debug mode.
957 DCHECK(
958 !message->header.queue_index.RelaxedLoad(memory_->queue_size()).valid())
959 << ": " << std::hex << scratch_index.get();
960
Austin Schuh20b2b082019-09-11 20:42:56 -0700961 message->header.length = length;
Austin Schuhad154822019-12-27 15:45:13 -0800962 // Pass these through. Any alternative behavior can be implemented out a
963 // layer.
964 message->header.remote_queue_index = remote_queue_index;
Austin Schuha9012be2021-07-21 15:19:11 -0700965 message->header.source_boot_uuid = source_boot_uuid;
Austin Schuhad154822019-12-27 15:45:13 -0800966 message->header.monotonic_remote_time = monotonic_remote_time;
967 message->header.realtime_remote_time = realtime_remote_time;
Austin Schuh20b2b082019-09-11 20:42:56 -0700968
Brian Silverman177567e2020-08-12 19:51:33 -0700969 Index to_replace = Index::Invalid();
Austin Schuh20b2b082019-09-11 20:42:56 -0700970 while (true) {
971 const QueueIndex actual_next_queue_index =
972 memory_->next_queue_index.Load(queue_size);
973 const QueueIndex next_queue_index = ZeroOrValid(actual_next_queue_index);
974
975 const QueueIndex incremented_queue_index = next_queue_index.Increment();
976
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800977 // This needs to synchronize with whoever the previous writer at this
978 // location was.
Brian Silverman177567e2020-08-12 19:51:33 -0700979 to_replace = memory_->LoadIndex(next_queue_index);
Austin Schuh20b2b082019-09-11 20:42:56 -0700980
981 const QueueIndex decremented_queue_index =
982 next_queue_index.DecrementBy(queue_size);
983
984 // See if we got beat. If we did, try to atomically update
985 // next_queue_index in case the previous writer failed and retry.
986 if (!to_replace.IsPlausible(decremented_queue_index)) {
987 // We don't care about the result. It will either succeed, or we got
988 // beat in fixing it and just need to give up and try again. If we got
989 // beat multiple times, the only way progress can be made is if the queue
990 // is updated as well. This means that if we retry reading
991 // next_queue_index, we will be at most off by one and can retry.
992 //
993 // Both require no further action from us.
994 //
995 // TODO(austin): If we are having fairness issues under contention, we
996 // could have a mode bit in next_queue_index, and could use a lock or some
997 // other form of PI boosting to let the higher priority task win.
998 memory_->next_queue_index.CompareAndExchangeStrong(
999 actual_next_queue_index, incremented_queue_index);
1000
Alex Perrycb7da4b2019-08-28 19:35:56 -07001001 VLOG(3) << "We were beat. Try again. Was " << std::hex
1002 << to_replace.get() << ", is " << decremented_queue_index.index();
Austin Schuh20b2b082019-09-11 20:42:56 -07001003 continue;
1004 }
1005
1006 // Confirm that the message is what it should be.
Brian Silverman177567e2020-08-12 19:51:33 -07001007 //
1008 // This is just a best-effort check to skip reading the clocks if possible.
1009 // If this fails, then the compare-exchange below definitely would, so we
1010 // can bail out now.
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001011 const Message *message_to_replace = memory_->GetMessage(to_replace);
1012 bool is_previous_index_valid = false;
Austin Schuh20b2b082019-09-11 20:42:56 -07001013 {
Austin Schuh20b2b082019-09-11 20:42:56 -07001014 const QueueIndex previous_index =
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001015 message_to_replace->header.queue_index.RelaxedLoad(queue_size);
1016 is_previous_index_valid = previous_index.valid();
1017 if (previous_index != decremented_queue_index &&
1018 is_previous_index_valid) {
Austin Schuh20b2b082019-09-11 20:42:56 -07001019 // Retry.
Alex Perrycb7da4b2019-08-28 19:35:56 -07001020 VLOG(3) << "Something fishy happened, queue index doesn't match. "
1021 "Retrying. Previous index was "
1022 << std::hex << previous_index.index() << ", should be "
1023 << decremented_queue_index.index();
Austin Schuh20b2b082019-09-11 20:42:56 -07001024 continue;
1025 }
1026 }
1027
1028 message->header.monotonic_sent_time = ::aos::monotonic_clock::now();
1029 message->header.realtime_sent_time = ::aos::realtime_clock::now();
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001030
Austin Schuhad154822019-12-27 15:45:13 -08001031 if (monotonic_sent_time != nullptr) {
1032 *monotonic_sent_time = message->header.monotonic_sent_time;
1033 }
1034 if (realtime_sent_time != nullptr) {
1035 *realtime_sent_time = message->header.realtime_sent_time;
1036 }
1037 if (queue_index != nullptr) {
1038 *queue_index = next_queue_index.index();
1039 }
Austin Schuh20b2b082019-09-11 20:42:56 -07001040
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001041 const auto to_replace_monotonic_sent_time =
1042 message_to_replace->header.monotonic_sent_time;
1043
1044 // If we are overwriting a message sent in the last
1045 // channel_storage_duration_, that means that we would be sending more than
1046 // queue_size messages and would therefore be sending too fast. If the
1047 // previous index is not valid then the message hasn't been filled out yet
1048 // so we aren't sending too fast. And, if it is not less than the sent time
1049 // of the message that we are going to write, someone else beat us and the
1050 // compare and exchange below will fail.
1051 if (is_previous_index_valid &&
1052 (to_replace_monotonic_sent_time <
1053 message->header.monotonic_sent_time) &&
1054 (message->header.monotonic_sent_time - to_replace_monotonic_sent_time <
1055 channel_storage_duration_)) {
1056 // There is a possibility that another context beat us to writing out the
1057 // message in the queue, but we beat that context to acquiring the sent
1058 // time. In this case our sent time is *greater than* the other context's
1059 // sent time. Therefore, we can check if we got beat filling out this
1060 // message *after* doing the above check to determine if we hit this edge
1061 // case. Otherwise, messages are being sent too fast.
1062 const QueueIndex previous_index =
1063 message_to_replace->header.queue_index.Load(queue_size);
1064 if (previous_index != decremented_queue_index && previous_index.valid()) {
1065 VLOG(3) << "Got beat during check for messages being sent too fast"
1066 "Retrying.";
1067 continue;
1068 } else {
Austin Schuh71e72142023-05-03 13:10:07 -07001069 VLOG(1) << "Messages sent too fast. Returning. Attempted index: "
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001070 << decremented_queue_index.index()
1071 << " message sent time: " << message->header.monotonic_sent_time
1072 << " message to replace sent time: "
1073 << to_replace_monotonic_sent_time;
Austin Schuh71e72142023-05-03 13:10:07 -07001074
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001075 // Since we are not using the message obtained from scratch_index
1076 // and we are not retrying, we need to invalidate its queue_index.
1077 message->header.queue_index.Invalidate();
1078 return Result::MESSAGES_SENT_TOO_FAST;
1079 }
1080 }
1081
Austin Schuh20b2b082019-09-11 20:42:56 -07001082 // Before we are fully done filling out the message, update the Sender state
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001083 // with the new index to write. This re-uses the barrier for the
Austin Schuh20b2b082019-09-11 20:42:56 -07001084 // queue_index store.
Alex Perrycb7da4b2019-08-28 19:35:56 -07001085 const Index index_to_write(next_queue_index, scratch_index.message_index());
Austin Schuh20b2b082019-09-11 20:42:56 -07001086
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001087 aos_compiler_memory_barrier();
1088 // We're the only person who cares about our scratch index, besides somebody
1089 // cleaning up after us.
Austin Schuh20b2b082019-09-11 20:42:56 -07001090 sender->scratch_index.RelaxedStore(index_to_write);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001091 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -07001092
1093 message->header.queue_index.Store(next_queue_index);
1094
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001095 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -07001096 // The message is now filled out, and we have a confirmed slot to store
1097 // into.
1098 //
1099 // Start by writing down what we are going to pull out of the queue. This
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001100 // was Invalid before now. Only person who will read this is whoever cleans
1101 // up after us, so no synchronization necessary.
Austin Schuh20b2b082019-09-11 20:42:56 -07001102 sender->to_replace.RelaxedStore(to_replace);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001103 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -07001104
1105 // Then exchange the next index into the queue.
1106 if (!memory_->GetQueue(next_queue_index.Wrapped())
1107 ->CompareAndExchangeStrong(to_replace, index_to_write)) {
1108 // Aw, didn't succeed. Retry.
1109 sender->to_replace.RelaxedInvalidate();
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001110 aos_compiler_memory_barrier();
Alex Perrycb7da4b2019-08-28 19:35:56 -07001111 VLOG(3) << "Failed to wrap into queue";
Austin Schuh20b2b082019-09-11 20:42:56 -07001112 continue;
1113 }
1114
1115 // Then update next_queue_index to save the next user some computation time.
1116 memory_->next_queue_index.CompareAndExchangeStrong(actual_next_queue_index,
1117 incremented_queue_index);
1118
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001119 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -07001120 // Now update the scratch space and record that we succeeded.
1121 sender->scratch_index.Store(to_replace);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001122 aos_compiler_memory_barrier();
1123 // And then record that we succeeded, but definitely after the above store.
Austin Schuh20b2b082019-09-11 20:42:56 -07001124 sender->to_replace.RelaxedInvalidate();
Brian Silverman177567e2020-08-12 19:51:33 -07001125
Austin Schuh20b2b082019-09-11 20:42:56 -07001126 break;
1127 }
Brian Silverman177567e2020-08-12 19:51:33 -07001128
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001129 DCHECK(!CheckBothRedzones(memory_, memory_->GetMessage(to_replace)))
1130 << ": Invalid message found in shared memory";
Brian Silverman177567e2020-08-12 19:51:33 -07001131 // to_replace is our current scratch_index. It isn't in the queue, which means
1132 // nobody new can pin it. They can set their `pinned` to it, but they will
1133 // back it out, so they don't count. This means that we just need to find a
1134 // message for which no pinner had it in `pinned`, and then we know this
1135 // message will never be pinned. We'll start with to_replace, and if that is
1136 // pinned then we'll look for a new one to use instead.
1137 const Index new_scratch =
1138 SwapPinnedSenderScratch(memory_, sender, to_replace);
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001139 DCHECK(!CheckBothRedzones(
1140 memory_, memory_->GetMessage(sender->scratch_index.RelaxedLoad())))
1141 << ": Invalid message found in shared memory";
Brian Silverman177567e2020-08-12 19:51:33 -07001142
1143 // If anybody is looking at this message (they shouldn't be), then try telling
1144 // them about it (best-effort).
1145 memory_->GetMessage(new_scratch)->header.queue_index.RelaxedInvalidate();
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001146 return Result::GOOD;
Austin Schuh20b2b082019-09-11 20:42:56 -07001147}
1148
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001149int LocklessQueueSender::buffer_index() const {
Brian Silverman4f4e0612020-08-12 19:54:41 -07001150 ::aos::ipc_lib::Sender *const sender = memory_->GetSender(sender_index_);
1151 // We can do a relaxed load on our sender because we're the only person
1152 // modifying it right now.
1153 const Index scratch_index = sender->scratch_index.RelaxedLoad();
1154 return scratch_index.message_index();
1155}
1156
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001157LocklessQueuePinner::LocklessQueuePinner(
1158 LocklessQueueMemory *memory, const LocklessQueueMemory *const_memory)
1159 : memory_(memory), const_memory_(const_memory) {
1160 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory_);
1161
1162 // Since we already have the lock, go ahead and try cleaning up.
1163 Cleanup(memory_, grab_queue_setup_lock);
1164
1165 const int num_pinners = memory_->num_pinners();
1166
1167 for (int i = 0; i < num_pinners; ++i) {
1168 ::aos::ipc_lib::Pinner *p = memory->GetPinner(i);
1169 // This doesn't need synchronization because we're the only process doing
1170 // initialization right now, and nobody else will be touching pinners which
1171 // we're interested in.
1172 const uint32_t tid = __atomic_load_n(&(p->tid.futex), __ATOMIC_RELAXED);
1173 if (tid == 0) {
1174 pinner_index_ = i;
1175 break;
1176 }
1177 }
1178
1179 if (pinner_index_ == -1) {
1180 VLOG(1) << "Too many pinners, starting to bail.";
1181 return;
1182 }
1183
1184 ::aos::ipc_lib::Pinner *p = memory_->GetPinner(pinner_index_);
1185 p->pinned.Invalidate();
1186
1187 // Indicate that we are now alive by taking over the slot. If the previous
1188 // owner died, we still want to do this.
1189 death_notification_init(&(p->tid));
1190}
1191
1192LocklessQueuePinner::~LocklessQueuePinner() {
1193 if (pinner_index_ != -1) {
1194 CHECK(memory_ != nullptr);
1195 memory_->GetPinner(pinner_index_)->pinned.Invalidate();
1196 aos_compiler_memory_barrier();
1197 death_notification_release(&(memory_->GetPinner(pinner_index_)->tid));
1198 }
1199}
1200
1201std::optional<LocklessQueuePinner> LocklessQueuePinner::Make(
1202 LocklessQueue queue) {
1203 queue.Initialize();
1204 LocklessQueuePinner result(queue.memory(), queue.const_memory());
1205 if (result.pinner_index_ != -1) {
James Kuszmaul9776b392023-01-14 14:08:08 -08001206 return result;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001207 } else {
1208 return std::nullopt;
1209 }
1210}
1211
1212// This method doesn't mess with any scratch_index, so it doesn't have to worry
1213// about message ownership.
1214int LocklessQueuePinner::PinIndex(uint32_t uint32_queue_index) {
1215 const size_t queue_size = memory_->queue_size();
1216 const QueueIndex queue_index =
1217 QueueIndex::Zero(queue_size).IncrementBy(uint32_queue_index);
1218 ipc_lib::Pinner *const pinner = memory_->GetPinner(pinner_index_);
1219
1220 AtomicIndex *const queue_slot = memory_->GetQueue(queue_index.Wrapped());
1221
1222 // Indicate that we want to pin this message.
1223 pinner->pinned.Store(queue_index);
1224 aos_compiler_memory_barrier();
1225
1226 {
1227 const Index message_index = queue_slot->Load();
1228 Message *const message = memory_->GetMessage(message_index);
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001229 DCHECK(!CheckBothRedzones(memory_, message))
1230 << ": Invalid message found in shared memory";
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001231
1232 const QueueIndex message_queue_index =
1233 message->header.queue_index.Load(queue_size);
1234 if (message_queue_index == queue_index) {
1235 VLOG(3) << "Eq: " << std::hex << message_queue_index.index();
1236 aos_compiler_memory_barrier();
1237 return message_index.message_index();
1238 }
1239 VLOG(3) << "Message reused: " << std::hex << message_queue_index.index()
1240 << ", " << queue_index.index();
1241 }
1242
1243 // Being down here means we asked to pin a message before realizing it's no
1244 // longer in the queue, so back that out now.
1245 pinner->pinned.Invalidate();
1246 VLOG(3) << "Unpinned: " << std::hex << queue_index.index();
1247 return -1;
1248}
1249
1250size_t LocklessQueuePinner::size() const {
1251 return const_memory_->message_data_size();
1252}
1253
1254const void *LocklessQueuePinner::Data() const {
1255 const size_t queue_size = const_memory_->queue_size();
1256 const ::aos::ipc_lib::Pinner *const pinner =
1257 const_memory_->GetPinner(pinner_index_);
1258 QueueIndex pinned = pinner->pinned.RelaxedLoad(queue_size);
1259 CHECK(pinned.valid());
1260 const Message *message = const_memory_->GetMessage(pinned);
1261
1262 return message->data(const_memory_->message_data_size());
1263}
1264
1265LocklessQueueReader::Result LocklessQueueReader::Read(
Austin Schuh20b2b082019-09-11 20:42:56 -07001266 uint32_t uint32_queue_index,
Austin Schuhb5c6f972021-03-14 21:53:07 -07001267 monotonic_clock::time_point *monotonic_sent_time,
1268 realtime_clock::time_point *realtime_sent_time,
1269 monotonic_clock::time_point *monotonic_remote_time,
1270 realtime_clock::time_point *realtime_remote_time,
Austin Schuha9012be2021-07-21 15:19:11 -07001271 uint32_t *remote_queue_index, UUID *source_boot_uuid, size_t *length,
Austin Schuhb5c6f972021-03-14 21:53:07 -07001272 char *data) const {
Austin Schuh20b2b082019-09-11 20:42:56 -07001273 const size_t queue_size = memory_->queue_size();
1274
1275 // Build up the QueueIndex.
1276 const QueueIndex queue_index =
1277 QueueIndex::Zero(queue_size).IncrementBy(uint32_queue_index);
1278
1279 // Read the message stored at the requested location.
1280 Index mi = memory_->LoadIndex(queue_index);
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001281 const Message *m = memory_->GetMessage(mi);
Austin Schuh20b2b082019-09-11 20:42:56 -07001282
1283 while (true) {
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001284 DCHECK(!CheckBothRedzones(memory_, m))
1285 << ": Invalid message found in shared memory";
Austin Schuh20b2b082019-09-11 20:42:56 -07001286 // We need to confirm that the data doesn't change while we are reading it.
1287 // Do that by first confirming that the message points to the queue index we
1288 // want.
1289 const QueueIndex starting_queue_index =
1290 m->header.queue_index.Load(queue_size);
1291 if (starting_queue_index != queue_index) {
1292 // If we found a message that is exactly 1 loop old, we just wrapped.
1293 if (starting_queue_index == queue_index.DecrementBy(queue_size)) {
Alex Perrycb7da4b2019-08-28 19:35:56 -07001294 VLOG(3) << "Matches: " << std::hex << starting_queue_index.index()
1295 << ", " << queue_index.DecrementBy(queue_size).index();
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001296 return Result::NOTHING_NEW;
Brian Silverman177567e2020-08-12 19:51:33 -07001297 }
1298
1299 // Someone has re-used this message between when we pulled it out of the
1300 // queue and when we grabbed its index. It is pretty hard to deduce
1301 // what happened. Just try again.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001302 const Message *const new_m = memory_->GetMessage(queue_index);
Brian Silverman177567e2020-08-12 19:51:33 -07001303 if (m != new_m) {
1304 m = new_m;
1305 VLOG(3) << "Retrying, m doesn't match";
1306 continue;
1307 }
1308
1309 // We have confirmed that message still points to the same message. This
1310 // means that the message didn't get swapped out from under us, so
1311 // starting_queue_index is correct.
1312 //
1313 // Either we got too far behind (signaled by this being a valid
1314 // message), or this is one of the initial messages which are invalid.
1315 if (starting_queue_index.valid()) {
1316 VLOG(3) << "Too old. Tried for " << std::hex << queue_index.index()
1317 << ", got " << starting_queue_index.index() << ", behind by "
1318 << std::dec
1319 << (starting_queue_index.index() - queue_index.index());
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001320 return Result::TOO_OLD;
Brian Silverman177567e2020-08-12 19:51:33 -07001321 }
1322
1323 VLOG(3) << "Initial";
1324
1325 // There isn't a valid message at this location.
1326 //
1327 // If someone asks for one of the messages within the first go around,
1328 // then they need to wait. They got ahead. Otherwise, they are
1329 // asking for something crazy, like something before the beginning of
1330 // the queue. Tell them that they are behind.
1331 if (uint32_queue_index < memory_->queue_size()) {
1332 VLOG(3) << "Near zero, " << std::hex << uint32_queue_index;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001333 return Result::NOTHING_NEW;
Austin Schuh20b2b082019-09-11 20:42:56 -07001334 } else {
Brian Silverman177567e2020-08-12 19:51:33 -07001335 VLOG(3) << "Not near zero, " << std::hex << uint32_queue_index;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001336 return Result::TOO_OLD;
Austin Schuh20b2b082019-09-11 20:42:56 -07001337 }
1338 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001339 VLOG(3) << "Eq: " << std::hex << starting_queue_index.index() << ", "
1340 << queue_index.index();
Austin Schuh20b2b082019-09-11 20:42:56 -07001341 break;
1342 }
1343
Alex Perrycb7da4b2019-08-28 19:35:56 -07001344 // Then read the data out. Copy it all out to be deterministic and so we can
1345 // make length be from either end.
Austin Schuh20b2b082019-09-11 20:42:56 -07001346 *monotonic_sent_time = m->header.monotonic_sent_time;
1347 *realtime_sent_time = m->header.realtime_sent_time;
Austin Schuhad154822019-12-27 15:45:13 -08001348 if (m->header.remote_queue_index == 0xffffffffu) {
1349 *remote_queue_index = queue_index.index();
1350 } else {
1351 *remote_queue_index = m->header.remote_queue_index;
1352 }
1353 *monotonic_remote_time = m->header.monotonic_remote_time;
1354 *realtime_remote_time = m->header.realtime_remote_time;
Austin Schuha9012be2021-07-21 15:19:11 -07001355 *source_boot_uuid = m->header.source_boot_uuid;
Brian Silverman6b8a3c32020-03-06 11:26:14 -08001356 if (data) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001357 memcpy(data, m->data(memory_->message_data_size()),
1358 memory_->message_data_size());
Brian Silverman6b8a3c32020-03-06 11:26:14 -08001359 }
Austin Schuh20b2b082019-09-11 20:42:56 -07001360 *length = m->header.length;
1361
1362 // And finally, confirm that the message *still* points to the queue index we
1363 // want. This means it didn't change out from under us.
1364 // If something changed out from under us, we were reading it much too late in
1365 // it's lifetime.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001366 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -07001367 const QueueIndex final_queue_index = m->header.queue_index.Load(queue_size);
1368 if (final_queue_index != queue_index) {
Alex Perrycb7da4b2019-08-28 19:35:56 -07001369 VLOG(3) << "Changed out from under us. Reading " << std::hex
1370 << queue_index.index() << ", finished with "
1371 << final_queue_index.index() << ", delta: " << std::dec
1372 << (final_queue_index.index() - queue_index.index());
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001373 return Result::OVERWROTE;
Austin Schuh20b2b082019-09-11 20:42:56 -07001374 }
1375
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001376 return Result::GOOD;
Austin Schuh20b2b082019-09-11 20:42:56 -07001377}
1378
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001379QueueIndex LocklessQueueReader::LatestIndex() const {
Austin Schuh20b2b082019-09-11 20:42:56 -07001380 const size_t queue_size = memory_->queue_size();
1381
1382 // There is only one interesting case. We need to know if the queue is empty.
1383 // That is done with a sentinel value. At worst, this will be off by one.
1384 const QueueIndex next_queue_index =
1385 memory_->next_queue_index.Load(queue_size);
1386 if (next_queue_index.valid()) {
1387 const QueueIndex current_queue_index = next_queue_index.DecrementBy(1u);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001388 return current_queue_index;
Austin Schuh20b2b082019-09-11 20:42:56 -07001389 }
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001390 return QueueIndex::Invalid();
1391}
1392
1393size_t LocklessQueueSize(const LocklessQueueMemory *memory) {
1394 return memory->queue_size();
1395}
1396
1397size_t LocklessQueueMessageDataSize(const LocklessQueueMemory *memory) {
1398 return memory->message_data_size();
Austin Schuh20b2b082019-09-11 20:42:56 -07001399}
1400
1401namespace {
1402
1403// Prints out the mutex state. Not safe to use while the mutex is being
1404// changed.
Austin Schuh83cbb1e2023-06-23 12:59:02 -07001405::std::string PrintMutex(const aos_mutex *mutex) {
Austin Schuh20b2b082019-09-11 20:42:56 -07001406 ::std::stringstream s;
1407 s << "aos_mutex(" << ::std::hex << mutex->futex;
1408
1409 if (mutex->futex != 0) {
1410 s << ":";
1411 if (mutex->futex & FUTEX_OWNER_DIED) {
1412 s << "FUTEX_OWNER_DIED|";
1413 }
1414 s << "tid=" << (mutex->futex & FUTEX_TID_MASK);
1415 }
1416
1417 s << ")";
1418 return s.str();
1419}
1420
1421} // namespace
1422
Austin Schuh83cbb1e2023-06-23 12:59:02 -07001423void PrintLocklessQueueMemory(const LocklessQueueMemory *memory) {
Austin Schuh20b2b082019-09-11 20:42:56 -07001424 const size_t queue_size = memory->queue_size();
1425 ::std::cout << "LocklessQueueMemory (" << memory << ") {" << ::std::endl;
1426 ::std::cout << " aos_mutex queue_setup_lock = "
1427 << PrintMutex(&memory->queue_setup_lock) << ::std::endl;
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001428 ::std::cout << " bool initialized = " << memory->initialized << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001429 ::std::cout << " config {" << ::std::endl;
1430 ::std::cout << " size_t num_watchers = " << memory->config.num_watchers
1431 << ::std::endl;
1432 ::std::cout << " size_t num_senders = " << memory->config.num_senders
1433 << ::std::endl;
Brian Silverman177567e2020-08-12 19:51:33 -07001434 ::std::cout << " size_t num_pinners = " << memory->config.num_pinners
1435 << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001436 ::std::cout << " size_t queue_size = " << memory->config.queue_size
1437 << ::std::endl;
1438 ::std::cout << " size_t message_data_size = "
1439 << memory->config.message_data_size << ::std::endl;
1440
1441 ::std::cout << " AtomicQueueIndex next_queue_index = "
1442 << memory->next_queue_index.Load(queue_size).DebugString()
1443 << ::std::endl;
1444
Austin Schuh3328d132020-02-28 13:54:57 -08001445 ::std::cout << " uid_t uid = " << memory->uid << ::std::endl;
1446
Austin Schuh20b2b082019-09-11 20:42:56 -07001447 ::std::cout << " }" << ::std::endl;
1448 ::std::cout << " AtomicIndex queue[" << queue_size << "] {" << ::std::endl;
1449 for (size_t i = 0; i < queue_size; ++i) {
1450 ::std::cout << " [" << i << "] -> "
1451 << memory->GetQueue(i)->Load().DebugString() << ::std::endl;
1452 }
1453 ::std::cout << " }" << ::std::endl;
1454 ::std::cout << " Message messages[" << memory->num_messages() << "] {"
1455 << ::std::endl;
1456 for (size_t i = 0; i < memory->num_messages(); ++i) {
Austin Schuh83cbb1e2023-06-23 12:59:02 -07001457 const Message *m = memory->GetMessage(Index(i, i));
Brian Silverman001f24d2020-08-12 19:33:20 -07001458 ::std::cout << " [" << i << "] -> Message 0x" << std::hex
1459 << (reinterpret_cast<uintptr_t>(
1460 memory->GetMessage(Index(i, i))) -
1461 reinterpret_cast<uintptr_t>(memory))
1462 << std::dec << " {" << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001463 ::std::cout << " Header {" << ::std::endl;
1464 ::std::cout << " AtomicQueueIndex queue_index = "
1465 << m->header.queue_index.Load(queue_size).DebugString()
1466 << ::std::endl;
Brian Silverman001f24d2020-08-12 19:33:20 -07001467 ::std::cout << " monotonic_clock::time_point monotonic_sent_time = "
1468 << m->header.monotonic_sent_time << " 0x" << std::hex
1469 << m->header.monotonic_sent_time.time_since_epoch().count()
1470 << std::dec << ::std::endl;
1471 ::std::cout << " realtime_clock::time_point realtime_sent_time = "
1472 << m->header.realtime_sent_time << " 0x" << std::hex
1473 << m->header.realtime_sent_time.time_since_epoch().count()
1474 << std::dec << ::std::endl;
1475 ::std::cout
1476 << " monotonic_clock::time_point monotonic_remote_time = "
1477 << m->header.monotonic_remote_time << " 0x" << std::hex
1478 << m->header.monotonic_remote_time.time_since_epoch().count()
1479 << std::dec << ::std::endl;
1480 ::std::cout << " realtime_clock::time_point realtime_remote_time = "
1481 << m->header.realtime_remote_time << " 0x" << std::hex
1482 << m->header.realtime_remote_time.time_since_epoch().count()
1483 << std::dec << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001484 ::std::cout << " size_t length = " << m->header.length
1485 << ::std::endl;
1486 ::std::cout << " }" << ::std::endl;
Austin Schuhbe416742020-10-03 17:24:26 -07001487 const bool corrupt = CheckBothRedzones(memory, m);
1488 if (corrupt) {
Austin Schuh83cbb1e2023-06-23 12:59:02 -07001489 absl::Span<const char> pre_redzone =
1490 m->PreRedzone(memory->message_data_size());
1491 absl::Span<const char> post_redzone =
Austin Schuhbe416742020-10-03 17:24:26 -07001492 m->PostRedzone(memory->message_data_size(), memory->message_size());
1493
1494 ::std::cout << " pre-redzone: \""
1495 << absl::BytesToHexString(std::string_view(
1496 pre_redzone.data(), pre_redzone.size()))
1497 << std::endl;
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001498 ::std::cout << " // *** DATA REDZONES ARE CORRUPTED ***"
1499 << ::std::endl;
Austin Schuhbe416742020-10-03 17:24:26 -07001500 ::std::cout << " post-redzone: \""
1501 << absl::BytesToHexString(std::string_view(
1502 post_redzone.data(), post_redzone.size()))
1503 << std::endl;
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001504 }
Austin Schuh20b2b082019-09-11 20:42:56 -07001505 ::std::cout << " data: {";
1506
Brian Silverman001f24d2020-08-12 19:33:20 -07001507 if (FLAGS_dump_lockless_queue_data) {
1508 const char *const m_data = m->data(memory->message_data_size());
Austin Schuhbe416742020-10-03 17:24:26 -07001509 std::cout << absl::BytesToHexString(std::string_view(
1510 m_data, corrupt ? memory->message_data_size() : m->header.length));
Austin Schuh20b2b082019-09-11 20:42:56 -07001511 }
1512 ::std::cout << ::std::setfill(' ') << ::std::dec << "}" << ::std::endl;
1513 ::std::cout << " }," << ::std::endl;
1514 }
1515 ::std::cout << " }" << ::std::endl;
1516
Alex Perrycb7da4b2019-08-28 19:35:56 -07001517 ::std::cout << " Sender senders[" << memory->num_senders() << "] {"
1518 << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001519 for (size_t i = 0; i < memory->num_senders(); ++i) {
Austin Schuh83cbb1e2023-06-23 12:59:02 -07001520 const Sender *s = memory->GetSender(i);
Austin Schuh20b2b082019-09-11 20:42:56 -07001521 ::std::cout << " [" << i << "] -> Sender {" << ::std::endl;
1522 ::std::cout << " aos_mutex tid = " << PrintMutex(&s->tid)
1523 << ::std::endl;
1524 ::std::cout << " AtomicIndex scratch_index = "
1525 << s->scratch_index.Load().DebugString() << ::std::endl;
1526 ::std::cout << " AtomicIndex to_replace = "
1527 << s->to_replace.Load().DebugString() << ::std::endl;
1528 ::std::cout << " }" << ::std::endl;
1529 }
1530 ::std::cout << " }" << ::std::endl;
1531
Brian Silverman177567e2020-08-12 19:51:33 -07001532 ::std::cout << " Pinner pinners[" << memory->num_pinners() << "] {"
1533 << ::std::endl;
1534 for (size_t i = 0; i < memory->num_pinners(); ++i) {
Austin Schuh83cbb1e2023-06-23 12:59:02 -07001535 const Pinner *p = memory->GetPinner(i);
Brian Silverman177567e2020-08-12 19:51:33 -07001536 ::std::cout << " [" << i << "] -> Pinner {" << ::std::endl;
1537 ::std::cout << " aos_mutex tid = " << PrintMutex(&p->tid)
1538 << ::std::endl;
1539 ::std::cout << " AtomicIndex scratch_index = "
1540 << p->scratch_index.Load().DebugString() << ::std::endl;
1541 ::std::cout << " AtomicIndex pinned = "
1542 << p->pinned.Load(memory->queue_size()).DebugString()
1543 << ::std::endl;
1544 ::std::cout << " }" << ::std::endl;
1545 }
1546 ::std::cout << " }" << ::std::endl;
1547
Austin Schuh20b2b082019-09-11 20:42:56 -07001548 ::std::cout << " Watcher watchers[" << memory->num_watchers() << "] {"
1549 << ::std::endl;
1550 for (size_t i = 0; i < memory->num_watchers(); ++i) {
Austin Schuh83cbb1e2023-06-23 12:59:02 -07001551 const Watcher *w = memory->GetWatcher(i);
Austin Schuh20b2b082019-09-11 20:42:56 -07001552 ::std::cout << " [" << i << "] -> Watcher {" << ::std::endl;
1553 ::std::cout << " aos_mutex tid = " << PrintMutex(&w->tid)
1554 << ::std::endl;
1555 ::std::cout << " pid_t pid = " << w->pid << ::std::endl;
1556 ::std::cout << " int priority = " << w->priority << ::std::endl;
1557 ::std::cout << " }" << ::std::endl;
1558 }
1559 ::std::cout << " }" << ::std::endl;
1560
1561 ::std::cout << "}" << ::std::endl;
1562}
1563
1564} // namespace ipc_lib
1565} // namespace aos