blob: 96ee6b2eee544c2c7a2d9550718dc279f598f96c [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 Gao770a6a42019-04-16 11:20:04 -070060// Not all USB controllers support operations larger than 16k, so don't go above that.
Josh Gao28293f12019-04-24 14:28:25 -070061// Also, each submitted operation does an allocation in the kernel of that size, so we want to
62// minimize our queue depth while still maintaining a deep enough queue to keep the USB stack fed.
63static constexpr size_t kUsbReadQueueDepth = 8;
Josh Gao770a6a42019-04-16 11:20:04 -070064static constexpr size_t kUsbReadSize = 4 * PAGE_SIZE;
Josh Gaoc51726c2018-10-11 16:33:05 -070065
Josh Gao28293f12019-04-24 14:28:25 -070066static constexpr size_t kUsbWriteQueueDepth = 8;
Josh Gao770a6a42019-04-16 11:20:04 -070067static constexpr size_t kUsbWriteSize = 4 * PAGE_SIZE;
Josh Gaoc51726c2018-10-11 16:33:05 -070068
69static const char* to_string(enum usb_functionfs_event_type type) {
70 switch (type) {
71 case FUNCTIONFS_BIND:
72 return "FUNCTIONFS_BIND";
73 case FUNCTIONFS_UNBIND:
74 return "FUNCTIONFS_UNBIND";
75 case FUNCTIONFS_ENABLE:
76 return "FUNCTIONFS_ENABLE";
77 case FUNCTIONFS_DISABLE:
78 return "FUNCTIONFS_DISABLE";
79 case FUNCTIONFS_SETUP:
80 return "FUNCTIONFS_SETUP";
81 case FUNCTIONFS_SUSPEND:
82 return "FUNCTIONFS_SUSPEND";
83 case FUNCTIONFS_RESUME:
84 return "FUNCTIONFS_RESUME";
85 }
86}
87
88enum class TransferDirection : uint64_t {
89 READ = 0,
90 WRITE = 1,
91};
92
93struct TransferId {
94 TransferDirection direction : 1;
95 uint64_t id : 63;
96
97 TransferId() : TransferId(TransferDirection::READ, 0) {}
98
99 private:
100 TransferId(TransferDirection direction, uint64_t id) : direction(direction), id(id) {}
101
102 public:
103 explicit operator uint64_t() const {
104 uint64_t result;
105 static_assert(sizeof(*this) == sizeof(result));
106 memcpy(&result, this, sizeof(*this));
107 return result;
108 }
109
110 static TransferId read(uint64_t id) { return TransferId(TransferDirection::READ, id); }
111 static TransferId write(uint64_t id) { return TransferId(TransferDirection::WRITE, id); }
112
113 static TransferId from_value(uint64_t value) {
114 TransferId result;
115 memcpy(&result, &value, sizeof(value));
116 return result;
117 }
118};
119
120struct IoBlock {
Josh Gaob0195742019-03-18 14:11:28 -0700121 bool pending = false;
Evgenii Stepanovfe7eca72019-05-15 18:45:01 -0700122 struct iocb control = {};
Josh Gao86b33be2019-02-26 17:53:52 -0800123 std::shared_ptr<Block> payload;
Josh Gaoc51726c2018-10-11 16:33:05 -0700124
125 TransferId id() const { return TransferId::from_value(control.aio_data); }
126};
127
128struct ScopedAioContext {
129 ScopedAioContext() = default;
130 ~ScopedAioContext() { reset(); }
131
132 ScopedAioContext(ScopedAioContext&& move) { reset(move.release()); }
133 ScopedAioContext(const ScopedAioContext& copy) = delete;
134
135 ScopedAioContext& operator=(ScopedAioContext&& move) {
136 reset(move.release());
137 return *this;
138 }
139 ScopedAioContext& operator=(const ScopedAioContext& copy) = delete;
140
141 static ScopedAioContext Create(size_t max_events) {
142 aio_context_t ctx = 0;
143 if (io_setup(max_events, &ctx) != 0) {
144 PLOG(FATAL) << "failed to create aio_context_t";
145 }
146 ScopedAioContext result;
147 result.reset(ctx);
148 return result;
149 }
150
151 aio_context_t release() {
152 aio_context_t result = context_;
153 context_ = 0;
154 return result;
155 }
156
157 void reset(aio_context_t new_context = 0) {
158 if (context_ != 0) {
159 io_destroy(context_);
160 }
161
162 context_ = new_context;
163 }
164
165 aio_context_t get() { return context_; }
166
167 private:
168 aio_context_t context_ = 0;
169};
170
171struct UsbFfsConnection : public Connection {
172 UsbFfsConnection(unique_fd control, unique_fd read, unique_fd write,
173 std::promise<void> destruction_notifier)
Josh Gao19dc2962019-03-26 18:47:45 -0700174 : worker_started_(false),
175 stopped_(false),
Josh Gaoc51726c2018-10-11 16:33:05 -0700176 destruction_notifier_(std::move(destruction_notifier)),
177 control_fd_(std::move(control)),
178 read_fd_(std::move(read)),
179 write_fd_(std::move(write)) {
180 LOG(INFO) << "UsbFfsConnection constructed";
Josh Gaoc0b831b2019-02-13 15:27:28 -0800181 worker_event_fd_.reset(eventfd(0, EFD_CLOEXEC));
182 if (worker_event_fd_ == -1) {
183 PLOG(FATAL) << "failed to create eventfd";
184 }
185
186 monitor_event_fd_.reset(eventfd(0, EFD_CLOEXEC));
187 if (monitor_event_fd_ == -1) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700188 PLOG(FATAL) << "failed to create eventfd";
189 }
190
191 aio_context_ = ScopedAioContext::Create(kUsbReadQueueDepth + kUsbWriteQueueDepth);
192 }
193
194 ~UsbFfsConnection() {
195 LOG(INFO) << "UsbFfsConnection being destroyed";
196 Stop();
197 monitor_thread_.join();
Josh Gaoc0b831b2019-02-13 15:27:28 -0800198
199 // We need to explicitly close our file descriptors before we notify our destruction,
200 // because the thread listening on the future will immediately try to reopen the endpoint.
Josh Gao19dc2962019-03-26 18:47:45 -0700201 aio_context_.reset();
Josh Gaoc0b831b2019-02-13 15:27:28 -0800202 control_fd_.reset();
203 read_fd_.reset();
204 write_fd_.reset();
205
Josh Gaoc51726c2018-10-11 16:33:05 -0700206 destruction_notifier_.set_value();
207 }
208
209 virtual bool Write(std::unique_ptr<apacket> packet) override final {
210 LOG(DEBUG) << "USB write: " << dump_header(&packet->msg);
211 Block header(sizeof(packet->msg));
212 memcpy(header.data(), &packet->msg, sizeof(packet->msg));
213
214 std::lock_guard<std::mutex> lock(write_mutex_);
215 write_requests_.push_back(CreateWriteBlock(std::move(header), next_write_id_++));
216 if (!packet->payload.empty()) {
Josh Gao86b33be2019-02-26 17:53:52 -0800217 // The kernel attempts to allocate a contiguous block of memory for each write,
218 // which can fail if the write is large and the kernel heap is fragmented.
219 // Split large writes into smaller chunks to avoid this.
220 std::shared_ptr<Block> payload = std::make_shared<Block>(std::move(packet->payload));
221 size_t offset = 0;
222 size_t len = payload->size();
223
224 while (len > 0) {
225 size_t write_size = std::min(kUsbWriteSize, len);
226 write_requests_.push_back(
227 CreateWriteBlock(payload, offset, write_size, next_write_id_++));
228 len -= write_size;
229 offset += write_size;
230 }
Josh Gaoc51726c2018-10-11 16:33:05 -0700231 }
232 SubmitWrites();
233 return true;
234 }
235
236 virtual void Start() override final { StartMonitor(); }
237
238 virtual void Stop() override final {
239 if (stopped_.exchange(true)) {
240 return;
241 }
242 stopped_ = true;
243 uint64_t notify = 1;
Josh Gaoc0b831b2019-02-13 15:27:28 -0800244 ssize_t rc = adb_write(worker_event_fd_.get(), &notify, sizeof(notify));
Josh Gaoc51726c2018-10-11 16:33:05 -0700245 if (rc < 0) {
Josh Gaoc0b831b2019-02-13 15:27:28 -0800246 PLOG(FATAL) << "failed to notify worker eventfd to stop UsbFfsConnection";
Josh Gaoc51726c2018-10-11 16:33:05 -0700247 }
248 CHECK_EQ(static_cast<size_t>(rc), sizeof(notify));
Josh Gaoc0b831b2019-02-13 15:27:28 -0800249
250 rc = adb_write(monitor_event_fd_.get(), &notify, sizeof(notify));
251 if (rc < 0) {
252 PLOG(FATAL) << "failed to notify monitor eventfd to stop UsbFfsConnection";
253 }
254
255 CHECK_EQ(static_cast<size_t>(rc), sizeof(notify));
Josh Gaoc51726c2018-10-11 16:33:05 -0700256 }
257
258 private:
259 void StartMonitor() {
260 // This is a bit of a mess.
261 // It's possible for io_submit to end up blocking, if we call it as the endpoint
262 // becomes disabled. Work around this by having a monitor thread to listen for functionfs
263 // lifecycle events. If we notice an error condition (either we've become disabled, or we
264 // were never enabled in the first place), we send interruption signals to the worker thread
265 // until it dies, and then report failure to the transport via HandleError, which will
266 // eventually result in the transport being destroyed, which will result in UsbFfsConnection
267 // being destroyed, which unblocks the open thread and restarts this entire process.
Josh Gaoc51726c2018-10-11 16:33:05 -0700268 static std::once_flag handler_once;
269 std::call_once(handler_once, []() { signal(kInterruptionSignal, [](int) {}); });
270
271 monitor_thread_ = std::thread([this]() {
272 adb_thread_setname("UsbFfs-monitor");
273
274 bool bound = false;
Josh Gao6933d542019-03-26 13:21:42 -0700275 bool enabled = false;
Josh Gaoc51726c2018-10-11 16:33:05 -0700276 bool running = true;
277 while (running) {
Josh Gaoc0b831b2019-02-13 15:27:28 -0800278 adb_pollfd pfd[2] = {
279 { .fd = control_fd_.get(), .events = POLLIN, .revents = 0 },
280 { .fd = monitor_event_fd_.get(), .events = POLLIN, .revents = 0 },
281 };
Josh Gao19dc2962019-03-26 18:47:45 -0700282
283 // If we don't see our first bind within a second, try again.
284 int timeout_ms = bound ? -1 : 1000;
285
286 int rc = TEMP_FAILURE_RETRY(adb_poll(pfd, 2, timeout_ms));
Josh Gaoc0b831b2019-02-13 15:27:28 -0800287 if (rc == -1) {
288 PLOG(FATAL) << "poll on USB control fd failed";
289 } else if (rc == 0) {
Josh Gao19dc2962019-03-26 18:47:45 -0700290 LOG(WARNING) << "timed out while waiting for FUNCTIONFS_BIND, trying again";
291 break;
Josh Gaoc0b831b2019-02-13 15:27:28 -0800292 }
293
294 if (pfd[1].revents) {
295 // We were told to die.
296 break;
Josh Gaoc51726c2018-10-11 16:33:05 -0700297 }
298
299 struct usb_functionfs_event event;
Josh Gao2916e142019-05-10 11:37:34 -0700300 rc = TEMP_FAILURE_RETRY(adb_read(control_fd_.get(), &event, sizeof(event)));
301 if (rc == -1) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700302 PLOG(FATAL) << "failed to read functionfs event";
Josh Gao2916e142019-05-10 11:37:34 -0700303 } else if (rc == 0) {
304 LOG(WARNING) << "hit EOF on functionfs control fd";
305 break;
306 } else if (rc != sizeof(event)) {
307 LOG(FATAL) << "read functionfs event of unexpected size, expected "
308 << sizeof(event) << ", got " << rc;
Josh Gaoc51726c2018-10-11 16:33:05 -0700309 }
310
311 LOG(INFO) << "USB event: "
312 << to_string(static_cast<usb_functionfs_event_type>(event.type));
313
314 switch (event.type) {
315 case FUNCTIONFS_BIND:
Josh Gao87afd522019-03-28 11:05:53 -0700316 if (bound) {
317 LOG(WARNING) << "received FUNCTIONFS_BIND while already bound?";
318 running = false;
Josh Gao910ce0f2019-05-01 16:53:53 -0700319 break;
Josh Gao87afd522019-03-28 11:05:53 -0700320 }
Josh Gao6933d542019-03-26 13:21:42 -0700321
Josh Gao87afd522019-03-28 11:05:53 -0700322 if (enabled) {
323 LOG(WARNING) << "received FUNCTIONFS_BIND while already enabled?";
324 running = false;
Josh Gao910ce0f2019-05-01 16:53:53 -0700325 break;
Josh Gao87afd522019-03-28 11:05:53 -0700326 }
327
328 bound = true;
Josh Gaoc51726c2018-10-11 16:33:05 -0700329 break;
330
331 case FUNCTIONFS_ENABLE:
Josh Gao87afd522019-03-28 11:05:53 -0700332 if (!bound) {
333 LOG(WARNING) << "received FUNCTIONFS_ENABLE while not bound?";
334 running = false;
Josh Gao910ce0f2019-05-01 16:53:53 -0700335 break;
Josh Gao87afd522019-03-28 11:05:53 -0700336 }
Josh Gao6933d542019-03-26 13:21:42 -0700337
Josh Gao87afd522019-03-28 11:05:53 -0700338 if (enabled) {
339 LOG(WARNING) << "received FUNCTIONFS_ENABLE while already enabled?";
340 running = false;
Josh Gao910ce0f2019-05-01 16:53:53 -0700341 break;
Josh Gao87afd522019-03-28 11:05:53 -0700342 }
343
344 enabled = true;
Josh Gaoc51726c2018-10-11 16:33:05 -0700345 StartWorker();
346 break;
347
348 case FUNCTIONFS_DISABLE:
Josh Gao87afd522019-03-28 11:05:53 -0700349 if (!bound) {
350 LOG(WARNING) << "received FUNCTIONFS_DISABLE while not bound?";
351 }
Josh Gao6933d542019-03-26 13:21:42 -0700352
Josh Gao87afd522019-03-28 11:05:53 -0700353 if (!enabled) {
354 LOG(WARNING) << "received FUNCTIONFS_DISABLE while not enabled?";
355 }
356
357 enabled = false;
Josh Gao6933d542019-03-26 13:21:42 -0700358 running = false;
359 break;
360
361 case FUNCTIONFS_UNBIND:
Josh Gao87afd522019-03-28 11:05:53 -0700362 if (enabled) {
363 LOG(WARNING) << "received FUNCTIONFS_UNBIND while still enabled?";
364 }
Josh Gao6933d542019-03-26 13:21:42 -0700365
Josh Gao87afd522019-03-28 11:05:53 -0700366 if (!bound) {
367 LOG(WARNING) << "received FUNCTIONFS_UNBIND when not bound?";
368 }
369
370 bound = false;
Josh Gaoc51726c2018-10-11 16:33:05 -0700371 running = false;
372 break;
373 }
374 }
375
Josh Gaoe778b3a2019-02-28 13:29:32 -0800376 StopWorker();
Josh Gao19dc2962019-03-26 18:47:45 -0700377 HandleError("monitor thread finished");
Josh Gaoc51726c2018-10-11 16:33:05 -0700378 });
379 }
380
381 void StartWorker() {
Josh Gao19dc2962019-03-26 18:47:45 -0700382 CHECK(!worker_started_);
383 worker_started_ = true;
Josh Gaoc51726c2018-10-11 16:33:05 -0700384 worker_thread_ = std::thread([this]() {
385 adb_thread_setname("UsbFfs-worker");
386 for (size_t i = 0; i < kUsbReadQueueDepth; ++i) {
387 read_requests_[i] = CreateReadBlock(next_read_id_++);
Josh Gaoc0b831b2019-02-13 15:27:28 -0800388 if (!SubmitRead(&read_requests_[i])) {
389 return;
390 }
Josh Gaoc51726c2018-10-11 16:33:05 -0700391 }
392
393 while (!stopped_) {
394 uint64_t dummy;
Josh Gaoc0b831b2019-02-13 15:27:28 -0800395 ssize_t rc = adb_read(worker_event_fd_.get(), &dummy, sizeof(dummy));
Josh Gaoc51726c2018-10-11 16:33:05 -0700396 if (rc == -1) {
397 PLOG(FATAL) << "failed to read from eventfd";
398 } else if (rc == 0) {
399 LOG(FATAL) << "hit EOF on eventfd";
400 }
401
Josh Gao6933d542019-03-26 13:21:42 -0700402 ReadEvents();
Josh Gaoc51726c2018-10-11 16:33:05 -0700403 }
404 });
405 }
406
Josh Gaoe778b3a2019-02-28 13:29:32 -0800407 void StopWorker() {
Josh Gao19dc2962019-03-26 18:47:45 -0700408 if (!worker_started_) {
409 return;
410 }
411
Josh Gaoe778b3a2019-02-28 13:29:32 -0800412 pthread_t worker_thread_handle = worker_thread_.native_handle();
413 while (true) {
414 int rc = pthread_kill(worker_thread_handle, kInterruptionSignal);
415 if (rc != 0) {
416 LOG(ERROR) << "failed to send interruption signal to worker: " << strerror(rc);
417 break;
418 }
419
420 std::this_thread::sleep_for(100ms);
421
422 rc = pthread_kill(worker_thread_handle, 0);
423 if (rc == 0) {
424 continue;
425 } else if (rc == ESRCH) {
426 break;
427 } else {
428 LOG(ERROR) << "failed to send interruption signal to worker: " << strerror(rc);
429 }
430 }
431
432 worker_thread_.join();
433 }
434
Josh Gaoc51726c2018-10-11 16:33:05 -0700435 void PrepareReadBlock(IoBlock* block, uint64_t id) {
436 block->pending = false;
Josh Gao86b33be2019-02-26 17:53:52 -0800437 block->payload = std::make_shared<Block>(kUsbReadSize);
Josh Gaoc51726c2018-10-11 16:33:05 -0700438 block->control.aio_data = static_cast<uint64_t>(TransferId::read(id));
Josh Gao86b33be2019-02-26 17:53:52 -0800439 block->control.aio_buf = reinterpret_cast<uintptr_t>(block->payload->data());
440 block->control.aio_nbytes = block->payload->size();
Josh Gaoc51726c2018-10-11 16:33:05 -0700441 }
442
443 IoBlock CreateReadBlock(uint64_t id) {
444 IoBlock block;
445 PrepareReadBlock(&block, id);
446 block.control.aio_rw_flags = 0;
447 block.control.aio_lio_opcode = IOCB_CMD_PREAD;
448 block.control.aio_reqprio = 0;
449 block.control.aio_fildes = read_fd_.get();
450 block.control.aio_offset = 0;
451 block.control.aio_flags = IOCB_FLAG_RESFD;
Josh Gaoc0b831b2019-02-13 15:27:28 -0800452 block.control.aio_resfd = worker_event_fd_.get();
Josh Gaoc51726c2018-10-11 16:33:05 -0700453 return block;
454 }
455
Josh Gao6933d542019-03-26 13:21:42 -0700456 void ReadEvents() {
Josh Gaoc51726c2018-10-11 16:33:05 -0700457 static constexpr size_t kMaxEvents = kUsbReadQueueDepth + kUsbWriteQueueDepth;
458 struct io_event events[kMaxEvents];
459 struct timespec timeout = {.tv_sec = 0, .tv_nsec = 0};
460 int rc = io_getevents(aio_context_.get(), 0, kMaxEvents, events, &timeout);
461 if (rc == -1) {
462 HandleError(StringPrintf("io_getevents failed while reading: %s", strerror(errno)));
463 return;
464 }
465
466 for (int event_idx = 0; event_idx < rc; ++event_idx) {
467 auto& event = events[event_idx];
468 TransferId id = TransferId::from_value(event.data);
469
470 if (event.res < 0) {
471 std::string error =
472 StringPrintf("%s %" PRIu64 " failed with error %s",
473 id.direction == TransferDirection::READ ? "read" : "write",
474 id.id, strerror(-event.res));
475 HandleError(error);
476 return;
477 }
478
479 if (id.direction == TransferDirection::READ) {
480 HandleRead(id, event.res);
481 } else {
482 HandleWrite(id);
483 }
484 }
485 }
486
487 void HandleRead(TransferId id, int64_t size) {
488 uint64_t read_idx = id.id % kUsbReadQueueDepth;
489 IoBlock* block = &read_requests_[read_idx];
490 block->pending = false;
Josh Gao86b33be2019-02-26 17:53:52 -0800491 block->payload->resize(size);
Josh Gaoc51726c2018-10-11 16:33:05 -0700492
493 // Notification for completed reads can be received out of order.
494 if (block->id().id != needed_read_id_) {
495 LOG(VERBOSE) << "read " << block->id().id << " completed while waiting for "
496 << needed_read_id_;
497 return;
498 }
499
500 for (uint64_t id = needed_read_id_;; ++id) {
501 size_t read_idx = id % kUsbReadQueueDepth;
502 IoBlock* current_block = &read_requests_[read_idx];
503 if (current_block->pending) {
504 break;
505 }
506 ProcessRead(current_block);
507 ++needed_read_id_;
508 }
509 }
510
511 void ProcessRead(IoBlock* block) {
Josh Gao86b33be2019-02-26 17:53:52 -0800512 if (!block->payload->empty()) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700513 if (!incoming_header_.has_value()) {
Josh Gao86b33be2019-02-26 17:53:52 -0800514 CHECK_EQ(sizeof(amessage), block->payload->size());
Josh Gaoc51726c2018-10-11 16:33:05 -0700515 amessage msg;
Josh Gao86b33be2019-02-26 17:53:52 -0800516 memcpy(&msg, block->payload->data(), sizeof(amessage));
Josh Gaoc51726c2018-10-11 16:33:05 -0700517 LOG(DEBUG) << "USB read:" << dump_header(&msg);
518 incoming_header_ = msg;
519 } else {
520 size_t bytes_left = incoming_header_->data_length - incoming_payload_.size();
Josh Gao86b33be2019-02-26 17:53:52 -0800521 Block payload = std::move(*block->payload);
Josh Gaoc51726c2018-10-11 16:33:05 -0700522 CHECK_LE(payload.size(), bytes_left);
523 incoming_payload_.append(std::make_unique<Block>(std::move(payload)));
524 }
525
526 if (incoming_header_->data_length == incoming_payload_.size()) {
527 auto packet = std::make_unique<apacket>();
528 packet->msg = *incoming_header_;
529
530 // TODO: Make apacket contain an IOVector so we don't have to coalesce.
531 packet->payload = incoming_payload_.coalesce();
532 read_callback_(this, std::move(packet));
533
534 incoming_header_.reset();
535 incoming_payload_.clear();
536 }
537 }
538
539 PrepareReadBlock(block, block->id().id + kUsbReadQueueDepth);
540 SubmitRead(block);
541 }
542
Josh Gaoc0b831b2019-02-13 15:27:28 -0800543 bool SubmitRead(IoBlock* block) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700544 block->pending = true;
545 struct iocb* iocb = &block->control;
546 if (io_submit(aio_context_.get(), 1, &iocb) != 1) {
Josh Gaoc0b831b2019-02-13 15:27:28 -0800547 if (errno == EINVAL && !gFfsAioSupported.has_value()) {
548 HandleError("failed to submit first read, AIO on FFS not supported");
549 gFfsAioSupported = false;
550 return false;
551 }
552
Josh Gaoc51726c2018-10-11 16:33:05 -0700553 HandleError(StringPrintf("failed to submit read: %s", strerror(errno)));
Josh Gaoc0b831b2019-02-13 15:27:28 -0800554 return false;
Josh Gaoc51726c2018-10-11 16:33:05 -0700555 }
Josh Gaoc0b831b2019-02-13 15:27:28 -0800556
557 gFfsAioSupported = true;
558 return true;
Josh Gaoc51726c2018-10-11 16:33:05 -0700559 }
560
561 void HandleWrite(TransferId id) {
562 std::lock_guard<std::mutex> lock(write_mutex_);
563 auto it =
564 std::find_if(write_requests_.begin(), write_requests_.end(), [id](const auto& req) {
565 return static_cast<uint64_t>(req->id()) == static_cast<uint64_t>(id);
566 });
567 CHECK(it != write_requests_.end());
568
569 write_requests_.erase(it);
570 size_t outstanding_writes = --writes_submitted_;
571 LOG(DEBUG) << "USB write: reaped, down to " << outstanding_writes;
572
573 SubmitWrites();
574 }
575
Josh Gao86b33be2019-02-26 17:53:52 -0800576 std::unique_ptr<IoBlock> CreateWriteBlock(std::shared_ptr<Block> payload, size_t offset,
577 size_t len, uint64_t id) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700578 auto block = std::make_unique<IoBlock>();
579 block->payload = std::move(payload);
580 block->control.aio_data = static_cast<uint64_t>(TransferId::write(id));
581 block->control.aio_rw_flags = 0;
582 block->control.aio_lio_opcode = IOCB_CMD_PWRITE;
583 block->control.aio_reqprio = 0;
584 block->control.aio_fildes = write_fd_.get();
Josh Gao86b33be2019-02-26 17:53:52 -0800585 block->control.aio_buf = reinterpret_cast<uintptr_t>(block->payload->data() + offset);
586 block->control.aio_nbytes = len;
Josh Gaoc51726c2018-10-11 16:33:05 -0700587 block->control.aio_offset = 0;
588 block->control.aio_flags = IOCB_FLAG_RESFD;
Josh Gaoc0b831b2019-02-13 15:27:28 -0800589 block->control.aio_resfd = worker_event_fd_.get();
Josh Gaoc51726c2018-10-11 16:33:05 -0700590 return block;
591 }
592
Josh Gao86b33be2019-02-26 17:53:52 -0800593 std::unique_ptr<IoBlock> CreateWriteBlock(Block payload, uint64_t id) {
594 std::shared_ptr<Block> block = std::make_shared<Block>(std::move(payload));
595 size_t len = block->size();
596 return CreateWriteBlock(std::move(block), 0, len, id);
597 }
598
Josh Gaoc51726c2018-10-11 16:33:05 -0700599 void SubmitWrites() REQUIRES(write_mutex_) {
600 if (writes_submitted_ == kUsbWriteQueueDepth) {
601 return;
602 }
603
604 ssize_t writes_to_submit = std::min(kUsbWriteQueueDepth - writes_submitted_,
605 write_requests_.size() - writes_submitted_);
606 CHECK_GE(writes_to_submit, 0);
607 if (writes_to_submit == 0) {
608 return;
609 }
610
611 struct iocb* iocbs[kUsbWriteQueueDepth];
612 for (int i = 0; i < writes_to_submit; ++i) {
613 CHECK(!write_requests_[writes_submitted_ + i]->pending);
614 write_requests_[writes_submitted_ + i]->pending = true;
615 iocbs[i] = &write_requests_[writes_submitted_ + i]->control;
616 LOG(VERBOSE) << "submitting write_request " << static_cast<void*>(iocbs[i]);
617 }
618
Josh Gao63b52ec2019-03-26 13:06:38 -0700619 writes_submitted_ += writes_to_submit;
620
Josh Gaoc51726c2018-10-11 16:33:05 -0700621 int rc = io_submit(aio_context_.get(), writes_to_submit, iocbs);
622 if (rc == -1) {
623 HandleError(StringPrintf("failed to submit write requests: %s", strerror(errno)));
624 return;
625 } else if (rc != writes_to_submit) {
626 LOG(FATAL) << "failed to submit all writes: wanted to submit " << writes_to_submit
627 << ", actually submitted " << rc;
628 }
Josh Gaoc51726c2018-10-11 16:33:05 -0700629 }
630
631 void HandleError(const std::string& error) {
632 std::call_once(error_flag_, [&]() {
633 error_callback_(this, error);
634 if (!stopped_) {
635 Stop();
636 }
637 });
638 }
639
640 std::thread monitor_thread_;
Josh Gao19dc2962019-03-26 18:47:45 -0700641
642 bool worker_started_;
Josh Gaoc51726c2018-10-11 16:33:05 -0700643 std::thread worker_thread_;
644
645 std::atomic<bool> stopped_;
646 std::promise<void> destruction_notifier_;
647 std::once_flag error_flag_;
648
Josh Gaoc0b831b2019-02-13 15:27:28 -0800649 unique_fd worker_event_fd_;
650 unique_fd monitor_event_fd_;
Josh Gaoc51726c2018-10-11 16:33:05 -0700651
652 ScopedAioContext aio_context_;
653 unique_fd control_fd_;
654 unique_fd read_fd_;
655 unique_fd write_fd_;
656
657 std::optional<amessage> incoming_header_;
658 IOVector incoming_payload_;
659
660 std::array<IoBlock, kUsbReadQueueDepth> read_requests_;
661 IOVector read_data_;
662
663 // ID of the next request that we're going to send out.
664 size_t next_read_id_ = 0;
665
666 // ID of the next packet we're waiting for.
667 size_t needed_read_id_ = 0;
668
669 std::mutex write_mutex_;
670 std::deque<std::unique_ptr<IoBlock>> write_requests_ GUARDED_BY(write_mutex_);
671 size_t next_write_id_ GUARDED_BY(write_mutex_) = 0;
672 size_t writes_submitted_ GUARDED_BY(write_mutex_) = 0;
Josh Gaoe778b3a2019-02-28 13:29:32 -0800673
674 static constexpr int kInterruptionSignal = SIGUSR1;
Josh Gaoc51726c2018-10-11 16:33:05 -0700675};
676
Josh Gaoc0b831b2019-02-13 15:27:28 -0800677void usb_init_legacy();
678
Josh Gaoc51726c2018-10-11 16:33:05 -0700679static void usb_ffs_open_thread() {
680 adb_thread_setname("usb ffs open");
681
682 while (true) {
Josh Gaoc0b831b2019-02-13 15:27:28 -0800683 if (gFfsAioSupported.has_value() && !gFfsAioSupported.value()) {
684 LOG(INFO) << "failed to use nonblocking ffs, falling back to legacy";
685 return usb_init_legacy();
686 }
687
Josh Gaoc51726c2018-10-11 16:33:05 -0700688 unique_fd control;
689 unique_fd bulk_out;
690 unique_fd bulk_in;
691 if (!open_functionfs(&control, &bulk_out, &bulk_in)) {
692 std::this_thread::sleep_for(1s);
693 continue;
694 }
695
696 atransport* transport = new atransport();
697 transport->serial = "UsbFfs";
698 std::promise<void> destruction_notifier;
699 std::future<void> future = destruction_notifier.get_future();
700 transport->SetConnection(std::make_unique<UsbFfsConnection>(
701 std::move(control), std::move(bulk_out), std::move(bulk_in),
702 std::move(destruction_notifier)));
703 register_transport(transport);
704 future.wait();
705 }
706}
707
Josh Gaoc51726c2018-10-11 16:33:05 -0700708void usb_init() {
Josh Gao8038e352019-03-18 16:33:18 -0700709 bool use_nonblocking = android::base::GetBoolProperty(
710 "persist.adb.nonblocking_ffs",
711 android::base::GetBoolProperty("ro.adb.nonblocking_ffs", true));
712
Josh Gao02e94a42019-02-28 07:26:20 +0000713 if (use_nonblocking) {
Josh Gao0d780392019-02-26 22:10:33 +0000714 std::thread(usb_ffs_open_thread).detach();
Josh Gao02e94a42019-02-28 07:26:20 +0000715 } else {
716 usb_init_legacy();
Josh Gaoc51726c2018-10-11 16:33:05 -0700717 }
718}