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