1 /* 2 * Copyright (C) 2007 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 <dirent.h> 22 #include <errno.h> 23 #include <linux/usb/ch9.h> 24 #include <linux/usb/functionfs.h> 25 #include <stdio.h> 26 #include <stdlib.h> 27 #include <string.h> 28 #include <sys/ioctl.h> 29 #include <sys/mman.h> 30 #include <sys/types.h> 31 #include <unistd.h> 32 33 #include <algorithm> 34 #include <atomic> 35 #include <chrono> 36 #include <condition_variable> 37 #include <mutex> 38 #include <thread> 39 40 #include <android-base/logging.h> 41 #include <android-base/properties.h> 42 43 #include "adb.h" 44 #include "daemon/usb.h" 45 #include "transport.h" 46 47 using namespace std::chrono_literals; 48 49 #define MAX_PACKET_SIZE_FS 64 50 #define MAX_PACKET_SIZE_HS 512 51 #define MAX_PACKET_SIZE_SS 1024 52 53 #define USB_FFS_BULK_SIZE 16384 54 55 // Number of buffers needed to fit MAX_PAYLOAD, with an extra for ZLPs. 56 #define USB_FFS_NUM_BUFS ((MAX_PAYLOAD / USB_FFS_BULK_SIZE) + 1) 57 58 #define cpu_to_le16(x) htole16(x) 59 #define cpu_to_le32(x) htole32(x) 60 61 static int dummy_fd = -1; 62 63 struct func_desc { 64 struct usb_interface_descriptor intf; 65 struct usb_endpoint_descriptor_no_audio source; 66 struct usb_endpoint_descriptor_no_audio sink; 67 } __attribute__((packed)); 68 69 struct ss_func_desc { 70 struct usb_interface_descriptor intf; 71 struct usb_endpoint_descriptor_no_audio source; 72 struct usb_ss_ep_comp_descriptor source_comp; 73 struct usb_endpoint_descriptor_no_audio sink; 74 struct usb_ss_ep_comp_descriptor sink_comp; 75 } __attribute__((packed)); 76 77 struct desc_v1 { 78 struct usb_functionfs_descs_head_v1 { 79 __le32 magic; 80 __le32 length; 81 __le32 fs_count; 82 __le32 hs_count; 83 } __attribute__((packed)) header; 84 struct func_desc fs_descs, hs_descs; 85 } __attribute__((packed)); 86 87 struct desc_v2 { 88 struct usb_functionfs_descs_head_v2 header; 89 // The rest of the structure depends on the flags in the header. 90 __le32 fs_count; 91 __le32 hs_count; 92 __le32 ss_count; 93 __le32 os_count; 94 struct func_desc fs_descs, hs_descs; 95 struct ss_func_desc ss_descs; 96 struct usb_os_desc_header os_header; 97 struct usb_ext_compat_desc os_desc; 98 } __attribute__((packed)); 99 100 static struct func_desc fs_descriptors = { 101 .intf = { 102 .bLength = sizeof(fs_descriptors.intf), 103 .bDescriptorType = USB_DT_INTERFACE, 104 .bInterfaceNumber = 0, 105 .bNumEndpoints = 2, 106 .bInterfaceClass = ADB_CLASS, 107 .bInterfaceSubClass = ADB_SUBCLASS, 108 .bInterfaceProtocol = ADB_PROTOCOL, 109 .iInterface = 1, /* first string from the provided table */ 110 }, 111 .source = { 112 .bLength = sizeof(fs_descriptors.source), 113 .bDescriptorType = USB_DT_ENDPOINT, 114 .bEndpointAddress = 1 | USB_DIR_OUT, 115 .bmAttributes = USB_ENDPOINT_XFER_BULK, 116 .wMaxPacketSize = MAX_PACKET_SIZE_FS, 117 }, 118 .sink = { 119 .bLength = sizeof(fs_descriptors.sink), 120 .bDescriptorType = USB_DT_ENDPOINT, 121 .bEndpointAddress = 2 | USB_DIR_IN, 122 .bmAttributes = USB_ENDPOINT_XFER_BULK, 123 .wMaxPacketSize = MAX_PACKET_SIZE_FS, 124 }, 125 }; 126 127 static struct func_desc hs_descriptors = { 128 .intf = { 129 .bLength = sizeof(hs_descriptors.intf), 130 .bDescriptorType = USB_DT_INTERFACE, 131 .bInterfaceNumber = 0, 132 .bNumEndpoints = 2, 133 .bInterfaceClass = ADB_CLASS, 134 .bInterfaceSubClass = ADB_SUBCLASS, 135 .bInterfaceProtocol = ADB_PROTOCOL, 136 .iInterface = 1, /* first string from the provided table */ 137 }, 138 .source = { 139 .bLength = sizeof(hs_descriptors.source), 140 .bDescriptorType = USB_DT_ENDPOINT, 141 .bEndpointAddress = 1 | USB_DIR_OUT, 142 .bmAttributes = USB_ENDPOINT_XFER_BULK, 143 .wMaxPacketSize = MAX_PACKET_SIZE_HS, 144 }, 145 .sink = { 146 .bLength = sizeof(hs_descriptors.sink), 147 .bDescriptorType = USB_DT_ENDPOINT, 148 .bEndpointAddress = 2 | USB_DIR_IN, 149 .bmAttributes = USB_ENDPOINT_XFER_BULK, 150 .wMaxPacketSize = MAX_PACKET_SIZE_HS, 151 }, 152 }; 153 154 static struct ss_func_desc ss_descriptors = { 155 .intf = { 156 .bLength = sizeof(ss_descriptors.intf), 157 .bDescriptorType = USB_DT_INTERFACE, 158 .bInterfaceNumber = 0, 159 .bNumEndpoints = 2, 160 .bInterfaceClass = ADB_CLASS, 161 .bInterfaceSubClass = ADB_SUBCLASS, 162 .bInterfaceProtocol = ADB_PROTOCOL, 163 .iInterface = 1, /* first string from the provided table */ 164 }, 165 .source = { 166 .bLength = sizeof(ss_descriptors.source), 167 .bDescriptorType = USB_DT_ENDPOINT, 168 .bEndpointAddress = 1 | USB_DIR_OUT, 169 .bmAttributes = USB_ENDPOINT_XFER_BULK, 170 .wMaxPacketSize = MAX_PACKET_SIZE_SS, 171 }, 172 .source_comp = { 173 .bLength = sizeof(ss_descriptors.source_comp), 174 .bDescriptorType = USB_DT_SS_ENDPOINT_COMP, 175 .bMaxBurst = 4, 176 }, 177 .sink = { 178 .bLength = sizeof(ss_descriptors.sink), 179 .bDescriptorType = USB_DT_ENDPOINT, 180 .bEndpointAddress = 2 | USB_DIR_IN, 181 .bmAttributes = USB_ENDPOINT_XFER_BULK, 182 .wMaxPacketSize = MAX_PACKET_SIZE_SS, 183 }, 184 .sink_comp = { 185 .bLength = sizeof(ss_descriptors.sink_comp), 186 .bDescriptorType = USB_DT_SS_ENDPOINT_COMP, 187 .bMaxBurst = 4, 188 }, 189 }; 190 191 struct usb_ext_compat_desc os_desc_compat = { 192 .bFirstInterfaceNumber = 0, 193 .Reserved1 = cpu_to_le32(1), 194 .CompatibleID = {0}, 195 .SubCompatibleID = {0}, 196 .Reserved2 = {0}, 197 }; 198 199 static struct usb_os_desc_header os_desc_header = { 200 .interface = cpu_to_le32(1), 201 .dwLength = cpu_to_le32(sizeof(os_desc_header) + sizeof(os_desc_compat)), 202 .bcdVersion = cpu_to_le32(1), 203 .wIndex = cpu_to_le32(4), 204 .bCount = cpu_to_le32(1), 205 .Reserved = cpu_to_le32(0), 206 }; 207 208 #define STR_INTERFACE_ "ADB Interface" 209 210 static const struct { 211 struct usb_functionfs_strings_head header; 212 struct { 213 __le16 code; 214 const char str1[sizeof(STR_INTERFACE_)]; 215 } __attribute__((packed)) lang0; 216 } __attribute__((packed)) strings = { 217 .header = { 218 .magic = cpu_to_le32(FUNCTIONFS_STRINGS_MAGIC), 219 .length = cpu_to_le32(sizeof(strings)), 220 .str_count = cpu_to_le32(1), 221 .lang_count = cpu_to_le32(1), 222 }, 223 .lang0 = { 224 cpu_to_le16(0x0409), /* en-us */ 225 STR_INTERFACE_, 226 }, 227 }; 228 229 static void aio_block_init(aio_block* aiob) { 230 aiob->iocb.resize(USB_FFS_NUM_BUFS); 231 aiob->iocbs.resize(USB_FFS_NUM_BUFS); 232 aiob->events.resize(USB_FFS_NUM_BUFS); 233 aiob->num_submitted = 0; 234 for (unsigned i = 0; i < USB_FFS_NUM_BUFS; i++) { 235 aiob->iocbs[i] = &aiob->iocb[i]; 236 } 237 } 238 239 static int getMaxPacketSize(int ffs_fd) { 240 usb_endpoint_descriptor desc; 241 if (ioctl(ffs_fd, FUNCTIONFS_ENDPOINT_DESC, reinterpret_cast<unsigned long>(&desc))) { 242 D("[ could not get endpoint descriptor! (%d) ]", errno); 243 return MAX_PACKET_SIZE_HS; 244 } else { 245 return desc.wMaxPacketSize; 246 } 247 } 248 249 bool init_functionfs(struct usb_handle* h) { 250 LOG(INFO) << "initializing functionfs"; 251 252 ssize_t ret; 253 struct desc_v1 v1_descriptor; 254 struct desc_v2 v2_descriptor; 255 256 v2_descriptor.header.magic = cpu_to_le32(FUNCTIONFS_DESCRIPTORS_MAGIC_V2); 257 v2_descriptor.header.length = cpu_to_le32(sizeof(v2_descriptor)); 258 v2_descriptor.header.flags = FUNCTIONFS_HAS_FS_DESC | FUNCTIONFS_HAS_HS_DESC | 259 FUNCTIONFS_HAS_SS_DESC | FUNCTIONFS_HAS_MS_OS_DESC; 260 v2_descriptor.fs_count = 3; 261 v2_descriptor.hs_count = 3; 262 v2_descriptor.ss_count = 5; 263 v2_descriptor.os_count = 1; 264 v2_descriptor.fs_descs = fs_descriptors; 265 v2_descriptor.hs_descs = hs_descriptors; 266 v2_descriptor.ss_descs = ss_descriptors; 267 v2_descriptor.os_header = os_desc_header; 268 v2_descriptor.os_desc = os_desc_compat; 269 270 if (h->control < 0) { // might have already done this before 271 LOG(INFO) << "opening control endpoint " << USB_FFS_ADB_EP0; 272 h->control = adb_open(USB_FFS_ADB_EP0, O_RDWR); 273 if (h->control < 0) { 274 PLOG(ERROR) << "cannot open control endpoint " << USB_FFS_ADB_EP0; 275 goto err; 276 } 277 278 ret = adb_write(h->control, &v2_descriptor, sizeof(v2_descriptor)); 279 if (ret < 0) { 280 v1_descriptor.header.magic = cpu_to_le32(FUNCTIONFS_DESCRIPTORS_MAGIC); 281 v1_descriptor.header.length = cpu_to_le32(sizeof(v1_descriptor)); 282 v1_descriptor.header.fs_count = 3; 283 v1_descriptor.header.hs_count = 3; 284 v1_descriptor.fs_descs = fs_descriptors; 285 v1_descriptor.hs_descs = hs_descriptors; 286 D("[ %s: Switching to V1_descriptor format errno=%d ]", USB_FFS_ADB_EP0, errno); 287 ret = adb_write(h->control, &v1_descriptor, sizeof(v1_descriptor)); 288 if (ret < 0) { 289 D("[ %s: write descriptors failed: errno=%d ]", USB_FFS_ADB_EP0, errno); 290 goto err; 291 } 292 } 293 294 ret = adb_write(h->control, &strings, sizeof(strings)); 295 if (ret < 0) { 296 D("[ %s: writing strings failed: errno=%d]", USB_FFS_ADB_EP0, errno); 297 goto err; 298 } 299 //Signal only when writing the descriptors to ffs 300 android::base::SetProperty("sys.usb.ffs.ready", "1"); 301 } 302 303 h->bulk_out = adb_open(USB_FFS_ADB_OUT, O_RDWR); 304 if (h->bulk_out < 0) { 305 PLOG(ERROR) << "cannot open bulk-out endpoint " << USB_FFS_ADB_OUT; 306 goto err; 307 } 308 309 h->bulk_in = adb_open(USB_FFS_ADB_IN, O_RDWR); 310 if (h->bulk_in < 0) { 311 PLOG(ERROR) << "cannot open bulk-in endpoint " << USB_FFS_ADB_IN; 312 goto err; 313 } 314 315 if (io_setup(USB_FFS_NUM_BUFS, &h->read_aiob.ctx) || 316 io_setup(USB_FFS_NUM_BUFS, &h->write_aiob.ctx)) { 317 D("[ aio: got error on io_setup (%d) ]", errno); 318 } 319 320 h->read_aiob.fd = h->bulk_out; 321 h->write_aiob.fd = h->bulk_in; 322 return true; 323 324 err: 325 if (h->bulk_in > 0) { 326 adb_close(h->bulk_in); 327 h->bulk_in = -1; 328 } 329 if (h->bulk_out > 0) { 330 adb_close(h->bulk_out); 331 h->bulk_out = -1; 332 } 333 if (h->control > 0) { 334 adb_close(h->control); 335 h->control = -1; 336 } 337 return false; 338 } 339 340 static void usb_ffs_open_thread(void* x) { 341 struct usb_handle* usb = (struct usb_handle*)x; 342 343 adb_thread_setname("usb ffs open"); 344 345 while (true) { 346 // wait until the USB device needs opening 347 std::unique_lock<std::mutex> lock(usb->lock); 348 while (!usb->open_new_connection) { 349 usb->notify.wait(lock); 350 } 351 usb->open_new_connection = false; 352 lock.unlock(); 353 354 while (true) { 355 if (init_functionfs(usb)) { 356 LOG(INFO) << "functionfs successfully initialized"; 357 break; 358 } 359 std::this_thread::sleep_for(1s); 360 } 361 362 LOG(INFO) << "registering usb transport"; 363 register_usb_transport(usb, 0, 0, 1); 364 } 365 366 // never gets here 367 abort(); 368 } 369 370 static int usb_ffs_write(usb_handle* h, const void* data, int len) { 371 D("about to write (fd=%d, len=%d)", h->bulk_in, len); 372 373 const char* buf = static_cast<const char*>(data); 374 while (len > 0) { 375 int write_len = std::min(USB_FFS_BULK_SIZE, len); 376 int n = adb_write(h->bulk_in, buf, write_len); 377 if (n < 0) { 378 D("ERROR: fd = %d, n = %d: %s", h->bulk_in, n, strerror(errno)); 379 return -1; 380 } 381 buf += n; 382 len -= n; 383 } 384 385 D("[ done fd=%d ]", h->bulk_in); 386 return 0; 387 } 388 389 static int usb_ffs_read(usb_handle* h, void* data, int len) { 390 D("about to read (fd=%d, len=%d)", h->bulk_out, len); 391 392 char* buf = static_cast<char*>(data); 393 while (len > 0) { 394 int read_len = std::min(USB_FFS_BULK_SIZE, len); 395 int n = adb_read(h->bulk_out, buf, read_len); 396 if (n < 0) { 397 D("ERROR: fd = %d, n = %d: %s", h->bulk_out, n, strerror(errno)); 398 return -1; 399 } 400 buf += n; 401 len -= n; 402 } 403 404 D("[ done fd=%d ]", h->bulk_out); 405 return 0; 406 } 407 408 static int usb_ffs_do_aio(usb_handle* h, const void* data, int len, bool read) { 409 aio_block* aiob = read ? &h->read_aiob : &h->write_aiob; 410 bool zero_packet = false; 411 412 int num_bufs = len / USB_FFS_BULK_SIZE + (len % USB_FFS_BULK_SIZE == 0 ? 0 : 1); 413 const char* cur_data = reinterpret_cast<const char*>(data); 414 int packet_size = getMaxPacketSize(aiob->fd); 415 416 if (posix_madvise(const_cast<void*>(data), len, POSIX_MADV_SEQUENTIAL | POSIX_MADV_WILLNEED) < 417 0) { 418 D("[ Failed to madvise: %d ]", errno); 419 } 420 421 for (int i = 0; i < num_bufs; i++) { 422 int buf_len = std::min(len, USB_FFS_BULK_SIZE); 423 io_prep(&aiob->iocb[i], aiob->fd, cur_data, buf_len, 0, read); 424 425 len -= buf_len; 426 cur_data += buf_len; 427 428 if (len == 0 && buf_len % packet_size == 0 && read) { 429 // adb does not expect the device to send a zero packet after data transfer, 430 // but the host *does* send a zero packet for the device to read. 431 zero_packet = true; 432 } 433 } 434 if (zero_packet) { 435 io_prep(&aiob->iocb[num_bufs], aiob->fd, reinterpret_cast<const void*>(cur_data), 436 packet_size, 0, read); 437 num_bufs += 1; 438 } 439 440 while (true) { 441 if (TEMP_FAILURE_RETRY(io_submit(aiob->ctx, num_bufs, aiob->iocbs.data())) < num_bufs) { 442 PLOG(ERROR) << "aio: got error submitting " << (read ? "read" : "write"); 443 return -1; 444 } 445 if (TEMP_FAILURE_RETRY(io_getevents(aiob->ctx, num_bufs, num_bufs, aiob->events.data(), 446 nullptr)) < num_bufs) { 447 PLOG(ERROR) << "aio: got error waiting " << (read ? "read" : "write"); 448 return -1; 449 } 450 if (num_bufs == 1 && aiob->events[0].res == -EINTR) { 451 continue; 452 } 453 for (int i = 0; i < num_bufs; i++) { 454 if (aiob->events[i].res < 0) { 455 errno = -aiob->events[i].res; 456 PLOG(ERROR) << "aio: got error event on " << (read ? "read" : "write") 457 << " total bufs " << num_bufs; 458 return -1; 459 } 460 } 461 return 0; 462 } 463 } 464 465 static int usb_ffs_aio_read(usb_handle* h, void* data, int len) { 466 return usb_ffs_do_aio(h, data, len, true); 467 } 468 469 static int usb_ffs_aio_write(usb_handle* h, const void* data, int len) { 470 return usb_ffs_do_aio(h, data, len, false); 471 } 472 473 static void usb_ffs_kick(usb_handle* h) { 474 int err; 475 476 err = ioctl(h->bulk_in, FUNCTIONFS_CLEAR_HALT); 477 if (err < 0) { 478 D("[ kick: source (fd=%d) clear halt failed (%d) ]", h->bulk_in, errno); 479 } 480 481 err = ioctl(h->bulk_out, FUNCTIONFS_CLEAR_HALT); 482 if (err < 0) { 483 D("[ kick: sink (fd=%d) clear halt failed (%d) ]", h->bulk_out, errno); 484 } 485 486 // don't close ep0 here, since we may not need to reinitialize it with 487 // the same descriptors again. if however ep1/ep2 fail to re-open in 488 // init_functionfs, only then would we close and open ep0 again. 489 // Ditto the comment in usb_adb_kick. 490 h->kicked = true; 491 TEMP_FAILURE_RETRY(dup2(dummy_fd, h->bulk_out)); 492 TEMP_FAILURE_RETRY(dup2(dummy_fd, h->bulk_in)); 493 } 494 495 static void usb_ffs_close(usb_handle* h) { 496 LOG(INFO) << "closing functionfs transport"; 497 498 h->kicked = false; 499 adb_close(h->bulk_out); 500 adb_close(h->bulk_in); 501 io_destroy(h->read_aiob.ctx); 502 io_destroy(h->write_aiob.ctx); 503 504 // Notify usb_adb_open_thread to open a new connection. 505 h->lock.lock(); 506 h->open_new_connection = true; 507 h->lock.unlock(); 508 h->notify.notify_one(); 509 } 510 511 static void usb_ffs_init() { 512 D("[ usb_init - using FunctionFS ]"); 513 514 usb_handle* h = new usb_handle(); 515 516 if (android::base::GetBoolProperty("sys.usb.ffs.aio_compat", false)) { 517 // Devices on older kernels (< 3.18) will not have aio support for ffs 518 // unless backported. Fall back on the non-aio functions instead. 519 h->write = usb_ffs_write; 520 h->read = usb_ffs_read; 521 } else { 522 h->write = usb_ffs_aio_write; 523 h->read = usb_ffs_aio_read; 524 aio_block_init(&h->read_aiob); 525 aio_block_init(&h->write_aiob); 526 } 527 h->kick = usb_ffs_kick; 528 h->close = usb_ffs_close; 529 530 D("[ usb_init - starting thread ]"); 531 std::thread(usb_ffs_open_thread, h).detach(); 532 } 533 534 void usb_init() { 535 dummy_fd = adb_open("/dev/null", O_WRONLY); 536 CHECK_NE(dummy_fd, -1); 537 usb_ffs_init(); 538 } 539 540 int usb_write(usb_handle* h, const void* data, int len) { 541 return h->write(h, data, len); 542 } 543 544 int usb_read(usb_handle* h, void* data, int len) { 545 return h->read(h, data, len); 546 } 547 548 int usb_close(usb_handle* h) { 549 h->close(h); 550 return 0; 551 } 552 553 void usb_kick(usb_handle* h) { 554 h->kick(h); 555 } 556