blob: 0fc4512c02f34854205700c9684ff0ebe533bff2 [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 Gao08ccc732019-04-16 11:20:04 -070060// Not all USB controllers support operations larger than 16k, so don't go above that.
Josh Gao5841a962019-02-28 15:44:05 -080061static constexpr size_t kUsbReadQueueDepth = 32;
Josh Gao08ccc732019-04-16 11:20:04 -070062static constexpr size_t kUsbReadSize = 4 * PAGE_SIZE;
Josh Gaoc51726c2018-10-11 16:33:05 -070063
Josh Gao5841a962019-02-28 15:44:05 -080064static constexpr size_t kUsbWriteQueueDepth = 32;
Josh Gao08ccc732019-04-16 11:20:04 -070065static constexpr size_t kUsbWriteSize = 4 * PAGE_SIZE;
Josh Gaoc51726c2018-10-11 16:33:05 -070066
67static const char* to_string(enum usb_functionfs_event_type type) {
68 switch (type) {
69 case FUNCTIONFS_BIND:
70 return "FUNCTIONFS_BIND";
71 case FUNCTIONFS_UNBIND:
72 return "FUNCTIONFS_UNBIND";
73 case FUNCTIONFS_ENABLE:
74 return "FUNCTIONFS_ENABLE";
75 case FUNCTIONFS_DISABLE:
76 return "FUNCTIONFS_DISABLE";
77 case FUNCTIONFS_SETUP:
78 return "FUNCTIONFS_SETUP";
79 case FUNCTIONFS_SUSPEND:
80 return "FUNCTIONFS_SUSPEND";
81 case FUNCTIONFS_RESUME:
82 return "FUNCTIONFS_RESUME";
83 }
84}
85
86enum class TransferDirection : uint64_t {
87 READ = 0,
88 WRITE = 1,
89};
90
91struct TransferId {
92 TransferDirection direction : 1;
93 uint64_t id : 63;
94
95 TransferId() : TransferId(TransferDirection::READ, 0) {}
96
97 private:
98 TransferId(TransferDirection direction, uint64_t id) : direction(direction), id(id) {}
99
100 public:
101 explicit operator uint64_t() const {
102 uint64_t result;
103 static_assert(sizeof(*this) == sizeof(result));
104 memcpy(&result, this, sizeof(*this));
105 return result;
106 }
107
108 static TransferId read(uint64_t id) { return TransferId(TransferDirection::READ, id); }
109 static TransferId write(uint64_t id) { return TransferId(TransferDirection::WRITE, id); }
110
111 static TransferId from_value(uint64_t value) {
112 TransferId result;
113 memcpy(&result, &value, sizeof(value));
114 return result;
115 }
116};
117
118struct IoBlock {
Josh Gaob0195742019-03-18 14:11:28 -0700119 bool pending = false;
Josh Gaoc51726c2018-10-11 16:33:05 -0700120 struct iocb control;
Josh Gao86b33be2019-02-26 17:53:52 -0800121 std::shared_ptr<Block> payload;
Josh Gaoc51726c2018-10-11 16:33:05 -0700122
123 TransferId id() const { return TransferId::from_value(control.aio_data); }
124};
125
126struct ScopedAioContext {
127 ScopedAioContext() = default;
128 ~ScopedAioContext() { reset(); }
129
130 ScopedAioContext(ScopedAioContext&& move) { reset(move.release()); }
131 ScopedAioContext(const ScopedAioContext& copy) = delete;
132
133 ScopedAioContext& operator=(ScopedAioContext&& move) {
134 reset(move.release());
135 return *this;
136 }
137 ScopedAioContext& operator=(const ScopedAioContext& copy) = delete;
138
139 static ScopedAioContext Create(size_t max_events) {
140 aio_context_t ctx = 0;
141 if (io_setup(max_events, &ctx) != 0) {
142 PLOG(FATAL) << "failed to create aio_context_t";
143 }
144 ScopedAioContext result;
145 result.reset(ctx);
146 return result;
147 }
148
149 aio_context_t release() {
150 aio_context_t result = context_;
151 context_ = 0;
152 return result;
153 }
154
155 void reset(aio_context_t new_context = 0) {
156 if (context_ != 0) {
157 io_destroy(context_);
158 }
159
160 context_ = new_context;
161 }
162
163 aio_context_t get() { return context_; }
164
165 private:
166 aio_context_t context_ = 0;
167};
168
169struct UsbFfsConnection : public Connection {
170 UsbFfsConnection(unique_fd control, unique_fd read, unique_fd write,
171 std::promise<void> destruction_notifier)
Josh Gao19dc2962019-03-26 18:47:45 -0700172 : worker_started_(false),
173 stopped_(false),
Josh Gaoc51726c2018-10-11 16:33:05 -0700174 destruction_notifier_(std::move(destruction_notifier)),
175 control_fd_(std::move(control)),
176 read_fd_(std::move(read)),
177 write_fd_(std::move(write)) {
178 LOG(INFO) << "UsbFfsConnection constructed";
Josh Gaoc0b831b2019-02-13 15:27:28 -0800179 worker_event_fd_.reset(eventfd(0, EFD_CLOEXEC));
180 if (worker_event_fd_ == -1) {
181 PLOG(FATAL) << "failed to create eventfd";
182 }
183
184 monitor_event_fd_.reset(eventfd(0, EFD_CLOEXEC));
185 if (monitor_event_fd_ == -1) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700186 PLOG(FATAL) << "failed to create eventfd";
187 }
188
189 aio_context_ = ScopedAioContext::Create(kUsbReadQueueDepth + kUsbWriteQueueDepth);
190 }
191
192 ~UsbFfsConnection() {
193 LOG(INFO) << "UsbFfsConnection being destroyed";
194 Stop();
195 monitor_thread_.join();
Josh Gaoc0b831b2019-02-13 15:27:28 -0800196
197 // We need to explicitly close our file descriptors before we notify our destruction,
198 // because the thread listening on the future will immediately try to reopen the endpoint.
Josh Gao19dc2962019-03-26 18:47:45 -0700199 aio_context_.reset();
Josh Gaoc0b831b2019-02-13 15:27:28 -0800200 control_fd_.reset();
201 read_fd_.reset();
202 write_fd_.reset();
203
Josh Gaoc51726c2018-10-11 16:33:05 -0700204 destruction_notifier_.set_value();
205 }
206
207 virtual bool Write(std::unique_ptr<apacket> packet) override final {
208 LOG(DEBUG) << "USB write: " << dump_header(&packet->msg);
209 Block header(sizeof(packet->msg));
210 memcpy(header.data(), &packet->msg, sizeof(packet->msg));
211
212 std::lock_guard<std::mutex> lock(write_mutex_);
213 write_requests_.push_back(CreateWriteBlock(std::move(header), next_write_id_++));
214 if (!packet->payload.empty()) {
Josh Gao86b33be2019-02-26 17:53:52 -0800215 // The kernel attempts to allocate a contiguous block of memory for each write,
216 // which can fail if the write is large and the kernel heap is fragmented.
217 // Split large writes into smaller chunks to avoid this.
218 std::shared_ptr<Block> payload = std::make_shared<Block>(std::move(packet->payload));
219 size_t offset = 0;
220 size_t len = payload->size();
221
222 while (len > 0) {
223 size_t write_size = std::min(kUsbWriteSize, len);
224 write_requests_.push_back(
225 CreateWriteBlock(payload, offset, write_size, next_write_id_++));
226 len -= write_size;
227 offset += write_size;
228 }
Josh Gaoc51726c2018-10-11 16:33:05 -0700229 }
230 SubmitWrites();
231 return true;
232 }
233
234 virtual void Start() override final { StartMonitor(); }
235
236 virtual void Stop() override final {
237 if (stopped_.exchange(true)) {
238 return;
239 }
240 stopped_ = true;
241 uint64_t notify = 1;
Josh Gaoc0b831b2019-02-13 15:27:28 -0800242 ssize_t rc = adb_write(worker_event_fd_.get(), &notify, sizeof(notify));
Josh Gaoc51726c2018-10-11 16:33:05 -0700243 if (rc < 0) {
Josh Gaoc0b831b2019-02-13 15:27:28 -0800244 PLOG(FATAL) << "failed to notify worker eventfd to stop UsbFfsConnection";
Josh Gaoc51726c2018-10-11 16:33:05 -0700245 }
246 CHECK_EQ(static_cast<size_t>(rc), sizeof(notify));
Josh Gaoc0b831b2019-02-13 15:27:28 -0800247
248 rc = adb_write(monitor_event_fd_.get(), &notify, sizeof(notify));
249 if (rc < 0) {
250 PLOG(FATAL) << "failed to notify monitor eventfd to stop UsbFfsConnection";
251 }
252
253 CHECK_EQ(static_cast<size_t>(rc), sizeof(notify));
Josh Gaoc51726c2018-10-11 16:33:05 -0700254 }
255
256 private:
257 void StartMonitor() {
258 // This is a bit of a mess.
259 // It's possible for io_submit to end up blocking, if we call it as the endpoint
260 // becomes disabled. Work around this by having a monitor thread to listen for functionfs
261 // lifecycle events. If we notice an error condition (either we've become disabled, or we
262 // were never enabled in the first place), we send interruption signals to the worker thread
263 // until it dies, and then report failure to the transport via HandleError, which will
264 // eventually result in the transport being destroyed, which will result in UsbFfsConnection
265 // being destroyed, which unblocks the open thread and restarts this entire process.
Josh Gaoc51726c2018-10-11 16:33:05 -0700266 static std::once_flag handler_once;
267 std::call_once(handler_once, []() { signal(kInterruptionSignal, [](int) {}); });
268
269 monitor_thread_ = std::thread([this]() {
270 adb_thread_setname("UsbFfs-monitor");
271
272 bool bound = false;
Josh Gao6933d542019-03-26 13:21:42 -0700273 bool enabled = false;
Josh Gaoc51726c2018-10-11 16:33:05 -0700274 bool running = true;
275 while (running) {
Josh Gaoc0b831b2019-02-13 15:27:28 -0800276 adb_pollfd pfd[2] = {
277 { .fd = control_fd_.get(), .events = POLLIN, .revents = 0 },
278 { .fd = monitor_event_fd_.get(), .events = POLLIN, .revents = 0 },
279 };
Josh Gao19dc2962019-03-26 18:47:45 -0700280
281 // If we don't see our first bind within a second, try again.
282 int timeout_ms = bound ? -1 : 1000;
283
284 int rc = TEMP_FAILURE_RETRY(adb_poll(pfd, 2, timeout_ms));
Josh Gaoc0b831b2019-02-13 15:27:28 -0800285 if (rc == -1) {
286 PLOG(FATAL) << "poll on USB control fd failed";
287 } else if (rc == 0) {
Josh Gao19dc2962019-03-26 18:47:45 -0700288 LOG(WARNING) << "timed out while waiting for FUNCTIONFS_BIND, trying again";
289 break;
Josh Gaoc0b831b2019-02-13 15:27:28 -0800290 }
291
292 if (pfd[1].revents) {
293 // We were told to die.
294 break;
Josh Gaoc51726c2018-10-11 16:33:05 -0700295 }
296
297 struct usb_functionfs_event event;
Josh Gao1f7ae9d2019-05-10 11:37:34 -0700298 rc = TEMP_FAILURE_RETRY(adb_read(control_fd_.get(), &event, sizeof(event)));
299 if (rc == -1) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700300 PLOG(FATAL) << "failed to read functionfs event";
Josh Gao1f7ae9d2019-05-10 11:37:34 -0700301 } else if (rc == 0) {
302 LOG(WARNING) << "hit EOF on functionfs control fd";
303 break;
304 } else if (rc != sizeof(event)) {
305 LOG(FATAL) << "read functionfs event of unexpected size, expected "
306 << sizeof(event) << ", got " << rc;
Josh Gaoc51726c2018-10-11 16:33:05 -0700307 }
308
309 LOG(INFO) << "USB event: "
310 << to_string(static_cast<usb_functionfs_event_type>(event.type));
311
312 switch (event.type) {
313 case FUNCTIONFS_BIND:
Josh Gao87afd522019-03-28 11:05:53 -0700314 if (bound) {
315 LOG(WARNING) << "received FUNCTIONFS_BIND while already bound?";
316 running = false;
317 }
Josh Gao6933d542019-03-26 13:21:42 -0700318
Josh Gao87afd522019-03-28 11:05:53 -0700319 if (enabled) {
320 LOG(WARNING) << "received FUNCTIONFS_BIND while already enabled?";
321 running = false;
322 }
323
324 bound = true;
Josh Gaoc51726c2018-10-11 16:33:05 -0700325 break;
326
327 case FUNCTIONFS_ENABLE:
Josh Gao87afd522019-03-28 11:05:53 -0700328 if (!bound) {
329 LOG(WARNING) << "received FUNCTIONFS_ENABLE while not bound?";
330 running = false;
331 }
Josh Gao6933d542019-03-26 13:21:42 -0700332
Josh Gao87afd522019-03-28 11:05:53 -0700333 if (enabled) {
334 LOG(WARNING) << "received FUNCTIONFS_ENABLE while already enabled?";
335 running = false;
336 }
337
338 enabled = true;
Josh Gaoc51726c2018-10-11 16:33:05 -0700339 StartWorker();
340 break;
341
342 case FUNCTIONFS_DISABLE:
Josh Gao87afd522019-03-28 11:05:53 -0700343 if (!bound) {
344 LOG(WARNING) << "received FUNCTIONFS_DISABLE while not bound?";
345 }
Josh Gao6933d542019-03-26 13:21:42 -0700346
Josh Gao87afd522019-03-28 11:05:53 -0700347 if (!enabled) {
348 LOG(WARNING) << "received FUNCTIONFS_DISABLE while not enabled?";
349 }
350
351 enabled = false;
Josh Gao6933d542019-03-26 13:21:42 -0700352 running = false;
353 break;
354
355 case FUNCTIONFS_UNBIND:
Josh Gao87afd522019-03-28 11:05:53 -0700356 if (enabled) {
357 LOG(WARNING) << "received FUNCTIONFS_UNBIND while still enabled?";
358 }
Josh Gao6933d542019-03-26 13:21:42 -0700359
Josh Gao87afd522019-03-28 11:05:53 -0700360 if (!bound) {
361 LOG(WARNING) << "received FUNCTIONFS_UNBIND when not bound?";
362 }
363
364 bound = false;
Josh Gaoc51726c2018-10-11 16:33:05 -0700365 running = false;
366 break;
367 }
368 }
369
Josh Gaoe778b3a2019-02-28 13:29:32 -0800370 StopWorker();
Josh Gao19dc2962019-03-26 18:47:45 -0700371 HandleError("monitor thread finished");
Josh Gaoc51726c2018-10-11 16:33:05 -0700372 });
373 }
374
375 void StartWorker() {
Josh Gao19dc2962019-03-26 18:47:45 -0700376 CHECK(!worker_started_);
377 worker_started_ = true;
Josh Gaoc51726c2018-10-11 16:33:05 -0700378 worker_thread_ = std::thread([this]() {
379 adb_thread_setname("UsbFfs-worker");
380 for (size_t i = 0; i < kUsbReadQueueDepth; ++i) {
381 read_requests_[i] = CreateReadBlock(next_read_id_++);
Josh Gaoc0b831b2019-02-13 15:27:28 -0800382 if (!SubmitRead(&read_requests_[i])) {
383 return;
384 }
Josh Gaoc51726c2018-10-11 16:33:05 -0700385 }
386
387 while (!stopped_) {
388 uint64_t dummy;
Josh Gaoc0b831b2019-02-13 15:27:28 -0800389 ssize_t rc = adb_read(worker_event_fd_.get(), &dummy, sizeof(dummy));
Josh Gaoc51726c2018-10-11 16:33:05 -0700390 if (rc == -1) {
391 PLOG(FATAL) << "failed to read from eventfd";
392 } else if (rc == 0) {
393 LOG(FATAL) << "hit EOF on eventfd";
394 }
395
Josh Gao6933d542019-03-26 13:21:42 -0700396 ReadEvents();
Josh Gaoc51726c2018-10-11 16:33:05 -0700397 }
398 });
399 }
400
Josh Gaoe778b3a2019-02-28 13:29:32 -0800401 void StopWorker() {
Josh Gao19dc2962019-03-26 18:47:45 -0700402 if (!worker_started_) {
403 return;
404 }
405
Josh Gaoe778b3a2019-02-28 13:29:32 -0800406 pthread_t worker_thread_handle = worker_thread_.native_handle();
407 while (true) {
408 int rc = pthread_kill(worker_thread_handle, kInterruptionSignal);
409 if (rc != 0) {
410 LOG(ERROR) << "failed to send interruption signal to worker: " << strerror(rc);
411 break;
412 }
413
414 std::this_thread::sleep_for(100ms);
415
416 rc = pthread_kill(worker_thread_handle, 0);
417 if (rc == 0) {
418 continue;
419 } else if (rc == ESRCH) {
420 break;
421 } else {
422 LOG(ERROR) << "failed to send interruption signal to worker: " << strerror(rc);
423 }
424 }
425
426 worker_thread_.join();
427 }
428
Josh Gaoc51726c2018-10-11 16:33:05 -0700429 void PrepareReadBlock(IoBlock* block, uint64_t id) {
430 block->pending = false;
Josh Gao86b33be2019-02-26 17:53:52 -0800431 block->payload = std::make_shared<Block>(kUsbReadSize);
Josh Gaoc51726c2018-10-11 16:33:05 -0700432 block->control.aio_data = static_cast<uint64_t>(TransferId::read(id));
Josh Gao86b33be2019-02-26 17:53:52 -0800433 block->control.aio_buf = reinterpret_cast<uintptr_t>(block->payload->data());
434 block->control.aio_nbytes = block->payload->size();
Josh Gaoc51726c2018-10-11 16:33:05 -0700435 }
436
437 IoBlock CreateReadBlock(uint64_t id) {
438 IoBlock block;
439 PrepareReadBlock(&block, id);
440 block.control.aio_rw_flags = 0;
441 block.control.aio_lio_opcode = IOCB_CMD_PREAD;
442 block.control.aio_reqprio = 0;
443 block.control.aio_fildes = read_fd_.get();
444 block.control.aio_offset = 0;
445 block.control.aio_flags = IOCB_FLAG_RESFD;
Josh Gaoc0b831b2019-02-13 15:27:28 -0800446 block.control.aio_resfd = worker_event_fd_.get();
Josh Gaoc51726c2018-10-11 16:33:05 -0700447 return block;
448 }
449
Josh Gao6933d542019-03-26 13:21:42 -0700450 void ReadEvents() {
Josh Gaoc51726c2018-10-11 16:33:05 -0700451 static constexpr size_t kMaxEvents = kUsbReadQueueDepth + kUsbWriteQueueDepth;
452 struct io_event events[kMaxEvents];
453 struct timespec timeout = {.tv_sec = 0, .tv_nsec = 0};
454 int rc = io_getevents(aio_context_.get(), 0, kMaxEvents, events, &timeout);
455 if (rc == -1) {
456 HandleError(StringPrintf("io_getevents failed while reading: %s", strerror(errno)));
457 return;
458 }
459
460 for (int event_idx = 0; event_idx < rc; ++event_idx) {
461 auto& event = events[event_idx];
462 TransferId id = TransferId::from_value(event.data);
463
464 if (event.res < 0) {
465 std::string error =
466 StringPrintf("%s %" PRIu64 " failed with error %s",
467 id.direction == TransferDirection::READ ? "read" : "write",
468 id.id, strerror(-event.res));
469 HandleError(error);
470 return;
471 }
472
473 if (id.direction == TransferDirection::READ) {
474 HandleRead(id, event.res);
475 } else {
476 HandleWrite(id);
477 }
478 }
479 }
480
481 void HandleRead(TransferId id, int64_t size) {
482 uint64_t read_idx = id.id % kUsbReadQueueDepth;
483 IoBlock* block = &read_requests_[read_idx];
484 block->pending = false;
Josh Gao86b33be2019-02-26 17:53:52 -0800485 block->payload->resize(size);
Josh Gaoc51726c2018-10-11 16:33:05 -0700486
487 // Notification for completed reads can be received out of order.
488 if (block->id().id != needed_read_id_) {
489 LOG(VERBOSE) << "read " << block->id().id << " completed while waiting for "
490 << needed_read_id_;
491 return;
492 }
493
494 for (uint64_t id = needed_read_id_;; ++id) {
495 size_t read_idx = id % kUsbReadQueueDepth;
496 IoBlock* current_block = &read_requests_[read_idx];
497 if (current_block->pending) {
498 break;
499 }
500 ProcessRead(current_block);
501 ++needed_read_id_;
502 }
503 }
504
505 void ProcessRead(IoBlock* block) {
Josh Gao86b33be2019-02-26 17:53:52 -0800506 if (!block->payload->empty()) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700507 if (!incoming_header_.has_value()) {
Josh Gao86b33be2019-02-26 17:53:52 -0800508 CHECK_EQ(sizeof(amessage), block->payload->size());
Josh Gaoc51726c2018-10-11 16:33:05 -0700509 amessage msg;
Josh Gao86b33be2019-02-26 17:53:52 -0800510 memcpy(&msg, block->payload->data(), sizeof(amessage));
Josh Gaoc51726c2018-10-11 16:33:05 -0700511 LOG(DEBUG) << "USB read:" << dump_header(&msg);
512 incoming_header_ = msg;
513 } else {
514 size_t bytes_left = incoming_header_->data_length - incoming_payload_.size();
Josh Gao86b33be2019-02-26 17:53:52 -0800515 Block payload = std::move(*block->payload);
Josh Gaoc51726c2018-10-11 16:33:05 -0700516 CHECK_LE(payload.size(), bytes_left);
517 incoming_payload_.append(std::make_unique<Block>(std::move(payload)));
518 }
519
520 if (incoming_header_->data_length == incoming_payload_.size()) {
521 auto packet = std::make_unique<apacket>();
522 packet->msg = *incoming_header_;
523
524 // TODO: Make apacket contain an IOVector so we don't have to coalesce.
525 packet->payload = incoming_payload_.coalesce();
526 read_callback_(this, std::move(packet));
527
528 incoming_header_.reset();
529 incoming_payload_.clear();
530 }
531 }
532
533 PrepareReadBlock(block, block->id().id + kUsbReadQueueDepth);
534 SubmitRead(block);
535 }
536
Josh Gaoc0b831b2019-02-13 15:27:28 -0800537 bool SubmitRead(IoBlock* block) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700538 block->pending = true;
539 struct iocb* iocb = &block->control;
540 if (io_submit(aio_context_.get(), 1, &iocb) != 1) {
Josh Gaoc0b831b2019-02-13 15:27:28 -0800541 if (errno == EINVAL && !gFfsAioSupported.has_value()) {
542 HandleError("failed to submit first read, AIO on FFS not supported");
543 gFfsAioSupported = false;
544 return false;
545 }
546
Josh Gaoc51726c2018-10-11 16:33:05 -0700547 HandleError(StringPrintf("failed to submit read: %s", strerror(errno)));
Josh Gaoc0b831b2019-02-13 15:27:28 -0800548 return false;
Josh Gaoc51726c2018-10-11 16:33:05 -0700549 }
Josh Gaoc0b831b2019-02-13 15:27:28 -0800550
551 gFfsAioSupported = true;
552 return true;
Josh Gaoc51726c2018-10-11 16:33:05 -0700553 }
554
555 void HandleWrite(TransferId id) {
556 std::lock_guard<std::mutex> lock(write_mutex_);
557 auto it =
558 std::find_if(write_requests_.begin(), write_requests_.end(), [id](const auto& req) {
559 return static_cast<uint64_t>(req->id()) == static_cast<uint64_t>(id);
560 });
561 CHECK(it != write_requests_.end());
562
563 write_requests_.erase(it);
564 size_t outstanding_writes = --writes_submitted_;
565 LOG(DEBUG) << "USB write: reaped, down to " << outstanding_writes;
566
567 SubmitWrites();
568 }
569
Josh Gao86b33be2019-02-26 17:53:52 -0800570 std::unique_ptr<IoBlock> CreateWriteBlock(std::shared_ptr<Block> payload, size_t offset,
571 size_t len, uint64_t id) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700572 auto block = std::make_unique<IoBlock>();
573 block->payload = std::move(payload);
574 block->control.aio_data = static_cast<uint64_t>(TransferId::write(id));
575 block->control.aio_rw_flags = 0;
576 block->control.aio_lio_opcode = IOCB_CMD_PWRITE;
577 block->control.aio_reqprio = 0;
578 block->control.aio_fildes = write_fd_.get();
Josh Gao86b33be2019-02-26 17:53:52 -0800579 block->control.aio_buf = reinterpret_cast<uintptr_t>(block->payload->data() + offset);
580 block->control.aio_nbytes = len;
Josh Gaoc51726c2018-10-11 16:33:05 -0700581 block->control.aio_offset = 0;
582 block->control.aio_flags = IOCB_FLAG_RESFD;
Josh Gaoc0b831b2019-02-13 15:27:28 -0800583 block->control.aio_resfd = worker_event_fd_.get();
Josh Gaoc51726c2018-10-11 16:33:05 -0700584 return block;
585 }
586
Josh Gao86b33be2019-02-26 17:53:52 -0800587 std::unique_ptr<IoBlock> CreateWriteBlock(Block payload, uint64_t id) {
588 std::shared_ptr<Block> block = std::make_shared<Block>(std::move(payload));
589 size_t len = block->size();
590 return CreateWriteBlock(std::move(block), 0, len, id);
591 }
592
Josh Gaoc51726c2018-10-11 16:33:05 -0700593 void SubmitWrites() REQUIRES(write_mutex_) {
594 if (writes_submitted_ == kUsbWriteQueueDepth) {
595 return;
596 }
597
598 ssize_t writes_to_submit = std::min(kUsbWriteQueueDepth - writes_submitted_,
599 write_requests_.size() - writes_submitted_);
600 CHECK_GE(writes_to_submit, 0);
601 if (writes_to_submit == 0) {
602 return;
603 }
604
605 struct iocb* iocbs[kUsbWriteQueueDepth];
606 for (int i = 0; i < writes_to_submit; ++i) {
607 CHECK(!write_requests_[writes_submitted_ + i]->pending);
608 write_requests_[writes_submitted_ + i]->pending = true;
609 iocbs[i] = &write_requests_[writes_submitted_ + i]->control;
610 LOG(VERBOSE) << "submitting write_request " << static_cast<void*>(iocbs[i]);
611 }
612
Josh Gao63b52ec2019-03-26 13:06:38 -0700613 writes_submitted_ += writes_to_submit;
614
Josh Gaoc51726c2018-10-11 16:33:05 -0700615 int rc = io_submit(aio_context_.get(), writes_to_submit, iocbs);
616 if (rc == -1) {
617 HandleError(StringPrintf("failed to submit write requests: %s", strerror(errno)));
618 return;
619 } else if (rc != writes_to_submit) {
620 LOG(FATAL) << "failed to submit all writes: wanted to submit " << writes_to_submit
621 << ", actually submitted " << rc;
622 }
Josh Gaoc51726c2018-10-11 16:33:05 -0700623 }
624
625 void HandleError(const std::string& error) {
626 std::call_once(error_flag_, [&]() {
627 error_callback_(this, error);
628 if (!stopped_) {
629 Stop();
630 }
631 });
632 }
633
634 std::thread monitor_thread_;
Josh Gao19dc2962019-03-26 18:47:45 -0700635
636 bool worker_started_;
Josh Gaoc51726c2018-10-11 16:33:05 -0700637 std::thread worker_thread_;
638
639 std::atomic<bool> stopped_;
640 std::promise<void> destruction_notifier_;
641 std::once_flag error_flag_;
642
Josh Gaoc0b831b2019-02-13 15:27:28 -0800643 unique_fd worker_event_fd_;
644 unique_fd monitor_event_fd_;
Josh Gaoc51726c2018-10-11 16:33:05 -0700645
646 ScopedAioContext aio_context_;
647 unique_fd control_fd_;
648 unique_fd read_fd_;
649 unique_fd write_fd_;
650
651 std::optional<amessage> incoming_header_;
652 IOVector incoming_payload_;
653
654 std::array<IoBlock, kUsbReadQueueDepth> read_requests_;
655 IOVector read_data_;
656
657 // ID of the next request that we're going to send out.
658 size_t next_read_id_ = 0;
659
660 // ID of the next packet we're waiting for.
661 size_t needed_read_id_ = 0;
662
663 std::mutex write_mutex_;
664 std::deque<std::unique_ptr<IoBlock>> write_requests_ GUARDED_BY(write_mutex_);
665 size_t next_write_id_ GUARDED_BY(write_mutex_) = 0;
666 size_t writes_submitted_ GUARDED_BY(write_mutex_) = 0;
Josh Gaoe778b3a2019-02-28 13:29:32 -0800667
668 static constexpr int kInterruptionSignal = SIGUSR1;
Josh Gaoc51726c2018-10-11 16:33:05 -0700669};
670
Josh Gaoc0b831b2019-02-13 15:27:28 -0800671void usb_init_legacy();
672
Josh Gaoc51726c2018-10-11 16:33:05 -0700673static void usb_ffs_open_thread() {
674 adb_thread_setname("usb ffs open");
675
676 while (true) {
Josh Gaoc0b831b2019-02-13 15:27:28 -0800677 if (gFfsAioSupported.has_value() && !gFfsAioSupported.value()) {
678 LOG(INFO) << "failed to use nonblocking ffs, falling back to legacy";
679 return usb_init_legacy();
680 }
681
Josh Gaoc51726c2018-10-11 16:33:05 -0700682 unique_fd control;
683 unique_fd bulk_out;
684 unique_fd bulk_in;
685 if (!open_functionfs(&control, &bulk_out, &bulk_in)) {
686 std::this_thread::sleep_for(1s);
687 continue;
688 }
689
690 atransport* transport = new atransport();
691 transport->serial = "UsbFfs";
692 std::promise<void> destruction_notifier;
693 std::future<void> future = destruction_notifier.get_future();
694 transport->SetConnection(std::make_unique<UsbFfsConnection>(
695 std::move(control), std::move(bulk_out), std::move(bulk_in),
696 std::move(destruction_notifier)));
697 register_transport(transport);
698 future.wait();
699 }
700}
701
Josh Gaoc51726c2018-10-11 16:33:05 -0700702void usb_init() {
Josh Gao8038e352019-03-18 16:33:18 -0700703 bool use_nonblocking = android::base::GetBoolProperty(
704 "persist.adb.nonblocking_ffs",
705 android::base::GetBoolProperty("ro.adb.nonblocking_ffs", true));
706
Josh Gao02e94a42019-02-28 07:26:20 +0000707 if (use_nonblocking) {
Josh Gao0d780392019-02-26 22:10:33 +0000708 std::thread(usb_ffs_open_thread).detach();
Josh Gao02e94a42019-02-28 07:26:20 +0000709 } else {
710 usb_init_legacy();
Josh Gaoc51726c2018-10-11 16:33:05 -0700711 }
712}