blob: afd65a3df5743b1875cbd299d70b69b20b9b6320 [file] [log] [blame]
Alex Perrycb7da4b2019-08-28 19:35:56 -07001#include "aos/events/shm_event_loop.h"
2
3#include <sys/mman.h>
4#include <sys/stat.h>
Austin Schuh39788ff2019-12-01 18:22:57 -08005#include <sys/syscall.h>
Alex Perrycb7da4b2019-08-28 19:35:56 -07006#include <sys/types.h>
7#include <unistd.h>
Tyler Chatow67ddb032020-01-12 14:30:04 -08008
Alex Perrycb7da4b2019-08-28 19:35:56 -07009#include <algorithm>
10#include <atomic>
11#include <chrono>
Austin Schuh39788ff2019-12-01 18:22:57 -080012#include <iterator>
Alex Perrycb7da4b2019-08-28 19:35:56 -070013#include <stdexcept>
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"
Alex Perrycb7da4b2019-08-28 19:35:56 -070019#include "aos/ipc_lib/lockless_queue.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080020#include "aos/ipc_lib/signalfd.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070021#include "aos/realtime.h"
Austin Schuh32fd5a72019-12-01 22:20:26 -080022#include "aos/stl_mutex/stl_mutex.h"
Austin Schuhfccb2d02020-01-26 16:11:19 -080023#include "aos/util/file.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070024#include "aos/util/phased_loop.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080025#include "glog/logging.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070026
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
Austin Schuhcdab6192019-12-29 17:47:46 -080050void SetShmBase(const std::string_view base) {
51 FLAGS_shm_base = std::string(base) + "/dev/shm/aos";
52}
53
Alex Perrycb7da4b2019-08-28 19:35:56 -070054std::string ShmFolder(const Channel *channel) {
55 CHECK(channel->has_name());
56 CHECK_EQ(channel->name()->string_view()[0], '/');
57 return FLAGS_shm_base + channel->name()->str() + "/";
58}
59std::string ShmPath(const Channel *channel) {
60 CHECK(channel->has_type());
Austin Schuh3328d132020-02-28 13:54:57 -080061 return ShmFolder(channel) + channel->type()->str() + ".v2";
Alex Perrycb7da4b2019-08-28 19:35:56 -070062}
63
64class MMapedQueue {
65 public:
Austin Schuhaa79e4e2019-12-29 20:43:32 -080066 MMapedQueue(const Channel *channel,
67 const std::chrono::seconds channel_storage_duration) {
Alex Perrycb7da4b2019-08-28 19:35:56 -070068 std::string path = ShmPath(channel);
69
Austin Schuh80c7fce2019-12-05 20:48:43 -080070 config_.num_watchers = channel->num_watchers();
71 config_.num_senders = channel->num_senders();
Austin Schuhaa79e4e2019-12-29 20:43:32 -080072 config_.queue_size =
73 channel_storage_duration.count() * channel->frequency();
Alex Perrycb7da4b2019-08-28 19:35:56 -070074 config_.message_data_size = channel->max_size();
75
76 size_ = ipc_lib::LocklessQueueMemorySize(config_);
77
Austin Schuhfccb2d02020-01-26 16:11:19 -080078 util::MkdirP(path, FLAGS_permissions);
Alex Perrycb7da4b2019-08-28 19:35:56 -070079
80 // There are 2 cases. Either the file already exists, or it does not
81 // already exist and we need to create it. Start by trying to create it. If
82 // that fails, the file has already been created and we can open it
83 // normally.. Once the file has been created it wil never be deleted.
Brian Silvermanf9f30ea2020-03-04 23:18:54 -080084 int fd = open(path.c_str(), O_RDWR | O_CREAT | O_EXCL,
Alex Perrycb7da4b2019-08-28 19:35:56 -070085 O_CLOEXEC | FLAGS_permissions);
Brian Silvermanf9f30ea2020-03-04 23:18:54 -080086 if (fd == -1 && errno == EEXIST) {
Alex Perrycb7da4b2019-08-28 19:35:56 -070087 VLOG(1) << path << " already created.";
88 // File already exists.
Brian Silvermanf9f30ea2020-03-04 23:18:54 -080089 fd = open(path.c_str(), O_RDWR, O_CLOEXEC);
90 PCHECK(fd != -1) << ": Failed to open " << path;
Alex Perrycb7da4b2019-08-28 19:35:56 -070091 while (true) {
92 struct stat st;
Brian Silvermanf9f30ea2020-03-04 23:18:54 -080093 PCHECK(fstat(fd, &st) == 0);
Alex Perrycb7da4b2019-08-28 19:35:56 -070094 if (st.st_size != 0) {
95 CHECK_EQ(static_cast<size_t>(st.st_size), size_)
96 << ": Size of " << path
97 << " doesn't match expected size of backing queue file. Did the "
98 "queue definition change?";
99 break;
100 } else {
101 // The creating process didn't get around to it yet. Give it a bit.
102 std::this_thread::sleep_for(std::chrono::milliseconds(10));
103 VLOG(1) << path << " is zero size, waiting";
104 }
105 }
106 } else {
107 VLOG(1) << "Created " << path;
Brian Silvermanf9f30ea2020-03-04 23:18:54 -0800108 PCHECK(fd != -1) << ": Failed to open " << path;
109 PCHECK(ftruncate(fd, size_) == 0);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700110 }
111
Brian Silvermanf9f30ea2020-03-04 23:18:54 -0800112 data_ = mmap(NULL, size_, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700113 PCHECK(data_ != MAP_FAILED);
Brian Silvermanf9f30ea2020-03-04 23:18:54 -0800114 PCHECK(close(fd) == 0);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700115
116 ipc_lib::InitializeLocklessQueueMemory(memory(), config_);
117 }
118
119 ~MMapedQueue() {
120 PCHECK(munmap(data_, size_) == 0);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700121 }
122
123 ipc_lib::LocklessQueueMemory *memory() const {
124 return reinterpret_cast<ipc_lib::LocklessQueueMemory *>(data_);
125 }
126
Austin Schuh39788ff2019-12-01 18:22:57 -0800127 const ipc_lib::LocklessQueueConfiguration &config() const { return config_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700128
Brian Silverman5120afb2020-01-31 17:44:35 -0800129 absl::Span<char> GetSharedMemory() const {
130 return absl::Span<char>(static_cast<char *>(data_), size_);
131 }
132
Alex Perrycb7da4b2019-08-28 19:35:56 -0700133 private:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700134 ipc_lib::LocklessQueueConfiguration config_;
135
Alex Perrycb7da4b2019-08-28 19:35:56 -0700136 size_t size_;
137 void *data_;
138};
139
Austin Schuh217a9782019-12-21 23:02:50 -0800140namespace {
141
Austin Schuh217a9782019-12-21 23:02:50 -0800142const Node *MaybeMyNode(const Configuration *configuration) {
143 if (!configuration->has_nodes()) {
144 return nullptr;
145 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700146
Austin Schuh217a9782019-12-21 23:02:50 -0800147 return configuration::GetMyNode(configuration);
148}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700149
150namespace chrono = ::std::chrono;
151
Austin Schuh39788ff2019-12-01 18:22:57 -0800152} // namespace
153
Austin Schuh217a9782019-12-21 23:02:50 -0800154ShmEventLoop::ShmEventLoop(const Configuration *configuration)
155 : EventLoop(configuration),
Austin Schuhe84c3ed2019-12-14 15:29:48 -0800156 name_(FLAGS_application_name),
Austin Schuh15649d62019-12-28 16:36:38 -0800157 node_(MaybeMyNode(configuration)) {
158 if (configuration->has_nodes()) {
159 CHECK(node_ != nullptr) << ": Couldn't find node in config.";
160 }
161}
Austin Schuh217a9782019-12-21 23:02:50 -0800162
Austin Schuh39788ff2019-12-01 18:22:57 -0800163namespace internal {
164
165class SimpleShmFetcher {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700166 public:
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800167 explicit SimpleShmFetcher(EventLoop *event_loop, const Channel *channel,
168 bool copy_data)
Austin Schuhf5652592019-12-29 16:26:15 -0800169 : channel_(channel),
Austin Schuhaa79e4e2019-12-29 20:43:32 -0800170 lockless_queue_memory_(
171 channel,
Brian Silverman587da252020-01-01 17:00:47 -0800172 chrono::ceil<chrono::seconds>(chrono::nanoseconds(
Austin Schuhaa79e4e2019-12-29 20:43:32 -0800173 event_loop->configuration()->channel_storage_duration()))),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700174 lockless_queue_(lockless_queue_memory_.memory(),
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800175 lockless_queue_memory_.config()) {
176 if (copy_data) {
177 data_storage_.reset(static_cast<char *>(
178 malloc(channel->max_size() + kChannelDataAlignment - 1)));
179 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700180 context_.data = nullptr;
181 // Point the queue index at the next index to read starting now. This
182 // makes it such that FetchNext will read the next message sent after
183 // the fetcher is created.
184 PointAtNextQueueIndex();
185 }
186
Austin Schuh39788ff2019-12-01 18:22:57 -0800187 ~SimpleShmFetcher() {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700188
189 // Points the next message to fetch at the queue index which will be
190 // populated next.
191 void PointAtNextQueueIndex() {
192 actual_queue_index_ = lockless_queue_.LatestQueueIndex();
193 if (!actual_queue_index_.valid()) {
194 // Nothing in the queue. The next element will show up at the 0th
195 // index in the queue.
196 actual_queue_index_ =
197 ipc_lib::QueueIndex::Zero(lockless_queue_.queue_size());
198 } else {
199 actual_queue_index_ = actual_queue_index_.Increment();
200 }
201 }
202
Austin Schuh39788ff2019-12-01 18:22:57 -0800203 bool FetchNext() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700204 // TODO(austin): Get behind and make sure it dies both here and with
205 // Fetch.
206 ipc_lib::LocklessQueue::ReadResult read_result = lockless_queue_.Read(
Austin Schuhad154822019-12-27 15:45:13 -0800207 actual_queue_index_.index(), &context_.monotonic_event_time,
208 &context_.realtime_event_time, &context_.monotonic_remote_time,
209 &context_.realtime_remote_time, &context_.remote_queue_index,
Brian Silvermana1652f32020-01-29 20:41:44 -0800210 &context_.size, data_storage_start());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700211 if (read_result == ipc_lib::LocklessQueue::ReadResult::GOOD) {
212 context_.queue_index = actual_queue_index_.index();
Austin Schuhad154822019-12-27 15:45:13 -0800213 if (context_.remote_queue_index == 0xffffffffu) {
214 context_.remote_queue_index = context_.queue_index;
215 }
216 if (context_.monotonic_remote_time == aos::monotonic_clock::min_time) {
217 context_.monotonic_remote_time = context_.monotonic_event_time;
218 }
219 if (context_.realtime_remote_time == aos::realtime_clock::min_time) {
220 context_.realtime_remote_time = context_.realtime_event_time;
221 }
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800222 if (copy_data()) {
223 context_.data = data_storage_start() +
224 lockless_queue_.message_data_size() - context_.size;
225 } else {
226 context_.data = nullptr;
227 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700228 actual_queue_index_ = actual_queue_index_.Increment();
229 }
230
231 // Make sure the data wasn't modified while we were reading it. This
232 // can only happen if you are reading the last message *while* it is
233 // being written to, which means you are pretty far behind.
234 CHECK(read_result != ipc_lib::LocklessQueue::ReadResult::OVERWROTE)
235 << ": Got behind while reading and the last message was modified "
Austin Schuhf5652592019-12-29 16:26:15 -0800236 "out from under us while we were reading it. Don't get so far "
237 "behind. "
238 << configuration::CleanedChannelToString(channel_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700239
240 CHECK(read_result != ipc_lib::LocklessQueue::ReadResult::TOO_OLD)
Austin Schuhf5652592019-12-29 16:26:15 -0800241 << ": The next message is no longer available. "
242 << configuration::CleanedChannelToString(channel_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700243 return read_result == ipc_lib::LocklessQueue::ReadResult::GOOD;
244 }
245
Austin Schuh39788ff2019-12-01 18:22:57 -0800246 bool Fetch() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700247 const ipc_lib::QueueIndex queue_index = lockless_queue_.LatestQueueIndex();
248 // actual_queue_index_ is only meaningful if it was set by Fetch or
249 // FetchNext. This happens when valid_data_ has been set. So, only
250 // skip checking if valid_data_ is true.
251 //
252 // Also, if the latest queue index is invalid, we are empty. So there
253 // is nothing to fetch.
Austin Schuh39788ff2019-12-01 18:22:57 -0800254 if ((context_.data != nullptr &&
Alex Perrycb7da4b2019-08-28 19:35:56 -0700255 queue_index == actual_queue_index_.DecrementBy(1u)) ||
256 !queue_index.valid()) {
257 return false;
258 }
259
Austin Schuhad154822019-12-27 15:45:13 -0800260 ipc_lib::LocklessQueue::ReadResult read_result = lockless_queue_.Read(
261 queue_index.index(), &context_.monotonic_event_time,
262 &context_.realtime_event_time, &context_.monotonic_remote_time,
263 &context_.realtime_remote_time, &context_.remote_queue_index,
Brian Silvermana1652f32020-01-29 20:41:44 -0800264 &context_.size, data_storage_start());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700265 if (read_result == ipc_lib::LocklessQueue::ReadResult::GOOD) {
266 context_.queue_index = queue_index.index();
Austin Schuhad154822019-12-27 15:45:13 -0800267 if (context_.remote_queue_index == 0xffffffffu) {
268 context_.remote_queue_index = context_.queue_index;
269 }
270 if (context_.monotonic_remote_time == aos::monotonic_clock::min_time) {
271 context_.monotonic_remote_time = context_.monotonic_event_time;
272 }
273 if (context_.realtime_remote_time == aos::realtime_clock::min_time) {
274 context_.realtime_remote_time = context_.realtime_event_time;
275 }
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800276 if (copy_data()) {
277 context_.data = data_storage_start() +
278 lockless_queue_.message_data_size() - context_.size;
279 } else {
280 context_.data = nullptr;
281 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700282 actual_queue_index_ = queue_index.Increment();
283 }
284
285 // Make sure the data wasn't modified while we were reading it. This
286 // can only happen if you are reading the last message *while* it is
287 // being written to, which means you are pretty far behind.
288 CHECK(read_result != ipc_lib::LocklessQueue::ReadResult::OVERWROTE)
289 << ": Got behind while reading and the last message was modified "
Austin Schuhf5652592019-12-29 16:26:15 -0800290 "out from under us while we were reading it. Don't get so far "
291 "behind."
292 << configuration::CleanedChannelToString(channel_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700293
294 CHECK(read_result != ipc_lib::LocklessQueue::ReadResult::NOTHING_NEW)
Austin Schuhf5652592019-12-29 16:26:15 -0800295 << ": Queue index went backwards. This should never happen. "
296 << configuration::CleanedChannelToString(channel_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700297
298 // We fell behind between when we read the index and read the value.
299 // This isn't worth recovering from since this means we went to sleep
300 // for a long time in the middle of this function.
301 CHECK(read_result != ipc_lib::LocklessQueue::ReadResult::TOO_OLD)
Austin Schuhf5652592019-12-29 16:26:15 -0800302 << ": The next message is no longer available. "
303 << configuration::CleanedChannelToString(channel_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700304 return read_result == ipc_lib::LocklessQueue::ReadResult::GOOD;
305 }
306
Austin Schuh39788ff2019-12-01 18:22:57 -0800307 Context context() const { return context_; }
308
Alex Perrycb7da4b2019-08-28 19:35:56 -0700309 bool RegisterWakeup(int priority) {
310 return lockless_queue_.RegisterWakeup(priority);
311 }
312
313 void UnregisterWakeup() { lockless_queue_.UnregisterWakeup(); }
314
Brian Silverman5120afb2020-01-31 17:44:35 -0800315 absl::Span<char> GetSharedMemory() const {
316 return lockless_queue_memory_.GetSharedMemory();
317 }
318
Alex Perrycb7da4b2019-08-28 19:35:56 -0700319 private:
Brian Silvermana1652f32020-01-29 20:41:44 -0800320 char *data_storage_start() {
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800321 if (!copy_data()) return nullptr;
Brian Silvermana1652f32020-01-29 20:41:44 -0800322 return RoundChannelData(data_storage_.get(), channel_->max_size());
323 }
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800324 bool copy_data() const { return static_cast<bool>(data_storage_); }
Brian Silvermana1652f32020-01-29 20:41:44 -0800325
Austin Schuhf5652592019-12-29 16:26:15 -0800326 const Channel *const channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700327 MMapedQueue lockless_queue_memory_;
328 ipc_lib::LocklessQueue lockless_queue_;
329
330 ipc_lib::QueueIndex actual_queue_index_ =
331 ipc_lib::LocklessQueue::empty_queue_index();
332
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800333 // This being empty indicates we're not going to copy data.
334 std::unique_ptr<char, decltype(&free)> data_storage_{nullptr, &free};
Austin Schuh39788ff2019-12-01 18:22:57 -0800335
336 Context context_;
337};
338
339class ShmFetcher : public RawFetcher {
340 public:
341 explicit ShmFetcher(EventLoop *event_loop, const Channel *channel)
Austin Schuhaa79e4e2019-12-29 20:43:32 -0800342 : RawFetcher(event_loop, channel),
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800343 simple_shm_fetcher_(event_loop, channel, true) {}
Austin Schuh39788ff2019-12-01 18:22:57 -0800344
345 ~ShmFetcher() { context_.data = nullptr; }
346
347 std::pair<bool, monotonic_clock::time_point> DoFetchNext() override {
348 if (simple_shm_fetcher_.FetchNext()) {
349 context_ = simple_shm_fetcher_.context();
350 return std::make_pair(true, monotonic_clock::now());
351 }
352 return std::make_pair(false, monotonic_clock::min_time);
353 }
354
355 std::pair<bool, monotonic_clock::time_point> DoFetch() override {
356 if (simple_shm_fetcher_.Fetch()) {
357 context_ = simple_shm_fetcher_.context();
358 return std::make_pair(true, monotonic_clock::now());
359 }
360 return std::make_pair(false, monotonic_clock::min_time);
361 }
362
363 private:
364 SimpleShmFetcher simple_shm_fetcher_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700365};
366
367class ShmSender : public RawSender {
368 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800369 explicit ShmSender(EventLoop *event_loop, const Channel *channel)
370 : RawSender(event_loop, channel),
Austin Schuhaa79e4e2019-12-29 20:43:32 -0800371 lockless_queue_memory_(
372 channel,
Brian Silverman587da252020-01-01 17:00:47 -0800373 chrono::ceil<chrono::seconds>(chrono::nanoseconds(
Austin Schuhaa79e4e2019-12-29 20:43:32 -0800374 event_loop->configuration()->channel_storage_duration()))),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700375 lockless_queue_(lockless_queue_memory_.memory(),
376 lockless_queue_memory_.config()),
377 lockless_queue_sender_(lockless_queue_.MakeSender()) {}
378
Austin Schuh39788ff2019-12-01 18:22:57 -0800379 ~ShmSender() override {}
380
Alex Perrycb7da4b2019-08-28 19:35:56 -0700381 void *data() override { return lockless_queue_sender_.Data(); }
382 size_t size() override { return lockless_queue_sender_.size(); }
Austin Schuhad154822019-12-27 15:45:13 -0800383 bool DoSend(size_t length,
384 aos::monotonic_clock::time_point monotonic_remote_time,
385 aos::realtime_clock::time_point realtime_remote_time,
386 uint32_t remote_queue_index) override {
387 lockless_queue_sender_.Send(
388 length, monotonic_remote_time, realtime_remote_time, remote_queue_index,
389 &monotonic_sent_time_, &realtime_sent_time_, &sent_queue_index_);
Austin Schuh39788ff2019-12-01 18:22:57 -0800390 lockless_queue_.Wakeup(event_loop()->priority());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700391 return true;
392 }
393
Austin Schuhad154822019-12-27 15:45:13 -0800394 bool DoSend(const void *msg, size_t length,
395 aos::monotonic_clock::time_point monotonic_remote_time,
396 aos::realtime_clock::time_point realtime_remote_time,
397 uint32_t remote_queue_index) override {
398 lockless_queue_sender_.Send(reinterpret_cast<const char *>(msg), length,
399 monotonic_remote_time, realtime_remote_time,
400 remote_queue_index, &monotonic_sent_time_,
401 &realtime_sent_time_, &sent_queue_index_);
Austin Schuh39788ff2019-12-01 18:22:57 -0800402 lockless_queue_.Wakeup(event_loop()->priority());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700403 // TODO(austin): Return an error if we send too fast.
404 return true;
405 }
406
Brian Silverman5120afb2020-01-31 17:44:35 -0800407 absl::Span<char> GetSharedMemory() const {
408 return lockless_queue_memory_.GetSharedMemory();
409 }
410
Alex Perrycb7da4b2019-08-28 19:35:56 -0700411 private:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700412 MMapedQueue lockless_queue_memory_;
413 ipc_lib::LocklessQueue lockless_queue_;
414 ipc_lib::LocklessQueue::Sender lockless_queue_sender_;
415};
416
Alex Perrycb7da4b2019-08-28 19:35:56 -0700417// Class to manage the state for a Watcher.
Austin Schuh39788ff2019-12-01 18:22:57 -0800418class WatcherState : public aos::WatcherState {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700419 public:
420 WatcherState(
Austin Schuh7d87b672019-12-01 20:23:49 -0800421 ShmEventLoop *event_loop, const Channel *channel,
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800422 std::function<void(const Context &context, const void *message)> fn,
423 bool copy_data)
Austin Schuh39788ff2019-12-01 18:22:57 -0800424 : aos::WatcherState(event_loop, channel, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800425 event_loop_(event_loop),
426 event_(this),
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800427 simple_shm_fetcher_(event_loop, channel, copy_data) {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700428
Austin Schuh7d87b672019-12-01 20:23:49 -0800429 ~WatcherState() override { event_loop_->RemoveEvent(&event_); }
Austin Schuh39788ff2019-12-01 18:22:57 -0800430
431 void Startup(EventLoop *event_loop) override {
Austin Schuh7d87b672019-12-01 20:23:49 -0800432 simple_shm_fetcher_.PointAtNextQueueIndex();
Austin Schuh39788ff2019-12-01 18:22:57 -0800433 CHECK(RegisterWakeup(event_loop->priority()));
434 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700435
Alex Perrycb7da4b2019-08-28 19:35:56 -0700436 // Returns true if there is new data available.
Austin Schuh7d87b672019-12-01 20:23:49 -0800437 bool CheckForNewData() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700438 if (!has_new_data_) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800439 has_new_data_ = simple_shm_fetcher_.FetchNext();
Austin Schuh7d87b672019-12-01 20:23:49 -0800440
441 if (has_new_data_) {
442 event_.set_event_time(
Austin Schuhad154822019-12-27 15:45:13 -0800443 simple_shm_fetcher_.context().monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800444 event_loop_->AddEvent(&event_);
445 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700446 }
447
448 return has_new_data_;
449 }
450
Alex Perrycb7da4b2019-08-28 19:35:56 -0700451 // Consumes the data by calling the callback.
Austin Schuh7d87b672019-12-01 20:23:49 -0800452 void HandleEvent() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700453 CHECK(has_new_data_);
Austin Schuh39788ff2019-12-01 18:22:57 -0800454 DoCallCallback(monotonic_clock::now, simple_shm_fetcher_.context());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700455 has_new_data_ = false;
Austin Schuh7d87b672019-12-01 20:23:49 -0800456 CheckForNewData();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700457 }
458
Austin Schuh39788ff2019-12-01 18:22:57 -0800459 // Registers us to receive a signal on event reception.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700460 bool RegisterWakeup(int priority) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800461 return simple_shm_fetcher_.RegisterWakeup(priority);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700462 }
463
Austin Schuh39788ff2019-12-01 18:22:57 -0800464 void UnregisterWakeup() { return simple_shm_fetcher_.UnregisterWakeup(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700465
Brian Silverman5120afb2020-01-31 17:44:35 -0800466 absl::Span<char> GetSharedMemory() const {
467 return simple_shm_fetcher_.GetSharedMemory();
468 }
469
Alex Perrycb7da4b2019-08-28 19:35:56 -0700470 private:
471 bool has_new_data_ = false;
472
Austin Schuh7d87b672019-12-01 20:23:49 -0800473 ShmEventLoop *event_loop_;
474 EventHandler<WatcherState> event_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800475 SimpleShmFetcher simple_shm_fetcher_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700476};
477
478// Adapter class to adapt a timerfd to a TimerHandler.
Austin Schuh7d87b672019-12-01 20:23:49 -0800479class TimerHandlerState final : public TimerHandler {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700480 public:
481 TimerHandlerState(ShmEventLoop *shm_event_loop, ::std::function<void()> fn)
Austin Schuh39788ff2019-12-01 18:22:57 -0800482 : TimerHandler(shm_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800483 shm_event_loop_(shm_event_loop),
484 event_(this) {
Austin Schuhcde39fd2020-02-22 20:58:24 -0800485 shm_event_loop_->epoll_.OnReadable(timerfd_.fd(), [this]() {
486 // The timer may fire spurriously. HandleEvent on the event loop will
487 // call the callback if it is needed. It may also have called it when
488 // processing some other event, and the kernel decided to deliver this
489 // wakeup anyways.
490 timerfd_.Read();
491 shm_event_loop_->HandleEvent();
492 });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700493 }
494
Austin Schuh7d87b672019-12-01 20:23:49 -0800495 ~TimerHandlerState() {
496 Disable();
497 shm_event_loop_->epoll_.DeleteFd(timerfd_.fd());
498 }
499
500 void HandleEvent() {
Austin Schuhcde39fd2020-02-22 20:58:24 -0800501 CHECK(!event_.valid());
502 const auto monotonic_now = Call(monotonic_clock::now, base_);
503 if (event_.valid()) {
504 // If someone called Setup inside Call, rescheduling is already taken care
505 // of. Bail.
506 return;
Austin Schuh7d87b672019-12-01 20:23:49 -0800507 }
508
Austin Schuhcde39fd2020-02-22 20:58:24 -0800509 if (repeat_offset_ == chrono::seconds(0)) {
510 timerfd_.Disable();
511 } else {
512 // Compute how many cycles have elapsed and schedule the next iteration
513 // for the next iteration in the future.
514 const int elapsed_cycles =
515 std::max<int>(0, (monotonic_now - base_ + repeat_offset_ -
516 std::chrono::nanoseconds(1)) /
517 repeat_offset_);
518 base_ += repeat_offset_ * elapsed_cycles;
Austin Schuh7d87b672019-12-01 20:23:49 -0800519
Austin Schuhcde39fd2020-02-22 20:58:24 -0800520 // Update the heap and schedule the timerfd wakeup.
Austin Schuh7d87b672019-12-01 20:23:49 -0800521 event_.set_event_time(base_);
522 shm_event_loop_->AddEvent(&event_);
Austin Schuhcde39fd2020-02-22 20:58:24 -0800523 timerfd_.SetTime(base_, chrono::seconds(0));
Austin Schuh7d87b672019-12-01 20:23:49 -0800524 }
525 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700526
527 void Setup(monotonic_clock::time_point base,
528 monotonic_clock::duration repeat_offset) override {
Austin Schuh7d87b672019-12-01 20:23:49 -0800529 if (event_.valid()) {
530 shm_event_loop_->RemoveEvent(&event_);
531 }
532
Alex Perrycb7da4b2019-08-28 19:35:56 -0700533 timerfd_.SetTime(base, repeat_offset);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800534 base_ = base;
535 repeat_offset_ = repeat_offset;
Austin Schuh7d87b672019-12-01 20:23:49 -0800536 event_.set_event_time(base_);
537 shm_event_loop_->AddEvent(&event_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700538 }
539
Austin Schuh7d87b672019-12-01 20:23:49 -0800540 void Disable() override {
541 shm_event_loop_->RemoveEvent(&event_);
542 timerfd_.Disable();
543 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700544
545 private:
546 ShmEventLoop *shm_event_loop_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800547 EventHandler<TimerHandlerState> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700548
549 TimerFd timerfd_;
550
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800551 monotonic_clock::time_point base_;
552 monotonic_clock::duration repeat_offset_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700553};
554
555// Adapter class to the timerfd and PhasedLoop.
Austin Schuh7d87b672019-12-01 20:23:49 -0800556class PhasedLoopHandler final : public ::aos::PhasedLoopHandler {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700557 public:
558 PhasedLoopHandler(ShmEventLoop *shm_event_loop, ::std::function<void(int)> fn,
559 const monotonic_clock::duration interval,
560 const monotonic_clock::duration offset)
Austin Schuh39788ff2019-12-01 18:22:57 -0800561 : aos::PhasedLoopHandler(shm_event_loop, std::move(fn), interval, offset),
Austin Schuh7d87b672019-12-01 20:23:49 -0800562 shm_event_loop_(shm_event_loop),
563 event_(this) {
564 shm_event_loop_->epoll_.OnReadable(
565 timerfd_.fd(), [this]() { shm_event_loop_->HandleEvent(); });
566 }
567
568 void HandleEvent() {
569 // The return value for read is the number of cycles that have elapsed.
570 // Because we check to see when this event *should* have happened, there are
571 // cases where Read() will return 0, when 1 cycle has actually happened.
572 // This occurs when the timer interrupt hasn't triggered yet. Therefore,
573 // ignore it. Call handles rescheduling and calculating elapsed cycles
574 // without any extra help.
575 timerfd_.Read();
576 event_.Invalidate();
577
578 Call(monotonic_clock::now, [this](monotonic_clock::time_point sleep_time) {
579 Schedule(sleep_time);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700580 });
581 }
582
Austin Schuh39788ff2019-12-01 18:22:57 -0800583 ~PhasedLoopHandler() override {
584 shm_event_loop_->epoll_.DeleteFd(timerfd_.fd());
Austin Schuh7d87b672019-12-01 20:23:49 -0800585 shm_event_loop_->RemoveEvent(&event_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700586 }
587
588 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800589 // Reschedules the timer.
Austin Schuh39788ff2019-12-01 18:22:57 -0800590 void Schedule(monotonic_clock::time_point sleep_time) override {
Austin Schuh7d87b672019-12-01 20:23:49 -0800591 if (event_.valid()) {
592 shm_event_loop_->RemoveEvent(&event_);
593 }
594
Austin Schuh39788ff2019-12-01 18:22:57 -0800595 timerfd_.SetTime(sleep_time, ::aos::monotonic_clock::zero());
Austin Schuh7d87b672019-12-01 20:23:49 -0800596 event_.set_event_time(sleep_time);
597 shm_event_loop_->AddEvent(&event_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700598 }
599
600 ShmEventLoop *shm_event_loop_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800601 EventHandler<PhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700602
603 TimerFd timerfd_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700604};
605} // namespace internal
606
607::std::unique_ptr<RawFetcher> ShmEventLoop::MakeRawFetcher(
608 const Channel *channel) {
Austin Schuhca4828c2019-12-28 14:21:35 -0800609 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
610 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
611 << "\", \"type\": \"" << channel->type()->string_view()
612 << "\" } is not able to be fetched on this node. Check your "
613 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800614 }
615
Austin Schuh39788ff2019-12-01 18:22:57 -0800616 return ::std::unique_ptr<RawFetcher>(new internal::ShmFetcher(this, channel));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700617}
618
619::std::unique_ptr<RawSender> ShmEventLoop::MakeRawSender(
620 const Channel *channel) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800621 TakeSender(channel);
Austin Schuh39788ff2019-12-01 18:22:57 -0800622
623 return ::std::unique_ptr<RawSender>(new internal::ShmSender(this, channel));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700624}
625
626void ShmEventLoop::MakeRawWatcher(
627 const Channel *channel,
628 std::function<void(const Context &context, const void *message)> watcher) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800629 TakeWatcher(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800630
Austin Schuh39788ff2019-12-01 18:22:57 -0800631 NewWatcher(::std::unique_ptr<WatcherState>(
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800632 new internal::WatcherState(this, channel, std::move(watcher), true)));
633}
634
635void ShmEventLoop::MakeRawNoArgWatcher(
636 const Channel *channel,
637 std::function<void(const Context &context)> watcher) {
638 TakeWatcher(channel);
639
640 NewWatcher(::std::unique_ptr<WatcherState>(new internal::WatcherState(
641 this, channel,
642 [watcher](const Context &context, const void *) { watcher(context); },
643 false)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700644}
645
646TimerHandler *ShmEventLoop::AddTimer(::std::function<void()> callback) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800647 return NewTimer(::std::unique_ptr<TimerHandler>(
648 new internal::TimerHandlerState(this, ::std::move(callback))));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700649}
650
651PhasedLoopHandler *ShmEventLoop::AddPhasedLoop(
652 ::std::function<void(int)> callback,
653 const monotonic_clock::duration interval,
654 const monotonic_clock::duration offset) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800655 return NewPhasedLoop(
656 ::std::unique_ptr<PhasedLoopHandler>(new internal::PhasedLoopHandler(
657 this, ::std::move(callback), interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700658}
659
660void ShmEventLoop::OnRun(::std::function<void()> on_run) {
661 on_run_.push_back(::std::move(on_run));
662}
663
Austin Schuh7d87b672019-12-01 20:23:49 -0800664void ShmEventLoop::HandleEvent() {
665 // Update all the times for handlers.
666 for (::std::unique_ptr<WatcherState> &base_watcher : watchers_) {
667 internal::WatcherState *watcher =
668 reinterpret_cast<internal::WatcherState *>(base_watcher.get());
669
670 watcher->CheckForNewData();
671 }
672
Austin Schuh39788ff2019-12-01 18:22:57 -0800673 while (true) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800674 if (EventCount() == 0 ||
675 PeekEvent()->event_time() > monotonic_clock::now()) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800676 break;
677 }
678
Austin Schuh7d87b672019-12-01 20:23:49 -0800679 EventLoopEvent *event = PopEvent();
680 event->HandleEvent();
Austin Schuh39788ff2019-12-01 18:22:57 -0800681 }
682}
683
Austin Schuh32fd5a72019-12-01 22:20:26 -0800684// RAII class to mask signals.
685class ScopedSignalMask {
686 public:
687 ScopedSignalMask(std::initializer_list<int> signals) {
688 sigset_t sigset;
689 PCHECK(sigemptyset(&sigset) == 0);
690 for (int signal : signals) {
691 PCHECK(sigaddset(&sigset, signal) == 0);
692 }
693
694 PCHECK(sigprocmask(SIG_BLOCK, &sigset, &old_) == 0);
695 }
696
697 ~ScopedSignalMask() { PCHECK(sigprocmask(SIG_SETMASK, &old_, nullptr) == 0); }
698
699 private:
700 sigset_t old_;
701};
702
703// Class to manage the static state associated with killing multiple event
704// loops.
705class SignalHandler {
706 public:
707 // Gets the singleton.
708 static SignalHandler *global() {
709 static SignalHandler loop;
710 return &loop;
711 }
712
713 // Handles the signal with the singleton.
714 static void HandleSignal(int) { global()->DoHandleSignal(); }
715
716 // Registers an event loop to receive Exit() calls.
717 void Register(ShmEventLoop *event_loop) {
718 // Block signals while we have the mutex so we never race with the signal
719 // handler.
720 ScopedSignalMask mask({SIGINT, SIGHUP, SIGTERM});
721 std::unique_lock<stl_mutex> locker(mutex_);
722 if (event_loops_.size() == 0) {
723 // The first caller registers the signal handler.
724 struct sigaction new_action;
725 sigemptyset(&new_action.sa_mask);
726 // This makes it so that 2 control c's to a stuck process will kill it by
727 // restoring the original signal handler.
728 new_action.sa_flags = SA_RESETHAND;
729 new_action.sa_handler = &HandleSignal;
730
731 PCHECK(sigaction(SIGINT, &new_action, &old_action_int_) == 0);
732 PCHECK(sigaction(SIGHUP, &new_action, &old_action_hup_) == 0);
733 PCHECK(sigaction(SIGTERM, &new_action, &old_action_term_) == 0);
734 }
735
736 event_loops_.push_back(event_loop);
737 }
738
739 // Unregisters an event loop to receive Exit() calls.
740 void Unregister(ShmEventLoop *event_loop) {
741 // Block signals while we have the mutex so we never race with the signal
742 // handler.
743 ScopedSignalMask mask({SIGINT, SIGHUP, SIGTERM});
744 std::unique_lock<stl_mutex> locker(mutex_);
745
Brian Silverman5120afb2020-01-31 17:44:35 -0800746 event_loops_.erase(
747 std::find(event_loops_.begin(), event_loops_.end(), event_loop));
Austin Schuh32fd5a72019-12-01 22:20:26 -0800748
749 if (event_loops_.size() == 0u) {
750 // The last caller restores the original signal handlers.
751 PCHECK(sigaction(SIGINT, &old_action_int_, nullptr) == 0);
752 PCHECK(sigaction(SIGHUP, &old_action_hup_, nullptr) == 0);
753 PCHECK(sigaction(SIGTERM, &old_action_term_, nullptr) == 0);
754 }
755 }
756
757 private:
758 void DoHandleSignal() {
759 // We block signals while grabbing the lock, so there should never be a
760 // race. Confirm that this is true using trylock.
761 CHECK(mutex_.try_lock()) << ": sigprocmask failed to block signals while "
762 "modifing the event loop list.";
763 for (ShmEventLoop *event_loop : event_loops_) {
764 event_loop->Exit();
765 }
766 mutex_.unlock();
767 }
768
769 // Mutex to protect all state.
770 stl_mutex mutex_;
771 std::vector<ShmEventLoop *> event_loops_;
772 struct sigaction old_action_int_;
773 struct sigaction old_action_hup_;
774 struct sigaction old_action_term_;
775};
776
Alex Perrycb7da4b2019-08-28 19:35:56 -0700777void ShmEventLoop::Run() {
Austin Schuh32fd5a72019-12-01 22:20:26 -0800778 SignalHandler::global()->Register(this);
Austin Schuh39788ff2019-12-01 18:22:57 -0800779
Alex Perrycb7da4b2019-08-28 19:35:56 -0700780 std::unique_ptr<ipc_lib::SignalFd> signalfd;
781
782 if (watchers_.size() > 0) {
783 signalfd.reset(new ipc_lib::SignalFd({ipc_lib::kWakeupSignal}));
784
785 epoll_.OnReadable(signalfd->fd(), [signalfd_ptr = signalfd.get(), this]() {
786 signalfd_siginfo result = signalfd_ptr->Read();
787 CHECK_EQ(result.ssi_signo, ipc_lib::kWakeupSignal);
788
789 // TODO(austin): We should really be checking *everything*, not just
790 // watchers, and calling the oldest thing first. That will improve
791 // determinism a lot.
792
Austin Schuh7d87b672019-12-01 20:23:49 -0800793 HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700794 });
795 }
796
Austin Schuh39788ff2019-12-01 18:22:57 -0800797 MaybeScheduleTimingReports();
798
Austin Schuh7d87b672019-12-01 20:23:49 -0800799 ReserveEvents();
800
Tyler Chatow67ddb032020-01-12 14:30:04 -0800801 {
802 AosLogToFbs aos_logger;
803 if (!skip_logger_) {
804 aos_logger.Initialize(MakeSender<logging::LogMessageFbs>("/aos"));
805 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700806
Tyler Chatow67ddb032020-01-12 14:30:04 -0800807 aos::SetCurrentThreadName(name_.substr(0, 16));
808 // Now, all the callbacks are setup. Lock everything into memory and go RT.
809 if (priority_ != 0) {
810 ::aos::InitRT();
811
812 LOG(INFO) << "Setting priority to " << priority_;
813 ::aos::SetCurrentThreadRealtimePriority(priority_);
814 }
815
816 set_is_running(true);
817
818 // Now that we are realtime (but before the OnRun handlers run), snap the
819 // queue index.
820 for (::std::unique_ptr<WatcherState> &watcher : watchers_) {
821 watcher->Startup(this);
822 }
823
824 // Now that we are RT, run all the OnRun handlers.
825 for (const auto &run : on_run_) {
826 run();
827 }
828
829 // And start our main event loop which runs all the timers and handles Quit.
830 epoll_.Run();
831
832 // Once epoll exits, there is no useful nonrt work left to do.
833 set_is_running(false);
834
835 // Nothing time or synchronization critical needs to happen after this
836 // point. Drop RT priority.
837 ::aos::UnsetCurrentThreadRealtimePriority();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700838 }
839
Austin Schuh39788ff2019-12-01 18:22:57 -0800840 for (::std::unique_ptr<WatcherState> &base_watcher : watchers_) {
841 internal::WatcherState *watcher =
842 reinterpret_cast<internal::WatcherState *>(base_watcher.get());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700843 watcher->UnregisterWakeup();
844 }
845
846 if (watchers_.size() > 0) {
847 epoll_.DeleteFd(signalfd->fd());
848 signalfd.reset();
849 }
Austin Schuh32fd5a72019-12-01 22:20:26 -0800850
851 SignalHandler::global()->Unregister(this);
Austin Schuhe84c3ed2019-12-14 15:29:48 -0800852
853 // Trigger any remaining senders or fetchers to be cleared before destroying
854 // the event loop so the book keeping matches. Do this in the thread that
855 // created the timing reporter.
856 timing_report_sender_.reset();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700857}
858
859void ShmEventLoop::Exit() { epoll_.Quit(); }
860
861ShmEventLoop::~ShmEventLoop() {
Austin Schuh39788ff2019-12-01 18:22:57 -0800862 // Force everything with a registered fd with epoll to be destroyed now.
863 timers_.clear();
864 phased_loops_.clear();
865 watchers_.clear();
866
Alex Perrycb7da4b2019-08-28 19:35:56 -0700867 CHECK(!is_running()) << ": ShmEventLoop destroyed while running";
868}
869
Alex Perrycb7da4b2019-08-28 19:35:56 -0700870void ShmEventLoop::SetRuntimeRealtimePriority(int priority) {
871 if (is_running()) {
872 LOG(FATAL) << "Cannot set realtime priority while running.";
873 }
874 priority_ = priority;
875}
876
James Kuszmaul57c2baa2020-01-19 14:52:52 -0800877void ShmEventLoop::set_name(const std::string_view name) {
878 name_ = std::string(name);
879 UpdateTimingReport();
880}
881
Brian Silverman5120afb2020-01-31 17:44:35 -0800882absl::Span<char> ShmEventLoop::GetWatcherSharedMemory(const Channel *channel) {
883 internal::WatcherState *const watcher_state =
884 static_cast<internal::WatcherState *>(GetWatcherState(channel));
885 return watcher_state->GetSharedMemory();
886}
887
888absl::Span<char> ShmEventLoop::GetShmSenderSharedMemory(
889 const aos::RawSender *sender) const {
890 return static_cast<const internal::ShmSender *>(sender)->GetSharedMemory();
891}
892
Austin Schuh39788ff2019-12-01 18:22:57 -0800893pid_t ShmEventLoop::GetTid() { return syscall(SYS_gettid); }
894
Alex Perrycb7da4b2019-08-28 19:35:56 -0700895} // namespace aos