blob: 13155107d97501f554981403755e4421b617d74b [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
Brian Silverman148d43d2020-06-07 18:19:22 -050050using namespace shm_event_loop_internal;
51
Austin Schuhcdab6192019-12-29 17:47:46 -080052void SetShmBase(const std::string_view base) {
53 FLAGS_shm_base = std::string(base) + "/dev/shm/aos";
54}
55
Alex Perrycb7da4b2019-08-28 19:35:56 -070056std::string ShmFolder(const Channel *channel) {
57 CHECK(channel->has_name());
58 CHECK_EQ(channel->name()->string_view()[0], '/');
59 return FLAGS_shm_base + channel->name()->str() + "/";
60}
61std::string ShmPath(const Channel *channel) {
62 CHECK(channel->has_type());
Austin Schuh3328d132020-02-28 13:54:57 -080063 return ShmFolder(channel) + channel->type()->str() + ".v2";
Alex Perrycb7da4b2019-08-28 19:35:56 -070064}
65
66class MMapedQueue {
67 public:
Austin Schuhaa79e4e2019-12-29 20:43:32 -080068 MMapedQueue(const Channel *channel,
69 const std::chrono::seconds channel_storage_duration) {
Alex Perrycb7da4b2019-08-28 19:35:56 -070070 std::string path = ShmPath(channel);
71
Austin Schuh80c7fce2019-12-05 20:48:43 -080072 config_.num_watchers = channel->num_watchers();
73 config_.num_senders = channel->num_senders();
Austin Schuhaa79e4e2019-12-29 20:43:32 -080074 config_.queue_size =
75 channel_storage_duration.count() * channel->frequency();
Alex Perrycb7da4b2019-08-28 19:35:56 -070076 config_.message_data_size = channel->max_size();
77
78 size_ = ipc_lib::LocklessQueueMemorySize(config_);
79
Austin Schuhfccb2d02020-01-26 16:11:19 -080080 util::MkdirP(path, FLAGS_permissions);
Alex Perrycb7da4b2019-08-28 19:35:56 -070081
82 // There are 2 cases. Either the file already exists, or it does not
83 // already exist and we need to create it. Start by trying to create it. If
84 // that fails, the file has already been created and we can open it
85 // normally.. Once the file has been created it wil never be deleted.
Brian Silvermanf9f30ea2020-03-04 23:18:54 -080086 int fd = open(path.c_str(), O_RDWR | O_CREAT | O_EXCL,
Brian Silverman148d43d2020-06-07 18:19:22 -050087 O_CLOEXEC | FLAGS_permissions);
Brian Silvermanf9f30ea2020-03-04 23:18:54 -080088 if (fd == -1 && errno == EEXIST) {
Alex Perrycb7da4b2019-08-28 19:35:56 -070089 VLOG(1) << path << " already created.";
90 // File already exists.
Brian Silvermanf9f30ea2020-03-04 23:18:54 -080091 fd = open(path.c_str(), O_RDWR, O_CLOEXEC);
92 PCHECK(fd != -1) << ": Failed to open " << path;
Alex Perrycb7da4b2019-08-28 19:35:56 -070093 while (true) {
94 struct stat st;
Brian Silvermanf9f30ea2020-03-04 23:18:54 -080095 PCHECK(fstat(fd, &st) == 0);
Alex Perrycb7da4b2019-08-28 19:35:56 -070096 if (st.st_size != 0) {
97 CHECK_EQ(static_cast<size_t>(st.st_size), size_)
98 << ": Size of " << path
99 << " doesn't match expected size of backing queue file. Did the "
100 "queue definition change?";
101 break;
102 } else {
103 // The creating process didn't get around to it yet. Give it a bit.
104 std::this_thread::sleep_for(std::chrono::milliseconds(10));
105 VLOG(1) << path << " is zero size, waiting";
106 }
107 }
108 } else {
109 VLOG(1) << "Created " << path;
Brian Silvermanf9f30ea2020-03-04 23:18:54 -0800110 PCHECK(fd != -1) << ": Failed to open " << path;
111 PCHECK(ftruncate(fd, size_) == 0);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700112 }
113
Brian Silvermanf9f30ea2020-03-04 23:18:54 -0800114 data_ = mmap(NULL, size_, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700115 PCHECK(data_ != MAP_FAILED);
Brian Silvermanf9f30ea2020-03-04 23:18:54 -0800116 PCHECK(close(fd) == 0);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700117
118 ipc_lib::InitializeLocklessQueueMemory(memory(), config_);
119 }
120
Brian Silverman148d43d2020-06-07 18:19:22 -0500121 ~MMapedQueue() { PCHECK(munmap(data_, size_) == 0); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700122
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
Brian Silverman148d43d2020-06-07 18:19:22 -0500163namespace shm_event_loop_internal {
Austin Schuh39788ff2019-12-01 18:22:57 -0800164
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
Brian Silverman6d2b3592020-06-18 14:40:15 -0700319 absl::Span<char> GetPrivateMemory() const {
320 CHECK(copy_data());
321 return absl::Span<char>(
322 const_cast<SimpleShmFetcher *>(this)->data_storage_start(),
323 lockless_queue_.message_data_size());
324 }
325
Alex Perrycb7da4b2019-08-28 19:35:56 -0700326 private:
Brian Silvermana1652f32020-01-29 20:41:44 -0800327 char *data_storage_start() {
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800328 if (!copy_data()) return nullptr;
Brian Silvermana1652f32020-01-29 20:41:44 -0800329 return RoundChannelData(data_storage_.get(), channel_->max_size());
330 }
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800331 bool copy_data() const { return static_cast<bool>(data_storage_); }
Brian Silvermana1652f32020-01-29 20:41:44 -0800332
Austin Schuhf5652592019-12-29 16:26:15 -0800333 const Channel *const channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700334 MMapedQueue lockless_queue_memory_;
335 ipc_lib::LocklessQueue lockless_queue_;
336
337 ipc_lib::QueueIndex actual_queue_index_ =
338 ipc_lib::LocklessQueue::empty_queue_index();
339
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800340 // This being empty indicates we're not going to copy data.
341 std::unique_ptr<char, decltype(&free)> data_storage_{nullptr, &free};
Austin Schuh39788ff2019-12-01 18:22:57 -0800342
343 Context context_;
344};
345
346class ShmFetcher : public RawFetcher {
347 public:
348 explicit ShmFetcher(EventLoop *event_loop, const Channel *channel)
Austin Schuhaa79e4e2019-12-29 20:43:32 -0800349 : RawFetcher(event_loop, channel),
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800350 simple_shm_fetcher_(event_loop, channel, true) {}
Austin Schuh39788ff2019-12-01 18:22:57 -0800351
352 ~ShmFetcher() { context_.data = nullptr; }
353
354 std::pair<bool, monotonic_clock::time_point> DoFetchNext() override {
355 if (simple_shm_fetcher_.FetchNext()) {
356 context_ = simple_shm_fetcher_.context();
357 return std::make_pair(true, monotonic_clock::now());
358 }
359 return std::make_pair(false, monotonic_clock::min_time);
360 }
361
362 std::pair<bool, monotonic_clock::time_point> DoFetch() override {
363 if (simple_shm_fetcher_.Fetch()) {
364 context_ = simple_shm_fetcher_.context();
365 return std::make_pair(true, monotonic_clock::now());
366 }
367 return std::make_pair(false, monotonic_clock::min_time);
368 }
369
Brian Silverman6d2b3592020-06-18 14:40:15 -0700370 absl::Span<char> GetPrivateMemory() const {
371 return simple_shm_fetcher_.GetPrivateMemory();
372 }
373
Austin Schuh39788ff2019-12-01 18:22:57 -0800374 private:
375 SimpleShmFetcher simple_shm_fetcher_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700376};
377
378class ShmSender : public RawSender {
379 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800380 explicit ShmSender(EventLoop *event_loop, const Channel *channel)
381 : RawSender(event_loop, channel),
Austin Schuhaa79e4e2019-12-29 20:43:32 -0800382 lockless_queue_memory_(
383 channel,
Brian Silverman587da252020-01-01 17:00:47 -0800384 chrono::ceil<chrono::seconds>(chrono::nanoseconds(
Austin Schuhaa79e4e2019-12-29 20:43:32 -0800385 event_loop->configuration()->channel_storage_duration()))),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700386 lockless_queue_(lockless_queue_memory_.memory(),
387 lockless_queue_memory_.config()),
Austin Schuhe516ab02020-05-06 21:37:04 -0700388 lockless_queue_sender_(
389 VerifySender(lockless_queue_.MakeSender(), channel)) {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700390
Austin Schuh39788ff2019-12-01 18:22:57 -0800391 ~ShmSender() override {}
392
Austin Schuhe516ab02020-05-06 21:37:04 -0700393 static ipc_lib::LocklessQueue::Sender VerifySender(
394 std::optional<ipc_lib::LocklessQueue::Sender> &&sender,
395 const Channel *channel) {
396 if (sender) {
397 return std::move(sender.value());
398 }
399 LOG(FATAL) << "Failed to create sender on "
400 << configuration::CleanedChannelToString(channel)
401 << ", too many senders.";
402 }
403
Alex Perrycb7da4b2019-08-28 19:35:56 -0700404 void *data() override { return lockless_queue_sender_.Data(); }
405 size_t size() override { return lockless_queue_sender_.size(); }
Austin Schuhad154822019-12-27 15:45:13 -0800406 bool DoSend(size_t length,
407 aos::monotonic_clock::time_point monotonic_remote_time,
408 aos::realtime_clock::time_point realtime_remote_time,
409 uint32_t remote_queue_index) override {
Austin Schuh0f7ed462020-03-28 20:38:34 -0700410 CHECK_LE(length, static_cast<size_t>(channel()->max_size()))
411 << ": Sent too big a message on "
412 << configuration::CleanedChannelToString(channel());
Austin Schuhad154822019-12-27 15:45:13 -0800413 lockless_queue_sender_.Send(
414 length, monotonic_remote_time, realtime_remote_time, remote_queue_index,
415 &monotonic_sent_time_, &realtime_sent_time_, &sent_queue_index_);
Austin Schuh39788ff2019-12-01 18:22:57 -0800416 lockless_queue_.Wakeup(event_loop()->priority());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700417 return true;
418 }
419
Austin Schuhad154822019-12-27 15:45:13 -0800420 bool DoSend(const void *msg, size_t length,
421 aos::monotonic_clock::time_point monotonic_remote_time,
422 aos::realtime_clock::time_point realtime_remote_time,
423 uint32_t remote_queue_index) override {
Austin Schuh0f7ed462020-03-28 20:38:34 -0700424 CHECK_LE(length, static_cast<size_t>(channel()->max_size()))
425 << ": Sent too big a message on "
426 << configuration::CleanedChannelToString(channel());
Austin Schuhad154822019-12-27 15:45:13 -0800427 lockless_queue_sender_.Send(reinterpret_cast<const char *>(msg), length,
428 monotonic_remote_time, realtime_remote_time,
429 remote_queue_index, &monotonic_sent_time_,
430 &realtime_sent_time_, &sent_queue_index_);
Austin Schuh39788ff2019-12-01 18:22:57 -0800431 lockless_queue_.Wakeup(event_loop()->priority());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700432 // TODO(austin): Return an error if we send too fast.
433 return true;
434 }
435
Brian Silverman5120afb2020-01-31 17:44:35 -0800436 absl::Span<char> GetSharedMemory() const {
437 return lockless_queue_memory_.GetSharedMemory();
438 }
439
Alex Perrycb7da4b2019-08-28 19:35:56 -0700440 private:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700441 MMapedQueue lockless_queue_memory_;
442 ipc_lib::LocklessQueue lockless_queue_;
443 ipc_lib::LocklessQueue::Sender lockless_queue_sender_;
444};
445
Alex Perrycb7da4b2019-08-28 19:35:56 -0700446// Class to manage the state for a Watcher.
Brian Silverman148d43d2020-06-07 18:19:22 -0500447class ShmWatcherState : public WatcherState {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700448 public:
Brian Silverman148d43d2020-06-07 18:19:22 -0500449 ShmWatcherState(
Austin Schuh7d87b672019-12-01 20:23:49 -0800450 ShmEventLoop *event_loop, const Channel *channel,
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800451 std::function<void(const Context &context, const void *message)> fn,
452 bool copy_data)
Brian Silverman148d43d2020-06-07 18:19:22 -0500453 : WatcherState(event_loop, channel, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800454 event_loop_(event_loop),
455 event_(this),
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800456 simple_shm_fetcher_(event_loop, channel, copy_data) {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700457
Brian Silverman148d43d2020-06-07 18:19:22 -0500458 ~ShmWatcherState() override { event_loop_->RemoveEvent(&event_); }
Austin Schuh39788ff2019-12-01 18:22:57 -0800459
460 void Startup(EventLoop *event_loop) override {
Austin Schuh7d87b672019-12-01 20:23:49 -0800461 simple_shm_fetcher_.PointAtNextQueueIndex();
Austin Schuh39788ff2019-12-01 18:22:57 -0800462 CHECK(RegisterWakeup(event_loop->priority()));
463 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700464
Alex Perrycb7da4b2019-08-28 19:35:56 -0700465 // Returns true if there is new data available.
Austin Schuh7d87b672019-12-01 20:23:49 -0800466 bool CheckForNewData() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700467 if (!has_new_data_) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800468 has_new_data_ = simple_shm_fetcher_.FetchNext();
Austin Schuh7d87b672019-12-01 20:23:49 -0800469
470 if (has_new_data_) {
471 event_.set_event_time(
Austin Schuhad154822019-12-27 15:45:13 -0800472 simple_shm_fetcher_.context().monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800473 event_loop_->AddEvent(&event_);
474 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700475 }
476
477 return has_new_data_;
478 }
479
Alex Perrycb7da4b2019-08-28 19:35:56 -0700480 // Consumes the data by calling the callback.
Austin Schuh7d87b672019-12-01 20:23:49 -0800481 void HandleEvent() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700482 CHECK(has_new_data_);
Austin Schuh39788ff2019-12-01 18:22:57 -0800483 DoCallCallback(monotonic_clock::now, simple_shm_fetcher_.context());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700484 has_new_data_ = false;
Austin Schuh7d87b672019-12-01 20:23:49 -0800485 CheckForNewData();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700486 }
487
Austin Schuh39788ff2019-12-01 18:22:57 -0800488 // Registers us to receive a signal on event reception.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700489 bool RegisterWakeup(int priority) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800490 return simple_shm_fetcher_.RegisterWakeup(priority);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700491 }
492
Austin Schuh39788ff2019-12-01 18:22:57 -0800493 void UnregisterWakeup() { return simple_shm_fetcher_.UnregisterWakeup(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700494
Brian Silverman5120afb2020-01-31 17:44:35 -0800495 absl::Span<char> GetSharedMemory() const {
496 return simple_shm_fetcher_.GetSharedMemory();
497 }
498
Alex Perrycb7da4b2019-08-28 19:35:56 -0700499 private:
500 bool has_new_data_ = false;
501
Austin Schuh7d87b672019-12-01 20:23:49 -0800502 ShmEventLoop *event_loop_;
Brian Silverman148d43d2020-06-07 18:19:22 -0500503 EventHandler<ShmWatcherState> event_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800504 SimpleShmFetcher simple_shm_fetcher_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700505};
506
507// Adapter class to adapt a timerfd to a TimerHandler.
Brian Silverman148d43d2020-06-07 18:19:22 -0500508class ShmTimerHandler final : public TimerHandler {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700509 public:
Brian Silverman148d43d2020-06-07 18:19:22 -0500510 ShmTimerHandler(ShmEventLoop *shm_event_loop, ::std::function<void()> fn)
Austin Schuh39788ff2019-12-01 18:22:57 -0800511 : TimerHandler(shm_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800512 shm_event_loop_(shm_event_loop),
513 event_(this) {
Austin Schuhcde39fd2020-02-22 20:58:24 -0800514 shm_event_loop_->epoll_.OnReadable(timerfd_.fd(), [this]() {
515 // The timer may fire spurriously. HandleEvent on the event loop will
516 // call the callback if it is needed. It may also have called it when
517 // processing some other event, and the kernel decided to deliver this
518 // wakeup anyways.
519 timerfd_.Read();
520 shm_event_loop_->HandleEvent();
521 });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700522 }
523
Brian Silverman148d43d2020-06-07 18:19:22 -0500524 ~ShmTimerHandler() {
Austin Schuh7d87b672019-12-01 20:23:49 -0800525 Disable();
526 shm_event_loop_->epoll_.DeleteFd(timerfd_.fd());
527 }
528
529 void HandleEvent() {
Austin Schuhcde39fd2020-02-22 20:58:24 -0800530 CHECK(!event_.valid());
531 const auto monotonic_now = Call(monotonic_clock::now, base_);
532 if (event_.valid()) {
533 // If someone called Setup inside Call, rescheduling is already taken care
534 // of. Bail.
535 return;
Austin Schuh7d87b672019-12-01 20:23:49 -0800536 }
537
Austin Schuhcde39fd2020-02-22 20:58:24 -0800538 if (repeat_offset_ == chrono::seconds(0)) {
539 timerfd_.Disable();
540 } else {
541 // Compute how many cycles have elapsed and schedule the next iteration
542 // for the next iteration in the future.
543 const int elapsed_cycles =
544 std::max<int>(0, (monotonic_now - base_ + repeat_offset_ -
545 std::chrono::nanoseconds(1)) /
546 repeat_offset_);
547 base_ += repeat_offset_ * elapsed_cycles;
Austin Schuh7d87b672019-12-01 20:23:49 -0800548
Austin Schuhcde39fd2020-02-22 20:58:24 -0800549 // Update the heap and schedule the timerfd wakeup.
Austin Schuh7d87b672019-12-01 20:23:49 -0800550 event_.set_event_time(base_);
551 shm_event_loop_->AddEvent(&event_);
Austin Schuhcde39fd2020-02-22 20:58:24 -0800552 timerfd_.SetTime(base_, chrono::seconds(0));
Austin Schuh7d87b672019-12-01 20:23:49 -0800553 }
554 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700555
556 void Setup(monotonic_clock::time_point base,
557 monotonic_clock::duration repeat_offset) override {
Austin Schuh7d87b672019-12-01 20:23:49 -0800558 if (event_.valid()) {
559 shm_event_loop_->RemoveEvent(&event_);
560 }
561
Alex Perrycb7da4b2019-08-28 19:35:56 -0700562 timerfd_.SetTime(base, repeat_offset);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800563 base_ = base;
564 repeat_offset_ = repeat_offset;
Austin Schuh7d87b672019-12-01 20:23:49 -0800565 event_.set_event_time(base_);
566 shm_event_loop_->AddEvent(&event_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700567 }
568
Austin Schuh7d87b672019-12-01 20:23:49 -0800569 void Disable() override {
570 shm_event_loop_->RemoveEvent(&event_);
571 timerfd_.Disable();
572 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700573
574 private:
575 ShmEventLoop *shm_event_loop_;
Brian Silverman148d43d2020-06-07 18:19:22 -0500576 EventHandler<ShmTimerHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700577
Brian Silverman148d43d2020-06-07 18:19:22 -0500578 internal::TimerFd timerfd_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700579
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800580 monotonic_clock::time_point base_;
581 monotonic_clock::duration repeat_offset_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700582};
583
584// Adapter class to the timerfd and PhasedLoop.
Brian Silverman148d43d2020-06-07 18:19:22 -0500585class ShmPhasedLoopHandler final : public PhasedLoopHandler {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700586 public:
Brian Silverman148d43d2020-06-07 18:19:22 -0500587 ShmPhasedLoopHandler(ShmEventLoop *shm_event_loop,
588 ::std::function<void(int)> fn,
589 const monotonic_clock::duration interval,
590 const monotonic_clock::duration offset)
591 : PhasedLoopHandler(shm_event_loop, std::move(fn), interval, offset),
Austin Schuh7d87b672019-12-01 20:23:49 -0800592 shm_event_loop_(shm_event_loop),
593 event_(this) {
594 shm_event_loop_->epoll_.OnReadable(
595 timerfd_.fd(), [this]() { shm_event_loop_->HandleEvent(); });
596 }
597
598 void HandleEvent() {
599 // The return value for read is the number of cycles that have elapsed.
600 // Because we check to see when this event *should* have happened, there are
601 // cases where Read() will return 0, when 1 cycle has actually happened.
602 // This occurs when the timer interrupt hasn't triggered yet. Therefore,
603 // ignore it. Call handles rescheduling and calculating elapsed cycles
604 // without any extra help.
605 timerfd_.Read();
606 event_.Invalidate();
607
608 Call(monotonic_clock::now, [this](monotonic_clock::time_point sleep_time) {
609 Schedule(sleep_time);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700610 });
611 }
612
Brian Silverman148d43d2020-06-07 18:19:22 -0500613 ~ShmPhasedLoopHandler() override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800614 shm_event_loop_->epoll_.DeleteFd(timerfd_.fd());
Austin Schuh7d87b672019-12-01 20:23:49 -0800615 shm_event_loop_->RemoveEvent(&event_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700616 }
617
618 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800619 // Reschedules the timer.
Austin Schuh39788ff2019-12-01 18:22:57 -0800620 void Schedule(monotonic_clock::time_point sleep_time) override {
Austin Schuh7d87b672019-12-01 20:23:49 -0800621 if (event_.valid()) {
622 shm_event_loop_->RemoveEvent(&event_);
623 }
624
Austin Schuh39788ff2019-12-01 18:22:57 -0800625 timerfd_.SetTime(sleep_time, ::aos::monotonic_clock::zero());
Austin Schuh7d87b672019-12-01 20:23:49 -0800626 event_.set_event_time(sleep_time);
627 shm_event_loop_->AddEvent(&event_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700628 }
629
630 ShmEventLoop *shm_event_loop_;
Brian Silverman148d43d2020-06-07 18:19:22 -0500631 EventHandler<ShmPhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700632
Brian Silverman148d43d2020-06-07 18:19:22 -0500633 internal::TimerFd timerfd_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700634};
Brian Silverman148d43d2020-06-07 18:19:22 -0500635
636} // namespace shm_event_loop_internal
Alex Perrycb7da4b2019-08-28 19:35:56 -0700637
638::std::unique_ptr<RawFetcher> ShmEventLoop::MakeRawFetcher(
639 const Channel *channel) {
Austin Schuhca4828c2019-12-28 14:21:35 -0800640 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
641 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
642 << "\", \"type\": \"" << channel->type()->string_view()
643 << "\" } is not able to be fetched on this node. Check your "
644 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800645 }
646
Brian Silverman148d43d2020-06-07 18:19:22 -0500647 return ::std::unique_ptr<RawFetcher>(new ShmFetcher(this, channel));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700648}
649
650::std::unique_ptr<RawSender> ShmEventLoop::MakeRawSender(
651 const Channel *channel) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800652 TakeSender(channel);
Austin Schuh39788ff2019-12-01 18:22:57 -0800653
Brian Silverman148d43d2020-06-07 18:19:22 -0500654 return ::std::unique_ptr<RawSender>(new ShmSender(this, channel));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700655}
656
657void ShmEventLoop::MakeRawWatcher(
658 const Channel *channel,
659 std::function<void(const Context &context, const void *message)> watcher) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800660 TakeWatcher(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800661
Austin Schuh39788ff2019-12-01 18:22:57 -0800662 NewWatcher(::std::unique_ptr<WatcherState>(
Brian Silverman148d43d2020-06-07 18:19:22 -0500663 new ShmWatcherState(this, channel, std::move(watcher), true)));
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800664}
665
666void ShmEventLoop::MakeRawNoArgWatcher(
667 const Channel *channel,
668 std::function<void(const Context &context)> watcher) {
669 TakeWatcher(channel);
670
Brian Silverman148d43d2020-06-07 18:19:22 -0500671 NewWatcher(::std::unique_ptr<WatcherState>(new ShmWatcherState(
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800672 this, channel,
673 [watcher](const Context &context, const void *) { watcher(context); },
674 false)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700675}
676
677TimerHandler *ShmEventLoop::AddTimer(::std::function<void()> callback) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800678 return NewTimer(::std::unique_ptr<TimerHandler>(
Brian Silverman148d43d2020-06-07 18:19:22 -0500679 new ShmTimerHandler(this, ::std::move(callback))));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700680}
681
682PhasedLoopHandler *ShmEventLoop::AddPhasedLoop(
683 ::std::function<void(int)> callback,
684 const monotonic_clock::duration interval,
685 const monotonic_clock::duration offset) {
Brian Silverman148d43d2020-06-07 18:19:22 -0500686 return NewPhasedLoop(::std::unique_ptr<PhasedLoopHandler>(
687 new ShmPhasedLoopHandler(this, ::std::move(callback), interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700688}
689
690void ShmEventLoop::OnRun(::std::function<void()> on_run) {
691 on_run_.push_back(::std::move(on_run));
692}
693
Austin Schuh7d87b672019-12-01 20:23:49 -0800694void ShmEventLoop::HandleEvent() {
695 // Update all the times for handlers.
696 for (::std::unique_ptr<WatcherState> &base_watcher : watchers_) {
Brian Silverman148d43d2020-06-07 18:19:22 -0500697 ShmWatcherState *watcher =
698 reinterpret_cast<ShmWatcherState *>(base_watcher.get());
Austin Schuh7d87b672019-12-01 20:23:49 -0800699
700 watcher->CheckForNewData();
701 }
702
Austin Schuh39788ff2019-12-01 18:22:57 -0800703 while (true) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800704 if (EventCount() == 0 ||
705 PeekEvent()->event_time() > monotonic_clock::now()) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800706 break;
707 }
708
Austin Schuh7d87b672019-12-01 20:23:49 -0800709 EventLoopEvent *event = PopEvent();
710 event->HandleEvent();
Austin Schuh39788ff2019-12-01 18:22:57 -0800711 }
712}
713
Austin Schuh32fd5a72019-12-01 22:20:26 -0800714// RAII class to mask signals.
715class ScopedSignalMask {
716 public:
717 ScopedSignalMask(std::initializer_list<int> signals) {
718 sigset_t sigset;
719 PCHECK(sigemptyset(&sigset) == 0);
720 for (int signal : signals) {
721 PCHECK(sigaddset(&sigset, signal) == 0);
722 }
723
724 PCHECK(sigprocmask(SIG_BLOCK, &sigset, &old_) == 0);
725 }
726
727 ~ScopedSignalMask() { PCHECK(sigprocmask(SIG_SETMASK, &old_, nullptr) == 0); }
728
729 private:
730 sigset_t old_;
731};
732
733// Class to manage the static state associated with killing multiple event
734// loops.
735class SignalHandler {
736 public:
737 // Gets the singleton.
738 static SignalHandler *global() {
739 static SignalHandler loop;
740 return &loop;
741 }
742
743 // Handles the signal with the singleton.
744 static void HandleSignal(int) { global()->DoHandleSignal(); }
745
746 // Registers an event loop to receive Exit() calls.
747 void Register(ShmEventLoop *event_loop) {
748 // Block signals while we have the mutex so we never race with the signal
749 // handler.
750 ScopedSignalMask mask({SIGINT, SIGHUP, SIGTERM});
751 std::unique_lock<stl_mutex> locker(mutex_);
752 if (event_loops_.size() == 0) {
753 // The first caller registers the signal handler.
754 struct sigaction new_action;
755 sigemptyset(&new_action.sa_mask);
756 // This makes it so that 2 control c's to a stuck process will kill it by
757 // restoring the original signal handler.
758 new_action.sa_flags = SA_RESETHAND;
759 new_action.sa_handler = &HandleSignal;
760
761 PCHECK(sigaction(SIGINT, &new_action, &old_action_int_) == 0);
762 PCHECK(sigaction(SIGHUP, &new_action, &old_action_hup_) == 0);
763 PCHECK(sigaction(SIGTERM, &new_action, &old_action_term_) == 0);
764 }
765
766 event_loops_.push_back(event_loop);
767 }
768
769 // Unregisters an event loop to receive Exit() calls.
770 void Unregister(ShmEventLoop *event_loop) {
771 // Block signals while we have the mutex so we never race with the signal
772 // handler.
773 ScopedSignalMask mask({SIGINT, SIGHUP, SIGTERM});
774 std::unique_lock<stl_mutex> locker(mutex_);
775
Brian Silverman5120afb2020-01-31 17:44:35 -0800776 event_loops_.erase(
777 std::find(event_loops_.begin(), event_loops_.end(), event_loop));
Austin Schuh32fd5a72019-12-01 22:20:26 -0800778
779 if (event_loops_.size() == 0u) {
780 // The last caller restores the original signal handlers.
781 PCHECK(sigaction(SIGINT, &old_action_int_, nullptr) == 0);
782 PCHECK(sigaction(SIGHUP, &old_action_hup_, nullptr) == 0);
783 PCHECK(sigaction(SIGTERM, &old_action_term_, nullptr) == 0);
784 }
785 }
786
787 private:
788 void DoHandleSignal() {
789 // We block signals while grabbing the lock, so there should never be a
790 // race. Confirm that this is true using trylock.
791 CHECK(mutex_.try_lock()) << ": sigprocmask failed to block signals while "
792 "modifing the event loop list.";
793 for (ShmEventLoop *event_loop : event_loops_) {
794 event_loop->Exit();
795 }
796 mutex_.unlock();
797 }
798
799 // Mutex to protect all state.
800 stl_mutex mutex_;
801 std::vector<ShmEventLoop *> event_loops_;
802 struct sigaction old_action_int_;
803 struct sigaction old_action_hup_;
804 struct sigaction old_action_term_;
805};
806
Alex Perrycb7da4b2019-08-28 19:35:56 -0700807void ShmEventLoop::Run() {
Austin Schuh32fd5a72019-12-01 22:20:26 -0800808 SignalHandler::global()->Register(this);
Austin Schuh39788ff2019-12-01 18:22:57 -0800809
Alex Perrycb7da4b2019-08-28 19:35:56 -0700810 std::unique_ptr<ipc_lib::SignalFd> signalfd;
811
812 if (watchers_.size() > 0) {
813 signalfd.reset(new ipc_lib::SignalFd({ipc_lib::kWakeupSignal}));
814
815 epoll_.OnReadable(signalfd->fd(), [signalfd_ptr = signalfd.get(), this]() {
816 signalfd_siginfo result = signalfd_ptr->Read();
817 CHECK_EQ(result.ssi_signo, ipc_lib::kWakeupSignal);
818
819 // TODO(austin): We should really be checking *everything*, not just
820 // watchers, and calling the oldest thing first. That will improve
821 // determinism a lot.
822
Austin Schuh7d87b672019-12-01 20:23:49 -0800823 HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700824 });
825 }
826
Austin Schuh39788ff2019-12-01 18:22:57 -0800827 MaybeScheduleTimingReports();
828
Austin Schuh7d87b672019-12-01 20:23:49 -0800829 ReserveEvents();
830
Tyler Chatow67ddb032020-01-12 14:30:04 -0800831 {
832 AosLogToFbs aos_logger;
833 if (!skip_logger_) {
834 aos_logger.Initialize(MakeSender<logging::LogMessageFbs>("/aos"));
835 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700836
Tyler Chatow67ddb032020-01-12 14:30:04 -0800837 aos::SetCurrentThreadName(name_.substr(0, 16));
Brian Silverman6a54ff32020-04-28 16:41:39 -0700838 const cpu_set_t default_affinity = DefaultAffinity();
839 if (!CPU_EQUAL(&affinity_, &default_affinity)) {
840 ::aos::SetCurrentThreadAffinity(affinity_);
841 }
Tyler Chatow67ddb032020-01-12 14:30:04 -0800842 // Now, all the callbacks are setup. Lock everything into memory and go RT.
843 if (priority_ != 0) {
844 ::aos::InitRT();
845
846 LOG(INFO) << "Setting priority to " << priority_;
847 ::aos::SetCurrentThreadRealtimePriority(priority_);
848 }
849
850 set_is_running(true);
851
852 // Now that we are realtime (but before the OnRun handlers run), snap the
853 // queue index.
854 for (::std::unique_ptr<WatcherState> &watcher : watchers_) {
855 watcher->Startup(this);
856 }
857
858 // Now that we are RT, run all the OnRun handlers.
859 for (const auto &run : on_run_) {
860 run();
861 }
862
863 // And start our main event loop which runs all the timers and handles Quit.
864 epoll_.Run();
865
866 // Once epoll exits, there is no useful nonrt work left to do.
867 set_is_running(false);
868
869 // Nothing time or synchronization critical needs to happen after this
870 // point. Drop RT priority.
871 ::aos::UnsetCurrentThreadRealtimePriority();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700872 }
873
Austin Schuh39788ff2019-12-01 18:22:57 -0800874 for (::std::unique_ptr<WatcherState> &base_watcher : watchers_) {
Brian Silverman148d43d2020-06-07 18:19:22 -0500875 ShmWatcherState *watcher =
876 reinterpret_cast<ShmWatcherState *>(base_watcher.get());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700877 watcher->UnregisterWakeup();
878 }
879
880 if (watchers_.size() > 0) {
881 epoll_.DeleteFd(signalfd->fd());
882 signalfd.reset();
883 }
Austin Schuh32fd5a72019-12-01 22:20:26 -0800884
885 SignalHandler::global()->Unregister(this);
Austin Schuhe84c3ed2019-12-14 15:29:48 -0800886
887 // Trigger any remaining senders or fetchers to be cleared before destroying
888 // the event loop so the book keeping matches. Do this in the thread that
889 // created the timing reporter.
890 timing_report_sender_.reset();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700891}
892
893void ShmEventLoop::Exit() { epoll_.Quit(); }
894
895ShmEventLoop::~ShmEventLoop() {
Austin Schuh39788ff2019-12-01 18:22:57 -0800896 // Force everything with a registered fd with epoll to be destroyed now.
897 timers_.clear();
898 phased_loops_.clear();
899 watchers_.clear();
900
Alex Perrycb7da4b2019-08-28 19:35:56 -0700901 CHECK(!is_running()) << ": ShmEventLoop destroyed while running";
902}
903
Alex Perrycb7da4b2019-08-28 19:35:56 -0700904void ShmEventLoop::SetRuntimeRealtimePriority(int priority) {
905 if (is_running()) {
906 LOG(FATAL) << "Cannot set realtime priority while running.";
907 }
908 priority_ = priority;
909}
910
Brian Silverman6a54ff32020-04-28 16:41:39 -0700911void ShmEventLoop::SetRuntimeAffinity(const cpu_set_t &cpuset) {
912 if (is_running()) {
913 LOG(FATAL) << "Cannot set affinity while running.";
914 }
915 affinity_ = cpuset;
916}
917
James Kuszmaul57c2baa2020-01-19 14:52:52 -0800918void ShmEventLoop::set_name(const std::string_view name) {
919 name_ = std::string(name);
920 UpdateTimingReport();
921}
922
Brian Silverman5120afb2020-01-31 17:44:35 -0800923absl::Span<char> ShmEventLoop::GetWatcherSharedMemory(const Channel *channel) {
Brian Silverman148d43d2020-06-07 18:19:22 -0500924 ShmWatcherState *const watcher_state =
925 static_cast<ShmWatcherState *>(GetWatcherState(channel));
Brian Silverman5120afb2020-01-31 17:44:35 -0800926 return watcher_state->GetSharedMemory();
927}
928
929absl::Span<char> ShmEventLoop::GetShmSenderSharedMemory(
930 const aos::RawSender *sender) const {
Brian Silverman148d43d2020-06-07 18:19:22 -0500931 return static_cast<const ShmSender *>(sender)->GetSharedMemory();
Brian Silverman5120afb2020-01-31 17:44:35 -0800932}
933
Brian Silverman6d2b3592020-06-18 14:40:15 -0700934absl::Span<char> ShmEventLoop::GetShmFetcherPrivateMemory(
935 const aos::RawFetcher *fetcher) const {
936 return static_cast<const ShmFetcher *>(fetcher)->GetPrivateMemory();
937}
938
Austin Schuh39788ff2019-12-01 18:22:57 -0800939pid_t ShmEventLoop::GetTid() { return syscall(SYS_gettid); }
940
Alex Perrycb7da4b2019-08-28 19:35:56 -0700941} // namespace aos