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