Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 1 | #include "aos/events/shm_event_loop.h" |
| 2 | |
| 3 | #include <sys/mman.h> |
| 4 | #include <sys/stat.h> |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 5 | #include <sys/syscall.h> |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 6 | #include <sys/types.h> |
| 7 | #include <unistd.h> |
| 8 | #include <algorithm> |
| 9 | #include <atomic> |
| 10 | #include <chrono> |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 11 | #include <iterator> |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 12 | #include <stdexcept> |
| 13 | |
| 14 | #include "aos/events/epoll.h" |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 15 | #include "aos/events/event_loop_generated.h" |
| 16 | #include "aos/events/timing_statistics.h" |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 17 | #include "aos/ipc_lib/lockless_queue.h" |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 18 | #include "aos/ipc_lib/signalfd.h" |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 19 | #include "aos/realtime.h" |
Austin Schuh | 32fd5a7 | 2019-12-01 22:20:26 -0800 | [diff] [blame] | 20 | #include "aos/stl_mutex/stl_mutex.h" |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 21 | #include "aos/util/phased_loop.h" |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 22 | #include "glog/logging.h" |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 23 | |
| 24 | DEFINE_string(shm_base, "/dev/shm/aos", |
| 25 | "Directory to place queue backing mmaped files in."); |
| 26 | DEFINE_uint32(permissions, 0770, |
| 27 | "Permissions to make shared memory files and folders."); |
| 28 | |
| 29 | namespace aos { |
| 30 | |
| 31 | std::string ShmFolder(const Channel *channel) { |
| 32 | CHECK(channel->has_name()); |
| 33 | CHECK_EQ(channel->name()->string_view()[0], '/'); |
| 34 | return FLAGS_shm_base + channel->name()->str() + "/"; |
| 35 | } |
| 36 | std::string ShmPath(const Channel *channel) { |
| 37 | CHECK(channel->has_type()); |
Austin Schuh | ad15482 | 2019-12-27 15:45:13 -0800 | [diff] [blame] | 38 | return ShmFolder(channel) + channel->type()->str() + ".v1"; |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 39 | } |
| 40 | |
| 41 | class MMapedQueue { |
| 42 | public: |
| 43 | MMapedQueue(const Channel *channel) { |
| 44 | std::string path = ShmPath(channel); |
| 45 | |
Austin Schuh | 80c7fce | 2019-12-05 20:48:43 -0800 | [diff] [blame] | 46 | config_.num_watchers = channel->num_watchers(); |
| 47 | config_.num_senders = channel->num_senders(); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 48 | config_.queue_size = 2 * channel->frequency(); |
| 49 | config_.message_data_size = channel->max_size(); |
| 50 | |
| 51 | size_ = ipc_lib::LocklessQueueMemorySize(config_); |
| 52 | |
| 53 | MkdirP(path); |
| 54 | |
| 55 | // There are 2 cases. Either the file already exists, or it does not |
| 56 | // already exist and we need to create it. Start by trying to create it. If |
| 57 | // that fails, the file has already been created and we can open it |
| 58 | // normally.. Once the file has been created it wil never be deleted. |
| 59 | fd_ = open(path.c_str(), O_RDWR | O_CREAT | O_EXCL, |
| 60 | O_CLOEXEC | FLAGS_permissions); |
| 61 | if (fd_ == -1 && errno == EEXIST) { |
| 62 | VLOG(1) << path << " already created."; |
| 63 | // File already exists. |
| 64 | fd_ = open(path.c_str(), O_RDWR, O_CLOEXEC); |
| 65 | PCHECK(fd_ != -1) << ": Failed to open " << path; |
| 66 | while (true) { |
| 67 | struct stat st; |
| 68 | PCHECK(fstat(fd_, &st) == 0); |
| 69 | if (st.st_size != 0) { |
| 70 | CHECK_EQ(static_cast<size_t>(st.st_size), size_) |
| 71 | << ": Size of " << path |
| 72 | << " doesn't match expected size of backing queue file. Did the " |
| 73 | "queue definition change?"; |
| 74 | break; |
| 75 | } else { |
| 76 | // The creating process didn't get around to it yet. Give it a bit. |
| 77 | std::this_thread::sleep_for(std::chrono::milliseconds(10)); |
| 78 | VLOG(1) << path << " is zero size, waiting"; |
| 79 | } |
| 80 | } |
| 81 | } else { |
| 82 | VLOG(1) << "Created " << path; |
| 83 | PCHECK(fd_ != -1) << ": Failed to open " << path; |
| 84 | PCHECK(ftruncate(fd_, size_) == 0); |
| 85 | } |
| 86 | |
| 87 | data_ = mmap(NULL, size_, PROT_READ | PROT_WRITE, MAP_SHARED, fd_, 0); |
| 88 | PCHECK(data_ != MAP_FAILED); |
| 89 | |
| 90 | ipc_lib::InitializeLocklessQueueMemory(memory(), config_); |
| 91 | } |
| 92 | |
| 93 | ~MMapedQueue() { |
| 94 | PCHECK(munmap(data_, size_) == 0); |
| 95 | PCHECK(close(fd_) == 0); |
| 96 | } |
| 97 | |
| 98 | ipc_lib::LocklessQueueMemory *memory() const { |
| 99 | return reinterpret_cast<ipc_lib::LocklessQueueMemory *>(data_); |
| 100 | } |
| 101 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 102 | const ipc_lib::LocklessQueueConfiguration &config() const { return config_; } |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 103 | |
| 104 | private: |
James Kuszmaul | 3ae4226 | 2019-11-08 12:33:41 -0800 | [diff] [blame] | 105 | void MkdirP(std::string_view path) { |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 106 | auto last_slash_pos = path.find_last_of("/"); |
| 107 | |
James Kuszmaul | 3ae4226 | 2019-11-08 12:33:41 -0800 | [diff] [blame] | 108 | std::string folder(last_slash_pos == std::string_view::npos |
| 109 | ? std::string_view("") |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 110 | : path.substr(0, last_slash_pos)); |
Austin Schuh | 8ec7618 | 2019-12-23 16:28:00 -0800 | [diff] [blame] | 111 | if (folder.empty()) return; |
| 112 | MkdirP(folder); |
| 113 | VLOG(1) << "Creating " << folder; |
| 114 | const int result = mkdir(folder.c_str(), FLAGS_permissions); |
| 115 | if (result == -1 && errno == EEXIST) { |
| 116 | VLOG(1) << "Already exists"; |
| 117 | return; |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 118 | } |
Austin Schuh | 8ec7618 | 2019-12-23 16:28:00 -0800 | [diff] [blame] | 119 | PCHECK(result == 0) << ": Error creating " << folder; |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 120 | } |
| 121 | |
| 122 | ipc_lib::LocklessQueueConfiguration config_; |
| 123 | |
| 124 | int fd_; |
| 125 | |
| 126 | size_t size_; |
| 127 | void *data_; |
| 128 | }; |
| 129 | |
Austin Schuh | 217a978 | 2019-12-21 23:02:50 -0800 | [diff] [blame] | 130 | namespace { |
| 131 | |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 132 | // Returns the portion of the path after the last /. |
James Kuszmaul | 3ae4226 | 2019-11-08 12:33:41 -0800 | [diff] [blame] | 133 | std::string_view Filename(std::string_view path) { |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 134 | auto last_slash_pos = path.find_last_of("/"); |
| 135 | |
James Kuszmaul | 3ae4226 | 2019-11-08 12:33:41 -0800 | [diff] [blame] | 136 | return last_slash_pos == std::string_view::npos |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 137 | ? path |
| 138 | : path.substr(last_slash_pos + 1, path.size()); |
| 139 | } |
| 140 | |
Austin Schuh | 217a978 | 2019-12-21 23:02:50 -0800 | [diff] [blame] | 141 | const Node *MaybeMyNode(const Configuration *configuration) { |
| 142 | if (!configuration->has_nodes()) { |
| 143 | return nullptr; |
| 144 | } |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 145 | |
Austin Schuh | 217a978 | 2019-12-21 23:02:50 -0800 | [diff] [blame] | 146 | return configuration::GetMyNode(configuration); |
| 147 | } |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 148 | |
| 149 | namespace chrono = ::std::chrono; |
| 150 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 151 | } // namespace |
| 152 | |
Austin Schuh | 217a978 | 2019-12-21 23:02:50 -0800 | [diff] [blame] | 153 | ShmEventLoop::ShmEventLoop(const Configuration *configuration) |
| 154 | : EventLoop(configuration), |
| 155 | name_(Filename(program_invocation_name)), |
| 156 | node_(MaybeMyNode(configuration)) {} |
| 157 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 158 | namespace internal { |
| 159 | |
| 160 | class SimpleShmFetcher { |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 161 | public: |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 162 | explicit SimpleShmFetcher(const Channel *channel) |
| 163 | : lockless_queue_memory_(channel), |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 164 | lockless_queue_(lockless_queue_memory_.memory(), |
| 165 | lockless_queue_memory_.config()), |
| 166 | data_storage_(static_cast<AlignedChar *>(aligned_alloc( |
| 167 | alignof(AlignedChar), channel->max_size())), |
| 168 | &free) { |
| 169 | context_.data = nullptr; |
| 170 | // Point the queue index at the next index to read starting now. This |
| 171 | // makes it such that FetchNext will read the next message sent after |
| 172 | // the fetcher is created. |
| 173 | PointAtNextQueueIndex(); |
| 174 | } |
| 175 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 176 | ~SimpleShmFetcher() {} |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 177 | |
| 178 | // Points the next message to fetch at the queue index which will be |
| 179 | // populated next. |
| 180 | void PointAtNextQueueIndex() { |
| 181 | actual_queue_index_ = lockless_queue_.LatestQueueIndex(); |
| 182 | if (!actual_queue_index_.valid()) { |
| 183 | // Nothing in the queue. The next element will show up at the 0th |
| 184 | // index in the queue. |
| 185 | actual_queue_index_ = |
| 186 | ipc_lib::QueueIndex::Zero(lockless_queue_.queue_size()); |
| 187 | } else { |
| 188 | actual_queue_index_ = actual_queue_index_.Increment(); |
| 189 | } |
| 190 | } |
| 191 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 192 | bool FetchNext() { |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 193 | // TODO(austin): Get behind and make sure it dies both here and with |
| 194 | // Fetch. |
| 195 | ipc_lib::LocklessQueue::ReadResult read_result = lockless_queue_.Read( |
Austin Schuh | ad15482 | 2019-12-27 15:45:13 -0800 | [diff] [blame] | 196 | actual_queue_index_.index(), &context_.monotonic_event_time, |
| 197 | &context_.realtime_event_time, &context_.monotonic_remote_time, |
| 198 | &context_.realtime_remote_time, &context_.remote_queue_index, |
| 199 | &context_.size, reinterpret_cast<char *>(data_storage_.get())); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 200 | if (read_result == ipc_lib::LocklessQueue::ReadResult::GOOD) { |
| 201 | context_.queue_index = actual_queue_index_.index(); |
Austin Schuh | ad15482 | 2019-12-27 15:45:13 -0800 | [diff] [blame] | 202 | if (context_.remote_queue_index == 0xffffffffu) { |
| 203 | context_.remote_queue_index = context_.queue_index; |
| 204 | } |
| 205 | if (context_.monotonic_remote_time == aos::monotonic_clock::min_time) { |
| 206 | context_.monotonic_remote_time = context_.monotonic_event_time; |
| 207 | } |
| 208 | if (context_.realtime_remote_time == aos::realtime_clock::min_time) { |
| 209 | context_.realtime_remote_time = context_.realtime_event_time; |
| 210 | } |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 211 | context_.data = reinterpret_cast<char *>(data_storage_.get()) + |
| 212 | lockless_queue_.message_data_size() - context_.size; |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 213 | actual_queue_index_ = actual_queue_index_.Increment(); |
| 214 | } |
| 215 | |
| 216 | // Make sure the data wasn't modified while we were reading it. This |
| 217 | // can only happen if you are reading the last message *while* it is |
| 218 | // being written to, which means you are pretty far behind. |
| 219 | CHECK(read_result != ipc_lib::LocklessQueue::ReadResult::OVERWROTE) |
| 220 | << ": Got behind while reading and the last message was modified " |
| 221 | "out " |
| 222 | "from under us while we were reading it. Don't get so far " |
| 223 | "behind."; |
| 224 | |
| 225 | CHECK(read_result != ipc_lib::LocklessQueue::ReadResult::TOO_OLD) |
| 226 | << ": The next message is no longer available."; |
| 227 | return read_result == ipc_lib::LocklessQueue::ReadResult::GOOD; |
| 228 | } |
| 229 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 230 | bool Fetch() { |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 231 | const ipc_lib::QueueIndex queue_index = lockless_queue_.LatestQueueIndex(); |
| 232 | // actual_queue_index_ is only meaningful if it was set by Fetch or |
| 233 | // FetchNext. This happens when valid_data_ has been set. So, only |
| 234 | // skip checking if valid_data_ is true. |
| 235 | // |
| 236 | // Also, if the latest queue index is invalid, we are empty. So there |
| 237 | // is nothing to fetch. |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 238 | if ((context_.data != nullptr && |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 239 | queue_index == actual_queue_index_.DecrementBy(1u)) || |
| 240 | !queue_index.valid()) { |
| 241 | return false; |
| 242 | } |
| 243 | |
Austin Schuh | ad15482 | 2019-12-27 15:45:13 -0800 | [diff] [blame] | 244 | ipc_lib::LocklessQueue::ReadResult read_result = lockless_queue_.Read( |
| 245 | queue_index.index(), &context_.monotonic_event_time, |
| 246 | &context_.realtime_event_time, &context_.monotonic_remote_time, |
| 247 | &context_.realtime_remote_time, &context_.remote_queue_index, |
| 248 | &context_.size, reinterpret_cast<char *>(data_storage_.get())); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 249 | if (read_result == ipc_lib::LocklessQueue::ReadResult::GOOD) { |
| 250 | context_.queue_index = queue_index.index(); |
Austin Schuh | ad15482 | 2019-12-27 15:45:13 -0800 | [diff] [blame] | 251 | if (context_.remote_queue_index == 0xffffffffu) { |
| 252 | context_.remote_queue_index = context_.queue_index; |
| 253 | } |
| 254 | if (context_.monotonic_remote_time == aos::monotonic_clock::min_time) { |
| 255 | context_.monotonic_remote_time = context_.monotonic_event_time; |
| 256 | } |
| 257 | if (context_.realtime_remote_time == aos::realtime_clock::min_time) { |
| 258 | context_.realtime_remote_time = context_.realtime_event_time; |
| 259 | } |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 260 | context_.data = reinterpret_cast<char *>(data_storage_.get()) + |
| 261 | lockless_queue_.message_data_size() - context_.size; |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 262 | actual_queue_index_ = queue_index.Increment(); |
| 263 | } |
| 264 | |
| 265 | // Make sure the data wasn't modified while we were reading it. This |
| 266 | // can only happen if you are reading the last message *while* it is |
| 267 | // being written to, which means you are pretty far behind. |
| 268 | CHECK(read_result != ipc_lib::LocklessQueue::ReadResult::OVERWROTE) |
| 269 | << ": Got behind while reading and the last message was modified " |
| 270 | "out " |
| 271 | "from under us while we were reading it. Don't get so far " |
| 272 | "behind."; |
| 273 | |
| 274 | CHECK(read_result != ipc_lib::LocklessQueue::ReadResult::NOTHING_NEW) |
| 275 | << ": Queue index went backwards. This should never happen."; |
| 276 | |
| 277 | // We fell behind between when we read the index and read the value. |
| 278 | // This isn't worth recovering from since this means we went to sleep |
| 279 | // for a long time in the middle of this function. |
| 280 | CHECK(read_result != ipc_lib::LocklessQueue::ReadResult::TOO_OLD) |
| 281 | << ": The next message is no longer available."; |
| 282 | return read_result == ipc_lib::LocklessQueue::ReadResult::GOOD; |
| 283 | } |
| 284 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 285 | Context context() const { return context_; } |
| 286 | |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 287 | bool RegisterWakeup(int priority) { |
| 288 | return lockless_queue_.RegisterWakeup(priority); |
| 289 | } |
| 290 | |
| 291 | void UnregisterWakeup() { lockless_queue_.UnregisterWakeup(); } |
| 292 | |
| 293 | private: |
| 294 | MMapedQueue lockless_queue_memory_; |
| 295 | ipc_lib::LocklessQueue lockless_queue_; |
| 296 | |
| 297 | ipc_lib::QueueIndex actual_queue_index_ = |
| 298 | ipc_lib::LocklessQueue::empty_queue_index(); |
| 299 | |
| 300 | struct AlignedChar { |
| 301 | alignas(32) char data; |
| 302 | }; |
| 303 | |
| 304 | std::unique_ptr<AlignedChar, decltype(&free)> data_storage_; |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 305 | |
| 306 | Context context_; |
| 307 | }; |
| 308 | |
| 309 | class ShmFetcher : public RawFetcher { |
| 310 | public: |
| 311 | explicit ShmFetcher(EventLoop *event_loop, const Channel *channel) |
| 312 | : RawFetcher(event_loop, channel), simple_shm_fetcher_(channel) {} |
| 313 | |
| 314 | ~ShmFetcher() { context_.data = nullptr; } |
| 315 | |
| 316 | std::pair<bool, monotonic_clock::time_point> DoFetchNext() override { |
| 317 | if (simple_shm_fetcher_.FetchNext()) { |
| 318 | context_ = simple_shm_fetcher_.context(); |
| 319 | return std::make_pair(true, monotonic_clock::now()); |
| 320 | } |
| 321 | return std::make_pair(false, monotonic_clock::min_time); |
| 322 | } |
| 323 | |
| 324 | std::pair<bool, monotonic_clock::time_point> DoFetch() override { |
| 325 | if (simple_shm_fetcher_.Fetch()) { |
| 326 | context_ = simple_shm_fetcher_.context(); |
| 327 | return std::make_pair(true, monotonic_clock::now()); |
| 328 | } |
| 329 | return std::make_pair(false, monotonic_clock::min_time); |
| 330 | } |
| 331 | |
| 332 | private: |
| 333 | SimpleShmFetcher simple_shm_fetcher_; |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 334 | }; |
| 335 | |
| 336 | class ShmSender : public RawSender { |
| 337 | public: |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 338 | explicit ShmSender(EventLoop *event_loop, const Channel *channel) |
| 339 | : RawSender(event_loop, channel), |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 340 | lockless_queue_memory_(channel), |
| 341 | lockless_queue_(lockless_queue_memory_.memory(), |
| 342 | lockless_queue_memory_.config()), |
| 343 | lockless_queue_sender_(lockless_queue_.MakeSender()) {} |
| 344 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 345 | ~ShmSender() override {} |
| 346 | |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 347 | void *data() override { return lockless_queue_sender_.Data(); } |
| 348 | size_t size() override { return lockless_queue_sender_.size(); } |
Austin Schuh | ad15482 | 2019-12-27 15:45:13 -0800 | [diff] [blame] | 349 | bool DoSend(size_t length, |
| 350 | aos::monotonic_clock::time_point monotonic_remote_time, |
| 351 | aos::realtime_clock::time_point realtime_remote_time, |
| 352 | uint32_t remote_queue_index) override { |
| 353 | lockless_queue_sender_.Send( |
| 354 | length, monotonic_remote_time, realtime_remote_time, remote_queue_index, |
| 355 | &monotonic_sent_time_, &realtime_sent_time_, &sent_queue_index_); |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 356 | lockless_queue_.Wakeup(event_loop()->priority()); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 357 | return true; |
| 358 | } |
| 359 | |
Austin Schuh | ad15482 | 2019-12-27 15:45:13 -0800 | [diff] [blame] | 360 | bool DoSend(const void *msg, size_t length, |
| 361 | aos::monotonic_clock::time_point monotonic_remote_time, |
| 362 | aos::realtime_clock::time_point realtime_remote_time, |
| 363 | uint32_t remote_queue_index) override { |
| 364 | lockless_queue_sender_.Send(reinterpret_cast<const char *>(msg), length, |
| 365 | monotonic_remote_time, realtime_remote_time, |
| 366 | remote_queue_index, &monotonic_sent_time_, |
| 367 | &realtime_sent_time_, &sent_queue_index_); |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 368 | lockless_queue_.Wakeup(event_loop()->priority()); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 369 | // TODO(austin): Return an error if we send too fast. |
| 370 | return true; |
| 371 | } |
| 372 | |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 373 | private: |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 374 | MMapedQueue lockless_queue_memory_; |
| 375 | ipc_lib::LocklessQueue lockless_queue_; |
| 376 | ipc_lib::LocklessQueue::Sender lockless_queue_sender_; |
| 377 | }; |
| 378 | |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 379 | // Class to manage the state for a Watcher. |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 380 | class WatcherState : public aos::WatcherState { |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 381 | public: |
| 382 | WatcherState( |
Austin Schuh | 7d87b67 | 2019-12-01 20:23:49 -0800 | [diff] [blame] | 383 | ShmEventLoop *event_loop, const Channel *channel, |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 384 | std::function<void(const Context &context, const void *message)> fn) |
| 385 | : aos::WatcherState(event_loop, channel, std::move(fn)), |
Austin Schuh | 7d87b67 | 2019-12-01 20:23:49 -0800 | [diff] [blame] | 386 | event_loop_(event_loop), |
| 387 | event_(this), |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 388 | simple_shm_fetcher_(channel) {} |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 389 | |
Austin Schuh | 7d87b67 | 2019-12-01 20:23:49 -0800 | [diff] [blame] | 390 | ~WatcherState() override { event_loop_->RemoveEvent(&event_); } |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 391 | |
| 392 | void Startup(EventLoop *event_loop) override { |
Austin Schuh | 7d87b67 | 2019-12-01 20:23:49 -0800 | [diff] [blame] | 393 | simple_shm_fetcher_.PointAtNextQueueIndex(); |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 394 | CHECK(RegisterWakeup(event_loop->priority())); |
| 395 | } |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 396 | |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 397 | // Returns true if there is new data available. |
Austin Schuh | 7d87b67 | 2019-12-01 20:23:49 -0800 | [diff] [blame] | 398 | bool CheckForNewData() { |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 399 | if (!has_new_data_) { |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 400 | has_new_data_ = simple_shm_fetcher_.FetchNext(); |
Austin Schuh | 7d87b67 | 2019-12-01 20:23:49 -0800 | [diff] [blame] | 401 | |
| 402 | if (has_new_data_) { |
| 403 | event_.set_event_time( |
Austin Schuh | ad15482 | 2019-12-27 15:45:13 -0800 | [diff] [blame] | 404 | simple_shm_fetcher_.context().monotonic_event_time); |
Austin Schuh | 7d87b67 | 2019-12-01 20:23:49 -0800 | [diff] [blame] | 405 | event_loop_->AddEvent(&event_); |
| 406 | } |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 407 | } |
| 408 | |
| 409 | return has_new_data_; |
| 410 | } |
| 411 | |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 412 | // Consumes the data by calling the callback. |
Austin Schuh | 7d87b67 | 2019-12-01 20:23:49 -0800 | [diff] [blame] | 413 | void HandleEvent() { |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 414 | CHECK(has_new_data_); |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 415 | DoCallCallback(monotonic_clock::now, simple_shm_fetcher_.context()); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 416 | has_new_data_ = false; |
Austin Schuh | 7d87b67 | 2019-12-01 20:23:49 -0800 | [diff] [blame] | 417 | CheckForNewData(); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 418 | } |
| 419 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 420 | // Registers us to receive a signal on event reception. |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 421 | bool RegisterWakeup(int priority) { |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 422 | return simple_shm_fetcher_.RegisterWakeup(priority); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 423 | } |
| 424 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 425 | void UnregisterWakeup() { return simple_shm_fetcher_.UnregisterWakeup(); } |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 426 | |
| 427 | private: |
| 428 | bool has_new_data_ = false; |
| 429 | |
Austin Schuh | 7d87b67 | 2019-12-01 20:23:49 -0800 | [diff] [blame] | 430 | ShmEventLoop *event_loop_; |
| 431 | EventHandler<WatcherState> event_; |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 432 | SimpleShmFetcher simple_shm_fetcher_; |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 433 | }; |
| 434 | |
| 435 | // Adapter class to adapt a timerfd to a TimerHandler. |
Austin Schuh | 7d87b67 | 2019-12-01 20:23:49 -0800 | [diff] [blame] | 436 | class TimerHandlerState final : public TimerHandler { |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 437 | public: |
| 438 | TimerHandlerState(ShmEventLoop *shm_event_loop, ::std::function<void()> fn) |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 439 | : TimerHandler(shm_event_loop, std::move(fn)), |
Austin Schuh | 7d87b67 | 2019-12-01 20:23:49 -0800 | [diff] [blame] | 440 | shm_event_loop_(shm_event_loop), |
| 441 | event_(this) { |
| 442 | shm_event_loop_->epoll_.OnReadable( |
| 443 | timerfd_.fd(), [this]() { shm_event_loop_->HandleEvent(); }); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 444 | } |
| 445 | |
Austin Schuh | 7d87b67 | 2019-12-01 20:23:49 -0800 | [diff] [blame] | 446 | ~TimerHandlerState() { |
| 447 | Disable(); |
| 448 | shm_event_loop_->epoll_.DeleteFd(timerfd_.fd()); |
| 449 | } |
| 450 | |
| 451 | void HandleEvent() { |
| 452 | uint64_t elapsed_cycles = timerfd_.Read(); |
| 453 | if (elapsed_cycles == 0u) { |
| 454 | // We got called before the timer interrupt could happen, but because we |
| 455 | // are checking the time, we got called on time. Push the timer out by 1 |
| 456 | // cycle. |
| 457 | elapsed_cycles = 1u; |
| 458 | timerfd_.SetTime(base_ + repeat_offset_, repeat_offset_); |
| 459 | } |
| 460 | |
| 461 | Call(monotonic_clock::now, base_); |
| 462 | |
| 463 | base_ += repeat_offset_ * elapsed_cycles; |
| 464 | |
| 465 | if (repeat_offset_ != chrono::seconds(0)) { |
| 466 | event_.set_event_time(base_); |
| 467 | shm_event_loop_->AddEvent(&event_); |
| 468 | } |
| 469 | } |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 470 | |
| 471 | void Setup(monotonic_clock::time_point base, |
| 472 | monotonic_clock::duration repeat_offset) override { |
Austin Schuh | 7d87b67 | 2019-12-01 20:23:49 -0800 | [diff] [blame] | 473 | if (event_.valid()) { |
| 474 | shm_event_loop_->RemoveEvent(&event_); |
| 475 | } |
| 476 | |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 477 | timerfd_.SetTime(base, repeat_offset); |
Austin Schuh | de8a8ff | 2019-11-30 15:25:36 -0800 | [diff] [blame] | 478 | base_ = base; |
| 479 | repeat_offset_ = repeat_offset; |
Austin Schuh | 7d87b67 | 2019-12-01 20:23:49 -0800 | [diff] [blame] | 480 | event_.set_event_time(base_); |
| 481 | shm_event_loop_->AddEvent(&event_); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 482 | } |
| 483 | |
Austin Schuh | 7d87b67 | 2019-12-01 20:23:49 -0800 | [diff] [blame] | 484 | void Disable() override { |
| 485 | shm_event_loop_->RemoveEvent(&event_); |
| 486 | timerfd_.Disable(); |
| 487 | } |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 488 | |
| 489 | private: |
| 490 | ShmEventLoop *shm_event_loop_; |
Austin Schuh | 7d87b67 | 2019-12-01 20:23:49 -0800 | [diff] [blame] | 491 | EventHandler<TimerHandlerState> event_; |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 492 | |
| 493 | TimerFd timerfd_; |
| 494 | |
Austin Schuh | de8a8ff | 2019-11-30 15:25:36 -0800 | [diff] [blame] | 495 | monotonic_clock::time_point base_; |
| 496 | monotonic_clock::duration repeat_offset_; |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 497 | }; |
| 498 | |
| 499 | // Adapter class to the timerfd and PhasedLoop. |
Austin Schuh | 7d87b67 | 2019-12-01 20:23:49 -0800 | [diff] [blame] | 500 | class PhasedLoopHandler final : public ::aos::PhasedLoopHandler { |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 501 | public: |
| 502 | PhasedLoopHandler(ShmEventLoop *shm_event_loop, ::std::function<void(int)> fn, |
| 503 | const monotonic_clock::duration interval, |
| 504 | const monotonic_clock::duration offset) |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 505 | : aos::PhasedLoopHandler(shm_event_loop, std::move(fn), interval, offset), |
Austin Schuh | 7d87b67 | 2019-12-01 20:23:49 -0800 | [diff] [blame] | 506 | shm_event_loop_(shm_event_loop), |
| 507 | event_(this) { |
| 508 | shm_event_loop_->epoll_.OnReadable( |
| 509 | timerfd_.fd(), [this]() { shm_event_loop_->HandleEvent(); }); |
| 510 | } |
| 511 | |
| 512 | void HandleEvent() { |
| 513 | // The return value for read is the number of cycles that have elapsed. |
| 514 | // Because we check to see when this event *should* have happened, there are |
| 515 | // cases where Read() will return 0, when 1 cycle has actually happened. |
| 516 | // This occurs when the timer interrupt hasn't triggered yet. Therefore, |
| 517 | // ignore it. Call handles rescheduling and calculating elapsed cycles |
| 518 | // without any extra help. |
| 519 | timerfd_.Read(); |
| 520 | event_.Invalidate(); |
| 521 | |
| 522 | Call(monotonic_clock::now, [this](monotonic_clock::time_point sleep_time) { |
| 523 | Schedule(sleep_time); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 524 | }); |
| 525 | } |
| 526 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 527 | ~PhasedLoopHandler() override { |
| 528 | shm_event_loop_->epoll_.DeleteFd(timerfd_.fd()); |
Austin Schuh | 7d87b67 | 2019-12-01 20:23:49 -0800 | [diff] [blame] | 529 | shm_event_loop_->RemoveEvent(&event_); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 530 | } |
| 531 | |
| 532 | private: |
Austin Schuh | de8a8ff | 2019-11-30 15:25:36 -0800 | [diff] [blame] | 533 | // Reschedules the timer. |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 534 | void Schedule(monotonic_clock::time_point sleep_time) override { |
Austin Schuh | 7d87b67 | 2019-12-01 20:23:49 -0800 | [diff] [blame] | 535 | if (event_.valid()) { |
| 536 | shm_event_loop_->RemoveEvent(&event_); |
| 537 | } |
| 538 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 539 | timerfd_.SetTime(sleep_time, ::aos::monotonic_clock::zero()); |
Austin Schuh | 7d87b67 | 2019-12-01 20:23:49 -0800 | [diff] [blame] | 540 | event_.set_event_time(sleep_time); |
| 541 | shm_event_loop_->AddEvent(&event_); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 542 | } |
| 543 | |
| 544 | ShmEventLoop *shm_event_loop_; |
Austin Schuh | 7d87b67 | 2019-12-01 20:23:49 -0800 | [diff] [blame] | 545 | EventHandler<PhasedLoopHandler> event_; |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 546 | |
| 547 | TimerFd timerfd_; |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 548 | }; |
| 549 | } // namespace internal |
| 550 | |
| 551 | ::std::unique_ptr<RawFetcher> ShmEventLoop::MakeRawFetcher( |
| 552 | const Channel *channel) { |
Austin Schuh | ca4828c | 2019-12-28 14:21:35 -0800 | [diff] [blame^] | 553 | if (!configuration::ChannelIsReadableOnNode(channel, node())) { |
| 554 | LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view() |
| 555 | << "\", \"type\": \"" << channel->type()->string_view() |
| 556 | << "\" } is not able to be fetched on this node. Check your " |
| 557 | "configuration."; |
Austin Schuh | 217a978 | 2019-12-21 23:02:50 -0800 | [diff] [blame] | 558 | } |
| 559 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 560 | return ::std::unique_ptr<RawFetcher>(new internal::ShmFetcher(this, channel)); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 561 | } |
| 562 | |
| 563 | ::std::unique_ptr<RawSender> ShmEventLoop::MakeRawSender( |
| 564 | const Channel *channel) { |
| 565 | Take(channel); |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 566 | |
| 567 | return ::std::unique_ptr<RawSender>(new internal::ShmSender(this, channel)); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 568 | } |
| 569 | |
| 570 | void ShmEventLoop::MakeRawWatcher( |
| 571 | const Channel *channel, |
| 572 | std::function<void(const Context &context, const void *message)> watcher) { |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 573 | Take(channel); |
| 574 | |
Austin Schuh | ca4828c | 2019-12-28 14:21:35 -0800 | [diff] [blame^] | 575 | if (!configuration::ChannelIsReadableOnNode(channel, node())) { |
| 576 | LOG(FATAL) << "Channel { \"name\": \"" << channel->name()->string_view() |
| 577 | << "\", \"type\": \"" << channel->type()->string_view() |
| 578 | << "\" } is not able to be watched on this node. Check your " |
| 579 | "configuration."; |
Austin Schuh | 217a978 | 2019-12-21 23:02:50 -0800 | [diff] [blame] | 580 | } |
| 581 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 582 | NewWatcher(::std::unique_ptr<WatcherState>( |
| 583 | new internal::WatcherState(this, channel, std::move(watcher)))); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 584 | } |
| 585 | |
| 586 | TimerHandler *ShmEventLoop::AddTimer(::std::function<void()> callback) { |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 587 | return NewTimer(::std::unique_ptr<TimerHandler>( |
| 588 | new internal::TimerHandlerState(this, ::std::move(callback)))); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 589 | } |
| 590 | |
| 591 | PhasedLoopHandler *ShmEventLoop::AddPhasedLoop( |
| 592 | ::std::function<void(int)> callback, |
| 593 | const monotonic_clock::duration interval, |
| 594 | const monotonic_clock::duration offset) { |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 595 | return NewPhasedLoop( |
| 596 | ::std::unique_ptr<PhasedLoopHandler>(new internal::PhasedLoopHandler( |
| 597 | this, ::std::move(callback), interval, offset))); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 598 | } |
| 599 | |
| 600 | void ShmEventLoop::OnRun(::std::function<void()> on_run) { |
| 601 | on_run_.push_back(::std::move(on_run)); |
| 602 | } |
| 603 | |
Austin Schuh | 7d87b67 | 2019-12-01 20:23:49 -0800 | [diff] [blame] | 604 | void ShmEventLoop::HandleEvent() { |
| 605 | // Update all the times for handlers. |
| 606 | for (::std::unique_ptr<WatcherState> &base_watcher : watchers_) { |
| 607 | internal::WatcherState *watcher = |
| 608 | reinterpret_cast<internal::WatcherState *>(base_watcher.get()); |
| 609 | |
| 610 | watcher->CheckForNewData(); |
| 611 | } |
| 612 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 613 | while (true) { |
Austin Schuh | 7d87b67 | 2019-12-01 20:23:49 -0800 | [diff] [blame] | 614 | if (EventCount() == 0 || |
| 615 | PeekEvent()->event_time() > monotonic_clock::now()) { |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 616 | break; |
| 617 | } |
| 618 | |
Austin Schuh | 7d87b67 | 2019-12-01 20:23:49 -0800 | [diff] [blame] | 619 | EventLoopEvent *event = PopEvent(); |
| 620 | event->HandleEvent(); |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 621 | } |
| 622 | } |
| 623 | |
Austin Schuh | 32fd5a7 | 2019-12-01 22:20:26 -0800 | [diff] [blame] | 624 | // RAII class to mask signals. |
| 625 | class ScopedSignalMask { |
| 626 | public: |
| 627 | ScopedSignalMask(std::initializer_list<int> signals) { |
| 628 | sigset_t sigset; |
| 629 | PCHECK(sigemptyset(&sigset) == 0); |
| 630 | for (int signal : signals) { |
| 631 | PCHECK(sigaddset(&sigset, signal) == 0); |
| 632 | } |
| 633 | |
| 634 | PCHECK(sigprocmask(SIG_BLOCK, &sigset, &old_) == 0); |
| 635 | } |
| 636 | |
| 637 | ~ScopedSignalMask() { PCHECK(sigprocmask(SIG_SETMASK, &old_, nullptr) == 0); } |
| 638 | |
| 639 | private: |
| 640 | sigset_t old_; |
| 641 | }; |
| 642 | |
| 643 | // Class to manage the static state associated with killing multiple event |
| 644 | // loops. |
| 645 | class SignalHandler { |
| 646 | public: |
| 647 | // Gets the singleton. |
| 648 | static SignalHandler *global() { |
| 649 | static SignalHandler loop; |
| 650 | return &loop; |
| 651 | } |
| 652 | |
| 653 | // Handles the signal with the singleton. |
| 654 | static void HandleSignal(int) { global()->DoHandleSignal(); } |
| 655 | |
| 656 | // Registers an event loop to receive Exit() calls. |
| 657 | void Register(ShmEventLoop *event_loop) { |
| 658 | // Block signals while we have the mutex so we never race with the signal |
| 659 | // handler. |
| 660 | ScopedSignalMask mask({SIGINT, SIGHUP, SIGTERM}); |
| 661 | std::unique_lock<stl_mutex> locker(mutex_); |
| 662 | if (event_loops_.size() == 0) { |
| 663 | // The first caller registers the signal handler. |
| 664 | struct sigaction new_action; |
| 665 | sigemptyset(&new_action.sa_mask); |
| 666 | // This makes it so that 2 control c's to a stuck process will kill it by |
| 667 | // restoring the original signal handler. |
| 668 | new_action.sa_flags = SA_RESETHAND; |
| 669 | new_action.sa_handler = &HandleSignal; |
| 670 | |
| 671 | PCHECK(sigaction(SIGINT, &new_action, &old_action_int_) == 0); |
| 672 | PCHECK(sigaction(SIGHUP, &new_action, &old_action_hup_) == 0); |
| 673 | PCHECK(sigaction(SIGTERM, &new_action, &old_action_term_) == 0); |
| 674 | } |
| 675 | |
| 676 | event_loops_.push_back(event_loop); |
| 677 | } |
| 678 | |
| 679 | // Unregisters an event loop to receive Exit() calls. |
| 680 | void Unregister(ShmEventLoop *event_loop) { |
| 681 | // Block signals while we have the mutex so we never race with the signal |
| 682 | // handler. |
| 683 | ScopedSignalMask mask({SIGINT, SIGHUP, SIGTERM}); |
| 684 | std::unique_lock<stl_mutex> locker(mutex_); |
| 685 | |
| 686 | event_loops_.erase(std::find(event_loops_.begin(), event_loops_.end(), event_loop)); |
| 687 | |
| 688 | if (event_loops_.size() == 0u) { |
| 689 | // The last caller restores the original signal handlers. |
| 690 | PCHECK(sigaction(SIGINT, &old_action_int_, nullptr) == 0); |
| 691 | PCHECK(sigaction(SIGHUP, &old_action_hup_, nullptr) == 0); |
| 692 | PCHECK(sigaction(SIGTERM, &old_action_term_, nullptr) == 0); |
| 693 | } |
| 694 | } |
| 695 | |
| 696 | private: |
| 697 | void DoHandleSignal() { |
| 698 | // We block signals while grabbing the lock, so there should never be a |
| 699 | // race. Confirm that this is true using trylock. |
| 700 | CHECK(mutex_.try_lock()) << ": sigprocmask failed to block signals while " |
| 701 | "modifing the event loop list."; |
| 702 | for (ShmEventLoop *event_loop : event_loops_) { |
| 703 | event_loop->Exit(); |
| 704 | } |
| 705 | mutex_.unlock(); |
| 706 | } |
| 707 | |
| 708 | // Mutex to protect all state. |
| 709 | stl_mutex mutex_; |
| 710 | std::vector<ShmEventLoop *> event_loops_; |
| 711 | struct sigaction old_action_int_; |
| 712 | struct sigaction old_action_hup_; |
| 713 | struct sigaction old_action_term_; |
| 714 | }; |
| 715 | |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 716 | void ShmEventLoop::Run() { |
Austin Schuh | 32fd5a7 | 2019-12-01 22:20:26 -0800 | [diff] [blame] | 717 | SignalHandler::global()->Register(this); |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 718 | |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 719 | std::unique_ptr<ipc_lib::SignalFd> signalfd; |
| 720 | |
| 721 | if (watchers_.size() > 0) { |
| 722 | signalfd.reset(new ipc_lib::SignalFd({ipc_lib::kWakeupSignal})); |
| 723 | |
| 724 | epoll_.OnReadable(signalfd->fd(), [signalfd_ptr = signalfd.get(), this]() { |
| 725 | signalfd_siginfo result = signalfd_ptr->Read(); |
| 726 | CHECK_EQ(result.ssi_signo, ipc_lib::kWakeupSignal); |
| 727 | |
| 728 | // TODO(austin): We should really be checking *everything*, not just |
| 729 | // watchers, and calling the oldest thing first. That will improve |
| 730 | // determinism a lot. |
| 731 | |
Austin Schuh | 7d87b67 | 2019-12-01 20:23:49 -0800 | [diff] [blame] | 732 | HandleEvent(); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 733 | }); |
| 734 | } |
| 735 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 736 | MaybeScheduleTimingReports(); |
| 737 | |
Austin Schuh | 7d87b67 | 2019-12-01 20:23:49 -0800 | [diff] [blame] | 738 | ReserveEvents(); |
| 739 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 740 | // Now, all the callbacks are setup. Lock everything into memory and go RT. |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 741 | if (priority_ != 0) { |
| 742 | ::aos::InitRT(); |
| 743 | |
| 744 | LOG(INFO) << "Setting priority to " << priority_; |
| 745 | ::aos::SetCurrentThreadRealtimePriority(priority_); |
| 746 | } |
| 747 | |
| 748 | set_is_running(true); |
| 749 | |
| 750 | // Now that we are realtime (but before the OnRun handlers run), snap the |
| 751 | // queue index. |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 752 | for (::std::unique_ptr<WatcherState> &watcher : watchers_) { |
| 753 | watcher->Startup(this); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 754 | } |
| 755 | |
| 756 | // Now that we are RT, run all the OnRun handlers. |
| 757 | for (const auto &run : on_run_) { |
| 758 | run(); |
| 759 | } |
| 760 | |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 761 | // And start our main event loop which runs all the timers and handles Quit. |
| 762 | epoll_.Run(); |
| 763 | |
| 764 | // Once epoll exits, there is no useful nonrt work left to do. |
| 765 | set_is_running(false); |
| 766 | |
| 767 | // Nothing time or synchronization critical needs to happen after this point. |
| 768 | // Drop RT priority. |
| 769 | ::aos::UnsetCurrentThreadRealtimePriority(); |
| 770 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 771 | for (::std::unique_ptr<WatcherState> &base_watcher : watchers_) { |
| 772 | internal::WatcherState *watcher = |
| 773 | reinterpret_cast<internal::WatcherState *>(base_watcher.get()); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 774 | watcher->UnregisterWakeup(); |
| 775 | } |
| 776 | |
| 777 | if (watchers_.size() > 0) { |
| 778 | epoll_.DeleteFd(signalfd->fd()); |
| 779 | signalfd.reset(); |
| 780 | } |
Austin Schuh | 32fd5a7 | 2019-12-01 22:20:26 -0800 | [diff] [blame] | 781 | |
| 782 | SignalHandler::global()->Unregister(this); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 783 | } |
| 784 | |
| 785 | void ShmEventLoop::Exit() { epoll_.Quit(); } |
| 786 | |
| 787 | ShmEventLoop::~ShmEventLoop() { |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 788 | // Trigger any remaining senders or fetchers to be cleared before destroying |
| 789 | // the event loop so the book keeping matches. |
| 790 | timing_report_sender_.reset(); |
| 791 | |
| 792 | // Force everything with a registered fd with epoll to be destroyed now. |
| 793 | timers_.clear(); |
| 794 | phased_loops_.clear(); |
| 795 | watchers_.clear(); |
| 796 | |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 797 | CHECK(!is_running()) << ": ShmEventLoop destroyed while running"; |
| 798 | } |
| 799 | |
| 800 | void ShmEventLoop::Take(const Channel *channel) { |
| 801 | CHECK(!is_running()) << ": Cannot add new objects while running."; |
| 802 | |
| 803 | // Cheat aggresively. Use the shared memory path as a proxy for a unique |
| 804 | // identifier for the channel. |
| 805 | const std::string path = ShmPath(channel); |
| 806 | |
| 807 | const auto prior = ::std::find(taken_.begin(), taken_.end(), path); |
| 808 | CHECK(prior == taken_.end()) << ": " << path << " is already being used."; |
| 809 | |
| 810 | taken_.emplace_back(path); |
| 811 | } |
| 812 | |
| 813 | void ShmEventLoop::SetRuntimeRealtimePriority(int priority) { |
| 814 | if (is_running()) { |
| 815 | LOG(FATAL) << "Cannot set realtime priority while running."; |
| 816 | } |
| 817 | priority_ = priority; |
| 818 | } |
| 819 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame] | 820 | pid_t ShmEventLoop::GetTid() { return syscall(SYS_gettid); } |
| 821 | |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 822 | } // namespace aos |