linux/drivers/usb/gadget/printer.c
<<
>>
Prefs
   1/*
   2 * printer.c -- Printer gadget driver
   3 *
   4 * Copyright (C) 2003-2005 David Brownell
   5 * Copyright (C) 2006 Craig W. Nadler
   6 *
   7 * This program is free software; you can redistribute it and/or modify
   8 * it under the terms of the GNU General Public License as published by
   9 * the Free Software Foundation; either version 2 of the License, or
  10 * (at your option) any later version.
  11 */
  12
  13#include <linux/module.h>
  14#include <linux/kernel.h>
  15#include <linux/delay.h>
  16#include <linux/ioport.h>
  17#include <linux/sched.h>
  18#include <linux/slab.h>
  19#include <linux/mutex.h>
  20#include <linux/errno.h>
  21#include <linux/init.h>
  22#include <linux/timer.h>
  23#include <linux/list.h>
  24#include <linux/interrupt.h>
  25#include <linux/utsname.h>
  26#include <linux/device.h>
  27#include <linux/moduleparam.h>
  28#include <linux/fs.h>
  29#include <linux/poll.h>
  30#include <linux/types.h>
  31#include <linux/ctype.h>
  32#include <linux/cdev.h>
  33
  34#include <asm/byteorder.h>
  35#include <linux/io.h>
  36#include <linux/irq.h>
  37#include <asm/system.h>
  38#include <linux/uaccess.h>
  39#include <asm/unaligned.h>
  40
  41#include <linux/usb/ch9.h>
  42#include <linux/usb/gadget.h>
  43#include <linux/usb/g_printer.h>
  44
  45#include "gadget_chips.h"
  46
  47
  48/*
  49 * Kbuild is not very cooperative with respect to linking separately
  50 * compiled library objects into one module.  So for now we won't use
  51 * separate compilation ... ensuring init/exit sections work to shrink
  52 * the runtime footprint, and giving us at least some parts of what
  53 * a "gcc --combine ... part1.c part2.c part3.c ... " build would.
  54 */
  55#include "usbstring.c"
  56#include "config.c"
  57#include "epautoconf.c"
  58
  59/*-------------------------------------------------------------------------*/
  60
  61#define DRIVER_DESC             "Printer Gadget"
  62#define DRIVER_VERSION          "2007 OCT 06"
  63
  64static DEFINE_MUTEX(printer_mutex);
  65static const char shortname [] = "printer";
  66static const char driver_desc [] = DRIVER_DESC;
  67
  68static dev_t g_printer_devno;
  69
  70static struct class *usb_gadget_class;
  71
  72/*-------------------------------------------------------------------------*/
  73
  74struct printer_dev {
  75        spinlock_t              lock;           /* lock this structure */
  76        /* lock buffer lists during read/write calls */
  77        struct mutex            lock_printer_io;
  78        struct usb_gadget       *gadget;
  79        struct usb_request      *req;           /* for control responses */
  80        u8                      config;
  81        s8                      interface;
  82        struct usb_ep           *in_ep, *out_ep;
  83
  84        struct list_head        rx_reqs;        /* List of free RX structs */
  85        struct list_head        rx_reqs_active; /* List of Active RX xfers */
  86        struct list_head        rx_buffers;     /* List of completed xfers */
  87        /* wait until there is data to be read. */
  88        wait_queue_head_t       rx_wait;
  89        struct list_head        tx_reqs;        /* List of free TX structs */
  90        struct list_head        tx_reqs_active; /* List of Active TX xfers */
  91        /* Wait until there are write buffers available to use. */
  92        wait_queue_head_t       tx_wait;
  93        /* Wait until all write buffers have been sent. */
  94        wait_queue_head_t       tx_flush_wait;
  95        struct usb_request      *current_rx_req;
  96        size_t                  current_rx_bytes;
  97        u8                      *current_rx_buf;
  98        u8                      printer_status;
  99        u8                      reset_printer;
 100        struct cdev             printer_cdev;
 101        struct device           *pdev;
 102        u8                      printer_cdev_open;
 103        wait_queue_head_t       wait;
 104};
 105
 106static struct printer_dev usb_printer_gadget;
 107
 108/*-------------------------------------------------------------------------*/
 109
 110/* DO NOT REUSE THESE IDs with a protocol-incompatible driver!!  Ever!!
 111 * Instead:  allocate your own, using normal USB-IF procedures.
 112 */
 113
 114/* Thanks to NetChip Technologies for donating this product ID.
 115 */
 116#define PRINTER_VENDOR_NUM      0x0525          /* NetChip */
 117#define PRINTER_PRODUCT_NUM     0xa4a8          /* Linux-USB Printer Gadget */
 118
 119/* Some systems will want different product identifiers published in the
 120 * device descriptor, either numbers or strings or both.  These string
 121 * parameters are in UTF-8 (superset of ASCII's 7 bit characters).
 122 */
 123
 124static ushort idVendor;
 125module_param(idVendor, ushort, S_IRUGO);
 126MODULE_PARM_DESC(idVendor, "USB Vendor ID");
 127
 128static ushort idProduct;
 129module_param(idProduct, ushort, S_IRUGO);
 130MODULE_PARM_DESC(idProduct, "USB Product ID");
 131
 132static ushort bcdDevice;
 133module_param(bcdDevice, ushort, S_IRUGO);
 134MODULE_PARM_DESC(bcdDevice, "USB Device version (BCD)");
 135
 136static char *iManufacturer;
 137module_param(iManufacturer, charp, S_IRUGO);
 138MODULE_PARM_DESC(iManufacturer, "USB Manufacturer string");
 139
 140static char *iProduct;
 141module_param(iProduct, charp, S_IRUGO);
 142MODULE_PARM_DESC(iProduct, "USB Product string");
 143
 144static char *iSerialNum;
 145module_param(iSerialNum, charp, S_IRUGO);
 146MODULE_PARM_DESC(iSerialNum, "1");
 147
 148static char *iPNPstring;
 149module_param(iPNPstring, charp, S_IRUGO);
 150MODULE_PARM_DESC(iPNPstring, "MFG:linux;MDL:g_printer;CLS:PRINTER;SN:1;");
 151
 152/* Number of requests to allocate per endpoint, not used for ep0. */
 153static unsigned qlen = 10;
 154module_param(qlen, uint, S_IRUGO|S_IWUSR);
 155
 156#define QLEN    qlen
 157
 158#ifdef CONFIG_USB_GADGET_DUALSPEED
 159#define DEVSPEED        USB_SPEED_HIGH
 160#else   /* full speed (low speed doesn't do bulk) */
 161#define DEVSPEED        USB_SPEED_FULL
 162#endif
 163
 164/*-------------------------------------------------------------------------*/
 165
 166#define xprintk(d, level, fmt, args...) \
 167        printk(level "%s: " fmt, DRIVER_DESC, ## args)
 168
 169#ifdef DEBUG
 170#define DBG(dev, fmt, args...) \
 171        xprintk(dev, KERN_DEBUG, fmt, ## args)
 172#else
 173#define DBG(dev, fmt, args...) \
 174        do { } while (0)
 175#endif /* DEBUG */
 176
 177#ifdef VERBOSE
 178#define VDBG(dev, fmt, args...) \
 179        xprintk(dev, KERN_DEBUG, fmt, ## args)
 180#else
 181#define VDBG(dev, fmt, args...) \
 182        do { } while (0)
 183#endif /* VERBOSE */
 184
 185#define ERROR(dev, fmt, args...) \
 186        xprintk(dev, KERN_ERR, fmt, ## args)
 187#define WARNING(dev, fmt, args...) \
 188        xprintk(dev, KERN_WARNING, fmt, ## args)
 189#define INFO(dev, fmt, args...) \
 190        xprintk(dev, KERN_INFO, fmt, ## args)
 191
 192/*-------------------------------------------------------------------------*/
 193
 194/* USB DRIVER HOOKUP (to the hardware driver, below us), mostly
 195 * ep0 implementation:  descriptors, config management, setup().
 196 * also optional class-specific notification interrupt transfer.
 197 */
 198
 199/*
 200 * DESCRIPTORS ... most are static, but strings and (full) configuration
 201 * descriptors are built on demand.
 202 */
 203
 204#define STRING_MANUFACTURER             1
 205#define STRING_PRODUCT                  2
 206#define STRING_SERIALNUM                3
 207
 208/* holds our biggest descriptor */
 209#define USB_DESC_BUFSIZE                256
 210#define USB_BUFSIZE                     8192
 211
 212/* This device advertises one configuration. */
 213#define DEV_CONFIG_VALUE                1
 214#define PRINTER_INTERFACE               0
 215
 216static struct usb_device_descriptor device_desc = {
 217        .bLength =              sizeof device_desc,
 218        .bDescriptorType =      USB_DT_DEVICE,
 219        .bcdUSB =               cpu_to_le16(0x0200),
 220        .bDeviceClass =         USB_CLASS_PER_INTERFACE,
 221        .bDeviceSubClass =      0,
 222        .bDeviceProtocol =      0,
 223        .idVendor =             cpu_to_le16(PRINTER_VENDOR_NUM),
 224        .idProduct =            cpu_to_le16(PRINTER_PRODUCT_NUM),
 225        .iManufacturer =        STRING_MANUFACTURER,
 226        .iProduct =             STRING_PRODUCT,
 227        .iSerialNumber =        STRING_SERIALNUM,
 228        .bNumConfigurations =   1
 229};
 230
 231static struct usb_otg_descriptor otg_desc = {
 232        .bLength =              sizeof otg_desc,
 233        .bDescriptorType =      USB_DT_OTG,
 234        .bmAttributes =         USB_OTG_SRP
 235};
 236
 237static struct usb_config_descriptor config_desc = {
 238        .bLength =              sizeof config_desc,
 239        .bDescriptorType =      USB_DT_CONFIG,
 240
 241        /* compute wTotalLength on the fly */
 242        .bNumInterfaces =       1,
 243        .bConfigurationValue =  DEV_CONFIG_VALUE,
 244        .iConfiguration =       0,
 245        .bmAttributes =         USB_CONFIG_ATT_ONE | USB_CONFIG_ATT_SELFPOWER,
 246        .bMaxPower =            CONFIG_USB_GADGET_VBUS_DRAW / 2,
 247};
 248
 249static struct usb_interface_descriptor intf_desc = {
 250        .bLength =              sizeof intf_desc,
 251        .bDescriptorType =      USB_DT_INTERFACE,
 252        .bInterfaceNumber =     PRINTER_INTERFACE,
 253        .bNumEndpoints =        2,
 254        .bInterfaceClass =      USB_CLASS_PRINTER,
 255        .bInterfaceSubClass =   1,      /* Printer Sub-Class */
 256        .bInterfaceProtocol =   2,      /* Bi-Directional */
 257        .iInterface =           0
 258};
 259
 260static struct usb_endpoint_descriptor fs_ep_in_desc = {
 261        .bLength =              USB_DT_ENDPOINT_SIZE,
 262        .bDescriptorType =      USB_DT_ENDPOINT,
 263        .bEndpointAddress =     USB_DIR_IN,
 264        .bmAttributes =         USB_ENDPOINT_XFER_BULK
 265};
 266
 267static struct usb_endpoint_descriptor fs_ep_out_desc = {
 268        .bLength =              USB_DT_ENDPOINT_SIZE,
 269        .bDescriptorType =      USB_DT_ENDPOINT,
 270        .bEndpointAddress =     USB_DIR_OUT,
 271        .bmAttributes =         USB_ENDPOINT_XFER_BULK
 272};
 273
 274static const struct usb_descriptor_header *fs_printer_function [11] = {
 275        (struct usb_descriptor_header *) &otg_desc,
 276        (struct usb_descriptor_header *) &intf_desc,
 277        (struct usb_descriptor_header *) &fs_ep_in_desc,
 278        (struct usb_descriptor_header *) &fs_ep_out_desc,
 279        NULL
 280};
 281
 282#ifdef  CONFIG_USB_GADGET_DUALSPEED
 283
 284/*
 285 * usb 2.0 devices need to expose both high speed and full speed
 286 * descriptors, unless they only run at full speed.
 287 */
 288
 289static struct usb_endpoint_descriptor hs_ep_in_desc = {
 290        .bLength =              USB_DT_ENDPOINT_SIZE,
 291        .bDescriptorType =      USB_DT_ENDPOINT,
 292        .bmAttributes =         USB_ENDPOINT_XFER_BULK,
 293        .wMaxPacketSize =       cpu_to_le16(512)
 294};
 295
 296static struct usb_endpoint_descriptor hs_ep_out_desc = {
 297        .bLength =              USB_DT_ENDPOINT_SIZE,
 298        .bDescriptorType =      USB_DT_ENDPOINT,
 299        .bmAttributes =         USB_ENDPOINT_XFER_BULK,
 300        .wMaxPacketSize =       cpu_to_le16(512)
 301};
 302
 303static struct usb_qualifier_descriptor dev_qualifier = {
 304        .bLength =              sizeof dev_qualifier,
 305        .bDescriptorType =      USB_DT_DEVICE_QUALIFIER,
 306        .bcdUSB =               cpu_to_le16(0x0200),
 307        .bDeviceClass =         USB_CLASS_PRINTER,
 308        .bNumConfigurations =   1
 309};
 310
 311static const struct usb_descriptor_header *hs_printer_function [11] = {
 312        (struct usb_descriptor_header *) &otg_desc,
 313        (struct usb_descriptor_header *) &intf_desc,
 314        (struct usb_descriptor_header *) &hs_ep_in_desc,
 315        (struct usb_descriptor_header *) &hs_ep_out_desc,
 316        NULL
 317};
 318
 319/* maxpacket and other transfer characteristics vary by speed. */
 320#define ep_desc(g, hs, fs) (((g)->speed == USB_SPEED_HIGH)?(hs):(fs))
 321
 322#else
 323
 324/* if there's no high speed support, maxpacket doesn't change. */
 325#define ep_desc(g, hs, fs) (((void)(g)), (fs))
 326
 327#endif  /* !CONFIG_USB_GADGET_DUALSPEED */
 328
 329/*-------------------------------------------------------------------------*/
 330
 331/* descriptors that are built on-demand */
 332
 333static char                             manufacturer [50];
 334static char                             product_desc [40] = DRIVER_DESC;
 335static char                             serial_num [40] = "1";
 336static char                             pnp_string [1024] =
 337        "XXMFG:linux;MDL:g_printer;CLS:PRINTER;SN:1;";
 338
 339/* static strings, in UTF-8 */
 340static struct usb_string                strings [] = {
 341        { STRING_MANUFACTURER,  manufacturer, },
 342        { STRING_PRODUCT,       product_desc, },
 343        { STRING_SERIALNUM,     serial_num, },
 344        {  }            /* end of list */
 345};
 346
 347static struct usb_gadget_strings        stringtab = {
 348        .language       = 0x0409,       /* en-us */
 349        .strings        = strings,
 350};
 351
 352/*-------------------------------------------------------------------------*/
 353
 354static struct usb_request *
 355printer_req_alloc(struct usb_ep *ep, unsigned len, gfp_t gfp_flags)
 356{
 357        struct usb_request      *req;
 358
 359        req = usb_ep_alloc_request(ep, gfp_flags);
 360
 361        if (req != NULL) {
 362                req->length = len;
 363                req->buf = kmalloc(len, gfp_flags);
 364                if (req->buf == NULL) {
 365                        usb_ep_free_request(ep, req);
 366                        return NULL;
 367                }
 368        }
 369
 370        return req;
 371}
 372
 373static void
 374printer_req_free(struct usb_ep *ep, struct usb_request *req)
 375{
 376        if (ep != NULL && req != NULL) {
 377                kfree(req->buf);
 378                usb_ep_free_request(ep, req);
 379        }
 380}
 381
 382/*-------------------------------------------------------------------------*/
 383
 384static void rx_complete(struct usb_ep *ep, struct usb_request *req)
 385{
 386        struct printer_dev      *dev = ep->driver_data;
 387        int                     status = req->status;
 388        unsigned long           flags;
 389
 390        spin_lock_irqsave(&dev->lock, flags);
 391
 392        list_del_init(&req->list);      /* Remode from Active List */
 393
 394        switch (status) {
 395
 396        /* normal completion */
 397        case 0:
 398                if (req->actual > 0) {
 399                        list_add_tail(&req->list, &dev->rx_buffers);
 400                        DBG(dev, "G_Printer : rx length %d\n", req->actual);
 401                } else {
 402                        list_add(&req->list, &dev->rx_reqs);
 403                }
 404                break;
 405
 406        /* software-driven interface shutdown */
 407        case -ECONNRESET:               /* unlink */
 408        case -ESHUTDOWN:                /* disconnect etc */
 409                VDBG(dev, "rx shutdown, code %d\n", status);
 410                list_add(&req->list, &dev->rx_reqs);
 411                break;
 412
 413        /* for hardware automagic (such as pxa) */
 414        case -ECONNABORTED:             /* endpoint reset */
 415                DBG(dev, "rx %s reset\n", ep->name);
 416                list_add(&req->list, &dev->rx_reqs);
 417                break;
 418
 419        /* data overrun */
 420        case -EOVERFLOW:
 421                /* FALLTHROUGH */
 422
 423        default:
 424                DBG(dev, "rx status %d\n", status);
 425                list_add(&req->list, &dev->rx_reqs);
 426                break;
 427        }
 428
 429        wake_up_interruptible(&dev->rx_wait);
 430        spin_unlock_irqrestore(&dev->lock, flags);
 431}
 432
 433static void tx_complete(struct usb_ep *ep, struct usb_request *req)
 434{
 435        struct printer_dev      *dev = ep->driver_data;
 436
 437        switch (req->status) {
 438        default:
 439                VDBG(dev, "tx err %d\n", req->status);
 440                /* FALLTHROUGH */
 441        case -ECONNRESET:               /* unlink */
 442        case -ESHUTDOWN:                /* disconnect etc */
 443                break;
 444        case 0:
 445                break;
 446        }
 447
 448        spin_lock(&dev->lock);
 449        /* Take the request struct off the active list and put it on the
 450         * free list.
 451         */
 452        list_del_init(&req->list);
 453        list_add(&req->list, &dev->tx_reqs);
 454        wake_up_interruptible(&dev->tx_wait);
 455        if (likely(list_empty(&dev->tx_reqs_active)))
 456                wake_up_interruptible(&dev->tx_flush_wait);
 457
 458        spin_unlock(&dev->lock);
 459}
 460
 461/*-------------------------------------------------------------------------*/
 462
 463static int
 464printer_open(struct inode *inode, struct file *fd)
 465{
 466        struct printer_dev      *dev;
 467        unsigned long           flags;
 468        int                     ret = -EBUSY;
 469
 470        mutex_lock(&printer_mutex);
 471        dev = container_of(inode->i_cdev, struct printer_dev, printer_cdev);
 472
 473        spin_lock_irqsave(&dev->lock, flags);
 474
 475        if (!dev->printer_cdev_open) {
 476                dev->printer_cdev_open = 1;
 477                fd->private_data = dev;
 478                ret = 0;
 479                /* Change the printer status to show that it's on-line. */
 480                dev->printer_status |= PRINTER_SELECTED;
 481        }
 482
 483        spin_unlock_irqrestore(&dev->lock, flags);
 484
 485        DBG(dev, "printer_open returned %x\n", ret);
 486        mutex_unlock(&printer_mutex);
 487        return ret;
 488}
 489
 490static int
 491printer_close(struct inode *inode, struct file *fd)
 492{
 493        struct printer_dev      *dev = fd->private_data;
 494        unsigned long           flags;
 495
 496        spin_lock_irqsave(&dev->lock, flags);
 497        dev->printer_cdev_open = 0;
 498        fd->private_data = NULL;
 499        /* Change printer status to show that the printer is off-line. */
 500        dev->printer_status &= ~PRINTER_SELECTED;
 501        spin_unlock_irqrestore(&dev->lock, flags);
 502
 503        DBG(dev, "printer_close\n");
 504
 505        return 0;
 506}
 507
 508/* This function must be called with interrupts turned off. */
 509static void
 510setup_rx_reqs(struct printer_dev *dev)
 511{
 512        struct usb_request              *req;
 513
 514        while (likely(!list_empty(&dev->rx_reqs))) {
 515                int error;
 516
 517                req = container_of(dev->rx_reqs.next,
 518                                struct usb_request, list);
 519                list_del_init(&req->list);
 520
 521                /* The USB Host sends us whatever amount of data it wants to
 522                 * so we always set the length field to the full USB_BUFSIZE.
 523                 * If the amount of data is more than the read() caller asked
 524                 * for it will be stored in the request buffer until it is
 525                 * asked for by read().
 526                 */
 527                req->length = USB_BUFSIZE;
 528                req->complete = rx_complete;
 529
 530                error = usb_ep_queue(dev->out_ep, req, GFP_ATOMIC);
 531                if (error) {
 532                        DBG(dev, "rx submit --> %d\n", error);
 533                        list_add(&req->list, &dev->rx_reqs);
 534                        break;
 535                } else {
 536                        list_add(&req->list, &dev->rx_reqs_active);
 537                }
 538        }
 539}
 540
 541static ssize_t
 542printer_read(struct file *fd, char __user *buf, size_t len, loff_t *ptr)
 543{
 544        struct printer_dev              *dev = fd->private_data;
 545        unsigned long                   flags;
 546        size_t                          size;
 547        size_t                          bytes_copied;
 548        struct usb_request              *req;
 549        /* This is a pointer to the current USB rx request. */
 550        struct usb_request              *current_rx_req;
 551        /* This is the number of bytes in the current rx buffer. */
 552        size_t                          current_rx_bytes;
 553        /* This is a pointer to the current rx buffer. */
 554        u8                              *current_rx_buf;
 555
 556        if (len == 0)
 557                return -EINVAL;
 558
 559        DBG(dev, "printer_read trying to read %d bytes\n", (int)len);
 560
 561        mutex_lock(&dev->lock_printer_io);
 562        spin_lock_irqsave(&dev->lock, flags);
 563
 564        /* We will use this flag later to check if a printer reset happened
 565         * after we turn interrupts back on.
 566         */
 567        dev->reset_printer = 0;
 568
 569        setup_rx_reqs(dev);
 570
 571        bytes_copied = 0;
 572        current_rx_req = dev->current_rx_req;
 573        current_rx_bytes = dev->current_rx_bytes;
 574        current_rx_buf = dev->current_rx_buf;
 575        dev->current_rx_req = NULL;
 576        dev->current_rx_bytes = 0;
 577        dev->current_rx_buf = NULL;
 578
 579        /* Check if there is any data in the read buffers. Please note that
 580         * current_rx_bytes is the number of bytes in the current rx buffer.
 581         * If it is zero then check if there are any other rx_buffers that
 582         * are on the completed list. We are only out of data if all rx
 583         * buffers are empty.
 584         */
 585        if ((current_rx_bytes == 0) &&
 586                        (likely(list_empty(&dev->rx_buffers)))) {
 587                /* Turn interrupts back on before sleeping. */
 588                spin_unlock_irqrestore(&dev->lock, flags);
 589
 590                /*
 591                 * If no data is available check if this is a NON-Blocking
 592                 * call or not.
 593                 */
 594                if (fd->f_flags & (O_NONBLOCK|O_NDELAY)) {
 595                        mutex_unlock(&dev->lock_printer_io);
 596                        return -EAGAIN;
 597                }
 598
 599                /* Sleep until data is available */
 600                wait_event_interruptible(dev->rx_wait,
 601                                (likely(!list_empty(&dev->rx_buffers))));
 602                spin_lock_irqsave(&dev->lock, flags);
 603        }
 604
 605        /* We have data to return then copy it to the caller's buffer.*/
 606        while ((current_rx_bytes || likely(!list_empty(&dev->rx_buffers)))
 607                        && len) {
 608                if (current_rx_bytes == 0) {
 609                        req = container_of(dev->rx_buffers.next,
 610                                        struct usb_request, list);
 611                        list_del_init(&req->list);
 612
 613                        if (req->actual && req->buf) {
 614                                current_rx_req = req;
 615                                current_rx_bytes = req->actual;
 616                                current_rx_buf = req->buf;
 617                        } else {
 618                                list_add(&req->list, &dev->rx_reqs);
 619                                continue;
 620                        }
 621                }
 622
 623                /* Don't leave irqs off while doing memory copies */
 624                spin_unlock_irqrestore(&dev->lock, flags);
 625
 626                if (len > current_rx_bytes)
 627                        size = current_rx_bytes;
 628                else
 629                        size = len;
 630
 631                size -= copy_to_user(buf, current_rx_buf, size);
 632                bytes_copied += size;
 633                len -= size;
 634                buf += size;
 635
 636                spin_lock_irqsave(&dev->lock, flags);
 637
 638                /* We've disconnected or reset so return. */
 639                if (dev->reset_printer) {
 640                        list_add(&current_rx_req->list, &dev->rx_reqs);
 641                        spin_unlock_irqrestore(&dev->lock, flags);
 642                        mutex_unlock(&dev->lock_printer_io);
 643                        return -EAGAIN;
 644                }
 645
 646                /* If we not returning all the data left in this RX request
 647                 * buffer then adjust the amount of data left in the buffer.
 648                 * Othewise if we are done with this RX request buffer then
 649                 * requeue it to get any incoming data from the USB host.
 650                 */
 651                if (size < current_rx_bytes) {
 652                        current_rx_bytes -= size;
 653                        current_rx_buf += size;
 654                } else {
 655                        list_add(&current_rx_req->list, &dev->rx_reqs);
 656                        current_rx_bytes = 0;
 657                        current_rx_buf = NULL;
 658                        current_rx_req = NULL;
 659                }
 660        }
 661
 662        dev->current_rx_req = current_rx_req;
 663        dev->current_rx_bytes = current_rx_bytes;
 664        dev->current_rx_buf = current_rx_buf;
 665
 666        spin_unlock_irqrestore(&dev->lock, flags);
 667        mutex_unlock(&dev->lock_printer_io);
 668
 669        DBG(dev, "printer_read returned %d bytes\n", (int)bytes_copied);
 670
 671        if (bytes_copied)
 672                return bytes_copied;
 673        else
 674                return -EAGAIN;
 675}
 676
 677static ssize_t
 678printer_write(struct file *fd, const char __user *buf, size_t len, loff_t *ptr)
 679{
 680        struct printer_dev      *dev = fd->private_data;
 681        unsigned long           flags;
 682        size_t                  size;   /* Amount of data in a TX request. */
 683        size_t                  bytes_copied = 0;
 684        struct usb_request      *req;
 685
 686        DBG(dev, "printer_write trying to send %d bytes\n", (int)len);
 687
 688        if (len == 0)
 689                return -EINVAL;
 690
 691        mutex_lock(&dev->lock_printer_io);
 692        spin_lock_irqsave(&dev->lock, flags);
 693
 694        /* Check if a printer reset happens while we have interrupts on */
 695        dev->reset_printer = 0;
 696
 697        /* Check if there is any available write buffers */
 698        if (likely(list_empty(&dev->tx_reqs))) {
 699                /* Turn interrupts back on before sleeping. */
 700                spin_unlock_irqrestore(&dev->lock, flags);
 701
 702                /*
 703                 * If write buffers are available check if this is
 704                 * a NON-Blocking call or not.
 705                 */
 706                if (fd->f_flags & (O_NONBLOCK|O_NDELAY)) {
 707                        mutex_unlock(&dev->lock_printer_io);
 708                        return -EAGAIN;
 709                }
 710
 711                /* Sleep until a write buffer is available */
 712                wait_event_interruptible(dev->tx_wait,
 713                                (likely(!list_empty(&dev->tx_reqs))));
 714                spin_lock_irqsave(&dev->lock, flags);
 715        }
 716
 717        while (likely(!list_empty(&dev->tx_reqs)) && len) {
 718
 719                if (len > USB_BUFSIZE)
 720                        size = USB_BUFSIZE;
 721                else
 722                        size = len;
 723
 724                req = container_of(dev->tx_reqs.next, struct usb_request,
 725                                list);
 726                list_del_init(&req->list);
 727
 728                req->complete = tx_complete;
 729                req->length = size;
 730
 731                /* Check if we need to send a zero length packet. */
 732                if (len > size)
 733                        /* They will be more TX requests so no yet. */
 734                        req->zero = 0;
 735                else
 736                        /* If the data amount is not a multple of the
 737                         * maxpacket size then send a zero length packet.
 738                         */
 739                        req->zero = ((len % dev->in_ep->maxpacket) == 0);
 740
 741                /* Don't leave irqs off while doing memory copies */
 742                spin_unlock_irqrestore(&dev->lock, flags);
 743
 744                if (copy_from_user(req->buf, buf, size)) {
 745                        list_add(&req->list, &dev->tx_reqs);
 746                        mutex_unlock(&dev->lock_printer_io);
 747                        return bytes_copied;
 748                }
 749
 750                bytes_copied += size;
 751                len -= size;
 752                buf += size;
 753
 754                spin_lock_irqsave(&dev->lock, flags);
 755
 756                /* We've disconnected or reset so free the req and buffer */
 757                if (dev->reset_printer) {
 758                        list_add(&req->list, &dev->tx_reqs);
 759                        spin_unlock_irqrestore(&dev->lock, flags);
 760                        mutex_unlock(&dev->lock_printer_io);
 761                        return -EAGAIN;
 762                }
 763
 764                if (usb_ep_queue(dev->in_ep, req, GFP_ATOMIC)) {
 765                        list_add(&req->list, &dev->tx_reqs);
 766                        spin_unlock_irqrestore(&dev->lock, flags);
 767                        mutex_unlock(&dev->lock_printer_io);
 768                        return -EAGAIN;
 769                }
 770
 771                list_add(&req->list, &dev->tx_reqs_active);
 772
 773        }
 774
 775        spin_unlock_irqrestore(&dev->lock, flags);
 776        mutex_unlock(&dev->lock_printer_io);
 777
 778        DBG(dev, "printer_write sent %d bytes\n", (int)bytes_copied);
 779
 780        if (bytes_copied) {
 781                return bytes_copied;
 782        } else {
 783                return -EAGAIN;
 784        }
 785}
 786
 787static int
 788printer_fsync(struct file *fd, loff_t start, loff_t end, int datasync)
 789{
 790        struct printer_dev      *dev = fd->private_data;
 791        struct inode *inode = fd->f_path.dentry->d_inode;
 792        unsigned long           flags;
 793        int                     tx_list_empty;
 794
 795        mutex_lock(&inode->i_mutex);
 796        spin_lock_irqsave(&dev->lock, flags);
 797        tx_list_empty = (likely(list_empty(&dev->tx_reqs)));
 798        spin_unlock_irqrestore(&dev->lock, flags);
 799
 800        if (!tx_list_empty) {
 801                /* Sleep until all data has been sent */
 802                wait_event_interruptible(dev->tx_flush_wait,
 803                                (likely(list_empty(&dev->tx_reqs_active))));
 804        }
 805        mutex_unlock(&inode->i_mutex);
 806
 807        return 0;
 808}
 809
 810static unsigned int
 811printer_poll(struct file *fd, poll_table *wait)
 812{
 813        struct printer_dev      *dev = fd->private_data;
 814        unsigned long           flags;
 815        int                     status = 0;
 816
 817        mutex_lock(&dev->lock_printer_io);
 818        spin_lock_irqsave(&dev->lock, flags);
 819        setup_rx_reqs(dev);
 820        spin_unlock_irqrestore(&dev->lock, flags);
 821        mutex_unlock(&dev->lock_printer_io);
 822
 823        poll_wait(fd, &dev->rx_wait, wait);
 824        poll_wait(fd, &dev->tx_wait, wait);
 825
 826        spin_lock_irqsave(&dev->lock, flags);
 827        if (likely(!list_empty(&dev->tx_reqs)))
 828                status |= POLLOUT | POLLWRNORM;
 829
 830        if (likely(dev->current_rx_bytes) ||
 831                        likely(!list_empty(&dev->rx_buffers)))
 832                status |= POLLIN | POLLRDNORM;
 833
 834        spin_unlock_irqrestore(&dev->lock, flags);
 835
 836        return status;
 837}
 838
 839static long
 840printer_ioctl(struct file *fd, unsigned int code, unsigned long arg)
 841{
 842        struct printer_dev      *dev = fd->private_data;
 843        unsigned long           flags;
 844        int                     status = 0;
 845
 846        DBG(dev, "printer_ioctl: cmd=0x%4.4x, arg=%lu\n", code, arg);
 847
 848        /* handle ioctls */
 849
 850        spin_lock_irqsave(&dev->lock, flags);
 851
 852        switch (code) {
 853        case GADGET_GET_PRINTER_STATUS:
 854                status = (int)dev->printer_status;
 855                break;
 856        case GADGET_SET_PRINTER_STATUS:
 857                dev->printer_status = (u8)arg;
 858                break;
 859        default:
 860                /* could not handle ioctl */
 861                DBG(dev, "printer_ioctl: ERROR cmd=0x%4.4xis not supported\n",
 862                                code);
 863                status = -ENOTTY;
 864        }
 865
 866        spin_unlock_irqrestore(&dev->lock, flags);
 867
 868        return status;
 869}
 870
 871/* used after endpoint configuration */
 872static const struct file_operations printer_io_operations = {
 873        .owner =        THIS_MODULE,
 874        .open =         printer_open,
 875        .read =         printer_read,
 876        .write =        printer_write,
 877        .fsync =        printer_fsync,
 878        .poll =         printer_poll,
 879        .unlocked_ioctl = printer_ioctl,
 880        .release =      printer_close,
 881        .llseek =       noop_llseek,
 882};
 883
 884/*-------------------------------------------------------------------------*/
 885
 886static int
 887set_printer_interface(struct printer_dev *dev)
 888{
 889        int                     result = 0;
 890
 891        dev->in_ep->desc = ep_desc(dev->gadget, &hs_ep_in_desc, &fs_ep_in_desc);
 892        dev->in_ep->driver_data = dev;
 893
 894        dev->out_ep->desc = ep_desc(dev->gadget, &hs_ep_out_desc,
 895                                    &fs_ep_out_desc);
 896        dev->out_ep->driver_data = dev;
 897
 898        result = usb_ep_enable(dev->in_ep);
 899        if (result != 0) {
 900                DBG(dev, "enable %s --> %d\n", dev->in_ep->name, result);
 901                goto done;
 902        }
 903
 904        result = usb_ep_enable(dev->out_ep);
 905        if (result != 0) {
 906                DBG(dev, "enable %s --> %d\n", dev->in_ep->name, result);
 907                goto done;
 908        }
 909
 910done:
 911        /* on error, disable any endpoints  */
 912        if (result != 0) {
 913                (void) usb_ep_disable(dev->in_ep);
 914                (void) usb_ep_disable(dev->out_ep);
 915                dev->in_ep->desc = NULL;
 916                dev->out_ep->desc = NULL;
 917        }
 918
 919        /* caller is responsible for cleanup on error */
 920        return result;
 921}
 922
 923static void printer_reset_interface(struct printer_dev *dev)
 924{
 925        if (dev->interface < 0)
 926                return;
 927
 928        DBG(dev, "%s\n", __func__);
 929
 930        if (dev->in_ep->desc)
 931                usb_ep_disable(dev->in_ep);
 932
 933        if (dev->out_ep->desc)
 934                usb_ep_disable(dev->out_ep);
 935
 936        dev->in_ep->desc = NULL;
 937        dev->out_ep->desc = NULL;
 938        dev->interface = -1;
 939}
 940
 941/* change our operational config.  must agree with the code
 942 * that returns config descriptors, and altsetting code.
 943 */
 944static int
 945printer_set_config(struct printer_dev *dev, unsigned number)
 946{
 947        int                     result = 0;
 948        struct usb_gadget       *gadget = dev->gadget;
 949
 950        switch (number) {
 951        case DEV_CONFIG_VALUE:
 952                result = 0;
 953                break;
 954        default:
 955                result = -EINVAL;
 956                /* FALL THROUGH */
 957        case 0:
 958                break;
 959        }
 960
 961        if (result) {
 962                usb_gadget_vbus_draw(dev->gadget,
 963                                dev->gadget->is_otg ? 8 : 100);
 964        } else {
 965                unsigned power;
 966
 967                power = 2 * config_desc.bMaxPower;
 968                usb_gadget_vbus_draw(dev->gadget, power);
 969
 970                dev->config = number;
 971                INFO(dev, "%s config #%d: %d mA, %s\n",
 972                     usb_speed_string(gadget->speed),
 973                     number, power, driver_desc);
 974        }
 975        return result;
 976}
 977
 978static int
 979config_buf(enum usb_device_speed speed, u8 *buf, u8 type, unsigned index,
 980                int is_otg)
 981{
 982        int                                     len;
 983        const struct usb_descriptor_header      **function;
 984#ifdef CONFIG_USB_GADGET_DUALSPEED
 985        int                                     hs = (speed == USB_SPEED_HIGH);
 986
 987        if (type == USB_DT_OTHER_SPEED_CONFIG)
 988                hs = !hs;
 989
 990        if (hs) {
 991                function = hs_printer_function;
 992        } else {
 993                function = fs_printer_function;
 994        }
 995#else
 996        function = fs_printer_function;
 997#endif
 998
 999        if (index >= device_desc.bNumConfigurations)
1000                return -EINVAL;
1001
1002        /* for now, don't advertise srp-only devices */
1003        if (!is_otg)
1004                function++;
1005
1006        len = usb_gadget_config_buf(&config_desc, buf, USB_DESC_BUFSIZE,
1007                        function);
1008        if (len < 0)
1009                return len;
1010        ((struct usb_config_descriptor *) buf)->bDescriptorType = type;
1011        return len;
1012}
1013
1014/* Change our operational Interface. */
1015static int
1016set_interface(struct printer_dev *dev, unsigned number)
1017{
1018        int                     result = 0;
1019
1020        /* Free the current interface */
1021        switch (dev->interface) {
1022        case PRINTER_INTERFACE:
1023                printer_reset_interface(dev);
1024                break;
1025        }
1026
1027        switch (number) {
1028        case PRINTER_INTERFACE:
1029                result = set_printer_interface(dev);
1030                if (result) {
1031                        printer_reset_interface(dev);
1032                } else {
1033                        dev->interface = PRINTER_INTERFACE;
1034                }
1035                break;
1036        default:
1037                result = -EINVAL;
1038                /* FALL THROUGH */
1039        }
1040
1041        if (!result)
1042                INFO(dev, "Using interface %x\n", number);
1043
1044        return result;
1045}
1046
1047static void printer_setup_complete(struct usb_ep *ep, struct usb_request *req)
1048{
1049        if (req->status || req->actual != req->length)
1050                DBG((struct printer_dev *) ep->driver_data,
1051                                "setup complete --> %d, %d/%d\n",
1052                                req->status, req->actual, req->length);
1053}
1054
1055static void printer_soft_reset(struct printer_dev *dev)
1056{
1057        struct usb_request      *req;
1058
1059        INFO(dev, "Received Printer Reset Request\n");
1060
1061        if (usb_ep_disable(dev->in_ep))
1062                DBG(dev, "Failed to disable USB in_ep\n");
1063        if (usb_ep_disable(dev->out_ep))
1064                DBG(dev, "Failed to disable USB out_ep\n");
1065
1066        if (dev->current_rx_req != NULL) {
1067                list_add(&dev->current_rx_req->list, &dev->rx_reqs);
1068                dev->current_rx_req = NULL;
1069        }
1070        dev->current_rx_bytes = 0;
1071        dev->current_rx_buf = NULL;
1072        dev->reset_printer = 1;
1073
1074        while (likely(!(list_empty(&dev->rx_buffers)))) {
1075                req = container_of(dev->rx_buffers.next, struct usb_request,
1076                                list);
1077                list_del_init(&req->list);
1078                list_add(&req->list, &dev->rx_reqs);
1079        }
1080
1081        while (likely(!(list_empty(&dev->rx_reqs_active)))) {
1082                req = container_of(dev->rx_buffers.next, struct usb_request,
1083                                list);
1084                list_del_init(&req->list);
1085                list_add(&req->list, &dev->rx_reqs);
1086        }
1087
1088        while (likely(!(list_empty(&dev->tx_reqs_active)))) {
1089                req = container_of(dev->tx_reqs_active.next,
1090                                struct usb_request, list);
1091                list_del_init(&req->list);
1092                list_add(&req->list, &dev->tx_reqs);
1093        }
1094
1095        if (usb_ep_enable(dev->in_ep))
1096                DBG(dev, "Failed to enable USB in_ep\n");
1097        if (usb_ep_enable(dev->out_ep))
1098                DBG(dev, "Failed to enable USB out_ep\n");
1099
1100        wake_up_interruptible(&dev->rx_wait);
1101        wake_up_interruptible(&dev->tx_wait);
1102        wake_up_interruptible(&dev->tx_flush_wait);
1103}
1104
1105/*-------------------------------------------------------------------------*/
1106
1107/*
1108 * The setup() callback implements all the ep0 functionality that's not
1109 * handled lower down.
1110 */
1111static int
1112printer_setup(struct usb_gadget *gadget, const struct usb_ctrlrequest *ctrl)
1113{
1114        struct printer_dev      *dev = get_gadget_data(gadget);
1115        struct usb_request      *req = dev->req;
1116        int                     value = -EOPNOTSUPP;
1117        u16                     wIndex = le16_to_cpu(ctrl->wIndex);
1118        u16                     wValue = le16_to_cpu(ctrl->wValue);
1119        u16                     wLength = le16_to_cpu(ctrl->wLength);
1120
1121        DBG(dev, "ctrl req%02x.%02x v%04x i%04x l%d\n",
1122                ctrl->bRequestType, ctrl->bRequest, wValue, wIndex, wLength);
1123
1124        req->complete = printer_setup_complete;
1125
1126        switch (ctrl->bRequestType&USB_TYPE_MASK) {
1127
1128        case USB_TYPE_STANDARD:
1129                switch (ctrl->bRequest) {
1130
1131                case USB_REQ_GET_DESCRIPTOR:
1132                        if (ctrl->bRequestType != USB_DIR_IN)
1133                                break;
1134                        switch (wValue >> 8) {
1135
1136                        case USB_DT_DEVICE:
1137                                device_desc.bMaxPacketSize0 =
1138                                        gadget->ep0->maxpacket;
1139                                value = min(wLength, (u16) sizeof device_desc);
1140                                memcpy(req->buf, &device_desc, value);
1141                                break;
1142#ifdef CONFIG_USB_GADGET_DUALSPEED
1143                        case USB_DT_DEVICE_QUALIFIER:
1144                                if (!gadget_is_dualspeed(gadget))
1145                                        break;
1146                                /*
1147                                 * assumes ep0 uses the same value for both
1148                                 * speeds
1149                                 */
1150                                dev_qualifier.bMaxPacketSize0 =
1151                                        gadget->ep0->maxpacket;
1152                                value = min(wLength,
1153                                                (u16) sizeof dev_qualifier);
1154                                memcpy(req->buf, &dev_qualifier, value);
1155                                break;
1156
1157                        case USB_DT_OTHER_SPEED_CONFIG:
1158                                if (!gadget_is_dualspeed(gadget))
1159                                        break;
1160                                /* FALLTHROUGH */
1161#endif /* CONFIG_USB_GADGET_DUALSPEED */
1162                        case USB_DT_CONFIG:
1163                                value = config_buf(gadget->speed, req->buf,
1164                                                wValue >> 8,
1165                                                wValue & 0xff,
1166                                                gadget->is_otg);
1167                                if (value >= 0)
1168                                        value = min(wLength, (u16) value);
1169                                break;
1170
1171                        case USB_DT_STRING:
1172                                value = usb_gadget_get_string(&stringtab,
1173                                                wValue & 0xff, req->buf);
1174                                if (value >= 0)
1175                                        value = min(wLength, (u16) value);
1176                                break;
1177                        }
1178                        break;
1179
1180                case USB_REQ_SET_CONFIGURATION:
1181                        if (ctrl->bRequestType != 0)
1182                                break;
1183                        if (gadget->a_hnp_support)
1184                                DBG(dev, "HNP available\n");
1185                        else if (gadget->a_alt_hnp_support)
1186                                DBG(dev, "HNP needs a different root port\n");
1187                        value = printer_set_config(dev, wValue);
1188                        if (!value)
1189                                value = set_interface(dev, PRINTER_INTERFACE);
1190                        break;
1191                case USB_REQ_GET_CONFIGURATION:
1192                        if (ctrl->bRequestType != USB_DIR_IN)
1193                                break;
1194                        *(u8 *)req->buf = dev->config;
1195                        value = min(wLength, (u16) 1);
1196                        break;
1197
1198                case USB_REQ_SET_INTERFACE:
1199                        if (ctrl->bRequestType != USB_RECIP_INTERFACE ||
1200                                        !dev->config)
1201                                break;
1202
1203                        value = set_interface(dev, PRINTER_INTERFACE);
1204                        break;
1205                case USB_REQ_GET_INTERFACE:
1206                        if (ctrl->bRequestType !=
1207                                        (USB_DIR_IN|USB_RECIP_INTERFACE)
1208                                        || !dev->config)
1209                                break;
1210
1211                        *(u8 *)req->buf = dev->interface;
1212                        value = min(wLength, (u16) 1);
1213                        break;
1214
1215                default:
1216                        goto unknown;
1217                }
1218                break;
1219
1220        case USB_TYPE_CLASS:
1221                switch (ctrl->bRequest) {
1222                case 0: /* Get the IEEE-1284 PNP String */
1223                        /* Only one printer interface is supported. */
1224                        if ((wIndex>>8) != PRINTER_INTERFACE)
1225                                break;
1226
1227                        value = (pnp_string[0]<<8)|pnp_string[1];
1228                        memcpy(req->buf, pnp_string, value);
1229                        DBG(dev, "1284 PNP String: %x %s\n", value,
1230                                        &pnp_string[2]);
1231                        break;
1232
1233                case 1: /* Get Port Status */
1234                        /* Only one printer interface is supported. */
1235                        if (wIndex != PRINTER_INTERFACE)
1236                                break;
1237
1238                        *(u8 *)req->buf = dev->printer_status;
1239                        value = min(wLength, (u16) 1);
1240                        break;
1241
1242                case 2: /* Soft Reset */
1243                        /* Only one printer interface is supported. */
1244                        if (wIndex != PRINTER_INTERFACE)
1245                                break;
1246
1247                        printer_soft_reset(dev);
1248
1249                        value = 0;
1250                        break;
1251
1252                default:
1253                        goto unknown;
1254                }
1255                break;
1256
1257        default:
1258unknown:
1259                VDBG(dev,
1260                        "unknown ctrl req%02x.%02x v%04x i%04x l%d\n",
1261                        ctrl->bRequestType, ctrl->bRequest,
1262                        wValue, wIndex, wLength);
1263                break;
1264        }
1265
1266        /* respond with data transfer before status phase? */
1267        if (value >= 0) {
1268                req->length = value;
1269                req->zero = value < wLength;
1270                value = usb_ep_queue(gadget->ep0, req, GFP_ATOMIC);
1271                if (value < 0) {
1272                        DBG(dev, "ep_queue --> %d\n", value);
1273                        req->status = 0;
1274                        printer_setup_complete(gadget->ep0, req);
1275                }
1276        }
1277
1278        /* host either stalls (value < 0) or reports success */
1279        return value;
1280}
1281
1282static void
1283printer_disconnect(struct usb_gadget *gadget)
1284{
1285        struct printer_dev      *dev = get_gadget_data(gadget);
1286        unsigned long           flags;
1287
1288        DBG(dev, "%s\n", __func__);
1289
1290        spin_lock_irqsave(&dev->lock, flags);
1291
1292        printer_reset_interface(dev);
1293
1294        spin_unlock_irqrestore(&dev->lock, flags);
1295}
1296
1297static void
1298printer_unbind(struct usb_gadget *gadget)
1299{
1300        struct printer_dev      *dev = get_gadget_data(gadget);
1301        struct usb_request      *req;
1302
1303
1304        DBG(dev, "%s\n", __func__);
1305
1306        /* Remove sysfs files */
1307        device_destroy(usb_gadget_class, g_printer_devno);
1308
1309        /* Remove Character Device */
1310        cdev_del(&dev->printer_cdev);
1311
1312        /* we must already have been disconnected ... no i/o may be active */
1313        WARN_ON(!list_empty(&dev->tx_reqs_active));
1314        WARN_ON(!list_empty(&dev->rx_reqs_active));
1315
1316        /* Free all memory for this driver. */
1317        while (!list_empty(&dev->tx_reqs)) {
1318                req = container_of(dev->tx_reqs.next, struct usb_request,
1319                                list);
1320                list_del(&req->list);
1321                printer_req_free(dev->in_ep, req);
1322        }
1323
1324        if (dev->current_rx_req != NULL)
1325                printer_req_free(dev->out_ep, dev->current_rx_req);
1326
1327        while (!list_empty(&dev->rx_reqs)) {
1328                req = container_of(dev->rx_reqs.next,
1329                                struct usb_request, list);
1330                list_del(&req->list);
1331                printer_req_free(dev->out_ep, req);
1332        }
1333
1334        while (!list_empty(&dev->rx_buffers)) {
1335                req = container_of(dev->rx_buffers.next,
1336                                struct usb_request, list);
1337                list_del(&req->list);
1338                printer_req_free(dev->out_ep, req);
1339        }
1340
1341        if (dev->req) {
1342                printer_req_free(gadget->ep0, dev->req);
1343                dev->req = NULL;
1344        }
1345
1346        set_gadget_data(gadget, NULL);
1347}
1348
1349static int __init
1350printer_bind(struct usb_gadget *gadget)
1351{
1352        struct printer_dev      *dev;
1353        struct usb_ep           *in_ep, *out_ep;
1354        int                     status = -ENOMEM;
1355        int                     gcnum;
1356        size_t                  len;
1357        u32                     i;
1358        struct usb_request      *req;
1359
1360        dev = &usb_printer_gadget;
1361
1362
1363        /* Setup the sysfs files for the printer gadget. */
1364        dev->pdev = device_create(usb_gadget_class, NULL, g_printer_devno,
1365                                  NULL, "g_printer");
1366        if (IS_ERR(dev->pdev)) {
1367                ERROR(dev, "Failed to create device: g_printer\n");
1368                goto fail;
1369        }
1370
1371        /*
1372         * Register a character device as an interface to a user mode
1373         * program that handles the printer specific functionality.
1374         */
1375        cdev_init(&dev->printer_cdev, &printer_io_operations);
1376        dev->printer_cdev.owner = THIS_MODULE;
1377        status = cdev_add(&dev->printer_cdev, g_printer_devno, 1);
1378        if (status) {
1379                ERROR(dev, "Failed to open char device\n");
1380                goto fail;
1381        }
1382
1383        gcnum = usb_gadget_controller_number(gadget);
1384        if (gcnum >= 0) {
1385                device_desc.bcdDevice = cpu_to_le16(0x0200 + gcnum);
1386        } else {
1387                dev_warn(&gadget->dev, "controller '%s' not recognized\n",
1388                        gadget->name);
1389                /* unrecognized, but safe unless bulk is REALLY quirky */
1390                device_desc.bcdDevice =
1391                        cpu_to_le16(0xFFFF);
1392        }
1393        snprintf(manufacturer, sizeof(manufacturer), "%s %s with %s",
1394                init_utsname()->sysname, init_utsname()->release,
1395                gadget->name);
1396
1397        device_desc.idVendor =
1398                cpu_to_le16(PRINTER_VENDOR_NUM);
1399        device_desc.idProduct =
1400                cpu_to_le16(PRINTER_PRODUCT_NUM);
1401
1402        /* support optional vendor/distro customization */
1403        if (idVendor) {
1404                if (!idProduct) {
1405                        dev_err(&gadget->dev, "idVendor needs idProduct!\n");
1406                        return -ENODEV;
1407                }
1408                device_desc.idVendor = cpu_to_le16(idVendor);
1409                device_desc.idProduct = cpu_to_le16(idProduct);
1410                if (bcdDevice)
1411                        device_desc.bcdDevice = cpu_to_le16(bcdDevice);
1412        }
1413
1414        if (iManufacturer)
1415                strlcpy(manufacturer, iManufacturer, sizeof manufacturer);
1416
1417        if (iProduct)
1418                strlcpy(product_desc, iProduct, sizeof product_desc);
1419
1420        if (iSerialNum)
1421                strlcpy(serial_num, iSerialNum, sizeof serial_num);
1422
1423        if (iPNPstring)
1424                strlcpy(&pnp_string[2], iPNPstring, (sizeof pnp_string)-2);
1425
1426        len = strlen(pnp_string);
1427        pnp_string[0] = (len >> 8) & 0xFF;
1428        pnp_string[1] = len & 0xFF;
1429
1430        /* all we really need is bulk IN/OUT */
1431        usb_ep_autoconfig_reset(gadget);
1432        in_ep = usb_ep_autoconfig(gadget, &fs_ep_in_desc);
1433        if (!in_ep) {
1434autoconf_fail:
1435                dev_err(&gadget->dev, "can't autoconfigure on %s\n",
1436                        gadget->name);
1437                return -ENODEV;
1438        }
1439        in_ep->driver_data = in_ep;     /* claim */
1440
1441        out_ep = usb_ep_autoconfig(gadget, &fs_ep_out_desc);
1442        if (!out_ep)
1443                goto autoconf_fail;
1444        out_ep->driver_data = out_ep;   /* claim */
1445
1446#ifdef  CONFIG_USB_GADGET_DUALSPEED
1447        /* assumes that all endpoints are dual-speed */
1448        hs_ep_in_desc.bEndpointAddress = fs_ep_in_desc.bEndpointAddress;
1449        hs_ep_out_desc.bEndpointAddress = fs_ep_out_desc.bEndpointAddress;
1450#endif  /* DUALSPEED */
1451
1452        usb_gadget_set_selfpowered(gadget);
1453
1454        if (gadget->is_otg) {
1455                otg_desc.bmAttributes |= USB_OTG_HNP,
1456                config_desc.bmAttributes |= USB_CONFIG_ATT_WAKEUP;
1457        }
1458
1459        spin_lock_init(&dev->lock);
1460        mutex_init(&dev->lock_printer_io);
1461        INIT_LIST_HEAD(&dev->tx_reqs);
1462        INIT_LIST_HEAD(&dev->tx_reqs_active);
1463        INIT_LIST_HEAD(&dev->rx_reqs);
1464        INIT_LIST_HEAD(&dev->rx_reqs_active);
1465        INIT_LIST_HEAD(&dev->rx_buffers);
1466        init_waitqueue_head(&dev->rx_wait);
1467        init_waitqueue_head(&dev->tx_wait);
1468        init_waitqueue_head(&dev->tx_flush_wait);
1469
1470        dev->config = 0;
1471        dev->interface = -1;
1472        dev->printer_cdev_open = 0;
1473        dev->printer_status = PRINTER_NOT_ERROR;
1474        dev->current_rx_req = NULL;
1475        dev->current_rx_bytes = 0;
1476        dev->current_rx_buf = NULL;
1477
1478        dev->in_ep = in_ep;
1479        dev->out_ep = out_ep;
1480
1481        /* preallocate control message data and buffer */
1482        dev->req = printer_req_alloc(gadget->ep0, USB_DESC_BUFSIZE,
1483                        GFP_KERNEL);
1484        if (!dev->req) {
1485                status = -ENOMEM;
1486                goto fail;
1487        }
1488
1489        for (i = 0; i < QLEN; i++) {
1490                req = printer_req_alloc(dev->in_ep, USB_BUFSIZE, GFP_KERNEL);
1491                if (!req) {
1492                        while (!list_empty(&dev->tx_reqs)) {
1493                                req = container_of(dev->tx_reqs.next,
1494                                                struct usb_request, list);
1495                                list_del(&req->list);
1496                                printer_req_free(dev->in_ep, req);
1497                        }
1498                        return -ENOMEM;
1499                }
1500                list_add(&req->list, &dev->tx_reqs);
1501        }
1502
1503        for (i = 0; i < QLEN; i++) {
1504                req = printer_req_alloc(dev->out_ep, USB_BUFSIZE, GFP_KERNEL);
1505                if (!req) {
1506                        while (!list_empty(&dev->rx_reqs)) {
1507                                req = container_of(dev->rx_reqs.next,
1508                                                struct usb_request, list);
1509                                list_del(&req->list);
1510                                printer_req_free(dev->out_ep, req);
1511                        }
1512                        return -ENOMEM;
1513                }
1514                list_add(&req->list, &dev->rx_reqs);
1515        }
1516
1517        dev->req->complete = printer_setup_complete;
1518
1519        /* finish hookup to lower layer ... */
1520        dev->gadget = gadget;
1521        set_gadget_data(gadget, dev);
1522        gadget->ep0->driver_data = dev;
1523
1524        INFO(dev, "%s, version: " DRIVER_VERSION "\n", driver_desc);
1525        INFO(dev, "using %s, OUT %s IN %s\n", gadget->name, out_ep->name,
1526                        in_ep->name);
1527
1528        return 0;
1529
1530fail:
1531        printer_unbind(gadget);
1532        return status;
1533}
1534
1535/*-------------------------------------------------------------------------*/
1536
1537static struct usb_gadget_driver printer_driver = {
1538        .max_speed      = DEVSPEED,
1539
1540        .function       = (char *) driver_desc,
1541        .unbind         = printer_unbind,
1542
1543        .setup          = printer_setup,
1544        .disconnect     = printer_disconnect,
1545
1546        .driver         = {
1547                .name           = (char *) shortname,
1548                .owner          = THIS_MODULE,
1549        },
1550};
1551
1552MODULE_DESCRIPTION(DRIVER_DESC);
1553MODULE_AUTHOR("Craig Nadler");
1554MODULE_LICENSE("GPL");
1555
1556static int __init
1557init(void)
1558{
1559        int status;
1560
1561        usb_gadget_class = class_create(THIS_MODULE, "usb_printer_gadget");
1562        if (IS_ERR(usb_gadget_class)) {
1563                status = PTR_ERR(usb_gadget_class);
1564                ERROR(dev, "unable to create usb_gadget class %d\n", status);
1565                return status;
1566        }
1567
1568        status = alloc_chrdev_region(&g_printer_devno, 0, 1,
1569                        "USB printer gadget");
1570        if (status) {
1571                ERROR(dev, "alloc_chrdev_region %d\n", status);
1572                class_destroy(usb_gadget_class);
1573                return status;
1574        }
1575
1576        status = usb_gadget_probe_driver(&printer_driver, printer_bind);
1577        if (status) {
1578                class_destroy(usb_gadget_class);
1579                unregister_chrdev_region(g_printer_devno, 1);
1580                DBG(dev, "usb_gadget_probe_driver %x\n", status);
1581        }
1582
1583        return status;
1584}
1585module_init(init);
1586
1587static void __exit
1588cleanup(void)
1589{
1590        int status;
1591
1592        mutex_lock(&usb_printer_gadget.lock_printer_io);
1593        status = usb_gadget_unregister_driver(&printer_driver);
1594        if (status)
1595                ERROR(dev, "usb_gadget_unregister_driver %x\n", status);
1596
1597        unregister_chrdev_region(g_printer_devno, 1);
1598        class_destroy(usb_gadget_class);
1599        mutex_unlock(&usb_printer_gadget.lock_printer_io);
1600}
1601module_exit(cleanup);
1602
lxr.linux.no kindly hosted by Redpill Linpro AS, provider of Linux consulting and operations services since 1995.