blob: 0f933f94a3d33bef3acb54010461bc2f90af3915 [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 auto last_slash_pos = path.find_last_of("/");
107
James Kuszmaul3ae42262019-11-08 12:33:41 -0800108 std::string folder(last_slash_pos == std::string_view::npos
109 ? std::string_view("")
Alex Perrycb7da4b2019-08-28 19:35:56 -0700110 : path.substr(0, last_slash_pos));
Austin Schuh8ec76182019-12-23 16:28:00 -0800111 if (folder.empty()) return;
112 MkdirP(folder);
113 VLOG(1) << "Creating " << folder;
114 const int result = mkdir(folder.c_str(), FLAGS_permissions);
115 if (result == -1 && errno == EEXIST) {
116 VLOG(1) << "Already exists";
117 return;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700118 }
Austin Schuh8ec76182019-12-23 16:28:00 -0800119 PCHECK(result == 0) << ": Error creating " << folder;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700120 }
121
122 ipc_lib::LocklessQueueConfiguration config_;
123
124 int fd_;
125
126 size_t size_;
127 void *data_;
128};
129
Austin Schuh217a9782019-12-21 23:02:50 -0800130namespace {
131
Alex Perrycb7da4b2019-08-28 19:35:56 -0700132// Returns the portion of the path after the last /.
James Kuszmaul3ae42262019-11-08 12:33:41 -0800133std::string_view Filename(std::string_view path) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700134 auto last_slash_pos = path.find_last_of("/");
135
James Kuszmaul3ae42262019-11-08 12:33:41 -0800136 return last_slash_pos == std::string_view::npos
Alex Perrycb7da4b2019-08-28 19:35:56 -0700137 ? path
138 : path.substr(last_slash_pos + 1, path.size());
139}
140
Austin Schuh217a9782019-12-21 23:02:50 -0800141const Node *MaybeMyNode(const Configuration *configuration) {
142 if (!configuration->has_nodes()) {
143 return nullptr;
144 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700145
Austin Schuh217a9782019-12-21 23:02:50 -0800146 return configuration::GetMyNode(configuration);
147}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700148
149namespace chrono = ::std::chrono;
150
Austin Schuh39788ff2019-12-01 18:22:57 -0800151} // namespace
152
Austin Schuh217a9782019-12-21 23:02:50 -0800153ShmEventLoop::ShmEventLoop(const Configuration *configuration)
154 : EventLoop(configuration),
155 name_(Filename(program_invocation_name)),
156 node_(MaybeMyNode(configuration)) {}
157
Austin Schuh39788ff2019-12-01 18:22:57 -0800158namespace internal {
159
160class SimpleShmFetcher {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700161 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800162 explicit SimpleShmFetcher(const Channel *channel)
163 : lockless_queue_memory_(channel),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700164 lockless_queue_(lockless_queue_memory_.memory(),
165 lockless_queue_memory_.config()),
166 data_storage_(static_cast<AlignedChar *>(aligned_alloc(
167 alignof(AlignedChar), channel->max_size())),
168 &free) {
169 context_.data = nullptr;
170 // Point the queue index at the next index to read starting now. This
171 // makes it such that FetchNext will read the next message sent after
172 // the fetcher is created.
173 PointAtNextQueueIndex();
174 }
175
Austin Schuh39788ff2019-12-01 18:22:57 -0800176 ~SimpleShmFetcher() {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700177
178 // Points the next message to fetch at the queue index which will be
179 // populated next.
180 void PointAtNextQueueIndex() {
181 actual_queue_index_ = lockless_queue_.LatestQueueIndex();
182 if (!actual_queue_index_.valid()) {
183 // Nothing in the queue. The next element will show up at the 0th
184 // index in the queue.
185 actual_queue_index_ =
186 ipc_lib::QueueIndex::Zero(lockless_queue_.queue_size());
187 } else {
188 actual_queue_index_ = actual_queue_index_.Increment();
189 }
190 }
191
Austin Schuh39788ff2019-12-01 18:22:57 -0800192 bool FetchNext() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700193 // TODO(austin): Get behind and make sure it dies both here and with
194 // Fetch.
195 ipc_lib::LocklessQueue::ReadResult read_result = lockless_queue_.Read(
196 actual_queue_index_.index(), &context_.monotonic_sent_time,
197 &context_.realtime_sent_time, &context_.size,
198 reinterpret_cast<char *>(data_storage_.get()));
199 if (read_result == ipc_lib::LocklessQueue::ReadResult::GOOD) {
200 context_.queue_index = actual_queue_index_.index();
Austin Schuh39788ff2019-12-01 18:22:57 -0800201 context_.data = reinterpret_cast<char *>(data_storage_.get()) +
202 lockless_queue_.message_data_size() - context_.size;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700203 actual_queue_index_ = actual_queue_index_.Increment();
204 }
205
206 // Make sure the data wasn't modified while we were reading it. This
207 // can only happen if you are reading the last message *while* it is
208 // being written to, which means you are pretty far behind.
209 CHECK(read_result != ipc_lib::LocklessQueue::ReadResult::OVERWROTE)
210 << ": Got behind while reading and the last message was modified "
211 "out "
212 "from under us while we were reading it. Don't get so far "
213 "behind.";
214
215 CHECK(read_result != ipc_lib::LocklessQueue::ReadResult::TOO_OLD)
216 << ": The next message is no longer available.";
217 return read_result == ipc_lib::LocklessQueue::ReadResult::GOOD;
218 }
219
Austin Schuh39788ff2019-12-01 18:22:57 -0800220 bool Fetch() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700221 const ipc_lib::QueueIndex queue_index = lockless_queue_.LatestQueueIndex();
222 // actual_queue_index_ is only meaningful if it was set by Fetch or
223 // FetchNext. This happens when valid_data_ has been set. So, only
224 // skip checking if valid_data_ is true.
225 //
226 // Also, if the latest queue index is invalid, we are empty. So there
227 // is nothing to fetch.
Austin Schuh39788ff2019-12-01 18:22:57 -0800228 if ((context_.data != nullptr &&
Alex Perrycb7da4b2019-08-28 19:35:56 -0700229 queue_index == actual_queue_index_.DecrementBy(1u)) ||
230 !queue_index.valid()) {
231 return false;
232 }
233
234 ipc_lib::LocklessQueue::ReadResult read_result =
235 lockless_queue_.Read(queue_index.index(), &context_.monotonic_sent_time,
236 &context_.realtime_sent_time, &context_.size,
237 reinterpret_cast<char *>(data_storage_.get()));
238 if (read_result == ipc_lib::LocklessQueue::ReadResult::GOOD) {
239 context_.queue_index = queue_index.index();
Austin Schuh39788ff2019-12-01 18:22:57 -0800240 context_.data = reinterpret_cast<char *>(data_storage_.get()) +
241 lockless_queue_.message_data_size() - context_.size;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700242 actual_queue_index_ = queue_index.Increment();
243 }
244
245 // Make sure the data wasn't modified while we were reading it. This
246 // can only happen if you are reading the last message *while* it is
247 // being written to, which means you are pretty far behind.
248 CHECK(read_result != ipc_lib::LocklessQueue::ReadResult::OVERWROTE)
249 << ": Got behind while reading and the last message was modified "
250 "out "
251 "from under us while we were reading it. Don't get so far "
252 "behind.";
253
254 CHECK(read_result != ipc_lib::LocklessQueue::ReadResult::NOTHING_NEW)
255 << ": Queue index went backwards. This should never happen.";
256
257 // We fell behind between when we read the index and read the value.
258 // This isn't worth recovering from since this means we went to sleep
259 // for a long time in the middle of this function.
260 CHECK(read_result != ipc_lib::LocklessQueue::ReadResult::TOO_OLD)
261 << ": The next message is no longer available.";
262 return read_result == ipc_lib::LocklessQueue::ReadResult::GOOD;
263 }
264
Austin Schuh39788ff2019-12-01 18:22:57 -0800265 Context context() const { return context_; }
266
Alex Perrycb7da4b2019-08-28 19:35:56 -0700267 bool RegisterWakeup(int priority) {
268 return lockless_queue_.RegisterWakeup(priority);
269 }
270
271 void UnregisterWakeup() { lockless_queue_.UnregisterWakeup(); }
272
273 private:
274 MMapedQueue lockless_queue_memory_;
275 ipc_lib::LocklessQueue lockless_queue_;
276
277 ipc_lib::QueueIndex actual_queue_index_ =
278 ipc_lib::LocklessQueue::empty_queue_index();
279
280 struct AlignedChar {
281 alignas(32) char data;
282 };
283
284 std::unique_ptr<AlignedChar, decltype(&free)> data_storage_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800285
286 Context context_;
287};
288
289class ShmFetcher : public RawFetcher {
290 public:
291 explicit ShmFetcher(EventLoop *event_loop, const Channel *channel)
292 : RawFetcher(event_loop, channel), simple_shm_fetcher_(channel) {}
293
294 ~ShmFetcher() { context_.data = nullptr; }
295
296 std::pair<bool, monotonic_clock::time_point> DoFetchNext() override {
297 if (simple_shm_fetcher_.FetchNext()) {
298 context_ = simple_shm_fetcher_.context();
299 return std::make_pair(true, monotonic_clock::now());
300 }
301 return std::make_pair(false, monotonic_clock::min_time);
302 }
303
304 std::pair<bool, monotonic_clock::time_point> DoFetch() override {
305 if (simple_shm_fetcher_.Fetch()) {
306 context_ = simple_shm_fetcher_.context();
307 return std::make_pair(true, monotonic_clock::now());
308 }
309 return std::make_pair(false, monotonic_clock::min_time);
310 }
311
312 private:
313 SimpleShmFetcher simple_shm_fetcher_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700314};
315
316class ShmSender : public RawSender {
317 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800318 explicit ShmSender(EventLoop *event_loop, const Channel *channel)
319 : RawSender(event_loop, channel),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700320 lockless_queue_memory_(channel),
321 lockless_queue_(lockless_queue_memory_.memory(),
322 lockless_queue_memory_.config()),
323 lockless_queue_sender_(lockless_queue_.MakeSender()) {}
324
Austin Schuh39788ff2019-12-01 18:22:57 -0800325 ~ShmSender() override {}
326
Alex Perrycb7da4b2019-08-28 19:35:56 -0700327 void *data() override { return lockless_queue_sender_.Data(); }
328 size_t size() override { return lockless_queue_sender_.size(); }
Austin Schuh39788ff2019-12-01 18:22:57 -0800329 bool DoSend(size_t length) override {
330 lockless_queue_sender_.Send(length);
331 lockless_queue_.Wakeup(event_loop()->priority());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700332 return true;
333 }
334
Austin Schuh39788ff2019-12-01 18:22:57 -0800335 bool DoSend(const void *msg, size_t length) override {
Austin Schuh4726ce92019-11-29 13:23:18 -0800336 lockless_queue_sender_.Send(reinterpret_cast<const char *>(msg), length);
Austin Schuh39788ff2019-12-01 18:22:57 -0800337 lockless_queue_.Wakeup(event_loop()->priority());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700338 // TODO(austin): Return an error if we send too fast.
339 return true;
340 }
341
Alex Perrycb7da4b2019-08-28 19:35:56 -0700342 private:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700343 MMapedQueue lockless_queue_memory_;
344 ipc_lib::LocklessQueue lockless_queue_;
345 ipc_lib::LocklessQueue::Sender lockless_queue_sender_;
346};
347
Alex Perrycb7da4b2019-08-28 19:35:56 -0700348// Class to manage the state for a Watcher.
Austin Schuh39788ff2019-12-01 18:22:57 -0800349class WatcherState : public aos::WatcherState {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700350 public:
351 WatcherState(
Austin Schuh7d87b672019-12-01 20:23:49 -0800352 ShmEventLoop *event_loop, const Channel *channel,
Austin Schuh39788ff2019-12-01 18:22:57 -0800353 std::function<void(const Context &context, const void *message)> fn)
354 : aos::WatcherState(event_loop, channel, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800355 event_loop_(event_loop),
356 event_(this),
Austin Schuh39788ff2019-12-01 18:22:57 -0800357 simple_shm_fetcher_(channel) {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700358
Austin Schuh7d87b672019-12-01 20:23:49 -0800359 ~WatcherState() override { event_loop_->RemoveEvent(&event_); }
Austin Schuh39788ff2019-12-01 18:22:57 -0800360
361 void Startup(EventLoop *event_loop) override {
Austin Schuh7d87b672019-12-01 20:23:49 -0800362 simple_shm_fetcher_.PointAtNextQueueIndex();
Austin Schuh39788ff2019-12-01 18:22:57 -0800363 CHECK(RegisterWakeup(event_loop->priority()));
364 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700365
Alex Perrycb7da4b2019-08-28 19:35:56 -0700366 // Returns true if there is new data available.
Austin Schuh7d87b672019-12-01 20:23:49 -0800367 bool CheckForNewData() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700368 if (!has_new_data_) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800369 has_new_data_ = simple_shm_fetcher_.FetchNext();
Austin Schuh7d87b672019-12-01 20:23:49 -0800370
371 if (has_new_data_) {
372 event_.set_event_time(
373 simple_shm_fetcher_.context().monotonic_sent_time);
374 event_loop_->AddEvent(&event_);
375 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700376 }
377
378 return has_new_data_;
379 }
380
Alex Perrycb7da4b2019-08-28 19:35:56 -0700381 // Consumes the data by calling the callback.
Austin Schuh7d87b672019-12-01 20:23:49 -0800382 void HandleEvent() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700383 CHECK(has_new_data_);
Austin Schuh39788ff2019-12-01 18:22:57 -0800384 DoCallCallback(monotonic_clock::now, simple_shm_fetcher_.context());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700385 has_new_data_ = false;
Austin Schuh7d87b672019-12-01 20:23:49 -0800386 CheckForNewData();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700387 }
388
Austin Schuh39788ff2019-12-01 18:22:57 -0800389 // Registers us to receive a signal on event reception.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700390 bool RegisterWakeup(int priority) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800391 return simple_shm_fetcher_.RegisterWakeup(priority);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700392 }
393
Austin Schuh39788ff2019-12-01 18:22:57 -0800394 void UnregisterWakeup() { return simple_shm_fetcher_.UnregisterWakeup(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700395
396 private:
397 bool has_new_data_ = false;
398
Austin Schuh7d87b672019-12-01 20:23:49 -0800399 ShmEventLoop *event_loop_;
400 EventHandler<WatcherState> event_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800401 SimpleShmFetcher simple_shm_fetcher_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700402};
403
404// Adapter class to adapt a timerfd to a TimerHandler.
Austin Schuh7d87b672019-12-01 20:23:49 -0800405class TimerHandlerState final : public TimerHandler {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700406 public:
407 TimerHandlerState(ShmEventLoop *shm_event_loop, ::std::function<void()> fn)
Austin Schuh39788ff2019-12-01 18:22:57 -0800408 : TimerHandler(shm_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800409 shm_event_loop_(shm_event_loop),
410 event_(this) {
411 shm_event_loop_->epoll_.OnReadable(
412 timerfd_.fd(), [this]() { shm_event_loop_->HandleEvent(); });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700413 }
414
Austin Schuh7d87b672019-12-01 20:23:49 -0800415 ~TimerHandlerState() {
416 Disable();
417 shm_event_loop_->epoll_.DeleteFd(timerfd_.fd());
418 }
419
420 void HandleEvent() {
421 uint64_t elapsed_cycles = timerfd_.Read();
422 if (elapsed_cycles == 0u) {
423 // We got called before the timer interrupt could happen, but because we
424 // are checking the time, we got called on time. Push the timer out by 1
425 // cycle.
426 elapsed_cycles = 1u;
427 timerfd_.SetTime(base_ + repeat_offset_, repeat_offset_);
428 }
429
430 Call(monotonic_clock::now, base_);
431
432 base_ += repeat_offset_ * elapsed_cycles;
433
434 if (repeat_offset_ != chrono::seconds(0)) {
435 event_.set_event_time(base_);
436 shm_event_loop_->AddEvent(&event_);
437 }
438 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700439
440 void Setup(monotonic_clock::time_point base,
441 monotonic_clock::duration repeat_offset) override {
Austin Schuh7d87b672019-12-01 20:23:49 -0800442 if (event_.valid()) {
443 shm_event_loop_->RemoveEvent(&event_);
444 }
445
Alex Perrycb7da4b2019-08-28 19:35:56 -0700446 timerfd_.SetTime(base, repeat_offset);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800447 base_ = base;
448 repeat_offset_ = repeat_offset;
Austin Schuh7d87b672019-12-01 20:23:49 -0800449 event_.set_event_time(base_);
450 shm_event_loop_->AddEvent(&event_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700451 }
452
Austin Schuh7d87b672019-12-01 20:23:49 -0800453 void Disable() override {
454 shm_event_loop_->RemoveEvent(&event_);
455 timerfd_.Disable();
456 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700457
458 private:
459 ShmEventLoop *shm_event_loop_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800460 EventHandler<TimerHandlerState> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700461
462 TimerFd timerfd_;
463
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800464 monotonic_clock::time_point base_;
465 monotonic_clock::duration repeat_offset_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700466};
467
468// Adapter class to the timerfd and PhasedLoop.
Austin Schuh7d87b672019-12-01 20:23:49 -0800469class PhasedLoopHandler final : public ::aos::PhasedLoopHandler {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700470 public:
471 PhasedLoopHandler(ShmEventLoop *shm_event_loop, ::std::function<void(int)> fn,
472 const monotonic_clock::duration interval,
473 const monotonic_clock::duration offset)
Austin Schuh39788ff2019-12-01 18:22:57 -0800474 : aos::PhasedLoopHandler(shm_event_loop, std::move(fn), interval, offset),
Austin Schuh7d87b672019-12-01 20:23:49 -0800475 shm_event_loop_(shm_event_loop),
476 event_(this) {
477 shm_event_loop_->epoll_.OnReadable(
478 timerfd_.fd(), [this]() { shm_event_loop_->HandleEvent(); });
479 }
480
481 void HandleEvent() {
482 // The return value for read is the number of cycles that have elapsed.
483 // Because we check to see when this event *should* have happened, there are
484 // cases where Read() will return 0, when 1 cycle has actually happened.
485 // This occurs when the timer interrupt hasn't triggered yet. Therefore,
486 // ignore it. Call handles rescheduling and calculating elapsed cycles
487 // without any extra help.
488 timerfd_.Read();
489 event_.Invalidate();
490
491 Call(monotonic_clock::now, [this](monotonic_clock::time_point sleep_time) {
492 Schedule(sleep_time);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700493 });
494 }
495
Austin Schuh39788ff2019-12-01 18:22:57 -0800496 ~PhasedLoopHandler() override {
497 shm_event_loop_->epoll_.DeleteFd(timerfd_.fd());
Austin Schuh7d87b672019-12-01 20:23:49 -0800498 shm_event_loop_->RemoveEvent(&event_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700499 }
500
501 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800502 // Reschedules the timer.
Austin Schuh39788ff2019-12-01 18:22:57 -0800503 void Schedule(monotonic_clock::time_point sleep_time) override {
Austin Schuh7d87b672019-12-01 20:23:49 -0800504 if (event_.valid()) {
505 shm_event_loop_->RemoveEvent(&event_);
506 }
507
Austin Schuh39788ff2019-12-01 18:22:57 -0800508 timerfd_.SetTime(sleep_time, ::aos::monotonic_clock::zero());
Austin Schuh7d87b672019-12-01 20:23:49 -0800509 event_.set_event_time(sleep_time);
510 shm_event_loop_->AddEvent(&event_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700511 }
512
513 ShmEventLoop *shm_event_loop_;
Austin Schuh7d87b672019-12-01 20:23:49 -0800514 EventHandler<PhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700515
516 TimerFd timerfd_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700517};
518} // namespace internal
519
520::std::unique_ptr<RawFetcher> ShmEventLoop::MakeRawFetcher(
521 const Channel *channel) {
Austin Schuh217a9782019-12-21 23:02:50 -0800522
523 if (node() != nullptr) {
524 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
525 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
526 << "\", \"type\": \"" << channel->type()->string_view()
527 << "\" } is not able to be fetched on this node. Check your "
528 "configuration.";
529 }
530 }
531
Austin Schuh39788ff2019-12-01 18:22:57 -0800532 return ::std::unique_ptr<RawFetcher>(new internal::ShmFetcher(this, channel));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700533}
534
535::std::unique_ptr<RawSender> ShmEventLoop::MakeRawSender(
536 const Channel *channel) {
537 Take(channel);
Austin Schuh39788ff2019-12-01 18:22:57 -0800538
539 return ::std::unique_ptr<RawSender>(new internal::ShmSender(this, channel));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700540}
541
542void ShmEventLoop::MakeRawWatcher(
543 const Channel *channel,
544 std::function<void(const Context &context, const void *message)> watcher) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700545 Take(channel);
546
Austin Schuh217a9782019-12-21 23:02:50 -0800547 if (node() != nullptr) {
548 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
549 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
550 << "\", \"type\": \"" << channel->type()->string_view()
551 << "\" } is not able to be watched on this node. Check your "
552 "configuration.";
553 }
554 }
555
Austin Schuh39788ff2019-12-01 18:22:57 -0800556 NewWatcher(::std::unique_ptr<WatcherState>(
557 new internal::WatcherState(this, channel, std::move(watcher))));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700558}
559
560TimerHandler *ShmEventLoop::AddTimer(::std::function<void()> callback) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800561 return NewTimer(::std::unique_ptr<TimerHandler>(
562 new internal::TimerHandlerState(this, ::std::move(callback))));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700563}
564
565PhasedLoopHandler *ShmEventLoop::AddPhasedLoop(
566 ::std::function<void(int)> callback,
567 const monotonic_clock::duration interval,
568 const monotonic_clock::duration offset) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800569 return NewPhasedLoop(
570 ::std::unique_ptr<PhasedLoopHandler>(new internal::PhasedLoopHandler(
571 this, ::std::move(callback), interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700572}
573
574void ShmEventLoop::OnRun(::std::function<void()> on_run) {
575 on_run_.push_back(::std::move(on_run));
576}
577
Austin Schuh7d87b672019-12-01 20:23:49 -0800578void ShmEventLoop::HandleEvent() {
579 // Update all the times for handlers.
580 for (::std::unique_ptr<WatcherState> &base_watcher : watchers_) {
581 internal::WatcherState *watcher =
582 reinterpret_cast<internal::WatcherState *>(base_watcher.get());
583
584 watcher->CheckForNewData();
585 }
586
Austin Schuh39788ff2019-12-01 18:22:57 -0800587 while (true) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800588 if (EventCount() == 0 ||
589 PeekEvent()->event_time() > monotonic_clock::now()) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800590 break;
591 }
592
Austin Schuh7d87b672019-12-01 20:23:49 -0800593 EventLoopEvent *event = PopEvent();
594 event->HandleEvent();
Austin Schuh39788ff2019-12-01 18:22:57 -0800595 }
596}
597
Austin Schuh32fd5a72019-12-01 22:20:26 -0800598// RAII class to mask signals.
599class ScopedSignalMask {
600 public:
601 ScopedSignalMask(std::initializer_list<int> signals) {
602 sigset_t sigset;
603 PCHECK(sigemptyset(&sigset) == 0);
604 for (int signal : signals) {
605 PCHECK(sigaddset(&sigset, signal) == 0);
606 }
607
608 PCHECK(sigprocmask(SIG_BLOCK, &sigset, &old_) == 0);
609 }
610
611 ~ScopedSignalMask() { PCHECK(sigprocmask(SIG_SETMASK, &old_, nullptr) == 0); }
612
613 private:
614 sigset_t old_;
615};
616
617// Class to manage the static state associated with killing multiple event
618// loops.
619class SignalHandler {
620 public:
621 // Gets the singleton.
622 static SignalHandler *global() {
623 static SignalHandler loop;
624 return &loop;
625 }
626
627 // Handles the signal with the singleton.
628 static void HandleSignal(int) { global()->DoHandleSignal(); }
629
630 // Registers an event loop to receive Exit() calls.
631 void Register(ShmEventLoop *event_loop) {
632 // Block signals while we have the mutex so we never race with the signal
633 // handler.
634 ScopedSignalMask mask({SIGINT, SIGHUP, SIGTERM});
635 std::unique_lock<stl_mutex> locker(mutex_);
636 if (event_loops_.size() == 0) {
637 // The first caller registers the signal handler.
638 struct sigaction new_action;
639 sigemptyset(&new_action.sa_mask);
640 // This makes it so that 2 control c's to a stuck process will kill it by
641 // restoring the original signal handler.
642 new_action.sa_flags = SA_RESETHAND;
643 new_action.sa_handler = &HandleSignal;
644
645 PCHECK(sigaction(SIGINT, &new_action, &old_action_int_) == 0);
646 PCHECK(sigaction(SIGHUP, &new_action, &old_action_hup_) == 0);
647 PCHECK(sigaction(SIGTERM, &new_action, &old_action_term_) == 0);
648 }
649
650 event_loops_.push_back(event_loop);
651 }
652
653 // Unregisters an event loop to receive Exit() calls.
654 void Unregister(ShmEventLoop *event_loop) {
655 // Block signals while we have the mutex so we never race with the signal
656 // handler.
657 ScopedSignalMask mask({SIGINT, SIGHUP, SIGTERM});
658 std::unique_lock<stl_mutex> locker(mutex_);
659
660 event_loops_.erase(std::find(event_loops_.begin(), event_loops_.end(), event_loop));
661
662 if (event_loops_.size() == 0u) {
663 // The last caller restores the original signal handlers.
664 PCHECK(sigaction(SIGINT, &old_action_int_, nullptr) == 0);
665 PCHECK(sigaction(SIGHUP, &old_action_hup_, nullptr) == 0);
666 PCHECK(sigaction(SIGTERM, &old_action_term_, nullptr) == 0);
667 }
668 }
669
670 private:
671 void DoHandleSignal() {
672 // We block signals while grabbing the lock, so there should never be a
673 // race. Confirm that this is true using trylock.
674 CHECK(mutex_.try_lock()) << ": sigprocmask failed to block signals while "
675 "modifing the event loop list.";
676 for (ShmEventLoop *event_loop : event_loops_) {
677 event_loop->Exit();
678 }
679 mutex_.unlock();
680 }
681
682 // Mutex to protect all state.
683 stl_mutex mutex_;
684 std::vector<ShmEventLoop *> event_loops_;
685 struct sigaction old_action_int_;
686 struct sigaction old_action_hup_;
687 struct sigaction old_action_term_;
688};
689
Alex Perrycb7da4b2019-08-28 19:35:56 -0700690void ShmEventLoop::Run() {
Austin Schuh32fd5a72019-12-01 22:20:26 -0800691 SignalHandler::global()->Register(this);
Austin Schuh39788ff2019-12-01 18:22:57 -0800692
Alex Perrycb7da4b2019-08-28 19:35:56 -0700693 std::unique_ptr<ipc_lib::SignalFd> signalfd;
694
695 if (watchers_.size() > 0) {
696 signalfd.reset(new ipc_lib::SignalFd({ipc_lib::kWakeupSignal}));
697
698 epoll_.OnReadable(signalfd->fd(), [signalfd_ptr = signalfd.get(), this]() {
699 signalfd_siginfo result = signalfd_ptr->Read();
700 CHECK_EQ(result.ssi_signo, ipc_lib::kWakeupSignal);
701
702 // TODO(austin): We should really be checking *everything*, not just
703 // watchers, and calling the oldest thing first. That will improve
704 // determinism a lot.
705
Austin Schuh7d87b672019-12-01 20:23:49 -0800706 HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700707 });
708 }
709
Austin Schuh39788ff2019-12-01 18:22:57 -0800710 MaybeScheduleTimingReports();
711
Austin Schuh7d87b672019-12-01 20:23:49 -0800712 ReserveEvents();
713
Austin Schuh39788ff2019-12-01 18:22:57 -0800714 // Now, all the callbacks are setup. Lock everything into memory and go RT.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700715 if (priority_ != 0) {
716 ::aos::InitRT();
717
718 LOG(INFO) << "Setting priority to " << priority_;
719 ::aos::SetCurrentThreadRealtimePriority(priority_);
720 }
721
722 set_is_running(true);
723
724 // Now that we are realtime (but before the OnRun handlers run), snap the
725 // queue index.
Austin Schuh39788ff2019-12-01 18:22:57 -0800726 for (::std::unique_ptr<WatcherState> &watcher : watchers_) {
727 watcher->Startup(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700728 }
729
730 // Now that we are RT, run all the OnRun handlers.
731 for (const auto &run : on_run_) {
732 run();
733 }
734
Alex Perrycb7da4b2019-08-28 19:35:56 -0700735 // And start our main event loop which runs all the timers and handles Quit.
736 epoll_.Run();
737
738 // Once epoll exits, there is no useful nonrt work left to do.
739 set_is_running(false);
740
741 // Nothing time or synchronization critical needs to happen after this point.
742 // Drop RT priority.
743 ::aos::UnsetCurrentThreadRealtimePriority();
744
Austin Schuh39788ff2019-12-01 18:22:57 -0800745 for (::std::unique_ptr<WatcherState> &base_watcher : watchers_) {
746 internal::WatcherState *watcher =
747 reinterpret_cast<internal::WatcherState *>(base_watcher.get());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700748 watcher->UnregisterWakeup();
749 }
750
751 if (watchers_.size() > 0) {
752 epoll_.DeleteFd(signalfd->fd());
753 signalfd.reset();
754 }
Austin Schuh32fd5a72019-12-01 22:20:26 -0800755
756 SignalHandler::global()->Unregister(this);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700757}
758
759void ShmEventLoop::Exit() { epoll_.Quit(); }
760
761ShmEventLoop::~ShmEventLoop() {
Austin Schuh39788ff2019-12-01 18:22:57 -0800762 // Trigger any remaining senders or fetchers to be cleared before destroying
763 // the event loop so the book keeping matches.
764 timing_report_sender_.reset();
765
766 // Force everything with a registered fd with epoll to be destroyed now.
767 timers_.clear();
768 phased_loops_.clear();
769 watchers_.clear();
770
Alex Perrycb7da4b2019-08-28 19:35:56 -0700771 CHECK(!is_running()) << ": ShmEventLoop destroyed while running";
772}
773
774void ShmEventLoop::Take(const Channel *channel) {
775 CHECK(!is_running()) << ": Cannot add new objects while running.";
776
777 // Cheat aggresively. Use the shared memory path as a proxy for a unique
778 // identifier for the channel.
779 const std::string path = ShmPath(channel);
780
781 const auto prior = ::std::find(taken_.begin(), taken_.end(), path);
782 CHECK(prior == taken_.end()) << ": " << path << " is already being used.";
783
784 taken_.emplace_back(path);
785}
786
787void ShmEventLoop::SetRuntimeRealtimePriority(int priority) {
788 if (is_running()) {
789 LOG(FATAL) << "Cannot set realtime priority while running.";
790 }
791 priority_ = priority;
792}
793
Austin Schuh39788ff2019-12-01 18:22:57 -0800794pid_t ShmEventLoop::GetTid() { return syscall(SYS_gettid); }
795
Alex Perrycb7da4b2019-08-28 19:35:56 -0700796} // namespace aos