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