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 <cutils/properties.h>
22 #include <dirent.h>
23 #include <errno.h>
24 #include <linux/usb/ch9.h>
25 #include <linux/usb/functionfs.h>
26 #include <stdio.h>
27 #include <stdlib.h>
28 #include <string.h>
29 #include <sys/ioctl.h>
30 #include <sys/types.h>
31 #include <unistd.h>
32
33 #include <algorithm>
34 #include <atomic>
35
36 #include <android-base/logging.h>
37
38 #include "adb.h"
39 #include "transport.h"
40
41 #define MAX_PACKET_SIZE_FS 64
42 #define MAX_PACKET_SIZE_HS 512
43 #define MAX_PACKET_SIZE_SS 1024
44
45 // Writes larger than 16k fail on some devices (seed with 3.10.49-g209ea2f in particular).
46 #define USB_FFS_MAX_WRITE 16384
47
48 // The kernel allocates a contiguous buffer for reads, which can fail for large ones due to
49 // fragmentation. 16k chosen arbitrarily to match the write limit.
50 #define USB_FFS_MAX_READ 16384
51
52 #define cpu_to_le16(x) htole16(x)
53 #define cpu_to_le32(x) htole32(x)
54
55 static int dummy_fd = -1;
56
57 struct usb_handle
58 {
59 adb_cond_t notify;
60 adb_mutex_t lock;
61 bool open_new_connection;
62 std::atomic<bool> kicked;
63
64 int (*write)(usb_handle *h, const void *data, int len);
65 int (*read)(usb_handle *h, void *data, int len);
66 void (*kick)(usb_handle *h);
67 void (*close)(usb_handle *h);
68
69 // Legacy f_adb
70 int fd;
71
72 // FunctionFS
73 int control;
74 int bulk_out; /* "out" from the host's perspective => source for adbd */
75 int bulk_in; /* "in" from the host's perspective => sink for adbd */
76 };
77
78 struct func_desc {
79 struct usb_interface_descriptor intf;
80 struct usb_endpoint_descriptor_no_audio source;
81 struct usb_endpoint_descriptor_no_audio sink;
82 } __attribute__((packed));
83
84 struct ss_func_desc {
85 struct usb_interface_descriptor intf;
86 struct usb_endpoint_descriptor_no_audio source;
87 struct usb_ss_ep_comp_descriptor source_comp;
88 struct usb_endpoint_descriptor_no_audio sink;
89 struct usb_ss_ep_comp_descriptor sink_comp;
90 } __attribute__((packed));
91
92 struct desc_v1 {
93 struct usb_functionfs_descs_head_v1 {
94 __le32 magic;
95 __le32 length;
96 __le32 fs_count;
97 __le32 hs_count;
98 } __attribute__((packed)) header;
99 struct func_desc fs_descs, hs_descs;
100 } __attribute__((packed));
101
102 struct desc_v2 {
103 struct usb_functionfs_descs_head_v2 header;
104 // The rest of the structure depends on the flags in the header.
105 __le32 fs_count;
106 __le32 hs_count;
107 __le32 ss_count;
108 __le32 os_count;
109 struct func_desc fs_descs, hs_descs;
110 struct ss_func_desc ss_descs;
111 struct usb_os_desc_header os_header;
112 struct usb_ext_compat_desc os_desc;
113 } __attribute__((packed));
114
115 static struct func_desc fs_descriptors = {
116 .intf = {
117 .bLength = sizeof(fs_descriptors.intf),
118 .bDescriptorType = USB_DT_INTERFACE,
119 .bInterfaceNumber = 0,
120 .bNumEndpoints = 2,
121 .bInterfaceClass = ADB_CLASS,
122 .bInterfaceSubClass = ADB_SUBCLASS,
123 .bInterfaceProtocol = ADB_PROTOCOL,
124 .iInterface = 1, /* first string from the provided table */
125 },
126 .source = {
127 .bLength = sizeof(fs_descriptors.source),
128 .bDescriptorType = USB_DT_ENDPOINT,
129 .bEndpointAddress = 1 | USB_DIR_OUT,
130 .bmAttributes = USB_ENDPOINT_XFER_BULK,
131 .wMaxPacketSize = MAX_PACKET_SIZE_FS,
132 },
133 .sink = {
134 .bLength = sizeof(fs_descriptors.sink),
135 .bDescriptorType = USB_DT_ENDPOINT,
136 .bEndpointAddress = 2 | USB_DIR_IN,
137 .bmAttributes = USB_ENDPOINT_XFER_BULK,
138 .wMaxPacketSize = MAX_PACKET_SIZE_FS,
139 },
140 };
141
142 static struct func_desc hs_descriptors = {
143 .intf = {
144 .bLength = sizeof(hs_descriptors.intf),
145 .bDescriptorType = USB_DT_INTERFACE,
146 .bInterfaceNumber = 0,
147 .bNumEndpoints = 2,
148 .bInterfaceClass = ADB_CLASS,
149 .bInterfaceSubClass = ADB_SUBCLASS,
150 .bInterfaceProtocol = ADB_PROTOCOL,
151 .iInterface = 1, /* first string from the provided table */
152 },
153 .source = {
154 .bLength = sizeof(hs_descriptors.source),
155 .bDescriptorType = USB_DT_ENDPOINT,
156 .bEndpointAddress = 1 | USB_DIR_OUT,
157 .bmAttributes = USB_ENDPOINT_XFER_BULK,
158 .wMaxPacketSize = MAX_PACKET_SIZE_HS,
159 },
160 .sink = {
161 .bLength = sizeof(hs_descriptors.sink),
162 .bDescriptorType = USB_DT_ENDPOINT,
163 .bEndpointAddress = 2 | USB_DIR_IN,
164 .bmAttributes = USB_ENDPOINT_XFER_BULK,
165 .wMaxPacketSize = MAX_PACKET_SIZE_HS,
166 },
167 };
168
169 static struct ss_func_desc ss_descriptors = {
170 .intf = {
171 .bLength = sizeof(ss_descriptors.intf),
172 .bDescriptorType = USB_DT_INTERFACE,
173 .bInterfaceNumber = 0,
174 .bNumEndpoints = 2,
175 .bInterfaceClass = ADB_CLASS,
176 .bInterfaceSubClass = ADB_SUBCLASS,
177 .bInterfaceProtocol = ADB_PROTOCOL,
178 .iInterface = 1, /* first string from the provided table */
179 },
180 .source = {
181 .bLength = sizeof(ss_descriptors.source),
182 .bDescriptorType = USB_DT_ENDPOINT,
183 .bEndpointAddress = 1 | USB_DIR_OUT,
184 .bmAttributes = USB_ENDPOINT_XFER_BULK,
185 .wMaxPacketSize = MAX_PACKET_SIZE_SS,
186 },
187 .source_comp = {
188 .bLength = sizeof(ss_descriptors.source_comp),
189 .bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
190 },
191 .sink = {
192 .bLength = sizeof(ss_descriptors.sink),
193 .bDescriptorType = USB_DT_ENDPOINT,
194 .bEndpointAddress = 2 | USB_DIR_IN,
195 .bmAttributes = USB_ENDPOINT_XFER_BULK,
196 .wMaxPacketSize = MAX_PACKET_SIZE_SS,
197 },
198 .sink_comp = {
199 .bLength = sizeof(ss_descriptors.sink_comp),
200 .bDescriptorType = USB_DT_SS_ENDPOINT_COMP,
201 },
202 };
203
204 struct usb_ext_compat_desc os_desc_compat = {
205 .bFirstInterfaceNumber = 0,
206 .Reserved1 = cpu_to_le32(1),
207 .CompatibleID = {0},
208 .SubCompatibleID = {0},
209 .Reserved2 = {0},
210 };
211
212 static struct usb_os_desc_header os_desc_header = {
213 .interface = cpu_to_le32(1),
214 .dwLength = cpu_to_le32(sizeof(os_desc_header) + sizeof(os_desc_compat)),
215 .bcdVersion = cpu_to_le32(1),
216 .wIndex = cpu_to_le32(4),
217 .bCount = cpu_to_le32(1),
218 .Reserved = cpu_to_le32(0),
219 };
220
221
222 #define STR_INTERFACE_ "ADB Interface"
223
224 static const struct {
225 struct usb_functionfs_strings_head header;
226 struct {
227 __le16 code;
228 const char str1[sizeof(STR_INTERFACE_)];
229 } __attribute__((packed)) lang0;
230 } __attribute__((packed)) strings = {
231 .header = {
232 .magic = cpu_to_le32(FUNCTIONFS_STRINGS_MAGIC),
233 .length = cpu_to_le32(sizeof(strings)),
234 .str_count = cpu_to_le32(1),
235 .lang_count = cpu_to_le32(1),
236 },
237 .lang0 = {
238 cpu_to_le16(0x0409), /* en-us */
239 STR_INTERFACE_,
240 },
241 };
242
usb_adb_open_thread(void * x)243 static void usb_adb_open_thread(void* x) {
244 struct usb_handle *usb = (struct usb_handle *)x;
245 int fd;
246
247 adb_thread_setname("usb open");
248
249 while (true) {
250 // wait until the USB device needs opening
251 adb_mutex_lock(&usb->lock);
252 while (!usb->open_new_connection) {
253 adb_cond_wait(&usb->notify, &usb->lock);
254 }
255 usb->open_new_connection = false;
256 adb_mutex_unlock(&usb->lock);
257
258 D("[ usb_thread - opening device ]");
259 do {
260 /* XXX use inotify? */
261 fd = unix_open("/dev/android_adb", O_RDWR);
262 if (fd < 0) {
263 // to support older kernels
264 fd = unix_open("/dev/android", O_RDWR);
265 }
266 if (fd < 0) {
267 adb_sleep_ms(1000);
268 }
269 } while (fd < 0);
270 D("[ opening device succeeded ]");
271
272 close_on_exec(fd);
273 usb->fd = fd;
274
275 D("[ usb_thread - registering device ]");
276 register_usb_transport(usb, 0, 0, 1);
277 }
278
279 // never gets here
280 abort();
281 }
282
usb_adb_write(usb_handle * h,const void * data,int len)283 static int usb_adb_write(usb_handle *h, const void *data, int len)
284 {
285 int n;
286
287 D("about to write (fd=%d, len=%d)", h->fd, len);
288 n = unix_write(h->fd, data, len);
289 if(n != len) {
290 D("ERROR: fd = %d, n = %d, errno = %d (%s)",
291 h->fd, n, errno, strerror(errno));
292 return -1;
293 }
294 if (h->kicked) {
295 D("usb_adb_write finished due to kicked");
296 return -1;
297 }
298 D("[ done fd=%d ]", h->fd);
299 return 0;
300 }
301
usb_adb_read(usb_handle * h,void * data,int len)302 static int usb_adb_read(usb_handle *h, void *data, int len)
303 {
304 D("about to read (fd=%d, len=%d)", h->fd, len);
305 while (len > 0) {
306 // The kernel implementation of adb_read in f_adb.c doesn't support
307 // reads larger then 4096 bytes. Read the data in 4096 byte chunks to
308 // avoid the issue. (The ffs implementation doesn't have this limit.)
309 int bytes_to_read = len < 4096 ? len : 4096;
310 int n = unix_read(h->fd, data, bytes_to_read);
311 if (n != bytes_to_read) {
312 D("ERROR: fd = %d, n = %d, errno = %d (%s)",
313 h->fd, n, errno, strerror(errno));
314 return -1;
315 }
316 if (h->kicked) {
317 D("usb_adb_read finished due to kicked");
318 return -1;
319 }
320 len -= n;
321 data = ((char*)data) + n;
322 }
323 D("[ done fd=%d ]", h->fd);
324 return 0;
325 }
326
usb_adb_kick(usb_handle * h)327 static void usb_adb_kick(usb_handle *h) {
328 D("usb_kick");
329 // Other threads may be calling usb_adb_read/usb_adb_write at the same time.
330 // If we close h->fd, the file descriptor will be reused to open other files,
331 // and the read/write thread may operate on the wrong file. So instead
332 // we set the kicked flag and reopen h->fd to a dummy file here. After read/write
333 // threads finish, we close h->fd in usb_adb_close().
334 h->kicked = true;
335 TEMP_FAILURE_RETRY(dup2(dummy_fd, h->fd));
336 }
337
usb_adb_close(usb_handle * h)338 static void usb_adb_close(usb_handle *h) {
339 h->kicked = false;
340 adb_close(h->fd);
341 // Notify usb_adb_open_thread to open a new connection.
342 adb_mutex_lock(&h->lock);
343 h->open_new_connection = true;
344 adb_cond_signal(&h->notify);
345 adb_mutex_unlock(&h->lock);
346 }
347
usb_adb_init()348 static void usb_adb_init()
349 {
350 usb_handle* h = reinterpret_cast<usb_handle*>(calloc(1, sizeof(usb_handle)));
351 if (h == nullptr) fatal("couldn't allocate usb_handle");
352
353 h->write = usb_adb_write;
354 h->read = usb_adb_read;
355 h->kick = usb_adb_kick;
356 h->close = usb_adb_close;
357 h->kicked = false;
358 h->fd = -1;
359
360 h->open_new_connection = true;
361 adb_cond_init(&h->notify, 0);
362 adb_mutex_init(&h->lock, 0);
363
364 // Open the file /dev/android_adb_enable to trigger
365 // the enabling of the adb USB function in the kernel.
366 // We never touch this file again - just leave it open
367 // indefinitely so the kernel will know when we are running
368 // and when we are not.
369 int fd = unix_open("/dev/android_adb_enable", O_RDWR);
370 if (fd < 0) {
371 D("failed to open /dev/android_adb_enable");
372 } else {
373 close_on_exec(fd);
374 }
375
376 D("[ usb_init - starting thread ]");
377 if (!adb_thread_create(usb_adb_open_thread, h)) {
378 fatal_errno("cannot create usb thread");
379 }
380 }
381
382
init_functionfs(struct usb_handle * h)383 static bool init_functionfs(struct usb_handle *h)
384 {
385 ssize_t ret;
386 struct desc_v1 v1_descriptor;
387 struct desc_v2 v2_descriptor;
388
389 v2_descriptor.header.magic = cpu_to_le32(FUNCTIONFS_DESCRIPTORS_MAGIC_V2);
390 v2_descriptor.header.length = cpu_to_le32(sizeof(v2_descriptor));
391 v2_descriptor.header.flags = FUNCTIONFS_HAS_FS_DESC | FUNCTIONFS_HAS_HS_DESC |
392 FUNCTIONFS_HAS_SS_DESC | FUNCTIONFS_HAS_MS_OS_DESC;
393 v2_descriptor.fs_count = 3;
394 v2_descriptor.hs_count = 3;
395 v2_descriptor.ss_count = 5;
396 v2_descriptor.os_count = 1;
397 v2_descriptor.fs_descs = fs_descriptors;
398 v2_descriptor.hs_descs = hs_descriptors;
399 v2_descriptor.ss_descs = ss_descriptors;
400 v2_descriptor.os_header = os_desc_header;
401 v2_descriptor.os_desc = os_desc_compat;
402
403 if (h->control < 0) { // might have already done this before
404 D("OPENING %s", USB_FFS_ADB_EP0);
405 h->control = adb_open(USB_FFS_ADB_EP0, O_RDWR);
406 if (h->control < 0) {
407 D("[ %s: cannot open control endpoint: errno=%d]", USB_FFS_ADB_EP0, errno);
408 goto err;
409 }
410
411 ret = adb_write(h->control, &v2_descriptor, sizeof(v2_descriptor));
412 if (ret < 0) {
413 v1_descriptor.header.magic = cpu_to_le32(FUNCTIONFS_DESCRIPTORS_MAGIC);
414 v1_descriptor.header.length = cpu_to_le32(sizeof(v1_descriptor));
415 v1_descriptor.header.fs_count = 3;
416 v1_descriptor.header.hs_count = 3;
417 v1_descriptor.fs_descs = fs_descriptors;
418 v1_descriptor.hs_descs = hs_descriptors;
419 D("[ %s: Switching to V1_descriptor format errno=%d ]", USB_FFS_ADB_EP0, errno);
420 ret = adb_write(h->control, &v1_descriptor, sizeof(v1_descriptor));
421 if (ret < 0) {
422 D("[ %s: write descriptors failed: errno=%d ]", USB_FFS_ADB_EP0, errno);
423 goto err;
424 }
425 }
426
427 ret = adb_write(h->control, &strings, sizeof(strings));
428 if (ret < 0) {
429 D("[ %s: writing strings failed: errno=%d]", USB_FFS_ADB_EP0, errno);
430 goto err;
431 }
432 }
433
434 h->bulk_out = adb_open(USB_FFS_ADB_OUT, O_RDWR);
435 if (h->bulk_out < 0) {
436 D("[ %s: cannot open bulk-out ep: errno=%d ]", USB_FFS_ADB_OUT, errno);
437 goto err;
438 }
439
440 h->bulk_in = adb_open(USB_FFS_ADB_IN, O_RDWR);
441 if (h->bulk_in < 0) {
442 D("[ %s: cannot open bulk-in ep: errno=%d ]", USB_FFS_ADB_IN, errno);
443 goto err;
444 }
445
446 return true;
447
448 err:
449 if (h->bulk_in > 0) {
450 adb_close(h->bulk_in);
451 h->bulk_in = -1;
452 }
453 if (h->bulk_out > 0) {
454 adb_close(h->bulk_out);
455 h->bulk_out = -1;
456 }
457 if (h->control > 0) {
458 adb_close(h->control);
459 h->control = -1;
460 }
461 return false;
462 }
463
usb_ffs_open_thread(void * x)464 static void usb_ffs_open_thread(void* x) {
465 struct usb_handle *usb = (struct usb_handle *)x;
466
467 adb_thread_setname("usb ffs open");
468
469 while (true) {
470 // wait until the USB device needs opening
471 adb_mutex_lock(&usb->lock);
472 while (!usb->open_new_connection) {
473 adb_cond_wait(&usb->notify, &usb->lock);
474 }
475 usb->open_new_connection = false;
476 adb_mutex_unlock(&usb->lock);
477
478 while (true) {
479 if (init_functionfs(usb)) {
480 break;
481 }
482 adb_sleep_ms(1000);
483 }
484 property_set("sys.usb.ffs.ready", "1");
485
486 D("[ usb_thread - registering device ]");
487 register_usb_transport(usb, 0, 0, 1);
488 }
489
490 // never gets here
491 abort();
492 }
493
usb_ffs_write(usb_handle * h,const void * data,int len)494 static int usb_ffs_write(usb_handle* h, const void* data, int len) {
495 D("about to write (fd=%d, len=%d)", h->bulk_in, len);
496
497 const char* buf = static_cast<const char*>(data);
498 while (len > 0) {
499 int write_len = std::min(USB_FFS_MAX_WRITE, len);
500 int n = adb_write(h->bulk_in, buf, write_len);
501 if (n < 0) {
502 D("ERROR: fd = %d, n = %d: %s", h->bulk_in, n, strerror(errno));
503 return -1;
504 }
505 buf += n;
506 len -= n;
507 }
508
509 D("[ done fd=%d ]", h->bulk_in);
510 return 0;
511 }
512
usb_ffs_read(usb_handle * h,void * data,int len)513 static int usb_ffs_read(usb_handle* h, void* data, int len) {
514 D("about to read (fd=%d, len=%d)", h->bulk_out, len);
515
516 char* buf = static_cast<char*>(data);
517 while (len > 0) {
518 int read_len = std::min(USB_FFS_MAX_READ, len);
519 int n = adb_read(h->bulk_out, buf, read_len);
520 if (n < 0) {
521 D("ERROR: fd = %d, n = %d: %s", h->bulk_out, n, strerror(errno));
522 return -1;
523 }
524 buf += n;
525 len -= n;
526 }
527
528 D("[ done fd=%d ]", h->bulk_out);
529 return 0;
530 }
531
usb_ffs_kick(usb_handle * h)532 static void usb_ffs_kick(usb_handle *h)
533 {
534 int err;
535
536 err = ioctl(h->bulk_in, FUNCTIONFS_CLEAR_HALT);
537 if (err < 0) {
538 D("[ kick: source (fd=%d) clear halt failed (%d) ]", h->bulk_in, errno);
539 }
540
541 err = ioctl(h->bulk_out, FUNCTIONFS_CLEAR_HALT);
542 if (err < 0) {
543 D("[ kick: sink (fd=%d) clear halt failed (%d) ]", h->bulk_out, errno);
544 }
545
546 // don't close ep0 here, since we may not need to reinitialize it with
547 // the same descriptors again. if however ep1/ep2 fail to re-open in
548 // init_functionfs, only then would we close and open ep0 again.
549 // Ditto the comment in usb_adb_kick.
550 h->kicked = true;
551 TEMP_FAILURE_RETRY(dup2(dummy_fd, h->bulk_out));
552 TEMP_FAILURE_RETRY(dup2(dummy_fd, h->bulk_in));
553 }
554
usb_ffs_close(usb_handle * h)555 static void usb_ffs_close(usb_handle *h) {
556 h->kicked = false;
557 adb_close(h->bulk_out);
558 adb_close(h->bulk_in);
559 // Notify usb_adb_open_thread to open a new connection.
560 adb_mutex_lock(&h->lock);
561 h->open_new_connection = true;
562 adb_cond_signal(&h->notify);
563 adb_mutex_unlock(&h->lock);
564 }
565
usb_ffs_init()566 static void usb_ffs_init()
567 {
568 D("[ usb_init - using FunctionFS ]");
569
570 usb_handle* h = reinterpret_cast<usb_handle*>(calloc(1, sizeof(usb_handle)));
571 if (h == nullptr) fatal("couldn't allocate usb_handle");
572
573 h->write = usb_ffs_write;
574 h->read = usb_ffs_read;
575 h->kick = usb_ffs_kick;
576 h->close = usb_ffs_close;
577 h->kicked = false;
578 h->control = -1;
579 h->bulk_out = -1;
580 h->bulk_out = -1;
581
582 h->open_new_connection = true;
583 adb_cond_init(&h->notify, 0);
584 adb_mutex_init(&h->lock, 0);
585
586 D("[ usb_init - starting thread ]");
587 if (!adb_thread_create(usb_ffs_open_thread, h)) {
588 fatal_errno("[ cannot create usb thread ]\n");
589 }
590 }
591
usb_init()592 void usb_init()
593 {
594 dummy_fd = adb_open("/dev/null", O_WRONLY);
595 CHECK_NE(dummy_fd, -1);
596 if (access(USB_FFS_ADB_EP0, F_OK) == 0)
597 usb_ffs_init();
598 else
599 usb_adb_init();
600 }
601
usb_write(usb_handle * h,const void * data,int len)602 int usb_write(usb_handle *h, const void *data, int len)
603 {
604 return h->write(h, data, len);
605 }
606
usb_read(usb_handle * h,void * data,int len)607 int usb_read(usb_handle *h, void *data, int len)
608 {
609 return h->read(h, data, len);
610 }
usb_close(usb_handle * h)611 int usb_close(usb_handle *h)
612 {
613 h->close(h);
614 return 0;
615 }
616
usb_kick(usb_handle * h)617 void usb_kick(usb_handle *h)
618 {
619 h->kick(h);
620 }
621