xref: /linux/drivers/usb/misc/legousbtower.c (revision 5fd54ace4721fc5ce2bb5aef6318fcf17f421460)
1 // SPDX-License-Identifier: GPL-2.0+
2 /*
3  * LEGO USB Tower driver
4  *
5  * Copyright (C) 2003 David Glance <davidgsf@sourceforge.net>
6  *               2001-2004 Juergen Stuber <starblue@users.sourceforge.net>
7  *
8  *	This program is free software; you can redistribute it and/or
9  *	modify it under the terms of the GNU General Public License as
10  *	published by the Free Software Foundation; either version 2 of
11  *	the License, or (at your option) any later version.
12  *
13  * derived from USB Skeleton driver - 0.5
14  * Copyright (C) 2001 Greg Kroah-Hartman (greg@kroah.com)
15  *
16  * History:
17  *
18  * 2001-10-13 - 0.1 js
19  *   - first version
20  * 2001-11-03 - 0.2 js
21  *   - simplified buffering, one-shot URBs for writing
22  * 2001-11-10 - 0.3 js
23  *   - removed IOCTL (setting power/mode is more complicated, postponed)
24  * 2001-11-28 - 0.4 js
25  *   - added vendor commands for mode of operation and power level in open
26  * 2001-12-04 - 0.5 js
27  *   - set IR mode by default (by oversight 0.4 set VLL mode)
28  * 2002-01-11 - 0.5? pcchan
29  *   - make read buffer reusable and work around bytes_to_write issue between
30  *     uhci and legusbtower
31  * 2002-09-23 - 0.52 david (david@csse.uwa.edu.au)
32  *   - imported into lejos project
33  *   - changed wake_up to wake_up_interruptible
34  *   - changed to use lego0 rather than tower0
35  *   - changed dbg() to use __func__ rather than deprecated __func__
36  * 2003-01-12 - 0.53 david (david@csse.uwa.edu.au)
37  *   - changed read and write to write everything or
38  *     timeout (from a patch by Chris Riesen and Brett Thaeler driver)
39  *   - added ioctl functionality to set timeouts
40  * 2003-07-18 - 0.54 davidgsf (david@csse.uwa.edu.au)
41  *   - initial import into LegoUSB project
42  *   - merge of existing LegoUSB.c driver
43  * 2003-07-18 - 0.56 davidgsf (david@csse.uwa.edu.au)
44  *   - port to 2.6 style driver
45  * 2004-02-29 - 0.6 Juergen Stuber <starblue@users.sourceforge.net>
46  *   - fix locking
47  *   - unlink read URBs which are no longer needed
48  *   - allow increased buffer size, eliminates need for timeout on write
49  *   - have read URB running continuously
50  *   - added poll
51  *   - forbid seeking
52  *   - added nonblocking I/O
53  *   - changed back __func__ to __func__
54  *   - read and log tower firmware version
55  *   - reset tower on probe, avoids failure of first write
56  * 2004-03-09 - 0.7 Juergen Stuber <starblue@users.sourceforge.net>
57  *   - timeout read now only after inactivity, shorten default accordingly
58  * 2004-03-11 - 0.8 Juergen Stuber <starblue@users.sourceforge.net>
59  *   - log major, minor instead of possibly confusing device filename
60  *   - whitespace cleanup
61  * 2004-03-12 - 0.9 Juergen Stuber <starblue@users.sourceforge.net>
62  *   - normalize whitespace in debug messages
63  *   - take care about endianness in control message responses
64  * 2004-03-13 - 0.91 Juergen Stuber <starblue@users.sourceforge.net>
65  *   - make default intervals longer to accommodate current EHCI driver
66  * 2004-03-19 - 0.92 Juergen Stuber <starblue@users.sourceforge.net>
67  *   - replaced atomic_t by memory barriers
68  * 2004-04-21 - 0.93 Juergen Stuber <starblue@users.sourceforge.net>
69  *   - wait for completion of write urb in release (needed for remotecontrol)
70  *   - corrected poll for write direction (missing negation)
71  * 2004-04-22 - 0.94 Juergen Stuber <starblue@users.sourceforge.net>
72  *   - make device locking interruptible
73  * 2004-04-30 - 0.95 Juergen Stuber <starblue@users.sourceforge.net>
74  *   - check for valid udev on resubmitting and unlinking urbs
75  * 2004-08-03 - 0.96 Juergen Stuber <starblue@users.sourceforge.net>
76  *   - move reset into open to clean out spurious data
77  */
78 
79 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
80 
81 #include <linux/kernel.h>
82 #include <linux/errno.h>
83 #include <linux/slab.h>
84 #include <linux/module.h>
85 #include <linux/completion.h>
86 #include <linux/mutex.h>
87 #include <linux/uaccess.h>
88 #include <linux/usb.h>
89 #include <linux/poll.h>
90 
91 
92 #define DRIVER_AUTHOR "Juergen Stuber <starblue@sourceforge.net>"
93 #define DRIVER_DESC "LEGO USB Tower Driver"
94 
95 
96 /* The defaults are chosen to work with the latest versions of leJOS and NQC.
97  */
98 
99 /* Some legacy software likes to receive packets in one piece.
100  * In this case read_buffer_size should exceed the maximal packet length
101  * (417 for datalog uploads), and packet_timeout should be set.
102  */
103 static int read_buffer_size = 480;
104 module_param(read_buffer_size, int, 0);
105 MODULE_PARM_DESC(read_buffer_size, "Read buffer size");
106 
107 /* Some legacy software likes to send packets in one piece.
108  * In this case write_buffer_size should exceed the maximal packet length
109  * (417 for firmware and program downloads).
110  * A problem with long writes is that the following read may time out
111  * if the software is not prepared to wait long enough.
112  */
113 static int write_buffer_size = 480;
114 module_param(write_buffer_size, int, 0);
115 MODULE_PARM_DESC(write_buffer_size, "Write buffer size");
116 
117 /* Some legacy software expects reads to contain whole LASM packets.
118  * To achieve this, characters which arrive before a packet timeout
119  * occurs will be returned in a single read operation.
120  * A problem with long reads is that the software may time out
121  * if it is not prepared to wait long enough.
122  * The packet timeout should be greater than the time between the
123  * reception of subsequent characters, which should arrive about
124  * every 5ms for the standard 2400 baud.
125  * Set it to 0 to disable.
126  */
127 static int packet_timeout = 50;
128 module_param(packet_timeout, int, 0);
129 MODULE_PARM_DESC(packet_timeout, "Packet timeout in ms");
130 
131 /* Some legacy software expects blocking reads to time out.
132  * Timeout occurs after the specified time of read and write inactivity.
133  * Set it to 0 to disable.
134  */
135 static int read_timeout = 200;
136 module_param(read_timeout, int, 0);
137 MODULE_PARM_DESC(read_timeout, "Read timeout in ms");
138 
139 /* As of kernel version 2.6.4 ehci-hcd uses an
140  * "only one interrupt transfer per frame" shortcut
141  * to simplify the scheduling of periodic transfers.
142  * This conflicts with our standard 1ms intervals for in and out URBs.
143  * We use default intervals of 2ms for in and 8ms for out transfers,
144  * which is fast enough for 2400 baud and allows a small additional load.
145  * Increase the interval to allow more devices that do interrupt transfers,
146  * or set to 0 to use the standard interval from the endpoint descriptors.
147  */
148 static int interrupt_in_interval = 2;
149 module_param(interrupt_in_interval, int, 0);
150 MODULE_PARM_DESC(interrupt_in_interval, "Interrupt in interval in ms");
151 
152 static int interrupt_out_interval = 8;
153 module_param(interrupt_out_interval, int, 0);
154 MODULE_PARM_DESC(interrupt_out_interval, "Interrupt out interval in ms");
155 
156 /* Define these values to match your device */
157 #define LEGO_USB_TOWER_VENDOR_ID	0x0694
158 #define LEGO_USB_TOWER_PRODUCT_ID	0x0001
159 
160 /* Vendor requests */
161 #define LEGO_USB_TOWER_REQUEST_RESET		0x04
162 #define LEGO_USB_TOWER_REQUEST_GET_VERSION	0xFD
163 
164 struct tower_reset_reply {
165 	__le16 size;		/* little-endian */
166 	__u8 err_code;
167 	__u8 spare;
168 } __attribute__ ((packed));
169 
170 struct tower_get_version_reply {
171 	__le16 size;		/* little-endian */
172 	__u8 err_code;
173 	__u8 spare;
174 	__u8 major;
175 	__u8 minor;
176 	__le16 build_no;		/* little-endian */
177 } __attribute__ ((packed));
178 
179 
180 /* table of devices that work with this driver */
181 static const struct usb_device_id tower_table[] = {
182 	{ USB_DEVICE(LEGO_USB_TOWER_VENDOR_ID, LEGO_USB_TOWER_PRODUCT_ID) },
183 	{ }					/* Terminating entry */
184 };
185 
186 MODULE_DEVICE_TABLE (usb, tower_table);
187 static DEFINE_MUTEX(open_disc_mutex);
188 
189 #define LEGO_USB_TOWER_MINOR_BASE	160
190 
191 
192 /* Structure to hold all of our device specific stuff */
193 struct lego_usb_tower {
194 	struct mutex		lock;		/* locks this structure */
195 	struct usb_device*	udev;		/* save off the usb device pointer */
196 	unsigned char		minor;		/* the starting minor number for this device */
197 
198 	int			open_count;	/* number of times this port has been opened */
199 
200 	char*			read_buffer;
201 	size_t			read_buffer_length; /* this much came in */
202 	size_t			read_packet_length; /* this much will be returned on read */
203 	spinlock_t		read_buffer_lock;
204 	int			packet_timeout_jiffies;
205 	unsigned long		read_last_arrival;
206 
207 	wait_queue_head_t	read_wait;
208 	wait_queue_head_t	write_wait;
209 
210 	char*			interrupt_in_buffer;
211 	struct usb_endpoint_descriptor* interrupt_in_endpoint;
212 	struct urb*		interrupt_in_urb;
213 	int			interrupt_in_interval;
214 	int			interrupt_in_running;
215 	int			interrupt_in_done;
216 
217 	char*			interrupt_out_buffer;
218 	struct usb_endpoint_descriptor* interrupt_out_endpoint;
219 	struct urb*		interrupt_out_urb;
220 	int			interrupt_out_interval;
221 	int			interrupt_out_busy;
222 
223 };
224 
225 
226 /* local function prototypes */
227 static ssize_t tower_read	(struct file *file, char __user *buffer, size_t count, loff_t *ppos);
228 static ssize_t tower_write	(struct file *file, const char __user *buffer, size_t count, loff_t *ppos);
229 static inline void tower_delete (struct lego_usb_tower *dev);
230 static int tower_open		(struct inode *inode, struct file *file);
231 static int tower_release	(struct inode *inode, struct file *file);
232 static unsigned int tower_poll	(struct file *file, poll_table *wait);
233 static loff_t tower_llseek	(struct file *file, loff_t off, int whence);
234 
235 static void tower_abort_transfers (struct lego_usb_tower *dev);
236 static void tower_check_for_read_packet (struct lego_usb_tower *dev);
237 static void tower_interrupt_in_callback (struct urb *urb);
238 static void tower_interrupt_out_callback (struct urb *urb);
239 
240 static int  tower_probe	(struct usb_interface *interface, const struct usb_device_id *id);
241 static void tower_disconnect	(struct usb_interface *interface);
242 
243 
244 /* file operations needed when we register this driver */
245 static const struct file_operations tower_fops = {
246 	.owner =	THIS_MODULE,
247 	.read  =	tower_read,
248 	.write =	tower_write,
249 	.open =		tower_open,
250 	.release =	tower_release,
251 	.poll =		tower_poll,
252 	.llseek =	tower_llseek,
253 };
254 
255 static char *legousbtower_devnode(struct device *dev, umode_t *mode)
256 {
257 	return kasprintf(GFP_KERNEL, "usb/%s", dev_name(dev));
258 }
259 
260 /*
261  * usb class driver info in order to get a minor number from the usb core,
262  * and to have the device registered with the driver core
263  */
264 static struct usb_class_driver tower_class = {
265 	.name =		"legousbtower%d",
266 	.devnode = 	legousbtower_devnode,
267 	.fops =		&tower_fops,
268 	.minor_base =	LEGO_USB_TOWER_MINOR_BASE,
269 };
270 
271 
272 /* usb specific object needed to register this driver with the usb subsystem */
273 static struct usb_driver tower_driver = {
274 	.name =		"legousbtower",
275 	.probe =	tower_probe,
276 	.disconnect =	tower_disconnect,
277 	.id_table =	tower_table,
278 };
279 
280 
281 /**
282  *	lego_usb_tower_debug_data
283  */
284 static inline void lego_usb_tower_debug_data(struct device *dev,
285 					     const char *function, int size,
286 					     const unsigned char *data)
287 {
288 	dev_dbg(dev, "%s - length = %d, data = %*ph\n",
289 		function, size, size, data);
290 }
291 
292 
293 /**
294  *	tower_delete
295  */
296 static inline void tower_delete (struct lego_usb_tower *dev)
297 {
298 	tower_abort_transfers (dev);
299 
300 	/* free data structures */
301 	usb_free_urb(dev->interrupt_in_urb);
302 	usb_free_urb(dev->interrupt_out_urb);
303 	kfree (dev->read_buffer);
304 	kfree (dev->interrupt_in_buffer);
305 	kfree (dev->interrupt_out_buffer);
306 	kfree (dev);
307 }
308 
309 
310 /**
311  *	tower_open
312  */
313 static int tower_open (struct inode *inode, struct file *file)
314 {
315 	struct lego_usb_tower *dev = NULL;
316 	int subminor;
317 	int retval = 0;
318 	struct usb_interface *interface;
319 	struct tower_reset_reply *reset_reply;
320 	int result;
321 
322 	reset_reply = kmalloc(sizeof(*reset_reply), GFP_KERNEL);
323 
324 	if (!reset_reply) {
325 		retval = -ENOMEM;
326 		goto exit;
327 	}
328 
329 	nonseekable_open(inode, file);
330 	subminor = iminor(inode);
331 
332 	interface = usb_find_interface (&tower_driver, subminor);
333 
334 	if (!interface) {
335 		pr_err("error, can't find device for minor %d\n", subminor);
336 		retval = -ENODEV;
337 		goto exit;
338 	}
339 
340 	mutex_lock(&open_disc_mutex);
341 	dev = usb_get_intfdata(interface);
342 
343 	if (!dev) {
344 		mutex_unlock(&open_disc_mutex);
345 		retval = -ENODEV;
346 		goto exit;
347 	}
348 
349 	/* lock this device */
350 	if (mutex_lock_interruptible(&dev->lock)) {
351 		mutex_unlock(&open_disc_mutex);
352 	        retval = -ERESTARTSYS;
353 		goto exit;
354 	}
355 
356 
357 	/* allow opening only once */
358 	if (dev->open_count) {
359 		mutex_unlock(&open_disc_mutex);
360 		retval = -EBUSY;
361 		goto unlock_exit;
362 	}
363 	dev->open_count = 1;
364 	mutex_unlock(&open_disc_mutex);
365 
366 	/* reset the tower */
367 	result = usb_control_msg (dev->udev,
368 				  usb_rcvctrlpipe(dev->udev, 0),
369 				  LEGO_USB_TOWER_REQUEST_RESET,
370 				  USB_TYPE_VENDOR | USB_DIR_IN | USB_RECIP_DEVICE,
371 				  0,
372 				  0,
373 				  reset_reply,
374 				  sizeof(*reset_reply),
375 				  1000);
376 	if (result < 0) {
377 		dev_err(&dev->udev->dev,
378 			"LEGO USB Tower reset control request failed\n");
379 		retval = result;
380 		goto unlock_exit;
381 	}
382 
383 	/* initialize in direction */
384 	dev->read_buffer_length = 0;
385 	dev->read_packet_length = 0;
386 	usb_fill_int_urb (dev->interrupt_in_urb,
387 			  dev->udev,
388 			  usb_rcvintpipe(dev->udev, dev->interrupt_in_endpoint->bEndpointAddress),
389 			  dev->interrupt_in_buffer,
390 			  usb_endpoint_maxp(dev->interrupt_in_endpoint),
391 			  tower_interrupt_in_callback,
392 			  dev,
393 			  dev->interrupt_in_interval);
394 
395 	dev->interrupt_in_running = 1;
396 	dev->interrupt_in_done = 0;
397 	mb();
398 
399 	retval = usb_submit_urb (dev->interrupt_in_urb, GFP_KERNEL);
400 	if (retval) {
401 		dev_err(&dev->udev->dev,
402 			"Couldn't submit interrupt_in_urb %d\n", retval);
403 		dev->interrupt_in_running = 0;
404 		dev->open_count = 0;
405 		goto unlock_exit;
406 	}
407 
408 	/* save device in the file's private structure */
409 	file->private_data = dev;
410 
411 unlock_exit:
412 	mutex_unlock(&dev->lock);
413 
414 exit:
415 	kfree(reset_reply);
416 	return retval;
417 }
418 
419 /**
420  *	tower_release
421  */
422 static int tower_release (struct inode *inode, struct file *file)
423 {
424 	struct lego_usb_tower *dev;
425 	int retval = 0;
426 
427 	dev = file->private_data;
428 
429 	if (dev == NULL) {
430 		retval = -ENODEV;
431 		goto exit_nolock;
432 	}
433 
434 	mutex_lock(&open_disc_mutex);
435 	if (mutex_lock_interruptible(&dev->lock)) {
436 	        retval = -ERESTARTSYS;
437 		goto exit;
438 	}
439 
440 	if (dev->open_count != 1) {
441 		dev_dbg(&dev->udev->dev, "%s: device not opened exactly once\n",
442 			__func__);
443 		retval = -ENODEV;
444 		goto unlock_exit;
445 	}
446 	if (dev->udev == NULL) {
447 		/* the device was unplugged before the file was released */
448 
449 		/* unlock here as tower_delete frees dev */
450 		mutex_unlock(&dev->lock);
451 		tower_delete (dev);
452 		goto exit;
453 	}
454 
455 	/* wait until write transfer is finished */
456 	if (dev->interrupt_out_busy) {
457 		wait_event_interruptible_timeout (dev->write_wait, !dev->interrupt_out_busy, 2 * HZ);
458 	}
459 	tower_abort_transfers (dev);
460 	dev->open_count = 0;
461 
462 unlock_exit:
463 	mutex_unlock(&dev->lock);
464 
465 exit:
466 	mutex_unlock(&open_disc_mutex);
467 exit_nolock:
468 	return retval;
469 }
470 
471 
472 /**
473  *	tower_abort_transfers
474  *      aborts transfers and frees associated data structures
475  */
476 static void tower_abort_transfers (struct lego_usb_tower *dev)
477 {
478 	if (dev == NULL)
479 		return;
480 
481 	/* shutdown transfer */
482 	if (dev->interrupt_in_running) {
483 		dev->interrupt_in_running = 0;
484 		mb();
485 		if (dev->udev)
486 			usb_kill_urb (dev->interrupt_in_urb);
487 	}
488 	if (dev->interrupt_out_busy && dev->udev)
489 		usb_kill_urb(dev->interrupt_out_urb);
490 }
491 
492 
493 /**
494  *	tower_check_for_read_packet
495  *
496  *      To get correct semantics for signals and non-blocking I/O
497  *      with packetizing we pretend not to see any data in the read buffer
498  *      until it has been there unchanged for at least
499  *      dev->packet_timeout_jiffies, or until the buffer is full.
500  */
501 static void tower_check_for_read_packet (struct lego_usb_tower *dev)
502 {
503 	spin_lock_irq (&dev->read_buffer_lock);
504 	if (!packet_timeout
505 	    || time_after(jiffies, dev->read_last_arrival + dev->packet_timeout_jiffies)
506 	    || dev->read_buffer_length == read_buffer_size) {
507 		dev->read_packet_length = dev->read_buffer_length;
508 	}
509 	dev->interrupt_in_done = 0;
510 	spin_unlock_irq (&dev->read_buffer_lock);
511 }
512 
513 
514 /**
515  *	tower_poll
516  */
517 static unsigned int tower_poll (struct file *file, poll_table *wait)
518 {
519 	struct lego_usb_tower *dev;
520 	unsigned int mask = 0;
521 
522 	dev = file->private_data;
523 
524 	if (!dev->udev)
525 		return POLLERR | POLLHUP;
526 
527 	poll_wait(file, &dev->read_wait, wait);
528 	poll_wait(file, &dev->write_wait, wait);
529 
530 	tower_check_for_read_packet(dev);
531 	if (dev->read_packet_length > 0) {
532 		mask |= POLLIN | POLLRDNORM;
533 	}
534 	if (!dev->interrupt_out_busy) {
535 		mask |= POLLOUT | POLLWRNORM;
536 	}
537 
538 	return mask;
539 }
540 
541 
542 /**
543  *	tower_llseek
544  */
545 static loff_t tower_llseek (struct file *file, loff_t off, int whence)
546 {
547 	return -ESPIPE;		/* unseekable */
548 }
549 
550 
551 /**
552  *	tower_read
553  */
554 static ssize_t tower_read (struct file *file, char __user *buffer, size_t count, loff_t *ppos)
555 {
556 	struct lego_usb_tower *dev;
557 	size_t bytes_to_read;
558 	int i;
559 	int retval = 0;
560 	unsigned long timeout = 0;
561 
562 	dev = file->private_data;
563 
564 	/* lock this object */
565 	if (mutex_lock_interruptible(&dev->lock)) {
566 		retval = -ERESTARTSYS;
567 		goto exit;
568 	}
569 
570 	/* verify that the device wasn't unplugged */
571 	if (dev->udev == NULL) {
572 		retval = -ENODEV;
573 		pr_err("No device or device unplugged %d\n", retval);
574 		goto unlock_exit;
575 	}
576 
577 	/* verify that we actually have some data to read */
578 	if (count == 0) {
579 		dev_dbg(&dev->udev->dev, "read request of 0 bytes\n");
580 		goto unlock_exit;
581 	}
582 
583 	if (read_timeout) {
584 		timeout = jiffies + msecs_to_jiffies(read_timeout);
585 	}
586 
587 	/* wait for data */
588 	tower_check_for_read_packet (dev);
589 	while (dev->read_packet_length == 0) {
590 		if (file->f_flags & O_NONBLOCK) {
591 			retval = -EAGAIN;
592 			goto unlock_exit;
593 		}
594 		retval = wait_event_interruptible_timeout(dev->read_wait, dev->interrupt_in_done, dev->packet_timeout_jiffies);
595 		if (retval < 0) {
596 			goto unlock_exit;
597 		}
598 
599 		/* reset read timeout during read or write activity */
600 		if (read_timeout
601 		    && (dev->read_buffer_length || dev->interrupt_out_busy)) {
602 			timeout = jiffies + msecs_to_jiffies(read_timeout);
603 		}
604 		/* check for read timeout */
605 		if (read_timeout && time_after (jiffies, timeout)) {
606 			retval = -ETIMEDOUT;
607 			goto unlock_exit;
608 		}
609 		tower_check_for_read_packet (dev);
610 	}
611 
612 	/* copy the data from read_buffer into userspace */
613 	bytes_to_read = min(count, dev->read_packet_length);
614 
615 	if (copy_to_user (buffer, dev->read_buffer, bytes_to_read)) {
616 		retval = -EFAULT;
617 		goto unlock_exit;
618 	}
619 
620 	spin_lock_irq (&dev->read_buffer_lock);
621 	dev->read_buffer_length -= bytes_to_read;
622 	dev->read_packet_length -= bytes_to_read;
623 	for (i=0; i<dev->read_buffer_length; i++) {
624 		dev->read_buffer[i] = dev->read_buffer[i+bytes_to_read];
625 	}
626 	spin_unlock_irq (&dev->read_buffer_lock);
627 
628 	retval = bytes_to_read;
629 
630 unlock_exit:
631 	/* unlock the device */
632 	mutex_unlock(&dev->lock);
633 
634 exit:
635 	return retval;
636 }
637 
638 
639 /**
640  *	tower_write
641  */
642 static ssize_t tower_write (struct file *file, const char __user *buffer, size_t count, loff_t *ppos)
643 {
644 	struct lego_usb_tower *dev;
645 	size_t bytes_to_write;
646 	int retval = 0;
647 
648 	dev = file->private_data;
649 
650 	/* lock this object */
651 	if (mutex_lock_interruptible(&dev->lock)) {
652 		retval = -ERESTARTSYS;
653 		goto exit;
654 	}
655 
656 	/* verify that the device wasn't unplugged */
657 	if (dev->udev == NULL) {
658 		retval = -ENODEV;
659 		pr_err("No device or device unplugged %d\n", retval);
660 		goto unlock_exit;
661 	}
662 
663 	/* verify that we actually have some data to write */
664 	if (count == 0) {
665 		dev_dbg(&dev->udev->dev, "write request of 0 bytes\n");
666 		goto unlock_exit;
667 	}
668 
669 	/* wait until previous transfer is finished */
670 	while (dev->interrupt_out_busy) {
671 		if (file->f_flags & O_NONBLOCK) {
672 			retval = -EAGAIN;
673 			goto unlock_exit;
674 		}
675 		retval = wait_event_interruptible (dev->write_wait, !dev->interrupt_out_busy);
676 		if (retval) {
677 			goto unlock_exit;
678 		}
679 	}
680 
681 	/* write the data into interrupt_out_buffer from userspace */
682 	bytes_to_write = min_t(int, count, write_buffer_size);
683 	dev_dbg(&dev->udev->dev, "%s: count = %zd, bytes_to_write = %zd\n",
684 		__func__, count, bytes_to_write);
685 
686 	if (copy_from_user (dev->interrupt_out_buffer, buffer, bytes_to_write)) {
687 		retval = -EFAULT;
688 		goto unlock_exit;
689 	}
690 
691 	/* send off the urb */
692 	usb_fill_int_urb(dev->interrupt_out_urb,
693 			 dev->udev,
694 			 usb_sndintpipe(dev->udev, dev->interrupt_out_endpoint->bEndpointAddress),
695 			 dev->interrupt_out_buffer,
696 			 bytes_to_write,
697 			 tower_interrupt_out_callback,
698 			 dev,
699 			 dev->interrupt_out_interval);
700 
701 	dev->interrupt_out_busy = 1;
702 	wmb();
703 
704 	retval = usb_submit_urb (dev->interrupt_out_urb, GFP_KERNEL);
705 	if (retval) {
706 		dev->interrupt_out_busy = 0;
707 		dev_err(&dev->udev->dev,
708 			"Couldn't submit interrupt_out_urb %d\n", retval);
709 		goto unlock_exit;
710 	}
711 	retval = bytes_to_write;
712 
713 unlock_exit:
714 	/* unlock the device */
715 	mutex_unlock(&dev->lock);
716 
717 exit:
718 	return retval;
719 }
720 
721 
722 /**
723  *	tower_interrupt_in_callback
724  */
725 static void tower_interrupt_in_callback (struct urb *urb)
726 {
727 	struct lego_usb_tower *dev = urb->context;
728 	int status = urb->status;
729 	int retval;
730 
731 	lego_usb_tower_debug_data(&dev->udev->dev, __func__,
732 				  urb->actual_length, urb->transfer_buffer);
733 
734 	if (status) {
735 		if (status == -ENOENT ||
736 		    status == -ECONNRESET ||
737 		    status == -ESHUTDOWN) {
738 			goto exit;
739 		} else {
740 			dev_dbg(&dev->udev->dev,
741 				"%s: nonzero status received: %d\n", __func__,
742 				status);
743 			goto resubmit; /* maybe we can recover */
744 		}
745 	}
746 
747 	if (urb->actual_length > 0) {
748 		spin_lock (&dev->read_buffer_lock);
749 		if (dev->read_buffer_length + urb->actual_length < read_buffer_size) {
750 			memcpy (dev->read_buffer + dev->read_buffer_length,
751 				dev->interrupt_in_buffer,
752 				urb->actual_length);
753 			dev->read_buffer_length += urb->actual_length;
754 			dev->read_last_arrival = jiffies;
755 			dev_dbg(&dev->udev->dev, "%s: received %d bytes\n",
756 				__func__, urb->actual_length);
757 		} else {
758 			pr_warn("read_buffer overflow, %d bytes dropped\n",
759 				urb->actual_length);
760 		}
761 		spin_unlock (&dev->read_buffer_lock);
762 	}
763 
764 resubmit:
765 	/* resubmit if we're still running */
766 	if (dev->interrupt_in_running && dev->udev) {
767 		retval = usb_submit_urb (dev->interrupt_in_urb, GFP_ATOMIC);
768 		if (retval)
769 			dev_err(&dev->udev->dev,
770 				"%s: usb_submit_urb failed (%d)\n",
771 				__func__, retval);
772 	}
773 
774 exit:
775 	dev->interrupt_in_done = 1;
776 	wake_up_interruptible (&dev->read_wait);
777 }
778 
779 
780 /**
781  *	tower_interrupt_out_callback
782  */
783 static void tower_interrupt_out_callback (struct urb *urb)
784 {
785 	struct lego_usb_tower *dev = urb->context;
786 	int status = urb->status;
787 
788 	lego_usb_tower_debug_data(&dev->udev->dev, __func__,
789 				  urb->actual_length, urb->transfer_buffer);
790 
791 	/* sync/async unlink faults aren't errors */
792 	if (status && !(status == -ENOENT ||
793 			status == -ECONNRESET ||
794 			status == -ESHUTDOWN)) {
795 		dev_dbg(&dev->udev->dev,
796 			"%s: nonzero write bulk status received: %d\n", __func__,
797 			status);
798 	}
799 
800 	dev->interrupt_out_busy = 0;
801 	wake_up_interruptible(&dev->write_wait);
802 }
803 
804 
805 /**
806  *	tower_probe
807  *
808  *	Called by the usb core when a new device is connected that it thinks
809  *	this driver might be interested in.
810  */
811 static int tower_probe (struct usb_interface *interface, const struct usb_device_id *id)
812 {
813 	struct device *idev = &interface->dev;
814 	struct usb_device *udev = interface_to_usbdev(interface);
815 	struct lego_usb_tower *dev = NULL;
816 	struct tower_get_version_reply *get_version_reply = NULL;
817 	int retval = -ENOMEM;
818 	int result;
819 
820 	/* allocate memory for our device state and initialize it */
821 
822 	dev = kmalloc (sizeof(struct lego_usb_tower), GFP_KERNEL);
823 
824 	if (!dev)
825 		goto exit;
826 
827 	mutex_init(&dev->lock);
828 
829 	dev->udev = udev;
830 	dev->open_count = 0;
831 
832 	dev->read_buffer = NULL;
833 	dev->read_buffer_length = 0;
834 	dev->read_packet_length = 0;
835 	spin_lock_init (&dev->read_buffer_lock);
836 	dev->packet_timeout_jiffies = msecs_to_jiffies(packet_timeout);
837 	dev->read_last_arrival = jiffies;
838 
839 	init_waitqueue_head (&dev->read_wait);
840 	init_waitqueue_head (&dev->write_wait);
841 
842 	dev->interrupt_in_buffer = NULL;
843 	dev->interrupt_in_endpoint = NULL;
844 	dev->interrupt_in_urb = NULL;
845 	dev->interrupt_in_running = 0;
846 	dev->interrupt_in_done = 0;
847 
848 	dev->interrupt_out_buffer = NULL;
849 	dev->interrupt_out_endpoint = NULL;
850 	dev->interrupt_out_urb = NULL;
851 	dev->interrupt_out_busy = 0;
852 
853 	result = usb_find_common_endpoints_reverse(interface->cur_altsetting,
854 			NULL, NULL,
855 			&dev->interrupt_in_endpoint,
856 			&dev->interrupt_out_endpoint);
857 	if (result) {
858 		dev_err(idev, "interrupt endpoints not found\n");
859 		retval = result;
860 		goto error;
861 	}
862 
863 	dev->read_buffer = kmalloc (read_buffer_size, GFP_KERNEL);
864 	if (!dev->read_buffer)
865 		goto error;
866 	dev->interrupt_in_buffer = kmalloc (usb_endpoint_maxp(dev->interrupt_in_endpoint), GFP_KERNEL);
867 	if (!dev->interrupt_in_buffer)
868 		goto error;
869 	dev->interrupt_in_urb = usb_alloc_urb(0, GFP_KERNEL);
870 	if (!dev->interrupt_in_urb)
871 		goto error;
872 	dev->interrupt_out_buffer = kmalloc (write_buffer_size, GFP_KERNEL);
873 	if (!dev->interrupt_out_buffer)
874 		goto error;
875 	dev->interrupt_out_urb = usb_alloc_urb(0, GFP_KERNEL);
876 	if (!dev->interrupt_out_urb)
877 		goto error;
878 	dev->interrupt_in_interval = interrupt_in_interval ? interrupt_in_interval : dev->interrupt_in_endpoint->bInterval;
879 	dev->interrupt_out_interval = interrupt_out_interval ? interrupt_out_interval : dev->interrupt_out_endpoint->bInterval;
880 
881 	get_version_reply = kmalloc(sizeof(*get_version_reply), GFP_KERNEL);
882 
883 	if (!get_version_reply) {
884 		retval = -ENOMEM;
885 		goto error;
886 	}
887 
888 	/* get the firmware version and log it */
889 	result = usb_control_msg (udev,
890 				  usb_rcvctrlpipe(udev, 0),
891 				  LEGO_USB_TOWER_REQUEST_GET_VERSION,
892 				  USB_TYPE_VENDOR | USB_DIR_IN | USB_RECIP_DEVICE,
893 				  0,
894 				  0,
895 				  get_version_reply,
896 				  sizeof(*get_version_reply),
897 				  1000);
898 	if (result < 0) {
899 		dev_err(idev, "LEGO USB Tower get version control request failed\n");
900 		retval = result;
901 		goto error;
902 	}
903 	dev_info(&interface->dev,
904 		 "LEGO USB Tower firmware version is %d.%d build %d\n",
905 		 get_version_reply->major,
906 		 get_version_reply->minor,
907 		 le16_to_cpu(get_version_reply->build_no));
908 
909 	/* we can register the device now, as it is ready */
910 	usb_set_intfdata (interface, dev);
911 
912 	retval = usb_register_dev (interface, &tower_class);
913 
914 	if (retval) {
915 		/* something prevented us from registering this driver */
916 		dev_err(idev, "Not able to get a minor for this device.\n");
917 		usb_set_intfdata (interface, NULL);
918 		goto error;
919 	}
920 	dev->minor = interface->minor;
921 
922 	/* let the user know what node this device is now attached to */
923 	dev_info(&interface->dev, "LEGO USB Tower #%d now attached to major "
924 		 "%d minor %d\n", (dev->minor - LEGO_USB_TOWER_MINOR_BASE),
925 		 USB_MAJOR, dev->minor);
926 
927 exit:
928 	kfree(get_version_reply);
929 	return retval;
930 
931 error:
932 	kfree(get_version_reply);
933 	tower_delete(dev);
934 	return retval;
935 }
936 
937 
938 /**
939  *	tower_disconnect
940  *
941  *	Called by the usb core when the device is removed from the system.
942  */
943 static void tower_disconnect (struct usb_interface *interface)
944 {
945 	struct lego_usb_tower *dev;
946 	int minor;
947 
948 	dev = usb_get_intfdata (interface);
949 	mutex_lock(&open_disc_mutex);
950 	usb_set_intfdata (interface, NULL);
951 
952 	minor = dev->minor;
953 
954 	/* give back our minor */
955 	usb_deregister_dev (interface, &tower_class);
956 
957 	mutex_lock(&dev->lock);
958 	mutex_unlock(&open_disc_mutex);
959 
960 	/* if the device is not opened, then we clean up right now */
961 	if (!dev->open_count) {
962 		mutex_unlock(&dev->lock);
963 		tower_delete (dev);
964 	} else {
965 		dev->udev = NULL;
966 		/* wake up pollers */
967 		wake_up_interruptible_all(&dev->read_wait);
968 		wake_up_interruptible_all(&dev->write_wait);
969 		mutex_unlock(&dev->lock);
970 	}
971 
972 	dev_info(&interface->dev, "LEGO USB Tower #%d now disconnected\n",
973 		 (minor - LEGO_USB_TOWER_MINOR_BASE));
974 }
975 
976 module_usb_driver(tower_driver);
977 
978 MODULE_AUTHOR(DRIVER_AUTHOR);
979 MODULE_DESCRIPTION(DRIVER_DESC);
980 #ifdef MODULE_LICENSE
981 MODULE_LICENSE("GPL");
982 #endif
983