Staging: cpc-usb: add driver to the build
[linux-2.6] / drivers / staging / cpc-usb / cpc-usb_drv.c
1 /*
2  * CPC-USB CAN Interface Kernel Driver
3  *
4  * Copyright (C) 2004-2009 EMS Dr. Thomas Wuensche
5  *
6  * This program is free software; you can redistribute it and/or modify it
7  * under the terms of the GNU General Public License as published
8  * by the Free Software Foundation; version 2 of the License.
9  *
10  * This program is distributed in the hope that it will be useful, but
11  * WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License along
16  * with this program; if not, write to the Free Software Foundation, Inc.,
17  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18  */
19 #include <linux/kernel.h>
20 #include <linux/errno.h>
21 #include <linux/init.h>
22 #include <linux/slab.h>
23 #include <linux/vmalloc.h>
24 #include <linux/module.h>
25 #include <linux/poll.h>
26 #include <linux/smp_lock.h>
27 #include <linux/completion.h>
28 #include <asm/uaccess.h>
29 #include <linux/usb.h>
30
31 #include <linux/version.h>
32
33 /* usb_kill_urb has been introduced in kernel version 2.6.8 (RC2) */
34 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,8))
35 #define usb_kill_urb usb_unlink_urb
36 #endif
37
38 #ifdef CONFIG_PROC_FS
39 #   include <linux/proc_fs.h>
40 #endif
41
42 #include "cpc.h"
43
44 #include "cpc_int.h"
45 #include "cpcusb.h"
46
47 #include "sja2m16c.h"
48
49 /* Version Information */
50 #define DRIVER_AUTHOR  "Sebastian Haas <haas@ems-wuensche.com>"
51 #define DRIVER_DESC    "CPC-USB Driver for Linux Kernel 2.6"
52 #define DRIVER_VERSION CPC_DRIVER_VERSION
53
54 MODULE_AUTHOR(DRIVER_AUTHOR);
55 MODULE_DESCRIPTION(DRIVER_DESC);
56 MODULE_VERSION(DRIVER_VERSION);
57 MODULE_LICENSE("GPL v2");
58
59 /* Define these values to match your devices */
60 #define USB_CPCUSB_VENDOR_ID    0x12D6
61
62 #define USB_CPCUSB_M16C_PRODUCT_ID    0x0888
63 #define USB_CPCUSB_LPC2119_PRODUCT_ID 0x0444
64
65 #ifndef CONFIG_PROC_FS
66 #error "PROCFS needed"
67 #endif
68
69 #define CPC_USB_PROC_DIR     CPC_PROC_DIR "cpc-usb"
70
71 static struct proc_dir_entry *procDir = NULL;
72 static struct proc_dir_entry *procEntry = NULL;
73
74 /* Module parameters */
75 static int debug = 0;
76 module_param(debug, int, S_IRUGO);
77
78 /* table of devices that work with this driver */
79 static struct usb_device_id cpcusb_table[] = {
80         {USB_DEVICE(USB_CPCUSB_VENDOR_ID, USB_CPCUSB_M16C_PRODUCT_ID)},
81         {USB_DEVICE(USB_CPCUSB_VENDOR_ID, USB_CPCUSB_LPC2119_PRODUCT_ID)},
82         {}                      /* Terminating entry */
83 };
84
85 MODULE_DEVICE_TABLE(usb, cpcusb_table);
86
87 /* use to prevent kernel panic if driver is unloaded
88  * while a programm has still open the device
89  */
90 DECLARE_WAIT_QUEUE_HEAD(rmmodWq);
91 atomic_t useCount;
92
93 static CPC_USB_T *CPCUSB_Table[CPC_USB_CARD_CNT] = { 0 };
94 static unsigned int CPCUsbCnt = 0;
95
96 /* prevent races between open() and disconnect() */
97 static DECLARE_MUTEX(disconnect_sem);
98
99 /* local function prototypes */
100 static ssize_t cpcusb_read(struct file *file, char *buffer, size_t count,
101                            loff_t * ppos);
102 static ssize_t cpcusb_write(struct file *file, const char *buffer,
103                             size_t count, loff_t * ppos);
104 static unsigned int cpcusb_poll(struct file *file, poll_table * wait);
105 static int cpcusb_open(struct inode *inode, struct file *file);
106 static int cpcusb_release(struct inode *inode, struct file *file);
107
108 static int cpcusb_probe(struct usb_interface *interface,
109                         const struct usb_device_id *id);
110 static void cpcusb_disconnect(struct usb_interface *interface);
111
112 static void cpcusb_read_bulk_callback(struct urb *urb
113 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,19))
114                                            , struct pt_regs *regs
115 #endif
116 );
117 static void cpcusb_write_bulk_callback(struct urb *urb
118 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,19))
119                                            , struct pt_regs *regs
120 #endif
121 );
122 static void cpcusb_read_interrupt_callback(struct urb *urb
123 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,19))
124                                            , struct pt_regs *regs
125 #endif
126 );
127
128 static int cpcusb_setup_intrep(CPC_USB_T * card);
129
130 static struct file_operations cpcusb_fops = {
131         /*
132          * The owner field is part of the module-locking
133          * mechanism. The idea is that the kernel knows
134          * which module to increment the use-counter of
135          * BEFORE it calls the device's open() function.
136          * This also means that the kernel can decrement
137          * the use-counter again before calling release()
138          * or should the open() function fail.
139          */
140         .owner = THIS_MODULE,
141
142         .read = cpcusb_read,
143         .write = cpcusb_write,
144         .poll = cpcusb_poll,
145         .open = cpcusb_open,
146         .release = cpcusb_release,
147 };
148
149 /*
150  * usb class driver info in order to get a minor number from the usb core,
151  * and to have the device registered with devfs and the driver core
152  */
153 static struct usb_class_driver cpcusb_class = {
154         .name = "usb/cpc_usb%d",
155         .fops = &cpcusb_fops,
156 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,14))
157         .mode =
158             S_IFCHR | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH |
159             S_IWOTH,
160 #endif
161         .minor_base = CPC_USB_BASE_MNR,
162 };
163
164 /* usb specific object needed to register this driver with the usb subsystem */
165 static struct usb_driver cpcusb_driver = {
166 #if (LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,14))
167         .owner = THIS_MODULE,
168 #endif
169         .name = "cpc-usb",
170         .probe = cpcusb_probe,
171         .disconnect = cpcusb_disconnect,
172         .id_table = cpcusb_table,
173 };
174
175 static int cpcusb_create_info_output(char *buf)
176 {
177         int i = 0, j;
178
179         for (j = 0; j < CPC_USB_CARD_CNT; j++) {
180                 if (CPCUSB_Table[j]) {
181                         CPC_USB_T *card = CPCUSB_Table[j];
182                         CPC_CHAN_T *chan = card->chan;
183
184                         /* MINOR CHANNELNO BUSNO SLOTNO */
185                         i += sprintf(&buf[i], "%d %s\n", chan->minor,
186                                      card->serialNumber);
187                 }
188         }
189
190         return i;
191 }
192
193 static int cpcusb_proc_read_info(char *page, char **start, off_t off,
194                                  int count, int *eof, void *data)
195 {
196         int len = cpcusb_create_info_output(page);
197
198         if (len <= off + count)
199                 *eof = 1;
200         *start = page + off;
201         len -= off;
202         if (len > count)
203                 len = count;
204         if (len < 0)
205                 len = 0;
206
207         return len;
208 }
209
210 /*
211  * Remove CPC-USB and cleanup
212  */
213 static inline void cpcusb_delete(CPC_USB_T * card)
214 {
215         if (card) {
216                 if (card->chan) {
217                         if (card->chan->buf)
218                                 vfree(card->chan->buf);
219
220                         if (card->chan->CPCWait_q)
221                                 kfree(card->chan->CPCWait_q);
222
223                         kfree(card->chan);
224                 }
225
226                 CPCUSB_Table[card->idx] = NULL;
227                 kfree(card);
228         }
229 }
230
231 /*
232  * setup the interrupt IN endpoint of a specific CPC-USB device
233  */
234 static int cpcusb_setup_intrep(CPC_USB_T * card)
235 {
236         int retval = 0;
237         struct usb_endpoint_descriptor *ep;
238
239         ep = &card->interface->altsetting[0].endpoint[card->num_intr_in].desc;
240
241         card->intr_in_buffer[0] = 0;
242         card->free_slots = 15;  /* initial size */
243
244         /* setup the urb */
245         usb_fill_int_urb(card->intr_in_urb, card->udev,
246                          usb_rcvintpipe(card->udev, card->num_intr_in),
247                          card->intr_in_buffer,
248                          sizeof(card->intr_in_buffer),
249                          cpcusb_read_interrupt_callback,
250                          card,
251                          ep->bInterval);
252
253         card->intr_in_urb->status = 0;  /* needed! */
254
255         /* submit the urb */
256         retval = usb_submit_urb(card->intr_in_urb, GFP_KERNEL);
257
258         if (retval) {
259                 err("%s - failed submitting intr urb, error %d", __FUNCTION__, retval);
260         }
261
262         return retval;
263 }
264
265 static int cpcusb_open(struct inode *inode, struct file *file)
266 {
267         CPC_USB_T *card = NULL;
268         struct usb_interface *interface;
269         int subminor;
270         int j, retval = 0;
271
272         subminor = iminor(inode);
273
274         /* prevent disconnects */
275         down(&disconnect_sem);
276
277         interface = usb_find_interface(&cpcusb_driver, subminor);
278         if (!interface) {
279                 err("%s - error, can't find device for minor %d",
280                                 __FUNCTION__, subminor);
281                 retval = CPC_ERR_NO_INTERFACE_PRESENT;
282                 goto exit_no_device;
283         }
284
285         card = usb_get_intfdata(interface);
286         if (!card) {
287                 retval = CPC_ERR_NO_INTERFACE_PRESENT;
288                 goto exit_no_device;
289         }
290
291         /* lock this device */
292         down(&card->sem);
293
294         /* increment our usage count for the driver */
295         if (card->open) {
296                 dbg("device already opened");
297                 retval = CPC_ERR_CHANNEL_ALREADY_OPEN;
298                 goto exit_on_error;
299         }
300
301         /* save our object in the file's private structure */
302         file->private_data = card;
303         for (j = 0; j < CPC_USB_URB_CNT; j++) {
304                 usb_fill_bulk_urb(card->urbs[j].urb, card->udev,
305                                   usb_rcvbulkpipe(card->udev, card->num_bulk_in),
306                                   card->urbs[j].buffer, card->urbs[j].size,
307                                   cpcusb_read_bulk_callback, card);
308
309                 retval = usb_submit_urb(card->urbs[j].urb, GFP_KERNEL);
310
311                 if (retval) {
312                         err("%s - failed submitting read urb, error %d",
313                             __FUNCTION__, retval);
314                         retval = CPC_ERR_TRANSMISSION_FAILED;
315                         goto exit_on_error;
316                 }
317         }
318
319         info("%s - %d URB's submitted", __FUNCTION__, j);
320
321         ResetBuffer(card->chan);
322
323         cpcusb_setup_intrep(card);
324         card->open = 1;
325
326         atomic_inc(&useCount);
327
328 exit_on_error:
329         /* unlock this device */
330         up(&card->sem);
331
332 exit_no_device:
333         up(&disconnect_sem);
334
335         return retval;
336 }
337
338 static unsigned int cpcusb_poll(struct file *file, poll_table * wait)
339 {
340         CPC_USB_T *card = (CPC_USB_T *) file->private_data;
341         unsigned int retval = 0;
342
343         if (!card) {
344                 err("%s - device object lost", __FUNCTION__);
345                 return -EIO;
346         }
347
348         poll_wait(file, card->chan->CPCWait_q, wait);
349
350         if (IsBufferNotEmpty(card->chan) || !(card->present))
351                 retval |= (POLLIN | POLLRDNORM);
352
353         if (card->free_slots)
354                 retval |= (POLLOUT | POLLWRNORM);
355
356         return retval;
357 }
358
359 static int cpcusb_release(struct inode *inode, struct file *file)
360 {
361         CPC_USB_T *card = (CPC_USB_T *) file->private_data;
362         int j, retval = 0;
363
364         if (card == NULL) {
365                 dbg("%s - object is NULL", __FUNCTION__);
366                 return CPC_ERR_NO_INTERFACE_PRESENT;
367         }
368
369         /* lock our device */
370         down(&card->sem);
371
372         if (!card->open) {
373                 dbg("%s - device not opened", __FUNCTION__);
374                 retval = CPC_ERR_NO_INTERFACE_PRESENT;
375                 goto exit_not_opened;
376         }
377
378         /* if device wasn't unplugged kill all urbs */
379         if (card->present) {
380                 /* kill read urbs */
381                 for (j = 0; j < CPC_USB_URB_CNT; j++) {
382                         usb_kill_urb(card->urbs[j].urb);
383                 }
384
385                 /* kill irq urb */
386                 usb_kill_urb(card->intr_in_urb);
387
388                 /* kill write urbs */
389                 for (j = 0; j < CPC_USB_URB_CNT; j++) {
390                         if (atomic_read(&card->wrUrbs[j].busy)) {
391                                 usb_kill_urb(card->wrUrbs[j].urb);
392                                 wait_for_completion(&card->wrUrbs[j].finished);
393                         }
394                 }
395         }
396
397         atomic_dec(&useCount);
398
399         /* last process detached */
400         if (atomic_read(&useCount) == 0) {
401                 wake_up(&rmmodWq);
402         }
403
404         if (!card->present && card->open) {
405                 /* the device was unplugged before the file was released */
406                 up(&card->sem);
407                 cpcusb_delete(card);
408                 return 0;
409         }
410
411         card->open = 0;
412
413 exit_not_opened:
414         up(&card->sem);
415
416         return 0;
417 }
418
419 static ssize_t cpcusb_read(struct file *file, char *buffer, size_t count,
420                            loff_t * ppos)
421 {
422         CPC_USB_T *card = (CPC_USB_T *) file->private_data;
423         CPC_CHAN_T *chan;
424         int retval = 0;
425
426         if (count < sizeof(CPC_MSG_T))
427                 return CPC_ERR_UNKNOWN;
428
429         /* check if can read from the given address */
430         if (!access_ok(VERIFY_WRITE, buffer, count))
431                 return CPC_ERR_UNKNOWN;
432
433         /* lock this object */
434         down(&card->sem);
435
436         /* verify that the device wasn't unplugged */
437         if (!card->present) {
438                 up(&card->sem);
439                 return CPC_ERR_NO_INTERFACE_PRESENT;
440         }
441
442         if (IsBufferEmpty(card->chan)) {
443                 retval = 0;
444         } else {
445                 chan = card->chan;
446
447 #if 0
448                 /* convert LPC2119 params back to SJA1000 params */
449                 if (card->deviceRevision >= 0x0200
450                     && chan->buf[chan->oidx].type == CPC_MSG_T_CAN_PRMS) {
451                         LPC2119_TO_SJA1000_Params(&chan->buf[chan->oidx]);
452                 }
453 #endif
454
455                 if (copy_to_user(buffer, &chan->buf[chan->oidx], count) != 0) {
456                         retval = CPC_ERR_IO_TRANSFER;
457                 } else {
458                         chan->oidx = (chan->oidx + 1) % CPC_MSG_BUF_CNT;
459                         chan->WnR = 1;
460                         retval = sizeof(CPC_MSG_T);
461                 }
462         }
463 //    spin_unlock_irqrestore(&card->slock, flags);
464
465         /* unlock the device */
466         up(&card->sem);
467
468         return retval;
469 }
470
471 #define SHIFT  1
472 static void inline cpcusb_align_buffer_alignment(unsigned char *buf)
473 {
474         // CPC-USB uploads packed bytes.
475         CPC_MSG_T *cpc = (CPC_MSG_T *) buf;
476         unsigned int i;
477
478         for (i = 0; i < cpc->length + (2 * sizeof(unsigned long)); i++) {
479                 ((unsigned char *) &cpc->msgid)[1 + i] =
480                     ((unsigned char *) &cpc->msgid)[1 + SHIFT + i];
481         }
482 }
483
484 static int cpc_get_buffer_count(CPC_CHAN_T * chan)
485 {
486         // check the buffer parameters
487         if (chan->iidx == chan->oidx)
488                 return !chan->WnR ? CPC_MSG_BUF_CNT : 0;
489         else if (chan->iidx >= chan->oidx)
490                 return (chan->iidx - chan->oidx) % CPC_MSG_BUF_CNT;
491
492         return (chan->iidx + CPC_MSG_BUF_CNT - chan->oidx) % CPC_MSG_BUF_CNT;
493 }
494
495 static ssize_t cpcusb_write(struct file *file, const char *buffer,
496                             size_t count, loff_t * ppos)
497 {
498         CPC_USB_T *card = (CPC_USB_T *) file->private_data;
499         CPC_USB_WRITE_URB_T *wrUrb = NULL;
500
501         ssize_t bytes_written = 0;
502         int retval = 0;
503         int j;
504
505         unsigned char *obuf = NULL;
506         unsigned char type = 0;
507         CPC_MSG_T *info = NULL;
508
509         dbg("%s - entered minor %d, count = %d, present = %d",
510             __FUNCTION__, card->minor, count, card->present);
511
512         if (count > sizeof(CPC_MSG_T))
513                 return CPC_ERR_UNKNOWN;
514
515         /* check if can read from the given address */
516         if (!access_ok(VERIFY_READ, buffer, count))
517                 return CPC_ERR_UNKNOWN;
518
519         /* lock this object */
520         down(&card->sem);
521
522         /* verify that the device wasn't unplugged */
523         if (!card->present) {
524                 retval = CPC_ERR_NO_INTERFACE_PRESENT;
525                 goto exit;
526         }
527
528         /* verify that we actually have some data to write */
529         if (count == 0) {
530                 dbg("%s - write request of 0 bytes", __FUNCTION__);
531                 goto exit;
532         }
533
534         if (card->free_slots <= 5) {
535                 info = (CPC_MSG_T *) buffer;
536
537                 if (info->type != CPC_CMD_T_CLEAR_CMD_QUEUE
538                     || card->free_slots <= 0) {
539                         dbg("%s - send buffer full please try again %d",
540                             __FUNCTION__, card->free_slots);
541                         retval = CPC_ERR_CAN_NO_TRANSMIT_BUF;
542                         goto exit;
543                 }
544         }
545
546         /* Find a free write urb */
547         for (j = 0; j < CPC_USB_URB_CNT; j++) {
548                 if (!atomic_read(&card->wrUrbs[j].busy)) {
549                         wrUrb = &card->wrUrbs[j];       /* remember found URB */
550                         atomic_set(&wrUrb->busy, 1);    /* lock this URB      */
551                         init_completion(&wrUrb->finished);      /* init completion    */
552                         dbg("WR URB no. %d started", j);
553                         break;
554                 }
555         }
556
557         /* don't found write urb say error */
558         if (!wrUrb) {
559                 dbg("%s - no free send urb available", __FUNCTION__);
560                 retval = CPC_ERR_CAN_NO_TRANSMIT_BUF;
561                 goto exit;
562         }
563         dbg("URB write req");
564
565         obuf = (unsigned char *) wrUrb->urb->transfer_buffer;
566
567         /* copy the data from userspace into our transfer buffer;
568          * this is the only copy required.
569          */
570         if (copy_from_user(&obuf[4], buffer, count) != 0) {
571                 atomic_set(&wrUrb->busy, 0);    /* release urb */
572                 retval = CPC_ERR_IO_TRANSFER;
573                 goto exit;
574         }
575
576         /* check if it is a DRIVER information message, so we can
577          * response to that message and not the USB
578          */
579         info = (CPC_MSG_T *) & obuf[4];
580
581         bytes_written = 11 + info->length;
582         if (bytes_written >= wrUrb->size) {
583                 retval = CPC_ERR_IO_TRANSFER;
584                 goto exit;
585         }
586
587         switch (info->type) {
588         case CPC_CMD_T_CLEAR_MSG_QUEUE:
589                 ResetBuffer(card->chan);
590                 break;
591
592         case CPC_CMD_T_INQ_MSG_QUEUE_CNT:
593                 retval = cpc_get_buffer_count(card->chan);
594                 atomic_set(&wrUrb->busy, 0);
595
596                 goto exit;
597
598         case CPC_CMD_T_INQ_INFO:
599                 if (info->msg.info.source == CPC_INFOMSG_T_DRIVER) {
600                         /* release urb cause we'll use it for driver
601                          * information
602                          */
603                         atomic_set(&wrUrb->busy, 0);
604                         if (IsBufferFull(card->chan)) {
605                                 retval = CPC_ERR_IO_TRANSFER;
606                                 goto exit;
607                         }
608
609                         /* it is a driver information request message and we have
610                          * free rx slots to store the response
611                          */
612                         type = info->msg.info.type;
613                         info = &card->chan->buf[card->chan->iidx];
614
615                         info->type = CPC_MSG_T_INFO;
616                         info->msg.info.source = CPC_INFOMSG_T_DRIVER;
617                         info->msg.info.type = type;
618
619                         switch (type) {
620                         case CPC_INFOMSG_T_VERSION:
621                                 info->length = strlen(CPC_DRIVER_VERSION) + 2;
622                                 sprintf(info->msg.info.msg, "%s\n",
623                                         CPC_DRIVER_VERSION);
624                                 break;
625
626                         case CPC_INFOMSG_T_SERIAL:
627                                 info->length = strlen(CPC_DRIVER_SERIAL) + 2;
628                                 sprintf(info->msg.info.msg, "%s\n",
629                                         CPC_DRIVER_SERIAL);
630                                 break;
631
632                         default:
633                                 info->length = 2;
634                                 info->msg.info.type =
635                                     CPC_INFOMSG_T_UNKNOWN_TYPE;
636                         }
637
638                         card->chan->WnR = 0;
639                         card->chan->iidx =
640                             (card->chan->iidx + 1) % CPC_MSG_BUF_CNT;
641
642                         retval = info->length;
643                         goto exit;
644                 }
645                 break;
646         case CPC_CMD_T_CAN_PRMS:
647                 /* Check the controller type. If it's the new CPC-USB, make sure if these are SJA1000 params */
648                 if (info->msg.canparams.cc_type != SJA1000
649                     && info->msg.canparams.cc_type != M16C_BASIC
650                     && (card->productId == USB_CPCUSB_LPC2119_PRODUCT_ID
651                         && info->msg.canparams.cc_type != SJA1000)) {
652                         /* don't forget to release the urb */
653                         atomic_set(&wrUrb->busy, 0);
654                         retval = CPC_ERR_WRONG_CONTROLLER_TYPE;
655                         goto exit;
656                 }
657                 break;
658         }
659
660         /* just convert the params if it is an old CPC-USB with M16C controller */
661         if (card->productId == USB_CPCUSB_M16C_PRODUCT_ID) {
662                 /* if it is a parameter message convert it from SJA1000 controller
663                  * settings to M16C Basic controller settings
664                  */
665                 SJA1000_TO_M16C_BASIC_Params((CPC_MSG_T *) & obuf[4]);
666         }
667
668         /* don't forget the byte alignment */
669         cpcusb_align_buffer_alignment(&obuf[4]);
670
671         /* setup a the 4 byte header */
672         obuf[0] = obuf[1] = obuf[2] = obuf[3] = 0;
673
674         /* this urb was already set up, except for this write size */
675         wrUrb->urb->transfer_buffer_length = bytes_written + 4;
676
677         /* send the data out the bulk port */
678         /* a character device write uses GFP_KERNEL,
679            unless a spinlock is held */
680         retval = usb_submit_urb(wrUrb->urb, GFP_KERNEL);
681         if (retval) {
682                 atomic_set(&wrUrb->busy, 0);    /* release urb */
683                 err("%s - failed submitting write urb, error %d",
684                     __FUNCTION__, retval);
685         } else {
686                 retval = bytes_written;
687         }
688
689 exit:
690         /* unlock the device */
691         up(&card->sem);
692
693         dbg("%s - leaved", __FUNCTION__);
694
695         return retval;
696 }
697
698 /*
699  * callback for interrupt IN urb
700  */
701 static void cpcusb_read_interrupt_callback(struct urb *urb
702 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,19))
703                                            , struct pt_regs *regs
704 #endif
705 )
706 {
707         CPC_USB_T *card = (CPC_USB_T *) urb->context;
708         int retval;
709         unsigned long flags;
710
711         spin_lock_irqsave(&card->slock, flags);
712
713         if (!card->present) {
714                 spin_unlock_irqrestore(&card->slock, flags);
715                 info("%s - no such device", __FUNCTION__);
716                 return;
717         }
718
719         switch (urb->status) {
720         case 0: /* success */
721                 card->free_slots = card->intr_in_buffer[1];
722                 break;
723         case -ECONNRESET:
724         case -ENOENT:
725         case -ESHUTDOWN:
726                 /* urb was killed */
727                 spin_unlock_irqrestore(&card->slock, flags);
728                 dbg("%s - intr urb killed", __FUNCTION__);
729                 return;
730         default:
731                 info("%s - nonzero urb status %d", __FUNCTION__, urb->status);
732                 break;
733         }
734
735         retval = usb_submit_urb(urb, GFP_ATOMIC);
736         if (retval) {
737                 err("%s - failed resubmitting intr urb, error %d",
738                     __FUNCTION__, retval);
739         }
740
741         spin_unlock_irqrestore(&card->slock, flags);
742         wake_up_interruptible(card->chan->CPCWait_q);
743
744         return;
745 }
746
747 #define UN_SHIFT  1
748 #define CPCMSG_HEADER_LEN_FIRMWARE   11
749 static int inline cpcusb_unalign_and_copy_buffy(unsigned char *out,
750                                         unsigned char *in)
751 {
752         unsigned int i, j;
753
754         for (i = 0; i < 3; i++) {
755                 out[i] = in[i];
756         }
757
758         for (j = 0; j < (in[1] + (CPCMSG_HEADER_LEN_FIRMWARE - 3)); j++) {
759                 out[j + i + UN_SHIFT] = in[j + i];
760         }
761
762         return i + j;
763 }
764
765 /*
766  * callback for bulk IN urb
767  */
768 static void cpcusb_read_bulk_callback(struct urb *urb
769 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,19))
770                                            , struct pt_regs *regs
771 #endif
772 )
773 {
774         CPC_USB_T *card = (CPC_USB_T *) urb->context;
775         CPC_CHAN_T *chan;
776         unsigned char *ibuf = urb->transfer_buffer;
777         int retval, msgCnt, start, again = 0;
778         unsigned long flags;
779
780         if (!card) {
781                 err("%s - device object lost", __FUNCTION__);
782                 return;
783         }
784
785         spin_lock_irqsave(&card->slock, flags);
786
787         if (!card->present) {
788                 spin_unlock_irqrestore(&card->slock, flags);
789                 info("%s - no such device", __FUNCTION__);
790                 return;
791         }
792
793         switch (urb->status) {
794         case 0:         /* success */
795                 break;
796         case -ECONNRESET:
797         case -ENOENT:
798         case -ESHUTDOWN:
799                 /* urb was killed */
800                 spin_unlock_irqrestore(&card->slock, flags);
801                 dbg("%s - read urb killed", __FUNCTION__);
802                 return;
803         default:
804                 info("%s - nonzero urb status %d", __FUNCTION__, urb->status);
805                 break;
806         }
807
808         if (urb->actual_length) {
809                 msgCnt = ibuf[0] & ~0x80;
810                 again = ibuf[0] & 0x80;
811
812                 /* we have a 4 byte header */
813                 start = 4;
814                 chan = card->chan;
815                 while (msgCnt) {
816                         if (!(IsBufferFull(card->chan))) {
817                                 start +=
818                                     cpcusb_unalign_and_copy_buffy((unsigned char *)
819                                                           &chan->buf[chan->iidx], &ibuf[start]);
820
821                                 if (start > urb->transfer_buffer_length) {
822                                         err("%d > %d", start, urb->transfer_buffer_length);
823                                         break;
824                                 }
825
826                                 chan->WnR = 0;
827                                 chan->iidx = (chan->iidx + 1) % CPC_MSG_BUF_CNT;
828                                 msgCnt--;
829                         } else {
830                                 break;
831                         }
832                 }
833         }
834
835         usb_fill_bulk_urb(urb, card->udev,
836                           usb_rcvbulkpipe(card->udev, card->num_bulk_in),
837                           urb->transfer_buffer,
838                           urb->transfer_buffer_length,
839                           cpcusb_read_bulk_callback, card);
840
841         retval = usb_submit_urb(urb, GFP_ATOMIC);
842
843         if (retval) {
844                 err("%s - failed resubmitting read urb, error %d", __FUNCTION__, retval);
845         }
846
847         spin_unlock_irqrestore(&card->slock, flags);
848
849         wake_up_interruptible(card->chan->CPCWait_q);
850 }
851
852 /*
853  * callback for bulk IN urb
854  */
855 static void cpcusb_write_bulk_callback(struct urb *urb
856 #if (LINUX_VERSION_CODE < KERNEL_VERSION(2,6,19))
857                                            , struct pt_regs *regs
858 #endif
859 )
860 {
861         CPC_USB_T *card = (CPC_USB_T *) urb->context;
862         unsigned long flags;
863         int j;
864
865         spin_lock_irqsave(&card->slock, flags);
866
867         /* find this urb */
868         for (j = 0; j < CPC_USB_URB_CNT; j++) {
869                 if (card->wrUrbs[j].urb == urb) {
870                         dbg("URB found no. %d", j);
871                         /* notify anyone waiting that the write has finished */
872                         complete(&card->wrUrbs[j].finished);
873                         atomic_set(&card->wrUrbs[j].busy, 0);
874                         break;
875                 }
876         }
877
878         switch (urb->status) {
879         case 0:         /* success */
880                 break;
881         case -ECONNRESET:
882         case -ENOENT:
883         case -ESHUTDOWN:
884                 /* urb was killed */
885                 spin_unlock_irqrestore(&card->slock, flags);
886                 dbg("%s - write urb no. %d killed", __FUNCTION__, j);
887                 return;
888         default:
889                 info("%s - nonzero urb status %d", __FUNCTION__, urb->status);
890                 break;
891         }
892
893         spin_unlock_irqrestore(&card->slock, flags);
894
895         wake_up_interruptible(card->chan->CPCWait_q);
896 }
897
898 static inline int cpcusb_get_free_slot(void)
899 {
900         int i;
901
902         for (i = 0; i < CPC_USB_CARD_CNT; i++) {
903                 if (!CPCUSB_Table[i])
904                         return i;
905         }
906
907         return -1;
908 }
909
910 /*
911  * probe function for new CPC-USB devices
912  */
913 static int cpcusb_probe(struct usb_interface *interface,
914                                 const struct usb_device_id *id)
915 {
916         CPC_USB_T *card = NULL;
917         CPC_CHAN_T *chan = NULL;
918
919         struct usb_device *udev = interface_to_usbdev(interface);
920         struct usb_host_interface *iface_desc;
921         struct usb_endpoint_descriptor *endpoint;
922
923         int i, j, retval = -ENOMEM, slot;
924
925         if ((slot = cpcusb_get_free_slot()) < 0) {
926                 info("No more devices supported");
927                 return -ENOMEM;
928         }
929
930         /* allocate memory for our device state and initialize it */
931         card = kzalloc(sizeof(CPC_USB_T), GFP_KERNEL);
932         if (!card) {
933                 err("Out of memory");
934                 return -ENOMEM;
935         }
936         CPCUSB_Table[slot] = card;
937
938         /* allocate and initialize the channel struct */
939         card->chan = kmalloc(sizeof(CPC_CHAN_T), GFP_KERNEL);
940         if (!card) {
941                 kfree(card);
942                 err("Out of memory");
943                 return -ENOMEM;
944         }
945
946         chan = card->chan;
947         memset(chan, 0, sizeof(CPC_CHAN_T));
948         ResetBuffer(chan);
949
950         init_MUTEX(&card->sem);
951         spin_lock_init(&card->slock);
952
953         card->udev = udev;
954         card->interface = interface;
955         if (udev->descriptor.iSerialNumber) {
956                 usb_string(udev, udev->descriptor.iSerialNumber, card->serialNumber,
957                                    128);
958                 info("Serial %s", card->serialNumber);
959         }
960
961         card->productId = udev->descriptor.idProduct;
962         info("Product %s",
963              card->productId == USB_CPCUSB_LPC2119_PRODUCT_ID ?
964                          "CPC-USB/ARM7" : "CPC-USB/M16C");
965
966         /* set up the endpoint information */
967         /* check out the endpoints */
968         /* use only the first bulk-in and bulk-out endpoints */
969         iface_desc = &interface->altsetting[0];
970         for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {
971                 endpoint = &iface_desc->endpoint[i].desc;
972
973                 if (!card->num_intr_in &&
974                     (endpoint->bEndpointAddress & USB_DIR_IN) &&
975                     ((endpoint->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
976                      == USB_ENDPOINT_XFER_INT)) {
977                         card->intr_in_urb = usb_alloc_urb(0, GFP_KERNEL);
978                         card->num_intr_in = 1;
979
980                         if (!card->intr_in_urb) {
981                                 err("No free urbs available");
982                                 goto error;
983                         }
984
985                         dbg("intr_in urb %d", card->num_intr_in);
986                 }
987
988                 if (!card->num_bulk_in &&
989                     (endpoint->bEndpointAddress & USB_DIR_IN) &&
990                     ((endpoint->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
991                      == USB_ENDPOINT_XFER_BULK)) {
992                         card->num_bulk_in = 2;
993                         for (j = 0; j < CPC_USB_URB_CNT; j++) {
994                                 card->urbs[j].size = endpoint->wMaxPacketSize;
995                                 card->urbs[j].urb = usb_alloc_urb(0, GFP_KERNEL);
996                                 if (!card->urbs[j].urb) {
997                                         err("No free urbs available");
998                                         goto error;
999                                 }
1000                                 card->urbs[j].buffer =
1001                                     usb_buffer_alloc(udev,
1002                                                      card->urbs[j].size,
1003                                                      GFP_KERNEL,
1004                                                      &card->urbs[j].urb->transfer_dma);
1005                                 if (!card->urbs[j].buffer) {
1006                                         err("Couldn't allocate bulk_in_buffer");
1007                                         goto error;
1008                                 }
1009                         }
1010                         info("%s - %d reading URB's allocated",
1011                              __FUNCTION__, CPC_USB_URB_CNT);
1012                 }
1013
1014                 if (!card->num_bulk_out &&
1015                     !(endpoint->bEndpointAddress & USB_DIR_IN) &&
1016                     ((endpoint->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK)
1017                      == USB_ENDPOINT_XFER_BULK)) {
1018
1019                         card->num_bulk_out = 2;
1020
1021                         for (j = 0; j < CPC_USB_URB_CNT; j++) {
1022                                 card->wrUrbs[j].size =
1023                                     endpoint->wMaxPacketSize;
1024                                 card->wrUrbs[j].urb =
1025                                     usb_alloc_urb(0, GFP_KERNEL);
1026                                 if (!card->wrUrbs[j].urb) {
1027                                         err("No free urbs available");
1028                                         goto error;
1029                                 }
1030                                 card->wrUrbs[j].buffer = usb_buffer_alloc(udev,
1031                                                                card->wrUrbs[j].size, GFP_KERNEL,
1032                                                                &card->wrUrbs[j].urb->transfer_dma);
1033
1034                                 if (!card->wrUrbs[j].buffer) {
1035                                         err("Couldn't allocate bulk_out_buffer");
1036                                         goto error;
1037                                 }
1038
1039                                 usb_fill_bulk_urb(card->wrUrbs[j].urb, udev,
1040                                                 usb_sndbulkpipe(udev, endpoint->bEndpointAddress),
1041                                                 card->wrUrbs[j].buffer,
1042                                                 card->wrUrbs[j].size,
1043                                                 cpcusb_write_bulk_callback,
1044                                                 card);
1045                         }
1046
1047                         info("%s - %d writing URB's allocated", __FUNCTION__, CPC_USB_URB_CNT);
1048                 }
1049         }
1050
1051         if (!(card->num_bulk_in && card->num_bulk_out)) {
1052                 err("Couldn't find both bulk-in and bulk-out endpoints");
1053                 goto error;
1054         }
1055
1056         /* allow device read, write and ioctl */
1057         card->present = 1;
1058
1059         /* we can register the device now, as it is ready */
1060         usb_set_intfdata(interface, card);
1061         retval = usb_register_dev(interface, &cpcusb_class);
1062
1063         if (retval) {
1064                 /* something prevented us from registering this driver */
1065                 err("Not able to get a minor for this device.");
1066                 usb_set_intfdata(interface, NULL);
1067                 goto error;
1068         }
1069
1070         card->chan->minor = card->minor = interface->minor;
1071
1072         chan->buf = vmalloc(sizeof(CPC_MSG_T) * CPC_MSG_BUF_CNT);
1073         if (chan->buf == NULL) {
1074                 err("Out of memory");
1075                 retval = -ENOMEM;
1076                 goto error;
1077         }
1078         info("Allocated memory for %d messages (%d kbytes)",
1079              CPC_MSG_BUF_CNT, (sizeof(CPC_MSG_T) * CPC_MSG_BUF_CNT) / 1000);
1080         memset(chan->buf, 0, sizeof(CPC_MSG_T) * CPC_MSG_BUF_CNT);
1081
1082         ResetBuffer(chan);
1083
1084         card->chan->CPCWait_q = kmalloc(sizeof(wait_queue_head_t), GFP_KERNEL);
1085         if (!card->chan->CPCWait_q) {
1086                 err("Out of memory");
1087                 retval = -ENOMEM;
1088                 goto error;
1089         }
1090         init_waitqueue_head(card->chan->CPCWait_q);
1091
1092         CPCUSB_Table[slot] = card;
1093         card->idx = slot;
1094         CPCUsbCnt++;
1095
1096         /* let the user know what node this device is now attached to */
1097         info("Device now attached to USB-%d", card->minor);
1098         return 0;
1099
1100 error:
1101         for (j = 0; j < CPC_USB_URB_CNT; j++) {
1102                 if (card->urbs[j].buffer) {
1103                         usb_buffer_free(card->udev, card->urbs[j].size,
1104                                         card->urbs[j].buffer,
1105                                         card->urbs[j].urb->transfer_dma);
1106                         card->urbs[j].buffer = NULL;
1107                 }
1108                 if (card->urbs[j].urb) {
1109                         usb_free_urb(card->urbs[j].urb);
1110                         card->urbs[j].urb = NULL;
1111                 }
1112         }
1113
1114         cpcusb_delete(card);
1115         return retval;
1116 }
1117
1118 /*
1119  * called by the usb core when the device is removed from the system
1120  */
1121 static void cpcusb_disconnect(struct usb_interface *interface)
1122 {
1123         CPC_USB_T *card = NULL;
1124         int minor, j;
1125
1126         /* prevent races with open() */
1127         down(&disconnect_sem);
1128
1129         card = usb_get_intfdata(interface);
1130         usb_set_intfdata(interface, NULL);
1131
1132         down(&card->sem);
1133
1134         /* prevent device read, write and ioctl */
1135         card->present = 0;
1136
1137         minor = card->minor;
1138
1139         /* free all urbs and their buffers */
1140         for (j = 0; j < CPC_USB_URB_CNT; j++) {
1141                 /* terminate an ongoing write */
1142                 if (atomic_read(&card->wrUrbs[j].busy)) {
1143                         usb_kill_urb(card->wrUrbs[j].urb);
1144                         wait_for_completion(&card->wrUrbs[j].finished);
1145                 }
1146                 usb_buffer_free(card->udev, card->wrUrbs[j].size,
1147                                 card->wrUrbs[j].buffer,
1148                                 card->wrUrbs[j].urb->transfer_dma);
1149                 usb_free_urb(card->wrUrbs[j].urb);
1150         }
1151         info("%d write URBs freed", CPC_USB_URB_CNT);
1152
1153         /* free all urbs and their buffers */
1154         for (j = 0; j < CPC_USB_URB_CNT; j++) {
1155                 usb_buffer_free(card->udev, card->urbs[j].size,
1156                                 card->urbs[j].buffer,
1157                                 card->urbs[j].urb->transfer_dma);
1158                 usb_free_urb(card->urbs[j].urb);
1159         }
1160         info("%d read URBs freed", CPC_USB_URB_CNT);
1161         usb_free_urb(card->intr_in_urb);
1162
1163         /* give back our minor */
1164         usb_deregister_dev(interface, &cpcusb_class);
1165
1166         up(&card->sem);
1167
1168         /* if the device is opened, cpcusb_release will clean this up */
1169         if (!card->open)
1170                 cpcusb_delete(card);
1171         else
1172                 wake_up_interruptible(card->chan->CPCWait_q);
1173
1174         up(&disconnect_sem);
1175
1176         CPCUsbCnt--;
1177         info("USB-%d now disconnected", minor);
1178 }
1179
1180 static int __init CPCUsb_Init(void)
1181 {
1182         int result, i;
1183
1184         info(DRIVER_DESC " v" DRIVER_VERSION);
1185         info("Build on " __DATE__ " at " __TIME__);
1186
1187         for (i = 0; i < CPC_USB_CARD_CNT; i++)
1188                 CPCUSB_Table[i] = 0;
1189
1190         /* register this driver with the USB subsystem */
1191         result = usb_register(&cpcusb_driver);
1192         if (result) {
1193                 err("usb_register failed. Error number %d", result);
1194                 return result;
1195         }
1196
1197         procDir = proc_mkdir(CPC_USB_PROC_DIR, NULL);
1198         if (!procDir) {
1199                 err("Could not create proc entry");
1200         } else {
1201                 procEntry = create_proc_read_entry("info", 0444, procDir,
1202                                                    cpcusb_proc_read_info,
1203                                                    NULL);
1204                 if (!procEntry) {
1205                         err("Could not create proc entry %s", CPC_USB_PROC_DIR "/info");
1206                         remove_proc_entry(CPC_USB_PROC_DIR, NULL);
1207                         procDir = NULL;
1208                 }
1209         }
1210
1211         return 0;
1212 }
1213
1214 static void __exit CPCUsb_Exit(void)
1215 {
1216         wait_event(rmmodWq, !atomic_read(&useCount));
1217
1218         /* deregister this driver with the USB subsystem */
1219         usb_deregister(&cpcusb_driver);
1220
1221         if (procDir) {
1222                 if (procEntry)
1223                         remove_proc_entry("info", procDir);
1224                 remove_proc_entry(CPC_USB_PROC_DIR, NULL);
1225         }
1226 }
1227
1228 module_init(CPCUsb_Init);
1229 module_exit(CPCUsb_Exit);