Josh Gao | 3a34bc5 | 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 | b9727b0 | 2019-02-26 17:53:52 -0800 | [diff] [blame^] | 32 | #include <algorithm> |
Josh Gao | 3a34bc5 | 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 | b8afeea | 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 | 3a34bc5 | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 60 | static constexpr size_t kUsbReadQueueDepth = 16; |
| 61 | static constexpr size_t kUsbReadSize = 16384; |
| 62 | |
| 63 | static constexpr size_t kUsbWriteQueueDepth = 16; |
Josh Gao | b9727b0 | 2019-02-26 17:53:52 -0800 | [diff] [blame^] | 64 | static constexpr size_t kUsbWriteSize = 16 * PAGE_SIZE; |
Josh Gao | 3a34bc5 | 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 { |
| 118 | bool pending; |
| 119 | struct iocb control; |
Josh Gao | b9727b0 | 2019-02-26 17:53:52 -0800 | [diff] [blame^] | 120 | std::shared_ptr<Block> payload; |
Josh Gao | 3a34bc5 | 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 | b8afeea | 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 | 3a34bc5 | 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 | b8afeea | 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 | 3a34bc5 | 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 | b9727b0 | 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 | 3a34bc5 | 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 | b8afeea | 2019-02-13 15:27:28 -0800 | [diff] [blame] | 239 | ssize_t rc = adb_write(worker_event_fd_.get(), ¬ify, sizeof(notify)); |
Josh Gao | 3a34bc5 | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 240 | if (rc < 0) { |
Josh Gao | b8afeea | 2019-02-13 15:27:28 -0800 | [diff] [blame] | 241 | PLOG(FATAL) << "failed to notify worker eventfd to stop UsbFfsConnection"; |
Josh Gao | 3a34bc5 | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 242 | } |
| 243 | CHECK_EQ(static_cast<size_t>(rc), sizeof(notify)); |
Josh Gao | b8afeea | 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 | 3a34bc5 | 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. |
| 263 | static constexpr int kInterruptionSignal = SIGUSR1; |
| 264 | static std::once_flag handler_once; |
| 265 | std::call_once(handler_once, []() { signal(kInterruptionSignal, [](int) {}); }); |
| 266 | |
| 267 | monitor_thread_ = std::thread([this]() { |
| 268 | adb_thread_setname("UsbFfs-monitor"); |
| 269 | |
| 270 | bool bound = false; |
| 271 | bool started = false; |
| 272 | bool running = true; |
| 273 | while (running) { |
Josh Gao | b8afeea | 2019-02-13 15:27:28 -0800 | [diff] [blame] | 274 | int timeout = -1; |
Josh Gao | 3a34bc5 | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 275 | if (!bound || !started) { |
Josh Gao | b8afeea | 2019-02-13 15:27:28 -0800 | [diff] [blame] | 276 | timeout = 5000 /*ms*/; |
| 277 | } |
| 278 | |
| 279 | adb_pollfd pfd[2] = { |
| 280 | { .fd = control_fd_.get(), .events = POLLIN, .revents = 0 }, |
| 281 | { .fd = monitor_event_fd_.get(), .events = POLLIN, .revents = 0 }, |
| 282 | }; |
| 283 | int rc = TEMP_FAILURE_RETRY(adb_poll(pfd, 2, timeout)); |
| 284 | if (rc == -1) { |
| 285 | PLOG(FATAL) << "poll on USB control fd failed"; |
| 286 | } else if (rc == 0) { |
| 287 | // Something in the kernel presumably went wrong. |
| 288 | // Close our endpoints, wait for a bit, and then try again. |
| 289 | aio_context_.reset(); |
| 290 | read_fd_.reset(); |
| 291 | write_fd_.reset(); |
| 292 | control_fd_.reset(); |
| 293 | std::this_thread::sleep_for(5s); |
| 294 | HandleError("didn't receive FUNCTIONFS_ENABLE, retrying"); |
| 295 | return; |
| 296 | } |
| 297 | |
| 298 | if (pfd[1].revents) { |
| 299 | // We were told to die. |
| 300 | break; |
Josh Gao | 3a34bc5 | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 301 | } |
| 302 | |
| 303 | struct usb_functionfs_event event; |
| 304 | if (TEMP_FAILURE_RETRY(adb_read(control_fd_.get(), &event, sizeof(event))) != |
| 305 | sizeof(event)) { |
| 306 | PLOG(FATAL) << "failed to read functionfs event"; |
| 307 | } |
| 308 | |
| 309 | LOG(INFO) << "USB event: " |
| 310 | << to_string(static_cast<usb_functionfs_event_type>(event.type)); |
| 311 | |
| 312 | switch (event.type) { |
| 313 | case FUNCTIONFS_BIND: |
| 314 | CHECK(!started) << "received FUNCTIONFS_ENABLE while already bound?"; |
| 315 | bound = true; |
| 316 | break; |
| 317 | |
| 318 | case FUNCTIONFS_ENABLE: |
| 319 | CHECK(!started) << "received FUNCTIONFS_ENABLE while already running?"; |
| 320 | started = true; |
| 321 | StartWorker(); |
| 322 | break; |
| 323 | |
| 324 | case FUNCTIONFS_DISABLE: |
| 325 | running = false; |
| 326 | break; |
| 327 | } |
| 328 | } |
| 329 | |
| 330 | pthread_t worker_thread_handle = worker_thread_.native_handle(); |
| 331 | while (true) { |
| 332 | int rc = pthread_kill(worker_thread_handle, kInterruptionSignal); |
| 333 | if (rc != 0) { |
| 334 | LOG(ERROR) << "failed to send interruption signal to worker: " << strerror(rc); |
| 335 | break; |
| 336 | } |
| 337 | |
| 338 | std::this_thread::sleep_for(100ms); |
| 339 | |
| 340 | rc = pthread_kill(worker_thread_handle, 0); |
| 341 | if (rc == 0) { |
| 342 | continue; |
| 343 | } else if (rc == ESRCH) { |
| 344 | break; |
| 345 | } else { |
| 346 | LOG(ERROR) << "failed to send interruption signal to worker: " << strerror(rc); |
| 347 | } |
| 348 | } |
| 349 | |
| 350 | worker_thread_.join(); |
| 351 | |
| 352 | aio_context_.reset(); |
| 353 | read_fd_.reset(); |
| 354 | write_fd_.reset(); |
| 355 | }); |
| 356 | } |
| 357 | |
| 358 | void StartWorker() { |
| 359 | worker_thread_ = std::thread([this]() { |
| 360 | adb_thread_setname("UsbFfs-worker"); |
| 361 | for (size_t i = 0; i < kUsbReadQueueDepth; ++i) { |
| 362 | read_requests_[i] = CreateReadBlock(next_read_id_++); |
Josh Gao | b8afeea | 2019-02-13 15:27:28 -0800 | [diff] [blame] | 363 | if (!SubmitRead(&read_requests_[i])) { |
| 364 | return; |
| 365 | } |
Josh Gao | 3a34bc5 | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 366 | } |
| 367 | |
| 368 | while (!stopped_) { |
| 369 | uint64_t dummy; |
Josh Gao | b8afeea | 2019-02-13 15:27:28 -0800 | [diff] [blame] | 370 | ssize_t rc = adb_read(worker_event_fd_.get(), &dummy, sizeof(dummy)); |
Josh Gao | 3a34bc5 | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 371 | if (rc == -1) { |
| 372 | PLOG(FATAL) << "failed to read from eventfd"; |
| 373 | } else if (rc == 0) { |
| 374 | LOG(FATAL) << "hit EOF on eventfd"; |
| 375 | } |
| 376 | |
| 377 | WaitForEvents(); |
| 378 | } |
| 379 | }); |
| 380 | } |
| 381 | |
| 382 | void PrepareReadBlock(IoBlock* block, uint64_t id) { |
| 383 | block->pending = false; |
Josh Gao | b9727b0 | 2019-02-26 17:53:52 -0800 | [diff] [blame^] | 384 | block->payload = std::make_shared<Block>(kUsbReadSize); |
Josh Gao | 3a34bc5 | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 385 | block->control.aio_data = static_cast<uint64_t>(TransferId::read(id)); |
Josh Gao | b9727b0 | 2019-02-26 17:53:52 -0800 | [diff] [blame^] | 386 | block->control.aio_buf = reinterpret_cast<uintptr_t>(block->payload->data()); |
| 387 | block->control.aio_nbytes = block->payload->size(); |
Josh Gao | 3a34bc5 | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 388 | } |
| 389 | |
| 390 | IoBlock CreateReadBlock(uint64_t id) { |
| 391 | IoBlock block; |
| 392 | PrepareReadBlock(&block, id); |
| 393 | block.control.aio_rw_flags = 0; |
| 394 | block.control.aio_lio_opcode = IOCB_CMD_PREAD; |
| 395 | block.control.aio_reqprio = 0; |
| 396 | block.control.aio_fildes = read_fd_.get(); |
| 397 | block.control.aio_offset = 0; |
| 398 | block.control.aio_flags = IOCB_FLAG_RESFD; |
Josh Gao | b8afeea | 2019-02-13 15:27:28 -0800 | [diff] [blame] | 399 | block.control.aio_resfd = worker_event_fd_.get(); |
Josh Gao | 3a34bc5 | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 400 | return block; |
| 401 | } |
| 402 | |
| 403 | void WaitForEvents() { |
| 404 | static constexpr size_t kMaxEvents = kUsbReadQueueDepth + kUsbWriteQueueDepth; |
| 405 | struct io_event events[kMaxEvents]; |
| 406 | struct timespec timeout = {.tv_sec = 0, .tv_nsec = 0}; |
| 407 | int rc = io_getevents(aio_context_.get(), 0, kMaxEvents, events, &timeout); |
| 408 | if (rc == -1) { |
| 409 | HandleError(StringPrintf("io_getevents failed while reading: %s", strerror(errno))); |
| 410 | return; |
| 411 | } |
| 412 | |
| 413 | for (int event_idx = 0; event_idx < rc; ++event_idx) { |
| 414 | auto& event = events[event_idx]; |
| 415 | TransferId id = TransferId::from_value(event.data); |
| 416 | |
| 417 | if (event.res < 0) { |
| 418 | std::string error = |
| 419 | StringPrintf("%s %" PRIu64 " failed with error %s", |
| 420 | id.direction == TransferDirection::READ ? "read" : "write", |
| 421 | id.id, strerror(-event.res)); |
| 422 | HandleError(error); |
| 423 | return; |
| 424 | } |
| 425 | |
| 426 | if (id.direction == TransferDirection::READ) { |
| 427 | HandleRead(id, event.res); |
| 428 | } else { |
| 429 | HandleWrite(id); |
| 430 | } |
| 431 | } |
| 432 | } |
| 433 | |
| 434 | void HandleRead(TransferId id, int64_t size) { |
| 435 | uint64_t read_idx = id.id % kUsbReadQueueDepth; |
| 436 | IoBlock* block = &read_requests_[read_idx]; |
| 437 | block->pending = false; |
Josh Gao | b9727b0 | 2019-02-26 17:53:52 -0800 | [diff] [blame^] | 438 | block->payload->resize(size); |
Josh Gao | 3a34bc5 | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 439 | |
| 440 | // Notification for completed reads can be received out of order. |
| 441 | if (block->id().id != needed_read_id_) { |
| 442 | LOG(VERBOSE) << "read " << block->id().id << " completed while waiting for " |
| 443 | << needed_read_id_; |
| 444 | return; |
| 445 | } |
| 446 | |
| 447 | for (uint64_t id = needed_read_id_;; ++id) { |
| 448 | size_t read_idx = id % kUsbReadQueueDepth; |
| 449 | IoBlock* current_block = &read_requests_[read_idx]; |
| 450 | if (current_block->pending) { |
| 451 | break; |
| 452 | } |
| 453 | ProcessRead(current_block); |
| 454 | ++needed_read_id_; |
| 455 | } |
| 456 | } |
| 457 | |
| 458 | void ProcessRead(IoBlock* block) { |
Josh Gao | b9727b0 | 2019-02-26 17:53:52 -0800 | [diff] [blame^] | 459 | if (!block->payload->empty()) { |
Josh Gao | 3a34bc5 | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 460 | if (!incoming_header_.has_value()) { |
Josh Gao | b9727b0 | 2019-02-26 17:53:52 -0800 | [diff] [blame^] | 461 | CHECK_EQ(sizeof(amessage), block->payload->size()); |
Josh Gao | 3a34bc5 | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 462 | amessage msg; |
Josh Gao | b9727b0 | 2019-02-26 17:53:52 -0800 | [diff] [blame^] | 463 | memcpy(&msg, block->payload->data(), sizeof(amessage)); |
Josh Gao | 3a34bc5 | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 464 | LOG(DEBUG) << "USB read:" << dump_header(&msg); |
| 465 | incoming_header_ = msg; |
| 466 | } else { |
| 467 | size_t bytes_left = incoming_header_->data_length - incoming_payload_.size(); |
Josh Gao | b9727b0 | 2019-02-26 17:53:52 -0800 | [diff] [blame^] | 468 | Block payload = std::move(*block->payload); |
Josh Gao | 3a34bc5 | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 469 | CHECK_LE(payload.size(), bytes_left); |
| 470 | incoming_payload_.append(std::make_unique<Block>(std::move(payload))); |
| 471 | } |
| 472 | |
| 473 | if (incoming_header_->data_length == incoming_payload_.size()) { |
| 474 | auto packet = std::make_unique<apacket>(); |
| 475 | packet->msg = *incoming_header_; |
| 476 | |
| 477 | // TODO: Make apacket contain an IOVector so we don't have to coalesce. |
| 478 | packet->payload = incoming_payload_.coalesce(); |
| 479 | read_callback_(this, std::move(packet)); |
| 480 | |
| 481 | incoming_header_.reset(); |
| 482 | incoming_payload_.clear(); |
| 483 | } |
| 484 | } |
| 485 | |
| 486 | PrepareReadBlock(block, block->id().id + kUsbReadQueueDepth); |
| 487 | SubmitRead(block); |
| 488 | } |
| 489 | |
Josh Gao | b8afeea | 2019-02-13 15:27:28 -0800 | [diff] [blame] | 490 | bool SubmitRead(IoBlock* block) { |
Josh Gao | 3a34bc5 | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 491 | block->pending = true; |
| 492 | struct iocb* iocb = &block->control; |
| 493 | if (io_submit(aio_context_.get(), 1, &iocb) != 1) { |
Josh Gao | b8afeea | 2019-02-13 15:27:28 -0800 | [diff] [blame] | 494 | if (errno == EINVAL && !gFfsAioSupported.has_value()) { |
| 495 | HandleError("failed to submit first read, AIO on FFS not supported"); |
| 496 | gFfsAioSupported = false; |
| 497 | return false; |
| 498 | } |
| 499 | |
Josh Gao | 3a34bc5 | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 500 | HandleError(StringPrintf("failed to submit read: %s", strerror(errno))); |
Josh Gao | b8afeea | 2019-02-13 15:27:28 -0800 | [diff] [blame] | 501 | return false; |
Josh Gao | 3a34bc5 | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 502 | } |
Josh Gao | b8afeea | 2019-02-13 15:27:28 -0800 | [diff] [blame] | 503 | |
| 504 | gFfsAioSupported = true; |
| 505 | return true; |
Josh Gao | 3a34bc5 | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 506 | } |
| 507 | |
| 508 | void HandleWrite(TransferId id) { |
| 509 | std::lock_guard<std::mutex> lock(write_mutex_); |
| 510 | auto it = |
| 511 | std::find_if(write_requests_.begin(), write_requests_.end(), [id](const auto& req) { |
| 512 | return static_cast<uint64_t>(req->id()) == static_cast<uint64_t>(id); |
| 513 | }); |
| 514 | CHECK(it != write_requests_.end()); |
| 515 | |
| 516 | write_requests_.erase(it); |
| 517 | size_t outstanding_writes = --writes_submitted_; |
| 518 | LOG(DEBUG) << "USB write: reaped, down to " << outstanding_writes; |
| 519 | |
| 520 | SubmitWrites(); |
| 521 | } |
| 522 | |
Josh Gao | b9727b0 | 2019-02-26 17:53:52 -0800 | [diff] [blame^] | 523 | std::unique_ptr<IoBlock> CreateWriteBlock(std::shared_ptr<Block> payload, size_t offset, |
| 524 | size_t len, uint64_t id) { |
Josh Gao | 3a34bc5 | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 525 | auto block = std::make_unique<IoBlock>(); |
| 526 | block->payload = std::move(payload); |
| 527 | block->control.aio_data = static_cast<uint64_t>(TransferId::write(id)); |
| 528 | block->control.aio_rw_flags = 0; |
| 529 | block->control.aio_lio_opcode = IOCB_CMD_PWRITE; |
| 530 | block->control.aio_reqprio = 0; |
| 531 | block->control.aio_fildes = write_fd_.get(); |
Josh Gao | b9727b0 | 2019-02-26 17:53:52 -0800 | [diff] [blame^] | 532 | block->control.aio_buf = reinterpret_cast<uintptr_t>(block->payload->data() + offset); |
| 533 | block->control.aio_nbytes = len; |
Josh Gao | 3a34bc5 | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 534 | block->control.aio_offset = 0; |
| 535 | block->control.aio_flags = IOCB_FLAG_RESFD; |
Josh Gao | b8afeea | 2019-02-13 15:27:28 -0800 | [diff] [blame] | 536 | block->control.aio_resfd = worker_event_fd_.get(); |
Josh Gao | 3a34bc5 | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 537 | return block; |
| 538 | } |
| 539 | |
Josh Gao | b9727b0 | 2019-02-26 17:53:52 -0800 | [diff] [blame^] | 540 | std::unique_ptr<IoBlock> CreateWriteBlock(Block payload, uint64_t id) { |
| 541 | std::shared_ptr<Block> block = std::make_shared<Block>(std::move(payload)); |
| 542 | size_t len = block->size(); |
| 543 | return CreateWriteBlock(std::move(block), 0, len, id); |
| 544 | } |
| 545 | |
Josh Gao | 3a34bc5 | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 546 | void SubmitWrites() REQUIRES(write_mutex_) { |
| 547 | if (writes_submitted_ == kUsbWriteQueueDepth) { |
| 548 | return; |
| 549 | } |
| 550 | |
| 551 | ssize_t writes_to_submit = std::min(kUsbWriteQueueDepth - writes_submitted_, |
| 552 | write_requests_.size() - writes_submitted_); |
| 553 | CHECK_GE(writes_to_submit, 0); |
| 554 | if (writes_to_submit == 0) { |
| 555 | return; |
| 556 | } |
| 557 | |
| 558 | struct iocb* iocbs[kUsbWriteQueueDepth]; |
| 559 | for (int i = 0; i < writes_to_submit; ++i) { |
| 560 | CHECK(!write_requests_[writes_submitted_ + i]->pending); |
| 561 | write_requests_[writes_submitted_ + i]->pending = true; |
| 562 | iocbs[i] = &write_requests_[writes_submitted_ + i]->control; |
| 563 | LOG(VERBOSE) << "submitting write_request " << static_cast<void*>(iocbs[i]); |
| 564 | } |
| 565 | |
| 566 | int rc = io_submit(aio_context_.get(), writes_to_submit, iocbs); |
| 567 | if (rc == -1) { |
| 568 | HandleError(StringPrintf("failed to submit write requests: %s", strerror(errno))); |
| 569 | return; |
| 570 | } else if (rc != writes_to_submit) { |
| 571 | LOG(FATAL) << "failed to submit all writes: wanted to submit " << writes_to_submit |
| 572 | << ", actually submitted " << rc; |
| 573 | } |
| 574 | |
| 575 | writes_submitted_ += rc; |
| 576 | } |
| 577 | |
| 578 | void HandleError(const std::string& error) { |
| 579 | std::call_once(error_flag_, [&]() { |
| 580 | error_callback_(this, error); |
| 581 | if (!stopped_) { |
| 582 | Stop(); |
| 583 | } |
| 584 | }); |
| 585 | } |
| 586 | |
| 587 | std::thread monitor_thread_; |
| 588 | std::thread worker_thread_; |
| 589 | |
| 590 | std::atomic<bool> stopped_; |
| 591 | std::promise<void> destruction_notifier_; |
| 592 | std::once_flag error_flag_; |
| 593 | |
Josh Gao | b8afeea | 2019-02-13 15:27:28 -0800 | [diff] [blame] | 594 | unique_fd worker_event_fd_; |
| 595 | unique_fd monitor_event_fd_; |
Josh Gao | 3a34bc5 | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 596 | |
| 597 | ScopedAioContext aio_context_; |
| 598 | unique_fd control_fd_; |
| 599 | unique_fd read_fd_; |
| 600 | unique_fd write_fd_; |
| 601 | |
| 602 | std::optional<amessage> incoming_header_; |
| 603 | IOVector incoming_payload_; |
| 604 | |
| 605 | std::array<IoBlock, kUsbReadQueueDepth> read_requests_; |
| 606 | IOVector read_data_; |
| 607 | |
| 608 | // ID of the next request that we're going to send out. |
| 609 | size_t next_read_id_ = 0; |
| 610 | |
| 611 | // ID of the next packet we're waiting for. |
| 612 | size_t needed_read_id_ = 0; |
| 613 | |
| 614 | std::mutex write_mutex_; |
| 615 | std::deque<std::unique_ptr<IoBlock>> write_requests_ GUARDED_BY(write_mutex_); |
| 616 | size_t next_write_id_ GUARDED_BY(write_mutex_) = 0; |
| 617 | size_t writes_submitted_ GUARDED_BY(write_mutex_) = 0; |
| 618 | }; |
| 619 | |
Josh Gao | b8afeea | 2019-02-13 15:27:28 -0800 | [diff] [blame] | 620 | void usb_init_legacy(); |
| 621 | |
Josh Gao | 3a34bc5 | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 622 | static void usb_ffs_open_thread() { |
| 623 | adb_thread_setname("usb ffs open"); |
| 624 | |
| 625 | while (true) { |
Josh Gao | b8afeea | 2019-02-13 15:27:28 -0800 | [diff] [blame] | 626 | if (gFfsAioSupported.has_value() && !gFfsAioSupported.value()) { |
| 627 | LOG(INFO) << "failed to use nonblocking ffs, falling back to legacy"; |
| 628 | return usb_init_legacy(); |
| 629 | } |
| 630 | |
Josh Gao | 3a34bc5 | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 631 | unique_fd control; |
| 632 | unique_fd bulk_out; |
| 633 | unique_fd bulk_in; |
| 634 | if (!open_functionfs(&control, &bulk_out, &bulk_in)) { |
| 635 | std::this_thread::sleep_for(1s); |
| 636 | continue; |
| 637 | } |
| 638 | |
| 639 | atransport* transport = new atransport(); |
| 640 | transport->serial = "UsbFfs"; |
| 641 | std::promise<void> destruction_notifier; |
| 642 | std::future<void> future = destruction_notifier.get_future(); |
| 643 | transport->SetConnection(std::make_unique<UsbFfsConnection>( |
| 644 | std::move(control), std::move(bulk_out), std::move(bulk_in), |
| 645 | std::move(destruction_notifier))); |
| 646 | register_transport(transport); |
| 647 | future.wait(); |
| 648 | } |
| 649 | } |
| 650 | |
Josh Gao | 3a34bc5 | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 651 | void usb_init() { |
Josh Gao | a8d018c | 2019-02-26 22:10:33 +0000 | [diff] [blame] | 652 | if (!android::base::GetBoolProperty("persist.adb.nonblocking_ffs", false)) { |
Josh Gao | 52bce2d | 2019-02-04 13:18:54 -0800 | [diff] [blame] | 653 | usb_init_legacy(); |
Josh Gao | a8d018c | 2019-02-26 22:10:33 +0000 | [diff] [blame] | 654 | } else { |
| 655 | std::thread(usb_ffs_open_thread).detach(); |
Josh Gao | 3a34bc5 | 2018-10-11 16:33:05 -0700 | [diff] [blame] | 656 | } |
| 657 | } |