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