blob: 2c44032a8d83f888391f1dc1ec4981b3d41487f0 [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>
Josh Gaoa9b62d52020-02-19 13:50:57 -080022#include <inttypes.h>
Josh Gaoc51726c2018-10-11 16:33:05 -070023#include <stdio.h>
24#include <stdlib.h>
25#include <string.h>
26#include <sys/ioctl.h>
27#include <sys/types.h>
28#include <unistd.h>
29
30#include <linux/usb/functionfs.h>
31#include <sys/eventfd.h>
32
Josh Gao86b33be2019-02-26 17:53:52 -080033#include <algorithm>
Josh Gaoc51726c2018-10-11 16:33:05 -070034#include <array>
35#include <future>
36#include <memory>
37#include <mutex>
38#include <optional>
39#include <vector>
40
41#include <asyncio/AsyncIO.h>
42
43#include <android-base/logging.h>
44#include <android-base/macros.h>
45#include <android-base/properties.h>
46#include <android-base/thread_annotations.h>
47
48#include <adbd/usb.h>
49
50#include "adb_unique_fd.h"
51#include "adb_utils.h"
52#include "sysdeps/chrono.h"
53#include "transport.h"
54#include "types.h"
55
56using android::base::StringPrintf;
57
Josh Gaoc0b831b2019-02-13 15:27:28 -080058// We can't find out whether we have support for AIO on ffs endpoints until we submit a read.
59static std::optional<bool> gFfsAioSupported;
60
Josh Gao08ccc732019-04-16 11:20:04 -070061// Not all USB controllers support operations larger than 16k, so don't go above that.
Josh Gaod0feaf92019-04-24 14:28:25 -070062// Also, each submitted operation does an allocation in the kernel of that size, so we want to
63// minimize our queue depth while still maintaining a deep enough queue to keep the USB stack fed.
64static constexpr size_t kUsbReadQueueDepth = 8;
Josh Gao08ccc732019-04-16 11:20:04 -070065static constexpr size_t kUsbReadSize = 4 * PAGE_SIZE;
Josh Gaoc51726c2018-10-11 16:33:05 -070066
Josh Gaod0feaf92019-04-24 14:28:25 -070067static constexpr size_t kUsbWriteQueueDepth = 8;
Josh Gao08ccc732019-04-16 11:20:04 -070068static constexpr size_t kUsbWriteSize = 4 * PAGE_SIZE;
Josh Gaoc51726c2018-10-11 16:33:05 -070069
Dan Albert782036b2019-06-24 14:35:35 -070070static const char* to_string(enum usb_functionfs_event_type type) {
71 switch (type) {
72 case FUNCTIONFS_BIND:
73 return "FUNCTIONFS_BIND";
74 case FUNCTIONFS_UNBIND:
75 return "FUNCTIONFS_UNBIND";
76 case FUNCTIONFS_ENABLE:
77 return "FUNCTIONFS_ENABLE";
78 case FUNCTIONFS_DISABLE:
79 return "FUNCTIONFS_DISABLE";
80 case FUNCTIONFS_SETUP:
81 return "FUNCTIONFS_SETUP";
82 case FUNCTIONFS_SUSPEND:
83 return "FUNCTIONFS_SUSPEND";
84 case FUNCTIONFS_RESUME:
85 return "FUNCTIONFS_RESUME";
86 }
87}
88
Josh Gaoc51726c2018-10-11 16:33:05 -070089enum class TransferDirection : uint64_t {
90 READ = 0,
91 WRITE = 1,
92};
93
94struct TransferId {
95 TransferDirection direction : 1;
96 uint64_t id : 63;
97
98 TransferId() : TransferId(TransferDirection::READ, 0) {}
99
100 private:
101 TransferId(TransferDirection direction, uint64_t id) : direction(direction), id(id) {}
102
103 public:
104 explicit operator uint64_t() const {
105 uint64_t result;
106 static_assert(sizeof(*this) == sizeof(result));
107 memcpy(&result, this, sizeof(*this));
108 return result;
109 }
110
111 static TransferId read(uint64_t id) { return TransferId(TransferDirection::READ, id); }
112 static TransferId write(uint64_t id) { return TransferId(TransferDirection::WRITE, id); }
113
114 static TransferId from_value(uint64_t value) {
115 TransferId result;
116 memcpy(&result, &value, sizeof(value));
117 return result;
118 }
119};
120
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700121template <class Payload>
Josh Gaoc51726c2018-10-11 16:33:05 -0700122struct IoBlock {
Josh Gaob0195742019-03-18 14:11:28 -0700123 bool pending = false;
Evgenii Stepanov9da358d2019-05-15 18:45:01 -0700124 struct iocb control = {};
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700125 Payload payload;
Josh Gaoc51726c2018-10-11 16:33:05 -0700126
127 TransferId id() const { return TransferId::from_value(control.aio_data); }
128};
129
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700130using IoReadBlock = IoBlock<Block>;
131using IoWriteBlock = IoBlock<std::shared_ptr<Block>>;
132
Josh Gaoc51726c2018-10-11 16:33:05 -0700133struct ScopedAioContext {
134 ScopedAioContext() = default;
135 ~ScopedAioContext() { reset(); }
136
137 ScopedAioContext(ScopedAioContext&& move) { reset(move.release()); }
138 ScopedAioContext(const ScopedAioContext& copy) = delete;
139
140 ScopedAioContext& operator=(ScopedAioContext&& move) {
141 reset(move.release());
142 return *this;
143 }
144 ScopedAioContext& operator=(const ScopedAioContext& copy) = delete;
145
146 static ScopedAioContext Create(size_t max_events) {
147 aio_context_t ctx = 0;
148 if (io_setup(max_events, &ctx) != 0) {
149 PLOG(FATAL) << "failed to create aio_context_t";
150 }
151 ScopedAioContext result;
152 result.reset(ctx);
153 return result;
154 }
155
156 aio_context_t release() {
157 aio_context_t result = context_;
158 context_ = 0;
159 return result;
160 }
161
162 void reset(aio_context_t new_context = 0) {
163 if (context_ != 0) {
164 io_destroy(context_);
165 }
166
167 context_ = new_context;
168 }
169
170 aio_context_t get() { return context_; }
171
172 private:
173 aio_context_t context_ = 0;
174};
175
176struct UsbFfsConnection : public Connection {
Dan Albert782036b2019-06-24 14:35:35 -0700177 UsbFfsConnection(unique_fd control, unique_fd read, unique_fd write,
Josh Gaoc51726c2018-10-11 16:33:05 -0700178 std::promise<void> destruction_notifier)
Josh Gao19dc2962019-03-26 18:47:45 -0700179 : worker_started_(false),
180 stopped_(false),
Josh Gaoc51726c2018-10-11 16:33:05 -0700181 destruction_notifier_(std::move(destruction_notifier)),
Dan Albert782036b2019-06-24 14:35:35 -0700182 control_fd_(std::move(control)),
Josh Gaoc51726c2018-10-11 16:33:05 -0700183 read_fd_(std::move(read)),
184 write_fd_(std::move(write)) {
185 LOG(INFO) << "UsbFfsConnection constructed";
Josh Gaoc0b831b2019-02-13 15:27:28 -0800186 worker_event_fd_.reset(eventfd(0, EFD_CLOEXEC));
187 if (worker_event_fd_ == -1) {
188 PLOG(FATAL) << "failed to create eventfd";
189 }
190
Dan Albert782036b2019-06-24 14:35:35 -0700191 monitor_event_fd_.reset(eventfd(0, EFD_CLOEXEC));
192 if (monitor_event_fd_ == -1) {
193 PLOG(FATAL) << "failed to create eventfd";
194 }
195
Josh Gaoc51726c2018-10-11 16:33:05 -0700196 aio_context_ = ScopedAioContext::Create(kUsbReadQueueDepth + kUsbWriteQueueDepth);
197 }
198
199 ~UsbFfsConnection() {
200 LOG(INFO) << "UsbFfsConnection being destroyed";
201 Stop();
202 monitor_thread_.join();
Josh Gaoc0b831b2019-02-13 15:27:28 -0800203
204 // We need to explicitly close our file descriptors before we notify our destruction,
205 // because the thread listening on the future will immediately try to reopen the endpoint.
Josh Gao19dc2962019-03-26 18:47:45 -0700206 aio_context_.reset();
Dan Albert782036b2019-06-24 14:35:35 -0700207 control_fd_.reset();
Josh Gaoc0b831b2019-02-13 15:27:28 -0800208 read_fd_.reset();
209 write_fd_.reset();
210
Josh Gaoc51726c2018-10-11 16:33:05 -0700211 destruction_notifier_.set_value();
212 }
213
214 virtual bool Write(std::unique_ptr<apacket> packet) override final {
215 LOG(DEBUG) << "USB write: " << dump_header(&packet->msg);
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700216 auto header = std::make_shared<Block>(sizeof(packet->msg));
217 memcpy(header->data(), &packet->msg, sizeof(packet->msg));
Josh Gaoc51726c2018-10-11 16:33:05 -0700218
219 std::lock_guard<std::mutex> lock(write_mutex_);
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700220 write_requests_.push_back(
221 CreateWriteBlock(std::move(header), 0, sizeof(packet->msg), next_write_id_++));
Josh Gaoc51726c2018-10-11 16:33:05 -0700222 if (!packet->payload.empty()) {
Josh Gao86b33be2019-02-26 17:53:52 -0800223 // The kernel attempts to allocate a contiguous block of memory for each write,
224 // which can fail if the write is large and the kernel heap is fragmented.
225 // Split large writes into smaller chunks to avoid this.
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700226 auto payload = std::make_shared<Block>(std::move(packet->payload));
Josh Gao86b33be2019-02-26 17:53:52 -0800227 size_t offset = 0;
228 size_t len = payload->size();
229
230 while (len > 0) {
231 size_t write_size = std::min(kUsbWriteSize, len);
232 write_requests_.push_back(
233 CreateWriteBlock(payload, offset, write_size, next_write_id_++));
234 len -= write_size;
235 offset += write_size;
236 }
Josh Gaoc51726c2018-10-11 16:33:05 -0700237 }
238 SubmitWrites();
239 return true;
240 }
241
242 virtual void Start() override final { StartMonitor(); }
243
244 virtual void Stop() override final {
245 if (stopped_.exchange(true)) {
246 return;
247 }
248 stopped_ = true;
249 uint64_t notify = 1;
Josh Gaoc0b831b2019-02-13 15:27:28 -0800250 ssize_t rc = adb_write(worker_event_fd_.get(), &notify, sizeof(notify));
Josh Gaoc51726c2018-10-11 16:33:05 -0700251 if (rc < 0) {
Josh Gaoc0b831b2019-02-13 15:27:28 -0800252 PLOG(FATAL) << "failed to notify worker eventfd to stop UsbFfsConnection";
Josh Gaoc51726c2018-10-11 16:33:05 -0700253 }
254 CHECK_EQ(static_cast<size_t>(rc), sizeof(notify));
Dan Albert782036b2019-06-24 14:35:35 -0700255
256 rc = adb_write(monitor_event_fd_.get(), &notify, sizeof(notify));
257 if (rc < 0) {
258 PLOG(FATAL) << "failed to notify monitor eventfd to stop UsbFfsConnection";
259 }
260
261 CHECK_EQ(static_cast<size_t>(rc), sizeof(notify));
Josh Gaoc51726c2018-10-11 16:33:05 -0700262 }
263
Joshua Duong5cf78682020-01-21 13:19:42 -0800264 virtual bool DoTlsHandshake(RSA* key, std::string* auth_key) override final {
265 // TODO: support TLS for usb connections.
266 LOG(FATAL) << "Not supported yet.";
267 return false;
268 }
269
Josh Gaoc51726c2018-10-11 16:33:05 -0700270 private:
271 void StartMonitor() {
272 // This is a bit of a mess.
273 // It's possible for io_submit to end up blocking, if we call it as the endpoint
274 // becomes disabled. Work around this by having a monitor thread to listen for functionfs
275 // lifecycle events. If we notice an error condition (either we've become disabled, or we
276 // were never enabled in the first place), we send interruption signals to the worker thread
277 // until it dies, and then report failure to the transport via HandleError, which will
278 // eventually result in the transport being destroyed, which will result in UsbFfsConnection
279 // being destroyed, which unblocks the open thread and restarts this entire process.
Josh Gaoc51726c2018-10-11 16:33:05 -0700280 static std::once_flag handler_once;
281 std::call_once(handler_once, []() { signal(kInterruptionSignal, [](int) {}); });
282
283 monitor_thread_ = std::thread([this]() {
284 adb_thread_setname("UsbFfs-monitor");
285
Dan Albert782036b2019-06-24 14:35:35 -0700286 bool bound = false;
Josh Gao6933d542019-03-26 13:21:42 -0700287 bool enabled = false;
Josh Gaoc51726c2018-10-11 16:33:05 -0700288 bool running = true;
289 while (running) {
Josh Gaoc0b831b2019-02-13 15:27:28 -0800290 adb_pollfd pfd[2] = {
Dan Albert782036b2019-06-24 14:35:35 -0700291 { .fd = control_fd_.get(), .events = POLLIN, .revents = 0 },
292 { .fd = monitor_event_fd_.get(), .events = POLLIN, .revents = 0 },
Josh Gaoc0b831b2019-02-13 15:27:28 -0800293 };
Josh Gao19dc2962019-03-26 18:47:45 -0700294
Dan Albert782036b2019-06-24 14:35:35 -0700295 // If we don't see our first bind within a second, try again.
296 int timeout_ms = bound ? -1 : 1000;
297
298 int rc = TEMP_FAILURE_RETRY(adb_poll(pfd, 2, timeout_ms));
Josh Gaoc0b831b2019-02-13 15:27:28 -0800299 if (rc == -1) {
300 PLOG(FATAL) << "poll on USB control fd failed";
Dan Albert782036b2019-06-24 14:35:35 -0700301 } else if (rc == 0) {
302 LOG(WARNING) << "timed out while waiting for FUNCTIONFS_BIND, trying again";
303 break;
Josh Gaoc0b831b2019-02-13 15:27:28 -0800304 }
305
306 if (pfd[1].revents) {
Dan Albert782036b2019-06-24 14:35:35 -0700307 // We were told to die.
308 break;
Josh Gaoc51726c2018-10-11 16:33:05 -0700309 }
310
311 struct usb_functionfs_event event;
Dan Albert782036b2019-06-24 14:35:35 -0700312 rc = TEMP_FAILURE_RETRY(adb_read(control_fd_.get(), &event, sizeof(event)));
Josh Gao1f7ae9d2019-05-10 11:37:34 -0700313 if (rc == -1) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700314 PLOG(FATAL) << "failed to read functionfs event";
Josh Gao1f7ae9d2019-05-10 11:37:34 -0700315 } else if (rc == 0) {
316 LOG(WARNING) << "hit EOF on functionfs control fd";
317 break;
318 } else if (rc != sizeof(event)) {
319 LOG(FATAL) << "read functionfs event of unexpected size, expected "
320 << sizeof(event) << ", got " << rc;
Josh Gaoc51726c2018-10-11 16:33:05 -0700321 }
322
323 LOG(INFO) << "USB event: "
Dan Albert782036b2019-06-24 14:35:35 -0700324 << to_string(static_cast<usb_functionfs_event_type>(event.type));
Josh Gaoc51726c2018-10-11 16:33:05 -0700325
326 switch (event.type) {
327 case FUNCTIONFS_BIND:
Dan Albert782036b2019-06-24 14:35:35 -0700328 if (bound) {
329 LOG(WARNING) << "received FUNCTIONFS_BIND while already bound?";
330 running = false;
331 break;
332 }
333
334 if (enabled) {
335 LOG(WARNING) << "received FUNCTIONFS_BIND while already enabled?";
336 running = false;
337 break;
338 }
339
340 bound = true;
Josh Gaoc51726c2018-10-11 16:33:05 -0700341 break;
342
343 case FUNCTIONFS_ENABLE:
Dan Albert782036b2019-06-24 14:35:35 -0700344 if (!bound) {
345 LOG(WARNING) << "received FUNCTIONFS_ENABLE while not bound?";
346 running = false;
347 break;
348 }
349
Josh Gao87afd522019-03-28 11:05:53 -0700350 if (enabled) {
351 LOG(WARNING) << "received FUNCTIONFS_ENABLE while already enabled?";
352 running = false;
Josh Gao94fb36b2019-05-01 16:53:53 -0700353 break;
Josh Gao87afd522019-03-28 11:05:53 -0700354 }
355
356 enabled = true;
Josh Gaoc51726c2018-10-11 16:33:05 -0700357 StartWorker();
358 break;
359
360 case FUNCTIONFS_DISABLE:
Dan Albert782036b2019-06-24 14:35:35 -0700361 if (!bound) {
362 LOG(WARNING) << "received FUNCTIONFS_DISABLE while not bound?";
363 }
364
Josh Gao87afd522019-03-28 11:05:53 -0700365 if (!enabled) {
366 LOG(WARNING) << "received FUNCTIONFS_DISABLE while not enabled?";
367 }
368
369 enabled = false;
Josh Gao6933d542019-03-26 13:21:42 -0700370 running = false;
371 break;
372
373 case FUNCTIONFS_UNBIND:
Josh Gao87afd522019-03-28 11:05:53 -0700374 if (enabled) {
375 LOG(WARNING) << "received FUNCTIONFS_UNBIND while still enabled?";
376 }
Josh Gao6933d542019-03-26 13:21:42 -0700377
Dan Albert782036b2019-06-24 14:35:35 -0700378 if (!bound) {
379 LOG(WARNING) << "received FUNCTIONFS_UNBIND when not bound?";
380 }
381
382 bound = false;
Josh Gaoc51726c2018-10-11 16:33:05 -0700383 running = false;
384 break;
Josh Gao12807c72019-05-15 18:03:29 -0700385
386 case FUNCTIONFS_SETUP: {
Dan Albert782036b2019-06-24 14:35:35 -0700387 LOG(INFO) << "received FUNCTIONFS_SETUP control transfer: bRequestType = "
388 << static_cast<int>(event.u.setup.bRequestType)
389 << ", bRequest = " << static_cast<int>(event.u.setup.bRequest)
390 << ", wValue = " << static_cast<int>(event.u.setup.wValue)
391 << ", wIndex = " << static_cast<int>(event.u.setup.wIndex)
392 << ", wLength = " << static_cast<int>(event.u.setup.wLength);
393
394 if ((event.u.setup.bRequestType & USB_DIR_IN)) {
395 LOG(INFO) << "acking device-to-host control transfer";
396 ssize_t rc = adb_write(control_fd_.get(), "", 0);
397 if (rc != 0) {
398 PLOG(ERROR) << "failed to write empty packet to host";
399 break;
400 }
401 } else {
402 std::string buf;
403 buf.resize(event.u.setup.wLength + 1);
404
405 ssize_t rc = adb_read(control_fd_.get(), buf.data(), buf.size());
406 if (rc != event.u.setup.wLength) {
407 LOG(ERROR)
408 << "read " << rc
409 << " bytes when trying to read control request, expected "
410 << event.u.setup.wLength;
411 }
412
413 LOG(INFO) << "control request contents: " << buf;
414 break;
415 }
Josh Gao12807c72019-05-15 18:03:29 -0700416 }
Josh Gaoc51726c2018-10-11 16:33:05 -0700417 }
418 }
419
Josh Gaoe778b3a2019-02-28 13:29:32 -0800420 StopWorker();
Josh Gao19dc2962019-03-26 18:47:45 -0700421 HandleError("monitor thread finished");
Josh Gaoc51726c2018-10-11 16:33:05 -0700422 });
423 }
424
425 void StartWorker() {
Josh Gao19dc2962019-03-26 18:47:45 -0700426 CHECK(!worker_started_);
427 worker_started_ = true;
Josh Gaoc51726c2018-10-11 16:33:05 -0700428 worker_thread_ = std::thread([this]() {
429 adb_thread_setname("UsbFfs-worker");
430 for (size_t i = 0; i < kUsbReadQueueDepth; ++i) {
431 read_requests_[i] = CreateReadBlock(next_read_id_++);
Josh Gaoc0b831b2019-02-13 15:27:28 -0800432 if (!SubmitRead(&read_requests_[i])) {
433 return;
434 }
Josh Gaoc51726c2018-10-11 16:33:05 -0700435 }
436
437 while (!stopped_) {
438 uint64_t dummy;
Josh Gaoc0b831b2019-02-13 15:27:28 -0800439 ssize_t rc = adb_read(worker_event_fd_.get(), &dummy, sizeof(dummy));
Josh Gaoc51726c2018-10-11 16:33:05 -0700440 if (rc == -1) {
441 PLOG(FATAL) << "failed to read from eventfd";
442 } else if (rc == 0) {
443 LOG(FATAL) << "hit EOF on eventfd";
444 }
445
Josh Gao6933d542019-03-26 13:21:42 -0700446 ReadEvents();
Josh Gaoc51726c2018-10-11 16:33:05 -0700447 }
448 });
449 }
450
Josh Gaoe778b3a2019-02-28 13:29:32 -0800451 void StopWorker() {
Josh Gao19dc2962019-03-26 18:47:45 -0700452 if (!worker_started_) {
453 return;
454 }
455
Josh Gaoe778b3a2019-02-28 13:29:32 -0800456 pthread_t worker_thread_handle = worker_thread_.native_handle();
457 while (true) {
458 int rc = pthread_kill(worker_thread_handle, kInterruptionSignal);
459 if (rc != 0) {
460 LOG(ERROR) << "failed to send interruption signal to worker: " << strerror(rc);
461 break;
462 }
463
464 std::this_thread::sleep_for(100ms);
465
466 rc = pthread_kill(worker_thread_handle, 0);
467 if (rc == 0) {
468 continue;
469 } else if (rc == ESRCH) {
470 break;
471 } else {
472 LOG(ERROR) << "failed to send interruption signal to worker: " << strerror(rc);
473 }
474 }
475
476 worker_thread_.join();
477 }
478
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700479 void PrepareReadBlock(IoReadBlock* block, uint64_t id) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700480 block->pending = false;
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700481 if (block->payload.capacity() >= kUsbReadSize) {
482 block->payload.resize(kUsbReadSize);
483 } else {
484 block->payload = Block(kUsbReadSize);
485 }
Josh Gaoc51726c2018-10-11 16:33:05 -0700486 block->control.aio_data = static_cast<uint64_t>(TransferId::read(id));
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700487 block->control.aio_buf = reinterpret_cast<uintptr_t>(block->payload.data());
488 block->control.aio_nbytes = block->payload.size();
Josh Gaoc51726c2018-10-11 16:33:05 -0700489 }
490
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700491 IoReadBlock CreateReadBlock(uint64_t id) {
492 IoReadBlock block;
Josh Gaoc51726c2018-10-11 16:33:05 -0700493 PrepareReadBlock(&block, id);
494 block.control.aio_rw_flags = 0;
495 block.control.aio_lio_opcode = IOCB_CMD_PREAD;
496 block.control.aio_reqprio = 0;
497 block.control.aio_fildes = read_fd_.get();
498 block.control.aio_offset = 0;
499 block.control.aio_flags = IOCB_FLAG_RESFD;
Josh Gaoc0b831b2019-02-13 15:27:28 -0800500 block.control.aio_resfd = worker_event_fd_.get();
Josh Gaoc51726c2018-10-11 16:33:05 -0700501 return block;
502 }
503
Josh Gao6933d542019-03-26 13:21:42 -0700504 void ReadEvents() {
Josh Gaoc51726c2018-10-11 16:33:05 -0700505 static constexpr size_t kMaxEvents = kUsbReadQueueDepth + kUsbWriteQueueDepth;
506 struct io_event events[kMaxEvents];
507 struct timespec timeout = {.tv_sec = 0, .tv_nsec = 0};
508 int rc = io_getevents(aio_context_.get(), 0, kMaxEvents, events, &timeout);
509 if (rc == -1) {
510 HandleError(StringPrintf("io_getevents failed while reading: %s", strerror(errno)));
511 return;
512 }
513
514 for (int event_idx = 0; event_idx < rc; ++event_idx) {
515 auto& event = events[event_idx];
516 TransferId id = TransferId::from_value(event.data);
517
518 if (event.res < 0) {
519 std::string error =
520 StringPrintf("%s %" PRIu64 " failed with error %s",
521 id.direction == TransferDirection::READ ? "read" : "write",
522 id.id, strerror(-event.res));
523 HandleError(error);
524 return;
525 }
526
527 if (id.direction == TransferDirection::READ) {
Josh Gao7b304842020-02-28 14:53:56 -0800528 if (!HandleRead(id, event.res)) {
529 return;
530 }
Josh Gaoc51726c2018-10-11 16:33:05 -0700531 } else {
532 HandleWrite(id);
533 }
534 }
535 }
536
Josh Gao7b304842020-02-28 14:53:56 -0800537 bool HandleRead(TransferId id, int64_t size) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700538 uint64_t read_idx = id.id % kUsbReadQueueDepth;
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700539 IoReadBlock* block = &read_requests_[read_idx];
Josh Gaoc51726c2018-10-11 16:33:05 -0700540 block->pending = false;
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700541 block->payload.resize(size);
Josh Gaoc51726c2018-10-11 16:33:05 -0700542
543 // Notification for completed reads can be received out of order.
544 if (block->id().id != needed_read_id_) {
545 LOG(VERBOSE) << "read " << block->id().id << " completed while waiting for "
546 << needed_read_id_;
Josh Gao7b304842020-02-28 14:53:56 -0800547 return true;
Josh Gaoc51726c2018-10-11 16:33:05 -0700548 }
549
550 for (uint64_t id = needed_read_id_;; ++id) {
551 size_t read_idx = id % kUsbReadQueueDepth;
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700552 IoReadBlock* current_block = &read_requests_[read_idx];
Josh Gaoc51726c2018-10-11 16:33:05 -0700553 if (current_block->pending) {
554 break;
555 }
Josh Gao7b304842020-02-28 14:53:56 -0800556 if (!ProcessRead(current_block)) {
557 return false;
558 }
Josh Gaoc51726c2018-10-11 16:33:05 -0700559 ++needed_read_id_;
560 }
Josh Gao7b304842020-02-28 14:53:56 -0800561
562 return true;
Josh Gaoc51726c2018-10-11 16:33:05 -0700563 }
564
Josh Gao7b304842020-02-28 14:53:56 -0800565 bool ProcessRead(IoReadBlock* block) {
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700566 if (!block->payload.empty()) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700567 if (!incoming_header_.has_value()) {
Josh Gao7b304842020-02-28 14:53:56 -0800568 if (block->payload.size() != sizeof(amessage)) {
569 HandleError("received packet of unexpected length while reading header");
570 return false;
571 }
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700572 amessage& msg = incoming_header_.emplace();
573 memcpy(&msg, block->payload.data(), sizeof(msg));
Josh Gaoc51726c2018-10-11 16:33:05 -0700574 LOG(DEBUG) << "USB read:" << dump_header(&msg);
575 incoming_header_ = msg;
576 } else {
577 size_t bytes_left = incoming_header_->data_length - incoming_payload_.size();
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700578 Block payload = std::move(block->payload);
Josh Gao7b304842020-02-28 14:53:56 -0800579 if (block->payload.size() > bytes_left) {
580 HandleError("received too many bytes while waiting for payload");
581 return false;
582 }
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700583 incoming_payload_.append(std::move(payload));
Josh Gaoc51726c2018-10-11 16:33:05 -0700584 }
585
586 if (incoming_header_->data_length == incoming_payload_.size()) {
587 auto packet = std::make_unique<apacket>();
588 packet->msg = *incoming_header_;
589
590 // TODO: Make apacket contain an IOVector so we don't have to coalesce.
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700591 packet->payload = std::move(incoming_payload_).coalesce();
Josh Gaoc51726c2018-10-11 16:33:05 -0700592 read_callback_(this, std::move(packet));
593
594 incoming_header_.reset();
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700595 // reuse the capacity of the incoming payload while we can.
596 auto free_block = incoming_payload_.clear();
597 if (block->payload.capacity() == 0) {
598 block->payload = std::move(free_block);
599 }
Josh Gaoc51726c2018-10-11 16:33:05 -0700600 }
601 }
602
603 PrepareReadBlock(block, block->id().id + kUsbReadQueueDepth);
604 SubmitRead(block);
Josh Gao7b304842020-02-28 14:53:56 -0800605 return true;
Josh Gaoc51726c2018-10-11 16:33:05 -0700606 }
607
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700608 bool SubmitRead(IoReadBlock* block) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700609 block->pending = true;
610 struct iocb* iocb = &block->control;
611 if (io_submit(aio_context_.get(), 1, &iocb) != 1) {
Josh Gaoc0b831b2019-02-13 15:27:28 -0800612 if (errno == EINVAL && !gFfsAioSupported.has_value()) {
613 HandleError("failed to submit first read, AIO on FFS not supported");
614 gFfsAioSupported = false;
615 return false;
616 }
617
Josh Gaoc51726c2018-10-11 16:33:05 -0700618 HandleError(StringPrintf("failed to submit read: %s", strerror(errno)));
Josh Gaoc0b831b2019-02-13 15:27:28 -0800619 return false;
Josh Gaoc51726c2018-10-11 16:33:05 -0700620 }
Josh Gaoc0b831b2019-02-13 15:27:28 -0800621
622 gFfsAioSupported = true;
623 return true;
Josh Gaoc51726c2018-10-11 16:33:05 -0700624 }
625
626 void HandleWrite(TransferId id) {
627 std::lock_guard<std::mutex> lock(write_mutex_);
628 auto it =
629 std::find_if(write_requests_.begin(), write_requests_.end(), [id](const auto& req) {
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700630 return static_cast<uint64_t>(req.id()) == static_cast<uint64_t>(id);
Josh Gaoc51726c2018-10-11 16:33:05 -0700631 });
632 CHECK(it != write_requests_.end());
633
634 write_requests_.erase(it);
635 size_t outstanding_writes = --writes_submitted_;
636 LOG(DEBUG) << "USB write: reaped, down to " << outstanding_writes;
637
638 SubmitWrites();
639 }
640
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700641 IoWriteBlock CreateWriteBlock(std::shared_ptr<Block> payload, size_t offset, size_t len,
642 uint64_t id) {
643 auto block = IoWriteBlock();
644 block.payload = std::move(payload);
645 block.control.aio_data = static_cast<uint64_t>(TransferId::write(id));
646 block.control.aio_rw_flags = 0;
647 block.control.aio_lio_opcode = IOCB_CMD_PWRITE;
648 block.control.aio_reqprio = 0;
649 block.control.aio_fildes = write_fd_.get();
650 block.control.aio_buf = reinterpret_cast<uintptr_t>(block.payload->data() + offset);
651 block.control.aio_nbytes = len;
652 block.control.aio_offset = 0;
653 block.control.aio_flags = IOCB_FLAG_RESFD;
654 block.control.aio_resfd = worker_event_fd_.get();
Josh Gaoc51726c2018-10-11 16:33:05 -0700655 return block;
656 }
657
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700658 IoWriteBlock CreateWriteBlock(Block&& payload, uint64_t id) {
659 size_t len = payload.size();
660 return CreateWriteBlock(std::make_shared<Block>(std::move(payload)), 0, len, id);
Josh Gao86b33be2019-02-26 17:53:52 -0800661 }
662
Josh Gaoc51726c2018-10-11 16:33:05 -0700663 void SubmitWrites() REQUIRES(write_mutex_) {
664 if (writes_submitted_ == kUsbWriteQueueDepth) {
665 return;
666 }
667
668 ssize_t writes_to_submit = std::min(kUsbWriteQueueDepth - writes_submitted_,
669 write_requests_.size() - writes_submitted_);
670 CHECK_GE(writes_to_submit, 0);
671 if (writes_to_submit == 0) {
672 return;
673 }
674
675 struct iocb* iocbs[kUsbWriteQueueDepth];
676 for (int i = 0; i < writes_to_submit; ++i) {
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700677 CHECK(!write_requests_[writes_submitted_ + i].pending);
678 write_requests_[writes_submitted_ + i].pending = true;
679 iocbs[i] = &write_requests_[writes_submitted_ + i].control;
Josh Gaoc51726c2018-10-11 16:33:05 -0700680 LOG(VERBOSE) << "submitting write_request " << static_cast<void*>(iocbs[i]);
681 }
682
Josh Gao63b52ec2019-03-26 13:06:38 -0700683 writes_submitted_ += writes_to_submit;
684
Josh Gaoc51726c2018-10-11 16:33:05 -0700685 int rc = io_submit(aio_context_.get(), writes_to_submit, iocbs);
686 if (rc == -1) {
687 HandleError(StringPrintf("failed to submit write requests: %s", strerror(errno)));
688 return;
689 } else if (rc != writes_to_submit) {
690 LOG(FATAL) << "failed to submit all writes: wanted to submit " << writes_to_submit
691 << ", actually submitted " << rc;
692 }
Josh Gaoc51726c2018-10-11 16:33:05 -0700693 }
694
695 void HandleError(const std::string& error) {
696 std::call_once(error_flag_, [&]() {
697 error_callback_(this, error);
698 if (!stopped_) {
699 Stop();
700 }
701 });
702 }
703
704 std::thread monitor_thread_;
Josh Gao19dc2962019-03-26 18:47:45 -0700705
706 bool worker_started_;
Josh Gaoc51726c2018-10-11 16:33:05 -0700707 std::thread worker_thread_;
708
709 std::atomic<bool> stopped_;
710 std::promise<void> destruction_notifier_;
711 std::once_flag error_flag_;
712
Josh Gaoc0b831b2019-02-13 15:27:28 -0800713 unique_fd worker_event_fd_;
Dan Albert782036b2019-06-24 14:35:35 -0700714 unique_fd monitor_event_fd_;
Josh Gaoc51726c2018-10-11 16:33:05 -0700715
716 ScopedAioContext aio_context_;
Dan Albert782036b2019-06-24 14:35:35 -0700717 unique_fd control_fd_;
Josh Gaoc51726c2018-10-11 16:33:05 -0700718 unique_fd read_fd_;
719 unique_fd write_fd_;
720
721 std::optional<amessage> incoming_header_;
722 IOVector incoming_payload_;
723
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700724 std::array<IoReadBlock, kUsbReadQueueDepth> read_requests_;
Josh Gaoc51726c2018-10-11 16:33:05 -0700725 IOVector read_data_;
726
727 // ID of the next request that we're going to send out.
728 size_t next_read_id_ = 0;
729
730 // ID of the next packet we're waiting for.
731 size_t needed_read_id_ = 0;
732
733 std::mutex write_mutex_;
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700734 std::deque<IoWriteBlock> write_requests_ GUARDED_BY(write_mutex_);
Josh Gaoc51726c2018-10-11 16:33:05 -0700735 size_t next_write_id_ GUARDED_BY(write_mutex_) = 0;
736 size_t writes_submitted_ GUARDED_BY(write_mutex_) = 0;
Josh Gaoe778b3a2019-02-28 13:29:32 -0800737
738 static constexpr int kInterruptionSignal = SIGUSR1;
Josh Gaoc51726c2018-10-11 16:33:05 -0700739};
740
Josh Gaoc0b831b2019-02-13 15:27:28 -0800741void usb_init_legacy();
742
Josh Gaoc51726c2018-10-11 16:33:05 -0700743static void usb_ffs_open_thread() {
744 adb_thread_setname("usb ffs open");
745
746 while (true) {
Josh Gaoc0b831b2019-02-13 15:27:28 -0800747 if (gFfsAioSupported.has_value() && !gFfsAioSupported.value()) {
748 LOG(INFO) << "failed to use nonblocking ffs, falling back to legacy";
749 return usb_init_legacy();
750 }
751
Dan Albert782036b2019-06-24 14:35:35 -0700752 unique_fd control;
753 unique_fd bulk_out;
754 unique_fd bulk_in;
Josh Gaoc51726c2018-10-11 16:33:05 -0700755 if (!open_functionfs(&control, &bulk_out, &bulk_in)) {
756 std::this_thread::sleep_for(1s);
757 continue;
758 }
759
760 atransport* transport = new atransport();
761 transport->serial = "UsbFfs";
762 std::promise<void> destruction_notifier;
763 std::future<void> future = destruction_notifier.get_future();
764 transport->SetConnection(std::make_unique<UsbFfsConnection>(
Dan Albert782036b2019-06-24 14:35:35 -0700765 std::move(control), std::move(bulk_out), std::move(bulk_in),
Josh Gaoc51726c2018-10-11 16:33:05 -0700766 std::move(destruction_notifier)));
767 register_transport(transport);
768 future.wait();
769 }
770}
771
Josh Gaoc51726c2018-10-11 16:33:05 -0700772void usb_init() {
Josh Gao8038e352019-03-18 16:33:18 -0700773 bool use_nonblocking = android::base::GetBoolProperty(
774 "persist.adb.nonblocking_ffs",
775 android::base::GetBoolProperty("ro.adb.nonblocking_ffs", true));
776
Josh Gao02e94a42019-02-28 07:26:20 +0000777 if (use_nonblocking) {
Josh Gao0d780392019-02-26 22:10:33 +0000778 std::thread(usb_ffs_open_thread).detach();
Josh Gao02e94a42019-02-28 07:26:20 +0000779 } else {
780 usb_init_legacy();
Josh Gaoc51726c2018-10-11 16:33:05 -0700781 }
782}