blob: ae3a4937babad56479393ef70fd4d6c095457cfa [file] [log] [blame]
Austin Schuh20b2b082019-09-11 20:42:56 -07001#include "aos/ipc_lib/lockless_queue.h"
2
3#include <linux/futex.h>
Brennan Coslett6af53bb2023-07-18 15:22:46 -05004#include <pwd.h>
Stephan Pleines682928d2024-05-31 20:43:48 -07005#include <sched.h>
6#include <string.h>
7#include <sys/syscall.h>
Austin Schuh20b2b082019-09-11 20:42:56 -07008#include <sys/types.h>
Austin Schuh20b2b082019-09-11 20:42:56 -07009#include <unistd.h>
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -070010
Austin Schuh20b2b082019-09-11 20:42:56 -070011#include <algorithm>
Stephan Pleines682928d2024-05-31 20:43:48 -070012#include <chrono>
13#include <compare>
Austin Schuh20b2b082019-09-11 20:42:56 -070014#include <iomanip>
15#include <iostream>
Stephan Pleines682928d2024-05-31 20:43:48 -070016#include <string>
17#include <string_view>
Austin Schuh20b2b082019-09-11 20:42:56 -070018
Austin Schuhbe416742020-10-03 17:24:26 -070019#include "absl/strings/escaping.h"
Philipp Schrader790cb542023-07-05 21:06:52 -070020#include "gflags/gflags.h"
21#include "glog/logging.h"
22
Austin Schuh20b2b082019-09-11 20:42:56 -070023#include "aos/ipc_lib/lockless_queue_memory.h"
Austin Schuh20b2b082019-09-11 20:42:56 -070024#include "aos/util/compiler_memory_barrier.h"
25
Brian Silverman001f24d2020-08-12 19:33:20 -070026DEFINE_bool(dump_lockless_queue_data, false,
27 "If true, print the data out when dumping the queue.");
Austin Schuh151f7822024-03-16 12:52:32 -070028DECLARE_bool(skip_realtime_scheduler);
Brian Silverman001f24d2020-08-12 19:33:20 -070029
Stephan Pleinesf63bde82024-01-13 15:59:33 -080030namespace aos::ipc_lib {
Austin Schuh20b2b082019-09-11 20:42:56 -070031namespace {
32
Brian Silvermanfafe1fa2019-12-18 21:42:18 -080033class GrabQueueSetupLockOrDie {
34 public:
35 GrabQueueSetupLockOrDie(LocklessQueueMemory *memory) : memory_(memory) {
36 const int result = mutex_grab(&(memory->queue_setup_lock));
37 CHECK(result == 0 || result == 1) << ": " << result;
38 }
Austin Schuh20b2b082019-09-11 20:42:56 -070039
Brian Silvermanfafe1fa2019-12-18 21:42:18 -080040 ~GrabQueueSetupLockOrDie() { mutex_unlock(&(memory_->queue_setup_lock)); }
41
42 GrabQueueSetupLockOrDie(const GrabQueueSetupLockOrDie &) = delete;
43 GrabQueueSetupLockOrDie &operator=(const GrabQueueSetupLockOrDie &) = delete;
44
45 private:
46 LocklessQueueMemory *const memory_;
47};
48
Brian Silverman177567e2020-08-12 19:51:33 -070049bool IsPinned(LocklessQueueMemory *memory, Index index) {
50 DCHECK(index.valid());
51 const size_t queue_size = memory->queue_size();
52 const QueueIndex message_index =
53 memory->GetMessage(index)->header.queue_index.Load(queue_size);
54 if (!message_index.valid()) {
55 return false;
56 }
57 DCHECK(memory->GetQueue(message_index.Wrapped())->Load() != index)
58 << ": Message is in the queue";
59 for (int pinner_index = 0;
60 pinner_index < static_cast<int>(memory->config.num_pinners);
61 ++pinner_index) {
62 ipc_lib::Pinner *const pinner = memory->GetPinner(pinner_index);
63
64 if (pinner->pinned.RelaxedLoad(queue_size) == message_index) {
65 return true;
66 }
67 }
68 return false;
69}
70
71// Ensures sender->scratch_index (which must contain to_replace) is not pinned.
72//
73// Returns the new scratch_index value.
74Index SwapPinnedSenderScratch(LocklessQueueMemory *const memory,
75 ipc_lib::Sender *const sender,
76 const Index to_replace) {
77 // If anybody's trying to pin this message, then grab a message from a pinner
78 // to write into instead, and leave the message we pulled out of the queue
79 // (currently in our scratch_index) with a pinner.
80 //
81 // This loop will terminate in at most one iteration through the pinners in
82 // any steady-state configuration of the memory. There are only as many
83 // Pinner::pinned values to worry about as there are Pinner::scratch_index
84 // values to check against, plus to_replace, which means there will always be
85 // a free one. We might have to make multiple passes if things are being
86 // changed concurrently though, but nobody dying can make this loop fail to
87 // terminate (because the number of processes that can die is bounded, because
88 // no new ones can start while we've got the lock).
89 for (int pinner_index = 0; true;
90 pinner_index = (pinner_index + 1) % memory->config.num_pinners) {
91 if (!IsPinned(memory, to_replace)) {
92 // No pinners on our current scratch_index, so we're fine now.
93 VLOG(3) << "No pinners: " << to_replace.DebugString();
94 return to_replace;
95 }
96
97 ipc_lib::Pinner *const pinner = memory->GetPinner(pinner_index);
98
99 const Index pinner_scratch = pinner->scratch_index.RelaxedLoad();
100 CHECK(pinner_scratch.valid())
101 << ": Pinner scratch_index should always be valid";
102 if (IsPinned(memory, pinner_scratch)) {
103 // Wouldn't do us any good to swap with this one, so don't bother, and
104 // move onto the next one.
105 VLOG(3) << "Also pinned: " << pinner_scratch.DebugString();
106 continue;
107 }
108
109 sender->to_replace.RelaxedStore(pinner_scratch);
110 aos_compiler_memory_barrier();
111 // Give the pinner the message (which is currently in
112 // sender->scratch_index).
113 if (!pinner->scratch_index.CompareAndExchangeStrong(pinner_scratch,
114 to_replace)) {
115 // Somebody swapped into this pinner before us. The new value is probably
116 // pinned, so we don't want to look at it again immediately.
117 VLOG(3) << "Pinner " << pinner_index
118 << " scratch_index changed: " << pinner_scratch.DebugString()
119 << ", " << to_replace.DebugString();
120 sender->to_replace.RelaxedInvalidate();
121 continue;
122 }
123 aos_compiler_memory_barrier();
124 // Now update the sender's scratch space and record that we succeeded.
125 sender->scratch_index.Store(pinner_scratch);
126 aos_compiler_memory_barrier();
127 // And then record that we succeeded, but definitely after the above
128 // store.
129 sender->to_replace.RelaxedInvalidate();
130 VLOG(3) << "Got new scratch message: " << pinner_scratch.DebugString();
131
132 // If it's in a pinner's scratch_index, it should not be in the queue, which
133 // means nobody new can pin it for real. However, they can still attempt to
134 // pin it, which means we can't verify !IsPinned down here.
135
136 return pinner_scratch;
137 }
138}
139
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700140// Returns true if it succeeded. Returns false if another sender died in the
141// middle.
142bool DoCleanup(LocklessQueueMemory *memory, const GrabQueueSetupLockOrDie &) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800143 // Make sure we start looking at shared memory fresh right now. We'll handle
144 // people dying partway through by either cleaning up after them or not, but
145 // we want to ensure we clean up after anybody who has already died when we
146 // start.
147 aos_compiler_memory_barrier();
148
Austin Schuh20b2b082019-09-11 20:42:56 -0700149 const size_t num_senders = memory->num_senders();
Brian Silverman177567e2020-08-12 19:51:33 -0700150 const size_t num_pinners = memory->num_pinners();
Austin Schuh20b2b082019-09-11 20:42:56 -0700151 const size_t queue_size = memory->queue_size();
152 const size_t num_messages = memory->num_messages();
153
154 // There are a large number of crazy cases here for how things can go wrong
155 // and how we have to recover. They either require us to keep extra track of
156 // what is going on, slowing down the send path, or require a large number of
157 // cases.
158 //
159 // The solution here is to not over-think it. This is running while not real
160 // time during construction. It is allowed to be slow. It will also very
161 // rarely trigger. There is a small uS window where process death is
162 // ambiguous.
163 //
164 // So, build up a list N long, where N is the number of messages. Search
165 // through the entire queue and the sender list (ignoring any dead senders),
166 // and mark down which ones we have seen. Once we have seen all the messages
167 // except the N dead senders, we know which messages are dead. Because the
168 // queue is active while we do this, it may take a couple of go arounds to see
169 // everything.
170
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700171 ::std::vector<bool> need_recovery(num_senders, false);
172
Austin Schuh20b2b082019-09-11 20:42:56 -0700173 // Do the easy case. Find all senders who have died. See if they are either
174 // consistent already, or if they have copied over to_replace to the scratch
175 // index, but haven't cleared to_replace. Count them.
176 size_t valid_senders = 0;
177 for (size_t i = 0; i < num_senders; ++i) {
178 Sender *sender = memory->GetSender(i);
Philipp Schrader81fa3fb2023-09-17 18:58:35 -0700179 if (!sender->ownership_tracker.OwnerIsDefinitelyAbsolutelyDead()) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700180 // Not dead.
181 ++valid_senders;
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700182 continue;
Austin Schuh20b2b082019-09-11 20:42:56 -0700183 }
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700184 VLOG(3) << "Found an easy death for sender " << i;
185 // We can do a relaxed load here because we're the only person touching
186 // this sender at this point.
187 const Index to_replace = sender->to_replace.RelaxedLoad();
188 const Index scratch_index = sender->scratch_index.Load();
189
190 // I find it easiest to think about this in terms of the set of observable
191 // states. The main code progresses through the following states:
192
193 // 1) scratch_index = xxx
194 // to_replace = invalid
195 // This is unambiguous. Already good.
196
197 // 2) scratch_index = xxx
198 // to_replace = yyy
199 // Very ambiguous. Is xxx or yyy the correct one? Need to either roll
200 // this forwards or backwards.
201
202 // 3) scratch_index = yyy
203 // to_replace = yyy
204 // We are in the act of moving to_replace to scratch_index, but didn't
205 // finish. Easy.
Brian Silverman177567e2020-08-12 19:51:33 -0700206 //
207 // If doing a pinner swap, we've definitely done it.
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700208
209 // 4) scratch_index = yyy
210 // to_replace = invalid
211 // Finished, but died. Looks like 1)
212
Brian Silverman177567e2020-08-12 19:51:33 -0700213 // Swapping with a pinner's scratch_index passes through the same states.
214 // We just need to ensure the message that ends up in the senders's
215 // scratch_index isn't pinned, using the same code as sending does.
216
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700217 // Any cleanup code needs to follow the same set of states to be robust to
218 // death, so death can be restarted.
219
220 if (!to_replace.valid()) {
221 // 1) or 4). Make sure we aren't corrupted and declare victory.
222 CHECK(scratch_index.valid());
223
Brian Silverman177567e2020-08-12 19:51:33 -0700224 // If it's in 1) with a pinner, the sender might have a pinned message,
225 // so fix that.
226 SwapPinnedSenderScratch(memory, sender, scratch_index);
227
228 // If it's in 4), it may not have completed this step yet. This will
229 // always be a NOP if it's in 1), verified by a DCHECK.
230 memory->GetMessage(scratch_index)->header.queue_index.RelaxedInvalidate();
231
Philipp Schraderab2f8432023-09-17 18:58:06 -0700232 sender->ownership_tracker.ForceClear();
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700233 ++valid_senders;
234 continue;
235 }
236
237 // Could be 2) or 3) at this point.
238
239 if (to_replace == scratch_index) {
240 // 3) for sure.
241 // Just need to invalidate to_replace to finish.
242 sender->to_replace.Invalidate();
243
Brian Silverman177567e2020-08-12 19:51:33 -0700244 // Make sure to indicate it's an unused message before a sender gets its
245 // hands on it.
246 memory->GetMessage(scratch_index)->header.queue_index.RelaxedInvalidate();
247 aos_compiler_memory_barrier();
248
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700249 // And mark that we succeeded.
Philipp Schraderab2f8432023-09-17 18:58:06 -0700250 sender->ownership_tracker.ForceClear();
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700251 ++valid_senders;
252 continue;
253 }
254
255 // Must be 2). Mark it for later.
256 need_recovery[i] = true;
Austin Schuh20b2b082019-09-11 20:42:56 -0700257 }
258
Brian Silverman177567e2020-08-12 19:51:33 -0700259 // Cleaning up pinners is easy. We don't actually have to do anything, but
260 // invalidating its pinned field might help catch bugs elsewhere trying to
261 // read it before it's set.
262 for (size_t i = 0; i < num_pinners; ++i) {
263 Pinner *const pinner = memory->GetPinner(i);
Philipp Schrader81fa3fb2023-09-17 18:58:35 -0700264 if (!pinner->ownership_tracker.OwnerIsDefinitelyAbsolutelyDead()) {
Brian Silverman177567e2020-08-12 19:51:33 -0700265 continue;
266 }
267 pinner->pinned.Invalidate();
Philipp Schraderab2f8432023-09-17 18:58:06 -0700268 pinner->ownership_tracker.ForceClear();
Brian Silverman177567e2020-08-12 19:51:33 -0700269 }
270
Austin Schuh20b2b082019-09-11 20:42:56 -0700271 // If all the senders are (or were made) good, there is no need to do the hard
272 // case.
273 if (valid_senders == num_senders) {
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700274 return true;
Austin Schuh20b2b082019-09-11 20:42:56 -0700275 }
276
Alex Perrycb7da4b2019-08-28 19:35:56 -0700277 VLOG(3) << "Starting hard cleanup";
Austin Schuh20b2b082019-09-11 20:42:56 -0700278
279 size_t num_accounted_for = 0;
280 size_t num_missing = 0;
281 ::std::vector<bool> accounted_for(num_messages, false);
282
283 while ((num_accounted_for + num_missing) != num_messages) {
284 num_missing = 0;
285 for (size_t i = 0; i < num_senders; ++i) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800286 Sender *const sender = memory->GetSender(i);
Philipp Schrader81fa3fb2023-09-17 18:58:35 -0700287 if (sender->ownership_tracker.OwnerIsDefinitelyAbsolutelyDead()) {
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700288 if (!need_recovery[i]) {
289 return false;
290 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700291 ++num_missing;
Brian Silverman177567e2020-08-12 19:51:33 -0700292 continue;
Austin Schuh20b2b082019-09-11 20:42:56 -0700293 }
Brian Silverman177567e2020-08-12 19:51:33 -0700294 CHECK(!need_recovery[i]) << ": Somebody else recovered a sender: " << i;
295 // We can do a relaxed load here because we're the only person touching
296 // this sender at this point, if it matters. If it's not a dead sender,
297 // then any message it ever has will eventually be accounted for if we
298 // make enough tries through the outer loop.
299 const Index scratch_index = sender->scratch_index.RelaxedLoad();
300 if (!accounted_for[scratch_index.message_index()]) {
301 ++num_accounted_for;
302 }
303 accounted_for[scratch_index.message_index()] = true;
Austin Schuh20b2b082019-09-11 20:42:56 -0700304 }
305
306 for (size_t i = 0; i < queue_size; ++i) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800307 // Same logic as above for scratch_index applies here too.
Austin Schuh20b2b082019-09-11 20:42:56 -0700308 const Index index = memory->GetQueue(i)->RelaxedLoad();
309 if (!accounted_for[index.message_index()]) {
310 ++num_accounted_for;
311 }
312 accounted_for[index.message_index()] = true;
313 }
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700314
Brian Silverman177567e2020-08-12 19:51:33 -0700315 for (size_t pinner_index = 0; pinner_index < num_pinners; ++pinner_index) {
316 // Same logic as above for scratch_index applies here too.
317 const Index index =
318 memory->GetPinner(pinner_index)->scratch_index.RelaxedLoad();
319 if (!accounted_for[index.message_index()]) {
320 ++num_accounted_for;
321 }
322 accounted_for[index.message_index()] = true;
323 }
324
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700325 CHECK_LE(num_accounted_for + num_missing, num_messages);
Austin Schuh20b2b082019-09-11 20:42:56 -0700326 }
327
328 while (num_missing != 0) {
329 const size_t starting_num_missing = num_missing;
330 for (size_t i = 0; i < num_senders; ++i) {
331 Sender *sender = memory->GetSender(i);
Philipp Schrader81fa3fb2023-09-17 18:58:35 -0700332 if (!sender->ownership_tracker.OwnerIsDefinitelyAbsolutelyDead()) {
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700333 CHECK(!need_recovery[i]) << ": Somebody else recovered a sender: " << i;
334 continue;
335 }
336 if (!need_recovery[i]) {
337 return false;
338 }
339 // We can do relaxed loads here because we're the only person touching
340 // this sender at this point.
341 const Index scratch_index = sender->scratch_index.RelaxedLoad();
342 const Index to_replace = sender->to_replace.RelaxedLoad();
Austin Schuh20b2b082019-09-11 20:42:56 -0700343
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700344 // Candidate.
345 if (to_replace.valid()) {
346 CHECK_LE(to_replace.message_index(), accounted_for.size());
347 }
348 if (scratch_index.valid()) {
349 CHECK_LE(scratch_index.message_index(), accounted_for.size());
350 }
351 if (!to_replace.valid() || accounted_for[to_replace.message_index()]) {
352 CHECK(scratch_index.valid());
353 VLOG(3) << "Sender " << i
354 << " died, to_replace is already accounted for";
355 // If both are accounted for, we are corrupt...
356 CHECK(!accounted_for[scratch_index.message_index()]);
Austin Schuh20b2b082019-09-11 20:42:56 -0700357
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700358 // to_replace is already accounted for. This means that we didn't
359 // atomically insert scratch_index into the queue yet. So
360 // invalidate to_replace.
361 sender->to_replace.Invalidate();
Brian Silverman177567e2020-08-12 19:51:33 -0700362 // Sender definitely will not have gotten here, so finish for it.
363 memory->GetMessage(scratch_index)
364 ->header.queue_index.RelaxedInvalidate();
Austin Schuh20b2b082019-09-11 20:42:56 -0700365
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700366 // And then mark this sender clean.
Philipp Schraderab2f8432023-09-17 18:58:06 -0700367 sender->ownership_tracker.ForceClear();
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700368 need_recovery[i] = false;
Austin Schuh20b2b082019-09-11 20:42:56 -0700369
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700370 // And account for scratch_index.
371 accounted_for[scratch_index.message_index()] = true;
372 --num_missing;
373 ++num_accounted_for;
374 } else if (!scratch_index.valid() ||
375 accounted_for[scratch_index.message_index()]) {
376 VLOG(3) << "Sender " << i
377 << " died, scratch_index is already accounted for";
378 // scratch_index is accounted for. That means we did the insert,
379 // but didn't record it.
380 CHECK(to_replace.valid());
Brian Silverman177567e2020-08-12 19:51:33 -0700381
382 // Make sure to indicate it's an unused message before a sender gets its
383 // hands on it.
384 memory->GetMessage(to_replace)->header.queue_index.RelaxedInvalidate();
385 aos_compiler_memory_barrier();
386
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700387 // Finish the transaction. Copy to_replace, then clear it.
Austin Schuh20b2b082019-09-11 20:42:56 -0700388
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700389 sender->scratch_index.Store(to_replace);
390 sender->to_replace.Invalidate();
Austin Schuh20b2b082019-09-11 20:42:56 -0700391
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700392 // And then mark this sender clean.
Philipp Schraderab2f8432023-09-17 18:58:06 -0700393 sender->ownership_tracker.ForceClear();
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700394 need_recovery[i] = false;
Austin Schuh20b2b082019-09-11 20:42:56 -0700395
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700396 // And account for to_replace.
397 accounted_for[to_replace.message_index()] = true;
398 --num_missing;
399 ++num_accounted_for;
400 } else {
401 VLOG(3) << "Sender " << i << " died, neither is accounted for";
402 // Ambiguous. There will be an unambiguous one somewhere that we
403 // can do first.
Austin Schuh20b2b082019-09-11 20:42:56 -0700404 }
405 }
406 // CHECK that we are making progress.
407 CHECK_NE(num_missing, starting_num_missing);
408 }
Brian Silvermand5ca8c62020-08-12 19:51:03 -0700409 return true;
410}
411
412void Cleanup(LocklessQueueMemory *memory, const GrabQueueSetupLockOrDie &lock) {
413 // The number of iterations is bounded here because there are only a finite
414 // number of senders in existence which could die, and no new ones can be
415 // created while we're in here holding the lock.
416 while (!DoCleanup(memory, lock)) {
417 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700418}
419
420// Exposes rt_tgsigqueueinfo so we can send the signal *just* to the target
421// thread.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800422// TODO(Brian): Do directly in assembly for armhf at least for efficiency.
Austin Schuh20b2b082019-09-11 20:42:56 -0700423int rt_tgsigqueueinfo(pid_t tgid, pid_t tid, int sig, siginfo_t *si) {
424 return syscall(SYS_rt_tgsigqueueinfo, tgid, tid, sig, si);
425}
426
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700427QueueIndex ZeroOrValid(QueueIndex index) {
428 if (!index.valid()) {
429 return index.Clear();
430 }
431 return index;
432}
433
Austin Schuh20b2b082019-09-11 20:42:56 -0700434} // namespace
435
Philipp Schraderab2f8432023-09-17 18:58:06 -0700436bool PretendThatOwnerIsDeadForTesting(aos_mutex *mutex, pid_t tid) {
437 if (static_cast<pid_t>(mutex->futex & FUTEX_TID_MASK) == tid) {
438 mutex->futex = FUTEX_OWNER_DIED;
439 return true;
440 }
441 return false;
442}
443
Austin Schuh4bc4f902019-12-23 18:04:51 -0800444size_t LocklessQueueConfiguration::message_size() const {
445 // Round up the message size so following data is aligned appropriately.
Brian Silverman0eaa1da2020-08-12 20:03:52 -0700446 // Make sure to leave space to align the message data. It will be aligned
447 // relative to the start of the shared memory region, but that might not be
448 // aligned for some use cases.
Brian Silvermana1652f32020-01-29 20:41:44 -0800449 return LocklessQueueMemory::AlignmentRoundUp(message_data_size +
Brian Silverman0eaa1da2020-08-12 20:03:52 -0700450 kChannelDataRedzone * 2 +
Brian Silvermana1652f32020-01-29 20:41:44 -0800451 (kChannelDataAlignment - 1)) +
Austin Schuh4bc4f902019-12-23 18:04:51 -0800452 sizeof(Message);
453}
454
Austin Schuh20b2b082019-09-11 20:42:56 -0700455size_t LocklessQueueMemorySize(LocklessQueueConfiguration config) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800456 // Round up the message size so following data is aligned appropriately.
457 config.message_data_size =
458 LocklessQueueMemory::AlignmentRoundUp(config.message_data_size);
Austin Schuh20b2b082019-09-11 20:42:56 -0700459
460 // As we build up the size, confirm that everything is aligned to the
461 // alignment requirements of the type.
462 size_t size = sizeof(LocklessQueueMemory);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800463 CHECK_EQ(size % alignof(LocklessQueueMemory), 0u);
Austin Schuh20b2b082019-09-11 20:42:56 -0700464
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800465 CHECK_EQ(size % alignof(AtomicIndex), 0u);
Austin Schuh20b2b082019-09-11 20:42:56 -0700466 size += LocklessQueueMemory::SizeOfQueue(config);
467
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800468 CHECK_EQ(size % alignof(Message), 0u);
Austin Schuh20b2b082019-09-11 20:42:56 -0700469 size += LocklessQueueMemory::SizeOfMessages(config);
470
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800471 CHECK_EQ(size % alignof(Watcher), 0u);
Austin Schuh20b2b082019-09-11 20:42:56 -0700472 size += LocklessQueueMemory::SizeOfWatchers(config);
473
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800474 CHECK_EQ(size % alignof(Sender), 0u);
Austin Schuh20b2b082019-09-11 20:42:56 -0700475 size += LocklessQueueMemory::SizeOfSenders(config);
476
Brian Silverman177567e2020-08-12 19:51:33 -0700477 CHECK_EQ(size % alignof(Pinner), 0u);
478 size += LocklessQueueMemory::SizeOfPinners(config);
479
Austin Schuh20b2b082019-09-11 20:42:56 -0700480 return size;
481}
482
Brian Silverman0eaa1da2020-08-12 20:03:52 -0700483// Calculates the starting byte for a redzone in shared memory. This starting
484// value is simply incremented for subsequent bytes.
485//
486// The result is based on the offset of the region in shared memor, to ensure it
487// is the same for each region when we generate and verify, but different for
488// each region to help catch forms of corruption like copying out-of-bounds data
489// from one place to another.
490//
491// memory is the base pointer to the shared memory. It is used to calculated
492// offsets. starting_data is the start of the redzone's data. Each one will
493// get a unique pattern.
494uint8_t RedzoneStart(const LocklessQueueMemory *memory,
495 const char *starting_data) {
496 const auto memory_int = reinterpret_cast<uintptr_t>(memory);
497 const auto starting_int = reinterpret_cast<uintptr_t>(starting_data);
498 DCHECK(starting_int >= memory_int);
499 DCHECK(starting_int < memory_int + LocklessQueueMemorySize(memory->config));
500 const uintptr_t starting_offset = starting_int - memory_int;
501 // Just XOR the lower 2 bytes. They higher-order bytes are probably 0
502 // anyways.
503 return (starting_offset & 0xFF) ^ ((starting_offset >> 8) & 0xFF);
504}
505
506// Returns true if the given redzone has invalid data.
507bool CheckRedzone(const LocklessQueueMemory *memory,
508 absl::Span<const char> redzone) {
509 uint8_t redzone_value = RedzoneStart(memory, redzone.data());
510
511 bool bad = false;
512
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700513 for (size_t i = 0; i < redzone.size() && !bad; ++i) {
Brian Silverman0eaa1da2020-08-12 20:03:52 -0700514 if (memcmp(&redzone[i], &redzone_value, 1)) {
515 bad = true;
516 }
517 ++redzone_value;
518 }
519
520 return bad;
521}
522
523// Returns true if either of message's redzones has invalid data.
524bool CheckBothRedzones(const LocklessQueueMemory *memory,
525 const Message *message) {
526 return CheckRedzone(memory,
527 message->PreRedzone(memory->message_data_size())) ||
528 CheckRedzone(memory, message->PostRedzone(memory->message_data_size(),
529 memory->message_size()));
530}
531
532// Fills the given redzone with the expected data.
533void FillRedzone(LocklessQueueMemory *memory, absl::Span<char> redzone) {
534 uint8_t redzone_value = RedzoneStart(memory, redzone.data());
535 for (size_t i = 0; i < redzone.size(); ++i) {
536 memcpy(&redzone[i], &redzone_value, 1);
537 ++redzone_value;
538 }
539
540 // Just double check that the implementations match.
541 CHECK(!CheckRedzone(memory, redzone));
542}
543
Austin Schuh20b2b082019-09-11 20:42:56 -0700544LocklessQueueMemory *InitializeLocklessQueueMemory(
545 LocklessQueueMemory *memory, LocklessQueueConfiguration config) {
546 // Everything should be zero initialized already. So we just need to fill
547 // everything out properly.
548
Brian Silvermanc57ff0a2020-04-28 16:45:13 -0700549 // This is the UID we will use for checking signal-sending permission
550 // compatibility.
551 //
552 // The manpage says:
553 // For a process to have permission to send a signal, it must either be
554 // privileged [...], or the real or effective user ID of the sending process
555 // must equal the real or saved set-user-ID of the target process.
556 //
557 // Processes typically initialize a queue in random order as they start up.
558 // This means we need an algorithm for verifying all processes have
559 // permissions to send each other signals which gives the same answer no
560 // matter what order they attach in. We would also like to avoid maintaining a
561 // shared list of the UIDs of all processes.
562 //
563 // To do this while still giving sufficient flexibility for all current use
564 // cases, we track a single UID for the queue. All processes with a matching
565 // euid+suid must have this UID. Any processes with distinct euid/suid must
566 // instead have a matching ruid. This guarantees signals can be sent between
567 // all processes attached to the queue.
568 //
569 // In particular, this allows a process to change only its euid (to interact
570 // with a queue) while still maintaining privileges via its ruid. However, it
571 // can only use privileges in ways that do not require changing the euid back,
572 // because while the euid is different it will not be able to receive signals.
573 // We can't actually verify that, but we can sanity check that things are
574 // valid when the queue is initialized.
575
576 uid_t uid;
577 {
578 uid_t ruid, euid, suid;
579 PCHECK(getresuid(&ruid, &euid, &suid) == 0);
580 // If these are equal, then use them, even if that's different from the real
581 // UID. This allows processes to keep a real UID of 0 (to have permissions
582 // to perform system-level changes) while still being able to communicate
583 // with processes running unprivileged as a distinct user.
584 if (euid == suid) {
585 uid = euid;
586 VLOG(1) << "Using euid==suid " << uid;
587 } else {
588 uid = ruid;
589 VLOG(1) << "Using ruid " << ruid;
590 }
591 }
592
Austin Schuh20b2b082019-09-11 20:42:56 -0700593 // Grab the mutex. We don't care if the previous reader died. We are going
594 // to check everything anyways.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800595 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory);
Austin Schuh20b2b082019-09-11 20:42:56 -0700596
597 if (!memory->initialized) {
598 // TODO(austin): Check these for out of bounds.
599 memory->config.num_watchers = config.num_watchers;
600 memory->config.num_senders = config.num_senders;
Brian Silverman177567e2020-08-12 19:51:33 -0700601 memory->config.num_pinners = config.num_pinners;
Austin Schuh20b2b082019-09-11 20:42:56 -0700602 memory->config.queue_size = config.queue_size;
Austin Schuh4bc4f902019-12-23 18:04:51 -0800603 memory->config.message_data_size = config.message_data_size;
Austin Schuh20b2b082019-09-11 20:42:56 -0700604
605 const size_t num_messages = memory->num_messages();
606 // There need to be at most MaxMessages() messages allocated.
607 CHECK_LE(num_messages, Index::MaxMessages());
608
609 for (size_t i = 0; i < num_messages; ++i) {
Brian Silverman0eaa1da2020-08-12 20:03:52 -0700610 Message *const message =
611 memory->GetMessage(Index(QueueIndex::Zero(memory->queue_size()), i));
612 message->header.queue_index.Invalidate();
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700613 message->header.monotonic_sent_time = monotonic_clock::min_time;
Brian Silverman0eaa1da2020-08-12 20:03:52 -0700614 FillRedzone(memory, message->PreRedzone(memory->message_data_size()));
615 FillRedzone(memory, message->PostRedzone(memory->message_data_size(),
616 memory->message_size()));
Austin Schuh20b2b082019-09-11 20:42:56 -0700617 }
618
619 for (size_t i = 0; i < memory->queue_size(); ++i) {
620 // Make the initial counter be the furthest away number. That means that
621 // index 0 should be 0xffff, 1 should be 0, etc.
622 memory->GetQueue(i)->Store(Index(QueueIndex::Zero(memory->queue_size())
623 .IncrementBy(i)
624 .DecrementBy(memory->queue_size()),
625 i));
626 }
627
628 memory->next_queue_index.Invalidate();
Brian Silvermanc57ff0a2020-04-28 16:45:13 -0700629 memory->uid = uid;
Austin Schuh20b2b082019-09-11 20:42:56 -0700630
631 for (size_t i = 0; i < memory->num_senders(); ++i) {
632 ::aos::ipc_lib::Sender *s = memory->GetSender(i);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800633 // Nobody else can possibly be touching these because we haven't set
634 // initialized to true yet.
Austin Schuh83cbb1e2023-06-23 12:59:02 -0700635 s->scratch_index.RelaxedStore(
636 Index(QueueIndex::Invalid(), i + memory->queue_size()));
Austin Schuh20b2b082019-09-11 20:42:56 -0700637 s->to_replace.RelaxedInvalidate();
638 }
639
Brian Silverman177567e2020-08-12 19:51:33 -0700640 for (size_t i = 0; i < memory->num_pinners(); ++i) {
641 ::aos::ipc_lib::Pinner *pinner = memory->GetPinner(i);
642 // Nobody else can possibly be touching these because we haven't set
643 // initialized to true yet.
644 pinner->scratch_index.RelaxedStore(
Austin Schuh83cbb1e2023-06-23 12:59:02 -0700645 Index(QueueIndex::Invalid(),
646 i + memory->num_senders() + memory->queue_size()));
Brian Silverman177567e2020-08-12 19:51:33 -0700647 pinner->pinned.Invalidate();
648 }
649
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800650 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -0700651 // Signal everything is done. This needs to be done last, so if we die, we
652 // redo initialization.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800653 memory->initialized = true;
Austin Schuh3328d132020-02-28 13:54:57 -0800654 } else {
Brennan Coslett6af53bb2023-07-18 15:22:46 -0500655 if (memory->uid != uid) {
656 // Subsequent calls to getpwuid() overwrite this
657 // pointer, pull the thing we care about into a
658 // string.
659 struct passwd const *user_pw = getpwuid(uid);
660 std::string user_username = user_pw->pw_name;
661 struct passwd const *memory_pw = getpwuid(memory->uid);
662 std::string memory_username = memory_pw->pw_name;
663 LOG(FATAL) << "Current user " << user_username << " (uid:" << uid << ") "
664 << "doesn't match shared memory user " << memory_username
665 << " (uid:" << memory->uid << "). "
Philipp Schrader5f832612023-08-21 10:29:57 -0700666 << "Log in as " << memory_username
Brennan Coslett6af53bb2023-07-18 15:22:46 -0500667 << " user to access this channel.";
668 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700669 }
670
Austin Schuh20b2b082019-09-11 20:42:56 -0700671 return memory;
672}
673
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700674void LocklessQueue::Initialize() {
675 InitializeLocklessQueueMemory(memory_, config_);
676}
Austin Schuh20b2b082019-09-11 20:42:56 -0700677
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700678LocklessQueueWatcher::~LocklessQueueWatcher() {
679 if (watcher_index_ == -1) {
680 return;
681 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700682
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700683 // Since everything is self consistent, all we need to do is make sure nobody
684 // else is running. Someone dying will get caught in the generic consistency
685 // check.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800686 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory_);
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700687
688 // Make sure we are registered.
689 CHECK_NE(watcher_index_, -1);
690
691 // Make sure we still own the slot we are supposed to.
Philipp Schraderab2f8432023-09-17 18:58:06 -0700692 CHECK(memory_->GetWatcher(watcher_index_)->ownership_tracker.IsHeldBySelf());
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700693
694 // The act of unlocking invalidates the entry. Invalidate it.
Philipp Schraderab2f8432023-09-17 18:58:06 -0700695 memory_->GetWatcher(watcher_index_)->ownership_tracker.Release();
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700696 // And internally forget the slot.
697 watcher_index_ = -1;
698
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800699 // Cleanup is cheap. The next user will do it anyways, so no need for us to do
700 // anything right now.
Austin Schuh20b2b082019-09-11 20:42:56 -0700701
702 // And confirm that nothing is owned by us.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700703 const int num_watchers = memory_->num_watchers();
Austin Schuh20b2b082019-09-11 20:42:56 -0700704 for (int i = 0; i < num_watchers; ++i) {
Philipp Schraderab2f8432023-09-17 18:58:06 -0700705 CHECK(!memory_->GetWatcher(i)->ownership_tracker.IsHeldBySelf())
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700706 << ": " << i;
Austin Schuh20b2b082019-09-11 20:42:56 -0700707 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700708}
709
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700710std::optional<LocklessQueueWatcher> LocklessQueueWatcher::Make(
711 LocklessQueue queue, int priority) {
712 queue.Initialize();
713 LocklessQueueWatcher result(queue.memory(), priority);
714 if (result.watcher_index_ != -1) {
James Kuszmaul9776b392023-01-14 14:08:08 -0800715 return result;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700716 } else {
717 return std::nullopt;
718 }
719}
Austin Schuh20b2b082019-09-11 20:42:56 -0700720
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700721LocklessQueueWatcher::LocklessQueueWatcher(LocklessQueueMemory *memory,
722 int priority)
723 : memory_(memory) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700724 // TODO(austin): Make sure signal coalescing is turned on. We don't need
725 // duplicates. That will improve performance under high load.
726
727 // Since everything is self consistent, all we need to do is make sure nobody
728 // else is running. Someone dying will get caught in the generic consistency
729 // check.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800730 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory_);
Austin Schuh20b2b082019-09-11 20:42:56 -0700731 const int num_watchers = memory_->num_watchers();
732
733 // Now, find the first empty watcher and grab it.
734 CHECK_EQ(watcher_index_, -1);
735 for (int i = 0; i < num_watchers; ++i) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800736 // If we see a slot the kernel has marked as dead, everything we do reusing
737 // it needs to happen-after whatever that process did before dying.
Philipp Schraderab2f8432023-09-17 18:58:06 -0700738 auto *const ownership_tracker =
739 &(memory_->GetWatcher(i)->ownership_tracker);
Philipp Schrader81fa3fb2023-09-17 18:58:35 -0700740 if (ownership_tracker->LoadAcquire().IsUnclaimed() ||
741 ownership_tracker->OwnerIsDefinitelyAbsolutelyDead()) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700742 watcher_index_ = i;
Brian Silverman2484eea2019-12-21 16:48:46 -0800743 // Relaxed is OK here because we're the only task going to touch it
744 // between here and the write in death_notification_init below (other
745 // recovery is blocked by us holding the setup lock).
Philipp Schraderab2f8432023-09-17 18:58:06 -0700746 ownership_tracker->ForceClear();
Austin Schuh20b2b082019-09-11 20:42:56 -0700747 break;
748 }
749 }
750
751 // Bail if we failed to find an open slot.
752 if (watcher_index_ == -1) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700753 return;
Austin Schuh20b2b082019-09-11 20:42:56 -0700754 }
755
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700756 Watcher *const w = memory_->GetWatcher(watcher_index_);
Austin Schuh20b2b082019-09-11 20:42:56 -0700757
758 w->pid = getpid();
759 w->priority = priority;
760
761 // Grabbing a mutex is a compiler and memory barrier, so nothing before will
762 // get rearranged afterwords.
Philipp Schraderab2f8432023-09-17 18:58:06 -0700763 w->ownership_tracker.Acquire();
Austin Schuh20b2b082019-09-11 20:42:56 -0700764}
765
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700766LocklessQueueWakeUpper::LocklessQueueWakeUpper(LocklessQueue queue)
767 : memory_(queue.const_memory()), pid_(getpid()), uid_(getuid()) {
768 queue.Initialize();
769 watcher_copy_.resize(memory_->num_watchers());
Austin Schuh20b2b082019-09-11 20:42:56 -0700770}
771
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700772int LocklessQueueWakeUpper::Wakeup(const int current_priority) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700773 const size_t num_watchers = memory_->num_watchers();
774
775 CHECK_EQ(watcher_copy_.size(), num_watchers);
776
777 // Grab a copy so it won't change out from underneath us, and we can sort it
778 // nicely in C++.
779 // Do note that there is still a window where the process can die *after* we
780 // read everything. We will still PI boost and send a signal to the thread in
781 // question. There is no way without pidfd's to close this window, and
782 // creating a pidfd is likely not RT.
783 for (size_t i = 0; i < num_watchers; ++i) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700784 const Watcher *w = memory_->GetWatcher(i);
Philipp Schraderab2f8432023-09-17 18:58:06 -0700785 watcher_copy_[i].ownership_snapshot = w->ownership_tracker.LoadRelaxed();
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800786 // Force the load of the TID to come first.
787 aos_compiler_memory_barrier();
788 watcher_copy_[i].pid = w->pid.load(std::memory_order_relaxed);
789 watcher_copy_[i].priority = w->priority.load(std::memory_order_relaxed);
Austin Schuh20b2b082019-09-11 20:42:56 -0700790
791 // Use a priority of -1 to mean an invalid entry to make sorting easier.
Philipp Schraderab2f8432023-09-17 18:58:06 -0700792 if (watcher_copy_[i].ownership_snapshot.OwnerIsDead() ||
793 watcher_copy_[i].ownership_snapshot.IsUnclaimed()) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700794 watcher_copy_[i].priority = -1;
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800795 } else {
796 // Ensure all of this happens after we're done looking at the pid+priority
797 // in shared memory.
798 aos_compiler_memory_barrier();
Philipp Schraderab2f8432023-09-17 18:58:06 -0700799 if (watcher_copy_[i].ownership_snapshot !=
800 w->ownership_tracker.LoadRelaxed()) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800801 // Confirm that the watcher hasn't been re-used and modified while we
802 // read it. If it has, mark it invalid again.
803 watcher_copy_[i].priority = -1;
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800804 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700805 }
806 }
807
808 // Now sort.
809 ::std::sort(watcher_copy_.begin(), watcher_copy_.end(),
810 [](const WatcherCopy &a, const WatcherCopy &b) {
811 return a.priority > b.priority;
812 });
813
814 int count = 0;
815 if (watcher_copy_[0].priority != -1) {
816 const int max_priority =
817 ::std::max(current_priority, watcher_copy_[0].priority);
818 // Boost if we are RT and there is a higher priority sender out there.
819 // Otherwise we might run into priority inversions.
820 if (max_priority > current_priority && current_priority > 0) {
Austin Schuh151f7822024-03-16 12:52:32 -0700821 // Inline the setscheduler call rather than using aos/realtime.h. This is
822 // quite performance sensitive, and halves the time needed to send a
823 // message when pi boosting is in effect.
824 if (!FLAGS_skip_realtime_scheduler) {
825 // TODO(austin): Do we need to boost the soft limit here too like we
826 // were before?
827 struct sched_param param;
828 param.sched_priority = max_priority;
829 PCHECK(sched_setscheduler(0, SCHED_FIFO, &param) == 0)
830 << ": changing to SCHED_FIFO with " << max_priority
831 << ", if you want to bypass this check for testing, use "
832 "--skip_realtime_scheduler";
833 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700834 }
835
836 // Build up the siginfo to send.
837 siginfo_t uinfo;
838 memset(&uinfo, 0, sizeof(uinfo));
839
840 uinfo.si_code = SI_QUEUE;
841 uinfo.si_pid = pid_;
842 uinfo.si_uid = uid_;
843 uinfo.si_value.sival_int = 0;
844
845 for (const WatcherCopy &watcher_copy : watcher_copy_) {
846 // The first -1 priority means we are at the end of the valid list.
847 if (watcher_copy.priority == -1) {
848 break;
849 }
850
851 // Send the signal. Target just the thread that sent it so that we can
852 // support multiple watchers in a process (when someone creates multiple
853 // event loops in different threads).
Philipp Schraderab2f8432023-09-17 18:58:06 -0700854 rt_tgsigqueueinfo(watcher_copy.pid, watcher_copy.ownership_snapshot.tid(),
855 kWakeupSignal, &uinfo);
Austin Schuh20b2b082019-09-11 20:42:56 -0700856
857 ++count;
858 }
859
860 // Drop back down if we were boosted.
861 if (max_priority > current_priority && current_priority > 0) {
Austin Schuh151f7822024-03-16 12:52:32 -0700862 if (!FLAGS_skip_realtime_scheduler) {
863 struct sched_param param;
864 param.sched_priority = current_priority;
865 PCHECK(sched_setscheduler(0, SCHED_FIFO, &param) == 0)
866 << ": changing to SCHED_FIFO with " << max_priority
867 << ", if you want to bypass this check for testing, use "
868 "--skip_realtime_scheduler";
869 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700870 }
871 }
872
873 return count;
874}
875
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700876std::ostream &operator<<(std::ostream &os,
877 const LocklessQueueSender::Result r) {
878 os << static_cast<int>(r);
879 return os;
880}
881
882LocklessQueueSender::LocklessQueueSender(
883 LocklessQueueMemory *memory,
884 monotonic_clock::duration channel_storage_duration)
885 : memory_(memory), channel_storage_duration_(channel_storage_duration) {
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800886 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory_);
Austin Schuh20b2b082019-09-11 20:42:56 -0700887
888 // Since we already have the lock, go ahead and try cleaning up.
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800889 Cleanup(memory_, grab_queue_setup_lock);
Austin Schuh20b2b082019-09-11 20:42:56 -0700890
891 const int num_senders = memory_->num_senders();
892
893 for (int i = 0; i < num_senders; ++i) {
894 ::aos::ipc_lib::Sender *s = memory->GetSender(i);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800895 // This doesn't need synchronization because we're the only process doing
896 // initialization right now, and nobody else will be touching senders which
897 // we're interested in.
Philipp Schraderab2f8432023-09-17 18:58:06 -0700898 if (s->ownership_tracker.LoadRelaxed().IsUnclaimed()) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700899 sender_index_ = i;
900 break;
901 }
902 }
903
904 if (sender_index_ == -1) {
Austin Schuhe516ab02020-05-06 21:37:04 -0700905 VLOG(1) << "Too many senders, starting to bail.";
906 return;
Austin Schuh20b2b082019-09-11 20:42:56 -0700907 }
908
Brian Silverman177567e2020-08-12 19:51:33 -0700909 ::aos::ipc_lib::Sender *const sender = memory_->GetSender(sender_index_);
Austin Schuh20b2b082019-09-11 20:42:56 -0700910
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800911 // Indicate that we are now alive by taking over the slot. If the previous
912 // owner died, we still want to do this.
Philipp Schraderab2f8432023-09-17 18:58:06 -0700913 sender->ownership_tracker.Acquire();
Brian Silverman177567e2020-08-12 19:51:33 -0700914
915 const Index scratch_index = sender->scratch_index.RelaxedLoad();
916 Message *const message = memory_->GetMessage(scratch_index);
917 CHECK(!message->header.queue_index.RelaxedLoad(memory_->queue_size()).valid())
918 << ": " << std::hex << scratch_index.get();
Austin Schuh20b2b082019-09-11 20:42:56 -0700919}
920
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700921LocklessQueueSender::~LocklessQueueSender() {
922 if (sender_index_ != -1) {
923 CHECK(memory_ != nullptr);
Philipp Schraderab2f8432023-09-17 18:58:06 -0700924 memory_->GetSender(sender_index_)->ownership_tracker.Release();
Austin Schuh20b2b082019-09-11 20:42:56 -0700925 }
926}
927
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700928std::optional<LocklessQueueSender> LocklessQueueSender::Make(
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700929 LocklessQueue queue, monotonic_clock::duration channel_storage_duration) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700930 queue.Initialize();
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700931 LocklessQueueSender result(queue.memory(), channel_storage_duration);
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700932 if (result.sender_index_ != -1) {
James Kuszmaul9776b392023-01-14 14:08:08 -0800933 return result;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700934 } else {
935 return std::nullopt;
936 }
937}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700938
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700939size_t LocklessQueueSender::size() const {
940 return memory_->message_data_size();
941}
942
943void *LocklessQueueSender::Data() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700944 ::aos::ipc_lib::Sender *sender = memory_->GetSender(sender_index_);
Brian Silverman177567e2020-08-12 19:51:33 -0700945 const Index scratch_index = sender->scratch_index.RelaxedLoad();
946 Message *const message = memory_->GetMessage(scratch_index);
947 // We should have invalidated this when we first got the buffer. Verify that
948 // in debug mode.
949 DCHECK(
950 !message->header.queue_index.RelaxedLoad(memory_->queue_size()).valid())
951 << ": " << std::hex << scratch_index.get();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700952
Brian Silvermana1652f32020-01-29 20:41:44 -0800953 return message->data(memory_->message_data_size());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700954}
955
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700956LocklessQueueSender::Result LocklessQueueSender::Send(
Austin Schuhad154822019-12-27 15:45:13 -0800957 const char *data, size_t length,
Austin Schuhb5c6f972021-03-14 21:53:07 -0700958 monotonic_clock::time_point monotonic_remote_time,
959 realtime_clock::time_point realtime_remote_time,
Austin Schuhac6d89e2024-03-27 14:56:09 -0700960 monotonic_clock::time_point monotonic_remote_transmit_time,
Austin Schuha9012be2021-07-21 15:19:11 -0700961 uint32_t remote_queue_index, const UUID &source_boot_uuid,
Austin Schuhb5c6f972021-03-14 21:53:07 -0700962 monotonic_clock::time_point *monotonic_sent_time,
963 realtime_clock::time_point *realtime_sent_time, uint32_t *queue_index) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700964 CHECK_LE(length, size());
Austin Schuh67420a42019-12-21 21:55:04 -0800965 // Flatbuffers write from the back of the buffer to the front. If we are
966 // going to write an explicit chunk of memory into the buffer, we need to
967 // adhere to this convention and place it at the end.
968 memcpy((reinterpret_cast<char *>(Data()) + size() - length), data, length);
Austin Schuh91ba6392020-10-03 13:27:47 -0700969 return Send(length, monotonic_remote_time, realtime_remote_time,
Austin Schuhac6d89e2024-03-27 14:56:09 -0700970 monotonic_remote_transmit_time, remote_queue_index,
971 source_boot_uuid, monotonic_sent_time, realtime_sent_time,
972 queue_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700973}
974
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700975LocklessQueueSender::Result LocklessQueueSender::Send(
Austin Schuhb5c6f972021-03-14 21:53:07 -0700976 size_t length, monotonic_clock::time_point monotonic_remote_time,
977 realtime_clock::time_point realtime_remote_time,
Austin Schuhac6d89e2024-03-27 14:56:09 -0700978 monotonic_clock::time_point monotonic_remote_transmit_time,
Austin Schuha9012be2021-07-21 15:19:11 -0700979 uint32_t remote_queue_index, const UUID &source_boot_uuid,
Austin Schuhb5c6f972021-03-14 21:53:07 -0700980 monotonic_clock::time_point *monotonic_sent_time,
981 realtime_clock::time_point *realtime_sent_time, uint32_t *queue_index) {
Austin Schuh20b2b082019-09-11 20:42:56 -0700982 const size_t queue_size = memory_->queue_size();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700983 CHECK_LE(length, size());
Austin Schuh20b2b082019-09-11 20:42:56 -0700984
Brian Silvermanfafe1fa2019-12-18 21:42:18 -0800985 ::aos::ipc_lib::Sender *const sender = memory_->GetSender(sender_index_);
986 // We can do a relaxed load on our sender because we're the only person
987 // modifying it right now.
988 const Index scratch_index = sender->scratch_index.RelaxedLoad();
989 Message *const message = memory_->GetMessage(scratch_index);
Austin Schuh91ba6392020-10-03 13:27:47 -0700990 if (CheckBothRedzones(memory_, message)) {
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700991 return Result::INVALID_REDZONE;
Austin Schuh91ba6392020-10-03 13:27:47 -0700992 }
Austin Schuh20b2b082019-09-11 20:42:56 -0700993
Brian Silverman177567e2020-08-12 19:51:33 -0700994 // We should have invalidated this when we first got the buffer. Verify that
995 // in debug mode.
996 DCHECK(
997 !message->header.queue_index.RelaxedLoad(memory_->queue_size()).valid())
998 << ": " << std::hex << scratch_index.get();
999
Austin Schuh20b2b082019-09-11 20:42:56 -07001000 message->header.length = length;
Austin Schuhad154822019-12-27 15:45:13 -08001001 // Pass these through. Any alternative behavior can be implemented out a
1002 // layer.
1003 message->header.remote_queue_index = remote_queue_index;
Austin Schuha9012be2021-07-21 15:19:11 -07001004 message->header.source_boot_uuid = source_boot_uuid;
Austin Schuhad154822019-12-27 15:45:13 -08001005 message->header.monotonic_remote_time = monotonic_remote_time;
1006 message->header.realtime_remote_time = realtime_remote_time;
Austin Schuhac6d89e2024-03-27 14:56:09 -07001007 message->header.monotonic_remote_transmit_time =
1008 monotonic_remote_transmit_time;
Austin Schuh20b2b082019-09-11 20:42:56 -07001009
Brian Silverman177567e2020-08-12 19:51:33 -07001010 Index to_replace = Index::Invalid();
Austin Schuh20b2b082019-09-11 20:42:56 -07001011 while (true) {
1012 const QueueIndex actual_next_queue_index =
1013 memory_->next_queue_index.Load(queue_size);
1014 const QueueIndex next_queue_index = ZeroOrValid(actual_next_queue_index);
1015
1016 const QueueIndex incremented_queue_index = next_queue_index.Increment();
1017
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001018 // This needs to synchronize with whoever the previous writer at this
1019 // location was.
Brian Silverman177567e2020-08-12 19:51:33 -07001020 to_replace = memory_->LoadIndex(next_queue_index);
Austin Schuh20b2b082019-09-11 20:42:56 -07001021
1022 const QueueIndex decremented_queue_index =
1023 next_queue_index.DecrementBy(queue_size);
1024
1025 // See if we got beat. If we did, try to atomically update
1026 // next_queue_index in case the previous writer failed and retry.
1027 if (!to_replace.IsPlausible(decremented_queue_index)) {
1028 // We don't care about the result. It will either succeed, or we got
1029 // beat in fixing it and just need to give up and try again. If we got
1030 // beat multiple times, the only way progress can be made is if the queue
1031 // is updated as well. This means that if we retry reading
1032 // next_queue_index, we will be at most off by one and can retry.
1033 //
1034 // Both require no further action from us.
1035 //
1036 // TODO(austin): If we are having fairness issues under contention, we
1037 // could have a mode bit in next_queue_index, and could use a lock or some
1038 // other form of PI boosting to let the higher priority task win.
1039 memory_->next_queue_index.CompareAndExchangeStrong(
1040 actual_next_queue_index, incremented_queue_index);
1041
Alex Perrycb7da4b2019-08-28 19:35:56 -07001042 VLOG(3) << "We were beat. Try again. Was " << std::hex
1043 << to_replace.get() << ", is " << decremented_queue_index.index();
Austin Schuh20b2b082019-09-11 20:42:56 -07001044 continue;
1045 }
1046
1047 // Confirm that the message is what it should be.
Brian Silverman177567e2020-08-12 19:51:33 -07001048 //
1049 // This is just a best-effort check to skip reading the clocks if possible.
1050 // If this fails, then the compare-exchange below definitely would, so we
1051 // can bail out now.
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001052 const Message *message_to_replace = memory_->GetMessage(to_replace);
1053 bool is_previous_index_valid = false;
Austin Schuh20b2b082019-09-11 20:42:56 -07001054 {
Austin Schuh20b2b082019-09-11 20:42:56 -07001055 const QueueIndex previous_index =
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001056 message_to_replace->header.queue_index.RelaxedLoad(queue_size);
1057 is_previous_index_valid = previous_index.valid();
1058 if (previous_index != decremented_queue_index &&
1059 is_previous_index_valid) {
Austin Schuh20b2b082019-09-11 20:42:56 -07001060 // Retry.
Alex Perrycb7da4b2019-08-28 19:35:56 -07001061 VLOG(3) << "Something fishy happened, queue index doesn't match. "
1062 "Retrying. Previous index was "
1063 << std::hex << previous_index.index() << ", should be "
1064 << decremented_queue_index.index();
Austin Schuh20b2b082019-09-11 20:42:56 -07001065 continue;
1066 }
1067 }
1068
1069 message->header.monotonic_sent_time = ::aos::monotonic_clock::now();
1070 message->header.realtime_sent_time = ::aos::realtime_clock::now();
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001071
Austin Schuhad154822019-12-27 15:45:13 -08001072 if (monotonic_sent_time != nullptr) {
1073 *monotonic_sent_time = message->header.monotonic_sent_time;
1074 }
1075 if (realtime_sent_time != nullptr) {
1076 *realtime_sent_time = message->header.realtime_sent_time;
1077 }
1078 if (queue_index != nullptr) {
1079 *queue_index = next_queue_index.index();
1080 }
Austin Schuh20b2b082019-09-11 20:42:56 -07001081
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001082 const auto to_replace_monotonic_sent_time =
1083 message_to_replace->header.monotonic_sent_time;
1084
1085 // If we are overwriting a message sent in the last
1086 // channel_storage_duration_, that means that we would be sending more than
1087 // queue_size messages and would therefore be sending too fast. If the
1088 // previous index is not valid then the message hasn't been filled out yet
1089 // so we aren't sending too fast. And, if it is not less than the sent time
1090 // of the message that we are going to write, someone else beat us and the
1091 // compare and exchange below will fail.
1092 if (is_previous_index_valid &&
1093 (to_replace_monotonic_sent_time <
1094 message->header.monotonic_sent_time) &&
1095 (message->header.monotonic_sent_time - to_replace_monotonic_sent_time <
1096 channel_storage_duration_)) {
1097 // There is a possibility that another context beat us to writing out the
1098 // message in the queue, but we beat that context to acquiring the sent
1099 // time. In this case our sent time is *greater than* the other context's
1100 // sent time. Therefore, we can check if we got beat filling out this
1101 // message *after* doing the above check to determine if we hit this edge
1102 // case. Otherwise, messages are being sent too fast.
1103 const QueueIndex previous_index =
1104 message_to_replace->header.queue_index.Load(queue_size);
1105 if (previous_index != decremented_queue_index && previous_index.valid()) {
1106 VLOG(3) << "Got beat during check for messages being sent too fast"
1107 "Retrying.";
1108 continue;
1109 } else {
Austin Schuh71e72142023-05-03 13:10:07 -07001110 VLOG(1) << "Messages sent too fast. Returning. Attempted index: "
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001111 << decremented_queue_index.index()
1112 << " message sent time: " << message->header.monotonic_sent_time
1113 << " message to replace sent time: "
1114 << to_replace_monotonic_sent_time;
Austin Schuh71e72142023-05-03 13:10:07 -07001115
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001116 // Since we are not using the message obtained from scratch_index
1117 // and we are not retrying, we need to invalidate its queue_index.
1118 message->header.queue_index.Invalidate();
1119 return Result::MESSAGES_SENT_TOO_FAST;
1120 }
1121 }
1122
Austin Schuh20b2b082019-09-11 20:42:56 -07001123 // Before we are fully done filling out the message, update the Sender state
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001124 // with the new index to write. This re-uses the barrier for the
Austin Schuh20b2b082019-09-11 20:42:56 -07001125 // queue_index store.
Alex Perrycb7da4b2019-08-28 19:35:56 -07001126 const Index index_to_write(next_queue_index, scratch_index.message_index());
Austin Schuh20b2b082019-09-11 20:42:56 -07001127
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001128 aos_compiler_memory_barrier();
1129 // We're the only person who cares about our scratch index, besides somebody
1130 // cleaning up after us.
Austin Schuh20b2b082019-09-11 20:42:56 -07001131 sender->scratch_index.RelaxedStore(index_to_write);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001132 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -07001133
1134 message->header.queue_index.Store(next_queue_index);
1135
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001136 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -07001137 // The message is now filled out, and we have a confirmed slot to store
1138 // into.
1139 //
1140 // Start by writing down what we are going to pull out of the queue. This
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001141 // was Invalid before now. Only person who will read this is whoever cleans
1142 // up after us, so no synchronization necessary.
Austin Schuh20b2b082019-09-11 20:42:56 -07001143 sender->to_replace.RelaxedStore(to_replace);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001144 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -07001145
1146 // Then exchange the next index into the queue.
1147 if (!memory_->GetQueue(next_queue_index.Wrapped())
1148 ->CompareAndExchangeStrong(to_replace, index_to_write)) {
1149 // Aw, didn't succeed. Retry.
1150 sender->to_replace.RelaxedInvalidate();
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001151 aos_compiler_memory_barrier();
Alex Perrycb7da4b2019-08-28 19:35:56 -07001152 VLOG(3) << "Failed to wrap into queue";
Austin Schuh20b2b082019-09-11 20:42:56 -07001153 continue;
1154 }
1155
1156 // Then update next_queue_index to save the next user some computation time.
1157 memory_->next_queue_index.CompareAndExchangeStrong(actual_next_queue_index,
1158 incremented_queue_index);
1159
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001160 aos_compiler_memory_barrier();
Austin Schuh20b2b082019-09-11 20:42:56 -07001161 // Now update the scratch space and record that we succeeded.
1162 sender->scratch_index.Store(to_replace);
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001163 aos_compiler_memory_barrier();
1164 // And then record that we succeeded, but definitely after the above store.
Austin Schuh20b2b082019-09-11 20:42:56 -07001165 sender->to_replace.RelaxedInvalidate();
Brian Silverman177567e2020-08-12 19:51:33 -07001166
Austin Schuh20b2b082019-09-11 20:42:56 -07001167 break;
1168 }
Brian Silverman177567e2020-08-12 19:51:33 -07001169
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001170 DCHECK(!CheckBothRedzones(memory_, memory_->GetMessage(to_replace)))
1171 << ": Invalid message found in shared memory";
Brian Silverman177567e2020-08-12 19:51:33 -07001172 // to_replace is our current scratch_index. It isn't in the queue, which means
1173 // nobody new can pin it. They can set their `pinned` to it, but they will
1174 // back it out, so they don't count. This means that we just need to find a
1175 // message for which no pinner had it in `pinned`, and then we know this
1176 // message will never be pinned. We'll start with to_replace, and if that is
1177 // pinned then we'll look for a new one to use instead.
1178 const Index new_scratch =
1179 SwapPinnedSenderScratch(memory_, sender, to_replace);
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001180 DCHECK(!CheckBothRedzones(
1181 memory_, memory_->GetMessage(sender->scratch_index.RelaxedLoad())))
1182 << ": Invalid message found in shared memory";
Brian Silverman177567e2020-08-12 19:51:33 -07001183
1184 // If anybody is looking at this message (they shouldn't be), then try telling
1185 // them about it (best-effort).
1186 memory_->GetMessage(new_scratch)->header.queue_index.RelaxedInvalidate();
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -07001187 return Result::GOOD;
Austin Schuh20b2b082019-09-11 20:42:56 -07001188}
1189
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001190int LocklessQueueSender::buffer_index() const {
Brian Silverman4f4e0612020-08-12 19:54:41 -07001191 ::aos::ipc_lib::Sender *const sender = memory_->GetSender(sender_index_);
1192 // We can do a relaxed load on our sender because we're the only person
1193 // modifying it right now.
1194 const Index scratch_index = sender->scratch_index.RelaxedLoad();
1195 return scratch_index.message_index();
1196}
1197
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001198LocklessQueuePinner::LocklessQueuePinner(
1199 LocklessQueueMemory *memory, const LocklessQueueMemory *const_memory)
1200 : memory_(memory), const_memory_(const_memory) {
1201 GrabQueueSetupLockOrDie grab_queue_setup_lock(memory_);
1202
1203 // Since we already have the lock, go ahead and try cleaning up.
1204 Cleanup(memory_, grab_queue_setup_lock);
1205
1206 const int num_pinners = memory_->num_pinners();
1207
1208 for (int i = 0; i < num_pinners; ++i) {
1209 ::aos::ipc_lib::Pinner *p = memory->GetPinner(i);
1210 // This doesn't need synchronization because we're the only process doing
1211 // initialization right now, and nobody else will be touching pinners which
1212 // we're interested in.
Philipp Schraderab2f8432023-09-17 18:58:06 -07001213 if (p->ownership_tracker.LoadRelaxed().IsUnclaimed()) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001214 pinner_index_ = i;
1215 break;
1216 }
1217 }
1218
1219 if (pinner_index_ == -1) {
1220 VLOG(1) << "Too many pinners, starting to bail.";
1221 return;
1222 }
1223
1224 ::aos::ipc_lib::Pinner *p = memory_->GetPinner(pinner_index_);
1225 p->pinned.Invalidate();
1226
1227 // Indicate that we are now alive by taking over the slot. If the previous
1228 // owner died, we still want to do this.
Philipp Schraderab2f8432023-09-17 18:58:06 -07001229 p->ownership_tracker.Acquire();
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001230}
1231
1232LocklessQueuePinner::~LocklessQueuePinner() {
1233 if (pinner_index_ != -1) {
1234 CHECK(memory_ != nullptr);
1235 memory_->GetPinner(pinner_index_)->pinned.Invalidate();
1236 aos_compiler_memory_barrier();
Philipp Schraderab2f8432023-09-17 18:58:06 -07001237 memory_->GetPinner(pinner_index_)->ownership_tracker.Release();
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001238 }
1239}
1240
1241std::optional<LocklessQueuePinner> LocklessQueuePinner::Make(
1242 LocklessQueue queue) {
1243 queue.Initialize();
1244 LocklessQueuePinner result(queue.memory(), queue.const_memory());
1245 if (result.pinner_index_ != -1) {
James Kuszmaul9776b392023-01-14 14:08:08 -08001246 return result;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001247 } else {
1248 return std::nullopt;
1249 }
1250}
1251
1252// This method doesn't mess with any scratch_index, so it doesn't have to worry
1253// about message ownership.
1254int LocklessQueuePinner::PinIndex(uint32_t uint32_queue_index) {
1255 const size_t queue_size = memory_->queue_size();
1256 const QueueIndex queue_index =
1257 QueueIndex::Zero(queue_size).IncrementBy(uint32_queue_index);
1258 ipc_lib::Pinner *const pinner = memory_->GetPinner(pinner_index_);
1259
1260 AtomicIndex *const queue_slot = memory_->GetQueue(queue_index.Wrapped());
1261
1262 // Indicate that we want to pin this message.
1263 pinner->pinned.Store(queue_index);
1264 aos_compiler_memory_barrier();
1265
1266 {
1267 const Index message_index = queue_slot->Load();
1268 Message *const message = memory_->GetMessage(message_index);
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001269 DCHECK(!CheckBothRedzones(memory_, message))
1270 << ": Invalid message found in shared memory";
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001271
1272 const QueueIndex message_queue_index =
1273 message->header.queue_index.Load(queue_size);
1274 if (message_queue_index == queue_index) {
1275 VLOG(3) << "Eq: " << std::hex << message_queue_index.index();
1276 aos_compiler_memory_barrier();
1277 return message_index.message_index();
1278 }
1279 VLOG(3) << "Message reused: " << std::hex << message_queue_index.index()
1280 << ", " << queue_index.index();
1281 }
1282
1283 // Being down here means we asked to pin a message before realizing it's no
1284 // longer in the queue, so back that out now.
1285 pinner->pinned.Invalidate();
1286 VLOG(3) << "Unpinned: " << std::hex << queue_index.index();
1287 return -1;
1288}
1289
1290size_t LocklessQueuePinner::size() const {
1291 return const_memory_->message_data_size();
1292}
1293
1294const void *LocklessQueuePinner::Data() const {
1295 const size_t queue_size = const_memory_->queue_size();
1296 const ::aos::ipc_lib::Pinner *const pinner =
1297 const_memory_->GetPinner(pinner_index_);
1298 QueueIndex pinned = pinner->pinned.RelaxedLoad(queue_size);
1299 CHECK(pinned.valid());
1300 const Message *message = const_memory_->GetMessage(pinned);
1301
1302 return message->data(const_memory_->message_data_size());
1303}
1304
1305LocklessQueueReader::Result LocklessQueueReader::Read(
Austin Schuh20b2b082019-09-11 20:42:56 -07001306 uint32_t uint32_queue_index,
Austin Schuhb5c6f972021-03-14 21:53:07 -07001307 monotonic_clock::time_point *monotonic_sent_time,
1308 realtime_clock::time_point *realtime_sent_time,
1309 monotonic_clock::time_point *monotonic_remote_time,
Austin Schuhac6d89e2024-03-27 14:56:09 -07001310 monotonic_clock::time_point *monotonic_remote_transmit_time,
Austin Schuhb5c6f972021-03-14 21:53:07 -07001311 realtime_clock::time_point *realtime_remote_time,
Austin Schuha9012be2021-07-21 15:19:11 -07001312 uint32_t *remote_queue_index, UUID *source_boot_uuid, size_t *length,
Austin Schuhfaec51a2023-09-08 17:43:32 -07001313 char *data,
1314 std::function<bool(const Context &)> should_read_callback) const {
1315 const size_t queue_size = const_memory_->queue_size();
Austin Schuh20b2b082019-09-11 20:42:56 -07001316
1317 // Build up the QueueIndex.
1318 const QueueIndex queue_index =
1319 QueueIndex::Zero(queue_size).IncrementBy(uint32_queue_index);
1320
1321 // Read the message stored at the requested location.
Austin Schuhfaec51a2023-09-08 17:43:32 -07001322 Index mi = const_memory_->LoadIndex(queue_index);
1323 const Message *m = const_memory_->GetMessage(mi);
Austin Schuh20b2b082019-09-11 20:42:56 -07001324
1325 while (true) {
Austin Schuhfaec51a2023-09-08 17:43:32 -07001326 DCHECK(!CheckBothRedzones(const_memory_, m))
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001327 << ": Invalid message found in shared memory";
Austin Schuh20b2b082019-09-11 20:42:56 -07001328 // We need to confirm that the data doesn't change while we are reading it.
1329 // Do that by first confirming that the message points to the queue index we
1330 // want.
1331 const QueueIndex starting_queue_index =
1332 m->header.queue_index.Load(queue_size);
1333 if (starting_queue_index != queue_index) {
1334 // If we found a message that is exactly 1 loop old, we just wrapped.
1335 if (starting_queue_index == queue_index.DecrementBy(queue_size)) {
Alex Perrycb7da4b2019-08-28 19:35:56 -07001336 VLOG(3) << "Matches: " << std::hex << starting_queue_index.index()
1337 << ", " << queue_index.DecrementBy(queue_size).index();
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001338 return Result::NOTHING_NEW;
Brian Silverman177567e2020-08-12 19:51:33 -07001339 }
1340
1341 // Someone has re-used this message between when we pulled it out of the
1342 // queue and when we grabbed its index. It is pretty hard to deduce
1343 // what happened. Just try again.
Austin Schuhfaec51a2023-09-08 17:43:32 -07001344 const Message *const new_m = const_memory_->GetMessage(queue_index);
Brian Silverman177567e2020-08-12 19:51:33 -07001345 if (m != new_m) {
1346 m = new_m;
1347 VLOG(3) << "Retrying, m doesn't match";
1348 continue;
1349 }
1350
1351 // We have confirmed that message still points to the same message. This
1352 // means that the message didn't get swapped out from under us, so
1353 // starting_queue_index is correct.
1354 //
1355 // Either we got too far behind (signaled by this being a valid
1356 // message), or this is one of the initial messages which are invalid.
1357 if (starting_queue_index.valid()) {
1358 VLOG(3) << "Too old. Tried for " << std::hex << queue_index.index()
1359 << ", got " << starting_queue_index.index() << ", behind by "
1360 << std::dec
1361 << (starting_queue_index.index() - queue_index.index());
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001362 return Result::TOO_OLD;
Brian Silverman177567e2020-08-12 19:51:33 -07001363 }
1364
1365 VLOG(3) << "Initial";
1366
1367 // There isn't a valid message at this location.
1368 //
1369 // If someone asks for one of the messages within the first go around,
1370 // then they need to wait. They got ahead. Otherwise, they are
1371 // asking for something crazy, like something before the beginning of
1372 // the queue. Tell them that they are behind.
Austin Schuhfaec51a2023-09-08 17:43:32 -07001373 if (uint32_queue_index < const_memory_->queue_size()) {
Brian Silverman177567e2020-08-12 19:51:33 -07001374 VLOG(3) << "Near zero, " << std::hex << uint32_queue_index;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001375 return Result::NOTHING_NEW;
Austin Schuh20b2b082019-09-11 20:42:56 -07001376 } else {
Brian Silverman177567e2020-08-12 19:51:33 -07001377 VLOG(3) << "Not near zero, " << std::hex << uint32_queue_index;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001378 return Result::TOO_OLD;
Austin Schuh20b2b082019-09-11 20:42:56 -07001379 }
1380 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001381 VLOG(3) << "Eq: " << std::hex << starting_queue_index.index() << ", "
1382 << queue_index.index();
Austin Schuh20b2b082019-09-11 20:42:56 -07001383 break;
1384 }
1385
Alex Perrycb7da4b2019-08-28 19:35:56 -07001386 // Then read the data out. Copy it all out to be deterministic and so we can
1387 // make length be from either end.
Austin Schuhfaec51a2023-09-08 17:43:32 -07001388 Context context;
1389 context.monotonic_event_time = m->header.monotonic_sent_time;
1390 context.realtime_event_time = m->header.realtime_sent_time;
1391 context.monotonic_remote_time = m->header.monotonic_remote_time;
Austin Schuhac6d89e2024-03-27 14:56:09 -07001392 context.monotonic_remote_transmit_time =
1393 m->header.monotonic_remote_transmit_time;
Austin Schuhfaec51a2023-09-08 17:43:32 -07001394 context.realtime_remote_time = m->header.realtime_remote_time;
1395 context.queue_index = queue_index.index();
1396 if (m->header.remote_queue_index == 0xffffffffu) {
1397 context.remote_queue_index = context.queue_index;
Austin Schuhad154822019-12-27 15:45:13 -08001398 } else {
Austin Schuhfaec51a2023-09-08 17:43:32 -07001399 context.remote_queue_index = m->header.remote_queue_index;
1400 }
1401 context.source_boot_uuid = m->header.source_boot_uuid;
1402 context.size = m->header.length;
1403 context.data = nullptr;
1404 context.buffer_index = -1;
Austin Schuh82ea7382023-07-14 15:17:34 -07001405
Austin Schuhfaec51a2023-09-08 17:43:32 -07001406 // If the callback is provided, use it.
1407 if (should_read_callback) {
Austin Schuh82ea7382023-07-14 15:17:34 -07001408 // And finally, confirm that the message *still* points to the queue index
1409 // we want. This means it didn't change out from under us. If something
1410 // changed out from under us, we were reading it much too late in its
1411 // lifetime.
1412 aos_compiler_memory_barrier();
1413 const QueueIndex final_queue_index = m->header.queue_index.Load(queue_size);
1414 if (final_queue_index != queue_index) {
1415 VLOG(3) << "Changed out from under us. Reading " << std::hex
1416 << queue_index.index() << ", finished with "
1417 << final_queue_index.index() << ", delta: " << std::dec
1418 << (final_queue_index.index() - queue_index.index());
1419 return Result::OVERWROTE;
1420 }
1421
1422 // We now know that the context is safe to use. See if we are supposed to
1423 // take the message or not.
Austin Schuhfaec51a2023-09-08 17:43:32 -07001424 if (!should_read_callback(context)) {
Austin Schuh82ea7382023-07-14 15:17:34 -07001425 return Result::FILTERED;
1426 }
Austin Schuhad154822019-12-27 15:45:13 -08001427 }
Austin Schuh20b2b082019-09-11 20:42:56 -07001428
Austin Schuhfaec51a2023-09-08 17:43:32 -07001429 // Read the data if requested.
1430 if (data) {
1431 memcpy(data, m->data(const_memory_->message_data_size()),
1432 const_memory_->message_data_size());
1433 }
1434
1435 // Now, we need to confirm that nothing has changed by re-reading the queue
1436 // index from the header since we've read all the body. We only need to do it
1437 // if we have read anything new after the previous check up above, which
1438 // happens if we read the data, or if we didn't check for the filtered case.
1439 if (data || !should_read_callback) {
Austin Schuh82ea7382023-07-14 15:17:34 -07001440 aos_compiler_memory_barrier();
1441 const QueueIndex final_queue_index = m->header.queue_index.Load(queue_size);
1442 if (final_queue_index != queue_index) {
1443 VLOG(3) << "Changed out from under us. Reading " << std::hex
1444 << queue_index.index() << ", finished with "
1445 << final_queue_index.index() << ", delta: " << std::dec
1446 << (final_queue_index.index() - queue_index.index());
1447 return Result::OVERWROTE;
1448 }
Austin Schuh20b2b082019-09-11 20:42:56 -07001449 }
1450
Austin Schuhfaec51a2023-09-08 17:43:32 -07001451 // And now take it and make it visible to the user. By doing it here, we will
1452 // never present partial or corrupted state to the user in the output
1453 // pointers.
1454 *monotonic_sent_time = context.monotonic_event_time;
1455 *realtime_sent_time = context.realtime_event_time;
1456 *remote_queue_index = context.remote_queue_index;
1457 *monotonic_remote_time = context.monotonic_remote_time;
Austin Schuhac6d89e2024-03-27 14:56:09 -07001458 *monotonic_remote_transmit_time = context.monotonic_remote_transmit_time;
Austin Schuhfaec51a2023-09-08 17:43:32 -07001459 *realtime_remote_time = context.realtime_remote_time;
1460 *source_boot_uuid = context.source_boot_uuid;
1461 *length = context.size;
1462
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001463 return Result::GOOD;
Austin Schuh20b2b082019-09-11 20:42:56 -07001464}
1465
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001466QueueIndex LocklessQueueReader::LatestIndex() const {
Austin Schuhfaec51a2023-09-08 17:43:32 -07001467 const size_t queue_size = const_memory_->queue_size();
Austin Schuh20b2b082019-09-11 20:42:56 -07001468
Austin Schuhfaec51a2023-09-08 17:43:32 -07001469 // There are 2 main cases. Either the next queue index is right, or it is
1470 // behind by 1 and wrong. If nothing has been published, the next queue index
1471 // will be the reserved "Invalid" value, otherwise it will point to the next
1472 // place to write. We need to figure out if it is right or wrong, and it if
1473 // is wrong, fix it. If we don't, Read() can find the next message before
1474 // LatestIndex() sees it if someone is hammering on Read() until it returns
1475 // nothing new is left, which mean watchers and fetchers may disagree on when
1476 // a message is published.
1477 QueueIndex actual_next_queue_index =
1478 const_memory_->next_queue_index.Load(queue_size);
1479
1480 // Handle the "nothing has been published" case by making next_queue_index
1481 // point to the 0th index.
1482 const QueueIndex next_queue_index = ZeroOrValid(actual_next_queue_index);
1483
1484 // This needs to synchronize with whoever the previous writer at this
1485 // location was. Read what is there to see if the message has been published
1486 // and next_queue_index is just behind.
1487 Index to_replace = const_memory_->LoadIndex(next_queue_index);
1488
1489 // See if next_queue_index is consistent with the state of the queue. If it
1490 // is not, try to atomically update next_queue_index in case the previous
1491 // writer failed and retry.
1492 if (to_replace.IsPlausible(next_queue_index)) {
1493 // If next_queue_index ends up pointing to a message with a matching index,
1494 // this is what next_queue_index needs to be updated to
1495 const QueueIndex incremented_queue_index = next_queue_index.Increment();
1496
1497 // We don't care about the result. It will either succeed, or we got
1498 // beat in fixing it. The way the Send logic works, the pointer can never
1499 // get more than 1 behind or the next send will repair it. So, if we fail,
1500 // that means that someone else got there first and fixed it up (and
1501 // potentially someone further continued to send).
1502 //
1503 // Both require no further action from us. Worst case, our Next pointer
1504 // will not be the latest message, but there will always be a point after
1505 // which the index can change. We just need a consistent snapshot where
1506 // there is nothing in the queue that isn't accounted for by
1507 // next_queue_index.
1508 memory_->next_queue_index.CompareAndExchangeStrong(actual_next_queue_index,
1509 incremented_queue_index);
1510
1511 VLOG(3) << "next_queue_index is lagging, fixed it. Found " << std::hex
1512 << to_replace.get() << ", expected "
1513 << next_queue_index.DecrementBy(queue_size).index();
1514
1515 actual_next_queue_index = incremented_queue_index;
1516 }
1517
1518 if (actual_next_queue_index.valid()) {
1519 const QueueIndex current_queue_index =
1520 actual_next_queue_index.DecrementBy(1u);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001521 return current_queue_index;
Austin Schuh20b2b082019-09-11 20:42:56 -07001522 }
Brian Silvermanfc0d2e82020-08-12 19:58:35 -07001523 return QueueIndex::Invalid();
1524}
1525
1526size_t LocklessQueueSize(const LocklessQueueMemory *memory) {
1527 return memory->queue_size();
1528}
1529
1530size_t LocklessQueueMessageDataSize(const LocklessQueueMemory *memory) {
1531 return memory->message_data_size();
Austin Schuh20b2b082019-09-11 20:42:56 -07001532}
1533
1534namespace {
1535
1536// Prints out the mutex state. Not safe to use while the mutex is being
1537// changed.
Austin Schuh83cbb1e2023-06-23 12:59:02 -07001538::std::string PrintMutex(const aos_mutex *mutex) {
Austin Schuh20b2b082019-09-11 20:42:56 -07001539 ::std::stringstream s;
1540 s << "aos_mutex(" << ::std::hex << mutex->futex;
1541
1542 if (mutex->futex != 0) {
1543 s << ":";
1544 if (mutex->futex & FUTEX_OWNER_DIED) {
1545 s << "FUTEX_OWNER_DIED|";
1546 }
1547 s << "tid=" << (mutex->futex & FUTEX_TID_MASK);
1548 }
1549
1550 s << ")";
1551 return s.str();
1552}
1553
1554} // namespace
1555
Austin Schuh83cbb1e2023-06-23 12:59:02 -07001556void PrintLocklessQueueMemory(const LocklessQueueMemory *memory) {
Austin Schuh20b2b082019-09-11 20:42:56 -07001557 const size_t queue_size = memory->queue_size();
1558 ::std::cout << "LocklessQueueMemory (" << memory << ") {" << ::std::endl;
1559 ::std::cout << " aos_mutex queue_setup_lock = "
1560 << PrintMutex(&memory->queue_setup_lock) << ::std::endl;
Brian Silvermanfafe1fa2019-12-18 21:42:18 -08001561 ::std::cout << " bool initialized = " << memory->initialized << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001562 ::std::cout << " config {" << ::std::endl;
1563 ::std::cout << " size_t num_watchers = " << memory->config.num_watchers
1564 << ::std::endl;
1565 ::std::cout << " size_t num_senders = " << memory->config.num_senders
1566 << ::std::endl;
Brian Silverman177567e2020-08-12 19:51:33 -07001567 ::std::cout << " size_t num_pinners = " << memory->config.num_pinners
1568 << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001569 ::std::cout << " size_t queue_size = " << memory->config.queue_size
1570 << ::std::endl;
1571 ::std::cout << " size_t message_data_size = "
1572 << memory->config.message_data_size << ::std::endl;
1573
1574 ::std::cout << " AtomicQueueIndex next_queue_index = "
1575 << memory->next_queue_index.Load(queue_size).DebugString()
1576 << ::std::endl;
1577
Austin Schuh3328d132020-02-28 13:54:57 -08001578 ::std::cout << " uid_t uid = " << memory->uid << ::std::endl;
1579
Austin Schuh20b2b082019-09-11 20:42:56 -07001580 ::std::cout << " }" << ::std::endl;
1581 ::std::cout << " AtomicIndex queue[" << queue_size << "] {" << ::std::endl;
1582 for (size_t i = 0; i < queue_size; ++i) {
1583 ::std::cout << " [" << i << "] -> "
1584 << memory->GetQueue(i)->Load().DebugString() << ::std::endl;
1585 }
1586 ::std::cout << " }" << ::std::endl;
1587 ::std::cout << " Message messages[" << memory->num_messages() << "] {"
1588 << ::std::endl;
1589 for (size_t i = 0; i < memory->num_messages(); ++i) {
Austin Schuh83cbb1e2023-06-23 12:59:02 -07001590 const Message *m = memory->GetMessage(Index(i, i));
Brian Silverman001f24d2020-08-12 19:33:20 -07001591 ::std::cout << " [" << i << "] -> Message 0x" << std::hex
1592 << (reinterpret_cast<uintptr_t>(
1593 memory->GetMessage(Index(i, i))) -
1594 reinterpret_cast<uintptr_t>(memory))
1595 << std::dec << " {" << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001596 ::std::cout << " Header {" << ::std::endl;
1597 ::std::cout << " AtomicQueueIndex queue_index = "
1598 << m->header.queue_index.Load(queue_size).DebugString()
1599 << ::std::endl;
Brian Silverman001f24d2020-08-12 19:33:20 -07001600 ::std::cout << " monotonic_clock::time_point monotonic_sent_time = "
1601 << m->header.monotonic_sent_time << " 0x" << std::hex
1602 << m->header.monotonic_sent_time.time_since_epoch().count()
1603 << std::dec << ::std::endl;
1604 ::std::cout << " realtime_clock::time_point realtime_sent_time = "
1605 << m->header.realtime_sent_time << " 0x" << std::hex
1606 << m->header.realtime_sent_time.time_since_epoch().count()
1607 << std::dec << ::std::endl;
1608 ::std::cout
1609 << " monotonic_clock::time_point monotonic_remote_time = "
1610 << m->header.monotonic_remote_time << " 0x" << std::hex
1611 << m->header.monotonic_remote_time.time_since_epoch().count()
1612 << std::dec << ::std::endl;
Austin Schuhac6d89e2024-03-27 14:56:09 -07001613 ::std::cout
1614 << " monotonic_clock::time_point "
1615 "monotonic_remote_transmit_time = "
1616 << m->header.monotonic_remote_transmit_time << " 0x" << std::hex
1617 << m->header.monotonic_remote_transmit_time.time_since_epoch().count()
1618 << std::dec << ::std::endl;
Brian Silverman001f24d2020-08-12 19:33:20 -07001619 ::std::cout << " realtime_clock::time_point realtime_remote_time = "
1620 << m->header.realtime_remote_time << " 0x" << std::hex
1621 << m->header.realtime_remote_time.time_since_epoch().count()
1622 << std::dec << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001623 ::std::cout << " size_t length = " << m->header.length
1624 << ::std::endl;
1625 ::std::cout << " }" << ::std::endl;
Austin Schuhbe416742020-10-03 17:24:26 -07001626 const bool corrupt = CheckBothRedzones(memory, m);
1627 if (corrupt) {
Austin Schuh83cbb1e2023-06-23 12:59:02 -07001628 absl::Span<const char> pre_redzone =
1629 m->PreRedzone(memory->message_data_size());
1630 absl::Span<const char> post_redzone =
Austin Schuhbe416742020-10-03 17:24:26 -07001631 m->PostRedzone(memory->message_data_size(), memory->message_size());
1632
1633 ::std::cout << " pre-redzone: \""
1634 << absl::BytesToHexString(std::string_view(
1635 pre_redzone.data(), pre_redzone.size()))
1636 << std::endl;
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001637 ::std::cout << " // *** DATA REDZONES ARE CORRUPTED ***"
1638 << ::std::endl;
Austin Schuhbe416742020-10-03 17:24:26 -07001639 ::std::cout << " post-redzone: \""
1640 << absl::BytesToHexString(std::string_view(
1641 post_redzone.data(), post_redzone.size()))
1642 << std::endl;
Brian Silverman0eaa1da2020-08-12 20:03:52 -07001643 }
Austin Schuh20b2b082019-09-11 20:42:56 -07001644 ::std::cout << " data: {";
1645
Brian Silverman001f24d2020-08-12 19:33:20 -07001646 if (FLAGS_dump_lockless_queue_data) {
1647 const char *const m_data = m->data(memory->message_data_size());
Austin Schuhbe416742020-10-03 17:24:26 -07001648 std::cout << absl::BytesToHexString(std::string_view(
1649 m_data, corrupt ? memory->message_data_size() : m->header.length));
Austin Schuh20b2b082019-09-11 20:42:56 -07001650 }
1651 ::std::cout << ::std::setfill(' ') << ::std::dec << "}" << ::std::endl;
1652 ::std::cout << " }," << ::std::endl;
1653 }
1654 ::std::cout << " }" << ::std::endl;
1655
Alex Perrycb7da4b2019-08-28 19:35:56 -07001656 ::std::cout << " Sender senders[" << memory->num_senders() << "] {"
1657 << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001658 for (size_t i = 0; i < memory->num_senders(); ++i) {
Austin Schuh83cbb1e2023-06-23 12:59:02 -07001659 const Sender *s = memory->GetSender(i);
Austin Schuh20b2b082019-09-11 20:42:56 -07001660 ::std::cout << " [" << i << "] -> Sender {" << ::std::endl;
Philipp Schraderab2f8432023-09-17 18:58:06 -07001661 ::std::cout << " RobustOwnershipTracker ownership_tracker = "
1662 << s->ownership_tracker.DebugString() << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001663 ::std::cout << " AtomicIndex scratch_index = "
1664 << s->scratch_index.Load().DebugString() << ::std::endl;
1665 ::std::cout << " AtomicIndex to_replace = "
1666 << s->to_replace.Load().DebugString() << ::std::endl;
1667 ::std::cout << " }" << ::std::endl;
1668 }
1669 ::std::cout << " }" << ::std::endl;
1670
Brian Silverman177567e2020-08-12 19:51:33 -07001671 ::std::cout << " Pinner pinners[" << memory->num_pinners() << "] {"
1672 << ::std::endl;
1673 for (size_t i = 0; i < memory->num_pinners(); ++i) {
Austin Schuh83cbb1e2023-06-23 12:59:02 -07001674 const Pinner *p = memory->GetPinner(i);
Brian Silverman177567e2020-08-12 19:51:33 -07001675 ::std::cout << " [" << i << "] -> Pinner {" << ::std::endl;
Philipp Schraderab2f8432023-09-17 18:58:06 -07001676 ::std::cout << " RobustOwnershipTracker ownership_tracker = "
1677 << p->ownership_tracker.DebugString() << ::std::endl;
Brian Silverman177567e2020-08-12 19:51:33 -07001678 ::std::cout << " AtomicIndex scratch_index = "
1679 << p->scratch_index.Load().DebugString() << ::std::endl;
1680 ::std::cout << " AtomicIndex pinned = "
1681 << p->pinned.Load(memory->queue_size()).DebugString()
1682 << ::std::endl;
1683 ::std::cout << " }" << ::std::endl;
1684 }
1685 ::std::cout << " }" << ::std::endl;
1686
Austin Schuh20b2b082019-09-11 20:42:56 -07001687 ::std::cout << " Watcher watchers[" << memory->num_watchers() << "] {"
1688 << ::std::endl;
1689 for (size_t i = 0; i < memory->num_watchers(); ++i) {
Austin Schuh83cbb1e2023-06-23 12:59:02 -07001690 const Watcher *w = memory->GetWatcher(i);
Austin Schuh20b2b082019-09-11 20:42:56 -07001691 ::std::cout << " [" << i << "] -> Watcher {" << ::std::endl;
Philipp Schraderab2f8432023-09-17 18:58:06 -07001692 ::std::cout << " RobustOwnershipTracker ownership_tracker = "
1693 << w->ownership_tracker.DebugString() << ::std::endl;
Austin Schuh20b2b082019-09-11 20:42:56 -07001694 ::std::cout << " pid_t pid = " << w->pid << ::std::endl;
1695 ::std::cout << " int priority = " << w->priority << ::std::endl;
1696 ::std::cout << " }" << ::std::endl;
1697 }
1698 ::std::cout << " }" << ::std::endl;
1699
1700 ::std::cout << "}" << ::std::endl;
1701}
1702
Stephan Pleinesf63bde82024-01-13 15:59:33 -08001703} // namespace aos::ipc_lib