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