blob: 8c33ca58046f574e1cd8c6ac2f60d01d00f34a8e [file] [log] [blame]
Josh Gaoc51726c2018-10-11 16:33:05 -07001/*
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 Gao86b33be2019-02-26 17:53:52 -080032#include <algorithm>
Josh Gaoc51726c2018-10-11 16:33:05 -070033#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
55using android::base::StringPrintf;
56
Josh Gaoc0b831b2019-02-13 15:27:28 -080057// We can't find out whether we have support for AIO on ffs endpoints until we submit a read.
58static std::optional<bool> gFfsAioSupported;
59
Josh Gao5841a962019-02-28 15:44:05 -080060static constexpr size_t kUsbReadQueueDepth = 32;
61static constexpr size_t kUsbReadSize = 8 * PAGE_SIZE;
Josh Gaoc51726c2018-10-11 16:33:05 -070062
Josh Gao5841a962019-02-28 15:44:05 -080063static constexpr size_t kUsbWriteQueueDepth = 32;
64static constexpr size_t kUsbWriteSize = 8 * PAGE_SIZE;
Josh Gaoc51726c2018-10-11 16:33:05 -070065
66static 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
85enum class TransferDirection : uint64_t {
86 READ = 0,
87 WRITE = 1,
88};
89
90struct 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
117struct IoBlock {
Josh Gaob0195742019-03-18 14:11:28 -0700118 bool pending = false;
Josh Gaoc51726c2018-10-11 16:33:05 -0700119 struct iocb control;
Josh Gao86b33be2019-02-26 17:53:52 -0800120 std::shared_ptr<Block> payload;
Josh Gaoc51726c2018-10-11 16:33:05 -0700121
122 TransferId id() const { return TransferId::from_value(control.aio_data); }
123};
124
125struct 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
168struct UsbFfsConnection : public Connection {
169 UsbFfsConnection(unique_fd control, unique_fd read, unique_fd write,
170 std::promise<void> destruction_notifier)
Josh Gao19dc2962019-03-26 18:47:45 -0700171 : worker_started_(false),
172 stopped_(false),
Josh Gaoc51726c2018-10-11 16:33:05 -0700173 destruction_notifier_(std::move(destruction_notifier)),
174 control_fd_(std::move(control)),
175 read_fd_(std::move(read)),
176 write_fd_(std::move(write)) {
177 LOG(INFO) << "UsbFfsConnection constructed";
Josh Gaoc0b831b2019-02-13 15:27:28 -0800178 worker_event_fd_.reset(eventfd(0, EFD_CLOEXEC));
179 if (worker_event_fd_ == -1) {
180 PLOG(FATAL) << "failed to create eventfd";
181 }
182
183 monitor_event_fd_.reset(eventfd(0, EFD_CLOEXEC));
184 if (monitor_event_fd_ == -1) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700185 PLOG(FATAL) << "failed to create eventfd";
186 }
187
188 aio_context_ = ScopedAioContext::Create(kUsbReadQueueDepth + kUsbWriteQueueDepth);
189 }
190
191 ~UsbFfsConnection() {
192 LOG(INFO) << "UsbFfsConnection being destroyed";
193 Stop();
194 monitor_thread_.join();
Josh Gaoc0b831b2019-02-13 15:27:28 -0800195
196 // We need to explicitly close our file descriptors before we notify our destruction,
197 // because the thread listening on the future will immediately try to reopen the endpoint.
Josh Gao19dc2962019-03-26 18:47:45 -0700198 aio_context_.reset();
Josh Gaoc0b831b2019-02-13 15:27:28 -0800199 control_fd_.reset();
200 read_fd_.reset();
201 write_fd_.reset();
202
Josh Gaoc51726c2018-10-11 16:33:05 -0700203 destruction_notifier_.set_value();
204 }
205
206 virtual bool Write(std::unique_ptr<apacket> packet) override final {
207 LOG(DEBUG) << "USB write: " << dump_header(&packet->msg);
208 Block header(sizeof(packet->msg));
209 memcpy(header.data(), &packet->msg, sizeof(packet->msg));
210
211 std::lock_guard<std::mutex> lock(write_mutex_);
212 write_requests_.push_back(CreateWriteBlock(std::move(header), next_write_id_++));
213 if (!packet->payload.empty()) {
Josh Gao86b33be2019-02-26 17:53:52 -0800214 // The kernel attempts to allocate a contiguous block of memory for each write,
215 // which can fail if the write is large and the kernel heap is fragmented.
216 // Split large writes into smaller chunks to avoid this.
217 std::shared_ptr<Block> payload = std::make_shared<Block>(std::move(packet->payload));
218 size_t offset = 0;
219 size_t len = payload->size();
220
221 while (len > 0) {
222 size_t write_size = std::min(kUsbWriteSize, len);
223 write_requests_.push_back(
224 CreateWriteBlock(payload, offset, write_size, next_write_id_++));
225 len -= write_size;
226 offset += write_size;
227 }
Josh Gaoc51726c2018-10-11 16:33:05 -0700228 }
229 SubmitWrites();
230 return true;
231 }
232
233 virtual void Start() override final { StartMonitor(); }
234
235 virtual void Stop() override final {
236 if (stopped_.exchange(true)) {
237 return;
238 }
239 stopped_ = true;
240 uint64_t notify = 1;
Josh Gaoc0b831b2019-02-13 15:27:28 -0800241 ssize_t rc = adb_write(worker_event_fd_.get(), &notify, sizeof(notify));
Josh Gaoc51726c2018-10-11 16:33:05 -0700242 if (rc < 0) {
Josh Gaoc0b831b2019-02-13 15:27:28 -0800243 PLOG(FATAL) << "failed to notify worker eventfd to stop UsbFfsConnection";
Josh Gaoc51726c2018-10-11 16:33:05 -0700244 }
245 CHECK_EQ(static_cast<size_t>(rc), sizeof(notify));
Josh Gaoc0b831b2019-02-13 15:27:28 -0800246
247 rc = adb_write(monitor_event_fd_.get(), &notify, sizeof(notify));
248 if (rc < 0) {
249 PLOG(FATAL) << "failed to notify monitor eventfd to stop UsbFfsConnection";
250 }
251
252 CHECK_EQ(static_cast<size_t>(rc), sizeof(notify));
Josh Gaoc51726c2018-10-11 16:33:05 -0700253 }
254
255 private:
256 void StartMonitor() {
257 // This is a bit of a mess.
258 // It's possible for io_submit to end up blocking, if we call it as the endpoint
259 // becomes disabled. Work around this by having a monitor thread to listen for functionfs
260 // lifecycle events. If we notice an error condition (either we've become disabled, or we
261 // were never enabled in the first place), we send interruption signals to the worker thread
262 // until it dies, and then report failure to the transport via HandleError, which will
263 // eventually result in the transport being destroyed, which will result in UsbFfsConnection
264 // being destroyed, which unblocks the open thread and restarts this entire process.
Josh Gaoc51726c2018-10-11 16:33:05 -0700265 static std::once_flag handler_once;
266 std::call_once(handler_once, []() { signal(kInterruptionSignal, [](int) {}); });
267
268 monitor_thread_ = std::thread([this]() {
269 adb_thread_setname("UsbFfs-monitor");
270
271 bool bound = false;
Josh Gao6933d542019-03-26 13:21:42 -0700272 bool enabled = false;
Josh Gaoc51726c2018-10-11 16:33:05 -0700273 bool running = true;
274 while (running) {
Josh Gaoc0b831b2019-02-13 15:27:28 -0800275 adb_pollfd pfd[2] = {
276 { .fd = control_fd_.get(), .events = POLLIN, .revents = 0 },
277 { .fd = monitor_event_fd_.get(), .events = POLLIN, .revents = 0 },
278 };
Josh Gao19dc2962019-03-26 18:47:45 -0700279
280 // If we don't see our first bind within a second, try again.
281 int timeout_ms = bound ? -1 : 1000;
282
283 int rc = TEMP_FAILURE_RETRY(adb_poll(pfd, 2, timeout_ms));
Josh Gaoc0b831b2019-02-13 15:27:28 -0800284 if (rc == -1) {
285 PLOG(FATAL) << "poll on USB control fd failed";
286 } else if (rc == 0) {
Josh Gao19dc2962019-03-26 18:47:45 -0700287 LOG(WARNING) << "timed out while waiting for FUNCTIONFS_BIND, trying again";
288 break;
Josh Gaoc0b831b2019-02-13 15:27:28 -0800289 }
290
291 if (pfd[1].revents) {
292 // We were told to die.
293 break;
Josh Gaoc51726c2018-10-11 16:33:05 -0700294 }
295
296 struct usb_functionfs_event event;
297 if (TEMP_FAILURE_RETRY(adb_read(control_fd_.get(), &event, sizeof(event))) !=
298 sizeof(event)) {
299 PLOG(FATAL) << "failed to read functionfs event";
300 }
301
302 LOG(INFO) << "USB event: "
303 << to_string(static_cast<usb_functionfs_event_type>(event.type));
304
305 switch (event.type) {
306 case FUNCTIONFS_BIND:
Josh Gao87afd522019-03-28 11:05:53 -0700307 if (bound) {
308 LOG(WARNING) << "received FUNCTIONFS_BIND while already bound?";
309 running = false;
310 }
Josh Gao6933d542019-03-26 13:21:42 -0700311
Josh Gao87afd522019-03-28 11:05:53 -0700312 if (enabled) {
313 LOG(WARNING) << "received FUNCTIONFS_BIND while already enabled?";
314 running = false;
315 }
316
317 bound = true;
Josh Gaoc51726c2018-10-11 16:33:05 -0700318 break;
319
320 case FUNCTIONFS_ENABLE:
Josh Gao87afd522019-03-28 11:05:53 -0700321 if (!bound) {
322 LOG(WARNING) << "received FUNCTIONFS_ENABLE while not bound?";
323 running = false;
324 }
Josh Gao6933d542019-03-26 13:21:42 -0700325
Josh Gao87afd522019-03-28 11:05:53 -0700326 if (enabled) {
327 LOG(WARNING) << "received FUNCTIONFS_ENABLE while already enabled?";
328 running = false;
329 }
330
331 enabled = true;
Josh Gaoc51726c2018-10-11 16:33:05 -0700332 StartWorker();
333 break;
334
335 case FUNCTIONFS_DISABLE:
Josh Gao87afd522019-03-28 11:05:53 -0700336 if (!bound) {
337 LOG(WARNING) << "received FUNCTIONFS_DISABLE while not bound?";
338 }
Josh Gao6933d542019-03-26 13:21:42 -0700339
Josh Gao87afd522019-03-28 11:05:53 -0700340 if (!enabled) {
341 LOG(WARNING) << "received FUNCTIONFS_DISABLE while not enabled?";
342 }
343
344 enabled = false;
Josh Gao6933d542019-03-26 13:21:42 -0700345 running = false;
346 break;
347
348 case FUNCTIONFS_UNBIND:
Josh Gao87afd522019-03-28 11:05:53 -0700349 if (enabled) {
350 LOG(WARNING) << "received FUNCTIONFS_UNBIND while still enabled?";
351 }
Josh Gao6933d542019-03-26 13:21:42 -0700352
Josh Gao87afd522019-03-28 11:05:53 -0700353 if (!bound) {
354 LOG(WARNING) << "received FUNCTIONFS_UNBIND when not bound?";
355 }
356
357 bound = false;
Josh Gaoc51726c2018-10-11 16:33:05 -0700358 running = false;
359 break;
360 }
361 }
362
Josh Gaoe778b3a2019-02-28 13:29:32 -0800363 StopWorker();
Josh Gao19dc2962019-03-26 18:47:45 -0700364 HandleError("monitor thread finished");
Josh Gaoc51726c2018-10-11 16:33:05 -0700365 });
366 }
367
368 void StartWorker() {
Josh Gao19dc2962019-03-26 18:47:45 -0700369 CHECK(!worker_started_);
370 worker_started_ = true;
Josh Gaoc51726c2018-10-11 16:33:05 -0700371 worker_thread_ = std::thread([this]() {
372 adb_thread_setname("UsbFfs-worker");
373 for (size_t i = 0; i < kUsbReadQueueDepth; ++i) {
374 read_requests_[i] = CreateReadBlock(next_read_id_++);
Josh Gaoc0b831b2019-02-13 15:27:28 -0800375 if (!SubmitRead(&read_requests_[i])) {
376 return;
377 }
Josh Gaoc51726c2018-10-11 16:33:05 -0700378 }
379
380 while (!stopped_) {
381 uint64_t dummy;
Josh Gaoc0b831b2019-02-13 15:27:28 -0800382 ssize_t rc = adb_read(worker_event_fd_.get(), &dummy, sizeof(dummy));
Josh Gaoc51726c2018-10-11 16:33:05 -0700383 if (rc == -1) {
384 PLOG(FATAL) << "failed to read from eventfd";
385 } else if (rc == 0) {
386 LOG(FATAL) << "hit EOF on eventfd";
387 }
388
Josh Gao6933d542019-03-26 13:21:42 -0700389 ReadEvents();
Josh Gaoc51726c2018-10-11 16:33:05 -0700390 }
391 });
392 }
393
Josh Gaoe778b3a2019-02-28 13:29:32 -0800394 void StopWorker() {
Josh Gao19dc2962019-03-26 18:47:45 -0700395 if (!worker_started_) {
396 return;
397 }
398
Josh Gaoe778b3a2019-02-28 13:29:32 -0800399 pthread_t worker_thread_handle = worker_thread_.native_handle();
400 while (true) {
401 int rc = pthread_kill(worker_thread_handle, kInterruptionSignal);
402 if (rc != 0) {
403 LOG(ERROR) << "failed to send interruption signal to worker: " << strerror(rc);
404 break;
405 }
406
407 std::this_thread::sleep_for(100ms);
408
409 rc = pthread_kill(worker_thread_handle, 0);
410 if (rc == 0) {
411 continue;
412 } else if (rc == ESRCH) {
413 break;
414 } else {
415 LOG(ERROR) << "failed to send interruption signal to worker: " << strerror(rc);
416 }
417 }
418
419 worker_thread_.join();
420 }
421
Josh Gaoc51726c2018-10-11 16:33:05 -0700422 void PrepareReadBlock(IoBlock* block, uint64_t id) {
423 block->pending = false;
Josh Gao86b33be2019-02-26 17:53:52 -0800424 block->payload = std::make_shared<Block>(kUsbReadSize);
Josh Gaoc51726c2018-10-11 16:33:05 -0700425 block->control.aio_data = static_cast<uint64_t>(TransferId::read(id));
Josh Gao86b33be2019-02-26 17:53:52 -0800426 block->control.aio_buf = reinterpret_cast<uintptr_t>(block->payload->data());
427 block->control.aio_nbytes = block->payload->size();
Josh Gaoc51726c2018-10-11 16:33:05 -0700428 }
429
430 IoBlock CreateReadBlock(uint64_t id) {
431 IoBlock block;
432 PrepareReadBlock(&block, id);
433 block.control.aio_rw_flags = 0;
434 block.control.aio_lio_opcode = IOCB_CMD_PREAD;
435 block.control.aio_reqprio = 0;
436 block.control.aio_fildes = read_fd_.get();
437 block.control.aio_offset = 0;
438 block.control.aio_flags = IOCB_FLAG_RESFD;
Josh Gaoc0b831b2019-02-13 15:27:28 -0800439 block.control.aio_resfd = worker_event_fd_.get();
Josh Gaoc51726c2018-10-11 16:33:05 -0700440 return block;
441 }
442
Josh Gao6933d542019-03-26 13:21:42 -0700443 void ReadEvents() {
Josh Gaoc51726c2018-10-11 16:33:05 -0700444 static constexpr size_t kMaxEvents = kUsbReadQueueDepth + kUsbWriteQueueDepth;
445 struct io_event events[kMaxEvents];
446 struct timespec timeout = {.tv_sec = 0, .tv_nsec = 0};
447 int rc = io_getevents(aio_context_.get(), 0, kMaxEvents, events, &timeout);
448 if (rc == -1) {
449 HandleError(StringPrintf("io_getevents failed while reading: %s", strerror(errno)));
450 return;
451 }
452
453 for (int event_idx = 0; event_idx < rc; ++event_idx) {
454 auto& event = events[event_idx];
455 TransferId id = TransferId::from_value(event.data);
456
457 if (event.res < 0) {
458 std::string error =
459 StringPrintf("%s %" PRIu64 " failed with error %s",
460 id.direction == TransferDirection::READ ? "read" : "write",
461 id.id, strerror(-event.res));
462 HandleError(error);
463 return;
464 }
465
466 if (id.direction == TransferDirection::READ) {
467 HandleRead(id, event.res);
468 } else {
469 HandleWrite(id);
470 }
471 }
472 }
473
474 void HandleRead(TransferId id, int64_t size) {
475 uint64_t read_idx = id.id % kUsbReadQueueDepth;
476 IoBlock* block = &read_requests_[read_idx];
477 block->pending = false;
Josh Gao86b33be2019-02-26 17:53:52 -0800478 block->payload->resize(size);
Josh Gaoc51726c2018-10-11 16:33:05 -0700479
480 // Notification for completed reads can be received out of order.
481 if (block->id().id != needed_read_id_) {
482 LOG(VERBOSE) << "read " << block->id().id << " completed while waiting for "
483 << needed_read_id_;
484 return;
485 }
486
487 for (uint64_t id = needed_read_id_;; ++id) {
488 size_t read_idx = id % kUsbReadQueueDepth;
489 IoBlock* current_block = &read_requests_[read_idx];
490 if (current_block->pending) {
491 break;
492 }
493 ProcessRead(current_block);
494 ++needed_read_id_;
495 }
496 }
497
498 void ProcessRead(IoBlock* block) {
Josh Gao86b33be2019-02-26 17:53:52 -0800499 if (!block->payload->empty()) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700500 if (!incoming_header_.has_value()) {
Josh Gao86b33be2019-02-26 17:53:52 -0800501 CHECK_EQ(sizeof(amessage), block->payload->size());
Josh Gaoc51726c2018-10-11 16:33:05 -0700502 amessage msg;
Josh Gao86b33be2019-02-26 17:53:52 -0800503 memcpy(&msg, block->payload->data(), sizeof(amessage));
Josh Gaoc51726c2018-10-11 16:33:05 -0700504 LOG(DEBUG) << "USB read:" << dump_header(&msg);
505 incoming_header_ = msg;
506 } else {
507 size_t bytes_left = incoming_header_->data_length - incoming_payload_.size();
Josh Gao86b33be2019-02-26 17:53:52 -0800508 Block payload = std::move(*block->payload);
Josh Gaoc51726c2018-10-11 16:33:05 -0700509 CHECK_LE(payload.size(), bytes_left);
510 incoming_payload_.append(std::make_unique<Block>(std::move(payload)));
511 }
512
513 if (incoming_header_->data_length == incoming_payload_.size()) {
514 auto packet = std::make_unique<apacket>();
515 packet->msg = *incoming_header_;
516
517 // TODO: Make apacket contain an IOVector so we don't have to coalesce.
518 packet->payload = incoming_payload_.coalesce();
519 read_callback_(this, std::move(packet));
520
521 incoming_header_.reset();
522 incoming_payload_.clear();
523 }
524 }
525
526 PrepareReadBlock(block, block->id().id + kUsbReadQueueDepth);
527 SubmitRead(block);
528 }
529
Josh Gaoc0b831b2019-02-13 15:27:28 -0800530 bool SubmitRead(IoBlock* block) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700531 block->pending = true;
532 struct iocb* iocb = &block->control;
533 if (io_submit(aio_context_.get(), 1, &iocb) != 1) {
Josh Gaoc0b831b2019-02-13 15:27:28 -0800534 if (errno == EINVAL && !gFfsAioSupported.has_value()) {
535 HandleError("failed to submit first read, AIO on FFS not supported");
536 gFfsAioSupported = false;
537 return false;
538 }
539
Josh Gaoc51726c2018-10-11 16:33:05 -0700540 HandleError(StringPrintf("failed to submit read: %s", strerror(errno)));
Josh Gaoc0b831b2019-02-13 15:27:28 -0800541 return false;
Josh Gaoc51726c2018-10-11 16:33:05 -0700542 }
Josh Gaoc0b831b2019-02-13 15:27:28 -0800543
544 gFfsAioSupported = true;
545 return true;
Josh Gaoc51726c2018-10-11 16:33:05 -0700546 }
547
548 void HandleWrite(TransferId id) {
549 std::lock_guard<std::mutex> lock(write_mutex_);
550 auto it =
551 std::find_if(write_requests_.begin(), write_requests_.end(), [id](const auto& req) {
552 return static_cast<uint64_t>(req->id()) == static_cast<uint64_t>(id);
553 });
554 CHECK(it != write_requests_.end());
555
556 write_requests_.erase(it);
557 size_t outstanding_writes = --writes_submitted_;
558 LOG(DEBUG) << "USB write: reaped, down to " << outstanding_writes;
559
560 SubmitWrites();
561 }
562
Josh Gao86b33be2019-02-26 17:53:52 -0800563 std::unique_ptr<IoBlock> CreateWriteBlock(std::shared_ptr<Block> payload, size_t offset,
564 size_t len, uint64_t id) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700565 auto block = std::make_unique<IoBlock>();
566 block->payload = std::move(payload);
567 block->control.aio_data = static_cast<uint64_t>(TransferId::write(id));
568 block->control.aio_rw_flags = 0;
569 block->control.aio_lio_opcode = IOCB_CMD_PWRITE;
570 block->control.aio_reqprio = 0;
571 block->control.aio_fildes = write_fd_.get();
Josh Gao86b33be2019-02-26 17:53:52 -0800572 block->control.aio_buf = reinterpret_cast<uintptr_t>(block->payload->data() + offset);
573 block->control.aio_nbytes = len;
Josh Gaoc51726c2018-10-11 16:33:05 -0700574 block->control.aio_offset = 0;
575 block->control.aio_flags = IOCB_FLAG_RESFD;
Josh Gaoc0b831b2019-02-13 15:27:28 -0800576 block->control.aio_resfd = worker_event_fd_.get();
Josh Gaoc51726c2018-10-11 16:33:05 -0700577 return block;
578 }
579
Josh Gao86b33be2019-02-26 17:53:52 -0800580 std::unique_ptr<IoBlock> CreateWriteBlock(Block payload, uint64_t id) {
581 std::shared_ptr<Block> block = std::make_shared<Block>(std::move(payload));
582 size_t len = block->size();
583 return CreateWriteBlock(std::move(block), 0, len, id);
584 }
585
Josh Gaoc51726c2018-10-11 16:33:05 -0700586 void SubmitWrites() REQUIRES(write_mutex_) {
587 if (writes_submitted_ == kUsbWriteQueueDepth) {
588 return;
589 }
590
591 ssize_t writes_to_submit = std::min(kUsbWriteQueueDepth - writes_submitted_,
592 write_requests_.size() - writes_submitted_);
593 CHECK_GE(writes_to_submit, 0);
594 if (writes_to_submit == 0) {
595 return;
596 }
597
598 struct iocb* iocbs[kUsbWriteQueueDepth];
599 for (int i = 0; i < writes_to_submit; ++i) {
600 CHECK(!write_requests_[writes_submitted_ + i]->pending);
601 write_requests_[writes_submitted_ + i]->pending = true;
602 iocbs[i] = &write_requests_[writes_submitted_ + i]->control;
603 LOG(VERBOSE) << "submitting write_request " << static_cast<void*>(iocbs[i]);
604 }
605
Josh Gao63b52ec2019-03-26 13:06:38 -0700606 writes_submitted_ += writes_to_submit;
607
Josh Gaoc51726c2018-10-11 16:33:05 -0700608 int rc = io_submit(aio_context_.get(), writes_to_submit, iocbs);
609 if (rc == -1) {
610 HandleError(StringPrintf("failed to submit write requests: %s", strerror(errno)));
611 return;
612 } else if (rc != writes_to_submit) {
613 LOG(FATAL) << "failed to submit all writes: wanted to submit " << writes_to_submit
614 << ", actually submitted " << rc;
615 }
Josh Gaoc51726c2018-10-11 16:33:05 -0700616 }
617
618 void HandleError(const std::string& error) {
619 std::call_once(error_flag_, [&]() {
620 error_callback_(this, error);
621 if (!stopped_) {
622 Stop();
623 }
624 });
625 }
626
627 std::thread monitor_thread_;
Josh Gao19dc2962019-03-26 18:47:45 -0700628
629 bool worker_started_;
Josh Gaoc51726c2018-10-11 16:33:05 -0700630 std::thread worker_thread_;
631
632 std::atomic<bool> stopped_;
633 std::promise<void> destruction_notifier_;
634 std::once_flag error_flag_;
635
Josh Gaoc0b831b2019-02-13 15:27:28 -0800636 unique_fd worker_event_fd_;
637 unique_fd monitor_event_fd_;
Josh Gaoc51726c2018-10-11 16:33:05 -0700638
639 ScopedAioContext aio_context_;
640 unique_fd control_fd_;
641 unique_fd read_fd_;
642 unique_fd write_fd_;
643
644 std::optional<amessage> incoming_header_;
645 IOVector incoming_payload_;
646
647 std::array<IoBlock, kUsbReadQueueDepth> read_requests_;
648 IOVector read_data_;
649
650 // ID of the next request that we're going to send out.
651 size_t next_read_id_ = 0;
652
653 // ID of the next packet we're waiting for.
654 size_t needed_read_id_ = 0;
655
656 std::mutex write_mutex_;
657 std::deque<std::unique_ptr<IoBlock>> write_requests_ GUARDED_BY(write_mutex_);
658 size_t next_write_id_ GUARDED_BY(write_mutex_) = 0;
659 size_t writes_submitted_ GUARDED_BY(write_mutex_) = 0;
Josh Gaoe778b3a2019-02-28 13:29:32 -0800660
661 static constexpr int kInterruptionSignal = SIGUSR1;
Josh Gaoc51726c2018-10-11 16:33:05 -0700662};
663
Josh Gaoc0b831b2019-02-13 15:27:28 -0800664void usb_init_legacy();
665
Josh Gaoc51726c2018-10-11 16:33:05 -0700666static void usb_ffs_open_thread() {
667 adb_thread_setname("usb ffs open");
668
669 while (true) {
Josh Gaoc0b831b2019-02-13 15:27:28 -0800670 if (gFfsAioSupported.has_value() && !gFfsAioSupported.value()) {
671 LOG(INFO) << "failed to use nonblocking ffs, falling back to legacy";
672 return usb_init_legacy();
673 }
674
Josh Gaoc51726c2018-10-11 16:33:05 -0700675 unique_fd control;
676 unique_fd bulk_out;
677 unique_fd bulk_in;
678 if (!open_functionfs(&control, &bulk_out, &bulk_in)) {
679 std::this_thread::sleep_for(1s);
680 continue;
681 }
682
683 atransport* transport = new atransport();
684 transport->serial = "UsbFfs";
685 std::promise<void> destruction_notifier;
686 std::future<void> future = destruction_notifier.get_future();
687 transport->SetConnection(std::make_unique<UsbFfsConnection>(
688 std::move(control), std::move(bulk_out), std::move(bulk_in),
689 std::move(destruction_notifier)));
690 register_transport(transport);
691 future.wait();
692 }
693}
694
Josh Gaoc51726c2018-10-11 16:33:05 -0700695void usb_init() {
Josh Gao8038e352019-03-18 16:33:18 -0700696 bool use_nonblocking = android::base::GetBoolProperty(
697 "persist.adb.nonblocking_ffs",
698 android::base::GetBoolProperty("ro.adb.nonblocking_ffs", true));
699
Josh Gao02e94a42019-02-28 07:26:20 +0000700 if (use_nonblocking) {
Josh Gao0d780392019-02-26 22:10:33 +0000701 std::thread(usb_ffs_open_thread).detach();
Josh Gao02e94a42019-02-28 07:26:20 +0000702 } else {
703 usb_init_legacy();
Josh Gaoc51726c2018-10-11 16:33:05 -0700704 }
705}