ccdc4cdc496fc8977de86ef9be948a04998d165e
[firefly-linux-kernel-4.4.55.git] / drivers / net / can / usb / kvaser_usb.c
1 /*
2  * This program is free software; you can redistribute it and/or
3  * modify it under the terms of the GNU General Public License as
4  * published by the Free Software Foundation version 2.
5  *
6  * Parts of this driver are based on the following:
7  *  - Kvaser linux leaf driver (version 4.78)
8  *  - CAN driver for esd CAN-USB/2
9  *
10  * Copyright (C) 2002-2006 KVASER AB, Sweden. All rights reserved.
11  * Copyright (C) 2010 Matthias Fuchs <matthias.fuchs@esd.eu>, esd gmbh
12  * Copyright (C) 2012 Olivier Sobrie <olivier@sobrie.be>
13  */
14
15 #include <linux/init.h>
16 #include <linux/completion.h>
17 #include <linux/module.h>
18 #include <linux/netdevice.h>
19 #include <linux/usb.h>
20
21 #include <linux/can.h>
22 #include <linux/can/dev.h>
23 #include <linux/can/error.h>
24
25 #define MAX_TX_URBS                     16
26 #define MAX_RX_URBS                     4
27 #define START_TIMEOUT                   1000 /* msecs */
28 #define STOP_TIMEOUT                    1000 /* msecs */
29 #define USB_SEND_TIMEOUT                1000 /* msecs */
30 #define USB_RECV_TIMEOUT                1000 /* msecs */
31 #define RX_BUFFER_SIZE                  3072
32 #define CAN_USB_CLOCK                   8000000
33 #define MAX_NET_DEVICES                 3
34
35 /* Kvaser USB devices */
36 #define KVASER_VENDOR_ID                0x0bfd
37 #define USB_LEAF_DEVEL_PRODUCT_ID       10
38 #define USB_LEAF_LITE_PRODUCT_ID        11
39 #define USB_LEAF_PRO_PRODUCT_ID         12
40 #define USB_LEAF_SPRO_PRODUCT_ID        14
41 #define USB_LEAF_PRO_LS_PRODUCT_ID      15
42 #define USB_LEAF_PRO_SWC_PRODUCT_ID     16
43 #define USB_LEAF_PRO_LIN_PRODUCT_ID     17
44 #define USB_LEAF_SPRO_LS_PRODUCT_ID     18
45 #define USB_LEAF_SPRO_SWC_PRODUCT_ID    19
46 #define USB_MEMO2_DEVEL_PRODUCT_ID      22
47 #define USB_MEMO2_HSHS_PRODUCT_ID       23
48 #define USB_UPRO_HSHS_PRODUCT_ID        24
49 #define USB_LEAF_LITE_GI_PRODUCT_ID     25
50 #define USB_LEAF_PRO_OBDII_PRODUCT_ID   26
51 #define USB_MEMO2_HSLS_PRODUCT_ID       27
52 #define USB_LEAF_LITE_CH_PRODUCT_ID     28
53 #define USB_BLACKBIRD_SPRO_PRODUCT_ID   29
54 #define USB_OEM_MERCURY_PRODUCT_ID      34
55 #define USB_OEM_LEAF_PRODUCT_ID         35
56 #define USB_CAN_R_PRODUCT_ID            39
57
58 /* USB devices features */
59 #define KVASER_HAS_SILENT_MODE          BIT(0)
60 #define KVASER_HAS_TXRX_ERRORS          BIT(1)
61
62 /* Message header size */
63 #define MSG_HEADER_LEN                  2
64
65 /* Can message flags */
66 #define MSG_FLAG_ERROR_FRAME            BIT(0)
67 #define MSG_FLAG_OVERRUN                BIT(1)
68 #define MSG_FLAG_NERR                   BIT(2)
69 #define MSG_FLAG_WAKEUP                 BIT(3)
70 #define MSG_FLAG_REMOTE_FRAME           BIT(4)
71 #define MSG_FLAG_RESERVED               BIT(5)
72 #define MSG_FLAG_TX_ACK                 BIT(6)
73 #define MSG_FLAG_TX_REQUEST             BIT(7)
74
75 /* Can states */
76 #define M16C_STATE_BUS_RESET            BIT(0)
77 #define M16C_STATE_BUS_ERROR            BIT(4)
78 #define M16C_STATE_BUS_PASSIVE          BIT(5)
79 #define M16C_STATE_BUS_OFF              BIT(6)
80
81 /* Can msg ids */
82 #define CMD_RX_STD_MESSAGE              12
83 #define CMD_TX_STD_MESSAGE              13
84 #define CMD_RX_EXT_MESSAGE              14
85 #define CMD_TX_EXT_MESSAGE              15
86 #define CMD_SET_BUS_PARAMS              16
87 #define CMD_GET_BUS_PARAMS              17
88 #define CMD_GET_BUS_PARAMS_REPLY        18
89 #define CMD_GET_CHIP_STATE              19
90 #define CMD_CHIP_STATE_EVENT            20
91 #define CMD_SET_CTRL_MODE               21
92 #define CMD_GET_CTRL_MODE               22
93 #define CMD_GET_CTRL_MODE_REPLY         23
94 #define CMD_RESET_CHIP                  24
95 #define CMD_RESET_CARD                  25
96 #define CMD_START_CHIP                  26
97 #define CMD_START_CHIP_REPLY            27
98 #define CMD_STOP_CHIP                   28
99 #define CMD_STOP_CHIP_REPLY             29
100 #define CMD_GET_CARD_INFO2              32
101 #define CMD_GET_CARD_INFO               34
102 #define CMD_GET_CARD_INFO_REPLY         35
103 #define CMD_GET_SOFTWARE_INFO           38
104 #define CMD_GET_SOFTWARE_INFO_REPLY     39
105 #define CMD_ERROR_EVENT                 45
106 #define CMD_FLUSH_QUEUE                 48
107 #define CMD_RESET_ERROR_COUNTER         49
108 #define CMD_TX_ACKNOWLEDGE              50
109 #define CMD_CAN_ERROR_EVENT             51
110 #define CMD_USB_THROTTLE                77
111 #define CMD_LOG_MESSAGE                 106
112
113 /* error factors */
114 #define M16C_EF_ACKE                    BIT(0)
115 #define M16C_EF_CRCE                    BIT(1)
116 #define M16C_EF_FORME                   BIT(2)
117 #define M16C_EF_STFE                    BIT(3)
118 #define M16C_EF_BITE0                   BIT(4)
119 #define M16C_EF_BITE1                   BIT(5)
120 #define M16C_EF_RCVE                    BIT(6)
121 #define M16C_EF_TRE                     BIT(7)
122
123 /* bittiming parameters */
124 #define KVASER_USB_TSEG1_MIN            1
125 #define KVASER_USB_TSEG1_MAX            16
126 #define KVASER_USB_TSEG2_MIN            1
127 #define KVASER_USB_TSEG2_MAX            8
128 #define KVASER_USB_SJW_MAX              4
129 #define KVASER_USB_BRP_MIN              1
130 #define KVASER_USB_BRP_MAX              64
131 #define KVASER_USB_BRP_INC              1
132
133 /* ctrl modes */
134 #define KVASER_CTRL_MODE_NORMAL         1
135 #define KVASER_CTRL_MODE_SILENT         2
136 #define KVASER_CTRL_MODE_SELFRECEPTION  3
137 #define KVASER_CTRL_MODE_OFF            4
138
139 /* log message */
140 #define KVASER_EXTENDED_FRAME           BIT(31)
141
142 struct kvaser_msg_simple {
143         u8 tid;
144         u8 channel;
145 } __packed;
146
147 struct kvaser_msg_cardinfo {
148         u8 tid;
149         u8 nchannels;
150         __le32 serial_number;
151         __le32 padding;
152         __le32 clock_resolution;
153         __le32 mfgdate;
154         u8 ean[8];
155         u8 hw_revision;
156         u8 usb_hs_mode;
157         __le16 padding2;
158 } __packed;
159
160 struct kvaser_msg_cardinfo2 {
161         u8 tid;
162         u8 channel;
163         u8 pcb_id[24];
164         __le32 oem_unlock_code;
165 } __packed;
166
167 struct kvaser_msg_softinfo {
168         u8 tid;
169         u8 channel;
170         __le32 sw_options;
171         __le32 fw_version;
172         __le16 max_outstanding_tx;
173         __le16 padding[9];
174 } __packed;
175
176 struct kvaser_msg_busparams {
177         u8 tid;
178         u8 channel;
179         __le32 bitrate;
180         u8 tseg1;
181         u8 tseg2;
182         u8 sjw;
183         u8 no_samp;
184 } __packed;
185
186 struct kvaser_msg_tx_can {
187         u8 channel;
188         u8 tid;
189         u8 msg[14];
190         u8 padding;
191         u8 flags;
192 } __packed;
193
194 struct kvaser_msg_rx_can {
195         u8 channel;
196         u8 flag;
197         __le16 time[3];
198         u8 msg[14];
199 } __packed;
200
201 struct kvaser_msg_chip_state_event {
202         u8 tid;
203         u8 channel;
204         __le16 time[3];
205         u8 tx_errors_count;
206         u8 rx_errors_count;
207         u8 status;
208         u8 padding[3];
209 } __packed;
210
211 struct kvaser_msg_tx_acknowledge {
212         u8 channel;
213         u8 tid;
214         __le16 time[3];
215         u8 flags;
216         u8 time_offset;
217 } __packed;
218
219 struct kvaser_msg_error_event {
220         u8 tid;
221         u8 flags;
222         __le16 time[3];
223         u8 channel;
224         u8 padding;
225         u8 tx_errors_count;
226         u8 rx_errors_count;
227         u8 status;
228         u8 error_factor;
229 } __packed;
230
231 struct kvaser_msg_ctrl_mode {
232         u8 tid;
233         u8 channel;
234         u8 ctrl_mode;
235         u8 padding[3];
236 } __packed;
237
238 struct kvaser_msg_flush_queue {
239         u8 tid;
240         u8 channel;
241         u8 flags;
242         u8 padding[3];
243 } __packed;
244
245 struct kvaser_msg_log_message {
246         u8 channel;
247         u8 flags;
248         __le16 time[3];
249         u8 dlc;
250         u8 time_offset;
251         __le32 id;
252         u8 data[8];
253 } __packed;
254
255 struct kvaser_msg {
256         u8 len;
257         u8 id;
258         union   {
259                 struct kvaser_msg_simple simple;
260                 struct kvaser_msg_cardinfo cardinfo;
261                 struct kvaser_msg_cardinfo2 cardinfo2;
262                 struct kvaser_msg_softinfo softinfo;
263                 struct kvaser_msg_busparams busparams;
264                 struct kvaser_msg_tx_can tx_can;
265                 struct kvaser_msg_rx_can rx_can;
266                 struct kvaser_msg_chip_state_event chip_state_event;
267                 struct kvaser_msg_tx_acknowledge tx_acknowledge;
268                 struct kvaser_msg_error_event error_event;
269                 struct kvaser_msg_ctrl_mode ctrl_mode;
270                 struct kvaser_msg_flush_queue flush_queue;
271                 struct kvaser_msg_log_message log_message;
272         } u;
273 } __packed;
274
275 struct kvaser_usb_tx_urb_context {
276         struct kvaser_usb_net_priv *priv;
277         u32 echo_index;
278         int dlc;
279 };
280
281 struct kvaser_usb {
282         struct usb_device *udev;
283         struct kvaser_usb_net_priv *nets[MAX_NET_DEVICES];
284
285         struct usb_endpoint_descriptor *bulk_in, *bulk_out;
286         struct usb_anchor rx_submitted;
287
288         u32 fw_version;
289         unsigned int nchannels;
290
291         bool rxinitdone;
292         void *rxbuf[MAX_RX_URBS];
293         dma_addr_t rxbuf_dma[MAX_RX_URBS];
294 };
295
296 struct kvaser_usb_net_priv {
297         struct can_priv can;
298
299         atomic_t active_tx_urbs;
300         struct usb_anchor tx_submitted;
301         struct kvaser_usb_tx_urb_context tx_contexts[MAX_TX_URBS];
302
303         struct completion start_comp, stop_comp;
304
305         struct kvaser_usb *dev;
306         struct net_device *netdev;
307         int channel;
308
309         struct can_berr_counter bec;
310 };
311
312 static const struct usb_device_id kvaser_usb_table[] = {
313         { USB_DEVICE(KVASER_VENDOR_ID, USB_LEAF_DEVEL_PRODUCT_ID) },
314         { USB_DEVICE(KVASER_VENDOR_ID, USB_LEAF_LITE_PRODUCT_ID) },
315         { USB_DEVICE(KVASER_VENDOR_ID, USB_LEAF_PRO_PRODUCT_ID),
316                 .driver_info = KVASER_HAS_TXRX_ERRORS |
317                                KVASER_HAS_SILENT_MODE },
318         { USB_DEVICE(KVASER_VENDOR_ID, USB_LEAF_SPRO_PRODUCT_ID),
319                 .driver_info = KVASER_HAS_TXRX_ERRORS |
320                                KVASER_HAS_SILENT_MODE },
321         { USB_DEVICE(KVASER_VENDOR_ID, USB_LEAF_PRO_LS_PRODUCT_ID),
322                 .driver_info = KVASER_HAS_TXRX_ERRORS |
323                                KVASER_HAS_SILENT_MODE },
324         { USB_DEVICE(KVASER_VENDOR_ID, USB_LEAF_PRO_SWC_PRODUCT_ID),
325                 .driver_info = KVASER_HAS_TXRX_ERRORS |
326                                KVASER_HAS_SILENT_MODE },
327         { USB_DEVICE(KVASER_VENDOR_ID, USB_LEAF_PRO_LIN_PRODUCT_ID),
328                 .driver_info = KVASER_HAS_TXRX_ERRORS |
329                                KVASER_HAS_SILENT_MODE },
330         { USB_DEVICE(KVASER_VENDOR_ID, USB_LEAF_SPRO_LS_PRODUCT_ID),
331                 .driver_info = KVASER_HAS_TXRX_ERRORS |
332                                KVASER_HAS_SILENT_MODE },
333         { USB_DEVICE(KVASER_VENDOR_ID, USB_LEAF_SPRO_SWC_PRODUCT_ID),
334                 .driver_info = KVASER_HAS_TXRX_ERRORS |
335                                KVASER_HAS_SILENT_MODE },
336         { USB_DEVICE(KVASER_VENDOR_ID, USB_MEMO2_DEVEL_PRODUCT_ID),
337                 .driver_info = KVASER_HAS_TXRX_ERRORS |
338                                KVASER_HAS_SILENT_MODE },
339         { USB_DEVICE(KVASER_VENDOR_ID, USB_MEMO2_HSHS_PRODUCT_ID),
340                 .driver_info = KVASER_HAS_TXRX_ERRORS |
341                                KVASER_HAS_SILENT_MODE },
342         { USB_DEVICE(KVASER_VENDOR_ID, USB_UPRO_HSHS_PRODUCT_ID),
343                 .driver_info = KVASER_HAS_TXRX_ERRORS },
344         { USB_DEVICE(KVASER_VENDOR_ID, USB_LEAF_LITE_GI_PRODUCT_ID) },
345         { USB_DEVICE(KVASER_VENDOR_ID, USB_LEAF_PRO_OBDII_PRODUCT_ID),
346                 .driver_info = KVASER_HAS_TXRX_ERRORS |
347                                KVASER_HAS_SILENT_MODE },
348         { USB_DEVICE(KVASER_VENDOR_ID, USB_MEMO2_HSLS_PRODUCT_ID),
349                 .driver_info = KVASER_HAS_TXRX_ERRORS },
350         { USB_DEVICE(KVASER_VENDOR_ID, USB_LEAF_LITE_CH_PRODUCT_ID),
351                 .driver_info = KVASER_HAS_TXRX_ERRORS },
352         { USB_DEVICE(KVASER_VENDOR_ID, USB_BLACKBIRD_SPRO_PRODUCT_ID),
353                 .driver_info = KVASER_HAS_TXRX_ERRORS },
354         { USB_DEVICE(KVASER_VENDOR_ID, USB_OEM_MERCURY_PRODUCT_ID),
355                 .driver_info = KVASER_HAS_TXRX_ERRORS },
356         { USB_DEVICE(KVASER_VENDOR_ID, USB_OEM_LEAF_PRODUCT_ID),
357                 .driver_info = KVASER_HAS_TXRX_ERRORS },
358         { USB_DEVICE(KVASER_VENDOR_ID, USB_CAN_R_PRODUCT_ID),
359                 .driver_info = KVASER_HAS_TXRX_ERRORS },
360         { }
361 };
362 MODULE_DEVICE_TABLE(usb, kvaser_usb_table);
363
364 static inline int kvaser_usb_send_msg(const struct kvaser_usb *dev,
365                                       struct kvaser_msg *msg)
366 {
367         int actual_len;
368
369         return usb_bulk_msg(dev->udev,
370                             usb_sndbulkpipe(dev->udev,
371                                         dev->bulk_out->bEndpointAddress),
372                             msg, msg->len, &actual_len,
373                             USB_SEND_TIMEOUT);
374 }
375
376 static int kvaser_usb_wait_msg(const struct kvaser_usb *dev, u8 id,
377                                struct kvaser_msg *msg)
378 {
379         struct kvaser_msg *tmp;
380         void *buf;
381         int actual_len;
382         int err;
383         int pos = 0;
384
385         buf = kzalloc(RX_BUFFER_SIZE, GFP_KERNEL);
386         if (!buf)
387                 return -ENOMEM;
388
389         err = usb_bulk_msg(dev->udev,
390                            usb_rcvbulkpipe(dev->udev,
391                                            dev->bulk_in->bEndpointAddress),
392                            buf, RX_BUFFER_SIZE, &actual_len,
393                            USB_RECV_TIMEOUT);
394         if (err < 0)
395                 goto end;
396
397         while (pos <= actual_len - MSG_HEADER_LEN) {
398                 tmp = buf + pos;
399
400                 if (!tmp->len)
401                         break;
402
403                 if (pos + tmp->len > actual_len) {
404                         dev_err(dev->udev->dev.parent, "Format error\n");
405                         break;
406                 }
407
408                 if (tmp->id == id) {
409                         memcpy(msg, tmp, tmp->len);
410                         goto end;
411                 }
412
413                 pos += tmp->len;
414         }
415
416         err = -EINVAL;
417
418 end:
419         kfree(buf);
420
421         return err;
422 }
423
424 static int kvaser_usb_send_simple_msg(const struct kvaser_usb *dev,
425                                       u8 msg_id, int channel)
426 {
427         struct kvaser_msg *msg;
428         int rc;
429
430         msg = kmalloc(sizeof(*msg), GFP_KERNEL);
431         if (!msg)
432                 return -ENOMEM;
433
434         msg->id = msg_id;
435         msg->len = MSG_HEADER_LEN + sizeof(struct kvaser_msg_simple);
436         msg->u.simple.channel = channel;
437         msg->u.simple.tid = 0xff;
438
439         rc = kvaser_usb_send_msg(dev, msg);
440
441         kfree(msg);
442         return rc;
443 }
444
445 static int kvaser_usb_get_software_info(struct kvaser_usb *dev)
446 {
447         struct kvaser_msg msg;
448         int err;
449
450         err = kvaser_usb_send_simple_msg(dev, CMD_GET_SOFTWARE_INFO, 0);
451         if (err)
452                 return err;
453
454         err = kvaser_usb_wait_msg(dev, CMD_GET_SOFTWARE_INFO_REPLY, &msg);
455         if (err)
456                 return err;
457
458         dev->fw_version = le32_to_cpu(msg.u.softinfo.fw_version);
459
460         return 0;
461 }
462
463 static int kvaser_usb_get_card_info(struct kvaser_usb *dev)
464 {
465         struct kvaser_msg msg;
466         int err;
467
468         err = kvaser_usb_send_simple_msg(dev, CMD_GET_CARD_INFO, 0);
469         if (err)
470                 return err;
471
472         err = kvaser_usb_wait_msg(dev, CMD_GET_CARD_INFO_REPLY, &msg);
473         if (err)
474                 return err;
475
476         dev->nchannels = msg.u.cardinfo.nchannels;
477         if (dev->nchannels > MAX_NET_DEVICES)
478                 return -EINVAL;
479
480         return 0;
481 }
482
483 static void kvaser_usb_tx_acknowledge(const struct kvaser_usb *dev,
484                                       const struct kvaser_msg *msg)
485 {
486         struct net_device_stats *stats;
487         struct kvaser_usb_tx_urb_context *context;
488         struct kvaser_usb_net_priv *priv;
489         struct sk_buff *skb;
490         struct can_frame *cf;
491         u8 channel = msg->u.tx_acknowledge.channel;
492         u8 tid = msg->u.tx_acknowledge.tid;
493
494         if (channel >= dev->nchannels) {
495                 dev_err(dev->udev->dev.parent,
496                         "Invalid channel number (%d)\n", channel);
497                 return;
498         }
499
500         priv = dev->nets[channel];
501
502         if (!netif_device_present(priv->netdev))
503                 return;
504
505         stats = &priv->netdev->stats;
506
507         context = &priv->tx_contexts[tid % MAX_TX_URBS];
508
509         /* Sometimes the state change doesn't come after a bus-off event */
510         if (priv->can.restart_ms &&
511             (priv->can.state >= CAN_STATE_BUS_OFF)) {
512                 skb = alloc_can_err_skb(priv->netdev, &cf);
513                 if (skb) {
514                         cf->can_id |= CAN_ERR_RESTARTED;
515                         netif_rx(skb);
516
517                         stats->rx_packets++;
518                         stats->rx_bytes += cf->can_dlc;
519                 } else {
520                         netdev_err(priv->netdev,
521                                    "No memory left for err_skb\n");
522                 }
523
524                 priv->can.can_stats.restarts++;
525                 netif_carrier_on(priv->netdev);
526
527                 priv->can.state = CAN_STATE_ERROR_ACTIVE;
528         }
529
530         stats->tx_packets++;
531         stats->tx_bytes += context->dlc;
532         can_get_echo_skb(priv->netdev, context->echo_index);
533
534         context->echo_index = MAX_TX_URBS;
535         atomic_dec(&priv->active_tx_urbs);
536
537         netif_wake_queue(priv->netdev);
538 }
539
540 static void kvaser_usb_simple_msg_callback(struct urb *urb)
541 {
542         struct net_device *netdev = urb->context;
543
544         kfree(urb->transfer_buffer);
545
546         if (urb->status)
547                 netdev_warn(netdev, "urb status received: %d\n",
548                             urb->status);
549 }
550
551 static int kvaser_usb_simple_msg_async(struct kvaser_usb_net_priv *priv,
552                                        u8 msg_id)
553 {
554         struct kvaser_usb *dev = priv->dev;
555         struct net_device *netdev = priv->netdev;
556         struct kvaser_msg *msg;
557         struct urb *urb;
558         void *buf;
559         int err;
560
561         urb = usb_alloc_urb(0, GFP_ATOMIC);
562         if (!urb) {
563                 netdev_err(netdev, "No memory left for URBs\n");
564                 return -ENOMEM;
565         }
566
567         buf = kmalloc(sizeof(struct kvaser_msg), GFP_ATOMIC);
568         if (!buf) {
569                 usb_free_urb(urb);
570                 return -ENOMEM;
571         }
572
573         msg = (struct kvaser_msg *)buf;
574         msg->len = MSG_HEADER_LEN + sizeof(struct kvaser_msg_simple);
575         msg->id = msg_id;
576         msg->u.simple.channel = priv->channel;
577
578         usb_fill_bulk_urb(urb, dev->udev,
579                           usb_sndbulkpipe(dev->udev,
580                                           dev->bulk_out->bEndpointAddress),
581                           buf, msg->len,
582                           kvaser_usb_simple_msg_callback, priv);
583         usb_anchor_urb(urb, &priv->tx_submitted);
584
585         err = usb_submit_urb(urb, GFP_ATOMIC);
586         if (err) {
587                 netdev_err(netdev, "Error transmitting URB\n");
588                 usb_unanchor_urb(urb);
589                 usb_free_urb(urb);
590                 kfree(buf);
591                 return err;
592         }
593
594         usb_free_urb(urb);
595
596         return 0;
597 }
598
599 static void kvaser_usb_unlink_tx_urbs(struct kvaser_usb_net_priv *priv)
600 {
601         int i;
602
603         usb_kill_anchored_urbs(&priv->tx_submitted);
604         atomic_set(&priv->active_tx_urbs, 0);
605
606         for (i = 0; i < MAX_TX_URBS; i++)
607                 priv->tx_contexts[i].echo_index = MAX_TX_URBS;
608 }
609
610 static void kvaser_usb_rx_error(const struct kvaser_usb *dev,
611                                 const struct kvaser_msg *msg)
612 {
613         struct can_frame *cf;
614         struct sk_buff *skb;
615         struct net_device_stats *stats;
616         struct kvaser_usb_net_priv *priv;
617         unsigned int new_state;
618         u8 channel, status, txerr, rxerr, error_factor;
619
620         switch (msg->id) {
621         case CMD_CAN_ERROR_EVENT:
622                 channel = msg->u.error_event.channel;
623                 status =  msg->u.error_event.status;
624                 txerr = msg->u.error_event.tx_errors_count;
625                 rxerr = msg->u.error_event.rx_errors_count;
626                 error_factor = msg->u.error_event.error_factor;
627                 break;
628         case CMD_LOG_MESSAGE:
629                 channel = msg->u.log_message.channel;
630                 status = msg->u.log_message.data[0];
631                 txerr = msg->u.log_message.data[2];
632                 rxerr = msg->u.log_message.data[3];
633                 error_factor = msg->u.log_message.data[1];
634                 break;
635         case CMD_CHIP_STATE_EVENT:
636                 channel = msg->u.chip_state_event.channel;
637                 status =  msg->u.chip_state_event.status;
638                 txerr = msg->u.chip_state_event.tx_errors_count;
639                 rxerr = msg->u.chip_state_event.rx_errors_count;
640                 error_factor = 0;
641                 break;
642         default:
643                 dev_err(dev->udev->dev.parent, "Invalid msg id (%d)\n",
644                         msg->id);
645                 return;
646         }
647
648         if (channel >= dev->nchannels) {
649                 dev_err(dev->udev->dev.parent,
650                         "Invalid channel number (%d)\n", channel);
651                 return;
652         }
653
654         priv = dev->nets[channel];
655         stats = &priv->netdev->stats;
656
657         skb = alloc_can_err_skb(priv->netdev, &cf);
658         if (!skb) {
659                 stats->rx_dropped++;
660                 return;
661         }
662
663         new_state = priv->can.state;
664
665         netdev_dbg(priv->netdev, "Error status: 0x%02x\n", status);
666
667         if (status & (M16C_STATE_BUS_OFF | M16C_STATE_BUS_RESET)) {
668                 cf->can_id |= CAN_ERR_BUSOFF;
669
670                 priv->can.can_stats.bus_off++;
671                 if (!priv->can.restart_ms)
672                         kvaser_usb_simple_msg_async(priv, CMD_STOP_CHIP);
673
674                 netif_carrier_off(priv->netdev);
675
676                 new_state = CAN_STATE_BUS_OFF;
677         } else if (status & M16C_STATE_BUS_PASSIVE) {
678                 if (priv->can.state != CAN_STATE_ERROR_PASSIVE) {
679                         cf->can_id |= CAN_ERR_CRTL;
680
681                         if (txerr || rxerr)
682                                 cf->data[1] = (txerr > rxerr)
683                                                 ? CAN_ERR_CRTL_TX_PASSIVE
684                                                 : CAN_ERR_CRTL_RX_PASSIVE;
685                         else
686                                 cf->data[1] = CAN_ERR_CRTL_TX_PASSIVE |
687                                               CAN_ERR_CRTL_RX_PASSIVE;
688
689                         priv->can.can_stats.error_passive++;
690                 }
691
692                 new_state = CAN_STATE_ERROR_PASSIVE;
693         }
694
695         if (status == M16C_STATE_BUS_ERROR) {
696                 if ((priv->can.state < CAN_STATE_ERROR_WARNING) &&
697                     ((txerr >= 96) || (rxerr >= 96))) {
698                         cf->can_id |= CAN_ERR_CRTL;
699                         cf->data[1] = (txerr > rxerr)
700                                         ? CAN_ERR_CRTL_TX_WARNING
701                                         : CAN_ERR_CRTL_RX_WARNING;
702
703                         priv->can.can_stats.error_warning++;
704                         new_state = CAN_STATE_ERROR_WARNING;
705                 } else if (priv->can.state > CAN_STATE_ERROR_ACTIVE) {
706                         cf->can_id |= CAN_ERR_PROT;
707                         cf->data[2] = CAN_ERR_PROT_ACTIVE;
708
709                         new_state = CAN_STATE_ERROR_ACTIVE;
710                 }
711         }
712
713         if (!status) {
714                 cf->can_id |= CAN_ERR_PROT;
715                 cf->data[2] = CAN_ERR_PROT_ACTIVE;
716
717                 new_state = CAN_STATE_ERROR_ACTIVE;
718         }
719
720         if (priv->can.restart_ms &&
721             (priv->can.state >= CAN_STATE_BUS_OFF) &&
722             (new_state < CAN_STATE_BUS_OFF)) {
723                 cf->can_id |= CAN_ERR_RESTARTED;
724                 netif_carrier_on(priv->netdev);
725
726                 priv->can.can_stats.restarts++;
727         }
728
729         if (error_factor) {
730                 priv->can.can_stats.bus_error++;
731                 stats->rx_errors++;
732
733                 cf->can_id |= CAN_ERR_BUSERROR | CAN_ERR_PROT;
734
735                 if (error_factor & M16C_EF_ACKE)
736                         cf->data[3] |= (CAN_ERR_PROT_LOC_ACK);
737                 if (error_factor & M16C_EF_CRCE)
738                         cf->data[3] |= (CAN_ERR_PROT_LOC_CRC_SEQ |
739                                         CAN_ERR_PROT_LOC_CRC_DEL);
740                 if (error_factor & M16C_EF_FORME)
741                         cf->data[2] |= CAN_ERR_PROT_FORM;
742                 if (error_factor & M16C_EF_STFE)
743                         cf->data[2] |= CAN_ERR_PROT_STUFF;
744                 if (error_factor & M16C_EF_BITE0)
745                         cf->data[2] |= CAN_ERR_PROT_BIT0;
746                 if (error_factor & M16C_EF_BITE1)
747                         cf->data[2] |= CAN_ERR_PROT_BIT1;
748                 if (error_factor & M16C_EF_TRE)
749                         cf->data[2] |= CAN_ERR_PROT_TX;
750         }
751
752         cf->data[6] = txerr;
753         cf->data[7] = rxerr;
754
755         priv->bec.txerr = txerr;
756         priv->bec.rxerr = rxerr;
757
758         priv->can.state = new_state;
759
760         netif_rx(skb);
761
762         stats->rx_packets++;
763         stats->rx_bytes += cf->can_dlc;
764 }
765
766 static void kvaser_usb_rx_can_err(const struct kvaser_usb_net_priv *priv,
767                                   const struct kvaser_msg *msg)
768 {
769         struct can_frame *cf;
770         struct sk_buff *skb;
771         struct net_device_stats *stats = &priv->netdev->stats;
772
773         if (msg->u.rx_can.flag & (MSG_FLAG_ERROR_FRAME |
774                                          MSG_FLAG_NERR)) {
775                 netdev_err(priv->netdev, "Unknow error (flags: 0x%02x)\n",
776                            msg->u.rx_can.flag);
777
778                 stats->rx_errors++;
779                 return;
780         }
781
782         if (msg->u.rx_can.flag & MSG_FLAG_OVERRUN) {
783                 skb = alloc_can_err_skb(priv->netdev, &cf);
784                 if (!skb) {
785                         stats->rx_dropped++;
786                         return;
787                 }
788
789                 cf->can_id |= CAN_ERR_CRTL;
790                 cf->data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
791
792                 stats->rx_over_errors++;
793                 stats->rx_errors++;
794
795                 netif_rx(skb);
796
797                 stats->rx_packets++;
798                 stats->rx_bytes += cf->can_dlc;
799         }
800 }
801
802 static void kvaser_usb_rx_can_msg(const struct kvaser_usb *dev,
803                                   const struct kvaser_msg *msg)
804 {
805         struct kvaser_usb_net_priv *priv;
806         struct can_frame *cf;
807         struct sk_buff *skb;
808         struct net_device_stats *stats;
809         u8 channel = msg->u.rx_can.channel;
810
811         if (channel >= dev->nchannels) {
812                 dev_err(dev->udev->dev.parent,
813                         "Invalid channel number (%d)\n", channel);
814                 return;
815         }
816
817         priv = dev->nets[channel];
818         stats = &priv->netdev->stats;
819
820         if ((msg->u.rx_can.flag & MSG_FLAG_ERROR_FRAME) &&
821             (msg->id == CMD_LOG_MESSAGE)) {
822                 kvaser_usb_rx_error(dev, msg);
823                 return;
824         } else if (msg->u.rx_can.flag & (MSG_FLAG_ERROR_FRAME |
825                                          MSG_FLAG_NERR |
826                                          MSG_FLAG_OVERRUN)) {
827                 kvaser_usb_rx_can_err(priv, msg);
828                 return;
829         } else if (msg->u.rx_can.flag & ~MSG_FLAG_REMOTE_FRAME) {
830                 netdev_warn(priv->netdev,
831                             "Unhandled frame (flags: 0x%02x)",
832                             msg->u.rx_can.flag);
833                 return;
834         }
835
836         skb = alloc_can_skb(priv->netdev, &cf);
837         if (!skb) {
838                 stats->tx_dropped++;
839                 return;
840         }
841
842         if (msg->id == CMD_LOG_MESSAGE) {
843                 cf->can_id = le32_to_cpu(msg->u.log_message.id);
844                 if (cf->can_id & KVASER_EXTENDED_FRAME)
845                         cf->can_id &= CAN_EFF_MASK | CAN_EFF_FLAG;
846                 else
847                         cf->can_id &= CAN_SFF_MASK;
848
849                 cf->can_dlc = get_can_dlc(msg->u.log_message.dlc);
850
851                 if (msg->u.log_message.flags & MSG_FLAG_REMOTE_FRAME)
852                         cf->can_id |= CAN_RTR_FLAG;
853                 else
854                         memcpy(cf->data, &msg->u.log_message.data,
855                                cf->can_dlc);
856         } else {
857                 cf->can_id = ((msg->u.rx_can.msg[0] & 0x1f) << 6) |
858                              (msg->u.rx_can.msg[1] & 0x3f);
859
860                 if (msg->id == CMD_RX_EXT_MESSAGE) {
861                         cf->can_id <<= 18;
862                         cf->can_id |= ((msg->u.rx_can.msg[2] & 0x0f) << 14) |
863                                       ((msg->u.rx_can.msg[3] & 0xff) << 6) |
864                                       (msg->u.rx_can.msg[4] & 0x3f);
865                         cf->can_id |= CAN_EFF_FLAG;
866                 }
867
868                 cf->can_dlc = get_can_dlc(msg->u.rx_can.msg[5]);
869
870                 if (msg->u.rx_can.flag & MSG_FLAG_REMOTE_FRAME)
871                         cf->can_id |= CAN_RTR_FLAG;
872                 else
873                         memcpy(cf->data, &msg->u.rx_can.msg[6],
874                                cf->can_dlc);
875         }
876
877         netif_rx(skb);
878
879         stats->rx_packets++;
880         stats->rx_bytes += cf->can_dlc;
881 }
882
883 static void kvaser_usb_start_chip_reply(const struct kvaser_usb *dev,
884                                         const struct kvaser_msg *msg)
885 {
886         struct kvaser_usb_net_priv *priv;
887         u8 channel = msg->u.simple.channel;
888
889         if (channel >= dev->nchannels) {
890                 dev_err(dev->udev->dev.parent,
891                         "Invalid channel number (%d)\n", channel);
892                 return;
893         }
894
895         priv = dev->nets[channel];
896
897         if (completion_done(&priv->start_comp) &&
898             netif_queue_stopped(priv->netdev)) {
899                 netif_wake_queue(priv->netdev);
900         } else {
901                 netif_start_queue(priv->netdev);
902                 complete(&priv->start_comp);
903         }
904 }
905
906 static void kvaser_usb_stop_chip_reply(const struct kvaser_usb *dev,
907                                        const struct kvaser_msg *msg)
908 {
909         struct kvaser_usb_net_priv *priv;
910         u8 channel = msg->u.simple.channel;
911
912         if (channel >= dev->nchannels) {
913                 dev_err(dev->udev->dev.parent,
914                         "Invalid channel number (%d)\n", channel);
915                 return;
916         }
917
918         priv = dev->nets[channel];
919
920         complete(&priv->stop_comp);
921 }
922
923 static void kvaser_usb_handle_message(const struct kvaser_usb *dev,
924                                       const struct kvaser_msg *msg)
925 {
926         switch (msg->id) {
927         case CMD_START_CHIP_REPLY:
928                 kvaser_usb_start_chip_reply(dev, msg);
929                 break;
930
931         case CMD_STOP_CHIP_REPLY:
932                 kvaser_usb_stop_chip_reply(dev, msg);
933                 break;
934
935         case CMD_RX_STD_MESSAGE:
936         case CMD_RX_EXT_MESSAGE:
937         case CMD_LOG_MESSAGE:
938                 kvaser_usb_rx_can_msg(dev, msg);
939                 break;
940
941         case CMD_CHIP_STATE_EVENT:
942         case CMD_CAN_ERROR_EVENT:
943                 kvaser_usb_rx_error(dev, msg);
944                 break;
945
946         case CMD_TX_ACKNOWLEDGE:
947                 kvaser_usb_tx_acknowledge(dev, msg);
948                 break;
949
950         default:
951                 dev_warn(dev->udev->dev.parent,
952                          "Unhandled message (%d)\n", msg->id);
953                 break;
954         }
955 }
956
957 static void kvaser_usb_read_bulk_callback(struct urb *urb)
958 {
959         struct kvaser_usb *dev = urb->context;
960         struct kvaser_msg *msg;
961         int pos = 0;
962         int err, i;
963
964         switch (urb->status) {
965         case 0:
966                 break;
967         case -ENOENT:
968         case -ESHUTDOWN:
969                 return;
970         default:
971                 dev_info(dev->udev->dev.parent, "Rx URB aborted (%d)\n",
972                          urb->status);
973                 goto resubmit_urb;
974         }
975
976         while (pos <= urb->actual_length - MSG_HEADER_LEN) {
977                 msg = urb->transfer_buffer + pos;
978
979                 if (!msg->len)
980                         break;
981
982                 if (pos + msg->len > urb->actual_length) {
983                         dev_err(dev->udev->dev.parent, "Format error\n");
984                         break;
985                 }
986
987                 kvaser_usb_handle_message(dev, msg);
988
989                 pos += msg->len;
990         }
991
992 resubmit_urb:
993         usb_fill_bulk_urb(urb, dev->udev,
994                           usb_rcvbulkpipe(dev->udev,
995                                           dev->bulk_in->bEndpointAddress),
996                           urb->transfer_buffer, RX_BUFFER_SIZE,
997                           kvaser_usb_read_bulk_callback, dev);
998
999         err = usb_submit_urb(urb, GFP_ATOMIC);
1000         if (err == -ENODEV) {
1001                 for (i = 0; i < dev->nchannels; i++) {
1002                         if (!dev->nets[i])
1003                                 continue;
1004
1005                         netif_device_detach(dev->nets[i]->netdev);
1006                 }
1007         } else if (err) {
1008                 dev_err(dev->udev->dev.parent,
1009                         "Failed resubmitting read bulk urb: %d\n", err);
1010         }
1011
1012         return;
1013 }
1014
1015 static int kvaser_usb_setup_rx_urbs(struct kvaser_usb *dev)
1016 {
1017         int i, err = 0;
1018
1019         if (dev->rxinitdone)
1020                 return 0;
1021
1022         for (i = 0; i < MAX_RX_URBS; i++) {
1023                 struct urb *urb = NULL;
1024                 u8 *buf = NULL;
1025                 dma_addr_t buf_dma;
1026
1027                 urb = usb_alloc_urb(0, GFP_KERNEL);
1028                 if (!urb) {
1029                         dev_warn(dev->udev->dev.parent,
1030                                  "No memory left for URBs\n");
1031                         err = -ENOMEM;
1032                         break;
1033                 }
1034
1035                 buf = usb_alloc_coherent(dev->udev, RX_BUFFER_SIZE,
1036                                          GFP_KERNEL, &buf_dma);
1037                 if (!buf) {
1038                         dev_warn(dev->udev->dev.parent,
1039                                  "No memory left for USB buffer\n");
1040                         usb_free_urb(urb);
1041                         err = -ENOMEM;
1042                         break;
1043                 }
1044
1045                 usb_fill_bulk_urb(urb, dev->udev,
1046                                   usb_rcvbulkpipe(dev->udev,
1047                                           dev->bulk_in->bEndpointAddress),
1048                                   buf, RX_BUFFER_SIZE,
1049                                   kvaser_usb_read_bulk_callback,
1050                                   dev);
1051                 urb->transfer_dma = buf_dma;
1052                 urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
1053                 usb_anchor_urb(urb, &dev->rx_submitted);
1054
1055                 err = usb_submit_urb(urb, GFP_KERNEL);
1056                 if (err) {
1057                         usb_unanchor_urb(urb);
1058                         usb_free_coherent(dev->udev, RX_BUFFER_SIZE, buf,
1059                                           buf_dma);
1060                         usb_free_urb(urb);
1061                         break;
1062                 }
1063
1064                 dev->rxbuf[i] = buf;
1065                 dev->rxbuf_dma[i] = buf_dma;
1066
1067                 usb_free_urb(urb);
1068         }
1069
1070         if (i == 0) {
1071                 dev_warn(dev->udev->dev.parent,
1072                          "Cannot setup read URBs, error %d\n", err);
1073                 return err;
1074         } else if (i < MAX_RX_URBS) {
1075                 dev_warn(dev->udev->dev.parent,
1076                          "RX performances may be slow\n");
1077         }
1078
1079         dev->rxinitdone = true;
1080
1081         return 0;
1082 }
1083
1084 static int kvaser_usb_set_opt_mode(const struct kvaser_usb_net_priv *priv)
1085 {
1086         struct kvaser_msg *msg;
1087         int rc;
1088
1089         msg = kmalloc(sizeof(*msg), GFP_KERNEL);
1090         if (!msg)
1091                 return -ENOMEM;
1092
1093         msg->id = CMD_SET_CTRL_MODE;
1094         msg->len = MSG_HEADER_LEN + sizeof(struct kvaser_msg_ctrl_mode);
1095         msg->u.ctrl_mode.tid = 0xff;
1096         msg->u.ctrl_mode.channel = priv->channel;
1097
1098         if (priv->can.ctrlmode & CAN_CTRLMODE_LISTENONLY)
1099                 msg->u.ctrl_mode.ctrl_mode = KVASER_CTRL_MODE_SILENT;
1100         else
1101                 msg->u.ctrl_mode.ctrl_mode = KVASER_CTRL_MODE_NORMAL;
1102
1103         rc = kvaser_usb_send_msg(priv->dev, msg);
1104
1105         kfree(msg);
1106         return rc;
1107 }
1108
1109 static int kvaser_usb_start_chip(struct kvaser_usb_net_priv *priv)
1110 {
1111         int err;
1112
1113         init_completion(&priv->start_comp);
1114
1115         err = kvaser_usb_send_simple_msg(priv->dev, CMD_START_CHIP,
1116                                          priv->channel);
1117         if (err)
1118                 return err;
1119
1120         if (!wait_for_completion_timeout(&priv->start_comp,
1121                                          msecs_to_jiffies(START_TIMEOUT)))
1122                 return -ETIMEDOUT;
1123
1124         return 0;
1125 }
1126
1127 static int kvaser_usb_open(struct net_device *netdev)
1128 {
1129         struct kvaser_usb_net_priv *priv = netdev_priv(netdev);
1130         struct kvaser_usb *dev = priv->dev;
1131         int err;
1132
1133         err = open_candev(netdev);
1134         if (err)
1135                 return err;
1136
1137         err = kvaser_usb_setup_rx_urbs(dev);
1138         if (err)
1139                 goto error;
1140
1141         err = kvaser_usb_set_opt_mode(priv);
1142         if (err)
1143                 goto error;
1144
1145         err = kvaser_usb_start_chip(priv);
1146         if (err) {
1147                 netdev_warn(netdev, "Cannot start device, error %d\n", err);
1148                 goto error;
1149         }
1150
1151         priv->can.state = CAN_STATE_ERROR_ACTIVE;
1152
1153         return 0;
1154
1155 error:
1156         close_candev(netdev);
1157         return err;
1158 }
1159
1160 static void kvaser_usb_unlink_all_urbs(struct kvaser_usb *dev)
1161 {
1162         int i;
1163
1164         usb_kill_anchored_urbs(&dev->rx_submitted);
1165
1166         for (i = 0; i < MAX_RX_URBS; i++)
1167                 usb_free_coherent(dev->udev, RX_BUFFER_SIZE,
1168                                   dev->rxbuf[i],
1169                                   dev->rxbuf_dma[i]);
1170
1171         for (i = 0; i < MAX_NET_DEVICES; i++) {
1172                 struct kvaser_usb_net_priv *priv = dev->nets[i];
1173
1174                 if (priv)
1175                         kvaser_usb_unlink_tx_urbs(priv);
1176         }
1177 }
1178
1179 static int kvaser_usb_stop_chip(struct kvaser_usb_net_priv *priv)
1180 {
1181         int err;
1182
1183         init_completion(&priv->stop_comp);
1184
1185         err = kvaser_usb_send_simple_msg(priv->dev, CMD_STOP_CHIP,
1186                                          priv->channel);
1187         if (err)
1188                 return err;
1189
1190         if (!wait_for_completion_timeout(&priv->stop_comp,
1191                                          msecs_to_jiffies(STOP_TIMEOUT)))
1192                 return -ETIMEDOUT;
1193
1194         return 0;
1195 }
1196
1197 static int kvaser_usb_flush_queue(struct kvaser_usb_net_priv *priv)
1198 {
1199         struct kvaser_msg *msg;
1200         int rc;
1201
1202         msg = kmalloc(sizeof(*msg), GFP_KERNEL);
1203         if (!msg)
1204                 return -ENOMEM;
1205
1206         msg->id = CMD_FLUSH_QUEUE;
1207         msg->len = MSG_HEADER_LEN + sizeof(struct kvaser_msg_flush_queue);
1208         msg->u.flush_queue.channel = priv->channel;
1209         msg->u.flush_queue.flags = 0x00;
1210
1211         rc = kvaser_usb_send_msg(priv->dev, msg);
1212
1213         kfree(msg);
1214         return rc;
1215 }
1216
1217 static int kvaser_usb_close(struct net_device *netdev)
1218 {
1219         struct kvaser_usb_net_priv *priv = netdev_priv(netdev);
1220         struct kvaser_usb *dev = priv->dev;
1221         int err;
1222
1223         netif_stop_queue(netdev);
1224
1225         err = kvaser_usb_flush_queue(priv);
1226         if (err)
1227                 netdev_warn(netdev, "Cannot flush queue, error %d\n", err);
1228
1229         if (kvaser_usb_send_simple_msg(dev, CMD_RESET_CHIP, priv->channel))
1230                 netdev_warn(netdev, "Cannot reset card, error %d\n", err);
1231
1232         err = kvaser_usb_stop_chip(priv);
1233         if (err)
1234                 netdev_warn(netdev, "Cannot stop device, error %d\n", err);
1235
1236         /* reset tx contexts */
1237         kvaser_usb_unlink_tx_urbs(priv);
1238
1239         priv->can.state = CAN_STATE_STOPPED;
1240         close_candev(priv->netdev);
1241
1242         return 0;
1243 }
1244
1245 static void kvaser_usb_write_bulk_callback(struct urb *urb)
1246 {
1247         struct kvaser_usb_tx_urb_context *context = urb->context;
1248         struct kvaser_usb_net_priv *priv;
1249         struct net_device *netdev;
1250
1251         if (WARN_ON(!context))
1252                 return;
1253
1254         priv = context->priv;
1255         netdev = priv->netdev;
1256
1257         kfree(urb->transfer_buffer);
1258
1259         if (!netif_device_present(netdev))
1260                 return;
1261
1262         if (urb->status)
1263                 netdev_info(netdev, "Tx URB aborted (%d)\n", urb->status);
1264 }
1265
1266 static netdev_tx_t kvaser_usb_start_xmit(struct sk_buff *skb,
1267                                          struct net_device *netdev)
1268 {
1269         struct kvaser_usb_net_priv *priv = netdev_priv(netdev);
1270         struct kvaser_usb *dev = priv->dev;
1271         struct net_device_stats *stats = &netdev->stats;
1272         struct can_frame *cf = (struct can_frame *)skb->data;
1273         struct kvaser_usb_tx_urb_context *context = NULL;
1274         struct urb *urb;
1275         void *buf;
1276         struct kvaser_msg *msg;
1277         int i, err;
1278         int ret = NETDEV_TX_OK;
1279
1280         if (can_dropped_invalid_skb(netdev, skb))
1281                 return NETDEV_TX_OK;
1282
1283         urb = usb_alloc_urb(0, GFP_ATOMIC);
1284         if (!urb) {
1285                 netdev_err(netdev, "No memory left for URBs\n");
1286                 stats->tx_dropped++;
1287                 dev_kfree_skb(skb);
1288                 return NETDEV_TX_OK;
1289         }
1290
1291         buf = kmalloc(sizeof(struct kvaser_msg), GFP_ATOMIC);
1292         if (!buf) {
1293                 stats->tx_dropped++;
1294                 dev_kfree_skb(skb);
1295                 goto nobufmem;
1296         }
1297
1298         msg = buf;
1299         msg->len = MSG_HEADER_LEN + sizeof(struct kvaser_msg_tx_can);
1300         msg->u.tx_can.flags = 0;
1301         msg->u.tx_can.channel = priv->channel;
1302
1303         if (cf->can_id & CAN_EFF_FLAG) {
1304                 msg->id = CMD_TX_EXT_MESSAGE;
1305                 msg->u.tx_can.msg[0] = (cf->can_id >> 24) & 0x1f;
1306                 msg->u.tx_can.msg[1] = (cf->can_id >> 18) & 0x3f;
1307                 msg->u.tx_can.msg[2] = (cf->can_id >> 14) & 0x0f;
1308                 msg->u.tx_can.msg[3] = (cf->can_id >> 6) & 0xff;
1309                 msg->u.tx_can.msg[4] = cf->can_id & 0x3f;
1310         } else {
1311                 msg->id = CMD_TX_STD_MESSAGE;
1312                 msg->u.tx_can.msg[0] = (cf->can_id >> 6) & 0x1f;
1313                 msg->u.tx_can.msg[1] = cf->can_id & 0x3f;
1314         }
1315
1316         msg->u.tx_can.msg[5] = cf->can_dlc;
1317         memcpy(&msg->u.tx_can.msg[6], cf->data, cf->can_dlc);
1318
1319         if (cf->can_id & CAN_RTR_FLAG)
1320                 msg->u.tx_can.flags |= MSG_FLAG_REMOTE_FRAME;
1321
1322         for (i = 0; i < ARRAY_SIZE(priv->tx_contexts); i++) {
1323                 if (priv->tx_contexts[i].echo_index == MAX_TX_URBS) {
1324                         context = &priv->tx_contexts[i];
1325                         break;
1326                 }
1327         }
1328
1329         /* This should never happen; it implies a flow control bug */
1330         if (!context) {
1331                 netdev_warn(netdev, "cannot find free context\n");
1332                 ret =  NETDEV_TX_BUSY;
1333                 goto releasebuf;
1334         }
1335
1336         context->priv = priv;
1337         context->echo_index = i;
1338         context->dlc = cf->can_dlc;
1339
1340         msg->u.tx_can.tid = context->echo_index;
1341
1342         usb_fill_bulk_urb(urb, dev->udev,
1343                           usb_sndbulkpipe(dev->udev,
1344                                           dev->bulk_out->bEndpointAddress),
1345                           buf, msg->len,
1346                           kvaser_usb_write_bulk_callback, context);
1347         usb_anchor_urb(urb, &priv->tx_submitted);
1348
1349         can_put_echo_skb(skb, netdev, context->echo_index);
1350
1351         atomic_inc(&priv->active_tx_urbs);
1352
1353         if (atomic_read(&priv->active_tx_urbs) >= MAX_TX_URBS)
1354                 netif_stop_queue(netdev);
1355
1356         err = usb_submit_urb(urb, GFP_ATOMIC);
1357         if (unlikely(err)) {
1358                 can_free_echo_skb(netdev, context->echo_index);
1359
1360                 atomic_dec(&priv->active_tx_urbs);
1361                 usb_unanchor_urb(urb);
1362
1363                 stats->tx_dropped++;
1364
1365                 if (err == -ENODEV)
1366                         netif_device_detach(netdev);
1367                 else
1368                         netdev_warn(netdev, "Failed tx_urb %d\n", err);
1369
1370                 goto releasebuf;
1371         }
1372
1373         usb_free_urb(urb);
1374
1375         return NETDEV_TX_OK;
1376
1377 releasebuf:
1378         kfree(buf);
1379 nobufmem:
1380         usb_free_urb(urb);
1381         return ret;
1382 }
1383
1384 static const struct net_device_ops kvaser_usb_netdev_ops = {
1385         .ndo_open = kvaser_usb_open,
1386         .ndo_stop = kvaser_usb_close,
1387         .ndo_start_xmit = kvaser_usb_start_xmit,
1388 };
1389
1390 static const struct can_bittiming_const kvaser_usb_bittiming_const = {
1391         .name = "kvaser_usb",
1392         .tseg1_min = KVASER_USB_TSEG1_MIN,
1393         .tseg1_max = KVASER_USB_TSEG1_MAX,
1394         .tseg2_min = KVASER_USB_TSEG2_MIN,
1395         .tseg2_max = KVASER_USB_TSEG2_MAX,
1396         .sjw_max = KVASER_USB_SJW_MAX,
1397         .brp_min = KVASER_USB_BRP_MIN,
1398         .brp_max = KVASER_USB_BRP_MAX,
1399         .brp_inc = KVASER_USB_BRP_INC,
1400 };
1401
1402 static int kvaser_usb_set_bittiming(struct net_device *netdev)
1403 {
1404         struct kvaser_usb_net_priv *priv = netdev_priv(netdev);
1405         struct can_bittiming *bt = &priv->can.bittiming;
1406         struct kvaser_usb *dev = priv->dev;
1407         struct kvaser_msg *msg;
1408         int rc;
1409
1410         msg = kmalloc(sizeof(*msg), GFP_KERNEL);
1411         if (!msg)
1412                 return -ENOMEM;
1413
1414         msg->id = CMD_SET_BUS_PARAMS;
1415         msg->len = MSG_HEADER_LEN + sizeof(struct kvaser_msg_busparams);
1416         msg->u.busparams.channel = priv->channel;
1417         msg->u.busparams.tid = 0xff;
1418         msg->u.busparams.bitrate = cpu_to_le32(bt->bitrate);
1419         msg->u.busparams.sjw = bt->sjw;
1420         msg->u.busparams.tseg1 = bt->prop_seg + bt->phase_seg1;
1421         msg->u.busparams.tseg2 = bt->phase_seg2;
1422
1423         if (priv->can.ctrlmode & CAN_CTRLMODE_3_SAMPLES)
1424                 msg->u.busparams.no_samp = 3;
1425         else
1426                 msg->u.busparams.no_samp = 1;
1427
1428         rc = kvaser_usb_send_msg(dev, msg);
1429
1430         kfree(msg);
1431         return rc;
1432 }
1433
1434 static int kvaser_usb_set_mode(struct net_device *netdev,
1435                                enum can_mode mode)
1436 {
1437         struct kvaser_usb_net_priv *priv = netdev_priv(netdev);
1438         int err;
1439
1440         switch (mode) {
1441         case CAN_MODE_START:
1442                 err = kvaser_usb_simple_msg_async(priv, CMD_START_CHIP);
1443                 if (err)
1444                         return err;
1445                 break;
1446         default:
1447                 return -EOPNOTSUPP;
1448         }
1449
1450         return 0;
1451 }
1452
1453 static int kvaser_usb_get_berr_counter(const struct net_device *netdev,
1454                                        struct can_berr_counter *bec)
1455 {
1456         struct kvaser_usb_net_priv *priv = netdev_priv(netdev);
1457
1458         *bec = priv->bec;
1459
1460         return 0;
1461 }
1462
1463 static void kvaser_usb_remove_interfaces(struct kvaser_usb *dev)
1464 {
1465         int i;
1466
1467         for (i = 0; i < dev->nchannels; i++) {
1468                 if (!dev->nets[i])
1469                         continue;
1470
1471                 unregister_netdev(dev->nets[i]->netdev);
1472         }
1473
1474         kvaser_usb_unlink_all_urbs(dev);
1475
1476         for (i = 0; i < dev->nchannels; i++) {
1477                 if (!dev->nets[i])
1478                         continue;
1479
1480                 free_candev(dev->nets[i]->netdev);
1481         }
1482 }
1483
1484 static int kvaser_usb_init_one(struct usb_interface *intf,
1485                                const struct usb_device_id *id, int channel)
1486 {
1487         struct kvaser_usb *dev = usb_get_intfdata(intf);
1488         struct net_device *netdev;
1489         struct kvaser_usb_net_priv *priv;
1490         int i, err;
1491
1492         err = kvaser_usb_send_simple_msg(dev, CMD_RESET_CHIP, channel);
1493         if (err)
1494                 return err;
1495
1496         netdev = alloc_candev(sizeof(*priv), MAX_TX_URBS);
1497         if (!netdev) {
1498                 dev_err(&intf->dev, "Cannot alloc candev\n");
1499                 return -ENOMEM;
1500         }
1501
1502         priv = netdev_priv(netdev);
1503
1504         init_completion(&priv->start_comp);
1505         init_completion(&priv->stop_comp);
1506
1507         init_usb_anchor(&priv->tx_submitted);
1508         atomic_set(&priv->active_tx_urbs, 0);
1509
1510         for (i = 0; i < ARRAY_SIZE(priv->tx_contexts); i++)
1511                 priv->tx_contexts[i].echo_index = MAX_TX_URBS;
1512
1513         priv->dev = dev;
1514         priv->netdev = netdev;
1515         priv->channel = channel;
1516
1517         priv->can.state = CAN_STATE_STOPPED;
1518         priv->can.clock.freq = CAN_USB_CLOCK;
1519         priv->can.bittiming_const = &kvaser_usb_bittiming_const;
1520         priv->can.do_set_bittiming = kvaser_usb_set_bittiming;
1521         priv->can.do_set_mode = kvaser_usb_set_mode;
1522         if (id->driver_info & KVASER_HAS_TXRX_ERRORS)
1523                 priv->can.do_get_berr_counter = kvaser_usb_get_berr_counter;
1524         priv->can.ctrlmode_supported = CAN_CTRLMODE_3_SAMPLES;
1525         if (id->driver_info & KVASER_HAS_SILENT_MODE)
1526                 priv->can.ctrlmode_supported |= CAN_CTRLMODE_LISTENONLY;
1527
1528         netdev->flags |= IFF_ECHO;
1529
1530         netdev->netdev_ops = &kvaser_usb_netdev_ops;
1531
1532         SET_NETDEV_DEV(netdev, &intf->dev);
1533
1534         dev->nets[channel] = priv;
1535
1536         err = register_candev(netdev);
1537         if (err) {
1538                 dev_err(&intf->dev, "Failed to register can device\n");
1539                 free_candev(netdev);
1540                 dev->nets[channel] = NULL;
1541                 return err;
1542         }
1543
1544         netdev_dbg(netdev, "device registered\n");
1545
1546         return 0;
1547 }
1548
1549 static int kvaser_usb_get_endpoints(const struct usb_interface *intf,
1550                                     struct usb_endpoint_descriptor **in,
1551                                     struct usb_endpoint_descriptor **out)
1552 {
1553         const struct usb_host_interface *iface_desc;
1554         struct usb_endpoint_descriptor *endpoint;
1555         int i;
1556
1557         iface_desc = &intf->altsetting[0];
1558
1559         for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {
1560                 endpoint = &iface_desc->endpoint[i].desc;
1561
1562                 if (!*in && usb_endpoint_is_bulk_in(endpoint))
1563                         *in = endpoint;
1564
1565                 if (!*out && usb_endpoint_is_bulk_out(endpoint))
1566                         *out = endpoint;
1567
1568                 /* use first bulk endpoint for in and out */
1569                 if (*in && *out)
1570                         return 0;
1571         }
1572
1573         return -ENODEV;
1574 }
1575
1576 static int kvaser_usb_probe(struct usb_interface *intf,
1577                             const struct usb_device_id *id)
1578 {
1579         struct kvaser_usb *dev;
1580         int err = -ENOMEM;
1581         int i;
1582
1583         dev = devm_kzalloc(&intf->dev, sizeof(*dev), GFP_KERNEL);
1584         if (!dev)
1585                 return -ENOMEM;
1586
1587         err = kvaser_usb_get_endpoints(intf, &dev->bulk_in, &dev->bulk_out);
1588         if (err) {
1589                 dev_err(&intf->dev, "Cannot get usb endpoint(s)");
1590                 return err;
1591         }
1592
1593         dev->udev = interface_to_usbdev(intf);
1594
1595         init_usb_anchor(&dev->rx_submitted);
1596
1597         usb_set_intfdata(intf, dev);
1598
1599         err = kvaser_usb_get_software_info(dev);
1600         if (err) {
1601                 dev_err(&intf->dev,
1602                         "Cannot get software infos, error %d\n", err);
1603                 return err;
1604         }
1605
1606         err = kvaser_usb_get_card_info(dev);
1607         if (err) {
1608                 dev_err(&intf->dev,
1609                         "Cannot get card infos, error %d\n", err);
1610                 return err;
1611         }
1612
1613         dev_dbg(&intf->dev, "Firmware version: %d.%d.%d\n",
1614                 ((dev->fw_version >> 24) & 0xff),
1615                 ((dev->fw_version >> 16) & 0xff),
1616                 (dev->fw_version & 0xffff));
1617
1618         for (i = 0; i < dev->nchannels; i++) {
1619                 err = kvaser_usb_init_one(intf, id, i);
1620                 if (err) {
1621                         kvaser_usb_remove_interfaces(dev);
1622                         return err;
1623                 }
1624         }
1625
1626         return 0;
1627 }
1628
1629 static void kvaser_usb_disconnect(struct usb_interface *intf)
1630 {
1631         struct kvaser_usb *dev = usb_get_intfdata(intf);
1632
1633         usb_set_intfdata(intf, NULL);
1634
1635         if (!dev)
1636                 return;
1637
1638         kvaser_usb_remove_interfaces(dev);
1639 }
1640
1641 static struct usb_driver kvaser_usb_driver = {
1642         .name = "kvaser_usb",
1643         .probe = kvaser_usb_probe,
1644         .disconnect = kvaser_usb_disconnect,
1645         .id_table = kvaser_usb_table,
1646 };
1647
1648 module_usb_driver(kvaser_usb_driver);
1649
1650 MODULE_AUTHOR("Olivier Sobrie <olivier@sobrie.be>");
1651 MODULE_DESCRIPTION("CAN driver for Kvaser CAN/USB devices");
1652 MODULE_LICENSE("GPL v2");