Merge branch 'master' into windows
[ardour.git] / libs / surfaces / frontier / kernel_drivers / tranzport.c
1 /*
2  * Frontier Designs Tranzport driver
3  *
4  * Copyright (C) 2007 Michael Taht (m@taht.net)
5  *
6  * Based on the usbled driver and ldusb drivers by
7  *
8  * Copyright (C) 2004 Greg Kroah-Hartman (greg@kroah.com)
9  * Copyright (C) 2005 Michael Hund <mhund@ld-didactic.de>
10  * 
11  * The ldusb driver was, in turn, derived from Lego USB Tower driver
12  * Copyright (C) 2003 David Glance <advidgsf@sourceforge.net>
13  *               2001-2004 Juergen Stuber <starblue@users.sourceforge.net>
14  *
15  *      This program is free software; you can redistribute it and/or
16  *      modify it under the terms of the GNU General Public License as
17  *      published by the Free Software Foundation, version 2.
18  *
19  */
20
21 /**
22  * This driver uses a ring buffer for time critical reading of
23  * interrupt in reports and provides read and write methods for
24  * raw interrupt reports.
25  */
26
27 /* Note: this currently uses a dumb ringbuffer for reads and writes.
28  * A more optimal driver would cache and kill off outstanding urbs that are 
29  * now invalid, and ignore ones that already were in the queue but valid
30  * as we only have 17 commands for the tranzport. In particular this is
31  * key for getting lights to flash in time as otherwise many commands 
32  * can be buffered up before the light change makes it to the interface.
33 */
34
35 #include <linux/kernel.h>
36 #include <linux/errno.h>
37 #include <linux/init.h>
38 #include <linux/slab.h>
39 #include <linux/module.h>
40 #include <linux/mutex.h>
41 #include <linux/version.h>
42
43 #include <asm/uaccess.h>
44 #include <linux/input.h>
45 #include <linux/usb.h>
46 #include <linux/poll.h>
47
48 /* Define these values to match your devices */
49 #define VENDOR_ID       0x165b
50 #define PRODUCT_ID      0x8101
51
52 #ifdef CONFIG_USB_DYNAMIC_MINORS
53 #define USB_TRANZPORT_MINOR_BASE        0
54 #else
55 // FIXME 176 - is the ldusb driver's minor - apply for that
56 #define USB_TRANZPORT_MINOR_BASE        176
57 #endif
58
59 /* table of devices that work with this driver */
60 static struct usb_device_id usb_tranzport_table [] = {
61         { USB_DEVICE(VENDOR_ID, PRODUCT_ID) },
62         { }                                     /* Terminating entry */
63 };
64 MODULE_DEVICE_TABLE(usb, usb_tranzport_table);
65 MODULE_VERSION("0.29");
66 MODULE_AUTHOR("Mike Taht <m@taht.net>");
67 MODULE_DESCRIPTION("Tranzport USB Driver");
68 MODULE_LICENSE("GPL");
69 MODULE_SUPPORTED_DEVICE("Frontier Designs Control Surface");
70
71
72 /* make this work on older kernel versions */
73
74 #if LINUX_VERSION_CODE < KERNEL_VERSION(2, 6, 19)
75
76 /**
77  * usb_endpoint_dir_out - check if the endpoint has OUT direction
78  * @epd: endpoint to be checked
79  *
80  * Returns true if the endpoint is of type OUT, otherwise it returns false.
81  */
82
83 static inline int usb_endpoint_dir_out(const struct usb_endpoint_descriptor *epd)
84 {
85        return ((epd->bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_DIR_OUT);
86 }
87
88 static inline int usb_endpoint_dir_in(const struct usb_endpoint_descriptor *epd)
89 {
90        return ((epd->bEndpointAddress & USB_ENDPOINT_DIR_MASK) == USB_DIR_IN);
91 }
92
93
94 /**
95  * usb_endpoint_xfer_int - check if the endpoint has interrupt transfer type
96  * @epd: endpoint to be checked
97  *
98  * Returns true if the endpoint is of type interrupt, otherwise it returns
99  * false.
100  */
101 static inline int usb_endpoint_xfer_int(const struct usb_endpoint_descriptor *epd)
102 {
103        return ((epd->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
104                USB_ENDPOINT_XFER_INT);
105 }
106
107
108 /**
109  * usb_endpoint_is_int_in - check if the endpoint is interrupt IN
110  * @epd: endpoint to be checked
111  *
112  * Returns true if the endpoint has interrupt transfer type and IN direction,
113  * otherwise it returns false.
114  */
115
116 static inline int usb_endpoint_is_int_in(const struct usb_endpoint_descriptor *epd)
117 {
118        return (usb_endpoint_xfer_int(epd) && usb_endpoint_dir_in(epd));
119 }
120
121 /**
122  * usb_endpoint_is_int_out - check if the endpoint is interrupt OUT
123  * @epd: endpoint to be checked
124  *
125  * Returns true if the endpoint has interrupt transfer type and OUT direction,
126  * otherwise it returns false.
127  */
128
129 static inline int usb_endpoint_is_int_out(const struct usb_endpoint_descriptor *epd)
130 {
131        return (usb_endpoint_xfer_int(epd) && usb_endpoint_dir_out(epd));
132 }
133
134 #endif /* older kernel versions */
135
136 /* These two aren't done yet */
137
138 #define SUPPRESS_EXTRA_ONLINE_EVENTS 0
139 #define BUFFERED_WRITES 0
140
141 #define SUPPRESS_EXTRA_OFFLINE_EVENTS 1
142 #define COMPRESS_WHEEL_EVENTS 1
143 #define BUFFERED_READS 1
144 #define RING_BUFFER_SIZE 1000
145 #define WRITE_BUFFER_SIZE 34
146 #define TRANZPORT_USB_TIMEOUT 10
147
148
149 static int debug = 0;
150
151 /* Use our own dbg macro */
152 #define dbg_info(dev, format, arg...) do { if (debug) dev_info(dev , format , ## arg); } while (0)
153
154 /* Module parameters */
155
156 module_param(debug, int, S_IRUGO | S_IWUSR);
157 MODULE_PARM_DESC(debug, "Debug enabled or not");
158
159 /* All interrupt in transfers are collected in a ring buffer to
160  * avoid racing conditions and get better performance of the driver.
161  */
162
163 static int ring_buffer_size = RING_BUFFER_SIZE;
164
165 module_param(ring_buffer_size, int,  S_IRUGO);
166 MODULE_PARM_DESC(ring_buffer_size, "Read ring buffer size in reports");
167
168 /* The write_buffer can one day contain more than one interrupt out transfer.
169  */
170 static int write_buffer_size = WRITE_BUFFER_SIZE;
171 module_param(write_buffer_size, int,  S_IRUGO);
172 MODULE_PARM_DESC(write_buffer_size, "Write buffer size");
173
174 /* 
175  * Increase the interval for debugging purposes.
176  * or set to 1 to use the standard interval from the endpoint descriptors.
177  */
178
179 static int min_interrupt_in_interval = TRANZPORT_USB_TIMEOUT;
180 module_param(min_interrupt_in_interval, int, 0);
181 MODULE_PARM_DESC(min_interrupt_in_interval, "Minimum interrupt in interval in ms");
182
183 static int min_interrupt_out_interval = TRANZPORT_USB_TIMEOUT;
184 module_param(min_interrupt_out_interval, int, 0);
185 MODULE_PARM_DESC(min_interrupt_out_interval, "Minimum interrupt out interval in ms");
186
187 struct tranzport_cmd {
188     unsigned char cmd[8];
189 };
190
191 /* Structure to hold all of our device specific stuff */
192 struct usb_tranzport {
193         struct semaphore        sem;            /* locks this structure */
194         struct usb_interface*   intf;           /* save off the usb interface pointer */
195
196         int                     open_count;     /* number of times this port has been opened */
197
198         struct tranzport_cmd    (*ring_buffer)[RING_BUFFER_SIZE]; /* just make c happy */
199         unsigned int            ring_head;
200         unsigned int            ring_tail;
201
202         wait_queue_head_t       read_wait;
203         wait_queue_head_t       write_wait;
204
205         unsigned char*          interrupt_in_buffer;
206         struct usb_endpoint_descriptor* interrupt_in_endpoint;
207         struct urb*             interrupt_in_urb;
208         int                     interrupt_in_interval;
209         size_t                  interrupt_in_endpoint_size;
210         int                     interrupt_in_running;
211         int                     interrupt_in_done;
212
213         char*                   interrupt_out_buffer;
214         struct usb_endpoint_descriptor* interrupt_out_endpoint;
215         struct urb*             interrupt_out_urb;
216         int                     interrupt_out_interval;
217         size_t                  interrupt_out_endpoint_size;
218         int                     interrupt_out_busy;
219
220         /* Sysfs support - most of these are not hooked up yet */
221
222     int event; /* alternate interface to events */
223     int wheel; /* - for negative, 0 for none, + for positive */
224     int lights; 
225     unsigned char dump_state; /* 0 if disabled 1 if enabled */
226     unsigned char enable; /* 0 if disabled 1 if enabled */
227     unsigned char offline; /* if the device is out of range or asleep */
228     unsigned char compress_wheel; /* flag to compress wheel events */
229     unsigned char  LightRecord;
230     unsigned char  LightTrackrec;
231     unsigned char  LightTrackmute;
232     unsigned char  LightTracksolo;
233     unsigned char  LightAnysolo;
234     unsigned char  LightLoop;
235     unsigned char  LightPunch;
236     unsigned char  last_cmd[8];
237     unsigned char  screen[40]; // We'll also have cells
238         
239 };
240
241 /* prevent races between open() and disconnect() */
242 static DEFINE_MUTEX(disconnect_mutex);
243
244 static struct usb_driver usb_tranzport_driver;
245
246 /**
247  *      usb_tranzport_abort_transfers
248  *      aborts transfers and frees associated data structures
249  */
250 static void usb_tranzport_abort_transfers(struct usb_tranzport *dev)
251 {
252         /* shutdown transfer */
253         if (dev->interrupt_in_running) {
254                 dev->interrupt_in_running = 0;
255                 if (dev->intf)
256                         usb_kill_urb(dev->interrupt_in_urb);
257         }
258         if (dev->interrupt_out_busy)
259                 if (dev->intf)
260                         usb_kill_urb(dev->interrupt_out_urb);
261 }
262
263 #define show_set_light(value)   \
264 static ssize_t show_##value(struct device *dev, struct device_attribute *attr, char *buf)               \
265 {                                                                       \
266         struct usb_interface *intf = to_usb_interface(dev);             \
267         struct usb_tranzport *t = usb_get_intfdata(intf);                       \
268                                                                         \
269         return sprintf(buf, "%d\n", t->value);                  \
270 }                                                                       \
271 static ssize_t set_##value(struct device *dev, struct device_attribute *attr, const char *buf, size_t count)    \
272 {                                                                       \
273         struct usb_interface *intf = to_usb_interface(dev);             \
274         struct usb_tranzport *t = usb_get_intfdata(intf);                       \
275         int temp = simple_strtoul(buf, NULL, 10);                       \
276                                                                         \
277         t->value = temp;                                                \
278         return count;                                                   \
279 }                                                                       \
280 static DEVICE_ATTR(value, S_IWUGO | S_IRUGO, show_##value, set_##value);
281
282 show_set_light(LightRecord);
283 show_set_light(LightTrackrec);
284 show_set_light(LightTrackmute);
285 show_set_light(LightTracksolo);
286 show_set_light(LightAnysolo);
287 show_set_light(LightLoop);
288 show_set_light(LightPunch);
289
290 show_set_light(enable);
291 show_set_light(offline);
292 show_set_light(compress_wheel);
293 show_set_light(dump_state);
294
295 #define show_set_int(value)     \
296 static ssize_t show_##value(struct device *dev, struct device_attribute *attr, char *buf)               \
297 {                                                                       \
298         struct usb_interface *intf = to_usb_interface(dev);             \
299         struct usb_tranzport *t = usb_get_intfdata(intf);                       \
300                                                                         \
301         return sprintf(buf, "%d\n", t->value);                  \
302 }                                                                       \
303 static ssize_t set_##value(struct device *dev, struct device_attribute *attr, const char *buf, size_t count)    \
304 {                                                                       \
305         struct usb_interface *intf = to_usb_interface(dev);             \
306         struct usb_tranzport *t = usb_get_intfdata(intf);                       \
307         int temp = simple_strtoul(buf, NULL, 10);                       \
308                                                                         \
309         t->value = temp;                                                \
310         return count;                                                   \
311 }                                                                       \
312 static DEVICE_ATTR(value, S_IWUGO | S_IRUGO, show_##value, set_##value);
313
314 show_set_int(wheel);
315 show_set_int(event);
316
317 #define show_set_cmd(value)     \
318 static ssize_t show_##value(struct device *dev, struct device_attribute *attr, char *buf)               \
319 {                                                                       \
320         struct usb_interface *intf = to_usb_interface(dev);             \
321         struct usb_tranzport *t = usb_get_intfdata(intf);                       \
322                                                                         \
323         return sprintf(buf, "%d\n", t->value);                  \
324 }                                                                       \
325 static ssize_t set_##value(struct device *dev, struct device_attribute *attr, const char *buf, size_t count)    \
326 {                                                                       \
327         struct usb_interface *intf = to_usb_interface(dev);             \
328         struct usb_tranzport *t = usb_get_intfdata(intf);                       \
329         int temp = simple_strtoul(buf, NULL, 10);                       \
330                                                                         \
331         t->value = temp;                                                \
332         return count;                                                   \
333 }                                                                       \
334 static DEVICE_ATTR(value, S_IWUGO | S_IRUGO, show_##value, set_##value);
335
336
337
338
339 /**
340  *      usb_tranzport_delete
341  */
342 static void usb_tranzport_delete(struct usb_tranzport *dev)
343 {
344         usb_tranzport_abort_transfers(dev);
345         /*  This is just too twisted to be correct */
346         if(dev->intf != NULL) {
347         device_remove_file(&dev->intf->dev, &dev_attr_LightRecord);
348         device_remove_file(&dev->intf->dev, &dev_attr_LightTrackrec);
349         device_remove_file(&dev->intf->dev, &dev_attr_LightTrackmute);
350         device_remove_file(&dev->intf->dev, &dev_attr_LightTracksolo);
351         device_remove_file(&dev->intf->dev, &dev_attr_LightTrackmute);
352         device_remove_file(&dev->intf->dev, &dev_attr_LightAnysolo);
353         device_remove_file(&dev->intf->dev, &dev_attr_LightLoop);
354         device_remove_file(&dev->intf->dev, &dev_attr_LightPunch);
355         device_remove_file(&dev->intf->dev, &dev_attr_wheel);
356         device_remove_file(&dev->intf->dev, &dev_attr_enable);
357         device_remove_file(&dev->intf->dev, &dev_attr_event);
358         device_remove_file(&dev->intf->dev, &dev_attr_offline);
359         device_remove_file(&dev->intf->dev, &dev_attr_compress_wheel);
360
361         device_remove_file(&dev->intf->dev, &dev_attr_dump_state);
362         }
363
364         /* free data structures */
365         usb_free_urb(dev->interrupt_in_urb);
366         usb_free_urb(dev->interrupt_out_urb);
367         kfree(dev->ring_buffer);
368         kfree(dev->interrupt_in_buffer);
369         kfree(dev->interrupt_out_buffer);
370         kfree(dev);
371 }
372
373 /**
374  *      usb_tranzport_interrupt_in_callback
375  */
376
377 static void usb_tranzport_interrupt_in_callback(struct urb *urb)
378 {
379         struct usb_tranzport *dev = urb->context;
380         unsigned int next_ring_head;
381         int retval = -1;
382
383         if (urb->status) {
384                 if (urb->status == -ENOENT ||
385                     urb->status == -ECONNRESET ||
386                     urb->status == -ESHUTDOWN) {
387                         goto exit;
388                 } else {
389                         dbg_info(&dev->intf->dev, "%s: nonzero status received: %d\n",
390                                  __FUNCTION__, urb->status);
391                         goto resubmit; /* maybe we can recover */
392                 }
393         }
394     
395         if (urb->actual_length != 8) {
396                 dev_warn(&dev->intf->dev,
397                          "Urb length was %d bytes!! Do something intelligent \n", urb->actual_length); 
398         } else {
399                 dbg_info(&dev->intf->dev, "%s: received: %02x%02x%02x%02x%02x%02x%02x%02x\n",
400                          __FUNCTION__, dev->interrupt_in_buffer[0],dev->interrupt_in_buffer[1],dev->interrupt_in_buffer[2],dev->interrupt_in_buffer[3],dev->interrupt_in_buffer[4],dev->interrupt_in_buffer[5],dev->interrupt_in_buffer[6],dev->interrupt_in_buffer[7]);
401 #if SUPPRESS_EXTRA_OFFLINE_EVENTS
402                 if(dev->offline == 2 && dev->interrupt_in_buffer[1] == 0xff) { goto resubmit; }
403                 if(dev->offline == 1 && dev->interrupt_in_buffer[1] == 0xff) { dev->offline = 2; goto resubmit; }
404
405 /* Always pass one offline event up the stack */
406                 if(dev->offline > 0 && dev->interrupt_in_buffer[1] != 0xff) { dev->offline = 0; }
407                 if(dev->offline == 0 && dev->interrupt_in_buffer[1] == 0xff) { dev->offline = 1; }
408                         
409 #endif 
410                 dbg_info(&dev->intf->dev, "%s: head, tail are %x, %x\n", __FUNCTION__,dev->ring_head,dev->ring_tail);
411
412                 next_ring_head = (dev->ring_head+1) % ring_buffer_size;
413         
414                 if (next_ring_head != dev->ring_tail) {
415                         memcpy(&((*dev->ring_buffer)[dev->ring_head]), dev->interrupt_in_buffer, urb->actual_length);
416                         dev->ring_head = next_ring_head;
417                         retval = 0;
418                         memset(dev->interrupt_in_buffer, 0, urb->actual_length);
419                 } else {
420                         dev_warn(&dev->intf->dev,
421                                  "Ring buffer overflow, %d bytes dropped\n",
422                                  urb->actual_length);
423                         memset(dev->interrupt_in_buffer, 0, urb->actual_length);
424                 }
425         } 
426
427 resubmit:
428         /* resubmit if we're still running */
429         if (dev->interrupt_in_running && dev->intf) {
430                 retval = usb_submit_urb(dev->interrupt_in_urb, GFP_ATOMIC); 
431                 if (retval)
432                         dev_err(&dev->intf->dev,
433                                 "usb_submit_urb failed (%d)\n", retval);
434         }
435     
436 exit:
437         dev->interrupt_in_done = 1;
438         wake_up_interruptible(&dev->read_wait);
439 }
440
441 /**
442  *      usb_tranzport_interrupt_out_callback
443  */
444 static void usb_tranzport_interrupt_out_callback(struct urb *urb)
445 {
446         struct usb_tranzport *dev = urb->context;
447
448         /* sync/async ::g_unlink faults aren't errors */
449         if (urb->status && !(urb->status == -ENOENT ||
450                              urb->status == -ECONNRESET ||
451                              urb->status == -ESHUTDOWN))
452                 dbg_info(&dev->intf->dev,
453                          "%s - nonzero write interrupt status received: %d\n",
454                          __FUNCTION__, urb->status);
455
456         dev->interrupt_out_busy = 0;
457         wake_up_interruptible(&dev->write_wait);
458 }
459
460 /**
461  *      usb_tranzport_open
462  */
463 static int usb_tranzport_open(struct inode *inode, struct file *file)
464 {
465         struct usb_tranzport *dev;
466         int subminor;
467         int retval = 0;
468         struct usb_interface *interface;
469
470         nonseekable_open(inode, file);
471         subminor = iminor(inode);
472
473         mutex_lock(&disconnect_mutex);
474
475         interface = usb_find_interface(&usb_tranzport_driver, subminor);
476
477         if (!interface) {
478                 err("%s - error, can't find device for minor %d\n",
479                      __FUNCTION__, subminor);
480                 retval = -ENODEV;
481                 goto unlock_disconnect_exit;
482         }
483
484         dev = usb_get_intfdata(interface);
485
486         if (!dev) {
487                 retval = -ENODEV;
488                 goto unlock_disconnect_exit;
489         }
490
491         /* lock this device */
492         if (down_interruptible(&dev->sem)) {
493                 retval = -ERESTARTSYS;
494                 goto unlock_disconnect_exit;
495         }
496
497         /* allow opening only once */
498         if (dev->open_count) {
499                 retval = -EBUSY;
500                 goto unlock_exit;
501         }
502         dev->open_count = 1;
503
504         /* initialize in direction */
505         dev->ring_head = 0;
506         dev->ring_tail = 0;
507         usb_fill_int_urb(dev->interrupt_in_urb,
508                          interface_to_usbdev(interface),
509                          usb_rcvintpipe(interface_to_usbdev(interface),
510                                         dev->interrupt_in_endpoint->bEndpointAddress),
511                          dev->interrupt_in_buffer,
512                          dev->interrupt_in_endpoint_size,
513                          usb_tranzport_interrupt_in_callback,
514                          dev,
515                          dev->interrupt_in_interval);
516
517         dev->interrupt_in_running = 1;
518         dev->interrupt_in_done = 0;
519         dev->enable = 1;
520         dev->offline = 0;
521         dev->compress_wheel = 1;
522
523         retval = usb_submit_urb(dev->interrupt_in_urb, GFP_KERNEL);
524         if (retval) {
525                 dev_err(&interface->dev, "Couldn't submit interrupt_in_urb %d\n", retval);
526                 dev->interrupt_in_running = 0;
527                 dev->open_count = 0;
528                 goto unlock_exit;
529         }
530
531         /* save device in the file's private structure */
532         file->private_data = dev;
533
534
535 unlock_exit:
536         up(&dev->sem);
537
538 unlock_disconnect_exit:
539         mutex_unlock(&disconnect_mutex);
540
541         return retval;
542 }
543
544 /**
545  *      usb_tranzport_release
546  */
547 static int usb_tranzport_release(struct inode *inode, struct file *file)
548 {
549         struct usb_tranzport *dev;
550         int retval = 0;
551
552         dev = file->private_data;
553
554         if (dev == NULL) {
555                 retval = -ENODEV;
556                 goto exit;
557         }
558
559         if (down_interruptible(&dev->sem)) {
560                 retval = -ERESTARTSYS;
561                 goto exit;
562         }
563
564         if (dev->open_count != 1) {
565                 retval = -ENODEV;
566                 goto unlock_exit;
567         }
568
569         if (dev->intf == NULL) {
570                 /* the device was unplugged before the file was released */
571                 up(&dev->sem);
572                 /* unlock here as usb_tranzport_delete frees dev */
573                 usb_tranzport_delete(dev);
574                 retval = -ENODEV;
575                 goto exit;
576         }
577
578         /* wait until write transfer is finished */
579         if (dev->interrupt_out_busy)
580                 wait_event_interruptible_timeout(dev->write_wait, !dev->interrupt_out_busy, 2 * HZ);
581         usb_tranzport_abort_transfers(dev);
582         dev->open_count = 0;
583
584 unlock_exit:
585         up(&dev->sem);
586
587 exit:
588         return retval;
589 }
590
591 /**
592  *      usb_tranzport_poll
593  */
594 static unsigned int usb_tranzport_poll(struct file *file, poll_table *wait)
595 {
596         struct usb_tranzport *dev;
597         unsigned int mask = 0;
598
599         dev = file->private_data;
600
601         poll_wait(file, &dev->read_wait, wait);
602         poll_wait(file, &dev->write_wait, wait);
603
604         if (dev->ring_head != dev->ring_tail)
605                 mask |= POLLIN | POLLRDNORM;
606         if (!dev->interrupt_out_busy)
607                 mask |= POLLOUT | POLLWRNORM;
608
609         return mask;
610 }
611
612 /**
613  *      usb_tranzport_read
614  */
615 static ssize_t usb_tranzport_read(struct file *file, char __user *buffer, size_t count,
616                            loff_t *ppos)
617 {
618         struct usb_tranzport *dev;
619         size_t bytes_to_read;
620         int retval = 0;
621
622 #if BUFFERED_READS
623         int c = 0;
624 #endif
625
626 #if COMPRESS_WHEEL_EVENTS
627         signed char oldwheel;
628         signed char newwheel;
629         int cancompress = 1;
630         int next_tail;
631 #endif
632
633 /* do I have such a thing as a null event? */
634
635         dev = file->private_data;
636
637         /* verify that we actually have some data to read */
638         if (count == 0)
639                 goto exit;
640
641         /* lock this object */
642         if (down_interruptible(&dev->sem)) {
643                 retval = -ERESTARTSYS;
644                 goto exit;
645         }
646
647         /* verify that the device wasn't unplugged */
648         if (dev->intf == NULL) {
649                 retval = -ENODEV;
650                 err("No device or device unplugged %d\n", retval);
651                 goto unlock_exit;
652         }
653
654         while (dev->ring_head == dev->ring_tail) {
655
656                 if (file->f_flags & O_NONBLOCK) {
657                         retval = -EAGAIN;
658                         goto unlock_exit;
659                 }
660                 // atomic_cmp_exchange(&dev->interrupt_in_done,0,0);
661                 dev->interrupt_in_done = 0 ; /* tiny race - FIXME: make atomic? */
662                 retval = wait_event_interruptible(dev->read_wait, dev->interrupt_in_done);
663                 if (retval < 0) {
664                         goto unlock_exit;
665                 } 
666         }
667
668         dbg_info(&dev->intf->dev, "%s: copying to userspace: %02x%02x%02x%02x%02x%02x%02x%02x\n",
669                          __FUNCTION__, (*dev->ring_buffer)[dev->ring_tail].cmd[0],(*dev->ring_buffer)[dev->ring_tail].cmd[1],(*dev->ring_buffer)[dev->ring_tail].cmd[2],(*dev->ring_buffer)[dev->ring_tail].cmd[3],(*dev->ring_buffer)[dev->ring_tail].cmd[4],(*dev->ring_buffer)[dev->ring_tail].cmd[5],(*dev->ring_buffer)[dev->ring_tail].cmd[6],(*dev->ring_buffer)[dev->ring_tail].cmd[7]);
670
671 #if BUFFERED_READS
672            c = 0;
673            while((c < count) && (dev->ring_tail != dev->ring_head)) {
674
675 /* This started off in the lower level service routine, and I moved it here. Then my brain died. Not done yet. */
676 #if COMPRESS_WHEEL_EVENTS 
677                 next_tail = (dev->ring_tail+1) % ring_buffer_size;
678                 if(dev->compress_wheel) cancompress = 1;
679                 while(dev->ring_head != next_tail && cancompress == 1 ) { 
680                         newwheel = (*dev->ring_buffer)[next_tail].cmd[6];
681                         oldwheel = (*dev->ring_buffer)[dev->ring_tail].cmd[6];
682                         // if both are wheel events, and no buttons have changes (FIXME, do I have to check?),
683                         // and we are the same sign, we can compress +- 7F
684                         // FIXME: saner check for overflow! - max of +- 7F
685                         // FIXME the math is wrong for going in reverse, actually, as the midi spec doesn't allow signed chars
686
687         dbg_info(&dev->intf->dev, "%s: trying to compress: %02x%02x%02x%02x%02x %02x %02x %02x\n",
688                          __FUNCTION__, (*dev->ring_buffer)[dev->ring_tail].cmd[0],(*dev->ring_buffer)[dev->ring_tail].cmd[1],(*dev->ring_buffer)[dev->ring_tail].cmd[2],(*dev->ring_buffer)[dev->ring_tail].cmd[3],(*dev->ring_buffer)[dev->ring_tail].cmd[4],(*dev->ring_buffer)[dev->ring_tail].cmd[5],(*dev->ring_buffer)[dev->ring_tail].cmd[6],(*dev->ring_buffer)[dev->ring_tail].cmd[7]);
689
690                         
691                         if(((*dev->ring_buffer)[dev->ring_tail].cmd[6] != 0 && 
692                             (*dev->ring_buffer)[next_tail].cmd[6] != 0 ) && 
693                                 ((newwheel > 0 && oldwheel > 0) || 
694                                 (newwheel < 0 && oldwheel < 0)) &&
695                                 ((*dev->ring_buffer)[dev->ring_tail].cmd[2] == (*dev->ring_buffer)[next_tail].cmd[2]) &&
696                                 ((*dev->ring_buffer)[dev->ring_tail].cmd[3] == (*dev->ring_buffer)[next_tail].cmd[3]) &&
697                                 ((*dev->ring_buffer)[dev->ring_tail].cmd[4] == (*dev->ring_buffer)[next_tail].cmd[4]) &&
698                                 ((*dev->ring_buffer)[dev->ring_tail].cmd[5] == (*dev->ring_buffer)[next_tail].cmd[5]))
699  {
700         dbg_info(&dev->intf->dev, "%s: should compress: %02x%02x%02x%02x%02x%02x%02x%02x\n",
701                          __FUNCTION__, (*dev->ring_buffer)[dev->ring_tail].cmd[0],(*dev->ring_buffer)[dev->ring_tail].cmd[1],(*dev->ring_buffer)[dev->ring_tail].cmd[2],(*dev->ring_buffer)[dev->ring_tail].cmd[3],(*dev->ring_buffer)[dev->ring_tail].cmd[4],(*dev->ring_buffer)[dev->ring_tail].cmd[5],(*dev->ring_buffer)[dev->ring_tail].cmd[6],(*dev->ring_buffer)[dev->ring_tail].cmd[7]);
702
703                                 newwheel += oldwheel;
704                                 if(oldwheel > 0 && !(newwheel > 0)) {
705                                         newwheel = 0x7f; 
706                                         cancompress = 0;
707                                 }
708                                 if(oldwheel < 0 && !(newwheel < 0)) {
709                                         newwheel = 0x80; 
710                                         cancompress = 0;
711                                 }
712
713                                 (*dev->ring_buffer)[next_tail].cmd[6] = newwheel; 
714                                 dev->ring_tail = next_tail;
715                                 next_tail = (dev->ring_tail+1) % ring_buffer_size;
716                         } else {
717                                 cancompress = 0;
718                         }
719                 }
720 #endif /* COMPRESS_WHEEL_EVENTS */
721
722                 if (copy_to_user(&buffer[c], &(*dev->ring_buffer)[dev->ring_tail], 8)) {
723                         retval = -EFAULT;
724                         goto unlock_exit;
725                 }
726                 
727                 dev->ring_tail = (dev->ring_tail+1) % ring_buffer_size;
728                 c+=8;
729                 dbg_info(&dev->intf->dev, "%s: head, tail are %x, %x\n", __FUNCTION__,dev->ring_head,dev->ring_tail);
730            }
731            retval = c;
732            
733 #else
734         if (copy_to_user(buffer, &(*dev->ring_buffer)[dev->ring_tail], 8)) {
735                 retval = -EFAULT;
736                 goto unlock_exit;
737         }
738
739         dev->ring_tail = (dev->ring_tail+1) % ring_buffer_size;
740         dbg_info(&dev->intf->dev, "%s: head, tail are %x, %x\n", __FUNCTION__,dev->ring_head,dev->ring_tail);
741
742         retval = 8;
743 #endif /* BUFFERED_READS */
744
745 unlock_exit:
746         /* unlock the device */
747         up(&dev->sem);
748
749 exit:
750         return retval;
751 }
752
753 /**
754  *      usb_tranzport_write
755  */
756 static ssize_t usb_tranzport_write(struct file *file, const char __user *buffer,
757                             size_t count, loff_t *ppos)
758 {
759         struct usb_tranzport *dev;
760         size_t bytes_to_write;
761         int retval = 0;
762
763         dev = file->private_data;
764
765         /* verify that we actually have some data to write */
766         if (count == 0)
767                 goto exit;
768
769         /* lock this object */
770         if (down_interruptible(&dev->sem)) {
771                 retval = -ERESTARTSYS;
772                 goto exit;
773         }
774
775         /* verify that the device wasn't unplugged */
776         if (dev->intf == NULL) {
777                 retval = -ENODEV;
778                 err("No device or device unplugged %d\n", retval);
779                 goto unlock_exit;
780         }
781
782         /* wait until previous transfer is finished */
783         if (dev->interrupt_out_busy) {
784                 if (file->f_flags & O_NONBLOCK) {
785                         retval = -EAGAIN;
786                         goto unlock_exit;
787                 }
788                 retval = wait_event_interruptible(dev->write_wait, !dev->interrupt_out_busy);
789                 if (retval < 0) {
790                         goto unlock_exit;
791                 }
792         }
793
794         /* write the data into interrupt_out_buffer from userspace */
795         bytes_to_write = min(count, write_buffer_size*dev->interrupt_out_endpoint_size);
796         if (bytes_to_write < count)
797                 dev_warn(&dev->intf->dev, "Write buffer overflow, %zd bytes dropped\n",count-bytes_to_write);
798
799         dbg_info(&dev->intf->dev, "%s: count = %zd, bytes_to_write = %zd\n", __FUNCTION__, count, bytes_to_write);
800
801         if (copy_from_user(dev->interrupt_out_buffer, buffer, bytes_to_write)) {
802                 retval = -EFAULT;
803                 goto unlock_exit;
804         }
805
806         if (dev->interrupt_out_endpoint == NULL) {
807                 err("Endpoint should not be be null! \n");
808                 goto unlock_exit;
809         }
810
811         /* send off the urb */
812         usb_fill_int_urb(dev->interrupt_out_urb,
813                          interface_to_usbdev(dev->intf),
814                          usb_sndintpipe(interface_to_usbdev(dev->intf),
815                                         dev->interrupt_out_endpoint->bEndpointAddress),
816                          dev->interrupt_out_buffer,
817                          bytes_to_write,
818                          usb_tranzport_interrupt_out_callback,
819                          dev,
820                          dev->interrupt_out_interval);
821
822         dev->interrupt_out_busy = 1;
823         wmb();
824
825         retval = usb_submit_urb(dev->interrupt_out_urb, GFP_KERNEL);
826         if (retval) {
827                 dev->interrupt_out_busy = 0;
828                 err("Couldn't submit interrupt_out_urb %d\n", retval);
829                 goto unlock_exit;
830         }
831         retval = bytes_to_write;
832
833 unlock_exit:
834         /* unlock the device */
835         up(&dev->sem);
836
837 exit:
838         return retval;
839 }
840
841 /* file operations needed when we register this driver */
842 static const struct file_operations usb_tranzport_fops = {
843         .owner =        THIS_MODULE,
844         .read  =        usb_tranzport_read,
845         .write =        usb_tranzport_write,
846         .open =         usb_tranzport_open,
847         .release =      usb_tranzport_release,
848         .poll =         usb_tranzport_poll,
849 };
850
851 /*
852  * usb class driver info in order to get a minor number from the usb core,
853  * and to have the device registered with the driver core
854  */
855 static struct usb_class_driver usb_tranzport_class = {
856         .name =         "tranzport%d",
857         .fops =         &usb_tranzport_fops,
858         .minor_base =   USB_TRANZPORT_MINOR_BASE,
859 };
860
861
862 /**
863  *      usb_tranzport_probe
864  *
865  *      Called by the usb core when a new device is connected that it thinks
866  *      this driver might be interested in.
867  */
868 static int usb_tranzport_probe(struct usb_interface *intf, const struct usb_device_id *id)
869 {
870         struct usb_device *udev = interface_to_usbdev(intf);
871         struct usb_tranzport *dev = NULL;
872         struct usb_host_interface *iface_desc;
873         struct usb_endpoint_descriptor *endpoint;
874         int i;
875         int true_size;
876         int retval = -ENOMEM;
877
878         /* allocate memory for our device state and intialize it */
879
880         dev = kzalloc(sizeof(*dev), GFP_KERNEL);
881         if (dev == NULL) {
882                 dev_err(&intf->dev, "Out of memory\n");
883                 goto exit;
884         }
885         init_MUTEX(&dev->sem);
886         dev->intf = intf;
887         init_waitqueue_head(&dev->read_wait);
888         init_waitqueue_head(&dev->write_wait);
889
890         iface_desc = intf->cur_altsetting;
891
892         /* set up the endpoint information */
893         for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {
894                 endpoint = &iface_desc->endpoint[i].desc;
895
896                 if (usb_endpoint_is_int_in(endpoint))
897                         dev->interrupt_in_endpoint = endpoint;
898
899                 if (usb_endpoint_is_int_out(endpoint))
900                         dev->interrupt_out_endpoint = endpoint;
901         }
902         if (dev->interrupt_in_endpoint == NULL) {
903                 dev_err(&intf->dev, "Interrupt in endpoint not found\n");
904                 goto error;
905         }
906         if (dev->interrupt_out_endpoint == NULL)
907                 dev_warn(&intf->dev, "Interrupt out endpoint not found (using control endpoint instead)\n");
908
909
910         dev->interrupt_in_endpoint_size = le16_to_cpu(dev->interrupt_in_endpoint->wMaxPacketSize);
911
912         if (dev->interrupt_in_endpoint_size != 8)
913             dev_warn(&intf->dev, "Interrupt in endpoint size is not 8!\n");
914
915         if(ring_buffer_size == 0) { ring_buffer_size = RING_BUFFER_SIZE; }
916         true_size = min(ring_buffer_size,RING_BUFFER_SIZE);
917         /* FIXME - there are more usb_alloc routines for dma correctness. Needed? */
918
919         dev->ring_buffer = kmalloc((true_size*sizeof(struct tranzport_cmd))+8, GFP_KERNEL); 
920
921         if (!dev->ring_buffer) {
922                 dev_err(&intf->dev, "Couldn't allocate ring_buffer of size %d\n",true_size);
923                 goto error;
924         }
925         dev->interrupt_in_buffer = kmalloc(dev->interrupt_in_endpoint_size, GFP_KERNEL); 
926         if (!dev->interrupt_in_buffer) {
927                 dev_err(&intf->dev, "Couldn't allocate interrupt_in_buffer\n");
928                 goto error;
929         }
930         dev->interrupt_in_urb = usb_alloc_urb(0, GFP_KERNEL);
931         if (!dev->interrupt_in_urb) {
932                 dev_err(&intf->dev, "Couldn't allocate interrupt_in_urb\n");
933                 goto error;
934         }
935         dev->interrupt_out_endpoint_size = dev->interrupt_out_endpoint ? le16_to_cpu(dev->interrupt_out_endpoint->wMaxPacketSize) :
936                                                                          udev->descriptor.bMaxPacketSize0;
937
938         if (dev->interrupt_out_endpoint_size !=8)
939                 dev_warn(&intf->dev, "Interrupt out endpoint size is not 8!)\n");
940
941         dev->interrupt_out_buffer = kmalloc(write_buffer_size*dev->interrupt_out_endpoint_size, GFP_KERNEL);
942         if (!dev->interrupt_out_buffer) {
943                 dev_err(&intf->dev, "Couldn't allocate interrupt_out_buffer\n");
944                 goto error;
945         }
946         dev->interrupt_out_urb = usb_alloc_urb(0, GFP_KERNEL);
947         if (!dev->interrupt_out_urb) {
948                 dev_err(&intf->dev, "Couldn't allocate interrupt_out_urb\n");
949                 goto error;
950         }
951         dev->interrupt_in_interval = min_interrupt_in_interval > dev->interrupt_in_endpoint->bInterval ? min_interrupt_in_interval : dev->interrupt_in_endpoint->bInterval;
952         if (dev->interrupt_out_endpoint)
953                 dev->interrupt_out_interval = min_interrupt_out_interval > dev->interrupt_out_endpoint->bInterval ? min_interrupt_out_interval : dev->interrupt_out_endpoint->bInterval;
954
955         /* we can register the device now, as it is ready */
956         usb_set_intfdata(intf, dev);
957
958         retval = usb_register_dev(intf, &usb_tranzport_class);
959         if (retval) {
960                 /* something prevented us from registering this driver */
961                 dev_err(&intf->dev, "Not able to get a minor for this device.\n");
962                 usb_set_intfdata(intf, NULL);
963                 goto error;
964         }
965
966         if((retval = device_create_file(&intf->dev, &dev_attr_LightRecord))) goto error;
967         if((retval = device_create_file(&intf->dev, &dev_attr_LightTrackrec))) goto error;
968         if((retval = device_create_file(&intf->dev, &dev_attr_LightTrackmute))) goto error;
969         if((retval = device_create_file(&intf->dev, &dev_attr_LightTracksolo))) goto error;
970         if((retval = device_create_file(&intf->dev, &dev_attr_LightAnysolo))) goto error;
971         if((retval = device_create_file(&intf->dev, &dev_attr_LightLoop))) goto error;
972         if((retval = device_create_file(&intf->dev, &dev_attr_LightPunch))) goto error;
973         if((retval = device_create_file(&intf->dev, &dev_attr_wheel))) goto error;
974         if((retval = device_create_file(&intf->dev, &dev_attr_event))) goto error;
975         if((retval = device_create_file(&intf->dev, &dev_attr_dump_state))) goto error;
976         if((retval = device_create_file(&intf->dev, &dev_attr_compress_wheel))) goto error;
977         if((retval = device_create_file(&intf->dev, &dev_attr_enable))) goto error;
978         if((retval = device_create_file(&intf->dev, &dev_attr_offline))) goto error;
979
980         /* let the user know what node this device is now attached to */
981         dev_info(&intf->dev, "Tranzport Device #%d now attached to major %d minor %d\n",
982                 (intf->minor - USB_TRANZPORT_MINOR_BASE), USB_MAJOR, intf->minor);
983
984 exit:
985         return retval;
986
987 error:
988         usb_tranzport_delete(dev);
989
990         return retval;
991 }
992
993 /**
994  *      usb_tranzport_disconnect
995  *
996  *      Called by the usb core when the device is removed from the system.
997  */
998 static void usb_tranzport_disconnect(struct usb_interface *intf)
999 {
1000         struct usb_tranzport *dev;
1001         int minor;
1002
1003         /* FIXME: The skel code calls lock_kernel here, doesn't use a mutex, needed? */
1004         mutex_lock(&disconnect_mutex);
1005
1006         dev = usb_get_intfdata(intf);
1007         usb_set_intfdata(intf, NULL);
1008
1009         down(&dev->sem);
1010
1011         minor = intf->minor;
1012
1013         /* give back our minor */
1014         usb_deregister_dev(intf, &usb_tranzport_class);
1015
1016         /* if the device is not opened, then we clean up right now */
1017         if (!dev->open_count) {
1018                 up(&dev->sem);
1019                 usb_tranzport_delete(dev);
1020         } else {
1021                 dev->intf = NULL;
1022                 up(&dev->sem);
1023         }
1024
1025         mutex_unlock(&disconnect_mutex);
1026
1027         dev_info(&intf->dev, "Tranzport Surface #%d now disconnected\n",
1028                  (minor - USB_TRANZPORT_MINOR_BASE));
1029 }
1030
1031 /* usb specific object needed to register this driver with the usb subsystem */
1032 static struct usb_driver usb_tranzport_driver = {
1033         .name =         "tranzport",
1034         .probe =        usb_tranzport_probe,
1035         .disconnect =   usb_tranzport_disconnect,
1036         .id_table =     usb_tranzport_table,
1037 };
1038
1039 /**
1040  *      usb_tranzport_init
1041  */
1042 static int __init usb_tranzport_init(void)
1043 {
1044         int retval;
1045
1046         /* register this driver with the USB subsystem */
1047         retval = usb_register(&usb_tranzport_driver);
1048         if (retval)
1049                 err("usb_register failed for the "__FILE__" driver. Error number %d\n", retval);
1050
1051         return retval;
1052 }
1053
1054 /**
1055  *      usb_tranzport_exit
1056  */
1057 static void __exit usb_tranzport_exit(void)
1058 {
1059         /* deregister this driver with the USB subsystem */
1060         usb_deregister(&usb_tranzport_driver);
1061 }
1062
1063 module_init(usb_tranzport_init);
1064 module_exit(usb_tranzport_exit);
1065