blob: 14cdb69613286a43e5cea0fac594a8909d6ecb14 [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 Gao5841a962019-02-28 15:44:05 -080060static constexpr size_t kUsbReadQueueDepth = 32;
61static constexpr size_t kUsbReadSize = 8 * PAGE_SIZE;
Josh Gaoc51726c2018-10-11 16:33:05 -070062
Josh Gao5841a962019-02-28 15:44:05 -080063static constexpr size_t kUsbWriteQueueDepth = 32;
64static constexpr size_t kUsbWriteSize = 8 * 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 {
Josh Gaob0195742019-03-18 14:11:28 -0700118 bool pending = false;
Josh Gaoc51726c2018-10-11 16:33:05 -0700119 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)
Josh Gao19dc2962019-03-26 18:47:45 -0700171 : worker_started_(false),
172 stopped_(false),
Josh Gaoc51726c2018-10-11 16:33:05 -0700173 destruction_notifier_(std::move(destruction_notifier)),
174 control_fd_(std::move(control)),
175 read_fd_(std::move(read)),
176 write_fd_(std::move(write)) {
177 LOG(INFO) << "UsbFfsConnection constructed";
Josh Gaoc0b831b2019-02-13 15:27:28 -0800178 worker_event_fd_.reset(eventfd(0, EFD_CLOEXEC));
179 if (worker_event_fd_ == -1) {
180 PLOG(FATAL) << "failed to create eventfd";
181 }
182
183 monitor_event_fd_.reset(eventfd(0, EFD_CLOEXEC));
184 if (monitor_event_fd_ == -1) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700185 PLOG(FATAL) << "failed to create eventfd";
186 }
187
188 aio_context_ = ScopedAioContext::Create(kUsbReadQueueDepth + kUsbWriteQueueDepth);
189 }
190
191 ~UsbFfsConnection() {
192 LOG(INFO) << "UsbFfsConnection being destroyed";
193 Stop();
194 monitor_thread_.join();
Josh Gaoc0b831b2019-02-13 15:27:28 -0800195
196 // We need to explicitly close our file descriptors before we notify our destruction,
197 // because the thread listening on the future will immediately try to reopen the endpoint.
Josh Gao19dc2962019-03-26 18:47:45 -0700198 aio_context_.reset();
Josh Gaoc0b831b2019-02-13 15:27:28 -0800199 control_fd_.reset();
200 read_fd_.reset();
201 write_fd_.reset();
202
Josh Gaoc51726c2018-10-11 16:33:05 -0700203 destruction_notifier_.set_value();
204 }
205
206 virtual bool Write(std::unique_ptr<apacket> packet) override final {
207 LOG(DEBUG) << "USB write: " << dump_header(&packet->msg);
208 Block header(sizeof(packet->msg));
209 memcpy(header.data(), &packet->msg, sizeof(packet->msg));
210
211 std::lock_guard<std::mutex> lock(write_mutex_);
212 write_requests_.push_back(CreateWriteBlock(std::move(header), next_write_id_++));
213 if (!packet->payload.empty()) {
Josh Gao86b33be2019-02-26 17:53:52 -0800214 // The kernel attempts to allocate a contiguous block of memory for each write,
215 // which can fail if the write is large and the kernel heap is fragmented.
216 // Split large writes into smaller chunks to avoid this.
217 std::shared_ptr<Block> payload = std::make_shared<Block>(std::move(packet->payload));
218 size_t offset = 0;
219 size_t len = payload->size();
220
221 while (len > 0) {
222 size_t write_size = std::min(kUsbWriteSize, len);
223 write_requests_.push_back(
224 CreateWriteBlock(payload, offset, write_size, next_write_id_++));
225 len -= write_size;
226 offset += write_size;
227 }
Josh Gaoc51726c2018-10-11 16:33:05 -0700228 }
229 SubmitWrites();
230 return true;
231 }
232
233 virtual void Start() override final { StartMonitor(); }
234
235 virtual void Stop() override final {
236 if (stopped_.exchange(true)) {
237 return;
238 }
239 stopped_ = true;
240 uint64_t notify = 1;
Josh Gaoc0b831b2019-02-13 15:27:28 -0800241 ssize_t rc = adb_write(worker_event_fd_.get(), &notify, sizeof(notify));
Josh Gaoc51726c2018-10-11 16:33:05 -0700242 if (rc < 0) {
Josh Gaoc0b831b2019-02-13 15:27:28 -0800243 PLOG(FATAL) << "failed to notify worker eventfd to stop UsbFfsConnection";
Josh Gaoc51726c2018-10-11 16:33:05 -0700244 }
245 CHECK_EQ(static_cast<size_t>(rc), sizeof(notify));
Josh Gaoc0b831b2019-02-13 15:27:28 -0800246
247 rc = adb_write(monitor_event_fd_.get(), &notify, sizeof(notify));
248 if (rc < 0) {
249 PLOG(FATAL) << "failed to notify monitor eventfd to stop UsbFfsConnection";
250 }
251
252 CHECK_EQ(static_cast<size_t>(rc), sizeof(notify));
Josh Gaoc51726c2018-10-11 16:33:05 -0700253 }
254
255 private:
256 void StartMonitor() {
257 // This is a bit of a mess.
258 // It's possible for io_submit to end up blocking, if we call it as the endpoint
259 // becomes disabled. Work around this by having a monitor thread to listen for functionfs
260 // lifecycle events. If we notice an error condition (either we've become disabled, or we
261 // were never enabled in the first place), we send interruption signals to the worker thread
262 // until it dies, and then report failure to the transport via HandleError, which will
263 // eventually result in the transport being destroyed, which will result in UsbFfsConnection
264 // being destroyed, which unblocks the open thread and restarts this entire process.
Josh Gaoc51726c2018-10-11 16:33:05 -0700265 static std::once_flag handler_once;
266 std::call_once(handler_once, []() { signal(kInterruptionSignal, [](int) {}); });
267
268 monitor_thread_ = std::thread([this]() {
269 adb_thread_setname("UsbFfs-monitor");
270
271 bool bound = false;
Josh Gao6933d542019-03-26 13:21:42 -0700272 bool enabled = false;
Josh Gaoc51726c2018-10-11 16:33:05 -0700273 bool running = true;
274 while (running) {
Josh Gaoc0b831b2019-02-13 15:27:28 -0800275 adb_pollfd pfd[2] = {
276 { .fd = control_fd_.get(), .events = POLLIN, .revents = 0 },
277 { .fd = monitor_event_fd_.get(), .events = POLLIN, .revents = 0 },
278 };
Josh Gao19dc2962019-03-26 18:47:45 -0700279
280 // If we don't see our first bind within a second, try again.
281 int timeout_ms = bound ? -1 : 1000;
282
283 int rc = TEMP_FAILURE_RETRY(adb_poll(pfd, 2, timeout_ms));
Josh Gaoc0b831b2019-02-13 15:27:28 -0800284 if (rc == -1) {
285 PLOG(FATAL) << "poll on USB control fd failed";
286 } else if (rc == 0) {
Josh Gao19dc2962019-03-26 18:47:45 -0700287 LOG(WARNING) << "timed out while waiting for FUNCTIONFS_BIND, trying again";
288 break;
Josh Gaoc0b831b2019-02-13 15:27:28 -0800289 }
290
291 if (pfd[1].revents) {
292 // We were told to die.
293 break;
Josh Gaoc51726c2018-10-11 16:33:05 -0700294 }
295
296 struct usb_functionfs_event event;
297 if (TEMP_FAILURE_RETRY(adb_read(control_fd_.get(), &event, sizeof(event))) !=
298 sizeof(event)) {
299 PLOG(FATAL) << "failed to read functionfs event";
300 }
301
302 LOG(INFO) << "USB event: "
303 << to_string(static_cast<usb_functionfs_event_type>(event.type));
304
305 switch (event.type) {
306 case FUNCTIONFS_BIND:
Josh Gaoe778b3a2019-02-28 13:29:32 -0800307 CHECK(!bound) << "received FUNCTIONFS_BIND while already bound?";
Josh Gao6933d542019-03-26 13:21:42 -0700308 CHECK(!enabled) << "received FUNCTIONFS_BIND while already enabled?";
Josh Gaoc51726c2018-10-11 16:33:05 -0700309 bound = true;
Josh Gao6933d542019-03-26 13:21:42 -0700310
Josh Gaoc51726c2018-10-11 16:33:05 -0700311 break;
312
313 case FUNCTIONFS_ENABLE:
Josh Gao6933d542019-03-26 13:21:42 -0700314 CHECK(bound) << "received FUNCTIONFS_ENABLE while not bound?";
315 CHECK(!enabled) << "received FUNCTIONFS_ENABLE while already enabled?";
316 enabled = true;
317
Josh Gaoc51726c2018-10-11 16:33:05 -0700318 StartWorker();
319 break;
320
321 case FUNCTIONFS_DISABLE:
Josh Gao6933d542019-03-26 13:21:42 -0700322 CHECK(bound) << "received FUNCTIONFS_DISABLE while not bound?";
323 CHECK(enabled) << "received FUNCTIONFS_DISABLE while not enabled?";
324 enabled = false;
325
326 running = false;
327 break;
328
329 case FUNCTIONFS_UNBIND:
330 CHECK(!enabled) << "received FUNCTIONFS_UNBIND while still enabled?";
331 CHECK(bound) << "received FUNCTIONFS_UNBIND when not bound?";
332 bound = false;
333
Josh Gaoc51726c2018-10-11 16:33:05 -0700334 running = false;
335 break;
336 }
337 }
338
Josh Gaoe778b3a2019-02-28 13:29:32 -0800339 StopWorker();
Josh Gao19dc2962019-03-26 18:47:45 -0700340 HandleError("monitor thread finished");
Josh Gaoc51726c2018-10-11 16:33:05 -0700341 });
342 }
343
344 void StartWorker() {
Josh Gao19dc2962019-03-26 18:47:45 -0700345 CHECK(!worker_started_);
346 worker_started_ = true;
Josh Gaoc51726c2018-10-11 16:33:05 -0700347 worker_thread_ = std::thread([this]() {
348 adb_thread_setname("UsbFfs-worker");
349 for (size_t i = 0; i < kUsbReadQueueDepth; ++i) {
350 read_requests_[i] = CreateReadBlock(next_read_id_++);
Josh Gaoc0b831b2019-02-13 15:27:28 -0800351 if (!SubmitRead(&read_requests_[i])) {
352 return;
353 }
Josh Gaoc51726c2018-10-11 16:33:05 -0700354 }
355
356 while (!stopped_) {
357 uint64_t dummy;
Josh Gaoc0b831b2019-02-13 15:27:28 -0800358 ssize_t rc = adb_read(worker_event_fd_.get(), &dummy, sizeof(dummy));
Josh Gaoc51726c2018-10-11 16:33:05 -0700359 if (rc == -1) {
360 PLOG(FATAL) << "failed to read from eventfd";
361 } else if (rc == 0) {
362 LOG(FATAL) << "hit EOF on eventfd";
363 }
364
Josh Gao6933d542019-03-26 13:21:42 -0700365 ReadEvents();
Josh Gaoc51726c2018-10-11 16:33:05 -0700366 }
367 });
368 }
369
Josh Gaoe778b3a2019-02-28 13:29:32 -0800370 void StopWorker() {
Josh Gao19dc2962019-03-26 18:47:45 -0700371 if (!worker_started_) {
372 return;
373 }
374
Josh Gaoe778b3a2019-02-28 13:29:32 -0800375 pthread_t worker_thread_handle = worker_thread_.native_handle();
376 while (true) {
377 int rc = pthread_kill(worker_thread_handle, kInterruptionSignal);
378 if (rc != 0) {
379 LOG(ERROR) << "failed to send interruption signal to worker: " << strerror(rc);
380 break;
381 }
382
383 std::this_thread::sleep_for(100ms);
384
385 rc = pthread_kill(worker_thread_handle, 0);
386 if (rc == 0) {
387 continue;
388 } else if (rc == ESRCH) {
389 break;
390 } else {
391 LOG(ERROR) << "failed to send interruption signal to worker: " << strerror(rc);
392 }
393 }
394
395 worker_thread_.join();
396 }
397
Josh Gaoc51726c2018-10-11 16:33:05 -0700398 void PrepareReadBlock(IoBlock* block, uint64_t id) {
399 block->pending = false;
Josh Gao86b33be2019-02-26 17:53:52 -0800400 block->payload = std::make_shared<Block>(kUsbReadSize);
Josh Gaoc51726c2018-10-11 16:33:05 -0700401 block->control.aio_data = static_cast<uint64_t>(TransferId::read(id));
Josh Gao86b33be2019-02-26 17:53:52 -0800402 block->control.aio_buf = reinterpret_cast<uintptr_t>(block->payload->data());
403 block->control.aio_nbytes = block->payload->size();
Josh Gaoc51726c2018-10-11 16:33:05 -0700404 }
405
406 IoBlock CreateReadBlock(uint64_t id) {
407 IoBlock block;
408 PrepareReadBlock(&block, id);
409 block.control.aio_rw_flags = 0;
410 block.control.aio_lio_opcode = IOCB_CMD_PREAD;
411 block.control.aio_reqprio = 0;
412 block.control.aio_fildes = read_fd_.get();
413 block.control.aio_offset = 0;
414 block.control.aio_flags = IOCB_FLAG_RESFD;
Josh Gaoc0b831b2019-02-13 15:27:28 -0800415 block.control.aio_resfd = worker_event_fd_.get();
Josh Gaoc51726c2018-10-11 16:33:05 -0700416 return block;
417 }
418
Josh Gao6933d542019-03-26 13:21:42 -0700419 void ReadEvents() {
Josh Gaoc51726c2018-10-11 16:33:05 -0700420 static constexpr size_t kMaxEvents = kUsbReadQueueDepth + kUsbWriteQueueDepth;
421 struct io_event events[kMaxEvents];
422 struct timespec timeout = {.tv_sec = 0, .tv_nsec = 0};
423 int rc = io_getevents(aio_context_.get(), 0, kMaxEvents, events, &timeout);
424 if (rc == -1) {
425 HandleError(StringPrintf("io_getevents failed while reading: %s", strerror(errno)));
426 return;
427 }
428
429 for (int event_idx = 0; event_idx < rc; ++event_idx) {
430 auto& event = events[event_idx];
431 TransferId id = TransferId::from_value(event.data);
432
433 if (event.res < 0) {
434 std::string error =
435 StringPrintf("%s %" PRIu64 " failed with error %s",
436 id.direction == TransferDirection::READ ? "read" : "write",
437 id.id, strerror(-event.res));
438 HandleError(error);
439 return;
440 }
441
442 if (id.direction == TransferDirection::READ) {
443 HandleRead(id, event.res);
444 } else {
445 HandleWrite(id);
446 }
447 }
448 }
449
450 void HandleRead(TransferId id, int64_t size) {
451 uint64_t read_idx = id.id % kUsbReadQueueDepth;
452 IoBlock* block = &read_requests_[read_idx];
453 block->pending = false;
Josh Gao86b33be2019-02-26 17:53:52 -0800454 block->payload->resize(size);
Josh Gaoc51726c2018-10-11 16:33:05 -0700455
456 // Notification for completed reads can be received out of order.
457 if (block->id().id != needed_read_id_) {
458 LOG(VERBOSE) << "read " << block->id().id << " completed while waiting for "
459 << needed_read_id_;
460 return;
461 }
462
463 for (uint64_t id = needed_read_id_;; ++id) {
464 size_t read_idx = id % kUsbReadQueueDepth;
465 IoBlock* current_block = &read_requests_[read_idx];
466 if (current_block->pending) {
467 break;
468 }
469 ProcessRead(current_block);
470 ++needed_read_id_;
471 }
472 }
473
474 void ProcessRead(IoBlock* block) {
Josh Gao86b33be2019-02-26 17:53:52 -0800475 if (!block->payload->empty()) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700476 if (!incoming_header_.has_value()) {
Josh Gao86b33be2019-02-26 17:53:52 -0800477 CHECK_EQ(sizeof(amessage), block->payload->size());
Josh Gaoc51726c2018-10-11 16:33:05 -0700478 amessage msg;
Josh Gao86b33be2019-02-26 17:53:52 -0800479 memcpy(&msg, block->payload->data(), sizeof(amessage));
Josh Gaoc51726c2018-10-11 16:33:05 -0700480 LOG(DEBUG) << "USB read:" << dump_header(&msg);
481 incoming_header_ = msg;
482 } else {
483 size_t bytes_left = incoming_header_->data_length - incoming_payload_.size();
Josh Gao86b33be2019-02-26 17:53:52 -0800484 Block payload = std::move(*block->payload);
Josh Gaoc51726c2018-10-11 16:33:05 -0700485 CHECK_LE(payload.size(), bytes_left);
486 incoming_payload_.append(std::make_unique<Block>(std::move(payload)));
487 }
488
489 if (incoming_header_->data_length == incoming_payload_.size()) {
490 auto packet = std::make_unique<apacket>();
491 packet->msg = *incoming_header_;
492
493 // TODO: Make apacket contain an IOVector so we don't have to coalesce.
494 packet->payload = incoming_payload_.coalesce();
495 read_callback_(this, std::move(packet));
496
497 incoming_header_.reset();
498 incoming_payload_.clear();
499 }
500 }
501
502 PrepareReadBlock(block, block->id().id + kUsbReadQueueDepth);
503 SubmitRead(block);
504 }
505
Josh Gaoc0b831b2019-02-13 15:27:28 -0800506 bool SubmitRead(IoBlock* block) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700507 block->pending = true;
508 struct iocb* iocb = &block->control;
509 if (io_submit(aio_context_.get(), 1, &iocb) != 1) {
Josh Gaoc0b831b2019-02-13 15:27:28 -0800510 if (errno == EINVAL && !gFfsAioSupported.has_value()) {
511 HandleError("failed to submit first read, AIO on FFS not supported");
512 gFfsAioSupported = false;
513 return false;
514 }
515
Josh Gaoc51726c2018-10-11 16:33:05 -0700516 HandleError(StringPrintf("failed to submit read: %s", strerror(errno)));
Josh Gaoc0b831b2019-02-13 15:27:28 -0800517 return false;
Josh Gaoc51726c2018-10-11 16:33:05 -0700518 }
Josh Gaoc0b831b2019-02-13 15:27:28 -0800519
520 gFfsAioSupported = true;
521 return true;
Josh Gaoc51726c2018-10-11 16:33:05 -0700522 }
523
524 void HandleWrite(TransferId id) {
525 std::lock_guard<std::mutex> lock(write_mutex_);
526 auto it =
527 std::find_if(write_requests_.begin(), write_requests_.end(), [id](const auto& req) {
528 return static_cast<uint64_t>(req->id()) == static_cast<uint64_t>(id);
529 });
530 CHECK(it != write_requests_.end());
531
532 write_requests_.erase(it);
533 size_t outstanding_writes = --writes_submitted_;
534 LOG(DEBUG) << "USB write: reaped, down to " << outstanding_writes;
535
536 SubmitWrites();
537 }
538
Josh Gao86b33be2019-02-26 17:53:52 -0800539 std::unique_ptr<IoBlock> CreateWriteBlock(std::shared_ptr<Block> payload, size_t offset,
540 size_t len, uint64_t id) {
Josh Gaoc51726c2018-10-11 16:33:05 -0700541 auto block = std::make_unique<IoBlock>();
542 block->payload = std::move(payload);
543 block->control.aio_data = static_cast<uint64_t>(TransferId::write(id));
544 block->control.aio_rw_flags = 0;
545 block->control.aio_lio_opcode = IOCB_CMD_PWRITE;
546 block->control.aio_reqprio = 0;
547 block->control.aio_fildes = write_fd_.get();
Josh Gao86b33be2019-02-26 17:53:52 -0800548 block->control.aio_buf = reinterpret_cast<uintptr_t>(block->payload->data() + offset);
549 block->control.aio_nbytes = len;
Josh Gaoc51726c2018-10-11 16:33:05 -0700550 block->control.aio_offset = 0;
551 block->control.aio_flags = IOCB_FLAG_RESFD;
Josh Gaoc0b831b2019-02-13 15:27:28 -0800552 block->control.aio_resfd = worker_event_fd_.get();
Josh Gaoc51726c2018-10-11 16:33:05 -0700553 return block;
554 }
555
Josh Gao86b33be2019-02-26 17:53:52 -0800556 std::unique_ptr<IoBlock> CreateWriteBlock(Block payload, uint64_t id) {
557 std::shared_ptr<Block> block = std::make_shared<Block>(std::move(payload));
558 size_t len = block->size();
559 return CreateWriteBlock(std::move(block), 0, len, id);
560 }
561
Josh Gaoc51726c2018-10-11 16:33:05 -0700562 void SubmitWrites() REQUIRES(write_mutex_) {
563 if (writes_submitted_ == kUsbWriteQueueDepth) {
564 return;
565 }
566
567 ssize_t writes_to_submit = std::min(kUsbWriteQueueDepth - writes_submitted_,
568 write_requests_.size() - writes_submitted_);
569 CHECK_GE(writes_to_submit, 0);
570 if (writes_to_submit == 0) {
571 return;
572 }
573
574 struct iocb* iocbs[kUsbWriteQueueDepth];
575 for (int i = 0; i < writes_to_submit; ++i) {
576 CHECK(!write_requests_[writes_submitted_ + i]->pending);
577 write_requests_[writes_submitted_ + i]->pending = true;
578 iocbs[i] = &write_requests_[writes_submitted_ + i]->control;
579 LOG(VERBOSE) << "submitting write_request " << static_cast<void*>(iocbs[i]);
580 }
581
Josh Gao63b52ec2019-03-26 13:06:38 -0700582 writes_submitted_ += writes_to_submit;
583
Josh Gaoc51726c2018-10-11 16:33:05 -0700584 int rc = io_submit(aio_context_.get(), writes_to_submit, iocbs);
585 if (rc == -1) {
586 HandleError(StringPrintf("failed to submit write requests: %s", strerror(errno)));
587 return;
588 } else if (rc != writes_to_submit) {
589 LOG(FATAL) << "failed to submit all writes: wanted to submit " << writes_to_submit
590 << ", actually submitted " << rc;
591 }
Josh Gaoc51726c2018-10-11 16:33:05 -0700592 }
593
594 void HandleError(const std::string& error) {
595 std::call_once(error_flag_, [&]() {
596 error_callback_(this, error);
597 if (!stopped_) {
598 Stop();
599 }
600 });
601 }
602
603 std::thread monitor_thread_;
Josh Gao19dc2962019-03-26 18:47:45 -0700604
605 bool worker_started_;
Josh Gaoc51726c2018-10-11 16:33:05 -0700606 std::thread worker_thread_;
607
608 std::atomic<bool> stopped_;
609 std::promise<void> destruction_notifier_;
610 std::once_flag error_flag_;
611
Josh Gaoc0b831b2019-02-13 15:27:28 -0800612 unique_fd worker_event_fd_;
613 unique_fd monitor_event_fd_;
Josh Gaoc51726c2018-10-11 16:33:05 -0700614
615 ScopedAioContext aio_context_;
616 unique_fd control_fd_;
617 unique_fd read_fd_;
618 unique_fd write_fd_;
619
620 std::optional<amessage> incoming_header_;
621 IOVector incoming_payload_;
622
623 std::array<IoBlock, kUsbReadQueueDepth> read_requests_;
624 IOVector read_data_;
625
626 // ID of the next request that we're going to send out.
627 size_t next_read_id_ = 0;
628
629 // ID of the next packet we're waiting for.
630 size_t needed_read_id_ = 0;
631
632 std::mutex write_mutex_;
633 std::deque<std::unique_ptr<IoBlock>> write_requests_ GUARDED_BY(write_mutex_);
634 size_t next_write_id_ GUARDED_BY(write_mutex_) = 0;
635 size_t writes_submitted_ GUARDED_BY(write_mutex_) = 0;
Josh Gaoe778b3a2019-02-28 13:29:32 -0800636
637 static constexpr int kInterruptionSignal = SIGUSR1;
Josh Gaoc51726c2018-10-11 16:33:05 -0700638};
639
Josh Gaoc0b831b2019-02-13 15:27:28 -0800640void usb_init_legacy();
641
Josh Gaoc51726c2018-10-11 16:33:05 -0700642static void usb_ffs_open_thread() {
643 adb_thread_setname("usb ffs open");
644
645 while (true) {
Josh Gaoc0b831b2019-02-13 15:27:28 -0800646 if (gFfsAioSupported.has_value() && !gFfsAioSupported.value()) {
647 LOG(INFO) << "failed to use nonblocking ffs, falling back to legacy";
648 return usb_init_legacy();
649 }
650
Josh Gaoc51726c2018-10-11 16:33:05 -0700651 unique_fd control;
652 unique_fd bulk_out;
653 unique_fd bulk_in;
654 if (!open_functionfs(&control, &bulk_out, &bulk_in)) {
655 std::this_thread::sleep_for(1s);
656 continue;
657 }
658
659 atransport* transport = new atransport();
660 transport->serial = "UsbFfs";
661 std::promise<void> destruction_notifier;
662 std::future<void> future = destruction_notifier.get_future();
663 transport->SetConnection(std::make_unique<UsbFfsConnection>(
664 std::move(control), std::move(bulk_out), std::move(bulk_in),
665 std::move(destruction_notifier)));
666 register_transport(transport);
667 future.wait();
668 }
669}
670
Josh Gaoc51726c2018-10-11 16:33:05 -0700671void usb_init() {
Josh Gao8038e352019-03-18 16:33:18 -0700672 bool use_nonblocking = android::base::GetBoolProperty(
673 "persist.adb.nonblocking_ffs",
674 android::base::GetBoolProperty("ro.adb.nonblocking_ffs", true));
675
Josh Gao02e94a42019-02-28 07:26:20 +0000676 if (use_nonblocking) {
Josh Gao0d780392019-02-26 22:10:33 +0000677 std::thread(usb_ffs_open_thread).detach();
Josh Gao02e94a42019-02-28 07:26:20 +0000678 } else {
679 usb_init_legacy();
Josh Gaoc51726c2018-10-11 16:33:05 -0700680 }
681}