qemu/hw/usb/host-bsd.c
<<
>>
Prefs
   1/*
   2 * BSD host USB redirector
   3 *
   4 * Copyright (c) 2006 Lonnie Mendez
   5 * Portions of code and concepts borrowed from
   6 * usb-linux.c and libusb's bsd.c and are copyright their respective owners.
   7 *
   8 * Permission is hereby granted, free of charge, to any person obtaining a copy
   9 * of this software and associated documentation files (the "Software"), to deal
  10 * in the Software without restriction, including without limitation the rights
  11 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  12 * copies of the Software, and to permit persons to whom the Software is
  13 * furnished to do so, subject to the following conditions:
  14 *
  15 * The above copyright notice and this permission notice shall be included in
  16 * all copies or substantial portions of the Software.
  17 *
  18 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  19 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  20 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
  21 * THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  22 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  23 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  24 * THE SOFTWARE.
  25 */
  26
  27#include "qemu-common.h"
  28#include "monitor/monitor.h"
  29#include "hw/usb.h"
  30
  31/* usb.h declares these */
  32#undef USB_SPEED_HIGH
  33#undef USB_SPEED_FULL
  34#undef USB_SPEED_LOW
  35
  36#include <sys/ioctl.h>
  37#ifndef __DragonFly__
  38#include <dev/usb/usb.h>
  39#else
  40#include <bus/usb/usb.h>
  41#endif
  42
  43/* This value has maximum potential at 16.
  44 * You should also set hw.usb.debug to gain
  45 * more detailed view.
  46 */
  47//#define DEBUG
  48#define UGEN_DEBUG_LEVEL 0
  49
  50
  51typedef int USBScanFunc(void *opaque, int bus_num, int addr, int class_id,
  52                        int vendor_id, int product_id,
  53                        const char *product_name, int speed);
  54static int usb_host_find_device(int *pbus_num, int *paddr,
  55                                const char *devname);
  56
  57typedef struct USBHostDevice {
  58    USBDevice dev;
  59    int ep_fd[USB_MAX_ENDPOINTS];
  60    int devfd;
  61    char devpath[32];
  62} USBHostDevice;
  63
  64
  65static int ensure_ep_open(USBHostDevice *dev, int ep, int mode)
  66{
  67    char buf[32];
  68    int fd;
  69
  70    /* Get the address for this endpoint */
  71    ep = UE_GET_ADDR(ep);
  72
  73    if (dev->ep_fd[ep] < 0) {
  74#if defined(__FreeBSD__) || defined(__DragonFly__)
  75        snprintf(buf, sizeof(buf) - 1, "%s.%d", dev->devpath, ep);
  76#else
  77        snprintf(buf, sizeof(buf) - 1, "%s.%02d", dev->devpath, ep);
  78#endif
  79        /* Try to open it O_RDWR first for those devices which have in and out
  80         * endpoints with the same address (eg 0x02 and 0x82)
  81         */
  82        fd = open(buf, O_RDWR);
  83        if (fd < 0 && errno == ENXIO)
  84            fd = open(buf, mode);
  85        if (fd < 0) {
  86#ifdef DEBUG
  87            printf("ensure_ep_open: failed to open device endpoint %s: %s\n",
  88                   buf, strerror(errno));
  89#endif
  90        }
  91        dev->ep_fd[ep] = fd;
  92    }
  93
  94    return dev->ep_fd[ep];
  95}
  96
  97static void ensure_eps_closed(USBHostDevice *dev)
  98{
  99    int epnum = 1;
 100
 101    if (!dev)
 102        return;
 103
 104    while (epnum < USB_MAX_ENDPOINTS) {
 105        if (dev->ep_fd[epnum] >= 0) {
 106            close(dev->ep_fd[epnum]);
 107            dev->ep_fd[epnum] = -1;
 108        }
 109        epnum++;
 110    }
 111}
 112
 113static void usb_host_handle_reset(USBDevice *dev)
 114{
 115#if 0
 116    USBHostDevice *s = (USBHostDevice *)dev;
 117#endif
 118}
 119
 120/* XXX:
 121 * -check device states against transfer requests
 122 *  and return appropriate response
 123 */
 124static void usb_host_handle_control(USBDevice *dev,
 125                                   USBPacket *p,
 126                                   int request,
 127                                   int value,
 128                                   int index,
 129                                   int length,
 130                                   uint8_t *data)
 131{
 132    USBHostDevice *s = (USBHostDevice *)dev;
 133    struct usb_ctl_request req;
 134    struct usb_alt_interface aiface;
 135    int ret, timeout = 50;
 136
 137    if ((request >> 8) == UT_WRITE_DEVICE &&
 138        (request & 0xff) == UR_SET_ADDRESS) {
 139
 140        /* specific SET_ADDRESS support */
 141        dev->addr = value;
 142    } else if ((request >> 8) == UT_WRITE_DEVICE &&
 143               (request & 0xff) == UR_SET_CONFIG) {
 144
 145        ensure_eps_closed(s); /* can't do this without all eps closed */
 146
 147        ret = ioctl(s->devfd, USB_SET_CONFIG, &value);
 148        if (ret < 0) {
 149#ifdef DEBUG
 150            printf("handle_control: failed to set configuration - %s\n",
 151                   strerror(errno));
 152#endif
 153            p->status = USB_RET_STALL;
 154        }
 155    } else if ((request >> 8) == UT_WRITE_INTERFACE &&
 156               (request & 0xff) == UR_SET_INTERFACE) {
 157
 158        aiface.uai_interface_index = index;
 159        aiface.uai_alt_no = value;
 160
 161        ensure_eps_closed(s); /* can't do this without all eps closed */
 162        ret = ioctl(s->devfd, USB_SET_ALTINTERFACE, &aiface);
 163        if (ret < 0) {
 164#ifdef DEBUG
 165            printf("handle_control: failed to set alternate interface - %s\n",
 166                   strerror(errno));
 167#endif
 168            p->status = USB_RET_STALL;
 169        }
 170    } else {
 171        req.ucr_request.bmRequestType = request >> 8;
 172        req.ucr_request.bRequest = request & 0xff;
 173        USETW(req.ucr_request.wValue, value);
 174        USETW(req.ucr_request.wIndex, index);
 175        USETW(req.ucr_request.wLength, length);
 176        req.ucr_data = data;
 177        req.ucr_flags = USBD_SHORT_XFER_OK;
 178
 179        ret = ioctl(s->devfd, USB_SET_TIMEOUT, &timeout);
 180#if defined(__NetBSD__) || defined(__OpenBSD__)
 181        if (ret < 0 && errno != EINVAL) {
 182#else
 183        if (ret < 0) {
 184#endif
 185#ifdef DEBUG
 186            printf("handle_control: setting timeout failed - %s\n",
 187                   strerror(errno));
 188#endif
 189        }
 190
 191        ret = ioctl(s->devfd, USB_DO_REQUEST, &req);
 192        /* ugen returns EIO for usbd_do_request_ no matter what
 193         * happens with the transfer */
 194        if (ret < 0) {
 195#ifdef DEBUG
 196            printf("handle_control: error after request - %s\n",
 197                   strerror(errno));
 198#endif
 199            p->status = USB_RET_NAK; /* STALL */
 200        } else {
 201            p->actual_length = req.ucr_actlen;
 202        }
 203    }
 204}
 205
 206static void usb_host_handle_data(USBDevice *dev, USBPacket *p)
 207{
 208    USBHostDevice *s = (USBHostDevice *)dev;
 209    int ret, fd, mode;
 210    int one = 1, shortpacket = 0, timeout = 50;
 211    sigset_t new_mask, old_mask;
 212    uint8_t devep = p->ep->nr;
 213
 214    /* protect data transfers from SIGALRM signal */
 215    sigemptyset(&new_mask);
 216    sigaddset(&new_mask, SIGALRM);
 217    sigprocmask(SIG_BLOCK, &new_mask, &old_mask);
 218
 219    if (p->pid == USB_TOKEN_IN) {
 220        devep |= 0x80;
 221        mode = O_RDONLY;
 222        shortpacket = 1;
 223    } else {
 224        mode = O_WRONLY;
 225    }
 226
 227    fd = ensure_ep_open(s, devep, mode);
 228    if (fd < 0) {
 229        sigprocmask(SIG_SETMASK, &old_mask, NULL);
 230        p->status = USB_RET_NODEV;
 231        return;
 232    }
 233
 234    if (ioctl(fd, USB_SET_TIMEOUT, &timeout) < 0) {
 235#ifdef DEBUG
 236        printf("handle_data: failed to set timeout - %s\n",
 237               strerror(errno));
 238#endif
 239    }
 240
 241    if (shortpacket) {
 242        if (ioctl(fd, USB_SET_SHORT_XFER, &one) < 0) {
 243#ifdef DEBUG
 244            printf("handle_data: failed to set short xfer mode - %s\n",
 245                   strerror(errno));
 246#endif
 247            sigprocmask(SIG_SETMASK, &old_mask, NULL);
 248        }
 249    }
 250
 251    if (p->pid == USB_TOKEN_IN)
 252        ret = readv(fd, p->iov.iov, p->iov.niov);
 253    else
 254        ret = writev(fd, p->iov.iov, p->iov.niov);
 255
 256    sigprocmask(SIG_SETMASK, &old_mask, NULL);
 257
 258    if (ret < 0) {
 259#ifdef DEBUG
 260        printf("handle_data: error after %s data - %s\n",
 261               pid == USB_TOKEN_IN ? "reading" : "writing", strerror(errno));
 262#endif
 263        switch(errno) {
 264        case ETIMEDOUT:
 265        case EINTR:
 266            p->status = USB_RET_NAK;
 267            break;
 268        default:
 269            p->status = USB_RET_STALL;
 270        }
 271    } else {
 272        p->actual_length = ret;
 273    }
 274}
 275
 276static void usb_host_handle_destroy(USBDevice *opaque)
 277{
 278    USBHostDevice *s = (USBHostDevice *)opaque;
 279    int i;
 280
 281    for (i = 0; i < USB_MAX_ENDPOINTS; i++)
 282        if (s->ep_fd[i] >= 0)
 283            close(s->ep_fd[i]);
 284
 285    if (s->devfd < 0)
 286        return;
 287
 288    close(s->devfd);
 289
 290    g_free(s);
 291}
 292
 293static int usb_host_initfn(USBDevice *dev)
 294{
 295    dev->flags |= (1 << USB_DEV_FLAG_IS_HOST);
 296    return 0;
 297}
 298
 299USBDevice *usb_host_device_open(USBBus *guest_bus, const char *devname)
 300{
 301    struct usb_device_info bus_info, dev_info;
 302    USBDevice *d = NULL, *ret = NULL;
 303    USBHostDevice *dev;
 304    char ctlpath[PATH_MAX + 1];
 305    char buspath[PATH_MAX + 1];
 306    int bfd, dfd, bus, address, i;
 307    int ugendebug = UGEN_DEBUG_LEVEL;
 308
 309    if (usb_host_find_device(&bus, &address, devname) < 0) {
 310        goto fail;
 311    }
 312
 313    snprintf(buspath, PATH_MAX, "/dev/usb%d", bus);
 314
 315    bfd = open(buspath, O_RDWR);
 316    if (bfd < 0) {
 317#ifdef DEBUG
 318        printf("usb_host_device_open: failed to open usb bus - %s\n",
 319               strerror(errno));
 320#endif
 321        goto fail;
 322    }
 323
 324    bus_info.udi_addr = address;
 325    if (ioctl(bfd, USB_DEVICEINFO, &bus_info) < 0) {
 326#ifdef DEBUG
 327        printf("usb_host_device_open: failed to grab bus information - %s\n",
 328               strerror(errno));
 329#endif
 330        goto fail_bfd;
 331    }
 332
 333#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
 334    snprintf(ctlpath, PATH_MAX, "/dev/%s", bus_info.udi_devnames[0]);
 335#else
 336    snprintf(ctlpath, PATH_MAX, "/dev/%s.00", bus_info.udi_devnames[0]);
 337#endif
 338
 339    dfd  = open(ctlpath, O_RDWR);
 340    if (dfd < 0) {
 341        dfd = open(ctlpath, O_RDONLY);
 342        if (dfd < 0) {
 343#ifdef DEBUG
 344            printf("usb_host_device_open: failed to open usb device %s - %s\n",
 345                   ctlpath, strerror(errno));
 346#endif
 347        }
 348        goto fail_dfd;
 349    }
 350
 351    if (ioctl(dfd, USB_GET_DEVICEINFO, &dev_info) < 0) {
 352#ifdef DEBUG
 353        printf("usb_host_device_open: failed to grab device info - %s\n",
 354               strerror(errno));
 355#endif
 356        goto fail_dfd;
 357    }
 358
 359    d = usb_create(guest_bus, "usb-host");
 360    dev = DO_UPCAST(USBHostDevice, dev, d);
 361
 362    if (dev_info.udi_speed == 1) {
 363        dev->dev.speed = USB_SPEED_LOW - 1;
 364        dev->dev.speedmask = USB_SPEED_MASK_LOW;
 365    } else {
 366        dev->dev.speed = USB_SPEED_FULL - 1;
 367        dev->dev.speedmask = USB_SPEED_MASK_FULL;
 368    }
 369
 370    if (strncmp(dev_info.udi_product, "product", 7) != 0) {
 371        pstrcpy(dev->dev.product_desc, sizeof(dev->dev.product_desc),
 372                dev_info.udi_product);
 373    } else {
 374        snprintf(dev->dev.product_desc, sizeof(dev->dev.product_desc),
 375                 "host:%s", devname);
 376    }
 377
 378    pstrcpy(dev->devpath, sizeof(dev->devpath), "/dev/");
 379    pstrcat(dev->devpath, sizeof(dev->devpath), dev_info.udi_devnames[0]);
 380
 381    /* Mark the endpoints as not yet open */
 382    for (i = 0; i < USB_MAX_ENDPOINTS; i++) {
 383        dev->ep_fd[i] = -1;
 384    }
 385
 386    ioctl(dfd, USB_SETDEBUG, &ugendebug);
 387
 388    ret = (USBDevice *)dev;
 389
 390fail_dfd:
 391    close(dfd);
 392fail_bfd:
 393    close(bfd);
 394fail:
 395    return ret;
 396}
 397
 398static void usb_host_class_initfn(ObjectClass *klass, void *data)
 399{
 400    USBDeviceClass *uc = USB_DEVICE_CLASS(klass);
 401
 402    uc->product_desc   = "USB Host Device";
 403    uc->init           = usb_host_initfn;
 404    uc->handle_reset   = usb_host_handle_reset;
 405    uc->handle_control = usb_host_handle_control;
 406    uc->handle_data    = usb_host_handle_data;
 407    uc->handle_destroy = usb_host_handle_destroy;
 408}
 409
 410static const TypeInfo usb_host_dev_info = {
 411    .name          = "usb-host",
 412    .parent        = TYPE_USB_DEVICE,
 413    .instance_size = sizeof(USBHostDevice),
 414    .class_init    = usb_host_class_initfn,
 415};
 416
 417static void usb_host_register_types(void)
 418{
 419    type_register_static(&usb_host_dev_info);
 420}
 421
 422type_init(usb_host_register_types)
 423
 424static int usb_host_scan(void *opaque, USBScanFunc *func)
 425{
 426    struct usb_device_info bus_info;
 427    struct usb_device_info dev_info;
 428    uint16_t vendor_id, product_id, class_id, speed;
 429    int bfd, dfd, bus, address;
 430    char busbuf[20], devbuf[20], product_name[256];
 431    int ret = 0;
 432
 433    for (bus = 0; bus < 10; bus++) {
 434
 435        snprintf(busbuf, sizeof(busbuf) - 1, "/dev/usb%d", bus);
 436        bfd = open(busbuf, O_RDWR);
 437        if (bfd < 0)
 438            continue;
 439
 440        for (address = 1; address < 127; address++) {
 441
 442            bus_info.udi_addr = address;
 443            if (ioctl(bfd, USB_DEVICEINFO, &bus_info) < 0)
 444                continue;
 445
 446            /* only list devices that can be used by generic layer */
 447            if (strncmp(bus_info.udi_devnames[0], "ugen", 4) != 0)
 448                continue;
 449
 450#if defined(__FreeBSD__) || defined(__FreeBSD_kernel__) || defined(__DragonFly__)
 451            snprintf(devbuf, sizeof(devbuf) - 1, "/dev/%s", bus_info.udi_devnames[0]);
 452#else
 453            snprintf(devbuf, sizeof(devbuf) - 1, "/dev/%s.00", bus_info.udi_devnames[0]);
 454#endif
 455
 456            dfd = open(devbuf, O_RDONLY);
 457            if (dfd < 0) {
 458#ifdef DEBUG
 459                printf("usb_host_scan: couldn't open device %s - %s\n", devbuf,
 460                       strerror(errno));
 461#endif
 462                continue;
 463            }
 464
 465            if (ioctl(dfd, USB_GET_DEVICEINFO, &dev_info) < 0)
 466                printf("usb_host_scan: couldn't get device information for %s - %s\n",
 467                       devbuf, strerror(errno));
 468
 469            /* XXX: might need to fixup endianness of word values before copying over */
 470
 471            vendor_id = dev_info.udi_vendorNo;
 472            product_id = dev_info.udi_productNo;
 473            class_id = dev_info.udi_class;
 474            speed = dev_info.udi_speed;
 475
 476            if (strncmp(dev_info.udi_product, "product", 7) != 0)
 477                pstrcpy(product_name, sizeof(product_name),
 478                        dev_info.udi_product);
 479            else
 480                product_name[0] = '\0';
 481
 482            ret = func(opaque, bus, address, class_id, vendor_id,
 483                       product_id, product_name, speed);
 484
 485            close(dfd);
 486
 487            if (ret)
 488                goto the_end;
 489        }
 490
 491        close(bfd);
 492    }
 493
 494the_end:
 495    return ret;
 496}
 497
 498typedef struct FindDeviceState {
 499    int vendor_id;
 500    int product_id;
 501    int bus_num;
 502    int addr;
 503} FindDeviceState;
 504
 505static int usb_host_find_device_scan(void *opaque, int bus_num, int addr,
 506                                     int class_id,
 507                                     int vendor_id, int product_id,
 508                                     const char *product_name, int speed)
 509{
 510    FindDeviceState *s = opaque;
 511    if (vendor_id == s->vendor_id &&
 512        product_id == s->product_id) {
 513        s->bus_num = bus_num;
 514        s->addr = addr;
 515        return 1;
 516     } else {
 517        return 0;
 518     }
 519}
 520
 521
 522/* the syntax is :
 523   'bus.addr' (decimal numbers) or
 524   'vendor_id:product_id' (hexa numbers) */
 525static int usb_host_find_device(int *pbus_num, int *paddr,
 526                                const char *devname)
 527{
 528    const char *p;
 529    int ret;
 530    FindDeviceState fs;
 531
 532    p = strchr(devname, '.');
 533    if (p) {
 534        *pbus_num = strtoul(devname, NULL, 0);
 535        *paddr = strtoul(p + 1, NULL, 0);
 536        return 0;
 537    }
 538    p = strchr(devname, ':');
 539    if (p) {
 540        fs.vendor_id = strtoul(devname, NULL, 16);
 541        fs.product_id = strtoul(p + 1, NULL, 16);
 542        ret = usb_host_scan(&fs, usb_host_find_device_scan);
 543        if (ret) {
 544            *pbus_num = fs.bus_num;
 545            *paddr = fs.addr;
 546            return 0;
 547        }
 548     }
 549     return -1;
 550}
 551
 552/**********************/
 553/* USB host device info */
 554
 555struct usb_class_info {
 556    int class;
 557    const char *class_name;
 558};
 559
 560static const struct usb_class_info usb_class_info[] = {
 561    { USB_CLASS_AUDIO, "Audio"},
 562    { USB_CLASS_COMM, "Communication"},
 563    { USB_CLASS_HID, "HID"},
 564    { USB_CLASS_HUB, "Hub" },
 565    { USB_CLASS_PHYSICAL, "Physical" },
 566    { USB_CLASS_PRINTER, "Printer" },
 567    { USB_CLASS_MASS_STORAGE, "Storage" },
 568    { USB_CLASS_CDC_DATA, "Data" },
 569    { USB_CLASS_APP_SPEC, "Application Specific" },
 570    { USB_CLASS_VENDOR_SPEC, "Vendor Specific" },
 571    { USB_CLASS_STILL_IMAGE, "Still Image" },
 572    { USB_CLASS_CSCID, "Smart Card" },
 573    { USB_CLASS_CONTENT_SEC, "Content Security" },
 574    { -1, NULL }
 575};
 576
 577static const char *usb_class_str(uint8_t class)
 578{
 579    const struct usb_class_info *p;
 580    for (p = usb_class_info; p->class != -1; p++) {
 581        if (p->class == class)
 582            break;
 583    }
 584    return p->class_name;
 585}
 586
 587static void usb_info_device(Monitor *mon, int bus_num, int addr, int class_id,
 588                            int vendor_id, int product_id,
 589                            const char *product_name,
 590                            int speed)
 591{
 592    const char *class_str, *speed_str;
 593
 594    switch(speed) {
 595    case USB_SPEED_LOW:
 596        speed_str = "1.5";
 597        break;
 598    case USB_SPEED_FULL:
 599        speed_str = "12";
 600        break;
 601    case USB_SPEED_HIGH:
 602        speed_str = "480";
 603        break;
 604    default:
 605        speed_str = "?";
 606        break;
 607    }
 608
 609    monitor_printf(mon, "  Device %d.%d, speed %s Mb/s\n",
 610                   bus_num, addr, speed_str);
 611    class_str = usb_class_str(class_id);
 612    if (class_str)
 613        monitor_printf(mon, "    %s:", class_str);
 614    else
 615        monitor_printf(mon, "    Class %02x:", class_id);
 616    monitor_printf(mon, " USB device %04x:%04x", vendor_id, product_id);
 617    if (product_name[0] != '\0')
 618        monitor_printf(mon, ", %s", product_name);
 619    monitor_printf(mon, "\n");
 620}
 621
 622static int usb_host_info_device(void *opaque,
 623                                int bus_num, int addr,
 624                                int class_id,
 625                                int vendor_id, int product_id,
 626                                const char *product_name,
 627                                int speed)
 628{
 629    Monitor *mon = opaque;
 630
 631    usb_info_device(mon, bus_num, addr, class_id, vendor_id, product_id,
 632                    product_name, speed);
 633    return 0;
 634}
 635
 636void usb_host_info(Monitor *mon, const QDict *qdict)
 637{
 638    usb_host_scan(mon, usb_host_info_device);
 639}
 640