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