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    if (h->control < 0) { // might have already done this before
268        D("OPENING %s\n", USB_FFS_ADB_EP0);
269        h->control = adb_open(USB_FFS_ADB_EP0, O_RDWR);
270        if (h->control < 0) {
271            D("[ %s: cannot open control endpoint: errno=%d]\n", USB_FFS_ADB_EP0, errno);
272            goto err;
273        }
274
275        ret = adb_write(h->control, &descriptors, sizeof(descriptors));
276        if (ret < 0) {
277            D("[ %s: write descriptors failed: errno=%d ]\n", USB_FFS_ADB_EP0, errno);
278            goto err;
279        }
280
281        ret = adb_write(h->control, &strings, sizeof(strings));
282        if (ret < 0) {
283            D("[ %s: writing strings failed: errno=%d]\n", USB_FFS_ADB_EP0, errno);
284            goto err;
285        }
286    }
287
288    h->bulk_out = adb_open(USB_FFS_ADB_OUT, O_RDWR);
289    if (h->bulk_out < 0) {
290        D("[ %s: cannot open bulk-out ep: errno=%d ]\n", USB_FFS_ADB_OUT, errno);
291        goto err;
292    }
293
294    h->bulk_in = adb_open(USB_FFS_ADB_IN, O_RDWR);
295    if (h->bulk_in < 0) {
296        D("[ %s: cannot open bulk-in ep: errno=%d ]\n", USB_FFS_ADB_IN, errno);
297        goto err;
298    }
299
300    return;
301
302err:
303    if (h->bulk_in > 0) {
304        adb_close(h->bulk_in);
305        h->bulk_in = -1;
306    }
307    if (h->bulk_out > 0) {
308        adb_close(h->bulk_out);
309        h->bulk_out = -1;
310    }
311    if (h->control > 0) {
312        adb_close(h->control);
313        h->control = -1;
314    }
315    return;
316}
317
318static void *usb_ffs_open_thread(void *x)
319{
320    struct usb_handle *usb = (struct usb_handle *)x;
321
322    while (1) {
323        // wait until the USB device needs opening
324        adb_mutex_lock(&usb->lock);
325        while (usb->control != -1 && usb->bulk_in != -1 && usb->bulk_out != -1)
326            adb_cond_wait(&usb->notify, &usb->lock);
327        adb_mutex_unlock(&usb->lock);
328
329        while (1) {
330            init_functionfs(usb);
331
332            if (usb->control >= 0 && usb->bulk_in >= 0 && usb->bulk_out >= 0)
333                break;
334
335            adb_sleep_ms(1000);
336        }
337
338        D("[ usb_thread - registering device ]\n");
339        register_usb_transport(usb, 0, 0, 1);
340    }
341
342    // never gets here
343    return 0;
344}
345
346static int bulk_write(int bulk_in, const char *buf, size_t length)
347{
348    size_t count = 0;
349    int ret;
350
351    do {
352        ret = adb_write(bulk_in, buf + count, length - count);
353        if (ret < 0) {
354            if (errno != EINTR)
355                return ret;
356        } else {
357            count += ret;
358        }
359    } while (count < length);
360
361    D("[ bulk_write done fd=%d ]\n", bulk_in);
362    return count;
363}
364
365static int usb_ffs_write(usb_handle *h, const void *data, int len)
366{
367    int n;
368
369    D("about to write (fd=%d, len=%d)\n", h->bulk_in, len);
370    n = bulk_write(h->bulk_in, data, len);
371    if (n != len) {
372        D("ERROR: fd = %d, n = %d, errno = %d (%s)\n",
373            h->bulk_in, n, errno, strerror(errno));
374        return -1;
375    }
376    D("[ done fd=%d ]\n", h->bulk_in);
377    return 0;
378}
379
380static int bulk_read(int bulk_out, char *buf, size_t length)
381{
382    size_t count = 0;
383    int ret;
384
385    do {
386        ret = adb_read(bulk_out, buf + count, length - count);
387        if (ret < 0) {
388            if (errno != EINTR) {
389                D("[ bulk_read failed fd=%d length=%zu count=%zu ]\n",
390                                           bulk_out, length, count);
391                return ret;
392            }
393        } else {
394            count += ret;
395        }
396    } while (count < length);
397
398    return count;
399}
400
401static int usb_ffs_read(usb_handle *h, void *data, int len)
402{
403    int n;
404
405    D("about to read (fd=%d, len=%d)\n", h->bulk_out, len);
406    n = bulk_read(h->bulk_out, data, len);
407    if (n != len) {
408        D("ERROR: fd = %d, n = %d, errno = %d (%s)\n",
409            h->bulk_out, n, errno, strerror(errno));
410        return -1;
411    }
412    D("[ done fd=%d ]\n", h->bulk_out);
413    return 0;
414}
415
416static void usb_ffs_kick(usb_handle *h)
417{
418    int err;
419
420    err = ioctl(h->bulk_in, FUNCTIONFS_CLEAR_HALT);
421    if (err < 0)
422        D("[ kick: source (fd=%d) clear halt failed (%d) ]", h->bulk_in, errno);
423
424    err = ioctl(h->bulk_out, FUNCTIONFS_CLEAR_HALT);
425    if (err < 0)
426        D("[ kick: sink (fd=%d) clear halt failed (%d) ]", h->bulk_out, errno);
427
428    adb_mutex_lock(&h->lock);
429
430    // don't close ep0 here, since we may not need to reinitialize it with
431    // the same descriptors again. if however ep1/ep2 fail to re-open in
432    // init_functionfs, only then would we close and open ep0 again.
433    adb_close(h->bulk_out);
434    adb_close(h->bulk_in);
435    h->bulk_out = h->bulk_in = -1;
436
437    // notify usb_ffs_open_thread that we are disconnected
438    adb_cond_signal(&h->notify);
439    adb_mutex_unlock(&h->lock);
440}
441
442static void usb_ffs_init()
443{
444    usb_handle *h;
445    adb_thread_t tid;
446
447    D("[ usb_init - using FunctionFS ]\n");
448
449    h = calloc(1, sizeof(usb_handle));
450
451    h->write = usb_ffs_write;
452    h->read = usb_ffs_read;
453    h->kick = usb_ffs_kick;
454
455    h->control  = -1;
456    h->bulk_out = -1;
457    h->bulk_out = -1;
458
459    adb_cond_init(&h->notify, 0);
460    adb_mutex_init(&h->lock, 0);
461
462    D("[ usb_init - starting thread ]\n");
463    if (adb_thread_create(&tid, usb_ffs_open_thread, h)){
464        fatal_errno("[ cannot create usb thread ]\n");
465    }
466}
467
468void usb_init()
469{
470    if (access(USB_FFS_ADB_EP0, F_OK) == 0)
471        usb_ffs_init();
472    else
473        usb_adb_init();
474}
475
476void usb_cleanup()
477{
478}
479
480int usb_write(usb_handle *h, const void *data, int len)
481{
482    return h->write(h, data, len);
483}
484
485int usb_read(usb_handle *h, void *data, int len)
486{
487    return h->read(h, data, len);
488}
489int usb_close(usb_handle *h)
490{
491    return 0;
492}
493
494void usb_kick(usb_handle *h)
495{
496    h->kick(h);
497}
498