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