1// SPDX-License-Identifier: GPL-2.0
2/*
3 *  Native support for the I/O-Warrior USB devices
4 *
5 *  Copyright (c) 2003-2005, 2020  Code Mercenaries GmbH
6 *  written by Christian Lucht <lucht@codemercs.com> and
7 *  Christoph Jung <jung@codemercs.com>
8 *
9 *  based on
10
11 *  usb-skeleton.c by Greg Kroah-Hartman  <greg@kroah.com>
12 *  brlvger.c by Stephane Dalton  <sdalton@videotron.ca>
13 *           and Stephane Doyon   <s.doyon@videotron.ca>
14 *
15 *  Released under the GPLv2.
16 */
17
18#include <linux/module.h>
19#include <linux/usb.h>
20#include <linux/slab.h>
21#include <linux/sched.h>
22#include <linux/mutex.h>
23#include <linux/poll.h>
24#include <linux/usb/iowarrior.h>
25
26#define DRIVER_AUTHOR "Christian Lucht <lucht@codemercs.com>"
27#define DRIVER_DESC "USB IO-Warrior driver"
28
29#define USB_VENDOR_ID_CODEMERCS		1984
30/* low speed iowarrior */
31#define USB_DEVICE_ID_CODEMERCS_IOW40	0x1500
32#define USB_DEVICE_ID_CODEMERCS_IOW24	0x1501
33#define USB_DEVICE_ID_CODEMERCS_IOWPV1	0x1511
34#define USB_DEVICE_ID_CODEMERCS_IOWPV2	0x1512
35/* full speed iowarrior */
36#define USB_DEVICE_ID_CODEMERCS_IOW56	0x1503
37/* fuller speed iowarrior */
38#define USB_DEVICE_ID_CODEMERCS_IOW28	0x1504
39#define USB_DEVICE_ID_CODEMERCS_IOW28L	0x1505
40#define USB_DEVICE_ID_CODEMERCS_IOW100	0x1506
41
42/* OEMed devices */
43#define USB_DEVICE_ID_CODEMERCS_IOW24SAG	0x158a
44#define USB_DEVICE_ID_CODEMERCS_IOW56AM		0x158b
45
46/* Get a minor range for your devices from the usb maintainer */
47#ifdef CONFIG_USB_DYNAMIC_MINORS
48#define IOWARRIOR_MINOR_BASE	0
49#else
50#define IOWARRIOR_MINOR_BASE	208	// SKELETON_MINOR_BASE 192 + 16, not official yet
51#endif
52
53/* interrupt input queue size */
54#define MAX_INTERRUPT_BUFFER 16
55/*
56   maximum number of urbs that are submitted for writes at the same time,
57   this applies to the IOWarrior56 only!
58   IOWarrior24 and IOWarrior40 use synchronous usb_control_msg calls.
59*/
60#define MAX_WRITES_IN_FLIGHT 4
61
62MODULE_AUTHOR(DRIVER_AUTHOR);
63MODULE_DESCRIPTION(DRIVER_DESC);
64MODULE_LICENSE("GPL");
65
66static struct usb_driver iowarrior_driver;
67
68/*--------------*/
69/*     data     */
70/*--------------*/
71
72/* Structure to hold all of our device specific stuff */
73struct iowarrior {
74	struct mutex mutex;			/* locks this structure */
75	struct usb_device *udev;		/* save off the usb device pointer */
76	struct usb_interface *interface;	/* the interface for this device */
77	unsigned char minor;			/* the starting minor number for this device */
78	struct usb_endpoint_descriptor *int_out_endpoint;	/* endpoint for reading (needed for IOW56 only) */
79	struct usb_endpoint_descriptor *int_in_endpoint;	/* endpoint for reading */
80	struct urb *int_in_urb;		/* the urb for reading data */
81	unsigned char *int_in_buffer;	/* buffer for data to be read */
82	unsigned char serial_number;	/* to detect lost packages */
83	unsigned char *read_queue;	/* size is MAX_INTERRUPT_BUFFER * packet size */
84	wait_queue_head_t read_wait;
85	wait_queue_head_t write_wait;	/* wait-queue for writing to the device */
86	atomic_t write_busy;		/* number of write-urbs submitted */
87	atomic_t read_idx;
88	atomic_t intr_idx;
89	atomic_t overflow_flag;		/* signals an index 'rollover' */
90	int present;			/* this is 1 as long as the device is connected */
91	int opened;			/* this is 1 if the device is currently open */
92	char chip_serial[9];		/* the serial number string of the chip connected */
93	int report_size;		/* number of bytes in a report */
94	u16 product_id;
95	struct usb_anchor submitted;
96};
97
98/*--------------*/
99/*    globals   */
100/*--------------*/
101
102#define USB_REQ_GET_REPORT  0x01
103//#if 0
104static int usb_get_report(struct usb_device *dev,
105			  struct usb_host_interface *inter, unsigned char type,
106			  unsigned char id, void *buf, int size)
107{
108	return usb_control_msg(dev, usb_rcvctrlpipe(dev, 0),
109			       USB_REQ_GET_REPORT,
110			       USB_DIR_IN | USB_TYPE_CLASS |
111			       USB_RECIP_INTERFACE, (type << 8) + id,
112			       inter->desc.bInterfaceNumber, buf, size,
113			       USB_CTRL_GET_TIMEOUT);
114}
115//#endif
116
117#define USB_REQ_SET_REPORT 0x09
118
119static int usb_set_report(struct usb_interface *intf, unsigned char type,
120			  unsigned char id, void *buf, int size)
121{
122	return usb_control_msg(interface_to_usbdev(intf),
123			       usb_sndctrlpipe(interface_to_usbdev(intf), 0),
124			       USB_REQ_SET_REPORT,
125			       USB_TYPE_CLASS | USB_RECIP_INTERFACE,
126			       (type << 8) + id,
127			       intf->cur_altsetting->desc.bInterfaceNumber, buf,
128			       size, 1000);
129}
130
131/*---------------------*/
132/* driver registration */
133/*---------------------*/
134/* table of devices that work with this driver */
135static const struct usb_device_id iowarrior_ids[] = {
136	{USB_DEVICE(USB_VENDOR_ID_CODEMERCS, USB_DEVICE_ID_CODEMERCS_IOW40)},
137	{USB_DEVICE(USB_VENDOR_ID_CODEMERCS, USB_DEVICE_ID_CODEMERCS_IOW24)},
138	{USB_DEVICE(USB_VENDOR_ID_CODEMERCS, USB_DEVICE_ID_CODEMERCS_IOWPV1)},
139	{USB_DEVICE(USB_VENDOR_ID_CODEMERCS, USB_DEVICE_ID_CODEMERCS_IOWPV2)},
140	{USB_DEVICE(USB_VENDOR_ID_CODEMERCS, USB_DEVICE_ID_CODEMERCS_IOW56)},
141	{USB_DEVICE(USB_VENDOR_ID_CODEMERCS, USB_DEVICE_ID_CODEMERCS_IOW24SAG)},
142	{USB_DEVICE(USB_VENDOR_ID_CODEMERCS, USB_DEVICE_ID_CODEMERCS_IOW56AM)},
143	{USB_DEVICE(USB_VENDOR_ID_CODEMERCS, USB_DEVICE_ID_CODEMERCS_IOW28)},
144	{USB_DEVICE(USB_VENDOR_ID_CODEMERCS, USB_DEVICE_ID_CODEMERCS_IOW28L)},
145	{USB_DEVICE(USB_VENDOR_ID_CODEMERCS, USB_DEVICE_ID_CODEMERCS_IOW100)},
146	{}			/* Terminating entry */
147};
148MODULE_DEVICE_TABLE(usb, iowarrior_ids);
149
150/*
151 * USB callback handler for reading data
152 */
153static void iowarrior_callback(struct urb *urb)
154{
155	struct iowarrior *dev = urb->context;
156	int intr_idx;
157	int read_idx;
158	int aux_idx;
159	int offset;
160	int status = urb->status;
161	int retval;
162
163	switch (status) {
164	case 0:
165		/* success */
166		break;
167	case -ECONNRESET:
168	case -ENOENT:
169	case -ESHUTDOWN:
170		return;
171	default:
172		goto exit;
173	}
174
175	intr_idx = atomic_read(&dev->intr_idx);
176	/* aux_idx become previous intr_idx */
177	aux_idx = (intr_idx == 0) ? (MAX_INTERRUPT_BUFFER - 1) : (intr_idx - 1);
178	read_idx = atomic_read(&dev->read_idx);
179
180	/* queue is not empty and it's interface 0 */
181	if ((intr_idx != read_idx)
182	    && (dev->interface->cur_altsetting->desc.bInterfaceNumber == 0)) {
183		/* + 1 for serial number */
184		offset = aux_idx * (dev->report_size + 1);
185		if (!memcmp
186		    (dev->read_queue + offset, urb->transfer_buffer,
187		     dev->report_size)) {
188			/* equal values on interface 0 will be ignored */
189			goto exit;
190		}
191	}
192
193	/* aux_idx become next intr_idx */
194	aux_idx = (intr_idx == (MAX_INTERRUPT_BUFFER - 1)) ? 0 : (intr_idx + 1);
195	if (read_idx == aux_idx) {
196		/* queue full, dropping oldest input */
197		read_idx = (++read_idx == MAX_INTERRUPT_BUFFER) ? 0 : read_idx;
198		atomic_set(&dev->read_idx, read_idx);
199		atomic_set(&dev->overflow_flag, 1);
200	}
201
202	/* +1 for serial number */
203	offset = intr_idx * (dev->report_size + 1);
204	memcpy(dev->read_queue + offset, urb->transfer_buffer,
205	       dev->report_size);
206	*(dev->read_queue + offset + (dev->report_size)) = dev->serial_number++;
207
208	atomic_set(&dev->intr_idx, aux_idx);
209	/* tell the blocking read about the new data */
210	wake_up_interruptible(&dev->read_wait);
211
212exit:
213	retval = usb_submit_urb(urb, GFP_ATOMIC);
214	if (retval)
215		dev_err(&dev->interface->dev, "%s - usb_submit_urb failed with result %d\n",
216			__func__, retval);
217
218}
219
220/*
221 * USB Callback handler for write-ops
222 */
223static void iowarrior_write_callback(struct urb *urb)
224{
225	struct iowarrior *dev;
226	int status = urb->status;
227
228	dev = urb->context;
229	/* sync/async unlink faults aren't errors */
230	if (status &&
231	    !(status == -ENOENT ||
232	      status == -ECONNRESET || status == -ESHUTDOWN)) {
233		dev_dbg(&dev->interface->dev,
234			"nonzero write bulk status received: %d\n", status);
235	}
236	/* free up our allocated buffer */
237	usb_free_coherent(urb->dev, urb->transfer_buffer_length,
238			  urb->transfer_buffer, urb->transfer_dma);
239	/* tell a waiting writer the interrupt-out-pipe is available again */
240	atomic_dec(&dev->write_busy);
241	wake_up_interruptible(&dev->write_wait);
242}
243
244/*
245 *	iowarrior_delete
246 */
247static inline void iowarrior_delete(struct iowarrior *dev)
248{
249	dev_dbg(&dev->interface->dev, "minor %d\n", dev->minor);
250	kfree(dev->int_in_buffer);
251	usb_free_urb(dev->int_in_urb);
252	kfree(dev->read_queue);
253	usb_put_intf(dev->interface);
254	kfree(dev);
255}
256
257/*---------------------*/
258/* fops implementation */
259/*---------------------*/
260
261static int read_index(struct iowarrior *dev)
262{
263	int intr_idx, read_idx;
264
265	read_idx = atomic_read(&dev->read_idx);
266	intr_idx = atomic_read(&dev->intr_idx);
267
268	return (read_idx == intr_idx ? -1 : read_idx);
269}
270
271/*
272 *  iowarrior_read
273 */
274static ssize_t iowarrior_read(struct file *file, char __user *buffer,
275			      size_t count, loff_t *ppos)
276{
277	struct iowarrior *dev;
278	int read_idx;
279	int offset;
280
281	dev = file->private_data;
282
283	/* verify that the device wasn't unplugged */
284	if (!dev || !dev->present)
285		return -ENODEV;
286
287	dev_dbg(&dev->interface->dev, "minor %d, count = %zd\n",
288		dev->minor, count);
289
290	/* read count must be packet size (+ time stamp) */
291	if ((count != dev->report_size)
292	    && (count != (dev->report_size + 1)))
293		return -EINVAL;
294
295	/* repeat until no buffer overrun in callback handler occur */
296	do {
297		atomic_set(&dev->overflow_flag, 0);
298		if ((read_idx = read_index(dev)) == -1) {
299			/* queue empty */
300			if (file->f_flags & O_NONBLOCK)
301				return -EAGAIN;
302			else {
303				//next line will return when there is either new data, or the device is unplugged
304				int r = wait_event_interruptible(dev->read_wait,
305								 (!dev->present
306								  || (read_idx =
307								      read_index
308								      (dev)) !=
309								  -1));
310				if (r) {
311					//we were interrupted by a signal
312					return -ERESTART;
313				}
314				if (!dev->present) {
315					//The device was unplugged
316					return -ENODEV;
317				}
318				if (read_idx == -1) {
319					// Can this happen ???
320					return 0;
321				}
322			}
323		}
324
325		offset = read_idx * (dev->report_size + 1);
326		if (copy_to_user(buffer, dev->read_queue + offset, count)) {
327			return -EFAULT;
328		}
329	} while (atomic_read(&dev->overflow_flag));
330
331	read_idx = ++read_idx == MAX_INTERRUPT_BUFFER ? 0 : read_idx;
332	atomic_set(&dev->read_idx, read_idx);
333	return count;
334}
335
336/*
337 * iowarrior_write
338 */
339static ssize_t iowarrior_write(struct file *file,
340			       const char __user *user_buffer,
341			       size_t count, loff_t *ppos)
342{
343	struct iowarrior *dev;
344	int retval = 0;
345	char *buf = NULL;	/* for IOW24 and IOW56 we need a buffer */
346	struct urb *int_out_urb = NULL;
347
348	dev = file->private_data;
349
350	mutex_lock(&dev->mutex);
351	/* verify that the device wasn't unplugged */
352	if (!dev->present) {
353		retval = -ENODEV;
354		goto exit;
355	}
356	dev_dbg(&dev->interface->dev, "minor %d, count = %zd\n",
357		dev->minor, count);
358	/* if count is 0 we're already done */
359	if (count == 0) {
360		retval = 0;
361		goto exit;
362	}
363	/* We only accept full reports */
364	if (count != dev->report_size) {
365		retval = -EINVAL;
366		goto exit;
367	}
368	switch (dev->product_id) {
369	case USB_DEVICE_ID_CODEMERCS_IOW24:
370	case USB_DEVICE_ID_CODEMERCS_IOW24SAG:
371	case USB_DEVICE_ID_CODEMERCS_IOWPV1:
372	case USB_DEVICE_ID_CODEMERCS_IOWPV2:
373	case USB_DEVICE_ID_CODEMERCS_IOW40:
374		/* IOW24 and IOW40 use a synchronous call */
375		buf = memdup_user(user_buffer, count);
376		if (IS_ERR(buf)) {
377			retval = PTR_ERR(buf);
378			goto exit;
379		}
380		retval = usb_set_report(dev->interface, 2, 0, buf, count);
381		kfree(buf);
382		goto exit;
383		break;
384	case USB_DEVICE_ID_CODEMERCS_IOW56:
385	case USB_DEVICE_ID_CODEMERCS_IOW56AM:
386	case USB_DEVICE_ID_CODEMERCS_IOW28:
387	case USB_DEVICE_ID_CODEMERCS_IOW28L:
388	case USB_DEVICE_ID_CODEMERCS_IOW100:
389		/* The IOW56 uses asynchronous IO and more urbs */
390		if (atomic_read(&dev->write_busy) == MAX_WRITES_IN_FLIGHT) {
391			/* Wait until we are below the limit for submitted urbs */
392			if (file->f_flags & O_NONBLOCK) {
393				retval = -EAGAIN;
394				goto exit;
395			} else {
396				retval = wait_event_interruptible(dev->write_wait,
397								  (!dev->present || (atomic_read (&dev-> write_busy) < MAX_WRITES_IN_FLIGHT)));
398				if (retval) {
399					/* we were interrupted by a signal */
400					retval = -ERESTART;
401					goto exit;
402				}
403				if (!dev->present) {
404					/* The device was unplugged */
405					retval = -ENODEV;
406					goto exit;
407				}
408				if (!dev->opened) {
409					/* We were closed while waiting for an URB */
410					retval = -ENODEV;
411					goto exit;
412				}
413			}
414		}
415		atomic_inc(&dev->write_busy);
416		int_out_urb = usb_alloc_urb(0, GFP_KERNEL);
417		if (!int_out_urb) {
418			retval = -ENOMEM;
419			goto error_no_urb;
420		}
421		buf = usb_alloc_coherent(dev->udev, dev->report_size,
422					 GFP_KERNEL, &int_out_urb->transfer_dma);
423		if (!buf) {
424			retval = -ENOMEM;
425			dev_dbg(&dev->interface->dev,
426				"Unable to allocate buffer\n");
427			goto error_no_buffer;
428		}
429		usb_fill_int_urb(int_out_urb, dev->udev,
430				 usb_sndintpipe(dev->udev,
431						dev->int_out_endpoint->bEndpointAddress),
432				 buf, dev->report_size,
433				 iowarrior_write_callback, dev,
434				 dev->int_out_endpoint->bInterval);
435		int_out_urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
436		if (copy_from_user(buf, user_buffer, count)) {
437			retval = -EFAULT;
438			goto error;
439		}
440		usb_anchor_urb(int_out_urb, &dev->submitted);
441		retval = usb_submit_urb(int_out_urb, GFP_KERNEL);
442		if (retval) {
443			dev_dbg(&dev->interface->dev,
444				"submit error %d for urb nr.%d\n",
445				retval, atomic_read(&dev->write_busy));
446			usb_unanchor_urb(int_out_urb);
447			goto error;
448		}
449		/* submit was ok */
450		retval = count;
451		usb_free_urb(int_out_urb);
452		goto exit;
453		break;
454	default:
455		/* what do we have here ? An unsupported Product-ID ? */
456		dev_err(&dev->interface->dev, "%s - not supported for product=0x%x\n",
457			__func__, dev->product_id);
458		retval = -EFAULT;
459		goto exit;
460		break;
461	}
462error:
463	usb_free_coherent(dev->udev, dev->report_size, buf,
464			  int_out_urb->transfer_dma);
465error_no_buffer:
466	usb_free_urb(int_out_urb);
467error_no_urb:
468	atomic_dec(&dev->write_busy);
469	wake_up_interruptible(&dev->write_wait);
470exit:
471	mutex_unlock(&dev->mutex);
472	return retval;
473}
474
475/*
476 *	iowarrior_ioctl
477 */
478static long iowarrior_ioctl(struct file *file, unsigned int cmd,
479							unsigned long arg)
480{
481	struct iowarrior *dev = NULL;
482	__u8 *buffer;
483	__u8 __user *user_buffer;
484	int retval;
485	int io_res;		/* checks for bytes read/written and copy_to/from_user results */
486
487	dev = file->private_data;
488	if (!dev)
489		return -ENODEV;
490
491	buffer = kzalloc(dev->report_size, GFP_KERNEL);
492	if (!buffer)
493		return -ENOMEM;
494
495	mutex_lock(&dev->mutex);
496
497	/* verify that the device wasn't unplugged */
498	if (!dev->present) {
499		retval = -ENODEV;
500		goto error_out;
501	}
502
503	dev_dbg(&dev->interface->dev, "minor %d, cmd 0x%.4x, arg %ld\n",
504		dev->minor, cmd, arg);
505
506	retval = 0;
507	io_res = 0;
508	switch (cmd) {
509	case IOW_WRITE:
510		if (dev->product_id == USB_DEVICE_ID_CODEMERCS_IOW24 ||
511		    dev->product_id == USB_DEVICE_ID_CODEMERCS_IOW24SAG ||
512		    dev->product_id == USB_DEVICE_ID_CODEMERCS_IOWPV1 ||
513		    dev->product_id == USB_DEVICE_ID_CODEMERCS_IOWPV2 ||
514		    dev->product_id == USB_DEVICE_ID_CODEMERCS_IOW40) {
515			user_buffer = (__u8 __user *)arg;
516			io_res = copy_from_user(buffer, user_buffer,
517						dev->report_size);
518			if (io_res) {
519				retval = -EFAULT;
520			} else {
521				io_res = usb_set_report(dev->interface, 2, 0,
522							buffer,
523							dev->report_size);
524				if (io_res < 0)
525					retval = io_res;
526			}
527		} else {
528			retval = -EINVAL;
529			dev_err(&dev->interface->dev,
530				"ioctl 'IOW_WRITE' is not supported for product=0x%x.\n",
531				dev->product_id);
532		}
533		break;
534	case IOW_READ:
535		user_buffer = (__u8 __user *)arg;
536		io_res = usb_get_report(dev->udev,
537					dev->interface->cur_altsetting, 1, 0,
538					buffer, dev->report_size);
539		if (io_res < 0)
540			retval = io_res;
541		else {
542			io_res = copy_to_user(user_buffer, buffer, dev->report_size);
543			if (io_res)
544				retval = -EFAULT;
545		}
546		break;
547	case IOW_GETINFO:
548		{
549			/* Report available information for the device */
550			struct iowarrior_info info;
551			/* needed for power consumption */
552			struct usb_config_descriptor *cfg_descriptor = &dev->udev->actconfig->desc;
553
554			memset(&info, 0, sizeof(info));
555			/* directly from the descriptor */
556			info.vendor = le16_to_cpu(dev->udev->descriptor.idVendor);
557			info.product = dev->product_id;
558			info.revision = le16_to_cpu(dev->udev->descriptor.bcdDevice);
559
560			/* 0==UNKNOWN, 1==LOW(usb1.1) ,2=FULL(usb1.1), 3=HIGH(usb2.0) */
561			info.speed = dev->udev->speed;
562			info.if_num = dev->interface->cur_altsetting->desc.bInterfaceNumber;
563			info.report_size = dev->report_size;
564
565			/* serial number string has been read earlier 8 chars or empty string */
566			memcpy(info.serial, dev->chip_serial,
567			       sizeof(dev->chip_serial));
568			if (cfg_descriptor == NULL) {
569				info.power = -1;	/* no information available */
570			} else {
571				/* the MaxPower is stored in units of 2mA to make it fit into a byte-value */
572				info.power = cfg_descriptor->bMaxPower * 2;
573			}
574			io_res = copy_to_user((struct iowarrior_info __user *)arg, &info,
575					 sizeof(struct iowarrior_info));
576			if (io_res)
577				retval = -EFAULT;
578			break;
579		}
580	default:
581		/* return that we did not understand this ioctl call */
582		retval = -ENOTTY;
583		break;
584	}
585error_out:
586	/* unlock the device */
587	mutex_unlock(&dev->mutex);
588	kfree(buffer);
589	return retval;
590}
591
592/*
593 *	iowarrior_open
594 */
595static int iowarrior_open(struct inode *inode, struct file *file)
596{
597	struct iowarrior *dev = NULL;
598	struct usb_interface *interface;
599	int subminor;
600	int retval = 0;
601
602	subminor = iminor(inode);
603
604	interface = usb_find_interface(&iowarrior_driver, subminor);
605	if (!interface) {
606		pr_err("%s - error, can't find device for minor %d\n",
607		       __func__, subminor);
608		return -ENODEV;
609	}
610
611	dev = usb_get_intfdata(interface);
612	if (!dev)
613		return -ENODEV;
614
615	mutex_lock(&dev->mutex);
616
617	/* Only one process can open each device, no sharing. */
618	if (dev->opened) {
619		retval = -EBUSY;
620		goto out;
621	}
622
623	/* setup interrupt handler for receiving values */
624	if ((retval = usb_submit_urb(dev->int_in_urb, GFP_KERNEL)) < 0) {
625		dev_err(&interface->dev, "Error %d while submitting URB\n", retval);
626		retval = -EFAULT;
627		goto out;
628	}
629	/* increment our usage count for the driver */
630	++dev->opened;
631	/* save our object in the file's private structure */
632	file->private_data = dev;
633	retval = 0;
634
635out:
636	mutex_unlock(&dev->mutex);
637	return retval;
638}
639
640/*
641 *	iowarrior_release
642 */
643static int iowarrior_release(struct inode *inode, struct file *file)
644{
645	struct iowarrior *dev;
646	int retval = 0;
647
648	dev = file->private_data;
649	if (!dev)
650		return -ENODEV;
651
652	dev_dbg(&dev->interface->dev, "minor %d\n", dev->minor);
653
654	/* lock our device */
655	mutex_lock(&dev->mutex);
656
657	if (dev->opened <= 0) {
658		retval = -ENODEV;	/* close called more than once */
659		mutex_unlock(&dev->mutex);
660	} else {
661		dev->opened = 0;	/* we're closing now */
662		retval = 0;
663		if (dev->present) {
664			/*
665			   The device is still connected so we only shutdown
666			   pending read-/write-ops.
667			 */
668			usb_kill_urb(dev->int_in_urb);
669			wake_up_interruptible(&dev->read_wait);
670			wake_up_interruptible(&dev->write_wait);
671			mutex_unlock(&dev->mutex);
672		} else {
673			/* The device was unplugged, cleanup resources */
674			mutex_unlock(&dev->mutex);
675			iowarrior_delete(dev);
676		}
677	}
678	return retval;
679}
680
681static __poll_t iowarrior_poll(struct file *file, poll_table * wait)
682{
683	struct iowarrior *dev = file->private_data;
684	__poll_t mask = 0;
685
686	if (!dev->present)
687		return EPOLLERR | EPOLLHUP;
688
689	poll_wait(file, &dev->read_wait, wait);
690	poll_wait(file, &dev->write_wait, wait);
691
692	if (!dev->present)
693		return EPOLLERR | EPOLLHUP;
694
695	if (read_index(dev) != -1)
696		mask |= EPOLLIN | EPOLLRDNORM;
697
698	if (atomic_read(&dev->write_busy) < MAX_WRITES_IN_FLIGHT)
699		mask |= EPOLLOUT | EPOLLWRNORM;
700	return mask;
701}
702
703/*
704 * File operations needed when we register this driver.
705 * This assumes that this driver NEEDS file operations,
706 * of course, which means that the driver is expected
707 * to have a node in the /dev directory. If the USB
708 * device were for a network interface then the driver
709 * would use "struct net_driver" instead, and a serial
710 * device would use "struct tty_driver".
711 */
712static const struct file_operations iowarrior_fops = {
713	.owner = THIS_MODULE,
714	.write = iowarrior_write,
715	.read = iowarrior_read,
716	.unlocked_ioctl = iowarrior_ioctl,
717	.open = iowarrior_open,
718	.release = iowarrior_release,
719	.poll = iowarrior_poll,
720	.llseek = noop_llseek,
721};
722
723static char *iowarrior_devnode(struct device *dev, umode_t *mode)
724{
725	return kasprintf(GFP_KERNEL, "usb/%s", dev_name(dev));
726}
727
728/*
729 * usb class driver info in order to get a minor number from the usb core,
730 * and to have the device registered with devfs and the driver core
731 */
732static struct usb_class_driver iowarrior_class = {
733	.name = "iowarrior%d",
734	.devnode = iowarrior_devnode,
735	.fops = &iowarrior_fops,
736	.minor_base = IOWARRIOR_MINOR_BASE,
737};
738
739/*---------------------------------*/
740/*  probe and disconnect functions */
741/*---------------------------------*/
742/*
743 *	iowarrior_probe
744 *
745 *	Called by the usb core when a new device is connected that it thinks
746 *	this driver might be interested in.
747 */
748static int iowarrior_probe(struct usb_interface *interface,
749			   const struct usb_device_id *id)
750{
751	struct usb_device *udev = interface_to_usbdev(interface);
752	struct iowarrior *dev = NULL;
753	struct usb_host_interface *iface_desc;
754	int retval = -ENOMEM;
755	int res;
756
757	/* allocate memory for our device state and initialize it */
758	dev = kzalloc(sizeof(struct iowarrior), GFP_KERNEL);
759	if (!dev)
760		return retval;
761
762	mutex_init(&dev->mutex);
763
764	atomic_set(&dev->intr_idx, 0);
765	atomic_set(&dev->read_idx, 0);
766	atomic_set(&dev->overflow_flag, 0);
767	init_waitqueue_head(&dev->read_wait);
768	atomic_set(&dev->write_busy, 0);
769	init_waitqueue_head(&dev->write_wait);
770
771	dev->udev = udev;
772	dev->interface = usb_get_intf(interface);
773
774	iface_desc = interface->cur_altsetting;
775	dev->product_id = le16_to_cpu(udev->descriptor.idProduct);
776
777	init_usb_anchor(&dev->submitted);
778
779	res = usb_find_last_int_in_endpoint(iface_desc, &dev->int_in_endpoint);
780	if (res) {
781		dev_err(&interface->dev, "no interrupt-in endpoint found\n");
782		retval = res;
783		goto error;
784	}
785
786	if ((dev->product_id == USB_DEVICE_ID_CODEMERCS_IOW56) ||
787	    (dev->product_id == USB_DEVICE_ID_CODEMERCS_IOW56AM) ||
788	    (dev->product_id == USB_DEVICE_ID_CODEMERCS_IOW28) ||
789	    (dev->product_id == USB_DEVICE_ID_CODEMERCS_IOW28L) ||
790	    (dev->product_id == USB_DEVICE_ID_CODEMERCS_IOW100)) {
791		res = usb_find_last_int_out_endpoint(iface_desc,
792				&dev->int_out_endpoint);
793		if (res) {
794			dev_err(&interface->dev, "no interrupt-out endpoint found\n");
795			retval = res;
796			goto error;
797		}
798	}
799
800	/* we have to check the report_size often, so remember it in the endianness suitable for our machine */
801	dev->report_size = usb_endpoint_maxp(dev->int_in_endpoint);
802
803	/*
804	 * Some devices need the report size to be different than the
805	 * endpoint size.
806	 */
807	if (dev->interface->cur_altsetting->desc.bInterfaceNumber == 0) {
808		switch (dev->product_id) {
809		case USB_DEVICE_ID_CODEMERCS_IOW56:
810		case USB_DEVICE_ID_CODEMERCS_IOW56AM:
811			dev->report_size = 7;
812			break;
813
814		case USB_DEVICE_ID_CODEMERCS_IOW28:
815		case USB_DEVICE_ID_CODEMERCS_IOW28L:
816			dev->report_size = 4;
817			break;
818
819		case USB_DEVICE_ID_CODEMERCS_IOW100:
820			dev->report_size = 12;
821			break;
822		}
823	}
824
825	/* create the urb and buffer for reading */
826	dev->int_in_urb = usb_alloc_urb(0, GFP_KERNEL);
827	if (!dev->int_in_urb)
828		goto error;
829	dev->int_in_buffer = kmalloc(dev->report_size, GFP_KERNEL);
830	if (!dev->int_in_buffer)
831		goto error;
832	usb_fill_int_urb(dev->int_in_urb, dev->udev,
833			 usb_rcvintpipe(dev->udev,
834					dev->int_in_endpoint->bEndpointAddress),
835			 dev->int_in_buffer, dev->report_size,
836			 iowarrior_callback, dev,
837			 dev->int_in_endpoint->bInterval);
838	/* create an internal buffer for interrupt data from the device */
839	dev->read_queue =
840	    kmalloc_array(dev->report_size + 1, MAX_INTERRUPT_BUFFER,
841			  GFP_KERNEL);
842	if (!dev->read_queue)
843		goto error;
844	/* Get the serial-number of the chip */
845	memset(dev->chip_serial, 0x00, sizeof(dev->chip_serial));
846	usb_string(udev, udev->descriptor.iSerialNumber, dev->chip_serial,
847		   sizeof(dev->chip_serial));
848	if (strlen(dev->chip_serial) != 8)
849		memset(dev->chip_serial, 0x00, sizeof(dev->chip_serial));
850
851	/* Set the idle timeout to 0, if this is interface 0 */
852	if (dev->interface->cur_altsetting->desc.bInterfaceNumber == 0) {
853	    usb_control_msg(udev, usb_sndctrlpipe(udev, 0),
854			    0x0A,
855			    USB_TYPE_CLASS | USB_RECIP_INTERFACE, 0,
856			    0, NULL, 0, USB_CTRL_SET_TIMEOUT);
857	}
858	/* allow device read and ioctl */
859	dev->present = 1;
860
861	/* we can register the device now, as it is ready */
862	usb_set_intfdata(interface, dev);
863
864	retval = usb_register_dev(interface, &iowarrior_class);
865	if (retval) {
866		/* something prevented us from registering this driver */
867		dev_err(&interface->dev, "Not able to get a minor for this device.\n");
868		goto error;
869	}
870
871	dev->minor = interface->minor;
872
873	/* let the user know what node this device is now attached to */
874	dev_info(&interface->dev, "IOWarrior product=0x%x, serial=%s interface=%d "
875		 "now attached to iowarrior%d\n", dev->product_id, dev->chip_serial,
876		 iface_desc->desc.bInterfaceNumber, dev->minor - IOWARRIOR_MINOR_BASE);
877	return retval;
878
879error:
880	iowarrior_delete(dev);
881	return retval;
882}
883
884/*
885 *	iowarrior_disconnect
886 *
887 *	Called by the usb core when the device is removed from the system.
888 */
889static void iowarrior_disconnect(struct usb_interface *interface)
890{
891	struct iowarrior *dev = usb_get_intfdata(interface);
892	int minor = dev->minor;
893
894	usb_deregister_dev(interface, &iowarrior_class);
895
896	mutex_lock(&dev->mutex);
897
898	/* prevent device read, write and ioctl */
899	dev->present = 0;
900
901	if (dev->opened) {
902		/* There is a process that holds a filedescriptor to the device ,
903		   so we only shutdown read-/write-ops going on.
904		   Deleting the device is postponed until close() was called.
905		 */
906		usb_kill_urb(dev->int_in_urb);
907		usb_kill_anchored_urbs(&dev->submitted);
908		wake_up_interruptible(&dev->read_wait);
909		wake_up_interruptible(&dev->write_wait);
910		mutex_unlock(&dev->mutex);
911	} else {
912		/* no process is using the device, cleanup now */
913		mutex_unlock(&dev->mutex);
914		iowarrior_delete(dev);
915	}
916
917	dev_info(&interface->dev, "I/O-Warror #%d now disconnected\n",
918		 minor - IOWARRIOR_MINOR_BASE);
919}
920
921/* usb specific object needed to register this driver with the usb subsystem */
922static struct usb_driver iowarrior_driver = {
923	.name = "iowarrior",
924	.probe = iowarrior_probe,
925	.disconnect = iowarrior_disconnect,
926	.id_table = iowarrior_ids,
927};
928
929module_usb_driver(iowarrior_driver);
930