blob: ac2d1c7eed37098f8c84f4a942440ada24db27c1 [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 Gaoc51726c2018-10-11 16:33:05 -070060static constexpr size_t kUsbReadQueueDepth = 16;
61static constexpr size_t kUsbReadSize = 16384;
62
63static constexpr size_t kUsbWriteQueueDepth = 16;
Josh Gao86b33be2019-02-26 17:53:52 -080064static constexpr size_t kUsbWriteSize = 16 * PAGE_SIZE;
Josh Gaoc51726c2018-10-11 16:33:05 -070065
66static const char* to_string(enum usb_functionfs_event_type type) {
67 switch (type) {
68 case FUNCTIONFS_BIND:
69 return "FUNCTIONFS_BIND";
70 case FUNCTIONFS_UNBIND:
71 return "FUNCTIONFS_UNBIND";
72 case FUNCTIONFS_ENABLE:
73 return "FUNCTIONFS_ENABLE";
74 case FUNCTIONFS_DISABLE:
75 return "FUNCTIONFS_DISABLE";
76 case FUNCTIONFS_SETUP:
77 return "FUNCTIONFS_SETUP";
78 case FUNCTIONFS_SUSPEND:
79 return "FUNCTIONFS_SUSPEND";
80 case FUNCTIONFS_RESUME:
81 return "FUNCTIONFS_RESUME";
82 }
83}
84
85enum class TransferDirection : uint64_t {
86 READ = 0,
87 WRITE = 1,
88};
89
90struct TransferId {
91 TransferDirection direction : 1;
92 uint64_t id : 63;
93
94 TransferId() : TransferId(TransferDirection::READ, 0) {}
95
96 private:
97 TransferId(TransferDirection direction, uint64_t id) : direction(direction), id(id) {}
98
99 public:
100 explicit operator uint64_t() const {
101 uint64_t result;
102 static_assert(sizeof(*this) == sizeof(result));
103 memcpy(&result, this, sizeof(*this));
104 return result;
105 }
106
107 static TransferId read(uint64_t id) { return TransferId(TransferDirection::READ, id); }
108 static TransferId write(uint64_t id) { return TransferId(TransferDirection::WRITE, id); }
109
110 static TransferId from_value(uint64_t value) {
111 TransferId result;
112 memcpy(&result, &value, sizeof(value));
113 return result;
114 }
115};
116
117struct IoBlock {
118 bool pending;
119 struct iocb control;
Josh Gao86b33be2019-02-26 17:53:52 -0800120 std::shared_ptr<Block> payload;
Josh Gaoc51726c2018-10-11 16:33:05 -0700121
122 TransferId id() const { return TransferId::from_value(control.aio_data); }
123};
124
125struct ScopedAioContext {
126 ScopedAioContext() = default;
127 ~ScopedAioContext() { reset(); }
128
129 ScopedAioContext(ScopedAioContext&& move) { reset(move.release()); }
130 ScopedAioContext(const ScopedAioContext& copy) = delete;
131
132 ScopedAioContext& operator=(ScopedAioContext&& move) {
133 reset(move.release());
134 return *this;
135 }
136 ScopedAioContext& operator=(const ScopedAioContext& copy) = delete;
137
138 static ScopedAioContext Create(size_t max_events) {
139 aio_context_t ctx = 0;
140 if (io_setup(max_events, &ctx) != 0) {
141 PLOG(FATAL) << "failed to create aio_context_t";
142 }
143 ScopedAioContext result;
144 result.reset(ctx);
145 return result;
146 }
147
148 aio_context_t release() {
149 aio_context_t result = context_;
150 context_ = 0;
151 return result;
152 }
153
154 void reset(aio_context_t new_context = 0) {
155 if (context_ != 0) {
156 io_destroy(context_);
157 }
158
159 context_ = new_context;
160 }
161
162 aio_context_t get() { return context_; }
163
164 private:
165 aio_context_t context_ = 0;
166};
167
168struct UsbFfsConnection : public Connection {
169 UsbFfsConnection(unique_fd control, unique_fd read, unique_fd write,
170 std::promise<void> destruction_notifier)
171 : stopped_(false),
172 destruction_notifier_(std::move(destruction_notifier)),
173 control_fd_(std::move(control)),
174 read_fd_(std::move(read)),
175 write_fd_(std::move(write)) {
176 LOG(INFO) << "UsbFfsConnection constructed";
Josh Gaoc0b831b2019-02-13 15:27:28 -0800177 worker_event_fd_.reset(eventfd(0, EFD_CLOEXEC));
178 if (worker_event_fd_ == -1) {
179 PLOG(FATAL) << "failed to create eventfd";
180 }
181
182 monitor_event_fd_.reset(eventfd(0, EFD_CLOEXEC));
183 if (monitor_event_fd_ == -1) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700184 PLOG(FATAL) << "failed to create eventfd";
185 }
186
187 aio_context_ = ScopedAioContext::Create(kUsbReadQueueDepth + kUsbWriteQueueDepth);
188 }
189
190 ~UsbFfsConnection() {
191 LOG(INFO) << "UsbFfsConnection being destroyed";
192 Stop();
193 monitor_thread_.join();
Josh Gaoc0b831b2019-02-13 15:27:28 -0800194
195 // We need to explicitly close our file descriptors before we notify our destruction,
196 // because the thread listening on the future will immediately try to reopen the endpoint.
197 control_fd_.reset();
198 read_fd_.reset();
199 write_fd_.reset();
200
Josh Gaoc51726c2018-10-11 16:33:05 -0700201 destruction_notifier_.set_value();
202 }
203
204 virtual bool Write(std::unique_ptr<apacket> packet) override final {
205 LOG(DEBUG) << "USB write: " << dump_header(&packet->msg);
206 Block header(sizeof(packet->msg));
207 memcpy(header.data(), &packet->msg, sizeof(packet->msg));
208
209 std::lock_guard<std::mutex> lock(write_mutex_);
210 write_requests_.push_back(CreateWriteBlock(std::move(header), next_write_id_++));
211 if (!packet->payload.empty()) {
Josh Gao86b33be2019-02-26 17:53:52 -0800212 // The kernel attempts to allocate a contiguous block of memory for each write,
213 // which can fail if the write is large and the kernel heap is fragmented.
214 // Split large writes into smaller chunks to avoid this.
215 std::shared_ptr<Block> payload = std::make_shared<Block>(std::move(packet->payload));
216 size_t offset = 0;
217 size_t len = payload->size();
218
219 while (len > 0) {
220 size_t write_size = std::min(kUsbWriteSize, len);
221 write_requests_.push_back(
222 CreateWriteBlock(payload, offset, write_size, next_write_id_++));
223 len -= write_size;
224 offset += write_size;
225 }
Josh Gaoc51726c2018-10-11 16:33:05 -0700226 }
227 SubmitWrites();
228 return true;
229 }
230
231 virtual void Start() override final { StartMonitor(); }
232
233 virtual void Stop() override final {
234 if (stopped_.exchange(true)) {
235 return;
236 }
237 stopped_ = true;
238 uint64_t notify = 1;
Josh Gaoc0b831b2019-02-13 15:27:28 -0800239 ssize_t rc = adb_write(worker_event_fd_.get(), &notify, sizeof(notify));
Josh Gaoc51726c2018-10-11 16:33:05 -0700240 if (rc < 0) {
Josh Gaoc0b831b2019-02-13 15:27:28 -0800241 PLOG(FATAL) << "failed to notify worker eventfd to stop UsbFfsConnection";
Josh Gaoc51726c2018-10-11 16:33:05 -0700242 }
243 CHECK_EQ(static_cast<size_t>(rc), sizeof(notify));
Josh Gaoc0b831b2019-02-13 15:27:28 -0800244
245 rc = adb_write(monitor_event_fd_.get(), &notify, sizeof(notify));
246 if (rc < 0) {
247 PLOG(FATAL) << "failed to notify monitor eventfd to stop UsbFfsConnection";
248 }
249
250 CHECK_EQ(static_cast<size_t>(rc), sizeof(notify));
Josh Gaoc51726c2018-10-11 16:33:05 -0700251 }
252
253 private:
254 void StartMonitor() {
255 // This is a bit of a mess.
256 // It's possible for io_submit to end up blocking, if we call it as the endpoint
257 // becomes disabled. Work around this by having a monitor thread to listen for functionfs
258 // lifecycle events. If we notice an error condition (either we've become disabled, or we
259 // were never enabled in the first place), we send interruption signals to the worker thread
260 // until it dies, and then report failure to the transport via HandleError, which will
261 // eventually result in the transport being destroyed, which will result in UsbFfsConnection
262 // being destroyed, which unblocks the open thread and restarts this entire process.
Josh Gaoc51726c2018-10-11 16:33:05 -0700263 static std::once_flag handler_once;
264 std::call_once(handler_once, []() { signal(kInterruptionSignal, [](int) {}); });
265
266 monitor_thread_ = std::thread([this]() {
267 adb_thread_setname("UsbFfs-monitor");
268
269 bool bound = false;
270 bool started = false;
271 bool running = true;
272 while (running) {
Josh Gaoc0b831b2019-02-13 15:27:28 -0800273 int timeout = -1;
Josh Gaoc51726c2018-10-11 16:33:05 -0700274 if (!bound || !started) {
Josh Gaoc0b831b2019-02-13 15:27:28 -0800275 timeout = 5000 /*ms*/;
276 }
277
278 adb_pollfd pfd[2] = {
279 { .fd = control_fd_.get(), .events = POLLIN, .revents = 0 },
280 { .fd = monitor_event_fd_.get(), .events = POLLIN, .revents = 0 },
281 };
282 int rc = TEMP_FAILURE_RETRY(adb_poll(pfd, 2, timeout));
283 if (rc == -1) {
284 PLOG(FATAL) << "poll on USB control fd failed";
285 } else if (rc == 0) {
286 // Something in the kernel presumably went wrong.
287 // Close our endpoints, wait for a bit, and then try again.
Josh Gaoe778b3a2019-02-28 13:29:32 -0800288 StopWorker();
Josh Gaoc0b831b2019-02-13 15:27:28 -0800289 aio_context_.reset();
290 read_fd_.reset();
291 write_fd_.reset();
292 control_fd_.reset();
293 std::this_thread::sleep_for(5s);
294 HandleError("didn't receive FUNCTIONFS_ENABLE, retrying");
295 return;
296 }
297
298 if (pfd[1].revents) {
299 // We were told to die.
300 break;
Josh Gaoc51726c2018-10-11 16:33:05 -0700301 }
302
303 struct usb_functionfs_event event;
304 if (TEMP_FAILURE_RETRY(adb_read(control_fd_.get(), &event, sizeof(event))) !=
305 sizeof(event)) {
306 PLOG(FATAL) << "failed to read functionfs event";
307 }
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 Gaoe778b3a2019-02-28 13:29:32 -0800314 CHECK(!bound) << "received FUNCTIONFS_BIND while already bound?";
Josh Gaoc51726c2018-10-11 16:33:05 -0700315 bound = true;
316 break;
317
318 case FUNCTIONFS_ENABLE:
319 CHECK(!started) << "received FUNCTIONFS_ENABLE while already running?";
320 started = true;
321 StartWorker();
322 break;
323
324 case FUNCTIONFS_DISABLE:
325 running = false;
326 break;
327 }
328 }
329
Josh Gaoe778b3a2019-02-28 13:29:32 -0800330 StopWorker();
Josh Gaoc51726c2018-10-11 16:33:05 -0700331 aio_context_.reset();
332 read_fd_.reset();
333 write_fd_.reset();
334 });
335 }
336
337 void StartWorker() {
338 worker_thread_ = std::thread([this]() {
339 adb_thread_setname("UsbFfs-worker");
340 for (size_t i = 0; i < kUsbReadQueueDepth; ++i) {
341 read_requests_[i] = CreateReadBlock(next_read_id_++);
Josh Gaoc0b831b2019-02-13 15:27:28 -0800342 if (!SubmitRead(&read_requests_[i])) {
343 return;
344 }
Josh Gaoc51726c2018-10-11 16:33:05 -0700345 }
346
347 while (!stopped_) {
348 uint64_t dummy;
Josh Gaoc0b831b2019-02-13 15:27:28 -0800349 ssize_t rc = adb_read(worker_event_fd_.get(), &dummy, sizeof(dummy));
Josh Gaoc51726c2018-10-11 16:33:05 -0700350 if (rc == -1) {
351 PLOG(FATAL) << "failed to read from eventfd";
352 } else if (rc == 0) {
353 LOG(FATAL) << "hit EOF on eventfd";
354 }
355
356 WaitForEvents();
357 }
358 });
359 }
360
Josh Gaoe778b3a2019-02-28 13:29:32 -0800361 void StopWorker() {
362 pthread_t worker_thread_handle = worker_thread_.native_handle();
363 while (true) {
364 int rc = pthread_kill(worker_thread_handle, kInterruptionSignal);
365 if (rc != 0) {
366 LOG(ERROR) << "failed to send interruption signal to worker: " << strerror(rc);
367 break;
368 }
369
370 std::this_thread::sleep_for(100ms);
371
372 rc = pthread_kill(worker_thread_handle, 0);
373 if (rc == 0) {
374 continue;
375 } else if (rc == ESRCH) {
376 break;
377 } else {
378 LOG(ERROR) << "failed to send interruption signal to worker: " << strerror(rc);
379 }
380 }
381
382 worker_thread_.join();
383 }
384
Josh Gaoc51726c2018-10-11 16:33:05 -0700385 void PrepareReadBlock(IoBlock* block, uint64_t id) {
386 block->pending = false;
Josh Gao86b33be2019-02-26 17:53:52 -0800387 block->payload = std::make_shared<Block>(kUsbReadSize);
Josh Gaoc51726c2018-10-11 16:33:05 -0700388 block->control.aio_data = static_cast<uint64_t>(TransferId::read(id));
Josh Gao86b33be2019-02-26 17:53:52 -0800389 block->control.aio_buf = reinterpret_cast<uintptr_t>(block->payload->data());
390 block->control.aio_nbytes = block->payload->size();
Josh Gaoc51726c2018-10-11 16:33:05 -0700391 }
392
393 IoBlock CreateReadBlock(uint64_t id) {
394 IoBlock block;
395 PrepareReadBlock(&block, id);
396 block.control.aio_rw_flags = 0;
397 block.control.aio_lio_opcode = IOCB_CMD_PREAD;
398 block.control.aio_reqprio = 0;
399 block.control.aio_fildes = read_fd_.get();
400 block.control.aio_offset = 0;
401 block.control.aio_flags = IOCB_FLAG_RESFD;
Josh Gaoc0b831b2019-02-13 15:27:28 -0800402 block.control.aio_resfd = worker_event_fd_.get();
Josh Gaoc51726c2018-10-11 16:33:05 -0700403 return block;
404 }
405
406 void WaitForEvents() {
407 static constexpr size_t kMaxEvents = kUsbReadQueueDepth + kUsbWriteQueueDepth;
408 struct io_event events[kMaxEvents];
409 struct timespec timeout = {.tv_sec = 0, .tv_nsec = 0};
410 int rc = io_getevents(aio_context_.get(), 0, kMaxEvents, events, &timeout);
411 if (rc == -1) {
412 HandleError(StringPrintf("io_getevents failed while reading: %s", strerror(errno)));
413 return;
414 }
415
416 for (int event_idx = 0; event_idx < rc; ++event_idx) {
417 auto& event = events[event_idx];
418 TransferId id = TransferId::from_value(event.data);
419
420 if (event.res < 0) {
421 std::string error =
422 StringPrintf("%s %" PRIu64 " failed with error %s",
423 id.direction == TransferDirection::READ ? "read" : "write",
424 id.id, strerror(-event.res));
425 HandleError(error);
426 return;
427 }
428
429 if (id.direction == TransferDirection::READ) {
430 HandleRead(id, event.res);
431 } else {
432 HandleWrite(id);
433 }
434 }
435 }
436
437 void HandleRead(TransferId id, int64_t size) {
438 uint64_t read_idx = id.id % kUsbReadQueueDepth;
439 IoBlock* block = &read_requests_[read_idx];
440 block->pending = false;
Josh Gao86b33be2019-02-26 17:53:52 -0800441 block->payload->resize(size);
Josh Gaoc51726c2018-10-11 16:33:05 -0700442
443 // Notification for completed reads can be received out of order.
444 if (block->id().id != needed_read_id_) {
445 LOG(VERBOSE) << "read " << block->id().id << " completed while waiting for "
446 << needed_read_id_;
447 return;
448 }
449
450 for (uint64_t id = needed_read_id_;; ++id) {
451 size_t read_idx = id % kUsbReadQueueDepth;
452 IoBlock* current_block = &read_requests_[read_idx];
453 if (current_block->pending) {
454 break;
455 }
456 ProcessRead(current_block);
457 ++needed_read_id_;
458 }
459 }
460
461 void ProcessRead(IoBlock* block) {
Josh Gao86b33be2019-02-26 17:53:52 -0800462 if (!block->payload->empty()) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700463 if (!incoming_header_.has_value()) {
Josh Gao86b33be2019-02-26 17:53:52 -0800464 CHECK_EQ(sizeof(amessage), block->payload->size());
Josh Gaoc51726c2018-10-11 16:33:05 -0700465 amessage msg;
Josh Gao86b33be2019-02-26 17:53:52 -0800466 memcpy(&msg, block->payload->data(), sizeof(amessage));
Josh Gaoc51726c2018-10-11 16:33:05 -0700467 LOG(DEBUG) << "USB read:" << dump_header(&msg);
468 incoming_header_ = msg;
469 } else {
470 size_t bytes_left = incoming_header_->data_length - incoming_payload_.size();
Josh Gao86b33be2019-02-26 17:53:52 -0800471 Block payload = std::move(*block->payload);
Josh Gaoc51726c2018-10-11 16:33:05 -0700472 CHECK_LE(payload.size(), bytes_left);
473 incoming_payload_.append(std::make_unique<Block>(std::move(payload)));
474 }
475
476 if (incoming_header_->data_length == incoming_payload_.size()) {
477 auto packet = std::make_unique<apacket>();
478 packet->msg = *incoming_header_;
479
480 // TODO: Make apacket contain an IOVector so we don't have to coalesce.
481 packet->payload = incoming_payload_.coalesce();
482 read_callback_(this, std::move(packet));
483
484 incoming_header_.reset();
485 incoming_payload_.clear();
486 }
487 }
488
489 PrepareReadBlock(block, block->id().id + kUsbReadQueueDepth);
490 SubmitRead(block);
491 }
492
Josh Gaoc0b831b2019-02-13 15:27:28 -0800493 bool SubmitRead(IoBlock* block) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700494 block->pending = true;
495 struct iocb* iocb = &block->control;
496 if (io_submit(aio_context_.get(), 1, &iocb) != 1) {
Josh Gaoc0b831b2019-02-13 15:27:28 -0800497 if (errno == EINVAL && !gFfsAioSupported.has_value()) {
498 HandleError("failed to submit first read, AIO on FFS not supported");
499 gFfsAioSupported = false;
500 return false;
501 }
502
Josh Gaoc51726c2018-10-11 16:33:05 -0700503 HandleError(StringPrintf("failed to submit read: %s", strerror(errno)));
Josh Gaoc0b831b2019-02-13 15:27:28 -0800504 return false;
Josh Gaoc51726c2018-10-11 16:33:05 -0700505 }
Josh Gaoc0b831b2019-02-13 15:27:28 -0800506
507 gFfsAioSupported = true;
508 return true;
Josh Gaoc51726c2018-10-11 16:33:05 -0700509 }
510
511 void HandleWrite(TransferId id) {
512 std::lock_guard<std::mutex> lock(write_mutex_);
513 auto it =
514 std::find_if(write_requests_.begin(), write_requests_.end(), [id](const auto& req) {
515 return static_cast<uint64_t>(req->id()) == static_cast<uint64_t>(id);
516 });
517 CHECK(it != write_requests_.end());
518
519 write_requests_.erase(it);
520 size_t outstanding_writes = --writes_submitted_;
521 LOG(DEBUG) << "USB write: reaped, down to " << outstanding_writes;
522
523 SubmitWrites();
524 }
525
Josh Gao86b33be2019-02-26 17:53:52 -0800526 std::unique_ptr<IoBlock> CreateWriteBlock(std::shared_ptr<Block> payload, size_t offset,
527 size_t len, uint64_t id) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700528 auto block = std::make_unique<IoBlock>();
529 block->payload = std::move(payload);
530 block->control.aio_data = static_cast<uint64_t>(TransferId::write(id));
531 block->control.aio_rw_flags = 0;
532 block->control.aio_lio_opcode = IOCB_CMD_PWRITE;
533 block->control.aio_reqprio = 0;
534 block->control.aio_fildes = write_fd_.get();
Josh Gao86b33be2019-02-26 17:53:52 -0800535 block->control.aio_buf = reinterpret_cast<uintptr_t>(block->payload->data() + offset);
536 block->control.aio_nbytes = len;
Josh Gaoc51726c2018-10-11 16:33:05 -0700537 block->control.aio_offset = 0;
538 block->control.aio_flags = IOCB_FLAG_RESFD;
Josh Gaoc0b831b2019-02-13 15:27:28 -0800539 block->control.aio_resfd = worker_event_fd_.get();
Josh Gaoc51726c2018-10-11 16:33:05 -0700540 return block;
541 }
542
Josh Gao86b33be2019-02-26 17:53:52 -0800543 std::unique_ptr<IoBlock> CreateWriteBlock(Block payload, uint64_t id) {
544 std::shared_ptr<Block> block = std::make_shared<Block>(std::move(payload));
545 size_t len = block->size();
546 return CreateWriteBlock(std::move(block), 0, len, id);
547 }
548
Josh Gaoc51726c2018-10-11 16:33:05 -0700549 void SubmitWrites() REQUIRES(write_mutex_) {
550 if (writes_submitted_ == kUsbWriteQueueDepth) {
551 return;
552 }
553
554 ssize_t writes_to_submit = std::min(kUsbWriteQueueDepth - writes_submitted_,
555 write_requests_.size() - writes_submitted_);
556 CHECK_GE(writes_to_submit, 0);
557 if (writes_to_submit == 0) {
558 return;
559 }
560
561 struct iocb* iocbs[kUsbWriteQueueDepth];
562 for (int i = 0; i < writes_to_submit; ++i) {
563 CHECK(!write_requests_[writes_submitted_ + i]->pending);
564 write_requests_[writes_submitted_ + i]->pending = true;
565 iocbs[i] = &write_requests_[writes_submitted_ + i]->control;
566 LOG(VERBOSE) << "submitting write_request " << static_cast<void*>(iocbs[i]);
567 }
568
569 int rc = io_submit(aio_context_.get(), writes_to_submit, iocbs);
570 if (rc == -1) {
571 HandleError(StringPrintf("failed to submit write requests: %s", strerror(errno)));
572 return;
573 } else if (rc != writes_to_submit) {
574 LOG(FATAL) << "failed to submit all writes: wanted to submit " << writes_to_submit
575 << ", actually submitted " << rc;
576 }
577
578 writes_submitted_ += rc;
579 }
580
581 void HandleError(const std::string& error) {
582 std::call_once(error_flag_, [&]() {
583 error_callback_(this, error);
584 if (!stopped_) {
585 Stop();
586 }
587 });
588 }
589
590 std::thread monitor_thread_;
591 std::thread worker_thread_;
592
593 std::atomic<bool> stopped_;
594 std::promise<void> destruction_notifier_;
595 std::once_flag error_flag_;
596
Josh Gaoc0b831b2019-02-13 15:27:28 -0800597 unique_fd worker_event_fd_;
598 unique_fd monitor_event_fd_;
Josh Gaoc51726c2018-10-11 16:33:05 -0700599
600 ScopedAioContext aio_context_;
601 unique_fd control_fd_;
602 unique_fd read_fd_;
603 unique_fd write_fd_;
604
605 std::optional<amessage> incoming_header_;
606 IOVector incoming_payload_;
607
608 std::array<IoBlock, kUsbReadQueueDepth> read_requests_;
609 IOVector read_data_;
610
611 // ID of the next request that we're going to send out.
612 size_t next_read_id_ = 0;
613
614 // ID of the next packet we're waiting for.
615 size_t needed_read_id_ = 0;
616
617 std::mutex write_mutex_;
618 std::deque<std::unique_ptr<IoBlock>> write_requests_ GUARDED_BY(write_mutex_);
619 size_t next_write_id_ GUARDED_BY(write_mutex_) = 0;
620 size_t writes_submitted_ GUARDED_BY(write_mutex_) = 0;
Josh Gaoe778b3a2019-02-28 13:29:32 -0800621
622 static constexpr int kInterruptionSignal = SIGUSR1;
Josh Gaoc51726c2018-10-11 16:33:05 -0700623};
624
Josh Gaoc0b831b2019-02-13 15:27:28 -0800625void usb_init_legacy();
626
Josh Gaoc51726c2018-10-11 16:33:05 -0700627static void usb_ffs_open_thread() {
628 adb_thread_setname("usb ffs open");
629
630 while (true) {
Josh Gaoc0b831b2019-02-13 15:27:28 -0800631 if (gFfsAioSupported.has_value() && !gFfsAioSupported.value()) {
632 LOG(INFO) << "failed to use nonblocking ffs, falling back to legacy";
633 return usb_init_legacy();
634 }
635
Josh Gaoc51726c2018-10-11 16:33:05 -0700636 unique_fd control;
637 unique_fd bulk_out;
638 unique_fd bulk_in;
639 if (!open_functionfs(&control, &bulk_out, &bulk_in)) {
640 std::this_thread::sleep_for(1s);
641 continue;
642 }
643
644 atransport* transport = new atransport();
645 transport->serial = "UsbFfs";
646 std::promise<void> destruction_notifier;
647 std::future<void> future = destruction_notifier.get_future();
648 transport->SetConnection(std::make_unique<UsbFfsConnection>(
649 std::move(control), std::move(bulk_out), std::move(bulk_in),
650 std::move(destruction_notifier)));
651 register_transport(transport);
652 future.wait();
653 }
654}
655
Josh Gaoc51726c2018-10-11 16:33:05 -0700656void usb_init() {
Josh Gao0d780392019-02-26 22:10:33 +0000657 if (!android::base::GetBoolProperty("persist.adb.nonblocking_ffs", false)) {
Josh Gao12f32842019-02-04 13:18:54 -0800658 usb_init_legacy();
Josh Gao0d780392019-02-26 22:10:33 +0000659 } else {
660 std::thread(usb_ffs_open_thread).detach();
Josh Gaoc51726c2018-10-11 16:33:05 -0700661 }
662}