1/*
2 * Copyright (C) 2010 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 DEBUG 1
18#if DEBUG
19
20#ifdef USE_LIBLOG
21#define LOG_TAG "usbhost"
22#include "utils/Log.h"
23#define D ALOGD
24#else
25#define D printf
26#endif
27
28#else
29#define D(...)
30#endif
31
32#include <stdio.h>
33#include <stdlib.h>
34#include <unistd.h>
35#include <string.h>
36#include <stddef.h>
37
38#include <sys/ioctl.h>
39#include <sys/types.h>
40#include <sys/time.h>
41#include <sys/inotify.h>
42#include <dirent.h>
43#include <fcntl.h>
44#include <errno.h>
45#include <ctype.h>
46#include <pthread.h>
47
48#include <linux/usbdevice_fs.h>
49#include <asm/byteorder.h>
50
51#include "usbhost/usbhost.h"
52
53#define DEV_DIR             "/dev"
54#define DEV_BUS_DIR         DEV_DIR "/bus"
55#define USB_FS_DIR          DEV_BUS_DIR "/usb"
56#define USB_FS_ID_SCANNER   USB_FS_DIR "/%d/%d"
57#define USB_FS_ID_FORMAT    USB_FS_DIR "/%03d/%03d"
58
59// From drivers/usb/core/devio.c
60// I don't know why this isn't in a kernel header
61#define MAX_USBFS_BUFFER_SIZE   16384
62
63#define MAX_USBFS_WD_COUNT      10
64
65struct usb_host_context {
66    int                         fd;
67    usb_device_added_cb         cb_added;
68    usb_device_removed_cb       cb_removed;
69    void                        *data;
70    int                         wds[MAX_USBFS_WD_COUNT];
71    int                         wdd;
72    int                         wddbus;
73};
74
75struct usb_device {
76    char dev_name[64];
77    unsigned char desc[4096];
78    int desc_length;
79    int fd;
80    int writeable;
81};
82
83static inline int badname(const char *name)
84{
85    while(*name) {
86        if(!isdigit(*name++)) return 1;
87    }
88    return 0;
89}
90
91static int find_existing_devices_bus(char *busname,
92                                     usb_device_added_cb added_cb,
93                                     void *client_data)
94{
95    char devname[32];
96    DIR *devdir;
97    struct dirent *de;
98    int done = 0;
99
100    devdir = opendir(busname);
101    if(devdir == 0) return 0;
102
103    while ((de = readdir(devdir)) && !done) {
104        if(badname(de->d_name)) continue;
105
106        snprintf(devname, sizeof(devname), "%s/%s", busname, de->d_name);
107        done = added_cb(devname, client_data);
108    } // end of devdir while
109    closedir(devdir);
110
111    return done;
112}
113
114/* returns true if one of the callbacks indicates we are done */
115static int find_existing_devices(usb_device_added_cb added_cb,
116                                  void *client_data)
117{
118    char busname[32];
119    DIR *busdir;
120    struct dirent *de;
121    int done = 0;
122
123    busdir = opendir(USB_FS_DIR);
124    if(busdir == 0) return 0;
125
126    while ((de = readdir(busdir)) != 0 && !done) {
127        if(badname(de->d_name)) continue;
128
129        snprintf(busname, sizeof(busname), USB_FS_DIR "/%s", de->d_name);
130        done = find_existing_devices_bus(busname, added_cb,
131                                         client_data);
132    } //end of busdir while
133    closedir(busdir);
134
135    return done;
136}
137
138static void watch_existing_subdirs(struct usb_host_context *context,
139                                   int *wds, int wd_count)
140{
141    char path[100];
142    int i, ret;
143
144    wds[0] = inotify_add_watch(context->fd, USB_FS_DIR, IN_CREATE | IN_DELETE);
145    if (wds[0] < 0)
146        return;
147
148    /* watch existing subdirectories of USB_FS_DIR */
149    for (i = 1; i < wd_count; i++) {
150        snprintf(path, sizeof(path), USB_FS_DIR "/%03d", i);
151        ret = inotify_add_watch(context->fd, path, IN_CREATE | IN_DELETE);
152        if (ret >= 0)
153            wds[i] = ret;
154    }
155}
156
157struct usb_host_context *usb_host_init()
158{
159    struct usb_host_context *context = calloc(1, sizeof(struct usb_host_context));
160    if (!context) {
161        fprintf(stderr, "out of memory in usb_host_context\n");
162        return NULL;
163    }
164    context->fd = inotify_init();
165    if (context->fd < 0) {
166        fprintf(stderr, "inotify_init failed\n");
167        free(context);
168        return NULL;
169    }
170    return context;
171}
172
173void usb_host_cleanup(struct usb_host_context *context)
174{
175    close(context->fd);
176    free(context);
177}
178
179int usb_host_get_fd(struct usb_host_context *context)
180{
181    return context->fd;
182} /* usb_host_get_fd() */
183
184int usb_host_load(struct usb_host_context *context,
185                  usb_device_added_cb added_cb,
186                  usb_device_removed_cb removed_cb,
187                  usb_discovery_done_cb discovery_done_cb,
188                  void *client_data)
189{
190    int done = 0;
191    int i;
192
193    context->cb_added = added_cb;
194    context->cb_removed = removed_cb;
195    context->data = client_data;
196
197    D("Created device discovery thread\n");
198
199    /* watch for files added and deleted within USB_FS_DIR */
200    context->wddbus = -1;
201    for (i = 0; i < MAX_USBFS_WD_COUNT; i++)
202        context->wds[i] = -1;
203
204    /* watch the root for new subdirectories */
205    context->wdd = inotify_add_watch(context->fd, DEV_DIR, IN_CREATE | IN_DELETE);
206    if (context->wdd < 0) {
207        fprintf(stderr, "inotify_add_watch failed\n");
208        if (discovery_done_cb)
209            discovery_done_cb(client_data);
210        return done;
211    }
212
213    watch_existing_subdirs(context, context->wds, MAX_USBFS_WD_COUNT);
214
215    /* check for existing devices first, after we have inotify set up */
216    done = find_existing_devices(added_cb, client_data);
217    if (discovery_done_cb)
218        done |= discovery_done_cb(client_data);
219
220    return done;
221} /* usb_host_load() */
222
223int usb_host_read_event(struct usb_host_context *context)
224{
225    struct inotify_event* event;
226    char event_buf[512];
227    char path[100];
228    int i, ret, done = 0;
229    int offset = 0;
230    int wd;
231
232    ret = read(context->fd, event_buf, sizeof(event_buf));
233    if (ret >= (int)sizeof(struct inotify_event)) {
234        while (offset < ret && !done) {
235            event = (struct inotify_event*)&event_buf[offset];
236            done = 0;
237            wd = event->wd;
238            if (wd == context->wdd) {
239                if ((event->mask & IN_CREATE) && !strcmp(event->name, "bus")) {
240                    context->wddbus = inotify_add_watch(context->fd, DEV_BUS_DIR, IN_CREATE | IN_DELETE);
241                    if (context->wddbus < 0) {
242                        done = 1;
243                    } else {
244                        watch_existing_subdirs(context, context->wds, MAX_USBFS_WD_COUNT);
245                        done = find_existing_devices(context->cb_added, context->data);
246                    }
247                }
248            } else if (wd == context->wddbus) {
249                if ((event->mask & IN_CREATE) && !strcmp(event->name, "usb")) {
250                    watch_existing_subdirs(context, context->wds, MAX_USBFS_WD_COUNT);
251                    done = find_existing_devices(context->cb_added, context->data);
252                } else if ((event->mask & IN_DELETE) && !strcmp(event->name, "usb")) {
253                    for (i = 0; i < MAX_USBFS_WD_COUNT; i++) {
254                        if (context->wds[i] >= 0) {
255                            inotify_rm_watch(context->fd, context->wds[i]);
256                            context->wds[i] = -1;
257                        }
258                    }
259                }
260            } else if (wd == context->wds[0]) {
261                i = atoi(event->name);
262                snprintf(path, sizeof(path), USB_FS_DIR "/%s", event->name);
263                D("%s subdirectory %s: index: %d\n", (event->mask & IN_CREATE) ?
264                        "new" : "gone", path, i);
265                if (i > 0 && i < MAX_USBFS_WD_COUNT) {
266                    if (event->mask & IN_CREATE) {
267                        ret = inotify_add_watch(context->fd, path,
268                                IN_CREATE | IN_DELETE);
269                        if (ret >= 0)
270                            context->wds[i] = ret;
271                        done = find_existing_devices_bus(path, context->cb_added,
272                                context->data);
273                    } else if (event->mask & IN_DELETE) {
274                        inotify_rm_watch(context->fd, context->wds[i]);
275                        context->wds[i] = -1;
276                    }
277                }
278            } else {
279                for (i = 1; (i < MAX_USBFS_WD_COUNT) && !done; i++) {
280                    if (wd == context->wds[i]) {
281                        snprintf(path, sizeof(path), USB_FS_DIR "/%03d/%s", i, event->name);
282                        if (event->mask == IN_CREATE) {
283                            D("new device %s\n", path);
284                            done = context->cb_added(path, context->data);
285                        } else if (event->mask == IN_DELETE) {
286                            D("gone device %s\n", path);
287                            done = context->cb_removed(path, context->data);
288                        }
289                    }
290                }
291            }
292
293            offset += sizeof(struct inotify_event) + event->len;
294        }
295    }
296
297    return done;
298} /* usb_host_read_event() */
299
300void usb_host_run(struct usb_host_context *context,
301                  usb_device_added_cb added_cb,
302                  usb_device_removed_cb removed_cb,
303                  usb_discovery_done_cb discovery_done_cb,
304                  void *client_data)
305{
306    int done;
307
308    done = usb_host_load(context, added_cb, removed_cb, discovery_done_cb, client_data);
309
310    while (!done) {
311
312        done = usb_host_read_event(context);
313    }
314} /* usb_host_run() */
315
316struct usb_device *usb_device_open(const char *dev_name)
317{
318    int fd, did_retry = 0, writeable = 1;
319
320    D("usb_device_open %s\n", dev_name);
321
322retry:
323    fd = open(dev_name, O_RDWR);
324    if (fd < 0) {
325        /* if we fail, see if have read-only access */
326        fd = open(dev_name, O_RDONLY);
327        D("usb_device_open open returned %d errno %d\n", fd, errno);
328        if (fd < 0 && (errno == EACCES || errno == ENOENT) && !did_retry) {
329            /* work around race condition between inotify and permissions management */
330            sleep(1);
331            did_retry = 1;
332            goto retry;
333        }
334
335        if (fd < 0)
336            return NULL;
337        writeable = 0;
338        D("[ usb open read-only %s fd = %d]\n", dev_name, fd);
339    }
340
341    struct usb_device* result = usb_device_new(dev_name, fd);
342    if (result)
343        result->writeable = writeable;
344    return result;
345}
346
347void usb_device_close(struct usb_device *device)
348{
349    close(device->fd);
350    free(device);
351}
352
353struct usb_device *usb_device_new(const char *dev_name, int fd)
354{
355    struct usb_device *device = calloc(1, sizeof(struct usb_device));
356    int length;
357
358    D("usb_device_new %s fd: %d\n", dev_name, fd);
359
360    if (lseek(fd, 0, SEEK_SET) != 0)
361        goto failed;
362    length = read(fd, device->desc, sizeof(device->desc));
363    D("usb_device_new read returned %d errno %d\n", length, errno);
364    if (length < 0)
365        goto failed;
366
367    strncpy(device->dev_name, dev_name, sizeof(device->dev_name) - 1);
368    device->fd = fd;
369    device->desc_length = length;
370    // assume we are writeable, since usb_device_get_fd will only return writeable fds
371    device->writeable = 1;
372    return device;
373
374failed:
375    close(fd);
376    free(device);
377    return NULL;
378}
379
380static int usb_device_reopen_writeable(struct usb_device *device)
381{
382    if (device->writeable)
383        return 1;
384
385    int fd = open(device->dev_name, O_RDWR);
386    if (fd >= 0) {
387        close(device->fd);
388        device->fd = fd;
389        device->writeable = 1;
390        return 1;
391    }
392    D("usb_device_reopen_writeable failed errno %d\n", errno);
393    return 0;
394}
395
396int usb_device_get_fd(struct usb_device *device)
397{
398    if (!usb_device_reopen_writeable(device))
399        return -1;
400    return device->fd;
401}
402
403const char* usb_device_get_name(struct usb_device *device)
404{
405    return device->dev_name;
406}
407
408int usb_device_get_unique_id(struct usb_device *device)
409{
410    int bus = 0, dev = 0;
411    sscanf(device->dev_name, USB_FS_ID_SCANNER, &bus, &dev);
412    return bus * 1000 + dev;
413}
414
415int usb_device_get_unique_id_from_name(const char* name)
416{
417    int bus = 0, dev = 0;
418    sscanf(name, USB_FS_ID_SCANNER, &bus, &dev);
419    return bus * 1000 + dev;
420}
421
422char* usb_device_get_name_from_unique_id(int id)
423{
424    int bus = id / 1000;
425    int dev = id % 1000;
426    char* result = (char *)calloc(1, strlen(USB_FS_ID_FORMAT));
427    snprintf(result, strlen(USB_FS_ID_FORMAT) - 1, USB_FS_ID_FORMAT, bus, dev);
428    return result;
429}
430
431uint16_t usb_device_get_vendor_id(struct usb_device *device)
432{
433    struct usb_device_descriptor* desc = (struct usb_device_descriptor*)device->desc;
434    return __le16_to_cpu(desc->idVendor);
435}
436
437uint16_t usb_device_get_product_id(struct usb_device *device)
438{
439    struct usb_device_descriptor* desc = (struct usb_device_descriptor*)device->desc;
440    return __le16_to_cpu(desc->idProduct);
441}
442
443const struct usb_device_descriptor* usb_device_get_device_descriptor(struct usb_device *device)
444{
445    return (struct usb_device_descriptor*)device->desc;
446}
447
448char* usb_device_get_string(struct usb_device *device, int id)
449{
450    char string[256];
451    __u16 buffer[128];
452    __u16 languages[128];
453    int i, result;
454    int languageCount = 0;
455
456    string[0] = 0;
457    memset(languages, 0, sizeof(languages));
458
459    // read list of supported languages
460    result = usb_device_control_transfer(device,
461            USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE, USB_REQ_GET_DESCRIPTOR,
462            (USB_DT_STRING << 8) | 0, 0, languages, sizeof(languages), 0);
463    if (result > 0)
464        languageCount = (result - 2) / 2;
465
466    for (i = 1; i <= languageCount; i++) {
467        memset(buffer, 0, sizeof(buffer));
468
469        result = usb_device_control_transfer(device,
470                USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE, USB_REQ_GET_DESCRIPTOR,
471                (USB_DT_STRING << 8) | id, languages[i], buffer, sizeof(buffer), 0);
472        if (result > 0) {
473            int i;
474            // skip first word, and copy the rest to the string, changing shorts to bytes.
475            result /= 2;
476            for (i = 1; i < result; i++)
477                string[i - 1] = buffer[i];
478            string[i - 1] = 0;
479            return strdup(string);
480        }
481    }
482
483    return NULL;
484}
485
486char* usb_device_get_manufacturer_name(struct usb_device *device)
487{
488    struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
489
490    if (desc->iManufacturer)
491        return usb_device_get_string(device, desc->iManufacturer);
492    else
493        return NULL;
494}
495
496char* usb_device_get_product_name(struct usb_device *device)
497{
498    struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
499
500    if (desc->iProduct)
501        return usb_device_get_string(device, desc->iProduct);
502    else
503        return NULL;
504}
505
506char* usb_device_get_serial(struct usb_device *device)
507{
508    struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
509
510    if (desc->iSerialNumber)
511        return usb_device_get_string(device, desc->iSerialNumber);
512    else
513        return NULL;
514}
515
516int usb_device_is_writeable(struct usb_device *device)
517{
518    return device->writeable;
519}
520
521void usb_descriptor_iter_init(struct usb_device *device, struct usb_descriptor_iter *iter)
522{
523    iter->config = device->desc;
524    iter->config_end = device->desc + device->desc_length;
525    iter->curr_desc = device->desc;
526}
527
528struct usb_descriptor_header *usb_descriptor_iter_next(struct usb_descriptor_iter *iter)
529{
530    struct usb_descriptor_header* next;
531    if (iter->curr_desc >= iter->config_end)
532        return NULL;
533    next = (struct usb_descriptor_header*)iter->curr_desc;
534    iter->curr_desc += next->bLength;
535    return next;
536}
537
538int usb_device_claim_interface(struct usb_device *device, unsigned int interface)
539{
540    return ioctl(device->fd, USBDEVFS_CLAIMINTERFACE, &interface);
541}
542
543int usb_device_release_interface(struct usb_device *device, unsigned int interface)
544{
545    return ioctl(device->fd, USBDEVFS_RELEASEINTERFACE, &interface);
546}
547
548int usb_device_connect_kernel_driver(struct usb_device *device,
549        unsigned int interface, int connect)
550{
551    struct usbdevfs_ioctl ctl;
552
553    ctl.ifno = interface;
554    ctl.ioctl_code = (connect ? USBDEVFS_CONNECT : USBDEVFS_DISCONNECT);
555    ctl.data = NULL;
556    return ioctl(device->fd, USBDEVFS_IOCTL, &ctl);
557}
558
559int usb_device_control_transfer(struct usb_device *device,
560                            int requestType,
561                            int request,
562                            int value,
563                            int index,
564                            void* buffer,
565                            int length,
566                            unsigned int timeout)
567{
568    struct usbdevfs_ctrltransfer  ctrl;
569
570    // this usually requires read/write permission
571    if (!usb_device_reopen_writeable(device))
572        return -1;
573
574    memset(&ctrl, 0, sizeof(ctrl));
575    ctrl.bRequestType = requestType;
576    ctrl.bRequest = request;
577    ctrl.wValue = value;
578    ctrl.wIndex = index;
579    ctrl.wLength = length;
580    ctrl.data = buffer;
581    ctrl.timeout = timeout;
582    return ioctl(device->fd, USBDEVFS_CONTROL, &ctrl);
583}
584
585int usb_device_bulk_transfer(struct usb_device *device,
586                            int endpoint,
587                            void* buffer,
588                            int length,
589                            unsigned int timeout)
590{
591    struct usbdevfs_bulktransfer  ctrl;
592
593    // need to limit request size to avoid EINVAL
594    if (length > MAX_USBFS_BUFFER_SIZE)
595        length = MAX_USBFS_BUFFER_SIZE;
596
597    memset(&ctrl, 0, sizeof(ctrl));
598    ctrl.ep = endpoint;
599    ctrl.len = length;
600    ctrl.data = buffer;
601    ctrl.timeout = timeout;
602    return ioctl(device->fd, USBDEVFS_BULK, &ctrl);
603}
604
605struct usb_request *usb_request_new(struct usb_device *dev,
606        const struct usb_endpoint_descriptor *ep_desc)
607{
608    struct usbdevfs_urb *urb = calloc(1, sizeof(struct usbdevfs_urb));
609    if (!urb)
610        return NULL;
611
612    if ((ep_desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_BULK)
613        urb->type = USBDEVFS_URB_TYPE_BULK;
614    else if ((ep_desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) == USB_ENDPOINT_XFER_INT)
615        urb->type = USBDEVFS_URB_TYPE_INTERRUPT;
616    else {
617        D("Unsupported endpoint type %d", ep_desc->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK);
618        free(urb);
619        return NULL;
620    }
621    urb->endpoint = ep_desc->bEndpointAddress;
622
623    struct usb_request *req = calloc(1, sizeof(struct usb_request));
624    if (!req) {
625        free(urb);
626        return NULL;
627    }
628
629    req->dev = dev;
630    req->max_packet_size = __le16_to_cpu(ep_desc->wMaxPacketSize);
631    req->private_data = urb;
632    req->endpoint = urb->endpoint;
633    urb->usercontext = req;
634
635    return req;
636}
637
638void usb_request_free(struct usb_request *req)
639{
640    free(req->private_data);
641    free(req);
642}
643
644int usb_request_queue(struct usb_request *req)
645{
646    struct usbdevfs_urb *urb = (struct usbdevfs_urb*)req->private_data;
647    int res;
648
649    urb->status = -1;
650    urb->buffer = req->buffer;
651    // need to limit request size to avoid EINVAL
652    if (req->buffer_length > MAX_USBFS_BUFFER_SIZE)
653        urb->buffer_length = MAX_USBFS_BUFFER_SIZE;
654    else
655        urb->buffer_length = req->buffer_length;
656
657    do {
658        res = ioctl(req->dev->fd, USBDEVFS_SUBMITURB, urb);
659    } while((res < 0) && (errno == EINTR));
660
661    return res;
662}
663
664struct usb_request *usb_request_wait(struct usb_device *dev)
665{
666    struct usbdevfs_urb *urb = NULL;
667    struct usb_request *req = NULL;
668
669    while (1) {
670        int res = ioctl(dev->fd, USBDEVFS_REAPURB, &urb);
671        D("USBDEVFS_REAPURB returned %d\n", res);
672        if (res < 0) {
673            if(errno == EINTR) {
674                continue;
675            }
676            D("[ reap urb - error ]\n");
677            return NULL;
678        } else {
679            D("[ urb @%p status = %d, actual = %d ]\n",
680                urb, urb->status, urb->actual_length);
681            req = (struct usb_request*)urb->usercontext;
682            req->actual_length = urb->actual_length;
683        }
684        break;
685    }
686    return req;
687}
688
689int usb_request_cancel(struct usb_request *req)
690{
691    struct usbdevfs_urb *urb = ((struct usbdevfs_urb*)req->private_data);
692    return ioctl(req->dev->fd, USBDEVFS_DISCARDURB, &urb);
693}
694
695