blob: 5be50777d10be67a83edebbbde2834ac571ce2e7 [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
Tyler Chatow67ddb032020-01-12 14:30:04 -080013#include "aos/events/aos_logging.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070014#include "aos/events/epoll.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080015#include "aos/events/event_loop_generated.h"
16#include "aos/events/timing_statistics.h"
Austin Schuh094d09b2020-11-20 23:26:52 -080017#include "aos/init.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070018#include "aos/ipc_lib/lockless_queue.h"
Austin Schuh4d275fc2022-09-16 15:42:45 -070019#include "aos/ipc_lib/memory_mapped_queue.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070020#include "aos/realtime.h"
Austin Schuh32fd5a72019-12-01 22:20:26 -080021#include "aos/stl_mutex/stl_mutex.h"
Austin Schuhfccb2d02020-01-26 16:11:19 -080022#include "aos/util/file.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070023#include "aos/util/phased_loop.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080024#include "glog/logging.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070025
Austin Schuhe84c3ed2019-12-14 15:29:48 -080026namespace {
27
28// Returns the portion of the path after the last /. This very much assumes
29// that the application name is null terminated.
30const char *Filename(const char *path) {
31 const std::string_view path_string_view = path;
32 auto last_slash_pos = path_string_view.find_last_of("/");
33
34 return last_slash_pos == std::string_view::npos ? path
35 : path + last_slash_pos + 1;
36}
37
38} // namespace
39
Alex Perrycb7da4b2019-08-28 19:35:56 -070040DEFINE_string(shm_base, "/dev/shm/aos",
41 "Directory to place queue backing mmaped files in.");
42DEFINE_uint32(permissions, 0770,
43 "Permissions to make shared memory files and folders.");
Austin Schuhe84c3ed2019-12-14 15:29:48 -080044DEFINE_string(application_name, Filename(program_invocation_name),
45 "The application name");
Alex Perrycb7da4b2019-08-28 19:35:56 -070046
47namespace aos {
48
Brian Silverman148d43d2020-06-07 18:19:22 -050049using namespace shm_event_loop_internal;
50
Austin Schuhcdab6192019-12-29 17:47:46 -080051void SetShmBase(const std::string_view base) {
Austin Schuhef323c02020-09-01 14:55:28 -070052 FLAGS_shm_base = std::string(base) + "/aos";
Austin Schuhcdab6192019-12-29 17:47:46 -080053}
54
Brian Silverman4f4e0612020-08-12 19:54:41 -070055namespace {
56
Austin Schuh217a9782019-12-21 23:02:50 -080057const Node *MaybeMyNode(const Configuration *configuration) {
58 if (!configuration->has_nodes()) {
59 return nullptr;
60 }
Alex Perrycb7da4b2019-08-28 19:35:56 -070061
Austin Schuh217a9782019-12-21 23:02:50 -080062 return configuration::GetMyNode(configuration);
63}
Alex Perrycb7da4b2019-08-28 19:35:56 -070064
Austin Schuh39788ff2019-12-01 18:22:57 -080065} // namespace
66
Austin Schuh217a9782019-12-21 23:02:50 -080067ShmEventLoop::ShmEventLoop(const Configuration *configuration)
Austin Schuh83c7f702021-01-19 22:36:29 -080068 : EventLoop(configuration),
69 boot_uuid_(UUID::BootUUID()),
Austin Schuhef323c02020-09-01 14:55:28 -070070 shm_base_(FLAGS_shm_base),
Austin Schuhe84c3ed2019-12-14 15:29:48 -080071 name_(FLAGS_application_name),
Austin Schuh15649d62019-12-28 16:36:38 -080072 node_(MaybeMyNode(configuration)) {
Austin Schuh094d09b2020-11-20 23:26:52 -080073 CHECK(IsInitialized()) << ": Need to initialize AOS first.";
Austin Schuh0debde12022-08-17 16:25:17 -070074 ClearContext();
Austin Schuh15649d62019-12-28 16:36:38 -080075 if (configuration->has_nodes()) {
76 CHECK(node_ != nullptr) << ": Couldn't find node in config.";
77 }
78}
Austin Schuh217a9782019-12-21 23:02:50 -080079
Brian Silverman148d43d2020-06-07 18:19:22 -050080namespace shm_event_loop_internal {
Austin Schuh39788ff2019-12-01 18:22:57 -080081
82class SimpleShmFetcher {
Alex Perrycb7da4b2019-08-28 19:35:56 -070083 public:
Austin Schuhef323c02020-09-01 14:55:28 -070084 explicit SimpleShmFetcher(std::string_view shm_base, ShmEventLoop *event_loop,
85 const Channel *channel)
Austin Schuh432784f2020-06-23 17:27:35 -070086 : event_loop_(event_loop),
87 channel_(channel),
Austin Schuh4d275fc2022-09-16 15:42:45 -070088 lockless_queue_memory_(shm_base, FLAGS_permissions,
89 event_loop->configuration(), channel),
Brian Silvermanfc0d2e82020-08-12 19:58:35 -070090 reader_(lockless_queue_memory_.queue()) {
Alex Perrycb7da4b2019-08-28 19:35:56 -070091 context_.data = nullptr;
92 // Point the queue index at the next index to read starting now. This
93 // makes it such that FetchNext will read the next message sent after
94 // the fetcher is created.
95 PointAtNextQueueIndex();
96 }
97
Austin Schuh39788ff2019-12-01 18:22:57 -080098 ~SimpleShmFetcher() {}
Alex Perrycb7da4b2019-08-28 19:35:56 -070099
Brian Silverman77162972020-08-12 19:52:40 -0700100 // Sets this object to pin or copy data, as configured in the channel.
101 void RetrieveData() {
102 if (channel_->read_method() == ReadMethod::PIN) {
103 PinDataOnFetch();
104 } else {
105 CopyDataOnFetch();
106 }
107 }
108
Brian Silverman3bca5322020-08-12 19:35:29 -0700109 // Sets this object to copy data out of the shared memory into a private
110 // buffer when fetching.
111 void CopyDataOnFetch() {
Brian Silverman77162972020-08-12 19:52:40 -0700112 CHECK(!pin_data());
Brian Silverman3bca5322020-08-12 19:35:29 -0700113 data_storage_.reset(static_cast<char *>(
114 malloc(channel_->max_size() + kChannelDataAlignment - 1)));
115 }
116
Brian Silverman77162972020-08-12 19:52:40 -0700117 // Sets this object to pin data in shared memory when fetching.
118 void PinDataOnFetch() {
119 CHECK(!copy_data());
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700120 auto maybe_pinner =
121 ipc_lib::LocklessQueuePinner::Make(lockless_queue_memory_.queue());
Brian Silverman77162972020-08-12 19:52:40 -0700122 if (!maybe_pinner) {
123 LOG(FATAL) << "Failed to create reader on "
124 << configuration::CleanedChannelToString(channel_)
125 << ", too many readers.";
126 }
127 pinner_ = std::move(maybe_pinner.value());
128 }
129
Alex Perrycb7da4b2019-08-28 19:35:56 -0700130 // Points the next message to fetch at the queue index which will be
131 // populated next.
132 void PointAtNextQueueIndex() {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700133 actual_queue_index_ = reader_.LatestIndex();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700134 if (!actual_queue_index_.valid()) {
135 // Nothing in the queue. The next element will show up at the 0th
136 // index in the queue.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700137 actual_queue_index_ = ipc_lib::QueueIndex::Zero(
138 LocklessQueueSize(lockless_queue_memory_.memory()));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700139 } else {
140 actual_queue_index_ = actual_queue_index_.Increment();
141 }
142 }
143
Austin Schuh39788ff2019-12-01 18:22:57 -0800144 bool FetchNext() {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700145 const ipc_lib::LocklessQueueReader::Result read_result =
Brian Silverman3bca5322020-08-12 19:35:29 -0700146 DoFetch(actual_queue_index_);
Austin Schuh432784f2020-06-23 17:27:35 -0700147
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700148 return read_result == ipc_lib::LocklessQueueReader::Result::GOOD;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700149 }
150
Austin Schuh39788ff2019-12-01 18:22:57 -0800151 bool Fetch() {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700152 const ipc_lib::QueueIndex queue_index = reader_.LatestIndex();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700153 // actual_queue_index_ is only meaningful if it was set by Fetch or
154 // FetchNext. This happens when valid_data_ has been set. So, only
155 // skip checking if valid_data_ is true.
156 //
157 // Also, if the latest queue index is invalid, we are empty. So there
158 // is nothing to fetch.
Austin Schuh39788ff2019-12-01 18:22:57 -0800159 if ((context_.data != nullptr &&
Alex Perrycb7da4b2019-08-28 19:35:56 -0700160 queue_index == actual_queue_index_.DecrementBy(1u)) ||
161 !queue_index.valid()) {
162 return false;
163 }
164
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700165 const ipc_lib::LocklessQueueReader::Result read_result =
166 DoFetch(queue_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700167
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700168 CHECK(read_result != ipc_lib::LocklessQueueReader::Result::NOTHING_NEW)
Austin Schuhf5652592019-12-29 16:26:15 -0800169 << ": Queue index went backwards. This should never happen. "
170 << configuration::CleanedChannelToString(channel_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700171
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700172 return read_result == ipc_lib::LocklessQueueReader::Result::GOOD;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700173 }
174
Austin Schuh39788ff2019-12-01 18:22:57 -0800175 Context context() const { return context_; }
176
Alex Perrycb7da4b2019-08-28 19:35:56 -0700177 bool RegisterWakeup(int priority) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700178 CHECK(!watcher_);
179 watcher_ = ipc_lib::LocklessQueueWatcher::Make(
180 lockless_queue_memory_.queue(), priority);
181 return static_cast<bool>(watcher_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700182 }
183
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700184 void UnregisterWakeup() {
185 CHECK(watcher_);
186 watcher_ = std::nullopt;
187 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700188
Brian Silvermana5450a92020-08-12 19:59:57 -0700189 absl::Span<char> GetMutableSharedMemory() {
190 return lockless_queue_memory_.GetMutableSharedMemory();
Brian Silverman5120afb2020-01-31 17:44:35 -0800191 }
192
Brian Silvermana5450a92020-08-12 19:59:57 -0700193 absl::Span<const char> GetConstSharedMemory() const {
194 return lockless_queue_memory_.GetConstSharedMemory();
195 }
196
197 absl::Span<const char> GetPrivateMemory() const {
198 if (pin_data()) {
199 return lockless_queue_memory_.GetConstSharedMemory();
200 }
Brian Silverman6d2b3592020-06-18 14:40:15 -0700201 return absl::Span<char>(
202 const_cast<SimpleShmFetcher *>(this)->data_storage_start(),
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700203 LocklessQueueMessageDataSize(lockless_queue_memory_.memory()));
Brian Silverman6d2b3592020-06-18 14:40:15 -0700204 }
205
Alex Perrycb7da4b2019-08-28 19:35:56 -0700206 private:
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700207 ipc_lib::LocklessQueueReader::Result DoFetch(
208 ipc_lib::QueueIndex queue_index) {
Brian Silverman3bca5322020-08-12 19:35:29 -0700209 // TODO(austin): Get behind and make sure it dies.
210 char *copy_buffer = nullptr;
211 if (copy_data()) {
212 copy_buffer = data_storage_start();
213 }
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700214 ipc_lib::LocklessQueueReader::Result read_result = reader_.Read(
Brian Silverman3bca5322020-08-12 19:35:29 -0700215 queue_index.index(), &context_.monotonic_event_time,
216 &context_.realtime_event_time, &context_.monotonic_remote_time,
217 &context_.realtime_remote_time, &context_.remote_queue_index,
Austin Schuha9012be2021-07-21 15:19:11 -0700218 &context_.source_boot_uuid, &context_.size, copy_buffer);
Brian Silverman3bca5322020-08-12 19:35:29 -0700219
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700220 if (read_result == ipc_lib::LocklessQueueReader::Result::GOOD) {
Brian Silverman77162972020-08-12 19:52:40 -0700221 if (pin_data()) {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700222 const int pin_result = pinner_->PinIndex(queue_index.index());
223 CHECK(pin_result >= 0)
Brian Silverman77162972020-08-12 19:52:40 -0700224 << ": Got behind while reading and the last message was modified "
225 "out from under us while we tried to pin it. Don't get so far "
226 "behind on: "
227 << configuration::CleanedChannelToString(channel_);
Brian Silverman4f4e0612020-08-12 19:54:41 -0700228 context_.buffer_index = pin_result;
229 } else {
230 context_.buffer_index = -1;
Brian Silverman77162972020-08-12 19:52:40 -0700231 }
232
Brian Silverman3bca5322020-08-12 19:35:29 -0700233 context_.queue_index = queue_index.index();
234 if (context_.remote_queue_index == 0xffffffffu) {
235 context_.remote_queue_index = context_.queue_index;
236 }
237 if (context_.monotonic_remote_time == aos::monotonic_clock::min_time) {
238 context_.monotonic_remote_time = context_.monotonic_event_time;
239 }
240 if (context_.realtime_remote_time == aos::realtime_clock::min_time) {
241 context_.realtime_remote_time = context_.realtime_event_time;
242 }
243 const char *const data = DataBuffer();
244 if (data) {
245 context_.data =
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700246 data +
247 LocklessQueueMessageDataSize(lockless_queue_memory_.memory()) -
248 context_.size;
Brian Silverman3bca5322020-08-12 19:35:29 -0700249 } else {
250 context_.data = nullptr;
251 }
252 actual_queue_index_ = queue_index.Increment();
253 }
254
255 // Make sure the data wasn't modified while we were reading it. This
256 // can only happen if you are reading the last message *while* it is
257 // being written to, which means you are pretty far behind.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700258 CHECK(read_result != ipc_lib::LocklessQueueReader::Result::OVERWROTE)
Brian Silverman3bca5322020-08-12 19:35:29 -0700259 << ": Got behind while reading and the last message was modified "
260 "out from under us while we were reading it. Don't get so far "
261 "behind on: "
262 << configuration::CleanedChannelToString(channel_);
263
264 // We fell behind between when we read the index and read the value.
265 // This isn't worth recovering from since this means we went to sleep
266 // for a long time in the middle of this function.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700267 if (read_result == ipc_lib::LocklessQueueReader::Result::TOO_OLD) {
Brian Silverman3bca5322020-08-12 19:35:29 -0700268 event_loop_->SendTimingReport();
269 LOG(FATAL) << "The next message is no longer available. "
270 << configuration::CleanedChannelToString(channel_);
271 }
272
273 return read_result;
274 }
275
276 char *data_storage_start() const {
277 CHECK(copy_data());
Brian Silvermana1652f32020-01-29 20:41:44 -0800278 return RoundChannelData(data_storage_.get(), channel_->max_size());
279 }
Brian Silverman3bca5322020-08-12 19:35:29 -0700280
281 // Note that for some modes the return value will change as new messages are
282 // read.
283 const char *DataBuffer() const {
284 if (copy_data()) {
285 return data_storage_start();
286 }
Brian Silverman77162972020-08-12 19:52:40 -0700287 if (pin_data()) {
288 return static_cast<const char *>(pinner_->Data());
289 }
Brian Silverman3bca5322020-08-12 19:35:29 -0700290 return nullptr;
291 }
292
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800293 bool copy_data() const { return static_cast<bool>(data_storage_); }
Brian Silverman77162972020-08-12 19:52:40 -0700294 bool pin_data() const { return static_cast<bool>(pinner_); }
Brian Silvermana1652f32020-01-29 20:41:44 -0800295
Austin Schuh432784f2020-06-23 17:27:35 -0700296 aos::ShmEventLoop *event_loop_;
Austin Schuhf5652592019-12-29 16:26:15 -0800297 const Channel *const channel_;
Austin Schuh4d275fc2022-09-16 15:42:45 -0700298 ipc_lib::MemoryMappedQueue lockless_queue_memory_;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700299 ipc_lib::LocklessQueueReader reader_;
300 // This being nullopt indicates we're not looking for wakeups right now.
301 std::optional<ipc_lib::LocklessQueueWatcher> watcher_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700302
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700303 ipc_lib::QueueIndex actual_queue_index_ = ipc_lib::QueueIndex::Invalid();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700304
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800305 // This being empty indicates we're not going to copy data.
306 std::unique_ptr<char, decltype(&free)> data_storage_{nullptr, &free};
Austin Schuh39788ff2019-12-01 18:22:57 -0800307
Brian Silverman77162972020-08-12 19:52:40 -0700308 // This being nullopt indicates we're not going to pin messages.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700309 std::optional<ipc_lib::LocklessQueuePinner> pinner_;
Brian Silverman77162972020-08-12 19:52:40 -0700310
Austin Schuh39788ff2019-12-01 18:22:57 -0800311 Context context_;
312};
313
314class ShmFetcher : public RawFetcher {
315 public:
Austin Schuhef323c02020-09-01 14:55:28 -0700316 explicit ShmFetcher(std::string_view shm_base, ShmEventLoop *event_loop,
317 const Channel *channel)
Austin Schuhaa79e4e2019-12-29 20:43:32 -0800318 : RawFetcher(event_loop, channel),
Austin Schuhef323c02020-09-01 14:55:28 -0700319 simple_shm_fetcher_(shm_base, event_loop, channel) {
Brian Silverman77162972020-08-12 19:52:40 -0700320 simple_shm_fetcher_.RetrieveData();
Brian Silverman3bca5322020-08-12 19:35:29 -0700321 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800322
Austin Schuh3054f5f2021-07-21 15:38:01 -0700323 ~ShmFetcher() override {
324 shm_event_loop()->CheckCurrentThread();
325 context_.data = nullptr;
326 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800327
328 std::pair<bool, monotonic_clock::time_point> DoFetchNext() override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700329 shm_event_loop()->CheckCurrentThread();
Austin Schuh39788ff2019-12-01 18:22:57 -0800330 if (simple_shm_fetcher_.FetchNext()) {
331 context_ = simple_shm_fetcher_.context();
332 return std::make_pair(true, monotonic_clock::now());
333 }
334 return std::make_pair(false, monotonic_clock::min_time);
335 }
336
337 std::pair<bool, monotonic_clock::time_point> DoFetch() override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700338 shm_event_loop()->CheckCurrentThread();
Austin Schuh39788ff2019-12-01 18:22:57 -0800339 if (simple_shm_fetcher_.Fetch()) {
340 context_ = simple_shm_fetcher_.context();
341 return std::make_pair(true, monotonic_clock::now());
342 }
343 return std::make_pair(false, monotonic_clock::min_time);
344 }
345
Brian Silvermana5450a92020-08-12 19:59:57 -0700346 absl::Span<const char> GetPrivateMemory() const {
Brian Silverman6d2b3592020-06-18 14:40:15 -0700347 return simple_shm_fetcher_.GetPrivateMemory();
348 }
349
Austin Schuh39788ff2019-12-01 18:22:57 -0800350 private:
Austin Schuh3054f5f2021-07-21 15:38:01 -0700351 const ShmEventLoop *shm_event_loop() const {
352 return static_cast<const ShmEventLoop *>(event_loop());
353 }
354
Austin Schuh39788ff2019-12-01 18:22:57 -0800355 SimpleShmFetcher simple_shm_fetcher_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700356};
357
Brian Silvermane1fe2512022-08-14 23:18:50 -0700358class ShmExitHandle : public ExitHandle {
359 public:
360 ShmExitHandle(ShmEventLoop *event_loop) : event_loop_(event_loop) {
361 ++event_loop_->exit_handle_count_;
362 }
363 ~ShmExitHandle() override {
364 CHECK_GT(event_loop_->exit_handle_count_, 0);
365 --event_loop_->exit_handle_count_;
366 }
367
368 void Exit() override { event_loop_->Exit(); }
369
370 private:
371 ShmEventLoop *const event_loop_;
372};
373
Alex Perrycb7da4b2019-08-28 19:35:56 -0700374class ShmSender : public RawSender {
375 public:
Austin Schuhef323c02020-09-01 14:55:28 -0700376 explicit ShmSender(std::string_view shm_base, EventLoop *event_loop,
377 const Channel *channel)
Austin Schuh39788ff2019-12-01 18:22:57 -0800378 : RawSender(event_loop, channel),
Austin Schuh4d275fc2022-09-16 15:42:45 -0700379 lockless_queue_memory_(shm_base, FLAGS_permissions,
380 event_loop->configuration(), channel),
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700381 lockless_queue_sender_(VerifySender(
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700382 ipc_lib::LocklessQueueSender::Make(
383 lockless_queue_memory_.queue(),
384 std::chrono::nanoseconds(
385 event_loop->configuration()->channel_storage_duration())),
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700386 channel)),
387 wake_upper_(lockless_queue_memory_.queue()) {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700388
Austin Schuh3054f5f2021-07-21 15:38:01 -0700389 ~ShmSender() override { shm_event_loop()->CheckCurrentThread(); }
Austin Schuh39788ff2019-12-01 18:22:57 -0800390
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700391 static ipc_lib::LocklessQueueSender VerifySender(
392 std::optional<ipc_lib::LocklessQueueSender> sender,
Austin Schuhe516ab02020-05-06 21:37:04 -0700393 const Channel *channel) {
394 if (sender) {
395 return std::move(sender.value());
396 }
397 LOG(FATAL) << "Failed to create sender on "
398 << configuration::CleanedChannelToString(channel)
399 << ", too many senders.";
400 }
401
Austin Schuh3054f5f2021-07-21 15:38:01 -0700402 void *data() override {
403 shm_event_loop()->CheckCurrentThread();
404 return lockless_queue_sender_.Data();
405 }
406 size_t size() override {
407 shm_event_loop()->CheckCurrentThread();
408 return lockless_queue_sender_.size();
409 }
milind1f1dca32021-07-03 13:50:07 -0700410
411 Error DoSend(size_t length,
412 aos::monotonic_clock::time_point monotonic_remote_time,
413 aos::realtime_clock::time_point realtime_remote_time,
414 uint32_t remote_queue_index,
415 const UUID &source_boot_uuid) override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700416 shm_event_loop()->CheckCurrentThread();
Austin Schuh0f7ed462020-03-28 20:38:34 -0700417 CHECK_LE(length, static_cast<size_t>(channel()->max_size()))
418 << ": Sent too big a message on "
419 << configuration::CleanedChannelToString(channel());
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700420 const auto result = lockless_queue_sender_.Send(
421 length, monotonic_remote_time, realtime_remote_time, remote_queue_index,
422 source_boot_uuid, &monotonic_sent_time_, &realtime_sent_time_,
423 &sent_queue_index_);
424 CHECK_NE(result, ipc_lib::LocklessQueueSender::Result::INVALID_REDZONE)
Austin Schuh91ba6392020-10-03 13:27:47 -0700425 << ": Somebody wrote outside the buffer of their message on channel "
426 << configuration::CleanedChannelToString(channel());
427
Austin Schuh65493d62022-08-17 15:10:37 -0700428 wake_upper_.Wakeup(event_loop()->is_running()
429 ? event_loop()->runtime_realtime_priority()
430 : 0);
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700431 return CheckLocklessQueueResult(result);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700432 }
433
milind1f1dca32021-07-03 13:50:07 -0700434 Error DoSend(const void *msg, size_t length,
435 aos::monotonic_clock::time_point monotonic_remote_time,
436 aos::realtime_clock::time_point realtime_remote_time,
437 uint32_t remote_queue_index,
438 const UUID &source_boot_uuid) override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700439 shm_event_loop()->CheckCurrentThread();
Austin Schuh0f7ed462020-03-28 20:38:34 -0700440 CHECK_LE(length, static_cast<size_t>(channel()->max_size()))
441 << ": Sent too big a message on "
442 << configuration::CleanedChannelToString(channel());
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700443 const auto result = lockless_queue_sender_.Send(
Brian Silvermanaf9a4d82020-10-06 15:10:58 -0700444 reinterpret_cast<const char *>(msg), length, monotonic_remote_time,
Austin Schuha9012be2021-07-21 15:19:11 -0700445 realtime_remote_time, remote_queue_index, source_boot_uuid,
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700446 &monotonic_sent_time_, &realtime_sent_time_, &sent_queue_index_);
447
448 CHECK_NE(result, ipc_lib::LocklessQueueSender::Result::INVALID_REDZONE)
449 << ": Somebody wrote outside the buffer of their message on "
450 "channel "
Austin Schuh91ba6392020-10-03 13:27:47 -0700451 << configuration::CleanedChannelToString(channel());
Austin Schuh65493d62022-08-17 15:10:37 -0700452 wake_upper_.Wakeup(event_loop()->is_running()
453 ? event_loop()->runtime_realtime_priority()
454 : 0);
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700455
456 return CheckLocklessQueueResult(result);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700457 }
458
Brian Silverman5120afb2020-01-31 17:44:35 -0800459 absl::Span<char> GetSharedMemory() const {
Brian Silvermana5450a92020-08-12 19:59:57 -0700460 return lockless_queue_memory_.GetMutableSharedMemory();
Brian Silverman5120afb2020-01-31 17:44:35 -0800461 }
462
Austin Schuh3054f5f2021-07-21 15:38:01 -0700463 int buffer_index() override {
464 shm_event_loop()->CheckCurrentThread();
465 return lockless_queue_sender_.buffer_index();
466 }
Brian Silverman4f4e0612020-08-12 19:54:41 -0700467
Alex Perrycb7da4b2019-08-28 19:35:56 -0700468 private:
Austin Schuh3054f5f2021-07-21 15:38:01 -0700469 const ShmEventLoop *shm_event_loop() const {
470 return static_cast<const ShmEventLoop *>(event_loop());
471 }
472
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700473 RawSender::Error CheckLocklessQueueResult(
474 const ipc_lib::LocklessQueueSender::Result &result) {
475 switch (result) {
476 case ipc_lib::LocklessQueueSender::Result::GOOD:
477 return Error::kOk;
478 case ipc_lib::LocklessQueueSender::Result::MESSAGES_SENT_TOO_FAST:
479 return Error::kMessagesSentTooFast;
480 case ipc_lib::LocklessQueueSender::Result::INVALID_REDZONE:
481 return Error::kInvalidRedzone;
482 }
483 LOG(FATAL) << "Unknown lockless queue sender result"
484 << static_cast<int>(result);
485 }
486
Austin Schuh4d275fc2022-09-16 15:42:45 -0700487 ipc_lib::MemoryMappedQueue lockless_queue_memory_;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700488 ipc_lib::LocklessQueueSender lockless_queue_sender_;
489 ipc_lib::LocklessQueueWakeUpper wake_upper_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700490};
491
Alex Perrycb7da4b2019-08-28 19:35:56 -0700492// Class to manage the state for a Watcher.
Brian Silverman148d43d2020-06-07 18:19:22 -0500493class ShmWatcherState : public WatcherState {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700494 public:
Brian Silverman148d43d2020-06-07 18:19:22 -0500495 ShmWatcherState(
Austin Schuhef323c02020-09-01 14:55:28 -0700496 std::string_view shm_base, ShmEventLoop *event_loop,
497 const Channel *channel,
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800498 std::function<void(const Context &context, const void *message)> fn,
499 bool copy_data)
Brian Silverman148d43d2020-06-07 18:19:22 -0500500 : WatcherState(event_loop, channel, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800501 event_loop_(event_loop),
502 event_(this),
Austin Schuhef323c02020-09-01 14:55:28 -0700503 simple_shm_fetcher_(shm_base, event_loop, channel) {
Brian Silverman3bca5322020-08-12 19:35:29 -0700504 if (copy_data) {
Brian Silverman77162972020-08-12 19:52:40 -0700505 simple_shm_fetcher_.RetrieveData();
Brian Silverman3bca5322020-08-12 19:35:29 -0700506 }
507 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700508
Austin Schuh3054f5f2021-07-21 15:38:01 -0700509 ~ShmWatcherState() override {
510 event_loop_->CheckCurrentThread();
511 event_loop_->RemoveEvent(&event_);
512 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800513
514 void Startup(EventLoop *event_loop) override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700515 event_loop_->CheckCurrentThread();
Austin Schuh7d87b672019-12-01 20:23:49 -0800516 simple_shm_fetcher_.PointAtNextQueueIndex();
Austin Schuh65493d62022-08-17 15:10:37 -0700517 CHECK(RegisterWakeup(event_loop->runtime_realtime_priority()));
Austin Schuh39788ff2019-12-01 18:22:57 -0800518 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700519
Alex Perrycb7da4b2019-08-28 19:35:56 -0700520 // Returns true if there is new data available.
Austin Schuh7d87b672019-12-01 20:23:49 -0800521 bool CheckForNewData() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700522 if (!has_new_data_) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800523 has_new_data_ = simple_shm_fetcher_.FetchNext();
Austin Schuh7d87b672019-12-01 20:23:49 -0800524
525 if (has_new_data_) {
526 event_.set_event_time(
Austin Schuhad154822019-12-27 15:45:13 -0800527 simple_shm_fetcher_.context().monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800528 event_loop_->AddEvent(&event_);
529 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700530 }
531
532 return has_new_data_;
533 }
534
Alex Perrycb7da4b2019-08-28 19:35:56 -0700535 // Consumes the data by calling the callback.
Austin Schuh7d87b672019-12-01 20:23:49 -0800536 void HandleEvent() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700537 CHECK(has_new_data_);
Austin Schuh39788ff2019-12-01 18:22:57 -0800538 DoCallCallback(monotonic_clock::now, simple_shm_fetcher_.context());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700539 has_new_data_ = false;
Austin Schuh7d87b672019-12-01 20:23:49 -0800540 CheckForNewData();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700541 }
542
Austin Schuh39788ff2019-12-01 18:22:57 -0800543 // Registers us to receive a signal on event reception.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700544 bool RegisterWakeup(int priority) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800545 return simple_shm_fetcher_.RegisterWakeup(priority);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700546 }
547
Austin Schuh39788ff2019-12-01 18:22:57 -0800548 void UnregisterWakeup() { return simple_shm_fetcher_.UnregisterWakeup(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700549
Brian Silvermana5450a92020-08-12 19:59:57 -0700550 absl::Span<const char> GetSharedMemory() const {
551 return simple_shm_fetcher_.GetConstSharedMemory();
Brian Silverman5120afb2020-01-31 17:44:35 -0800552 }
553
Alex Perrycb7da4b2019-08-28 19:35:56 -0700554 private:
555 bool has_new_data_ = false;
556
Austin Schuh7d87b672019-12-01 20:23:49 -0800557 ShmEventLoop *event_loop_;
Brian Silverman148d43d2020-06-07 18:19:22 -0500558 EventHandler<ShmWatcherState> event_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800559 SimpleShmFetcher simple_shm_fetcher_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700560};
561
562// Adapter class to adapt a timerfd to a TimerHandler.
Brian Silverman148d43d2020-06-07 18:19:22 -0500563class ShmTimerHandler final : public TimerHandler {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700564 public:
Brian Silverman148d43d2020-06-07 18:19:22 -0500565 ShmTimerHandler(ShmEventLoop *shm_event_loop, ::std::function<void()> fn)
Austin Schuh39788ff2019-12-01 18:22:57 -0800566 : TimerHandler(shm_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800567 shm_event_loop_(shm_event_loop),
568 event_(this) {
Austin Schuhcde39fd2020-02-22 20:58:24 -0800569 shm_event_loop_->epoll_.OnReadable(timerfd_.fd(), [this]() {
Austin Schuh5ca13112021-02-07 22:06:53 -0800570 // The timer may fire spuriously. HandleEvent on the event loop will
Austin Schuhcde39fd2020-02-22 20:58:24 -0800571 // call the callback if it is needed. It may also have called it when
572 // processing some other event, and the kernel decided to deliver this
573 // wakeup anyways.
574 timerfd_.Read();
575 shm_event_loop_->HandleEvent();
576 });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700577 }
578
Brian Silverman148d43d2020-06-07 18:19:22 -0500579 ~ShmTimerHandler() {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700580 shm_event_loop_->CheckCurrentThread();
Austin Schuh7d87b672019-12-01 20:23:49 -0800581 Disable();
582 shm_event_loop_->epoll_.DeleteFd(timerfd_.fd());
583 }
584
585 void HandleEvent() {
Austin Schuhcde39fd2020-02-22 20:58:24 -0800586 CHECK(!event_.valid());
Brian Silvermanaf9a4d82020-10-06 15:10:58 -0700587 disabled_ = false;
Austin Schuhcde39fd2020-02-22 20:58:24 -0800588 const auto monotonic_now = Call(monotonic_clock::now, base_);
589 if (event_.valid()) {
590 // If someone called Setup inside Call, rescheduling is already taken care
591 // of. Bail.
592 return;
Austin Schuh7d87b672019-12-01 20:23:49 -0800593 }
Brian Silvermanaf9a4d82020-10-06 15:10:58 -0700594 if (disabled_) {
595 // Somebody called Disable inside Call, so we don't want to reschedule.
596 // Bail.
597 return;
598 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800599
Austin Schuh4d275fc2022-09-16 15:42:45 -0700600 if (repeat_offset_ == std::chrono::seconds(0)) {
Austin Schuhcde39fd2020-02-22 20:58:24 -0800601 timerfd_.Disable();
602 } else {
603 // Compute how many cycles have elapsed and schedule the next iteration
604 // for the next iteration in the future.
605 const int elapsed_cycles =
606 std::max<int>(0, (monotonic_now - base_ + repeat_offset_ -
607 std::chrono::nanoseconds(1)) /
608 repeat_offset_);
609 base_ += repeat_offset_ * elapsed_cycles;
Austin Schuh7d87b672019-12-01 20:23:49 -0800610
Austin Schuhcde39fd2020-02-22 20:58:24 -0800611 // Update the heap and schedule the timerfd wakeup.
Austin Schuh7d87b672019-12-01 20:23:49 -0800612 event_.set_event_time(base_);
613 shm_event_loop_->AddEvent(&event_);
Austin Schuh4d275fc2022-09-16 15:42:45 -0700614 timerfd_.SetTime(base_, std::chrono::seconds(0));
Austin Schuh7d87b672019-12-01 20:23:49 -0800615 }
616 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700617
618 void Setup(monotonic_clock::time_point base,
619 monotonic_clock::duration repeat_offset) override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700620 shm_event_loop_->CheckCurrentThread();
Austin Schuh7d87b672019-12-01 20:23:49 -0800621 if (event_.valid()) {
622 shm_event_loop_->RemoveEvent(&event_);
623 }
624
Alex Perrycb7da4b2019-08-28 19:35:56 -0700625 timerfd_.SetTime(base, repeat_offset);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800626 base_ = base;
627 repeat_offset_ = repeat_offset;
Austin Schuh7d87b672019-12-01 20:23:49 -0800628 event_.set_event_time(base_);
629 shm_event_loop_->AddEvent(&event_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700630 }
631
Austin Schuh7d87b672019-12-01 20:23:49 -0800632 void Disable() override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700633 shm_event_loop_->CheckCurrentThread();
Austin Schuh7d87b672019-12-01 20:23:49 -0800634 shm_event_loop_->RemoveEvent(&event_);
635 timerfd_.Disable();
Brian Silvermanaf9a4d82020-10-06 15:10:58 -0700636 disabled_ = true;
Austin Schuh7d87b672019-12-01 20:23:49 -0800637 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700638
639 private:
640 ShmEventLoop *shm_event_loop_;
Brian Silverman148d43d2020-06-07 18:19:22 -0500641 EventHandler<ShmTimerHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700642
Brian Silverman148d43d2020-06-07 18:19:22 -0500643 internal::TimerFd timerfd_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700644
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800645 monotonic_clock::time_point base_;
646 monotonic_clock::duration repeat_offset_;
Brian Silvermanaf9a4d82020-10-06 15:10:58 -0700647
648 // Used to track if Disable() was called during the callback, so we know not
649 // to reschedule.
650 bool disabled_ = false;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700651};
652
653// Adapter class to the timerfd and PhasedLoop.
Brian Silverman148d43d2020-06-07 18:19:22 -0500654class ShmPhasedLoopHandler final : public PhasedLoopHandler {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700655 public:
Brian Silverman148d43d2020-06-07 18:19:22 -0500656 ShmPhasedLoopHandler(ShmEventLoop *shm_event_loop,
657 ::std::function<void(int)> fn,
658 const monotonic_clock::duration interval,
659 const monotonic_clock::duration offset)
660 : PhasedLoopHandler(shm_event_loop, std::move(fn), interval, offset),
Austin Schuh7d87b672019-12-01 20:23:49 -0800661 shm_event_loop_(shm_event_loop),
662 event_(this) {
663 shm_event_loop_->epoll_.OnReadable(
664 timerfd_.fd(), [this]() { shm_event_loop_->HandleEvent(); });
665 }
666
667 void HandleEvent() {
668 // The return value for read is the number of cycles that have elapsed.
669 // Because we check to see when this event *should* have happened, there are
670 // cases where Read() will return 0, when 1 cycle has actually happened.
671 // This occurs when the timer interrupt hasn't triggered yet. Therefore,
672 // ignore it. Call handles rescheduling and calculating elapsed cycles
673 // without any extra help.
674 timerfd_.Read();
675 event_.Invalidate();
676
677 Call(monotonic_clock::now, [this](monotonic_clock::time_point sleep_time) {
678 Schedule(sleep_time);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700679 });
680 }
681
Brian Silverman148d43d2020-06-07 18:19:22 -0500682 ~ShmPhasedLoopHandler() override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700683 shm_event_loop_->CheckCurrentThread();
Austin Schuh39788ff2019-12-01 18:22:57 -0800684 shm_event_loop_->epoll_.DeleteFd(timerfd_.fd());
Austin Schuh7d87b672019-12-01 20:23:49 -0800685 shm_event_loop_->RemoveEvent(&event_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700686 }
687
688 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800689 // Reschedules the timer.
Austin Schuh39788ff2019-12-01 18:22:57 -0800690 void Schedule(monotonic_clock::time_point sleep_time) override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700691 shm_event_loop_->CheckCurrentThread();
Austin Schuh7d87b672019-12-01 20:23:49 -0800692 if (event_.valid()) {
693 shm_event_loop_->RemoveEvent(&event_);
694 }
695
Austin Schuh39788ff2019-12-01 18:22:57 -0800696 timerfd_.SetTime(sleep_time, ::aos::monotonic_clock::zero());
Austin Schuh7d87b672019-12-01 20:23:49 -0800697 event_.set_event_time(sleep_time);
698 shm_event_loop_->AddEvent(&event_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700699 }
700
701 ShmEventLoop *shm_event_loop_;
Brian Silverman148d43d2020-06-07 18:19:22 -0500702 EventHandler<ShmPhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700703
Brian Silverman148d43d2020-06-07 18:19:22 -0500704 internal::TimerFd timerfd_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700705};
Brian Silverman148d43d2020-06-07 18:19:22 -0500706
707} // namespace shm_event_loop_internal
Alex Perrycb7da4b2019-08-28 19:35:56 -0700708
709::std::unique_ptr<RawFetcher> ShmEventLoop::MakeRawFetcher(
710 const Channel *channel) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700711 CheckCurrentThread();
Austin Schuhca4828c2019-12-28 14:21:35 -0800712 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
713 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
714 << "\", \"type\": \"" << channel->type()->string_view()
715 << "\" } is not able to be fetched on this node. Check your "
716 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800717 }
718
Austin Schuhef323c02020-09-01 14:55:28 -0700719 return ::std::unique_ptr<RawFetcher>(
720 new ShmFetcher(shm_base_, this, channel));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700721}
722
723::std::unique_ptr<RawSender> ShmEventLoop::MakeRawSender(
724 const Channel *channel) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700725 CheckCurrentThread();
Brian Silverman0fc69932020-01-24 21:54:02 -0800726 TakeSender(channel);
Austin Schuh39788ff2019-12-01 18:22:57 -0800727
Austin Schuhef323c02020-09-01 14:55:28 -0700728 return ::std::unique_ptr<RawSender>(new ShmSender(shm_base_, this, channel));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700729}
730
731void ShmEventLoop::MakeRawWatcher(
732 const Channel *channel,
733 std::function<void(const Context &context, const void *message)> watcher) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700734 CheckCurrentThread();
Brian Silverman0fc69932020-01-24 21:54:02 -0800735 TakeWatcher(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800736
Austin Schuh39788ff2019-12-01 18:22:57 -0800737 NewWatcher(::std::unique_ptr<WatcherState>(
Austin Schuhef323c02020-09-01 14:55:28 -0700738 new ShmWatcherState(shm_base_, this, channel, std::move(watcher), true)));
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800739}
740
741void ShmEventLoop::MakeRawNoArgWatcher(
742 const Channel *channel,
743 std::function<void(const Context &context)> watcher) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700744 CheckCurrentThread();
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800745 TakeWatcher(channel);
746
Brian Silverman148d43d2020-06-07 18:19:22 -0500747 NewWatcher(::std::unique_ptr<WatcherState>(new ShmWatcherState(
Austin Schuhef323c02020-09-01 14:55:28 -0700748 shm_base_, this, channel,
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800749 [watcher](const Context &context, const void *) { watcher(context); },
750 false)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700751}
752
753TimerHandler *ShmEventLoop::AddTimer(::std::function<void()> callback) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700754 CheckCurrentThread();
Austin Schuh39788ff2019-12-01 18:22:57 -0800755 return NewTimer(::std::unique_ptr<TimerHandler>(
Brian Silverman148d43d2020-06-07 18:19:22 -0500756 new ShmTimerHandler(this, ::std::move(callback))));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700757}
758
759PhasedLoopHandler *ShmEventLoop::AddPhasedLoop(
760 ::std::function<void(int)> callback,
761 const monotonic_clock::duration interval,
762 const monotonic_clock::duration offset) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700763 CheckCurrentThread();
Brian Silverman148d43d2020-06-07 18:19:22 -0500764 return NewPhasedLoop(::std::unique_ptr<PhasedLoopHandler>(
765 new ShmPhasedLoopHandler(this, ::std::move(callback), interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700766}
767
768void ShmEventLoop::OnRun(::std::function<void()> on_run) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700769 CheckCurrentThread();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700770 on_run_.push_back(::std::move(on_run));
771}
772
Austin Schuh3054f5f2021-07-21 15:38:01 -0700773void ShmEventLoop::CheckCurrentThread() const {
774 if (__builtin_expect(check_mutex_ != nullptr, false)) {
775 CHECK(check_mutex_->is_locked())
776 << ": The configured mutex is not locked while calling a "
777 "ShmEventLoop function";
778 }
779 if (__builtin_expect(!!check_tid_, false)) {
780 CHECK_EQ(syscall(SYS_gettid), *check_tid_)
781 << ": Being called from the wrong thread";
782 }
783}
784
Austin Schuh5ca13112021-02-07 22:06:53 -0800785// This is a bit tricky because watchers can generate new events at any time (as
786// long as it's in the past). We want to check the watchers at least once before
787// declaring there are no events to handle, and we want to check them again if
788// event processing takes long enough that we find an event after that point in
789// time to handle.
Austin Schuh7d87b672019-12-01 20:23:49 -0800790void ShmEventLoop::HandleEvent() {
Austin Schuh5ca13112021-02-07 22:06:53 -0800791 // Time through which we've checked for new events in watchers.
792 monotonic_clock::time_point checked_until = monotonic_clock::min_time;
793 if (!signalfd_) {
794 // Nothing to check, so we can bail out immediately once we're out of
795 // events.
796 CHECK(watchers_.empty());
797 checked_until = monotonic_clock::max_time;
Austin Schuh7d87b672019-12-01 20:23:49 -0800798 }
799
Austin Schuh5ca13112021-02-07 22:06:53 -0800800 // Loop until we run out of events to check.
Austin Schuh39788ff2019-12-01 18:22:57 -0800801 while (true) {
Austin Schuh5ca13112021-02-07 22:06:53 -0800802 // Time of the next event we know about. If this is before checked_until, we
803 // know there aren't any new events before the next one that we already know
804 // about, so no need to check the watchers.
805 monotonic_clock::time_point next_time = monotonic_clock::max_time;
806
807 if (EventCount() == 0) {
808 if (checked_until != monotonic_clock::min_time) {
809 // No events, and we've already checked the watchers at least once, so
810 // we're all done.
811 //
812 // There's a small chance that a watcher has gotten another event in
813 // between checked_until and now. If so, then the signalfd will be
814 // triggered now and we'll re-enter HandleEvent immediately. This is
815 // unlikely though, so we don't want to spend time checking all the
816 // watchers unnecessarily.
817 break;
818 }
819 } else {
820 next_time = PeekEvent()->event_time();
821 }
Austin Schuh00cad2e2022-12-02 20:11:04 -0800822 monotonic_clock::time_point now;
823 bool new_data = false;
Austin Schuh5ca13112021-02-07 22:06:53 -0800824
825 if (next_time > checked_until) {
826 // Read all of the signals, because there's no point in waking up again
827 // immediately to handle each one if we've fallen behind.
828 //
829 // This is safe before checking for new data on the watchers. If a signal
830 // is cleared here, the corresponding CheckForNewData() call below will
831 // pick it up.
832 while (true) {
833 const signalfd_siginfo result = signalfd_->Read();
834 if (result.ssi_signo == 0) {
835 break;
836 }
837 CHECK_EQ(result.ssi_signo, ipc_lib::kWakeupSignal);
838 }
Austin Schuh00cad2e2022-12-02 20:11:04 -0800839 // This is the last time we can guarantee that if a message is published
840 // before, we will notice it.
841 now = monotonic_clock::now();
Austin Schuh5ca13112021-02-07 22:06:53 -0800842
843 // Check all the watchers for new events.
844 for (std::unique_ptr<WatcherState> &base_watcher : watchers_) {
845 ShmWatcherState *const watcher =
846 reinterpret_cast<ShmWatcherState *>(base_watcher.get());
847
Austin Schuh00cad2e2022-12-02 20:11:04 -0800848 // Track if we got a message.
849 if (watcher->CheckForNewData()) {
850 new_data = true;
851 }
Austin Schuh5ca13112021-02-07 22:06:53 -0800852 }
853 if (EventCount() == 0) {
854 // Still no events, all done now.
855 break;
856 }
857
858 checked_until = now;
859 // Check for any new events we found.
860 next_time = PeekEvent()->event_time();
Austin Schuh00cad2e2022-12-02 20:11:04 -0800861 } else {
862 now = monotonic_clock::now();
Austin Schuh5ca13112021-02-07 22:06:53 -0800863 }
864
865 if (next_time > now) {
Austin Schuh00cad2e2022-12-02 20:11:04 -0800866 // Ok, we got a message with a timestamp *after* we wrote down time. We
867 // need to process it (otherwise we will go to sleep without processing
868 // it), but we also need to make sure no other messages have come in
869 // before it that we would process out of order. Just go around again to
870 // redo the checks.
871 if (new_data) {
872 continue;
873 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800874 break;
875 }
876
Austin Schuh5ca13112021-02-07 22:06:53 -0800877 EventLoopEvent *const event = PopEvent();
Austin Schuh7d87b672019-12-01 20:23:49 -0800878 event->HandleEvent();
Austin Schuh39788ff2019-12-01 18:22:57 -0800879 }
880}
881
Austin Schuh32fd5a72019-12-01 22:20:26 -0800882// RAII class to mask signals.
883class ScopedSignalMask {
884 public:
885 ScopedSignalMask(std::initializer_list<int> signals) {
886 sigset_t sigset;
887 PCHECK(sigemptyset(&sigset) == 0);
888 for (int signal : signals) {
889 PCHECK(sigaddset(&sigset, signal) == 0);
890 }
891
892 PCHECK(sigprocmask(SIG_BLOCK, &sigset, &old_) == 0);
893 }
894
895 ~ScopedSignalMask() { PCHECK(sigprocmask(SIG_SETMASK, &old_, nullptr) == 0); }
896
897 private:
898 sigset_t old_;
899};
900
901// Class to manage the static state associated with killing multiple event
902// loops.
903class SignalHandler {
904 public:
905 // Gets the singleton.
906 static SignalHandler *global() {
907 static SignalHandler loop;
908 return &loop;
909 }
910
911 // Handles the signal with the singleton.
912 static void HandleSignal(int) { global()->DoHandleSignal(); }
913
914 // Registers an event loop to receive Exit() calls.
915 void Register(ShmEventLoop *event_loop) {
916 // Block signals while we have the mutex so we never race with the signal
917 // handler.
918 ScopedSignalMask mask({SIGINT, SIGHUP, SIGTERM});
919 std::unique_lock<stl_mutex> locker(mutex_);
920 if (event_loops_.size() == 0) {
921 // The first caller registers the signal handler.
922 struct sigaction new_action;
923 sigemptyset(&new_action.sa_mask);
924 // This makes it so that 2 control c's to a stuck process will kill it by
925 // restoring the original signal handler.
926 new_action.sa_flags = SA_RESETHAND;
927 new_action.sa_handler = &HandleSignal;
928
929 PCHECK(sigaction(SIGINT, &new_action, &old_action_int_) == 0);
930 PCHECK(sigaction(SIGHUP, &new_action, &old_action_hup_) == 0);
931 PCHECK(sigaction(SIGTERM, &new_action, &old_action_term_) == 0);
932 }
933
934 event_loops_.push_back(event_loop);
935 }
936
937 // Unregisters an event loop to receive Exit() calls.
938 void Unregister(ShmEventLoop *event_loop) {
939 // Block signals while we have the mutex so we never race with the signal
940 // handler.
941 ScopedSignalMask mask({SIGINT, SIGHUP, SIGTERM});
942 std::unique_lock<stl_mutex> locker(mutex_);
943
Brian Silverman5120afb2020-01-31 17:44:35 -0800944 event_loops_.erase(
945 std::find(event_loops_.begin(), event_loops_.end(), event_loop));
Austin Schuh32fd5a72019-12-01 22:20:26 -0800946
947 if (event_loops_.size() == 0u) {
948 // The last caller restores the original signal handlers.
949 PCHECK(sigaction(SIGINT, &old_action_int_, nullptr) == 0);
950 PCHECK(sigaction(SIGHUP, &old_action_hup_, nullptr) == 0);
951 PCHECK(sigaction(SIGTERM, &old_action_term_, nullptr) == 0);
952 }
953 }
954
955 private:
956 void DoHandleSignal() {
957 // We block signals while grabbing the lock, so there should never be a
958 // race. Confirm that this is true using trylock.
959 CHECK(mutex_.try_lock()) << ": sigprocmask failed to block signals while "
960 "modifing the event loop list.";
961 for (ShmEventLoop *event_loop : event_loops_) {
962 event_loop->Exit();
963 }
964 mutex_.unlock();
965 }
966
967 // Mutex to protect all state.
968 stl_mutex mutex_;
969 std::vector<ShmEventLoop *> event_loops_;
970 struct sigaction old_action_int_;
971 struct sigaction old_action_hup_;
972 struct sigaction old_action_term_;
973};
974
Alex Perrycb7da4b2019-08-28 19:35:56 -0700975void ShmEventLoop::Run() {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700976 CheckCurrentThread();
Austin Schuh32fd5a72019-12-01 22:20:26 -0800977 SignalHandler::global()->Register(this);
Austin Schuh39788ff2019-12-01 18:22:57 -0800978
Alex Perrycb7da4b2019-08-28 19:35:56 -0700979 if (watchers_.size() > 0) {
Austin Schuh5ca13112021-02-07 22:06:53 -0800980 signalfd_.reset(new ipc_lib::SignalFd({ipc_lib::kWakeupSignal}));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700981
Austin Schuh5ca13112021-02-07 22:06:53 -0800982 epoll_.OnReadable(signalfd_->fd(), [this]() { HandleEvent(); });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700983 }
984
Austin Schuh39788ff2019-12-01 18:22:57 -0800985 MaybeScheduleTimingReports();
986
Austin Schuh7d87b672019-12-01 20:23:49 -0800987 ReserveEvents();
988
Tyler Chatow67ddb032020-01-12 14:30:04 -0800989 {
Austin Schuha0c41ba2020-09-10 22:59:14 -0700990 logging::ScopedLogRestorer prev_logger;
Tyler Chatow67ddb032020-01-12 14:30:04 -0800991 AosLogToFbs aos_logger;
992 if (!skip_logger_) {
Austin Schuhad9e5eb2021-11-19 20:33:55 -0800993 aos_logger.Initialize(&name_, MakeSender<logging::LogMessageFbs>("/aos"));
Austin Schuha0c41ba2020-09-10 22:59:14 -0700994 prev_logger.Swap(aos_logger.implementation());
Tyler Chatow67ddb032020-01-12 14:30:04 -0800995 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700996
Tyler Chatow67ddb032020-01-12 14:30:04 -0800997 aos::SetCurrentThreadName(name_.substr(0, 16));
Brian Silverman6a54ff32020-04-28 16:41:39 -0700998 const cpu_set_t default_affinity = DefaultAffinity();
999 if (!CPU_EQUAL(&affinity_, &default_affinity)) {
1000 ::aos::SetCurrentThreadAffinity(affinity_);
1001 }
Tyler Chatow67ddb032020-01-12 14:30:04 -08001002 // Now, all the callbacks are setup. Lock everything into memory and go RT.
1003 if (priority_ != 0) {
1004 ::aos::InitRT();
1005
1006 LOG(INFO) << "Setting priority to " << priority_;
1007 ::aos::SetCurrentThreadRealtimePriority(priority_);
1008 }
1009
1010 set_is_running(true);
1011
1012 // Now that we are realtime (but before the OnRun handlers run), snap the
1013 // queue index.
1014 for (::std::unique_ptr<WatcherState> &watcher : watchers_) {
1015 watcher->Startup(this);
1016 }
1017
1018 // Now that we are RT, run all the OnRun handlers.
Austin Schuha9012be2021-07-21 15:19:11 -07001019 SetTimerContext(monotonic_clock::now());
Tyler Chatow67ddb032020-01-12 14:30:04 -08001020 for (const auto &run : on_run_) {
1021 run();
1022 }
1023
1024 // And start our main event loop which runs all the timers and handles Quit.
1025 epoll_.Run();
1026
1027 // Once epoll exits, there is no useful nonrt work left to do.
1028 set_is_running(false);
1029
1030 // Nothing time or synchronization critical needs to happen after this
1031 // point. Drop RT priority.
1032 ::aos::UnsetCurrentThreadRealtimePriority();
Alex Perrycb7da4b2019-08-28 19:35:56 -07001033 }
1034
Austin Schuh39788ff2019-12-01 18:22:57 -08001035 for (::std::unique_ptr<WatcherState> &base_watcher : watchers_) {
Brian Silverman148d43d2020-06-07 18:19:22 -05001036 ShmWatcherState *watcher =
1037 reinterpret_cast<ShmWatcherState *>(base_watcher.get());
Alex Perrycb7da4b2019-08-28 19:35:56 -07001038 watcher->UnregisterWakeup();
1039 }
1040
1041 if (watchers_.size() > 0) {
Austin Schuh5ca13112021-02-07 22:06:53 -08001042 epoll_.DeleteFd(signalfd_->fd());
1043 signalfd_.reset();
Alex Perrycb7da4b2019-08-28 19:35:56 -07001044 }
Austin Schuh32fd5a72019-12-01 22:20:26 -08001045
1046 SignalHandler::global()->Unregister(this);
Austin Schuhe84c3ed2019-12-14 15:29:48 -08001047
1048 // Trigger any remaining senders or fetchers to be cleared before destroying
1049 // the event loop so the book keeping matches. Do this in the thread that
1050 // created the timing reporter.
1051 timing_report_sender_.reset();
Austin Schuh0debde12022-08-17 16:25:17 -07001052 ClearContext();
Alex Perrycb7da4b2019-08-28 19:35:56 -07001053}
1054
1055void ShmEventLoop::Exit() { epoll_.Quit(); }
1056
Brian Silvermane1fe2512022-08-14 23:18:50 -07001057std::unique_ptr<ExitHandle> ShmEventLoop::MakeExitHandle() {
1058 return std::make_unique<ShmExitHandle>(this);
1059}
1060
Alex Perrycb7da4b2019-08-28 19:35:56 -07001061ShmEventLoop::~ShmEventLoop() {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001062 CheckCurrentThread();
Austin Schuh39788ff2019-12-01 18:22:57 -08001063 // Force everything with a registered fd with epoll to be destroyed now.
1064 timers_.clear();
1065 phased_loops_.clear();
1066 watchers_.clear();
1067
Alex Perrycb7da4b2019-08-28 19:35:56 -07001068 CHECK(!is_running()) << ": ShmEventLoop destroyed while running";
Brian Silvermane1fe2512022-08-14 23:18:50 -07001069 CHECK_EQ(0, exit_handle_count_)
1070 << ": All ExitHandles must be destroyed before the ShmEventLoop";
Alex Perrycb7da4b2019-08-28 19:35:56 -07001071}
1072
Alex Perrycb7da4b2019-08-28 19:35:56 -07001073void ShmEventLoop::SetRuntimeRealtimePriority(int priority) {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001074 CheckCurrentThread();
Alex Perrycb7da4b2019-08-28 19:35:56 -07001075 if (is_running()) {
1076 LOG(FATAL) << "Cannot set realtime priority while running.";
1077 }
1078 priority_ = priority;
1079}
1080
Brian Silverman6a54ff32020-04-28 16:41:39 -07001081void ShmEventLoop::SetRuntimeAffinity(const cpu_set_t &cpuset) {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001082 CheckCurrentThread();
Brian Silverman6a54ff32020-04-28 16:41:39 -07001083 if (is_running()) {
1084 LOG(FATAL) << "Cannot set affinity while running.";
1085 }
1086 affinity_ = cpuset;
1087}
1088
James Kuszmaul57c2baa2020-01-19 14:52:52 -08001089void ShmEventLoop::set_name(const std::string_view name) {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001090 CheckCurrentThread();
James Kuszmaul57c2baa2020-01-19 14:52:52 -08001091 name_ = std::string(name);
1092 UpdateTimingReport();
1093}
1094
Brian Silvermana5450a92020-08-12 19:59:57 -07001095absl::Span<const char> ShmEventLoop::GetWatcherSharedMemory(
1096 const Channel *channel) {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001097 CheckCurrentThread();
Brian Silverman148d43d2020-06-07 18:19:22 -05001098 ShmWatcherState *const watcher_state =
1099 static_cast<ShmWatcherState *>(GetWatcherState(channel));
Brian Silverman5120afb2020-01-31 17:44:35 -08001100 return watcher_state->GetSharedMemory();
1101}
1102
Brian Silverman4f4e0612020-08-12 19:54:41 -07001103int ShmEventLoop::NumberBuffers(const Channel *channel) {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001104 CheckCurrentThread();
Austin Schuh4d275fc2022-09-16 15:42:45 -07001105 return ipc_lib::MakeQueueConfiguration(configuration(), channel)
1106 .num_messages();
Brian Silverman4f4e0612020-08-12 19:54:41 -07001107}
1108
Brian Silverman5120afb2020-01-31 17:44:35 -08001109absl::Span<char> ShmEventLoop::GetShmSenderSharedMemory(
1110 const aos::RawSender *sender) const {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001111 CheckCurrentThread();
Brian Silverman148d43d2020-06-07 18:19:22 -05001112 return static_cast<const ShmSender *>(sender)->GetSharedMemory();
Brian Silverman5120afb2020-01-31 17:44:35 -08001113}
1114
Brian Silvermana5450a92020-08-12 19:59:57 -07001115absl::Span<const char> ShmEventLoop::GetShmFetcherPrivateMemory(
Brian Silverman6d2b3592020-06-18 14:40:15 -07001116 const aos::RawFetcher *fetcher) const {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001117 CheckCurrentThread();
Brian Silverman6d2b3592020-06-18 14:40:15 -07001118 return static_cast<const ShmFetcher *>(fetcher)->GetPrivateMemory();
1119}
1120
Austin Schuh3054f5f2021-07-21 15:38:01 -07001121pid_t ShmEventLoop::GetTid() {
1122 CheckCurrentThread();
1123 return syscall(SYS_gettid);
1124}
Austin Schuh39788ff2019-12-01 18:22:57 -08001125
Alex Perrycb7da4b2019-08-28 19:35:56 -07001126} // namespace aos