blob: e45c065d59f3dfe40bbb5b89bed8166c9820bcbb [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
Brian Silverman4f4e0612020-08-12 19:54:41 -070056namespace {
57
Alex Perrycb7da4b2019-08-28 19:35:56 -070058std::string ShmFolder(const Channel *channel) {
59 CHECK(channel->has_name());
60 CHECK_EQ(channel->name()->string_view()[0], '/');
61 return FLAGS_shm_base + channel->name()->str() + "/";
62}
63std::string ShmPath(const Channel *channel) {
64 CHECK(channel->has_type());
Brian Silverman177567e2020-08-12 19:51:33 -070065 return ShmFolder(channel) + channel->type()->str() + ".v3";
Alex Perrycb7da4b2019-08-28 19:35:56 -070066}
67
Brian Silverman3b0cdaf2020-04-28 16:51:51 -070068void PageFaultData(char *data, size_t size) {
69 // This just has to divide the actual page size. Being smaller will make this
70 // a bit slower than necessary, but not much. 1024 is a pretty conservative
71 // choice (most pages are probably 4096).
72 static constexpr size_t kPageSize = 1024;
73 const size_t pages = (size + kPageSize - 1) / kPageSize;
74 for (size_t i = 0; i < pages; ++i) {
75 char zero = 0;
76 // We need to ensure there's a writable pagetable entry, but avoid modifying
77 // the data.
78 //
79 // Even if you lock the data into memory, some kernels still seem to lazily
80 // create the actual pagetable entries. This means we need to somehow
81 // "write" to the page.
82 //
83 // Also, this takes place while other processes may be concurrently
84 // opening/initializing the memory, so we need to avoid corrupting that.
85 //
86 // This is the simplest operation I could think of which achieves that:
87 // "store 0 if it's already 0".
88 __atomic_compare_exchange_n(&data[i * kPageSize], &zero, 0, true,
89 __ATOMIC_RELAXED, __ATOMIC_RELAXED);
90 }
91}
92
Brian Silverman4f4e0612020-08-12 19:54:41 -070093ipc_lib::LocklessQueueConfiguration MakeQueueConfiguration(
94 const Channel *channel, std::chrono::seconds channel_storage_duration) {
95 ipc_lib::LocklessQueueConfiguration config;
96
97 config.num_watchers = channel->num_watchers();
98 config.num_senders = channel->num_senders();
99 // The value in the channel will default to 0 if readers are configured to
100 // copy.
101 config.num_pinners = channel->num_readers();
102 config.queue_size = channel_storage_duration.count() * channel->frequency();
103 config.message_data_size = channel->max_size();
104
105 return config;
106}
107
Alex Perrycb7da4b2019-08-28 19:35:56 -0700108class MMapedQueue {
109 public:
Austin Schuhaa79e4e2019-12-29 20:43:32 -0800110 MMapedQueue(const Channel *channel,
Brian Silverman4f4e0612020-08-12 19:54:41 -0700111 std::chrono::seconds channel_storage_duration)
112 : config_(MakeQueueConfiguration(channel, channel_storage_duration)) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700113 std::string path = ShmPath(channel);
114
Alex Perrycb7da4b2019-08-28 19:35:56 -0700115 size_ = ipc_lib::LocklessQueueMemorySize(config_);
116
Austin Schuhfccb2d02020-01-26 16:11:19 -0800117 util::MkdirP(path, FLAGS_permissions);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700118
119 // There are 2 cases. Either the file already exists, or it does not
120 // already exist and we need to create it. Start by trying to create it. If
121 // that fails, the file has already been created and we can open it
Brian Silverman4f4e0612020-08-12 19:54:41 -0700122 // normally.. Once the file has been created it will never be deleted.
Brian Silvermanf9f30ea2020-03-04 23:18:54 -0800123 int fd = open(path.c_str(), O_RDWR | O_CREAT | O_EXCL,
Brian Silverman148d43d2020-06-07 18:19:22 -0500124 O_CLOEXEC | FLAGS_permissions);
Brian Silvermanf9f30ea2020-03-04 23:18:54 -0800125 if (fd == -1 && errno == EEXIST) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700126 VLOG(1) << path << " already created.";
127 // File already exists.
Brian Silvermanf9f30ea2020-03-04 23:18:54 -0800128 fd = open(path.c_str(), O_RDWR, O_CLOEXEC);
129 PCHECK(fd != -1) << ": Failed to open " << path;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700130 while (true) {
131 struct stat st;
Brian Silvermanf9f30ea2020-03-04 23:18:54 -0800132 PCHECK(fstat(fd, &st) == 0);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700133 if (st.st_size != 0) {
134 CHECK_EQ(static_cast<size_t>(st.st_size), size_)
135 << ": Size of " << path
136 << " doesn't match expected size of backing queue file. Did the "
137 "queue definition change?";
138 break;
139 } else {
140 // The creating process didn't get around to it yet. Give it a bit.
141 std::this_thread::sleep_for(std::chrono::milliseconds(10));
142 VLOG(1) << path << " is zero size, waiting";
143 }
144 }
145 } else {
146 VLOG(1) << "Created " << path;
Brian Silvermanf9f30ea2020-03-04 23:18:54 -0800147 PCHECK(fd != -1) << ": Failed to open " << path;
148 PCHECK(ftruncate(fd, size_) == 0);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700149 }
150
Brian Silvermanf9f30ea2020-03-04 23:18:54 -0800151 data_ = mmap(NULL, size_, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700152 PCHECK(data_ != MAP_FAILED);
Brian Silvermanf9f30ea2020-03-04 23:18:54 -0800153 PCHECK(close(fd) == 0);
Brian Silverman3b0cdaf2020-04-28 16:51:51 -0700154 PageFaultData(static_cast<char *>(data_), size_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700155
156 ipc_lib::InitializeLocklessQueueMemory(memory(), config_);
157 }
158
Brian Silverman148d43d2020-06-07 18:19:22 -0500159 ~MMapedQueue() { PCHECK(munmap(data_, size_) == 0); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700160
161 ipc_lib::LocklessQueueMemory *memory() const {
162 return reinterpret_cast<ipc_lib::LocklessQueueMemory *>(data_);
163 }
164
Austin Schuh39788ff2019-12-01 18:22:57 -0800165 const ipc_lib::LocklessQueueConfiguration &config() const { return config_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700166
Brian Silverman5120afb2020-01-31 17:44:35 -0800167 absl::Span<char> GetSharedMemory() const {
168 return absl::Span<char>(static_cast<char *>(data_), size_);
169 }
170
Alex Perrycb7da4b2019-08-28 19:35:56 -0700171 private:
Brian Silverman4f4e0612020-08-12 19:54:41 -0700172 const ipc_lib::LocklessQueueConfiguration config_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700173
Alex Perrycb7da4b2019-08-28 19:35:56 -0700174 size_t size_;
175 void *data_;
176};
177
Austin Schuh217a9782019-12-21 23:02:50 -0800178const Node *MaybeMyNode(const Configuration *configuration) {
179 if (!configuration->has_nodes()) {
180 return nullptr;
181 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700182
Austin Schuh217a9782019-12-21 23:02:50 -0800183 return configuration::GetMyNode(configuration);
184}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700185
186namespace chrono = ::std::chrono;
187
Austin Schuh39788ff2019-12-01 18:22:57 -0800188} // namespace
189
Austin Schuh217a9782019-12-21 23:02:50 -0800190ShmEventLoop::ShmEventLoop(const Configuration *configuration)
191 : EventLoop(configuration),
Austin Schuhe84c3ed2019-12-14 15:29:48 -0800192 name_(FLAGS_application_name),
Austin Schuh15649d62019-12-28 16:36:38 -0800193 node_(MaybeMyNode(configuration)) {
194 if (configuration->has_nodes()) {
195 CHECK(node_ != nullptr) << ": Couldn't find node in config.";
196 }
197}
Austin Schuh217a9782019-12-21 23:02:50 -0800198
Brian Silverman148d43d2020-06-07 18:19:22 -0500199namespace shm_event_loop_internal {
Austin Schuh39788ff2019-12-01 18:22:57 -0800200
201class SimpleShmFetcher {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700202 public:
Brian Silverman3bca5322020-08-12 19:35:29 -0700203 explicit SimpleShmFetcher(ShmEventLoop *event_loop, const Channel *channel)
Austin Schuh432784f2020-06-23 17:27:35 -0700204 : event_loop_(event_loop),
205 channel_(channel),
Austin Schuhaa79e4e2019-12-29 20:43:32 -0800206 lockless_queue_memory_(
207 channel,
Brian Silverman587da252020-01-01 17:00:47 -0800208 chrono::ceil<chrono::seconds>(chrono::nanoseconds(
Austin Schuhaa79e4e2019-12-29 20:43:32 -0800209 event_loop->configuration()->channel_storage_duration()))),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700210 lockless_queue_(lockless_queue_memory_.memory(),
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800211 lockless_queue_memory_.config()) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700212 context_.data = nullptr;
213 // Point the queue index at the next index to read starting now. This
214 // makes it such that FetchNext will read the next message sent after
215 // the fetcher is created.
216 PointAtNextQueueIndex();
217 }
218
Austin Schuh39788ff2019-12-01 18:22:57 -0800219 ~SimpleShmFetcher() {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700220
Brian Silverman77162972020-08-12 19:52:40 -0700221 // Sets this object to pin or copy data, as configured in the channel.
222 void RetrieveData() {
223 if (channel_->read_method() == ReadMethod::PIN) {
224 PinDataOnFetch();
225 } else {
226 CopyDataOnFetch();
227 }
228 }
229
Brian Silverman3bca5322020-08-12 19:35:29 -0700230 // Sets this object to copy data out of the shared memory into a private
231 // buffer when fetching.
232 void CopyDataOnFetch() {
Brian Silverman77162972020-08-12 19:52:40 -0700233 CHECK(!pin_data());
Brian Silverman3bca5322020-08-12 19:35:29 -0700234 data_storage_.reset(static_cast<char *>(
235 malloc(channel_->max_size() + kChannelDataAlignment - 1)));
236 }
237
Brian Silverman77162972020-08-12 19:52:40 -0700238 // Sets this object to pin data in shared memory when fetching.
239 void PinDataOnFetch() {
240 CHECK(!copy_data());
241 auto maybe_pinner = lockless_queue_.MakePinner();
242 if (!maybe_pinner) {
243 LOG(FATAL) << "Failed to create reader on "
244 << configuration::CleanedChannelToString(channel_)
245 << ", too many readers.";
246 }
247 pinner_ = std::move(maybe_pinner.value());
248 }
249
Alex Perrycb7da4b2019-08-28 19:35:56 -0700250 // Points the next message to fetch at the queue index which will be
251 // populated next.
252 void PointAtNextQueueIndex() {
253 actual_queue_index_ = lockless_queue_.LatestQueueIndex();
254 if (!actual_queue_index_.valid()) {
255 // Nothing in the queue. The next element will show up at the 0th
256 // index in the queue.
257 actual_queue_index_ =
258 ipc_lib::QueueIndex::Zero(lockless_queue_.queue_size());
259 } else {
260 actual_queue_index_ = actual_queue_index_.Increment();
261 }
262 }
263
Austin Schuh39788ff2019-12-01 18:22:57 -0800264 bool FetchNext() {
Brian Silverman3bca5322020-08-12 19:35:29 -0700265 const ipc_lib::LocklessQueue::ReadResult read_result =
266 DoFetch(actual_queue_index_);
Austin Schuh432784f2020-06-23 17:27:35 -0700267
Alex Perrycb7da4b2019-08-28 19:35:56 -0700268 return read_result == ipc_lib::LocklessQueue::ReadResult::GOOD;
269 }
270
Austin Schuh39788ff2019-12-01 18:22:57 -0800271 bool Fetch() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700272 const ipc_lib::QueueIndex queue_index = lockless_queue_.LatestQueueIndex();
273 // actual_queue_index_ is only meaningful if it was set by Fetch or
274 // FetchNext. This happens when valid_data_ has been set. So, only
275 // skip checking if valid_data_ is true.
276 //
277 // Also, if the latest queue index is invalid, we are empty. So there
278 // is nothing to fetch.
Austin Schuh39788ff2019-12-01 18:22:57 -0800279 if ((context_.data != nullptr &&
Alex Perrycb7da4b2019-08-28 19:35:56 -0700280 queue_index == actual_queue_index_.DecrementBy(1u)) ||
281 !queue_index.valid()) {
282 return false;
283 }
284
Brian Silverman3bca5322020-08-12 19:35:29 -0700285 const ipc_lib::LocklessQueue::ReadResult read_result = DoFetch(queue_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700286
287 CHECK(read_result != ipc_lib::LocklessQueue::ReadResult::NOTHING_NEW)
Austin Schuhf5652592019-12-29 16:26:15 -0800288 << ": Queue index went backwards. This should never happen. "
289 << configuration::CleanedChannelToString(channel_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700290
Alex Perrycb7da4b2019-08-28 19:35:56 -0700291 return read_result == ipc_lib::LocklessQueue::ReadResult::GOOD;
292 }
293
Austin Schuh39788ff2019-12-01 18:22:57 -0800294 Context context() const { return context_; }
295
Alex Perrycb7da4b2019-08-28 19:35:56 -0700296 bool RegisterWakeup(int priority) {
297 return lockless_queue_.RegisterWakeup(priority);
298 }
299
300 void UnregisterWakeup() { lockless_queue_.UnregisterWakeup(); }
301
Brian Silverman5120afb2020-01-31 17:44:35 -0800302 absl::Span<char> GetSharedMemory() const {
303 return lockless_queue_memory_.GetSharedMemory();
304 }
305
Brian Silverman6d2b3592020-06-18 14:40:15 -0700306 absl::Span<char> GetPrivateMemory() const {
Brian Silverman3bca5322020-08-12 19:35:29 -0700307 // Can't usefully expose this for pinning, because the buffer changes
308 // address for each message. Callers who want to work with that should just
309 // grab the whole shared memory buffer instead.
Brian Silverman6d2b3592020-06-18 14:40:15 -0700310 return absl::Span<char>(
311 const_cast<SimpleShmFetcher *>(this)->data_storage_start(),
312 lockless_queue_.message_data_size());
313 }
314
Alex Perrycb7da4b2019-08-28 19:35:56 -0700315 private:
Brian Silverman3bca5322020-08-12 19:35:29 -0700316 ipc_lib::LocklessQueue::ReadResult DoFetch(ipc_lib::QueueIndex queue_index) {
317 // TODO(austin): Get behind and make sure it dies.
318 char *copy_buffer = nullptr;
319 if (copy_data()) {
320 copy_buffer = data_storage_start();
321 }
322 ipc_lib::LocklessQueue::ReadResult read_result = lockless_queue_.Read(
323 queue_index.index(), &context_.monotonic_event_time,
324 &context_.realtime_event_time, &context_.monotonic_remote_time,
325 &context_.realtime_remote_time, &context_.remote_queue_index,
326 &context_.size, copy_buffer);
327
328 if (read_result == ipc_lib::LocklessQueue::ReadResult::GOOD) {
Brian Silverman77162972020-08-12 19:52:40 -0700329 if (pin_data()) {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700330 const int pin_result = pinner_->PinIndex(queue_index.index());
331 CHECK(pin_result >= 0)
Brian Silverman77162972020-08-12 19:52:40 -0700332 << ": Got behind while reading and the last message was modified "
333 "out from under us while we tried to pin it. Don't get so far "
334 "behind on: "
335 << configuration::CleanedChannelToString(channel_);
Brian Silverman4f4e0612020-08-12 19:54:41 -0700336 context_.buffer_index = pin_result;
337 } else {
338 context_.buffer_index = -1;
Brian Silverman77162972020-08-12 19:52:40 -0700339 }
340
Brian Silverman3bca5322020-08-12 19:35:29 -0700341 context_.queue_index = queue_index.index();
342 if (context_.remote_queue_index == 0xffffffffu) {
343 context_.remote_queue_index = context_.queue_index;
344 }
345 if (context_.monotonic_remote_time == aos::monotonic_clock::min_time) {
346 context_.monotonic_remote_time = context_.monotonic_event_time;
347 }
348 if (context_.realtime_remote_time == aos::realtime_clock::min_time) {
349 context_.realtime_remote_time = context_.realtime_event_time;
350 }
351 const char *const data = DataBuffer();
352 if (data) {
353 context_.data =
354 data + lockless_queue_.message_data_size() - context_.size;
355 } else {
356 context_.data = nullptr;
357 }
358 actual_queue_index_ = queue_index.Increment();
359 }
360
361 // Make sure the data wasn't modified while we were reading it. This
362 // can only happen if you are reading the last message *while* it is
363 // being written to, which means you are pretty far behind.
364 CHECK(read_result != ipc_lib::LocklessQueue::ReadResult::OVERWROTE)
365 << ": Got behind while reading and the last message was modified "
366 "out from under us while we were reading it. Don't get so far "
367 "behind on: "
368 << configuration::CleanedChannelToString(channel_);
369
370 // We fell behind between when we read the index and read the value.
371 // This isn't worth recovering from since this means we went to sleep
372 // for a long time in the middle of this function.
373 if (read_result == ipc_lib::LocklessQueue::ReadResult::TOO_OLD) {
374 event_loop_->SendTimingReport();
375 LOG(FATAL) << "The next message is no longer available. "
376 << configuration::CleanedChannelToString(channel_);
377 }
378
379 return read_result;
380 }
381
382 char *data_storage_start() const {
383 CHECK(copy_data());
Brian Silvermana1652f32020-01-29 20:41:44 -0800384 return RoundChannelData(data_storage_.get(), channel_->max_size());
385 }
Brian Silverman3bca5322020-08-12 19:35:29 -0700386
387 // Note that for some modes the return value will change as new messages are
388 // read.
389 const char *DataBuffer() const {
390 if (copy_data()) {
391 return data_storage_start();
392 }
Brian Silverman77162972020-08-12 19:52:40 -0700393 if (pin_data()) {
394 return static_cast<const char *>(pinner_->Data());
395 }
Brian Silverman3bca5322020-08-12 19:35:29 -0700396 return nullptr;
397 }
398
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800399 bool copy_data() const { return static_cast<bool>(data_storage_); }
Brian Silverman77162972020-08-12 19:52:40 -0700400 bool pin_data() const { return static_cast<bool>(pinner_); }
Brian Silvermana1652f32020-01-29 20:41:44 -0800401
Austin Schuh432784f2020-06-23 17:27:35 -0700402 aos::ShmEventLoop *event_loop_;
Austin Schuhf5652592019-12-29 16:26:15 -0800403 const Channel *const channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700404 MMapedQueue lockless_queue_memory_;
405 ipc_lib::LocklessQueue lockless_queue_;
406
407 ipc_lib::QueueIndex actual_queue_index_ =
408 ipc_lib::LocklessQueue::empty_queue_index();
409
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800410 // This being empty indicates we're not going to copy data.
411 std::unique_ptr<char, decltype(&free)> data_storage_{nullptr, &free};
Austin Schuh39788ff2019-12-01 18:22:57 -0800412
Brian Silverman77162972020-08-12 19:52:40 -0700413 // This being nullopt indicates we're not going to pin messages.
414 std::optional<ipc_lib::LocklessQueue::Pinner> pinner_;
415
Austin Schuh39788ff2019-12-01 18:22:57 -0800416 Context context_;
417};
418
419class ShmFetcher : public RawFetcher {
420 public:
Austin Schuh432784f2020-06-23 17:27:35 -0700421 explicit ShmFetcher(ShmEventLoop *event_loop, const Channel *channel)
Austin Schuhaa79e4e2019-12-29 20:43:32 -0800422 : RawFetcher(event_loop, channel),
Brian Silverman3bca5322020-08-12 19:35:29 -0700423 simple_shm_fetcher_(event_loop, channel) {
Brian Silverman77162972020-08-12 19:52:40 -0700424 simple_shm_fetcher_.RetrieveData();
Brian Silverman3bca5322020-08-12 19:35:29 -0700425 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800426
427 ~ShmFetcher() { context_.data = nullptr; }
428
429 std::pair<bool, monotonic_clock::time_point> DoFetchNext() override {
430 if (simple_shm_fetcher_.FetchNext()) {
431 context_ = simple_shm_fetcher_.context();
432 return std::make_pair(true, monotonic_clock::now());
433 }
434 return std::make_pair(false, monotonic_clock::min_time);
435 }
436
437 std::pair<bool, monotonic_clock::time_point> DoFetch() override {
438 if (simple_shm_fetcher_.Fetch()) {
439 context_ = simple_shm_fetcher_.context();
440 return std::make_pair(true, monotonic_clock::now());
441 }
442 return std::make_pair(false, monotonic_clock::min_time);
443 }
444
Brian Silverman6d2b3592020-06-18 14:40:15 -0700445 absl::Span<char> GetPrivateMemory() const {
446 return simple_shm_fetcher_.GetPrivateMemory();
447 }
448
Austin Schuh39788ff2019-12-01 18:22:57 -0800449 private:
450 SimpleShmFetcher simple_shm_fetcher_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700451};
452
453class ShmSender : public RawSender {
454 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800455 explicit ShmSender(EventLoop *event_loop, const Channel *channel)
456 : RawSender(event_loop, channel),
Austin Schuhaa79e4e2019-12-29 20:43:32 -0800457 lockless_queue_memory_(
458 channel,
Brian Silverman587da252020-01-01 17:00:47 -0800459 chrono::ceil<chrono::seconds>(chrono::nanoseconds(
Austin Schuhaa79e4e2019-12-29 20:43:32 -0800460 event_loop->configuration()->channel_storage_duration()))),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700461 lockless_queue_(lockless_queue_memory_.memory(),
462 lockless_queue_memory_.config()),
Austin Schuhe516ab02020-05-06 21:37:04 -0700463 lockless_queue_sender_(
464 VerifySender(lockless_queue_.MakeSender(), channel)) {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700465
Austin Schuh39788ff2019-12-01 18:22:57 -0800466 ~ShmSender() override {}
467
Austin Schuhe516ab02020-05-06 21:37:04 -0700468 static ipc_lib::LocklessQueue::Sender VerifySender(
469 std::optional<ipc_lib::LocklessQueue::Sender> &&sender,
470 const Channel *channel) {
471 if (sender) {
472 return std::move(sender.value());
473 }
474 LOG(FATAL) << "Failed to create sender on "
475 << configuration::CleanedChannelToString(channel)
476 << ", too many senders.";
477 }
478
Alex Perrycb7da4b2019-08-28 19:35:56 -0700479 void *data() override { return lockless_queue_sender_.Data(); }
480 size_t size() override { return lockless_queue_sender_.size(); }
Austin Schuhad154822019-12-27 15:45:13 -0800481 bool DoSend(size_t length,
482 aos::monotonic_clock::time_point monotonic_remote_time,
483 aos::realtime_clock::time_point realtime_remote_time,
484 uint32_t remote_queue_index) override {
Austin Schuh0f7ed462020-03-28 20:38:34 -0700485 CHECK_LE(length, static_cast<size_t>(channel()->max_size()))
486 << ": Sent too big a message on "
487 << configuration::CleanedChannelToString(channel());
Austin Schuhad154822019-12-27 15:45:13 -0800488 lockless_queue_sender_.Send(
489 length, monotonic_remote_time, realtime_remote_time, remote_queue_index,
490 &monotonic_sent_time_, &realtime_sent_time_, &sent_queue_index_);
Austin Schuh39788ff2019-12-01 18:22:57 -0800491 lockless_queue_.Wakeup(event_loop()->priority());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700492 return true;
493 }
494
Austin Schuhad154822019-12-27 15:45:13 -0800495 bool DoSend(const void *msg, size_t length,
496 aos::monotonic_clock::time_point monotonic_remote_time,
497 aos::realtime_clock::time_point realtime_remote_time,
498 uint32_t remote_queue_index) override {
Austin Schuh0f7ed462020-03-28 20:38:34 -0700499 CHECK_LE(length, static_cast<size_t>(channel()->max_size()))
500 << ": Sent too big a message on "
501 << configuration::CleanedChannelToString(channel());
Austin Schuhad154822019-12-27 15:45:13 -0800502 lockless_queue_sender_.Send(reinterpret_cast<const char *>(msg), length,
503 monotonic_remote_time, realtime_remote_time,
504 remote_queue_index, &monotonic_sent_time_,
505 &realtime_sent_time_, &sent_queue_index_);
Austin Schuh39788ff2019-12-01 18:22:57 -0800506 lockless_queue_.Wakeup(event_loop()->priority());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700507 // TODO(austin): Return an error if we send too fast.
508 return true;
509 }
510
Brian Silverman5120afb2020-01-31 17:44:35 -0800511 absl::Span<char> GetSharedMemory() const {
512 return lockless_queue_memory_.GetSharedMemory();
513 }
514
Brian Silverman4f4e0612020-08-12 19:54:41 -0700515 int buffer_index() override { return lockless_queue_sender_.buffer_index(); }
516
Alex Perrycb7da4b2019-08-28 19:35:56 -0700517 private:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700518 MMapedQueue lockless_queue_memory_;
519 ipc_lib::LocklessQueue lockless_queue_;
520 ipc_lib::LocklessQueue::Sender lockless_queue_sender_;
521};
522
Alex Perrycb7da4b2019-08-28 19:35:56 -0700523// Class to manage the state for a Watcher.
Brian Silverman148d43d2020-06-07 18:19:22 -0500524class ShmWatcherState : public WatcherState {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700525 public:
Brian Silverman148d43d2020-06-07 18:19:22 -0500526 ShmWatcherState(
Austin Schuh7d87b672019-12-01 20:23:49 -0800527 ShmEventLoop *event_loop, const Channel *channel,
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800528 std::function<void(const Context &context, const void *message)> fn,
529 bool copy_data)
Brian Silverman148d43d2020-06-07 18:19:22 -0500530 : WatcherState(event_loop, channel, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800531 event_loop_(event_loop),
532 event_(this),
Brian Silverman3bca5322020-08-12 19:35:29 -0700533 simple_shm_fetcher_(event_loop, channel) {
534 if (copy_data) {
Brian Silverman77162972020-08-12 19:52:40 -0700535 simple_shm_fetcher_.RetrieveData();
Brian Silverman3bca5322020-08-12 19:35:29 -0700536 }
537 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700538
Brian Silverman148d43d2020-06-07 18:19:22 -0500539 ~ShmWatcherState() override { event_loop_->RemoveEvent(&event_); }
Austin Schuh39788ff2019-12-01 18:22:57 -0800540
541 void Startup(EventLoop *event_loop) override {
Austin Schuh7d87b672019-12-01 20:23:49 -0800542 simple_shm_fetcher_.PointAtNextQueueIndex();
Austin Schuh39788ff2019-12-01 18:22:57 -0800543 CHECK(RegisterWakeup(event_loop->priority()));
544 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700545
Alex Perrycb7da4b2019-08-28 19:35:56 -0700546 // Returns true if there is new data available.
Austin Schuh7d87b672019-12-01 20:23:49 -0800547 bool CheckForNewData() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700548 if (!has_new_data_) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800549 has_new_data_ = simple_shm_fetcher_.FetchNext();
Austin Schuh7d87b672019-12-01 20:23:49 -0800550
551 if (has_new_data_) {
552 event_.set_event_time(
Austin Schuhad154822019-12-27 15:45:13 -0800553 simple_shm_fetcher_.context().monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800554 event_loop_->AddEvent(&event_);
555 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700556 }
557
558 return has_new_data_;
559 }
560
Alex Perrycb7da4b2019-08-28 19:35:56 -0700561 // Consumes the data by calling the callback.
Austin Schuh7d87b672019-12-01 20:23:49 -0800562 void HandleEvent() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700563 CHECK(has_new_data_);
Austin Schuh39788ff2019-12-01 18:22:57 -0800564 DoCallCallback(monotonic_clock::now, simple_shm_fetcher_.context());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700565 has_new_data_ = false;
Austin Schuh7d87b672019-12-01 20:23:49 -0800566 CheckForNewData();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700567 }
568
Austin Schuh39788ff2019-12-01 18:22:57 -0800569 // Registers us to receive a signal on event reception.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700570 bool RegisterWakeup(int priority) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800571 return simple_shm_fetcher_.RegisterWakeup(priority);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700572 }
573
Austin Schuh39788ff2019-12-01 18:22:57 -0800574 void UnregisterWakeup() { return simple_shm_fetcher_.UnregisterWakeup(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700575
Brian Silverman5120afb2020-01-31 17:44:35 -0800576 absl::Span<char> GetSharedMemory() const {
577 return simple_shm_fetcher_.GetSharedMemory();
578 }
579
Alex Perrycb7da4b2019-08-28 19:35:56 -0700580 private:
581 bool has_new_data_ = false;
582
Austin Schuh7d87b672019-12-01 20:23:49 -0800583 ShmEventLoop *event_loop_;
Brian Silverman148d43d2020-06-07 18:19:22 -0500584 EventHandler<ShmWatcherState> event_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800585 SimpleShmFetcher simple_shm_fetcher_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700586};
587
588// Adapter class to adapt a timerfd to a TimerHandler.
Brian Silverman148d43d2020-06-07 18:19:22 -0500589class ShmTimerHandler final : public TimerHandler {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700590 public:
Brian Silverman148d43d2020-06-07 18:19:22 -0500591 ShmTimerHandler(ShmEventLoop *shm_event_loop, ::std::function<void()> fn)
Austin Schuh39788ff2019-12-01 18:22:57 -0800592 : TimerHandler(shm_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800593 shm_event_loop_(shm_event_loop),
594 event_(this) {
Austin Schuhcde39fd2020-02-22 20:58:24 -0800595 shm_event_loop_->epoll_.OnReadable(timerfd_.fd(), [this]() {
596 // The timer may fire spurriously. HandleEvent on the event loop will
597 // call the callback if it is needed. It may also have called it when
598 // processing some other event, and the kernel decided to deliver this
599 // wakeup anyways.
600 timerfd_.Read();
601 shm_event_loop_->HandleEvent();
602 });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700603 }
604
Brian Silverman148d43d2020-06-07 18:19:22 -0500605 ~ShmTimerHandler() {
Austin Schuh7d87b672019-12-01 20:23:49 -0800606 Disable();
607 shm_event_loop_->epoll_.DeleteFd(timerfd_.fd());
608 }
609
610 void HandleEvent() {
Austin Schuhcde39fd2020-02-22 20:58:24 -0800611 CHECK(!event_.valid());
612 const auto monotonic_now = Call(monotonic_clock::now, base_);
613 if (event_.valid()) {
614 // If someone called Setup inside Call, rescheduling is already taken care
615 // of. Bail.
616 return;
Austin Schuh7d87b672019-12-01 20:23:49 -0800617 }
618
Austin Schuhcde39fd2020-02-22 20:58:24 -0800619 if (repeat_offset_ == chrono::seconds(0)) {
620 timerfd_.Disable();
621 } else {
622 // Compute how many cycles have elapsed and schedule the next iteration
623 // for the next iteration in the future.
624 const int elapsed_cycles =
625 std::max<int>(0, (monotonic_now - base_ + repeat_offset_ -
626 std::chrono::nanoseconds(1)) /
627 repeat_offset_);
628 base_ += repeat_offset_ * elapsed_cycles;
Austin Schuh7d87b672019-12-01 20:23:49 -0800629
Austin Schuhcde39fd2020-02-22 20:58:24 -0800630 // Update the heap and schedule the timerfd wakeup.
Austin Schuh7d87b672019-12-01 20:23:49 -0800631 event_.set_event_time(base_);
632 shm_event_loop_->AddEvent(&event_);
Austin Schuhcde39fd2020-02-22 20:58:24 -0800633 timerfd_.SetTime(base_, chrono::seconds(0));
Austin Schuh7d87b672019-12-01 20:23:49 -0800634 }
635 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700636
637 void Setup(monotonic_clock::time_point base,
638 monotonic_clock::duration repeat_offset) override {
Austin Schuh7d87b672019-12-01 20:23:49 -0800639 if (event_.valid()) {
640 shm_event_loop_->RemoveEvent(&event_);
641 }
642
Alex Perrycb7da4b2019-08-28 19:35:56 -0700643 timerfd_.SetTime(base, repeat_offset);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800644 base_ = base;
645 repeat_offset_ = repeat_offset;
Austin Schuh7d87b672019-12-01 20:23:49 -0800646 event_.set_event_time(base_);
647 shm_event_loop_->AddEvent(&event_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700648 }
649
Austin Schuh7d87b672019-12-01 20:23:49 -0800650 void Disable() override {
651 shm_event_loop_->RemoveEvent(&event_);
652 timerfd_.Disable();
653 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700654
655 private:
656 ShmEventLoop *shm_event_loop_;
Brian Silverman148d43d2020-06-07 18:19:22 -0500657 EventHandler<ShmTimerHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700658
Brian Silverman148d43d2020-06-07 18:19:22 -0500659 internal::TimerFd timerfd_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700660
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800661 monotonic_clock::time_point base_;
662 monotonic_clock::duration repeat_offset_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700663};
664
665// Adapter class to the timerfd and PhasedLoop.
Brian Silverman148d43d2020-06-07 18:19:22 -0500666class ShmPhasedLoopHandler final : public PhasedLoopHandler {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700667 public:
Brian Silverman148d43d2020-06-07 18:19:22 -0500668 ShmPhasedLoopHandler(ShmEventLoop *shm_event_loop,
669 ::std::function<void(int)> fn,
670 const monotonic_clock::duration interval,
671 const monotonic_clock::duration offset)
672 : PhasedLoopHandler(shm_event_loop, std::move(fn), interval, offset),
Austin Schuh7d87b672019-12-01 20:23:49 -0800673 shm_event_loop_(shm_event_loop),
674 event_(this) {
675 shm_event_loop_->epoll_.OnReadable(
676 timerfd_.fd(), [this]() { shm_event_loop_->HandleEvent(); });
677 }
678
679 void HandleEvent() {
680 // The return value for read is the number of cycles that have elapsed.
681 // Because we check to see when this event *should* have happened, there are
682 // cases where Read() will return 0, when 1 cycle has actually happened.
683 // This occurs when the timer interrupt hasn't triggered yet. Therefore,
684 // ignore it. Call handles rescheduling and calculating elapsed cycles
685 // without any extra help.
686 timerfd_.Read();
687 event_.Invalidate();
688
689 Call(monotonic_clock::now, [this](monotonic_clock::time_point sleep_time) {
690 Schedule(sleep_time);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700691 });
692 }
693
Brian Silverman148d43d2020-06-07 18:19:22 -0500694 ~ShmPhasedLoopHandler() override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800695 shm_event_loop_->epoll_.DeleteFd(timerfd_.fd());
Austin Schuh7d87b672019-12-01 20:23:49 -0800696 shm_event_loop_->RemoveEvent(&event_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700697 }
698
699 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800700 // Reschedules the timer.
Austin Schuh39788ff2019-12-01 18:22:57 -0800701 void Schedule(monotonic_clock::time_point sleep_time) override {
Austin Schuh7d87b672019-12-01 20:23:49 -0800702 if (event_.valid()) {
703 shm_event_loop_->RemoveEvent(&event_);
704 }
705
Austin Schuh39788ff2019-12-01 18:22:57 -0800706 timerfd_.SetTime(sleep_time, ::aos::monotonic_clock::zero());
Austin Schuh7d87b672019-12-01 20:23:49 -0800707 event_.set_event_time(sleep_time);
708 shm_event_loop_->AddEvent(&event_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700709 }
710
711 ShmEventLoop *shm_event_loop_;
Brian Silverman148d43d2020-06-07 18:19:22 -0500712 EventHandler<ShmPhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700713
Brian Silverman148d43d2020-06-07 18:19:22 -0500714 internal::TimerFd timerfd_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700715};
Brian Silverman148d43d2020-06-07 18:19:22 -0500716
717} // namespace shm_event_loop_internal
Alex Perrycb7da4b2019-08-28 19:35:56 -0700718
719::std::unique_ptr<RawFetcher> ShmEventLoop::MakeRawFetcher(
720 const Channel *channel) {
Austin Schuhca4828c2019-12-28 14:21:35 -0800721 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
722 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
723 << "\", \"type\": \"" << channel->type()->string_view()
724 << "\" } is not able to be fetched on this node. Check your "
725 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800726 }
727
Brian Silverman148d43d2020-06-07 18:19:22 -0500728 return ::std::unique_ptr<RawFetcher>(new ShmFetcher(this, channel));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700729}
730
731::std::unique_ptr<RawSender> ShmEventLoop::MakeRawSender(
732 const Channel *channel) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800733 TakeSender(channel);
Austin Schuh39788ff2019-12-01 18:22:57 -0800734
Brian Silverman148d43d2020-06-07 18:19:22 -0500735 return ::std::unique_ptr<RawSender>(new ShmSender(this, channel));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700736}
737
738void ShmEventLoop::MakeRawWatcher(
739 const Channel *channel,
740 std::function<void(const Context &context, const void *message)> watcher) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800741 TakeWatcher(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800742
Austin Schuh39788ff2019-12-01 18:22:57 -0800743 NewWatcher(::std::unique_ptr<WatcherState>(
Brian Silverman148d43d2020-06-07 18:19:22 -0500744 new ShmWatcherState(this, channel, std::move(watcher), true)));
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800745}
746
747void ShmEventLoop::MakeRawNoArgWatcher(
748 const Channel *channel,
749 std::function<void(const Context &context)> watcher) {
750 TakeWatcher(channel);
751
Brian Silverman148d43d2020-06-07 18:19:22 -0500752 NewWatcher(::std::unique_ptr<WatcherState>(new ShmWatcherState(
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800753 this, channel,
754 [watcher](const Context &context, const void *) { watcher(context); },
755 false)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700756}
757
758TimerHandler *ShmEventLoop::AddTimer(::std::function<void()> callback) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800759 return NewTimer(::std::unique_ptr<TimerHandler>(
Brian Silverman148d43d2020-06-07 18:19:22 -0500760 new ShmTimerHandler(this, ::std::move(callback))));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700761}
762
763PhasedLoopHandler *ShmEventLoop::AddPhasedLoop(
764 ::std::function<void(int)> callback,
765 const monotonic_clock::duration interval,
766 const monotonic_clock::duration offset) {
Brian Silverman148d43d2020-06-07 18:19:22 -0500767 return NewPhasedLoop(::std::unique_ptr<PhasedLoopHandler>(
768 new ShmPhasedLoopHandler(this, ::std::move(callback), interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700769}
770
771void ShmEventLoop::OnRun(::std::function<void()> on_run) {
772 on_run_.push_back(::std::move(on_run));
773}
774
Austin Schuh7d87b672019-12-01 20:23:49 -0800775void ShmEventLoop::HandleEvent() {
776 // Update all the times for handlers.
777 for (::std::unique_ptr<WatcherState> &base_watcher : watchers_) {
Brian Silverman148d43d2020-06-07 18:19:22 -0500778 ShmWatcherState *watcher =
779 reinterpret_cast<ShmWatcherState *>(base_watcher.get());
Austin Schuh7d87b672019-12-01 20:23:49 -0800780
781 watcher->CheckForNewData();
782 }
783
Austin Schuh39788ff2019-12-01 18:22:57 -0800784 while (true) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800785 if (EventCount() == 0 ||
786 PeekEvent()->event_time() > monotonic_clock::now()) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800787 break;
788 }
789
Austin Schuh7d87b672019-12-01 20:23:49 -0800790 EventLoopEvent *event = PopEvent();
791 event->HandleEvent();
Austin Schuh39788ff2019-12-01 18:22:57 -0800792 }
793}
794
Austin Schuh32fd5a72019-12-01 22:20:26 -0800795// RAII class to mask signals.
796class ScopedSignalMask {
797 public:
798 ScopedSignalMask(std::initializer_list<int> signals) {
799 sigset_t sigset;
800 PCHECK(sigemptyset(&sigset) == 0);
801 for (int signal : signals) {
802 PCHECK(sigaddset(&sigset, signal) == 0);
803 }
804
805 PCHECK(sigprocmask(SIG_BLOCK, &sigset, &old_) == 0);
806 }
807
808 ~ScopedSignalMask() { PCHECK(sigprocmask(SIG_SETMASK, &old_, nullptr) == 0); }
809
810 private:
811 sigset_t old_;
812};
813
814// Class to manage the static state associated with killing multiple event
815// loops.
816class SignalHandler {
817 public:
818 // Gets the singleton.
819 static SignalHandler *global() {
820 static SignalHandler loop;
821 return &loop;
822 }
823
824 // Handles the signal with the singleton.
825 static void HandleSignal(int) { global()->DoHandleSignal(); }
826
827 // Registers an event loop to receive Exit() calls.
828 void Register(ShmEventLoop *event_loop) {
829 // Block signals while we have the mutex so we never race with the signal
830 // handler.
831 ScopedSignalMask mask({SIGINT, SIGHUP, SIGTERM});
832 std::unique_lock<stl_mutex> locker(mutex_);
833 if (event_loops_.size() == 0) {
834 // The first caller registers the signal handler.
835 struct sigaction new_action;
836 sigemptyset(&new_action.sa_mask);
837 // This makes it so that 2 control c's to a stuck process will kill it by
838 // restoring the original signal handler.
839 new_action.sa_flags = SA_RESETHAND;
840 new_action.sa_handler = &HandleSignal;
841
842 PCHECK(sigaction(SIGINT, &new_action, &old_action_int_) == 0);
843 PCHECK(sigaction(SIGHUP, &new_action, &old_action_hup_) == 0);
844 PCHECK(sigaction(SIGTERM, &new_action, &old_action_term_) == 0);
845 }
846
847 event_loops_.push_back(event_loop);
848 }
849
850 // Unregisters an event loop to receive Exit() calls.
851 void Unregister(ShmEventLoop *event_loop) {
852 // Block signals while we have the mutex so we never race with the signal
853 // handler.
854 ScopedSignalMask mask({SIGINT, SIGHUP, SIGTERM});
855 std::unique_lock<stl_mutex> locker(mutex_);
856
Brian Silverman5120afb2020-01-31 17:44:35 -0800857 event_loops_.erase(
858 std::find(event_loops_.begin(), event_loops_.end(), event_loop));
Austin Schuh32fd5a72019-12-01 22:20:26 -0800859
860 if (event_loops_.size() == 0u) {
861 // The last caller restores the original signal handlers.
862 PCHECK(sigaction(SIGINT, &old_action_int_, nullptr) == 0);
863 PCHECK(sigaction(SIGHUP, &old_action_hup_, nullptr) == 0);
864 PCHECK(sigaction(SIGTERM, &old_action_term_, nullptr) == 0);
865 }
866 }
867
868 private:
869 void DoHandleSignal() {
870 // We block signals while grabbing the lock, so there should never be a
871 // race. Confirm that this is true using trylock.
872 CHECK(mutex_.try_lock()) << ": sigprocmask failed to block signals while "
873 "modifing the event loop list.";
874 for (ShmEventLoop *event_loop : event_loops_) {
875 event_loop->Exit();
876 }
877 mutex_.unlock();
878 }
879
880 // Mutex to protect all state.
881 stl_mutex mutex_;
882 std::vector<ShmEventLoop *> event_loops_;
883 struct sigaction old_action_int_;
884 struct sigaction old_action_hup_;
885 struct sigaction old_action_term_;
886};
887
Alex Perrycb7da4b2019-08-28 19:35:56 -0700888void ShmEventLoop::Run() {
Austin Schuh32fd5a72019-12-01 22:20:26 -0800889 SignalHandler::global()->Register(this);
Austin Schuh39788ff2019-12-01 18:22:57 -0800890
Alex Perrycb7da4b2019-08-28 19:35:56 -0700891 std::unique_ptr<ipc_lib::SignalFd> signalfd;
892
893 if (watchers_.size() > 0) {
894 signalfd.reset(new ipc_lib::SignalFd({ipc_lib::kWakeupSignal}));
895
896 epoll_.OnReadable(signalfd->fd(), [signalfd_ptr = signalfd.get(), this]() {
897 signalfd_siginfo result = signalfd_ptr->Read();
898 CHECK_EQ(result.ssi_signo, ipc_lib::kWakeupSignal);
899
900 // TODO(austin): We should really be checking *everything*, not just
901 // watchers, and calling the oldest thing first. That will improve
902 // determinism a lot.
903
Austin Schuh7d87b672019-12-01 20:23:49 -0800904 HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700905 });
906 }
907
Austin Schuh39788ff2019-12-01 18:22:57 -0800908 MaybeScheduleTimingReports();
909
Austin Schuh7d87b672019-12-01 20:23:49 -0800910 ReserveEvents();
911
Tyler Chatow67ddb032020-01-12 14:30:04 -0800912 {
913 AosLogToFbs aos_logger;
914 if (!skip_logger_) {
915 aos_logger.Initialize(MakeSender<logging::LogMessageFbs>("/aos"));
916 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700917
Tyler Chatow67ddb032020-01-12 14:30:04 -0800918 aos::SetCurrentThreadName(name_.substr(0, 16));
Brian Silverman6a54ff32020-04-28 16:41:39 -0700919 const cpu_set_t default_affinity = DefaultAffinity();
920 if (!CPU_EQUAL(&affinity_, &default_affinity)) {
921 ::aos::SetCurrentThreadAffinity(affinity_);
922 }
Tyler Chatow67ddb032020-01-12 14:30:04 -0800923 // Now, all the callbacks are setup. Lock everything into memory and go RT.
924 if (priority_ != 0) {
925 ::aos::InitRT();
926
927 LOG(INFO) << "Setting priority to " << priority_;
928 ::aos::SetCurrentThreadRealtimePriority(priority_);
929 }
930
931 set_is_running(true);
932
933 // Now that we are realtime (but before the OnRun handlers run), snap the
934 // queue index.
935 for (::std::unique_ptr<WatcherState> &watcher : watchers_) {
936 watcher->Startup(this);
937 }
938
939 // Now that we are RT, run all the OnRun handlers.
940 for (const auto &run : on_run_) {
941 run();
942 }
943
944 // And start our main event loop which runs all the timers and handles Quit.
945 epoll_.Run();
946
947 // Once epoll exits, there is no useful nonrt work left to do.
948 set_is_running(false);
949
950 // Nothing time or synchronization critical needs to happen after this
951 // point. Drop RT priority.
952 ::aos::UnsetCurrentThreadRealtimePriority();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700953 }
954
Austin Schuh39788ff2019-12-01 18:22:57 -0800955 for (::std::unique_ptr<WatcherState> &base_watcher : watchers_) {
Brian Silverman148d43d2020-06-07 18:19:22 -0500956 ShmWatcherState *watcher =
957 reinterpret_cast<ShmWatcherState *>(base_watcher.get());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700958 watcher->UnregisterWakeup();
959 }
960
961 if (watchers_.size() > 0) {
962 epoll_.DeleteFd(signalfd->fd());
963 signalfd.reset();
964 }
Austin Schuh32fd5a72019-12-01 22:20:26 -0800965
966 SignalHandler::global()->Unregister(this);
Austin Schuhe84c3ed2019-12-14 15:29:48 -0800967
968 // Trigger any remaining senders or fetchers to be cleared before destroying
969 // the event loop so the book keeping matches. Do this in the thread that
970 // created the timing reporter.
971 timing_report_sender_.reset();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700972}
973
974void ShmEventLoop::Exit() { epoll_.Quit(); }
975
976ShmEventLoop::~ShmEventLoop() {
Austin Schuh39788ff2019-12-01 18:22:57 -0800977 // Force everything with a registered fd with epoll to be destroyed now.
978 timers_.clear();
979 phased_loops_.clear();
980 watchers_.clear();
981
Alex Perrycb7da4b2019-08-28 19:35:56 -0700982 CHECK(!is_running()) << ": ShmEventLoop destroyed while running";
983}
984
Alex Perrycb7da4b2019-08-28 19:35:56 -0700985void ShmEventLoop::SetRuntimeRealtimePriority(int priority) {
986 if (is_running()) {
987 LOG(FATAL) << "Cannot set realtime priority while running.";
988 }
989 priority_ = priority;
990}
991
Brian Silverman6a54ff32020-04-28 16:41:39 -0700992void ShmEventLoop::SetRuntimeAffinity(const cpu_set_t &cpuset) {
993 if (is_running()) {
994 LOG(FATAL) << "Cannot set affinity while running.";
995 }
996 affinity_ = cpuset;
997}
998
James Kuszmaul57c2baa2020-01-19 14:52:52 -0800999void ShmEventLoop::set_name(const std::string_view name) {
1000 name_ = std::string(name);
1001 UpdateTimingReport();
1002}
1003
Brian Silverman5120afb2020-01-31 17:44:35 -08001004absl::Span<char> ShmEventLoop::GetWatcherSharedMemory(const Channel *channel) {
Brian Silverman148d43d2020-06-07 18:19:22 -05001005 ShmWatcherState *const watcher_state =
1006 static_cast<ShmWatcherState *>(GetWatcherState(channel));
Brian Silverman5120afb2020-01-31 17:44:35 -08001007 return watcher_state->GetSharedMemory();
1008}
1009
Brian Silverman4f4e0612020-08-12 19:54:41 -07001010int ShmEventLoop::NumberBuffers(const Channel *channel) {
1011 return MakeQueueConfiguration(
1012 channel, chrono::ceil<chrono::seconds>(chrono::nanoseconds(
1013 configuration()->channel_storage_duration())))
1014 .num_messages();
1015}
1016
Brian Silverman5120afb2020-01-31 17:44:35 -08001017absl::Span<char> ShmEventLoop::GetShmSenderSharedMemory(
1018 const aos::RawSender *sender) const {
Brian Silverman148d43d2020-06-07 18:19:22 -05001019 return static_cast<const ShmSender *>(sender)->GetSharedMemory();
Brian Silverman5120afb2020-01-31 17:44:35 -08001020}
1021
Brian Silverman6d2b3592020-06-18 14:40:15 -07001022absl::Span<char> ShmEventLoop::GetShmFetcherPrivateMemory(
1023 const aos::RawFetcher *fetcher) const {
1024 return static_cast<const ShmFetcher *>(fetcher)->GetPrivateMemory();
1025}
1026
Austin Schuh39788ff2019-12-01 18:22:57 -08001027pid_t ShmEventLoop::GetTid() { return syscall(SYS_gettid); }
1028
Alex Perrycb7da4b2019-08-28 19:35:56 -07001029} // namespace aos