Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 1 | /* |
| 2 | * Copyright (C) 2018 The Android Open Source Project |
| 3 | * |
| 4 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | * you may not use this file except in compliance with the License. |
| 6 | * You may obtain a copy of the License at |
| 7 | * |
| 8 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 9 | * |
| 10 | * Unless required by applicable law or agreed to in writing, software |
| 11 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | * See the License for the specific language governing permissions and |
| 14 | * limitations under the License. |
| 15 | */ |
| 16 | |
| 17 | #define TRACE_TAG USB |
| 18 | |
| 19 | #include "sysdeps.h" |
| 20 | |
| 21 | #include <errno.h> |
| 22 | #include <stdio.h> |
| 23 | #include <stdlib.h> |
| 24 | #include <string.h> |
| 25 | #include <sys/ioctl.h> |
| 26 | #include <sys/types.h> |
| 27 | #include <unistd.h> |
| 28 | |
| 29 | #include <linux/usb/functionfs.h> |
| 30 | #include <sys/eventfd.h> |
| 31 | |
Josh Gao | 86b33be | 2019-02-26 17:53:52 -0800 | [diff] [blame] | 32 | #include <algorithm> |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 33 | #include <array> |
| 34 | #include <future> |
| 35 | #include <memory> |
| 36 | #include <mutex> |
| 37 | #include <optional> |
| 38 | #include <vector> |
| 39 | |
| 40 | #include <asyncio/AsyncIO.h> |
| 41 | |
| 42 | #include <android-base/logging.h> |
| 43 | #include <android-base/macros.h> |
| 44 | #include <android-base/properties.h> |
| 45 | #include <android-base/thread_annotations.h> |
| 46 | |
| 47 | #include <adbd/usb.h> |
| 48 | |
| 49 | #include "adb_unique_fd.h" |
| 50 | #include "adb_utils.h" |
| 51 | #include "sysdeps/chrono.h" |
| 52 | #include "transport.h" |
| 53 | #include "types.h" |
| 54 | |
| 55 | using android::base::StringPrintf; |
| 56 | |
Josh Gao | c0b831b | 2019-02-13 15:27:28 -0800 | [diff] [blame] | 57 | // We can't find out whether we have support for AIO on ffs endpoints until we submit a read. |
| 58 | static std::optional<bool> gFfsAioSupported; |
| 59 | |
Josh Gao | 5841a96 | 2019-02-28 15:44:05 -0800 | [diff] [blame] | 60 | static constexpr size_t kUsbReadQueueDepth = 32; |
| 61 | static constexpr size_t kUsbReadSize = 8 * PAGE_SIZE; |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 62 | |
Josh Gao | 5841a96 | 2019-02-28 15:44:05 -0800 | [diff] [blame] | 63 | static constexpr size_t kUsbWriteQueueDepth = 32; |
| 64 | static constexpr size_t kUsbWriteSize = 8 * PAGE_SIZE; |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 65 | |
| 66 | static const char* to_string(enum usb_functionfs_event_type type) { |
| 67 | switch (type) { |
| 68 | case FUNCTIONFS_BIND: |
| 69 | return "FUNCTIONFS_BIND"; |
| 70 | case FUNCTIONFS_UNBIND: |
| 71 | return "FUNCTIONFS_UNBIND"; |
| 72 | case FUNCTIONFS_ENABLE: |
| 73 | return "FUNCTIONFS_ENABLE"; |
| 74 | case FUNCTIONFS_DISABLE: |
| 75 | return "FUNCTIONFS_DISABLE"; |
| 76 | case FUNCTIONFS_SETUP: |
| 77 | return "FUNCTIONFS_SETUP"; |
| 78 | case FUNCTIONFS_SUSPEND: |
| 79 | return "FUNCTIONFS_SUSPEND"; |
| 80 | case FUNCTIONFS_RESUME: |
| 81 | return "FUNCTIONFS_RESUME"; |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | enum class TransferDirection : uint64_t { |
| 86 | READ = 0, |
| 87 | WRITE = 1, |
| 88 | }; |
| 89 | |
| 90 | struct TransferId { |
| 91 | TransferDirection direction : 1; |
| 92 | uint64_t id : 63; |
| 93 | |
| 94 | TransferId() : TransferId(TransferDirection::READ, 0) {} |
| 95 | |
| 96 | private: |
| 97 | TransferId(TransferDirection direction, uint64_t id) : direction(direction), id(id) {} |
| 98 | |
| 99 | public: |
| 100 | explicit operator uint64_t() const { |
| 101 | uint64_t result; |
| 102 | static_assert(sizeof(*this) == sizeof(result)); |
| 103 | memcpy(&result, this, sizeof(*this)); |
| 104 | return result; |
| 105 | } |
| 106 | |
| 107 | static TransferId read(uint64_t id) { return TransferId(TransferDirection::READ, id); } |
| 108 | static TransferId write(uint64_t id) { return TransferId(TransferDirection::WRITE, id); } |
| 109 | |
| 110 | static TransferId from_value(uint64_t value) { |
| 111 | TransferId result; |
| 112 | memcpy(&result, &value, sizeof(value)); |
| 113 | return result; |
| 114 | } |
| 115 | }; |
| 116 | |
| 117 | struct IoBlock { |
Josh Gao | b019574 | 2019-03-18 14:11:28 -0700 | [diff] [blame^] | 118 | bool pending = false; |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 119 | struct iocb control; |
Josh Gao | 86b33be | 2019-02-26 17:53:52 -0800 | [diff] [blame] | 120 | std::shared_ptr<Block> payload; |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 121 | |
| 122 | TransferId id() const { return TransferId::from_value(control.aio_data); } |
| 123 | }; |
| 124 | |
| 125 | struct ScopedAioContext { |
| 126 | ScopedAioContext() = default; |
| 127 | ~ScopedAioContext() { reset(); } |
| 128 | |
| 129 | ScopedAioContext(ScopedAioContext&& move) { reset(move.release()); } |
| 130 | ScopedAioContext(const ScopedAioContext& copy) = delete; |
| 131 | |
| 132 | ScopedAioContext& operator=(ScopedAioContext&& move) { |
| 133 | reset(move.release()); |
| 134 | return *this; |
| 135 | } |
| 136 | ScopedAioContext& operator=(const ScopedAioContext& copy) = delete; |
| 137 | |
| 138 | static ScopedAioContext Create(size_t max_events) { |
| 139 | aio_context_t ctx = 0; |
| 140 | if (io_setup(max_events, &ctx) != 0) { |
| 141 | PLOG(FATAL) << "failed to create aio_context_t"; |
| 142 | } |
| 143 | ScopedAioContext result; |
| 144 | result.reset(ctx); |
| 145 | return result; |
| 146 | } |
| 147 | |
| 148 | aio_context_t release() { |
| 149 | aio_context_t result = context_; |
| 150 | context_ = 0; |
| 151 | return result; |
| 152 | } |
| 153 | |
| 154 | void reset(aio_context_t new_context = 0) { |
| 155 | if (context_ != 0) { |
| 156 | io_destroy(context_); |
| 157 | } |
| 158 | |
| 159 | context_ = new_context; |
| 160 | } |
| 161 | |
| 162 | aio_context_t get() { return context_; } |
| 163 | |
| 164 | private: |
| 165 | aio_context_t context_ = 0; |
| 166 | }; |
| 167 | |
| 168 | struct UsbFfsConnection : public Connection { |
| 169 | UsbFfsConnection(unique_fd control, unique_fd read, unique_fd write, |
| 170 | std::promise<void> destruction_notifier) |
| 171 | : stopped_(false), |
| 172 | destruction_notifier_(std::move(destruction_notifier)), |
| 173 | control_fd_(std::move(control)), |
| 174 | read_fd_(std::move(read)), |
| 175 | write_fd_(std::move(write)) { |
| 176 | LOG(INFO) << "UsbFfsConnection constructed"; |
Josh Gao | c0b831b | 2019-02-13 15:27:28 -0800 | [diff] [blame] | 177 | worker_event_fd_.reset(eventfd(0, EFD_CLOEXEC)); |
| 178 | if (worker_event_fd_ == -1) { |
| 179 | PLOG(FATAL) << "failed to create eventfd"; |
| 180 | } |
| 181 | |
| 182 | monitor_event_fd_.reset(eventfd(0, EFD_CLOEXEC)); |
| 183 | if (monitor_event_fd_ == -1) { |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 184 | PLOG(FATAL) << "failed to create eventfd"; |
| 185 | } |
| 186 | |
| 187 | aio_context_ = ScopedAioContext::Create(kUsbReadQueueDepth + kUsbWriteQueueDepth); |
| 188 | } |
| 189 | |
| 190 | ~UsbFfsConnection() { |
| 191 | LOG(INFO) << "UsbFfsConnection being destroyed"; |
| 192 | Stop(); |
| 193 | monitor_thread_.join(); |
Josh Gao | c0b831b | 2019-02-13 15:27:28 -0800 | [diff] [blame] | 194 | |
| 195 | // We need to explicitly close our file descriptors before we notify our destruction, |
| 196 | // because the thread listening on the future will immediately try to reopen the endpoint. |
| 197 | control_fd_.reset(); |
| 198 | read_fd_.reset(); |
| 199 | write_fd_.reset(); |
| 200 | |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 201 | destruction_notifier_.set_value(); |
| 202 | } |
| 203 | |
| 204 | virtual bool Write(std::unique_ptr<apacket> packet) override final { |
| 205 | LOG(DEBUG) << "USB write: " << dump_header(&packet->msg); |
| 206 | Block header(sizeof(packet->msg)); |
| 207 | memcpy(header.data(), &packet->msg, sizeof(packet->msg)); |
| 208 | |
| 209 | std::lock_guard<std::mutex> lock(write_mutex_); |
| 210 | write_requests_.push_back(CreateWriteBlock(std::move(header), next_write_id_++)); |
| 211 | if (!packet->payload.empty()) { |
Josh Gao | 86b33be | 2019-02-26 17:53:52 -0800 | [diff] [blame] | 212 | // The kernel attempts to allocate a contiguous block of memory for each write, |
| 213 | // which can fail if the write is large and the kernel heap is fragmented. |
| 214 | // Split large writes into smaller chunks to avoid this. |
| 215 | std::shared_ptr<Block> payload = std::make_shared<Block>(std::move(packet->payload)); |
| 216 | size_t offset = 0; |
| 217 | size_t len = payload->size(); |
| 218 | |
| 219 | while (len > 0) { |
| 220 | size_t write_size = std::min(kUsbWriteSize, len); |
| 221 | write_requests_.push_back( |
| 222 | CreateWriteBlock(payload, offset, write_size, next_write_id_++)); |
| 223 | len -= write_size; |
| 224 | offset += write_size; |
| 225 | } |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 226 | } |
| 227 | SubmitWrites(); |
| 228 | return true; |
| 229 | } |
| 230 | |
| 231 | virtual void Start() override final { StartMonitor(); } |
| 232 | |
| 233 | virtual void Stop() override final { |
| 234 | if (stopped_.exchange(true)) { |
| 235 | return; |
| 236 | } |
| 237 | stopped_ = true; |
| 238 | uint64_t notify = 1; |
Josh Gao | c0b831b | 2019-02-13 15:27:28 -0800 | [diff] [blame] | 239 | ssize_t rc = adb_write(worker_event_fd_.get(), ¬ify, sizeof(notify)); |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 240 | if (rc < 0) { |
Josh Gao | c0b831b | 2019-02-13 15:27:28 -0800 | [diff] [blame] | 241 | PLOG(FATAL) << "failed to notify worker eventfd to stop UsbFfsConnection"; |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 242 | } |
| 243 | CHECK_EQ(static_cast<size_t>(rc), sizeof(notify)); |
Josh Gao | c0b831b | 2019-02-13 15:27:28 -0800 | [diff] [blame] | 244 | |
| 245 | rc = adb_write(monitor_event_fd_.get(), ¬ify, sizeof(notify)); |
| 246 | if (rc < 0) { |
| 247 | PLOG(FATAL) << "failed to notify monitor eventfd to stop UsbFfsConnection"; |
| 248 | } |
| 249 | |
| 250 | CHECK_EQ(static_cast<size_t>(rc), sizeof(notify)); |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 251 | } |
| 252 | |
| 253 | private: |
| 254 | void StartMonitor() { |
| 255 | // This is a bit of a mess. |
| 256 | // It's possible for io_submit to end up blocking, if we call it as the endpoint |
| 257 | // becomes disabled. Work around this by having a monitor thread to listen for functionfs |
| 258 | // lifecycle events. If we notice an error condition (either we've become disabled, or we |
| 259 | // were never enabled in the first place), we send interruption signals to the worker thread |
| 260 | // until it dies, and then report failure to the transport via HandleError, which will |
| 261 | // eventually result in the transport being destroyed, which will result in UsbFfsConnection |
| 262 | // being destroyed, which unblocks the open thread and restarts this entire process. |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 263 | static std::once_flag handler_once; |
| 264 | std::call_once(handler_once, []() { signal(kInterruptionSignal, [](int) {}); }); |
| 265 | |
| 266 | monitor_thread_ = std::thread([this]() { |
| 267 | adb_thread_setname("UsbFfs-monitor"); |
| 268 | |
| 269 | bool bound = false; |
| 270 | bool started = false; |
| 271 | bool running = true; |
| 272 | while (running) { |
Josh Gao | c0b831b | 2019-02-13 15:27:28 -0800 | [diff] [blame] | 273 | adb_pollfd pfd[2] = { |
| 274 | { .fd = control_fd_.get(), .events = POLLIN, .revents = 0 }, |
| 275 | { .fd = monitor_event_fd_.get(), .events = POLLIN, .revents = 0 }, |
| 276 | }; |
Josh Gao | 007a4dc | 2019-03-11 13:03:08 -0700 | [diff] [blame] | 277 | int rc = TEMP_FAILURE_RETRY(adb_poll(pfd, 2, -1)); |
Josh Gao | c0b831b | 2019-02-13 15:27:28 -0800 | [diff] [blame] | 278 | if (rc == -1) { |
| 279 | PLOG(FATAL) << "poll on USB control fd failed"; |
| 280 | } else if (rc == 0) { |
Josh Gao | 007a4dc | 2019-03-11 13:03:08 -0700 | [diff] [blame] | 281 | LOG(FATAL) << "poll on USB control fd returned 0"; |
Josh Gao | c0b831b | 2019-02-13 15:27:28 -0800 | [diff] [blame] | 282 | } |
| 283 | |
| 284 | if (pfd[1].revents) { |
| 285 | // We were told to die. |
| 286 | break; |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 287 | } |
| 288 | |
| 289 | struct usb_functionfs_event event; |
| 290 | if (TEMP_FAILURE_RETRY(adb_read(control_fd_.get(), &event, sizeof(event))) != |
| 291 | sizeof(event)) { |
| 292 | PLOG(FATAL) << "failed to read functionfs event"; |
| 293 | } |
| 294 | |
| 295 | LOG(INFO) << "USB event: " |
| 296 | << to_string(static_cast<usb_functionfs_event_type>(event.type)); |
| 297 | |
| 298 | switch (event.type) { |
| 299 | case FUNCTIONFS_BIND: |
Josh Gao | e778b3a | 2019-02-28 13:29:32 -0800 | [diff] [blame] | 300 | CHECK(!bound) << "received FUNCTIONFS_BIND while already bound?"; |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 301 | bound = true; |
| 302 | break; |
| 303 | |
| 304 | case FUNCTIONFS_ENABLE: |
| 305 | CHECK(!started) << "received FUNCTIONFS_ENABLE while already running?"; |
| 306 | started = true; |
| 307 | StartWorker(); |
| 308 | break; |
| 309 | |
| 310 | case FUNCTIONFS_DISABLE: |
| 311 | running = false; |
| 312 | break; |
| 313 | } |
| 314 | } |
| 315 | |
Josh Gao | e778b3a | 2019-02-28 13:29:32 -0800 | [diff] [blame] | 316 | StopWorker(); |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 317 | aio_context_.reset(); |
| 318 | read_fd_.reset(); |
| 319 | write_fd_.reset(); |
| 320 | }); |
| 321 | } |
| 322 | |
| 323 | void StartWorker() { |
| 324 | worker_thread_ = std::thread([this]() { |
| 325 | adb_thread_setname("UsbFfs-worker"); |
| 326 | for (size_t i = 0; i < kUsbReadQueueDepth; ++i) { |
| 327 | read_requests_[i] = CreateReadBlock(next_read_id_++); |
Josh Gao | c0b831b | 2019-02-13 15:27:28 -0800 | [diff] [blame] | 328 | if (!SubmitRead(&read_requests_[i])) { |
| 329 | return; |
| 330 | } |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 331 | } |
| 332 | |
| 333 | while (!stopped_) { |
| 334 | uint64_t dummy; |
Josh Gao | c0b831b | 2019-02-13 15:27:28 -0800 | [diff] [blame] | 335 | ssize_t rc = adb_read(worker_event_fd_.get(), &dummy, sizeof(dummy)); |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 336 | if (rc == -1) { |
| 337 | PLOG(FATAL) << "failed to read from eventfd"; |
| 338 | } else if (rc == 0) { |
| 339 | LOG(FATAL) << "hit EOF on eventfd"; |
| 340 | } |
| 341 | |
| 342 | WaitForEvents(); |
| 343 | } |
| 344 | }); |
| 345 | } |
| 346 | |
Josh Gao | e778b3a | 2019-02-28 13:29:32 -0800 | [diff] [blame] | 347 | void StopWorker() { |
| 348 | pthread_t worker_thread_handle = worker_thread_.native_handle(); |
| 349 | while (true) { |
| 350 | int rc = pthread_kill(worker_thread_handle, kInterruptionSignal); |
| 351 | if (rc != 0) { |
| 352 | LOG(ERROR) << "failed to send interruption signal to worker: " << strerror(rc); |
| 353 | break; |
| 354 | } |
| 355 | |
| 356 | std::this_thread::sleep_for(100ms); |
| 357 | |
| 358 | rc = pthread_kill(worker_thread_handle, 0); |
| 359 | if (rc == 0) { |
| 360 | continue; |
| 361 | } else if (rc == ESRCH) { |
| 362 | break; |
| 363 | } else { |
| 364 | LOG(ERROR) << "failed to send interruption signal to worker: " << strerror(rc); |
| 365 | } |
| 366 | } |
| 367 | |
| 368 | worker_thread_.join(); |
| 369 | } |
| 370 | |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 371 | void PrepareReadBlock(IoBlock* block, uint64_t id) { |
| 372 | block->pending = false; |
Josh Gao | 86b33be | 2019-02-26 17:53:52 -0800 | [diff] [blame] | 373 | block->payload = std::make_shared<Block>(kUsbReadSize); |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 374 | block->control.aio_data = static_cast<uint64_t>(TransferId::read(id)); |
Josh Gao | 86b33be | 2019-02-26 17:53:52 -0800 | [diff] [blame] | 375 | block->control.aio_buf = reinterpret_cast<uintptr_t>(block->payload->data()); |
| 376 | block->control.aio_nbytes = block->payload->size(); |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 377 | } |
| 378 | |
| 379 | IoBlock CreateReadBlock(uint64_t id) { |
| 380 | IoBlock block; |
| 381 | PrepareReadBlock(&block, id); |
| 382 | block.control.aio_rw_flags = 0; |
| 383 | block.control.aio_lio_opcode = IOCB_CMD_PREAD; |
| 384 | block.control.aio_reqprio = 0; |
| 385 | block.control.aio_fildes = read_fd_.get(); |
| 386 | block.control.aio_offset = 0; |
| 387 | block.control.aio_flags = IOCB_FLAG_RESFD; |
Josh Gao | c0b831b | 2019-02-13 15:27:28 -0800 | [diff] [blame] | 388 | block.control.aio_resfd = worker_event_fd_.get(); |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 389 | return block; |
| 390 | } |
| 391 | |
| 392 | void WaitForEvents() { |
| 393 | static constexpr size_t kMaxEvents = kUsbReadQueueDepth + kUsbWriteQueueDepth; |
| 394 | struct io_event events[kMaxEvents]; |
| 395 | struct timespec timeout = {.tv_sec = 0, .tv_nsec = 0}; |
| 396 | int rc = io_getevents(aio_context_.get(), 0, kMaxEvents, events, &timeout); |
| 397 | if (rc == -1) { |
| 398 | HandleError(StringPrintf("io_getevents failed while reading: %s", strerror(errno))); |
| 399 | return; |
| 400 | } |
| 401 | |
| 402 | for (int event_idx = 0; event_idx < rc; ++event_idx) { |
| 403 | auto& event = events[event_idx]; |
| 404 | TransferId id = TransferId::from_value(event.data); |
| 405 | |
| 406 | if (event.res < 0) { |
| 407 | std::string error = |
| 408 | StringPrintf("%s %" PRIu64 " failed with error %s", |
| 409 | id.direction == TransferDirection::READ ? "read" : "write", |
| 410 | id.id, strerror(-event.res)); |
| 411 | HandleError(error); |
| 412 | return; |
| 413 | } |
| 414 | |
| 415 | if (id.direction == TransferDirection::READ) { |
| 416 | HandleRead(id, event.res); |
| 417 | } else { |
| 418 | HandleWrite(id); |
| 419 | } |
| 420 | } |
| 421 | } |
| 422 | |
| 423 | void HandleRead(TransferId id, int64_t size) { |
| 424 | uint64_t read_idx = id.id % kUsbReadQueueDepth; |
| 425 | IoBlock* block = &read_requests_[read_idx]; |
| 426 | block->pending = false; |
Josh Gao | 86b33be | 2019-02-26 17:53:52 -0800 | [diff] [blame] | 427 | block->payload->resize(size); |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 428 | |
| 429 | // Notification for completed reads can be received out of order. |
| 430 | if (block->id().id != needed_read_id_) { |
| 431 | LOG(VERBOSE) << "read " << block->id().id << " completed while waiting for " |
| 432 | << needed_read_id_; |
| 433 | return; |
| 434 | } |
| 435 | |
| 436 | for (uint64_t id = needed_read_id_;; ++id) { |
| 437 | size_t read_idx = id % kUsbReadQueueDepth; |
| 438 | IoBlock* current_block = &read_requests_[read_idx]; |
| 439 | if (current_block->pending) { |
| 440 | break; |
| 441 | } |
| 442 | ProcessRead(current_block); |
| 443 | ++needed_read_id_; |
| 444 | } |
| 445 | } |
| 446 | |
| 447 | void ProcessRead(IoBlock* block) { |
Josh Gao | 86b33be | 2019-02-26 17:53:52 -0800 | [diff] [blame] | 448 | if (!block->payload->empty()) { |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 449 | if (!incoming_header_.has_value()) { |
Josh Gao | 86b33be | 2019-02-26 17:53:52 -0800 | [diff] [blame] | 450 | CHECK_EQ(sizeof(amessage), block->payload->size()); |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 451 | amessage msg; |
Josh Gao | 86b33be | 2019-02-26 17:53:52 -0800 | [diff] [blame] | 452 | memcpy(&msg, block->payload->data(), sizeof(amessage)); |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 453 | LOG(DEBUG) << "USB read:" << dump_header(&msg); |
| 454 | incoming_header_ = msg; |
| 455 | } else { |
| 456 | size_t bytes_left = incoming_header_->data_length - incoming_payload_.size(); |
Josh Gao | 86b33be | 2019-02-26 17:53:52 -0800 | [diff] [blame] | 457 | Block payload = std::move(*block->payload); |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 458 | CHECK_LE(payload.size(), bytes_left); |
| 459 | incoming_payload_.append(std::make_unique<Block>(std::move(payload))); |
| 460 | } |
| 461 | |
| 462 | if (incoming_header_->data_length == incoming_payload_.size()) { |
| 463 | auto packet = std::make_unique<apacket>(); |
| 464 | packet->msg = *incoming_header_; |
| 465 | |
| 466 | // TODO: Make apacket contain an IOVector so we don't have to coalesce. |
| 467 | packet->payload = incoming_payload_.coalesce(); |
| 468 | read_callback_(this, std::move(packet)); |
| 469 | |
| 470 | incoming_header_.reset(); |
| 471 | incoming_payload_.clear(); |
| 472 | } |
| 473 | } |
| 474 | |
| 475 | PrepareReadBlock(block, block->id().id + kUsbReadQueueDepth); |
| 476 | SubmitRead(block); |
| 477 | } |
| 478 | |
Josh Gao | c0b831b | 2019-02-13 15:27:28 -0800 | [diff] [blame] | 479 | bool SubmitRead(IoBlock* block) { |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 480 | block->pending = true; |
| 481 | struct iocb* iocb = &block->control; |
| 482 | if (io_submit(aio_context_.get(), 1, &iocb) != 1) { |
Josh Gao | c0b831b | 2019-02-13 15:27:28 -0800 | [diff] [blame] | 483 | if (errno == EINVAL && !gFfsAioSupported.has_value()) { |
| 484 | HandleError("failed to submit first read, AIO on FFS not supported"); |
| 485 | gFfsAioSupported = false; |
| 486 | return false; |
| 487 | } |
| 488 | |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 489 | HandleError(StringPrintf("failed to submit read: %s", strerror(errno))); |
Josh Gao | c0b831b | 2019-02-13 15:27:28 -0800 | [diff] [blame] | 490 | return false; |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 491 | } |
Josh Gao | c0b831b | 2019-02-13 15:27:28 -0800 | [diff] [blame] | 492 | |
| 493 | gFfsAioSupported = true; |
| 494 | return true; |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 495 | } |
| 496 | |
| 497 | void HandleWrite(TransferId id) { |
| 498 | std::lock_guard<std::mutex> lock(write_mutex_); |
| 499 | auto it = |
| 500 | std::find_if(write_requests_.begin(), write_requests_.end(), [id](const auto& req) { |
| 501 | return static_cast<uint64_t>(req->id()) == static_cast<uint64_t>(id); |
| 502 | }); |
| 503 | CHECK(it != write_requests_.end()); |
| 504 | |
| 505 | write_requests_.erase(it); |
| 506 | size_t outstanding_writes = --writes_submitted_; |
| 507 | LOG(DEBUG) << "USB write: reaped, down to " << outstanding_writes; |
| 508 | |
| 509 | SubmitWrites(); |
| 510 | } |
| 511 | |
Josh Gao | 86b33be | 2019-02-26 17:53:52 -0800 | [diff] [blame] | 512 | std::unique_ptr<IoBlock> CreateWriteBlock(std::shared_ptr<Block> payload, size_t offset, |
| 513 | size_t len, uint64_t id) { |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 514 | auto block = std::make_unique<IoBlock>(); |
| 515 | block->payload = std::move(payload); |
| 516 | block->control.aio_data = static_cast<uint64_t>(TransferId::write(id)); |
| 517 | block->control.aio_rw_flags = 0; |
| 518 | block->control.aio_lio_opcode = IOCB_CMD_PWRITE; |
| 519 | block->control.aio_reqprio = 0; |
| 520 | block->control.aio_fildes = write_fd_.get(); |
Josh Gao | 86b33be | 2019-02-26 17:53:52 -0800 | [diff] [blame] | 521 | block->control.aio_buf = reinterpret_cast<uintptr_t>(block->payload->data() + offset); |
| 522 | block->control.aio_nbytes = len; |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 523 | block->control.aio_offset = 0; |
| 524 | block->control.aio_flags = IOCB_FLAG_RESFD; |
Josh Gao | c0b831b | 2019-02-13 15:27:28 -0800 | [diff] [blame] | 525 | block->control.aio_resfd = worker_event_fd_.get(); |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 526 | return block; |
| 527 | } |
| 528 | |
Josh Gao | 86b33be | 2019-02-26 17:53:52 -0800 | [diff] [blame] | 529 | std::unique_ptr<IoBlock> CreateWriteBlock(Block payload, uint64_t id) { |
| 530 | std::shared_ptr<Block> block = std::make_shared<Block>(std::move(payload)); |
| 531 | size_t len = block->size(); |
| 532 | return CreateWriteBlock(std::move(block), 0, len, id); |
| 533 | } |
| 534 | |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 535 | void SubmitWrites() REQUIRES(write_mutex_) { |
| 536 | if (writes_submitted_ == kUsbWriteQueueDepth) { |
| 537 | return; |
| 538 | } |
| 539 | |
| 540 | ssize_t writes_to_submit = std::min(kUsbWriteQueueDepth - writes_submitted_, |
| 541 | write_requests_.size() - writes_submitted_); |
| 542 | CHECK_GE(writes_to_submit, 0); |
| 543 | if (writes_to_submit == 0) { |
| 544 | return; |
| 545 | } |
| 546 | |
| 547 | struct iocb* iocbs[kUsbWriteQueueDepth]; |
| 548 | for (int i = 0; i < writes_to_submit; ++i) { |
| 549 | CHECK(!write_requests_[writes_submitted_ + i]->pending); |
| 550 | write_requests_[writes_submitted_ + i]->pending = true; |
| 551 | iocbs[i] = &write_requests_[writes_submitted_ + i]->control; |
| 552 | LOG(VERBOSE) << "submitting write_request " << static_cast<void*>(iocbs[i]); |
| 553 | } |
| 554 | |
| 555 | int rc = io_submit(aio_context_.get(), writes_to_submit, iocbs); |
| 556 | if (rc == -1) { |
| 557 | HandleError(StringPrintf("failed to submit write requests: %s", strerror(errno))); |
| 558 | return; |
| 559 | } else if (rc != writes_to_submit) { |
| 560 | LOG(FATAL) << "failed to submit all writes: wanted to submit " << writes_to_submit |
| 561 | << ", actually submitted " << rc; |
| 562 | } |
| 563 | |
| 564 | writes_submitted_ += rc; |
| 565 | } |
| 566 | |
| 567 | void HandleError(const std::string& error) { |
| 568 | std::call_once(error_flag_, [&]() { |
| 569 | error_callback_(this, error); |
| 570 | if (!stopped_) { |
| 571 | Stop(); |
| 572 | } |
| 573 | }); |
| 574 | } |
| 575 | |
| 576 | std::thread monitor_thread_; |
| 577 | std::thread worker_thread_; |
| 578 | |
| 579 | std::atomic<bool> stopped_; |
| 580 | std::promise<void> destruction_notifier_; |
| 581 | std::once_flag error_flag_; |
| 582 | |
Josh Gao | c0b831b | 2019-02-13 15:27:28 -0800 | [diff] [blame] | 583 | unique_fd worker_event_fd_; |
| 584 | unique_fd monitor_event_fd_; |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 585 | |
| 586 | ScopedAioContext aio_context_; |
| 587 | unique_fd control_fd_; |
| 588 | unique_fd read_fd_; |
| 589 | unique_fd write_fd_; |
| 590 | |
| 591 | std::optional<amessage> incoming_header_; |
| 592 | IOVector incoming_payload_; |
| 593 | |
| 594 | std::array<IoBlock, kUsbReadQueueDepth> read_requests_; |
| 595 | IOVector read_data_; |
| 596 | |
| 597 | // ID of the next request that we're going to send out. |
| 598 | size_t next_read_id_ = 0; |
| 599 | |
| 600 | // ID of the next packet we're waiting for. |
| 601 | size_t needed_read_id_ = 0; |
| 602 | |
| 603 | std::mutex write_mutex_; |
| 604 | std::deque<std::unique_ptr<IoBlock>> write_requests_ GUARDED_BY(write_mutex_); |
| 605 | size_t next_write_id_ GUARDED_BY(write_mutex_) = 0; |
| 606 | size_t writes_submitted_ GUARDED_BY(write_mutex_) = 0; |
Josh Gao | e778b3a | 2019-02-28 13:29:32 -0800 | [diff] [blame] | 607 | |
| 608 | static constexpr int kInterruptionSignal = SIGUSR1; |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 609 | }; |
| 610 | |
Josh Gao | c0b831b | 2019-02-13 15:27:28 -0800 | [diff] [blame] | 611 | void usb_init_legacy(); |
| 612 | |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 613 | static void usb_ffs_open_thread() { |
| 614 | adb_thread_setname("usb ffs open"); |
| 615 | |
| 616 | while (true) { |
Josh Gao | c0b831b | 2019-02-13 15:27:28 -0800 | [diff] [blame] | 617 | if (gFfsAioSupported.has_value() && !gFfsAioSupported.value()) { |
| 618 | LOG(INFO) << "failed to use nonblocking ffs, falling back to legacy"; |
| 619 | return usb_init_legacy(); |
| 620 | } |
| 621 | |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 622 | unique_fd control; |
| 623 | unique_fd bulk_out; |
| 624 | unique_fd bulk_in; |
| 625 | if (!open_functionfs(&control, &bulk_out, &bulk_in)) { |
| 626 | std::this_thread::sleep_for(1s); |
| 627 | continue; |
| 628 | } |
| 629 | |
| 630 | atransport* transport = new atransport(); |
| 631 | transport->serial = "UsbFfs"; |
| 632 | std::promise<void> destruction_notifier; |
| 633 | std::future<void> future = destruction_notifier.get_future(); |
| 634 | transport->SetConnection(std::make_unique<UsbFfsConnection>( |
| 635 | std::move(control), std::move(bulk_out), std::move(bulk_in), |
| 636 | std::move(destruction_notifier))); |
| 637 | register_transport(transport); |
| 638 | future.wait(); |
| 639 | } |
| 640 | } |
| 641 | |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 642 | void usb_init() { |
Josh Gao | 02e94a4 | 2019-02-28 07:26:20 +0000 | [diff] [blame] | 643 | bool use_nonblocking = android::base::GetBoolProperty("persist.adb.nonblocking_ffs", true); |
| 644 | if (use_nonblocking) { |
Josh Gao | 0d78039 | 2019-02-26 22:10:33 +0000 | [diff] [blame] | 645 | std::thread(usb_ffs_open_thread).detach(); |
Josh Gao | 02e94a4 | 2019-02-28 07:26:20 +0000 | [diff] [blame] | 646 | } else { |
| 647 | usb_init_legacy(); |
Josh Gao | c51726c | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 648 | } |
| 649 | } |