blob: 97c99634dc8c38002db3124baf812459063816db [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
Brian Silverman3b0cdaf2020-04-28 16:51:51 -070064void PageFaultData(char *data, size_t size) {
65 // This just has to divide the actual page size. Being smaller will make this
66 // a bit slower than necessary, but not much. 1024 is a pretty conservative
67 // choice (most pages are probably 4096).
68 static constexpr size_t kPageSize = 1024;
69 const size_t pages = (size + kPageSize - 1) / kPageSize;
70 for (size_t i = 0; i < pages; ++i) {
71 char zero = 0;
72 // We need to ensure there's a writable pagetable entry, but avoid modifying
73 // the data.
74 //
75 // Even if you lock the data into memory, some kernels still seem to lazily
76 // create the actual pagetable entries. This means we need to somehow
77 // "write" to the page.
78 //
79 // Also, this takes place while other processes may be concurrently
80 // opening/initializing the memory, so we need to avoid corrupting that.
81 //
82 // This is the simplest operation I could think of which achieves that:
83 // "store 0 if it's already 0".
84 __atomic_compare_exchange_n(&data[i * kPageSize], &zero, 0, true,
85 __ATOMIC_RELAXED, __ATOMIC_RELAXED);
86 }
87}
88
Alex Perrycb7da4b2019-08-28 19:35:56 -070089class MMapedQueue {
90 public:
Austin Schuhaa79e4e2019-12-29 20:43:32 -080091 MMapedQueue(const Channel *channel,
92 const std::chrono::seconds channel_storage_duration) {
Alex Perrycb7da4b2019-08-28 19:35:56 -070093 std::string path = ShmPath(channel);
94
Austin Schuh80c7fce2019-12-05 20:48:43 -080095 config_.num_watchers = channel->num_watchers();
96 config_.num_senders = channel->num_senders();
Austin Schuhaa79e4e2019-12-29 20:43:32 -080097 config_.queue_size =
98 channel_storage_duration.count() * channel->frequency();
Alex Perrycb7da4b2019-08-28 19:35:56 -070099 config_.message_data_size = channel->max_size();
100
101 size_ = ipc_lib::LocklessQueueMemorySize(config_);
102
Austin Schuhfccb2d02020-01-26 16:11:19 -0800103 util::MkdirP(path, FLAGS_permissions);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700104
105 // There are 2 cases. Either the file already exists, or it does not
106 // already exist and we need to create it. Start by trying to create it. If
107 // that fails, the file has already been created and we can open it
108 // normally.. Once the file has been created it wil never be deleted.
Brian Silvermanf9f30ea2020-03-04 23:18:54 -0800109 int fd = open(path.c_str(), O_RDWR | O_CREAT | O_EXCL,
Alex Perrycb7da4b2019-08-28 19:35:56 -0700110 O_CLOEXEC | FLAGS_permissions);
Brian Silvermanf9f30ea2020-03-04 23:18:54 -0800111 if (fd == -1 && errno == EEXIST) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700112 VLOG(1) << path << " already created.";
113 // File already exists.
Brian Silvermanf9f30ea2020-03-04 23:18:54 -0800114 fd = open(path.c_str(), O_RDWR, O_CLOEXEC);
115 PCHECK(fd != -1) << ": Failed to open " << path;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700116 while (true) {
117 struct stat st;
Brian Silvermanf9f30ea2020-03-04 23:18:54 -0800118 PCHECK(fstat(fd, &st) == 0);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700119 if (st.st_size != 0) {
120 CHECK_EQ(static_cast<size_t>(st.st_size), size_)
121 << ": Size of " << path
122 << " doesn't match expected size of backing queue file. Did the "
123 "queue definition change?";
124 break;
125 } else {
126 // The creating process didn't get around to it yet. Give it a bit.
127 std::this_thread::sleep_for(std::chrono::milliseconds(10));
128 VLOG(1) << path << " is zero size, waiting";
129 }
130 }
131 } else {
132 VLOG(1) << "Created " << path;
Brian Silvermanf9f30ea2020-03-04 23:18:54 -0800133 PCHECK(fd != -1) << ": Failed to open " << path;
134 PCHECK(ftruncate(fd, size_) == 0);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700135 }
136
Brian Silvermanf9f30ea2020-03-04 23:18:54 -0800137 data_ = mmap(NULL, size_, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700138 PCHECK(data_ != MAP_FAILED);
Brian Silvermanf9f30ea2020-03-04 23:18:54 -0800139 PCHECK(close(fd) == 0);
Brian Silverman3b0cdaf2020-04-28 16:51:51 -0700140 PageFaultData(static_cast<char *>(data_), size_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700141
142 ipc_lib::InitializeLocklessQueueMemory(memory(), config_);
143 }
144
145 ~MMapedQueue() {
146 PCHECK(munmap(data_, size_) == 0);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700147 }
148
149 ipc_lib::LocklessQueueMemory *memory() const {
150 return reinterpret_cast<ipc_lib::LocklessQueueMemory *>(data_);
151 }
152
Austin Schuh39788ff2019-12-01 18:22:57 -0800153 const ipc_lib::LocklessQueueConfiguration &config() const { return config_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700154
Brian Silverman5120afb2020-01-31 17:44:35 -0800155 absl::Span<char> GetSharedMemory() const {
156 return absl::Span<char>(static_cast<char *>(data_), size_);
157 }
158
Alex Perrycb7da4b2019-08-28 19:35:56 -0700159 private:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700160 ipc_lib::LocklessQueueConfiguration config_;
161
Alex Perrycb7da4b2019-08-28 19:35:56 -0700162 size_t size_;
163 void *data_;
164};
165
Austin Schuh217a9782019-12-21 23:02:50 -0800166namespace {
167
Austin Schuh217a9782019-12-21 23:02:50 -0800168const Node *MaybeMyNode(const Configuration *configuration) {
169 if (!configuration->has_nodes()) {
170 return nullptr;
171 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700172
Austin Schuh217a9782019-12-21 23:02:50 -0800173 return configuration::GetMyNode(configuration);
174}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700175
176namespace chrono = ::std::chrono;
177
Austin Schuh39788ff2019-12-01 18:22:57 -0800178} // namespace
179
Austin Schuh217a9782019-12-21 23:02:50 -0800180ShmEventLoop::ShmEventLoop(const Configuration *configuration)
181 : EventLoop(configuration),
Austin Schuhe84c3ed2019-12-14 15:29:48 -0800182 name_(FLAGS_application_name),
Austin Schuh15649d62019-12-28 16:36:38 -0800183 node_(MaybeMyNode(configuration)) {
184 if (configuration->has_nodes()) {
185 CHECK(node_ != nullptr) << ": Couldn't find node in config.";
186 }
187}
Austin Schuh217a9782019-12-21 23:02:50 -0800188
Austin Schuh39788ff2019-12-01 18:22:57 -0800189namespace internal {
190
191class SimpleShmFetcher {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700192 public:
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800193 explicit SimpleShmFetcher(EventLoop *event_loop, const Channel *channel,
194 bool copy_data)
Austin Schuhf5652592019-12-29 16:26:15 -0800195 : channel_(channel),
Austin Schuhaa79e4e2019-12-29 20:43:32 -0800196 lockless_queue_memory_(
197 channel,
Brian Silverman587da252020-01-01 17:00:47 -0800198 chrono::ceil<chrono::seconds>(chrono::nanoseconds(
Austin Schuhaa79e4e2019-12-29 20:43:32 -0800199 event_loop->configuration()->channel_storage_duration()))),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700200 lockless_queue_(lockless_queue_memory_.memory(),
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800201 lockless_queue_memory_.config()) {
202 if (copy_data) {
203 data_storage_.reset(static_cast<char *>(
204 malloc(channel->max_size() + kChannelDataAlignment - 1)));
205 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700206 context_.data = nullptr;
207 // Point the queue index at the next index to read starting now. This
208 // makes it such that FetchNext will read the next message sent after
209 // the fetcher is created.
210 PointAtNextQueueIndex();
211 }
212
Austin Schuh39788ff2019-12-01 18:22:57 -0800213 ~SimpleShmFetcher() {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700214
215 // Points the next message to fetch at the queue index which will be
216 // populated next.
217 void PointAtNextQueueIndex() {
218 actual_queue_index_ = lockless_queue_.LatestQueueIndex();
219 if (!actual_queue_index_.valid()) {
220 // Nothing in the queue. The next element will show up at the 0th
221 // index in the queue.
222 actual_queue_index_ =
223 ipc_lib::QueueIndex::Zero(lockless_queue_.queue_size());
224 } else {
225 actual_queue_index_ = actual_queue_index_.Increment();
226 }
227 }
228
Austin Schuh39788ff2019-12-01 18:22:57 -0800229 bool FetchNext() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700230 // TODO(austin): Get behind and make sure it dies both here and with
231 // Fetch.
232 ipc_lib::LocklessQueue::ReadResult read_result = lockless_queue_.Read(
Austin Schuhad154822019-12-27 15:45:13 -0800233 actual_queue_index_.index(), &context_.monotonic_event_time,
234 &context_.realtime_event_time, &context_.monotonic_remote_time,
235 &context_.realtime_remote_time, &context_.remote_queue_index,
Brian Silvermana1652f32020-01-29 20:41:44 -0800236 &context_.size, data_storage_start());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700237 if (read_result == ipc_lib::LocklessQueue::ReadResult::GOOD) {
238 context_.queue_index = actual_queue_index_.index();
Austin Schuhad154822019-12-27 15:45:13 -0800239 if (context_.remote_queue_index == 0xffffffffu) {
240 context_.remote_queue_index = context_.queue_index;
241 }
242 if (context_.monotonic_remote_time == aos::monotonic_clock::min_time) {
243 context_.monotonic_remote_time = context_.monotonic_event_time;
244 }
245 if (context_.realtime_remote_time == aos::realtime_clock::min_time) {
246 context_.realtime_remote_time = context_.realtime_event_time;
247 }
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800248 if (copy_data()) {
249 context_.data = data_storage_start() +
250 lockless_queue_.message_data_size() - context_.size;
251 } else {
252 context_.data = nullptr;
253 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700254 actual_queue_index_ = actual_queue_index_.Increment();
255 }
256
257 // Make sure the data wasn't modified while we were reading it. This
258 // can only happen if you are reading the last message *while* it is
259 // being written to, which means you are pretty far behind.
260 CHECK(read_result != ipc_lib::LocklessQueue::ReadResult::OVERWROTE)
261 << ": Got behind while reading and the last message was modified "
Austin Schuhf5652592019-12-29 16:26:15 -0800262 "out from under us while we were reading it. Don't get so far "
263 "behind. "
264 << configuration::CleanedChannelToString(channel_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700265
266 CHECK(read_result != ipc_lib::LocklessQueue::ReadResult::TOO_OLD)
Austin Schuhf5652592019-12-29 16:26:15 -0800267 << ": The next message is no longer available. "
268 << configuration::CleanedChannelToString(channel_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700269 return read_result == ipc_lib::LocklessQueue::ReadResult::GOOD;
270 }
271
Austin Schuh39788ff2019-12-01 18:22:57 -0800272 bool Fetch() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700273 const ipc_lib::QueueIndex queue_index = lockless_queue_.LatestQueueIndex();
274 // actual_queue_index_ is only meaningful if it was set by Fetch or
275 // FetchNext. This happens when valid_data_ has been set. So, only
276 // skip checking if valid_data_ is true.
277 //
278 // Also, if the latest queue index is invalid, we are empty. So there
279 // is nothing to fetch.
Austin Schuh39788ff2019-12-01 18:22:57 -0800280 if ((context_.data != nullptr &&
Alex Perrycb7da4b2019-08-28 19:35:56 -0700281 queue_index == actual_queue_index_.DecrementBy(1u)) ||
282 !queue_index.valid()) {
283 return false;
284 }
285
Austin Schuhad154822019-12-27 15:45:13 -0800286 ipc_lib::LocklessQueue::ReadResult read_result = lockless_queue_.Read(
287 queue_index.index(), &context_.monotonic_event_time,
288 &context_.realtime_event_time, &context_.monotonic_remote_time,
289 &context_.realtime_remote_time, &context_.remote_queue_index,
Brian Silvermana1652f32020-01-29 20:41:44 -0800290 &context_.size, data_storage_start());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700291 if (read_result == ipc_lib::LocklessQueue::ReadResult::GOOD) {
292 context_.queue_index = queue_index.index();
Austin Schuhad154822019-12-27 15:45:13 -0800293 if (context_.remote_queue_index == 0xffffffffu) {
294 context_.remote_queue_index = context_.queue_index;
295 }
296 if (context_.monotonic_remote_time == aos::monotonic_clock::min_time) {
297 context_.monotonic_remote_time = context_.monotonic_event_time;
298 }
299 if (context_.realtime_remote_time == aos::realtime_clock::min_time) {
300 context_.realtime_remote_time = context_.realtime_event_time;
301 }
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800302 if (copy_data()) {
303 context_.data = data_storage_start() +
304 lockless_queue_.message_data_size() - context_.size;
305 } else {
306 context_.data = nullptr;
307 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700308 actual_queue_index_ = queue_index.Increment();
309 }
310
311 // Make sure the data wasn't modified while we were reading it. This
312 // can only happen if you are reading the last message *while* it is
313 // being written to, which means you are pretty far behind.
314 CHECK(read_result != ipc_lib::LocklessQueue::ReadResult::OVERWROTE)
315 << ": Got behind while reading and the last message was modified "
Austin Schuhf5652592019-12-29 16:26:15 -0800316 "out from under us while we were reading it. Don't get so far "
317 "behind."
318 << configuration::CleanedChannelToString(channel_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700319
320 CHECK(read_result != ipc_lib::LocklessQueue::ReadResult::NOTHING_NEW)
Austin Schuhf5652592019-12-29 16:26:15 -0800321 << ": Queue index went backwards. This should never happen. "
322 << configuration::CleanedChannelToString(channel_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700323
324 // We fell behind between when we read the index and read the value.
325 // This isn't worth recovering from since this means we went to sleep
326 // for a long time in the middle of this function.
327 CHECK(read_result != ipc_lib::LocklessQueue::ReadResult::TOO_OLD)
Austin Schuhf5652592019-12-29 16:26:15 -0800328 << ": The next message is no longer available. "
329 << configuration::CleanedChannelToString(channel_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700330 return read_result == ipc_lib::LocklessQueue::ReadResult::GOOD;
331 }
332
Austin Schuh39788ff2019-12-01 18:22:57 -0800333 Context context() const { return context_; }
334
Alex Perrycb7da4b2019-08-28 19:35:56 -0700335 bool RegisterWakeup(int priority) {
336 return lockless_queue_.RegisterWakeup(priority);
337 }
338
339 void UnregisterWakeup() { lockless_queue_.UnregisterWakeup(); }
340
Brian Silverman5120afb2020-01-31 17:44:35 -0800341 absl::Span<char> GetSharedMemory() const {
342 return lockless_queue_memory_.GetSharedMemory();
343 }
344
Alex Perrycb7da4b2019-08-28 19:35:56 -0700345 private:
Brian Silvermana1652f32020-01-29 20:41:44 -0800346 char *data_storage_start() {
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800347 if (!copy_data()) return nullptr;
Brian Silvermana1652f32020-01-29 20:41:44 -0800348 return RoundChannelData(data_storage_.get(), channel_->max_size());
349 }
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800350 bool copy_data() const { return static_cast<bool>(data_storage_); }
Brian Silvermana1652f32020-01-29 20:41:44 -0800351
Austin Schuhf5652592019-12-29 16:26:15 -0800352 const Channel *const channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700353 MMapedQueue lockless_queue_memory_;
354 ipc_lib::LocklessQueue lockless_queue_;
355
356 ipc_lib::QueueIndex actual_queue_index_ =
357 ipc_lib::LocklessQueue::empty_queue_index();
358
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800359 // This being empty indicates we're not going to copy data.
360 std::unique_ptr<char, decltype(&free)> data_storage_{nullptr, &free};
Austin Schuh39788ff2019-12-01 18:22:57 -0800361
362 Context context_;
363};
364
365class ShmFetcher : public RawFetcher {
366 public:
367 explicit ShmFetcher(EventLoop *event_loop, const Channel *channel)
Austin Schuhaa79e4e2019-12-29 20:43:32 -0800368 : RawFetcher(event_loop, channel),
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800369 simple_shm_fetcher_(event_loop, channel, true) {}
Austin Schuh39788ff2019-12-01 18:22:57 -0800370
371 ~ShmFetcher() { context_.data = nullptr; }
372
373 std::pair<bool, monotonic_clock::time_point> DoFetchNext() override {
374 if (simple_shm_fetcher_.FetchNext()) {
375 context_ = simple_shm_fetcher_.context();
376 return std::make_pair(true, monotonic_clock::now());
377 }
378 return std::make_pair(false, monotonic_clock::min_time);
379 }
380
381 std::pair<bool, monotonic_clock::time_point> DoFetch() override {
382 if (simple_shm_fetcher_.Fetch()) {
383 context_ = simple_shm_fetcher_.context();
384 return std::make_pair(true, monotonic_clock::now());
385 }
386 return std::make_pair(false, monotonic_clock::min_time);
387 }
388
389 private:
390 SimpleShmFetcher simple_shm_fetcher_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700391};
392
393class ShmSender : public RawSender {
394 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800395 explicit ShmSender(EventLoop *event_loop, const Channel *channel)
396 : RawSender(event_loop, channel),
Austin Schuhaa79e4e2019-12-29 20:43:32 -0800397 lockless_queue_memory_(
398 channel,
Brian Silverman587da252020-01-01 17:00:47 -0800399 chrono::ceil<chrono::seconds>(chrono::nanoseconds(
Austin Schuhaa79e4e2019-12-29 20:43:32 -0800400 event_loop->configuration()->channel_storage_duration()))),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700401 lockless_queue_(lockless_queue_memory_.memory(),
402 lockless_queue_memory_.config()),
403 lockless_queue_sender_(lockless_queue_.MakeSender()) {}
404
Austin Schuh39788ff2019-12-01 18:22:57 -0800405 ~ShmSender() override {}
406
Alex Perrycb7da4b2019-08-28 19:35:56 -0700407 void *data() override { return lockless_queue_sender_.Data(); }
408 size_t size() override { return lockless_queue_sender_.size(); }
Austin Schuhad154822019-12-27 15:45:13 -0800409 bool DoSend(size_t length,
410 aos::monotonic_clock::time_point monotonic_remote_time,
411 aos::realtime_clock::time_point realtime_remote_time,
412 uint32_t remote_queue_index) override {
Austin Schuh0f7ed462020-03-28 20:38:34 -0700413 CHECK_LE(length, static_cast<size_t>(channel()->max_size()))
414 << ": Sent too big a message on "
415 << configuration::CleanedChannelToString(channel());
Austin Schuhad154822019-12-27 15:45:13 -0800416 lockless_queue_sender_.Send(
417 length, monotonic_remote_time, realtime_remote_time, remote_queue_index,
418 &monotonic_sent_time_, &realtime_sent_time_, &sent_queue_index_);
Austin Schuh39788ff2019-12-01 18:22:57 -0800419 lockless_queue_.Wakeup(event_loop()->priority());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700420 return true;
421 }
422
Austin Schuhad154822019-12-27 15:45:13 -0800423 bool DoSend(const void *msg, size_t length,
424 aos::monotonic_clock::time_point monotonic_remote_time,
425 aos::realtime_clock::time_point realtime_remote_time,
426 uint32_t remote_queue_index) override {
Austin Schuh0f7ed462020-03-28 20:38:34 -0700427 CHECK_LE(length, static_cast<size_t>(channel()->max_size()))
428 << ": Sent too big a message on "
429 << configuration::CleanedChannelToString(channel());
Austin Schuhad154822019-12-27 15:45:13 -0800430 lockless_queue_sender_.Send(reinterpret_cast<const char *>(msg), length,
431 monotonic_remote_time, realtime_remote_time,
432 remote_queue_index, &monotonic_sent_time_,
433 &realtime_sent_time_, &sent_queue_index_);
Austin Schuh39788ff2019-12-01 18:22:57 -0800434 lockless_queue_.Wakeup(event_loop()->priority());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700435 // TODO(austin): Return an error if we send too fast.
436 return true;
437 }
438
Brian Silverman5120afb2020-01-31 17:44:35 -0800439 absl::Span<char> GetSharedMemory() const {
440 return lockless_queue_memory_.GetSharedMemory();
441 }
442
Alex Perrycb7da4b2019-08-28 19:35:56 -0700443 private:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700444 MMapedQueue lockless_queue_memory_;
445 ipc_lib::LocklessQueue lockless_queue_;
446 ipc_lib::LocklessQueue::Sender lockless_queue_sender_;
447};
448
Alex Perrycb7da4b2019-08-28 19:35:56 -0700449// Class to manage the state for a Watcher.
Austin Schuh39788ff2019-12-01 18:22:57 -0800450class WatcherState : public aos::WatcherState {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700451 public:
452 WatcherState(
Austin Schuh7d87b672019-12-01 20:23:49 -0800453 ShmEventLoop *event_loop, const Channel *channel,
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800454 std::function<void(const Context &context, const void *message)> fn,
455 bool copy_data)
Austin Schuh39788ff2019-12-01 18:22:57 -0800456 : aos::WatcherState(event_loop, channel, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800457 event_loop_(event_loop),
458 event_(this),
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800459 simple_shm_fetcher_(event_loop, channel, copy_data) {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700460
Austin Schuh7d87b672019-12-01 20:23:49 -0800461 ~WatcherState() override { event_loop_->RemoveEvent(&event_); }
Austin Schuh39788ff2019-12-01 18:22:57 -0800462
463 void Startup(EventLoop *event_loop) override {
Austin Schuh7d87b672019-12-01 20:23:49 -0800464 simple_shm_fetcher_.PointAtNextQueueIndex();
Austin Schuh39788ff2019-12-01 18:22:57 -0800465 CHECK(RegisterWakeup(event_loop->priority()));
466 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700467
Alex Perrycb7da4b2019-08-28 19:35:56 -0700468 // Returns true if there is new data available.
Austin Schuh7d87b672019-12-01 20:23:49 -0800469 bool CheckForNewData() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700470 if (!has_new_data_) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800471 has_new_data_ = simple_shm_fetcher_.FetchNext();
Austin Schuh7d87b672019-12-01 20:23:49 -0800472
473 if (has_new_data_) {
474 event_.set_event_time(
Austin Schuhad154822019-12-27 15:45:13 -0800475 simple_shm_fetcher_.context().monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800476 event_loop_->AddEvent(&event_);
477 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700478 }
479
480 return has_new_data_;
481 }
482
Alex Perrycb7da4b2019-08-28 19:35:56 -0700483 // Consumes the data by calling the callback.
Austin Schuh7d87b672019-12-01 20:23:49 -0800484 void HandleEvent() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700485 CHECK(has_new_data_);
Austin Schuh39788ff2019-12-01 18:22:57 -0800486 DoCallCallback(monotonic_clock::now, simple_shm_fetcher_.context());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700487 has_new_data_ = false;
Austin Schuh7d87b672019-12-01 20:23:49 -0800488 CheckForNewData();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700489 }
490
Austin Schuh39788ff2019-12-01 18:22:57 -0800491 // Registers us to receive a signal on event reception.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700492 bool RegisterWakeup(int priority) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800493 return simple_shm_fetcher_.RegisterWakeup(priority);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700494 }
495
Austin Schuh39788ff2019-12-01 18:22:57 -0800496 void UnregisterWakeup() { return simple_shm_fetcher_.UnregisterWakeup(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700497
Brian Silverman5120afb2020-01-31 17:44:35 -0800498 absl::Span<char> GetSharedMemory() const {
499 return simple_shm_fetcher_.GetSharedMemory();
500 }
501
Alex Perrycb7da4b2019-08-28 19:35:56 -0700502 private:
503 bool has_new_data_ = false;
504
Austin Schuh7d87b672019-12-01 20:23:49 -0800505 ShmEventLoop *event_loop_;
506 EventHandler<WatcherState> event_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800507 SimpleShmFetcher simple_shm_fetcher_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700508};
509
510// Adapter class to adapt a timerfd to a TimerHandler.
Austin Schuh7d87b672019-12-01 20:23:49 -0800511class TimerHandlerState final : public TimerHandler {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700512 public:
513 TimerHandlerState(ShmEventLoop *shm_event_loop, ::std::function<void()> fn)
Austin Schuh39788ff2019-12-01 18:22:57 -0800514 : TimerHandler(shm_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800515 shm_event_loop_(shm_event_loop),
516 event_(this) {
Austin Schuhcde39fd2020-02-22 20:58:24 -0800517 shm_event_loop_->epoll_.OnReadable(timerfd_.fd(), [this]() {
518 // The timer may fire spurriously. HandleEvent on the event loop will
519 // call the callback if it is needed. It may also have called it when
520 // processing some other event, and the kernel decided to deliver this
521 // wakeup anyways.
522 timerfd_.Read();
523 shm_event_loop_->HandleEvent();
524 });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700525 }
526
Austin Schuh7d87b672019-12-01 20:23:49 -0800527 ~TimerHandlerState() {
528 Disable();
529 shm_event_loop_->epoll_.DeleteFd(timerfd_.fd());
530 }
531
532 void HandleEvent() {
Austin Schuhcde39fd2020-02-22 20:58:24 -0800533 CHECK(!event_.valid());
534 const auto monotonic_now = Call(monotonic_clock::now, base_);
535 if (event_.valid()) {
536 // If someone called Setup inside Call, rescheduling is already taken care
537 // of. Bail.
538 return;
Austin Schuh7d87b672019-12-01 20:23:49 -0800539 }
540
Austin Schuhcde39fd2020-02-22 20:58:24 -0800541 if (repeat_offset_ == chrono::seconds(0)) {
542 timerfd_.Disable();
543 } else {
544 // Compute how many cycles have elapsed and schedule the next iteration
545 // for the next iteration in the future.
546 const int elapsed_cycles =
547 std::max<int>(0, (monotonic_now - base_ + repeat_offset_ -
548 std::chrono::nanoseconds(1)) /
549 repeat_offset_);
550 base_ += repeat_offset_ * elapsed_cycles;
Austin Schuh7d87b672019-12-01 20:23:49 -0800551
Austin Schuhcde39fd2020-02-22 20:58:24 -0800552 // Update the heap and schedule the timerfd wakeup.
Austin Schuh7d87b672019-12-01 20:23:49 -0800553 event_.set_event_time(base_);
554 shm_event_loop_->AddEvent(&event_);
Austin Schuhcde39fd2020-02-22 20:58:24 -0800555 timerfd_.SetTime(base_, chrono::seconds(0));
Austin Schuh7d87b672019-12-01 20:23:49 -0800556 }
557 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700558
559 void Setup(monotonic_clock::time_point base,
560 monotonic_clock::duration repeat_offset) override {
Austin Schuh7d87b672019-12-01 20:23:49 -0800561 if (event_.valid()) {
562 shm_event_loop_->RemoveEvent(&event_);
563 }
564
Alex Perrycb7da4b2019-08-28 19:35:56 -0700565 timerfd_.SetTime(base, repeat_offset);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800566 base_ = base;
567 repeat_offset_ = repeat_offset;
Austin Schuh7d87b672019-12-01 20:23:49 -0800568 event_.set_event_time(base_);
569 shm_event_loop_->AddEvent(&event_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700570 }
571
Austin Schuh7d87b672019-12-01 20:23:49 -0800572 void Disable() override {
573 shm_event_loop_->RemoveEvent(&event_);
574 timerfd_.Disable();
575 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700576
577 private:
578 ShmEventLoop *shm_event_loop_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800579 EventHandler<TimerHandlerState> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700580
581 TimerFd timerfd_;
582
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800583 monotonic_clock::time_point base_;
584 monotonic_clock::duration repeat_offset_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700585};
586
587// Adapter class to the timerfd and PhasedLoop.
Austin Schuh7d87b672019-12-01 20:23:49 -0800588class PhasedLoopHandler final : public ::aos::PhasedLoopHandler {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700589 public:
590 PhasedLoopHandler(ShmEventLoop *shm_event_loop, ::std::function<void(int)> fn,
591 const monotonic_clock::duration interval,
592 const monotonic_clock::duration offset)
Austin Schuh39788ff2019-12-01 18:22:57 -0800593 : aos::PhasedLoopHandler(shm_event_loop, std::move(fn), interval, offset),
Austin Schuh7d87b672019-12-01 20:23:49 -0800594 shm_event_loop_(shm_event_loop),
595 event_(this) {
596 shm_event_loop_->epoll_.OnReadable(
597 timerfd_.fd(), [this]() { shm_event_loop_->HandleEvent(); });
598 }
599
600 void HandleEvent() {
601 // The return value for read is the number of cycles that have elapsed.
602 // Because we check to see when this event *should* have happened, there are
603 // cases where Read() will return 0, when 1 cycle has actually happened.
604 // This occurs when the timer interrupt hasn't triggered yet. Therefore,
605 // ignore it. Call handles rescheduling and calculating elapsed cycles
606 // without any extra help.
607 timerfd_.Read();
608 event_.Invalidate();
609
610 Call(monotonic_clock::now, [this](monotonic_clock::time_point sleep_time) {
611 Schedule(sleep_time);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700612 });
613 }
614
Austin Schuh39788ff2019-12-01 18:22:57 -0800615 ~PhasedLoopHandler() override {
616 shm_event_loop_->epoll_.DeleteFd(timerfd_.fd());
Austin Schuh7d87b672019-12-01 20:23:49 -0800617 shm_event_loop_->RemoveEvent(&event_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700618 }
619
620 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800621 // Reschedules the timer.
Austin Schuh39788ff2019-12-01 18:22:57 -0800622 void Schedule(monotonic_clock::time_point sleep_time) override {
Austin Schuh7d87b672019-12-01 20:23:49 -0800623 if (event_.valid()) {
624 shm_event_loop_->RemoveEvent(&event_);
625 }
626
Austin Schuh39788ff2019-12-01 18:22:57 -0800627 timerfd_.SetTime(sleep_time, ::aos::monotonic_clock::zero());
Austin Schuh7d87b672019-12-01 20:23:49 -0800628 event_.set_event_time(sleep_time);
629 shm_event_loop_->AddEvent(&event_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700630 }
631
632 ShmEventLoop *shm_event_loop_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800633 EventHandler<PhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700634
635 TimerFd timerfd_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700636};
637} // namespace internal
638
639::std::unique_ptr<RawFetcher> ShmEventLoop::MakeRawFetcher(
640 const Channel *channel) {
Austin Schuhca4828c2019-12-28 14:21:35 -0800641 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
642 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
643 << "\", \"type\": \"" << channel->type()->string_view()
644 << "\" } is not able to be fetched on this node. Check your "
645 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800646 }
647
Austin Schuh39788ff2019-12-01 18:22:57 -0800648 return ::std::unique_ptr<RawFetcher>(new internal::ShmFetcher(this, channel));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700649}
650
651::std::unique_ptr<RawSender> ShmEventLoop::MakeRawSender(
652 const Channel *channel) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800653 TakeSender(channel);
Austin Schuh39788ff2019-12-01 18:22:57 -0800654
655 return ::std::unique_ptr<RawSender>(new internal::ShmSender(this, channel));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700656}
657
658void ShmEventLoop::MakeRawWatcher(
659 const Channel *channel,
660 std::function<void(const Context &context, const void *message)> watcher) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800661 TakeWatcher(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800662
Austin Schuh39788ff2019-12-01 18:22:57 -0800663 NewWatcher(::std::unique_ptr<WatcherState>(
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800664 new internal::WatcherState(this, channel, std::move(watcher), true)));
665}
666
667void ShmEventLoop::MakeRawNoArgWatcher(
668 const Channel *channel,
669 std::function<void(const Context &context)> watcher) {
670 TakeWatcher(channel);
671
672 NewWatcher(::std::unique_ptr<WatcherState>(new internal::WatcherState(
673 this, channel,
674 [watcher](const Context &context, const void *) { watcher(context); },
675 false)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700676}
677
678TimerHandler *ShmEventLoop::AddTimer(::std::function<void()> callback) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800679 return NewTimer(::std::unique_ptr<TimerHandler>(
680 new internal::TimerHandlerState(this, ::std::move(callback))));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700681}
682
683PhasedLoopHandler *ShmEventLoop::AddPhasedLoop(
684 ::std::function<void(int)> callback,
685 const monotonic_clock::duration interval,
686 const monotonic_clock::duration offset) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800687 return NewPhasedLoop(
688 ::std::unique_ptr<PhasedLoopHandler>(new internal::PhasedLoopHandler(
689 this, ::std::move(callback), interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700690}
691
692void ShmEventLoop::OnRun(::std::function<void()> on_run) {
693 on_run_.push_back(::std::move(on_run));
694}
695
Austin Schuh7d87b672019-12-01 20:23:49 -0800696void ShmEventLoop::HandleEvent() {
697 // Update all the times for handlers.
698 for (::std::unique_ptr<WatcherState> &base_watcher : watchers_) {
699 internal::WatcherState *watcher =
700 reinterpret_cast<internal::WatcherState *>(base_watcher.get());
701
702 watcher->CheckForNewData();
703 }
704
Austin Schuh39788ff2019-12-01 18:22:57 -0800705 while (true) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800706 if (EventCount() == 0 ||
707 PeekEvent()->event_time() > monotonic_clock::now()) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800708 break;
709 }
710
Austin Schuh7d87b672019-12-01 20:23:49 -0800711 EventLoopEvent *event = PopEvent();
712 event->HandleEvent();
Austin Schuh39788ff2019-12-01 18:22:57 -0800713 }
714}
715
Austin Schuh32fd5a72019-12-01 22:20:26 -0800716// RAII class to mask signals.
717class ScopedSignalMask {
718 public:
719 ScopedSignalMask(std::initializer_list<int> signals) {
720 sigset_t sigset;
721 PCHECK(sigemptyset(&sigset) == 0);
722 for (int signal : signals) {
723 PCHECK(sigaddset(&sigset, signal) == 0);
724 }
725
726 PCHECK(sigprocmask(SIG_BLOCK, &sigset, &old_) == 0);
727 }
728
729 ~ScopedSignalMask() { PCHECK(sigprocmask(SIG_SETMASK, &old_, nullptr) == 0); }
730
731 private:
732 sigset_t old_;
733};
734
735// Class to manage the static state associated with killing multiple event
736// loops.
737class SignalHandler {
738 public:
739 // Gets the singleton.
740 static SignalHandler *global() {
741 static SignalHandler loop;
742 return &loop;
743 }
744
745 // Handles the signal with the singleton.
746 static void HandleSignal(int) { global()->DoHandleSignal(); }
747
748 // Registers an event loop to receive Exit() calls.
749 void Register(ShmEventLoop *event_loop) {
750 // Block signals while we have the mutex so we never race with the signal
751 // handler.
752 ScopedSignalMask mask({SIGINT, SIGHUP, SIGTERM});
753 std::unique_lock<stl_mutex> locker(mutex_);
754 if (event_loops_.size() == 0) {
755 // The first caller registers the signal handler.
756 struct sigaction new_action;
757 sigemptyset(&new_action.sa_mask);
758 // This makes it so that 2 control c's to a stuck process will kill it by
759 // restoring the original signal handler.
760 new_action.sa_flags = SA_RESETHAND;
761 new_action.sa_handler = &HandleSignal;
762
763 PCHECK(sigaction(SIGINT, &new_action, &old_action_int_) == 0);
764 PCHECK(sigaction(SIGHUP, &new_action, &old_action_hup_) == 0);
765 PCHECK(sigaction(SIGTERM, &new_action, &old_action_term_) == 0);
766 }
767
768 event_loops_.push_back(event_loop);
769 }
770
771 // Unregisters an event loop to receive Exit() calls.
772 void Unregister(ShmEventLoop *event_loop) {
773 // Block signals while we have the mutex so we never race with the signal
774 // handler.
775 ScopedSignalMask mask({SIGINT, SIGHUP, SIGTERM});
776 std::unique_lock<stl_mutex> locker(mutex_);
777
Brian Silverman5120afb2020-01-31 17:44:35 -0800778 event_loops_.erase(
779 std::find(event_loops_.begin(), event_loops_.end(), event_loop));
Austin Schuh32fd5a72019-12-01 22:20:26 -0800780
781 if (event_loops_.size() == 0u) {
782 // The last caller restores the original signal handlers.
783 PCHECK(sigaction(SIGINT, &old_action_int_, nullptr) == 0);
784 PCHECK(sigaction(SIGHUP, &old_action_hup_, nullptr) == 0);
785 PCHECK(sigaction(SIGTERM, &old_action_term_, nullptr) == 0);
786 }
787 }
788
789 private:
790 void DoHandleSignal() {
791 // We block signals while grabbing the lock, so there should never be a
792 // race. Confirm that this is true using trylock.
793 CHECK(mutex_.try_lock()) << ": sigprocmask failed to block signals while "
794 "modifing the event loop list.";
795 for (ShmEventLoop *event_loop : event_loops_) {
796 event_loop->Exit();
797 }
798 mutex_.unlock();
799 }
800
801 // Mutex to protect all state.
802 stl_mutex mutex_;
803 std::vector<ShmEventLoop *> event_loops_;
804 struct sigaction old_action_int_;
805 struct sigaction old_action_hup_;
806 struct sigaction old_action_term_;
807};
808
Alex Perrycb7da4b2019-08-28 19:35:56 -0700809void ShmEventLoop::Run() {
Austin Schuh32fd5a72019-12-01 22:20:26 -0800810 SignalHandler::global()->Register(this);
Austin Schuh39788ff2019-12-01 18:22:57 -0800811
Alex Perrycb7da4b2019-08-28 19:35:56 -0700812 std::unique_ptr<ipc_lib::SignalFd> signalfd;
813
814 if (watchers_.size() > 0) {
815 signalfd.reset(new ipc_lib::SignalFd({ipc_lib::kWakeupSignal}));
816
817 epoll_.OnReadable(signalfd->fd(), [signalfd_ptr = signalfd.get(), this]() {
818 signalfd_siginfo result = signalfd_ptr->Read();
819 CHECK_EQ(result.ssi_signo, ipc_lib::kWakeupSignal);
820
821 // TODO(austin): We should really be checking *everything*, not just
822 // watchers, and calling the oldest thing first. That will improve
823 // determinism a lot.
824
Austin Schuh7d87b672019-12-01 20:23:49 -0800825 HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700826 });
827 }
828
Austin Schuh39788ff2019-12-01 18:22:57 -0800829 MaybeScheduleTimingReports();
830
Austin Schuh7d87b672019-12-01 20:23:49 -0800831 ReserveEvents();
832
Tyler Chatow67ddb032020-01-12 14:30:04 -0800833 {
834 AosLogToFbs aos_logger;
835 if (!skip_logger_) {
836 aos_logger.Initialize(MakeSender<logging::LogMessageFbs>("/aos"));
837 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700838
Tyler Chatow67ddb032020-01-12 14:30:04 -0800839 aos::SetCurrentThreadName(name_.substr(0, 16));
840 // Now, all the callbacks are setup. Lock everything into memory and go RT.
841 if (priority_ != 0) {
842 ::aos::InitRT();
843
844 LOG(INFO) << "Setting priority to " << priority_;
845 ::aos::SetCurrentThreadRealtimePriority(priority_);
846 }
847
848 set_is_running(true);
849
850 // Now that we are realtime (but before the OnRun handlers run), snap the
851 // queue index.
852 for (::std::unique_ptr<WatcherState> &watcher : watchers_) {
853 watcher->Startup(this);
854 }
855
856 // Now that we are RT, run all the OnRun handlers.
857 for (const auto &run : on_run_) {
858 run();
859 }
860
861 // And start our main event loop which runs all the timers and handles Quit.
862 epoll_.Run();
863
864 // Once epoll exits, there is no useful nonrt work left to do.
865 set_is_running(false);
866
867 // Nothing time or synchronization critical needs to happen after this
868 // point. Drop RT priority.
869 ::aos::UnsetCurrentThreadRealtimePriority();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700870 }
871
Austin Schuh39788ff2019-12-01 18:22:57 -0800872 for (::std::unique_ptr<WatcherState> &base_watcher : watchers_) {
873 internal::WatcherState *watcher =
874 reinterpret_cast<internal::WatcherState *>(base_watcher.get());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700875 watcher->UnregisterWakeup();
876 }
877
878 if (watchers_.size() > 0) {
879 epoll_.DeleteFd(signalfd->fd());
880 signalfd.reset();
881 }
Austin Schuh32fd5a72019-12-01 22:20:26 -0800882
883 SignalHandler::global()->Unregister(this);
Austin Schuhe84c3ed2019-12-14 15:29:48 -0800884
885 // Trigger any remaining senders or fetchers to be cleared before destroying
886 // the event loop so the book keeping matches. Do this in the thread that
887 // created the timing reporter.
888 timing_report_sender_.reset();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700889}
890
891void ShmEventLoop::Exit() { epoll_.Quit(); }
892
893ShmEventLoop::~ShmEventLoop() {
Austin Schuh39788ff2019-12-01 18:22:57 -0800894 // Force everything with a registered fd with epoll to be destroyed now.
895 timers_.clear();
896 phased_loops_.clear();
897 watchers_.clear();
898
Alex Perrycb7da4b2019-08-28 19:35:56 -0700899 CHECK(!is_running()) << ": ShmEventLoop destroyed while running";
900}
901
Alex Perrycb7da4b2019-08-28 19:35:56 -0700902void ShmEventLoop::SetRuntimeRealtimePriority(int priority) {
903 if (is_running()) {
904 LOG(FATAL) << "Cannot set realtime priority while running.";
905 }
906 priority_ = priority;
907}
908
James Kuszmaul57c2baa2020-01-19 14:52:52 -0800909void ShmEventLoop::set_name(const std::string_view name) {
910 name_ = std::string(name);
911 UpdateTimingReport();
912}
913
Brian Silverman5120afb2020-01-31 17:44:35 -0800914absl::Span<char> ShmEventLoop::GetWatcherSharedMemory(const Channel *channel) {
915 internal::WatcherState *const watcher_state =
916 static_cast<internal::WatcherState *>(GetWatcherState(channel));
917 return watcher_state->GetSharedMemory();
918}
919
920absl::Span<char> ShmEventLoop::GetShmSenderSharedMemory(
921 const aos::RawSender *sender) const {
922 return static_cast<const internal::ShmSender *>(sender)->GetSharedMemory();
923}
924
Austin Schuh39788ff2019-12-01 18:22:57 -0800925pid_t ShmEventLoop::GetTid() { return syscall(SYS_gettid); }
926
Alex Perrycb7da4b2019-08-28 19:35:56 -0700927} // namespace aos