blob: 09cd48872b42e66f6b476d55c2f3332b9b591d6f [file] [log] [blame]
Alex Perrycb7da4b2019-08-28 19:35:56 -07001#include "aos/events/shm_event_loop.h"
2
Alex Perrycb7da4b2019-08-28 19:35:56 -07003#include <sys/stat.h>
Austin Schuh39788ff2019-12-01 18:22:57 -08004#include <sys/syscall.h>
Alex Perrycb7da4b2019-08-28 19:35:56 -07005#include <sys/types.h>
Tyler Chatow67ddb032020-01-12 14:30:04 -08006
Alex Perrycb7da4b2019-08-28 19:35:56 -07007#include <algorithm>
8#include <atomic>
9#include <chrono>
Austin Schuh39788ff2019-12-01 18:22:57 -080010#include <iterator>
Alex Perrycb7da4b2019-08-28 19:35:56 -070011#include <stdexcept>
12
Philipp Schrader790cb542023-07-05 21:06:52 -070013#include "glog/logging.h"
14
Tyler Chatow67ddb032020-01-12 14:30:04 -080015#include "aos/events/aos_logging.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070016#include "aos/events/epoll.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080017#include "aos/events/event_loop_generated.h"
18#include "aos/events/timing_statistics.h"
Austin Schuh094d09b2020-11-20 23:26:52 -080019#include "aos/init.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070020#include "aos/ipc_lib/lockless_queue.h"
Austin Schuh4d275fc2022-09-16 15:42:45 -070021#include "aos/ipc_lib/memory_mapped_queue.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070022#include "aos/realtime.h"
Austin Schuh32fd5a72019-12-01 22:20:26 -080023#include "aos/stl_mutex/stl_mutex.h"
Austin Schuhfccb2d02020-01-26 16:11:19 -080024#include "aos/util/file.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070025#include "aos/util/phased_loop.h"
26
Austin Schuhe84c3ed2019-12-14 15:29:48 -080027namespace {
28
29// Returns the portion of the path after the last /. This very much assumes
30// that the application name is null terminated.
31const char *Filename(const char *path) {
32 const std::string_view path_string_view = path;
33 auto last_slash_pos = path_string_view.find_last_of("/");
34
35 return last_slash_pos == std::string_view::npos ? path
36 : path + last_slash_pos + 1;
37}
38
39} // namespace
40
Alex Perrycb7da4b2019-08-28 19:35:56 -070041DEFINE_string(shm_base, "/dev/shm/aos",
42 "Directory to place queue backing mmaped files in.");
43DEFINE_uint32(permissions, 0770,
44 "Permissions to make shared memory files and folders.");
Austin Schuhe84c3ed2019-12-14 15:29:48 -080045DEFINE_string(application_name, Filename(program_invocation_name),
46 "The application name");
Alex Perrycb7da4b2019-08-28 19:35:56 -070047
48namespace aos {
49
Brian Silverman148d43d2020-06-07 18:19:22 -050050using namespace shm_event_loop_internal;
51
Austin Schuhcdab6192019-12-29 17:47:46 -080052void SetShmBase(const std::string_view base) {
Austin Schuhef323c02020-09-01 14:55:28 -070053 FLAGS_shm_base = std::string(base) + "/aos";
Austin Schuhcdab6192019-12-29 17:47:46 -080054}
55
Brian Silverman4f4e0612020-08-12 19:54:41 -070056namespace {
57
Austin Schuh217a9782019-12-21 23:02:50 -080058const Node *MaybeMyNode(const Configuration *configuration) {
59 if (!configuration->has_nodes()) {
60 return nullptr;
61 }
Alex Perrycb7da4b2019-08-28 19:35:56 -070062
Austin Schuh217a9782019-12-21 23:02:50 -080063 return configuration::GetMyNode(configuration);
64}
Alex Perrycb7da4b2019-08-28 19:35:56 -070065
Austin Schuh39788ff2019-12-01 18:22:57 -080066} // namespace
67
Austin Schuh217a9782019-12-21 23:02:50 -080068ShmEventLoop::ShmEventLoop(const Configuration *configuration)
Austin Schuh83c7f702021-01-19 22:36:29 -080069 : EventLoop(configuration),
70 boot_uuid_(UUID::BootUUID()),
Austin Schuhef323c02020-09-01 14:55:28 -070071 shm_base_(FLAGS_shm_base),
Austin Schuhe84c3ed2019-12-14 15:29:48 -080072 name_(FLAGS_application_name),
Austin Schuh15649d62019-12-28 16:36:38 -080073 node_(MaybeMyNode(configuration)) {
Austin Schuh094d09b2020-11-20 23:26:52 -080074 CHECK(IsInitialized()) << ": Need to initialize AOS first.";
Austin Schuh0debde12022-08-17 16:25:17 -070075 ClearContext();
Austin Schuh15649d62019-12-28 16:36:38 -080076 if (configuration->has_nodes()) {
77 CHECK(node_ != nullptr) << ": Couldn't find node in config.";
78 }
79}
Austin Schuh217a9782019-12-21 23:02:50 -080080
Brian Silverman148d43d2020-06-07 18:19:22 -050081namespace shm_event_loop_internal {
Austin Schuh39788ff2019-12-01 18:22:57 -080082
83class SimpleShmFetcher {
Alex Perrycb7da4b2019-08-28 19:35:56 -070084 public:
Austin Schuhef323c02020-09-01 14:55:28 -070085 explicit SimpleShmFetcher(std::string_view shm_base, ShmEventLoop *event_loop,
86 const Channel *channel)
Austin Schuh432784f2020-06-23 17:27:35 -070087 : event_loop_(event_loop),
88 channel_(channel),
Austin Schuh4d275fc2022-09-16 15:42:45 -070089 lockless_queue_memory_(shm_base, FLAGS_permissions,
90 event_loop->configuration(), channel),
Brian Silvermanfc0d2e82020-08-12 19:58:35 -070091 reader_(lockless_queue_memory_.queue()) {
Alex Perrycb7da4b2019-08-28 19:35:56 -070092 context_.data = nullptr;
93 // Point the queue index at the next index to read starting now. This
94 // makes it such that FetchNext will read the next message sent after
95 // the fetcher is created.
96 PointAtNextQueueIndex();
97 }
98
Austin Schuh39788ff2019-12-01 18:22:57 -080099 ~SimpleShmFetcher() {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700100
Brian Silverman77162972020-08-12 19:52:40 -0700101 // Sets this object to pin or copy data, as configured in the channel.
102 void RetrieveData() {
103 if (channel_->read_method() == ReadMethod::PIN) {
104 PinDataOnFetch();
105 } else {
106 CopyDataOnFetch();
107 }
108 }
109
Brian Silverman3bca5322020-08-12 19:35:29 -0700110 // Sets this object to copy data out of the shared memory into a private
111 // buffer when fetching.
112 void CopyDataOnFetch() {
Brian Silverman77162972020-08-12 19:52:40 -0700113 CHECK(!pin_data());
Brian Silverman3bca5322020-08-12 19:35:29 -0700114 data_storage_.reset(static_cast<char *>(
115 malloc(channel_->max_size() + kChannelDataAlignment - 1)));
116 }
117
Brian Silverman77162972020-08-12 19:52:40 -0700118 // Sets this object to pin data in shared memory when fetching.
119 void PinDataOnFetch() {
120 CHECK(!copy_data());
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700121 auto maybe_pinner =
122 ipc_lib::LocklessQueuePinner::Make(lockless_queue_memory_.queue());
Brian Silverman77162972020-08-12 19:52:40 -0700123 if (!maybe_pinner) {
124 LOG(FATAL) << "Failed to create reader on "
125 << configuration::CleanedChannelToString(channel_)
126 << ", too many readers.";
127 }
128 pinner_ = std::move(maybe_pinner.value());
129 }
130
Alex Perrycb7da4b2019-08-28 19:35:56 -0700131 // Points the next message to fetch at the queue index which will be
132 // populated next.
133 void PointAtNextQueueIndex() {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700134 actual_queue_index_ = reader_.LatestIndex();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700135 if (!actual_queue_index_.valid()) {
136 // Nothing in the queue. The next element will show up at the 0th
137 // index in the queue.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700138 actual_queue_index_ = ipc_lib::QueueIndex::Zero(
139 LocklessQueueSize(lockless_queue_memory_.memory()));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700140 } else {
141 actual_queue_index_ = actual_queue_index_.Increment();
142 }
143 }
144
Austin Schuh39788ff2019-12-01 18:22:57 -0800145 bool FetchNext() {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700146 const ipc_lib::LocklessQueueReader::Result read_result =
Brian Silverman3bca5322020-08-12 19:35:29 -0700147 DoFetch(actual_queue_index_);
Austin Schuh432784f2020-06-23 17:27:35 -0700148
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700149 return read_result == ipc_lib::LocklessQueueReader::Result::GOOD;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700150 }
151
Austin Schuh39788ff2019-12-01 18:22:57 -0800152 bool Fetch() {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700153 const ipc_lib::QueueIndex queue_index = reader_.LatestIndex();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700154 // actual_queue_index_ is only meaningful if it was set by Fetch or
155 // FetchNext. This happens when valid_data_ has been set. So, only
156 // skip checking if valid_data_ is true.
157 //
158 // Also, if the latest queue index is invalid, we are empty. So there
159 // is nothing to fetch.
Austin Schuh39788ff2019-12-01 18:22:57 -0800160 if ((context_.data != nullptr &&
Alex Perrycb7da4b2019-08-28 19:35:56 -0700161 queue_index == actual_queue_index_.DecrementBy(1u)) ||
162 !queue_index.valid()) {
163 return false;
164 }
165
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700166 const ipc_lib::LocklessQueueReader::Result read_result =
167 DoFetch(queue_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700168
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700169 CHECK(read_result != ipc_lib::LocklessQueueReader::Result::NOTHING_NEW)
Austin Schuhf5652592019-12-29 16:26:15 -0800170 << ": Queue index went backwards. This should never happen. "
171 << configuration::CleanedChannelToString(channel_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700172
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700173 return read_result == ipc_lib::LocklessQueueReader::Result::GOOD;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700174 }
175
Austin Schuh39788ff2019-12-01 18:22:57 -0800176 Context context() const { return context_; }
177
Alex Perrycb7da4b2019-08-28 19:35:56 -0700178 bool RegisterWakeup(int priority) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700179 CHECK(!watcher_);
180 watcher_ = ipc_lib::LocklessQueueWatcher::Make(
181 lockless_queue_memory_.queue(), priority);
182 return static_cast<bool>(watcher_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700183 }
184
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700185 void UnregisterWakeup() {
186 CHECK(watcher_);
187 watcher_ = std::nullopt;
188 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700189
Brian Silvermana5450a92020-08-12 19:59:57 -0700190 absl::Span<char> GetMutableSharedMemory() {
191 return lockless_queue_memory_.GetMutableSharedMemory();
Brian Silverman5120afb2020-01-31 17:44:35 -0800192 }
193
Brian Silvermana5450a92020-08-12 19:59:57 -0700194 absl::Span<const char> GetConstSharedMemory() const {
195 return lockless_queue_memory_.GetConstSharedMemory();
196 }
197
198 absl::Span<const char> GetPrivateMemory() const {
199 if (pin_data()) {
200 return lockless_queue_memory_.GetConstSharedMemory();
201 }
Brian Silverman6d2b3592020-06-18 14:40:15 -0700202 return absl::Span<char>(
203 const_cast<SimpleShmFetcher *>(this)->data_storage_start(),
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700204 LocklessQueueMessageDataSize(lockless_queue_memory_.memory()));
Brian Silverman6d2b3592020-06-18 14:40:15 -0700205 }
206
Alex Perrycb7da4b2019-08-28 19:35:56 -0700207 private:
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700208 ipc_lib::LocklessQueueReader::Result DoFetch(
209 ipc_lib::QueueIndex queue_index) {
Brian Silverman3bca5322020-08-12 19:35:29 -0700210 // TODO(austin): Get behind and make sure it dies.
211 char *copy_buffer = nullptr;
212 if (copy_data()) {
213 copy_buffer = data_storage_start();
214 }
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700215 ipc_lib::LocklessQueueReader::Result read_result = reader_.Read(
Brian Silverman3bca5322020-08-12 19:35:29 -0700216 queue_index.index(), &context_.monotonic_event_time,
217 &context_.realtime_event_time, &context_.monotonic_remote_time,
218 &context_.realtime_remote_time, &context_.remote_queue_index,
Austin Schuha9012be2021-07-21 15:19:11 -0700219 &context_.source_boot_uuid, &context_.size, copy_buffer);
Brian Silverman3bca5322020-08-12 19:35:29 -0700220
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700221 if (read_result == ipc_lib::LocklessQueueReader::Result::GOOD) {
Brian Silverman77162972020-08-12 19:52:40 -0700222 if (pin_data()) {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700223 const int pin_result = pinner_->PinIndex(queue_index.index());
224 CHECK(pin_result >= 0)
Brian Silverman77162972020-08-12 19:52:40 -0700225 << ": Got behind while reading and the last message was modified "
226 "out from under us while we tried to pin it. Don't get so far "
227 "behind on: "
228 << configuration::CleanedChannelToString(channel_);
Brian Silverman4f4e0612020-08-12 19:54:41 -0700229 context_.buffer_index = pin_result;
230 } else {
231 context_.buffer_index = -1;
Brian Silverman77162972020-08-12 19:52:40 -0700232 }
233
Brian Silverman3bca5322020-08-12 19:35:29 -0700234 context_.queue_index = queue_index.index();
235 if (context_.remote_queue_index == 0xffffffffu) {
236 context_.remote_queue_index = context_.queue_index;
237 }
238 if (context_.monotonic_remote_time == aos::monotonic_clock::min_time) {
239 context_.monotonic_remote_time = context_.monotonic_event_time;
240 }
241 if (context_.realtime_remote_time == aos::realtime_clock::min_time) {
242 context_.realtime_remote_time = context_.realtime_event_time;
243 }
244 const char *const data = DataBuffer();
245 if (data) {
246 context_.data =
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700247 data +
248 LocklessQueueMessageDataSize(lockless_queue_memory_.memory()) -
249 context_.size;
Brian Silverman3bca5322020-08-12 19:35:29 -0700250 } else {
251 context_.data = nullptr;
252 }
253 actual_queue_index_ = queue_index.Increment();
254 }
255
256 // Make sure the data wasn't modified while we were reading it. This
257 // can only happen if you are reading the last message *while* it is
258 // being written to, which means you are pretty far behind.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700259 CHECK(read_result != ipc_lib::LocklessQueueReader::Result::OVERWROTE)
Brian Silverman3bca5322020-08-12 19:35:29 -0700260 << ": Got behind while reading and the last message was modified "
261 "out from under us while we were reading it. Don't get so far "
262 "behind on: "
263 << configuration::CleanedChannelToString(channel_);
264
265 // We fell behind between when we read the index and read the value.
266 // This isn't worth recovering from since this means we went to sleep
267 // for a long time in the middle of this function.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700268 if (read_result == ipc_lib::LocklessQueueReader::Result::TOO_OLD) {
Brian Silverman3bca5322020-08-12 19:35:29 -0700269 event_loop_->SendTimingReport();
270 LOG(FATAL) << "The next message is no longer available. "
271 << configuration::CleanedChannelToString(channel_);
272 }
273
274 return read_result;
275 }
276
277 char *data_storage_start() const {
278 CHECK(copy_data());
Brian Silvermana1652f32020-01-29 20:41:44 -0800279 return RoundChannelData(data_storage_.get(), channel_->max_size());
280 }
Brian Silverman3bca5322020-08-12 19:35:29 -0700281
282 // Note that for some modes the return value will change as new messages are
283 // read.
284 const char *DataBuffer() const {
285 if (copy_data()) {
286 return data_storage_start();
287 }
Brian Silverman77162972020-08-12 19:52:40 -0700288 if (pin_data()) {
289 return static_cast<const char *>(pinner_->Data());
290 }
Brian Silverman3bca5322020-08-12 19:35:29 -0700291 return nullptr;
292 }
293
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800294 bool copy_data() const { return static_cast<bool>(data_storage_); }
Brian Silverman77162972020-08-12 19:52:40 -0700295 bool pin_data() const { return static_cast<bool>(pinner_); }
Brian Silvermana1652f32020-01-29 20:41:44 -0800296
Austin Schuh432784f2020-06-23 17:27:35 -0700297 aos::ShmEventLoop *event_loop_;
Austin Schuhf5652592019-12-29 16:26:15 -0800298 const Channel *const channel_;
Austin Schuh4d275fc2022-09-16 15:42:45 -0700299 ipc_lib::MemoryMappedQueue lockless_queue_memory_;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700300 ipc_lib::LocklessQueueReader reader_;
301 // This being nullopt indicates we're not looking for wakeups right now.
302 std::optional<ipc_lib::LocklessQueueWatcher> watcher_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700303
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700304 ipc_lib::QueueIndex actual_queue_index_ = ipc_lib::QueueIndex::Invalid();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700305
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800306 // This being empty indicates we're not going to copy data.
307 std::unique_ptr<char, decltype(&free)> data_storage_{nullptr, &free};
Austin Schuh39788ff2019-12-01 18:22:57 -0800308
Brian Silverman77162972020-08-12 19:52:40 -0700309 // This being nullopt indicates we're not going to pin messages.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700310 std::optional<ipc_lib::LocklessQueuePinner> pinner_;
Brian Silverman77162972020-08-12 19:52:40 -0700311
Austin Schuh39788ff2019-12-01 18:22:57 -0800312 Context context_;
313};
314
315class ShmFetcher : public RawFetcher {
316 public:
Austin Schuhef323c02020-09-01 14:55:28 -0700317 explicit ShmFetcher(std::string_view shm_base, ShmEventLoop *event_loop,
318 const Channel *channel)
Austin Schuhaa79e4e2019-12-29 20:43:32 -0800319 : RawFetcher(event_loop, channel),
Austin Schuhef323c02020-09-01 14:55:28 -0700320 simple_shm_fetcher_(shm_base, event_loop, channel) {
Brian Silverman77162972020-08-12 19:52:40 -0700321 simple_shm_fetcher_.RetrieveData();
Brian Silverman3bca5322020-08-12 19:35:29 -0700322 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800323
Austin Schuh3054f5f2021-07-21 15:38:01 -0700324 ~ShmFetcher() override {
325 shm_event_loop()->CheckCurrentThread();
326 context_.data = nullptr;
327 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800328
329 std::pair<bool, monotonic_clock::time_point> DoFetchNext() override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700330 shm_event_loop()->CheckCurrentThread();
Austin Schuh39788ff2019-12-01 18:22:57 -0800331 if (simple_shm_fetcher_.FetchNext()) {
332 context_ = simple_shm_fetcher_.context();
333 return std::make_pair(true, monotonic_clock::now());
334 }
335 return std::make_pair(false, monotonic_clock::min_time);
336 }
337
338 std::pair<bool, monotonic_clock::time_point> DoFetch() override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700339 shm_event_loop()->CheckCurrentThread();
Austin Schuh39788ff2019-12-01 18:22:57 -0800340 if (simple_shm_fetcher_.Fetch()) {
341 context_ = simple_shm_fetcher_.context();
342 return std::make_pair(true, monotonic_clock::now());
343 }
344 return std::make_pair(false, monotonic_clock::min_time);
345 }
346
Brian Silvermana5450a92020-08-12 19:59:57 -0700347 absl::Span<const char> GetPrivateMemory() const {
Brian Silverman6d2b3592020-06-18 14:40:15 -0700348 return simple_shm_fetcher_.GetPrivateMemory();
349 }
350
Austin Schuh39788ff2019-12-01 18:22:57 -0800351 private:
Austin Schuh3054f5f2021-07-21 15:38:01 -0700352 const ShmEventLoop *shm_event_loop() const {
353 return static_cast<const ShmEventLoop *>(event_loop());
354 }
355
Austin Schuh39788ff2019-12-01 18:22:57 -0800356 SimpleShmFetcher simple_shm_fetcher_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700357};
358
Brian Silvermane1fe2512022-08-14 23:18:50 -0700359class ShmExitHandle : public ExitHandle {
360 public:
361 ShmExitHandle(ShmEventLoop *event_loop) : event_loop_(event_loop) {
362 ++event_loop_->exit_handle_count_;
363 }
364 ~ShmExitHandle() override {
365 CHECK_GT(event_loop_->exit_handle_count_, 0);
366 --event_loop_->exit_handle_count_;
367 }
368
369 void Exit() override { event_loop_->Exit(); }
370
371 private:
372 ShmEventLoop *const event_loop_;
373};
374
Alex Perrycb7da4b2019-08-28 19:35:56 -0700375class ShmSender : public RawSender {
376 public:
Austin Schuhef323c02020-09-01 14:55:28 -0700377 explicit ShmSender(std::string_view shm_base, EventLoop *event_loop,
378 const Channel *channel)
Austin Schuh39788ff2019-12-01 18:22:57 -0800379 : RawSender(event_loop, channel),
Austin Schuh4d275fc2022-09-16 15:42:45 -0700380 lockless_queue_memory_(shm_base, FLAGS_permissions,
381 event_loop->configuration(), channel),
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700382 lockless_queue_sender_(VerifySender(
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700383 ipc_lib::LocklessQueueSender::Make(
384 lockless_queue_memory_.queue(),
385 std::chrono::nanoseconds(
386 event_loop->configuration()->channel_storage_duration())),
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700387 channel)),
388 wake_upper_(lockless_queue_memory_.queue()) {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700389
Austin Schuh3054f5f2021-07-21 15:38:01 -0700390 ~ShmSender() override { shm_event_loop()->CheckCurrentThread(); }
Austin Schuh39788ff2019-12-01 18:22:57 -0800391
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700392 static ipc_lib::LocklessQueueSender VerifySender(
393 std::optional<ipc_lib::LocklessQueueSender> sender,
Austin Schuhe516ab02020-05-06 21:37:04 -0700394 const Channel *channel) {
395 if (sender) {
396 return std::move(sender.value());
397 }
398 LOG(FATAL) << "Failed to create sender on "
399 << configuration::CleanedChannelToString(channel)
400 << ", too many senders.";
401 }
402
Austin Schuh3054f5f2021-07-21 15:38:01 -0700403 void *data() override {
404 shm_event_loop()->CheckCurrentThread();
405 return lockless_queue_sender_.Data();
406 }
407 size_t size() override {
408 shm_event_loop()->CheckCurrentThread();
409 return lockless_queue_sender_.size();
410 }
milind1f1dca32021-07-03 13:50:07 -0700411
412 Error DoSend(size_t length,
413 aos::monotonic_clock::time_point monotonic_remote_time,
414 aos::realtime_clock::time_point realtime_remote_time,
415 uint32_t remote_queue_index,
416 const UUID &source_boot_uuid) override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700417 shm_event_loop()->CheckCurrentThread();
Austin Schuh0f7ed462020-03-28 20:38:34 -0700418 CHECK_LE(length, static_cast<size_t>(channel()->max_size()))
419 << ": Sent too big a message on "
420 << configuration::CleanedChannelToString(channel());
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700421 const auto result = lockless_queue_sender_.Send(
422 length, monotonic_remote_time, realtime_remote_time, remote_queue_index,
423 source_boot_uuid, &monotonic_sent_time_, &realtime_sent_time_,
424 &sent_queue_index_);
425 CHECK_NE(result, ipc_lib::LocklessQueueSender::Result::INVALID_REDZONE)
Austin Schuh91ba6392020-10-03 13:27:47 -0700426 << ": Somebody wrote outside the buffer of their message on channel "
427 << configuration::CleanedChannelToString(channel());
428
Austin Schuh65493d62022-08-17 15:10:37 -0700429 wake_upper_.Wakeup(event_loop()->is_running()
430 ? event_loop()->runtime_realtime_priority()
431 : 0);
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700432 return CheckLocklessQueueResult(result);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700433 }
434
milind1f1dca32021-07-03 13:50:07 -0700435 Error DoSend(const void *msg, size_t length,
436 aos::monotonic_clock::time_point monotonic_remote_time,
437 aos::realtime_clock::time_point realtime_remote_time,
438 uint32_t remote_queue_index,
439 const UUID &source_boot_uuid) override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700440 shm_event_loop()->CheckCurrentThread();
Austin Schuh0f7ed462020-03-28 20:38:34 -0700441 CHECK_LE(length, static_cast<size_t>(channel()->max_size()))
442 << ": Sent too big a message on "
443 << configuration::CleanedChannelToString(channel());
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700444 const auto result = lockless_queue_sender_.Send(
Brian Silvermanaf9a4d82020-10-06 15:10:58 -0700445 reinterpret_cast<const char *>(msg), length, monotonic_remote_time,
Austin Schuha9012be2021-07-21 15:19:11 -0700446 realtime_remote_time, remote_queue_index, source_boot_uuid,
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700447 &monotonic_sent_time_, &realtime_sent_time_, &sent_queue_index_);
448
449 CHECK_NE(result, ipc_lib::LocklessQueueSender::Result::INVALID_REDZONE)
450 << ": Somebody wrote outside the buffer of their message on "
451 "channel "
Austin Schuh91ba6392020-10-03 13:27:47 -0700452 << configuration::CleanedChannelToString(channel());
Austin Schuh65493d62022-08-17 15:10:37 -0700453 wake_upper_.Wakeup(event_loop()->is_running()
454 ? event_loop()->runtime_realtime_priority()
455 : 0);
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700456
457 return CheckLocklessQueueResult(result);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700458 }
459
Brian Silverman5120afb2020-01-31 17:44:35 -0800460 absl::Span<char> GetSharedMemory() const {
Brian Silvermana5450a92020-08-12 19:59:57 -0700461 return lockless_queue_memory_.GetMutableSharedMemory();
Brian Silverman5120afb2020-01-31 17:44:35 -0800462 }
463
Austin Schuh3054f5f2021-07-21 15:38:01 -0700464 int buffer_index() override {
465 shm_event_loop()->CheckCurrentThread();
466 return lockless_queue_sender_.buffer_index();
467 }
Brian Silverman4f4e0612020-08-12 19:54:41 -0700468
Alex Perrycb7da4b2019-08-28 19:35:56 -0700469 private:
Austin Schuh3054f5f2021-07-21 15:38:01 -0700470 const ShmEventLoop *shm_event_loop() const {
471 return static_cast<const ShmEventLoop *>(event_loop());
472 }
473
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700474 RawSender::Error CheckLocklessQueueResult(
475 const ipc_lib::LocklessQueueSender::Result &result) {
476 switch (result) {
477 case ipc_lib::LocklessQueueSender::Result::GOOD:
478 return Error::kOk;
479 case ipc_lib::LocklessQueueSender::Result::MESSAGES_SENT_TOO_FAST:
480 return Error::kMessagesSentTooFast;
481 case ipc_lib::LocklessQueueSender::Result::INVALID_REDZONE:
482 return Error::kInvalidRedzone;
483 }
484 LOG(FATAL) << "Unknown lockless queue sender result"
485 << static_cast<int>(result);
486 }
487
Austin Schuh4d275fc2022-09-16 15:42:45 -0700488 ipc_lib::MemoryMappedQueue lockless_queue_memory_;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700489 ipc_lib::LocklessQueueSender lockless_queue_sender_;
490 ipc_lib::LocklessQueueWakeUpper wake_upper_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700491};
492
Alex Perrycb7da4b2019-08-28 19:35:56 -0700493// Class to manage the state for a Watcher.
Brian Silverman148d43d2020-06-07 18:19:22 -0500494class ShmWatcherState : public WatcherState {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700495 public:
Brian Silverman148d43d2020-06-07 18:19:22 -0500496 ShmWatcherState(
Austin Schuhef323c02020-09-01 14:55:28 -0700497 std::string_view shm_base, ShmEventLoop *event_loop,
498 const Channel *channel,
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800499 std::function<void(const Context &context, const void *message)> fn,
500 bool copy_data)
Brian Silverman148d43d2020-06-07 18:19:22 -0500501 : WatcherState(event_loop, channel, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800502 event_loop_(event_loop),
503 event_(this),
Austin Schuhef323c02020-09-01 14:55:28 -0700504 simple_shm_fetcher_(shm_base, event_loop, channel) {
Brian Silverman3bca5322020-08-12 19:35:29 -0700505 if (copy_data) {
Brian Silverman77162972020-08-12 19:52:40 -0700506 simple_shm_fetcher_.RetrieveData();
Brian Silverman3bca5322020-08-12 19:35:29 -0700507 }
508 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700509
Austin Schuh3054f5f2021-07-21 15:38:01 -0700510 ~ShmWatcherState() override {
511 event_loop_->CheckCurrentThread();
512 event_loop_->RemoveEvent(&event_);
513 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800514
515 void Startup(EventLoop *event_loop) override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700516 event_loop_->CheckCurrentThread();
Austin Schuh7d87b672019-12-01 20:23:49 -0800517 simple_shm_fetcher_.PointAtNextQueueIndex();
Austin Schuh65493d62022-08-17 15:10:37 -0700518 CHECK(RegisterWakeup(event_loop->runtime_realtime_priority()));
Austin Schuh39788ff2019-12-01 18:22:57 -0800519 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700520
Alex Perrycb7da4b2019-08-28 19:35:56 -0700521 // Returns true if there is new data available.
Austin Schuh7d87b672019-12-01 20:23:49 -0800522 bool CheckForNewData() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700523 if (!has_new_data_) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800524 has_new_data_ = simple_shm_fetcher_.FetchNext();
Austin Schuh7d87b672019-12-01 20:23:49 -0800525
526 if (has_new_data_) {
527 event_.set_event_time(
Austin Schuhad154822019-12-27 15:45:13 -0800528 simple_shm_fetcher_.context().monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800529 event_loop_->AddEvent(&event_);
530 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700531 }
532
533 return has_new_data_;
534 }
535
Alex Perrycb7da4b2019-08-28 19:35:56 -0700536 // Consumes the data by calling the callback.
Austin Schuh7d87b672019-12-01 20:23:49 -0800537 void HandleEvent() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700538 CHECK(has_new_data_);
Austin Schuh39788ff2019-12-01 18:22:57 -0800539 DoCallCallback(monotonic_clock::now, simple_shm_fetcher_.context());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700540 has_new_data_ = false;
Austin Schuh7d87b672019-12-01 20:23:49 -0800541 CheckForNewData();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700542 }
543
Austin Schuh39788ff2019-12-01 18:22:57 -0800544 // Registers us to receive a signal on event reception.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700545 bool RegisterWakeup(int priority) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800546 return simple_shm_fetcher_.RegisterWakeup(priority);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700547 }
548
Austin Schuh39788ff2019-12-01 18:22:57 -0800549 void UnregisterWakeup() { return simple_shm_fetcher_.UnregisterWakeup(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700550
Brian Silvermana5450a92020-08-12 19:59:57 -0700551 absl::Span<const char> GetSharedMemory() const {
552 return simple_shm_fetcher_.GetConstSharedMemory();
Brian Silverman5120afb2020-01-31 17:44:35 -0800553 }
554
Alex Perrycb7da4b2019-08-28 19:35:56 -0700555 private:
556 bool has_new_data_ = false;
557
Austin Schuh7d87b672019-12-01 20:23:49 -0800558 ShmEventLoop *event_loop_;
Brian Silverman148d43d2020-06-07 18:19:22 -0500559 EventHandler<ShmWatcherState> event_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800560 SimpleShmFetcher simple_shm_fetcher_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700561};
562
563// Adapter class to adapt a timerfd to a TimerHandler.
Brian Silverman148d43d2020-06-07 18:19:22 -0500564class ShmTimerHandler final : public TimerHandler {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700565 public:
Brian Silverman148d43d2020-06-07 18:19:22 -0500566 ShmTimerHandler(ShmEventLoop *shm_event_loop, ::std::function<void()> fn)
Austin Schuh39788ff2019-12-01 18:22:57 -0800567 : TimerHandler(shm_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800568 shm_event_loop_(shm_event_loop),
569 event_(this) {
Austin Schuhcde39fd2020-02-22 20:58:24 -0800570 shm_event_loop_->epoll_.OnReadable(timerfd_.fd(), [this]() {
Austin Schuh5ca13112021-02-07 22:06:53 -0800571 // The timer may fire spuriously. HandleEvent on the event loop will
Austin Schuhcde39fd2020-02-22 20:58:24 -0800572 // call the callback if it is needed. It may also have called it when
573 // processing some other event, and the kernel decided to deliver this
574 // wakeup anyways.
575 timerfd_.Read();
576 shm_event_loop_->HandleEvent();
577 });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700578 }
579
Brian Silverman148d43d2020-06-07 18:19:22 -0500580 ~ShmTimerHandler() {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700581 shm_event_loop_->CheckCurrentThread();
Austin Schuh7d87b672019-12-01 20:23:49 -0800582 Disable();
583 shm_event_loop_->epoll_.DeleteFd(timerfd_.fd());
584 }
585
586 void HandleEvent() {
Austin Schuhcde39fd2020-02-22 20:58:24 -0800587 CHECK(!event_.valid());
Brian Silvermanaf9a4d82020-10-06 15:10:58 -0700588 disabled_ = false;
Austin Schuhcde39fd2020-02-22 20:58:24 -0800589 const auto monotonic_now = Call(monotonic_clock::now, base_);
590 if (event_.valid()) {
Philipp Schradera6712522023-07-05 20:25:11 -0700591 // If someone called Schedule inside Call, rescheduling is already taken
592 // care of. Bail.
Austin Schuhcde39fd2020-02-22 20:58:24 -0800593 return;
Austin Schuh7d87b672019-12-01 20:23:49 -0800594 }
Brian Silvermanaf9a4d82020-10-06 15:10:58 -0700595 if (disabled_) {
596 // Somebody called Disable inside Call, so we don't want to reschedule.
597 // Bail.
598 return;
599 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800600
Austin Schuh4d275fc2022-09-16 15:42:45 -0700601 if (repeat_offset_ == std::chrono::seconds(0)) {
Austin Schuhcde39fd2020-02-22 20:58:24 -0800602 timerfd_.Disable();
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700603 disabled_ = true;
Austin Schuhcde39fd2020-02-22 20:58:24 -0800604 } else {
605 // Compute how many cycles have elapsed and schedule the next iteration
606 // for the next iteration in the future.
607 const int elapsed_cycles =
608 std::max<int>(0, (monotonic_now - base_ + repeat_offset_ -
609 std::chrono::nanoseconds(1)) /
610 repeat_offset_);
611 base_ += repeat_offset_ * elapsed_cycles;
Austin Schuh7d87b672019-12-01 20:23:49 -0800612
Austin Schuhcde39fd2020-02-22 20:58:24 -0800613 // Update the heap and schedule the timerfd wakeup.
Austin Schuh7d87b672019-12-01 20:23:49 -0800614 event_.set_event_time(base_);
615 shm_event_loop_->AddEvent(&event_);
Austin Schuh4d275fc2022-09-16 15:42:45 -0700616 timerfd_.SetTime(base_, std::chrono::seconds(0));
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700617 disabled_ = false;
Austin Schuh7d87b672019-12-01 20:23:49 -0800618 }
619 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700620
Philipp Schradera6712522023-07-05 20:25:11 -0700621 void Schedule(monotonic_clock::time_point base,
622 monotonic_clock::duration repeat_offset) override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700623 shm_event_loop_->CheckCurrentThread();
Austin Schuh7d87b672019-12-01 20:23:49 -0800624 if (event_.valid()) {
625 shm_event_loop_->RemoveEvent(&event_);
626 }
627
Alex Perrycb7da4b2019-08-28 19:35:56 -0700628 timerfd_.SetTime(base, repeat_offset);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800629 base_ = base;
630 repeat_offset_ = repeat_offset;
Austin Schuh7d87b672019-12-01 20:23:49 -0800631 event_.set_event_time(base_);
632 shm_event_loop_->AddEvent(&event_);
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700633 disabled_ = false;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700634 }
635
Austin Schuh7d87b672019-12-01 20:23:49 -0800636 void Disable() override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700637 shm_event_loop_->CheckCurrentThread();
Austin Schuh7d87b672019-12-01 20:23:49 -0800638 shm_event_loop_->RemoveEvent(&event_);
639 timerfd_.Disable();
Brian Silvermanaf9a4d82020-10-06 15:10:58 -0700640 disabled_ = true;
Austin Schuh7d87b672019-12-01 20:23:49 -0800641 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700642
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700643 bool IsDisabled() override { return disabled_; }
644
Alex Perrycb7da4b2019-08-28 19:35:56 -0700645 private:
646 ShmEventLoop *shm_event_loop_;
Brian Silverman148d43d2020-06-07 18:19:22 -0500647 EventHandler<ShmTimerHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700648
Brian Silverman148d43d2020-06-07 18:19:22 -0500649 internal::TimerFd timerfd_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700650
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800651 monotonic_clock::time_point base_;
652 monotonic_clock::duration repeat_offset_;
Brian Silvermanaf9a4d82020-10-06 15:10:58 -0700653
654 // Used to track if Disable() was called during the callback, so we know not
655 // to reschedule.
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700656 bool disabled_ = true;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700657};
658
659// Adapter class to the timerfd and PhasedLoop.
Brian Silverman148d43d2020-06-07 18:19:22 -0500660class ShmPhasedLoopHandler final : public PhasedLoopHandler {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700661 public:
Brian Silverman148d43d2020-06-07 18:19:22 -0500662 ShmPhasedLoopHandler(ShmEventLoop *shm_event_loop,
663 ::std::function<void(int)> fn,
664 const monotonic_clock::duration interval,
665 const monotonic_clock::duration offset)
666 : PhasedLoopHandler(shm_event_loop, std::move(fn), interval, offset),
Austin Schuh7d87b672019-12-01 20:23:49 -0800667 shm_event_loop_(shm_event_loop),
668 event_(this) {
669 shm_event_loop_->epoll_.OnReadable(
670 timerfd_.fd(), [this]() { shm_event_loop_->HandleEvent(); });
671 }
672
673 void HandleEvent() {
674 // The return value for read is the number of cycles that have elapsed.
675 // Because we check to see when this event *should* have happened, there are
676 // cases where Read() will return 0, when 1 cycle has actually happened.
677 // This occurs when the timer interrupt hasn't triggered yet. Therefore,
678 // ignore it. Call handles rescheduling and calculating elapsed cycles
679 // without any extra help.
680 timerfd_.Read();
681 event_.Invalidate();
682
James Kuszmaul20dcc7c2023-01-20 11:06:31 -0800683 Call(monotonic_clock::now);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700684 }
685
Brian Silverman148d43d2020-06-07 18:19:22 -0500686 ~ShmPhasedLoopHandler() override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700687 shm_event_loop_->CheckCurrentThread();
Austin Schuh39788ff2019-12-01 18:22:57 -0800688 shm_event_loop_->epoll_.DeleteFd(timerfd_.fd());
Austin Schuh7d87b672019-12-01 20:23:49 -0800689 shm_event_loop_->RemoveEvent(&event_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700690 }
691
692 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800693 // Reschedules the timer.
Austin Schuh39788ff2019-12-01 18:22:57 -0800694 void Schedule(monotonic_clock::time_point sleep_time) override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700695 shm_event_loop_->CheckCurrentThread();
Austin Schuh7d87b672019-12-01 20:23:49 -0800696 if (event_.valid()) {
697 shm_event_loop_->RemoveEvent(&event_);
698 }
699
Austin Schuh39788ff2019-12-01 18:22:57 -0800700 timerfd_.SetTime(sleep_time, ::aos::monotonic_clock::zero());
Austin Schuh7d87b672019-12-01 20:23:49 -0800701 event_.set_event_time(sleep_time);
702 shm_event_loop_->AddEvent(&event_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700703 }
704
705 ShmEventLoop *shm_event_loop_;
Brian Silverman148d43d2020-06-07 18:19:22 -0500706 EventHandler<ShmPhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700707
Brian Silverman148d43d2020-06-07 18:19:22 -0500708 internal::TimerFd timerfd_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700709};
Brian Silverman148d43d2020-06-07 18:19:22 -0500710
711} // namespace shm_event_loop_internal
Alex Perrycb7da4b2019-08-28 19:35:56 -0700712
713::std::unique_ptr<RawFetcher> ShmEventLoop::MakeRawFetcher(
714 const Channel *channel) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700715 CheckCurrentThread();
Austin Schuhca4828c2019-12-28 14:21:35 -0800716 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
717 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
718 << "\", \"type\": \"" << channel->type()->string_view()
719 << "\" } is not able to be fetched on this node. Check your "
720 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800721 }
722
Austin Schuhef323c02020-09-01 14:55:28 -0700723 return ::std::unique_ptr<RawFetcher>(
724 new ShmFetcher(shm_base_, this, channel));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700725}
726
727::std::unique_ptr<RawSender> ShmEventLoop::MakeRawSender(
728 const Channel *channel) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700729 CheckCurrentThread();
Brian Silverman0fc69932020-01-24 21:54:02 -0800730 TakeSender(channel);
Austin Schuh39788ff2019-12-01 18:22:57 -0800731
Austin Schuhef323c02020-09-01 14:55:28 -0700732 return ::std::unique_ptr<RawSender>(new ShmSender(shm_base_, this, channel));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700733}
734
735void ShmEventLoop::MakeRawWatcher(
736 const Channel *channel,
737 std::function<void(const Context &context, const void *message)> watcher) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700738 CheckCurrentThread();
Brian Silverman0fc69932020-01-24 21:54:02 -0800739 TakeWatcher(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800740
Austin Schuh39788ff2019-12-01 18:22:57 -0800741 NewWatcher(::std::unique_ptr<WatcherState>(
Austin Schuhef323c02020-09-01 14:55:28 -0700742 new ShmWatcherState(shm_base_, this, channel, std::move(watcher), true)));
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800743}
744
745void ShmEventLoop::MakeRawNoArgWatcher(
746 const Channel *channel,
747 std::function<void(const Context &context)> watcher) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700748 CheckCurrentThread();
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800749 TakeWatcher(channel);
750
Brian Silverman148d43d2020-06-07 18:19:22 -0500751 NewWatcher(::std::unique_ptr<WatcherState>(new ShmWatcherState(
Austin Schuhef323c02020-09-01 14:55:28 -0700752 shm_base_, this, channel,
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800753 [watcher](const Context &context, const void *) { watcher(context); },
754 false)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700755}
756
757TimerHandler *ShmEventLoop::AddTimer(::std::function<void()> callback) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700758 CheckCurrentThread();
Austin Schuh39788ff2019-12-01 18:22:57 -0800759 return NewTimer(::std::unique_ptr<TimerHandler>(
Brian Silverman148d43d2020-06-07 18:19:22 -0500760 new ShmTimerHandler(this, ::std::move(callback))));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700761}
762
763PhasedLoopHandler *ShmEventLoop::AddPhasedLoop(
764 ::std::function<void(int)> callback,
765 const monotonic_clock::duration interval,
766 const monotonic_clock::duration offset) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700767 CheckCurrentThread();
Brian Silverman148d43d2020-06-07 18:19:22 -0500768 return NewPhasedLoop(::std::unique_ptr<PhasedLoopHandler>(
769 new ShmPhasedLoopHandler(this, ::std::move(callback), interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700770}
771
772void ShmEventLoop::OnRun(::std::function<void()> on_run) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700773 CheckCurrentThread();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700774 on_run_.push_back(::std::move(on_run));
775}
776
Austin Schuh3054f5f2021-07-21 15:38:01 -0700777void ShmEventLoop::CheckCurrentThread() const {
778 if (__builtin_expect(check_mutex_ != nullptr, false)) {
779 CHECK(check_mutex_->is_locked())
780 << ": The configured mutex is not locked while calling a "
781 "ShmEventLoop function";
782 }
783 if (__builtin_expect(!!check_tid_, false)) {
784 CHECK_EQ(syscall(SYS_gettid), *check_tid_)
785 << ": Being called from the wrong thread";
786 }
787}
788
Austin Schuh5ca13112021-02-07 22:06:53 -0800789// This is a bit tricky because watchers can generate new events at any time (as
790// long as it's in the past). We want to check the watchers at least once before
791// declaring there are no events to handle, and we want to check them again if
792// event processing takes long enough that we find an event after that point in
793// time to handle.
Austin Schuh7d87b672019-12-01 20:23:49 -0800794void ShmEventLoop::HandleEvent() {
Austin Schuh5ca13112021-02-07 22:06:53 -0800795 // Time through which we've checked for new events in watchers.
796 monotonic_clock::time_point checked_until = monotonic_clock::min_time;
797 if (!signalfd_) {
798 // Nothing to check, so we can bail out immediately once we're out of
799 // events.
800 CHECK(watchers_.empty());
801 checked_until = monotonic_clock::max_time;
Austin Schuh7d87b672019-12-01 20:23:49 -0800802 }
803
Austin Schuh5ca13112021-02-07 22:06:53 -0800804 // Loop until we run out of events to check.
Austin Schuh39788ff2019-12-01 18:22:57 -0800805 while (true) {
Austin Schuh5ca13112021-02-07 22:06:53 -0800806 // Time of the next event we know about. If this is before checked_until, we
807 // know there aren't any new events before the next one that we already know
808 // about, so no need to check the watchers.
809 monotonic_clock::time_point next_time = monotonic_clock::max_time;
810
811 if (EventCount() == 0) {
812 if (checked_until != monotonic_clock::min_time) {
813 // No events, and we've already checked the watchers at least once, so
814 // we're all done.
815 //
816 // There's a small chance that a watcher has gotten another event in
817 // between checked_until and now. If so, then the signalfd will be
818 // triggered now and we'll re-enter HandleEvent immediately. This is
819 // unlikely though, so we don't want to spend time checking all the
820 // watchers unnecessarily.
821 break;
822 }
823 } else {
824 next_time = PeekEvent()->event_time();
825 }
Austin Schuh00cad2e2022-12-02 20:11:04 -0800826 monotonic_clock::time_point now;
827 bool new_data = false;
Austin Schuh5ca13112021-02-07 22:06:53 -0800828
829 if (next_time > checked_until) {
830 // Read all of the signals, because there's no point in waking up again
831 // immediately to handle each one if we've fallen behind.
832 //
833 // This is safe before checking for new data on the watchers. If a signal
834 // is cleared here, the corresponding CheckForNewData() call below will
835 // pick it up.
836 while (true) {
837 const signalfd_siginfo result = signalfd_->Read();
838 if (result.ssi_signo == 0) {
839 break;
840 }
841 CHECK_EQ(result.ssi_signo, ipc_lib::kWakeupSignal);
842 }
Austin Schuh00cad2e2022-12-02 20:11:04 -0800843 // This is the last time we can guarantee that if a message is published
844 // before, we will notice it.
845 now = monotonic_clock::now();
Austin Schuh5ca13112021-02-07 22:06:53 -0800846
847 // Check all the watchers for new events.
848 for (std::unique_ptr<WatcherState> &base_watcher : watchers_) {
849 ShmWatcherState *const watcher =
850 reinterpret_cast<ShmWatcherState *>(base_watcher.get());
851
Austin Schuh00cad2e2022-12-02 20:11:04 -0800852 // Track if we got a message.
853 if (watcher->CheckForNewData()) {
854 new_data = true;
855 }
Austin Schuh5ca13112021-02-07 22:06:53 -0800856 }
857 if (EventCount() == 0) {
858 // Still no events, all done now.
859 break;
860 }
861
862 checked_until = now;
863 // Check for any new events we found.
864 next_time = PeekEvent()->event_time();
Austin Schuh00cad2e2022-12-02 20:11:04 -0800865 } else {
866 now = monotonic_clock::now();
Austin Schuh5ca13112021-02-07 22:06:53 -0800867 }
868
869 if (next_time > now) {
Austin Schuh00cad2e2022-12-02 20:11:04 -0800870 // Ok, we got a message with a timestamp *after* we wrote down time. We
871 // need to process it (otherwise we will go to sleep without processing
872 // it), but we also need to make sure no other messages have come in
873 // before it that we would process out of order. Just go around again to
874 // redo the checks.
875 if (new_data) {
876 continue;
877 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800878 break;
879 }
880
Austin Schuh5ca13112021-02-07 22:06:53 -0800881 EventLoopEvent *const event = PopEvent();
Austin Schuh7d87b672019-12-01 20:23:49 -0800882 event->HandleEvent();
Austin Schuh39788ff2019-12-01 18:22:57 -0800883 }
884}
885
Austin Schuh32fd5a72019-12-01 22:20:26 -0800886// RAII class to mask signals.
887class ScopedSignalMask {
888 public:
889 ScopedSignalMask(std::initializer_list<int> signals) {
890 sigset_t sigset;
891 PCHECK(sigemptyset(&sigset) == 0);
892 for (int signal : signals) {
893 PCHECK(sigaddset(&sigset, signal) == 0);
894 }
895
896 PCHECK(sigprocmask(SIG_BLOCK, &sigset, &old_) == 0);
897 }
898
899 ~ScopedSignalMask() { PCHECK(sigprocmask(SIG_SETMASK, &old_, nullptr) == 0); }
900
901 private:
902 sigset_t old_;
903};
904
905// Class to manage the static state associated with killing multiple event
906// loops.
907class SignalHandler {
908 public:
909 // Gets the singleton.
910 static SignalHandler *global() {
911 static SignalHandler loop;
912 return &loop;
913 }
914
915 // Handles the signal with the singleton.
916 static void HandleSignal(int) { global()->DoHandleSignal(); }
917
918 // Registers an event loop to receive Exit() calls.
919 void Register(ShmEventLoop *event_loop) {
920 // Block signals while we have the mutex so we never race with the signal
921 // handler.
922 ScopedSignalMask mask({SIGINT, SIGHUP, SIGTERM});
923 std::unique_lock<stl_mutex> locker(mutex_);
924 if (event_loops_.size() == 0) {
925 // The first caller registers the signal handler.
926 struct sigaction new_action;
927 sigemptyset(&new_action.sa_mask);
928 // This makes it so that 2 control c's to a stuck process will kill it by
929 // restoring the original signal handler.
930 new_action.sa_flags = SA_RESETHAND;
931 new_action.sa_handler = &HandleSignal;
932
933 PCHECK(sigaction(SIGINT, &new_action, &old_action_int_) == 0);
934 PCHECK(sigaction(SIGHUP, &new_action, &old_action_hup_) == 0);
935 PCHECK(sigaction(SIGTERM, &new_action, &old_action_term_) == 0);
936 }
937
938 event_loops_.push_back(event_loop);
939 }
940
941 // Unregisters an event loop to receive Exit() calls.
942 void Unregister(ShmEventLoop *event_loop) {
943 // Block signals while we have the mutex so we never race with the signal
944 // handler.
945 ScopedSignalMask mask({SIGINT, SIGHUP, SIGTERM});
946 std::unique_lock<stl_mutex> locker(mutex_);
947
Brian Silverman5120afb2020-01-31 17:44:35 -0800948 event_loops_.erase(
949 std::find(event_loops_.begin(), event_loops_.end(), event_loop));
Austin Schuh32fd5a72019-12-01 22:20:26 -0800950
951 if (event_loops_.size() == 0u) {
952 // The last caller restores the original signal handlers.
953 PCHECK(sigaction(SIGINT, &old_action_int_, nullptr) == 0);
954 PCHECK(sigaction(SIGHUP, &old_action_hup_, nullptr) == 0);
955 PCHECK(sigaction(SIGTERM, &old_action_term_, nullptr) == 0);
956 }
957 }
958
959 private:
960 void DoHandleSignal() {
961 // We block signals while grabbing the lock, so there should never be a
962 // race. Confirm that this is true using trylock.
963 CHECK(mutex_.try_lock()) << ": sigprocmask failed to block signals while "
964 "modifing the event loop list.";
965 for (ShmEventLoop *event_loop : event_loops_) {
966 event_loop->Exit();
967 }
968 mutex_.unlock();
969 }
970
971 // Mutex to protect all state.
972 stl_mutex mutex_;
973 std::vector<ShmEventLoop *> event_loops_;
974 struct sigaction old_action_int_;
975 struct sigaction old_action_hup_;
976 struct sigaction old_action_term_;
977};
978
Alex Perrycb7da4b2019-08-28 19:35:56 -0700979void ShmEventLoop::Run() {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700980 CheckCurrentThread();
Austin Schuh32fd5a72019-12-01 22:20:26 -0800981 SignalHandler::global()->Register(this);
Austin Schuh39788ff2019-12-01 18:22:57 -0800982
Alex Perrycb7da4b2019-08-28 19:35:56 -0700983 if (watchers_.size() > 0) {
Austin Schuh5ca13112021-02-07 22:06:53 -0800984 signalfd_.reset(new ipc_lib::SignalFd({ipc_lib::kWakeupSignal}));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700985
Austin Schuh5ca13112021-02-07 22:06:53 -0800986 epoll_.OnReadable(signalfd_->fd(), [this]() { HandleEvent(); });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700987 }
988
Austin Schuh39788ff2019-12-01 18:22:57 -0800989 MaybeScheduleTimingReports();
990
Austin Schuh7d87b672019-12-01 20:23:49 -0800991 ReserveEvents();
992
Tyler Chatow67ddb032020-01-12 14:30:04 -0800993 {
Austin Schuha0c41ba2020-09-10 22:59:14 -0700994 logging::ScopedLogRestorer prev_logger;
Tyler Chatow67ddb032020-01-12 14:30:04 -0800995 AosLogToFbs aos_logger;
996 if (!skip_logger_) {
Austin Schuhad9e5eb2021-11-19 20:33:55 -0800997 aos_logger.Initialize(&name_, MakeSender<logging::LogMessageFbs>("/aos"));
Austin Schuha0c41ba2020-09-10 22:59:14 -0700998 prev_logger.Swap(aos_logger.implementation());
Tyler Chatow67ddb032020-01-12 14:30:04 -0800999 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001000
Tyler Chatow67ddb032020-01-12 14:30:04 -08001001 aos::SetCurrentThreadName(name_.substr(0, 16));
Brian Silverman6a54ff32020-04-28 16:41:39 -07001002 const cpu_set_t default_affinity = DefaultAffinity();
1003 if (!CPU_EQUAL(&affinity_, &default_affinity)) {
1004 ::aos::SetCurrentThreadAffinity(affinity_);
1005 }
Tyler Chatow67ddb032020-01-12 14:30:04 -08001006 // Now, all the callbacks are setup. Lock everything into memory and go RT.
1007 if (priority_ != 0) {
1008 ::aos::InitRT();
1009
1010 LOG(INFO) << "Setting priority to " << priority_;
1011 ::aos::SetCurrentThreadRealtimePriority(priority_);
1012 }
1013
1014 set_is_running(true);
1015
1016 // Now that we are realtime (but before the OnRun handlers run), snap the
1017 // queue index.
1018 for (::std::unique_ptr<WatcherState> &watcher : watchers_) {
1019 watcher->Startup(this);
1020 }
1021
1022 // Now that we are RT, run all the OnRun handlers.
Austin Schuha9012be2021-07-21 15:19:11 -07001023 SetTimerContext(monotonic_clock::now());
Tyler Chatow67ddb032020-01-12 14:30:04 -08001024 for (const auto &run : on_run_) {
1025 run();
1026 }
1027
1028 // And start our main event loop which runs all the timers and handles Quit.
1029 epoll_.Run();
1030
1031 // Once epoll exits, there is no useful nonrt work left to do.
1032 set_is_running(false);
1033
1034 // Nothing time or synchronization critical needs to happen after this
1035 // point. Drop RT priority.
1036 ::aos::UnsetCurrentThreadRealtimePriority();
Alex Perrycb7da4b2019-08-28 19:35:56 -07001037 }
1038
Austin Schuh39788ff2019-12-01 18:22:57 -08001039 for (::std::unique_ptr<WatcherState> &base_watcher : watchers_) {
Brian Silverman148d43d2020-06-07 18:19:22 -05001040 ShmWatcherState *watcher =
1041 reinterpret_cast<ShmWatcherState *>(base_watcher.get());
Alex Perrycb7da4b2019-08-28 19:35:56 -07001042 watcher->UnregisterWakeup();
1043 }
1044
1045 if (watchers_.size() > 0) {
Austin Schuh5ca13112021-02-07 22:06:53 -08001046 epoll_.DeleteFd(signalfd_->fd());
1047 signalfd_.reset();
Alex Perrycb7da4b2019-08-28 19:35:56 -07001048 }
Austin Schuh32fd5a72019-12-01 22:20:26 -08001049
1050 SignalHandler::global()->Unregister(this);
Austin Schuhe84c3ed2019-12-14 15:29:48 -08001051
1052 // Trigger any remaining senders or fetchers to be cleared before destroying
1053 // the event loop so the book keeping matches. Do this in the thread that
1054 // created the timing reporter.
1055 timing_report_sender_.reset();
Austin Schuh0debde12022-08-17 16:25:17 -07001056 ClearContext();
Alex Perrycb7da4b2019-08-28 19:35:56 -07001057}
1058
1059void ShmEventLoop::Exit() { epoll_.Quit(); }
1060
Brian Silvermane1fe2512022-08-14 23:18:50 -07001061std::unique_ptr<ExitHandle> ShmEventLoop::MakeExitHandle() {
1062 return std::make_unique<ShmExitHandle>(this);
1063}
1064
Alex Perrycb7da4b2019-08-28 19:35:56 -07001065ShmEventLoop::~ShmEventLoop() {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001066 CheckCurrentThread();
Austin Schuh39788ff2019-12-01 18:22:57 -08001067 // Force everything with a registered fd with epoll to be destroyed now.
1068 timers_.clear();
1069 phased_loops_.clear();
1070 watchers_.clear();
1071
Alex Perrycb7da4b2019-08-28 19:35:56 -07001072 CHECK(!is_running()) << ": ShmEventLoop destroyed while running";
Brian Silvermane1fe2512022-08-14 23:18:50 -07001073 CHECK_EQ(0, exit_handle_count_)
1074 << ": All ExitHandles must be destroyed before the ShmEventLoop";
Alex Perrycb7da4b2019-08-28 19:35:56 -07001075}
1076
Alex Perrycb7da4b2019-08-28 19:35:56 -07001077void ShmEventLoop::SetRuntimeRealtimePriority(int priority) {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001078 CheckCurrentThread();
Alex Perrycb7da4b2019-08-28 19:35:56 -07001079 if (is_running()) {
1080 LOG(FATAL) << "Cannot set realtime priority while running.";
1081 }
1082 priority_ = priority;
1083}
1084
Brian Silverman6a54ff32020-04-28 16:41:39 -07001085void ShmEventLoop::SetRuntimeAffinity(const cpu_set_t &cpuset) {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001086 CheckCurrentThread();
Brian Silverman6a54ff32020-04-28 16:41:39 -07001087 if (is_running()) {
1088 LOG(FATAL) << "Cannot set affinity while running.";
1089 }
1090 affinity_ = cpuset;
1091}
1092
James Kuszmaul57c2baa2020-01-19 14:52:52 -08001093void ShmEventLoop::set_name(const std::string_view name) {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001094 CheckCurrentThread();
James Kuszmaul57c2baa2020-01-19 14:52:52 -08001095 name_ = std::string(name);
1096 UpdateTimingReport();
1097}
1098
Brian Silvermana5450a92020-08-12 19:59:57 -07001099absl::Span<const char> ShmEventLoop::GetWatcherSharedMemory(
1100 const Channel *channel) {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001101 CheckCurrentThread();
Brian Silverman148d43d2020-06-07 18:19:22 -05001102 ShmWatcherState *const watcher_state =
1103 static_cast<ShmWatcherState *>(GetWatcherState(channel));
Brian Silverman5120afb2020-01-31 17:44:35 -08001104 return watcher_state->GetSharedMemory();
1105}
1106
Brian Silverman4f4e0612020-08-12 19:54:41 -07001107int ShmEventLoop::NumberBuffers(const Channel *channel) {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001108 CheckCurrentThread();
Austin Schuh4d275fc2022-09-16 15:42:45 -07001109 return ipc_lib::MakeQueueConfiguration(configuration(), channel)
1110 .num_messages();
Brian Silverman4f4e0612020-08-12 19:54:41 -07001111}
1112
Brian Silverman5120afb2020-01-31 17:44:35 -08001113absl::Span<char> ShmEventLoop::GetShmSenderSharedMemory(
1114 const aos::RawSender *sender) const {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001115 CheckCurrentThread();
Brian Silverman148d43d2020-06-07 18:19:22 -05001116 return static_cast<const ShmSender *>(sender)->GetSharedMemory();
Brian Silverman5120afb2020-01-31 17:44:35 -08001117}
1118
Brian Silvermana5450a92020-08-12 19:59:57 -07001119absl::Span<const char> ShmEventLoop::GetShmFetcherPrivateMemory(
Brian Silverman6d2b3592020-06-18 14:40:15 -07001120 const aos::RawFetcher *fetcher) const {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001121 CheckCurrentThread();
Brian Silverman6d2b3592020-06-18 14:40:15 -07001122 return static_cast<const ShmFetcher *>(fetcher)->GetPrivateMemory();
1123}
1124
Austin Schuh3054f5f2021-07-21 15:38:01 -07001125pid_t ShmEventLoop::GetTid() {
1126 CheckCurrentThread();
1127 return syscall(SYS_gettid);
1128}
Austin Schuh39788ff2019-12-01 18:22:57 -08001129
Alex Perrycb7da4b2019-08-28 19:35:56 -07001130} // namespace aos