blob: e549d5772cb09343825267d79ac040e9e1b5d5cc [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>
8#include <algorithm>
9#include <atomic>
10#include <chrono>
Austin Schuh39788ff2019-12-01 18:22:57 -080011#include <iterator>
Alex Perrycb7da4b2019-08-28 19:35:56 -070012#include <stdexcept>
13
14#include "aos/events/epoll.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080015#include "aos/events/event_loop_generated.h"
16#include "aos/events/timing_statistics.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070017#include "aos/ipc_lib/lockless_queue.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080018#include "aos/ipc_lib/signalfd.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070019#include "aos/realtime.h"
Austin Schuh32fd5a72019-12-01 22:20:26 -080020#include "aos/stl_mutex/stl_mutex.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070021#include "aos/util/phased_loop.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080022#include "glog/logging.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070023
24DEFINE_string(shm_base, "/dev/shm/aos",
25 "Directory to place queue backing mmaped files in.");
26DEFINE_uint32(permissions, 0770,
27 "Permissions to make shared memory files and folders.");
28
29namespace aos {
30
31std::string ShmFolder(const Channel *channel) {
32 CHECK(channel->has_name());
33 CHECK_EQ(channel->name()->string_view()[0], '/');
34 return FLAGS_shm_base + channel->name()->str() + "/";
35}
36std::string ShmPath(const Channel *channel) {
37 CHECK(channel->has_type());
38 return ShmFolder(channel) + channel->type()->str() + ".v0";
39}
40
41class MMapedQueue {
42 public:
43 MMapedQueue(const Channel *channel) {
44 std::string path = ShmPath(channel);
45
Austin Schuh80c7fce2019-12-05 20:48:43 -080046 config_.num_watchers = channel->num_watchers();
47 config_.num_senders = channel->num_senders();
Alex Perrycb7da4b2019-08-28 19:35:56 -070048 config_.queue_size = 2 * channel->frequency();
49 config_.message_data_size = channel->max_size();
50
51 size_ = ipc_lib::LocklessQueueMemorySize(config_);
52
53 MkdirP(path);
54
55 // There are 2 cases. Either the file already exists, or it does not
56 // already exist and we need to create it. Start by trying to create it. If
57 // that fails, the file has already been created and we can open it
58 // normally.. Once the file has been created it wil never be deleted.
59 fd_ = open(path.c_str(), O_RDWR | O_CREAT | O_EXCL,
60 O_CLOEXEC | FLAGS_permissions);
61 if (fd_ == -1 && errno == EEXIST) {
62 VLOG(1) << path << " already created.";
63 // File already exists.
64 fd_ = open(path.c_str(), O_RDWR, O_CLOEXEC);
65 PCHECK(fd_ != -1) << ": Failed to open " << path;
66 while (true) {
67 struct stat st;
68 PCHECK(fstat(fd_, &st) == 0);
69 if (st.st_size != 0) {
70 CHECK_EQ(static_cast<size_t>(st.st_size), size_)
71 << ": Size of " << path
72 << " doesn't match expected size of backing queue file. Did the "
73 "queue definition change?";
74 break;
75 } else {
76 // The creating process didn't get around to it yet. Give it a bit.
77 std::this_thread::sleep_for(std::chrono::milliseconds(10));
78 VLOG(1) << path << " is zero size, waiting";
79 }
80 }
81 } else {
82 VLOG(1) << "Created " << path;
83 PCHECK(fd_ != -1) << ": Failed to open " << path;
84 PCHECK(ftruncate(fd_, size_) == 0);
85 }
86
87 data_ = mmap(NULL, size_, PROT_READ | PROT_WRITE, MAP_SHARED, fd_, 0);
88 PCHECK(data_ != MAP_FAILED);
89
90 ipc_lib::InitializeLocklessQueueMemory(memory(), config_);
91 }
92
93 ~MMapedQueue() {
94 PCHECK(munmap(data_, size_) == 0);
95 PCHECK(close(fd_) == 0);
96 }
97
98 ipc_lib::LocklessQueueMemory *memory() const {
99 return reinterpret_cast<ipc_lib::LocklessQueueMemory *>(data_);
100 }
101
Austin Schuh39788ff2019-12-01 18:22:57 -0800102 const ipc_lib::LocklessQueueConfiguration &config() const { return config_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700103
104 private:
James Kuszmaul3ae42262019-11-08 12:33:41 -0800105 void MkdirP(std::string_view path) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700106 struct stat st;
107 auto last_slash_pos = path.find_last_of("/");
108
James Kuszmaul3ae42262019-11-08 12:33:41 -0800109 std::string folder(last_slash_pos == std::string_view::npos
110 ? std::string_view("")
Alex Perrycb7da4b2019-08-28 19:35:56 -0700111 : path.substr(0, last_slash_pos));
112 if (stat(folder.c_str(), &st) == -1) {
113 PCHECK(errno == ENOENT);
114 CHECK_NE(folder, "") << ": Base path doesn't exist";
115 MkdirP(folder);
116 VLOG(1) << "Creating " << folder;
117 PCHECK(mkdir(folder.c_str(), FLAGS_permissions) == 0);
118 }
119 }
120
121 ipc_lib::LocklessQueueConfiguration config_;
122
123 int fd_;
124
125 size_t size_;
126 void *data_;
127};
128
129// Returns the portion of the path after the last /.
James Kuszmaul3ae42262019-11-08 12:33:41 -0800130std::string_view Filename(std::string_view path) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700131 auto last_slash_pos = path.find_last_of("/");
132
James Kuszmaul3ae42262019-11-08 12:33:41 -0800133 return last_slash_pos == std::string_view::npos
Alex Perrycb7da4b2019-08-28 19:35:56 -0700134 ? path
135 : path.substr(last_slash_pos + 1, path.size());
136}
137
138ShmEventLoop::ShmEventLoop(const Configuration *configuration)
139 : EventLoop(configuration), name_(Filename(program_invocation_name)) {}
140
141namespace {
142
143namespace chrono = ::std::chrono;
144
Austin Schuh39788ff2019-12-01 18:22:57 -0800145} // namespace
146
147namespace internal {
148
149class SimpleShmFetcher {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700150 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800151 explicit SimpleShmFetcher(const Channel *channel)
152 : lockless_queue_memory_(channel),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700153 lockless_queue_(lockless_queue_memory_.memory(),
154 lockless_queue_memory_.config()),
155 data_storage_(static_cast<AlignedChar *>(aligned_alloc(
156 alignof(AlignedChar), channel->max_size())),
157 &free) {
158 context_.data = nullptr;
159 // Point the queue index at the next index to read starting now. This
160 // makes it such that FetchNext will read the next message sent after
161 // the fetcher is created.
162 PointAtNextQueueIndex();
163 }
164
Austin Schuh39788ff2019-12-01 18:22:57 -0800165 ~SimpleShmFetcher() {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700166
167 // Points the next message to fetch at the queue index which will be
168 // populated next.
169 void PointAtNextQueueIndex() {
170 actual_queue_index_ = lockless_queue_.LatestQueueIndex();
171 if (!actual_queue_index_.valid()) {
172 // Nothing in the queue. The next element will show up at the 0th
173 // index in the queue.
174 actual_queue_index_ =
175 ipc_lib::QueueIndex::Zero(lockless_queue_.queue_size());
176 } else {
177 actual_queue_index_ = actual_queue_index_.Increment();
178 }
179 }
180
Austin Schuh39788ff2019-12-01 18:22:57 -0800181 bool FetchNext() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700182 // TODO(austin): Get behind and make sure it dies both here and with
183 // Fetch.
184 ipc_lib::LocklessQueue::ReadResult read_result = lockless_queue_.Read(
185 actual_queue_index_.index(), &context_.monotonic_sent_time,
186 &context_.realtime_sent_time, &context_.size,
187 reinterpret_cast<char *>(data_storage_.get()));
188 if (read_result == ipc_lib::LocklessQueue::ReadResult::GOOD) {
189 context_.queue_index = actual_queue_index_.index();
Austin Schuh39788ff2019-12-01 18:22:57 -0800190 context_.data = reinterpret_cast<char *>(data_storage_.get()) +
191 lockless_queue_.message_data_size() - context_.size;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700192 actual_queue_index_ = actual_queue_index_.Increment();
193 }
194
195 // Make sure the data wasn't modified while we were reading it. This
196 // can only happen if you are reading the last message *while* it is
197 // being written to, which means you are pretty far behind.
198 CHECK(read_result != ipc_lib::LocklessQueue::ReadResult::OVERWROTE)
199 << ": Got behind while reading and the last message was modified "
200 "out "
201 "from under us while we were reading it. Don't get so far "
202 "behind.";
203
204 CHECK(read_result != ipc_lib::LocklessQueue::ReadResult::TOO_OLD)
205 << ": The next message is no longer available.";
206 return read_result == ipc_lib::LocklessQueue::ReadResult::GOOD;
207 }
208
Austin Schuh39788ff2019-12-01 18:22:57 -0800209 bool Fetch() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700210 const ipc_lib::QueueIndex queue_index = lockless_queue_.LatestQueueIndex();
211 // actual_queue_index_ is only meaningful if it was set by Fetch or
212 // FetchNext. This happens when valid_data_ has been set. So, only
213 // skip checking if valid_data_ is true.
214 //
215 // Also, if the latest queue index is invalid, we are empty. So there
216 // is nothing to fetch.
Austin Schuh39788ff2019-12-01 18:22:57 -0800217 if ((context_.data != nullptr &&
Alex Perrycb7da4b2019-08-28 19:35:56 -0700218 queue_index == actual_queue_index_.DecrementBy(1u)) ||
219 !queue_index.valid()) {
220 return false;
221 }
222
223 ipc_lib::LocklessQueue::ReadResult read_result =
224 lockless_queue_.Read(queue_index.index(), &context_.monotonic_sent_time,
225 &context_.realtime_sent_time, &context_.size,
226 reinterpret_cast<char *>(data_storage_.get()));
227 if (read_result == ipc_lib::LocklessQueue::ReadResult::GOOD) {
228 context_.queue_index = queue_index.index();
Austin Schuh39788ff2019-12-01 18:22:57 -0800229 context_.data = reinterpret_cast<char *>(data_storage_.get()) +
230 lockless_queue_.message_data_size() - context_.size;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700231 actual_queue_index_ = queue_index.Increment();
232 }
233
234 // Make sure the data wasn't modified while we were reading it. This
235 // can only happen if you are reading the last message *while* it is
236 // being written to, which means you are pretty far behind.
237 CHECK(read_result != ipc_lib::LocklessQueue::ReadResult::OVERWROTE)
238 << ": Got behind while reading and the last message was modified "
239 "out "
240 "from under us while we were reading it. Don't get so far "
241 "behind.";
242
243 CHECK(read_result != ipc_lib::LocklessQueue::ReadResult::NOTHING_NEW)
244 << ": Queue index went backwards. This should never happen.";
245
246 // We fell behind between when we read the index and read the value.
247 // This isn't worth recovering from since this means we went to sleep
248 // for a long time in the middle of this function.
249 CHECK(read_result != ipc_lib::LocklessQueue::ReadResult::TOO_OLD)
250 << ": The next message is no longer available.";
251 return read_result == ipc_lib::LocklessQueue::ReadResult::GOOD;
252 }
253
Austin Schuh39788ff2019-12-01 18:22:57 -0800254 Context context() const { return context_; }
255
Alex Perrycb7da4b2019-08-28 19:35:56 -0700256 bool RegisterWakeup(int priority) {
257 return lockless_queue_.RegisterWakeup(priority);
258 }
259
260 void UnregisterWakeup() { lockless_queue_.UnregisterWakeup(); }
261
262 private:
263 MMapedQueue lockless_queue_memory_;
264 ipc_lib::LocklessQueue lockless_queue_;
265
266 ipc_lib::QueueIndex actual_queue_index_ =
267 ipc_lib::LocklessQueue::empty_queue_index();
268
269 struct AlignedChar {
270 alignas(32) char data;
271 };
272
273 std::unique_ptr<AlignedChar, decltype(&free)> data_storage_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800274
275 Context context_;
276};
277
278class ShmFetcher : public RawFetcher {
279 public:
280 explicit ShmFetcher(EventLoop *event_loop, const Channel *channel)
281 : RawFetcher(event_loop, channel), simple_shm_fetcher_(channel) {}
282
283 ~ShmFetcher() { context_.data = nullptr; }
284
285 std::pair<bool, monotonic_clock::time_point> DoFetchNext() override {
286 if (simple_shm_fetcher_.FetchNext()) {
287 context_ = simple_shm_fetcher_.context();
288 return std::make_pair(true, monotonic_clock::now());
289 }
290 return std::make_pair(false, monotonic_clock::min_time);
291 }
292
293 std::pair<bool, monotonic_clock::time_point> DoFetch() override {
294 if (simple_shm_fetcher_.Fetch()) {
295 context_ = simple_shm_fetcher_.context();
296 return std::make_pair(true, monotonic_clock::now());
297 }
298 return std::make_pair(false, monotonic_clock::min_time);
299 }
300
301 private:
302 SimpleShmFetcher simple_shm_fetcher_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700303};
304
305class ShmSender : public RawSender {
306 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800307 explicit ShmSender(EventLoop *event_loop, const Channel *channel)
308 : RawSender(event_loop, channel),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700309 lockless_queue_memory_(channel),
310 lockless_queue_(lockless_queue_memory_.memory(),
311 lockless_queue_memory_.config()),
312 lockless_queue_sender_(lockless_queue_.MakeSender()) {}
313
Austin Schuh39788ff2019-12-01 18:22:57 -0800314 ~ShmSender() override {}
315
Alex Perrycb7da4b2019-08-28 19:35:56 -0700316 void *data() override { return lockless_queue_sender_.Data(); }
317 size_t size() override { return lockless_queue_sender_.size(); }
Austin Schuh39788ff2019-12-01 18:22:57 -0800318 bool DoSend(size_t length) override {
319 lockless_queue_sender_.Send(length);
320 lockless_queue_.Wakeup(event_loop()->priority());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700321 return true;
322 }
323
Austin Schuh39788ff2019-12-01 18:22:57 -0800324 bool DoSend(const void *msg, size_t length) override {
Austin Schuh4726ce92019-11-29 13:23:18 -0800325 lockless_queue_sender_.Send(reinterpret_cast<const char *>(msg), length);
Austin Schuh39788ff2019-12-01 18:22:57 -0800326 lockless_queue_.Wakeup(event_loop()->priority());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700327 // TODO(austin): Return an error if we send too fast.
328 return true;
329 }
330
Alex Perrycb7da4b2019-08-28 19:35:56 -0700331 private:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700332 MMapedQueue lockless_queue_memory_;
333 ipc_lib::LocklessQueue lockless_queue_;
334 ipc_lib::LocklessQueue::Sender lockless_queue_sender_;
335};
336
Alex Perrycb7da4b2019-08-28 19:35:56 -0700337// Class to manage the state for a Watcher.
Austin Schuh39788ff2019-12-01 18:22:57 -0800338class WatcherState : public aos::WatcherState {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700339 public:
340 WatcherState(
Austin Schuh7d87b672019-12-01 20:23:49 -0800341 ShmEventLoop *event_loop, const Channel *channel,
Austin Schuh39788ff2019-12-01 18:22:57 -0800342 std::function<void(const Context &context, const void *message)> fn)
343 : aos::WatcherState(event_loop, channel, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800344 event_loop_(event_loop),
345 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800346 simple_shm_fetcher_(channel) {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700347
Austin Schuh7d87b672019-12-01 20:23:49 -0800348 ~WatcherState() override { event_loop_->RemoveEvent(&event_); }
Austin Schuh39788ff2019-12-01 18:22:57 -0800349
350 void Startup(EventLoop *event_loop) override {
Austin Schuh7d87b672019-12-01 20:23:49 -0800351 simple_shm_fetcher_.PointAtNextQueueIndex();
Austin Schuh39788ff2019-12-01 18:22:57 -0800352 CHECK(RegisterWakeup(event_loop->priority()));
353 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700354
Alex Perrycb7da4b2019-08-28 19:35:56 -0700355 // Returns true if there is new data available.
Austin Schuh7d87b672019-12-01 20:23:49 -0800356 bool CheckForNewData() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700357 if (!has_new_data_) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800358 has_new_data_ = simple_shm_fetcher_.FetchNext();
Austin Schuh7d87b672019-12-01 20:23:49 -0800359
360 if (has_new_data_) {
361 event_.set_event_time(
362 simple_shm_fetcher_.context().monotonic_sent_time);
363 event_loop_->AddEvent(&event_);
364 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700365 }
366
367 return has_new_data_;
368 }
369
Alex Perrycb7da4b2019-08-28 19:35:56 -0700370 // Consumes the data by calling the callback.
Austin Schuh7d87b672019-12-01 20:23:49 -0800371 void HandleEvent() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700372 CHECK(has_new_data_);
Austin Schuh39788ff2019-12-01 18:22:57 -0800373 DoCallCallback(monotonic_clock::now, simple_shm_fetcher_.context());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700374 has_new_data_ = false;
Austin Schuh7d87b672019-12-01 20:23:49 -0800375 CheckForNewData();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700376 }
377
Austin Schuh39788ff2019-12-01 18:22:57 -0800378 // Registers us to receive a signal on event reception.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700379 bool RegisterWakeup(int priority) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800380 return simple_shm_fetcher_.RegisterWakeup(priority);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700381 }
382
Austin Schuh39788ff2019-12-01 18:22:57 -0800383 void UnregisterWakeup() { return simple_shm_fetcher_.UnregisterWakeup(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700384
385 private:
386 bool has_new_data_ = false;
387
Austin Schuh7d87b672019-12-01 20:23:49 -0800388 ShmEventLoop *event_loop_;
389 EventHandler<WatcherState> event_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800390 SimpleShmFetcher simple_shm_fetcher_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700391};
392
393// Adapter class to adapt a timerfd to a TimerHandler.
Austin Schuh7d87b672019-12-01 20:23:49 -0800394class TimerHandlerState final : public TimerHandler {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700395 public:
396 TimerHandlerState(ShmEventLoop *shm_event_loop, ::std::function<void()> fn)
Austin Schuh39788ff2019-12-01 18:22:57 -0800397 : TimerHandler(shm_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800398 shm_event_loop_(shm_event_loop),
399 event_(this) {
400 shm_event_loop_->epoll_.OnReadable(
401 timerfd_.fd(), [this]() { shm_event_loop_->HandleEvent(); });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700402 }
403
Austin Schuh7d87b672019-12-01 20:23:49 -0800404 ~TimerHandlerState() {
405 Disable();
406 shm_event_loop_->epoll_.DeleteFd(timerfd_.fd());
407 }
408
409 void HandleEvent() {
410 uint64_t elapsed_cycles = timerfd_.Read();
411 if (elapsed_cycles == 0u) {
412 // We got called before the timer interrupt could happen, but because we
413 // are checking the time, we got called on time. Push the timer out by 1
414 // cycle.
415 elapsed_cycles = 1u;
416 timerfd_.SetTime(base_ + repeat_offset_, repeat_offset_);
417 }
418
419 Call(monotonic_clock::now, base_);
420
421 base_ += repeat_offset_ * elapsed_cycles;
422
423 if (repeat_offset_ != chrono::seconds(0)) {
424 event_.set_event_time(base_);
425 shm_event_loop_->AddEvent(&event_);
426 }
427 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700428
429 void Setup(monotonic_clock::time_point base,
430 monotonic_clock::duration repeat_offset) override {
Austin Schuh7d87b672019-12-01 20:23:49 -0800431 if (event_.valid()) {
432 shm_event_loop_->RemoveEvent(&event_);
433 }
434
Alex Perrycb7da4b2019-08-28 19:35:56 -0700435 timerfd_.SetTime(base, repeat_offset);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800436 base_ = base;
437 repeat_offset_ = repeat_offset;
Austin Schuh7d87b672019-12-01 20:23:49 -0800438 event_.set_event_time(base_);
439 shm_event_loop_->AddEvent(&event_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700440 }
441
Austin Schuh7d87b672019-12-01 20:23:49 -0800442 void Disable() override {
443 shm_event_loop_->RemoveEvent(&event_);
444 timerfd_.Disable();
445 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700446
447 private:
448 ShmEventLoop *shm_event_loop_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800449 EventHandler<TimerHandlerState> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700450
451 TimerFd timerfd_;
452
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800453 monotonic_clock::time_point base_;
454 monotonic_clock::duration repeat_offset_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700455};
456
457// Adapter class to the timerfd and PhasedLoop.
Austin Schuh7d87b672019-12-01 20:23:49 -0800458class PhasedLoopHandler final : public ::aos::PhasedLoopHandler {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700459 public:
460 PhasedLoopHandler(ShmEventLoop *shm_event_loop, ::std::function<void(int)> fn,
461 const monotonic_clock::duration interval,
462 const monotonic_clock::duration offset)
Austin Schuh39788ff2019-12-01 18:22:57 -0800463 : aos::PhasedLoopHandler(shm_event_loop, std::move(fn), interval, offset),
Austin Schuh7d87b672019-12-01 20:23:49 -0800464 shm_event_loop_(shm_event_loop),
465 event_(this) {
466 shm_event_loop_->epoll_.OnReadable(
467 timerfd_.fd(), [this]() { shm_event_loop_->HandleEvent(); });
468 }
469
470 void HandleEvent() {
471 // The return value for read is the number of cycles that have elapsed.
472 // Because we check to see when this event *should* have happened, there are
473 // cases where Read() will return 0, when 1 cycle has actually happened.
474 // This occurs when the timer interrupt hasn't triggered yet. Therefore,
475 // ignore it. Call handles rescheduling and calculating elapsed cycles
476 // without any extra help.
477 timerfd_.Read();
478 event_.Invalidate();
479
480 Call(monotonic_clock::now, [this](monotonic_clock::time_point sleep_time) {
481 Schedule(sleep_time);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700482 });
483 }
484
Austin Schuh39788ff2019-12-01 18:22:57 -0800485 ~PhasedLoopHandler() override {
486 shm_event_loop_->epoll_.DeleteFd(timerfd_.fd());
Austin Schuh7d87b672019-12-01 20:23:49 -0800487 shm_event_loop_->RemoveEvent(&event_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700488 }
489
490 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800491 // Reschedules the timer.
Austin Schuh39788ff2019-12-01 18:22:57 -0800492 void Schedule(monotonic_clock::time_point sleep_time) override {
Austin Schuh7d87b672019-12-01 20:23:49 -0800493 if (event_.valid()) {
494 shm_event_loop_->RemoveEvent(&event_);
495 }
496
Austin Schuh39788ff2019-12-01 18:22:57 -0800497 timerfd_.SetTime(sleep_time, ::aos::monotonic_clock::zero());
Austin Schuh7d87b672019-12-01 20:23:49 -0800498 event_.set_event_time(sleep_time);
499 shm_event_loop_->AddEvent(&event_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700500 }
501
502 ShmEventLoop *shm_event_loop_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800503 EventHandler<PhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700504
505 TimerFd timerfd_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700506};
507} // namespace internal
508
509::std::unique_ptr<RawFetcher> ShmEventLoop::MakeRawFetcher(
510 const Channel *channel) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800511 return ::std::unique_ptr<RawFetcher>(new internal::ShmFetcher(this, channel));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700512}
513
514::std::unique_ptr<RawSender> ShmEventLoop::MakeRawSender(
515 const Channel *channel) {
516 Take(channel);
Austin Schuh39788ff2019-12-01 18:22:57 -0800517
518 return ::std::unique_ptr<RawSender>(new internal::ShmSender(this, channel));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700519}
520
521void ShmEventLoop::MakeRawWatcher(
522 const Channel *channel,
523 std::function<void(const Context &context, const void *message)> watcher) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700524 Take(channel);
525
Austin Schuh39788ff2019-12-01 18:22:57 -0800526 NewWatcher(::std::unique_ptr<WatcherState>(
527 new internal::WatcherState(this, channel, std::move(watcher))));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700528}
529
530TimerHandler *ShmEventLoop::AddTimer(::std::function<void()> callback) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800531 return NewTimer(::std::unique_ptr<TimerHandler>(
532 new internal::TimerHandlerState(this, ::std::move(callback))));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700533}
534
535PhasedLoopHandler *ShmEventLoop::AddPhasedLoop(
536 ::std::function<void(int)> callback,
537 const monotonic_clock::duration interval,
538 const monotonic_clock::duration offset) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800539 return NewPhasedLoop(
540 ::std::unique_ptr<PhasedLoopHandler>(new internal::PhasedLoopHandler(
541 this, ::std::move(callback), interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700542}
543
544void ShmEventLoop::OnRun(::std::function<void()> on_run) {
545 on_run_.push_back(::std::move(on_run));
546}
547
Austin Schuh7d87b672019-12-01 20:23:49 -0800548void ShmEventLoop::HandleEvent() {
549 // Update all the times for handlers.
550 for (::std::unique_ptr<WatcherState> &base_watcher : watchers_) {
551 internal::WatcherState *watcher =
552 reinterpret_cast<internal::WatcherState *>(base_watcher.get());
553
554 watcher->CheckForNewData();
555 }
556
Austin Schuh39788ff2019-12-01 18:22:57 -0800557 while (true) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800558 if (EventCount() == 0 ||
559 PeekEvent()->event_time() > monotonic_clock::now()) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800560 break;
561 }
562
Austin Schuh7d87b672019-12-01 20:23:49 -0800563 EventLoopEvent *event = PopEvent();
564 event->HandleEvent();
Austin Schuh39788ff2019-12-01 18:22:57 -0800565 }
566}
567
Austin Schuh32fd5a72019-12-01 22:20:26 -0800568// RAII class to mask signals.
569class ScopedSignalMask {
570 public:
571 ScopedSignalMask(std::initializer_list<int> signals) {
572 sigset_t sigset;
573 PCHECK(sigemptyset(&sigset) == 0);
574 for (int signal : signals) {
575 PCHECK(sigaddset(&sigset, signal) == 0);
576 }
577
578 PCHECK(sigprocmask(SIG_BLOCK, &sigset, &old_) == 0);
579 }
580
581 ~ScopedSignalMask() { PCHECK(sigprocmask(SIG_SETMASK, &old_, nullptr) == 0); }
582
583 private:
584 sigset_t old_;
585};
586
587// Class to manage the static state associated with killing multiple event
588// loops.
589class SignalHandler {
590 public:
591 // Gets the singleton.
592 static SignalHandler *global() {
593 static SignalHandler loop;
594 return &loop;
595 }
596
597 // Handles the signal with the singleton.
598 static void HandleSignal(int) { global()->DoHandleSignal(); }
599
600 // Registers an event loop to receive Exit() calls.
601 void Register(ShmEventLoop *event_loop) {
602 // Block signals while we have the mutex so we never race with the signal
603 // handler.
604 ScopedSignalMask mask({SIGINT, SIGHUP, SIGTERM});
605 std::unique_lock<stl_mutex> locker(mutex_);
606 if (event_loops_.size() == 0) {
607 // The first caller registers the signal handler.
608 struct sigaction new_action;
609 sigemptyset(&new_action.sa_mask);
610 // This makes it so that 2 control c's to a stuck process will kill it by
611 // restoring the original signal handler.
612 new_action.sa_flags = SA_RESETHAND;
613 new_action.sa_handler = &HandleSignal;
614
615 PCHECK(sigaction(SIGINT, &new_action, &old_action_int_) == 0);
616 PCHECK(sigaction(SIGHUP, &new_action, &old_action_hup_) == 0);
617 PCHECK(sigaction(SIGTERM, &new_action, &old_action_term_) == 0);
618 }
619
620 event_loops_.push_back(event_loop);
621 }
622
623 // Unregisters an event loop to receive Exit() calls.
624 void Unregister(ShmEventLoop *event_loop) {
625 // Block signals while we have the mutex so we never race with the signal
626 // handler.
627 ScopedSignalMask mask({SIGINT, SIGHUP, SIGTERM});
628 std::unique_lock<stl_mutex> locker(mutex_);
629
630 event_loops_.erase(std::find(event_loops_.begin(), event_loops_.end(), event_loop));
631
632 if (event_loops_.size() == 0u) {
633 // The last caller restores the original signal handlers.
634 PCHECK(sigaction(SIGINT, &old_action_int_, nullptr) == 0);
635 PCHECK(sigaction(SIGHUP, &old_action_hup_, nullptr) == 0);
636 PCHECK(sigaction(SIGTERM, &old_action_term_, nullptr) == 0);
637 }
638 }
639
640 private:
641 void DoHandleSignal() {
642 // We block signals while grabbing the lock, so there should never be a
643 // race. Confirm that this is true using trylock.
644 CHECK(mutex_.try_lock()) << ": sigprocmask failed to block signals while "
645 "modifing the event loop list.";
646 for (ShmEventLoop *event_loop : event_loops_) {
647 event_loop->Exit();
648 }
649 mutex_.unlock();
650 }
651
652 // Mutex to protect all state.
653 stl_mutex mutex_;
654 std::vector<ShmEventLoop *> event_loops_;
655 struct sigaction old_action_int_;
656 struct sigaction old_action_hup_;
657 struct sigaction old_action_term_;
658};
659
Alex Perrycb7da4b2019-08-28 19:35:56 -0700660void ShmEventLoop::Run() {
Austin Schuh32fd5a72019-12-01 22:20:26 -0800661 SignalHandler::global()->Register(this);
Austin Schuh39788ff2019-12-01 18:22:57 -0800662
Alex Perrycb7da4b2019-08-28 19:35:56 -0700663 std::unique_ptr<ipc_lib::SignalFd> signalfd;
664
665 if (watchers_.size() > 0) {
666 signalfd.reset(new ipc_lib::SignalFd({ipc_lib::kWakeupSignal}));
667
668 epoll_.OnReadable(signalfd->fd(), [signalfd_ptr = signalfd.get(), this]() {
669 signalfd_siginfo result = signalfd_ptr->Read();
670 CHECK_EQ(result.ssi_signo, ipc_lib::kWakeupSignal);
671
672 // TODO(austin): We should really be checking *everything*, not just
673 // watchers, and calling the oldest thing first. That will improve
674 // determinism a lot.
675
Austin Schuh7d87b672019-12-01 20:23:49 -0800676 HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700677 });
678 }
679
Austin Schuh39788ff2019-12-01 18:22:57 -0800680 MaybeScheduleTimingReports();
681
Austin Schuh7d87b672019-12-01 20:23:49 -0800682 ReserveEvents();
683
Austin Schuh39788ff2019-12-01 18:22:57 -0800684 // Now, all the callbacks are setup. Lock everything into memory and go RT.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700685 if (priority_ != 0) {
686 ::aos::InitRT();
687
688 LOG(INFO) << "Setting priority to " << priority_;
689 ::aos::SetCurrentThreadRealtimePriority(priority_);
690 }
691
692 set_is_running(true);
693
694 // Now that we are realtime (but before the OnRun handlers run), snap the
695 // queue index.
Austin Schuh39788ff2019-12-01 18:22:57 -0800696 for (::std::unique_ptr<WatcherState> &watcher : watchers_) {
697 watcher->Startup(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700698 }
699
700 // Now that we are RT, run all the OnRun handlers.
701 for (const auto &run : on_run_) {
702 run();
703 }
704
Alex Perrycb7da4b2019-08-28 19:35:56 -0700705 // And start our main event loop which runs all the timers and handles Quit.
706 epoll_.Run();
707
708 // Once epoll exits, there is no useful nonrt work left to do.
709 set_is_running(false);
710
711 // Nothing time or synchronization critical needs to happen after this point.
712 // Drop RT priority.
713 ::aos::UnsetCurrentThreadRealtimePriority();
714
Austin Schuh39788ff2019-12-01 18:22:57 -0800715 for (::std::unique_ptr<WatcherState> &base_watcher : watchers_) {
716 internal::WatcherState *watcher =
717 reinterpret_cast<internal::WatcherState *>(base_watcher.get());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700718 watcher->UnregisterWakeup();
719 }
720
721 if (watchers_.size() > 0) {
722 epoll_.DeleteFd(signalfd->fd());
723 signalfd.reset();
724 }
Austin Schuh32fd5a72019-12-01 22:20:26 -0800725
726 SignalHandler::global()->Unregister(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700727}
728
729void ShmEventLoop::Exit() { epoll_.Quit(); }
730
731ShmEventLoop::~ShmEventLoop() {
Austin Schuh39788ff2019-12-01 18:22:57 -0800732 // Trigger any remaining senders or fetchers to be cleared before destroying
733 // the event loop so the book keeping matches.
734 timing_report_sender_.reset();
735
736 // Force everything with a registered fd with epoll to be destroyed now.
737 timers_.clear();
738 phased_loops_.clear();
739 watchers_.clear();
740
Alex Perrycb7da4b2019-08-28 19:35:56 -0700741 CHECK(!is_running()) << ": ShmEventLoop destroyed while running";
742}
743
744void ShmEventLoop::Take(const Channel *channel) {
745 CHECK(!is_running()) << ": Cannot add new objects while running.";
746
747 // Cheat aggresively. Use the shared memory path as a proxy for a unique
748 // identifier for the channel.
749 const std::string path = ShmPath(channel);
750
751 const auto prior = ::std::find(taken_.begin(), taken_.end(), path);
752 CHECK(prior == taken_.end()) << ": " << path << " is already being used.";
753
754 taken_.emplace_back(path);
755}
756
757void ShmEventLoop::SetRuntimeRealtimePriority(int priority) {
758 if (is_running()) {
759 LOG(FATAL) << "Cannot set realtime priority while running.";
760 }
761 priority_ = priority;
762}
763
Austin Schuh39788ff2019-12-01 18:22:57 -0800764pid_t ShmEventLoop::GetTid() { return syscall(SYS_gettid); }
765
Alex Perrycb7da4b2019-08-28 19:35:56 -0700766} // namespace aos