blob: 2ca27aca03ce12b052c06425596dcc24b35fe132 [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.");
Brennan Coslett6fd3c002023-07-11 17:41:09 -050043// This value is affected by the umask of the process which is calling it
44// and is set to the user's value by default (check yours running `umask` on
45// the command line).
46// Any file mode requested is transformed using: mode & ~umask and the default
47// umask is 0022 (allow any permissions for the user, dont allow writes for
48// groups or others).
49// See https://man7.org/linux/man-pages/man2/umask.2.html for more details.
50// WITH THE DEFAULT UMASK YOU WONT ACTUALLY GET THESE PERMISSIONS :)
Alex Perrycb7da4b2019-08-28 19:35:56 -070051DEFINE_uint32(permissions, 0770,
Brennan Coslett6fd3c002023-07-11 17:41:09 -050052 "Permissions to make shared memory files and folders, "
53 "effected by the processes umask. "
54 "See shm_event_loop.cc for more details.");
Austin Schuhe84c3ed2019-12-14 15:29:48 -080055DEFINE_string(application_name, Filename(program_invocation_name),
56 "The application name");
Alex Perrycb7da4b2019-08-28 19:35:56 -070057
58namespace aos {
59
Brian Silverman148d43d2020-06-07 18:19:22 -050060using namespace shm_event_loop_internal;
61
Austin Schuhcdab6192019-12-29 17:47:46 -080062void SetShmBase(const std::string_view base) {
Austin Schuhef323c02020-09-01 14:55:28 -070063 FLAGS_shm_base = std::string(base) + "/aos";
Austin Schuhcdab6192019-12-29 17:47:46 -080064}
65
Brian Silverman4f4e0612020-08-12 19:54:41 -070066namespace {
67
Austin Schuh217a9782019-12-21 23:02:50 -080068const Node *MaybeMyNode(const Configuration *configuration) {
69 if (!configuration->has_nodes()) {
70 return nullptr;
71 }
Alex Perrycb7da4b2019-08-28 19:35:56 -070072
Austin Schuh217a9782019-12-21 23:02:50 -080073 return configuration::GetMyNode(configuration);
74}
Alex Perrycb7da4b2019-08-28 19:35:56 -070075
Austin Schuh39788ff2019-12-01 18:22:57 -080076} // namespace
77
Austin Schuh217a9782019-12-21 23:02:50 -080078ShmEventLoop::ShmEventLoop(const Configuration *configuration)
Austin Schuh83c7f702021-01-19 22:36:29 -080079 : EventLoop(configuration),
80 boot_uuid_(UUID::BootUUID()),
Austin Schuhef323c02020-09-01 14:55:28 -070081 shm_base_(FLAGS_shm_base),
Austin Schuhe84c3ed2019-12-14 15:29:48 -080082 name_(FLAGS_application_name),
Austin Schuh15649d62019-12-28 16:36:38 -080083 node_(MaybeMyNode(configuration)) {
Austin Schuh094d09b2020-11-20 23:26:52 -080084 CHECK(IsInitialized()) << ": Need to initialize AOS first.";
Austin Schuh0debde12022-08-17 16:25:17 -070085 ClearContext();
Austin Schuh15649d62019-12-28 16:36:38 -080086 if (configuration->has_nodes()) {
87 CHECK(node_ != nullptr) << ": Couldn't find node in config.";
88 }
89}
Austin Schuh217a9782019-12-21 23:02:50 -080090
Brian Silverman148d43d2020-06-07 18:19:22 -050091namespace shm_event_loop_internal {
Austin Schuh39788ff2019-12-01 18:22:57 -080092
93class SimpleShmFetcher {
Alex Perrycb7da4b2019-08-28 19:35:56 -070094 public:
Austin Schuhef323c02020-09-01 14:55:28 -070095 explicit SimpleShmFetcher(std::string_view shm_base, ShmEventLoop *event_loop,
96 const Channel *channel)
Austin Schuh432784f2020-06-23 17:27:35 -070097 : event_loop_(event_loop),
98 channel_(channel),
Austin Schuh4d275fc2022-09-16 15:42:45 -070099 lockless_queue_memory_(shm_base, FLAGS_permissions,
100 event_loop->configuration(), channel),
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700101 reader_(lockless_queue_memory_.queue()) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700102 context_.data = nullptr;
103 // Point the queue index at the next index to read starting now. This
104 // makes it such that FetchNext will read the next message sent after
105 // the fetcher is created.
106 PointAtNextQueueIndex();
107 }
108
Austin Schuh39788ff2019-12-01 18:22:57 -0800109 ~SimpleShmFetcher() {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700110
Brian Silverman77162972020-08-12 19:52:40 -0700111 // Sets this object to pin or copy data, as configured in the channel.
112 void RetrieveData() {
113 if (channel_->read_method() == ReadMethod::PIN) {
114 PinDataOnFetch();
115 } else {
116 CopyDataOnFetch();
117 }
118 }
119
Brian Silverman3bca5322020-08-12 19:35:29 -0700120 // Sets this object to copy data out of the shared memory into a private
121 // buffer when fetching.
122 void CopyDataOnFetch() {
Brian Silverman77162972020-08-12 19:52:40 -0700123 CHECK(!pin_data());
Brian Silverman3bca5322020-08-12 19:35:29 -0700124 data_storage_.reset(static_cast<char *>(
125 malloc(channel_->max_size() + kChannelDataAlignment - 1)));
126 }
127
Brian Silverman77162972020-08-12 19:52:40 -0700128 // Sets this object to pin data in shared memory when fetching.
129 void PinDataOnFetch() {
130 CHECK(!copy_data());
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700131 auto maybe_pinner =
132 ipc_lib::LocklessQueuePinner::Make(lockless_queue_memory_.queue());
Brian Silverman77162972020-08-12 19:52:40 -0700133 if (!maybe_pinner) {
134 LOG(FATAL) << "Failed to create reader on "
135 << configuration::CleanedChannelToString(channel_)
136 << ", too many readers.";
137 }
138 pinner_ = std::move(maybe_pinner.value());
139 }
140
Alex Perrycb7da4b2019-08-28 19:35:56 -0700141 // Points the next message to fetch at the queue index which will be
142 // populated next.
143 void PointAtNextQueueIndex() {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700144 actual_queue_index_ = reader_.LatestIndex();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700145 if (!actual_queue_index_.valid()) {
146 // Nothing in the queue. The next element will show up at the 0th
147 // index in the queue.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700148 actual_queue_index_ = ipc_lib::QueueIndex::Zero(
149 LocklessQueueSize(lockless_queue_memory_.memory()));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700150 } else {
151 actual_queue_index_ = actual_queue_index_.Increment();
152 }
153 }
154
Austin Schuh39788ff2019-12-01 18:22:57 -0800155 bool FetchNext() {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700156 const ipc_lib::LocklessQueueReader::Result read_result =
Brian Silverman3bca5322020-08-12 19:35:29 -0700157 DoFetch(actual_queue_index_);
Austin Schuh432784f2020-06-23 17:27:35 -0700158
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700159 return read_result == ipc_lib::LocklessQueueReader::Result::GOOD;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700160 }
161
Austin Schuh39788ff2019-12-01 18:22:57 -0800162 bool Fetch() {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700163 const ipc_lib::QueueIndex queue_index = reader_.LatestIndex();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700164 // actual_queue_index_ is only meaningful if it was set by Fetch or
165 // FetchNext. This happens when valid_data_ has been set. So, only
166 // skip checking if valid_data_ is true.
167 //
168 // Also, if the latest queue index is invalid, we are empty. So there
169 // is nothing to fetch.
Austin Schuh39788ff2019-12-01 18:22:57 -0800170 if ((context_.data != nullptr &&
Alex Perrycb7da4b2019-08-28 19:35:56 -0700171 queue_index == actual_queue_index_.DecrementBy(1u)) ||
172 !queue_index.valid()) {
173 return false;
174 }
175
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700176 const ipc_lib::LocklessQueueReader::Result read_result =
177 DoFetch(queue_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700178
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700179 CHECK(read_result != ipc_lib::LocklessQueueReader::Result::NOTHING_NEW)
Austin Schuhf5652592019-12-29 16:26:15 -0800180 << ": Queue index went backwards. This should never happen. "
181 << configuration::CleanedChannelToString(channel_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700182
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700183 return read_result == ipc_lib::LocklessQueueReader::Result::GOOD;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700184 }
185
Austin Schuh39788ff2019-12-01 18:22:57 -0800186 Context context() const { return context_; }
187
Alex Perrycb7da4b2019-08-28 19:35:56 -0700188 bool RegisterWakeup(int priority) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700189 CHECK(!watcher_);
190 watcher_ = ipc_lib::LocklessQueueWatcher::Make(
191 lockless_queue_memory_.queue(), priority);
192 return static_cast<bool>(watcher_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700193 }
194
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700195 void UnregisterWakeup() {
196 CHECK(watcher_);
197 watcher_ = std::nullopt;
198 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700199
Brian Silvermana5450a92020-08-12 19:59:57 -0700200 absl::Span<char> GetMutableSharedMemory() {
201 return lockless_queue_memory_.GetMutableSharedMemory();
Brian Silverman5120afb2020-01-31 17:44:35 -0800202 }
203
Brian Silvermana5450a92020-08-12 19:59:57 -0700204 absl::Span<const char> GetConstSharedMemory() const {
205 return lockless_queue_memory_.GetConstSharedMemory();
206 }
207
208 absl::Span<const char> GetPrivateMemory() const {
209 if (pin_data()) {
210 return lockless_queue_memory_.GetConstSharedMemory();
211 }
Brian Silverman6d2b3592020-06-18 14:40:15 -0700212 return absl::Span<char>(
213 const_cast<SimpleShmFetcher *>(this)->data_storage_start(),
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700214 LocklessQueueMessageDataSize(lockless_queue_memory_.memory()));
Brian Silverman6d2b3592020-06-18 14:40:15 -0700215 }
216
Alex Perrycb7da4b2019-08-28 19:35:56 -0700217 private:
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700218 ipc_lib::LocklessQueueReader::Result DoFetch(
219 ipc_lib::QueueIndex queue_index) {
Brian Silverman3bca5322020-08-12 19:35:29 -0700220 // TODO(austin): Get behind and make sure it dies.
221 char *copy_buffer = nullptr;
222 if (copy_data()) {
223 copy_buffer = data_storage_start();
224 }
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700225 ipc_lib::LocklessQueueReader::Result read_result = reader_.Read(
Brian Silverman3bca5322020-08-12 19:35:29 -0700226 queue_index.index(), &context_.monotonic_event_time,
227 &context_.realtime_event_time, &context_.monotonic_remote_time,
228 &context_.realtime_remote_time, &context_.remote_queue_index,
Austin Schuha9012be2021-07-21 15:19:11 -0700229 &context_.source_boot_uuid, &context_.size, copy_buffer);
Brian Silverman3bca5322020-08-12 19:35:29 -0700230
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700231 if (read_result == ipc_lib::LocklessQueueReader::Result::GOOD) {
Brian Silverman77162972020-08-12 19:52:40 -0700232 if (pin_data()) {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700233 const int pin_result = pinner_->PinIndex(queue_index.index());
234 CHECK(pin_result >= 0)
Brian Silverman77162972020-08-12 19:52:40 -0700235 << ": Got behind while reading and the last message was modified "
236 "out from under us while we tried to pin it. Don't get so far "
237 "behind on: "
238 << configuration::CleanedChannelToString(channel_);
Brian Silverman4f4e0612020-08-12 19:54:41 -0700239 context_.buffer_index = pin_result;
240 } else {
241 context_.buffer_index = -1;
Brian Silverman77162972020-08-12 19:52:40 -0700242 }
243
Brian Silverman3bca5322020-08-12 19:35:29 -0700244 context_.queue_index = queue_index.index();
245 if (context_.remote_queue_index == 0xffffffffu) {
246 context_.remote_queue_index = context_.queue_index;
247 }
248 if (context_.monotonic_remote_time == aos::monotonic_clock::min_time) {
249 context_.monotonic_remote_time = context_.monotonic_event_time;
250 }
251 if (context_.realtime_remote_time == aos::realtime_clock::min_time) {
252 context_.realtime_remote_time = context_.realtime_event_time;
253 }
254 const char *const data = DataBuffer();
255 if (data) {
256 context_.data =
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700257 data +
258 LocklessQueueMessageDataSize(lockless_queue_memory_.memory()) -
259 context_.size;
Brian Silverman3bca5322020-08-12 19:35:29 -0700260 } else {
261 context_.data = nullptr;
262 }
263 actual_queue_index_ = queue_index.Increment();
264 }
265
266 // Make sure the data wasn't modified while we were reading it. This
267 // can only happen if you are reading the last message *while* it is
268 // being written to, which means you are pretty far behind.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700269 CHECK(read_result != ipc_lib::LocklessQueueReader::Result::OVERWROTE)
Brian Silverman3bca5322020-08-12 19:35:29 -0700270 << ": Got behind while reading and the last message was modified "
271 "out from under us while we were reading it. Don't get so far "
272 "behind on: "
273 << configuration::CleanedChannelToString(channel_);
274
275 // We fell behind between when we read the index and read the value.
276 // This isn't worth recovering from since this means we went to sleep
277 // for a long time in the middle of this function.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700278 if (read_result == ipc_lib::LocklessQueueReader::Result::TOO_OLD) {
Brian Silverman3bca5322020-08-12 19:35:29 -0700279 event_loop_->SendTimingReport();
280 LOG(FATAL) << "The next message is no longer available. "
281 << configuration::CleanedChannelToString(channel_);
282 }
283
284 return read_result;
285 }
286
287 char *data_storage_start() const {
288 CHECK(copy_data());
Brian Silvermana1652f32020-01-29 20:41:44 -0800289 return RoundChannelData(data_storage_.get(), channel_->max_size());
290 }
Brian Silverman3bca5322020-08-12 19:35:29 -0700291
292 // Note that for some modes the return value will change as new messages are
293 // read.
294 const char *DataBuffer() const {
295 if (copy_data()) {
296 return data_storage_start();
297 }
Brian Silverman77162972020-08-12 19:52:40 -0700298 if (pin_data()) {
299 return static_cast<const char *>(pinner_->Data());
300 }
Brian Silverman3bca5322020-08-12 19:35:29 -0700301 return nullptr;
302 }
303
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800304 bool copy_data() const { return static_cast<bool>(data_storage_); }
Brian Silverman77162972020-08-12 19:52:40 -0700305 bool pin_data() const { return static_cast<bool>(pinner_); }
Brian Silvermana1652f32020-01-29 20:41:44 -0800306
Austin Schuh432784f2020-06-23 17:27:35 -0700307 aos::ShmEventLoop *event_loop_;
Austin Schuhf5652592019-12-29 16:26:15 -0800308 const Channel *const channel_;
Austin Schuh4d275fc2022-09-16 15:42:45 -0700309 ipc_lib::MemoryMappedQueue lockless_queue_memory_;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700310 ipc_lib::LocklessQueueReader reader_;
311 // This being nullopt indicates we're not looking for wakeups right now.
312 std::optional<ipc_lib::LocklessQueueWatcher> watcher_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700313
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700314 ipc_lib::QueueIndex actual_queue_index_ = ipc_lib::QueueIndex::Invalid();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700315
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800316 // This being empty indicates we're not going to copy data.
317 std::unique_ptr<char, decltype(&free)> data_storage_{nullptr, &free};
Austin Schuh39788ff2019-12-01 18:22:57 -0800318
Brian Silverman77162972020-08-12 19:52:40 -0700319 // This being nullopt indicates we're not going to pin messages.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700320 std::optional<ipc_lib::LocklessQueuePinner> pinner_;
Brian Silverman77162972020-08-12 19:52:40 -0700321
Austin Schuh39788ff2019-12-01 18:22:57 -0800322 Context context_;
323};
324
325class ShmFetcher : public RawFetcher {
326 public:
Austin Schuhef323c02020-09-01 14:55:28 -0700327 explicit ShmFetcher(std::string_view shm_base, ShmEventLoop *event_loop,
328 const Channel *channel)
Austin Schuhaa79e4e2019-12-29 20:43:32 -0800329 : RawFetcher(event_loop, channel),
Austin Schuhef323c02020-09-01 14:55:28 -0700330 simple_shm_fetcher_(shm_base, event_loop, channel) {
Brian Silverman77162972020-08-12 19:52:40 -0700331 simple_shm_fetcher_.RetrieveData();
Brian Silverman3bca5322020-08-12 19:35:29 -0700332 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800333
Austin Schuh3054f5f2021-07-21 15:38:01 -0700334 ~ShmFetcher() override {
335 shm_event_loop()->CheckCurrentThread();
336 context_.data = nullptr;
337 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800338
339 std::pair<bool, monotonic_clock::time_point> DoFetchNext() override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700340 shm_event_loop()->CheckCurrentThread();
Austin Schuh39788ff2019-12-01 18:22:57 -0800341 if (simple_shm_fetcher_.FetchNext()) {
342 context_ = simple_shm_fetcher_.context();
343 return std::make_pair(true, monotonic_clock::now());
344 }
345 return std::make_pair(false, monotonic_clock::min_time);
346 }
347
348 std::pair<bool, monotonic_clock::time_point> DoFetch() override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700349 shm_event_loop()->CheckCurrentThread();
Austin Schuh39788ff2019-12-01 18:22:57 -0800350 if (simple_shm_fetcher_.Fetch()) {
351 context_ = simple_shm_fetcher_.context();
352 return std::make_pair(true, monotonic_clock::now());
353 }
354 return std::make_pair(false, monotonic_clock::min_time);
355 }
356
Brian Silvermana5450a92020-08-12 19:59:57 -0700357 absl::Span<const char> GetPrivateMemory() const {
Brian Silverman6d2b3592020-06-18 14:40:15 -0700358 return simple_shm_fetcher_.GetPrivateMemory();
359 }
360
Austin Schuh39788ff2019-12-01 18:22:57 -0800361 private:
Austin Schuh3054f5f2021-07-21 15:38:01 -0700362 const ShmEventLoop *shm_event_loop() const {
363 return static_cast<const ShmEventLoop *>(event_loop());
364 }
365
Austin Schuh39788ff2019-12-01 18:22:57 -0800366 SimpleShmFetcher simple_shm_fetcher_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700367};
368
Brian Silvermane1fe2512022-08-14 23:18:50 -0700369class ShmExitHandle : public ExitHandle {
370 public:
371 ShmExitHandle(ShmEventLoop *event_loop) : event_loop_(event_loop) {
372 ++event_loop_->exit_handle_count_;
373 }
374 ~ShmExitHandle() override {
375 CHECK_GT(event_loop_->exit_handle_count_, 0);
376 --event_loop_->exit_handle_count_;
377 }
378
379 void Exit() override { event_loop_->Exit(); }
380
381 private:
382 ShmEventLoop *const event_loop_;
383};
384
Alex Perrycb7da4b2019-08-28 19:35:56 -0700385class ShmSender : public RawSender {
386 public:
Austin Schuhef323c02020-09-01 14:55:28 -0700387 explicit ShmSender(std::string_view shm_base, EventLoop *event_loop,
388 const Channel *channel)
Austin Schuh39788ff2019-12-01 18:22:57 -0800389 : RawSender(event_loop, channel),
Austin Schuh4d275fc2022-09-16 15:42:45 -0700390 lockless_queue_memory_(shm_base, FLAGS_permissions,
391 event_loop->configuration(), channel),
Austin Schuhfff9c3a2023-06-16 18:48:23 -0700392 lockless_queue_sender_(
393 VerifySender(ipc_lib::LocklessQueueSender::Make(
394 lockless_queue_memory_.queue(),
395 configuration::ChannelStorageDuration(
396 event_loop->configuration(), channel)),
397 channel)),
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700398 wake_upper_(lockless_queue_memory_.queue()) {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700399
Austin Schuh3054f5f2021-07-21 15:38:01 -0700400 ~ShmSender() override { shm_event_loop()->CheckCurrentThread(); }
Austin Schuh39788ff2019-12-01 18:22:57 -0800401
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700402 static ipc_lib::LocklessQueueSender VerifySender(
403 std::optional<ipc_lib::LocklessQueueSender> sender,
Austin Schuhe516ab02020-05-06 21:37:04 -0700404 const Channel *channel) {
405 if (sender) {
406 return std::move(sender.value());
407 }
408 LOG(FATAL) << "Failed to create sender on "
409 << configuration::CleanedChannelToString(channel)
410 << ", too many senders.";
411 }
412
Austin Schuh3054f5f2021-07-21 15:38:01 -0700413 void *data() override {
414 shm_event_loop()->CheckCurrentThread();
415 return lockless_queue_sender_.Data();
416 }
417 size_t size() override {
418 shm_event_loop()->CheckCurrentThread();
419 return lockless_queue_sender_.size();
420 }
milind1f1dca32021-07-03 13:50:07 -0700421
422 Error DoSend(size_t length,
423 aos::monotonic_clock::time_point monotonic_remote_time,
424 aos::realtime_clock::time_point realtime_remote_time,
425 uint32_t remote_queue_index,
426 const UUID &source_boot_uuid) override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700427 shm_event_loop()->CheckCurrentThread();
Austin Schuh0f7ed462020-03-28 20:38:34 -0700428 CHECK_LE(length, static_cast<size_t>(channel()->max_size()))
429 << ": Sent too big a message on "
430 << configuration::CleanedChannelToString(channel());
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700431 const auto result = lockless_queue_sender_.Send(
432 length, monotonic_remote_time, realtime_remote_time, remote_queue_index,
433 source_boot_uuid, &monotonic_sent_time_, &realtime_sent_time_,
434 &sent_queue_index_);
435 CHECK_NE(result, ipc_lib::LocklessQueueSender::Result::INVALID_REDZONE)
Austin Schuh91ba6392020-10-03 13:27:47 -0700436 << ": Somebody wrote outside the buffer of their message on channel "
437 << configuration::CleanedChannelToString(channel());
438
Austin Schuh65493d62022-08-17 15:10:37 -0700439 wake_upper_.Wakeup(event_loop()->is_running()
440 ? event_loop()->runtime_realtime_priority()
441 : 0);
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700442 return CheckLocklessQueueResult(result);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700443 }
444
milind1f1dca32021-07-03 13:50:07 -0700445 Error DoSend(const void *msg, size_t length,
446 aos::monotonic_clock::time_point monotonic_remote_time,
447 aos::realtime_clock::time_point realtime_remote_time,
448 uint32_t remote_queue_index,
449 const UUID &source_boot_uuid) override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700450 shm_event_loop()->CheckCurrentThread();
Austin Schuh0f7ed462020-03-28 20:38:34 -0700451 CHECK_LE(length, static_cast<size_t>(channel()->max_size()))
452 << ": Sent too big a message on "
453 << configuration::CleanedChannelToString(channel());
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700454 const auto result = lockless_queue_sender_.Send(
Brian Silvermanaf9a4d82020-10-06 15:10:58 -0700455 reinterpret_cast<const char *>(msg), length, monotonic_remote_time,
Austin Schuha9012be2021-07-21 15:19:11 -0700456 realtime_remote_time, remote_queue_index, source_boot_uuid,
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700457 &monotonic_sent_time_, &realtime_sent_time_, &sent_queue_index_);
458
459 CHECK_NE(result, ipc_lib::LocklessQueueSender::Result::INVALID_REDZONE)
460 << ": Somebody wrote outside the buffer of their message on "
461 "channel "
Austin Schuh91ba6392020-10-03 13:27:47 -0700462 << configuration::CleanedChannelToString(channel());
Austin Schuh65493d62022-08-17 15:10:37 -0700463 wake_upper_.Wakeup(event_loop()->is_running()
464 ? event_loop()->runtime_realtime_priority()
465 : 0);
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700466
467 return CheckLocklessQueueResult(result);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700468 }
469
Brian Silverman5120afb2020-01-31 17:44:35 -0800470 absl::Span<char> GetSharedMemory() const {
Brian Silvermana5450a92020-08-12 19:59:57 -0700471 return lockless_queue_memory_.GetMutableSharedMemory();
Brian Silverman5120afb2020-01-31 17:44:35 -0800472 }
473
Austin Schuh3054f5f2021-07-21 15:38:01 -0700474 int buffer_index() override {
475 shm_event_loop()->CheckCurrentThread();
476 return lockless_queue_sender_.buffer_index();
477 }
Brian Silverman4f4e0612020-08-12 19:54:41 -0700478
Alex Perrycb7da4b2019-08-28 19:35:56 -0700479 private:
Austin Schuh3054f5f2021-07-21 15:38:01 -0700480 const ShmEventLoop *shm_event_loop() const {
481 return static_cast<const ShmEventLoop *>(event_loop());
482 }
483
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700484 RawSender::Error CheckLocklessQueueResult(
485 const ipc_lib::LocklessQueueSender::Result &result) {
486 switch (result) {
487 case ipc_lib::LocklessQueueSender::Result::GOOD:
488 return Error::kOk;
489 case ipc_lib::LocklessQueueSender::Result::MESSAGES_SENT_TOO_FAST:
490 return Error::kMessagesSentTooFast;
491 case ipc_lib::LocklessQueueSender::Result::INVALID_REDZONE:
492 return Error::kInvalidRedzone;
493 }
494 LOG(FATAL) << "Unknown lockless queue sender result"
495 << static_cast<int>(result);
496 }
497
Austin Schuh4d275fc2022-09-16 15:42:45 -0700498 ipc_lib::MemoryMappedQueue lockless_queue_memory_;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700499 ipc_lib::LocklessQueueSender lockless_queue_sender_;
500 ipc_lib::LocklessQueueWakeUpper wake_upper_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700501};
502
Alex Perrycb7da4b2019-08-28 19:35:56 -0700503// Class to manage the state for a Watcher.
Brian Silverman148d43d2020-06-07 18:19:22 -0500504class ShmWatcherState : public WatcherState {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700505 public:
Brian Silverman148d43d2020-06-07 18:19:22 -0500506 ShmWatcherState(
Austin Schuhef323c02020-09-01 14:55:28 -0700507 std::string_view shm_base, ShmEventLoop *event_loop,
508 const Channel *channel,
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800509 std::function<void(const Context &context, const void *message)> fn,
510 bool copy_data)
Brian Silverman148d43d2020-06-07 18:19:22 -0500511 : WatcherState(event_loop, channel, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800512 event_loop_(event_loop),
513 event_(this),
Austin Schuhef323c02020-09-01 14:55:28 -0700514 simple_shm_fetcher_(shm_base, event_loop, channel) {
Brian Silverman3bca5322020-08-12 19:35:29 -0700515 if (copy_data) {
Brian Silverman77162972020-08-12 19:52:40 -0700516 simple_shm_fetcher_.RetrieveData();
Brian Silverman3bca5322020-08-12 19:35:29 -0700517 }
518 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700519
Austin Schuh3054f5f2021-07-21 15:38:01 -0700520 ~ShmWatcherState() override {
521 event_loop_->CheckCurrentThread();
522 event_loop_->RemoveEvent(&event_);
523 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800524
525 void Startup(EventLoop *event_loop) override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700526 event_loop_->CheckCurrentThread();
Austin Schuh7d87b672019-12-01 20:23:49 -0800527 simple_shm_fetcher_.PointAtNextQueueIndex();
Austin Schuh65493d62022-08-17 15:10:37 -0700528 CHECK(RegisterWakeup(event_loop->runtime_realtime_priority()));
Austin Schuh39788ff2019-12-01 18:22:57 -0800529 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700530
Alex Perrycb7da4b2019-08-28 19:35:56 -0700531 // Returns true if there is new data available.
Austin Schuh7d87b672019-12-01 20:23:49 -0800532 bool CheckForNewData() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700533 if (!has_new_data_) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800534 has_new_data_ = simple_shm_fetcher_.FetchNext();
Austin Schuh7d87b672019-12-01 20:23:49 -0800535
536 if (has_new_data_) {
537 event_.set_event_time(
Austin Schuhad154822019-12-27 15:45:13 -0800538 simple_shm_fetcher_.context().monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800539 event_loop_->AddEvent(&event_);
540 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700541 }
542
543 return has_new_data_;
544 }
545
Alex Perrycb7da4b2019-08-28 19:35:56 -0700546 // Consumes the data by calling the callback.
Austin Schuh7d87b672019-12-01 20:23:49 -0800547 void HandleEvent() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700548 CHECK(has_new_data_);
Austin Schuh39788ff2019-12-01 18:22:57 -0800549 DoCallCallback(monotonic_clock::now, simple_shm_fetcher_.context());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700550 has_new_data_ = false;
Austin Schuh7d87b672019-12-01 20:23:49 -0800551 CheckForNewData();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700552 }
553
Austin Schuh39788ff2019-12-01 18:22:57 -0800554 // Registers us to receive a signal on event reception.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700555 bool RegisterWakeup(int priority) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800556 return simple_shm_fetcher_.RegisterWakeup(priority);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700557 }
558
Austin Schuh39788ff2019-12-01 18:22:57 -0800559 void UnregisterWakeup() { return simple_shm_fetcher_.UnregisterWakeup(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700560
Brian Silvermana5450a92020-08-12 19:59:57 -0700561 absl::Span<const char> GetSharedMemory() const {
562 return simple_shm_fetcher_.GetConstSharedMemory();
Brian Silverman5120afb2020-01-31 17:44:35 -0800563 }
564
Alex Perrycb7da4b2019-08-28 19:35:56 -0700565 private:
566 bool has_new_data_ = false;
567
Austin Schuh7d87b672019-12-01 20:23:49 -0800568 ShmEventLoop *event_loop_;
Brian Silverman148d43d2020-06-07 18:19:22 -0500569 EventHandler<ShmWatcherState> event_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800570 SimpleShmFetcher simple_shm_fetcher_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700571};
572
573// Adapter class to adapt a timerfd to a TimerHandler.
Brian Silverman148d43d2020-06-07 18:19:22 -0500574class ShmTimerHandler final : public TimerHandler {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700575 public:
Brian Silverman148d43d2020-06-07 18:19:22 -0500576 ShmTimerHandler(ShmEventLoop *shm_event_loop, ::std::function<void()> fn)
Austin Schuh39788ff2019-12-01 18:22:57 -0800577 : TimerHandler(shm_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800578 shm_event_loop_(shm_event_loop),
579 event_(this) {
Austin Schuhcde39fd2020-02-22 20:58:24 -0800580 shm_event_loop_->epoll_.OnReadable(timerfd_.fd(), [this]() {
Austin Schuh5ca13112021-02-07 22:06:53 -0800581 // The timer may fire spuriously. HandleEvent on the event loop will
Austin Schuhcde39fd2020-02-22 20:58:24 -0800582 // call the callback if it is needed. It may also have called it when
583 // processing some other event, and the kernel decided to deliver this
584 // wakeup anyways.
585 timerfd_.Read();
586 shm_event_loop_->HandleEvent();
587 });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700588 }
589
Brian Silverman148d43d2020-06-07 18:19:22 -0500590 ~ShmTimerHandler() {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700591 shm_event_loop_->CheckCurrentThread();
Austin Schuh7d87b672019-12-01 20:23:49 -0800592 Disable();
593 shm_event_loop_->epoll_.DeleteFd(timerfd_.fd());
594 }
595
596 void HandleEvent() {
Austin Schuhcde39fd2020-02-22 20:58:24 -0800597 CHECK(!event_.valid());
Brian Silvermanaf9a4d82020-10-06 15:10:58 -0700598 disabled_ = false;
Austin Schuhcde39fd2020-02-22 20:58:24 -0800599 const auto monotonic_now = Call(monotonic_clock::now, base_);
600 if (event_.valid()) {
Philipp Schradera6712522023-07-05 20:25:11 -0700601 // If someone called Schedule inside Call, rescheduling is already taken
602 // care of. Bail.
Austin Schuhcde39fd2020-02-22 20:58:24 -0800603 return;
Austin Schuh7d87b672019-12-01 20:23:49 -0800604 }
Brian Silvermanaf9a4d82020-10-06 15:10:58 -0700605 if (disabled_) {
606 // Somebody called Disable inside Call, so we don't want to reschedule.
607 // Bail.
608 return;
609 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800610
Austin Schuh4d275fc2022-09-16 15:42:45 -0700611 if (repeat_offset_ == std::chrono::seconds(0)) {
Austin Schuhcde39fd2020-02-22 20:58:24 -0800612 timerfd_.Disable();
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700613 disabled_ = true;
Austin Schuhcde39fd2020-02-22 20:58:24 -0800614 } else {
615 // Compute how many cycles have elapsed and schedule the next iteration
616 // for the next iteration in the future.
617 const int elapsed_cycles =
618 std::max<int>(0, (monotonic_now - base_ + repeat_offset_ -
619 std::chrono::nanoseconds(1)) /
620 repeat_offset_);
621 base_ += repeat_offset_ * elapsed_cycles;
Austin Schuh7d87b672019-12-01 20:23:49 -0800622
Austin Schuhcde39fd2020-02-22 20:58:24 -0800623 // Update the heap and schedule the timerfd wakeup.
Austin Schuh7d87b672019-12-01 20:23:49 -0800624 event_.set_event_time(base_);
625 shm_event_loop_->AddEvent(&event_);
Austin Schuh4d275fc2022-09-16 15:42:45 -0700626 timerfd_.SetTime(base_, std::chrono::seconds(0));
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700627 disabled_ = false;
Austin Schuh7d87b672019-12-01 20:23:49 -0800628 }
629 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700630
Philipp Schradera6712522023-07-05 20:25:11 -0700631 void Schedule(monotonic_clock::time_point base,
632 monotonic_clock::duration repeat_offset) override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700633 shm_event_loop_->CheckCurrentThread();
Austin Schuh7d87b672019-12-01 20:23:49 -0800634 if (event_.valid()) {
635 shm_event_loop_->RemoveEvent(&event_);
636 }
637
Alex Perrycb7da4b2019-08-28 19:35:56 -0700638 timerfd_.SetTime(base, repeat_offset);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800639 base_ = base;
640 repeat_offset_ = repeat_offset;
Austin Schuh7d87b672019-12-01 20:23:49 -0800641 event_.set_event_time(base_);
642 shm_event_loop_->AddEvent(&event_);
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700643 disabled_ = false;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700644 }
645
Austin Schuh7d87b672019-12-01 20:23:49 -0800646 void Disable() override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700647 shm_event_loop_->CheckCurrentThread();
Austin Schuh7d87b672019-12-01 20:23:49 -0800648 shm_event_loop_->RemoveEvent(&event_);
649 timerfd_.Disable();
Brian Silvermanaf9a4d82020-10-06 15:10:58 -0700650 disabled_ = true;
Austin Schuh7d87b672019-12-01 20:23:49 -0800651 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700652
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700653 bool IsDisabled() override { return disabled_; }
654
Alex Perrycb7da4b2019-08-28 19:35:56 -0700655 private:
656 ShmEventLoop *shm_event_loop_;
Brian Silverman148d43d2020-06-07 18:19:22 -0500657 EventHandler<ShmTimerHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700658
Brian Silverman148d43d2020-06-07 18:19:22 -0500659 internal::TimerFd timerfd_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700660
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800661 monotonic_clock::time_point base_;
662 monotonic_clock::duration repeat_offset_;
Brian Silvermanaf9a4d82020-10-06 15:10:58 -0700663
664 // Used to track if Disable() was called during the callback, so we know not
665 // to reschedule.
Naman Gupta4d13b0a2022-10-19 16:41:24 -0700666 bool disabled_ = true;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700667};
668
669// Adapter class to the timerfd and PhasedLoop.
Brian Silverman148d43d2020-06-07 18:19:22 -0500670class ShmPhasedLoopHandler final : public PhasedLoopHandler {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700671 public:
Brian Silverman148d43d2020-06-07 18:19:22 -0500672 ShmPhasedLoopHandler(ShmEventLoop *shm_event_loop,
673 ::std::function<void(int)> fn,
674 const monotonic_clock::duration interval,
675 const monotonic_clock::duration offset)
676 : PhasedLoopHandler(shm_event_loop, std::move(fn), interval, offset),
Austin Schuh7d87b672019-12-01 20:23:49 -0800677 shm_event_loop_(shm_event_loop),
678 event_(this) {
679 shm_event_loop_->epoll_.OnReadable(
680 timerfd_.fd(), [this]() { shm_event_loop_->HandleEvent(); });
681 }
682
683 void HandleEvent() {
684 // The return value for read is the number of cycles that have elapsed.
685 // Because we check to see when this event *should* have happened, there are
686 // cases where Read() will return 0, when 1 cycle has actually happened.
687 // This occurs when the timer interrupt hasn't triggered yet. Therefore,
688 // ignore it. Call handles rescheduling and calculating elapsed cycles
689 // without any extra help.
690 timerfd_.Read();
691 event_.Invalidate();
692
James Kuszmaul20dcc7c2023-01-20 11:06:31 -0800693 Call(monotonic_clock::now);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700694 }
695
Brian Silverman148d43d2020-06-07 18:19:22 -0500696 ~ShmPhasedLoopHandler() override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700697 shm_event_loop_->CheckCurrentThread();
Austin Schuh39788ff2019-12-01 18:22:57 -0800698 shm_event_loop_->epoll_.DeleteFd(timerfd_.fd());
Austin Schuh7d87b672019-12-01 20:23:49 -0800699 shm_event_loop_->RemoveEvent(&event_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700700 }
701
702 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800703 // Reschedules the timer.
Austin Schuh39788ff2019-12-01 18:22:57 -0800704 void Schedule(monotonic_clock::time_point sleep_time) override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700705 shm_event_loop_->CheckCurrentThread();
Austin Schuh7d87b672019-12-01 20:23:49 -0800706 if (event_.valid()) {
707 shm_event_loop_->RemoveEvent(&event_);
708 }
709
Austin Schuh39788ff2019-12-01 18:22:57 -0800710 timerfd_.SetTime(sleep_time, ::aos::monotonic_clock::zero());
Austin Schuh7d87b672019-12-01 20:23:49 -0800711 event_.set_event_time(sleep_time);
712 shm_event_loop_->AddEvent(&event_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700713 }
714
715 ShmEventLoop *shm_event_loop_;
Brian Silverman148d43d2020-06-07 18:19:22 -0500716 EventHandler<ShmPhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700717
Brian Silverman148d43d2020-06-07 18:19:22 -0500718 internal::TimerFd timerfd_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700719};
Brian Silverman148d43d2020-06-07 18:19:22 -0500720
721} // namespace shm_event_loop_internal
Alex Perrycb7da4b2019-08-28 19:35:56 -0700722
723::std::unique_ptr<RawFetcher> ShmEventLoop::MakeRawFetcher(
724 const Channel *channel) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700725 CheckCurrentThread();
Austin Schuhca4828c2019-12-28 14:21:35 -0800726 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
727 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
728 << "\", \"type\": \"" << channel->type()->string_view()
729 << "\" } is not able to be fetched on this node. Check your "
730 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800731 }
732
Austin Schuhef323c02020-09-01 14:55:28 -0700733 return ::std::unique_ptr<RawFetcher>(
734 new ShmFetcher(shm_base_, this, channel));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700735}
736
737::std::unique_ptr<RawSender> ShmEventLoop::MakeRawSender(
738 const Channel *channel) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700739 CheckCurrentThread();
Brian Silverman0fc69932020-01-24 21:54:02 -0800740 TakeSender(channel);
Austin Schuh39788ff2019-12-01 18:22:57 -0800741
Austin Schuhef323c02020-09-01 14:55:28 -0700742 return ::std::unique_ptr<RawSender>(new ShmSender(shm_base_, this, channel));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700743}
744
745void ShmEventLoop::MakeRawWatcher(
746 const Channel *channel,
747 std::function<void(const Context &context, const void *message)> watcher) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700748 CheckCurrentThread();
Brian Silverman0fc69932020-01-24 21:54:02 -0800749 TakeWatcher(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800750
Austin Schuh39788ff2019-12-01 18:22:57 -0800751 NewWatcher(::std::unique_ptr<WatcherState>(
Austin Schuhef323c02020-09-01 14:55:28 -0700752 new ShmWatcherState(shm_base_, this, channel, std::move(watcher), true)));
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800753}
754
755void ShmEventLoop::MakeRawNoArgWatcher(
756 const Channel *channel,
757 std::function<void(const Context &context)> watcher) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700758 CheckCurrentThread();
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800759 TakeWatcher(channel);
760
Brian Silverman148d43d2020-06-07 18:19:22 -0500761 NewWatcher(::std::unique_ptr<WatcherState>(new ShmWatcherState(
Austin Schuhef323c02020-09-01 14:55:28 -0700762 shm_base_, this, channel,
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800763 [watcher](const Context &context, const void *) { watcher(context); },
764 false)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700765}
766
767TimerHandler *ShmEventLoop::AddTimer(::std::function<void()> callback) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700768 CheckCurrentThread();
Austin Schuh39788ff2019-12-01 18:22:57 -0800769 return NewTimer(::std::unique_ptr<TimerHandler>(
Brian Silverman148d43d2020-06-07 18:19:22 -0500770 new ShmTimerHandler(this, ::std::move(callback))));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700771}
772
773PhasedLoopHandler *ShmEventLoop::AddPhasedLoop(
774 ::std::function<void(int)> callback,
775 const monotonic_clock::duration interval,
776 const monotonic_clock::duration offset) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700777 CheckCurrentThread();
Brian Silverman148d43d2020-06-07 18:19:22 -0500778 return NewPhasedLoop(::std::unique_ptr<PhasedLoopHandler>(
779 new ShmPhasedLoopHandler(this, ::std::move(callback), interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700780}
781
782void ShmEventLoop::OnRun(::std::function<void()> on_run) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700783 CheckCurrentThread();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700784 on_run_.push_back(::std::move(on_run));
785}
786
Austin Schuh3054f5f2021-07-21 15:38:01 -0700787void ShmEventLoop::CheckCurrentThread() const {
788 if (__builtin_expect(check_mutex_ != nullptr, false)) {
789 CHECK(check_mutex_->is_locked())
790 << ": The configured mutex is not locked while calling a "
791 "ShmEventLoop function";
792 }
793 if (__builtin_expect(!!check_tid_, false)) {
794 CHECK_EQ(syscall(SYS_gettid), *check_tid_)
795 << ": Being called from the wrong thread";
796 }
797}
798
Austin Schuh5ca13112021-02-07 22:06:53 -0800799// This is a bit tricky because watchers can generate new events at any time (as
800// long as it's in the past). We want to check the watchers at least once before
801// declaring there are no events to handle, and we want to check them again if
802// event processing takes long enough that we find an event after that point in
803// time to handle.
Austin Schuh7d87b672019-12-01 20:23:49 -0800804void ShmEventLoop::HandleEvent() {
Austin Schuh5ca13112021-02-07 22:06:53 -0800805 // Time through which we've checked for new events in watchers.
806 monotonic_clock::time_point checked_until = monotonic_clock::min_time;
807 if (!signalfd_) {
808 // Nothing to check, so we can bail out immediately once we're out of
809 // events.
810 CHECK(watchers_.empty());
811 checked_until = monotonic_clock::max_time;
Austin Schuh7d87b672019-12-01 20:23:49 -0800812 }
813
Austin Schuh5ca13112021-02-07 22:06:53 -0800814 // Loop until we run out of events to check.
Austin Schuh39788ff2019-12-01 18:22:57 -0800815 while (true) {
Austin Schuh5ca13112021-02-07 22:06:53 -0800816 // Time of the next event we know about. If this is before checked_until, we
817 // know there aren't any new events before the next one that we already know
818 // about, so no need to check the watchers.
819 monotonic_clock::time_point next_time = monotonic_clock::max_time;
820
821 if (EventCount() == 0) {
822 if (checked_until != monotonic_clock::min_time) {
823 // No events, and we've already checked the watchers at least once, so
824 // we're all done.
825 //
826 // There's a small chance that a watcher has gotten another event in
827 // between checked_until and now. If so, then the signalfd will be
828 // triggered now and we'll re-enter HandleEvent immediately. This is
829 // unlikely though, so we don't want to spend time checking all the
830 // watchers unnecessarily.
831 break;
832 }
833 } else {
834 next_time = PeekEvent()->event_time();
835 }
Austin Schuh00cad2e2022-12-02 20:11:04 -0800836 monotonic_clock::time_point now;
837 bool new_data = false;
Austin Schuh5ca13112021-02-07 22:06:53 -0800838
839 if (next_time > checked_until) {
840 // Read all of the signals, because there's no point in waking up again
841 // immediately to handle each one if we've fallen behind.
842 //
843 // This is safe before checking for new data on the watchers. If a signal
844 // is cleared here, the corresponding CheckForNewData() call below will
845 // pick it up.
846 while (true) {
847 const signalfd_siginfo result = signalfd_->Read();
848 if (result.ssi_signo == 0) {
849 break;
850 }
851 CHECK_EQ(result.ssi_signo, ipc_lib::kWakeupSignal);
852 }
Austin Schuh00cad2e2022-12-02 20:11:04 -0800853 // This is the last time we can guarantee that if a message is published
854 // before, we will notice it.
855 now = monotonic_clock::now();
Austin Schuh5ca13112021-02-07 22:06:53 -0800856
857 // Check all the watchers for new events.
858 for (std::unique_ptr<WatcherState> &base_watcher : watchers_) {
859 ShmWatcherState *const watcher =
860 reinterpret_cast<ShmWatcherState *>(base_watcher.get());
861
Austin Schuh00cad2e2022-12-02 20:11:04 -0800862 // Track if we got a message.
863 if (watcher->CheckForNewData()) {
864 new_data = true;
865 }
Austin Schuh5ca13112021-02-07 22:06:53 -0800866 }
867 if (EventCount() == 0) {
868 // Still no events, all done now.
869 break;
870 }
871
872 checked_until = now;
873 // Check for any new events we found.
874 next_time = PeekEvent()->event_time();
Austin Schuh00cad2e2022-12-02 20:11:04 -0800875 } else {
876 now = monotonic_clock::now();
Austin Schuh5ca13112021-02-07 22:06:53 -0800877 }
878
879 if (next_time > now) {
Austin Schuh00cad2e2022-12-02 20:11:04 -0800880 // Ok, we got a message with a timestamp *after* we wrote down time. We
881 // need to process it (otherwise we will go to sleep without processing
882 // it), but we also need to make sure no other messages have come in
883 // before it that we would process out of order. Just go around again to
884 // redo the checks.
885 if (new_data) {
886 continue;
887 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800888 break;
889 }
890
Austin Schuh5ca13112021-02-07 22:06:53 -0800891 EventLoopEvent *const event = PopEvent();
Austin Schuh7d87b672019-12-01 20:23:49 -0800892 event->HandleEvent();
Austin Schuh39788ff2019-12-01 18:22:57 -0800893 }
894}
895
Austin Schuh32fd5a72019-12-01 22:20:26 -0800896// RAII class to mask signals.
897class ScopedSignalMask {
898 public:
899 ScopedSignalMask(std::initializer_list<int> signals) {
900 sigset_t sigset;
901 PCHECK(sigemptyset(&sigset) == 0);
902 for (int signal : signals) {
903 PCHECK(sigaddset(&sigset, signal) == 0);
904 }
905
906 PCHECK(sigprocmask(SIG_BLOCK, &sigset, &old_) == 0);
907 }
908
909 ~ScopedSignalMask() { PCHECK(sigprocmask(SIG_SETMASK, &old_, nullptr) == 0); }
910
911 private:
912 sigset_t old_;
913};
914
915// Class to manage the static state associated with killing multiple event
916// loops.
917class SignalHandler {
918 public:
919 // Gets the singleton.
920 static SignalHandler *global() {
921 static SignalHandler loop;
922 return &loop;
923 }
924
925 // Handles the signal with the singleton.
926 static void HandleSignal(int) { global()->DoHandleSignal(); }
927
928 // Registers an event loop to receive Exit() calls.
929 void Register(ShmEventLoop *event_loop) {
930 // Block signals while we have the mutex so we never race with the signal
931 // handler.
932 ScopedSignalMask mask({SIGINT, SIGHUP, SIGTERM});
933 std::unique_lock<stl_mutex> locker(mutex_);
934 if (event_loops_.size() == 0) {
935 // The first caller registers the signal handler.
936 struct sigaction new_action;
937 sigemptyset(&new_action.sa_mask);
938 // This makes it so that 2 control c's to a stuck process will kill it by
939 // restoring the original signal handler.
940 new_action.sa_flags = SA_RESETHAND;
941 new_action.sa_handler = &HandleSignal;
942
943 PCHECK(sigaction(SIGINT, &new_action, &old_action_int_) == 0);
944 PCHECK(sigaction(SIGHUP, &new_action, &old_action_hup_) == 0);
945 PCHECK(sigaction(SIGTERM, &new_action, &old_action_term_) == 0);
946 }
947
948 event_loops_.push_back(event_loop);
949 }
950
951 // Unregisters an event loop to receive Exit() calls.
952 void Unregister(ShmEventLoop *event_loop) {
953 // Block signals while we have the mutex so we never race with the signal
954 // handler.
955 ScopedSignalMask mask({SIGINT, SIGHUP, SIGTERM});
956 std::unique_lock<stl_mutex> locker(mutex_);
957
Brian Silverman5120afb2020-01-31 17:44:35 -0800958 event_loops_.erase(
959 std::find(event_loops_.begin(), event_loops_.end(), event_loop));
Austin Schuh32fd5a72019-12-01 22:20:26 -0800960
961 if (event_loops_.size() == 0u) {
962 // The last caller restores the original signal handlers.
963 PCHECK(sigaction(SIGINT, &old_action_int_, nullptr) == 0);
964 PCHECK(sigaction(SIGHUP, &old_action_hup_, nullptr) == 0);
965 PCHECK(sigaction(SIGTERM, &old_action_term_, nullptr) == 0);
966 }
967 }
968
969 private:
970 void DoHandleSignal() {
971 // We block signals while grabbing the lock, so there should never be a
972 // race. Confirm that this is true using trylock.
973 CHECK(mutex_.try_lock()) << ": sigprocmask failed to block signals while "
974 "modifing the event loop list.";
975 for (ShmEventLoop *event_loop : event_loops_) {
976 event_loop->Exit();
977 }
978 mutex_.unlock();
979 }
980
981 // Mutex to protect all state.
982 stl_mutex mutex_;
983 std::vector<ShmEventLoop *> event_loops_;
984 struct sigaction old_action_int_;
985 struct sigaction old_action_hup_;
986 struct sigaction old_action_term_;
987};
988
Alex Perrycb7da4b2019-08-28 19:35:56 -0700989void ShmEventLoop::Run() {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700990 CheckCurrentThread();
Austin Schuh32fd5a72019-12-01 22:20:26 -0800991 SignalHandler::global()->Register(this);
Austin Schuh39788ff2019-12-01 18:22:57 -0800992
Alex Perrycb7da4b2019-08-28 19:35:56 -0700993 if (watchers_.size() > 0) {
Austin Schuh5ca13112021-02-07 22:06:53 -0800994 signalfd_.reset(new ipc_lib::SignalFd({ipc_lib::kWakeupSignal}));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700995
Austin Schuh5ca13112021-02-07 22:06:53 -0800996 epoll_.OnReadable(signalfd_->fd(), [this]() { HandleEvent(); });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700997 }
998
Austin Schuh39788ff2019-12-01 18:22:57 -0800999 MaybeScheduleTimingReports();
1000
Austin Schuh7d87b672019-12-01 20:23:49 -08001001 ReserveEvents();
1002
Tyler Chatow67ddb032020-01-12 14:30:04 -08001003 {
Austin Schuha0c41ba2020-09-10 22:59:14 -07001004 logging::ScopedLogRestorer prev_logger;
Tyler Chatow67ddb032020-01-12 14:30:04 -08001005 AosLogToFbs aos_logger;
1006 if (!skip_logger_) {
Austin Schuhad9e5eb2021-11-19 20:33:55 -08001007 aos_logger.Initialize(&name_, MakeSender<logging::LogMessageFbs>("/aos"));
Austin Schuha0c41ba2020-09-10 22:59:14 -07001008 prev_logger.Swap(aos_logger.implementation());
Tyler Chatow67ddb032020-01-12 14:30:04 -08001009 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001010
Tyler Chatow67ddb032020-01-12 14:30:04 -08001011 aos::SetCurrentThreadName(name_.substr(0, 16));
Brian Silverman6a54ff32020-04-28 16:41:39 -07001012 const cpu_set_t default_affinity = DefaultAffinity();
1013 if (!CPU_EQUAL(&affinity_, &default_affinity)) {
1014 ::aos::SetCurrentThreadAffinity(affinity_);
1015 }
Tyler Chatow67ddb032020-01-12 14:30:04 -08001016 // Now, all the callbacks are setup. Lock everything into memory and go RT.
1017 if (priority_ != 0) {
1018 ::aos::InitRT();
1019
1020 LOG(INFO) << "Setting priority to " << priority_;
1021 ::aos::SetCurrentThreadRealtimePriority(priority_);
1022 }
1023
1024 set_is_running(true);
1025
1026 // Now that we are realtime (but before the OnRun handlers run), snap the
1027 // queue index.
1028 for (::std::unique_ptr<WatcherState> &watcher : watchers_) {
1029 watcher->Startup(this);
1030 }
1031
1032 // Now that we are RT, run all the OnRun handlers.
Austin Schuha9012be2021-07-21 15:19:11 -07001033 SetTimerContext(monotonic_clock::now());
Tyler Chatow67ddb032020-01-12 14:30:04 -08001034 for (const auto &run : on_run_) {
1035 run();
1036 }
1037
1038 // And start our main event loop which runs all the timers and handles Quit.
1039 epoll_.Run();
1040
1041 // Once epoll exits, there is no useful nonrt work left to do.
1042 set_is_running(false);
1043
1044 // Nothing time or synchronization critical needs to happen after this
1045 // point. Drop RT priority.
1046 ::aos::UnsetCurrentThreadRealtimePriority();
Alex Perrycb7da4b2019-08-28 19:35:56 -07001047 }
1048
Austin Schuh39788ff2019-12-01 18:22:57 -08001049 for (::std::unique_ptr<WatcherState> &base_watcher : watchers_) {
Brian Silverman148d43d2020-06-07 18:19:22 -05001050 ShmWatcherState *watcher =
1051 reinterpret_cast<ShmWatcherState *>(base_watcher.get());
Alex Perrycb7da4b2019-08-28 19:35:56 -07001052 watcher->UnregisterWakeup();
1053 }
1054
1055 if (watchers_.size() > 0) {
Austin Schuh5ca13112021-02-07 22:06:53 -08001056 epoll_.DeleteFd(signalfd_->fd());
1057 signalfd_.reset();
Alex Perrycb7da4b2019-08-28 19:35:56 -07001058 }
Austin Schuh32fd5a72019-12-01 22:20:26 -08001059
1060 SignalHandler::global()->Unregister(this);
Austin Schuhe84c3ed2019-12-14 15:29:48 -08001061
1062 // Trigger any remaining senders or fetchers to be cleared before destroying
1063 // the event loop so the book keeping matches. Do this in the thread that
1064 // created the timing reporter.
1065 timing_report_sender_.reset();
Austin Schuh0debde12022-08-17 16:25:17 -07001066 ClearContext();
Alex Perrycb7da4b2019-08-28 19:35:56 -07001067}
1068
1069void ShmEventLoop::Exit() { epoll_.Quit(); }
1070
Brian Silvermane1fe2512022-08-14 23:18:50 -07001071std::unique_ptr<ExitHandle> ShmEventLoop::MakeExitHandle() {
1072 return std::make_unique<ShmExitHandle>(this);
1073}
1074
Alex Perrycb7da4b2019-08-28 19:35:56 -07001075ShmEventLoop::~ShmEventLoop() {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001076 CheckCurrentThread();
Austin Schuh39788ff2019-12-01 18:22:57 -08001077 // Force everything with a registered fd with epoll to be destroyed now.
1078 timers_.clear();
1079 phased_loops_.clear();
1080 watchers_.clear();
1081
Alex Perrycb7da4b2019-08-28 19:35:56 -07001082 CHECK(!is_running()) << ": ShmEventLoop destroyed while running";
Brian Silvermane1fe2512022-08-14 23:18:50 -07001083 CHECK_EQ(0, exit_handle_count_)
1084 << ": All ExitHandles must be destroyed before the ShmEventLoop";
Alex Perrycb7da4b2019-08-28 19:35:56 -07001085}
1086
Alex Perrycb7da4b2019-08-28 19:35:56 -07001087void ShmEventLoop::SetRuntimeRealtimePriority(int priority) {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001088 CheckCurrentThread();
Alex Perrycb7da4b2019-08-28 19:35:56 -07001089 if (is_running()) {
1090 LOG(FATAL) << "Cannot set realtime priority while running.";
1091 }
1092 priority_ = priority;
1093}
1094
Brian Silverman6a54ff32020-04-28 16:41:39 -07001095void ShmEventLoop::SetRuntimeAffinity(const cpu_set_t &cpuset) {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001096 CheckCurrentThread();
Brian Silverman6a54ff32020-04-28 16:41:39 -07001097 if (is_running()) {
1098 LOG(FATAL) << "Cannot set affinity while running.";
1099 }
1100 affinity_ = cpuset;
1101}
1102
James Kuszmaul57c2baa2020-01-19 14:52:52 -08001103void ShmEventLoop::set_name(const std::string_view name) {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001104 CheckCurrentThread();
James Kuszmaul57c2baa2020-01-19 14:52:52 -08001105 name_ = std::string(name);
1106 UpdateTimingReport();
1107}
1108
Brian Silvermana5450a92020-08-12 19:59:57 -07001109absl::Span<const char> ShmEventLoop::GetWatcherSharedMemory(
1110 const Channel *channel) {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001111 CheckCurrentThread();
Brian Silverman148d43d2020-06-07 18:19:22 -05001112 ShmWatcherState *const watcher_state =
1113 static_cast<ShmWatcherState *>(GetWatcherState(channel));
Brian Silverman5120afb2020-01-31 17:44:35 -08001114 return watcher_state->GetSharedMemory();
1115}
1116
Brian Silverman4f4e0612020-08-12 19:54:41 -07001117int ShmEventLoop::NumberBuffers(const Channel *channel) {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001118 CheckCurrentThread();
Austin Schuh4d275fc2022-09-16 15:42:45 -07001119 return ipc_lib::MakeQueueConfiguration(configuration(), channel)
1120 .num_messages();
Brian Silverman4f4e0612020-08-12 19:54:41 -07001121}
1122
Brian Silverman5120afb2020-01-31 17:44:35 -08001123absl::Span<char> ShmEventLoop::GetShmSenderSharedMemory(
1124 const aos::RawSender *sender) const {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001125 CheckCurrentThread();
Brian Silverman148d43d2020-06-07 18:19:22 -05001126 return static_cast<const ShmSender *>(sender)->GetSharedMemory();
Brian Silverman5120afb2020-01-31 17:44:35 -08001127}
1128
Brian Silvermana5450a92020-08-12 19:59:57 -07001129absl::Span<const char> ShmEventLoop::GetShmFetcherPrivateMemory(
Brian Silverman6d2b3592020-06-18 14:40:15 -07001130 const aos::RawFetcher *fetcher) const {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001131 CheckCurrentThread();
Brian Silverman6d2b3592020-06-18 14:40:15 -07001132 return static_cast<const ShmFetcher *>(fetcher)->GetPrivateMemory();
1133}
1134
Austin Schuh3054f5f2021-07-21 15:38:01 -07001135pid_t ShmEventLoop::GetTid() {
1136 CheckCurrentThread();
1137 return syscall(SYS_gettid);
1138}
Austin Schuh39788ff2019-12-01 18:22:57 -08001139
Alex Perrycb7da4b2019-08-28 19:35:56 -07001140} // namespace aos