blob: b33fe98500a64f53b03022395d33093ee6041dec [file] [log] [blame]
Alex Perrycb7da4b2019-08-28 19:35:56 -07001#include "aos/events/shm_event_loop.h"
2
3#include <sys/mman.h>
4#include <sys/stat.h>
Austin Schuh39788ff2019-12-01 18:22:57 -08005#include <sys/syscall.h>
Alex Perrycb7da4b2019-08-28 19:35:56 -07006#include <sys/types.h>
7#include <unistd.h>
Tyler Chatow67ddb032020-01-12 14:30:04 -08008
Alex Perrycb7da4b2019-08-28 19:35:56 -07009#include <algorithm>
10#include <atomic>
11#include <chrono>
Austin Schuh39788ff2019-12-01 18:22:57 -080012#include <iterator>
Alex Perrycb7da4b2019-08-28 19:35:56 -070013#include <stdexcept>
14
Tyler Chatow67ddb032020-01-12 14:30:04 -080015#include "aos/events/aos_logging.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070016#include "aos/events/epoll.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080017#include "aos/events/event_loop_generated.h"
18#include "aos/events/timing_statistics.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070019#include "aos/ipc_lib/lockless_queue.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080020#include "aos/ipc_lib/signalfd.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070021#include "aos/realtime.h"
Austin Schuh32fd5a72019-12-01 22:20:26 -080022#include "aos/stl_mutex/stl_mutex.h"
Austin Schuhfccb2d02020-01-26 16:11:19 -080023#include "aos/util/file.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070024#include "aos/util/phased_loop.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080025#include "glog/logging.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070026
Austin Schuhe84c3ed2019-12-14 15:29:48 -080027namespace {
28
29// Returns the portion of the path after the last /. This very much assumes
30// that the application name is null terminated.
31const char *Filename(const char *path) {
32 const std::string_view path_string_view = path;
33 auto last_slash_pos = path_string_view.find_last_of("/");
34
35 return last_slash_pos == std::string_view::npos ? path
36 : path + last_slash_pos + 1;
37}
38
39} // namespace
40
Alex Perrycb7da4b2019-08-28 19:35:56 -070041DEFINE_string(shm_base, "/dev/shm/aos",
42 "Directory to place queue backing mmaped files in.");
43DEFINE_uint32(permissions, 0770,
44 "Permissions to make shared memory files and folders.");
Austin Schuhe84c3ed2019-12-14 15:29:48 -080045DEFINE_string(application_name, Filename(program_invocation_name),
46 "The application name");
Alex Perrycb7da4b2019-08-28 19:35:56 -070047
48namespace aos {
49
Brian Silverman148d43d2020-06-07 18:19:22 -050050using namespace shm_event_loop_internal;
51
Austin Schuhcdab6192019-12-29 17:47:46 -080052void SetShmBase(const std::string_view base) {
53 FLAGS_shm_base = std::string(base) + "/dev/shm/aos";
54}
55
Alex Perrycb7da4b2019-08-28 19:35:56 -070056std::string ShmFolder(const Channel *channel) {
57 CHECK(channel->has_name());
58 CHECK_EQ(channel->name()->string_view()[0], '/');
59 return FLAGS_shm_base + channel->name()->str() + "/";
60}
61std::string ShmPath(const Channel *channel) {
62 CHECK(channel->has_type());
Brian Silverman177567e2020-08-12 19:51:33 -070063 return ShmFolder(channel) + channel->type()->str() + ".v3";
Alex Perrycb7da4b2019-08-28 19:35:56 -070064}
65
Brian Silverman3b0cdaf2020-04-28 16:51:51 -070066void PageFaultData(char *data, size_t size) {
67 // This just has to divide the actual page size. Being smaller will make this
68 // a bit slower than necessary, but not much. 1024 is a pretty conservative
69 // choice (most pages are probably 4096).
70 static constexpr size_t kPageSize = 1024;
71 const size_t pages = (size + kPageSize - 1) / kPageSize;
72 for (size_t i = 0; i < pages; ++i) {
73 char zero = 0;
74 // We need to ensure there's a writable pagetable entry, but avoid modifying
75 // the data.
76 //
77 // Even if you lock the data into memory, some kernels still seem to lazily
78 // create the actual pagetable entries. This means we need to somehow
79 // "write" to the page.
80 //
81 // Also, this takes place while other processes may be concurrently
82 // opening/initializing the memory, so we need to avoid corrupting that.
83 //
84 // This is the simplest operation I could think of which achieves that:
85 // "store 0 if it's already 0".
86 __atomic_compare_exchange_n(&data[i * kPageSize], &zero, 0, true,
87 __ATOMIC_RELAXED, __ATOMIC_RELAXED);
88 }
89}
90
Alex Perrycb7da4b2019-08-28 19:35:56 -070091class MMapedQueue {
92 public:
Austin Schuhaa79e4e2019-12-29 20:43:32 -080093 MMapedQueue(const Channel *channel,
94 const std::chrono::seconds channel_storage_duration) {
Alex Perrycb7da4b2019-08-28 19:35:56 -070095 std::string path = ShmPath(channel);
96
Austin Schuh80c7fce2019-12-05 20:48:43 -080097 config_.num_watchers = channel->num_watchers();
98 config_.num_senders = channel->num_senders();
Brian Silverman77162972020-08-12 19:52:40 -070099 // The value in the channel will default to 0 if readers are configured to
100 // copy.
101 config_.num_pinners = channel->num_readers();
Austin Schuhaa79e4e2019-12-29 20:43:32 -0800102 config_.queue_size =
103 channel_storage_duration.count() * channel->frequency();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700104 config_.message_data_size = channel->max_size();
105
106 size_ = ipc_lib::LocklessQueueMemorySize(config_);
107
Austin Schuhfccb2d02020-01-26 16:11:19 -0800108 util::MkdirP(path, FLAGS_permissions);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700109
110 // There are 2 cases. Either the file already exists, or it does not
111 // already exist and we need to create it. Start by trying to create it. If
112 // that fails, the file has already been created and we can open it
113 // normally.. Once the file has been created it wil never be deleted.
Brian Silvermanf9f30ea2020-03-04 23:18:54 -0800114 int fd = open(path.c_str(), O_RDWR | O_CREAT | O_EXCL,
Brian Silverman148d43d2020-06-07 18:19:22 -0500115 O_CLOEXEC | FLAGS_permissions);
Brian Silvermanf9f30ea2020-03-04 23:18:54 -0800116 if (fd == -1 && errno == EEXIST) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700117 VLOG(1) << path << " already created.";
118 // File already exists.
Brian Silvermanf9f30ea2020-03-04 23:18:54 -0800119 fd = open(path.c_str(), O_RDWR, O_CLOEXEC);
120 PCHECK(fd != -1) << ": Failed to open " << path;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700121 while (true) {
122 struct stat st;
Brian Silvermanf9f30ea2020-03-04 23:18:54 -0800123 PCHECK(fstat(fd, &st) == 0);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700124 if (st.st_size != 0) {
125 CHECK_EQ(static_cast<size_t>(st.st_size), size_)
126 << ": Size of " << path
127 << " doesn't match expected size of backing queue file. Did the "
128 "queue definition change?";
129 break;
130 } else {
131 // The creating process didn't get around to it yet. Give it a bit.
132 std::this_thread::sleep_for(std::chrono::milliseconds(10));
133 VLOG(1) << path << " is zero size, waiting";
134 }
135 }
136 } else {
137 VLOG(1) << "Created " << path;
Brian Silvermanf9f30ea2020-03-04 23:18:54 -0800138 PCHECK(fd != -1) << ": Failed to open " << path;
139 PCHECK(ftruncate(fd, size_) == 0);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700140 }
141
Brian Silvermanf9f30ea2020-03-04 23:18:54 -0800142 data_ = mmap(NULL, size_, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700143 PCHECK(data_ != MAP_FAILED);
Brian Silvermanf9f30ea2020-03-04 23:18:54 -0800144 PCHECK(close(fd) == 0);
Brian Silverman3b0cdaf2020-04-28 16:51:51 -0700145 PageFaultData(static_cast<char *>(data_), size_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700146
147 ipc_lib::InitializeLocklessQueueMemory(memory(), config_);
148 }
149
Brian Silverman148d43d2020-06-07 18:19:22 -0500150 ~MMapedQueue() { PCHECK(munmap(data_, size_) == 0); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700151
152 ipc_lib::LocklessQueueMemory *memory() const {
153 return reinterpret_cast<ipc_lib::LocklessQueueMemory *>(data_);
154 }
155
Austin Schuh39788ff2019-12-01 18:22:57 -0800156 const ipc_lib::LocklessQueueConfiguration &config() const { return config_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700157
Brian Silverman5120afb2020-01-31 17:44:35 -0800158 absl::Span<char> GetSharedMemory() const {
159 return absl::Span<char>(static_cast<char *>(data_), size_);
160 }
161
Alex Perrycb7da4b2019-08-28 19:35:56 -0700162 private:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700163 ipc_lib::LocklessQueueConfiguration config_;
164
Alex Perrycb7da4b2019-08-28 19:35:56 -0700165 size_t size_;
166 void *data_;
167};
168
Austin Schuh217a9782019-12-21 23:02:50 -0800169namespace {
170
Austin Schuh217a9782019-12-21 23:02:50 -0800171const Node *MaybeMyNode(const Configuration *configuration) {
172 if (!configuration->has_nodes()) {
173 return nullptr;
174 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700175
Austin Schuh217a9782019-12-21 23:02:50 -0800176 return configuration::GetMyNode(configuration);
177}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700178
179namespace chrono = ::std::chrono;
180
Austin Schuh39788ff2019-12-01 18:22:57 -0800181} // namespace
182
Austin Schuh217a9782019-12-21 23:02:50 -0800183ShmEventLoop::ShmEventLoop(const Configuration *configuration)
184 : EventLoop(configuration),
Austin Schuhe84c3ed2019-12-14 15:29:48 -0800185 name_(FLAGS_application_name),
Austin Schuh15649d62019-12-28 16:36:38 -0800186 node_(MaybeMyNode(configuration)) {
187 if (configuration->has_nodes()) {
188 CHECK(node_ != nullptr) << ": Couldn't find node in config.";
189 }
190}
Austin Schuh217a9782019-12-21 23:02:50 -0800191
Brian Silverman148d43d2020-06-07 18:19:22 -0500192namespace shm_event_loop_internal {
Austin Schuh39788ff2019-12-01 18:22:57 -0800193
194class SimpleShmFetcher {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700195 public:
Brian Silverman3bca5322020-08-12 19:35:29 -0700196 explicit SimpleShmFetcher(ShmEventLoop *event_loop, const Channel *channel)
Austin Schuh432784f2020-06-23 17:27:35 -0700197 : event_loop_(event_loop),
198 channel_(channel),
Austin Schuhaa79e4e2019-12-29 20:43:32 -0800199 lockless_queue_memory_(
200 channel,
Brian Silverman587da252020-01-01 17:00:47 -0800201 chrono::ceil<chrono::seconds>(chrono::nanoseconds(
Austin Schuhaa79e4e2019-12-29 20:43:32 -0800202 event_loop->configuration()->channel_storage_duration()))),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700203 lockless_queue_(lockless_queue_memory_.memory(),
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800204 lockless_queue_memory_.config()) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700205 context_.data = nullptr;
206 // Point the queue index at the next index to read starting now. This
207 // makes it such that FetchNext will read the next message sent after
208 // the fetcher is created.
209 PointAtNextQueueIndex();
210 }
211
Austin Schuh39788ff2019-12-01 18:22:57 -0800212 ~SimpleShmFetcher() {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700213
Brian Silverman77162972020-08-12 19:52:40 -0700214 // Sets this object to pin or copy data, as configured in the channel.
215 void RetrieveData() {
216 if (channel_->read_method() == ReadMethod::PIN) {
217 PinDataOnFetch();
218 } else {
219 CopyDataOnFetch();
220 }
221 }
222
Brian Silverman3bca5322020-08-12 19:35:29 -0700223 // Sets this object to copy data out of the shared memory into a private
224 // buffer when fetching.
225 void CopyDataOnFetch() {
Brian Silverman77162972020-08-12 19:52:40 -0700226 CHECK(!pin_data());
Brian Silverman3bca5322020-08-12 19:35:29 -0700227 data_storage_.reset(static_cast<char *>(
228 malloc(channel_->max_size() + kChannelDataAlignment - 1)));
229 }
230
Brian Silverman77162972020-08-12 19:52:40 -0700231 // Sets this object to pin data in shared memory when fetching.
232 void PinDataOnFetch() {
233 CHECK(!copy_data());
234 auto maybe_pinner = lockless_queue_.MakePinner();
235 if (!maybe_pinner) {
236 LOG(FATAL) << "Failed to create reader on "
237 << configuration::CleanedChannelToString(channel_)
238 << ", too many readers.";
239 }
240 pinner_ = std::move(maybe_pinner.value());
241 }
242
Alex Perrycb7da4b2019-08-28 19:35:56 -0700243 // Points the next message to fetch at the queue index which will be
244 // populated next.
245 void PointAtNextQueueIndex() {
246 actual_queue_index_ = lockless_queue_.LatestQueueIndex();
247 if (!actual_queue_index_.valid()) {
248 // Nothing in the queue. The next element will show up at the 0th
249 // index in the queue.
250 actual_queue_index_ =
251 ipc_lib::QueueIndex::Zero(lockless_queue_.queue_size());
252 } else {
253 actual_queue_index_ = actual_queue_index_.Increment();
254 }
255 }
256
Austin Schuh39788ff2019-12-01 18:22:57 -0800257 bool FetchNext() {
Brian Silverman3bca5322020-08-12 19:35:29 -0700258 const ipc_lib::LocklessQueue::ReadResult read_result =
259 DoFetch(actual_queue_index_);
Austin Schuh432784f2020-06-23 17:27:35 -0700260
Alex Perrycb7da4b2019-08-28 19:35:56 -0700261 return read_result == ipc_lib::LocklessQueue::ReadResult::GOOD;
262 }
263
Austin Schuh39788ff2019-12-01 18:22:57 -0800264 bool Fetch() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700265 const ipc_lib::QueueIndex queue_index = lockless_queue_.LatestQueueIndex();
266 // actual_queue_index_ is only meaningful if it was set by Fetch or
267 // FetchNext. This happens when valid_data_ has been set. So, only
268 // skip checking if valid_data_ is true.
269 //
270 // Also, if the latest queue index is invalid, we are empty. So there
271 // is nothing to fetch.
Austin Schuh39788ff2019-12-01 18:22:57 -0800272 if ((context_.data != nullptr &&
Alex Perrycb7da4b2019-08-28 19:35:56 -0700273 queue_index == actual_queue_index_.DecrementBy(1u)) ||
274 !queue_index.valid()) {
275 return false;
276 }
277
Brian Silverman3bca5322020-08-12 19:35:29 -0700278 const ipc_lib::LocklessQueue::ReadResult read_result = DoFetch(queue_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700279
280 CHECK(read_result != ipc_lib::LocklessQueue::ReadResult::NOTHING_NEW)
Austin Schuhf5652592019-12-29 16:26:15 -0800281 << ": Queue index went backwards. This should never happen. "
282 << configuration::CleanedChannelToString(channel_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700283
Alex Perrycb7da4b2019-08-28 19:35:56 -0700284 return read_result == ipc_lib::LocklessQueue::ReadResult::GOOD;
285 }
286
Austin Schuh39788ff2019-12-01 18:22:57 -0800287 Context context() const { return context_; }
288
Alex Perrycb7da4b2019-08-28 19:35:56 -0700289 bool RegisterWakeup(int priority) {
290 return lockless_queue_.RegisterWakeup(priority);
291 }
292
293 void UnregisterWakeup() { lockless_queue_.UnregisterWakeup(); }
294
Brian Silverman5120afb2020-01-31 17:44:35 -0800295 absl::Span<char> GetSharedMemory() const {
296 return lockless_queue_memory_.GetSharedMemory();
297 }
298
Brian Silverman6d2b3592020-06-18 14:40:15 -0700299 absl::Span<char> GetPrivateMemory() const {
Brian Silverman3bca5322020-08-12 19:35:29 -0700300 // Can't usefully expose this for pinning, because the buffer changes
301 // address for each message. Callers who want to work with that should just
302 // grab the whole shared memory buffer instead.
Brian Silverman6d2b3592020-06-18 14:40:15 -0700303 return absl::Span<char>(
304 const_cast<SimpleShmFetcher *>(this)->data_storage_start(),
305 lockless_queue_.message_data_size());
306 }
307
Alex Perrycb7da4b2019-08-28 19:35:56 -0700308 private:
Brian Silverman3bca5322020-08-12 19:35:29 -0700309 ipc_lib::LocklessQueue::ReadResult DoFetch(ipc_lib::QueueIndex queue_index) {
310 // TODO(austin): Get behind and make sure it dies.
311 char *copy_buffer = nullptr;
312 if (copy_data()) {
313 copy_buffer = data_storage_start();
314 }
315 ipc_lib::LocklessQueue::ReadResult read_result = lockless_queue_.Read(
316 queue_index.index(), &context_.monotonic_event_time,
317 &context_.realtime_event_time, &context_.monotonic_remote_time,
318 &context_.realtime_remote_time, &context_.remote_queue_index,
319 &context_.size, copy_buffer);
320
321 if (read_result == ipc_lib::LocklessQueue::ReadResult::GOOD) {
Brian Silverman77162972020-08-12 19:52:40 -0700322 if (pin_data()) {
323 CHECK(pinner_->PinIndex(queue_index.index()))
324 << ": Got behind while reading and the last message was modified "
325 "out from under us while we tried to pin it. Don't get so far "
326 "behind on: "
327 << configuration::CleanedChannelToString(channel_);
328 }
329
Brian Silverman3bca5322020-08-12 19:35:29 -0700330 context_.queue_index = queue_index.index();
331 if (context_.remote_queue_index == 0xffffffffu) {
332 context_.remote_queue_index = context_.queue_index;
333 }
334 if (context_.monotonic_remote_time == aos::monotonic_clock::min_time) {
335 context_.monotonic_remote_time = context_.monotonic_event_time;
336 }
337 if (context_.realtime_remote_time == aos::realtime_clock::min_time) {
338 context_.realtime_remote_time = context_.realtime_event_time;
339 }
340 const char *const data = DataBuffer();
341 if (data) {
342 context_.data =
343 data + lockless_queue_.message_data_size() - context_.size;
344 } else {
345 context_.data = nullptr;
346 }
347 actual_queue_index_ = queue_index.Increment();
348 }
349
350 // Make sure the data wasn't modified while we were reading it. This
351 // can only happen if you are reading the last message *while* it is
352 // being written to, which means you are pretty far behind.
353 CHECK(read_result != ipc_lib::LocklessQueue::ReadResult::OVERWROTE)
354 << ": Got behind while reading and the last message was modified "
355 "out from under us while we were reading it. Don't get so far "
356 "behind on: "
357 << configuration::CleanedChannelToString(channel_);
358
359 // We fell behind between when we read the index and read the value.
360 // This isn't worth recovering from since this means we went to sleep
361 // for a long time in the middle of this function.
362 if (read_result == ipc_lib::LocklessQueue::ReadResult::TOO_OLD) {
363 event_loop_->SendTimingReport();
364 LOG(FATAL) << "The next message is no longer available. "
365 << configuration::CleanedChannelToString(channel_);
366 }
367
368 return read_result;
369 }
370
371 char *data_storage_start() const {
372 CHECK(copy_data());
Brian Silvermana1652f32020-01-29 20:41:44 -0800373 return RoundChannelData(data_storage_.get(), channel_->max_size());
374 }
Brian Silverman3bca5322020-08-12 19:35:29 -0700375
376 // Note that for some modes the return value will change as new messages are
377 // read.
378 const char *DataBuffer() const {
379 if (copy_data()) {
380 return data_storage_start();
381 }
Brian Silverman77162972020-08-12 19:52:40 -0700382 if (pin_data()) {
383 return static_cast<const char *>(pinner_->Data());
384 }
Brian Silverman3bca5322020-08-12 19:35:29 -0700385 return nullptr;
386 }
387
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800388 bool copy_data() const { return static_cast<bool>(data_storage_); }
Brian Silverman77162972020-08-12 19:52:40 -0700389 bool pin_data() const { return static_cast<bool>(pinner_); }
Brian Silvermana1652f32020-01-29 20:41:44 -0800390
Austin Schuh432784f2020-06-23 17:27:35 -0700391 aos::ShmEventLoop *event_loop_;
Austin Schuhf5652592019-12-29 16:26:15 -0800392 const Channel *const channel_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700393 MMapedQueue lockless_queue_memory_;
394 ipc_lib::LocklessQueue lockless_queue_;
395
396 ipc_lib::QueueIndex actual_queue_index_ =
397 ipc_lib::LocklessQueue::empty_queue_index();
398
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800399 // This being empty indicates we're not going to copy data.
400 std::unique_ptr<char, decltype(&free)> data_storage_{nullptr, &free};
Austin Schuh39788ff2019-12-01 18:22:57 -0800401
Brian Silverman77162972020-08-12 19:52:40 -0700402 // This being nullopt indicates we're not going to pin messages.
403 std::optional<ipc_lib::LocklessQueue::Pinner> pinner_;
404
Austin Schuh39788ff2019-12-01 18:22:57 -0800405 Context context_;
406};
407
408class ShmFetcher : public RawFetcher {
409 public:
Austin Schuh432784f2020-06-23 17:27:35 -0700410 explicit ShmFetcher(ShmEventLoop *event_loop, const Channel *channel)
Austin Schuhaa79e4e2019-12-29 20:43:32 -0800411 : RawFetcher(event_loop, channel),
Brian Silverman3bca5322020-08-12 19:35:29 -0700412 simple_shm_fetcher_(event_loop, channel) {
Brian Silverman77162972020-08-12 19:52:40 -0700413 simple_shm_fetcher_.RetrieveData();
Brian Silverman3bca5322020-08-12 19:35:29 -0700414 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800415
416 ~ShmFetcher() { context_.data = nullptr; }
417
418 std::pair<bool, monotonic_clock::time_point> DoFetchNext() override {
419 if (simple_shm_fetcher_.FetchNext()) {
420 context_ = simple_shm_fetcher_.context();
421 return std::make_pair(true, monotonic_clock::now());
422 }
423 return std::make_pair(false, monotonic_clock::min_time);
424 }
425
426 std::pair<bool, monotonic_clock::time_point> DoFetch() override {
427 if (simple_shm_fetcher_.Fetch()) {
428 context_ = simple_shm_fetcher_.context();
429 return std::make_pair(true, monotonic_clock::now());
430 }
431 return std::make_pair(false, monotonic_clock::min_time);
432 }
433
Brian Silverman6d2b3592020-06-18 14:40:15 -0700434 absl::Span<char> GetPrivateMemory() const {
435 return simple_shm_fetcher_.GetPrivateMemory();
436 }
437
Austin Schuh39788ff2019-12-01 18:22:57 -0800438 private:
439 SimpleShmFetcher simple_shm_fetcher_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700440};
441
442class ShmSender : public RawSender {
443 public:
Austin Schuh39788ff2019-12-01 18:22:57 -0800444 explicit ShmSender(EventLoop *event_loop, const Channel *channel)
445 : RawSender(event_loop, channel),
Austin Schuhaa79e4e2019-12-29 20:43:32 -0800446 lockless_queue_memory_(
447 channel,
Brian Silverman587da252020-01-01 17:00:47 -0800448 chrono::ceil<chrono::seconds>(chrono::nanoseconds(
Austin Schuhaa79e4e2019-12-29 20:43:32 -0800449 event_loop->configuration()->channel_storage_duration()))),
Alex Perrycb7da4b2019-08-28 19:35:56 -0700450 lockless_queue_(lockless_queue_memory_.memory(),
451 lockless_queue_memory_.config()),
Austin Schuhe516ab02020-05-06 21:37:04 -0700452 lockless_queue_sender_(
453 VerifySender(lockless_queue_.MakeSender(), channel)) {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700454
Austin Schuh39788ff2019-12-01 18:22:57 -0800455 ~ShmSender() override {}
456
Austin Schuhe516ab02020-05-06 21:37:04 -0700457 static ipc_lib::LocklessQueue::Sender VerifySender(
458 std::optional<ipc_lib::LocklessQueue::Sender> &&sender,
459 const Channel *channel) {
460 if (sender) {
461 return std::move(sender.value());
462 }
463 LOG(FATAL) << "Failed to create sender on "
464 << configuration::CleanedChannelToString(channel)
465 << ", too many senders.";
466 }
467
Alex Perrycb7da4b2019-08-28 19:35:56 -0700468 void *data() override { return lockless_queue_sender_.Data(); }
469 size_t size() override { return lockless_queue_sender_.size(); }
Austin Schuhad154822019-12-27 15:45:13 -0800470 bool DoSend(size_t length,
471 aos::monotonic_clock::time_point monotonic_remote_time,
472 aos::realtime_clock::time_point realtime_remote_time,
473 uint32_t remote_queue_index) override {
Austin Schuh0f7ed462020-03-28 20:38:34 -0700474 CHECK_LE(length, static_cast<size_t>(channel()->max_size()))
475 << ": Sent too big a message on "
476 << configuration::CleanedChannelToString(channel());
Austin Schuhad154822019-12-27 15:45:13 -0800477 lockless_queue_sender_.Send(
478 length, monotonic_remote_time, realtime_remote_time, remote_queue_index,
479 &monotonic_sent_time_, &realtime_sent_time_, &sent_queue_index_);
Austin Schuh39788ff2019-12-01 18:22:57 -0800480 lockless_queue_.Wakeup(event_loop()->priority());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700481 return true;
482 }
483
Austin Schuhad154822019-12-27 15:45:13 -0800484 bool DoSend(const void *msg, size_t length,
485 aos::monotonic_clock::time_point monotonic_remote_time,
486 aos::realtime_clock::time_point realtime_remote_time,
487 uint32_t remote_queue_index) override {
Austin Schuh0f7ed462020-03-28 20:38:34 -0700488 CHECK_LE(length, static_cast<size_t>(channel()->max_size()))
489 << ": Sent too big a message on "
490 << configuration::CleanedChannelToString(channel());
Austin Schuhad154822019-12-27 15:45:13 -0800491 lockless_queue_sender_.Send(reinterpret_cast<const char *>(msg), length,
492 monotonic_remote_time, realtime_remote_time,
493 remote_queue_index, &monotonic_sent_time_,
494 &realtime_sent_time_, &sent_queue_index_);
Austin Schuh39788ff2019-12-01 18:22:57 -0800495 lockless_queue_.Wakeup(event_loop()->priority());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700496 // TODO(austin): Return an error if we send too fast.
497 return true;
498 }
499
Brian Silverman5120afb2020-01-31 17:44:35 -0800500 absl::Span<char> GetSharedMemory() const {
501 return lockless_queue_memory_.GetSharedMemory();
502 }
503
Alex Perrycb7da4b2019-08-28 19:35:56 -0700504 private:
Alex Perrycb7da4b2019-08-28 19:35:56 -0700505 MMapedQueue lockless_queue_memory_;
506 ipc_lib::LocklessQueue lockless_queue_;
507 ipc_lib::LocklessQueue::Sender lockless_queue_sender_;
508};
509
Alex Perrycb7da4b2019-08-28 19:35:56 -0700510// Class to manage the state for a Watcher.
Brian Silverman148d43d2020-06-07 18:19:22 -0500511class ShmWatcherState : public WatcherState {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700512 public:
Brian Silverman148d43d2020-06-07 18:19:22 -0500513 ShmWatcherState(
Austin Schuh7d87b672019-12-01 20:23:49 -0800514 ShmEventLoop *event_loop, const Channel *channel,
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800515 std::function<void(const Context &context, const void *message)> fn,
516 bool copy_data)
Brian Silverman148d43d2020-06-07 18:19:22 -0500517 : WatcherState(event_loop, channel, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800518 event_loop_(event_loop),
519 event_(this),
Brian Silverman3bca5322020-08-12 19:35:29 -0700520 simple_shm_fetcher_(event_loop, channel) {
521 if (copy_data) {
Brian Silverman77162972020-08-12 19:52:40 -0700522 simple_shm_fetcher_.RetrieveData();
Brian Silverman3bca5322020-08-12 19:35:29 -0700523 }
524 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700525
Brian Silverman148d43d2020-06-07 18:19:22 -0500526 ~ShmWatcherState() override { event_loop_->RemoveEvent(&event_); }
Austin Schuh39788ff2019-12-01 18:22:57 -0800527
528 void Startup(EventLoop *event_loop) override {
Austin Schuh7d87b672019-12-01 20:23:49 -0800529 simple_shm_fetcher_.PointAtNextQueueIndex();
Austin Schuh39788ff2019-12-01 18:22:57 -0800530 CHECK(RegisterWakeup(event_loop->priority()));
531 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700532
Alex Perrycb7da4b2019-08-28 19:35:56 -0700533 // Returns true if there is new data available.
Austin Schuh7d87b672019-12-01 20:23:49 -0800534 bool CheckForNewData() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700535 if (!has_new_data_) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800536 has_new_data_ = simple_shm_fetcher_.FetchNext();
Austin Schuh7d87b672019-12-01 20:23:49 -0800537
538 if (has_new_data_) {
539 event_.set_event_time(
Austin Schuhad154822019-12-27 15:45:13 -0800540 simple_shm_fetcher_.context().monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800541 event_loop_->AddEvent(&event_);
542 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700543 }
544
545 return has_new_data_;
546 }
547
Alex Perrycb7da4b2019-08-28 19:35:56 -0700548 // Consumes the data by calling the callback.
Austin Schuh7d87b672019-12-01 20:23:49 -0800549 void HandleEvent() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700550 CHECK(has_new_data_);
Austin Schuh39788ff2019-12-01 18:22:57 -0800551 DoCallCallback(monotonic_clock::now, simple_shm_fetcher_.context());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700552 has_new_data_ = false;
Austin Schuh7d87b672019-12-01 20:23:49 -0800553 CheckForNewData();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700554 }
555
Austin Schuh39788ff2019-12-01 18:22:57 -0800556 // Registers us to receive a signal on event reception.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700557 bool RegisterWakeup(int priority) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800558 return simple_shm_fetcher_.RegisterWakeup(priority);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700559 }
560
Austin Schuh39788ff2019-12-01 18:22:57 -0800561 void UnregisterWakeup() { return simple_shm_fetcher_.UnregisterWakeup(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700562
Brian Silverman5120afb2020-01-31 17:44:35 -0800563 absl::Span<char> GetSharedMemory() const {
564 return simple_shm_fetcher_.GetSharedMemory();
565 }
566
Alex Perrycb7da4b2019-08-28 19:35:56 -0700567 private:
568 bool has_new_data_ = false;
569
Austin Schuh7d87b672019-12-01 20:23:49 -0800570 ShmEventLoop *event_loop_;
Brian Silverman148d43d2020-06-07 18:19:22 -0500571 EventHandler<ShmWatcherState> event_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800572 SimpleShmFetcher simple_shm_fetcher_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700573};
574
575// Adapter class to adapt a timerfd to a TimerHandler.
Brian Silverman148d43d2020-06-07 18:19:22 -0500576class ShmTimerHandler final : public TimerHandler {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700577 public:
Brian Silverman148d43d2020-06-07 18:19:22 -0500578 ShmTimerHandler(ShmEventLoop *shm_event_loop, ::std::function<void()> fn)
Austin Schuh39788ff2019-12-01 18:22:57 -0800579 : TimerHandler(shm_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800580 shm_event_loop_(shm_event_loop),
581 event_(this) {
Austin Schuhcde39fd2020-02-22 20:58:24 -0800582 shm_event_loop_->epoll_.OnReadable(timerfd_.fd(), [this]() {
583 // The timer may fire spurriously. HandleEvent on the event loop will
584 // call the callback if it is needed. It may also have called it when
585 // processing some other event, and the kernel decided to deliver this
586 // wakeup anyways.
587 timerfd_.Read();
588 shm_event_loop_->HandleEvent();
589 });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700590 }
591
Brian Silverman148d43d2020-06-07 18:19:22 -0500592 ~ShmTimerHandler() {
Austin Schuh7d87b672019-12-01 20:23:49 -0800593 Disable();
594 shm_event_loop_->epoll_.DeleteFd(timerfd_.fd());
595 }
596
597 void HandleEvent() {
Austin Schuhcde39fd2020-02-22 20:58:24 -0800598 CHECK(!event_.valid());
599 const auto monotonic_now = Call(monotonic_clock::now, base_);
600 if (event_.valid()) {
601 // If someone called Setup inside Call, rescheduling is already taken care
602 // of. Bail.
603 return;
Austin Schuh7d87b672019-12-01 20:23:49 -0800604 }
605
Austin Schuhcde39fd2020-02-22 20:58:24 -0800606 if (repeat_offset_ == chrono::seconds(0)) {
607 timerfd_.Disable();
608 } else {
609 // Compute how many cycles have elapsed and schedule the next iteration
610 // for the next iteration in the future.
611 const int elapsed_cycles =
612 std::max<int>(0, (monotonic_now - base_ + repeat_offset_ -
613 std::chrono::nanoseconds(1)) /
614 repeat_offset_);
615 base_ += repeat_offset_ * elapsed_cycles;
Austin Schuh7d87b672019-12-01 20:23:49 -0800616
Austin Schuhcde39fd2020-02-22 20:58:24 -0800617 // Update the heap and schedule the timerfd wakeup.
Austin Schuh7d87b672019-12-01 20:23:49 -0800618 event_.set_event_time(base_);
619 shm_event_loop_->AddEvent(&event_);
Austin Schuhcde39fd2020-02-22 20:58:24 -0800620 timerfd_.SetTime(base_, chrono::seconds(0));
Austin Schuh7d87b672019-12-01 20:23:49 -0800621 }
622 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700623
624 void Setup(monotonic_clock::time_point base,
625 monotonic_clock::duration repeat_offset) override {
Austin Schuh7d87b672019-12-01 20:23:49 -0800626 if (event_.valid()) {
627 shm_event_loop_->RemoveEvent(&event_);
628 }
629
Alex Perrycb7da4b2019-08-28 19:35:56 -0700630 timerfd_.SetTime(base, repeat_offset);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800631 base_ = base;
632 repeat_offset_ = repeat_offset;
Austin Schuh7d87b672019-12-01 20:23:49 -0800633 event_.set_event_time(base_);
634 shm_event_loop_->AddEvent(&event_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700635 }
636
Austin Schuh7d87b672019-12-01 20:23:49 -0800637 void Disable() override {
638 shm_event_loop_->RemoveEvent(&event_);
639 timerfd_.Disable();
640 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700641
642 private:
643 ShmEventLoop *shm_event_loop_;
Brian Silverman148d43d2020-06-07 18:19:22 -0500644 EventHandler<ShmTimerHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700645
Brian Silverman148d43d2020-06-07 18:19:22 -0500646 internal::TimerFd timerfd_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700647
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800648 monotonic_clock::time_point base_;
649 monotonic_clock::duration repeat_offset_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700650};
651
652// Adapter class to the timerfd and PhasedLoop.
Brian Silverman148d43d2020-06-07 18:19:22 -0500653class ShmPhasedLoopHandler final : public PhasedLoopHandler {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700654 public:
Brian Silverman148d43d2020-06-07 18:19:22 -0500655 ShmPhasedLoopHandler(ShmEventLoop *shm_event_loop,
656 ::std::function<void(int)> fn,
657 const monotonic_clock::duration interval,
658 const monotonic_clock::duration offset)
659 : PhasedLoopHandler(shm_event_loop, std::move(fn), interval, offset),
Austin Schuh7d87b672019-12-01 20:23:49 -0800660 shm_event_loop_(shm_event_loop),
661 event_(this) {
662 shm_event_loop_->epoll_.OnReadable(
663 timerfd_.fd(), [this]() { shm_event_loop_->HandleEvent(); });
664 }
665
666 void HandleEvent() {
667 // The return value for read is the number of cycles that have elapsed.
668 // Because we check to see when this event *should* have happened, there are
669 // cases where Read() will return 0, when 1 cycle has actually happened.
670 // This occurs when the timer interrupt hasn't triggered yet. Therefore,
671 // ignore it. Call handles rescheduling and calculating elapsed cycles
672 // without any extra help.
673 timerfd_.Read();
674 event_.Invalidate();
675
676 Call(monotonic_clock::now, [this](monotonic_clock::time_point sleep_time) {
677 Schedule(sleep_time);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700678 });
679 }
680
Brian Silverman148d43d2020-06-07 18:19:22 -0500681 ~ShmPhasedLoopHandler() override {
Austin Schuh39788ff2019-12-01 18:22:57 -0800682 shm_event_loop_->epoll_.DeleteFd(timerfd_.fd());
Austin Schuh7d87b672019-12-01 20:23:49 -0800683 shm_event_loop_->RemoveEvent(&event_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700684 }
685
686 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800687 // Reschedules the timer.
Austin Schuh39788ff2019-12-01 18:22:57 -0800688 void Schedule(monotonic_clock::time_point sleep_time) override {
Austin Schuh7d87b672019-12-01 20:23:49 -0800689 if (event_.valid()) {
690 shm_event_loop_->RemoveEvent(&event_);
691 }
692
Austin Schuh39788ff2019-12-01 18:22:57 -0800693 timerfd_.SetTime(sleep_time, ::aos::monotonic_clock::zero());
Austin Schuh7d87b672019-12-01 20:23:49 -0800694 event_.set_event_time(sleep_time);
695 shm_event_loop_->AddEvent(&event_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700696 }
697
698 ShmEventLoop *shm_event_loop_;
Brian Silverman148d43d2020-06-07 18:19:22 -0500699 EventHandler<ShmPhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700700
Brian Silverman148d43d2020-06-07 18:19:22 -0500701 internal::TimerFd timerfd_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700702};
Brian Silverman148d43d2020-06-07 18:19:22 -0500703
704} // namespace shm_event_loop_internal
Alex Perrycb7da4b2019-08-28 19:35:56 -0700705
706::std::unique_ptr<RawFetcher> ShmEventLoop::MakeRawFetcher(
707 const Channel *channel) {
Austin Schuhca4828c2019-12-28 14:21:35 -0800708 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
709 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
710 << "\", \"type\": \"" << channel->type()->string_view()
711 << "\" } is not able to be fetched on this node. Check your "
712 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800713 }
714
Brian Silverman148d43d2020-06-07 18:19:22 -0500715 return ::std::unique_ptr<RawFetcher>(new ShmFetcher(this, channel));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700716}
717
718::std::unique_ptr<RawSender> ShmEventLoop::MakeRawSender(
719 const Channel *channel) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800720 TakeSender(channel);
Austin Schuh39788ff2019-12-01 18:22:57 -0800721
Brian Silverman148d43d2020-06-07 18:19:22 -0500722 return ::std::unique_ptr<RawSender>(new ShmSender(this, channel));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700723}
724
725void ShmEventLoop::MakeRawWatcher(
726 const Channel *channel,
727 std::function<void(const Context &context, const void *message)> watcher) {
Brian Silverman0fc69932020-01-24 21:54:02 -0800728 TakeWatcher(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800729
Austin Schuh39788ff2019-12-01 18:22:57 -0800730 NewWatcher(::std::unique_ptr<WatcherState>(
Brian Silverman148d43d2020-06-07 18:19:22 -0500731 new ShmWatcherState(this, channel, std::move(watcher), true)));
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800732}
733
734void ShmEventLoop::MakeRawNoArgWatcher(
735 const Channel *channel,
736 std::function<void(const Context &context)> watcher) {
737 TakeWatcher(channel);
738
Brian Silverman148d43d2020-06-07 18:19:22 -0500739 NewWatcher(::std::unique_ptr<WatcherState>(new ShmWatcherState(
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800740 this, channel,
741 [watcher](const Context &context, const void *) { watcher(context); },
742 false)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700743}
744
745TimerHandler *ShmEventLoop::AddTimer(::std::function<void()> callback) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800746 return NewTimer(::std::unique_ptr<TimerHandler>(
Brian Silverman148d43d2020-06-07 18:19:22 -0500747 new ShmTimerHandler(this, ::std::move(callback))));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700748}
749
750PhasedLoopHandler *ShmEventLoop::AddPhasedLoop(
751 ::std::function<void(int)> callback,
752 const monotonic_clock::duration interval,
753 const monotonic_clock::duration offset) {
Brian Silverman148d43d2020-06-07 18:19:22 -0500754 return NewPhasedLoop(::std::unique_ptr<PhasedLoopHandler>(
755 new ShmPhasedLoopHandler(this, ::std::move(callback), interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700756}
757
758void ShmEventLoop::OnRun(::std::function<void()> on_run) {
759 on_run_.push_back(::std::move(on_run));
760}
761
Austin Schuh7d87b672019-12-01 20:23:49 -0800762void ShmEventLoop::HandleEvent() {
763 // Update all the times for handlers.
764 for (::std::unique_ptr<WatcherState> &base_watcher : watchers_) {
Brian Silverman148d43d2020-06-07 18:19:22 -0500765 ShmWatcherState *watcher =
766 reinterpret_cast<ShmWatcherState *>(base_watcher.get());
Austin Schuh7d87b672019-12-01 20:23:49 -0800767
768 watcher->CheckForNewData();
769 }
770
Austin Schuh39788ff2019-12-01 18:22:57 -0800771 while (true) {
Austin Schuh7d87b672019-12-01 20:23:49 -0800772 if (EventCount() == 0 ||
773 PeekEvent()->event_time() > monotonic_clock::now()) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800774 break;
775 }
776
Austin Schuh7d87b672019-12-01 20:23:49 -0800777 EventLoopEvent *event = PopEvent();
778 event->HandleEvent();
Austin Schuh39788ff2019-12-01 18:22:57 -0800779 }
780}
781
Austin Schuh32fd5a72019-12-01 22:20:26 -0800782// RAII class to mask signals.
783class ScopedSignalMask {
784 public:
785 ScopedSignalMask(std::initializer_list<int> signals) {
786 sigset_t sigset;
787 PCHECK(sigemptyset(&sigset) == 0);
788 for (int signal : signals) {
789 PCHECK(sigaddset(&sigset, signal) == 0);
790 }
791
792 PCHECK(sigprocmask(SIG_BLOCK, &sigset, &old_) == 0);
793 }
794
795 ~ScopedSignalMask() { PCHECK(sigprocmask(SIG_SETMASK, &old_, nullptr) == 0); }
796
797 private:
798 sigset_t old_;
799};
800
801// Class to manage the static state associated with killing multiple event
802// loops.
803class SignalHandler {
804 public:
805 // Gets the singleton.
806 static SignalHandler *global() {
807 static SignalHandler loop;
808 return &loop;
809 }
810
811 // Handles the signal with the singleton.
812 static void HandleSignal(int) { global()->DoHandleSignal(); }
813
814 // Registers an event loop to receive Exit() calls.
815 void Register(ShmEventLoop *event_loop) {
816 // Block signals while we have the mutex so we never race with the signal
817 // handler.
818 ScopedSignalMask mask({SIGINT, SIGHUP, SIGTERM});
819 std::unique_lock<stl_mutex> locker(mutex_);
820 if (event_loops_.size() == 0) {
821 // The first caller registers the signal handler.
822 struct sigaction new_action;
823 sigemptyset(&new_action.sa_mask);
824 // This makes it so that 2 control c's to a stuck process will kill it by
825 // restoring the original signal handler.
826 new_action.sa_flags = SA_RESETHAND;
827 new_action.sa_handler = &HandleSignal;
828
829 PCHECK(sigaction(SIGINT, &new_action, &old_action_int_) == 0);
830 PCHECK(sigaction(SIGHUP, &new_action, &old_action_hup_) == 0);
831 PCHECK(sigaction(SIGTERM, &new_action, &old_action_term_) == 0);
832 }
833
834 event_loops_.push_back(event_loop);
835 }
836
837 // Unregisters an event loop to receive Exit() calls.
838 void Unregister(ShmEventLoop *event_loop) {
839 // Block signals while we have the mutex so we never race with the signal
840 // handler.
841 ScopedSignalMask mask({SIGINT, SIGHUP, SIGTERM});
842 std::unique_lock<stl_mutex> locker(mutex_);
843
Brian Silverman5120afb2020-01-31 17:44:35 -0800844 event_loops_.erase(
845 std::find(event_loops_.begin(), event_loops_.end(), event_loop));
Austin Schuh32fd5a72019-12-01 22:20:26 -0800846
847 if (event_loops_.size() == 0u) {
848 // The last caller restores the original signal handlers.
849 PCHECK(sigaction(SIGINT, &old_action_int_, nullptr) == 0);
850 PCHECK(sigaction(SIGHUP, &old_action_hup_, nullptr) == 0);
851 PCHECK(sigaction(SIGTERM, &old_action_term_, nullptr) == 0);
852 }
853 }
854
855 private:
856 void DoHandleSignal() {
857 // We block signals while grabbing the lock, so there should never be a
858 // race. Confirm that this is true using trylock.
859 CHECK(mutex_.try_lock()) << ": sigprocmask failed to block signals while "
860 "modifing the event loop list.";
861 for (ShmEventLoop *event_loop : event_loops_) {
862 event_loop->Exit();
863 }
864 mutex_.unlock();
865 }
866
867 // Mutex to protect all state.
868 stl_mutex mutex_;
869 std::vector<ShmEventLoop *> event_loops_;
870 struct sigaction old_action_int_;
871 struct sigaction old_action_hup_;
872 struct sigaction old_action_term_;
873};
874
Alex Perrycb7da4b2019-08-28 19:35:56 -0700875void ShmEventLoop::Run() {
Austin Schuh32fd5a72019-12-01 22:20:26 -0800876 SignalHandler::global()->Register(this);
Austin Schuh39788ff2019-12-01 18:22:57 -0800877
Alex Perrycb7da4b2019-08-28 19:35:56 -0700878 std::unique_ptr<ipc_lib::SignalFd> signalfd;
879
880 if (watchers_.size() > 0) {
881 signalfd.reset(new ipc_lib::SignalFd({ipc_lib::kWakeupSignal}));
882
883 epoll_.OnReadable(signalfd->fd(), [signalfd_ptr = signalfd.get(), this]() {
884 signalfd_siginfo result = signalfd_ptr->Read();
885 CHECK_EQ(result.ssi_signo, ipc_lib::kWakeupSignal);
886
887 // TODO(austin): We should really be checking *everything*, not just
888 // watchers, and calling the oldest thing first. That will improve
889 // determinism a lot.
890
Austin Schuh7d87b672019-12-01 20:23:49 -0800891 HandleEvent();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700892 });
893 }
894
Austin Schuh39788ff2019-12-01 18:22:57 -0800895 MaybeScheduleTimingReports();
896
Austin Schuh7d87b672019-12-01 20:23:49 -0800897 ReserveEvents();
898
Tyler Chatow67ddb032020-01-12 14:30:04 -0800899 {
900 AosLogToFbs aos_logger;
901 if (!skip_logger_) {
902 aos_logger.Initialize(MakeSender<logging::LogMessageFbs>("/aos"));
903 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700904
Tyler Chatow67ddb032020-01-12 14:30:04 -0800905 aos::SetCurrentThreadName(name_.substr(0, 16));
Brian Silverman6a54ff32020-04-28 16:41:39 -0700906 const cpu_set_t default_affinity = DefaultAffinity();
907 if (!CPU_EQUAL(&affinity_, &default_affinity)) {
908 ::aos::SetCurrentThreadAffinity(affinity_);
909 }
Tyler Chatow67ddb032020-01-12 14:30:04 -0800910 // Now, all the callbacks are setup. Lock everything into memory and go RT.
911 if (priority_ != 0) {
912 ::aos::InitRT();
913
914 LOG(INFO) << "Setting priority to " << priority_;
915 ::aos::SetCurrentThreadRealtimePriority(priority_);
916 }
917
918 set_is_running(true);
919
920 // Now that we are realtime (but before the OnRun handlers run), snap the
921 // queue index.
922 for (::std::unique_ptr<WatcherState> &watcher : watchers_) {
923 watcher->Startup(this);
924 }
925
926 // Now that we are RT, run all the OnRun handlers.
927 for (const auto &run : on_run_) {
928 run();
929 }
930
931 // And start our main event loop which runs all the timers and handles Quit.
932 epoll_.Run();
933
934 // Once epoll exits, there is no useful nonrt work left to do.
935 set_is_running(false);
936
937 // Nothing time or synchronization critical needs to happen after this
938 // point. Drop RT priority.
939 ::aos::UnsetCurrentThreadRealtimePriority();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700940 }
941
Austin Schuh39788ff2019-12-01 18:22:57 -0800942 for (::std::unique_ptr<WatcherState> &base_watcher : watchers_) {
Brian Silverman148d43d2020-06-07 18:19:22 -0500943 ShmWatcherState *watcher =
944 reinterpret_cast<ShmWatcherState *>(base_watcher.get());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700945 watcher->UnregisterWakeup();
946 }
947
948 if (watchers_.size() > 0) {
949 epoll_.DeleteFd(signalfd->fd());
950 signalfd.reset();
951 }
Austin Schuh32fd5a72019-12-01 22:20:26 -0800952
953 SignalHandler::global()->Unregister(this);
Austin Schuhe84c3ed2019-12-14 15:29:48 -0800954
955 // Trigger any remaining senders or fetchers to be cleared before destroying
956 // the event loop so the book keeping matches. Do this in the thread that
957 // created the timing reporter.
958 timing_report_sender_.reset();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700959}
960
961void ShmEventLoop::Exit() { epoll_.Quit(); }
962
963ShmEventLoop::~ShmEventLoop() {
Austin Schuh39788ff2019-12-01 18:22:57 -0800964 // Force everything with a registered fd with epoll to be destroyed now.
965 timers_.clear();
966 phased_loops_.clear();
967 watchers_.clear();
968
Alex Perrycb7da4b2019-08-28 19:35:56 -0700969 CHECK(!is_running()) << ": ShmEventLoop destroyed while running";
970}
971
Alex Perrycb7da4b2019-08-28 19:35:56 -0700972void ShmEventLoop::SetRuntimeRealtimePriority(int priority) {
973 if (is_running()) {
974 LOG(FATAL) << "Cannot set realtime priority while running.";
975 }
976 priority_ = priority;
977}
978
Brian Silverman6a54ff32020-04-28 16:41:39 -0700979void ShmEventLoop::SetRuntimeAffinity(const cpu_set_t &cpuset) {
980 if (is_running()) {
981 LOG(FATAL) << "Cannot set affinity while running.";
982 }
983 affinity_ = cpuset;
984}
985
James Kuszmaul57c2baa2020-01-19 14:52:52 -0800986void ShmEventLoop::set_name(const std::string_view name) {
987 name_ = std::string(name);
988 UpdateTimingReport();
989}
990
Brian Silverman5120afb2020-01-31 17:44:35 -0800991absl::Span<char> ShmEventLoop::GetWatcherSharedMemory(const Channel *channel) {
Brian Silverman148d43d2020-06-07 18:19:22 -0500992 ShmWatcherState *const watcher_state =
993 static_cast<ShmWatcherState *>(GetWatcherState(channel));
Brian Silverman5120afb2020-01-31 17:44:35 -0800994 return watcher_state->GetSharedMemory();
995}
996
997absl::Span<char> ShmEventLoop::GetShmSenderSharedMemory(
998 const aos::RawSender *sender) const {
Brian Silverman148d43d2020-06-07 18:19:22 -0500999 return static_cast<const ShmSender *>(sender)->GetSharedMemory();
Brian Silverman5120afb2020-01-31 17:44:35 -08001000}
1001
Brian Silverman6d2b3592020-06-18 14:40:15 -07001002absl::Span<char> ShmEventLoop::GetShmFetcherPrivateMemory(
1003 const aos::RawFetcher *fetcher) const {
1004 return static_cast<const ShmFetcher *>(fetcher)->GetPrivateMemory();
1005}
1006
Austin Schuh39788ff2019-12-01 18:22:57 -08001007pid_t ShmEventLoop::GetTid() { return syscall(SYS_gettid); }
1008
Alex Perrycb7da4b2019-08-28 19:35:56 -07001009} // namespace aos