xref: /linux/drivers/char/xillybus/xillyusb.c (revision 1ce74f6f221642501dd4ebf4e83af4bc0c3729d0)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * Copyright 2020 Xillybus Ltd, http://xillybus.com
4  *
5  * Driver for the XillyUSB FPGA/host framework.
6  *
7  * This driver interfaces with a special IP core in an FPGA, setting up
8  * a pipe between a hardware FIFO in the programmable logic and a device
9  * file in the host. The number of such pipes and their attributes are
10  * set up on the logic. This driver detects these automatically and
11  * creates the device files accordingly.
12  */
13 
14 #include <linux/types.h>
15 #include <linux/slab.h>
16 #include <linux/list.h>
17 #include <linux/device.h>
18 #include <linux/module.h>
19 #include <asm/byteorder.h>
20 #include <linux/io.h>
21 #include <linux/interrupt.h>
22 #include <linux/sched.h>
23 #include <linux/fs.h>
24 #include <linux/spinlock.h>
25 #include <linux/mutex.h>
26 #include <linux/workqueue.h>
27 #include <linux/sizes.h>
28 #include <linux/crc32.h>
29 #include <linux/poll.h>
30 #include <linux/delay.h>
31 #include <linux/usb.h>
32 
33 #include "xillybus_class.h"
34 
35 MODULE_DESCRIPTION("Driver for XillyUSB FPGA IP Core");
36 MODULE_AUTHOR("Eli Billauer, Xillybus Ltd.");
37 MODULE_ALIAS("xillyusb");
38 MODULE_LICENSE("GPL v2");
39 
40 #define XILLY_RX_TIMEOUT		(10 * HZ / 1000)
41 #define XILLY_RESPONSE_TIMEOUT		(500 * HZ / 1000)
42 
43 #define BUF_SIZE_ORDER			4
44 #define BUFNUM				8
45 #define LOG2_IDT_FIFO_SIZE		16
46 #define LOG2_INITIAL_FIFO_BUF_SIZE	16
47 
48 #define MSG_EP_NUM			1
49 #define IN_EP_NUM			1
50 
51 static const char xillyname[] = "xillyusb";
52 
53 static unsigned int fifo_buf_order;
54 static DEFINE_MUTEX(fifo_buf_order_mutex);
55 static struct workqueue_struct *wakeup_wq;
56 
57 #define USB_VENDOR_ID_XILINX		0x03fd
58 #define USB_VENDOR_ID_ALTERA		0x09fb
59 
60 #define USB_PRODUCT_ID_XILLYUSB		0xebbe
61 
62 static const struct usb_device_id xillyusb_table[] = {
63 	{ USB_DEVICE(USB_VENDOR_ID_XILINX, USB_PRODUCT_ID_XILLYUSB) },
64 	{ USB_DEVICE(USB_VENDOR_ID_ALTERA, USB_PRODUCT_ID_XILLYUSB) },
65 	{ }
66 };
67 
68 MODULE_DEVICE_TABLE(usb, xillyusb_table);
69 
70 struct xillyusb_dev;
71 
72 struct xillyfifo {
73 	unsigned int bufsize; /* In bytes, always a power of 2 */
74 	unsigned int bufnum;
75 	unsigned int size; /* Lazy: Equals bufsize * bufnum */
76 
77 	int fill; /* Number of bytes in the FIFO */
78 	spinlock_t lock;
79 	wait_queue_head_t waitq;
80 
81 	unsigned int readpos;
82 	unsigned int readbuf;
83 	unsigned int writepos;
84 	unsigned int writebuf;
85 	char **mem;
86 };
87 
88 struct xillyusb_channel;
89 
90 struct xillyusb_endpoint {
91 	struct xillyusb_dev *xdev;
92 
93 	struct mutex ep_mutex; /* serialize operations on endpoint */
94 
95 	struct list_head buffers;
96 	struct list_head filled_buffers;
97 	spinlock_t buffers_lock; /* protect these two lists */
98 
99 	unsigned int buffer_size;
100 
101 	unsigned int fill_mask;
102 
103 	int outstanding_urbs;
104 
105 	struct usb_anchor anchor;
106 
107 	struct xillyfifo fifo;
108 
109 	struct work_struct workitem;
110 
111 	bool shutting_down;
112 	bool drained;
113 	bool wake_on_drain;
114 
115 	u8 ep_num;
116 };
117 
118 struct xillyusb_channel {
119 	struct xillyusb_dev *xdev;
120 
121 	struct xillyfifo *in_fifo;
122 	struct xillyusb_endpoint *out_ep;
123 	struct mutex lock; /* protect @out_ep, @in_fifo, bit fields below */
124 
125 	struct mutex in_mutex; /* serialize fops on FPGA to host stream */
126 	struct mutex out_mutex; /* serialize fops on host to FPGA stream */
127 	wait_queue_head_t flushq;
128 
129 	int chan_idx;
130 
131 	u32 in_consumed_bytes;
132 	u32 in_current_checkpoint;
133 	u32 out_bytes;
134 
135 	unsigned int in_log2_element_size;
136 	unsigned int out_log2_element_size;
137 	unsigned int in_log2_fifo_size;
138 	unsigned int out_log2_fifo_size;
139 
140 	unsigned int read_data_ok; /* EOF not arrived (yet) */
141 	unsigned int poll_used;
142 	unsigned int flushing;
143 	unsigned int flushed;
144 	unsigned int canceled;
145 
146 	/* Bit fields protected by @lock except for initialization */
147 	unsigned readable:1;
148 	unsigned writable:1;
149 	unsigned open_for_read:1;
150 	unsigned open_for_write:1;
151 	unsigned in_synchronous:1;
152 	unsigned out_synchronous:1;
153 	unsigned in_seekable:1;
154 	unsigned out_seekable:1;
155 };
156 
157 struct xillybuffer {
158 	struct list_head entry;
159 	struct xillyusb_endpoint *ep;
160 	void *buf;
161 	unsigned int len;
162 };
163 
164 struct xillyusb_dev {
165 	struct xillyusb_channel *channels;
166 
167 	struct usb_device	*udev;
168 	struct device		*dev; /* For dev_err() and such */
169 	struct kref		kref;
170 	struct workqueue_struct	*workq;
171 
172 	int error;
173 	spinlock_t error_lock; /* protect @error */
174 	struct work_struct wakeup_workitem;
175 
176 	int num_channels;
177 
178 	struct xillyusb_endpoint *msg_ep;
179 	struct xillyusb_endpoint *in_ep;
180 
181 	struct mutex msg_mutex; /* serialize opcode transmission */
182 	int in_bytes_left;
183 	int leftover_chan_num;
184 	unsigned int in_counter;
185 	struct mutex process_in_mutex; /* synchronize wakeup_all() */
186 };
187 
188 /*
189  * kref_mutex is used in xillyusb_open() to prevent the xillyusb_dev
190  * struct from being freed during the gap between being found by
191  * xillybus_find_inode() and having its reference count incremented.
192  */
193 
194 static DEFINE_MUTEX(kref_mutex);
195 
196 /* FPGA to host opcodes */
197 enum {
198 	OPCODE_DATA = 0,
199 	OPCODE_QUIESCE_ACK = 1,
200 	OPCODE_EOF = 2,
201 	OPCODE_REACHED_CHECKPOINT = 3,
202 	OPCODE_CANCELED_CHECKPOINT = 4,
203 };
204 
205 /* Host to FPGA opcodes */
206 enum {
207 	OPCODE_QUIESCE = 0,
208 	OPCODE_REQ_IDT = 1,
209 	OPCODE_SET_CHECKPOINT = 2,
210 	OPCODE_CLOSE = 3,
211 	OPCODE_SET_PUSH = 4,
212 	OPCODE_UPDATE_PUSH = 5,
213 	OPCODE_CANCEL_CHECKPOINT = 6,
214 	OPCODE_SET_ADDR = 7,
215 };
216 
217 /*
218  * fifo_write() and fifo_read() are NOT reentrant (i.e. concurrent multiple
219  * calls to each on the same FIFO is not allowed) however it's OK to have
220  * threads calling each of the two functions once on the same FIFO, and
221  * at the same time.
222  */
223 
224 static int fifo_write(struct xillyfifo *fifo,
225 		      const void *data, unsigned int len,
226 		      int (*copier)(void *, const void *, int))
227 {
228 	unsigned int done = 0;
229 	unsigned int todo = len;
230 	unsigned int nmax;
231 	unsigned int writepos = fifo->writepos;
232 	unsigned int writebuf = fifo->writebuf;
233 	unsigned long flags;
234 	int rc;
235 
236 	nmax = fifo->size - READ_ONCE(fifo->fill);
237 
238 	while (1) {
239 		unsigned int nrail = fifo->bufsize - writepos;
240 		unsigned int n = min(todo, nmax);
241 
242 		if (n == 0) {
243 			spin_lock_irqsave(&fifo->lock, flags);
244 			fifo->fill += done;
245 			spin_unlock_irqrestore(&fifo->lock, flags);
246 
247 			fifo->writepos = writepos;
248 			fifo->writebuf = writebuf;
249 
250 			return done;
251 		}
252 
253 		if (n > nrail)
254 			n = nrail;
255 
256 		rc = (*copier)(fifo->mem[writebuf] + writepos, data + done, n);
257 
258 		if (rc)
259 			return rc;
260 
261 		done += n;
262 		todo -= n;
263 
264 		writepos += n;
265 		nmax -= n;
266 
267 		if (writepos == fifo->bufsize) {
268 			writepos = 0;
269 			writebuf++;
270 
271 			if (writebuf == fifo->bufnum)
272 				writebuf = 0;
273 		}
274 	}
275 }
276 
277 static int fifo_read(struct xillyfifo *fifo,
278 		     void *data, unsigned int len,
279 		     int (*copier)(void *, const void *, int))
280 {
281 	unsigned int done = 0;
282 	unsigned int todo = len;
283 	unsigned int fill;
284 	unsigned int readpos = fifo->readpos;
285 	unsigned int readbuf = fifo->readbuf;
286 	unsigned long flags;
287 	int rc;
288 
289 	/*
290 	 * The spinlock here is necessary, because otherwise fifo->fill
291 	 * could have been increased by fifo_write() after writing data
292 	 * to the buffer, but this data would potentially not have been
293 	 * visible on this thread at the time the updated fifo->fill was.
294 	 * That could lead to reading invalid data.
295 	 */
296 
297 	spin_lock_irqsave(&fifo->lock, flags);
298 	fill = fifo->fill;
299 	spin_unlock_irqrestore(&fifo->lock, flags);
300 
301 	while (1) {
302 		unsigned int nrail = fifo->bufsize - readpos;
303 		unsigned int n = min(todo, fill);
304 
305 		if (n == 0) {
306 			spin_lock_irqsave(&fifo->lock, flags);
307 			fifo->fill -= done;
308 			spin_unlock_irqrestore(&fifo->lock, flags);
309 
310 			fifo->readpos = readpos;
311 			fifo->readbuf = readbuf;
312 
313 			return done;
314 		}
315 
316 		if (n > nrail)
317 			n = nrail;
318 
319 		rc = (*copier)(data + done, fifo->mem[readbuf] + readpos, n);
320 
321 		if (rc)
322 			return rc;
323 
324 		done += n;
325 		todo -= n;
326 
327 		readpos += n;
328 		fill -= n;
329 
330 		if (readpos == fifo->bufsize) {
331 			readpos = 0;
332 			readbuf++;
333 
334 			if (readbuf == fifo->bufnum)
335 				readbuf = 0;
336 		}
337 	}
338 }
339 
340 /*
341  * These three wrapper functions are used as the @copier argument to
342  * fifo_write() and fifo_read(), so that they can work directly with
343  * user memory as well.
344  */
345 
346 static int xilly_copy_from_user(void *dst, const void *src, int n)
347 {
348 	if (copy_from_user(dst, (const void __user *)src, n))
349 		return -EFAULT;
350 
351 	return 0;
352 }
353 
354 static int xilly_copy_to_user(void *dst, const void *src, int n)
355 {
356 	if (copy_to_user((void __user *)dst, src, n))
357 		return -EFAULT;
358 
359 	return 0;
360 }
361 
362 static int xilly_memcpy(void *dst, const void *src, int n)
363 {
364 	memcpy(dst, src, n);
365 
366 	return 0;
367 }
368 
369 static int fifo_init(struct xillyfifo *fifo,
370 		     unsigned int log2_size)
371 {
372 	unsigned int log2_bufnum;
373 	int i;
374 
375 	unsigned int log2_fifo_buf_size;
376 
377 	mutex_lock(&fifo_buf_order_mutex);
378 
379 retry:
380 	log2_fifo_buf_size = fifo_buf_order + PAGE_SHIFT;
381 
382 	if (log2_size > log2_fifo_buf_size) {
383 		log2_bufnum = log2_size - log2_fifo_buf_size;
384 		fifo->bufsize = 1 << log2_fifo_buf_size;
385 	} else {
386 		log2_bufnum = 0;
387 		fifo->bufsize = 1 << log2_size;
388 	}
389 
390 	fifo->bufnum = 1 << log2_bufnum;
391 	fifo->size = fifo->bufnum * fifo->bufsize;
392 
393 	if (!fifo->size || /* Unsigned integer overflow */
394 	    fifo->size > SZ_1G) { /* Avoid signed int issues */
395 		mutex_unlock(&fifo_buf_order_mutex);
396 		return -ENOMEM; /* Reported as greed for memory */
397 	}
398 
399 	fifo->mem = kmalloc_array(fifo->bufnum, sizeof(void *), GFP_KERNEL);
400 
401 	if (!fifo->mem) {
402 		mutex_unlock(&fifo_buf_order_mutex);
403 		return -ENOMEM;
404 	}
405 
406 	for (i = 0; i < fifo->bufnum; i++) {
407 		fifo->mem[i] = kmalloc(fifo->bufsize, GFP_KERNEL);
408 
409 		if (!fifo->mem[i])
410 			goto memfail;
411 	}
412 
413 	fifo->fill = 0;
414 	fifo->readpos = 0;
415 	fifo->readbuf = 0;
416 	fifo->writepos = 0;
417 	fifo->writebuf = 0;
418 	spin_lock_init(&fifo->lock);
419 	init_waitqueue_head(&fifo->waitq);
420 
421 	mutex_unlock(&fifo_buf_order_mutex);
422 	return 0;
423 
424 memfail:
425 	for (i--; i >= 0; i--)
426 		kfree(fifo->mem[i]);
427 
428 	kfree(fifo->mem);
429 	fifo->mem = NULL;
430 
431 	if (fifo_buf_order) {
432 		fifo_buf_order--;
433 		goto retry;
434 	} else {
435 		mutex_unlock(&fifo_buf_order_mutex);
436 		return -ENOMEM;
437 	}
438 }
439 
440 static void fifo_mem_release(struct xillyfifo *fifo)
441 {
442 	int i;
443 
444 	if (!fifo->mem)
445 		return;
446 
447 	for (i = 0; i < fifo->bufnum; i++)
448 		kfree(fifo->mem[i]);
449 
450 	kfree(fifo->mem);
451 }
452 
453 /*
454  * When endpoint_quiesce() returns, the endpoint has no URBs submitted,
455  * won't accept any new URB submissions, and its related work item doesn't
456  * and won't run anymore.
457  */
458 
459 static void endpoint_quiesce(struct xillyusb_endpoint *ep)
460 {
461 	mutex_lock(&ep->ep_mutex);
462 	ep->shutting_down = true;
463 	mutex_unlock(&ep->ep_mutex);
464 
465 	usb_kill_anchored_urbs(&ep->anchor);
466 	cancel_work_sync(&ep->workitem);
467 }
468 
469 /*
470  * Note that endpoint_dealloc() also frees fifo memory (if allocated), even
471  * though endpoint_alloc doesn't allocate that memory.
472  */
473 
474 static void endpoint_dealloc(struct xillyusb_endpoint *ep)
475 {
476 	struct list_head *this, *next;
477 
478 	fifo_mem_release(&ep->fifo);
479 
480 	/* Join @filled_buffers with @buffers to free these entries too */
481 	list_splice(&ep->filled_buffers, &ep->buffers);
482 
483 	list_for_each_safe(this, next, &ep->buffers) {
484 		struct xillybuffer *xb =
485 			list_entry(this, struct xillybuffer, entry);
486 
487 		kfree(xb->buf);
488 		kfree(xb);
489 	}
490 
491 	kfree(ep);
492 }
493 
494 static struct xillyusb_endpoint
495 *endpoint_alloc(struct xillyusb_dev *xdev,
496 		u8 ep_num,
497 		void (*work)(struct work_struct *),
498 		unsigned int order,
499 		int bufnum)
500 {
501 	int i;
502 
503 	struct xillyusb_endpoint *ep;
504 
505 	ep = kzalloc_obj(*ep);
506 
507 	if (!ep)
508 		return NULL;
509 
510 	INIT_LIST_HEAD(&ep->buffers);
511 	INIT_LIST_HEAD(&ep->filled_buffers);
512 
513 	spin_lock_init(&ep->buffers_lock);
514 	mutex_init(&ep->ep_mutex);
515 
516 	init_usb_anchor(&ep->anchor);
517 	INIT_WORK(&ep->workitem, work);
518 
519 	ep->buffer_size = 1 << (PAGE_SHIFT + order);
520 	ep->outstanding_urbs = 0;
521 	ep->drained = true;
522 	ep->wake_on_drain = false;
523 	ep->xdev = xdev;
524 	ep->ep_num = ep_num;
525 	ep->shutting_down = false;
526 
527 	for (i = 0; i < bufnum; i++) {
528 		struct xillybuffer *xb;
529 
530 		xb = kzalloc_obj(*xb);
531 
532 		if (!xb) {
533 			endpoint_dealloc(ep);
534 			return NULL;
535 		}
536 
537 		xb->buf = kmalloc(ep->buffer_size, GFP_KERNEL);
538 
539 		if (!xb->buf) {
540 			kfree(xb);
541 			endpoint_dealloc(ep);
542 			return NULL;
543 		}
544 
545 		xb->ep = ep;
546 		list_add_tail(&xb->entry, &ep->buffers);
547 	}
548 	return ep;
549 }
550 
551 static void cleanup_dev(struct kref *kref)
552 {
553 	struct xillyusb_dev *xdev =
554 		container_of(kref, struct xillyusb_dev, kref);
555 
556 	if (xdev->in_ep)
557 		endpoint_dealloc(xdev->in_ep);
558 
559 	if (xdev->msg_ep)
560 		endpoint_dealloc(xdev->msg_ep);
561 
562 	if (xdev->workq)
563 		destroy_workqueue(xdev->workq);
564 
565 	usb_put_dev(xdev->udev);
566 	kfree(xdev->channels); /* Argument may be NULL, and that's fine */
567 	kfree(xdev);
568 }
569 
570 /*
571  * @process_in_mutex is taken to ensure that bulk_in_work() won't call
572  * process_bulk_in() after wakeup_all()'s execution: The latter zeroes all
573  * @read_data_ok entries, which will make process_bulk_in() report false
574  * errors if executed. The mechanism relies on that xdev->error is assigned
575  * a non-zero value by report_io_error() prior to queueing wakeup_all(),
576  * which prevents bulk_in_work() from calling process_bulk_in().
577  */
578 
579 static void wakeup_all(struct work_struct *work)
580 {
581 	int i;
582 	struct xillyusb_dev *xdev = container_of(work, struct xillyusb_dev,
583 						 wakeup_workitem);
584 
585 	mutex_lock(&xdev->process_in_mutex);
586 
587 	for (i = 0; i < xdev->num_channels; i++) {
588 		struct xillyusb_channel *chan = &xdev->channels[i];
589 
590 		mutex_lock(&chan->lock);
591 
592 		if (chan->in_fifo) {
593 			/*
594 			 * Fake an EOF: Even if such arrives, it won't be
595 			 * processed.
596 			 */
597 			chan->read_data_ok = 0;
598 			wake_up_interruptible(&chan->in_fifo->waitq);
599 		}
600 
601 		if (chan->out_ep)
602 			wake_up_interruptible(&chan->out_ep->fifo.waitq);
603 
604 		mutex_unlock(&chan->lock);
605 
606 		wake_up_interruptible(&chan->flushq);
607 	}
608 
609 	mutex_unlock(&xdev->process_in_mutex);
610 
611 	wake_up_interruptible(&xdev->msg_ep->fifo.waitq);
612 
613 	kref_put(&xdev->kref, cleanup_dev);
614 }
615 
616 static void report_io_error(struct xillyusb_dev *xdev,
617 			    int errcode)
618 {
619 	unsigned long flags;
620 	bool do_once = false;
621 
622 	spin_lock_irqsave(&xdev->error_lock, flags);
623 	if (!xdev->error) {
624 		xdev->error = errcode;
625 		do_once = true;
626 	}
627 	spin_unlock_irqrestore(&xdev->error_lock, flags);
628 
629 	if (do_once) {
630 		kref_get(&xdev->kref); /* xdev is used by work item */
631 		queue_work(wakeup_wq, &xdev->wakeup_workitem);
632 	}
633 }
634 
635 /*
636  * safely_assign_in_fifo() changes the value of chan->in_fifo and ensures
637  * the previous pointer is never used after its return.
638  */
639 
640 static void safely_assign_in_fifo(struct xillyusb_channel *chan,
641 				  struct xillyfifo *fifo)
642 {
643 	mutex_lock(&chan->lock);
644 	chan->in_fifo = fifo;
645 	mutex_unlock(&chan->lock);
646 
647 	flush_work(&chan->xdev->in_ep->workitem);
648 }
649 
650 static void bulk_in_completer(struct urb *urb)
651 {
652 	struct xillybuffer *xb = urb->context;
653 	struct xillyusb_endpoint *ep = xb->ep;
654 	unsigned long flags;
655 
656 	if (urb->status) {
657 		if (!(urb->status == -ENOENT ||
658 		      urb->status == -ECONNRESET ||
659 		      urb->status == -ESHUTDOWN))
660 			report_io_error(ep->xdev, -EIO);
661 
662 		spin_lock_irqsave(&ep->buffers_lock, flags);
663 		list_add_tail(&xb->entry, &ep->buffers);
664 		ep->outstanding_urbs--;
665 		spin_unlock_irqrestore(&ep->buffers_lock, flags);
666 
667 		return;
668 	}
669 
670 	xb->len = urb->actual_length;
671 
672 	spin_lock_irqsave(&ep->buffers_lock, flags);
673 	list_add_tail(&xb->entry, &ep->filled_buffers);
674 	spin_unlock_irqrestore(&ep->buffers_lock, flags);
675 
676 	if (!ep->shutting_down)
677 		queue_work(ep->xdev->workq, &ep->workitem);
678 }
679 
680 static void bulk_out_completer(struct urb *urb)
681 {
682 	struct xillybuffer *xb = urb->context;
683 	struct xillyusb_endpoint *ep = xb->ep;
684 	unsigned long flags;
685 
686 	if (urb->status &&
687 	    (!(urb->status == -ENOENT ||
688 	       urb->status == -ECONNRESET ||
689 	       urb->status == -ESHUTDOWN)))
690 		report_io_error(ep->xdev, -EIO);
691 
692 	spin_lock_irqsave(&ep->buffers_lock, flags);
693 	list_add_tail(&xb->entry, &ep->buffers);
694 	ep->outstanding_urbs--;
695 	spin_unlock_irqrestore(&ep->buffers_lock, flags);
696 
697 	if (!ep->shutting_down)
698 		queue_work(ep->xdev->workq, &ep->workitem);
699 }
700 
701 static void try_queue_bulk_in(struct xillyusb_endpoint *ep)
702 {
703 	struct xillyusb_dev *xdev = ep->xdev;
704 	struct xillybuffer *xb;
705 	struct urb *urb;
706 
707 	int rc;
708 	unsigned long flags;
709 	unsigned int bufsize = ep->buffer_size;
710 
711 	mutex_lock(&ep->ep_mutex);
712 
713 	if (ep->shutting_down || xdev->error)
714 		goto done;
715 
716 	while (1) {
717 		spin_lock_irqsave(&ep->buffers_lock, flags);
718 
719 		if (list_empty(&ep->buffers)) {
720 			spin_unlock_irqrestore(&ep->buffers_lock, flags);
721 			goto done;
722 		}
723 
724 		xb = list_first_entry(&ep->buffers, struct xillybuffer, entry);
725 		list_del(&xb->entry);
726 		ep->outstanding_urbs++;
727 
728 		spin_unlock_irqrestore(&ep->buffers_lock, flags);
729 
730 		urb = usb_alloc_urb(0, GFP_KERNEL);
731 		if (!urb) {
732 			report_io_error(xdev, -ENOMEM);
733 			goto relist;
734 		}
735 
736 		usb_fill_bulk_urb(urb, xdev->udev,
737 				  usb_rcvbulkpipe(xdev->udev, ep->ep_num),
738 				  xb->buf, bufsize, bulk_in_completer, xb);
739 
740 		usb_anchor_urb(urb, &ep->anchor);
741 
742 		rc = usb_submit_urb(urb, GFP_KERNEL);
743 
744 		if (rc) {
745 			report_io_error(xdev, (rc == -ENOMEM) ? -ENOMEM :
746 					-EIO);
747 			goto unanchor;
748 		}
749 
750 		usb_free_urb(urb); /* This just decrements reference count */
751 	}
752 
753 unanchor:
754 	usb_unanchor_urb(urb);
755 	usb_free_urb(urb);
756 
757 relist:
758 	spin_lock_irqsave(&ep->buffers_lock, flags);
759 	list_add_tail(&xb->entry, &ep->buffers);
760 	ep->outstanding_urbs--;
761 	spin_unlock_irqrestore(&ep->buffers_lock, flags);
762 
763 done:
764 	mutex_unlock(&ep->ep_mutex);
765 }
766 
767 static void try_queue_bulk_out(struct xillyusb_endpoint *ep)
768 {
769 	struct xillyfifo *fifo = &ep->fifo;
770 	struct xillyusb_dev *xdev = ep->xdev;
771 	struct xillybuffer *xb;
772 	struct urb *urb;
773 
774 	int rc;
775 	unsigned int fill;
776 	unsigned long flags;
777 	bool do_wake = false;
778 
779 	mutex_lock(&ep->ep_mutex);
780 
781 	if (ep->shutting_down || xdev->error)
782 		goto done;
783 
784 	fill = READ_ONCE(fifo->fill) & ep->fill_mask;
785 
786 	while (1) {
787 		int count;
788 		unsigned int max_read;
789 
790 		spin_lock_irqsave(&ep->buffers_lock, flags);
791 
792 		/*
793 		 * Race conditions might have the FIFO filled while the
794 		 * endpoint is marked as drained here. That doesn't matter,
795 		 * because the sole purpose of @drained is to ensure that
796 		 * certain data has been sent on the USB channel before
797 		 * shutting it down. Hence knowing that the FIFO appears
798 		 * to be empty with no outstanding URBs at some moment
799 		 * is good enough.
800 		 */
801 
802 		if (!fill) {
803 			ep->drained = !ep->outstanding_urbs;
804 			if (ep->drained && ep->wake_on_drain)
805 				do_wake = true;
806 
807 			spin_unlock_irqrestore(&ep->buffers_lock, flags);
808 			goto done;
809 		}
810 
811 		ep->drained = false;
812 
813 		if ((fill < ep->buffer_size && ep->outstanding_urbs) ||
814 		    list_empty(&ep->buffers)) {
815 			spin_unlock_irqrestore(&ep->buffers_lock, flags);
816 			goto done;
817 		}
818 
819 		xb = list_first_entry(&ep->buffers, struct xillybuffer, entry);
820 		list_del(&xb->entry);
821 		ep->outstanding_urbs++;
822 
823 		spin_unlock_irqrestore(&ep->buffers_lock, flags);
824 
825 		max_read = min(fill, ep->buffer_size);
826 
827 		count = fifo_read(&ep->fifo, xb->buf, max_read, xilly_memcpy);
828 
829 		/*
830 		 * xilly_memcpy always returns 0 => fifo_read can't fail =>
831 		 * count > 0
832 		 */
833 
834 		urb = usb_alloc_urb(0, GFP_KERNEL);
835 		if (!urb) {
836 			report_io_error(xdev, -ENOMEM);
837 			goto relist;
838 		}
839 
840 		usb_fill_bulk_urb(urb, xdev->udev,
841 				  usb_sndbulkpipe(xdev->udev, ep->ep_num),
842 				  xb->buf, count, bulk_out_completer, xb);
843 
844 		usb_anchor_urb(urb, &ep->anchor);
845 
846 		rc = usb_submit_urb(urb, GFP_KERNEL);
847 
848 		if (rc) {
849 			report_io_error(xdev, (rc == -ENOMEM) ? -ENOMEM :
850 					-EIO);
851 			goto unanchor;
852 		}
853 
854 		usb_free_urb(urb); /* This just decrements reference count */
855 
856 		fill -= count;
857 		do_wake = true;
858 	}
859 
860 unanchor:
861 	usb_unanchor_urb(urb);
862 	usb_free_urb(urb);
863 
864 relist:
865 	spin_lock_irqsave(&ep->buffers_lock, flags);
866 	list_add_tail(&xb->entry, &ep->buffers);
867 	ep->outstanding_urbs--;
868 	spin_unlock_irqrestore(&ep->buffers_lock, flags);
869 
870 done:
871 	mutex_unlock(&ep->ep_mutex);
872 
873 	if (do_wake)
874 		wake_up_interruptible(&fifo->waitq);
875 }
876 
877 static void bulk_out_work(struct work_struct *work)
878 {
879 	struct xillyusb_endpoint *ep = container_of(work,
880 						    struct xillyusb_endpoint,
881 						    workitem);
882 	try_queue_bulk_out(ep);
883 }
884 
885 static int process_in_opcode(struct xillyusb_dev *xdev,
886 			     int opcode,
887 			     int chan_num)
888 {
889 	struct xillyusb_channel *chan;
890 	struct device *dev = xdev->dev;
891 	int chan_idx = chan_num >> 1;
892 	struct xillyfifo *in_fifo;
893 
894 	if (chan_idx >= xdev->num_channels) {
895 		dev_err(dev, "Received illegal channel ID %d from FPGA\n",
896 			chan_num);
897 		return -EIO;
898 	}
899 
900 	chan = &xdev->channels[chan_idx];
901 
902 	switch (opcode) {
903 	case OPCODE_EOF:
904 		if (!chan->read_data_ok) {
905 			dev_err(dev, "Received unexpected EOF for channel %d\n",
906 				chan_num);
907 			return -EIO;
908 		}
909 
910 		/*
911 		 * A write memory barrier ensures that the FIFO's fill level
912 		 * is visible before read_data_ok turns zero, so the data in
913 		 * the FIFO isn't missed by the consumer.
914 		 */
915 		smp_wmb();
916 		WRITE_ONCE(chan->read_data_ok, 0);
917 
918 		in_fifo = READ_ONCE(chan->in_fifo);
919 		if (in_fifo)
920 			wake_up_interruptible(&in_fifo->waitq);
921 		break;
922 
923 	case OPCODE_REACHED_CHECKPOINT:
924 		chan->flushing = 0;
925 		wake_up_interruptible(&chan->flushq);
926 		break;
927 
928 	case OPCODE_CANCELED_CHECKPOINT:
929 		chan->canceled = 1;
930 		wake_up_interruptible(&chan->flushq);
931 		break;
932 
933 	default:
934 		dev_err(dev, "Received illegal opcode %d from FPGA\n",
935 			opcode);
936 		return -EIO;
937 	}
938 
939 	return 0;
940 }
941 
942 static int process_bulk_in(struct xillybuffer *xb)
943 {
944 	struct xillyusb_endpoint *ep = xb->ep;
945 	struct xillyusb_dev *xdev = ep->xdev;
946 	struct device *dev = xdev->dev;
947 	int dws = xb->len >> 2;
948 	__le32 *p = xb->buf;
949 	u32 ctrlword;
950 	struct xillyusb_channel *chan;
951 	struct xillyfifo *fifo;
952 	int chan_num = 0, opcode;
953 	int chan_idx;
954 	int bytes, count, dwconsume;
955 	int in_bytes_left = 0;
956 	int rc;
957 
958 	if ((dws << 2) != xb->len) {
959 		dev_err(dev, "Received BULK IN transfer with %d bytes, not a multiple of 4\n",
960 			xb->len);
961 		return -EIO;
962 	}
963 
964 	if (xdev->in_bytes_left) {
965 		bytes = min(xdev->in_bytes_left, dws << 2);
966 		in_bytes_left = xdev->in_bytes_left - bytes;
967 		chan_num = xdev->leftover_chan_num;
968 		goto resume_leftovers;
969 	}
970 
971 	while (dws) {
972 		ctrlword = le32_to_cpu(*p++);
973 		dws--;
974 
975 		chan_num = ctrlword & 0xfff;
976 		count = (ctrlword >> 12) & 0x3ff;
977 		opcode = (ctrlword >> 24) & 0xf;
978 
979 		if (opcode != OPCODE_DATA) {
980 			unsigned int in_counter = xdev->in_counter++ & 0x3ff;
981 
982 			if (count != in_counter) {
983 				dev_err(dev, "Expected opcode counter %d, got %d\n",
984 					in_counter, count);
985 				return -EIO;
986 			}
987 
988 			rc = process_in_opcode(xdev, opcode, chan_num);
989 
990 			if (rc)
991 				return rc;
992 
993 			continue;
994 		}
995 
996 		bytes = min(count + 1, dws << 2);
997 		in_bytes_left = count + 1 - bytes;
998 
999 resume_leftovers:
1000 		chan_idx = chan_num >> 1;
1001 
1002 		if (!(chan_num & 1) || chan_idx >= xdev->num_channels ||
1003 		    !xdev->channels[chan_idx].read_data_ok) {
1004 			dev_err(dev, "Received illegal channel ID %d from FPGA\n",
1005 				chan_num);
1006 			return -EIO;
1007 		}
1008 		chan = &xdev->channels[chan_idx];
1009 
1010 		fifo = chan->in_fifo;
1011 
1012 		if (unlikely(!fifo))
1013 			return -EIO; /* We got really unexpected data */
1014 
1015 		if (bytes != fifo_write(fifo, p, bytes, xilly_memcpy)) {
1016 			dev_err(dev, "Misbehaving FPGA overflowed an upstream FIFO!\n");
1017 			return -EIO;
1018 		}
1019 
1020 		wake_up_interruptible(&fifo->waitq);
1021 
1022 		dwconsume = (bytes + 3) >> 2;
1023 		dws -= dwconsume;
1024 		p += dwconsume;
1025 	}
1026 
1027 	xdev->in_bytes_left = in_bytes_left;
1028 	xdev->leftover_chan_num = chan_num;
1029 	return 0;
1030 }
1031 
1032 static void bulk_in_work(struct work_struct *work)
1033 {
1034 	struct xillyusb_endpoint *ep =
1035 		container_of(work, struct xillyusb_endpoint, workitem);
1036 	struct xillyusb_dev *xdev = ep->xdev;
1037 	unsigned long flags;
1038 	struct xillybuffer *xb;
1039 	bool consumed = false;
1040 	int rc = 0;
1041 
1042 	mutex_lock(&xdev->process_in_mutex);
1043 
1044 	spin_lock_irqsave(&ep->buffers_lock, flags);
1045 
1046 	while (1) {
1047 		if (rc || list_empty(&ep->filled_buffers)) {
1048 			spin_unlock_irqrestore(&ep->buffers_lock, flags);
1049 			mutex_unlock(&xdev->process_in_mutex);
1050 
1051 			if (rc)
1052 				report_io_error(xdev, rc);
1053 			else if (consumed)
1054 				try_queue_bulk_in(ep);
1055 
1056 			return;
1057 		}
1058 
1059 		xb = list_first_entry(&ep->filled_buffers, struct xillybuffer,
1060 				      entry);
1061 		list_del(&xb->entry);
1062 
1063 		spin_unlock_irqrestore(&ep->buffers_lock, flags);
1064 
1065 		consumed = true;
1066 
1067 		if (!xdev->error)
1068 			rc = process_bulk_in(xb);
1069 
1070 		spin_lock_irqsave(&ep->buffers_lock, flags);
1071 		list_add_tail(&xb->entry, &ep->buffers);
1072 		ep->outstanding_urbs--;
1073 	}
1074 }
1075 
1076 static int xillyusb_send_opcode(struct xillyusb_dev *xdev,
1077 				int chan_num, char opcode, u32 data)
1078 {
1079 	struct xillyusb_endpoint *ep = xdev->msg_ep;
1080 	struct xillyfifo *fifo = &ep->fifo;
1081 	__le32 msg[2];
1082 
1083 	int rc = 0;
1084 
1085 	msg[0] = cpu_to_le32((chan_num & 0xfff) |
1086 			     ((opcode & 0xf) << 24));
1087 	msg[1] = cpu_to_le32(data);
1088 
1089 	mutex_lock(&xdev->msg_mutex);
1090 
1091 	/*
1092 	 * The wait queue is woken with the interruptible variant, so the
1093 	 * wait function matches, however returning because of an interrupt
1094 	 * will mess things up considerably, in particular when the caller is
1095 	 * the release method. And the xdev->error part prevents being stuck
1096 	 * forever in the event of a bizarre hardware bug: Pull the USB plug.
1097 	 */
1098 
1099 	while (wait_event_interruptible(fifo->waitq,
1100 					fifo->fill <= (fifo->size - 8) ||
1101 					xdev->error))
1102 		; /* Empty loop */
1103 
1104 	if (xdev->error) {
1105 		rc = xdev->error;
1106 		goto unlock_done;
1107 	}
1108 
1109 	fifo_write(fifo, (void *)msg, 8, xilly_memcpy);
1110 
1111 	try_queue_bulk_out(ep);
1112 
1113 unlock_done:
1114 	mutex_unlock(&xdev->msg_mutex);
1115 
1116 	return rc;
1117 }
1118 
1119 /*
1120  * Note that flush_downstream() merely waits for the data to arrive to
1121  * the application logic at the FPGA -- unlike PCIe Xillybus' counterpart,
1122  * it does nothing to make it happen (and neither is it necessary).
1123  *
1124  * This function is not reentrant for the same @chan, but this is covered
1125  * by the fact that for any given @chan, it's called either by the open,
1126  * write, llseek and flush fops methods, which can't run in parallel (and the
1127  * write + flush and llseek method handlers are protected with out_mutex).
1128  *
1129  * chan->flushed is there to avoid multiple flushes at the same position,
1130  * in particular as a result of programs that close the file descriptor
1131  * e.g. after a dup2() for redirection.
1132  */
1133 
1134 static int flush_downstream(struct xillyusb_channel *chan,
1135 			    unsigned long timeout,
1136 			    bool interruptible)
1137 {
1138 	struct xillyusb_dev *xdev = chan->xdev;
1139 	int chan_num = chan->chan_idx << 1;
1140 	unsigned long deadline;
1141 	long left_to_sleep;
1142 	int rc;
1143 
1144 	if (chan->flushed)
1145 		return 0;
1146 
1147 	deadline = jiffies + 1 + timeout;
1148 
1149 	if (chan->flushing) {
1150 		unsigned long cancel_deadline =
1151 			jiffies + 1 + XILLY_RESPONSE_TIMEOUT;
1152 
1153 		chan->canceled = 0;
1154 		rc = xillyusb_send_opcode(xdev, chan_num,
1155 					  OPCODE_CANCEL_CHECKPOINT, 0);
1156 
1157 		if (rc)
1158 			return rc; /* Only real error, never -EINTR */
1159 
1160 		/* Ignoring interrupts. Cancellation must be handled */
1161 		while (!chan->canceled) {
1162 			left_to_sleep = cancel_deadline - jiffies;
1163 
1164 			if (left_to_sleep <= 0) {
1165 				report_io_error(xdev, -EIO);
1166 				return -EIO;
1167 			}
1168 
1169 			rc = wait_event_interruptible_timeout(chan->flushq,
1170 							      chan->canceled ||
1171 							      xdev->error,
1172 							      left_to_sleep);
1173 
1174 			if (xdev->error)
1175 				return xdev->error;
1176 		}
1177 	}
1178 
1179 	chan->flushing = 1;
1180 
1181 	/*
1182 	 * The checkpoint is given in terms of data elements, not bytes. As
1183 	 * a result, if less than an element's worth of data is stored in the
1184 	 * FIFO, it's not flushed, including the flush before closing, which
1185 	 * means that such data is lost. This is consistent with PCIe Xillybus.
1186 	 */
1187 
1188 	rc = xillyusb_send_opcode(xdev, chan_num,
1189 				  OPCODE_SET_CHECKPOINT,
1190 				  chan->out_bytes >>
1191 				  chan->out_log2_element_size);
1192 
1193 	if (rc)
1194 		return rc; /* Only real error, never -EINTR */
1195 
1196 	if (!timeout) {
1197 		while (chan->flushing) {
1198 			rc = wait_event_interruptible(chan->flushq,
1199 						      !chan->flushing ||
1200 						      xdev->error);
1201 			if (xdev->error)
1202 				return xdev->error;
1203 
1204 			if (interruptible && rc)
1205 				return -EINTR;
1206 		}
1207 
1208 		goto done;
1209 	}
1210 
1211 	while (chan->flushing) {
1212 		left_to_sleep = deadline - jiffies;
1213 
1214 		if (left_to_sleep <= 0)
1215 			return -ETIMEDOUT;
1216 
1217 		rc = wait_event_interruptible_timeout(chan->flushq,
1218 						      !chan->flushing ||
1219 						      xdev->error,
1220 						      left_to_sleep);
1221 
1222 		if (xdev->error)
1223 			return xdev->error;
1224 
1225 		if (interruptible && rc < 0)
1226 			return -EINTR;
1227 	}
1228 
1229 done:
1230 	chan->flushed = 1;
1231 	return 0;
1232 }
1233 
1234 /* request_read_anything(): Ask the FPGA for any little amount of data */
1235 static int request_read_anything(struct xillyusb_channel *chan,
1236 				 char opcode)
1237 {
1238 	struct xillyusb_dev *xdev = chan->xdev;
1239 	unsigned int sh = chan->in_log2_element_size;
1240 	int chan_num = (chan->chan_idx << 1) | 1;
1241 	u32 mercy = chan->in_consumed_bytes + (2 << sh) - 1;
1242 
1243 	return xillyusb_send_opcode(xdev, chan_num, opcode, mercy >> sh);
1244 }
1245 
1246 static int xillyusb_open(struct inode *inode, struct file *filp)
1247 {
1248 	struct xillyusb_dev *xdev;
1249 	struct xillyusb_channel *chan;
1250 	struct xillyfifo *in_fifo = NULL;
1251 	struct xillyusb_endpoint *out_ep = NULL;
1252 	int rc;
1253 	int index;
1254 
1255 	mutex_lock(&kref_mutex);
1256 
1257 	rc = xillybus_find_inode(inode, (void **)&xdev, &index);
1258 	if (rc) {
1259 		mutex_unlock(&kref_mutex);
1260 		return rc;
1261 	}
1262 
1263 	kref_get(&xdev->kref);
1264 	mutex_unlock(&kref_mutex);
1265 
1266 	chan = &xdev->channels[index];
1267 	filp->private_data = chan;
1268 
1269 	mutex_lock(&chan->lock);
1270 
1271 	rc = -ENODEV;
1272 
1273 	if (xdev->error)
1274 		goto unmutex_fail;
1275 
1276 	if (((filp->f_mode & FMODE_READ) && !chan->readable) ||
1277 	    ((filp->f_mode & FMODE_WRITE) && !chan->writable))
1278 		goto unmutex_fail;
1279 
1280 	if ((filp->f_flags & O_NONBLOCK) && (filp->f_mode & FMODE_READ) &&
1281 	    chan->in_synchronous) {
1282 		dev_err(xdev->dev,
1283 			"open() failed: O_NONBLOCK not allowed for read on this device\n");
1284 		goto unmutex_fail;
1285 	}
1286 
1287 	if ((filp->f_flags & O_NONBLOCK) && (filp->f_mode & FMODE_WRITE) &&
1288 	    chan->out_synchronous) {
1289 		dev_err(xdev->dev,
1290 			"open() failed: O_NONBLOCK not allowed for write on this device\n");
1291 		goto unmutex_fail;
1292 	}
1293 
1294 	rc = -EBUSY;
1295 
1296 	if (((filp->f_mode & FMODE_READ) && chan->open_for_read) ||
1297 	    ((filp->f_mode & FMODE_WRITE) && chan->open_for_write))
1298 		goto unmutex_fail;
1299 
1300 	if (filp->f_mode & FMODE_READ)
1301 		chan->open_for_read = 1;
1302 
1303 	if (filp->f_mode & FMODE_WRITE)
1304 		chan->open_for_write = 1;
1305 
1306 	mutex_unlock(&chan->lock);
1307 
1308 	if (filp->f_mode & FMODE_WRITE) {
1309 		out_ep = endpoint_alloc(xdev,
1310 					(chan->chan_idx + 2) | USB_DIR_OUT,
1311 					bulk_out_work, BUF_SIZE_ORDER, BUFNUM);
1312 
1313 		if (!out_ep) {
1314 			rc = -ENOMEM;
1315 			goto unopen;
1316 		}
1317 
1318 		rc = fifo_init(&out_ep->fifo, chan->out_log2_fifo_size);
1319 
1320 		if (rc)
1321 			goto late_unopen;
1322 
1323 		out_ep->fill_mask = -(1 << chan->out_log2_element_size);
1324 		chan->out_bytes = 0;
1325 		chan->flushed = 0;
1326 
1327 		/*
1328 		 * Sending a flush request to a previously closed stream
1329 		 * effectively opens it, and also waits until the command is
1330 		 * confirmed by the FPGA. The latter is necessary because the
1331 		 * data is sent through a separate BULK OUT endpoint, and the
1332 		 * xHCI controller is free to reorder transmissions.
1333 		 *
1334 		 * This can't go wrong unless there's a serious hardware error
1335 		 * (or the computer is stuck for 500 ms?)
1336 		 */
1337 		rc = flush_downstream(chan, XILLY_RESPONSE_TIMEOUT, false);
1338 
1339 		if (rc == -ETIMEDOUT) {
1340 			rc = -EIO;
1341 			report_io_error(xdev, rc);
1342 		}
1343 
1344 		if (rc)
1345 			goto late_unopen;
1346 	}
1347 
1348 	if (filp->f_mode & FMODE_READ) {
1349 		in_fifo = kzalloc_obj(*in_fifo);
1350 
1351 		if (!in_fifo) {
1352 			rc = -ENOMEM;
1353 			goto late_unopen;
1354 		}
1355 
1356 		rc = fifo_init(in_fifo, chan->in_log2_fifo_size);
1357 
1358 		if (rc) {
1359 			kfree(in_fifo);
1360 			goto late_unopen;
1361 		}
1362 	}
1363 
1364 	mutex_lock(&chan->lock);
1365 	if (in_fifo) {
1366 		chan->in_fifo = in_fifo;
1367 		chan->read_data_ok = 1;
1368 	}
1369 	if (out_ep)
1370 		chan->out_ep = out_ep;
1371 	mutex_unlock(&chan->lock);
1372 
1373 	if (in_fifo) {
1374 		u32 in_checkpoint = 0;
1375 
1376 		if (!chan->in_synchronous)
1377 			in_checkpoint = in_fifo->size >>
1378 				chan->in_log2_element_size;
1379 
1380 		chan->in_consumed_bytes = 0;
1381 		chan->poll_used = 0;
1382 		chan->in_current_checkpoint = in_checkpoint;
1383 		rc = xillyusb_send_opcode(xdev, (chan->chan_idx << 1) | 1,
1384 					  OPCODE_SET_CHECKPOINT,
1385 					  in_checkpoint);
1386 
1387 		if (rc) /* Failure guarantees that opcode wasn't sent */
1388 			goto unfifo;
1389 
1390 		/*
1391 		 * In non-blocking mode, request the FPGA to send any data it
1392 		 * has right away. Otherwise, the first read() will always
1393 		 * return -EAGAIN, which is OK strictly speaking, but ugly.
1394 		 * Checking and unrolling if this fails isn't worth the
1395 		 * effort -- the error is propagated to the first read()
1396 		 * anyhow.
1397 		 */
1398 		if (filp->f_flags & O_NONBLOCK)
1399 			request_read_anything(chan, OPCODE_SET_PUSH);
1400 	}
1401 
1402 	return 0;
1403 
1404 unfifo:
1405 	chan->read_data_ok = 0;
1406 	safely_assign_in_fifo(chan, NULL);
1407 	fifo_mem_release(in_fifo);
1408 	kfree(in_fifo);
1409 
1410 	if (out_ep) {
1411 		mutex_lock(&chan->lock);
1412 		chan->out_ep = NULL;
1413 		mutex_unlock(&chan->lock);
1414 	}
1415 
1416 late_unopen:
1417 	if (out_ep)
1418 		endpoint_dealloc(out_ep);
1419 
1420 unopen:
1421 	mutex_lock(&chan->lock);
1422 
1423 	if (filp->f_mode & FMODE_READ)
1424 		chan->open_for_read = 0;
1425 
1426 	if (filp->f_mode & FMODE_WRITE)
1427 		chan->open_for_write = 0;
1428 
1429 unmutex_fail:
1430 	mutex_unlock(&chan->lock);
1431 
1432 	kref_put(&xdev->kref, cleanup_dev);
1433 
1434 	return rc;
1435 }
1436 
1437 static ssize_t xillyusb_read(struct file *filp, char __user *userbuf,
1438 			     size_t count, loff_t *f_pos)
1439 {
1440 	struct xillyusb_channel *chan = filp->private_data;
1441 	struct xillyusb_dev *xdev = chan->xdev;
1442 	struct xillyfifo *fifo = chan->in_fifo;
1443 	int chan_num = (chan->chan_idx << 1) | 1;
1444 
1445 	unsigned long deadline;
1446 	long left_to_sleep;
1447 	int bytes_done = 0;
1448 	bool sent_set_push = false;
1449 	int rc;
1450 
1451 	deadline = jiffies + 1 + XILLY_RX_TIMEOUT;
1452 
1453 	rc = mutex_lock_interruptible(&chan->in_mutex);
1454 
1455 	if (rc)
1456 		return rc;
1457 
1458 	while (1) {
1459 		u32 fifo_checkpoint_bytes, complete_checkpoint_bytes;
1460 		u32 complete_checkpoint, fifo_checkpoint;
1461 		u32 checkpoint;
1462 		s32 diff, leap;
1463 		unsigned int sh = chan->in_log2_element_size;
1464 		bool checkpoint_for_complete;
1465 
1466 		rc = fifo_read(fifo, (__force void *)userbuf + bytes_done,
1467 			       count - bytes_done, xilly_copy_to_user);
1468 
1469 		if (rc < 0)
1470 			break;
1471 
1472 		bytes_done += rc;
1473 		chan->in_consumed_bytes += rc;
1474 
1475 		left_to_sleep = deadline - jiffies;
1476 
1477 		/*
1478 		 * Some 32-bit arithmetic that may wrap. Note that
1479 		 * complete_checkpoint is rounded up to the closest element
1480 		 * boundary, because the read() can't be completed otherwise.
1481 		 * fifo_checkpoint_bytes is rounded down, because it protects
1482 		 * in_fifo from overflowing.
1483 		 */
1484 
1485 		fifo_checkpoint_bytes = chan->in_consumed_bytes + fifo->size;
1486 		complete_checkpoint_bytes =
1487 			chan->in_consumed_bytes + count - bytes_done;
1488 
1489 		fifo_checkpoint = fifo_checkpoint_bytes >> sh;
1490 		complete_checkpoint =
1491 			(complete_checkpoint_bytes + (1 << sh) - 1) >> sh;
1492 
1493 		diff = (fifo_checkpoint - complete_checkpoint) << sh;
1494 
1495 		if (chan->in_synchronous && diff >= 0) {
1496 			checkpoint = complete_checkpoint;
1497 			checkpoint_for_complete = true;
1498 		} else {
1499 			checkpoint = fifo_checkpoint;
1500 			checkpoint_for_complete = false;
1501 		}
1502 
1503 		leap = (checkpoint - chan->in_current_checkpoint) << sh;
1504 
1505 		/*
1506 		 * To prevent flooding of OPCODE_SET_CHECKPOINT commands as
1507 		 * data is consumed, it's issued only if it moves the
1508 		 * checkpoint by at least an 8th of the FIFO's size, or if
1509 		 * it's necessary to complete the number of bytes requested by
1510 		 * the read() call.
1511 		 *
1512 		 * chan->read_data_ok is checked to spare an unnecessary
1513 		 * submission after receiving EOF, however it's harmless if
1514 		 * such slips away.
1515 		 */
1516 
1517 		if (chan->read_data_ok &&
1518 		    (leap > 0 && (leap > (fifo->size >> 3) ||
1519 				  checkpoint_for_complete))) {
1520 			chan->in_current_checkpoint = checkpoint;
1521 			rc = xillyusb_send_opcode(xdev, chan_num,
1522 						  OPCODE_SET_CHECKPOINT,
1523 						  checkpoint);
1524 
1525 			if (rc)
1526 				break;
1527 		}
1528 
1529 		if (bytes_done == count ||
1530 		    (left_to_sleep <= 0 && bytes_done))
1531 			break;
1532 
1533 		/*
1534 		 * Reaching here means that the FIFO was empty when
1535 		 * fifo_read() returned, but not necessarily right now. Error
1536 		 * and EOF are checked and reported only now, so that no data
1537 		 * that managed its way to the FIFO is lost.
1538 		 */
1539 
1540 		if (!READ_ONCE(chan->read_data_ok)) { /* FPGA has sent EOF */
1541 			/* Has data slipped into the FIFO since fifo_read()? */
1542 			smp_rmb();
1543 			if (READ_ONCE(fifo->fill))
1544 				continue;
1545 
1546 			rc = 0;
1547 			break;
1548 		}
1549 
1550 		if (xdev->error) {
1551 			rc = xdev->error;
1552 			break;
1553 		}
1554 
1555 		if (filp->f_flags & O_NONBLOCK) {
1556 			rc = -EAGAIN;
1557 			break;
1558 		}
1559 
1560 		if (!sent_set_push) {
1561 			rc = xillyusb_send_opcode(xdev, chan_num,
1562 						  OPCODE_SET_PUSH,
1563 						  complete_checkpoint);
1564 
1565 			if (rc)
1566 				break;
1567 
1568 			sent_set_push = true;
1569 		}
1570 
1571 		if (left_to_sleep > 0) {
1572 			/*
1573 			 * Note that when xdev->error is set (e.g. when the
1574 			 * device is unplugged), read_data_ok turns zero and
1575 			 * fifo->waitq is awaken.
1576 			 * Therefore no special attention to xdev->error.
1577 			 */
1578 
1579 			rc = wait_event_interruptible_timeout
1580 				(fifo->waitq,
1581 				 fifo->fill || !chan->read_data_ok,
1582 				 left_to_sleep);
1583 		} else { /* bytes_done == 0 */
1584 			/* Tell FPGA to send anything it has */
1585 			rc = request_read_anything(chan, OPCODE_UPDATE_PUSH);
1586 
1587 			if (rc)
1588 				break;
1589 
1590 			rc = wait_event_interruptible
1591 				(fifo->waitq,
1592 				 fifo->fill || !chan->read_data_ok);
1593 		}
1594 
1595 		if (rc < 0) {
1596 			rc = -EINTR;
1597 			break;
1598 		}
1599 	}
1600 
1601 	if (((filp->f_flags & O_NONBLOCK) || chan->poll_used) &&
1602 	    !READ_ONCE(fifo->fill))
1603 		request_read_anything(chan, OPCODE_SET_PUSH);
1604 
1605 	mutex_unlock(&chan->in_mutex);
1606 
1607 	if (bytes_done)
1608 		return bytes_done;
1609 
1610 	return rc;
1611 }
1612 
1613 static int xillyusb_flush(struct file *filp, fl_owner_t id)
1614 {
1615 	struct xillyusb_channel *chan = filp->private_data;
1616 	int rc;
1617 
1618 	if (!(filp->f_mode & FMODE_WRITE))
1619 		return 0;
1620 
1621 	rc = mutex_lock_interruptible(&chan->out_mutex);
1622 
1623 	if (rc)
1624 		return rc;
1625 
1626 	/*
1627 	 * One second's timeout on flushing. Interrupts are ignored, because if
1628 	 * the user pressed CTRL-C, that interrupt will still be in flight by
1629 	 * the time we reach here, and the opportunity to flush is lost.
1630 	 */
1631 	rc = flush_downstream(chan, HZ, false);
1632 
1633 	mutex_unlock(&chan->out_mutex);
1634 
1635 	if (rc == -ETIMEDOUT) {
1636 		/* The things you do to use dev_warn() and not pr_warn() */
1637 		struct xillyusb_dev *xdev = chan->xdev;
1638 
1639 		mutex_lock(&chan->lock);
1640 		if (!xdev->error)
1641 			dev_warn(xdev->dev,
1642 				 "Timed out while flushing. Output data may be lost.\n");
1643 		mutex_unlock(&chan->lock);
1644 	}
1645 
1646 	return rc;
1647 }
1648 
1649 static ssize_t xillyusb_write(struct file *filp, const char __user *userbuf,
1650 			      size_t count, loff_t *f_pos)
1651 {
1652 	struct xillyusb_channel *chan = filp->private_data;
1653 	struct xillyusb_dev *xdev = chan->xdev;
1654 	struct xillyfifo *fifo = &chan->out_ep->fifo;
1655 	int rc;
1656 
1657 	rc = mutex_lock_interruptible(&chan->out_mutex);
1658 
1659 	if (rc)
1660 		return rc;
1661 
1662 	while (1) {
1663 		if (xdev->error) {
1664 			rc = xdev->error;
1665 			break;
1666 		}
1667 
1668 		if (count == 0)
1669 			break;
1670 
1671 		rc = fifo_write(fifo, (__force void *)userbuf, count,
1672 				xilly_copy_from_user);
1673 
1674 		if (rc != 0)
1675 			break;
1676 
1677 		if (filp->f_flags & O_NONBLOCK) {
1678 			rc = -EAGAIN;
1679 			break;
1680 		}
1681 
1682 		if (wait_event_interruptible
1683 		    (fifo->waitq,
1684 		     fifo->fill != fifo->size || xdev->error)) {
1685 			rc = -EINTR;
1686 			break;
1687 		}
1688 	}
1689 
1690 	if (rc < 0)
1691 		goto done;
1692 
1693 	chan->out_bytes += rc;
1694 
1695 	if (rc) {
1696 		try_queue_bulk_out(chan->out_ep);
1697 		chan->flushed = 0;
1698 	}
1699 
1700 	if (chan->out_synchronous) {
1701 		int flush_rc = flush_downstream(chan, 0, true);
1702 
1703 		if (flush_rc && !rc)
1704 			rc = flush_rc;
1705 	}
1706 
1707 done:
1708 	mutex_unlock(&chan->out_mutex);
1709 
1710 	return rc;
1711 }
1712 
1713 static int xillyusb_release(struct inode *inode, struct file *filp)
1714 {
1715 	struct xillyusb_channel *chan = filp->private_data;
1716 	struct xillyusb_dev *xdev = chan->xdev;
1717 	int rc_read = 0, rc_write = 0;
1718 
1719 	if (filp->f_mode & FMODE_READ) {
1720 		struct xillyfifo *in_fifo = chan->in_fifo;
1721 
1722 		rc_read = xillyusb_send_opcode(xdev, (chan->chan_idx << 1) | 1,
1723 					       OPCODE_CLOSE, 0);
1724 		/*
1725 		 * If rc_read is nonzero, xdev->error indicates a global
1726 		 * device error. The error is reported later, so that
1727 		 * resources are freed.
1728 		 *
1729 		 * Looping on wait_event_interruptible() kinda breaks the idea
1730 		 * of being interruptible, and this should have been
1731 		 * wait_event(). Only it's being waken with
1732 		 * wake_up_interruptible() for the sake of other uses. If
1733 		 * there's a global device error, chan->read_data_ok is
1734 		 * deasserted and the wait queue is awaken, so this is covered.
1735 		 */
1736 
1737 		while (wait_event_interruptible(in_fifo->waitq,
1738 						!chan->read_data_ok))
1739 			; /* Empty loop */
1740 
1741 		safely_assign_in_fifo(chan, NULL);
1742 		fifo_mem_release(in_fifo);
1743 		kfree(in_fifo);
1744 
1745 		mutex_lock(&chan->lock);
1746 		chan->open_for_read = 0;
1747 		mutex_unlock(&chan->lock);
1748 	}
1749 
1750 	if (filp->f_mode & FMODE_WRITE) {
1751 		struct xillyusb_endpoint *ep = chan->out_ep;
1752 		/*
1753 		 * chan->flushing isn't zeroed. If the pre-release flush timed
1754 		 * out, a cancel request will be sent before the next
1755 		 * OPCODE_SET_CHECKPOINT (i.e. when the file is opened again).
1756 		 * This is despite that the FPGA forgets about the checkpoint
1757 		 * request as the file closes. Still, in an exceptional race
1758 		 * condition, the FPGA could send an OPCODE_REACHED_CHECKPOINT
1759 		 * just before closing that would reach the host after the
1760 		 * file has re-opened.
1761 		 */
1762 
1763 		mutex_lock(&chan->lock);
1764 		chan->out_ep = NULL;
1765 		mutex_unlock(&chan->lock);
1766 
1767 		endpoint_quiesce(ep);
1768 		endpoint_dealloc(ep);
1769 
1770 		/* See comments on rc_read above */
1771 		rc_write = xillyusb_send_opcode(xdev, chan->chan_idx << 1,
1772 						OPCODE_CLOSE, 0);
1773 
1774 		mutex_lock(&chan->lock);
1775 		chan->open_for_write = 0;
1776 		mutex_unlock(&chan->lock);
1777 	}
1778 
1779 	kref_put(&xdev->kref, cleanup_dev);
1780 
1781 	return rc_read ? rc_read : rc_write;
1782 }
1783 
1784 /*
1785  * Xillybus' API allows device nodes to be seekable, giving the user
1786  * application access to a RAM array on the FPGA (or logic emulating it).
1787  */
1788 
1789 static loff_t xillyusb_llseek(struct file *filp, loff_t offset, int whence)
1790 {
1791 	struct xillyusb_channel *chan = filp->private_data;
1792 	struct xillyusb_dev *xdev = chan->xdev;
1793 	loff_t pos = filp->f_pos;
1794 	int rc = 0;
1795 	unsigned int log2_element_size = chan->readable ?
1796 		chan->in_log2_element_size : chan->out_log2_element_size;
1797 
1798 	/*
1799 	 * Take both mutexes not allowing interrupts, since it seems like
1800 	 * common applications don't expect an -EINTR here. Besides, multiple
1801 	 * access to a single file descriptor on seekable devices is a mess
1802 	 * anyhow.
1803 	 */
1804 
1805 	mutex_lock(&chan->out_mutex);
1806 	mutex_lock(&chan->in_mutex);
1807 
1808 	switch (whence) {
1809 	case SEEK_SET:
1810 		pos = offset;
1811 		break;
1812 	case SEEK_CUR:
1813 		pos += offset;
1814 		break;
1815 	case SEEK_END:
1816 		pos = offset; /* Going to the end => to the beginning */
1817 		break;
1818 	default:
1819 		rc = -EINVAL;
1820 		goto end;
1821 	}
1822 
1823 	/* In any case, we must finish on an element boundary */
1824 	if (pos & ((1 << log2_element_size) - 1)) {
1825 		rc = -EINVAL;
1826 		goto end;
1827 	}
1828 
1829 	rc = xillyusb_send_opcode(xdev, chan->chan_idx << 1,
1830 				  OPCODE_SET_ADDR,
1831 				  pos >> log2_element_size);
1832 
1833 	if (rc)
1834 		goto end;
1835 
1836 	if (chan->writable) {
1837 		chan->flushed = 0;
1838 		rc = flush_downstream(chan, HZ, false);
1839 	}
1840 
1841 end:
1842 	mutex_unlock(&chan->out_mutex);
1843 	mutex_unlock(&chan->in_mutex);
1844 
1845 	if (rc) /* Return error after releasing mutexes */
1846 		return rc;
1847 
1848 	filp->f_pos = pos;
1849 
1850 	return pos;
1851 }
1852 
1853 static __poll_t xillyusb_poll(struct file *filp, poll_table *wait)
1854 {
1855 	struct xillyusb_channel *chan = filp->private_data;
1856 	__poll_t mask = 0;
1857 
1858 	if (chan->in_fifo)
1859 		poll_wait(filp, &chan->in_fifo->waitq, wait);
1860 
1861 	if (chan->out_ep)
1862 		poll_wait(filp, &chan->out_ep->fifo.waitq, wait);
1863 
1864 	/*
1865 	 * If this is the first time poll() is called, and the file is
1866 	 * readable, set the relevant flag. Also tell the FPGA to send all it
1867 	 * has, to kickstart the mechanism that ensures there's always some
1868 	 * data in in_fifo unless the stream is dry end-to-end. Note that the
1869 	 * first poll() may not return a EPOLLIN, even if there's data on the
1870 	 * FPGA. Rather, the data will arrive soon, and trigger the relevant
1871 	 * wait queue.
1872 	 */
1873 
1874 	if (!chan->poll_used && chan->in_fifo) {
1875 		chan->poll_used = 1;
1876 		request_read_anything(chan, OPCODE_SET_PUSH);
1877 	}
1878 
1879 	/*
1880 	 * poll() won't play ball regarding read() channels which
1881 	 * are synchronous. Allowing that will create situations where data has
1882 	 * been delivered at the FPGA, and users expecting select() to wake up,
1883 	 * which it may not. So make it never work.
1884 	 */
1885 
1886 	if (chan->in_fifo && !chan->in_synchronous &&
1887 	    (READ_ONCE(chan->in_fifo->fill) || !chan->read_data_ok))
1888 		mask |= EPOLLIN | EPOLLRDNORM;
1889 
1890 	if (chan->out_ep &&
1891 	    (READ_ONCE(chan->out_ep->fifo.fill) != chan->out_ep->fifo.size))
1892 		mask |= EPOLLOUT | EPOLLWRNORM;
1893 
1894 	if (chan->xdev->error)
1895 		mask |= EPOLLERR;
1896 
1897 	return mask;
1898 }
1899 
1900 static const struct file_operations xillyusb_fops = {
1901 	.owner      = THIS_MODULE,
1902 	.read       = xillyusb_read,
1903 	.write      = xillyusb_write,
1904 	.open       = xillyusb_open,
1905 	.flush      = xillyusb_flush,
1906 	.release    = xillyusb_release,
1907 	.llseek     = xillyusb_llseek,
1908 	.poll       = xillyusb_poll,
1909 };
1910 
1911 static int xillyusb_setup_base_eps(struct xillyusb_dev *xdev)
1912 {
1913 	struct usb_device *udev = xdev->udev;
1914 
1915 	/* Verify that device has the two fundamental bulk in/out endpoints */
1916 	if (usb_pipe_type_check(udev, usb_sndbulkpipe(udev, MSG_EP_NUM)) ||
1917 	    usb_pipe_type_check(udev, usb_rcvbulkpipe(udev, IN_EP_NUM)))
1918 		return -ENODEV;
1919 
1920 	xdev->msg_ep = endpoint_alloc(xdev, MSG_EP_NUM | USB_DIR_OUT,
1921 				      bulk_out_work, 1, 2);
1922 	if (!xdev->msg_ep)
1923 		return -ENOMEM;
1924 
1925 	if (fifo_init(&xdev->msg_ep->fifo, 13)) /* 8 kiB */
1926 		goto dealloc;
1927 
1928 	xdev->msg_ep->fill_mask = -8; /* 8 bytes granularity */
1929 
1930 	xdev->in_ep = endpoint_alloc(xdev, IN_EP_NUM | USB_DIR_IN,
1931 				     bulk_in_work, BUF_SIZE_ORDER, BUFNUM);
1932 	if (!xdev->in_ep)
1933 		goto dealloc;
1934 
1935 	try_queue_bulk_in(xdev->in_ep);
1936 
1937 	return 0;
1938 
1939 dealloc:
1940 	endpoint_dealloc(xdev->msg_ep); /* Also frees FIFO mem if allocated */
1941 	xdev->msg_ep = NULL;
1942 	return -ENOMEM;
1943 }
1944 
1945 static int setup_channels(struct xillyusb_dev *xdev,
1946 			  __le16 *chandesc,
1947 			  int num_channels)
1948 {
1949 	struct usb_device *udev = xdev->udev;
1950 	struct xillyusb_channel *chan, *new_channels;
1951 	int i;
1952 
1953 	/* Don't let process_bulk_in() run while we change the channels */
1954 	guard(mutex)(&xdev->process_in_mutex);
1955 
1956 	chan = kzalloc_objs(*chan, num_channels);
1957 	if (!chan)
1958 		return -ENOMEM;
1959 
1960 	new_channels = chan;
1961 
1962 	for (i = 0; i < num_channels; i++, chan++) {
1963 		unsigned int in_desc = le16_to_cpu(*chandesc++);
1964 		unsigned int out_desc = le16_to_cpu(*chandesc++);
1965 
1966 		chan->xdev = xdev;
1967 		mutex_init(&chan->in_mutex);
1968 		mutex_init(&chan->out_mutex);
1969 		mutex_init(&chan->lock);
1970 		init_waitqueue_head(&chan->flushq);
1971 
1972 		chan->chan_idx = i;
1973 
1974 		if (in_desc & 0x80) { /* Entry is valid */
1975 			chan->readable = 1;
1976 			chan->in_synchronous = !!(in_desc & 0x40);
1977 			chan->in_seekable = !!(in_desc & 0x20);
1978 			chan->in_log2_element_size = in_desc & 0x0f;
1979 			chan->in_log2_fifo_size = ((in_desc >> 8) & 0x1f) + 16;
1980 		}
1981 
1982 		/*
1983 		 * A downstream channel should never exist above index 13,
1984 		 * as it would request a nonexistent BULK endpoint > 15.
1985 		 * In the peculiar case that it does, it's ignored silently.
1986 		 */
1987 
1988 		if ((out_desc & 0x80) && i < 14) { /* Entry is valid */
1989 			if (usb_pipe_type_check(udev,
1990 						usb_sndbulkpipe(udev, i + 2))) {
1991 				dev_err(xdev->dev,
1992 					"Missing BULK OUT endpoint %d\n",
1993 					i + 2);
1994 				kfree(new_channels);
1995 				return -ENODEV;
1996 			}
1997 
1998 			chan->writable = 1;
1999 			chan->out_synchronous = !!(out_desc & 0x40);
2000 			chan->out_seekable = !!(out_desc & 0x20);
2001 			chan->out_log2_element_size = out_desc & 0x0f;
2002 			chan->out_log2_fifo_size =
2003 				((out_desc >> 8) & 0x1f) + 16;
2004 		}
2005 	}
2006 
2007 	xdev->channels = new_channels;
2008 	return 0;
2009 }
2010 
2011 static int xillyusb_discovery(struct usb_interface *interface)
2012 {
2013 	int rc;
2014 	struct xillyusb_dev *xdev = usb_get_intfdata(interface);
2015 	__le16 bogus_chandesc[2];
2016 	struct xillyfifo idt_fifo;
2017 	struct xillyusb_channel *chan;
2018 	unsigned int idt_len, names_offset;
2019 	unsigned char *idt;
2020 	int num_channels;
2021 
2022 	rc = xillyusb_send_opcode(xdev, ~0, OPCODE_QUIESCE, 0);
2023 
2024 	if (rc) {
2025 		dev_err(&interface->dev, "Failed to send quiesce request. Aborting.\n");
2026 		return rc;
2027 	}
2028 
2029 	/* Phase I: Set up one fake upstream channel and obtain IDT */
2030 
2031 	/* Set up a fake IDT with one async IN stream */
2032 	bogus_chandesc[0] = cpu_to_le16(0x80);
2033 	bogus_chandesc[1] = cpu_to_le16(0);
2034 
2035 	rc = setup_channels(xdev, bogus_chandesc, 1);
2036 
2037 	if (rc)
2038 		return rc;
2039 
2040 	rc = fifo_init(&idt_fifo, LOG2_IDT_FIFO_SIZE);
2041 
2042 	if (rc)
2043 		return rc;
2044 
2045 	chan = xdev->channels;
2046 
2047 	chan->in_fifo = &idt_fifo;
2048 	chan->read_data_ok = 1;
2049 
2050 	xdev->num_channels = 1;
2051 
2052 	rc = xillyusb_send_opcode(xdev, ~0, OPCODE_REQ_IDT, 0);
2053 
2054 	if (rc) {
2055 		dev_err(&interface->dev, "Failed to send IDT request. Aborting.\n");
2056 		goto unfifo;
2057 	}
2058 
2059 	rc = wait_event_interruptible_timeout(idt_fifo.waitq,
2060 					      !chan->read_data_ok,
2061 					      XILLY_RESPONSE_TIMEOUT);
2062 
2063 	if (xdev->error) {
2064 		rc = xdev->error;
2065 		goto unfifo;
2066 	}
2067 
2068 	if (rc < 0) {
2069 		rc = -EINTR; /* Interrupt on probe method? Interesting. */
2070 		goto unfifo;
2071 	}
2072 
2073 	if (chan->read_data_ok) {
2074 		rc = -ETIMEDOUT;
2075 		dev_err(&interface->dev, "No response from FPGA. Aborting.\n");
2076 		goto unfifo;
2077 	}
2078 
2079 	idt_len = READ_ONCE(idt_fifo.fill);
2080 
2081 	if (idt_len < 4 || idt_len > XILLYBUS_MAX_IDT) {
2082 		rc = -ENODEV;
2083 		dev_err(&interface->dev, "Invalid IDT length. Aborting.\n");
2084 		goto unfifo;
2085 	}
2086 
2087 	idt = kmalloc(idt_len, GFP_KERNEL);
2088 
2089 	if (!idt) {
2090 		rc = -ENOMEM;
2091 		goto unfifo;
2092 	}
2093 
2094 	fifo_read(&idt_fifo, idt, idt_len, xilly_memcpy);
2095 
2096 	if (crc32_le(~0, idt, idt_len) != 0) {
2097 		dev_err(&interface->dev, "IDT failed CRC check. Aborting.\n");
2098 		rc = -ENODEV;
2099 		goto unidt;
2100 	}
2101 
2102 	if (*idt > 0x90) {
2103 		dev_err(&interface->dev, "No support for IDT version 0x%02x. Maybe the xillyusb driver needs an upgrade. Aborting.\n",
2104 			(int)*idt);
2105 		rc = -ENODEV;
2106 		goto unidt;
2107 	}
2108 
2109 	/* Phase II: Set up the streams as defined in IDT */
2110 
2111 	num_channels = le16_to_cpu(*((__le16 *)(idt + 1)));
2112 	names_offset = 3 + num_channels * 4;
2113 	idt_len -= 4; /* Exclude CRC */
2114 
2115 	if (idt_len < names_offset) {
2116 		dev_err(&interface->dev, "IDT too short. This is exceptionally weird, because its CRC is OK\n");
2117 		rc = -ENODEV;
2118 		goto unidt;
2119 	}
2120 
2121 	if (num_channels == 0 || num_channels > XILLYBUS_MAX_NODES) {
2122 		dev_err(&interface->dev, "Unreasonable number of channels. Aborting.\n");
2123 		rc = -ENODEV;
2124 		goto unidt;
2125 	}
2126 
2127 	rc = setup_channels(xdev, (void *)idt + 3, num_channels);
2128 
2129 	if (rc)
2130 		goto unidt;
2131 
2132 	/*
2133 	 * Except for wildly misbehaving hardware, or if it was disconnected
2134 	 * just after responding with the IDT, there is no reason for any
2135 	 * work item to be running now. To be sure that xdev->channels
2136 	 * is updated on anything that might run in parallel, flush the
2137 	 * device's workqueue and the wakeup work item. This rarely
2138 	 * does anything.
2139 	 */
2140 	flush_workqueue(xdev->workq);
2141 	flush_work(&xdev->wakeup_workitem);
2142 
2143 	xdev->num_channels = num_channels;
2144 
2145 	fifo_mem_release(&idt_fifo);
2146 	kfree(chan);
2147 
2148 	rc = xillybus_init_chrdev(&interface->dev, &xillyusb_fops,
2149 				  THIS_MODULE, xdev,
2150 				  idt + names_offset,
2151 				  idt_len - names_offset,
2152 				  num_channels,
2153 				  xillyname, true);
2154 
2155 	kfree(idt);
2156 
2157 	return rc;
2158 
2159 unidt:
2160 	kfree(idt);
2161 
2162 unfifo:
2163 	safely_assign_in_fifo(chan, NULL);
2164 	fifo_mem_release(&idt_fifo);
2165 
2166 	return rc;
2167 }
2168 
2169 static int xillyusb_probe(struct usb_interface *interface,
2170 			  const struct usb_device_id *id)
2171 {
2172 	struct xillyusb_dev *xdev;
2173 	int rc;
2174 
2175 	xdev = kzalloc_obj(*xdev);
2176 	if (!xdev)
2177 		return -ENOMEM;
2178 
2179 	kref_init(&xdev->kref);
2180 	mutex_init(&xdev->process_in_mutex);
2181 	mutex_init(&xdev->msg_mutex);
2182 
2183 	xdev->udev = usb_get_dev(interface_to_usbdev(interface));
2184 	xdev->dev = &interface->dev;
2185 	xdev->error = 0;
2186 	spin_lock_init(&xdev->error_lock);
2187 	xdev->in_counter = 0;
2188 	xdev->in_bytes_left = 0;
2189 	xdev->workq = alloc_workqueue(xillyname, WQ_HIGHPRI | WQ_UNBOUND, 0);
2190 
2191 	if (!xdev->workq) {
2192 		dev_err(&interface->dev, "Failed to allocate work queue\n");
2193 		rc = -ENOMEM;
2194 		goto fail;
2195 	}
2196 
2197 	INIT_WORK(&xdev->wakeup_workitem, wakeup_all);
2198 
2199 	usb_set_intfdata(interface, xdev);
2200 
2201 	rc = xillyusb_setup_base_eps(xdev);
2202 	if (rc)
2203 		goto fail;
2204 
2205 	rc = xillyusb_discovery(interface);
2206 	if (rc)
2207 		goto latefail;
2208 
2209 	return 0;
2210 
2211 latefail:
2212 	endpoint_quiesce(xdev->in_ep);
2213 	endpoint_quiesce(xdev->msg_ep);
2214 
2215 fail:
2216 	usb_set_intfdata(interface, NULL);
2217 	kref_put(&xdev->kref, cleanup_dev);
2218 	return rc;
2219 }
2220 
2221 static void xillyusb_disconnect(struct usb_interface *interface)
2222 {
2223 	struct xillyusb_dev *xdev = usb_get_intfdata(interface);
2224 	struct xillyusb_endpoint *msg_ep = xdev->msg_ep;
2225 	struct xillyfifo *fifo = &msg_ep->fifo;
2226 	int rc;
2227 	int i;
2228 
2229 	xillybus_cleanup_chrdev(xdev, &interface->dev);
2230 
2231 	/*
2232 	 * Try to send OPCODE_QUIESCE, which will fail silently if the device
2233 	 * was disconnected, but makes sense on module unload.
2234 	 */
2235 
2236 	msg_ep->wake_on_drain = true;
2237 	xillyusb_send_opcode(xdev, ~0, OPCODE_QUIESCE, 0);
2238 
2239 	/*
2240 	 * If the device has been disconnected, sending the opcode causes
2241 	 * a global device error with xdev->error, if such error didn't
2242 	 * occur earlier. Hence timing out means that the USB link is fine,
2243 	 * but somehow the message wasn't sent. Should never happen.
2244 	 */
2245 
2246 	rc = wait_event_interruptible_timeout(fifo->waitq,
2247 					      msg_ep->drained || xdev->error,
2248 					      XILLY_RESPONSE_TIMEOUT);
2249 
2250 	if (!rc)
2251 		dev_err(&interface->dev,
2252 			"Weird timeout condition on sending quiesce request.\n");
2253 
2254 	report_io_error(xdev, -ENODEV); /* Discourage further activity */
2255 
2256 	/*
2257 	 * This device driver is declared with soft_unbind set, or else
2258 	 * sending OPCODE_QUIESCE above would always fail. The price is
2259 	 * that the USB framework didn't kill outstanding URBs, so it has
2260 	 * to be done explicitly before returning from this call.
2261 	 */
2262 
2263 	for (i = 0; i < xdev->num_channels; i++) {
2264 		struct xillyusb_channel *chan = &xdev->channels[i];
2265 
2266 		/*
2267 		 * Lock taken to prevent chan->out_ep from changing. It also
2268 		 * ensures xillyusb_open() and xillyusb_flush() don't access
2269 		 * xdev->dev after being nullified below.
2270 		 */
2271 		mutex_lock(&chan->lock);
2272 		if (chan->out_ep)
2273 			endpoint_quiesce(chan->out_ep);
2274 		mutex_unlock(&chan->lock);
2275 	}
2276 
2277 	endpoint_quiesce(xdev->in_ep);
2278 	endpoint_quiesce(xdev->msg_ep);
2279 
2280 	usb_set_intfdata(interface, NULL);
2281 
2282 	xdev->dev = NULL;
2283 
2284 	mutex_lock(&kref_mutex);
2285 	kref_put(&xdev->kref, cleanup_dev);
2286 	mutex_unlock(&kref_mutex);
2287 }
2288 
2289 static struct usb_driver xillyusb_driver = {
2290 	.name = xillyname,
2291 	.id_table = xillyusb_table,
2292 	.probe = xillyusb_probe,
2293 	.disconnect = xillyusb_disconnect,
2294 	.soft_unbind = 1,
2295 };
2296 
2297 static int __init xillyusb_init(void)
2298 {
2299 	int rc = 0;
2300 
2301 	wakeup_wq = alloc_workqueue(xillyname, WQ_UNBOUND, 0);
2302 	if (!wakeup_wq)
2303 		return -ENOMEM;
2304 
2305 	if (LOG2_INITIAL_FIFO_BUF_SIZE > PAGE_SHIFT)
2306 		fifo_buf_order = LOG2_INITIAL_FIFO_BUF_SIZE - PAGE_SHIFT;
2307 	else
2308 		fifo_buf_order = 0;
2309 
2310 	rc = usb_register(&xillyusb_driver);
2311 
2312 	if (rc)
2313 		destroy_workqueue(wakeup_wq);
2314 
2315 	return rc;
2316 }
2317 
2318 static void __exit xillyusb_exit(void)
2319 {
2320 	usb_deregister(&xillyusb_driver);
2321 
2322 	destroy_workqueue(wakeup_wq);
2323 }
2324 
2325 module_init(xillyusb_init);
2326 module_exit(xillyusb_exit);
2327