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