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