Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0-only
0002 /*
0003  * Copyright 2020 Xillybus Ltd, http://xillybus.com
0004  *
0005  * Driver for the XillyUSB FPGA/host framework.
0006  *
0007  * This driver interfaces with a special IP core in an FPGA, setting up
0008  * a pipe between a hardware FIFO in the programmable logic and a device
0009  * file in the host. The number of such pipes and their attributes are
0010  * set up on the logic. This driver detects these automatically and
0011  * creates the device files accordingly.
0012  */
0013 
0014 #include <linux/types.h>
0015 #include <linux/slab.h>
0016 #include <linux/list.h>
0017 #include <linux/device.h>
0018 #include <linux/module.h>
0019 #include <asm/byteorder.h>
0020 #include <linux/io.h>
0021 #include <linux/interrupt.h>
0022 #include <linux/sched.h>
0023 #include <linux/fs.h>
0024 #include <linux/spinlock.h>
0025 #include <linux/mutex.h>
0026 #include <linux/workqueue.h>
0027 #include <linux/crc32.h>
0028 #include <linux/poll.h>
0029 #include <linux/delay.h>
0030 #include <linux/usb.h>
0031 
0032 #include "xillybus_class.h"
0033 
0034 MODULE_DESCRIPTION("Driver for XillyUSB FPGA IP Core");
0035 MODULE_AUTHOR("Eli Billauer, Xillybus Ltd.");
0036 MODULE_ALIAS("xillyusb");
0037 MODULE_LICENSE("GPL v2");
0038 
0039 #define XILLY_RX_TIMEOUT        (10 * HZ / 1000)
0040 #define XILLY_RESPONSE_TIMEOUT      (500 * HZ / 1000)
0041 
0042 #define BUF_SIZE_ORDER          4
0043 #define BUFNUM              8
0044 #define LOG2_IDT_FIFO_SIZE      16
0045 #define LOG2_INITIAL_FIFO_BUF_SIZE  16
0046 
0047 #define MSG_EP_NUM          1
0048 #define IN_EP_NUM           1
0049 
0050 static const char xillyname[] = "xillyusb";
0051 
0052 static unsigned int fifo_buf_order;
0053 
0054 #define USB_VENDOR_ID_XILINX        0x03fd
0055 #define USB_VENDOR_ID_ALTERA        0x09fb
0056 
0057 #define USB_PRODUCT_ID_XILLYUSB     0xebbe
0058 
0059 static const struct usb_device_id xillyusb_table[] = {
0060     { USB_DEVICE(USB_VENDOR_ID_XILINX, USB_PRODUCT_ID_XILLYUSB) },
0061     { USB_DEVICE(USB_VENDOR_ID_ALTERA, USB_PRODUCT_ID_XILLYUSB) },
0062     { }
0063 };
0064 
0065 MODULE_DEVICE_TABLE(usb, xillyusb_table);
0066 
0067 struct xillyusb_dev;
0068 
0069 struct xillyfifo {
0070     unsigned int bufsize; /* In bytes, always a power of 2 */
0071     unsigned int bufnum;
0072     unsigned int size; /* Lazy: Equals bufsize * bufnum */
0073     unsigned int buf_order;
0074 
0075     int fill; /* Number of bytes in the FIFO */
0076     spinlock_t lock;
0077     wait_queue_head_t waitq;
0078 
0079     unsigned int readpos;
0080     unsigned int readbuf;
0081     unsigned int writepos;
0082     unsigned int writebuf;
0083     char **mem;
0084 };
0085 
0086 struct xillyusb_channel;
0087 
0088 struct xillyusb_endpoint {
0089     struct xillyusb_dev *xdev;
0090 
0091     struct mutex ep_mutex; /* serialize operations on endpoint */
0092 
0093     struct list_head buffers;
0094     struct list_head filled_buffers;
0095     spinlock_t buffers_lock; /* protect these two lists */
0096 
0097     unsigned int order;
0098     unsigned int buffer_size;
0099 
0100     unsigned int fill_mask;
0101 
0102     int outstanding_urbs;
0103 
0104     struct usb_anchor anchor;
0105 
0106     struct xillyfifo fifo;
0107 
0108     struct work_struct workitem;
0109 
0110     bool shutting_down;
0111     bool drained;
0112     bool wake_on_drain;
0113 
0114     u8 ep_num;
0115 };
0116 
0117 struct xillyusb_channel {
0118     struct xillyusb_dev *xdev;
0119 
0120     struct xillyfifo *in_fifo;
0121     struct xillyusb_endpoint *out_ep;
0122     struct mutex lock; /* protect @out_ep, @in_fifo, bit fields below */
0123 
0124     struct mutex in_mutex; /* serialize fops on FPGA to host stream */
0125     struct mutex out_mutex; /* serialize fops on host to FPGA stream */
0126     wait_queue_head_t flushq;
0127 
0128     int chan_idx;
0129 
0130     u32 in_consumed_bytes;
0131     u32 in_current_checkpoint;
0132     u32 out_bytes;
0133 
0134     unsigned int in_log2_element_size;
0135     unsigned int out_log2_element_size;
0136     unsigned int in_log2_fifo_size;
0137     unsigned int out_log2_fifo_size;
0138 
0139     unsigned int read_data_ok; /* EOF not arrived (yet) */
0140     unsigned int poll_used;
0141     unsigned int flushing;
0142     unsigned int flushed;
0143     unsigned int canceled;
0144 
0145     /* Bit fields protected by @lock except for initialization */
0146     unsigned readable:1;
0147     unsigned writable:1;
0148     unsigned open_for_read:1;
0149     unsigned open_for_write:1;
0150     unsigned in_synchronous:1;
0151     unsigned out_synchronous:1;
0152     unsigned in_seekable:1;
0153     unsigned out_seekable:1;
0154 };
0155 
0156 struct xillybuffer {
0157     struct list_head entry;
0158     struct xillyusb_endpoint *ep;
0159     void *buf;
0160     unsigned int len;
0161 };
0162 
0163 struct xillyusb_dev {
0164     struct xillyusb_channel *channels;
0165 
0166     struct usb_device   *udev;
0167     struct device       *dev; /* For dev_err() and such */
0168     struct kref     kref;
0169     struct workqueue_struct *workq;
0170 
0171     int error;
0172     spinlock_t error_lock; /* protect @error */
0173     struct work_struct wakeup_workitem;
0174 
0175     int num_channels;
0176 
0177     struct xillyusb_endpoint *msg_ep;
0178     struct xillyusb_endpoint *in_ep;
0179 
0180     struct mutex msg_mutex; /* serialize opcode transmission */
0181     int in_bytes_left;
0182     int leftover_chan_num;
0183     unsigned int in_counter;
0184     struct mutex process_in_mutex; /* synchronize wakeup_all() */
0185 };
0186 
0187 /* FPGA to host opcodes */
0188 enum {
0189     OPCODE_DATA = 0,
0190     OPCODE_QUIESCE_ACK = 1,
0191     OPCODE_EOF = 2,
0192     OPCODE_REACHED_CHECKPOINT = 3,
0193     OPCODE_CANCELED_CHECKPOINT = 4,
0194 };
0195 
0196 /* Host to FPGA opcodes */
0197 enum {
0198     OPCODE_QUIESCE = 0,
0199     OPCODE_REQ_IDT = 1,
0200     OPCODE_SET_CHECKPOINT = 2,
0201     OPCODE_CLOSE = 3,
0202     OPCODE_SET_PUSH = 4,
0203     OPCODE_UPDATE_PUSH = 5,
0204     OPCODE_CANCEL_CHECKPOINT = 6,
0205     OPCODE_SET_ADDR = 7,
0206 };
0207 
0208 /*
0209  * fifo_write() and fifo_read() are NOT reentrant (i.e. concurrent multiple
0210  * calls to each on the same FIFO is not allowed) however it's OK to have
0211  * threads calling each of the two functions once on the same FIFO, and
0212  * at the same time.
0213  */
0214 
0215 static int fifo_write(struct xillyfifo *fifo,
0216               const void *data, unsigned int len,
0217               int (*copier)(void *, const void *, int))
0218 {
0219     unsigned int done = 0;
0220     unsigned int todo = len;
0221     unsigned int nmax;
0222     unsigned int writepos = fifo->writepos;
0223     unsigned int writebuf = fifo->writebuf;
0224     unsigned long flags;
0225     int rc;
0226 
0227     nmax = fifo->size - READ_ONCE(fifo->fill);
0228 
0229     while (1) {
0230         unsigned int nrail = fifo->bufsize - writepos;
0231         unsigned int n = min(todo, nmax);
0232 
0233         if (n == 0) {
0234             spin_lock_irqsave(&fifo->lock, flags);
0235             fifo->fill += done;
0236             spin_unlock_irqrestore(&fifo->lock, flags);
0237 
0238             fifo->writepos = writepos;
0239             fifo->writebuf = writebuf;
0240 
0241             return done;
0242         }
0243 
0244         if (n > nrail)
0245             n = nrail;
0246 
0247         rc = (*copier)(fifo->mem[writebuf] + writepos, data + done, n);
0248 
0249         if (rc)
0250             return rc;
0251 
0252         done += n;
0253         todo -= n;
0254 
0255         writepos += n;
0256         nmax -= n;
0257 
0258         if (writepos == fifo->bufsize) {
0259             writepos = 0;
0260             writebuf++;
0261 
0262             if (writebuf == fifo->bufnum)
0263                 writebuf = 0;
0264         }
0265     }
0266 }
0267 
0268 static int fifo_read(struct xillyfifo *fifo,
0269              void *data, unsigned int len,
0270              int (*copier)(void *, const void *, int))
0271 {
0272     unsigned int done = 0;
0273     unsigned int todo = len;
0274     unsigned int fill;
0275     unsigned int readpos = fifo->readpos;
0276     unsigned int readbuf = fifo->readbuf;
0277     unsigned long flags;
0278     int rc;
0279 
0280     /*
0281      * The spinlock here is necessary, because otherwise fifo->fill
0282      * could have been increased by fifo_write() after writing data
0283      * to the buffer, but this data would potentially not have been
0284      * visible on this thread at the time the updated fifo->fill was.
0285      * That could lead to reading invalid data.
0286      */
0287 
0288     spin_lock_irqsave(&fifo->lock, flags);
0289     fill = fifo->fill;
0290     spin_unlock_irqrestore(&fifo->lock, flags);
0291 
0292     while (1) {
0293         unsigned int nrail = fifo->bufsize - readpos;
0294         unsigned int n = min(todo, fill);
0295 
0296         if (n == 0) {
0297             spin_lock_irqsave(&fifo->lock, flags);
0298             fifo->fill -= done;
0299             spin_unlock_irqrestore(&fifo->lock, flags);
0300 
0301             fifo->readpos = readpos;
0302             fifo->readbuf = readbuf;
0303 
0304             return done;
0305         }
0306 
0307         if (n > nrail)
0308             n = nrail;
0309 
0310         rc = (*copier)(data + done, fifo->mem[readbuf] + readpos, n);
0311 
0312         if (rc)
0313             return rc;
0314 
0315         done += n;
0316         todo -= n;
0317 
0318         readpos += n;
0319         fill -= n;
0320 
0321         if (readpos == fifo->bufsize) {
0322             readpos = 0;
0323             readbuf++;
0324 
0325             if (readbuf == fifo->bufnum)
0326                 readbuf = 0;
0327         }
0328     }
0329 }
0330 
0331 /*
0332  * These three wrapper functions are used as the @copier argument to
0333  * fifo_write() and fifo_read(), so that they can work directly with
0334  * user memory as well.
0335  */
0336 
0337 static int xilly_copy_from_user(void *dst, const void *src, int n)
0338 {
0339     if (copy_from_user(dst, (const void __user *)src, n))
0340         return -EFAULT;
0341 
0342     return 0;
0343 }
0344 
0345 static int xilly_copy_to_user(void *dst, const void *src, int n)
0346 {
0347     if (copy_to_user((void __user *)dst, src, n))
0348         return -EFAULT;
0349 
0350     return 0;
0351 }
0352 
0353 static int xilly_memcpy(void *dst, const void *src, int n)
0354 {
0355     memcpy(dst, src, n);
0356 
0357     return 0;
0358 }
0359 
0360 static int fifo_init(struct xillyfifo *fifo,
0361              unsigned int log2_size)
0362 {
0363     unsigned int log2_bufnum;
0364     unsigned int buf_order;
0365     int i;
0366 
0367     unsigned int log2_fifo_buf_size;
0368 
0369 retry:
0370     log2_fifo_buf_size = fifo_buf_order + PAGE_SHIFT;
0371 
0372     if (log2_size > log2_fifo_buf_size) {
0373         log2_bufnum = log2_size - log2_fifo_buf_size;
0374         buf_order = fifo_buf_order;
0375         fifo->bufsize = 1 << log2_fifo_buf_size;
0376     } else {
0377         log2_bufnum = 0;
0378         buf_order = (log2_size > PAGE_SHIFT) ?
0379             log2_size - PAGE_SHIFT : 0;
0380         fifo->bufsize = 1 << log2_size;
0381     }
0382 
0383     fifo->bufnum = 1 << log2_bufnum;
0384     fifo->size = fifo->bufnum * fifo->bufsize;
0385     fifo->buf_order = buf_order;
0386 
0387     fifo->mem = kmalloc_array(fifo->bufnum, sizeof(void *), GFP_KERNEL);
0388 
0389     if (!fifo->mem)
0390         return -ENOMEM;
0391 
0392     for (i = 0; i < fifo->bufnum; i++) {
0393         fifo->mem[i] = (void *)
0394             __get_free_pages(GFP_KERNEL, buf_order);
0395 
0396         if (!fifo->mem[i])
0397             goto memfail;
0398     }
0399 
0400     fifo->fill = 0;
0401     fifo->readpos = 0;
0402     fifo->readbuf = 0;
0403     fifo->writepos = 0;
0404     fifo->writebuf = 0;
0405     spin_lock_init(&fifo->lock);
0406     init_waitqueue_head(&fifo->waitq);
0407     return 0;
0408 
0409 memfail:
0410     for (i--; i >= 0; i--)
0411         free_pages((unsigned long)fifo->mem[i], buf_order);
0412 
0413     kfree(fifo->mem);
0414     fifo->mem = NULL;
0415 
0416     if (fifo_buf_order) {
0417         fifo_buf_order--;
0418         goto retry;
0419     } else {
0420         return -ENOMEM;
0421     }
0422 }
0423 
0424 static void fifo_mem_release(struct xillyfifo *fifo)
0425 {
0426     int i;
0427 
0428     if (!fifo->mem)
0429         return;
0430 
0431     for (i = 0; i < fifo->bufnum; i++)
0432         free_pages((unsigned long)fifo->mem[i], fifo->buf_order);
0433 
0434     kfree(fifo->mem);
0435 }
0436 
0437 /*
0438  * When endpoint_quiesce() returns, the endpoint has no URBs submitted,
0439  * won't accept any new URB submissions, and its related work item doesn't
0440  * and won't run anymore.
0441  */
0442 
0443 static void endpoint_quiesce(struct xillyusb_endpoint *ep)
0444 {
0445     mutex_lock(&ep->ep_mutex);
0446     ep->shutting_down = true;
0447     mutex_unlock(&ep->ep_mutex);
0448 
0449     usb_kill_anchored_urbs(&ep->anchor);
0450     cancel_work_sync(&ep->workitem);
0451 }
0452 
0453 /*
0454  * Note that endpoint_dealloc() also frees fifo memory (if allocated), even
0455  * though endpoint_alloc doesn't allocate that memory.
0456  */
0457 
0458 static void endpoint_dealloc(struct xillyusb_endpoint *ep)
0459 {
0460     struct list_head *this, *next;
0461 
0462     fifo_mem_release(&ep->fifo);
0463 
0464     /* Join @filled_buffers with @buffers to free these entries too */
0465     list_splice(&ep->filled_buffers, &ep->buffers);
0466 
0467     list_for_each_safe(this, next, &ep->buffers) {
0468         struct xillybuffer *xb =
0469             list_entry(this, struct xillybuffer, entry);
0470 
0471         free_pages((unsigned long)xb->buf, ep->order);
0472         kfree(xb);
0473     }
0474 
0475     kfree(ep);
0476 }
0477 
0478 static struct xillyusb_endpoint
0479 *endpoint_alloc(struct xillyusb_dev *xdev,
0480         u8 ep_num,
0481         void (*work)(struct work_struct *),
0482         unsigned int order,
0483         int bufnum)
0484 {
0485     int i;
0486 
0487     struct xillyusb_endpoint *ep;
0488 
0489     ep = kzalloc(sizeof(*ep), GFP_KERNEL);
0490 
0491     if (!ep)
0492         return NULL;
0493 
0494     INIT_LIST_HEAD(&ep->buffers);
0495     INIT_LIST_HEAD(&ep->filled_buffers);
0496 
0497     spin_lock_init(&ep->buffers_lock);
0498     mutex_init(&ep->ep_mutex);
0499 
0500     init_usb_anchor(&ep->anchor);
0501     INIT_WORK(&ep->workitem, work);
0502 
0503     ep->order = order;
0504     ep->buffer_size =  1 << (PAGE_SHIFT + order);
0505     ep->outstanding_urbs = 0;
0506     ep->drained = true;
0507     ep->wake_on_drain = false;
0508     ep->xdev = xdev;
0509     ep->ep_num = ep_num;
0510     ep->shutting_down = false;
0511 
0512     for (i = 0; i < bufnum; i++) {
0513         struct xillybuffer *xb;
0514         unsigned long addr;
0515 
0516         xb = kzalloc(sizeof(*xb), GFP_KERNEL);
0517 
0518         if (!xb) {
0519             endpoint_dealloc(ep);
0520             return NULL;
0521         }
0522 
0523         addr = __get_free_pages(GFP_KERNEL, order);
0524 
0525         if (!addr) {
0526             kfree(xb);
0527             endpoint_dealloc(ep);
0528             return NULL;
0529         }
0530 
0531         xb->buf = (void *)addr;
0532         xb->ep = ep;
0533         list_add_tail(&xb->entry, &ep->buffers);
0534     }
0535     return ep;
0536 }
0537 
0538 static void cleanup_dev(struct kref *kref)
0539 {
0540     struct xillyusb_dev *xdev =
0541         container_of(kref, struct xillyusb_dev, kref);
0542 
0543     if (xdev->in_ep)
0544         endpoint_dealloc(xdev->in_ep);
0545 
0546     if (xdev->msg_ep)
0547         endpoint_dealloc(xdev->msg_ep);
0548 
0549     if (xdev->workq)
0550         destroy_workqueue(xdev->workq);
0551 
0552     usb_put_dev(xdev->udev);
0553     kfree(xdev->channels); /* Argument may be NULL, and that's fine */
0554     kfree(xdev);
0555 }
0556 
0557 /*
0558  * @process_in_mutex is taken to ensure that bulk_in_work() won't call
0559  * process_bulk_in() after wakeup_all()'s execution: The latter zeroes all
0560  * @read_data_ok entries, which will make process_bulk_in() report false
0561  * errors if executed. The mechanism relies on that xdev->error is assigned
0562  * a non-zero value by report_io_error() prior to queueing wakeup_all(),
0563  * which prevents bulk_in_work() from calling process_bulk_in().
0564  *
0565  * The fact that wakeup_all() and bulk_in_work() are queued on the same
0566  * workqueue makes their concurrent execution very unlikely, however the
0567  * kernel's API doesn't seem to ensure this strictly.
0568  */
0569 
0570 static void wakeup_all(struct work_struct *work)
0571 {
0572     int i;
0573     struct xillyusb_dev *xdev = container_of(work, struct xillyusb_dev,
0574                          wakeup_workitem);
0575 
0576     mutex_lock(&xdev->process_in_mutex);
0577 
0578     for (i = 0; i < xdev->num_channels; i++) {
0579         struct xillyusb_channel *chan = &xdev->channels[i];
0580 
0581         mutex_lock(&chan->lock);
0582 
0583         if (chan->in_fifo) {
0584             /*
0585              * Fake an EOF: Even if such arrives, it won't be
0586              * processed.
0587              */
0588             chan->read_data_ok = 0;
0589             wake_up_interruptible(&chan->in_fifo->waitq);
0590         }
0591 
0592         if (chan->out_ep)
0593             wake_up_interruptible(&chan->out_ep->fifo.waitq);
0594 
0595         mutex_unlock(&chan->lock);
0596 
0597         wake_up_interruptible(&chan->flushq);
0598     }
0599 
0600     mutex_unlock(&xdev->process_in_mutex);
0601 
0602     wake_up_interruptible(&xdev->msg_ep->fifo.waitq);
0603 
0604     kref_put(&xdev->kref, cleanup_dev);
0605 }
0606 
0607 static void report_io_error(struct xillyusb_dev *xdev,
0608                 int errcode)
0609 {
0610     unsigned long flags;
0611     bool do_once = false;
0612 
0613     spin_lock_irqsave(&xdev->error_lock, flags);
0614     if (!xdev->error) {
0615         xdev->error = errcode;
0616         do_once = true;
0617     }
0618     spin_unlock_irqrestore(&xdev->error_lock, flags);
0619 
0620     if (do_once) {
0621         kref_get(&xdev->kref); /* xdev is used by work item */
0622         queue_work(xdev->workq, &xdev->wakeup_workitem);
0623     }
0624 }
0625 
0626 /*
0627  * safely_assign_in_fifo() changes the value of chan->in_fifo and ensures
0628  * the previous pointer is never used after its return.
0629  */
0630 
0631 static void safely_assign_in_fifo(struct xillyusb_channel *chan,
0632                   struct xillyfifo *fifo)
0633 {
0634     mutex_lock(&chan->lock);
0635     chan->in_fifo = fifo;
0636     mutex_unlock(&chan->lock);
0637 
0638     flush_work(&chan->xdev->in_ep->workitem);
0639 }
0640 
0641 static void bulk_in_completer(struct urb *urb)
0642 {
0643     struct xillybuffer *xb = urb->context;
0644     struct xillyusb_endpoint *ep = xb->ep;
0645     unsigned long flags;
0646 
0647     if (urb->status) {
0648         if (!(urb->status == -ENOENT ||
0649               urb->status == -ECONNRESET ||
0650               urb->status == -ESHUTDOWN))
0651             report_io_error(ep->xdev, -EIO);
0652 
0653         spin_lock_irqsave(&ep->buffers_lock, flags);
0654         list_add_tail(&xb->entry, &ep->buffers);
0655         ep->outstanding_urbs--;
0656         spin_unlock_irqrestore(&ep->buffers_lock, flags);
0657 
0658         return;
0659     }
0660 
0661     xb->len = urb->actual_length;
0662 
0663     spin_lock_irqsave(&ep->buffers_lock, flags);
0664     list_add_tail(&xb->entry, &ep->filled_buffers);
0665     spin_unlock_irqrestore(&ep->buffers_lock, flags);
0666 
0667     if (!ep->shutting_down)
0668         queue_work(ep->xdev->workq, &ep->workitem);
0669 }
0670 
0671 static void bulk_out_completer(struct urb *urb)
0672 {
0673     struct xillybuffer *xb = urb->context;
0674     struct xillyusb_endpoint *ep = xb->ep;
0675     unsigned long flags;
0676 
0677     if (urb->status &&
0678         (!(urb->status == -ENOENT ||
0679            urb->status == -ECONNRESET ||
0680            urb->status == -ESHUTDOWN)))
0681         report_io_error(ep->xdev, -EIO);
0682 
0683     spin_lock_irqsave(&ep->buffers_lock, flags);
0684     list_add_tail(&xb->entry, &ep->buffers);
0685     ep->outstanding_urbs--;
0686     spin_unlock_irqrestore(&ep->buffers_lock, flags);
0687 
0688     if (!ep->shutting_down)
0689         queue_work(ep->xdev->workq, &ep->workitem);
0690 }
0691 
0692 static void try_queue_bulk_in(struct xillyusb_endpoint *ep)
0693 {
0694     struct xillyusb_dev *xdev = ep->xdev;
0695     struct xillybuffer *xb;
0696     struct urb *urb;
0697 
0698     int rc;
0699     unsigned long flags;
0700     unsigned int bufsize = ep->buffer_size;
0701 
0702     mutex_lock(&ep->ep_mutex);
0703 
0704     if (ep->shutting_down || xdev->error)
0705         goto done;
0706 
0707     while (1) {
0708         spin_lock_irqsave(&ep->buffers_lock, flags);
0709 
0710         if (list_empty(&ep->buffers)) {
0711             spin_unlock_irqrestore(&ep->buffers_lock, flags);
0712             goto done;
0713         }
0714 
0715         xb = list_first_entry(&ep->buffers, struct xillybuffer, entry);
0716         list_del(&xb->entry);
0717         ep->outstanding_urbs++;
0718 
0719         spin_unlock_irqrestore(&ep->buffers_lock, flags);
0720 
0721         urb = usb_alloc_urb(0, GFP_KERNEL);
0722         if (!urb) {
0723             report_io_error(xdev, -ENOMEM);
0724             goto relist;
0725         }
0726 
0727         usb_fill_bulk_urb(urb, xdev->udev,
0728                   usb_rcvbulkpipe(xdev->udev, ep->ep_num),
0729                   xb->buf, bufsize, bulk_in_completer, xb);
0730 
0731         usb_anchor_urb(urb, &ep->anchor);
0732 
0733         rc = usb_submit_urb(urb, GFP_KERNEL);
0734 
0735         if (rc) {
0736             report_io_error(xdev, (rc == -ENOMEM) ? -ENOMEM :
0737                     -EIO);
0738             goto unanchor;
0739         }
0740 
0741         usb_free_urb(urb); /* This just decrements reference count */
0742     }
0743 
0744 unanchor:
0745     usb_unanchor_urb(urb);
0746     usb_free_urb(urb);
0747 
0748 relist:
0749     spin_lock_irqsave(&ep->buffers_lock, flags);
0750     list_add_tail(&xb->entry, &ep->buffers);
0751     ep->outstanding_urbs--;
0752     spin_unlock_irqrestore(&ep->buffers_lock, flags);
0753 
0754 done:
0755     mutex_unlock(&ep->ep_mutex);
0756 }
0757 
0758 static void try_queue_bulk_out(struct xillyusb_endpoint *ep)
0759 {
0760     struct xillyfifo *fifo = &ep->fifo;
0761     struct xillyusb_dev *xdev = ep->xdev;
0762     struct xillybuffer *xb;
0763     struct urb *urb;
0764 
0765     int rc;
0766     unsigned int fill;
0767     unsigned long flags;
0768     bool do_wake = false;
0769 
0770     mutex_lock(&ep->ep_mutex);
0771 
0772     if (ep->shutting_down || xdev->error)
0773         goto done;
0774 
0775     fill = READ_ONCE(fifo->fill) & ep->fill_mask;
0776 
0777     while (1) {
0778         int count;
0779         unsigned int max_read;
0780 
0781         spin_lock_irqsave(&ep->buffers_lock, flags);
0782 
0783         /*
0784          * Race conditions might have the FIFO filled while the
0785          * endpoint is marked as drained here. That doesn't matter,
0786          * because the sole purpose of @drained is to ensure that
0787          * certain data has been sent on the USB channel before
0788          * shutting it down. Hence knowing that the FIFO appears
0789          * to be empty with no outstanding URBs at some moment
0790          * is good enough.
0791          */
0792 
0793         if (!fill) {
0794             ep->drained = !ep->outstanding_urbs;
0795             if (ep->drained && ep->wake_on_drain)
0796                 do_wake = true;
0797 
0798             spin_unlock_irqrestore(&ep->buffers_lock, flags);
0799             goto done;
0800         }
0801 
0802         ep->drained = false;
0803 
0804         if ((fill < ep->buffer_size && ep->outstanding_urbs) ||
0805             list_empty(&ep->buffers)) {
0806             spin_unlock_irqrestore(&ep->buffers_lock, flags);
0807             goto done;
0808         }
0809 
0810         xb = list_first_entry(&ep->buffers, struct xillybuffer, entry);
0811         list_del(&xb->entry);
0812         ep->outstanding_urbs++;
0813 
0814         spin_unlock_irqrestore(&ep->buffers_lock, flags);
0815 
0816         max_read = min(fill, ep->buffer_size);
0817 
0818         count = fifo_read(&ep->fifo, xb->buf, max_read, xilly_memcpy);
0819 
0820         /*
0821          * xilly_memcpy always returns 0 => fifo_read can't fail =>
0822          * count > 0
0823          */
0824 
0825         urb = usb_alloc_urb(0, GFP_KERNEL);
0826         if (!urb) {
0827             report_io_error(xdev, -ENOMEM);
0828             goto relist;
0829         }
0830 
0831         usb_fill_bulk_urb(urb, xdev->udev,
0832                   usb_sndbulkpipe(xdev->udev, ep->ep_num),
0833                   xb->buf, count, bulk_out_completer, xb);
0834 
0835         usb_anchor_urb(urb, &ep->anchor);
0836 
0837         rc = usb_submit_urb(urb, GFP_KERNEL);
0838 
0839         if (rc) {
0840             report_io_error(xdev, (rc == -ENOMEM) ? -ENOMEM :
0841                     -EIO);
0842             goto unanchor;
0843         }
0844 
0845         usb_free_urb(urb); /* This just decrements reference count */
0846 
0847         fill -= count;
0848         do_wake = true;
0849     }
0850 
0851 unanchor:
0852     usb_unanchor_urb(urb);
0853     usb_free_urb(urb);
0854 
0855 relist:
0856     spin_lock_irqsave(&ep->buffers_lock, flags);
0857     list_add_tail(&xb->entry, &ep->buffers);
0858     ep->outstanding_urbs--;
0859     spin_unlock_irqrestore(&ep->buffers_lock, flags);
0860 
0861 done:
0862     mutex_unlock(&ep->ep_mutex);
0863 
0864     if (do_wake)
0865         wake_up_interruptible(&fifo->waitq);
0866 }
0867 
0868 static void bulk_out_work(struct work_struct *work)
0869 {
0870     struct xillyusb_endpoint *ep = container_of(work,
0871                             struct xillyusb_endpoint,
0872                             workitem);
0873     try_queue_bulk_out(ep);
0874 }
0875 
0876 static int process_in_opcode(struct xillyusb_dev *xdev,
0877                  int opcode,
0878                  int chan_num)
0879 {
0880     struct xillyusb_channel *chan;
0881     struct device *dev = xdev->dev;
0882     int chan_idx = chan_num >> 1;
0883 
0884     if (chan_idx >= xdev->num_channels) {
0885         dev_err(dev, "Received illegal channel ID %d from FPGA\n",
0886             chan_num);
0887         return -EIO;
0888     }
0889 
0890     chan = &xdev->channels[chan_idx];
0891 
0892     switch (opcode) {
0893     case OPCODE_EOF:
0894         if (!chan->read_data_ok) {
0895             dev_err(dev, "Received unexpected EOF for channel %d\n",
0896                 chan_num);
0897             return -EIO;
0898         }
0899 
0900         /*
0901          * A write memory barrier ensures that the FIFO's fill level
0902          * is visible before read_data_ok turns zero, so the data in
0903          * the FIFO isn't missed by the consumer.
0904          */
0905         smp_wmb();
0906         WRITE_ONCE(chan->read_data_ok, 0);
0907         wake_up_interruptible(&chan->in_fifo->waitq);
0908         break;
0909 
0910     case OPCODE_REACHED_CHECKPOINT:
0911         chan->flushing = 0;
0912         wake_up_interruptible(&chan->flushq);
0913         break;
0914 
0915     case OPCODE_CANCELED_CHECKPOINT:
0916         chan->canceled = 1;
0917         wake_up_interruptible(&chan->flushq);
0918         break;
0919 
0920     default:
0921         dev_err(dev, "Received illegal opcode %d from FPGA\n",
0922             opcode);
0923         return -EIO;
0924     }
0925 
0926     return 0;
0927 }
0928 
0929 static int process_bulk_in(struct xillybuffer *xb)
0930 {
0931     struct xillyusb_endpoint *ep = xb->ep;
0932     struct xillyusb_dev *xdev = ep->xdev;
0933     struct device *dev = xdev->dev;
0934     int dws = xb->len >> 2;
0935     __le32 *p = xb->buf;
0936     u32 ctrlword;
0937     struct xillyusb_channel *chan;
0938     struct xillyfifo *fifo;
0939     int chan_num = 0, opcode;
0940     int chan_idx;
0941     int bytes, count, dwconsume;
0942     int in_bytes_left = 0;
0943     int rc;
0944 
0945     if ((dws << 2) != xb->len) {
0946         dev_err(dev, "Received BULK IN transfer with %d bytes, not a multiple of 4\n",
0947             xb->len);
0948         return -EIO;
0949     }
0950 
0951     if (xdev->in_bytes_left) {
0952         bytes = min(xdev->in_bytes_left, dws << 2);
0953         in_bytes_left = xdev->in_bytes_left - bytes;
0954         chan_num = xdev->leftover_chan_num;
0955         goto resume_leftovers;
0956     }
0957 
0958     while (dws) {
0959         ctrlword = le32_to_cpu(*p++);
0960         dws--;
0961 
0962         chan_num = ctrlword & 0xfff;
0963         count = (ctrlword >> 12) & 0x3ff;
0964         opcode = (ctrlword >> 24) & 0xf;
0965 
0966         if (opcode != OPCODE_DATA) {
0967             unsigned int in_counter = xdev->in_counter++ & 0x3ff;
0968 
0969             if (count != in_counter) {
0970                 dev_err(dev, "Expected opcode counter %d, got %d\n",
0971                     in_counter, count);
0972                 return -EIO;
0973             }
0974 
0975             rc = process_in_opcode(xdev, opcode, chan_num);
0976 
0977             if (rc)
0978                 return rc;
0979 
0980             continue;
0981         }
0982 
0983         bytes = min(count + 1, dws << 2);
0984         in_bytes_left = count + 1 - bytes;
0985 
0986 resume_leftovers:
0987         chan_idx = chan_num >> 1;
0988 
0989         if (!(chan_num & 1) || chan_idx >= xdev->num_channels ||
0990             !xdev->channels[chan_idx].read_data_ok) {
0991             dev_err(dev, "Received illegal channel ID %d from FPGA\n",
0992                 chan_num);
0993             return -EIO;
0994         }
0995         chan = &xdev->channels[chan_idx];
0996 
0997         fifo = chan->in_fifo;
0998 
0999         if (unlikely(!fifo))
1000             return -EIO; /* We got really unexpected data */
1001 
1002         if (bytes != fifo_write(fifo, p, bytes, xilly_memcpy)) {
1003             dev_err(dev, "Misbehaving FPGA overflowed an upstream FIFO!\n");
1004             return -EIO;
1005         }
1006 
1007         wake_up_interruptible(&fifo->waitq);
1008 
1009         dwconsume = (bytes + 3) >> 2;
1010         dws -= dwconsume;
1011         p += dwconsume;
1012     }
1013 
1014     xdev->in_bytes_left = in_bytes_left;
1015     xdev->leftover_chan_num = chan_num;
1016     return 0;
1017 }
1018 
1019 static void bulk_in_work(struct work_struct *work)
1020 {
1021     struct xillyusb_endpoint *ep =
1022         container_of(work, struct xillyusb_endpoint, workitem);
1023     struct xillyusb_dev *xdev = ep->xdev;
1024     unsigned long flags;
1025     struct xillybuffer *xb;
1026     bool consumed = false;
1027     int rc = 0;
1028 
1029     mutex_lock(&xdev->process_in_mutex);
1030 
1031     spin_lock_irqsave(&ep->buffers_lock, flags);
1032 
1033     while (1) {
1034         if (rc || list_empty(&ep->filled_buffers)) {
1035             spin_unlock_irqrestore(&ep->buffers_lock, flags);
1036             mutex_unlock(&xdev->process_in_mutex);
1037 
1038             if (rc)
1039                 report_io_error(xdev, rc);
1040             else if (consumed)
1041                 try_queue_bulk_in(ep);
1042 
1043             return;
1044         }
1045 
1046         xb = list_first_entry(&ep->filled_buffers, struct xillybuffer,
1047                       entry);
1048         list_del(&xb->entry);
1049 
1050         spin_unlock_irqrestore(&ep->buffers_lock, flags);
1051 
1052         consumed = true;
1053 
1054         if (!xdev->error)
1055             rc = process_bulk_in(xb);
1056 
1057         spin_lock_irqsave(&ep->buffers_lock, flags);
1058         list_add_tail(&xb->entry, &ep->buffers);
1059         ep->outstanding_urbs--;
1060     }
1061 }
1062 
1063 static int xillyusb_send_opcode(struct xillyusb_dev *xdev,
1064                 int chan_num, char opcode, u32 data)
1065 {
1066     struct xillyusb_endpoint *ep = xdev->msg_ep;
1067     struct xillyfifo *fifo = &ep->fifo;
1068     __le32 msg[2];
1069 
1070     int rc = 0;
1071 
1072     msg[0] = cpu_to_le32((chan_num & 0xfff) |
1073                  ((opcode & 0xf) << 24));
1074     msg[1] = cpu_to_le32(data);
1075 
1076     mutex_lock(&xdev->msg_mutex);
1077 
1078     /*
1079      * The wait queue is woken with the interruptible variant, so the
1080      * wait function matches, however returning because of an interrupt
1081      * will mess things up considerably, in particular when the caller is
1082      * the release method. And the xdev->error part prevents being stuck
1083      * forever in the event of a bizarre hardware bug: Pull the USB plug.
1084      */
1085 
1086     while (wait_event_interruptible(fifo->waitq,
1087                     fifo->fill <= (fifo->size - 8) ||
1088                     xdev->error))
1089         ; /* Empty loop */
1090 
1091     if (xdev->error) {
1092         rc = xdev->error;
1093         goto unlock_done;
1094     }
1095 
1096     fifo_write(fifo, (void *)msg, 8, xilly_memcpy);
1097 
1098     try_queue_bulk_out(ep);
1099 
1100 unlock_done:
1101     mutex_unlock(&xdev->msg_mutex);
1102 
1103     return rc;
1104 }
1105 
1106 /*
1107  * Note that flush_downstream() merely waits for the data to arrive to
1108  * the application logic at the FPGA -- unlike PCIe Xillybus' counterpart,
1109  * it does nothing to make it happen (and neither is it necessary).
1110  *
1111  * This function is not reentrant for the same @chan, but this is covered
1112  * by the fact that for any given @chan, it's called either by the open,
1113  * write, llseek and flush fops methods, which can't run in parallel (and the
1114  * write + flush and llseek method handlers are protected with out_mutex).
1115  *
1116  * chan->flushed is there to avoid multiple flushes at the same position,
1117  * in particular as a result of programs that close the file descriptor
1118  * e.g. after a dup2() for redirection.
1119  */
1120 
1121 static int flush_downstream(struct xillyusb_channel *chan,
1122                 long timeout,
1123                 bool interruptible)
1124 {
1125     struct xillyusb_dev *xdev = chan->xdev;
1126     int chan_num = chan->chan_idx << 1;
1127     long deadline, left_to_sleep;
1128     int rc;
1129 
1130     if (chan->flushed)
1131         return 0;
1132 
1133     deadline = jiffies + 1 + timeout;
1134 
1135     if (chan->flushing) {
1136         long cancel_deadline = jiffies + 1 + XILLY_RESPONSE_TIMEOUT;
1137 
1138         chan->canceled = 0;
1139         rc = xillyusb_send_opcode(xdev, chan_num,
1140                       OPCODE_CANCEL_CHECKPOINT, 0);
1141 
1142         if (rc)
1143             return rc; /* Only real error, never -EINTR */
1144 
1145         /* Ignoring interrupts. Cancellation must be handled */
1146         while (!chan->canceled) {
1147             left_to_sleep = cancel_deadline - ((long)jiffies);
1148 
1149             if (left_to_sleep <= 0) {
1150                 report_io_error(xdev, -EIO);
1151                 return -EIO;
1152             }
1153 
1154             rc = wait_event_interruptible_timeout(chan->flushq,
1155                                   chan->canceled ||
1156                                   xdev->error,
1157                                   left_to_sleep);
1158 
1159             if (xdev->error)
1160                 return xdev->error;
1161         }
1162     }
1163 
1164     chan->flushing = 1;
1165 
1166     /*
1167      * The checkpoint is given in terms of data elements, not bytes. As
1168      * a result, if less than an element's worth of data is stored in the
1169      * FIFO, it's not flushed, including the flush before closing, which
1170      * means that such data is lost. This is consistent with PCIe Xillybus.
1171      */
1172 
1173     rc = xillyusb_send_opcode(xdev, chan_num,
1174                   OPCODE_SET_CHECKPOINT,
1175                   chan->out_bytes >>
1176                   chan->out_log2_element_size);
1177 
1178     if (rc)
1179         return rc; /* Only real error, never -EINTR */
1180 
1181     if (!timeout) {
1182         while (chan->flushing) {
1183             rc = wait_event_interruptible(chan->flushq,
1184                               !chan->flushing ||
1185                               xdev->error);
1186             if (xdev->error)
1187                 return xdev->error;
1188 
1189             if (interruptible && rc)
1190                 return -EINTR;
1191         }
1192 
1193         goto done;
1194     }
1195 
1196     while (chan->flushing) {
1197         left_to_sleep = deadline - ((long)jiffies);
1198 
1199         if (left_to_sleep <= 0)
1200             return -ETIMEDOUT;
1201 
1202         rc = wait_event_interruptible_timeout(chan->flushq,
1203                               !chan->flushing ||
1204                               xdev->error,
1205                               left_to_sleep);
1206 
1207         if (xdev->error)
1208             return xdev->error;
1209 
1210         if (interruptible && rc < 0)
1211             return -EINTR;
1212     }
1213 
1214 done:
1215     chan->flushed = 1;
1216     return 0;
1217 }
1218 
1219 /* request_read_anything(): Ask the FPGA for any little amount of data */
1220 static int request_read_anything(struct xillyusb_channel *chan,
1221                  char opcode)
1222 {
1223     struct xillyusb_dev *xdev = chan->xdev;
1224     unsigned int sh = chan->in_log2_element_size;
1225     int chan_num = (chan->chan_idx << 1) | 1;
1226     u32 mercy = chan->in_consumed_bytes + (2 << sh) - 1;
1227 
1228     return xillyusb_send_opcode(xdev, chan_num, opcode, mercy >> sh);
1229 }
1230 
1231 static int xillyusb_open(struct inode *inode, struct file *filp)
1232 {
1233     struct xillyusb_dev *xdev;
1234     struct xillyusb_channel *chan;
1235     struct xillyfifo *in_fifo = NULL;
1236     struct xillyusb_endpoint *out_ep = NULL;
1237     int rc;
1238     int index;
1239 
1240     rc = xillybus_find_inode(inode, (void **)&xdev, &index);
1241     if (rc)
1242         return rc;
1243 
1244     chan = &xdev->channels[index];
1245     filp->private_data = chan;
1246 
1247     mutex_lock(&chan->lock);
1248 
1249     rc = -ENODEV;
1250 
1251     if (xdev->error)
1252         goto unmutex_fail;
1253 
1254     if (((filp->f_mode & FMODE_READ) && !chan->readable) ||
1255         ((filp->f_mode & FMODE_WRITE) && !chan->writable))
1256         goto unmutex_fail;
1257 
1258     if ((filp->f_flags & O_NONBLOCK) && (filp->f_mode & FMODE_READ) &&
1259         chan->in_synchronous) {
1260         dev_err(xdev->dev,
1261             "open() failed: O_NONBLOCK not allowed for read on this device\n");
1262         goto unmutex_fail;
1263     }
1264 
1265     if ((filp->f_flags & O_NONBLOCK) && (filp->f_mode & FMODE_WRITE) &&
1266         chan->out_synchronous) {
1267         dev_err(xdev->dev,
1268             "open() failed: O_NONBLOCK not allowed for write on this device\n");
1269         goto unmutex_fail;
1270     }
1271 
1272     rc = -EBUSY;
1273 
1274     if (((filp->f_mode & FMODE_READ) && chan->open_for_read) ||
1275         ((filp->f_mode & FMODE_WRITE) && chan->open_for_write))
1276         goto unmutex_fail;
1277 
1278     kref_get(&xdev->kref);
1279 
1280     if (filp->f_mode & FMODE_READ)
1281         chan->open_for_read = 1;
1282 
1283     if (filp->f_mode & FMODE_WRITE)
1284         chan->open_for_write = 1;
1285 
1286     mutex_unlock(&chan->lock);
1287 
1288     if (filp->f_mode & FMODE_WRITE) {
1289         out_ep = endpoint_alloc(xdev,
1290                     (chan->chan_idx + 2) | USB_DIR_OUT,
1291                     bulk_out_work, BUF_SIZE_ORDER, BUFNUM);
1292 
1293         if (!out_ep) {
1294             rc = -ENOMEM;
1295             goto unopen;
1296         }
1297 
1298         rc = fifo_init(&out_ep->fifo, chan->out_log2_fifo_size);
1299 
1300         if (rc)
1301             goto late_unopen;
1302 
1303         out_ep->fill_mask = -(1 << chan->out_log2_element_size);
1304         chan->out_bytes = 0;
1305         chan->flushed = 0;
1306 
1307         /*
1308          * Sending a flush request to a previously closed stream
1309          * effectively opens it, and also waits until the command is
1310          * confirmed by the FPGA. The latter is necessary because the
1311          * data is sent through a separate BULK OUT endpoint, and the
1312          * xHCI controller is free to reorder transmissions.
1313          *
1314          * This can't go wrong unless there's a serious hardware error
1315          * (or the computer is stuck for 500 ms?)
1316          */
1317         rc = flush_downstream(chan, XILLY_RESPONSE_TIMEOUT, false);
1318 
1319         if (rc == -ETIMEDOUT) {
1320             rc = -EIO;
1321             report_io_error(xdev, rc);
1322         }
1323 
1324         if (rc)
1325             goto late_unopen;
1326     }
1327 
1328     if (filp->f_mode & FMODE_READ) {
1329         in_fifo = kzalloc(sizeof(*in_fifo), GFP_KERNEL);
1330 
1331         if (!in_fifo) {
1332             rc = -ENOMEM;
1333             goto late_unopen;
1334         }
1335 
1336         rc = fifo_init(in_fifo, chan->in_log2_fifo_size);
1337 
1338         if (rc) {
1339             kfree(in_fifo);
1340             goto late_unopen;
1341         }
1342     }
1343 
1344     mutex_lock(&chan->lock);
1345     if (in_fifo) {
1346         chan->in_fifo = in_fifo;
1347         chan->read_data_ok = 1;
1348     }
1349     if (out_ep)
1350         chan->out_ep = out_ep;
1351     mutex_unlock(&chan->lock);
1352 
1353     if (in_fifo) {
1354         u32 in_checkpoint = 0;
1355 
1356         if (!chan->in_synchronous)
1357             in_checkpoint = in_fifo->size >>
1358                 chan->in_log2_element_size;
1359 
1360         chan->in_consumed_bytes = 0;
1361         chan->poll_used = 0;
1362         chan->in_current_checkpoint = in_checkpoint;
1363         rc = xillyusb_send_opcode(xdev, (chan->chan_idx << 1) | 1,
1364                       OPCODE_SET_CHECKPOINT,
1365                       in_checkpoint);
1366 
1367         if (rc) /* Failure guarantees that opcode wasn't sent */
1368             goto unfifo;
1369 
1370         /*
1371          * In non-blocking mode, request the FPGA to send any data it
1372          * has right away. Otherwise, the first read() will always
1373          * return -EAGAIN, which is OK strictly speaking, but ugly.
1374          * Checking and unrolling if this fails isn't worth the
1375          * effort -- the error is propagated to the first read()
1376          * anyhow.
1377          */
1378         if (filp->f_flags & O_NONBLOCK)
1379             request_read_anything(chan, OPCODE_SET_PUSH);
1380     }
1381 
1382     return 0;
1383 
1384 unfifo:
1385     chan->read_data_ok = 0;
1386     safely_assign_in_fifo(chan, NULL);
1387     fifo_mem_release(in_fifo);
1388     kfree(in_fifo);
1389 
1390     if (out_ep) {
1391         mutex_lock(&chan->lock);
1392         chan->out_ep = NULL;
1393         mutex_unlock(&chan->lock);
1394     }
1395 
1396 late_unopen:
1397     if (out_ep)
1398         endpoint_dealloc(out_ep);
1399 
1400 unopen:
1401     mutex_lock(&chan->lock);
1402 
1403     if (filp->f_mode & FMODE_READ)
1404         chan->open_for_read = 0;
1405 
1406     if (filp->f_mode & FMODE_WRITE)
1407         chan->open_for_write = 0;
1408 
1409     mutex_unlock(&chan->lock);
1410 
1411     kref_put(&xdev->kref, cleanup_dev);
1412 
1413     return rc;
1414 
1415 unmutex_fail:
1416     mutex_unlock(&chan->lock);
1417     return rc;
1418 }
1419 
1420 static ssize_t xillyusb_read(struct file *filp, char __user *userbuf,
1421                  size_t count, loff_t *f_pos)
1422 {
1423     struct xillyusb_channel *chan = filp->private_data;
1424     struct xillyusb_dev *xdev = chan->xdev;
1425     struct xillyfifo *fifo = chan->in_fifo;
1426     int chan_num = (chan->chan_idx << 1) | 1;
1427 
1428     long deadline, left_to_sleep;
1429     int bytes_done = 0;
1430     bool sent_set_push = false;
1431     int rc;
1432 
1433     deadline = jiffies + 1 + XILLY_RX_TIMEOUT;
1434 
1435     rc = mutex_lock_interruptible(&chan->in_mutex);
1436 
1437     if (rc)
1438         return rc;
1439 
1440     while (1) {
1441         u32 fifo_checkpoint_bytes, complete_checkpoint_bytes;
1442         u32 complete_checkpoint, fifo_checkpoint;
1443         u32 checkpoint;
1444         s32 diff, leap;
1445         unsigned int sh = chan->in_log2_element_size;
1446         bool checkpoint_for_complete;
1447 
1448         rc = fifo_read(fifo, (__force void *)userbuf + bytes_done,
1449                    count - bytes_done, xilly_copy_to_user);
1450 
1451         if (rc < 0)
1452             break;
1453 
1454         bytes_done += rc;
1455         chan->in_consumed_bytes += rc;
1456 
1457         left_to_sleep = deadline - ((long)jiffies);
1458 
1459         /*
1460          * Some 32-bit arithmetic that may wrap. Note that
1461          * complete_checkpoint is rounded up to the closest element
1462          * boundary, because the read() can't be completed otherwise.
1463          * fifo_checkpoint_bytes is rounded down, because it protects
1464          * in_fifo from overflowing.
1465          */
1466 
1467         fifo_checkpoint_bytes = chan->in_consumed_bytes + fifo->size;
1468         complete_checkpoint_bytes =
1469             chan->in_consumed_bytes + count - bytes_done;
1470 
1471         fifo_checkpoint = fifo_checkpoint_bytes >> sh;
1472         complete_checkpoint =
1473             (complete_checkpoint_bytes + (1 << sh) - 1) >> sh;
1474 
1475         diff = (fifo_checkpoint - complete_checkpoint) << sh;
1476 
1477         if (chan->in_synchronous && diff >= 0) {
1478             checkpoint = complete_checkpoint;
1479             checkpoint_for_complete = true;
1480         } else {
1481             checkpoint = fifo_checkpoint;
1482             checkpoint_for_complete = false;
1483         }
1484 
1485         leap = (checkpoint - chan->in_current_checkpoint) << sh;
1486 
1487         /*
1488          * To prevent flooding of OPCODE_SET_CHECKPOINT commands as
1489          * data is consumed, it's issued only if it moves the
1490          * checkpoint by at least an 8th of the FIFO's size, or if
1491          * it's necessary to complete the number of bytes requested by
1492          * the read() call.
1493          *
1494          * chan->read_data_ok is checked to spare an unnecessary
1495          * submission after receiving EOF, however it's harmless if
1496          * such slips away.
1497          */
1498 
1499         if (chan->read_data_ok &&
1500             (leap > (fifo->size >> 3) ||
1501              (checkpoint_for_complete && leap > 0))) {
1502             chan->in_current_checkpoint = checkpoint;
1503             rc = xillyusb_send_opcode(xdev, chan_num,
1504                           OPCODE_SET_CHECKPOINT,
1505                           checkpoint);
1506 
1507             if (rc)
1508                 break;
1509         }
1510 
1511         if (bytes_done == count ||
1512             (left_to_sleep <= 0 && bytes_done))
1513             break;
1514 
1515         /*
1516          * Reaching here means that the FIFO was empty when
1517          * fifo_read() returned, but not necessarily right now. Error
1518          * and EOF are checked and reported only now, so that no data
1519          * that managed its way to the FIFO is lost.
1520          */
1521 
1522         if (!READ_ONCE(chan->read_data_ok)) { /* FPGA has sent EOF */
1523             /* Has data slipped into the FIFO since fifo_read()? */
1524             smp_rmb();
1525             if (READ_ONCE(fifo->fill))
1526                 continue;
1527 
1528             rc = 0;
1529             break;
1530         }
1531 
1532         if (xdev->error) {
1533             rc = xdev->error;
1534             break;
1535         }
1536 
1537         if (filp->f_flags & O_NONBLOCK) {
1538             rc = -EAGAIN;
1539             break;
1540         }
1541 
1542         if (!sent_set_push) {
1543             rc = xillyusb_send_opcode(xdev, chan_num,
1544                           OPCODE_SET_PUSH,
1545                           complete_checkpoint);
1546 
1547             if (rc)
1548                 break;
1549 
1550             sent_set_push = true;
1551         }
1552 
1553         if (left_to_sleep > 0) {
1554             /*
1555              * Note that when xdev->error is set (e.g. when the
1556              * device is unplugged), read_data_ok turns zero and
1557              * fifo->waitq is awaken.
1558              * Therefore no special attention to xdev->error.
1559              */
1560 
1561             rc = wait_event_interruptible_timeout
1562                 (fifo->waitq,
1563                  fifo->fill || !chan->read_data_ok,
1564                  left_to_sleep);
1565         } else { /* bytes_done == 0 */
1566             /* Tell FPGA to send anything it has */
1567             rc = request_read_anything(chan, OPCODE_UPDATE_PUSH);
1568 
1569             if (rc)
1570                 break;
1571 
1572             rc = wait_event_interruptible
1573                 (fifo->waitq,
1574                  fifo->fill || !chan->read_data_ok);
1575         }
1576 
1577         if (rc < 0) {
1578             rc = -EINTR;
1579             break;
1580         }
1581     }
1582 
1583     if (((filp->f_flags & O_NONBLOCK) || chan->poll_used) &&
1584         !READ_ONCE(fifo->fill))
1585         request_read_anything(chan, OPCODE_SET_PUSH);
1586 
1587     mutex_unlock(&chan->in_mutex);
1588 
1589     if (bytes_done)
1590         return bytes_done;
1591 
1592     return rc;
1593 }
1594 
1595 static int xillyusb_flush(struct file *filp, fl_owner_t id)
1596 {
1597     struct xillyusb_channel *chan = filp->private_data;
1598     int rc;
1599 
1600     if (!(filp->f_mode & FMODE_WRITE))
1601         return 0;
1602 
1603     rc = mutex_lock_interruptible(&chan->out_mutex);
1604 
1605     if (rc)
1606         return rc;
1607 
1608     /*
1609      * One second's timeout on flushing. Interrupts are ignored, because if
1610      * the user pressed CTRL-C, that interrupt will still be in flight by
1611      * the time we reach here, and the opportunity to flush is lost.
1612      */
1613     rc = flush_downstream(chan, HZ, false);
1614 
1615     mutex_unlock(&chan->out_mutex);
1616 
1617     if (rc == -ETIMEDOUT) {
1618         /* The things you do to use dev_warn() and not pr_warn() */
1619         struct xillyusb_dev *xdev = chan->xdev;
1620 
1621         mutex_lock(&chan->lock);
1622         if (!xdev->error)
1623             dev_warn(xdev->dev,
1624                  "Timed out while flushing. Output data may be lost.\n");
1625         mutex_unlock(&chan->lock);
1626     }
1627 
1628     return rc;
1629 }
1630 
1631 static ssize_t xillyusb_write(struct file *filp, const char __user *userbuf,
1632                   size_t count, loff_t *f_pos)
1633 {
1634     struct xillyusb_channel *chan = filp->private_data;
1635     struct xillyusb_dev *xdev = chan->xdev;
1636     struct xillyfifo *fifo = &chan->out_ep->fifo;
1637     int rc;
1638 
1639     rc = mutex_lock_interruptible(&chan->out_mutex);
1640 
1641     if (rc)
1642         return rc;
1643 
1644     while (1) {
1645         if (xdev->error) {
1646             rc = xdev->error;
1647             break;
1648         }
1649 
1650         if (count == 0)
1651             break;
1652 
1653         rc = fifo_write(fifo, (__force void *)userbuf, count,
1654                 xilly_copy_from_user);
1655 
1656         if (rc != 0)
1657             break;
1658 
1659         if (filp->f_flags & O_NONBLOCK) {
1660             rc = -EAGAIN;
1661             break;
1662         }
1663 
1664         if (wait_event_interruptible
1665             (fifo->waitq,
1666              fifo->fill != fifo->size || xdev->error)) {
1667             rc = -EINTR;
1668             break;
1669         }
1670     }
1671 
1672     if (rc < 0)
1673         goto done;
1674 
1675     chan->out_bytes += rc;
1676 
1677     if (rc) {
1678         try_queue_bulk_out(chan->out_ep);
1679         chan->flushed = 0;
1680     }
1681 
1682     if (chan->out_synchronous) {
1683         int flush_rc = flush_downstream(chan, 0, true);
1684 
1685         if (flush_rc && !rc)
1686             rc = flush_rc;
1687     }
1688 
1689 done:
1690     mutex_unlock(&chan->out_mutex);
1691 
1692     return rc;
1693 }
1694 
1695 static int xillyusb_release(struct inode *inode, struct file *filp)
1696 {
1697     struct xillyusb_channel *chan = filp->private_data;
1698     struct xillyusb_dev *xdev = chan->xdev;
1699     int rc_read = 0, rc_write = 0;
1700 
1701     if (filp->f_mode & FMODE_READ) {
1702         struct xillyfifo *in_fifo = chan->in_fifo;
1703 
1704         rc_read = xillyusb_send_opcode(xdev, (chan->chan_idx << 1) | 1,
1705                            OPCODE_CLOSE, 0);
1706         /*
1707          * If rc_read is nonzero, xdev->error indicates a global
1708          * device error. The error is reported later, so that
1709          * resources are freed.
1710          *
1711          * Looping on wait_event_interruptible() kinda breaks the idea
1712          * of being interruptible, and this should have been
1713          * wait_event(). Only it's being waken with
1714          * wake_up_interruptible() for the sake of other uses. If
1715          * there's a global device error, chan->read_data_ok is
1716          * deasserted and the wait queue is awaken, so this is covered.
1717          */
1718 
1719         while (wait_event_interruptible(in_fifo->waitq,
1720                         !chan->read_data_ok))
1721             ; /* Empty loop */
1722 
1723         safely_assign_in_fifo(chan, NULL);
1724         fifo_mem_release(in_fifo);
1725         kfree(in_fifo);
1726 
1727         mutex_lock(&chan->lock);
1728         chan->open_for_read = 0;
1729         mutex_unlock(&chan->lock);
1730     }
1731 
1732     if (filp->f_mode & FMODE_WRITE) {
1733         struct xillyusb_endpoint *ep = chan->out_ep;
1734         /*
1735          * chan->flushing isn't zeroed. If the pre-release flush timed
1736          * out, a cancel request will be sent before the next
1737          * OPCODE_SET_CHECKPOINT (i.e. when the file is opened again).
1738          * This is despite that the FPGA forgets about the checkpoint
1739          * request as the file closes. Still, in an exceptional race
1740          * condition, the FPGA could send an OPCODE_REACHED_CHECKPOINT
1741          * just before closing that would reach the host after the
1742          * file has re-opened.
1743          */
1744 
1745         mutex_lock(&chan->lock);
1746         chan->out_ep = NULL;
1747         mutex_unlock(&chan->lock);
1748 
1749         endpoint_quiesce(ep);
1750         endpoint_dealloc(ep);
1751 
1752         /* See comments on rc_read above */
1753         rc_write = xillyusb_send_opcode(xdev, chan->chan_idx << 1,
1754                         OPCODE_CLOSE, 0);
1755 
1756         mutex_lock(&chan->lock);
1757         chan->open_for_write = 0;
1758         mutex_unlock(&chan->lock);
1759     }
1760 
1761     kref_put(&xdev->kref, cleanup_dev);
1762 
1763     return rc_read ? rc_read : rc_write;
1764 }
1765 
1766 /*
1767  * Xillybus' API allows device nodes to be seekable, giving the user
1768  * application access to a RAM array on the FPGA (or logic emulating it).
1769  */
1770 
1771 static loff_t xillyusb_llseek(struct file *filp, loff_t offset, int whence)
1772 {
1773     struct xillyusb_channel *chan = filp->private_data;
1774     struct xillyusb_dev *xdev = chan->xdev;
1775     loff_t pos = filp->f_pos;
1776     int rc = 0;
1777     unsigned int log2_element_size = chan->readable ?
1778         chan->in_log2_element_size : chan->out_log2_element_size;
1779 
1780     /*
1781      * Take both mutexes not allowing interrupts, since it seems like
1782      * common applications don't expect an -EINTR here. Besides, multiple
1783      * access to a single file descriptor on seekable devices is a mess
1784      * anyhow.
1785      */
1786 
1787     mutex_lock(&chan->out_mutex);
1788     mutex_lock(&chan->in_mutex);
1789 
1790     switch (whence) {
1791     case SEEK_SET:
1792         pos = offset;
1793         break;
1794     case SEEK_CUR:
1795         pos += offset;
1796         break;
1797     case SEEK_END:
1798         pos = offset; /* Going to the end => to the beginning */
1799         break;
1800     default:
1801         rc = -EINVAL;
1802         goto end;
1803     }
1804 
1805     /* In any case, we must finish on an element boundary */
1806     if (pos & ((1 << log2_element_size) - 1)) {
1807         rc = -EINVAL;
1808         goto end;
1809     }
1810 
1811     rc = xillyusb_send_opcode(xdev, chan->chan_idx << 1,
1812                   OPCODE_SET_ADDR,
1813                   pos >> log2_element_size);
1814 
1815     if (rc)
1816         goto end;
1817 
1818     if (chan->writable) {
1819         chan->flushed = 0;
1820         rc = flush_downstream(chan, HZ, false);
1821     }
1822 
1823 end:
1824     mutex_unlock(&chan->out_mutex);
1825     mutex_unlock(&chan->in_mutex);
1826 
1827     if (rc) /* Return error after releasing mutexes */
1828         return rc;
1829 
1830     filp->f_pos = pos;
1831 
1832     return pos;
1833 }
1834 
1835 static __poll_t xillyusb_poll(struct file *filp, poll_table *wait)
1836 {
1837     struct xillyusb_channel *chan = filp->private_data;
1838     __poll_t mask = 0;
1839 
1840     if (chan->in_fifo)
1841         poll_wait(filp, &chan->in_fifo->waitq, wait);
1842 
1843     if (chan->out_ep)
1844         poll_wait(filp, &chan->out_ep->fifo.waitq, wait);
1845 
1846     /*
1847      * If this is the first time poll() is called, and the file is
1848      * readable, set the relevant flag. Also tell the FPGA to send all it
1849      * has, to kickstart the mechanism that ensures there's always some
1850      * data in in_fifo unless the stream is dry end-to-end. Note that the
1851      * first poll() may not return a EPOLLIN, even if there's data on the
1852      * FPGA. Rather, the data will arrive soon, and trigger the relevant
1853      * wait queue.
1854      */
1855 
1856     if (!chan->poll_used && chan->in_fifo) {
1857         chan->poll_used = 1;
1858         request_read_anything(chan, OPCODE_SET_PUSH);
1859     }
1860 
1861     /*
1862      * poll() won't play ball regarding read() channels which
1863      * are synchronous. Allowing that will create situations where data has
1864      * been delivered at the FPGA, and users expecting select() to wake up,
1865      * which it may not. So make it never work.
1866      */
1867 
1868     if (chan->in_fifo && !chan->in_synchronous &&
1869         (READ_ONCE(chan->in_fifo->fill) || !chan->read_data_ok))
1870         mask |= EPOLLIN | EPOLLRDNORM;
1871 
1872     if (chan->out_ep &&
1873         (READ_ONCE(chan->out_ep->fifo.fill) != chan->out_ep->fifo.size))
1874         mask |= EPOLLOUT | EPOLLWRNORM;
1875 
1876     if (chan->xdev->error)
1877         mask |= EPOLLERR;
1878 
1879     return mask;
1880 }
1881 
1882 static const struct file_operations xillyusb_fops = {
1883     .owner      = THIS_MODULE,
1884     .read       = xillyusb_read,
1885     .write      = xillyusb_write,
1886     .open       = xillyusb_open,
1887     .flush      = xillyusb_flush,
1888     .release    = xillyusb_release,
1889     .llseek     = xillyusb_llseek,
1890     .poll       = xillyusb_poll,
1891 };
1892 
1893 static int xillyusb_setup_base_eps(struct xillyusb_dev *xdev)
1894 {
1895     xdev->msg_ep = endpoint_alloc(xdev, MSG_EP_NUM | USB_DIR_OUT,
1896                       bulk_out_work, 1, 2);
1897     if (!xdev->msg_ep)
1898         return -ENOMEM;
1899 
1900     if (fifo_init(&xdev->msg_ep->fifo, 13)) /* 8 kiB */
1901         goto dealloc;
1902 
1903     xdev->msg_ep->fill_mask = -8; /* 8 bytes granularity */
1904 
1905     xdev->in_ep = endpoint_alloc(xdev, IN_EP_NUM | USB_DIR_IN,
1906                      bulk_in_work, BUF_SIZE_ORDER, BUFNUM);
1907     if (!xdev->in_ep)
1908         goto dealloc;
1909 
1910     try_queue_bulk_in(xdev->in_ep);
1911 
1912     return 0;
1913 
1914 dealloc:
1915     endpoint_dealloc(xdev->msg_ep); /* Also frees FIFO mem if allocated */
1916     xdev->msg_ep = NULL;
1917     return -ENOMEM;
1918 }
1919 
1920 static int setup_channels(struct xillyusb_dev *xdev,
1921               __le16 *chandesc,
1922               int num_channels)
1923 {
1924     struct xillyusb_channel *chan;
1925     int i;
1926 
1927     chan = kcalloc(num_channels, sizeof(*chan), GFP_KERNEL);
1928     if (!chan)
1929         return -ENOMEM;
1930 
1931     xdev->channels = chan;
1932 
1933     for (i = 0; i < num_channels; i++, chan++) {
1934         unsigned int in_desc = le16_to_cpu(*chandesc++);
1935         unsigned int out_desc = le16_to_cpu(*chandesc++);
1936 
1937         chan->xdev = xdev;
1938         mutex_init(&chan->in_mutex);
1939         mutex_init(&chan->out_mutex);
1940         mutex_init(&chan->lock);
1941         init_waitqueue_head(&chan->flushq);
1942 
1943         chan->chan_idx = i;
1944 
1945         if (in_desc & 0x80) { /* Entry is valid */
1946             chan->readable = 1;
1947             chan->in_synchronous = !!(in_desc & 0x40);
1948             chan->in_seekable = !!(in_desc & 0x20);
1949             chan->in_log2_element_size = in_desc & 0x0f;
1950             chan->in_log2_fifo_size = ((in_desc >> 8) & 0x1f) + 16;
1951         }
1952 
1953         /*
1954          * A downstream channel should never exist above index 13,
1955          * as it would request a nonexistent BULK endpoint > 15.
1956          * In the peculiar case that it does, it's ignored silently.
1957          */
1958 
1959         if ((out_desc & 0x80) && i < 14) { /* Entry is valid */
1960             chan->writable = 1;
1961             chan->out_synchronous = !!(out_desc & 0x40);
1962             chan->out_seekable = !!(out_desc & 0x20);
1963             chan->out_log2_element_size = out_desc & 0x0f;
1964             chan->out_log2_fifo_size =
1965                 ((out_desc >> 8) & 0x1f) + 16;
1966         }
1967     }
1968 
1969     return 0;
1970 }
1971 
1972 static int xillyusb_discovery(struct usb_interface *interface)
1973 {
1974     int rc;
1975     struct xillyusb_dev *xdev = usb_get_intfdata(interface);
1976     __le16 bogus_chandesc[2];
1977     struct xillyfifo idt_fifo;
1978     struct xillyusb_channel *chan;
1979     unsigned int idt_len, names_offset;
1980     unsigned char *idt;
1981     int num_channels;
1982 
1983     rc = xillyusb_send_opcode(xdev, ~0, OPCODE_QUIESCE, 0);
1984 
1985     if (rc) {
1986         dev_err(&interface->dev, "Failed to send quiesce request. Aborting.\n");
1987         return rc;
1988     }
1989 
1990     /* Phase I: Set up one fake upstream channel and obtain IDT */
1991 
1992     /* Set up a fake IDT with one async IN stream */
1993     bogus_chandesc[0] = cpu_to_le16(0x80);
1994     bogus_chandesc[1] = cpu_to_le16(0);
1995 
1996     rc = setup_channels(xdev, bogus_chandesc, 1);
1997 
1998     if (rc)
1999         return rc;
2000 
2001     rc = fifo_init(&idt_fifo, LOG2_IDT_FIFO_SIZE);
2002 
2003     if (rc)
2004         return rc;
2005 
2006     chan = xdev->channels;
2007 
2008     chan->in_fifo = &idt_fifo;
2009     chan->read_data_ok = 1;
2010 
2011     xdev->num_channels = 1;
2012 
2013     rc = xillyusb_send_opcode(xdev, ~0, OPCODE_REQ_IDT, 0);
2014 
2015     if (rc) {
2016         dev_err(&interface->dev, "Failed to send IDT request. Aborting.\n");
2017         goto unfifo;
2018     }
2019 
2020     rc = wait_event_interruptible_timeout(idt_fifo.waitq,
2021                           !chan->read_data_ok,
2022                           XILLY_RESPONSE_TIMEOUT);
2023 
2024     if (xdev->error) {
2025         rc = xdev->error;
2026         goto unfifo;
2027     }
2028 
2029     if (rc < 0) {
2030         rc = -EINTR; /* Interrupt on probe method? Interesting. */
2031         goto unfifo;
2032     }
2033 
2034     if (chan->read_data_ok) {
2035         rc = -ETIMEDOUT;
2036         dev_err(&interface->dev, "No response from FPGA. Aborting.\n");
2037         goto unfifo;
2038     }
2039 
2040     idt_len = READ_ONCE(idt_fifo.fill);
2041     idt = kmalloc(idt_len, GFP_KERNEL);
2042 
2043     if (!idt) {
2044         rc = -ENOMEM;
2045         goto unfifo;
2046     }
2047 
2048     fifo_read(&idt_fifo, idt, idt_len, xilly_memcpy);
2049 
2050     if (crc32_le(~0, idt, idt_len) != 0) {
2051         dev_err(&interface->dev, "IDT failed CRC check. Aborting.\n");
2052         rc = -ENODEV;
2053         goto unidt;
2054     }
2055 
2056     if (*idt > 0x90) {
2057         dev_err(&interface->dev, "No support for IDT version 0x%02x. Maybe the xillyusb driver needs an upgrade. Aborting.\n",
2058             (int)*idt);
2059         rc = -ENODEV;
2060         goto unidt;
2061     }
2062 
2063     /* Phase II: Set up the streams as defined in IDT */
2064 
2065     num_channels = le16_to_cpu(*((__le16 *)(idt + 1)));
2066     names_offset = 3 + num_channels * 4;
2067     idt_len -= 4; /* Exclude CRC */
2068 
2069     if (idt_len < names_offset) {
2070         dev_err(&interface->dev, "IDT too short. This is exceptionally weird, because its CRC is OK\n");
2071         rc = -ENODEV;
2072         goto unidt;
2073     }
2074 
2075     rc = setup_channels(xdev, (void *)idt + 3, num_channels);
2076 
2077     if (rc)
2078         goto unidt;
2079 
2080     /*
2081      * Except for wildly misbehaving hardware, or if it was disconnected
2082      * just after responding with the IDT, there is no reason for any
2083      * work item to be running now. To be sure that xdev->channels
2084      * is updated on anything that might run in parallel, flush the
2085      * workqueue, which rarely does anything.
2086      */
2087     flush_workqueue(xdev->workq);
2088 
2089     xdev->num_channels = num_channels;
2090 
2091     fifo_mem_release(&idt_fifo);
2092     kfree(chan);
2093 
2094     rc = xillybus_init_chrdev(&interface->dev, &xillyusb_fops,
2095                   THIS_MODULE, xdev,
2096                   idt + names_offset,
2097                   idt_len - names_offset,
2098                   num_channels,
2099                   xillyname, true);
2100 
2101     kfree(idt);
2102 
2103     return rc;
2104 
2105 unidt:
2106     kfree(idt);
2107 
2108 unfifo:
2109     safely_assign_in_fifo(chan, NULL);
2110     fifo_mem_release(&idt_fifo);
2111 
2112     return rc;
2113 }
2114 
2115 static int xillyusb_probe(struct usb_interface *interface,
2116               const struct usb_device_id *id)
2117 {
2118     struct xillyusb_dev *xdev;
2119     int rc;
2120 
2121     xdev = kzalloc(sizeof(*xdev), GFP_KERNEL);
2122     if (!xdev)
2123         return -ENOMEM;
2124 
2125     kref_init(&xdev->kref);
2126     mutex_init(&xdev->process_in_mutex);
2127     mutex_init(&xdev->msg_mutex);
2128 
2129     xdev->udev = usb_get_dev(interface_to_usbdev(interface));
2130     xdev->dev = &interface->dev;
2131     xdev->error = 0;
2132     spin_lock_init(&xdev->error_lock);
2133     xdev->in_counter = 0;
2134     xdev->in_bytes_left = 0;
2135     xdev->workq = alloc_workqueue(xillyname, WQ_HIGHPRI, 0);
2136 
2137     if (!xdev->workq) {
2138         dev_err(&interface->dev, "Failed to allocate work queue\n");
2139         rc = -ENOMEM;
2140         goto fail;
2141     }
2142 
2143     INIT_WORK(&xdev->wakeup_workitem, wakeup_all);
2144 
2145     usb_set_intfdata(interface, xdev);
2146 
2147     rc = xillyusb_setup_base_eps(xdev);
2148     if (rc)
2149         goto fail;
2150 
2151     rc = xillyusb_discovery(interface);
2152     if (rc)
2153         goto latefail;
2154 
2155     return 0;
2156 
2157 latefail:
2158     endpoint_quiesce(xdev->in_ep);
2159     endpoint_quiesce(xdev->msg_ep);
2160 
2161 fail:
2162     usb_set_intfdata(interface, NULL);
2163     kref_put(&xdev->kref, cleanup_dev);
2164     return rc;
2165 }
2166 
2167 static void xillyusb_disconnect(struct usb_interface *interface)
2168 {
2169     struct xillyusb_dev *xdev = usb_get_intfdata(interface);
2170     struct xillyusb_endpoint *msg_ep = xdev->msg_ep;
2171     struct xillyfifo *fifo = &msg_ep->fifo;
2172     int rc;
2173     int i;
2174 
2175     xillybus_cleanup_chrdev(xdev, &interface->dev);
2176 
2177     /*
2178      * Try to send OPCODE_QUIESCE, which will fail silently if the device
2179      * was disconnected, but makes sense on module unload.
2180      */
2181 
2182     msg_ep->wake_on_drain = true;
2183     xillyusb_send_opcode(xdev, ~0, OPCODE_QUIESCE, 0);
2184 
2185     /*
2186      * If the device has been disconnected, sending the opcode causes
2187      * a global device error with xdev->error, if such error didn't
2188      * occur earlier. Hence timing out means that the USB link is fine,
2189      * but somehow the message wasn't sent. Should never happen.
2190      */
2191 
2192     rc = wait_event_interruptible_timeout(fifo->waitq,
2193                           msg_ep->drained || xdev->error,
2194                           XILLY_RESPONSE_TIMEOUT);
2195 
2196     if (!rc)
2197         dev_err(&interface->dev,
2198             "Weird timeout condition on sending quiesce request.\n");
2199 
2200     report_io_error(xdev, -ENODEV); /* Discourage further activity */
2201 
2202     /*
2203      * This device driver is declared with soft_unbind set, or else
2204      * sending OPCODE_QUIESCE above would always fail. The price is
2205      * that the USB framework didn't kill outstanding URBs, so it has
2206      * to be done explicitly before returning from this call.
2207      */
2208 
2209     for (i = 0; i < xdev->num_channels; i++) {
2210         struct xillyusb_channel *chan = &xdev->channels[i];
2211 
2212         /*
2213          * Lock taken to prevent chan->out_ep from changing. It also
2214          * ensures xillyusb_open() and xillyusb_flush() don't access
2215          * xdev->dev after being nullified below.
2216          */
2217         mutex_lock(&chan->lock);
2218         if (chan->out_ep)
2219             endpoint_quiesce(chan->out_ep);
2220         mutex_unlock(&chan->lock);
2221     }
2222 
2223     endpoint_quiesce(xdev->in_ep);
2224     endpoint_quiesce(xdev->msg_ep);
2225 
2226     usb_set_intfdata(interface, NULL);
2227 
2228     xdev->dev = NULL;
2229 
2230     kref_put(&xdev->kref, cleanup_dev);
2231 }
2232 
2233 static struct usb_driver xillyusb_driver = {
2234     .name = xillyname,
2235     .id_table = xillyusb_table,
2236     .probe = xillyusb_probe,
2237     .disconnect = xillyusb_disconnect,
2238     .soft_unbind = 1,
2239 };
2240 
2241 static int __init xillyusb_init(void)
2242 {
2243     int rc = 0;
2244 
2245     if (LOG2_INITIAL_FIFO_BUF_SIZE > PAGE_SHIFT)
2246         fifo_buf_order = LOG2_INITIAL_FIFO_BUF_SIZE - PAGE_SHIFT;
2247     else
2248         fifo_buf_order = 0;
2249 
2250     rc = usb_register(&xillyusb_driver);
2251 
2252     return rc;
2253 }
2254 
2255 static void __exit xillyusb_exit(void)
2256 {
2257     usb_deregister(&xillyusb_driver);
2258 }
2259 
2260 module_init(xillyusb_init);
2261 module_exit(xillyusb_exit);