usbhost.c revision 7a96ba436c9a2bacc64e712bdb53bd7accc5c3a9
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 LOGD
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
37#include <sys/ioctl.h>
38#include <sys/types.h>
39#include <sys/time.h>
40#include <sys/inotify.h>
41#include <dirent.h>
42#include <fcntl.h>
43#include <errno.h>
44#include <ctype.h>
45#include <pthread.h>
46
47#include <linux/usbdevice_fs.h>
48#include <linux/version.h>
49#if LINUX_VERSION_CODE > KERNEL_VERSION(2, 6, 20)
50#include <linux/usb/ch9.h>
51#else
52#include <linux/usb_ch9.h>
53#endif
54#include <asm/byteorder.h>
55
56#include "usbhost/usbhost.h"
57
58#define USB_FS_DIR "/dev/bus/usb"
59#define USB_FS_ID_SCANNER   "/dev/bus/usb/%d/%d"
60
61
62struct usb_host_context {
63    int fd;
64};
65
66struct usb_device {
67    char dev_name[64];
68    unsigned char desc[256];
69    int desc_length;
70    int fd;
71    int writeable;
72};
73
74struct usb_endpoint
75{
76    struct usb_device *dev;
77    struct usb_endpoint_descriptor  desc;
78    struct usbdevfs_urb urb;
79};
80
81static inline int badname(const char *name)
82{
83    while(*name) {
84        if(!isdigit(*name++)) return 1;
85    }
86    return 0;
87}
88
89/* returns true if one of the callbacks indicates we are done */
90static int find_existing_devices(usb_device_added_cb added_cb,
91                                  usb_device_removed_cb removed_cb,
92                                  void *client_data)
93{
94    char busname[32], devname[32];
95    DIR *busdir , *devdir ;
96    struct dirent *de;
97    int done = 0;
98
99    busdir = opendir(USB_FS_DIR);
100    if(busdir == 0) return 1;
101
102    while ((de = readdir(busdir)) != 0 && !done) {
103        if(badname(de->d_name)) continue;
104
105        snprintf(busname, sizeof busname, "%s/%s", USB_FS_DIR, de->d_name);
106        devdir = opendir(busname);
107        if(devdir == 0) continue;
108
109        while ((de = readdir(devdir)) && !done) {
110            if(badname(de->d_name)) continue;
111
112            snprintf(devname, sizeof devname, "%s/%s", busname, de->d_name);
113            done = added_cb(devname, client_data);
114        } // end of devdir while
115        closedir(devdir);
116    } //end of busdir while
117    closedir(busdir);
118
119    return done;
120}
121
122struct usb_host_context *usb_host_init()
123{
124    struct usb_host_context *context = calloc(1, sizeof(struct usb_host_context));
125    if (!context) {
126        fprintf(stderr, "out of memory in usb_host_context\n");
127        return NULL;
128    }
129    context->fd = inotify_init();
130    if (context->fd < 0) {
131        fprintf(stderr, "inotify_init failed\n");
132        free(context);
133        return NULL;
134    }
135    return context;
136}
137
138void usb_host_cleanup(struct usb_host_context *context)
139{
140    close(context->fd);
141    free(context);
142}
143
144void usb_host_run(struct usb_host_context *context,
145                  usb_device_added_cb added_cb,
146                  usb_device_removed_cb removed_cb,
147                  void *client_data)
148{
149    struct inotify_event* event;
150    char event_buf[512];
151    char path[100];
152    int i, ret, done = 0;
153    int wd, wds[10];
154    int wd_count = sizeof(wds) / sizeof(wds[0]);
155
156    D("Created device discovery thread\n");
157
158    /* watch for files added and deleted within USB_FS_DIR */
159    memset(wds, 0, sizeof(wds));
160    /* watch the root for new subdirectories */
161    wds[0] = inotify_add_watch(context->fd, USB_FS_DIR, IN_CREATE | IN_DELETE);
162    if (wds[0] < 0) {
163        fprintf(stderr, "inotify_add_watch failed\n");
164        return;
165    }
166
167    /* watch existing subdirectories of USB_FS_DIR */
168    for (i = 1; i < wd_count; i++) {
169        snprintf(path, sizeof(path), "%s/%03d", USB_FS_DIR, i);
170        ret = inotify_add_watch(context->fd, path, IN_CREATE | IN_DELETE);
171        if (ret > 0)
172            wds[i] = ret;
173    }
174
175    /* check for existing devices first, after we have inotify set up */
176    done = find_existing_devices(added_cb, removed_cb, client_data);
177
178    while (!done) {
179        ret = read(context->fd, event_buf, sizeof(event_buf));
180        if (ret >= (int)sizeof(struct inotify_event)) {
181            event = (struct inotify_event *)event_buf;
182            wd = event->wd;
183            if (wd == wds[0]) {
184                i = atoi(event->name);
185                snprintf(path, sizeof(path), "%s/%s", USB_FS_DIR, event->name);
186                D("new subdirectory %s: index: %d\n", path, i);
187                if (i > 0 && i < wd_count) {
188                ret = inotify_add_watch(context->fd, path, IN_CREATE | IN_DELETE);
189                if (ret > 0)
190                    wds[i] = ret;
191                }
192            } else {
193                for (i = 1; i < wd_count && !done; i++) {
194                    if (wd == wds[i]) {
195                        snprintf(path, sizeof(path), "%s/%03d/%s", USB_FS_DIR, i, event->name);
196                        if (event->mask == IN_CREATE) {
197                            D("new device %s\n", path);
198                            done = added_cb(path, client_data);
199                        } else if (event->mask == IN_DELETE) {
200                            D("gone device %s\n", path);
201                            done = removed_cb(path, client_data);
202                        }
203                    }
204                }
205            }
206        }
207    }
208}
209
210struct usb_device *usb_device_open(const char *dev_name)
211{
212    struct usb_device *device = calloc(1, sizeof(struct usb_device));
213    int fd, length, did_retry = 0;
214
215    strcpy(device->dev_name, dev_name);
216    device->writeable = 1;
217
218retry:
219    fd = open(dev_name, O_RDWR);
220    if (fd < 0) {
221        /* if we fail, see if have read-only access */
222        fd = open(dev_name, O_RDONLY);
223        D("usb_device_open open returned %d errno %d\n", fd, errno);
224        if (fd < 0 && (errno == EACCES || errno == ENOENT) && !did_retry) {
225            /* work around race condition between inotify and permissions management */
226            sleep(1);
227            did_retry = 1;
228            goto retry;
229        }
230
231        if (fd < 0) goto fail;
232        device->writeable = 0;
233        D("[ usb open read-only %s fd = %d]\n", dev_name, fd);
234    }
235
236    length = read(fd, device->desc, sizeof(device->desc));
237    D("usb_device_open read returned %d errno %d\n", fd, errno);
238    if (length < 0)
239        goto fail;
240
241    device->fd = fd;
242    device->desc_length = length;
243    return device;
244fail:
245    close(fd);
246    free(device);
247    return NULL;
248}
249
250void usb_device_close(struct usb_device *device)
251{
252    close(device->fd);
253    free(device);
254}
255
256const char* usb_device_get_name(struct usb_device *device)
257{
258    return device->dev_name;
259}
260
261int usb_device_get_unique_id(struct usb_device *device)
262{
263    int bus = 0, dev = 0;
264    sscanf(device->dev_name, USB_FS_ID_SCANNER, &bus, &dev);
265    return bus * 1000 + dev;
266}
267
268uint16_t usb_device_get_vendor_id(struct usb_device *device)
269{
270    struct usb_device_descriptor* desc = (struct usb_device_descriptor*)device->desc;
271    return __le16_to_cpu(desc->idVendor);
272}
273
274uint16_t usb_device_get_product_id(struct usb_device *device)
275{
276    struct usb_device_descriptor* desc = (struct usb_device_descriptor*)device->desc;
277    return __le16_to_cpu(desc->idProduct);
278}
279
280char* usb_device_get_string(struct usb_device *device, int id)
281{
282    char string[256];
283    struct usbdevfs_ctrltransfer  ctrl;
284    __u16 buffer[128];
285    __u16 languages[128];
286    int i, result;
287    int languageCount = 0;
288
289    string[0] = 0;
290
291    // reading the string requires read/write permission
292    if (!device->writeable) {
293        int fd = open(device->dev_name, O_RDWR);
294        if (fd > 0) {
295            close(device->fd);
296            device->fd = fd;
297            device->writeable = 1;
298        } else {
299            return NULL;
300        }
301    }
302
303    memset(languages, 0, sizeof(languages));
304    memset(&ctrl, 0, sizeof(ctrl));
305
306    // read list of supported languages
307    ctrl.bRequestType = USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE;
308    ctrl.bRequest = USB_REQ_GET_DESCRIPTOR;
309    ctrl.wValue = (USB_DT_STRING << 8) | 0;
310    ctrl.wIndex = 0;
311    ctrl.wLength = sizeof(languages);
312    ctrl.data = languages;
313
314    result = ioctl(device->fd, USBDEVFS_CONTROL, &ctrl);
315    if (result > 0)
316        languageCount = (result - 2) / 2;
317
318    for (i = 1; i <= languageCount; i++) {
319        memset(buffer, 0, sizeof(buffer));
320        memset(&ctrl, 0, sizeof(ctrl));
321
322        ctrl.bRequestType = USB_DIR_IN|USB_TYPE_STANDARD|USB_RECIP_DEVICE;
323        ctrl.bRequest = USB_REQ_GET_DESCRIPTOR;
324        ctrl.wValue = (USB_DT_STRING << 8) | id;
325        ctrl.wIndex = languages[i];
326        ctrl.wLength = sizeof(buffer);
327        ctrl.data = buffer;
328
329        result = ioctl(device->fd, USBDEVFS_CONTROL, &ctrl);
330        if (result > 0) {
331            int i;
332            // skip first word, and copy the rest to the string, changing shorts to bytes.
333            result /= 2;
334            for (i = 1; i < result; i++)
335                string[i - 1] = buffer[i];
336            string[i - 1] = 0;
337            return strdup(string);
338        }
339    }
340
341    return NULL;
342}
343
344char* usb_device_get_manufacturer_name(struct usb_device *device)
345{
346    struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
347
348    if (desc->iManufacturer)
349        return usb_device_get_string(device, desc->iManufacturer);
350    else
351        return NULL;
352}
353
354char* usb_device_get_product_name(struct usb_device *device)
355{
356    struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
357
358    if (desc->iProduct)
359        return usb_device_get_string(device, desc->iProduct);
360    else
361        return NULL;
362}
363
364char* usb_device_get_serial(struct usb_device *device)
365{
366    struct usb_device_descriptor *desc = (struct usb_device_descriptor *)device->desc;
367
368    if (desc->iSerialNumber)
369        return usb_device_get_string(device, desc->iSerialNumber);
370    else
371        return NULL;
372}
373
374int usb_device_is_writeable(struct usb_device *device)
375{
376    return device->writeable;
377}
378
379void usb_descriptor_iter_init(struct usb_device *device, struct usb_descriptor_iter *iter)
380{
381    iter->config = device->desc;
382    iter->config_end = device->desc + device->desc_length;
383    iter->curr_desc = device->desc;
384}
385
386struct usb_descriptor_header *usb_descriptor_iter_next(struct usb_descriptor_iter *iter)
387{
388    struct usb_descriptor_header* next;
389    if (iter->curr_desc >= iter->config_end)
390        return NULL;
391    next = (struct usb_descriptor_header*)iter->curr_desc;
392    iter->curr_desc += next->bLength;
393    return next;
394}
395
396int usb_device_claim_interface(struct usb_device *device, unsigned int interface)
397{
398    return ioctl(device->fd, USBDEVFS_CLAIMINTERFACE, &interface);
399}
400
401int usb_device_release_interface(struct usb_device *device, unsigned int interface)
402{
403    return ioctl(device->fd, USBDEVFS_RELEASEINTERFACE, &interface);
404}
405
406struct usb_endpoint *usb_endpoint_open(struct usb_device *dev,
407        const struct usb_endpoint_descriptor *desc)
408{
409    struct usb_endpoint *ep = calloc(1, sizeof(struct usb_endpoint));
410    memcpy(&ep->desc, desc, sizeof(ep->desc));
411    ep->dev = dev;
412    return ep;
413}
414
415void usb_endpoint_close(struct usb_endpoint *ep)
416{
417    // cancel IO here?
418    free(ep);
419}
420
421int usb_endpoint_queue(struct usb_endpoint *ep, void *data, int len)
422{
423    struct usbdevfs_urb *urb = &ep->urb;
424    int res;
425
426    D("usb_endpoint_queue\n");
427    memset(urb, 0, sizeof(*urb));
428    urb->type = USBDEVFS_URB_TYPE_BULK;
429    urb->endpoint = ep->desc.bEndpointAddress;
430    urb->status = -1;
431    urb->buffer = data;
432    urb->buffer_length = len;
433
434    do {
435        res = ioctl(ep->dev->fd, USBDEVFS_SUBMITURB, urb);
436    } while((res < 0) && (errno == EINTR));
437
438    return res;
439}
440
441int usb_endpoint_wait(struct usb_device *dev, int *out_ep_num)
442{
443    struct usbdevfs_urb *out = NULL;
444    int res;
445
446    while (1) {
447        res = ioctl(dev->fd, USBDEVFS_REAPURB, &out);
448        D("USBDEVFS_REAPURB returned %d\n", res);
449        if (res < 0) {
450            if(errno == EINTR) {
451                continue;
452            }
453            D("[ reap urb - error ]\n");
454            *out_ep_num = -1;
455        } else {
456            D("[ urb @%p status = %d, actual = %d ]\n",
457                out, out->status, out->actual_length);
458            res = out->actual_length;
459            *out_ep_num = out->endpoint;
460        }
461        break;
462    }
463    return res;
464}
465
466int usb_endpoint_cancel(struct usb_endpoint *ep)
467{
468    return ioctl(ep->dev->fd, USBDEVFS_DISCARDURB, &ep->urb);
469}
470
471struct usb_device *usb_endpoint_get_device(struct usb_endpoint *ep)
472{
473    return ep->dev;
474}
475
476int usb_endpoint_number(struct usb_endpoint *ep)
477{
478    return ep->desc.bEndpointAddress;
479}
480
481int usb_endpoint_max_packet(struct usb_endpoint *ep)
482{
483    return __le16_to_cpu(ep->desc.wMaxPacketSize);
484}
485
486