blob: 3c89a1c1c2ae6f792ac3a1596b2bcba11bcd503e [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
Austin Schuhef323c02020-09-01 14:55:28 -070015#include "absl/strings/str_cat.h"
Tyler Chatow67ddb032020-01-12 14:30:04 -080016#include "aos/events/aos_logging.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070017#include "aos/events/epoll.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080018#include "aos/events/event_loop_generated.h"
19#include "aos/events/timing_statistics.h"
Austin Schuh094d09b2020-11-20 23:26:52 -080020#include "aos/init.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070021#include "aos/ipc_lib/lockless_queue.h"
22#include "aos/realtime.h"
Austin Schuh32fd5a72019-12-01 22:20:26 -080023#include "aos/stl_mutex/stl_mutex.h"
Austin Schuhfccb2d02020-01-26 16:11:19 -080024#include "aos/util/file.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070025#include "aos/util/phased_loop.h"
Austin Schuh39788ff2019-12-01 18:22:57 -080026#include "glog/logging.h"
Alex Perrycb7da4b2019-08-28 19:35:56 -070027
Austin Schuhe84c3ed2019-12-14 15:29:48 -080028namespace {
29
30// Returns the portion of the path after the last /. This very much assumes
31// that the application name is null terminated.
32const char *Filename(const char *path) {
33 const std::string_view path_string_view = path;
34 auto last_slash_pos = path_string_view.find_last_of("/");
35
36 return last_slash_pos == std::string_view::npos ? path
37 : path + last_slash_pos + 1;
38}
39
40} // namespace
41
Alex Perrycb7da4b2019-08-28 19:35:56 -070042DEFINE_string(shm_base, "/dev/shm/aos",
43 "Directory to place queue backing mmaped files in.");
44DEFINE_uint32(permissions, 0770,
45 "Permissions to make shared memory files and folders.");
Austin Schuhe84c3ed2019-12-14 15:29:48 -080046DEFINE_string(application_name, Filename(program_invocation_name),
47 "The application name");
Alex Perrycb7da4b2019-08-28 19:35:56 -070048
49namespace aos {
50
Brian Silverman148d43d2020-06-07 18:19:22 -050051using namespace shm_event_loop_internal;
52
Austin Schuhcdab6192019-12-29 17:47:46 -080053void SetShmBase(const std::string_view base) {
Austin Schuhef323c02020-09-01 14:55:28 -070054 FLAGS_shm_base = std::string(base) + "/aos";
Austin Schuhcdab6192019-12-29 17:47:46 -080055}
56
Brian Silverman4f4e0612020-08-12 19:54:41 -070057namespace {
58
Austin Schuhef323c02020-09-01 14:55:28 -070059std::string ShmFolder(std::string_view shm_base, const Channel *channel) {
Alex Perrycb7da4b2019-08-28 19:35:56 -070060 CHECK(channel->has_name());
61 CHECK_EQ(channel->name()->string_view()[0], '/');
Austin Schuhef323c02020-09-01 14:55:28 -070062 return absl::StrCat(shm_base, channel->name()->string_view(), "/");
Alex Perrycb7da4b2019-08-28 19:35:56 -070063}
Austin Schuhef323c02020-09-01 14:55:28 -070064std::string ShmPath(std::string_view shm_base, const Channel *channel) {
Alex Perrycb7da4b2019-08-28 19:35:56 -070065 CHECK(channel->has_type());
Austin Schuh8902fa52021-03-14 22:39:24 -070066 return ShmFolder(shm_base, channel) + channel->type()->str() + ".v4";
Alex Perrycb7da4b2019-08-28 19:35:56 -070067}
68
Brian Silvermana5450a92020-08-12 19:59:57 -070069void PageFaultDataWrite(char *data, size_t size) {
Brian Silverman3b0cdaf2020-04-28 16:51:51 -070070 // This just has to divide the actual page size. Being smaller will make this
71 // a bit slower than necessary, but not much. 1024 is a pretty conservative
72 // choice (most pages are probably 4096).
73 static constexpr size_t kPageSize = 1024;
74 const size_t pages = (size + kPageSize - 1) / kPageSize;
75 for (size_t i = 0; i < pages; ++i) {
76 char zero = 0;
77 // We need to ensure there's a writable pagetable entry, but avoid modifying
78 // the data.
79 //
80 // Even if you lock the data into memory, some kernels still seem to lazily
81 // create the actual pagetable entries. This means we need to somehow
82 // "write" to the page.
83 //
84 // Also, this takes place while other processes may be concurrently
85 // opening/initializing the memory, so we need to avoid corrupting that.
86 //
87 // This is the simplest operation I could think of which achieves that:
88 // "store 0 if it's already 0".
89 __atomic_compare_exchange_n(&data[i * kPageSize], &zero, 0, true,
90 __ATOMIC_RELAXED, __ATOMIC_RELAXED);
91 }
92}
93
Brian Silvermana5450a92020-08-12 19:59:57 -070094void PageFaultDataRead(const char *data, size_t size) {
95 // This just has to divide the actual page size. Being smaller will make this
96 // a bit slower than necessary, but not much. 1024 is a pretty conservative
97 // choice (most pages are probably 4096).
98 static constexpr size_t kPageSize = 1024;
99 const size_t pages = (size + kPageSize - 1) / kPageSize;
100 for (size_t i = 0; i < pages; ++i) {
101 // We need to ensure there's a readable pagetable entry.
102 __atomic_load_n(&data[i * kPageSize], __ATOMIC_RELAXED);
103 }
104}
105
Brian Silverman4f4e0612020-08-12 19:54:41 -0700106ipc_lib::LocklessQueueConfiguration MakeQueueConfiguration(
Austin Schuhfb37c612022-08-11 15:24:51 -0700107 const Configuration *configuration, const Channel *channel) {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700108 ipc_lib::LocklessQueueConfiguration config;
109
110 config.num_watchers = channel->num_watchers();
111 config.num_senders = channel->num_senders();
112 // The value in the channel will default to 0 if readers are configured to
113 // copy.
114 config.num_pinners = channel->num_readers();
Austin Schuhfb37c612022-08-11 15:24:51 -0700115 config.queue_size = configuration::QueueSize(configuration, channel);
Brian Silverman4f4e0612020-08-12 19:54:41 -0700116 config.message_data_size = channel->max_size();
117
118 return config;
119}
120
Austin Schuh2f8fd752020-09-01 22:38:28 -0700121class MMappedQueue {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700122 public:
Austin Schuhfb37c612022-08-11 15:24:51 -0700123 MMappedQueue(std::string_view shm_base, const Configuration *config,
124 const Channel *channel)
125 : config_(MakeQueueConfiguration(config, channel)) {
Austin Schuhef323c02020-09-01 14:55:28 -0700126 std::string path = ShmPath(shm_base, channel);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700127
Alex Perrycb7da4b2019-08-28 19:35:56 -0700128 size_ = ipc_lib::LocklessQueueMemorySize(config_);
129
Austin Schuhfccb2d02020-01-26 16:11:19 -0800130 util::MkdirP(path, FLAGS_permissions);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700131
132 // There are 2 cases. Either the file already exists, or it does not
133 // already exist and we need to create it. Start by trying to create it. If
134 // that fails, the file has already been created and we can open it
Brian Silverman4f4e0612020-08-12 19:54:41 -0700135 // normally.. Once the file has been created it will never be deleted.
Brian Silvermanf9f30ea2020-03-04 23:18:54 -0800136 int fd = open(path.c_str(), O_RDWR | O_CREAT | O_EXCL,
Brian Silverman148d43d2020-06-07 18:19:22 -0500137 O_CLOEXEC | FLAGS_permissions);
Brian Silvermanf9f30ea2020-03-04 23:18:54 -0800138 if (fd == -1 && errno == EEXIST) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700139 VLOG(1) << path << " already created.";
140 // File already exists.
Brian Silvermanf9f30ea2020-03-04 23:18:54 -0800141 fd = open(path.c_str(), O_RDWR, O_CLOEXEC);
142 PCHECK(fd != -1) << ": Failed to open " << path;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700143 while (true) {
144 struct stat st;
Brian Silvermanf9f30ea2020-03-04 23:18:54 -0800145 PCHECK(fstat(fd, &st) == 0);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700146 if (st.st_size != 0) {
147 CHECK_EQ(static_cast<size_t>(st.st_size), size_)
148 << ": Size of " << path
149 << " doesn't match expected size of backing queue file. Did the "
150 "queue definition change?";
151 break;
152 } else {
153 // The creating process didn't get around to it yet. Give it a bit.
154 std::this_thread::sleep_for(std::chrono::milliseconds(10));
155 VLOG(1) << path << " is zero size, waiting";
156 }
157 }
158 } else {
159 VLOG(1) << "Created " << path;
Brian Silvermanf9f30ea2020-03-04 23:18:54 -0800160 PCHECK(fd != -1) << ": Failed to open " << path;
161 PCHECK(ftruncate(fd, size_) == 0);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700162 }
163
Brian Silvermanf9f30ea2020-03-04 23:18:54 -0800164 data_ = mmap(NULL, size_, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700165 PCHECK(data_ != MAP_FAILED);
Brian Silvermana5450a92020-08-12 19:59:57 -0700166 const_data_ = mmap(NULL, size_, PROT_READ, MAP_SHARED, fd, 0);
167 PCHECK(const_data_ != MAP_FAILED);
Brian Silvermanf9f30ea2020-03-04 23:18:54 -0800168 PCHECK(close(fd) == 0);
Brian Silvermana5450a92020-08-12 19:59:57 -0700169 PageFaultDataWrite(static_cast<char *>(data_), size_);
170 PageFaultDataRead(static_cast<const char *>(const_data_), size_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700171
172 ipc_lib::InitializeLocklessQueueMemory(memory(), config_);
173 }
174
Austin Schuh2f8fd752020-09-01 22:38:28 -0700175 ~MMappedQueue() {
Brian Silvermana5450a92020-08-12 19:59:57 -0700176 PCHECK(munmap(data_, size_) == 0);
177 PCHECK(munmap(const_cast<void *>(const_data_), size_) == 0);
178 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700179
180 ipc_lib::LocklessQueueMemory *memory() const {
181 return reinterpret_cast<ipc_lib::LocklessQueueMemory *>(data_);
182 }
183
Brian Silvermana5450a92020-08-12 19:59:57 -0700184 const ipc_lib::LocklessQueueMemory *const_memory() const {
185 return reinterpret_cast<const ipc_lib::LocklessQueueMemory *>(const_data_);
186 }
187
Austin Schuh39788ff2019-12-01 18:22:57 -0800188 const ipc_lib::LocklessQueueConfiguration &config() const { return config_; }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700189
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700190 ipc_lib::LocklessQueue queue() const {
Brian Silvermana5450a92020-08-12 19:59:57 -0700191 return ipc_lib::LocklessQueue(const_memory(), memory(), config());
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700192 }
193
Brian Silvermana5450a92020-08-12 19:59:57 -0700194 absl::Span<char> GetMutableSharedMemory() const {
Brian Silverman5120afb2020-01-31 17:44:35 -0800195 return absl::Span<char>(static_cast<char *>(data_), size_);
196 }
197
Brian Silvermana5450a92020-08-12 19:59:57 -0700198 absl::Span<const char> GetConstSharedMemory() const {
199 return absl::Span<const char>(static_cast<const char *>(const_data_),
200 size_);
201 }
202
Alex Perrycb7da4b2019-08-28 19:35:56 -0700203 private:
Brian Silverman4f4e0612020-08-12 19:54:41 -0700204 const ipc_lib::LocklessQueueConfiguration config_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700205
Alex Perrycb7da4b2019-08-28 19:35:56 -0700206 size_t size_;
207 void *data_;
Brian Silvermana5450a92020-08-12 19:59:57 -0700208 const void *const_data_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700209};
210
Austin Schuh217a9782019-12-21 23:02:50 -0800211const Node *MaybeMyNode(const Configuration *configuration) {
212 if (!configuration->has_nodes()) {
213 return nullptr;
214 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700215
Austin Schuh217a9782019-12-21 23:02:50 -0800216 return configuration::GetMyNode(configuration);
217}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700218
219namespace chrono = ::std::chrono;
220
Austin Schuh39788ff2019-12-01 18:22:57 -0800221} // namespace
222
Austin Schuh217a9782019-12-21 23:02:50 -0800223ShmEventLoop::ShmEventLoop(const Configuration *configuration)
Austin Schuh83c7f702021-01-19 22:36:29 -0800224 : EventLoop(configuration),
225 boot_uuid_(UUID::BootUUID()),
Austin Schuhef323c02020-09-01 14:55:28 -0700226 shm_base_(FLAGS_shm_base),
Austin Schuhe84c3ed2019-12-14 15:29:48 -0800227 name_(FLAGS_application_name),
Austin Schuh15649d62019-12-28 16:36:38 -0800228 node_(MaybeMyNode(configuration)) {
Austin Schuh094d09b2020-11-20 23:26:52 -0800229 CHECK(IsInitialized()) << ": Need to initialize AOS first.";
Austin Schuh15649d62019-12-28 16:36:38 -0800230 if (configuration->has_nodes()) {
231 CHECK(node_ != nullptr) << ": Couldn't find node in config.";
232 }
233}
Austin Schuh217a9782019-12-21 23:02:50 -0800234
Brian Silverman148d43d2020-06-07 18:19:22 -0500235namespace shm_event_loop_internal {
Austin Schuh39788ff2019-12-01 18:22:57 -0800236
237class SimpleShmFetcher {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700238 public:
Austin Schuhef323c02020-09-01 14:55:28 -0700239 explicit SimpleShmFetcher(std::string_view shm_base, ShmEventLoop *event_loop,
240 const Channel *channel)
Austin Schuh432784f2020-06-23 17:27:35 -0700241 : event_loop_(event_loop),
242 channel_(channel),
Austin Schuhfb37c612022-08-11 15:24:51 -0700243 lockless_queue_memory_(shm_base, event_loop->configuration(), channel),
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700244 reader_(lockless_queue_memory_.queue()) {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700245 context_.data = nullptr;
246 // Point the queue index at the next index to read starting now. This
247 // makes it such that FetchNext will read the next message sent after
248 // the fetcher is created.
249 PointAtNextQueueIndex();
250 }
251
Austin Schuh39788ff2019-12-01 18:22:57 -0800252 ~SimpleShmFetcher() {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700253
Brian Silverman77162972020-08-12 19:52:40 -0700254 // Sets this object to pin or copy data, as configured in the channel.
255 void RetrieveData() {
256 if (channel_->read_method() == ReadMethod::PIN) {
257 PinDataOnFetch();
258 } else {
259 CopyDataOnFetch();
260 }
261 }
262
Brian Silverman3bca5322020-08-12 19:35:29 -0700263 // Sets this object to copy data out of the shared memory into a private
264 // buffer when fetching.
265 void CopyDataOnFetch() {
Brian Silverman77162972020-08-12 19:52:40 -0700266 CHECK(!pin_data());
Brian Silverman3bca5322020-08-12 19:35:29 -0700267 data_storage_.reset(static_cast<char *>(
268 malloc(channel_->max_size() + kChannelDataAlignment - 1)));
269 }
270
Brian Silverman77162972020-08-12 19:52:40 -0700271 // Sets this object to pin data in shared memory when fetching.
272 void PinDataOnFetch() {
273 CHECK(!copy_data());
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700274 auto maybe_pinner =
275 ipc_lib::LocklessQueuePinner::Make(lockless_queue_memory_.queue());
Brian Silverman77162972020-08-12 19:52:40 -0700276 if (!maybe_pinner) {
277 LOG(FATAL) << "Failed to create reader on "
278 << configuration::CleanedChannelToString(channel_)
279 << ", too many readers.";
280 }
281 pinner_ = std::move(maybe_pinner.value());
282 }
283
Alex Perrycb7da4b2019-08-28 19:35:56 -0700284 // Points the next message to fetch at the queue index which will be
285 // populated next.
286 void PointAtNextQueueIndex() {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700287 actual_queue_index_ = reader_.LatestIndex();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700288 if (!actual_queue_index_.valid()) {
289 // Nothing in the queue. The next element will show up at the 0th
290 // index in the queue.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700291 actual_queue_index_ = ipc_lib::QueueIndex::Zero(
292 LocklessQueueSize(lockless_queue_memory_.memory()));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700293 } else {
294 actual_queue_index_ = actual_queue_index_.Increment();
295 }
296 }
297
Austin Schuh39788ff2019-12-01 18:22:57 -0800298 bool FetchNext() {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700299 const ipc_lib::LocklessQueueReader::Result read_result =
Brian Silverman3bca5322020-08-12 19:35:29 -0700300 DoFetch(actual_queue_index_);
Austin Schuh432784f2020-06-23 17:27:35 -0700301
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700302 return read_result == ipc_lib::LocklessQueueReader::Result::GOOD;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700303 }
304
Austin Schuh39788ff2019-12-01 18:22:57 -0800305 bool Fetch() {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700306 const ipc_lib::QueueIndex queue_index = reader_.LatestIndex();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700307 // actual_queue_index_ is only meaningful if it was set by Fetch or
308 // FetchNext. This happens when valid_data_ has been set. So, only
309 // skip checking if valid_data_ is true.
310 //
311 // Also, if the latest queue index is invalid, we are empty. So there
312 // is nothing to fetch.
Austin Schuh39788ff2019-12-01 18:22:57 -0800313 if ((context_.data != nullptr &&
Alex Perrycb7da4b2019-08-28 19:35:56 -0700314 queue_index == actual_queue_index_.DecrementBy(1u)) ||
315 !queue_index.valid()) {
316 return false;
317 }
318
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700319 const ipc_lib::LocklessQueueReader::Result read_result =
320 DoFetch(queue_index);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700321
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700322 CHECK(read_result != ipc_lib::LocklessQueueReader::Result::NOTHING_NEW)
Austin Schuhf5652592019-12-29 16:26:15 -0800323 << ": Queue index went backwards. This should never happen. "
324 << configuration::CleanedChannelToString(channel_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700325
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700326 return read_result == ipc_lib::LocklessQueueReader::Result::GOOD;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700327 }
328
Austin Schuh39788ff2019-12-01 18:22:57 -0800329 Context context() const { return context_; }
330
Alex Perrycb7da4b2019-08-28 19:35:56 -0700331 bool RegisterWakeup(int priority) {
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700332 CHECK(!watcher_);
333 watcher_ = ipc_lib::LocklessQueueWatcher::Make(
334 lockless_queue_memory_.queue(), priority);
335 return static_cast<bool>(watcher_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700336 }
337
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700338 void UnregisterWakeup() {
339 CHECK(watcher_);
340 watcher_ = std::nullopt;
341 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700342
Brian Silvermana5450a92020-08-12 19:59:57 -0700343 absl::Span<char> GetMutableSharedMemory() {
344 return lockless_queue_memory_.GetMutableSharedMemory();
Brian Silverman5120afb2020-01-31 17:44:35 -0800345 }
346
Brian Silvermana5450a92020-08-12 19:59:57 -0700347 absl::Span<const char> GetConstSharedMemory() const {
348 return lockless_queue_memory_.GetConstSharedMemory();
349 }
350
351 absl::Span<const char> GetPrivateMemory() const {
352 if (pin_data()) {
353 return lockless_queue_memory_.GetConstSharedMemory();
354 }
Brian Silverman6d2b3592020-06-18 14:40:15 -0700355 return absl::Span<char>(
356 const_cast<SimpleShmFetcher *>(this)->data_storage_start(),
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700357 LocklessQueueMessageDataSize(lockless_queue_memory_.memory()));
Brian Silverman6d2b3592020-06-18 14:40:15 -0700358 }
359
Alex Perrycb7da4b2019-08-28 19:35:56 -0700360 private:
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700361 ipc_lib::LocklessQueueReader::Result DoFetch(
362 ipc_lib::QueueIndex queue_index) {
Brian Silverman3bca5322020-08-12 19:35:29 -0700363 // TODO(austin): Get behind and make sure it dies.
364 char *copy_buffer = nullptr;
365 if (copy_data()) {
366 copy_buffer = data_storage_start();
367 }
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700368 ipc_lib::LocklessQueueReader::Result read_result = reader_.Read(
Brian Silverman3bca5322020-08-12 19:35:29 -0700369 queue_index.index(), &context_.monotonic_event_time,
370 &context_.realtime_event_time, &context_.monotonic_remote_time,
371 &context_.realtime_remote_time, &context_.remote_queue_index,
Austin Schuha9012be2021-07-21 15:19:11 -0700372 &context_.source_boot_uuid, &context_.size, copy_buffer);
Brian Silverman3bca5322020-08-12 19:35:29 -0700373
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700374 if (read_result == ipc_lib::LocklessQueueReader::Result::GOOD) {
Brian Silverman77162972020-08-12 19:52:40 -0700375 if (pin_data()) {
Brian Silverman4f4e0612020-08-12 19:54:41 -0700376 const int pin_result = pinner_->PinIndex(queue_index.index());
377 CHECK(pin_result >= 0)
Brian Silverman77162972020-08-12 19:52:40 -0700378 << ": Got behind while reading and the last message was modified "
379 "out from under us while we tried to pin it. Don't get so far "
380 "behind on: "
381 << configuration::CleanedChannelToString(channel_);
Brian Silverman4f4e0612020-08-12 19:54:41 -0700382 context_.buffer_index = pin_result;
383 } else {
384 context_.buffer_index = -1;
Brian Silverman77162972020-08-12 19:52:40 -0700385 }
386
Brian Silverman3bca5322020-08-12 19:35:29 -0700387 context_.queue_index = queue_index.index();
388 if (context_.remote_queue_index == 0xffffffffu) {
389 context_.remote_queue_index = context_.queue_index;
390 }
391 if (context_.monotonic_remote_time == aos::monotonic_clock::min_time) {
392 context_.monotonic_remote_time = context_.monotonic_event_time;
393 }
394 if (context_.realtime_remote_time == aos::realtime_clock::min_time) {
395 context_.realtime_remote_time = context_.realtime_event_time;
396 }
397 const char *const data = DataBuffer();
398 if (data) {
399 context_.data =
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700400 data +
401 LocklessQueueMessageDataSize(lockless_queue_memory_.memory()) -
402 context_.size;
Brian Silverman3bca5322020-08-12 19:35:29 -0700403 } else {
404 context_.data = nullptr;
405 }
406 actual_queue_index_ = queue_index.Increment();
407 }
408
409 // Make sure the data wasn't modified while we were reading it. This
410 // can only happen if you are reading the last message *while* it is
411 // being written to, which means you are pretty far behind.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700412 CHECK(read_result != ipc_lib::LocklessQueueReader::Result::OVERWROTE)
Brian Silverman3bca5322020-08-12 19:35:29 -0700413 << ": Got behind while reading and the last message was modified "
414 "out from under us while we were reading it. Don't get so far "
415 "behind on: "
416 << configuration::CleanedChannelToString(channel_);
417
418 // We fell behind between when we read the index and read the value.
419 // This isn't worth recovering from since this means we went to sleep
420 // for a long time in the middle of this function.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700421 if (read_result == ipc_lib::LocklessQueueReader::Result::TOO_OLD) {
Brian Silverman3bca5322020-08-12 19:35:29 -0700422 event_loop_->SendTimingReport();
423 LOG(FATAL) << "The next message is no longer available. "
424 << configuration::CleanedChannelToString(channel_);
425 }
426
427 return read_result;
428 }
429
430 char *data_storage_start() const {
431 CHECK(copy_data());
Brian Silvermana1652f32020-01-29 20:41:44 -0800432 return RoundChannelData(data_storage_.get(), channel_->max_size());
433 }
Brian Silverman3bca5322020-08-12 19:35:29 -0700434
435 // Note that for some modes the return value will change as new messages are
436 // read.
437 const char *DataBuffer() const {
438 if (copy_data()) {
439 return data_storage_start();
440 }
Brian Silverman77162972020-08-12 19:52:40 -0700441 if (pin_data()) {
442 return static_cast<const char *>(pinner_->Data());
443 }
Brian Silverman3bca5322020-08-12 19:35:29 -0700444 return nullptr;
445 }
446
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800447 bool copy_data() const { return static_cast<bool>(data_storage_); }
Brian Silverman77162972020-08-12 19:52:40 -0700448 bool pin_data() const { return static_cast<bool>(pinner_); }
Brian Silvermana1652f32020-01-29 20:41:44 -0800449
Austin Schuh432784f2020-06-23 17:27:35 -0700450 aos::ShmEventLoop *event_loop_;
Austin Schuhf5652592019-12-29 16:26:15 -0800451 const Channel *const channel_;
Austin Schuh2f8fd752020-09-01 22:38:28 -0700452 MMappedQueue lockless_queue_memory_;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700453 ipc_lib::LocklessQueueReader reader_;
454 // This being nullopt indicates we're not looking for wakeups right now.
455 std::optional<ipc_lib::LocklessQueueWatcher> watcher_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700456
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700457 ipc_lib::QueueIndex actual_queue_index_ = ipc_lib::QueueIndex::Invalid();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700458
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800459 // This being empty indicates we're not going to copy data.
460 std::unique_ptr<char, decltype(&free)> data_storage_{nullptr, &free};
Austin Schuh39788ff2019-12-01 18:22:57 -0800461
Brian Silverman77162972020-08-12 19:52:40 -0700462 // This being nullopt indicates we're not going to pin messages.
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700463 std::optional<ipc_lib::LocklessQueuePinner> pinner_;
Brian Silverman77162972020-08-12 19:52:40 -0700464
Austin Schuh39788ff2019-12-01 18:22:57 -0800465 Context context_;
466};
467
468class ShmFetcher : public RawFetcher {
469 public:
Austin Schuhef323c02020-09-01 14:55:28 -0700470 explicit ShmFetcher(std::string_view shm_base, ShmEventLoop *event_loop,
471 const Channel *channel)
Austin Schuhaa79e4e2019-12-29 20:43:32 -0800472 : RawFetcher(event_loop, channel),
Austin Schuhef323c02020-09-01 14:55:28 -0700473 simple_shm_fetcher_(shm_base, event_loop, channel) {
Brian Silverman77162972020-08-12 19:52:40 -0700474 simple_shm_fetcher_.RetrieveData();
Brian Silverman3bca5322020-08-12 19:35:29 -0700475 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800476
Austin Schuh3054f5f2021-07-21 15:38:01 -0700477 ~ShmFetcher() override {
478 shm_event_loop()->CheckCurrentThread();
479 context_.data = nullptr;
480 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800481
482 std::pair<bool, monotonic_clock::time_point> DoFetchNext() override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700483 shm_event_loop()->CheckCurrentThread();
Austin Schuh39788ff2019-12-01 18:22:57 -0800484 if (simple_shm_fetcher_.FetchNext()) {
485 context_ = simple_shm_fetcher_.context();
486 return std::make_pair(true, monotonic_clock::now());
487 }
488 return std::make_pair(false, monotonic_clock::min_time);
489 }
490
491 std::pair<bool, monotonic_clock::time_point> DoFetch() override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700492 shm_event_loop()->CheckCurrentThread();
Austin Schuh39788ff2019-12-01 18:22:57 -0800493 if (simple_shm_fetcher_.Fetch()) {
494 context_ = simple_shm_fetcher_.context();
495 return std::make_pair(true, monotonic_clock::now());
496 }
497 return std::make_pair(false, monotonic_clock::min_time);
498 }
499
Brian Silvermana5450a92020-08-12 19:59:57 -0700500 absl::Span<const char> GetPrivateMemory() const {
Brian Silverman6d2b3592020-06-18 14:40:15 -0700501 return simple_shm_fetcher_.GetPrivateMemory();
502 }
503
Austin Schuh39788ff2019-12-01 18:22:57 -0800504 private:
Austin Schuh3054f5f2021-07-21 15:38:01 -0700505 const ShmEventLoop *shm_event_loop() const {
506 return static_cast<const ShmEventLoop *>(event_loop());
507 }
508
Austin Schuh39788ff2019-12-01 18:22:57 -0800509 SimpleShmFetcher simple_shm_fetcher_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700510};
511
Brian Silvermane1fe2512022-08-14 23:18:50 -0700512class ShmExitHandle : public ExitHandle {
513 public:
514 ShmExitHandle(ShmEventLoop *event_loop) : event_loop_(event_loop) {
515 ++event_loop_->exit_handle_count_;
516 }
517 ~ShmExitHandle() override {
518 CHECK_GT(event_loop_->exit_handle_count_, 0);
519 --event_loop_->exit_handle_count_;
520 }
521
522 void Exit() override { event_loop_->Exit(); }
523
524 private:
525 ShmEventLoop *const event_loop_;
526};
527
Alex Perrycb7da4b2019-08-28 19:35:56 -0700528class ShmSender : public RawSender {
529 public:
Austin Schuhef323c02020-09-01 14:55:28 -0700530 explicit ShmSender(std::string_view shm_base, EventLoop *event_loop,
531 const Channel *channel)
Austin Schuh39788ff2019-12-01 18:22:57 -0800532 : RawSender(event_loop, channel),
Austin Schuhfb37c612022-08-11 15:24:51 -0700533 lockless_queue_memory_(shm_base, event_loop->configuration(), channel),
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700534 lockless_queue_sender_(VerifySender(
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700535 ipc_lib::LocklessQueueSender::Make(
536 lockless_queue_memory_.queue(),
537 std::chrono::nanoseconds(
538 event_loop->configuration()->channel_storage_duration())),
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700539 channel)),
540 wake_upper_(lockless_queue_memory_.queue()) {}
Alex Perrycb7da4b2019-08-28 19:35:56 -0700541
Austin Schuh3054f5f2021-07-21 15:38:01 -0700542 ~ShmSender() override { shm_event_loop()->CheckCurrentThread(); }
Austin Schuh39788ff2019-12-01 18:22:57 -0800543
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700544 static ipc_lib::LocklessQueueSender VerifySender(
545 std::optional<ipc_lib::LocklessQueueSender> sender,
Austin Schuhe516ab02020-05-06 21:37:04 -0700546 const Channel *channel) {
547 if (sender) {
548 return std::move(sender.value());
549 }
550 LOG(FATAL) << "Failed to create sender on "
551 << configuration::CleanedChannelToString(channel)
552 << ", too many senders.";
553 }
554
Austin Schuh3054f5f2021-07-21 15:38:01 -0700555 void *data() override {
556 shm_event_loop()->CheckCurrentThread();
557 return lockless_queue_sender_.Data();
558 }
559 size_t size() override {
560 shm_event_loop()->CheckCurrentThread();
561 return lockless_queue_sender_.size();
562 }
milind1f1dca32021-07-03 13:50:07 -0700563
564 Error DoSend(size_t length,
565 aos::monotonic_clock::time_point monotonic_remote_time,
566 aos::realtime_clock::time_point realtime_remote_time,
567 uint32_t remote_queue_index,
568 const UUID &source_boot_uuid) override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700569 shm_event_loop()->CheckCurrentThread();
Austin Schuh0f7ed462020-03-28 20:38:34 -0700570 CHECK_LE(length, static_cast<size_t>(channel()->max_size()))
571 << ": Sent too big a message on "
572 << configuration::CleanedChannelToString(channel());
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700573 const auto result = lockless_queue_sender_.Send(
574 length, monotonic_remote_time, realtime_remote_time, remote_queue_index,
575 source_boot_uuid, &monotonic_sent_time_, &realtime_sent_time_,
576 &sent_queue_index_);
577 CHECK_NE(result, ipc_lib::LocklessQueueSender::Result::INVALID_REDZONE)
Austin Schuh91ba6392020-10-03 13:27:47 -0700578 << ": Somebody wrote outside the buffer of their message on channel "
579 << configuration::CleanedChannelToString(channel());
580
Austin Schuh65493d62022-08-17 15:10:37 -0700581 wake_upper_.Wakeup(event_loop()->is_running()
582 ? event_loop()->runtime_realtime_priority()
583 : 0);
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700584 return CheckLocklessQueueResult(result);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700585 }
586
milind1f1dca32021-07-03 13:50:07 -0700587 Error DoSend(const void *msg, size_t length,
588 aos::monotonic_clock::time_point monotonic_remote_time,
589 aos::realtime_clock::time_point realtime_remote_time,
590 uint32_t remote_queue_index,
591 const UUID &source_boot_uuid) override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700592 shm_event_loop()->CheckCurrentThread();
Austin Schuh0f7ed462020-03-28 20:38:34 -0700593 CHECK_LE(length, static_cast<size_t>(channel()->max_size()))
594 << ": Sent too big a message on "
595 << configuration::CleanedChannelToString(channel());
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700596 const auto result = lockless_queue_sender_.Send(
Brian Silvermanaf9a4d82020-10-06 15:10:58 -0700597 reinterpret_cast<const char *>(msg), length, monotonic_remote_time,
Austin Schuha9012be2021-07-21 15:19:11 -0700598 realtime_remote_time, remote_queue_index, source_boot_uuid,
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700599 &monotonic_sent_time_, &realtime_sent_time_, &sent_queue_index_);
600
601 CHECK_NE(result, ipc_lib::LocklessQueueSender::Result::INVALID_REDZONE)
602 << ": Somebody wrote outside the buffer of their message on "
603 "channel "
Austin Schuh91ba6392020-10-03 13:27:47 -0700604 << configuration::CleanedChannelToString(channel());
Austin Schuh65493d62022-08-17 15:10:37 -0700605 wake_upper_.Wakeup(event_loop()->is_running()
606 ? event_loop()->runtime_realtime_priority()
607 : 0);
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700608
609 return CheckLocklessQueueResult(result);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700610 }
611
Brian Silverman5120afb2020-01-31 17:44:35 -0800612 absl::Span<char> GetSharedMemory() const {
Brian Silvermana5450a92020-08-12 19:59:57 -0700613 return lockless_queue_memory_.GetMutableSharedMemory();
Brian Silverman5120afb2020-01-31 17:44:35 -0800614 }
615
Austin Schuh3054f5f2021-07-21 15:38:01 -0700616 int buffer_index() override {
617 shm_event_loop()->CheckCurrentThread();
618 return lockless_queue_sender_.buffer_index();
619 }
Brian Silverman4f4e0612020-08-12 19:54:41 -0700620
Alex Perrycb7da4b2019-08-28 19:35:56 -0700621 private:
Austin Schuh3054f5f2021-07-21 15:38:01 -0700622 const ShmEventLoop *shm_event_loop() const {
623 return static_cast<const ShmEventLoop *>(event_loop());
624 }
625
Eric Schmiedebergef44b8a2022-02-28 17:30:38 -0700626 RawSender::Error CheckLocklessQueueResult(
627 const ipc_lib::LocklessQueueSender::Result &result) {
628 switch (result) {
629 case ipc_lib::LocklessQueueSender::Result::GOOD:
630 return Error::kOk;
631 case ipc_lib::LocklessQueueSender::Result::MESSAGES_SENT_TOO_FAST:
632 return Error::kMessagesSentTooFast;
633 case ipc_lib::LocklessQueueSender::Result::INVALID_REDZONE:
634 return Error::kInvalidRedzone;
635 }
636 LOG(FATAL) << "Unknown lockless queue sender result"
637 << static_cast<int>(result);
638 }
639
Austin Schuh2f8fd752020-09-01 22:38:28 -0700640 MMappedQueue lockless_queue_memory_;
Brian Silvermanfc0d2e82020-08-12 19:58:35 -0700641 ipc_lib::LocklessQueueSender lockless_queue_sender_;
642 ipc_lib::LocklessQueueWakeUpper wake_upper_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700643};
644
Alex Perrycb7da4b2019-08-28 19:35:56 -0700645// Class to manage the state for a Watcher.
Brian Silverman148d43d2020-06-07 18:19:22 -0500646class ShmWatcherState : public WatcherState {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700647 public:
Brian Silverman148d43d2020-06-07 18:19:22 -0500648 ShmWatcherState(
Austin Schuhef323c02020-09-01 14:55:28 -0700649 std::string_view shm_base, ShmEventLoop *event_loop,
650 const Channel *channel,
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800651 std::function<void(const Context &context, const void *message)> fn,
652 bool copy_data)
Brian Silverman148d43d2020-06-07 18:19:22 -0500653 : WatcherState(event_loop, channel, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800654 event_loop_(event_loop),
655 event_(this),
Austin Schuhef323c02020-09-01 14:55:28 -0700656 simple_shm_fetcher_(shm_base, event_loop, channel) {
Brian Silverman3bca5322020-08-12 19:35:29 -0700657 if (copy_data) {
Brian Silverman77162972020-08-12 19:52:40 -0700658 simple_shm_fetcher_.RetrieveData();
Brian Silverman3bca5322020-08-12 19:35:29 -0700659 }
660 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700661
Austin Schuh3054f5f2021-07-21 15:38:01 -0700662 ~ShmWatcherState() override {
663 event_loop_->CheckCurrentThread();
664 event_loop_->RemoveEvent(&event_);
665 }
Austin Schuh39788ff2019-12-01 18:22:57 -0800666
667 void Startup(EventLoop *event_loop) override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700668 event_loop_->CheckCurrentThread();
Austin Schuh7d87b672019-12-01 20:23:49 -0800669 simple_shm_fetcher_.PointAtNextQueueIndex();
Austin Schuh65493d62022-08-17 15:10:37 -0700670 CHECK(RegisterWakeup(event_loop->runtime_realtime_priority()));
Austin Schuh39788ff2019-12-01 18:22:57 -0800671 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700672
Alex Perrycb7da4b2019-08-28 19:35:56 -0700673 // Returns true if there is new data available.
Austin Schuh7d87b672019-12-01 20:23:49 -0800674 bool CheckForNewData() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700675 if (!has_new_data_) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800676 has_new_data_ = simple_shm_fetcher_.FetchNext();
Austin Schuh7d87b672019-12-01 20:23:49 -0800677
678 if (has_new_data_) {
679 event_.set_event_time(
Austin Schuhad154822019-12-27 15:45:13 -0800680 simple_shm_fetcher_.context().monotonic_event_time);
Austin Schuh7d87b672019-12-01 20:23:49 -0800681 event_loop_->AddEvent(&event_);
682 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700683 }
684
685 return has_new_data_;
686 }
687
Alex Perrycb7da4b2019-08-28 19:35:56 -0700688 // Consumes the data by calling the callback.
Austin Schuh7d87b672019-12-01 20:23:49 -0800689 void HandleEvent() {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700690 CHECK(has_new_data_);
Austin Schuh39788ff2019-12-01 18:22:57 -0800691 DoCallCallback(monotonic_clock::now, simple_shm_fetcher_.context());
Alex Perrycb7da4b2019-08-28 19:35:56 -0700692 has_new_data_ = false;
Austin Schuh7d87b672019-12-01 20:23:49 -0800693 CheckForNewData();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700694 }
695
Austin Schuh39788ff2019-12-01 18:22:57 -0800696 // Registers us to receive a signal on event reception.
Alex Perrycb7da4b2019-08-28 19:35:56 -0700697 bool RegisterWakeup(int priority) {
Austin Schuh39788ff2019-12-01 18:22:57 -0800698 return simple_shm_fetcher_.RegisterWakeup(priority);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700699 }
700
Austin Schuh39788ff2019-12-01 18:22:57 -0800701 void UnregisterWakeup() { return simple_shm_fetcher_.UnregisterWakeup(); }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700702
Brian Silvermana5450a92020-08-12 19:59:57 -0700703 absl::Span<const char> GetSharedMemory() const {
704 return simple_shm_fetcher_.GetConstSharedMemory();
Brian Silverman5120afb2020-01-31 17:44:35 -0800705 }
706
Alex Perrycb7da4b2019-08-28 19:35:56 -0700707 private:
708 bool has_new_data_ = false;
709
Austin Schuh7d87b672019-12-01 20:23:49 -0800710 ShmEventLoop *event_loop_;
Brian Silverman148d43d2020-06-07 18:19:22 -0500711 EventHandler<ShmWatcherState> event_;
Austin Schuh39788ff2019-12-01 18:22:57 -0800712 SimpleShmFetcher simple_shm_fetcher_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700713};
714
715// Adapter class to adapt a timerfd to a TimerHandler.
Brian Silverman148d43d2020-06-07 18:19:22 -0500716class ShmTimerHandler final : public TimerHandler {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700717 public:
Brian Silverman148d43d2020-06-07 18:19:22 -0500718 ShmTimerHandler(ShmEventLoop *shm_event_loop, ::std::function<void()> fn)
Austin Schuh39788ff2019-12-01 18:22:57 -0800719 : TimerHandler(shm_event_loop, std::move(fn)),
Austin Schuh7d87b672019-12-01 20:23:49 -0800720 shm_event_loop_(shm_event_loop),
721 event_(this) {
Austin Schuhcde39fd2020-02-22 20:58:24 -0800722 shm_event_loop_->epoll_.OnReadable(timerfd_.fd(), [this]() {
Austin Schuh5ca13112021-02-07 22:06:53 -0800723 // The timer may fire spuriously. HandleEvent on the event loop will
Austin Schuhcde39fd2020-02-22 20:58:24 -0800724 // call the callback if it is needed. It may also have called it when
725 // processing some other event, and the kernel decided to deliver this
726 // wakeup anyways.
727 timerfd_.Read();
728 shm_event_loop_->HandleEvent();
729 });
Alex Perrycb7da4b2019-08-28 19:35:56 -0700730 }
731
Brian Silverman148d43d2020-06-07 18:19:22 -0500732 ~ShmTimerHandler() {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700733 shm_event_loop_->CheckCurrentThread();
Austin Schuh7d87b672019-12-01 20:23:49 -0800734 Disable();
735 shm_event_loop_->epoll_.DeleteFd(timerfd_.fd());
736 }
737
738 void HandleEvent() {
Austin Schuhcde39fd2020-02-22 20:58:24 -0800739 CHECK(!event_.valid());
Brian Silvermanaf9a4d82020-10-06 15:10:58 -0700740 disabled_ = false;
Austin Schuhcde39fd2020-02-22 20:58:24 -0800741 const auto monotonic_now = Call(monotonic_clock::now, base_);
742 if (event_.valid()) {
743 // If someone called Setup inside Call, rescheduling is already taken care
744 // of. Bail.
745 return;
Austin Schuh7d87b672019-12-01 20:23:49 -0800746 }
Brian Silvermanaf9a4d82020-10-06 15:10:58 -0700747 if (disabled_) {
748 // Somebody called Disable inside Call, so we don't want to reschedule.
749 // Bail.
750 return;
751 }
Austin Schuh7d87b672019-12-01 20:23:49 -0800752
Austin Schuhcde39fd2020-02-22 20:58:24 -0800753 if (repeat_offset_ == chrono::seconds(0)) {
754 timerfd_.Disable();
755 } else {
756 // Compute how many cycles have elapsed and schedule the next iteration
757 // for the next iteration in the future.
758 const int elapsed_cycles =
759 std::max<int>(0, (monotonic_now - base_ + repeat_offset_ -
760 std::chrono::nanoseconds(1)) /
761 repeat_offset_);
762 base_ += repeat_offset_ * elapsed_cycles;
Austin Schuh7d87b672019-12-01 20:23:49 -0800763
Austin Schuhcde39fd2020-02-22 20:58:24 -0800764 // Update the heap and schedule the timerfd wakeup.
Austin Schuh7d87b672019-12-01 20:23:49 -0800765 event_.set_event_time(base_);
766 shm_event_loop_->AddEvent(&event_);
Austin Schuhcde39fd2020-02-22 20:58:24 -0800767 timerfd_.SetTime(base_, chrono::seconds(0));
Austin Schuh7d87b672019-12-01 20:23:49 -0800768 }
769 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700770
771 void Setup(monotonic_clock::time_point base,
772 monotonic_clock::duration repeat_offset) override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700773 shm_event_loop_->CheckCurrentThread();
Austin Schuh7d87b672019-12-01 20:23:49 -0800774 if (event_.valid()) {
775 shm_event_loop_->RemoveEvent(&event_);
776 }
777
Alex Perrycb7da4b2019-08-28 19:35:56 -0700778 timerfd_.SetTime(base, repeat_offset);
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800779 base_ = base;
780 repeat_offset_ = repeat_offset;
Austin Schuh7d87b672019-12-01 20:23:49 -0800781 event_.set_event_time(base_);
782 shm_event_loop_->AddEvent(&event_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700783 }
784
Austin Schuh7d87b672019-12-01 20:23:49 -0800785 void Disable() override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700786 shm_event_loop_->CheckCurrentThread();
Austin Schuh7d87b672019-12-01 20:23:49 -0800787 shm_event_loop_->RemoveEvent(&event_);
788 timerfd_.Disable();
Brian Silvermanaf9a4d82020-10-06 15:10:58 -0700789 disabled_ = true;
Austin Schuh7d87b672019-12-01 20:23:49 -0800790 }
Alex Perrycb7da4b2019-08-28 19:35:56 -0700791
792 private:
793 ShmEventLoop *shm_event_loop_;
Brian Silverman148d43d2020-06-07 18:19:22 -0500794 EventHandler<ShmTimerHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700795
Brian Silverman148d43d2020-06-07 18:19:22 -0500796 internal::TimerFd timerfd_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700797
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800798 monotonic_clock::time_point base_;
799 monotonic_clock::duration repeat_offset_;
Brian Silvermanaf9a4d82020-10-06 15:10:58 -0700800
801 // Used to track if Disable() was called during the callback, so we know not
802 // to reschedule.
803 bool disabled_ = false;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700804};
805
806// Adapter class to the timerfd and PhasedLoop.
Brian Silverman148d43d2020-06-07 18:19:22 -0500807class ShmPhasedLoopHandler final : public PhasedLoopHandler {
Alex Perrycb7da4b2019-08-28 19:35:56 -0700808 public:
Brian Silverman148d43d2020-06-07 18:19:22 -0500809 ShmPhasedLoopHandler(ShmEventLoop *shm_event_loop,
810 ::std::function<void(int)> fn,
811 const monotonic_clock::duration interval,
812 const monotonic_clock::duration offset)
813 : PhasedLoopHandler(shm_event_loop, std::move(fn), interval, offset),
Austin Schuh7d87b672019-12-01 20:23:49 -0800814 shm_event_loop_(shm_event_loop),
815 event_(this) {
816 shm_event_loop_->epoll_.OnReadable(
817 timerfd_.fd(), [this]() { shm_event_loop_->HandleEvent(); });
818 }
819
820 void HandleEvent() {
821 // The return value for read is the number of cycles that have elapsed.
822 // Because we check to see when this event *should* have happened, there are
823 // cases where Read() will return 0, when 1 cycle has actually happened.
824 // This occurs when the timer interrupt hasn't triggered yet. Therefore,
825 // ignore it. Call handles rescheduling and calculating elapsed cycles
826 // without any extra help.
827 timerfd_.Read();
828 event_.Invalidate();
829
830 Call(monotonic_clock::now, [this](monotonic_clock::time_point sleep_time) {
831 Schedule(sleep_time);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700832 });
833 }
834
Brian Silverman148d43d2020-06-07 18:19:22 -0500835 ~ShmPhasedLoopHandler() override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700836 shm_event_loop_->CheckCurrentThread();
Austin Schuh39788ff2019-12-01 18:22:57 -0800837 shm_event_loop_->epoll_.DeleteFd(timerfd_.fd());
Austin Schuh7d87b672019-12-01 20:23:49 -0800838 shm_event_loop_->RemoveEvent(&event_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700839 }
840
841 private:
Austin Schuhde8a8ff2019-11-30 15:25:36 -0800842 // Reschedules the timer.
Austin Schuh39788ff2019-12-01 18:22:57 -0800843 void Schedule(monotonic_clock::time_point sleep_time) override {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700844 shm_event_loop_->CheckCurrentThread();
Austin Schuh7d87b672019-12-01 20:23:49 -0800845 if (event_.valid()) {
846 shm_event_loop_->RemoveEvent(&event_);
847 }
848
Austin Schuh39788ff2019-12-01 18:22:57 -0800849 timerfd_.SetTime(sleep_time, ::aos::monotonic_clock::zero());
Austin Schuh7d87b672019-12-01 20:23:49 -0800850 event_.set_event_time(sleep_time);
851 shm_event_loop_->AddEvent(&event_);
Alex Perrycb7da4b2019-08-28 19:35:56 -0700852 }
853
854 ShmEventLoop *shm_event_loop_;
Brian Silverman148d43d2020-06-07 18:19:22 -0500855 EventHandler<ShmPhasedLoopHandler> event_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700856
Brian Silverman148d43d2020-06-07 18:19:22 -0500857 internal::TimerFd timerfd_;
Alex Perrycb7da4b2019-08-28 19:35:56 -0700858};
Brian Silverman148d43d2020-06-07 18:19:22 -0500859
860} // namespace shm_event_loop_internal
Alex Perrycb7da4b2019-08-28 19:35:56 -0700861
862::std::unique_ptr<RawFetcher> ShmEventLoop::MakeRawFetcher(
863 const Channel *channel) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700864 CheckCurrentThread();
Austin Schuhca4828c2019-12-28 14:21:35 -0800865 if (!configuration::ChannelIsReadableOnNode(channel, node())) {
866 LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view()
867 << "\", \"type\": \"" << channel->type()->string_view()
868 << "\" } is not able to be fetched on this node. Check your "
869 "configuration.";
Austin Schuh217a9782019-12-21 23:02:50 -0800870 }
871
Austin Schuhef323c02020-09-01 14:55:28 -0700872 return ::std::unique_ptr<RawFetcher>(
873 new ShmFetcher(shm_base_, this, channel));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700874}
875
876::std::unique_ptr<RawSender> ShmEventLoop::MakeRawSender(
877 const Channel *channel) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700878 CheckCurrentThread();
Brian Silverman0fc69932020-01-24 21:54:02 -0800879 TakeSender(channel);
Austin Schuh39788ff2019-12-01 18:22:57 -0800880
Austin Schuhef323c02020-09-01 14:55:28 -0700881 return ::std::unique_ptr<RawSender>(new ShmSender(shm_base_, this, channel));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700882}
883
884void ShmEventLoop::MakeRawWatcher(
885 const Channel *channel,
886 std::function<void(const Context &context, const void *message)> watcher) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700887 CheckCurrentThread();
Brian Silverman0fc69932020-01-24 21:54:02 -0800888 TakeWatcher(channel);
Austin Schuh217a9782019-12-21 23:02:50 -0800889
Austin Schuh39788ff2019-12-01 18:22:57 -0800890 NewWatcher(::std::unique_ptr<WatcherState>(
Austin Schuhef323c02020-09-01 14:55:28 -0700891 new ShmWatcherState(shm_base_, this, channel, std::move(watcher), true)));
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800892}
893
894void ShmEventLoop::MakeRawNoArgWatcher(
895 const Channel *channel,
896 std::function<void(const Context &context)> watcher) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700897 CheckCurrentThread();
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800898 TakeWatcher(channel);
899
Brian Silverman148d43d2020-06-07 18:19:22 -0500900 NewWatcher(::std::unique_ptr<WatcherState>(new ShmWatcherState(
Austin Schuhef323c02020-09-01 14:55:28 -0700901 shm_base_, this, channel,
Brian Silverman6b8a3c32020-03-06 11:26:14 -0800902 [watcher](const Context &context, const void *) { watcher(context); },
903 false)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700904}
905
906TimerHandler *ShmEventLoop::AddTimer(::std::function<void()> callback) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700907 CheckCurrentThread();
Austin Schuh39788ff2019-12-01 18:22:57 -0800908 return NewTimer(::std::unique_ptr<TimerHandler>(
Brian Silverman148d43d2020-06-07 18:19:22 -0500909 new ShmTimerHandler(this, ::std::move(callback))));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700910}
911
912PhasedLoopHandler *ShmEventLoop::AddPhasedLoop(
913 ::std::function<void(int)> callback,
914 const monotonic_clock::duration interval,
915 const monotonic_clock::duration offset) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700916 CheckCurrentThread();
Brian Silverman148d43d2020-06-07 18:19:22 -0500917 return NewPhasedLoop(::std::unique_ptr<PhasedLoopHandler>(
918 new ShmPhasedLoopHandler(this, ::std::move(callback), interval, offset)));
Alex Perrycb7da4b2019-08-28 19:35:56 -0700919}
920
921void ShmEventLoop::OnRun(::std::function<void()> on_run) {
Austin Schuh3054f5f2021-07-21 15:38:01 -0700922 CheckCurrentThread();
Alex Perrycb7da4b2019-08-28 19:35:56 -0700923 on_run_.push_back(::std::move(on_run));
924}
925
Austin Schuh3054f5f2021-07-21 15:38:01 -0700926void ShmEventLoop::CheckCurrentThread() const {
927 if (__builtin_expect(check_mutex_ != nullptr, false)) {
928 CHECK(check_mutex_->is_locked())
929 << ": The configured mutex is not locked while calling a "
930 "ShmEventLoop function";
931 }
932 if (__builtin_expect(!!check_tid_, false)) {
933 CHECK_EQ(syscall(SYS_gettid), *check_tid_)
934 << ": Being called from the wrong thread";
935 }
936}
937
Austin Schuh5ca13112021-02-07 22:06:53 -0800938// This is a bit tricky because watchers can generate new events at any time (as
939// long as it's in the past). We want to check the watchers at least once before
940// declaring there are no events to handle, and we want to check them again if
941// event processing takes long enough that we find an event after that point in
942// time to handle.
Austin Schuh7d87b672019-12-01 20:23:49 -0800943void ShmEventLoop::HandleEvent() {
Austin Schuh5ca13112021-02-07 22:06:53 -0800944 // Time through which we've checked for new events in watchers.
945 monotonic_clock::time_point checked_until = monotonic_clock::min_time;
946 if (!signalfd_) {
947 // Nothing to check, so we can bail out immediately once we're out of
948 // events.
949 CHECK(watchers_.empty());
950 checked_until = monotonic_clock::max_time;
Austin Schuh7d87b672019-12-01 20:23:49 -0800951 }
952
Austin Schuh5ca13112021-02-07 22:06:53 -0800953 // Loop until we run out of events to check.
Austin Schuh39788ff2019-12-01 18:22:57 -0800954 while (true) {
Austin Schuh5ca13112021-02-07 22:06:53 -0800955 // Time of the next event we know about. If this is before checked_until, we
956 // know there aren't any new events before the next one that we already know
957 // about, so no need to check the watchers.
958 monotonic_clock::time_point next_time = monotonic_clock::max_time;
959
960 if (EventCount() == 0) {
961 if (checked_until != monotonic_clock::min_time) {
962 // No events, and we've already checked the watchers at least once, so
963 // we're all done.
964 //
965 // There's a small chance that a watcher has gotten another event in
966 // between checked_until and now. If so, then the signalfd will be
967 // triggered now and we'll re-enter HandleEvent immediately. This is
968 // unlikely though, so we don't want to spend time checking all the
969 // watchers unnecessarily.
970 break;
971 }
972 } else {
973 next_time = PeekEvent()->event_time();
974 }
975 const auto now = monotonic_clock::now();
976
977 if (next_time > checked_until) {
978 // Read all of the signals, because there's no point in waking up again
979 // immediately to handle each one if we've fallen behind.
980 //
981 // This is safe before checking for new data on the watchers. If a signal
982 // is cleared here, the corresponding CheckForNewData() call below will
983 // pick it up.
984 while (true) {
985 const signalfd_siginfo result = signalfd_->Read();
986 if (result.ssi_signo == 0) {
987 break;
988 }
989 CHECK_EQ(result.ssi_signo, ipc_lib::kWakeupSignal);
990 }
991
992 // Check all the watchers for new events.
993 for (std::unique_ptr<WatcherState> &base_watcher : watchers_) {
994 ShmWatcherState *const watcher =
995 reinterpret_cast<ShmWatcherState *>(base_watcher.get());
996
997 watcher->CheckForNewData();
998 }
999 if (EventCount() == 0) {
1000 // Still no events, all done now.
1001 break;
1002 }
1003
1004 checked_until = now;
1005 // Check for any new events we found.
1006 next_time = PeekEvent()->event_time();
1007 }
1008
1009 if (next_time > now) {
Austin Schuh39788ff2019-12-01 18:22:57 -08001010 break;
1011 }
1012
Austin Schuh5ca13112021-02-07 22:06:53 -08001013 EventLoopEvent *const event = PopEvent();
Austin Schuh7d87b672019-12-01 20:23:49 -08001014 event->HandleEvent();
Austin Schuh39788ff2019-12-01 18:22:57 -08001015 }
1016}
1017
Austin Schuh32fd5a72019-12-01 22:20:26 -08001018// RAII class to mask signals.
1019class ScopedSignalMask {
1020 public:
1021 ScopedSignalMask(std::initializer_list<int> signals) {
1022 sigset_t sigset;
1023 PCHECK(sigemptyset(&sigset) == 0);
1024 for (int signal : signals) {
1025 PCHECK(sigaddset(&sigset, signal) == 0);
1026 }
1027
1028 PCHECK(sigprocmask(SIG_BLOCK, &sigset, &old_) == 0);
1029 }
1030
1031 ~ScopedSignalMask() { PCHECK(sigprocmask(SIG_SETMASK, &old_, nullptr) == 0); }
1032
1033 private:
1034 sigset_t old_;
1035};
1036
1037// Class to manage the static state associated with killing multiple event
1038// loops.
1039class SignalHandler {
1040 public:
1041 // Gets the singleton.
1042 static SignalHandler *global() {
1043 static SignalHandler loop;
1044 return &loop;
1045 }
1046
1047 // Handles the signal with the singleton.
1048 static void HandleSignal(int) { global()->DoHandleSignal(); }
1049
1050 // Registers an event loop to receive Exit() calls.
1051 void Register(ShmEventLoop *event_loop) {
1052 // Block signals while we have the mutex so we never race with the signal
1053 // handler.
1054 ScopedSignalMask mask({SIGINT, SIGHUP, SIGTERM});
1055 std::unique_lock<stl_mutex> locker(mutex_);
1056 if (event_loops_.size() == 0) {
1057 // The first caller registers the signal handler.
1058 struct sigaction new_action;
1059 sigemptyset(&new_action.sa_mask);
1060 // This makes it so that 2 control c's to a stuck process will kill it by
1061 // restoring the original signal handler.
1062 new_action.sa_flags = SA_RESETHAND;
1063 new_action.sa_handler = &HandleSignal;
1064
1065 PCHECK(sigaction(SIGINT, &new_action, &old_action_int_) == 0);
1066 PCHECK(sigaction(SIGHUP, &new_action, &old_action_hup_) == 0);
1067 PCHECK(sigaction(SIGTERM, &new_action, &old_action_term_) == 0);
1068 }
1069
1070 event_loops_.push_back(event_loop);
1071 }
1072
1073 // Unregisters an event loop to receive Exit() calls.
1074 void Unregister(ShmEventLoop *event_loop) {
1075 // Block signals while we have the mutex so we never race with the signal
1076 // handler.
1077 ScopedSignalMask mask({SIGINT, SIGHUP, SIGTERM});
1078 std::unique_lock<stl_mutex> locker(mutex_);
1079
Brian Silverman5120afb2020-01-31 17:44:35 -08001080 event_loops_.erase(
1081 std::find(event_loops_.begin(), event_loops_.end(), event_loop));
Austin Schuh32fd5a72019-12-01 22:20:26 -08001082
1083 if (event_loops_.size() == 0u) {
1084 // The last caller restores the original signal handlers.
1085 PCHECK(sigaction(SIGINT, &old_action_int_, nullptr) == 0);
1086 PCHECK(sigaction(SIGHUP, &old_action_hup_, nullptr) == 0);
1087 PCHECK(sigaction(SIGTERM, &old_action_term_, nullptr) == 0);
1088 }
1089 }
1090
1091 private:
1092 void DoHandleSignal() {
1093 // We block signals while grabbing the lock, so there should never be a
1094 // race. Confirm that this is true using trylock.
1095 CHECK(mutex_.try_lock()) << ": sigprocmask failed to block signals while "
1096 "modifing the event loop list.";
1097 for (ShmEventLoop *event_loop : event_loops_) {
1098 event_loop->Exit();
1099 }
1100 mutex_.unlock();
1101 }
1102
1103 // Mutex to protect all state.
1104 stl_mutex mutex_;
1105 std::vector<ShmEventLoop *> event_loops_;
1106 struct sigaction old_action_int_;
1107 struct sigaction old_action_hup_;
1108 struct sigaction old_action_term_;
1109};
1110
Alex Perrycb7da4b2019-08-28 19:35:56 -07001111void ShmEventLoop::Run() {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001112 CheckCurrentThread();
Austin Schuh32fd5a72019-12-01 22:20:26 -08001113 SignalHandler::global()->Register(this);
Austin Schuh39788ff2019-12-01 18:22:57 -08001114
Alex Perrycb7da4b2019-08-28 19:35:56 -07001115 if (watchers_.size() > 0) {
Austin Schuh5ca13112021-02-07 22:06:53 -08001116 signalfd_.reset(new ipc_lib::SignalFd({ipc_lib::kWakeupSignal}));
Alex Perrycb7da4b2019-08-28 19:35:56 -07001117
Austin Schuh5ca13112021-02-07 22:06:53 -08001118 epoll_.OnReadable(signalfd_->fd(), [this]() { HandleEvent(); });
Alex Perrycb7da4b2019-08-28 19:35:56 -07001119 }
1120
Austin Schuh39788ff2019-12-01 18:22:57 -08001121 MaybeScheduleTimingReports();
1122
Austin Schuh7d87b672019-12-01 20:23:49 -08001123 ReserveEvents();
1124
Tyler Chatow67ddb032020-01-12 14:30:04 -08001125 {
Austin Schuha0c41ba2020-09-10 22:59:14 -07001126 logging::ScopedLogRestorer prev_logger;
Tyler Chatow67ddb032020-01-12 14:30:04 -08001127 AosLogToFbs aos_logger;
1128 if (!skip_logger_) {
Austin Schuhad9e5eb2021-11-19 20:33:55 -08001129 aos_logger.Initialize(&name_, MakeSender<logging::LogMessageFbs>("/aos"));
Austin Schuha0c41ba2020-09-10 22:59:14 -07001130 prev_logger.Swap(aos_logger.implementation());
Tyler Chatow67ddb032020-01-12 14:30:04 -08001131 }
Alex Perrycb7da4b2019-08-28 19:35:56 -07001132
Tyler Chatow67ddb032020-01-12 14:30:04 -08001133 aos::SetCurrentThreadName(name_.substr(0, 16));
Brian Silverman6a54ff32020-04-28 16:41:39 -07001134 const cpu_set_t default_affinity = DefaultAffinity();
1135 if (!CPU_EQUAL(&affinity_, &default_affinity)) {
1136 ::aos::SetCurrentThreadAffinity(affinity_);
1137 }
Tyler Chatow67ddb032020-01-12 14:30:04 -08001138 // Now, all the callbacks are setup. Lock everything into memory and go RT.
1139 if (priority_ != 0) {
1140 ::aos::InitRT();
1141
1142 LOG(INFO) << "Setting priority to " << priority_;
1143 ::aos::SetCurrentThreadRealtimePriority(priority_);
1144 }
1145
1146 set_is_running(true);
1147
1148 // Now that we are realtime (but before the OnRun handlers run), snap the
1149 // queue index.
1150 for (::std::unique_ptr<WatcherState> &watcher : watchers_) {
1151 watcher->Startup(this);
1152 }
1153
1154 // Now that we are RT, run all the OnRun handlers.
Austin Schuha9012be2021-07-21 15:19:11 -07001155 SetTimerContext(monotonic_clock::now());
Tyler Chatow67ddb032020-01-12 14:30:04 -08001156 for (const auto &run : on_run_) {
1157 run();
1158 }
1159
1160 // And start our main event loop which runs all the timers and handles Quit.
1161 epoll_.Run();
1162
1163 // Once epoll exits, there is no useful nonrt work left to do.
1164 set_is_running(false);
1165
1166 // Nothing time or synchronization critical needs to happen after this
1167 // point. Drop RT priority.
1168 ::aos::UnsetCurrentThreadRealtimePriority();
Alex Perrycb7da4b2019-08-28 19:35:56 -07001169 }
1170
Austin Schuh39788ff2019-12-01 18:22:57 -08001171 for (::std::unique_ptr<WatcherState> &base_watcher : watchers_) {
Brian Silverman148d43d2020-06-07 18:19:22 -05001172 ShmWatcherState *watcher =
1173 reinterpret_cast<ShmWatcherState *>(base_watcher.get());
Alex Perrycb7da4b2019-08-28 19:35:56 -07001174 watcher->UnregisterWakeup();
1175 }
1176
1177 if (watchers_.size() > 0) {
Austin Schuh5ca13112021-02-07 22:06:53 -08001178 epoll_.DeleteFd(signalfd_->fd());
1179 signalfd_.reset();
Alex Perrycb7da4b2019-08-28 19:35:56 -07001180 }
Austin Schuh32fd5a72019-12-01 22:20:26 -08001181
1182 SignalHandler::global()->Unregister(this);
Austin Schuhe84c3ed2019-12-14 15:29:48 -08001183
1184 // Trigger any remaining senders or fetchers to be cleared before destroying
1185 // the event loop so the book keeping matches. Do this in the thread that
1186 // created the timing reporter.
1187 timing_report_sender_.reset();
Alex Perrycb7da4b2019-08-28 19:35:56 -07001188}
1189
1190void ShmEventLoop::Exit() { epoll_.Quit(); }
1191
Brian Silvermane1fe2512022-08-14 23:18:50 -07001192std::unique_ptr<ExitHandle> ShmEventLoop::MakeExitHandle() {
1193 return std::make_unique<ShmExitHandle>(this);
1194}
1195
Alex Perrycb7da4b2019-08-28 19:35:56 -07001196ShmEventLoop::~ShmEventLoop() {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001197 CheckCurrentThread();
Austin Schuh39788ff2019-12-01 18:22:57 -08001198 // Force everything with a registered fd with epoll to be destroyed now.
1199 timers_.clear();
1200 phased_loops_.clear();
1201 watchers_.clear();
1202
Alex Perrycb7da4b2019-08-28 19:35:56 -07001203 CHECK(!is_running()) << ": ShmEventLoop destroyed while running";
Brian Silvermane1fe2512022-08-14 23:18:50 -07001204 CHECK_EQ(0, exit_handle_count_)
1205 << ": All ExitHandles must be destroyed before the ShmEventLoop";
Alex Perrycb7da4b2019-08-28 19:35:56 -07001206}
1207
Alex Perrycb7da4b2019-08-28 19:35:56 -07001208void ShmEventLoop::SetRuntimeRealtimePriority(int priority) {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001209 CheckCurrentThread();
Alex Perrycb7da4b2019-08-28 19:35:56 -07001210 if (is_running()) {
1211 LOG(FATAL) << "Cannot set realtime priority while running.";
1212 }
1213 priority_ = priority;
1214}
1215
Brian Silverman6a54ff32020-04-28 16:41:39 -07001216void ShmEventLoop::SetRuntimeAffinity(const cpu_set_t &cpuset) {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001217 CheckCurrentThread();
Brian Silverman6a54ff32020-04-28 16:41:39 -07001218 if (is_running()) {
1219 LOG(FATAL) << "Cannot set affinity while running.";
1220 }
1221 affinity_ = cpuset;
1222}
1223
James Kuszmaul57c2baa2020-01-19 14:52:52 -08001224void ShmEventLoop::set_name(const std::string_view name) {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001225 CheckCurrentThread();
James Kuszmaul57c2baa2020-01-19 14:52:52 -08001226 name_ = std::string(name);
1227 UpdateTimingReport();
1228}
1229
Brian Silvermana5450a92020-08-12 19:59:57 -07001230absl::Span<const char> ShmEventLoop::GetWatcherSharedMemory(
1231 const Channel *channel) {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001232 CheckCurrentThread();
Brian Silverman148d43d2020-06-07 18:19:22 -05001233 ShmWatcherState *const watcher_state =
1234 static_cast<ShmWatcherState *>(GetWatcherState(channel));
Brian Silverman5120afb2020-01-31 17:44:35 -08001235 return watcher_state->GetSharedMemory();
1236}
1237
Brian Silverman4f4e0612020-08-12 19:54:41 -07001238int ShmEventLoop::NumberBuffers(const Channel *channel) {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001239 CheckCurrentThread();
Austin Schuhfb37c612022-08-11 15:24:51 -07001240 return MakeQueueConfiguration(configuration(), channel).num_messages();
Brian Silverman4f4e0612020-08-12 19:54:41 -07001241}
1242
Brian Silverman5120afb2020-01-31 17:44:35 -08001243absl::Span<char> ShmEventLoop::GetShmSenderSharedMemory(
1244 const aos::RawSender *sender) const {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001245 CheckCurrentThread();
Brian Silverman148d43d2020-06-07 18:19:22 -05001246 return static_cast<const ShmSender *>(sender)->GetSharedMemory();
Brian Silverman5120afb2020-01-31 17:44:35 -08001247}
1248
Brian Silvermana5450a92020-08-12 19:59:57 -07001249absl::Span<const char> ShmEventLoop::GetShmFetcherPrivateMemory(
Brian Silverman6d2b3592020-06-18 14:40:15 -07001250 const aos::RawFetcher *fetcher) const {
Austin Schuh3054f5f2021-07-21 15:38:01 -07001251 CheckCurrentThread();
Brian Silverman6d2b3592020-06-18 14:40:15 -07001252 return static_cast<const ShmFetcher *>(fetcher)->GetPrivateMemory();
1253}
1254
Austin Schuh3054f5f2021-07-21 15:38:01 -07001255pid_t ShmEventLoop::GetTid() {
1256 CheckCurrentThread();
1257 return syscall(SYS_gettid);
1258}
Austin Schuh39788ff2019-12-01 18:22:57 -08001259
Alex Perrycb7da4b2019-08-28 19:35:56 -07001260} // namespace aos