blob: e15c0141886c5fcaf3c60513c374a358a501b10f [file] [log] [blame]
Alex Perrycb7da4b2019-08-28 19:35:56 -07001#include "aos/events/shm_event_loop.h"
2
Alex Perrycb7da4b2019-08-28 19:35:56 -07003#include <sys/stat.h>
Austin Schuh39788ff2019-12-01 18:22:57 -08004#include <sys/syscall.h>
Alex Perrycb7da4b2019-08-28 19:35:56 -07005#include <sys/types.h>
Tyler Chatow67ddb032020-01-12 14:30:04 -08006
Alex Perrycb7da4b2019-08-28 19:35:56 -07007#include <algorithm>
8#include <atomic>
9#include <chrono>
Austin Schuh39788ff2019-12-01 18:22:57 -080010#include <iterator>
Alex Perrycb7da4b2019-08-28 19:35:56 -070011#include <stdexcept>
12
Philipp Schrader790cb542023-07-05 21:06:52 -070013#include "glog/logging.h"
14
Tyler Chatow67ddb032020-01-12 14:30:04 -080015#include "aos/events/aos_logging.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070016#include "aos/events/epoll.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080017#include "aos/events/event_loop_generated.h"
18#include "aos/events/timing_statistics.h"
Austin Schuh094d09b2020-11-20 23:26:52 -080019#include "aos/init.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070020#include "aos/ipc_lib/lockless_queue.h"
Austin Schuh4d275fc2022-09-16 15:42:45 -070021#include "aos/ipc_lib/memory_mapped_queue.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070022#include "aos/realtime.h"
Austin Schuh32fd5a72019-12-01 22:20:26 -080023#include "aos/stl_mutex/stl_mutex.h"
Austin Schuhfccb2d02020-01-26 16:11:19 -080024#include "aos/util/file.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070025#include "aos/util/phased_loop.h"
26
Austin Schuhe84c3ed2019-12-14 15:29:48 -080027namespace {
28
29// Returns the portion of the path after the last /. This very much assumes
30// that the application name is null terminated.
31const char *Filename(const char *path) {
32 const std::string_view path_string_view = path;
33 auto last_slash_pos = path_string_view.find_last_of("/");
34
35 return last_slash_pos == std::string_view::npos ? path
36 : path + last_slash_pos + 1;
37}
38
39} // namespace
40
Brennan Coslett6fd3c002023-07-11 17:41:09 -050041// This value is affected by the umask of the process which is calling it
42// and is set to the user's value by default (check yours running `umask` on
43// the command line).
44// Any file mode requested is transformed using: mode & ~umask and the default
45// umask is 0022 (allow any permissions for the user, dont allow writes for
46// groups or others).
47// See https://man7.org/linux/man-pages/man2/umask.2.html for more details.
48// WITH THE DEFAULT UMASK YOU WONT ACTUALLY GET THESE PERMISSIONS :)
Alex Perrycb7da4b2019-08-28 19:35:56 -070049DEFINE_uint32(permissions, 0770,
Brennan Coslett6fd3c002023-07-11 17:41:09 -050050 "Permissions to make shared memory files and folders, "
Brennan Coslettd5077bc2023-07-13 08:49:35 -050051 "affected by the process's umask. "
Brennan Coslett6fd3c002023-07-11 17:41:09 -050052 "See shm_event_loop.cc for more details.");
Austin Schuhe84c3ed2019-12-14 15:29:48 -080053DEFINE_string(application_name, Filename(program_invocation_name),
54 "The application name");
Alex Perrycb7da4b2019-08-28 19:35:56 -070055
56namespace aos {
57
Brian Silverman148d43d2020-06-07 18:19:22 -050058using namespace shm_event_loop_internal;
59
Brian Silverman4f4e0612020-08-12 19:54:41 -070060namespace {
61
Austin Schuh217a9782019-12-21 23:02:50 -080062const Node *MaybeMyNode(const Configuration *configuration) {
63 if (!configuration->has_nodes()) {
64 return nullptr;
65 }
Alex Perrycb7da4b2019-08-28 19:35:56 -070066
Austin Schuh217a9782019-12-21 23:02:50 -080067 return configuration::GetMyNode(configuration);
68}
Alex Perrycb7da4b2019-08-28 19:35:56 -070069
Philipp Schradera8734662023-08-06 14:49:39 -070070void IgnoreWakeupSignal() {
71 struct sigaction action;
72 action.sa_handler = SIG_IGN;
73 PCHECK(sigemptyset(&action.sa_mask) == 0);
74 action.sa_flags = 0;
75 PCHECK(sigaction(ipc_lib::kWakeupSignal, &action, nullptr) == 0);
76}
77
Austin Schuh39788ff2019-12-01 18:22:57 -080078} // namespace
79
Austin Schuh217a9782019-12-21 23:02:50 -080080ShmEventLoop::ShmEventLoop(const Configuration *configuration)
Austin Schuh83c7f702021-01-19 22:36:29 -080081 : EventLoop(configuration),
82 boot_uuid_(UUID::BootUUID()),
Austin Schuhef323c02020-09-01 14:55:28 -070083 shm_base_(FLAGS_shm_base),
Austin Schuhe84c3ed2019-12-14 15:29:48 -080084 name_(FLAGS_application_name),
Austin Schuh15649d62019-12-28 16:36:38 -080085 node_(MaybeMyNode(configuration)) {
Philipp Schradera8734662023-08-06 14:49:39 -070086 // Ignore the wakeup signal by default. Otherwise, we have race conditions on
87 // shutdown where a wakeup signal will uncleanly terminate the process.
88 // See LocklessQueueWakeUpper::Wakeup() for some more information.
89 IgnoreWakeupSignal();
90
Austin Schuh094d09b2020-11-20 23:26:52 -080091 CHECK(IsInitialized()) << ": Need to initialize AOS first.";
Austin Schuh0debde12022-08-17 16:25:17 -070092 ClearContext();
Austin Schuh15649d62019-12-28 16:36:38 -080093 if (configuration->has_nodes()) {
94 CHECK(node_ != nullptr) << ": Couldn't find node in config.";
95 }
96}
Austin Schuh217a9782019-12-21 23:02:50 -080097
Brian Silverman148d43d2020-06-07 18:19:22 -050098namespace shm_event_loop_internal {
Austin Schuh39788ff2019-12-01 18:22:57 -080099
100class SimpleShmFetcher {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700101 public:
Austin Schuhef323c02020-09-01 14:55:28 -0700102 explicit SimpleShmFetcher(std::string_view shm_base, ShmEventLoop *event_loop,
103 const Channel *channel)
Austin Schuh432784f2020-06-23 17:27:35 -0700104 : event_loop_(event_loop),
105 channel_(channel),
Austin Schuh4d275fc2022-09-16 15:42:45 -0700106 lockless_queue_memory_(shm_base, FLAGS_permissions,
107 event_loop->configuration(), channel),
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700108 reader_(lockless_queue_memory_.queue()) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700109 context_.data = nullptr;
110 // Point the queue index at the next index to read starting now. This
111 // makes it such that FetchNext will read the next message sent after
112 // the fetcher is created.
113 PointAtNextQueueIndex();
114 }
115
Austin Schuh39788ff2019-12-01 18:22:57 -0800116 ~SimpleShmFetcher() {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700117
Brian Silverman77162972020-08-12 19:52:40 -0700118 // Sets this object to pin or copy data, as configured in the channel.
119 void RetrieveData() {
120 if (channel_->read_method() == ReadMethod::PIN) {
121 PinDataOnFetch();
122 } else {
123 CopyDataOnFetch();
124 }
125 }
126
Brian Silverman3bca5322020-08-12 19:35:29 -0700127 // Sets this object to copy data out of the shared memory into a private
128 // buffer when fetching.
129 void CopyDataOnFetch() {
Brian Silverman77162972020-08-12 19:52:40 -0700130 CHECK(!pin_data());
Brian Silverman3bca5322020-08-12 19:35:29 -0700131 data_storage_.reset(static_cast<char *>(
132 malloc(channel_->max_size() + kChannelDataAlignment - 1)));
133 }
134
Brian Silverman77162972020-08-12 19:52:40 -0700135 // Sets this object to pin data in shared memory when fetching.
136 void PinDataOnFetch() {
137 CHECK(!copy_data());
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700138 auto maybe_pinner =
139 ipc_lib::LocklessQueuePinner::Make(lockless_queue_memory_.queue());
Brian Silverman77162972020-08-12 19:52:40 -0700140 if (!maybe_pinner) {
141 LOG(FATAL) << "Failed to create reader on "
142 << configuration::CleanedChannelToString(channel_)
143 << ", too many readers.";
144 }
145 pinner_ = std::move(maybe_pinner.value());
146 }
147
Alex Perrycb7da4b2019-08-28 19:35:56 -0700148 // Points the next message to fetch at the queue index which will be
149 // populated next.
150 void PointAtNextQueueIndex() {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700151 actual_queue_index_ = reader_.LatestIndex();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700152 if (!actual_queue_index_.valid()) {
153 // Nothing in the queue. The next element will show up at the 0th
154 // index in the queue.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700155 actual_queue_index_ = ipc_lib::QueueIndex::Zero(
156 LocklessQueueSize(lockless_queue_memory_.memory()));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700157 } else {
158 actual_queue_index_ = actual_queue_index_.Increment();
159 }
160 }
161
Austin Schuh2b4661a2023-09-20 21:37:33 -0700162 bool FetchNext() { return FetchNextIf(should_fetch_); }
Austin Schuh98ed26f2023-07-19 14:12:28 -0700163
164 bool FetchNextIf(std::function<bool(const Context &)> fn) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700165 const ipc_lib::LocklessQueueReader::Result read_result =
Austin Schuh98ed26f2023-07-19 14:12:28 -0700166 DoFetch(actual_queue_index_, std::move(fn));
Austin Schuh432784f2020-06-23 17:27:35 -0700167
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700168 return read_result == ipc_lib::LocklessQueueReader::Result::GOOD;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700169 }
170
Austin Schuh98ed26f2023-07-19 14:12:28 -0700171 bool FetchIf(std::function<bool(const Context &)> fn) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700172 const ipc_lib::QueueIndex queue_index = reader_.LatestIndex();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700173 // actual_queue_index_ is only meaningful if it was set by Fetch or
174 // FetchNext. This happens when valid_data_ has been set. So, only
175 // skip checking if valid_data_ is true.
176 //
177 // Also, if the latest queue index is invalid, we are empty. So there
178 // is nothing to fetch.
Austin Schuh39788ff2019-12-01 18:22:57 -0800179 if ((context_.data != nullptr &&
Alex Perrycb7da4b2019-08-28 19:35:56 -0700180 queue_index == actual_queue_index_.DecrementBy(1u)) ||
181 !queue_index.valid()) {
182 return false;
183 }
184
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700185 const ipc_lib::LocklessQueueReader::Result read_result =
Austin Schuh98ed26f2023-07-19 14:12:28 -0700186 DoFetch(queue_index, std::move(fn));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700187
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700188 CHECK(read_result != ipc_lib::LocklessQueueReader::Result::NOTHING_NEW)
Austin Schuhf5652592019-12-29 16:26:15 -0800189 << ": Queue index went backwards. This should never happen. "
190 << configuration::CleanedChannelToString(channel_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700191
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700192 return read_result == ipc_lib::LocklessQueueReader::Result::GOOD;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700193 }
194
Austin Schuh2b4661a2023-09-20 21:37:33 -0700195 bool Fetch() { return FetchIf(should_fetch_); }
Austin Schuh98ed26f2023-07-19 14:12:28 -0700196
Austin Schuh39788ff2019-12-01 18:22:57 -0800197 Context context() const { return context_; }
198
Alex Perrycb7da4b2019-08-28 19:35:56 -0700199 bool RegisterWakeup(int priority) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700200 CHECK(!watcher_);
201 watcher_ = ipc_lib::LocklessQueueWatcher::Make(
202 lockless_queue_memory_.queue(), priority);
203 return static_cast<bool>(watcher_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700204 }
205
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700206 void UnregisterWakeup() {
207 CHECK(watcher_);
208 watcher_ = std::nullopt;
209 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700210
Brian Silvermana5450a92020-08-12 19:59:57 -0700211 absl::Span<char> GetMutableSharedMemory() {
212 return lockless_queue_memory_.GetMutableSharedMemory();
Brian Silverman5120afb2020-01-31 17:44:35 -0800213 }
214
Brian Silvermana5450a92020-08-12 19:59:57 -0700215 absl::Span<const char> GetConstSharedMemory() const {
216 return lockless_queue_memory_.GetConstSharedMemory();
217 }
218
219 absl::Span<const char> GetPrivateMemory() const {
220 if (pin_data()) {
221 return lockless_queue_memory_.GetConstSharedMemory();
222 }
Brian Silverman6d2b3592020-06-18 14:40:15 -0700223 return absl::Span<char>(
224 const_cast<SimpleShmFetcher *>(this)->data_storage_start(),
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700225 LocklessQueueMessageDataSize(lockless_queue_memory_.memory()));
Brian Silverman6d2b3592020-06-18 14:40:15 -0700226 }
227
Alex Perrycb7da4b2019-08-28 19:35:56 -0700228 private:
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700229 ipc_lib::LocklessQueueReader::Result DoFetch(
Austin Schuh98ed26f2023-07-19 14:12:28 -0700230 ipc_lib::QueueIndex queue_index,
231 std::function<bool(const Context &context)> fn) {
Brian Silverman3bca5322020-08-12 19:35:29 -0700232 // TODO(austin): Get behind and make sure it dies.
233 char *copy_buffer = nullptr;
234 if (copy_data()) {
235 copy_buffer = data_storage_start();
236 }
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700237 ipc_lib::LocklessQueueReader::Result read_result = reader_.Read(
Brian Silverman3bca5322020-08-12 19:35:29 -0700238 queue_index.index(), &context_.monotonic_event_time,
239 &context_.realtime_event_time, &context_.monotonic_remote_time,
Austin Schuhac6d89e2024-03-27 14:56:09 -0700240 &context_.monotonic_remote_transmit_time,
Brian Silverman3bca5322020-08-12 19:35:29 -0700241 &context_.realtime_remote_time, &context_.remote_queue_index,
Austin Schuh98ed26f2023-07-19 14:12:28 -0700242 &context_.source_boot_uuid, &context_.size, copy_buffer, std::move(fn));
Brian Silverman3bca5322020-08-12 19:35:29 -0700243
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700244 if (read_result == ipc_lib::LocklessQueueReader::Result::GOOD) {
Brian Silverman77162972020-08-12 19:52:40 -0700245 if (pin_data()) {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700246 const int pin_result = pinner_->PinIndex(queue_index.index());
247 CHECK(pin_result >= 0)
Brian Silverman77162972020-08-12 19:52:40 -0700248 << ": Got behind while reading and the last message was modified "
249 "out from under us while we tried to pin it. Don't get so far "
250 "behind on: "
251 << configuration::CleanedChannelToString(channel_);
Brian Silverman4f4e0612020-08-12 19:54:41 -0700252 context_.buffer_index = pin_result;
253 } else {
254 context_.buffer_index = -1;
Brian Silverman77162972020-08-12 19:52:40 -0700255 }
256
Brian Silverman3bca5322020-08-12 19:35:29 -0700257 context_.queue_index = queue_index.index();
258 if (context_.remote_queue_index == 0xffffffffu) {
259 context_.remote_queue_index = context_.queue_index;
260 }
261 if (context_.monotonic_remote_time == aos::monotonic_clock::min_time) {
262 context_.monotonic_remote_time = context_.monotonic_event_time;
263 }
264 if (context_.realtime_remote_time == aos::realtime_clock::min_time) {
265 context_.realtime_remote_time = context_.realtime_event_time;
266 }
267 const char *const data = DataBuffer();
268 if (data) {
269 context_.data =
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700270 data +
271 LocklessQueueMessageDataSize(lockless_queue_memory_.memory()) -
272 context_.size;
Brian Silverman3bca5322020-08-12 19:35:29 -0700273 } else {
274 context_.data = nullptr;
275 }
276 actual_queue_index_ = queue_index.Increment();
277 }
278
279 // Make sure the data wasn't modified while we were reading it. This
280 // can only happen if you are reading the last message *while* it is
281 // being written to, which means you are pretty far behind.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700282 CHECK(read_result != ipc_lib::LocklessQueueReader::Result::OVERWROTE)
Brian Silverman3bca5322020-08-12 19:35:29 -0700283 << ": Got behind while reading and the last message was modified "
284 "out from under us while we were reading it. Don't get so far "
285 "behind on: "
286 << configuration::CleanedChannelToString(channel_);
287
288 // We fell behind between when we read the index and read the value.
289 // This isn't worth recovering from since this means we went to sleep
290 // for a long time in the middle of this function.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700291 if (read_result == ipc_lib::LocklessQueueReader::Result::TOO_OLD) {
Brian Silverman3bca5322020-08-12 19:35:29 -0700292 event_loop_->SendTimingReport();
293 LOG(FATAL) << "The next message is no longer available. "
294 << configuration::CleanedChannelToString(channel_);
295 }
296
297 return read_result;
298 }
299
300 char *data_storage_start() const {
301 CHECK(copy_data());
Brian Silvermana1652f32020-01-29 20:41:44 -0800302 return RoundChannelData(data_storage_.get(), channel_->max_size());
303 }
Brian Silverman3bca5322020-08-12 19:35:29 -0700304
305 // Note that for some modes the return value will change as new messages are
306 // read.
307 const char *DataBuffer() const {
308 if (copy_data()) {
309 return data_storage_start();
310 }
Brian Silverman77162972020-08-12 19:52:40 -0700311 if (pin_data()) {
312 return static_cast<const char *>(pinner_->Data());
313 }
Brian Silverman3bca5322020-08-12 19:35:29 -0700314 return nullptr;
315 }
316
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800317 bool copy_data() const { return static_cast<bool>(data_storage_); }
Brian Silverman77162972020-08-12 19:52:40 -0700318 bool pin_data() const { return static_cast<bool>(pinner_); }
Brian Silvermana1652f32020-01-29 20:41:44 -0800319
Austin Schuh432784f2020-06-23 17:27:35 -0700320 aos::ShmEventLoop *event_loop_;
Austin Schuhf5652592019-12-29 16:26:15 -0800321 const Channel *const channel_;
Austin Schuh4d275fc2022-09-16 15:42:45 -0700322 ipc_lib::MemoryMappedQueue lockless_queue_memory_;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700323 ipc_lib::LocklessQueueReader reader_;
324 // This being nullopt indicates we're not looking for wakeups right now.
325 std::optional<ipc_lib::LocklessQueueWatcher> watcher_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700326
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700327 ipc_lib::QueueIndex actual_queue_index_ = ipc_lib::QueueIndex::Invalid();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700328
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800329 // This being empty indicates we're not going to copy data.
330 std::unique_ptr<char, decltype(&free)> data_storage_{nullptr, &free};
Austin Schuh39788ff2019-12-01 18:22:57 -0800331
Brian Silverman77162972020-08-12 19:52:40 -0700332 // This being nullopt indicates we're not going to pin messages.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700333 std::optional<ipc_lib::LocklessQueuePinner> pinner_;
Brian Silverman77162972020-08-12 19:52:40 -0700334
Austin Schuh39788ff2019-12-01 18:22:57 -0800335 Context context_;
Austin Schuh82ea7382023-07-14 15:17:34 -0700336
337 // Pre-allocated should_fetch function so we don't allocate.
Austin Schuh98ed26f2023-07-19 14:12:28 -0700338 const std::function<bool(const Context &)> should_fetch_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800339};
340
341class ShmFetcher : public RawFetcher {
342 public:
Austin Schuhef323c02020-09-01 14:55:28 -0700343 explicit ShmFetcher(std::string_view shm_base, ShmEventLoop *event_loop,
344 const Channel *channel)
Austin Schuhaa79e4e2019-12-29 20:43:32 -0800345 : RawFetcher(event_loop, channel),
Austin Schuhef323c02020-09-01 14:55:28 -0700346 simple_shm_fetcher_(shm_base, event_loop, channel) {
Brian Silverman77162972020-08-12 19:52:40 -0700347 simple_shm_fetcher_.RetrieveData();
Brian Silverman3bca5322020-08-12 19:35:29 -0700348 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800349
Austin Schuh3054f5f2021-07-21 15:38:01 -0700350 ~ShmFetcher() override {
351 shm_event_loop()->CheckCurrentThread();
352 context_.data = nullptr;
353 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800354
355 std::pair<bool, monotonic_clock::time_point> DoFetchNext() override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700356 shm_event_loop()->CheckCurrentThread();
Austin Schuh39788ff2019-12-01 18:22:57 -0800357 if (simple_shm_fetcher_.FetchNext()) {
358 context_ = simple_shm_fetcher_.context();
359 return std::make_pair(true, monotonic_clock::now());
360 }
361 return std::make_pair(false, monotonic_clock::min_time);
362 }
363
Austin Schuh98ed26f2023-07-19 14:12:28 -0700364 std::pair<bool, monotonic_clock::time_point> DoFetchNextIf(
365 std::function<bool(const Context &context)> fn) override {
366 shm_event_loop()->CheckCurrentThread();
367 if (simple_shm_fetcher_.FetchNextIf(std::move(fn))) {
368 context_ = simple_shm_fetcher_.context();
369 return std::make_pair(true, monotonic_clock::now());
370 }
371 return std::make_pair(false, monotonic_clock::min_time);
372 }
373
Austin Schuh39788ff2019-12-01 18:22:57 -0800374 std::pair<bool, monotonic_clock::time_point> DoFetch() override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700375 shm_event_loop()->CheckCurrentThread();
Austin Schuh39788ff2019-12-01 18:22:57 -0800376 if (simple_shm_fetcher_.Fetch()) {
377 context_ = simple_shm_fetcher_.context();
378 return std::make_pair(true, monotonic_clock::now());
379 }
380 return std::make_pair(false, monotonic_clock::min_time);
381 }
382
Austin Schuh98ed26f2023-07-19 14:12:28 -0700383 std::pair<bool, monotonic_clock::time_point> DoFetchIf(
384 std::function<bool(const Context &context)> fn) override {
385 shm_event_loop()->CheckCurrentThread();
386 if (simple_shm_fetcher_.FetchIf(std::move(fn))) {
387 context_ = simple_shm_fetcher_.context();
388 return std::make_pair(true, monotonic_clock::now());
389 }
390 return std::make_pair(false, monotonic_clock::min_time);
391 }
392
Brian Silvermana5450a92020-08-12 19:59:57 -0700393 absl::Span<const char> GetPrivateMemory() const {
Brian Silverman6d2b3592020-06-18 14:40:15 -0700394 return simple_shm_fetcher_.GetPrivateMemory();
395 }
396
Austin Schuh39788ff2019-12-01 18:22:57 -0800397 private:
Austin Schuh3054f5f2021-07-21 15:38:01 -0700398 const ShmEventLoop *shm_event_loop() const {
399 return static_cast<const ShmEventLoop *>(event_loop());
400 }
401
Austin Schuh39788ff2019-12-01 18:22:57 -0800402 SimpleShmFetcher simple_shm_fetcher_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700403};
404
Brian Silvermane1fe2512022-08-14 23:18:50 -0700405class ShmExitHandle : public ExitHandle {
406 public:
407 ShmExitHandle(ShmEventLoop *event_loop) : event_loop_(event_loop) {
408 ++event_loop_->exit_handle_count_;
409 }
410 ~ShmExitHandle() override {
411 CHECK_GT(event_loop_->exit_handle_count_, 0);
412 --event_loop_->exit_handle_count_;
413 }
414
415 void Exit() override { event_loop_->Exit(); }
416
417 private:
418 ShmEventLoop *const event_loop_;
419};
420
Alex Perrycb7da4b2019-08-28 19:35:56 -0700421class ShmSender : public RawSender {
422 public:
Austin Schuhef323c02020-09-01 14:55:28 -0700423 explicit ShmSender(std::string_view shm_base, EventLoop *event_loop,
424 const Channel *channel)
Austin Schuh39788ff2019-12-01 18:22:57 -0800425 : RawSender(event_loop, channel),
Austin Schuh4d275fc2022-09-16 15:42:45 -0700426 lockless_queue_memory_(shm_base, FLAGS_permissions,
427 event_loop->configuration(), channel),
Austin Schuhfff9c3a2023-06-16 18:48:23 -0700428 lockless_queue_sender_(
429 VerifySender(ipc_lib::LocklessQueueSender::Make(
430 lockless_queue_memory_.queue(),
431 configuration::ChannelStorageDuration(
432 event_loop->configuration(), channel)),
433 channel)),
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700434 wake_upper_(lockless_queue_memory_.queue()) {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700435
Austin Schuh3054f5f2021-07-21 15:38:01 -0700436 ~ShmSender() override { shm_event_loop()->CheckCurrentThread(); }
Austin Schuh39788ff2019-12-01 18:22:57 -0800437
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700438 static ipc_lib::LocklessQueueSender VerifySender(
439 std::optional<ipc_lib::LocklessQueueSender> sender,
Austin Schuhe516ab02020-05-06 21:37:04 -0700440 const Channel *channel) {
441 if (sender) {
442 return std::move(sender.value());
443 }
444 LOG(FATAL) << "Failed to create sender on "
445 << configuration::CleanedChannelToString(channel)
446 << ", too many senders.";
447 }
448
Austin Schuh3054f5f2021-07-21 15:38:01 -0700449 void *data() override {
450 shm_event_loop()->CheckCurrentThread();
451 return lockless_queue_sender_.Data();
452 }
453 size_t size() override {
454 shm_event_loop()->CheckCurrentThread();
455 return lockless_queue_sender_.size();
456 }
milind1f1dca32021-07-03 13:50:07 -0700457
458 Error DoSend(size_t length,
459 aos::monotonic_clock::time_point monotonic_remote_time,
460 aos::realtime_clock::time_point realtime_remote_time,
Austin Schuhac6d89e2024-03-27 14:56:09 -0700461 aos::monotonic_clock::time_point monotonic_remote_transmit_time,
milind1f1dca32021-07-03 13:50:07 -0700462 uint32_t remote_queue_index,
463 const UUID &source_boot_uuid) override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700464 shm_event_loop()->CheckCurrentThread();
Austin Schuh0f7ed462020-03-28 20:38:34 -0700465 CHECK_LE(length, static_cast<size_t>(channel()->max_size()))
466 << ": Sent too big a message on "
467 << configuration::CleanedChannelToString(channel());
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700468 const auto result = lockless_queue_sender_.Send(
Austin Schuhac6d89e2024-03-27 14:56:09 -0700469 length, monotonic_remote_time, realtime_remote_time,
470 monotonic_remote_transmit_time, remote_queue_index, source_boot_uuid,
471 &monotonic_sent_time_, &realtime_sent_time_, &sent_queue_index_);
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700472 CHECK_NE(result, ipc_lib::LocklessQueueSender::Result::INVALID_REDZONE)
Austin Schuh91ba6392020-10-03 13:27:47 -0700473 << ": Somebody wrote outside the buffer of their message on channel "
474 << configuration::CleanedChannelToString(channel());
475
Austin Schuh65493d62022-08-17 15:10:37 -0700476 wake_upper_.Wakeup(event_loop()->is_running()
477 ? event_loop()->runtime_realtime_priority()
478 : 0);
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700479 return CheckLocklessQueueResult(result);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700480 }
481
milind1f1dca32021-07-03 13:50:07 -0700482 Error DoSend(const void *msg, size_t length,
483 aos::monotonic_clock::time_point monotonic_remote_time,
484 aos::realtime_clock::time_point realtime_remote_time,
Austin Schuhac6d89e2024-03-27 14:56:09 -0700485 aos::monotonic_clock::time_point monotonic_remote_transmit_time,
milind1f1dca32021-07-03 13:50:07 -0700486 uint32_t remote_queue_index,
487 const UUID &source_boot_uuid) override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700488 shm_event_loop()->CheckCurrentThread();
Austin Schuh0f7ed462020-03-28 20:38:34 -0700489 CHECK_LE(length, static_cast<size_t>(channel()->max_size()))
490 << ": Sent too big a message on "
491 << configuration::CleanedChannelToString(channel());
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700492 const auto result = lockless_queue_sender_.Send(
Brian Silvermanaf9a4d82020-10-06 15:10:58 -0700493 reinterpret_cast<const char *>(msg), length, monotonic_remote_time,
Austin Schuhac6d89e2024-03-27 14:56:09 -0700494 realtime_remote_time, monotonic_remote_transmit_time,
495 remote_queue_index, source_boot_uuid, &monotonic_sent_time_,
496 &realtime_sent_time_, &sent_queue_index_);
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700497
498 CHECK_NE(result, ipc_lib::LocklessQueueSender::Result::INVALID_REDZONE)
499 << ": Somebody wrote outside the buffer of their message on "
500 "channel "
Austin Schuh91ba6392020-10-03 13:27:47 -0700501 << configuration::CleanedChannelToString(channel());
Austin Schuh65493d62022-08-17 15:10:37 -0700502 wake_upper_.Wakeup(event_loop()->is_running()
503 ? event_loop()->runtime_realtime_priority()
504 : 0);
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700505
506 return CheckLocklessQueueResult(result);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700507 }
508
Brian Silverman5120afb2020-01-31 17:44:35 -0800509 absl::Span<char> GetSharedMemory() const {
Brian Silvermana5450a92020-08-12 19:59:57 -0700510 return lockless_queue_memory_.GetMutableSharedMemory();
Brian Silverman5120afb2020-01-31 17:44:35 -0800511 }
512
Austin Schuh3054f5f2021-07-21 15:38:01 -0700513 int buffer_index() override {
514 shm_event_loop()->CheckCurrentThread();
515 return lockless_queue_sender_.buffer_index();
516 }
Brian Silverman4f4e0612020-08-12 19:54:41 -0700517
Alex Perrycb7da4b2019-08-28 19:35:56 -0700518 private:
Austin Schuh3054f5f2021-07-21 15:38:01 -0700519 const ShmEventLoop *shm_event_loop() const {
520 return static_cast<const ShmEventLoop *>(event_loop());
521 }
522
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700523 RawSender::Error CheckLocklessQueueResult(
524 const ipc_lib::LocklessQueueSender::Result &result) {
525 switch (result) {
526 case ipc_lib::LocklessQueueSender::Result::GOOD:
527 return Error::kOk;
528 case ipc_lib::LocklessQueueSender::Result::MESSAGES_SENT_TOO_FAST:
529 return Error::kMessagesSentTooFast;
530 case ipc_lib::LocklessQueueSender::Result::INVALID_REDZONE:
531 return Error::kInvalidRedzone;
532 }
533 LOG(FATAL) << "Unknown lockless queue sender result"
534 << static_cast<int>(result);
535 }
536
Austin Schuh4d275fc2022-09-16 15:42:45 -0700537 ipc_lib::MemoryMappedQueue lockless_queue_memory_;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700538 ipc_lib::LocklessQueueSender lockless_queue_sender_;
539 ipc_lib::LocklessQueueWakeUpper wake_upper_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700540};
541
Alex Perrycb7da4b2019-08-28 19:35:56 -0700542// Class to manage the state for a Watcher.
Brian Silverman148d43d2020-06-07 18:19:22 -0500543class ShmWatcherState : public WatcherState {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700544 public:
Brian Silverman148d43d2020-06-07 18:19:22 -0500545 ShmWatcherState(
Austin Schuhef323c02020-09-01 14:55:28 -0700546 std::string_view shm_base, ShmEventLoop *event_loop,
547 const Channel *channel,
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800548 std::function<void(const Context &context, const void *message)> fn,
549 bool copy_data)
Brian Silverman148d43d2020-06-07 18:19:22 -0500550 : WatcherState(event_loop, channel, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800551 event_loop_(event_loop),
552 event_(this),
Austin Schuhef323c02020-09-01 14:55:28 -0700553 simple_shm_fetcher_(shm_base, event_loop, channel) {
Brian Silverman3bca5322020-08-12 19:35:29 -0700554 if (copy_data) {
Brian Silverman77162972020-08-12 19:52:40 -0700555 simple_shm_fetcher_.RetrieveData();
Brian Silverman3bca5322020-08-12 19:35:29 -0700556 }
557 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700558
Austin Schuh3054f5f2021-07-21 15:38:01 -0700559 ~ShmWatcherState() override {
560 event_loop_->CheckCurrentThread();
561 event_loop_->RemoveEvent(&event_);
562 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800563
Philipp Schrader81fa3fb2023-09-17 18:58:35 -0700564 void Construct() override {
565 event_loop_->CheckCurrentThread();
566 CHECK(RegisterWakeup(event_loop_->runtime_realtime_priority()));
567 }
568
569 void Startup() override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700570 event_loop_->CheckCurrentThread();
Austin Schuh7d87b672019-12-01 20:23:49 -0800571 simple_shm_fetcher_.PointAtNextQueueIndex();
Austin Schuh39788ff2019-12-01 18:22:57 -0800572 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700573
Alex Perrycb7da4b2019-08-28 19:35:56 -0700574 // Returns true if there is new data available.
Austin Schuh7d87b672019-12-01 20:23:49 -0800575 bool CheckForNewData() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700576 if (!has_new_data_) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800577 has_new_data_ = simple_shm_fetcher_.FetchNext();
Austin Schuh7d87b672019-12-01 20:23:49 -0800578
579 if (has_new_data_) {
580 event_.set_event_time(
Austin Schuhad154822019-12-27 15:45:13 -0800581 simple_shm_fetcher_.context().monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800582 event_loop_->AddEvent(&event_);
583 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700584 }
585
586 return has_new_data_;
587 }
588
Alex Perrycb7da4b2019-08-28 19:35:56 -0700589 // Consumes the data by calling the callback.
Austin Schuh7d87b672019-12-01 20:23:49 -0800590 void HandleEvent() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700591 CHECK(has_new_data_);
Austin Schuh39788ff2019-12-01 18:22:57 -0800592 DoCallCallback(monotonic_clock::now, simple_shm_fetcher_.context());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700593 has_new_data_ = false;
Austin Schuh7d87b672019-12-01 20:23:49 -0800594 CheckForNewData();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700595 }
596
Austin Schuh39788ff2019-12-01 18:22:57 -0800597 // Registers us to receive a signal on event reception.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700598 bool RegisterWakeup(int priority) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800599 return simple_shm_fetcher_.RegisterWakeup(priority);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700600 }
601
Austin Schuh39788ff2019-12-01 18:22:57 -0800602 void UnregisterWakeup() { return simple_shm_fetcher_.UnregisterWakeup(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700603
Brian Silvermana5450a92020-08-12 19:59:57 -0700604 absl::Span<const char> GetSharedMemory() const {
605 return simple_shm_fetcher_.GetConstSharedMemory();
Brian Silverman5120afb2020-01-31 17:44:35 -0800606 }
607
Alex Perrycb7da4b2019-08-28 19:35:56 -0700608 private:
609 bool has_new_data_ = false;
610
Austin Schuh7d87b672019-12-01 20:23:49 -0800611 ShmEventLoop *event_loop_;
Brian Silverman148d43d2020-06-07 18:19:22 -0500612 EventHandler<ShmWatcherState> event_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800613 SimpleShmFetcher simple_shm_fetcher_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700614};
615
616// Adapter class to adapt a timerfd to a TimerHandler.
Brian Silverman148d43d2020-06-07 18:19:22 -0500617class ShmTimerHandler final : public TimerHandler {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700618 public:
Brian Silverman148d43d2020-06-07 18:19:22 -0500619 ShmTimerHandler(ShmEventLoop *shm_event_loop, ::std::function<void()> fn)
Austin Schuh39788ff2019-12-01 18:22:57 -0800620 : TimerHandler(shm_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800621 shm_event_loop_(shm_event_loop),
622 event_(this) {
Austin Schuhcde39fd2020-02-22 20:58:24 -0800623 shm_event_loop_->epoll_.OnReadable(timerfd_.fd(), [this]() {
Austin Schuh5ca13112021-02-07 22:06:53 -0800624 // The timer may fire spuriously. HandleEvent on the event loop will
Austin Schuhcde39fd2020-02-22 20:58:24 -0800625 // call the callback if it is needed. It may also have called it when
626 // processing some other event, and the kernel decided to deliver this
627 // wakeup anyways.
628 timerfd_.Read();
629 shm_event_loop_->HandleEvent();
630 });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700631 }
632
Brian Silverman148d43d2020-06-07 18:19:22 -0500633 ~ShmTimerHandler() {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700634 shm_event_loop_->CheckCurrentThread();
Austin Schuh7d87b672019-12-01 20:23:49 -0800635 Disable();
636 shm_event_loop_->epoll_.DeleteFd(timerfd_.fd());
637 }
638
639 void HandleEvent() {
Austin Schuhcde39fd2020-02-22 20:58:24 -0800640 CHECK(!event_.valid());
Brian Silvermanaf9a4d82020-10-06 15:10:58 -0700641 disabled_ = false;
Austin Schuhcde39fd2020-02-22 20:58:24 -0800642 const auto monotonic_now = Call(monotonic_clock::now, base_);
643 if (event_.valid()) {
Philipp Schradera6712522023-07-05 20:25:11 -0700644 // If someone called Schedule inside Call, rescheduling is already taken
645 // care of. Bail.
Austin Schuhcde39fd2020-02-22 20:58:24 -0800646 return;
Austin Schuh7d87b672019-12-01 20:23:49 -0800647 }
Brian Silvermanaf9a4d82020-10-06 15:10:58 -0700648 if (disabled_) {
649 // Somebody called Disable inside Call, so we don't want to reschedule.
650 // Bail.
651 return;
652 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800653
Austin Schuh4d275fc2022-09-16 15:42:45 -0700654 if (repeat_offset_ == std::chrono::seconds(0)) {
Austin Schuhcde39fd2020-02-22 20:58:24 -0800655 timerfd_.Disable();
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700656 disabled_ = true;
Austin Schuhcde39fd2020-02-22 20:58:24 -0800657 } else {
658 // Compute how many cycles have elapsed and schedule the next iteration
659 // for the next iteration in the future.
660 const int elapsed_cycles =
661 std::max<int>(0, (monotonic_now - base_ + repeat_offset_ -
662 std::chrono::nanoseconds(1)) /
663 repeat_offset_);
664 base_ += repeat_offset_ * elapsed_cycles;
Austin Schuh7d87b672019-12-01 20:23:49 -0800665
Austin Schuhcde39fd2020-02-22 20:58:24 -0800666 // Update the heap and schedule the timerfd wakeup.
Austin Schuh7d87b672019-12-01 20:23:49 -0800667 event_.set_event_time(base_);
668 shm_event_loop_->AddEvent(&event_);
Austin Schuh4d275fc2022-09-16 15:42:45 -0700669 timerfd_.SetTime(base_, std::chrono::seconds(0));
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700670 disabled_ = false;
Austin Schuh7d87b672019-12-01 20:23:49 -0800671 }
672 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700673
Philipp Schradera6712522023-07-05 20:25:11 -0700674 void Schedule(monotonic_clock::time_point base,
675 monotonic_clock::duration repeat_offset) override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700676 shm_event_loop_->CheckCurrentThread();
Austin Schuh7d87b672019-12-01 20:23:49 -0800677 if (event_.valid()) {
678 shm_event_loop_->RemoveEvent(&event_);
679 }
680
Alex Perrycb7da4b2019-08-28 19:35:56 -0700681 timerfd_.SetTime(base, repeat_offset);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800682 base_ = base;
683 repeat_offset_ = repeat_offset;
Austin Schuh7d87b672019-12-01 20:23:49 -0800684 event_.set_event_time(base_);
685 shm_event_loop_->AddEvent(&event_);
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700686 disabled_ = false;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700687 }
688
Austin Schuh7d87b672019-12-01 20:23:49 -0800689 void Disable() override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700690 shm_event_loop_->CheckCurrentThread();
Austin Schuh7d87b672019-12-01 20:23:49 -0800691 shm_event_loop_->RemoveEvent(&event_);
692 timerfd_.Disable();
Brian Silvermanaf9a4d82020-10-06 15:10:58 -0700693 disabled_ = true;
Austin Schuh7d87b672019-12-01 20:23:49 -0800694 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700695
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700696 bool IsDisabled() override { return disabled_; }
697
Alex Perrycb7da4b2019-08-28 19:35:56 -0700698 private:
699 ShmEventLoop *shm_event_loop_;
Brian Silverman148d43d2020-06-07 18:19:22 -0500700 EventHandler<ShmTimerHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700701
Brian Silverman148d43d2020-06-07 18:19:22 -0500702 internal::TimerFd timerfd_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700703
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800704 monotonic_clock::time_point base_;
705 monotonic_clock::duration repeat_offset_;
Brian Silvermanaf9a4d82020-10-06 15:10:58 -0700706
707 // Used to track if Disable() was called during the callback, so we know not
708 // to reschedule.
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700709 bool disabled_ = true;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700710};
711
712// Adapter class to the timerfd and PhasedLoop.
Brian Silverman148d43d2020-06-07 18:19:22 -0500713class ShmPhasedLoopHandler final : public PhasedLoopHandler {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700714 public:
Brian Silverman148d43d2020-06-07 18:19:22 -0500715 ShmPhasedLoopHandler(ShmEventLoop *shm_event_loop,
716 ::std::function<void(int)> fn,
717 const monotonic_clock::duration interval,
718 const monotonic_clock::duration offset)
719 : PhasedLoopHandler(shm_event_loop, std::move(fn), interval, offset),
Austin Schuh7d87b672019-12-01 20:23:49 -0800720 shm_event_loop_(shm_event_loop),
721 event_(this) {
722 shm_event_loop_->epoll_.OnReadable(
723 timerfd_.fd(), [this]() { shm_event_loop_->HandleEvent(); });
724 }
725
726 void HandleEvent() {
727 // The return value for read is the number of cycles that have elapsed.
728 // Because we check to see when this event *should* have happened, there are
729 // cases where Read() will return 0, when 1 cycle has actually happened.
730 // This occurs when the timer interrupt hasn't triggered yet. Therefore,
731 // ignore it. Call handles rescheduling and calculating elapsed cycles
732 // without any extra help.
733 timerfd_.Read();
734 event_.Invalidate();
735
James Kuszmaul20dcc7c2023-01-20 11:06:31 -0800736 Call(monotonic_clock::now);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700737 }
738
Brian Silverman148d43d2020-06-07 18:19:22 -0500739 ~ShmPhasedLoopHandler() override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700740 shm_event_loop_->CheckCurrentThread();
Austin Schuh39788ff2019-12-01 18:22:57 -0800741 shm_event_loop_->epoll_.DeleteFd(timerfd_.fd());
Austin Schuh7d87b672019-12-01 20:23:49 -0800742 shm_event_loop_->RemoveEvent(&event_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700743 }
744
745 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800746 // Reschedules the timer.
Austin Schuh39788ff2019-12-01 18:22:57 -0800747 void Schedule(monotonic_clock::time_point sleep_time) override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700748 shm_event_loop_->CheckCurrentThread();
Austin Schuh7d87b672019-12-01 20:23:49 -0800749 if (event_.valid()) {
750 shm_event_loop_->RemoveEvent(&event_);
751 }
752
Austin Schuh39788ff2019-12-01 18:22:57 -0800753 timerfd_.SetTime(sleep_time, ::aos::monotonic_clock::zero());
Austin Schuh7d87b672019-12-01 20:23:49 -0800754 event_.set_event_time(sleep_time);
755 shm_event_loop_->AddEvent(&event_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700756 }
757
758 ShmEventLoop *shm_event_loop_;
Brian Silverman148d43d2020-06-07 18:19:22 -0500759 EventHandler<ShmPhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700760
Brian Silverman148d43d2020-06-07 18:19:22 -0500761 internal::TimerFd timerfd_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700762};
Brian Silverman148d43d2020-06-07 18:19:22 -0500763
764} // namespace shm_event_loop_internal
Alex Perrycb7da4b2019-08-28 19:35:56 -0700765
766::std::unique_ptr<RawFetcher> ShmEventLoop::MakeRawFetcher(
767 const Channel *channel) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700768 CheckCurrentThread();
Austin Schuhca4828c2019-12-28 14:21:35 -0800769 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
770 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
771 << "\", \"type\": \"" << channel->type()->string_view()
772 << "\" } is not able to be fetched on this node. Check your "
773 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800774 }
775
Austin Schuhef323c02020-09-01 14:55:28 -0700776 return ::std::unique_ptr<RawFetcher>(
777 new ShmFetcher(shm_base_, this, channel));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700778}
779
780::std::unique_ptr<RawSender> ShmEventLoop::MakeRawSender(
781 const Channel *channel) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700782 CheckCurrentThread();
Brian Silverman0fc69932020-01-24 21:54:02 -0800783 TakeSender(channel);
Austin Schuh39788ff2019-12-01 18:22:57 -0800784
Austin Schuhef323c02020-09-01 14:55:28 -0700785 return ::std::unique_ptr<RawSender>(new ShmSender(shm_base_, this, channel));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700786}
787
788void ShmEventLoop::MakeRawWatcher(
789 const Channel *channel,
790 std::function<void(const Context &context, const void *message)> watcher) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700791 CheckCurrentThread();
Brian Silverman0fc69932020-01-24 21:54:02 -0800792 TakeWatcher(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800793
Austin Schuh39788ff2019-12-01 18:22:57 -0800794 NewWatcher(::std::unique_ptr<WatcherState>(
Austin Schuhef323c02020-09-01 14:55:28 -0700795 new ShmWatcherState(shm_base_, this, channel, std::move(watcher), true)));
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800796}
797
798void ShmEventLoop::MakeRawNoArgWatcher(
799 const Channel *channel,
800 std::function<void(const Context &context)> watcher) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700801 CheckCurrentThread();
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800802 TakeWatcher(channel);
803
Brian Silverman148d43d2020-06-07 18:19:22 -0500804 NewWatcher(::std::unique_ptr<WatcherState>(new ShmWatcherState(
Austin Schuhef323c02020-09-01 14:55:28 -0700805 shm_base_, this, channel,
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800806 [watcher](const Context &context, const void *) { watcher(context); },
807 false)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700808}
809
810TimerHandler *ShmEventLoop::AddTimer(::std::function<void()> callback) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700811 CheckCurrentThread();
Austin Schuh39788ff2019-12-01 18:22:57 -0800812 return NewTimer(::std::unique_ptr<TimerHandler>(
Brian Silverman148d43d2020-06-07 18:19:22 -0500813 new ShmTimerHandler(this, ::std::move(callback))));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700814}
815
816PhasedLoopHandler *ShmEventLoop::AddPhasedLoop(
817 ::std::function<void(int)> callback,
818 const monotonic_clock::duration interval,
819 const monotonic_clock::duration offset) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700820 CheckCurrentThread();
Brian Silverman148d43d2020-06-07 18:19:22 -0500821 return NewPhasedLoop(::std::unique_ptr<PhasedLoopHandler>(
822 new ShmPhasedLoopHandler(this, ::std::move(callback), interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700823}
824
825void ShmEventLoop::OnRun(::std::function<void()> on_run) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700826 CheckCurrentThread();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700827 on_run_.push_back(::std::move(on_run));
828}
829
Austin Schuh3054f5f2021-07-21 15:38:01 -0700830void ShmEventLoop::CheckCurrentThread() const {
831 if (__builtin_expect(check_mutex_ != nullptr, false)) {
832 CHECK(check_mutex_->is_locked())
833 << ": The configured mutex is not locked while calling a "
834 "ShmEventLoop function";
835 }
836 if (__builtin_expect(!!check_tid_, false)) {
837 CHECK_EQ(syscall(SYS_gettid), *check_tid_)
838 << ": Being called from the wrong thread";
839 }
840}
841
Austin Schuh5ca13112021-02-07 22:06:53 -0800842// This is a bit tricky because watchers can generate new events at any time (as
843// long as it's in the past). We want to check the watchers at least once before
844// declaring there are no events to handle, and we want to check them again if
845// event processing takes long enough that we find an event after that point in
846// time to handle.
Austin Schuh7d87b672019-12-01 20:23:49 -0800847void ShmEventLoop::HandleEvent() {
Austin Schuh5ca13112021-02-07 22:06:53 -0800848 // Time through which we've checked for new events in watchers.
849 monotonic_clock::time_point checked_until = monotonic_clock::min_time;
850 if (!signalfd_) {
851 // Nothing to check, so we can bail out immediately once we're out of
852 // events.
853 CHECK(watchers_.empty());
854 checked_until = monotonic_clock::max_time;
Austin Schuh7d87b672019-12-01 20:23:49 -0800855 }
856
Austin Schuh5ca13112021-02-07 22:06:53 -0800857 // Loop until we run out of events to check.
Austin Schuh39788ff2019-12-01 18:22:57 -0800858 while (true) {
Austin Schuh5ca13112021-02-07 22:06:53 -0800859 // Time of the next event we know about. If this is before checked_until, we
860 // know there aren't any new events before the next one that we already know
861 // about, so no need to check the watchers.
862 monotonic_clock::time_point next_time = monotonic_clock::max_time;
863
864 if (EventCount() == 0) {
865 if (checked_until != monotonic_clock::min_time) {
866 // No events, and we've already checked the watchers at least once, so
867 // we're all done.
868 //
869 // There's a small chance that a watcher has gotten another event in
870 // between checked_until and now. If so, then the signalfd will be
871 // triggered now and we'll re-enter HandleEvent immediately. This is
872 // unlikely though, so we don't want to spend time checking all the
873 // watchers unnecessarily.
874 break;
875 }
876 } else {
877 next_time = PeekEvent()->event_time();
878 }
Austin Schuh00cad2e2022-12-02 20:11:04 -0800879 monotonic_clock::time_point now;
880 bool new_data = false;
Austin Schuh5ca13112021-02-07 22:06:53 -0800881
882 if (next_time > checked_until) {
883 // Read all of the signals, because there's no point in waking up again
884 // immediately to handle each one if we've fallen behind.
885 //
886 // This is safe before checking for new data on the watchers. If a signal
887 // is cleared here, the corresponding CheckForNewData() call below will
888 // pick it up.
889 while (true) {
890 const signalfd_siginfo result = signalfd_->Read();
891 if (result.ssi_signo == 0) {
892 break;
893 }
894 CHECK_EQ(result.ssi_signo, ipc_lib::kWakeupSignal);
895 }
Austin Schuh00cad2e2022-12-02 20:11:04 -0800896 // This is the last time we can guarantee that if a message is published
897 // before, we will notice it.
898 now = monotonic_clock::now();
Austin Schuh5ca13112021-02-07 22:06:53 -0800899
900 // Check all the watchers for new events.
901 for (std::unique_ptr<WatcherState> &base_watcher : watchers_) {
902 ShmWatcherState *const watcher =
903 reinterpret_cast<ShmWatcherState *>(base_watcher.get());
904
Austin Schuh00cad2e2022-12-02 20:11:04 -0800905 // Track if we got a message.
906 if (watcher->CheckForNewData()) {
907 new_data = true;
908 }
Austin Schuh5ca13112021-02-07 22:06:53 -0800909 }
910 if (EventCount() == 0) {
911 // Still no events, all done now.
912 break;
913 }
914
915 checked_until = now;
916 // Check for any new events we found.
917 next_time = PeekEvent()->event_time();
Austin Schuh00cad2e2022-12-02 20:11:04 -0800918 } else {
919 now = monotonic_clock::now();
Austin Schuh5ca13112021-02-07 22:06:53 -0800920 }
921
922 if (next_time > now) {
Austin Schuh00cad2e2022-12-02 20:11:04 -0800923 // Ok, we got a message with a timestamp *after* we wrote down time. We
924 // need to process it (otherwise we will go to sleep without processing
925 // it), but we also need to make sure no other messages have come in
926 // before it that we would process out of order. Just go around again to
927 // redo the checks.
928 if (new_data) {
929 continue;
930 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800931 break;
932 }
933
Austin Schuh5ca13112021-02-07 22:06:53 -0800934 EventLoopEvent *const event = PopEvent();
Austin Schuh7d87b672019-12-01 20:23:49 -0800935 event->HandleEvent();
Austin Schuh39788ff2019-12-01 18:22:57 -0800936 }
937}
938
Austin Schuh32fd5a72019-12-01 22:20:26 -0800939// RAII class to mask signals.
940class ScopedSignalMask {
941 public:
942 ScopedSignalMask(std::initializer_list<int> signals) {
943 sigset_t sigset;
944 PCHECK(sigemptyset(&sigset) == 0);
945 for (int signal : signals) {
946 PCHECK(sigaddset(&sigset, signal) == 0);
947 }
948
949 PCHECK(sigprocmask(SIG_BLOCK, &sigset, &old_) == 0);
950 }
951
952 ~ScopedSignalMask() { PCHECK(sigprocmask(SIG_SETMASK, &old_, nullptr) == 0); }
953
954 private:
955 sigset_t old_;
956};
957
958// Class to manage the static state associated with killing multiple event
959// loops.
960class SignalHandler {
961 public:
962 // Gets the singleton.
963 static SignalHandler *global() {
964 static SignalHandler loop;
965 return &loop;
966 }
967
968 // Handles the signal with the singleton.
969 static void HandleSignal(int) { global()->DoHandleSignal(); }
970
971 // Registers an event loop to receive Exit() calls.
972 void Register(ShmEventLoop *event_loop) {
973 // Block signals while we have the mutex so we never race with the signal
974 // handler.
975 ScopedSignalMask mask({SIGINT, SIGHUP, SIGTERM});
976 std::unique_lock<stl_mutex> locker(mutex_);
977 if (event_loops_.size() == 0) {
978 // The first caller registers the signal handler.
979 struct sigaction new_action;
980 sigemptyset(&new_action.sa_mask);
981 // This makes it so that 2 control c's to a stuck process will kill it by
982 // restoring the original signal handler.
983 new_action.sa_flags = SA_RESETHAND;
984 new_action.sa_handler = &HandleSignal;
985
986 PCHECK(sigaction(SIGINT, &new_action, &old_action_int_) == 0);
987 PCHECK(sigaction(SIGHUP, &new_action, &old_action_hup_) == 0);
988 PCHECK(sigaction(SIGTERM, &new_action, &old_action_term_) == 0);
989 }
990
991 event_loops_.push_back(event_loop);
992 }
993
994 // Unregisters an event loop to receive Exit() calls.
995 void Unregister(ShmEventLoop *event_loop) {
996 // Block signals while we have the mutex so we never race with the signal
997 // handler.
998 ScopedSignalMask mask({SIGINT, SIGHUP, SIGTERM});
999 std::unique_lock<stl_mutex> locker(mutex_);
1000
Brian Silverman5120afb2020-01-31 17:44:35 -08001001 event_loops_.erase(
1002 std::find(event_loops_.begin(), event_loops_.end(), event_loop));
Austin Schuh32fd5a72019-12-01 22:20:26 -08001003
1004 if (event_loops_.size() == 0u) {
1005 // The last caller restores the original signal handlers.
1006 PCHECK(sigaction(SIGINT, &old_action_int_, nullptr) == 0);
1007 PCHECK(sigaction(SIGHUP, &old_action_hup_, nullptr) == 0);
1008 PCHECK(sigaction(SIGTERM, &old_action_term_, nullptr) == 0);
1009 }
1010 }
1011
1012 private:
1013 void DoHandleSignal() {
1014 // We block signals while grabbing the lock, so there should never be a
1015 // race. Confirm that this is true using trylock.
1016 CHECK(mutex_.try_lock()) << ": sigprocmask failed to block signals while "
1017 "modifing the event loop list.";
1018 for (ShmEventLoop *event_loop : event_loops_) {
1019 event_loop->Exit();
1020 }
1021 mutex_.unlock();
1022 }
1023
1024 // Mutex to protect all state.
1025 stl_mutex mutex_;
1026 std::vector<ShmEventLoop *> event_loops_;
1027 struct sigaction old_action_int_;
1028 struct sigaction old_action_hup_;
1029 struct sigaction old_action_term_;
1030};
1031
Alex Perrycb7da4b2019-08-28 19:35:56 -07001032void ShmEventLoop::Run() {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001033 CheckCurrentThread();
Austin Schuh32fd5a72019-12-01 22:20:26 -08001034 SignalHandler::global()->Register(this);
Austin Schuh39788ff2019-12-01 18:22:57 -08001035
Alex Perrycb7da4b2019-08-28 19:35:56 -07001036 if (watchers_.size() > 0) {
Austin Schuh5ca13112021-02-07 22:06:53 -08001037 signalfd_.reset(new ipc_lib::SignalFd({ipc_lib::kWakeupSignal}));
Brian Silverman36975282021-07-29 12:06:55 -07001038 signalfd_->LeaveSignalBlocked(ipc_lib::kWakeupSignal);
Alex Perrycb7da4b2019-08-28 19:35:56 -07001039
Austin Schuh5ca13112021-02-07 22:06:53 -08001040 epoll_.OnReadable(signalfd_->fd(), [this]() { HandleEvent(); });
Alex Perrycb7da4b2019-08-28 19:35:56 -07001041 }
1042
Austin Schuh39788ff2019-12-01 18:22:57 -08001043 MaybeScheduleTimingReports();
1044
Austin Schuh7d87b672019-12-01 20:23:49 -08001045 ReserveEvents();
1046
Tyler Chatow67ddb032020-01-12 14:30:04 -08001047 {
Austin Schuha0c41ba2020-09-10 22:59:14 -07001048 logging::ScopedLogRestorer prev_logger;
Tyler Chatow67ddb032020-01-12 14:30:04 -08001049 AosLogToFbs aos_logger;
1050 if (!skip_logger_) {
Austin Schuhad9e5eb2021-11-19 20:33:55 -08001051 aos_logger.Initialize(&name_, MakeSender<logging::LogMessageFbs>("/aos"));
Austin Schuha0c41ba2020-09-10 22:59:14 -07001052 prev_logger.Swap(aos_logger.implementation());
Tyler Chatow67ddb032020-01-12 14:30:04 -08001053 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001054
Tyler Chatow67ddb032020-01-12 14:30:04 -08001055 aos::SetCurrentThreadName(name_.substr(0, 16));
Brian Silverman6a54ff32020-04-28 16:41:39 -07001056 const cpu_set_t default_affinity = DefaultAffinity();
1057 if (!CPU_EQUAL(&affinity_, &default_affinity)) {
1058 ::aos::SetCurrentThreadAffinity(affinity_);
1059 }
Philipp Schrader81fa3fb2023-09-17 18:58:35 -07001060
1061 // Construct the watchers, but don't update the next pointer. This also
1062 // cleans up any watchers that previously died, and puts the nonrt work
1063 // before going realtime. After this happens, we will start queueing
1064 // signals (which may be a bit of extra work to process, but won't cause any
1065 // messages to be lost).
1066 for (::std::unique_ptr<WatcherState> &watcher : watchers_) {
1067 watcher->Construct();
1068 }
1069
Tyler Chatow67ddb032020-01-12 14:30:04 -08001070 // Now, all the callbacks are setup. Lock everything into memory and go RT.
1071 if (priority_ != 0) {
1072 ::aos::InitRT();
1073
1074 LOG(INFO) << "Setting priority to " << priority_;
1075 ::aos::SetCurrentThreadRealtimePriority(priority_);
1076 }
1077
1078 set_is_running(true);
1079
1080 // Now that we are realtime (but before the OnRun handlers run), snap the
Philipp Schrader81fa3fb2023-09-17 18:58:35 -07001081 // queue index pointer to the newest message. This happens in RT so that we
1082 // minimize the risk of losing messages.
Tyler Chatow67ddb032020-01-12 14:30:04 -08001083 for (::std::unique_ptr<WatcherState> &watcher : watchers_) {
Philipp Schrader81fa3fb2023-09-17 18:58:35 -07001084 watcher->Startup();
Tyler Chatow67ddb032020-01-12 14:30:04 -08001085 }
1086
1087 // Now that we are RT, run all the OnRun handlers.
Austin Schuha9012be2021-07-21 15:19:11 -07001088 SetTimerContext(monotonic_clock::now());
Tyler Chatow67ddb032020-01-12 14:30:04 -08001089 for (const auto &run : on_run_) {
1090 run();
1091 }
1092
1093 // And start our main event loop which runs all the timers and handles Quit.
1094 epoll_.Run();
1095
1096 // Once epoll exits, there is no useful nonrt work left to do.
1097 set_is_running(false);
1098
1099 // Nothing time or synchronization critical needs to happen after this
1100 // point. Drop RT priority.
1101 ::aos::UnsetCurrentThreadRealtimePriority();
Alex Perrycb7da4b2019-08-28 19:35:56 -07001102 }
1103
Austin Schuh39788ff2019-12-01 18:22:57 -08001104 for (::std::unique_ptr<WatcherState> &base_watcher : watchers_) {
Brian Silverman148d43d2020-06-07 18:19:22 -05001105 ShmWatcherState *watcher =
1106 reinterpret_cast<ShmWatcherState *>(base_watcher.get());
Alex Perrycb7da4b2019-08-28 19:35:56 -07001107 watcher->UnregisterWakeup();
1108 }
1109
1110 if (watchers_.size() > 0) {
Austin Schuh5ca13112021-02-07 22:06:53 -08001111 epoll_.DeleteFd(signalfd_->fd());
1112 signalfd_.reset();
Alex Perrycb7da4b2019-08-28 19:35:56 -07001113 }
Austin Schuh32fd5a72019-12-01 22:20:26 -08001114
1115 SignalHandler::global()->Unregister(this);
Austin Schuhe84c3ed2019-12-14 15:29:48 -08001116
1117 // Trigger any remaining senders or fetchers to be cleared before destroying
1118 // the event loop so the book keeping matches. Do this in the thread that
1119 // created the timing reporter.
1120 timing_report_sender_.reset();
Austin Schuh0debde12022-08-17 16:25:17 -07001121 ClearContext();
Alex Perrycb7da4b2019-08-28 19:35:56 -07001122}
1123
1124void ShmEventLoop::Exit() { epoll_.Quit(); }
1125
Brian Silvermane1fe2512022-08-14 23:18:50 -07001126std::unique_ptr<ExitHandle> ShmEventLoop::MakeExitHandle() {
1127 return std::make_unique<ShmExitHandle>(this);
1128}
1129
Alex Perrycb7da4b2019-08-28 19:35:56 -07001130ShmEventLoop::~ShmEventLoop() {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001131 CheckCurrentThread();
Austin Schuh39788ff2019-12-01 18:22:57 -08001132 // Force everything with a registered fd with epoll to be destroyed now.
1133 timers_.clear();
1134 phased_loops_.clear();
1135 watchers_.clear();
1136
Alex Perrycb7da4b2019-08-28 19:35:56 -07001137 CHECK(!is_running()) << ": ShmEventLoop destroyed while running";
Brian Silvermane1fe2512022-08-14 23:18:50 -07001138 CHECK_EQ(0, exit_handle_count_)
1139 << ": All ExitHandles must be destroyed before the ShmEventLoop";
Alex Perrycb7da4b2019-08-28 19:35:56 -07001140}
1141
Alex Perrycb7da4b2019-08-28 19:35:56 -07001142void ShmEventLoop::SetRuntimeRealtimePriority(int priority) {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001143 CheckCurrentThread();
Alex Perrycb7da4b2019-08-28 19:35:56 -07001144 if (is_running()) {
1145 LOG(FATAL) << "Cannot set realtime priority while running.";
1146 }
1147 priority_ = priority;
1148}
1149
Brian Silverman6a54ff32020-04-28 16:41:39 -07001150void ShmEventLoop::SetRuntimeAffinity(const cpu_set_t &cpuset) {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001151 CheckCurrentThread();
Brian Silverman6a54ff32020-04-28 16:41:39 -07001152 if (is_running()) {
1153 LOG(FATAL) << "Cannot set affinity while running.";
1154 }
1155 affinity_ = cpuset;
1156}
1157
James Kuszmaul57c2baa2020-01-19 14:52:52 -08001158void ShmEventLoop::set_name(const std::string_view name) {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001159 CheckCurrentThread();
James Kuszmaul57c2baa2020-01-19 14:52:52 -08001160 name_ = std::string(name);
1161 UpdateTimingReport();
1162}
1163
Brian Silvermana5450a92020-08-12 19:59:57 -07001164absl::Span<const char> ShmEventLoop::GetWatcherSharedMemory(
1165 const Channel *channel) {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001166 CheckCurrentThread();
Brian Silverman148d43d2020-06-07 18:19:22 -05001167 ShmWatcherState *const watcher_state =
1168 static_cast<ShmWatcherState *>(GetWatcherState(channel));
Brian Silverman5120afb2020-01-31 17:44:35 -08001169 return watcher_state->GetSharedMemory();
1170}
1171
Brian Silverman4f4e0612020-08-12 19:54:41 -07001172int ShmEventLoop::NumberBuffers(const Channel *channel) {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001173 CheckCurrentThread();
Austin Schuh4d275fc2022-09-16 15:42:45 -07001174 return ipc_lib::MakeQueueConfiguration(configuration(), channel)
1175 .num_messages();
Brian Silverman4f4e0612020-08-12 19:54:41 -07001176}
1177
Brian Silverman5120afb2020-01-31 17:44:35 -08001178absl::Span<char> ShmEventLoop::GetShmSenderSharedMemory(
1179 const aos::RawSender *sender) const {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001180 CheckCurrentThread();
Brian Silverman148d43d2020-06-07 18:19:22 -05001181 return static_cast<const ShmSender *>(sender)->GetSharedMemory();
Brian Silverman5120afb2020-01-31 17:44:35 -08001182}
1183
Brian Silvermana5450a92020-08-12 19:59:57 -07001184absl::Span<const char> ShmEventLoop::GetShmFetcherPrivateMemory(
Brian Silverman6d2b3592020-06-18 14:40:15 -07001185 const aos::RawFetcher *fetcher) const {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001186 CheckCurrentThread();
Brian Silverman6d2b3592020-06-18 14:40:15 -07001187 return static_cast<const ShmFetcher *>(fetcher)->GetPrivateMemory();
1188}
1189
Austin Schuh3054f5f2021-07-21 15:38:01 -07001190pid_t ShmEventLoop::GetTid() {
1191 CheckCurrentThread();
1192 return syscall(SYS_gettid);
1193}
Austin Schuh39788ff2019-12-01 18:22:57 -08001194
Alex Perrycb7da4b2019-08-28 19:35:56 -07001195} // namespace aos