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