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" |
| 20 | #include "aos/util/phased_loop.h" |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 21 | #include "glog/logging.h" |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 22 | |
| 23 | DEFINE_string(shm_base, "/dev/shm/aos", |
| 24 | "Directory to place queue backing mmaped files in."); |
| 25 | DEFINE_uint32(permissions, 0770, |
| 26 | "Permissions to make shared memory files and folders."); |
| 27 | |
| 28 | namespace aos { |
| 29 | |
| 30 | std::string ShmFolder(const Channel *channel) { |
| 31 | CHECK(channel->has_name()); |
| 32 | CHECK_EQ(channel->name()->string_view()[0], '/'); |
| 33 | return FLAGS_shm_base + channel->name()->str() + "/"; |
| 34 | } |
| 35 | std::string ShmPath(const Channel *channel) { |
| 36 | CHECK(channel->has_type()); |
| 37 | return ShmFolder(channel) + channel->type()->str() + ".v0"; |
| 38 | } |
| 39 | |
| 40 | class MMapedQueue { |
| 41 | public: |
| 42 | MMapedQueue(const Channel *channel) { |
| 43 | std::string path = ShmPath(channel); |
| 44 | |
| 45 | // TODO(austin): Pull these out into the config if there is a need. |
| 46 | config_.num_watchers = 10; |
| 47 | config_.num_senders = 10; |
| 48 | config_.queue_size = 2 * channel->frequency(); |
| 49 | config_.message_data_size = channel->max_size(); |
| 50 | |
| 51 | size_ = ipc_lib::LocklessQueueMemorySize(config_); |
| 52 | |
| 53 | MkdirP(path); |
| 54 | |
| 55 | // There are 2 cases. Either the file already exists, or it does not |
| 56 | // already exist and we need to create it. Start by trying to create it. If |
| 57 | // that fails, the file has already been created and we can open it |
| 58 | // normally.. Once the file has been created it wil never be deleted. |
| 59 | fd_ = open(path.c_str(), O_RDWR | O_CREAT | O_EXCL, |
| 60 | O_CLOEXEC | FLAGS_permissions); |
| 61 | if (fd_ == -1 && errno == EEXIST) { |
| 62 | VLOG(1) << path << " already created."; |
| 63 | // File already exists. |
| 64 | fd_ = open(path.c_str(), O_RDWR, O_CLOEXEC); |
| 65 | PCHECK(fd_ != -1) << ": Failed to open " << path; |
| 66 | while (true) { |
| 67 | struct stat st; |
| 68 | PCHECK(fstat(fd_, &st) == 0); |
| 69 | if (st.st_size != 0) { |
| 70 | CHECK_EQ(static_cast<size_t>(st.st_size), size_) |
| 71 | << ": Size of " << path |
| 72 | << " doesn't match expected size of backing queue file. Did the " |
| 73 | "queue definition change?"; |
| 74 | break; |
| 75 | } else { |
| 76 | // The creating process didn't get around to it yet. Give it a bit. |
| 77 | std::this_thread::sleep_for(std::chrono::milliseconds(10)); |
| 78 | VLOG(1) << path << " is zero size, waiting"; |
| 79 | } |
| 80 | } |
| 81 | } else { |
| 82 | VLOG(1) << "Created " << path; |
| 83 | PCHECK(fd_ != -1) << ": Failed to open " << path; |
| 84 | PCHECK(ftruncate(fd_, size_) == 0); |
| 85 | } |
| 86 | |
| 87 | data_ = mmap(NULL, size_, PROT_READ | PROT_WRITE, MAP_SHARED, fd_, 0); |
| 88 | PCHECK(data_ != MAP_FAILED); |
| 89 | |
| 90 | ipc_lib::InitializeLocklessQueueMemory(memory(), config_); |
| 91 | } |
| 92 | |
| 93 | ~MMapedQueue() { |
| 94 | PCHECK(munmap(data_, size_) == 0); |
| 95 | PCHECK(close(fd_) == 0); |
| 96 | } |
| 97 | |
| 98 | ipc_lib::LocklessQueueMemory *memory() const { |
| 99 | return reinterpret_cast<ipc_lib::LocklessQueueMemory *>(data_); |
| 100 | } |
| 101 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 102 | const ipc_lib::LocklessQueueConfiguration &config() const { return config_; } |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 103 | |
| 104 | private: |
James Kuszmaul | 3ae4226 | 2019-11-08 12:33:41 -0800 | [diff] [blame] | 105 | void MkdirP(std::string_view path) { |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 106 | struct stat st; |
| 107 | auto last_slash_pos = path.find_last_of("/"); |
| 108 | |
James Kuszmaul | 3ae4226 | 2019-11-08 12:33:41 -0800 | [diff] [blame] | 109 | std::string folder(last_slash_pos == std::string_view::npos |
| 110 | ? std::string_view("") |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 111 | : path.substr(0, last_slash_pos)); |
| 112 | if (stat(folder.c_str(), &st) == -1) { |
| 113 | PCHECK(errno == ENOENT); |
| 114 | CHECK_NE(folder, "") << ": Base path doesn't exist"; |
| 115 | MkdirP(folder); |
| 116 | VLOG(1) << "Creating " << folder; |
| 117 | PCHECK(mkdir(folder.c_str(), FLAGS_permissions) == 0); |
| 118 | } |
| 119 | } |
| 120 | |
| 121 | ipc_lib::LocklessQueueConfiguration config_; |
| 122 | |
| 123 | int fd_; |
| 124 | |
| 125 | size_t size_; |
| 126 | void *data_; |
| 127 | }; |
| 128 | |
| 129 | // Returns the portion of the path after the last /. |
James Kuszmaul | 3ae4226 | 2019-11-08 12:33:41 -0800 | [diff] [blame] | 130 | std::string_view Filename(std::string_view path) { |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 131 | auto last_slash_pos = path.find_last_of("/"); |
| 132 | |
James Kuszmaul | 3ae4226 | 2019-11-08 12:33:41 -0800 | [diff] [blame] | 133 | return last_slash_pos == std::string_view::npos |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 134 | ? path |
| 135 | : path.substr(last_slash_pos + 1, path.size()); |
| 136 | } |
| 137 | |
| 138 | ShmEventLoop::ShmEventLoop(const Configuration *configuration) |
| 139 | : EventLoop(configuration), name_(Filename(program_invocation_name)) {} |
| 140 | |
| 141 | namespace { |
| 142 | |
| 143 | namespace chrono = ::std::chrono; |
| 144 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 145 | } // namespace |
| 146 | |
| 147 | namespace internal { |
| 148 | |
| 149 | class SimpleShmFetcher { |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 150 | public: |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 151 | explicit SimpleShmFetcher(const Channel *channel) |
| 152 | : lockless_queue_memory_(channel), |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 153 | lockless_queue_(lockless_queue_memory_.memory(), |
| 154 | lockless_queue_memory_.config()), |
| 155 | data_storage_(static_cast<AlignedChar *>(aligned_alloc( |
| 156 | alignof(AlignedChar), channel->max_size())), |
| 157 | &free) { |
| 158 | context_.data = nullptr; |
| 159 | // Point the queue index at the next index to read starting now. This |
| 160 | // makes it such that FetchNext will read the next message sent after |
| 161 | // the fetcher is created. |
| 162 | PointAtNextQueueIndex(); |
| 163 | } |
| 164 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 165 | ~SimpleShmFetcher() {} |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 166 | |
| 167 | // Points the next message to fetch at the queue index which will be |
| 168 | // populated next. |
| 169 | void PointAtNextQueueIndex() { |
| 170 | actual_queue_index_ = lockless_queue_.LatestQueueIndex(); |
| 171 | if (!actual_queue_index_.valid()) { |
| 172 | // Nothing in the queue. The next element will show up at the 0th |
| 173 | // index in the queue. |
| 174 | actual_queue_index_ = |
| 175 | ipc_lib::QueueIndex::Zero(lockless_queue_.queue_size()); |
| 176 | } else { |
| 177 | actual_queue_index_ = actual_queue_index_.Increment(); |
| 178 | } |
| 179 | } |
| 180 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 181 | bool FetchNext() { |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 182 | // TODO(austin): Write a test which starts with nothing in the queue, |
| 183 | // and then calls FetchNext() after something is sent. |
| 184 | // TODO(austin): Get behind and make sure it dies both here and with |
| 185 | // Fetch. |
| 186 | ipc_lib::LocklessQueue::ReadResult read_result = lockless_queue_.Read( |
| 187 | actual_queue_index_.index(), &context_.monotonic_sent_time, |
| 188 | &context_.realtime_sent_time, &context_.size, |
| 189 | reinterpret_cast<char *>(data_storage_.get())); |
| 190 | if (read_result == ipc_lib::LocklessQueue::ReadResult::GOOD) { |
| 191 | context_.queue_index = actual_queue_index_.index(); |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 192 | context_.data = reinterpret_cast<char *>(data_storage_.get()) + |
| 193 | lockless_queue_.message_data_size() - context_.size; |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 194 | actual_queue_index_ = actual_queue_index_.Increment(); |
| 195 | } |
| 196 | |
| 197 | // Make sure the data wasn't modified while we were reading it. This |
| 198 | // can only happen if you are reading the last message *while* it is |
| 199 | // being written to, which means you are pretty far behind. |
| 200 | CHECK(read_result != ipc_lib::LocklessQueue::ReadResult::OVERWROTE) |
| 201 | << ": Got behind while reading and the last message was modified " |
| 202 | "out " |
| 203 | "from under us while we were reading it. Don't get so far " |
| 204 | "behind."; |
| 205 | |
| 206 | CHECK(read_result != ipc_lib::LocklessQueue::ReadResult::TOO_OLD) |
| 207 | << ": The next message is no longer available."; |
| 208 | return read_result == ipc_lib::LocklessQueue::ReadResult::GOOD; |
| 209 | } |
| 210 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 211 | bool Fetch() { |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 212 | const ipc_lib::QueueIndex queue_index = lockless_queue_.LatestQueueIndex(); |
| 213 | // actual_queue_index_ is only meaningful if it was set by Fetch or |
| 214 | // FetchNext. This happens when valid_data_ has been set. So, only |
| 215 | // skip checking if valid_data_ is true. |
| 216 | // |
| 217 | // Also, if the latest queue index is invalid, we are empty. So there |
| 218 | // is nothing to fetch. |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 219 | if ((context_.data != nullptr && |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 220 | queue_index == actual_queue_index_.DecrementBy(1u)) || |
| 221 | !queue_index.valid()) { |
| 222 | return false; |
| 223 | } |
| 224 | |
| 225 | ipc_lib::LocklessQueue::ReadResult read_result = |
| 226 | lockless_queue_.Read(queue_index.index(), &context_.monotonic_sent_time, |
| 227 | &context_.realtime_sent_time, &context_.size, |
| 228 | reinterpret_cast<char *>(data_storage_.get())); |
| 229 | if (read_result == ipc_lib::LocklessQueue::ReadResult::GOOD) { |
| 230 | context_.queue_index = queue_index.index(); |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 231 | context_.data = reinterpret_cast<char *>(data_storage_.get()) + |
| 232 | lockless_queue_.message_data_size() - context_.size; |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 233 | actual_queue_index_ = queue_index.Increment(); |
| 234 | } |
| 235 | |
| 236 | // Make sure the data wasn't modified while we were reading it. This |
| 237 | // can only happen if you are reading the last message *while* it is |
| 238 | // being written to, which means you are pretty far behind. |
| 239 | CHECK(read_result != ipc_lib::LocklessQueue::ReadResult::OVERWROTE) |
| 240 | << ": Got behind while reading and the last message was modified " |
| 241 | "out " |
| 242 | "from under us while we were reading it. Don't get so far " |
| 243 | "behind."; |
| 244 | |
| 245 | CHECK(read_result != ipc_lib::LocklessQueue::ReadResult::NOTHING_NEW) |
| 246 | << ": Queue index went backwards. This should never happen."; |
| 247 | |
| 248 | // We fell behind between when we read the index and read the value. |
| 249 | // This isn't worth recovering from since this means we went to sleep |
| 250 | // for a long time in the middle of this function. |
| 251 | CHECK(read_result != ipc_lib::LocklessQueue::ReadResult::TOO_OLD) |
| 252 | << ": The next message is no longer available."; |
| 253 | return read_result == ipc_lib::LocklessQueue::ReadResult::GOOD; |
| 254 | } |
| 255 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 256 | Context context() const { return context_; } |
| 257 | |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 258 | bool RegisterWakeup(int priority) { |
| 259 | return lockless_queue_.RegisterWakeup(priority); |
| 260 | } |
| 261 | |
| 262 | void UnregisterWakeup() { lockless_queue_.UnregisterWakeup(); } |
| 263 | |
| 264 | private: |
| 265 | MMapedQueue lockless_queue_memory_; |
| 266 | ipc_lib::LocklessQueue lockless_queue_; |
| 267 | |
| 268 | ipc_lib::QueueIndex actual_queue_index_ = |
| 269 | ipc_lib::LocklessQueue::empty_queue_index(); |
| 270 | |
| 271 | struct AlignedChar { |
| 272 | alignas(32) char data; |
| 273 | }; |
| 274 | |
| 275 | std::unique_ptr<AlignedChar, decltype(&free)> data_storage_; |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 276 | |
| 277 | Context context_; |
| 278 | }; |
| 279 | |
| 280 | class ShmFetcher : public RawFetcher { |
| 281 | public: |
| 282 | explicit ShmFetcher(EventLoop *event_loop, const Channel *channel) |
| 283 | : RawFetcher(event_loop, channel), simple_shm_fetcher_(channel) {} |
| 284 | |
| 285 | ~ShmFetcher() { context_.data = nullptr; } |
| 286 | |
| 287 | std::pair<bool, monotonic_clock::time_point> DoFetchNext() override { |
| 288 | if (simple_shm_fetcher_.FetchNext()) { |
| 289 | context_ = simple_shm_fetcher_.context(); |
| 290 | return std::make_pair(true, monotonic_clock::now()); |
| 291 | } |
| 292 | return std::make_pair(false, monotonic_clock::min_time); |
| 293 | } |
| 294 | |
| 295 | std::pair<bool, monotonic_clock::time_point> DoFetch() override { |
| 296 | if (simple_shm_fetcher_.Fetch()) { |
| 297 | context_ = simple_shm_fetcher_.context(); |
| 298 | return std::make_pair(true, monotonic_clock::now()); |
| 299 | } |
| 300 | return std::make_pair(false, monotonic_clock::min_time); |
| 301 | } |
| 302 | |
| 303 | private: |
| 304 | SimpleShmFetcher simple_shm_fetcher_; |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 305 | }; |
| 306 | |
| 307 | class ShmSender : public RawSender { |
| 308 | public: |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 309 | explicit ShmSender(EventLoop *event_loop, const Channel *channel) |
| 310 | : RawSender(event_loop, channel), |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 311 | lockless_queue_memory_(channel), |
| 312 | lockless_queue_(lockless_queue_memory_.memory(), |
| 313 | lockless_queue_memory_.config()), |
| 314 | lockless_queue_sender_(lockless_queue_.MakeSender()) {} |
| 315 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 316 | ~ShmSender() override {} |
| 317 | |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 318 | void *data() override { return lockless_queue_sender_.Data(); } |
| 319 | size_t size() override { return lockless_queue_sender_.size(); } |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 320 | bool DoSend(size_t length) override { |
| 321 | lockless_queue_sender_.Send(length); |
| 322 | lockless_queue_.Wakeup(event_loop()->priority()); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 323 | return true; |
| 324 | } |
| 325 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 326 | bool DoSend(const void *msg, size_t length) override { |
Austin Schuh | 4726ce9 | 2019-11-29 13:23:18 -0800 | [diff] [blame] | 327 | lockless_queue_sender_.Send(reinterpret_cast<const char *>(msg), length); |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 328 | lockless_queue_.Wakeup(event_loop()->priority()); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 329 | // TODO(austin): Return an error if we send too fast. |
| 330 | return true; |
| 331 | } |
| 332 | |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 333 | private: |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 334 | MMapedQueue lockless_queue_memory_; |
| 335 | ipc_lib::LocklessQueue lockless_queue_; |
| 336 | ipc_lib::LocklessQueue::Sender lockless_queue_sender_; |
| 337 | }; |
| 338 | |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 339 | // Class to manage the state for a Watcher. |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 340 | class WatcherState : public aos::WatcherState { |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 341 | public: |
| 342 | WatcherState( |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 343 | EventLoop *event_loop, const Channel *channel, |
| 344 | std::function<void(const Context &context, const void *message)> fn) |
| 345 | : aos::WatcherState(event_loop, channel, std::move(fn)), |
| 346 | simple_shm_fetcher_(channel) {} |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 347 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 348 | ~WatcherState() override {} |
| 349 | |
| 350 | void Startup(EventLoop *event_loop) override { |
| 351 | PointAtNextQueueIndex(); |
| 352 | CHECK(RegisterWakeup(event_loop->priority())); |
| 353 | } |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 354 | |
| 355 | // Points the next message to fetch at the queue index which will be populated |
| 356 | // next. |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 357 | void PointAtNextQueueIndex() { simple_shm_fetcher_.PointAtNextQueueIndex(); } |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 358 | |
| 359 | // Returns true if there is new data available. |
| 360 | bool HasNewData() { |
| 361 | if (!has_new_data_) { |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 362 | has_new_data_ = simple_shm_fetcher_.FetchNext(); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 363 | } |
| 364 | |
| 365 | return has_new_data_; |
| 366 | } |
| 367 | |
| 368 | // Returns the time of the current data sample. |
| 369 | aos::monotonic_clock::time_point event_time() const { |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 370 | return simple_shm_fetcher_.context().monotonic_sent_time; |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 371 | } |
| 372 | |
| 373 | // Consumes the data by calling the callback. |
| 374 | void CallCallback() { |
| 375 | CHECK(has_new_data_); |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 376 | DoCallCallback(monotonic_clock::now, simple_shm_fetcher_.context()); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 377 | has_new_data_ = false; |
| 378 | } |
| 379 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 380 | // Registers us to receive a signal on event reception. |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 381 | bool RegisterWakeup(int priority) { |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 382 | return simple_shm_fetcher_.RegisterWakeup(priority); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 383 | } |
| 384 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 385 | void UnregisterWakeup() { return simple_shm_fetcher_.UnregisterWakeup(); } |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 386 | |
| 387 | private: |
| 388 | bool has_new_data_ = false; |
| 389 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 390 | SimpleShmFetcher simple_shm_fetcher_; |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 391 | }; |
| 392 | |
| 393 | // Adapter class to adapt a timerfd to a TimerHandler. |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 394 | class TimerHandlerState : public TimerHandler { |
| 395 | public: |
| 396 | TimerHandlerState(ShmEventLoop *shm_event_loop, ::std::function<void()> fn) |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 397 | : TimerHandler(shm_event_loop, std::move(fn)), |
| 398 | shm_event_loop_(shm_event_loop) { |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 399 | shm_event_loop_->epoll_.OnReadable(timerfd_.fd(), [this]() { |
Austin Schuh | de8a8ff | 2019-11-30 15:25:36 -0800 | [diff] [blame] | 400 | const uint64_t elapsed_cycles = timerfd_.Read(); |
| 401 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 402 | Call(monotonic_clock::now, base_); |
Austin Schuh | de8a8ff | 2019-11-30 15:25:36 -0800 | [diff] [blame] | 403 | |
| 404 | base_ += repeat_offset_ * elapsed_cycles; |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 405 | }); |
| 406 | } |
| 407 | |
| 408 | ~TimerHandlerState() { shm_event_loop_->epoll_.DeleteFd(timerfd_.fd()); } |
| 409 | |
| 410 | void Setup(monotonic_clock::time_point base, |
| 411 | monotonic_clock::duration repeat_offset) override { |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 412 | timerfd_.SetTime(base, repeat_offset); |
Austin Schuh | de8a8ff | 2019-11-30 15:25:36 -0800 | [diff] [blame] | 413 | base_ = base; |
| 414 | repeat_offset_ = repeat_offset; |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 415 | } |
| 416 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 417 | void Disable() override { timerfd_.Disable(); } |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 418 | |
| 419 | private: |
| 420 | ShmEventLoop *shm_event_loop_; |
| 421 | |
| 422 | TimerFd timerfd_; |
| 423 | |
Austin Schuh | de8a8ff | 2019-11-30 15:25:36 -0800 | [diff] [blame] | 424 | monotonic_clock::time_point base_; |
| 425 | monotonic_clock::duration repeat_offset_; |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 426 | }; |
| 427 | |
| 428 | // Adapter class to the timerfd and PhasedLoop. |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 429 | class PhasedLoopHandler : public ::aos::PhasedLoopHandler { |
| 430 | public: |
| 431 | PhasedLoopHandler(ShmEventLoop *shm_event_loop, ::std::function<void(int)> fn, |
| 432 | const monotonic_clock::duration interval, |
| 433 | const monotonic_clock::duration offset) |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 434 | : aos::PhasedLoopHandler(shm_event_loop, std::move(fn), interval, offset), |
| 435 | shm_event_loop_(shm_event_loop) { |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 436 | shm_event_loop_->epoll_.OnReadable(timerfd_.fd(), [this]() { |
| 437 | timerfd_.Read(); |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 438 | Call(monotonic_clock::now, |
| 439 | [this](monotonic_clock::time_point sleep_time) { |
| 440 | Schedule(sleep_time); |
| 441 | }); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 442 | }); |
| 443 | } |
| 444 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 445 | ~PhasedLoopHandler() override { |
| 446 | shm_event_loop_->epoll_.DeleteFd(timerfd_.fd()); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 447 | } |
| 448 | |
| 449 | private: |
Austin Schuh | de8a8ff | 2019-11-30 15:25:36 -0800 | [diff] [blame] | 450 | // Reschedules the timer. |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 451 | void Schedule(monotonic_clock::time_point sleep_time) override { |
| 452 | timerfd_.SetTime(sleep_time, ::aos::monotonic_clock::zero()); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 453 | } |
| 454 | |
| 455 | ShmEventLoop *shm_event_loop_; |
| 456 | |
| 457 | TimerFd timerfd_; |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 458 | }; |
| 459 | } // namespace internal |
| 460 | |
| 461 | ::std::unique_ptr<RawFetcher> ShmEventLoop::MakeRawFetcher( |
| 462 | const Channel *channel) { |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 463 | return ::std::unique_ptr<RawFetcher>(new internal::ShmFetcher(this, channel)); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 464 | } |
| 465 | |
| 466 | ::std::unique_ptr<RawSender> ShmEventLoop::MakeRawSender( |
| 467 | const Channel *channel) { |
| 468 | Take(channel); |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 469 | |
| 470 | return ::std::unique_ptr<RawSender>(new internal::ShmSender(this, channel)); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 471 | } |
| 472 | |
| 473 | void ShmEventLoop::MakeRawWatcher( |
| 474 | const Channel *channel, |
| 475 | std::function<void(const Context &context, const void *message)> watcher) { |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 476 | Take(channel); |
| 477 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 478 | NewWatcher(::std::unique_ptr<WatcherState>( |
| 479 | new internal::WatcherState(this, channel, std::move(watcher)))); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 480 | } |
| 481 | |
| 482 | TimerHandler *ShmEventLoop::AddTimer(::std::function<void()> callback) { |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 483 | return NewTimer(::std::unique_ptr<TimerHandler>( |
| 484 | new internal::TimerHandlerState(this, ::std::move(callback)))); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 485 | } |
| 486 | |
| 487 | PhasedLoopHandler *ShmEventLoop::AddPhasedLoop( |
| 488 | ::std::function<void(int)> callback, |
| 489 | const monotonic_clock::duration interval, |
| 490 | const monotonic_clock::duration offset) { |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 491 | return NewPhasedLoop( |
| 492 | ::std::unique_ptr<PhasedLoopHandler>(new internal::PhasedLoopHandler( |
| 493 | this, ::std::move(callback), interval, offset))); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 494 | } |
| 495 | |
| 496 | void ShmEventLoop::OnRun(::std::function<void()> on_run) { |
| 497 | on_run_.push_back(::std::move(on_run)); |
| 498 | } |
| 499 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 500 | void ShmEventLoop::HandleWatcherSignal() { |
| 501 | while (true) { |
| 502 | // Call the handlers in time order of their messages. |
| 503 | aos::monotonic_clock::time_point min_event_time = |
| 504 | aos::monotonic_clock::max_time; |
| 505 | size_t min_watcher_index = -1; |
| 506 | size_t watcher_index = 0; |
| 507 | for (::std::unique_ptr<WatcherState> &base_watcher : watchers_) { |
| 508 | internal::WatcherState *watcher = |
| 509 | reinterpret_cast<internal::WatcherState *>(base_watcher.get()); |
| 510 | |
| 511 | if (watcher->HasNewData()) { |
| 512 | if (watcher->event_time() < min_event_time) { |
| 513 | min_watcher_index = watcher_index; |
| 514 | min_event_time = watcher->event_time(); |
| 515 | } |
| 516 | } |
| 517 | ++watcher_index; |
| 518 | } |
| 519 | |
| 520 | if (min_event_time == aos::monotonic_clock::max_time) { |
| 521 | break; |
| 522 | } |
| 523 | |
| 524 | reinterpret_cast<internal::WatcherState *>( |
| 525 | watchers_[min_watcher_index].get()) |
| 526 | ->CallCallback(); |
| 527 | } |
| 528 | } |
| 529 | |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 530 | void ShmEventLoop::Run() { |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 531 | // TODO(austin): Automatically register ^C with a sigaction so 2 in a row send |
| 532 | // an actual control C. |
| 533 | |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 534 | std::unique_ptr<ipc_lib::SignalFd> signalfd; |
| 535 | |
| 536 | if (watchers_.size() > 0) { |
| 537 | signalfd.reset(new ipc_lib::SignalFd({ipc_lib::kWakeupSignal})); |
| 538 | |
| 539 | epoll_.OnReadable(signalfd->fd(), [signalfd_ptr = signalfd.get(), this]() { |
| 540 | signalfd_siginfo result = signalfd_ptr->Read(); |
| 541 | CHECK_EQ(result.ssi_signo, ipc_lib::kWakeupSignal); |
| 542 | |
| 543 | // TODO(austin): We should really be checking *everything*, not just |
| 544 | // watchers, and calling the oldest thing first. That will improve |
| 545 | // determinism a lot. |
| 546 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 547 | HandleWatcherSignal(); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 548 | }); |
| 549 | } |
| 550 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 551 | MaybeScheduleTimingReports(); |
| 552 | |
| 553 | // 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] | 554 | if (priority_ != 0) { |
| 555 | ::aos::InitRT(); |
| 556 | |
| 557 | LOG(INFO) << "Setting priority to " << priority_; |
| 558 | ::aos::SetCurrentThreadRealtimePriority(priority_); |
| 559 | } |
| 560 | |
| 561 | set_is_running(true); |
| 562 | |
| 563 | // Now that we are realtime (but before the OnRun handlers run), snap the |
| 564 | // queue index. |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 565 | for (::std::unique_ptr<WatcherState> &watcher : watchers_) { |
| 566 | watcher->Startup(this); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 567 | } |
| 568 | |
| 569 | // Now that we are RT, run all the OnRun handlers. |
| 570 | for (const auto &run : on_run_) { |
| 571 | run(); |
| 572 | } |
| 573 | |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 574 | // And start our main event loop which runs all the timers and handles Quit. |
| 575 | epoll_.Run(); |
| 576 | |
| 577 | // Once epoll exits, there is no useful nonrt work left to do. |
| 578 | set_is_running(false); |
| 579 | |
| 580 | // Nothing time or synchronization critical needs to happen after this point. |
| 581 | // Drop RT priority. |
| 582 | ::aos::UnsetCurrentThreadRealtimePriority(); |
| 583 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 584 | for (::std::unique_ptr<WatcherState> &base_watcher : watchers_) { |
| 585 | internal::WatcherState *watcher = |
| 586 | reinterpret_cast<internal::WatcherState *>(base_watcher.get()); |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 587 | watcher->UnregisterWakeup(); |
| 588 | } |
| 589 | |
| 590 | if (watchers_.size() > 0) { |
| 591 | epoll_.DeleteFd(signalfd->fd()); |
| 592 | signalfd.reset(); |
| 593 | } |
| 594 | } |
| 595 | |
| 596 | void ShmEventLoop::Exit() { epoll_.Quit(); } |
| 597 | |
| 598 | ShmEventLoop::~ShmEventLoop() { |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 599 | // Trigger any remaining senders or fetchers to be cleared before destroying |
| 600 | // the event loop so the book keeping matches. |
| 601 | timing_report_sender_.reset(); |
| 602 | |
| 603 | // Force everything with a registered fd with epoll to be destroyed now. |
| 604 | timers_.clear(); |
| 605 | phased_loops_.clear(); |
| 606 | watchers_.clear(); |
| 607 | |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 608 | CHECK(!is_running()) << ": ShmEventLoop destroyed while running"; |
| 609 | } |
| 610 | |
| 611 | void ShmEventLoop::Take(const Channel *channel) { |
| 612 | CHECK(!is_running()) << ": Cannot add new objects while running."; |
| 613 | |
| 614 | // Cheat aggresively. Use the shared memory path as a proxy for a unique |
| 615 | // identifier for the channel. |
| 616 | const std::string path = ShmPath(channel); |
| 617 | |
| 618 | const auto prior = ::std::find(taken_.begin(), taken_.end(), path); |
| 619 | CHECK(prior == taken_.end()) << ": " << path << " is already being used."; |
| 620 | |
| 621 | taken_.emplace_back(path); |
| 622 | } |
| 623 | |
| 624 | void ShmEventLoop::SetRuntimeRealtimePriority(int priority) { |
| 625 | if (is_running()) { |
| 626 | LOG(FATAL) << "Cannot set realtime priority while running."; |
| 627 | } |
| 628 | priority_ = priority; |
| 629 | } |
| 630 | |
Austin Schuh | 39788ff | 2019-12-01 18:22:57 -0800 | [diff] [blame^] | 631 | pid_t ShmEventLoop::GetTid() { return syscall(SYS_gettid); } |
| 632 | |
Alex Perry | cb7da4b | 2019-08-28 19:35:56 -0700 | [diff] [blame] | 633 | } // namespace aos |