blob: 7fff05af1951fc1b07a7e81e7bd1f00c1ff81a6f [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
Josh Gaoc51726c2018-10-11 16:33:05 -070048#include "adb_unique_fd.h"
49#include "adb_utils.h"
Josh Gao08718242020-03-27 18:09:56 -070050#include "daemon/usb_ffs.h"
Josh Gaoc51726c2018-10-11 16:33:05 -070051#include "sysdeps/chrono.h"
52#include "transport.h"
53#include "types.h"
54
55using android::base::StringPrintf;
56
Josh Gao08ccc732019-04-16 11:20:04 -070057// Not all USB controllers support operations larger than 16k, so don't go above that.
Josh Gaod0feaf92019-04-24 14:28:25 -070058// Also, each submitted operation does an allocation in the kernel of that size, so we want to
59// minimize our queue depth while still maintaining a deep enough queue to keep the USB stack fed.
60static constexpr size_t kUsbReadQueueDepth = 8;
Josh Gao08ccc732019-04-16 11:20:04 -070061static constexpr size_t kUsbReadSize = 4 * PAGE_SIZE;
Josh Gaoc51726c2018-10-11 16:33:05 -070062
Josh Gaod0feaf92019-04-24 14:28:25 -070063static constexpr size_t kUsbWriteQueueDepth = 8;
Josh Gao08ccc732019-04-16 11:20:04 -070064static constexpr size_t kUsbWriteSize = 4 * PAGE_SIZE;
Josh Gaoc51726c2018-10-11 16:33:05 -070065
Dan Albert782036b2019-06-24 14:35:35 -070066static 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
Josh Gaoc51726c2018-10-11 16:33:05 -070085enum 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
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700117template <class Payload>
Josh Gaoc51726c2018-10-11 16:33:05 -0700118struct IoBlock {
Josh Gaob0195742019-03-18 14:11:28 -0700119 bool pending = false;
Evgenii Stepanov9da358d2019-05-15 18:45:01 -0700120 struct iocb control = {};
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700121 Payload payload;
Josh Gaoc51726c2018-10-11 16:33:05 -0700122
123 TransferId id() const { return TransferId::from_value(control.aio_data); }
124};
125
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700126using IoReadBlock = IoBlock<Block>;
127using IoWriteBlock = IoBlock<std::shared_ptr<Block>>;
128
Josh Gaoc51726c2018-10-11 16:33:05 -0700129struct ScopedAioContext {
130 ScopedAioContext() = default;
131 ~ScopedAioContext() { reset(); }
132
133 ScopedAioContext(ScopedAioContext&& move) { reset(move.release()); }
134 ScopedAioContext(const ScopedAioContext& copy) = delete;
135
136 ScopedAioContext& operator=(ScopedAioContext&& move) {
137 reset(move.release());
138 return *this;
139 }
140 ScopedAioContext& operator=(const ScopedAioContext& copy) = delete;
141
142 static ScopedAioContext Create(size_t max_events) {
143 aio_context_t ctx = 0;
144 if (io_setup(max_events, &ctx) != 0) {
145 PLOG(FATAL) << "failed to create aio_context_t";
146 }
147 ScopedAioContext result;
148 result.reset(ctx);
149 return result;
150 }
151
152 aio_context_t release() {
153 aio_context_t result = context_;
154 context_ = 0;
155 return result;
156 }
157
158 void reset(aio_context_t new_context = 0) {
159 if (context_ != 0) {
160 io_destroy(context_);
161 }
162
163 context_ = new_context;
164 }
165
166 aio_context_t get() { return context_; }
167
168 private:
169 aio_context_t context_ = 0;
170};
171
172struct UsbFfsConnection : public Connection {
Dan Albert782036b2019-06-24 14:35:35 -0700173 UsbFfsConnection(unique_fd control, unique_fd read, unique_fd write,
Josh Gaoc51726c2018-10-11 16:33:05 -0700174 std::promise<void> destruction_notifier)
Josh Gao19dc2962019-03-26 18:47:45 -0700175 : worker_started_(false),
176 stopped_(false),
Josh Gaoc51726c2018-10-11 16:33:05 -0700177 destruction_notifier_(std::move(destruction_notifier)),
Dan Albert782036b2019-06-24 14:35:35 -0700178 control_fd_(std::move(control)),
Josh Gaoc51726c2018-10-11 16:33:05 -0700179 read_fd_(std::move(read)),
180 write_fd_(std::move(write)) {
181 LOG(INFO) << "UsbFfsConnection constructed";
Josh Gaoc0b831b2019-02-13 15:27:28 -0800182 worker_event_fd_.reset(eventfd(0, EFD_CLOEXEC));
183 if (worker_event_fd_ == -1) {
184 PLOG(FATAL) << "failed to create eventfd";
185 }
186
Dan Albert782036b2019-06-24 14:35:35 -0700187 monitor_event_fd_.reset(eventfd(0, EFD_CLOEXEC));
188 if (monitor_event_fd_ == -1) {
189 PLOG(FATAL) << "failed to create eventfd";
190 }
191
Josh Gaoc51726c2018-10-11 16:33:05 -0700192 aio_context_ = ScopedAioContext::Create(kUsbReadQueueDepth + kUsbWriteQueueDepth);
193 }
194
195 ~UsbFfsConnection() {
196 LOG(INFO) << "UsbFfsConnection being destroyed";
197 Stop();
198 monitor_thread_.join();
Josh Gaoc0b831b2019-02-13 15:27:28 -0800199
200 // We need to explicitly close our file descriptors before we notify our destruction,
201 // because the thread listening on the future will immediately try to reopen the endpoint.
Josh Gao19dc2962019-03-26 18:47:45 -0700202 aio_context_.reset();
Dan Albert782036b2019-06-24 14:35:35 -0700203 control_fd_.reset();
Josh Gaoc0b831b2019-02-13 15:27:28 -0800204 read_fd_.reset();
205 write_fd_.reset();
206
Josh Gaoc51726c2018-10-11 16:33:05 -0700207 destruction_notifier_.set_value();
208 }
209
210 virtual bool Write(std::unique_ptr<apacket> packet) override final {
211 LOG(DEBUG) << "USB write: " << dump_header(&packet->msg);
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700212 auto header = std::make_shared<Block>(sizeof(packet->msg));
213 memcpy(header->data(), &packet->msg, sizeof(packet->msg));
Josh Gaoc51726c2018-10-11 16:33:05 -0700214
215 std::lock_guard<std::mutex> lock(write_mutex_);
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700216 write_requests_.push_back(
217 CreateWriteBlock(std::move(header), 0, sizeof(packet->msg), next_write_id_++));
Josh Gaoc51726c2018-10-11 16:33:05 -0700218 if (!packet->payload.empty()) {
Josh Gao86b33be2019-02-26 17:53:52 -0800219 // The kernel attempts to allocate a contiguous block of memory for each write,
220 // which can fail if the write is large and the kernel heap is fragmented.
221 // Split large writes into smaller chunks to avoid this.
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700222 auto payload = std::make_shared<Block>(std::move(packet->payload));
Josh Gao86b33be2019-02-26 17:53:52 -0800223 size_t offset = 0;
224 size_t len = payload->size();
225
226 while (len > 0) {
227 size_t write_size = std::min(kUsbWriteSize, len);
228 write_requests_.push_back(
229 CreateWriteBlock(payload, offset, write_size, next_write_id_++));
230 len -= write_size;
231 offset += write_size;
232 }
Josh Gaoc51726c2018-10-11 16:33:05 -0700233 }
234 SubmitWrites();
235 return true;
236 }
237
238 virtual void Start() override final { StartMonitor(); }
239
240 virtual void Stop() override final {
241 if (stopped_.exchange(true)) {
242 return;
243 }
244 stopped_ = true;
245 uint64_t notify = 1;
Josh Gaoc0b831b2019-02-13 15:27:28 -0800246 ssize_t rc = adb_write(worker_event_fd_.get(), &notify, sizeof(notify));
Josh Gaoc51726c2018-10-11 16:33:05 -0700247 if (rc < 0) {
Josh Gaoc0b831b2019-02-13 15:27:28 -0800248 PLOG(FATAL) << "failed to notify worker eventfd to stop UsbFfsConnection";
Josh Gaoc51726c2018-10-11 16:33:05 -0700249 }
250 CHECK_EQ(static_cast<size_t>(rc), sizeof(notify));
Dan Albert782036b2019-06-24 14:35:35 -0700251
252 rc = adb_write(monitor_event_fd_.get(), &notify, sizeof(notify));
253 if (rc < 0) {
254 PLOG(FATAL) << "failed to notify monitor eventfd to stop UsbFfsConnection";
255 }
256
257 CHECK_EQ(static_cast<size_t>(rc), sizeof(notify));
Josh Gaoc51726c2018-10-11 16:33:05 -0700258 }
259
Joshua Duong5cf78682020-01-21 13:19:42 -0800260 virtual bool DoTlsHandshake(RSA* key, std::string* auth_key) override final {
261 // TODO: support TLS for usb connections.
262 LOG(FATAL) << "Not supported yet.";
263 return false;
264 }
265
Josh Gaoc51726c2018-10-11 16:33:05 -0700266 private:
267 void StartMonitor() {
268 // This is a bit of a mess.
269 // It's possible for io_submit to end up blocking, if we call it as the endpoint
270 // becomes disabled. Work around this by having a monitor thread to listen for functionfs
271 // lifecycle events. If we notice an error condition (either we've become disabled, or we
272 // were never enabled in the first place), we send interruption signals to the worker thread
273 // until it dies, and then report failure to the transport via HandleError, which will
274 // eventually result in the transport being destroyed, which will result in UsbFfsConnection
275 // being destroyed, which unblocks the open thread and restarts this entire process.
Josh Gaoc51726c2018-10-11 16:33:05 -0700276 static std::once_flag handler_once;
277 std::call_once(handler_once, []() { signal(kInterruptionSignal, [](int) {}); });
278
279 monitor_thread_ = std::thread([this]() {
280 adb_thread_setname("UsbFfs-monitor");
Josh Gaoe3d34e12020-02-26 15:44:30 -0800281 LOG(INFO) << "UsbFfs-monitor thread spawned";
Josh Gaoc51726c2018-10-11 16:33:05 -0700282
Dan Albert782036b2019-06-24 14:35:35 -0700283 bool bound = false;
Josh Gao6933d542019-03-26 13:21:42 -0700284 bool enabled = false;
Josh Gaoc51726c2018-10-11 16:33:05 -0700285 bool running = true;
286 while (running) {
Josh Gaoc0b831b2019-02-13 15:27:28 -0800287 adb_pollfd pfd[2] = {
Dan Albert782036b2019-06-24 14:35:35 -0700288 { .fd = control_fd_.get(), .events = POLLIN, .revents = 0 },
289 { .fd = monitor_event_fd_.get(), .events = POLLIN, .revents = 0 },
Josh Gaoc0b831b2019-02-13 15:27:28 -0800290 };
Josh Gao19dc2962019-03-26 18:47:45 -0700291
Dan Albert782036b2019-06-24 14:35:35 -0700292 // If we don't see our first bind within a second, try again.
293 int timeout_ms = bound ? -1 : 1000;
294
295 int rc = TEMP_FAILURE_RETRY(adb_poll(pfd, 2, timeout_ms));
Josh Gaoc0b831b2019-02-13 15:27:28 -0800296 if (rc == -1) {
297 PLOG(FATAL) << "poll on USB control fd failed";
Dan Albert782036b2019-06-24 14:35:35 -0700298 } else if (rc == 0) {
299 LOG(WARNING) << "timed out while waiting for FUNCTIONFS_BIND, trying again";
300 break;
Josh Gaoc0b831b2019-02-13 15:27:28 -0800301 }
302
303 if (pfd[1].revents) {
Dan Albert782036b2019-06-24 14:35:35 -0700304 // We were told to die.
305 break;
Josh Gaoc51726c2018-10-11 16:33:05 -0700306 }
307
308 struct usb_functionfs_event event;
Dan Albert782036b2019-06-24 14:35:35 -0700309 rc = TEMP_FAILURE_RETRY(adb_read(control_fd_.get(), &event, sizeof(event)));
Josh Gao1f7ae9d2019-05-10 11:37:34 -0700310 if (rc == -1) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700311 PLOG(FATAL) << "failed to read functionfs event";
Josh Gao1f7ae9d2019-05-10 11:37:34 -0700312 } else if (rc == 0) {
313 LOG(WARNING) << "hit EOF on functionfs control fd";
314 break;
315 } else if (rc != sizeof(event)) {
316 LOG(FATAL) << "read functionfs event of unexpected size, expected "
317 << sizeof(event) << ", got " << rc;
Josh Gaoc51726c2018-10-11 16:33:05 -0700318 }
319
320 LOG(INFO) << "USB event: "
Dan Albert782036b2019-06-24 14:35:35 -0700321 << to_string(static_cast<usb_functionfs_event_type>(event.type));
Josh Gaoc51726c2018-10-11 16:33:05 -0700322
323 switch (event.type) {
324 case FUNCTIONFS_BIND:
Dan Albert782036b2019-06-24 14:35:35 -0700325 if (bound) {
326 LOG(WARNING) << "received FUNCTIONFS_BIND while already bound?";
327 running = false;
328 break;
329 }
330
331 if (enabled) {
332 LOG(WARNING) << "received FUNCTIONFS_BIND while already enabled?";
333 running = false;
334 break;
335 }
336
337 bound = true;
Josh Gaoc51726c2018-10-11 16:33:05 -0700338 break;
339
340 case FUNCTIONFS_ENABLE:
Dan Albert782036b2019-06-24 14:35:35 -0700341 if (!bound) {
342 LOG(WARNING) << "received FUNCTIONFS_ENABLE while not bound?";
343 running = false;
344 break;
345 }
346
Josh Gao87afd522019-03-28 11:05:53 -0700347 if (enabled) {
348 LOG(WARNING) << "received FUNCTIONFS_ENABLE while already enabled?";
349 running = false;
Josh Gao94fb36b2019-05-01 16:53:53 -0700350 break;
Josh Gao87afd522019-03-28 11:05:53 -0700351 }
352
353 enabled = true;
Josh Gaoc51726c2018-10-11 16:33:05 -0700354 StartWorker();
355 break;
356
357 case FUNCTIONFS_DISABLE:
Dan Albert782036b2019-06-24 14:35:35 -0700358 if (!bound) {
359 LOG(WARNING) << "received FUNCTIONFS_DISABLE while not bound?";
360 }
361
Josh Gao87afd522019-03-28 11:05:53 -0700362 if (!enabled) {
363 LOG(WARNING) << "received FUNCTIONFS_DISABLE while not enabled?";
364 }
365
366 enabled = false;
Josh Gao6933d542019-03-26 13:21:42 -0700367 running = false;
368 break;
369
370 case FUNCTIONFS_UNBIND:
Josh Gao87afd522019-03-28 11:05:53 -0700371 if (enabled) {
372 LOG(WARNING) << "received FUNCTIONFS_UNBIND while still enabled?";
373 }
Josh Gao6933d542019-03-26 13:21:42 -0700374
Dan Albert782036b2019-06-24 14:35:35 -0700375 if (!bound) {
376 LOG(WARNING) << "received FUNCTIONFS_UNBIND when not bound?";
377 }
378
379 bound = false;
Josh Gaoc51726c2018-10-11 16:33:05 -0700380 running = false;
381 break;
Josh Gao12807c72019-05-15 18:03:29 -0700382
383 case FUNCTIONFS_SETUP: {
Dan Albert782036b2019-06-24 14:35:35 -0700384 LOG(INFO) << "received FUNCTIONFS_SETUP control transfer: bRequestType = "
385 << static_cast<int>(event.u.setup.bRequestType)
386 << ", bRequest = " << static_cast<int>(event.u.setup.bRequest)
387 << ", wValue = " << static_cast<int>(event.u.setup.wValue)
388 << ", wIndex = " << static_cast<int>(event.u.setup.wIndex)
389 << ", wLength = " << static_cast<int>(event.u.setup.wLength);
390
391 if ((event.u.setup.bRequestType & USB_DIR_IN)) {
392 LOG(INFO) << "acking device-to-host control transfer";
393 ssize_t rc = adb_write(control_fd_.get(), "", 0);
394 if (rc != 0) {
395 PLOG(ERROR) << "failed to write empty packet to host";
396 break;
397 }
398 } else {
399 std::string buf;
400 buf.resize(event.u.setup.wLength + 1);
401
402 ssize_t rc = adb_read(control_fd_.get(), buf.data(), buf.size());
403 if (rc != event.u.setup.wLength) {
404 LOG(ERROR)
405 << "read " << rc
406 << " bytes when trying to read control request, expected "
407 << event.u.setup.wLength;
408 }
409
410 LOG(INFO) << "control request contents: " << buf;
411 break;
412 }
Josh Gao12807c72019-05-15 18:03:29 -0700413 }
Josh Gaoc51726c2018-10-11 16:33:05 -0700414 }
415 }
416
Josh Gaoe778b3a2019-02-28 13:29:32 -0800417 StopWorker();
Josh Gao19dc2962019-03-26 18:47:45 -0700418 HandleError("monitor thread finished");
Josh Gaoc51726c2018-10-11 16:33:05 -0700419 });
420 }
421
422 void StartWorker() {
Josh Gao19dc2962019-03-26 18:47:45 -0700423 CHECK(!worker_started_);
424 worker_started_ = true;
Josh Gaoc51726c2018-10-11 16:33:05 -0700425 worker_thread_ = std::thread([this]() {
426 adb_thread_setname("UsbFfs-worker");
Josh Gaoe3d34e12020-02-26 15:44:30 -0800427 LOG(INFO) << "UsbFfs-worker thread spawned";
428
Josh Gaoc51726c2018-10-11 16:33:05 -0700429 for (size_t i = 0; i < kUsbReadQueueDepth; ++i) {
430 read_requests_[i] = CreateReadBlock(next_read_id_++);
Josh Gaoc0b831b2019-02-13 15:27:28 -0800431 if (!SubmitRead(&read_requests_[i])) {
432 return;
433 }
Josh Gaoc51726c2018-10-11 16:33:05 -0700434 }
435
436 while (!stopped_) {
437 uint64_t dummy;
Josh Gaoc0b831b2019-02-13 15:27:28 -0800438 ssize_t rc = adb_read(worker_event_fd_.get(), &dummy, sizeof(dummy));
Josh Gaoc51726c2018-10-11 16:33:05 -0700439 if (rc == -1) {
440 PLOG(FATAL) << "failed to read from eventfd";
441 } else if (rc == 0) {
442 LOG(FATAL) << "hit EOF on eventfd";
443 }
444
Josh Gao6933d542019-03-26 13:21:42 -0700445 ReadEvents();
Josh Gaoc51726c2018-10-11 16:33:05 -0700446 }
447 });
448 }
449
Josh Gaoe778b3a2019-02-28 13:29:32 -0800450 void StopWorker() {
Josh Gao19dc2962019-03-26 18:47:45 -0700451 if (!worker_started_) {
452 return;
453 }
454
Josh Gaoe778b3a2019-02-28 13:29:32 -0800455 pthread_t worker_thread_handle = worker_thread_.native_handle();
456 while (true) {
457 int rc = pthread_kill(worker_thread_handle, kInterruptionSignal);
458 if (rc != 0) {
459 LOG(ERROR) << "failed to send interruption signal to worker: " << strerror(rc);
460 break;
461 }
462
463 std::this_thread::sleep_for(100ms);
464
465 rc = pthread_kill(worker_thread_handle, 0);
466 if (rc == 0) {
467 continue;
468 } else if (rc == ESRCH) {
469 break;
470 } else {
471 LOG(ERROR) << "failed to send interruption signal to worker: " << strerror(rc);
472 }
473 }
474
475 worker_thread_.join();
476 }
477
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700478 void PrepareReadBlock(IoReadBlock* block, uint64_t id) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700479 block->pending = false;
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700480 if (block->payload.capacity() >= kUsbReadSize) {
481 block->payload.resize(kUsbReadSize);
482 } else {
483 block->payload = Block(kUsbReadSize);
484 }
Josh Gaoc51726c2018-10-11 16:33:05 -0700485 block->control.aio_data = static_cast<uint64_t>(TransferId::read(id));
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700486 block->control.aio_buf = reinterpret_cast<uintptr_t>(block->payload.data());
487 block->control.aio_nbytes = block->payload.size();
Josh Gaoc51726c2018-10-11 16:33:05 -0700488 }
489
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700490 IoReadBlock CreateReadBlock(uint64_t id) {
491 IoReadBlock block;
Josh Gaoc51726c2018-10-11 16:33:05 -0700492 PrepareReadBlock(&block, id);
493 block.control.aio_rw_flags = 0;
494 block.control.aio_lio_opcode = IOCB_CMD_PREAD;
495 block.control.aio_reqprio = 0;
496 block.control.aio_fildes = read_fd_.get();
497 block.control.aio_offset = 0;
498 block.control.aio_flags = IOCB_FLAG_RESFD;
Josh Gaoc0b831b2019-02-13 15:27:28 -0800499 block.control.aio_resfd = worker_event_fd_.get();
Josh Gaoc51726c2018-10-11 16:33:05 -0700500 return block;
501 }
502
Josh Gao6933d542019-03-26 13:21:42 -0700503 void ReadEvents() {
Josh Gaoc51726c2018-10-11 16:33:05 -0700504 static constexpr size_t kMaxEvents = kUsbReadQueueDepth + kUsbWriteQueueDepth;
505 struct io_event events[kMaxEvents];
506 struct timespec timeout = {.tv_sec = 0, .tv_nsec = 0};
507 int rc = io_getevents(aio_context_.get(), 0, kMaxEvents, events, &timeout);
508 if (rc == -1) {
509 HandleError(StringPrintf("io_getevents failed while reading: %s", strerror(errno)));
510 return;
511 }
512
513 for (int event_idx = 0; event_idx < rc; ++event_idx) {
514 auto& event = events[event_idx];
515 TransferId id = TransferId::from_value(event.data);
516
517 if (event.res < 0) {
518 std::string error =
519 StringPrintf("%s %" PRIu64 " failed with error %s",
520 id.direction == TransferDirection::READ ? "read" : "write",
521 id.id, strerror(-event.res));
522 HandleError(error);
523 return;
524 }
525
526 if (id.direction == TransferDirection::READ) {
Josh Gao7b304842020-02-28 14:53:56 -0800527 if (!HandleRead(id, event.res)) {
528 return;
529 }
Josh Gaoc51726c2018-10-11 16:33:05 -0700530 } else {
531 HandleWrite(id);
532 }
533 }
534 }
535
Josh Gao7b304842020-02-28 14:53:56 -0800536 bool HandleRead(TransferId id, int64_t size) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700537 uint64_t read_idx = id.id % kUsbReadQueueDepth;
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700538 IoReadBlock* block = &read_requests_[read_idx];
Josh Gaoc51726c2018-10-11 16:33:05 -0700539 block->pending = false;
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700540 block->payload.resize(size);
Josh Gaoc51726c2018-10-11 16:33:05 -0700541
542 // Notification for completed reads can be received out of order.
543 if (block->id().id != needed_read_id_) {
544 LOG(VERBOSE) << "read " << block->id().id << " completed while waiting for "
545 << needed_read_id_;
Josh Gao7b304842020-02-28 14:53:56 -0800546 return true;
Josh Gaoc51726c2018-10-11 16:33:05 -0700547 }
548
549 for (uint64_t id = needed_read_id_;; ++id) {
550 size_t read_idx = id % kUsbReadQueueDepth;
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700551 IoReadBlock* current_block = &read_requests_[read_idx];
Josh Gaoc51726c2018-10-11 16:33:05 -0700552 if (current_block->pending) {
553 break;
554 }
Josh Gao7b304842020-02-28 14:53:56 -0800555 if (!ProcessRead(current_block)) {
556 return false;
557 }
Josh Gaoc51726c2018-10-11 16:33:05 -0700558 ++needed_read_id_;
559 }
Josh Gao7b304842020-02-28 14:53:56 -0800560
561 return true;
Josh Gaoc51726c2018-10-11 16:33:05 -0700562 }
563
Josh Gao7b304842020-02-28 14:53:56 -0800564 bool ProcessRead(IoReadBlock* block) {
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700565 if (!block->payload.empty()) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700566 if (!incoming_header_.has_value()) {
Josh Gao7b304842020-02-28 14:53:56 -0800567 if (block->payload.size() != sizeof(amessage)) {
568 HandleError("received packet of unexpected length while reading header");
569 return false;
570 }
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700571 amessage& msg = incoming_header_.emplace();
572 memcpy(&msg, block->payload.data(), sizeof(msg));
Josh Gaoc51726c2018-10-11 16:33:05 -0700573 LOG(DEBUG) << "USB read:" << dump_header(&msg);
574 incoming_header_ = msg;
575 } else {
576 size_t bytes_left = incoming_header_->data_length - incoming_payload_.size();
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700577 Block payload = std::move(block->payload);
Josh Gao7b304842020-02-28 14:53:56 -0800578 if (block->payload.size() > bytes_left) {
579 HandleError("received too many bytes while waiting for payload");
580 return false;
581 }
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700582 incoming_payload_.append(std::move(payload));
Josh Gaoc51726c2018-10-11 16:33:05 -0700583 }
584
585 if (incoming_header_->data_length == incoming_payload_.size()) {
586 auto packet = std::make_unique<apacket>();
587 packet->msg = *incoming_header_;
588
589 // TODO: Make apacket contain an IOVector so we don't have to coalesce.
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700590 packet->payload = std::move(incoming_payload_).coalesce();
Josh Gaoc51726c2018-10-11 16:33:05 -0700591 read_callback_(this, std::move(packet));
592
593 incoming_header_.reset();
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700594 // reuse the capacity of the incoming payload while we can.
595 auto free_block = incoming_payload_.clear();
596 if (block->payload.capacity() == 0) {
597 block->payload = std::move(free_block);
598 }
Josh Gaoc51726c2018-10-11 16:33:05 -0700599 }
600 }
601
602 PrepareReadBlock(block, block->id().id + kUsbReadQueueDepth);
603 SubmitRead(block);
Josh Gao7b304842020-02-28 14:53:56 -0800604 return true;
Josh Gaoc51726c2018-10-11 16:33:05 -0700605 }
606
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700607 bool SubmitRead(IoReadBlock* block) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700608 block->pending = true;
609 struct iocb* iocb = &block->control;
610 if (io_submit(aio_context_.get(), 1, &iocb) != 1) {
611 HandleError(StringPrintf("failed to submit read: %s", strerror(errno)));
Josh Gaoc0b831b2019-02-13 15:27:28 -0800612 return false;
Josh Gaoc51726c2018-10-11 16:33:05 -0700613 }
Josh Gaoc0b831b2019-02-13 15:27:28 -0800614
Josh Gaoc0b831b2019-02-13 15:27:28 -0800615 return true;
Josh Gaoc51726c2018-10-11 16:33:05 -0700616 }
617
618 void HandleWrite(TransferId id) {
619 std::lock_guard<std::mutex> lock(write_mutex_);
620 auto it =
621 std::find_if(write_requests_.begin(), write_requests_.end(), [id](const auto& req) {
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700622 return static_cast<uint64_t>(req.id()) == static_cast<uint64_t>(id);
Josh Gaoc51726c2018-10-11 16:33:05 -0700623 });
624 CHECK(it != write_requests_.end());
625
626 write_requests_.erase(it);
627 size_t outstanding_writes = --writes_submitted_;
628 LOG(DEBUG) << "USB write: reaped, down to " << outstanding_writes;
629
630 SubmitWrites();
631 }
632
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700633 IoWriteBlock CreateWriteBlock(std::shared_ptr<Block> payload, size_t offset, size_t len,
634 uint64_t id) {
635 auto block = IoWriteBlock();
636 block.payload = std::move(payload);
637 block.control.aio_data = static_cast<uint64_t>(TransferId::write(id));
638 block.control.aio_rw_flags = 0;
639 block.control.aio_lio_opcode = IOCB_CMD_PWRITE;
640 block.control.aio_reqprio = 0;
641 block.control.aio_fildes = write_fd_.get();
642 block.control.aio_buf = reinterpret_cast<uintptr_t>(block.payload->data() + offset);
643 block.control.aio_nbytes = len;
644 block.control.aio_offset = 0;
645 block.control.aio_flags = IOCB_FLAG_RESFD;
646 block.control.aio_resfd = worker_event_fd_.get();
Josh Gaoc51726c2018-10-11 16:33:05 -0700647 return block;
648 }
649
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700650 IoWriteBlock CreateWriteBlock(Block&& payload, uint64_t id) {
651 size_t len = payload.size();
652 return CreateWriteBlock(std::make_shared<Block>(std::move(payload)), 0, len, id);
Josh Gao86b33be2019-02-26 17:53:52 -0800653 }
654
Josh Gaoc51726c2018-10-11 16:33:05 -0700655 void SubmitWrites() REQUIRES(write_mutex_) {
656 if (writes_submitted_ == kUsbWriteQueueDepth) {
657 return;
658 }
659
660 ssize_t writes_to_submit = std::min(kUsbWriteQueueDepth - writes_submitted_,
661 write_requests_.size() - writes_submitted_);
662 CHECK_GE(writes_to_submit, 0);
663 if (writes_to_submit == 0) {
664 return;
665 }
666
667 struct iocb* iocbs[kUsbWriteQueueDepth];
668 for (int i = 0; i < writes_to_submit; ++i) {
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700669 CHECK(!write_requests_[writes_submitted_ + i].pending);
670 write_requests_[writes_submitted_ + i].pending = true;
671 iocbs[i] = &write_requests_[writes_submitted_ + i].control;
Josh Gaoc51726c2018-10-11 16:33:05 -0700672 LOG(VERBOSE) << "submitting write_request " << static_cast<void*>(iocbs[i]);
673 }
674
Josh Gao63b52ec2019-03-26 13:06:38 -0700675 writes_submitted_ += writes_to_submit;
676
Josh Gaoc51726c2018-10-11 16:33:05 -0700677 int rc = io_submit(aio_context_.get(), writes_to_submit, iocbs);
678 if (rc == -1) {
679 HandleError(StringPrintf("failed to submit write requests: %s", strerror(errno)));
680 return;
681 } else if (rc != writes_to_submit) {
682 LOG(FATAL) << "failed to submit all writes: wanted to submit " << writes_to_submit
683 << ", actually submitted " << rc;
684 }
Josh Gaoc51726c2018-10-11 16:33:05 -0700685 }
686
687 void HandleError(const std::string& error) {
688 std::call_once(error_flag_, [&]() {
689 error_callback_(this, error);
690 if (!stopped_) {
691 Stop();
692 }
693 });
694 }
695
696 std::thread monitor_thread_;
Josh Gao19dc2962019-03-26 18:47:45 -0700697
698 bool worker_started_;
Josh Gaoc51726c2018-10-11 16:33:05 -0700699 std::thread worker_thread_;
700
701 std::atomic<bool> stopped_;
702 std::promise<void> destruction_notifier_;
703 std::once_flag error_flag_;
704
Josh Gaoc0b831b2019-02-13 15:27:28 -0800705 unique_fd worker_event_fd_;
Dan Albert782036b2019-06-24 14:35:35 -0700706 unique_fd monitor_event_fd_;
Josh Gaoc51726c2018-10-11 16:33:05 -0700707
708 ScopedAioContext aio_context_;
Dan Albert782036b2019-06-24 14:35:35 -0700709 unique_fd control_fd_;
Josh Gaoc51726c2018-10-11 16:33:05 -0700710 unique_fd read_fd_;
711 unique_fd write_fd_;
712
713 std::optional<amessage> incoming_header_;
714 IOVector incoming_payload_;
715
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700716 std::array<IoReadBlock, kUsbReadQueueDepth> read_requests_;
Josh Gaoc51726c2018-10-11 16:33:05 -0700717 IOVector read_data_;
718
719 // ID of the next request that we're going to send out.
720 size_t next_read_id_ = 0;
721
722 // ID of the next packet we're waiting for.
723 size_t needed_read_id_ = 0;
724
725 std::mutex write_mutex_;
Yurii Zubrytskyi5dda7f62019-07-12 14:11:54 -0700726 std::deque<IoWriteBlock> write_requests_ GUARDED_BY(write_mutex_);
Josh Gaoc51726c2018-10-11 16:33:05 -0700727 size_t next_write_id_ GUARDED_BY(write_mutex_) = 0;
728 size_t writes_submitted_ GUARDED_BY(write_mutex_) = 0;
Josh Gaoe778b3a2019-02-28 13:29:32 -0800729
730 static constexpr int kInterruptionSignal = SIGUSR1;
Josh Gaoc51726c2018-10-11 16:33:05 -0700731};
732
733static void usb_ffs_open_thread() {
734 adb_thread_setname("usb ffs open");
735
736 while (true) {
Dan Albert782036b2019-06-24 14:35:35 -0700737 unique_fd control;
738 unique_fd bulk_out;
739 unique_fd bulk_in;
Josh Gaoc51726c2018-10-11 16:33:05 -0700740 if (!open_functionfs(&control, &bulk_out, &bulk_in)) {
741 std::this_thread::sleep_for(1s);
742 continue;
743 }
744
745 atransport* transport = new atransport();
746 transport->serial = "UsbFfs";
747 std::promise<void> destruction_notifier;
748 std::future<void> future = destruction_notifier.get_future();
749 transport->SetConnection(std::make_unique<UsbFfsConnection>(
Dan Albert782036b2019-06-24 14:35:35 -0700750 std::move(control), std::move(bulk_out), std::move(bulk_in),
Josh Gaoc51726c2018-10-11 16:33:05 -0700751 std::move(destruction_notifier)));
752 register_transport(transport);
753 future.wait();
754 }
755}
756
Josh Gaoc51726c2018-10-11 16:33:05 -0700757void usb_init() {
Josh Gao08718242020-03-27 18:09:56 -0700758 std::thread(usb_ffs_open_thread).detach();
Josh Gaoc51726c2018-10-11 16:33:05 -0700759}