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