]> rtime.felk.cvut.cz Git - lincan.git/blob - lincan/src/usbcan.c
Each (future) canchip associated to different usb endpoint, instead of whole device...
[lincan.git] / lincan / src / usbcan.c
1 /* usbcan.h
2  * Header file for the Linux CAN-bus driver.
3  * Written by Jan Kriz email:johen@post.cz
4  * This software is released under the GPL-License.
5  * Version lincan-0.3  17 Jul 2008
6  */
7
8 #include "../include/can.h"
9 #include "../include/can_sysdep.h"
10 #include "../include/main.h"
11 #include "../include/devcommon.h"
12 #include "../include/setup.h"
13 #include "../include/usbcan.h"
14
15 static int usbcan_probe(struct usb_interface *interface, const struct usb_device_id *id);
16 static void usbcan_disconnect(struct usb_interface *interface);
17
18 volatile int usbcan_chip_count=0;
19
20 /* table of devices that work with this driver */
21 static struct usb_device_id usbcan_table [] = {
22         { USB_DEVICE(USBCAN_VENDOR_ID, USBCAN_PRODUCT_ID) },
23         { }                                     /* Terminating entry */
24 };
25 MODULE_DEVICE_TABLE(usb, usbcan_table);
26
27 static struct usb_driver usbcan_driver = {
28         .name =         "usbcan",
29         .id_table = usbcan_table,
30         .probe =        usbcan_probe,
31         .disconnect =   usbcan_disconnect,
32 };
33
34 /**
35  * usbcan_request_io: - reserve io or memory range for can board
36  * @candev: pointer to candevice/board which asks for io. Field @io_addr
37  *      of @candev is used in most cases to define start of the range
38  *
39  * The function usbcan_request_io() is used to reserve the io-memory. If your
40  * hardware uses a dedicated memory range as hardware control registers you
41  * will have to add the code to reserve this memory as well.
42  * %IO_RANGE is the io-memory range that gets reserved, please adjust according
43  * your hardware. Example: #define IO_RANGE 0x100 for i82527 chips or
44  * #define IO_RANGE 0x20 for sja1000 chips in basic CAN mode.
45  * Return Value: The function returns zero on success or %-ENODEV on failure
46  * File: src/usbcan.c
47  */
48 int usbcan_request_io(struct candevice_t *candev)
49 {
50         struct usbcan_devs *usbdevs = (struct usbcan_devs *)candev->sysdevptr.anydev;
51
52         if (!usbdevs){
53                 CANMSG("USBCAN_REQUEST_IO: Cannot register usbcan while usb device is not present.\n");
54                 CANMSG("USBCAN_REQUEST_IO: Usbcan registers automatically on device insertion.\n");
55                 return -ENODEV;
56         }
57
58         return 0;
59 }
60
61 /**
62  * usbcan_release_io - free reserved io memory range
63  * @candev: pointer to candevice/board which releases io
64  *
65  * The function usbcan_release_io() is used to free reserved io-memory.
66  * In case you have reserved more io memory, don't forget to free it here.
67  * IO_RANGE is the io-memory range that gets released, please adjust according
68  * your hardware. Example: #define IO_RANGE 0x100 for i82527 chips or
69  * #define IO_RANGE 0x20 for sja1000 chips in basic CAN mode.
70  * Return Value: The function always returns zero
71  * File: src/usbcan.c
72  */
73 int usbcan_release_io(struct candevice_t *candev)
74 {
75         return 0;
76 }
77
78 /**
79  * usbcan_reset - hardware reset routine
80  * @candev: Pointer to candevice/board structure
81  *
82  * The function usbcan_reset() is used to give a hardware reset. This is
83  * rather hardware specific so I haven't included example code. Don't forget to
84  * check the reset status of the chip before returning.
85  * Return Value: The function returns zero on success or %-ENODEV on failure
86  * File: src/usbcan.c
87  */
88 int usbcan_reset(struct candevice_t *candev)
89 {
90         return 0;
91 }
92
93 /**
94  * usbcan_init_hw_data - Initialize hardware cards
95  * @candev: Pointer to candevice/board structure
96  *
97  * The function usbcan_init_hw_data() is used to initialize the hardware
98  * structure containing information about the installed CAN-board.
99  * %RESET_ADDR represents the io-address of the hardware reset register.
100  * %NR_82527 represents the number of Intel 82527 chips on the board.
101  * %NR_SJA1000 represents the number of Philips sja1000 chips on the board.
102  * The flags entry can currently only be %CANDEV_PROGRAMMABLE_IRQ to indicate that
103  * the hardware uses programmable interrupts.
104  * Return Value: The function always returns zero
105  * File: src/usbcan.c
106  */
107 int usbcan_init_hw_data(struct candevice_t *candev)
108 {
109         candev->res_addr=RESET_ADDR;
110         candev->nr_82527_chips=0;
111         candev->nr_sja1000_chips=0;
112         candev->nr_all_chips=usbcan_chip_count;
113         candev->flags |= CANDEV_PROGRAMMABLE_IRQ*0;
114
115         return 0;
116 }
117
118 /**
119  * usbcan_init_obj_data - Initialize message buffers
120  * @chip: Pointer to chip specific structure
121  * @objnr: Number of the message buffer
122  *
123  * The function usbcan_init_obj_data() is used to initialize the hardware
124  * structure containing information about the different message objects on the
125  * CAN chip. In case of the sja1000 there's only one message object but on the
126  * i82527 chip there are 15.
127  * The code below is for a i82527 chip and initializes the object base addresses
128  * The entry @obj_base_addr represents the first memory address of the message
129  * object. In case of the sja1000 @obj_base_addr is taken the same as the chips
130  * base address.
131  * Unless the hardware uses a segmented memory map, flags can be set zero.
132  * Return Value: The function always returns zero
133  * File: src/usbcan.c
134  */
135 int usbcan_init_obj_data(struct canchip_t *chip, int objnr)
136 {
137         chip->msgobj[objnr]->obj_base_addr=0;
138
139         return 0;
140 }
141
142 /**
143  * usbcan_program_irq - program interrupts
144  * @candev: Pointer to candevice/board structure
145  *
146  * The function usbcan_program_irq() is used for hardware that uses
147  * programmable interrupts. If your hardware doesn't use programmable interrupts
148  * you should not set the @candevices_t->flags entry to %CANDEV_PROGRAMMABLE_IRQ and
149  * leave this function unedited. Again this function is hardware specific so
150  * there's no example code.
151  * Return value: The function returns zero on success or %-ENODEV on failure
152  * File: src/usbcan.c
153  */
154 int usbcan_program_irq(struct candevice_t *candev)
155 {
156         return 0;
157 }
158
159 /* !!! Don't change this function !!! */
160 int usbcan_register(struct hwspecops_t *hwspecops)
161 {
162         hwspecops->request_io = usbcan_request_io;
163         hwspecops->release_io = usbcan_release_io;
164         hwspecops->reset = usbcan_reset;
165         hwspecops->init_hw_data = usbcan_init_hw_data;
166         hwspecops->init_chip_data = usbcan_init_chip_data;
167         hwspecops->init_obj_data = usbcan_init_obj_data;
168         hwspecops->write_register = NULL;
169         hwspecops->read_register = NULL;
170         hwspecops->program_irq = usbcan_program_irq;
171         return 0;
172 }
173
174 // static int sja1000_report_error_limit_counter;
175
176 static void sja1000_report_error(struct canchip_t *chip,
177                                 unsigned sr, unsigned ir, unsigned ecc)
178 {
179         /*TODO : Error reporting from device */
180
181 /*      if(sja1000_report_error_limit_counter>=100)
182                 return;
183
184         CANMSG("Error: status register: 0x%x irq_register: 0x%02x error: 0x%02x\n",
185                 sr, ir, ecc);
186
187         sja1000_report_error_limit_counter+=10;
188
189         if(sja1000_report_error_limit_counter>=100){
190                 sja1000_report_error_limit_counter+=10;
191                 CANMSG("Error: too many errors, reporting disabled\n");
192                 return;
193         }
194
195 #ifdef CONFIG_OC_LINCAN_DETAILED_ERRORS
196         CANMSG("SR: BS=%c  ES=%c  TS=%c  RS=%c  TCS=%c TBS=%c DOS=%c RBS=%c\n",
197                 sr&sjaSR_BS?'1':'0',sr&sjaSR_ES?'1':'0',
198                 sr&sjaSR_TS?'1':'0',sr&sjaSR_RS?'1':'0',
199                 sr&sjaSR_TCS?'1':'0',sr&sjaSR_TBS?'1':'0',
200                 sr&sjaSR_DOS?'1':'0',sr&sjaSR_RBS?'1':'0');
201         CANMSG("IR: BEI=%c ALI=%c EPI=%c WUI=%c DOI=%c EI=%c  TI=%c  RI=%c\n",
202                 sr&sjaIR_BEI?'1':'0',sr&sjaIR_ALI?'1':'0',
203                 sr&sjaIR_EPI?'1':'0',sr&sjaIR_WUI?'1':'0',
204                 sr&sjaIR_DOI?'1':'0',sr&sjaIR_EI?'1':'0',
205                 sr&sjaIR_TI?'1':'0',sr&sjaIR_RI?'1':'0');
206         if((sr&sjaIR_EI) || 1){
207                 CANMSG("EI: %s %s %s\n",
208                        sja1000_ecc_errc_str[(ecc&(sjaECC_ERCC1|sjaECC_ERCC0))/sjaECC_ERCC0],
209                        ecc&sjaECC_DIR?"RX":"TX",
210                        sja1000_ecc_seg_str[ecc&sjaECC_SEG_M]
211                       );
212         }
213 #endif /*CONFIG_OC_LINCAN_DETAILED_ERRORS*/
214 }
215
216
217 /**
218  * usbcan_enable_configuration - enable chip configuration mode
219  * @chip: pointer to chip state structure
220  */
221 int usbcan_enable_configuration(struct canchip_t *chip)
222 {
223         return 0;
224 }
225
226 /**
227  * usbcan_disable_configuration - disable chip configuration mode
228  * @chip: pointer to chip state structure
229  */
230 int usbcan_disable_configuration(struct canchip_t *chip)
231 {
232         return 0;
233 }
234
235 /**
236  * usbcan_chip_config: - can chip configuration
237  * @chip: pointer to chip state structure
238  *
239  * This function configures chip and prepares it for message
240  * transmission and reception. The function resets chip,
241  * resets mask for acceptance of all messages by call to
242  * usbcan_extended_mask() function and then
243  * computes and sets baudrate with use of function usbcan_baud_rate().
244  * Return Value: negative value reports error.
245  * File: src/usbcan.c
246  */
247 int usbcan_chip_config(struct canchip_t *chip)
248 {
249         return 0;
250 }
251
252 /**
253  * usbcan_extended_mask: - setup of extended mask for message filtering
254  * @chip: pointer to chip state structure
255  * @code: can message acceptance code
256  * @mask: can message acceptance mask
257  *
258  * Return Value: negative value reports error.
259  * File: src/usbcan.c
260  */
261 int usbcan_extended_mask(struct canchip_t *chip, unsigned long code, unsigned  long mask)
262 {
263         int retval;
264         struct usbcan_usb *dev=(struct usbcan_usb*)chip->chip_data;
265
266         u8 usbbuf[16];
267
268         if (!dev)
269                 return -ENODEV;
270
271         *(uint32_t *)(usbbuf)=cpu_to_le32(mask);
272         *(uint32_t *)(usbbuf+4)=cpu_to_le32(code);
273
274         retval=usb_control_msg(dev->udev,
275                 usb_sndctrlpipe(dev->udev, 0),
276                 USBCAN_VENDOR_EXT_MASK_SET,
277                 USB_TYPE_VENDOR,
278                 cpu_to_le16(0), cpu_to_le16(chip->chip_idx),
279                 &usbbuf, 16,
280                 10000);
281         if (retval<0)
282                 return -ENODEV;
283
284         retval = usb_control_msg(dev->udev,
285                 usb_rcvctrlpipe(dev->udev, 0),
286                 USBCAN_VENDOR_EXT_MASK_STATUS,
287                 USB_TYPE_VENDOR,
288                 cpu_to_le16(0), cpu_to_le16(chip->chip_idx),
289                 &usbbuf, 16,
290                 10000);
291
292         if (retval==1){
293                 if(usbbuf[0]==1){
294                         DEBUGMSG("Setting acceptance code to 0x%lx\n",(unsigned long)code);
295                         DEBUGMSG("Setting acceptance mask to 0x%lx\n",(unsigned long)mask);
296                         return 0;
297                 }
298         }
299
300         CANMSG("Setting extended mask failed\n");
301         return -EINVAL;
302 }
303
304 /**
305  * usbcan_baud_rate: - set communication parameters.
306  * @chip: pointer to chip state structure
307  * @rate: baud rate in Hz
308  * @clock: frequency of sja1000 clock in Hz (ISA osc is 14318000)
309  * @sjw: synchronization jump width (0-3) prescaled clock cycles
310  * @sampl_pt: sample point in % (0-100) sets (TSEG1+1)/(TSEG1+TSEG2+2) ratio
311  * @flags: fields %BTR1_SAM, %OCMODE, %OCPOL, %OCTP, %OCTN, %CLK_OFF, %CBP
312  *
313  * Return Value: negative value reports error.
314  * File: src/usbcan.c
315  */
316 int usbcan_baud_rate(struct canchip_t *chip, int rate, int clock, int sjw,
317                                                         int sampl_pt, int flags)
318 {
319         int retval;
320         struct usbcan_usb *dev=(struct usbcan_usb*)chip->chip_data;
321
322         u8 usbbuf[16];
323
324         if (!dev)
325                 return -ENODEV;
326
327         *(int32_t *)(usbbuf)=cpu_to_le32(rate);
328         *(int32_t *)(usbbuf+4)=cpu_to_le32(sjw);
329         *(int32_t *)(usbbuf+8)=cpu_to_le32(sampl_pt);
330         *(int32_t *)(usbbuf+12)=cpu_to_le32(flags);
331
332         retval=usb_control_msg(dev->udev,
333                 usb_sndctrlpipe(dev->udev, 0),
334                 USBCAN_VENDOR_BAUD_RATE_SET,
335                 USB_TYPE_VENDOR,
336                 cpu_to_le16(0), cpu_to_le16(chip->chip_idx),
337                 &usbbuf, 16,
338                 10000);
339         if (retval<0)
340                 return -ENODEV;
341
342         retval = usb_control_msg(dev->udev,
343                 usb_rcvctrlpipe(dev->udev, 0),
344                 USBCAN_VENDOR_BAUD_RATE_STATUS,
345                 USB_TYPE_VENDOR,
346                 cpu_to_le16(0), cpu_to_le16(chip->chip_idx),
347                 usbbuf, 16,
348                 10000);
349
350         if (retval==1){
351                 if(usbbuf[0]==1)
352                         return 0;
353         }
354
355         CANMSG("baud rate %d is not possible to set\n",
356                 rate);
357         return -EINVAL;
358 }
359
360 /**
361  * usbcan_pre_read_config: - prepares message object for message reception
362  * @chip: pointer to chip state structure
363  * @obj: pointer to message object state structure
364  *
365  * Return Value: negative value reports error.
366  *      Positive value indicates immediate reception of message.
367  * File: src/usbcan.c
368  */
369 int usbcan_pre_read_config(struct canchip_t *chip, struct msgobj_t *obj)
370 {
371         return 0;
372 }
373
374 #define MAX_TRANSMIT_WAIT_LOOPS 10
375 /**
376  * usbcan_pre_write_config: - prepares message object for message transmission
377  * @chip: pointer to chip state structure
378  * @obj: pointer to message object state structure
379  * @msg: pointer to CAN message
380  *
381  * This function prepares selected message object for future initiation
382  * of message transmission by usbcan_send_msg() function.
383  * The CAN message data and message ID are transfered from @msg slot
384  * into chip buffer in this function.
385  * Return Value: negative value reports error.
386  * File: src/usbcan.c
387  */
388 int usbcan_pre_write_config(struct canchip_t *chip, struct msgobj_t *obj,
389                                                         struct canmsg_t *msg)
390 {
391         struct usbcan_usb *dev=(struct usbcan_usb*)chip->chip_data;
392         int i=0;
393         int len;
394         u8 *ptr;
395
396         if (!dev)
397                 return -ENODEV;
398         /* Wait until Transmit Buffer Status is released */
399         while ( usbcan_chip_queue_status(chip) &&
400                                                 i++<MAX_TRANSMIT_WAIT_LOOPS) {
401                 udelay(i);
402         }
403         if (usbcan_chip_queue_status(chip)){
404                 CANMSG("Buffer full, cannot send message\n");
405                 return -EIO;
406         }
407
408         *(uint8_t *)(dev->tx_msg)=chip->chip_idx & 0xFF;
409
410         len = msg->length;
411         if(len > CAN_MSG_LENGTH) len = CAN_MSG_LENGTH;
412
413         *(uint8_t *)(dev->tx_msg+1)=len & 0xFF;
414         *(uint16_t *)(dev->tx_msg+2)=cpu_to_le16(msg->flags);
415         *(uint32_t *)(dev->tx_msg+4)=cpu_to_le32(msg->id);
416
417         for(ptr=dev->tx_msg+8,i=0; i < len; ptr++,i++) {
418                 *ptr=msg->data[i] & 0xFF;
419         }
420         for(; i < 8; ptr++,i++) {
421                 *ptr=0;
422         }
423         return 0;
424 }
425
426 /**
427  * usbcan_send_msg: - initiate message transmission
428  * @chip: pointer to chip state structure
429  * @obj: pointer to message object state structure
430  * @msg: pointer to CAN message
431  *
432  * This function is called after usbcan_pre_write_config() function,
433  * which prepares data in chip buffer.
434  * Return Value: negative value reports error.
435  * File: src/usbcan.c
436  */
437 int usbcan_send_msg(struct canchip_t *chip, struct msgobj_t *obj,
438                                                         struct canmsg_t *msg)
439 {
440         struct usbcan_usb *dev=(struct usbcan_usb*)chip->chip_data;
441         int len,retval;
442
443         if (!dev)
444                 return -ENODEV;
445
446         set_bit(USBCAN_TX_PENDING,&dev->flags);
447         retval=usb_bulk_msg(dev->udev,
448                         usb_sndbulkpipe(dev->udev, dev->bulk_out_endpointAddr),
449                         &dev->tx_msg, 16,
450                         &len,10000);
451         clear_bit(USBCAN_TX_PENDING,&dev->flags);
452         if (retval){
453                 CANMSG("URB error %d\n",retval);
454                 return -EIO;
455         }
456         if (len!=16){
457                 CANMSG("CAN message not sent\n");
458                 return -EIO;
459         }
460         CANMSG("Message sent\n");
461
462         if(obj->tx_slot){
463                 // Do local transmitted message distribution if enabled
464                 if (processlocal){
465                         // fill CAN message timestamp
466                         can_filltimestamp(&obj->tx_slot->msg.timestamp);
467
468                         obj->tx_slot->msg.flags |= MSG_LOCAL;
469                         canque_filter_msg2edges(obj->qends, &obj->tx_slot->msg);
470                 }
471                 // Free transmitted slot
472                 canque_free_outslot(obj->qends, obj->tx_qedge, obj->tx_slot);
473                 obj->tx_slot=NULL;
474         }
475
476         can_msgobj_clear_fl(obj,TX_PENDING);
477         return 0;
478 }
479
480 /**
481  * usbcan_check_tx_stat: - checks state of transmission engine
482  * @chip: pointer to chip state structure
483  *
484  * Return Value: negative value reports error.
485  *      Positive return value indicates transmission under way status.
486  *      Zero value indicates finishing of all issued transmission requests.
487  * File: src/usbcan.c
488  */
489 int usbcan_check_tx_stat(struct canchip_t *chip)
490 {
491         struct usbcan_usb *dev=(struct usbcan_usb*)chip->chip_data;
492         if (!dev)
493                 return 0;
494         if (test_bit(USBCAN_TX_PENDING,&dev->flags))
495                 return 1;
496         return 0;
497 }
498
499 /**
500  * usbcan_set_btregs: -  configures bitrate registers
501  * @chip: pointer to chip state structure
502  * @btr0: bitrate register 0
503  * @btr1: bitrate register 1
504  *
505  * Return Value: negative value reports error.
506  * File: src/usbcan.c
507  */
508 int usbcan_set_btregs(struct canchip_t *chip, unsigned short btr0,
509                                                         unsigned short btr1)
510 {
511         int retval;
512         u8      buf[16];
513         struct usbcan_usb *dev=(struct usbcan_usb*)chip->chip_data;
514         uint16_t value=(btr1&0xFF)<<8 | (btr0&0xFF);
515
516         if (!dev)
517                 return -ENODEV;
518
519         retval = usb_control_msg(dev->udev,
520         usb_rcvctrlpipe(dev->udev, 0),
521         USBCAN_VENDOR_SET_BTREGS,
522         USB_TYPE_VENDOR,
523         cpu_to_le16(value), cpu_to_le16(chip->chip_idx),
524         &buf, 16,
525         10000);
526
527         if (retval==1){
528                 if(buf[0]==1)
529                         return 0;
530         }
531         return -ENODEV;
532 }
533
534 /**
535  * usbcan_start_chip: -  starts chip message processing
536  * @chip: pointer to chip state structure
537  *
538  * Return Value: negative value reports error.
539  * File: src/usbcan.c
540  */
541 int usbcan_start_chip(struct canchip_t *chip)
542 {
543         int retval;
544         u8      buf[16];
545         struct usbcan_usb *dev=(struct usbcan_usb*)chip->chip_data;
546
547         if (!dev)
548                 return -ENODEV;
549
550         retval = usb_control_msg(dev->udev,
551         usb_rcvctrlpipe(dev->udev, 0),
552         USBCAN_VENDOR_START_CHIP,
553         USB_TYPE_VENDOR,
554         cpu_to_le16(0), cpu_to_le16(chip->chip_idx),
555         &buf, 16,
556         10000);
557
558         if (retval==1){
559                 if(buf[0]==1)
560                         return 0;
561         }
562         return -ENODEV;
563 }
564
565 /**
566  * usbcan_chip_queue_status: -  gets queue status from usb device
567  * @chip: pointer to chip state structure
568  *
569  * Return Value: negative value reports error.
570  * 0 means queue is not full
571  * 1 means queue is full
572  * File: src/usbcan.c
573  */
574 int usbcan_chip_queue_status(struct canchip_t *chip)
575 {
576         int retval;
577         u8      buf[16];
578         struct usbcan_usb *dev=(struct usbcan_usb*)chip->chip_data;
579
580         if (!dev)
581                 return -ENODEV;
582         retval = usb_control_msg(dev->udev,
583         usb_rcvctrlpipe(dev->udev, 0),
584         USBCAN_VENDOR_CHECK_TX_STAT,
585         USB_TYPE_VENDOR,
586         cpu_to_le16(0), cpu_to_le16(chip->chip_idx),
587         &buf, 16,
588         10000);
589
590         if (retval==1){
591                 CANMSG("Chip_queue_status: %d\n",buf[0]);
592                 if(buf[0]==1)
593                         return 0;
594                 if(buf[0]==0)
595                         return 1;
596         }
597         CANMSG("Chip_queue_status error: %d\n",retval);
598         return -ENODEV;
599 }
600
601 /**
602  * usbcan_stop_chip: -  stops chip message processing
603  * @chip: pointer to chip state structure
604  *
605  * Return Value: negative value reports error.
606  * File: src/usbcan.c
607  */
608 int usbcan_stop_chip(struct canchip_t *chip)
609 {
610         int retval;
611         u8      buf[16];
612         struct usbcan_usb *dev=(struct usbcan_usb*)chip->chip_data;
613
614         if (!dev)
615                 return -ENODEV;
616
617         retval = usb_control_msg(dev->udev,
618         usb_rcvctrlpipe(dev->udev, 0),
619         USBCAN_VENDOR_STOP_CHIP,
620         USB_TYPE_VENDOR,
621         cpu_to_le16(0), cpu_to_le16(chip->chip_idx),
622         &buf, 16,
623         10000);
624
625         if (retval==1){
626                 if(buf[0]==1)
627                         return 0;
628         }
629         return -ENODEV;
630 }
631
632 /**
633  * usbcan_register_devs: - attaches usb device data to the chip structure
634  * @chip: pointer to chip state structure
635  * @data: usb device data
636  *
637  * File: src/usbcan.c
638  */
639 void usbcan_register_devs(struct canchip_t *chip,void *data){
640         struct usbcan_devs *usbdevs=(struct usbcan_devs *)data;
641         if (!usbdevs){
642             CANMSG("Bad structure given\n");
643             return;
644         }
645         if (chip->chip_idx>=usbdevs->count) {
646             CANMSG("Requested chip number is bigger than chip count\n");
647             return;
648         }
649
650         usbdevs->devs[chip->chip_idx]->chip=chip;
651         chip->chip_data=(void *)usbdevs->devs[chip->chip_idx];
652 }
653
654 /**
655  * usbcan_attach_to_chip: - attaches to the chip, setups registers and state
656  * @chip: pointer to chip state structure
657  *
658  * Return Value: negative value reports error.
659  * File: src/usbcan.c
660  */
661 int usbcan_attach_to_chip(struct canchip_t *chip)
662 {
663         struct usbcan_usb *dev = (struct usbcan_usb *)chip->chip_data;
664
665         /* start kernel thread */
666         dev->comthread=can_kthread_run(usbcan_read_kthread, (void *)dev, "usbcan_%d",chip->chip_idx);
667
668         return 0;
669 }
670
671 /**
672  * usbcan_release_chip: - called before chip structure removal if %CHIP_ATTACHED is set
673  * @chip: pointer to chip state structure
674  *
675  * Return Value: negative value reports error.
676  * File: src/usbcan.c
677  */
678 int usbcan_release_chip(struct canchip_t *chip)
679 {
680         struct usbcan_usb *dev = (struct usbcan_usb *)chip->chip_data;
681
682         usbcan_stop_chip(chip);
683
684         /* terminate the kernel thread */
685         can_kthread_stop(dev->comthread);
686
687         return 0;
688 }
689
690 /**
691  * usbcan_remote_request: - configures message object and asks for RTR message
692  * @chip: pointer to chip state structure
693  * @obj: pointer to message object structure
694  *
695  * Return Value: negative value reports error.
696  * File: src/usbcan.c
697  */
698 int usbcan_remote_request(struct canchip_t *chip, struct msgobj_t *obj)
699 {
700         CANMSG("usbcan_remote_request not implemented\n");
701         return -ENOSYS;
702 }
703
704 /**
705  * usbcan_standard_mask: - setup of mask for message filtering
706  * @chip: pointer to chip state structure
707  * @code: can message acceptance code
708  * @mask: can message acceptance mask
709  *
710  * Return Value: negative value reports error.
711  * File: src/usbcan.c
712  */
713 int usbcan_standard_mask(struct canchip_t *chip, unsigned short code,
714                 unsigned short mask)
715 {
716         CANMSG("usbcan_standard_mask not implemented\n");
717         return -ENOSYS;
718 }
719
720 /**
721  * usbcan_clear_objects: - clears state of all message object residing in chip
722  * @chip: pointer to chip state structure
723  *
724  * Return Value: negative value reports error.
725  * File: src/usbcan.c
726  */
727 int usbcan_clear_objects(struct canchip_t *chip)
728 {
729         CANMSG("usbcan_clear_objects not implemented\n");
730         return -ENOSYS;
731 }
732
733 /**
734  * usbcan_config_irqs: - tunes chip hardware interrupt delivery
735  * @chip: pointer to chip state structure
736  * @irqs: requested chip IRQ configuration
737  *
738  * Return Value: negative value reports error.
739  * File: src/usbcan.c
740  */
741 int usbcan_config_irqs(struct canchip_t *chip, short irqs)
742 {
743         CANMSG("usbcan_config_irqs not implemented\n");
744         return -ENOSYS;
745 }
746
747 /**
748  * usbcan_irq_write_handler: - part of ISR code responsible for transmit events
749  * @chip: pointer to chip state structure
750  * @obj: pointer to attached queue description
751  *
752  * The main purpose of this function is to read message from attached queues
753  * and transfer message contents into CAN controller chip.
754  * This subroutine is called by
755  * usbcan_irq_write_handler() for transmit events.
756  * File: src/usbcan.c
757  */
758 void usbcan_irq_write_handler(struct canchip_t *chip, struct msgobj_t *obj)
759 {
760         int cmd;
761
762         if(obj->tx_slot){
763                 // Do local transmitted message distribution if enabled
764                 if (processlocal){
765                         // fill CAN message timestamp
766                         can_filltimestamp(&obj->tx_slot->msg.timestamp);
767
768                         obj->tx_slot->msg.flags |= MSG_LOCAL;
769                         canque_filter_msg2edges(obj->qends, &obj->tx_slot->msg);
770                 }
771                 // Free transmitted slot
772                 canque_free_outslot(obj->qends, obj->tx_qedge, obj->tx_slot);
773                 obj->tx_slot=NULL;
774         }
775
776         can_msgobj_clear_fl(obj,TX_PENDING);
777         cmd=canque_test_outslot(obj->qends, &obj->tx_qedge, &obj->tx_slot);
778         if(cmd<0)
779                 return;
780         can_msgobj_set_fl(obj,TX_PENDING);
781
782         if (chip->chipspecops->pre_write_config(chip, obj, &obj->tx_slot->msg)) {
783                 obj->ret = -1;
784                 canque_notify_inends(obj->tx_qedge, CANQUEUE_NOTIFY_ERRTX_PREP);
785                 canque_free_outslot(obj->qends, obj->tx_qedge, obj->tx_slot);
786                 obj->tx_slot=NULL;
787                 return;
788         }
789         if (chip->chipspecops->send_msg(chip, obj, &obj->tx_slot->msg)) {
790                 obj->ret = -1;
791                 canque_notify_inends(obj->tx_qedge, CANQUEUE_NOTIFY_ERRTX_SEND);
792                 canque_free_outslot(obj->qends, obj->tx_qedge, obj->tx_slot);
793                 obj->tx_slot=NULL;
794                 return;
795         }
796 }
797
798 #define MAX_RETR 10
799
800 /**
801  * usbcan_irq_handler: - interrupt service routine
802  * @irq: interrupt vector number, this value is system specific
803  * @chip: pointer to chip state structure
804  *
805  * Interrupt handler is activated when state of CAN controller chip changes,
806  * there is message to be read or there is more space for new messages or
807  * error occurs. The receive events results in reading of the message from
808  * CAN controller chip and distribution of message through attached
809  * message queues.
810  * File: src/usbcan.c
811  */
812 int usbcan_irq_handler(int irq, struct canchip_t *chip)
813 {
814 /*      int irq_register, status, error_code;
815         struct msgobj_t *obj=chip->msgobj[0];
816         int loop_cnt=CHIP_MAX_IRQLOOP;
817
818         irq_register=can_read_reg(chip,SJAIR);
819 //      DEBUGMSG("sja1000_irq_handler: SJAIR:%02x\n",irq_register);
820 //      DEBUGMSG("sja1000_irq_handler: SJASR:%02x\n",
821 //                                      can_read_reg(chip,SJASR));
822
823         if ((irq_register & (sjaIR_BEI|sjaIR_EPI|sjaIR_DOI|sjaIR_EI|sjaIR_TI|sjaIR_RI)) == 0)
824                 return CANCHIP_IRQ_NONE;
825
826         if(!(chip->flags&CHIP_CONFIGURED)) {
827                 CANMSG("usbcan_irq_handler: called for non-configured device, irq_register 0x%02x\n", irq_register);
828                 return CANCHIP_IRQ_NONE;
829         }
830
831         status=can_read_reg(chip,SJASR);
832
833         do {
834
835                 if(!loop_cnt--) {
836                         CANMSG("usbcan_irq_handler IRQ %d stuck\n",irq);
837                         return CANCHIP_IRQ_STUCK;
838                 }
839
840                 // (irq_register & sjaIR_TI)
841                 //      old variant using SJAIR, collides with intended use with irq_accept
842                 if (((status & sjaSR_TBS) && can_msgobj_test_fl(obj,TX_PENDING))||
843                     (can_msgobj_test_fl(obj,TX_REQUEST))) {
844                         DEBUGMSG("sja1000_irq_handler: TI or TX_PENDING and TBS\n");
845                         obj->ret = 0;
846                         can_msgobj_set_fl(obj,TX_REQUEST);
847                         while(!can_msgobj_test_and_set_fl(obj,TX_LOCK)){
848                                 can_msgobj_clear_fl(obj,TX_REQUEST);
849
850                                 if (can_read_reg(chip, SJASR) & sjaSR_TBS)
851                                         usbcan_irq_write_handler(chip, obj);
852
853                                 can_msgobj_clear_fl(obj,TX_LOCK);
854                                 if(!can_msgobj_test_fl(obj,TX_REQUEST)) break;
855                                 DEBUGMSG("TX looping in sja1000_irq_handler\n");
856                         }
857                 }
858                 if ((irq_register & (sjaIR_EI|sjaIR_BEI|sjaIR_EPI|sjaIR_DOI)) != 0) {
859                         // Some error happened
860                         error_code=can_read_reg(chip,SJAECC);
861                         sja1000_report_error(chip, status, irq_register, error_code);
862 // FIXME: chip should be brought to usable state. Transmission cancelled if in progress.
863 // Reset flag set to 0 if chip is already off the bus. Full state report
864                         obj->ret=-1;
865
866                         if(error_code == 0xd9) {
867                                 obj->ret= -ENXIO;
868                                 // no such device or address - no ACK received
869                         }
870                         if(obj->tx_retry_cnt++>MAX_RETR) {
871                                 can_write_reg(chip, sjaCMR_AT, SJACMR); // cancel any transmition
872                                 obj->tx_retry_cnt = 0;
873                         }
874                         if(status&sjaSR_BS) {
875                                 CANMSG("bus-off, resetting usbcan\n");
876                                 can_write_reg(chip, 0, SJAMOD);
877                         }
878
879                         if(obj->tx_slot){
880                                 canque_notify_inends(obj->tx_qedge, CANQUEUE_NOTIFY_ERRTX_BUS);
881                                 //canque_free_outslot(obj->qends, obj->tx_qedge, obj->tx_slot);
882                                 //obj->tx_slot=NULL;
883                         }
884
885                 } else {
886                         if(sja1000_report_error_limit_counter)
887                                 sja1000_report_error_limit_counter--;
888                         obj->tx_retry_cnt=0;
889                 }
890
891                 irq_register=can_read_reg(chip,SJAIR);
892
893                 status=can_read_reg(chip,SJASR);
894
895                 if(((status & sjaSR_TBS) && can_msgobj_test_fl(obj,TX_PENDING)) ||
896                    (irq_register & sjaIR_TI))
897                          can_msgobj_set_fl(obj,TX_REQUEST);
898
899         } while((irq_register & (sjaIR_BEI|sjaIR_EPI|sjaIR_DOI|sjaIR_EI|sjaIR_RI)) ||
900                 (can_msgobj_test_fl(obj,TX_REQUEST) && !can_msgobj_test_fl(obj,TX_LOCK)) ||
901                 (status & sjaSR_RBS));
902 */
903         return CANCHIP_IRQ_HANDLED;
904 }
905
906 /**
907  * usbcan_wakeup_tx: - wakeups TX processing
908  * @chip: pointer to chip state structure
909  * @obj: pointer to message object structure
910  *
911  * Function is responsible for initiating message transmition.
912  * It is responsible for clearing of object TX_REQUEST flag
913  *
914  * Return Value: negative value reports error.
915  * File: src/usbcan.c
916  */
917 int usbcan_wakeup_tx(struct canchip_t *chip, struct msgobj_t *obj)
918 {
919         CANMSG("Trying to send message\n");
920         can_preempt_disable();
921
922         can_msgobj_set_fl(obj,TX_PENDING);
923         can_msgobj_set_fl(obj,TX_REQUEST);
924         while(!can_msgobj_test_and_set_fl(obj,TX_LOCK)){
925                 can_msgobj_clear_fl(obj,TX_REQUEST);
926
927                 if (!usbcan_chip_queue_status(chip)){
928                         obj->tx_retry_cnt=0;
929                         usbcan_irq_write_handler(chip, obj);
930                 }
931
932                 can_msgobj_clear_fl(obj,TX_LOCK);
933                 if(!can_msgobj_test_fl(obj,TX_REQUEST)) break;
934                 DEBUGMSG("TX looping in usbcan_wakeup_tx\n");
935         }
936
937         can_preempt_enable();
938         return 0;
939 }
940
941 int usbcan_chipregister(struct chipspecops_t *chipspecops)
942 {
943         CANMSG("initializing usbcan chip operations\n");
944         chipspecops->chip_config=usbcan_chip_config;
945         chipspecops->baud_rate=usbcan_baud_rate;
946         chipspecops->standard_mask=usbcan_standard_mask;
947         chipspecops->extended_mask=usbcan_extended_mask;
948         chipspecops->message15_mask=usbcan_extended_mask;
949         chipspecops->clear_objects=usbcan_clear_objects;
950         chipspecops->config_irqs=usbcan_config_irqs;
951         chipspecops->pre_read_config=usbcan_pre_read_config;
952         chipspecops->pre_write_config=usbcan_pre_write_config;
953         chipspecops->send_msg=usbcan_send_msg;
954         chipspecops->check_tx_stat=usbcan_check_tx_stat;
955         chipspecops->wakeup_tx=usbcan_wakeup_tx;
956         chipspecops->remote_request=usbcan_remote_request;
957         chipspecops->enable_configuration=usbcan_enable_configuration;
958         chipspecops->disable_configuration=usbcan_disable_configuration;
959         chipspecops->attach_to_chip=usbcan_attach_to_chip;
960         chipspecops->release_chip=usbcan_release_chip;
961         chipspecops->set_btregs=usbcan_set_btregs;
962         chipspecops->start_chip=usbcan_start_chip;
963         chipspecops->stop_chip=usbcan_stop_chip;
964         chipspecops->irq_handler=usbcan_irq_handler;
965         chipspecops->irq_accept=NULL;
966         return 0;
967 }
968
969 /**
970  * usbcan_fill_chipspecops - fills chip specific operations
971  * @chip: pointer to chip representation structure
972  *
973  * The function fills chip specific operations for sja1000 (PeliCAN) chip.
974  *
975  * Return Value: returns negative number in the case of fail
976  */
977 int usbcan_fill_chipspecops(struct canchip_t *chip)
978 {
979         chip->chip_type="usbcan";
980         chip->max_objects=1;
981         usbcan_chipregister(chip->chipspecops);
982         return 0;
983 }
984
985 /**
986  * usbcan_init_chip_data - Initialize chips
987  * @candev: Pointer to candevice/board structure
988  * @chipnr: Number of the CAN chip on the hardware card
989  *
990  * The function usbcan_init_chip_data() is used to initialize the hardware
991  * structure containing information about the CAN chips.
992  * %CHIP_TYPE represents the type of CAN chip. %CHIP_TYPE can be "i82527" or
993  * "sja1000".
994  * The @chip_base_addr entry represents the start of the 'official' memory map
995  * of the installed chip. It's likely that this is the same as the @io_addr
996  * argument supplied at module loading time.
997  * The @clock entry holds the chip clock value in Hz.
998  * The entry @sja_cdr_reg holds hardware specific options for the Clock Divider
999  * register. Options defined in the %sja1000.h file:
1000  * %sjaCDR_CLKOUT_MASK, %sjaCDR_CLK_OFF, %sjaCDR_RXINPEN, %sjaCDR_CBP, %sjaCDR_PELICAN
1001  * The entry @sja_ocr_reg holds hardware specific options for the Output Control
1002  * register. Options defined in the %sja1000.h file:
1003  * %sjaOCR_MODE_BIPHASE, %sjaOCR_MODE_TEST, %sjaOCR_MODE_NORMAL, %sjaOCR_MODE_CLOCK,
1004  * %sjaOCR_TX0_LH, %sjaOCR_TX1_ZZ.
1005  * The entry @int_clk_reg holds hardware specific options for the Clock Out
1006  * register. Options defined in the %i82527.h file:
1007  * %iCLK_CD0, %iCLK_CD1, %iCLK_CD2, %iCLK_CD3, %iCLK_SL0, %iCLK_SL1.
1008  * The entry @int_bus_reg holds hardware specific options for the Bus
1009  * Configuration register. Options defined in the %i82527.h file:
1010  * %iBUS_DR0, %iBUS_DR1, %iBUS_DT1, %iBUS_POL, %iBUS_CBY.
1011  * The entry @int_cpu_reg holds hardware specific options for the cpu interface
1012  * register. Options defined in the %i82527.h file:
1013  * %iCPU_CEN, %iCPU_MUX, %iCPU_SLP, %iCPU_PWD, %iCPU_DMC, %iCPU_DSC, %iCPU_RST.
1014  * Return Value: The function always returns zero
1015  * File: src/usbcan.c
1016  */
1017 int usbcan_init_chip_data(struct candevice_t *candev, int chipnr)
1018 {
1019         struct canchip_t *chip=candev->chip[chipnr];
1020
1021         usbcan_fill_chipspecops(chip);
1022
1023         candev->chip[chipnr]->flags|=CHIP_IRQ_CUSTOM;
1024         candev->chip[chipnr]->chip_base_addr=0;
1025         candev->chip[chipnr]->clock = 0;
1026
1027         return 0;
1028 }
1029
1030
1031
1032 /* --------------------------------------------------------------------------------------------------- */
1033 static int usbcan_sleep_thread(struct usbcan_usb *dev)
1034 {
1035         int     rc = 0;
1036
1037         /* Wait until a signal arrives or we are woken up */
1038         for (;;) {
1039                 try_to_freeze();
1040                 set_current_state(TASK_INTERRUPTIBLE);
1041                 if (signal_pending(current)) {
1042                         rc = -EINTR;
1043                         break;
1044                 }
1045                 if (
1046                         can_kthread_should_stop() ||
1047                         test_bit(USBCAN_DATA_READ,&dev->flags) ||
1048                         test_bit(USBCAN_TERMINATE,&dev->flags) ||
1049                         test_bit(USBCAN_ERROR,&dev->flags)
1050                 )
1051                         break;
1052                 schedule();
1053         }
1054         __set_current_state(TASK_RUNNING);
1055         return rc;
1056 }
1057
1058 static void usbcan_rcv(struct urb *urb)
1059 {
1060         struct usbcan_usb *dev = urb->context;
1061         int retval;
1062
1063         if (!test_bit(USBCAN_THREAD_RUNNING,&dev->flags))
1064                 return;
1065
1066         switch (urb->status) {
1067         case 0:
1068                 /* success */
1069                 set_bit(USBCAN_DATA_READ,&dev->flags);
1070                 CANMSG("Message received\n");
1071                 if (test_bit(USBCAN_THREAD_RUNNING,&dev->flags))
1072                         wake_up_process(dev->comthread);
1073                 return;
1074         case -ECONNRESET:
1075         case -ENOENT:
1076         case -ESHUTDOWN:
1077                 /* this urb is terminated, clean up */
1078                 CANMSG("%s - urb shutting down with status: %d\n", __FUNCTION__, urb->status);
1079                 set_bit(USBCAN_TERMINATE,&dev->flags);
1080                 return;
1081         default:
1082 //              CANMSG("%s - nonzero urb status received: %d\n", __FUNCTION__, urb->status);
1083                 break;
1084         }
1085
1086         retval = usb_submit_urb (urb, GFP_ATOMIC);
1087         if (retval<0){
1088                 CANMSG("%s - usb_submit_urb failed with result %d ... retrying\n",
1089                      __FUNCTION__, retval);
1090                 set_bit(USBCAN_ERROR,&dev->flags);
1091                 if (test_bit(USBCAN_THREAD_RUNNING,&dev->flags))
1092                         wake_up_process(dev->comthread);
1093         }
1094 }
1095
1096 int usbcan_read_kthread(void *data)
1097 {
1098         int retval=0;
1099         struct usbcan_usb *dev=(struct usbcan_usb *)data;
1100         struct msgobj_t *obj;
1101
1102   /* this is normal work to do */
1103   CANMSG ("usbcan thread started!\n");
1104
1105         dev->rx = usb_alloc_urb(0, GFP_KERNEL);
1106         if (!dev->rx){
1107                 CANMSG("Error allocating usb urb\n");
1108                 goto error;
1109         }
1110         dev->rx->dev = dev->udev;
1111         usb_fill_bulk_urb(dev->rx, dev->udev,
1112                          usb_rcvbulkpipe(dev->udev, dev->bulk_in_endpointAddr),
1113                          &dev->rx_msg, 16,
1114                          usbcan_rcv, dev);
1115
1116         set_bit(USBCAN_THREAD_RUNNING,&dev->flags);
1117   /* an endless loop in which we are doing our work */
1118   for(;;)
1119   {
1120                 retval=usb_submit_urb(dev->rx, GFP_ATOMIC);
1121                 if (retval){
1122                         CANMSG("URB error %d\n",retval);
1123                         set_bit(USBCAN_ERROR,&dev->flags);
1124                         break;
1125                 }
1126                 /* We need to do a memory barrier here to be sure that
1127                 the flags are visible on all CPUs. */
1128                 mb();
1129                 /* fall asleep */
1130                 usbcan_sleep_thread(dev);
1131                 /* We need to do a memory barrier here to be sure that
1132                 the flags are visible on all CPUs. */
1133                 mb();
1134
1135                 /* here we are back from sleep because we caught a signal. */
1136                 if (can_kthread_should_stop())
1137                 {
1138                         /* we received a request to terminate ourself */
1139                         break;
1140                 }
1141
1142                 { /* Normal work to do */
1143                         if (test_bit(USBCAN_DATA_READ,&dev->flags)){
1144                                 int i, len;
1145                                 clear_bit(USBCAN_DATA_READ,&dev->flags);
1146                                 CANMSG("Thread got received message\n");
1147
1148                                 if ((dev->chip)&&
1149                                         (dev->chip->flags & CHIP_CONFIGURED)
1150                                 ){
1151                                         u8 *ptr;
1152
1153                                         obj=dev->chip->msgobj[0];
1154
1155                                         len=*(uint8_t *)(dev->rx_msg+1);
1156                                         if(len > CAN_MSG_LENGTH) len = CAN_MSG_LENGTH;
1157                                         obj->rx_msg.length = len;
1158
1159                                         obj->rx_msg.flags=le16_to_cpu(*(uint16_t *)(dev->rx_msg+2));
1160                                         obj->rx_msg.id=le32_to_cpu((*(uint32_t *)(dev->rx_msg+4)));
1161
1162                                         for(ptr=dev->rx_msg+8,i=0; i < len; ptr++,i++) {
1163                                                 obj->rx_msg.data[i]=*ptr;
1164                                         }
1165
1166                                         // fill CAN message timestamp
1167                                         can_filltimestamp(&obj->rx_msg.timestamp);
1168                                         canque_filter_msg2edges(obj->qends, &obj->rx_msg);
1169                                 }
1170                                 else
1171                                         CANMSG("Destination chip not found\n");
1172                         }
1173     }
1174   }
1175         clear_bit(USBCAN_THREAD_RUNNING,&dev->flags);
1176
1177   /* here we go only in case of termination of the thread */
1178         if (dev->rx){
1179                 usb_kill_urb(dev->rx);
1180                 usb_free_urb(dev->rx);
1181         }
1182
1183   CANMSG ("usbcan thread finished!\n");
1184   return 0;
1185 error:
1186   /* cleanup the thread, leave */
1187   CANMSG ("kernel thread terminated!\n");
1188   return -ENOMEM;
1189 }
1190
1191 static int usbcan_probe(struct usb_interface *interface, const struct usb_device_id *id)
1192 {
1193         struct usbcan_devs *usbdevs=NULL;
1194         struct usb_host_interface *iface_desc;
1195         struct usb_endpoint_descriptor *endpoint;
1196         size_t buffer_size;
1197         int i,j,k;
1198         int retval = -ENOMEM;
1199
1200         iface_desc = interface->cur_altsetting;
1201         if (iface_desc->desc.bNumEndpoints % 2){
1202                 err("Endpoint count must be even");
1203                 goto noalloc;
1204         }
1205
1206         usbcan_chip_count = iface_desc->desc.bNumEndpoints / 2;
1207
1208         usbdevs = (struct usbcan_devs *) can_checked_malloc(sizeof(struct usbcan_devs));
1209         if (!usbdevs) {
1210                 err("Out of memory");
1211                 goto error;
1212         }
1213         memset(usbdevs, 0, sizeof(struct usbcan_devs));
1214
1215         usbdevs->count=usbcan_chip_count;
1216
1217         usbdevs->devs = (struct usbcan_usb **) can_checked_malloc(usbcan_chip_count * sizeof(struct usbcan_usb *));
1218         if (!usbdevs->devs) {
1219                 err("Out of memory");
1220                 goto error;
1221         }
1222         memset(usbdevs->devs, 0, usbcan_chip_count * sizeof(struct usbcan_usb *));
1223
1224         for (j=0;j<usbcan_chip_count;j++){
1225                 struct usbcan_usb *dev;
1226                 int epnum=-1,was;
1227
1228                 /* allocate memory for our device state and initialize it */
1229                 usbdevs->devs[j] = (struct usbcan_usb *) can_checked_malloc(sizeof(struct usbcan_usb));
1230                 if (!usbdevs->devs[j]) {
1231                         err("Out of memory");
1232                         goto error;
1233                 }
1234                 memset(usbdevs->devs[j], 0, sizeof(struct usbcan_usb));
1235                 dev=usbdevs->devs[j];
1236
1237                 mutex_init(&dev->io_mutex);
1238                 dev->udev = interface_to_usbdev(interface);
1239                 dev->interface = interface;
1240
1241                 /* set up the endpoint information */
1242                 for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {
1243                         endpoint = &iface_desc->endpoint[i].desc;
1244
1245                         if (epnum==-1){
1246                                 was=0;
1247                                 for (k=0;k<j;k++){
1248                                         if ((usbdevs->devs[k]->bulk_in_endpointAddr & USB_ENDPOINT_NUMBER_MASK) == (endpoint->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK))
1249                                                 was=1;
1250                                 }
1251                                 if (was) continue;
1252                                 epnum=endpoint->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK;
1253                         }
1254
1255                         if (!dev->bulk_in_endpointAddr &&
1256                                         usb_endpoint_is_bulk_in(endpoint)) {
1257                                 if (epnum == (endpoint->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK)){
1258                                         /* we found a bulk in endpoint */
1259                                         buffer_size = le16_to_cpu(endpoint->wMaxPacketSize);
1260                                         dev->bulk_in_size = buffer_size;
1261                                         dev->bulk_in_endpointAddr = endpoint->bEndpointAddress;
1262                                         dev->bulk_in_buffer = can_checked_malloc(buffer_size);
1263                                         if (!dev->bulk_in_buffer) {
1264                                                 err("Could not allocate bulk_in_buffer");
1265                                                 goto error;
1266                                         }
1267                                 }
1268                         }
1269
1270                         if (!dev->bulk_out_endpointAddr &&
1271                                         usb_endpoint_is_bulk_out(endpoint)) {
1272                                 if (epnum == (endpoint->bEndpointAddress & USB_ENDPOINT_NUMBER_MASK)){
1273                                 /* we found a bulk out endpoint */
1274                                         dev->bulk_out_endpointAddr = endpoint->bEndpointAddress;
1275                                 }
1276                         }
1277
1278                 }
1279                 if (!(dev->bulk_in_endpointAddr && dev->bulk_out_endpointAddr)) {
1280                         err("Could not find all bulk-in and bulk-out endpoints for chip %d",j);
1281                         goto error;
1282                 }
1283         }
1284         /* save our data pointer in this interface device */
1285         usb_set_intfdata(interface, usbdevs);
1286
1287         if (!(usbdevs->candev=register_usbdev("usbcan",(void *) usbdevs, usbcan_register_devs)))
1288                 goto register_error;
1289
1290         /* let the user know what node this device is now attached to */
1291         DEBUGMSG("USBCAN device now attached");
1292         return 0;
1293
1294 register_error:
1295         cleanup_usbdev(usbdevs->candev);
1296 error:
1297         if (usbdevs){
1298                 if (usbdevs->devs){
1299                         if (usbdevs->devs[0]){
1300                                 usb_put_dev(usbdevs->devs[0]->udev);
1301                         }
1302                         for (j=0;j<usbdevs->count;j++){
1303                                 if (!usbdevs->devs[j])  continue;
1304
1305                                 if (usbdevs->devs[j]->bulk_in_buffer)
1306                                         can_checked_free(usbdevs->devs[j]->bulk_in_buffer);
1307                                 if (usbdevs->devs[j]->chip){
1308                                         usbdevs->devs[j]->chip->chip_data=NULL;
1309                                 }
1310                                 can_checked_free(usbdevs->devs[j]);
1311                         }
1312                         can_checked_free(usbdevs->devs);
1313                 }
1314                 can_checked_free(usbdevs);
1315         }
1316 noalloc:
1317         return retval;
1318 }
1319
1320 // Physically disconnected device
1321 static void usbcan_disconnect(struct usb_interface *interface)
1322 {
1323         struct usbcan_devs *usbdevs;
1324         int j;
1325         usbdevs = usb_get_intfdata(interface);
1326         if (usbdevs==NULL){
1327                 CANMSG("USBCAN device seems to be removed\n");
1328                 return;
1329         }
1330         usb_set_intfdata(interface, NULL);
1331
1332         if (usbdevs->devs){
1333                 usb_put_dev((*usbdevs->devs)->udev);
1334         }
1335         cleanup_usbdev(usbdevs->candev);
1336         if (usbdevs->devs){
1337                 for (j=0;j<usbdevs->count;j++){
1338                         if (!usbdevs->devs[j])  continue;
1339
1340                         /* prevent more I/O from starting */
1341                         mutex_lock(&usbdevs->devs[j]->io_mutex);
1342                         usbdevs->devs[j]->interface = NULL;
1343                         mutex_unlock(&usbdevs->devs[j]->io_mutex);
1344
1345                         if (usbdevs->devs[j]->bulk_in_buffer)
1346                                 can_checked_free(usbdevs->devs[j]->bulk_in_buffer);
1347                         // if (usbdevs->devs[j]->chip){
1348                         //      usbdevs->devs[j]->chip->chip_data=NULL;
1349                         // }
1350                         can_checked_free(usbdevs->devs[j]);
1351                         usbdevs->devs[j]=NULL;
1352                 }
1353                 can_checked_free(usbdevs->devs);
1354         }
1355         can_checked_free(usbdevs);
1356
1357         DEBUGMSG("USBCAN now disconnected");
1358 }
1359
1360 int usbcan_init(void){
1361         return usb_register(&usbcan_driver);
1362 }
1363
1364 void usbcan_exit(void){
1365         usb_deregister(&usbcan_driver);
1366 }