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