blob: 56d23575a0f51f54f2651ee4e150840eec7adea8 [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();
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700602 disabled_ = true;
Austin Schuhcde39fd2020-02-22 20:58:24 -0800603 } else {
604 // Compute how many cycles have elapsed and schedule the next iteration
605 // for the next iteration in the future.
606 const int elapsed_cycles =
607 std::max<int>(0, (monotonic_now - base_ + repeat_offset_ -
608 std::chrono::nanoseconds(1)) /
609 repeat_offset_);
610 base_ += repeat_offset_ * elapsed_cycles;
Austin Schuh7d87b672019-12-01 20:23:49 -0800611
Austin Schuhcde39fd2020-02-22 20:58:24 -0800612 // Update the heap and schedule the timerfd wakeup.
Austin Schuh7d87b672019-12-01 20:23:49 -0800613 event_.set_event_time(base_);
614 shm_event_loop_->AddEvent(&event_);
Austin Schuh4d275fc2022-09-16 15:42:45 -0700615 timerfd_.SetTime(base_, std::chrono::seconds(0));
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700616 disabled_ = false;
Austin Schuh7d87b672019-12-01 20:23:49 -0800617 }
618 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700619
620 void Setup(monotonic_clock::time_point base,
621 monotonic_clock::duration repeat_offset) override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700622 shm_event_loop_->CheckCurrentThread();
Austin Schuh7d87b672019-12-01 20:23:49 -0800623 if (event_.valid()) {
624 shm_event_loop_->RemoveEvent(&event_);
625 }
626
Alex Perrycb7da4b2019-08-28 19:35:56 -0700627 timerfd_.SetTime(base, repeat_offset);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800628 base_ = base;
629 repeat_offset_ = repeat_offset;
Austin Schuh7d87b672019-12-01 20:23:49 -0800630 event_.set_event_time(base_);
631 shm_event_loop_->AddEvent(&event_);
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700632 disabled_ = false;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700633 }
634
Austin Schuh7d87b672019-12-01 20:23:49 -0800635 void Disable() override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700636 shm_event_loop_->CheckCurrentThread();
Austin Schuh7d87b672019-12-01 20:23:49 -0800637 shm_event_loop_->RemoveEvent(&event_);
638 timerfd_.Disable();
Brian Silvermanaf9a4d82020-10-06 15:10:58 -0700639 disabled_ = true;
Austin Schuh7d87b672019-12-01 20:23:49 -0800640 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700641
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700642 bool IsDisabled() override { return disabled_; }
643
Alex Perrycb7da4b2019-08-28 19:35:56 -0700644 private:
645 ShmEventLoop *shm_event_loop_;
Brian Silverman148d43d2020-06-07 18:19:22 -0500646 EventHandler<ShmTimerHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700647
Brian Silverman148d43d2020-06-07 18:19:22 -0500648 internal::TimerFd timerfd_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700649
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800650 monotonic_clock::time_point base_;
651 monotonic_clock::duration repeat_offset_;
Brian Silvermanaf9a4d82020-10-06 15:10:58 -0700652
653 // Used to track if Disable() was called during the callback, so we know not
654 // to reschedule.
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700655 bool disabled_ = true;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700656};
657
658// Adapter class to the timerfd and PhasedLoop.
Brian Silverman148d43d2020-06-07 18:19:22 -0500659class ShmPhasedLoopHandler final : public PhasedLoopHandler {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700660 public:
Brian Silverman148d43d2020-06-07 18:19:22 -0500661 ShmPhasedLoopHandler(ShmEventLoop *shm_event_loop,
662 ::std::function<void(int)> fn,
663 const monotonic_clock::duration interval,
664 const monotonic_clock::duration offset)
665 : PhasedLoopHandler(shm_event_loop, std::move(fn), interval, offset),
Austin Schuh7d87b672019-12-01 20:23:49 -0800666 shm_event_loop_(shm_event_loop),
667 event_(this) {
668 shm_event_loop_->epoll_.OnReadable(
669 timerfd_.fd(), [this]() { shm_event_loop_->HandleEvent(); });
670 }
671
672 void HandleEvent() {
673 // The return value for read is the number of cycles that have elapsed.
674 // Because we check to see when this event *should* have happened, there are
675 // cases where Read() will return 0, when 1 cycle has actually happened.
676 // This occurs when the timer interrupt hasn't triggered yet. Therefore,
677 // ignore it. Call handles rescheduling and calculating elapsed cycles
678 // without any extra help.
679 timerfd_.Read();
680 event_.Invalidate();
681
682 Call(monotonic_clock::now, [this](monotonic_clock::time_point sleep_time) {
683 Schedule(sleep_time);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700684 });
685 }
686
Brian Silverman148d43d2020-06-07 18:19:22 -0500687 ~ShmPhasedLoopHandler() override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700688 shm_event_loop_->CheckCurrentThread();
Austin Schuh39788ff2019-12-01 18:22:57 -0800689 shm_event_loop_->epoll_.DeleteFd(timerfd_.fd());
Austin Schuh7d87b672019-12-01 20:23:49 -0800690 shm_event_loop_->RemoveEvent(&event_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700691 }
692
693 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800694 // Reschedules the timer.
Austin Schuh39788ff2019-12-01 18:22:57 -0800695 void Schedule(monotonic_clock::time_point sleep_time) override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700696 shm_event_loop_->CheckCurrentThread();
Austin Schuh7d87b672019-12-01 20:23:49 -0800697 if (event_.valid()) {
698 shm_event_loop_->RemoveEvent(&event_);
699 }
700
Austin Schuh39788ff2019-12-01 18:22:57 -0800701 timerfd_.SetTime(sleep_time, ::aos::monotonic_clock::zero());
Austin Schuh7d87b672019-12-01 20:23:49 -0800702 event_.set_event_time(sleep_time);
703 shm_event_loop_->AddEvent(&event_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700704 }
705
706 ShmEventLoop *shm_event_loop_;
Brian Silverman148d43d2020-06-07 18:19:22 -0500707 EventHandler<ShmPhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700708
Brian Silverman148d43d2020-06-07 18:19:22 -0500709 internal::TimerFd timerfd_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700710};
Brian Silverman148d43d2020-06-07 18:19:22 -0500711
712} // namespace shm_event_loop_internal
Alex Perrycb7da4b2019-08-28 19:35:56 -0700713
714::std::unique_ptr<RawFetcher> ShmEventLoop::MakeRawFetcher(
715 const Channel *channel) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700716 CheckCurrentThread();
Austin Schuhca4828c2019-12-28 14:21:35 -0800717 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
718 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
719 << "\", \"type\": \"" << channel->type()->string_view()
720 << "\" } is not able to be fetched on this node. Check your "
721 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800722 }
723
Austin Schuhef323c02020-09-01 14:55:28 -0700724 return ::std::unique_ptr<RawFetcher>(
725 new ShmFetcher(shm_base_, this, channel));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700726}
727
728::std::unique_ptr<RawSender> ShmEventLoop::MakeRawSender(
729 const Channel *channel) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700730 CheckCurrentThread();
Brian Silverman0fc69932020-01-24 21:54:02 -0800731 TakeSender(channel);
Austin Schuh39788ff2019-12-01 18:22:57 -0800732
Austin Schuhef323c02020-09-01 14:55:28 -0700733 return ::std::unique_ptr<RawSender>(new ShmSender(shm_base_, this, channel));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700734}
735
736void ShmEventLoop::MakeRawWatcher(
737 const Channel *channel,
738 std::function<void(const Context &context, const void *message)> watcher) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700739 CheckCurrentThread();
Brian Silverman0fc69932020-01-24 21:54:02 -0800740 TakeWatcher(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800741
Austin Schuh39788ff2019-12-01 18:22:57 -0800742 NewWatcher(::std::unique_ptr<WatcherState>(
Austin Schuhef323c02020-09-01 14:55:28 -0700743 new ShmWatcherState(shm_base_, this, channel, std::move(watcher), true)));
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800744}
745
746void ShmEventLoop::MakeRawNoArgWatcher(
747 const Channel *channel,
748 std::function<void(const Context &context)> watcher) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700749 CheckCurrentThread();
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800750 TakeWatcher(channel);
751
Brian Silverman148d43d2020-06-07 18:19:22 -0500752 NewWatcher(::std::unique_ptr<WatcherState>(new ShmWatcherState(
Austin Schuhef323c02020-09-01 14:55:28 -0700753 shm_base_, this, channel,
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800754 [watcher](const Context &context, const void *) { watcher(context); },
755 false)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700756}
757
758TimerHandler *ShmEventLoop::AddTimer(::std::function<void()> callback) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700759 CheckCurrentThread();
Austin Schuh39788ff2019-12-01 18:22:57 -0800760 return NewTimer(::std::unique_ptr<TimerHandler>(
Brian Silverman148d43d2020-06-07 18:19:22 -0500761 new ShmTimerHandler(this, ::std::move(callback))));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700762}
763
764PhasedLoopHandler *ShmEventLoop::AddPhasedLoop(
765 ::std::function<void(int)> callback,
766 const monotonic_clock::duration interval,
767 const monotonic_clock::duration offset) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700768 CheckCurrentThread();
Brian Silverman148d43d2020-06-07 18:19:22 -0500769 return NewPhasedLoop(::std::unique_ptr<PhasedLoopHandler>(
770 new ShmPhasedLoopHandler(this, ::std::move(callback), interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700771}
772
773void ShmEventLoop::OnRun(::std::function<void()> on_run) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700774 CheckCurrentThread();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700775 on_run_.push_back(::std::move(on_run));
776}
777
Austin Schuh3054f5f2021-07-21 15:38:01 -0700778void ShmEventLoop::CheckCurrentThread() const {
779 if (__builtin_expect(check_mutex_ != nullptr, false)) {
780 CHECK(check_mutex_->is_locked())
781 << ": The configured mutex is not locked while calling a "
782 "ShmEventLoop function";
783 }
784 if (__builtin_expect(!!check_tid_, false)) {
785 CHECK_EQ(syscall(SYS_gettid), *check_tid_)
786 << ": Being called from the wrong thread";
787 }
788}
789
Austin Schuh5ca13112021-02-07 22:06:53 -0800790// This is a bit tricky because watchers can generate new events at any time (as
791// long as it's in the past). We want to check the watchers at least once before
792// declaring there are no events to handle, and we want to check them again if
793// event processing takes long enough that we find an event after that point in
794// time to handle.
Austin Schuh7d87b672019-12-01 20:23:49 -0800795void ShmEventLoop::HandleEvent() {
Austin Schuh5ca13112021-02-07 22:06:53 -0800796 // Time through which we've checked for new events in watchers.
797 monotonic_clock::time_point checked_until = monotonic_clock::min_time;
798 if (!signalfd_) {
799 // Nothing to check, so we can bail out immediately once we're out of
800 // events.
801 CHECK(watchers_.empty());
802 checked_until = monotonic_clock::max_time;
Austin Schuh7d87b672019-12-01 20:23:49 -0800803 }
804
Austin Schuh5ca13112021-02-07 22:06:53 -0800805 // Loop until we run out of events to check.
Austin Schuh39788ff2019-12-01 18:22:57 -0800806 while (true) {
Austin Schuh5ca13112021-02-07 22:06:53 -0800807 // Time of the next event we know about. If this is before checked_until, we
808 // know there aren't any new events before the next one that we already know
809 // about, so no need to check the watchers.
810 monotonic_clock::time_point next_time = monotonic_clock::max_time;
811
812 if (EventCount() == 0) {
813 if (checked_until != monotonic_clock::min_time) {
814 // No events, and we've already checked the watchers at least once, so
815 // we're all done.
816 //
817 // There's a small chance that a watcher has gotten another event in
818 // between checked_until and now. If so, then the signalfd will be
819 // triggered now and we'll re-enter HandleEvent immediately. This is
820 // unlikely though, so we don't want to spend time checking all the
821 // watchers unnecessarily.
822 break;
823 }
824 } else {
825 next_time = PeekEvent()->event_time();
826 }
Austin Schuh00cad2e2022-12-02 20:11:04 -0800827 monotonic_clock::time_point now;
828 bool new_data = false;
Austin Schuh5ca13112021-02-07 22:06:53 -0800829
830 if (next_time > checked_until) {
831 // Read all of the signals, because there's no point in waking up again
832 // immediately to handle each one if we've fallen behind.
833 //
834 // This is safe before checking for new data on the watchers. If a signal
835 // is cleared here, the corresponding CheckForNewData() call below will
836 // pick it up.
837 while (true) {
838 const signalfd_siginfo result = signalfd_->Read();
839 if (result.ssi_signo == 0) {
840 break;
841 }
842 CHECK_EQ(result.ssi_signo, ipc_lib::kWakeupSignal);
843 }
Austin Schuh00cad2e2022-12-02 20:11:04 -0800844 // This is the last time we can guarantee that if a message is published
845 // before, we will notice it.
846 now = monotonic_clock::now();
Austin Schuh5ca13112021-02-07 22:06:53 -0800847
848 // Check all the watchers for new events.
849 for (std::unique_ptr<WatcherState> &base_watcher : watchers_) {
850 ShmWatcherState *const watcher =
851 reinterpret_cast<ShmWatcherState *>(base_watcher.get());
852
Austin Schuh00cad2e2022-12-02 20:11:04 -0800853 // Track if we got a message.
854 if (watcher->CheckForNewData()) {
855 new_data = true;
856 }
Austin Schuh5ca13112021-02-07 22:06:53 -0800857 }
858 if (EventCount() == 0) {
859 // Still no events, all done now.
860 break;
861 }
862
863 checked_until = now;
864 // Check for any new events we found.
865 next_time = PeekEvent()->event_time();
Austin Schuh00cad2e2022-12-02 20:11:04 -0800866 } else {
867 now = monotonic_clock::now();
Austin Schuh5ca13112021-02-07 22:06:53 -0800868 }
869
870 if (next_time > now) {
Austin Schuh00cad2e2022-12-02 20:11:04 -0800871 // Ok, we got a message with a timestamp *after* we wrote down time. We
872 // need to process it (otherwise we will go to sleep without processing
873 // it), but we also need to make sure no other messages have come in
874 // before it that we would process out of order. Just go around again to
875 // redo the checks.
876 if (new_data) {
877 continue;
878 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800879 break;
880 }
881
Austin Schuh5ca13112021-02-07 22:06:53 -0800882 EventLoopEvent *const event = PopEvent();
Austin Schuh7d87b672019-12-01 20:23:49 -0800883 event->HandleEvent();
Austin Schuh39788ff2019-12-01 18:22:57 -0800884 }
885}
886
Austin Schuh32fd5a72019-12-01 22:20:26 -0800887// RAII class to mask signals.
888class ScopedSignalMask {
889 public:
890 ScopedSignalMask(std::initializer_list<int> signals) {
891 sigset_t sigset;
892 PCHECK(sigemptyset(&sigset) == 0);
893 for (int signal : signals) {
894 PCHECK(sigaddset(&sigset, signal) == 0);
895 }
896
897 PCHECK(sigprocmask(SIG_BLOCK, &sigset, &old_) == 0);
898 }
899
900 ~ScopedSignalMask() { PCHECK(sigprocmask(SIG_SETMASK, &old_, nullptr) == 0); }
901
902 private:
903 sigset_t old_;
904};
905
906// Class to manage the static state associated with killing multiple event
907// loops.
908class SignalHandler {
909 public:
910 // Gets the singleton.
911 static SignalHandler *global() {
912 static SignalHandler loop;
913 return &loop;
914 }
915
916 // Handles the signal with the singleton.
917 static void HandleSignal(int) { global()->DoHandleSignal(); }
918
919 // Registers an event loop to receive Exit() calls.
920 void Register(ShmEventLoop *event_loop) {
921 // Block signals while we have the mutex so we never race with the signal
922 // handler.
923 ScopedSignalMask mask({SIGINT, SIGHUP, SIGTERM});
924 std::unique_lock<stl_mutex> locker(mutex_);
925 if (event_loops_.size() == 0) {
926 // The first caller registers the signal handler.
927 struct sigaction new_action;
928 sigemptyset(&new_action.sa_mask);
929 // This makes it so that 2 control c's to a stuck process will kill it by
930 // restoring the original signal handler.
931 new_action.sa_flags = SA_RESETHAND;
932 new_action.sa_handler = &HandleSignal;
933
934 PCHECK(sigaction(SIGINT, &new_action, &old_action_int_) == 0);
935 PCHECK(sigaction(SIGHUP, &new_action, &old_action_hup_) == 0);
936 PCHECK(sigaction(SIGTERM, &new_action, &old_action_term_) == 0);
937 }
938
939 event_loops_.push_back(event_loop);
940 }
941
942 // Unregisters an event loop to receive Exit() calls.
943 void Unregister(ShmEventLoop *event_loop) {
944 // Block signals while we have the mutex so we never race with the signal
945 // handler.
946 ScopedSignalMask mask({SIGINT, SIGHUP, SIGTERM});
947 std::unique_lock<stl_mutex> locker(mutex_);
948
Brian Silverman5120afb2020-01-31 17:44:35 -0800949 event_loops_.erase(
950 std::find(event_loops_.begin(), event_loops_.end(), event_loop));
Austin Schuh32fd5a72019-12-01 22:20:26 -0800951
952 if (event_loops_.size() == 0u) {
953 // The last caller restores the original signal handlers.
954 PCHECK(sigaction(SIGINT, &old_action_int_, nullptr) == 0);
955 PCHECK(sigaction(SIGHUP, &old_action_hup_, nullptr) == 0);
956 PCHECK(sigaction(SIGTERM, &old_action_term_, nullptr) == 0);
957 }
958 }
959
960 private:
961 void DoHandleSignal() {
962 // We block signals while grabbing the lock, so there should never be a
963 // race. Confirm that this is true using trylock.
964 CHECK(mutex_.try_lock()) << ": sigprocmask failed to block signals while "
965 "modifing the event loop list.";
966 for (ShmEventLoop *event_loop : event_loops_) {
967 event_loop->Exit();
968 }
969 mutex_.unlock();
970 }
971
972 // Mutex to protect all state.
973 stl_mutex mutex_;
974 std::vector<ShmEventLoop *> event_loops_;
975 struct sigaction old_action_int_;
976 struct sigaction old_action_hup_;
977 struct sigaction old_action_term_;
978};
979
Alex Perrycb7da4b2019-08-28 19:35:56 -0700980void ShmEventLoop::Run() {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700981 CheckCurrentThread();
Austin Schuh32fd5a72019-12-01 22:20:26 -0800982 SignalHandler::global()->Register(this);
Austin Schuh39788ff2019-12-01 18:22:57 -0800983
Alex Perrycb7da4b2019-08-28 19:35:56 -0700984 if (watchers_.size() > 0) {
Austin Schuh5ca13112021-02-07 22:06:53 -0800985 signalfd_.reset(new ipc_lib::SignalFd({ipc_lib::kWakeupSignal}));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700986
Austin Schuh5ca13112021-02-07 22:06:53 -0800987 epoll_.OnReadable(signalfd_->fd(), [this]() { HandleEvent(); });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700988 }
989
Austin Schuh39788ff2019-12-01 18:22:57 -0800990 MaybeScheduleTimingReports();
991
Austin Schuh7d87b672019-12-01 20:23:49 -0800992 ReserveEvents();
993
Tyler Chatow67ddb032020-01-12 14:30:04 -0800994 {
Austin Schuha0c41ba2020-09-10 22:59:14 -0700995 logging::ScopedLogRestorer prev_logger;
Tyler Chatow67ddb032020-01-12 14:30:04 -0800996 AosLogToFbs aos_logger;
997 if (!skip_logger_) {
Austin Schuhad9e5eb2021-11-19 20:33:55 -0800998 aos_logger.Initialize(&name_, MakeSender<logging::LogMessageFbs>("/aos"));
Austin Schuha0c41ba2020-09-10 22:59:14 -0700999 prev_logger.Swap(aos_logger.implementation());
Tyler Chatow67ddb032020-01-12 14:30:04 -08001000 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001001
Tyler Chatow67ddb032020-01-12 14:30:04 -08001002 aos::SetCurrentThreadName(name_.substr(0, 16));
Brian Silverman6a54ff32020-04-28 16:41:39 -07001003 const cpu_set_t default_affinity = DefaultAffinity();
1004 if (!CPU_EQUAL(&affinity_, &default_affinity)) {
1005 ::aos::SetCurrentThreadAffinity(affinity_);
1006 }
Tyler Chatow67ddb032020-01-12 14:30:04 -08001007 // Now, all the callbacks are setup. Lock everything into memory and go RT.
1008 if (priority_ != 0) {
1009 ::aos::InitRT();
1010
1011 LOG(INFO) << "Setting priority to " << priority_;
1012 ::aos::SetCurrentThreadRealtimePriority(priority_);
1013 }
1014
1015 set_is_running(true);
1016
1017 // Now that we are realtime (but before the OnRun handlers run), snap the
1018 // queue index.
1019 for (::std::unique_ptr<WatcherState> &watcher : watchers_) {
1020 watcher->Startup(this);
1021 }
1022
1023 // Now that we are RT, run all the OnRun handlers.
Austin Schuha9012be2021-07-21 15:19:11 -07001024 SetTimerContext(monotonic_clock::now());
Tyler Chatow67ddb032020-01-12 14:30:04 -08001025 for (const auto &run : on_run_) {
1026 run();
1027 }
1028
1029 // And start our main event loop which runs all the timers and handles Quit.
1030 epoll_.Run();
1031
1032 // Once epoll exits, there is no useful nonrt work left to do.
1033 set_is_running(false);
1034
1035 // Nothing time or synchronization critical needs to happen after this
1036 // point. Drop RT priority.
1037 ::aos::UnsetCurrentThreadRealtimePriority();
Alex Perrycb7da4b2019-08-28 19:35:56 -07001038 }
1039
Austin Schuh39788ff2019-12-01 18:22:57 -08001040 for (::std::unique_ptr<WatcherState> &base_watcher : watchers_) {
Brian Silverman148d43d2020-06-07 18:19:22 -05001041 ShmWatcherState *watcher =
1042 reinterpret_cast<ShmWatcherState *>(base_watcher.get());
Alex Perrycb7da4b2019-08-28 19:35:56 -07001043 watcher->UnregisterWakeup();
1044 }
1045
1046 if (watchers_.size() > 0) {
Austin Schuh5ca13112021-02-07 22:06:53 -08001047 epoll_.DeleteFd(signalfd_->fd());
1048 signalfd_.reset();
Alex Perrycb7da4b2019-08-28 19:35:56 -07001049 }
Austin Schuh32fd5a72019-12-01 22:20:26 -08001050
1051 SignalHandler::global()->Unregister(this);
Austin Schuhe84c3ed2019-12-14 15:29:48 -08001052
1053 // Trigger any remaining senders or fetchers to be cleared before destroying
1054 // the event loop so the book keeping matches. Do this in the thread that
1055 // created the timing reporter.
1056 timing_report_sender_.reset();
Austin Schuh0debde12022-08-17 16:25:17 -07001057 ClearContext();
Alex Perrycb7da4b2019-08-28 19:35:56 -07001058}
1059
1060void ShmEventLoop::Exit() { epoll_.Quit(); }
1061
Brian Silvermane1fe2512022-08-14 23:18:50 -07001062std::unique_ptr<ExitHandle> ShmEventLoop::MakeExitHandle() {
1063 return std::make_unique<ShmExitHandle>(this);
1064}
1065
Alex Perrycb7da4b2019-08-28 19:35:56 -07001066ShmEventLoop::~ShmEventLoop() {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001067 CheckCurrentThread();
Austin Schuh39788ff2019-12-01 18:22:57 -08001068 // Force everything with a registered fd with epoll to be destroyed now.
1069 timers_.clear();
1070 phased_loops_.clear();
1071 watchers_.clear();
1072
Alex Perrycb7da4b2019-08-28 19:35:56 -07001073 CHECK(!is_running()) << ": ShmEventLoop destroyed while running";
Brian Silvermane1fe2512022-08-14 23:18:50 -07001074 CHECK_EQ(0, exit_handle_count_)
1075 << ": All ExitHandles must be destroyed before the ShmEventLoop";
Alex Perrycb7da4b2019-08-28 19:35:56 -07001076}
1077
Alex Perrycb7da4b2019-08-28 19:35:56 -07001078void ShmEventLoop::SetRuntimeRealtimePriority(int priority) {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001079 CheckCurrentThread();
Alex Perrycb7da4b2019-08-28 19:35:56 -07001080 if (is_running()) {
1081 LOG(FATAL) << "Cannot set realtime priority while running.";
1082 }
1083 priority_ = priority;
1084}
1085
Brian Silverman6a54ff32020-04-28 16:41:39 -07001086void ShmEventLoop::SetRuntimeAffinity(const cpu_set_t &cpuset) {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001087 CheckCurrentThread();
Brian Silverman6a54ff32020-04-28 16:41:39 -07001088 if (is_running()) {
1089 LOG(FATAL) << "Cannot set affinity while running.";
1090 }
1091 affinity_ = cpuset;
1092}
1093
James Kuszmaul57c2baa2020-01-19 14:52:52 -08001094void ShmEventLoop::set_name(const std::string_view name) {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001095 CheckCurrentThread();
James Kuszmaul57c2baa2020-01-19 14:52:52 -08001096 name_ = std::string(name);
1097 UpdateTimingReport();
1098}
1099
Brian Silvermana5450a92020-08-12 19:59:57 -07001100absl::Span<const char> ShmEventLoop::GetWatcherSharedMemory(
1101 const Channel *channel) {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001102 CheckCurrentThread();
Brian Silverman148d43d2020-06-07 18:19:22 -05001103 ShmWatcherState *const watcher_state =
1104 static_cast<ShmWatcherState *>(GetWatcherState(channel));
Brian Silverman5120afb2020-01-31 17:44:35 -08001105 return watcher_state->GetSharedMemory();
1106}
1107
Brian Silverman4f4e0612020-08-12 19:54:41 -07001108int ShmEventLoop::NumberBuffers(const Channel *channel) {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001109 CheckCurrentThread();
Austin Schuh4d275fc2022-09-16 15:42:45 -07001110 return ipc_lib::MakeQueueConfiguration(configuration(), channel)
1111 .num_messages();
Brian Silverman4f4e0612020-08-12 19:54:41 -07001112}
1113
Brian Silverman5120afb2020-01-31 17:44:35 -08001114absl::Span<char> ShmEventLoop::GetShmSenderSharedMemory(
1115 const aos::RawSender *sender) const {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001116 CheckCurrentThread();
Brian Silverman148d43d2020-06-07 18:19:22 -05001117 return static_cast<const ShmSender *>(sender)->GetSharedMemory();
Brian Silverman5120afb2020-01-31 17:44:35 -08001118}
1119
Brian Silvermana5450a92020-08-12 19:59:57 -07001120absl::Span<const char> ShmEventLoop::GetShmFetcherPrivateMemory(
Brian Silverman6d2b3592020-06-18 14:40:15 -07001121 const aos::RawFetcher *fetcher) const {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001122 CheckCurrentThread();
Brian Silverman6d2b3592020-06-18 14:40:15 -07001123 return static_cast<const ShmFetcher *>(fetcher)->GetPrivateMemory();
1124}
1125
Austin Schuh3054f5f2021-07-21 15:38:01 -07001126pid_t ShmEventLoop::GetTid() {
1127 CheckCurrentThread();
1128 return syscall(SYS_gettid);
1129}
Austin Schuh39788ff2019-12-01 18:22:57 -08001130
Alex Perrycb7da4b2019-08-28 19:35:56 -07001131} // namespace aos