f6e30be1c0eb9f2899366c382993304371817182
[platform/kernel/linux-stable.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         if (status & M16C_STATE_BUS_RESET) {
658                 kvaser_usb_unlink_tx_urbs(priv);
659                 return;
660         }
661
662         skb = alloc_can_err_skb(priv->netdev, &cf);
663         if (!skb) {
664                 stats->rx_dropped++;
665                 return;
666         }
667
668         new_state = priv->can.state;
669
670         netdev_dbg(priv->netdev, "Error status: 0x%02x\n", status);
671
672         if (status & M16C_STATE_BUS_OFF) {
673                 cf->can_id |= CAN_ERR_BUSOFF;
674
675                 priv->can.can_stats.bus_off++;
676                 if (!priv->can.restart_ms)
677                         kvaser_usb_simple_msg_async(priv, CMD_STOP_CHIP);
678
679                 netif_carrier_off(priv->netdev);
680
681                 new_state = CAN_STATE_BUS_OFF;
682         } else if (status & M16C_STATE_BUS_PASSIVE) {
683                 if (priv->can.state != CAN_STATE_ERROR_PASSIVE) {
684                         cf->can_id |= CAN_ERR_CRTL;
685
686                         if (txerr || rxerr)
687                                 cf->data[1] = (txerr > rxerr)
688                                                 ? CAN_ERR_CRTL_TX_PASSIVE
689                                                 : CAN_ERR_CRTL_RX_PASSIVE;
690                         else
691                                 cf->data[1] = CAN_ERR_CRTL_TX_PASSIVE |
692                                               CAN_ERR_CRTL_RX_PASSIVE;
693
694                         priv->can.can_stats.error_passive++;
695                 }
696
697                 new_state = CAN_STATE_ERROR_PASSIVE;
698         }
699
700         if (status == M16C_STATE_BUS_ERROR) {
701                 if ((priv->can.state < CAN_STATE_ERROR_WARNING) &&
702                     ((txerr >= 96) || (rxerr >= 96))) {
703                         cf->can_id |= CAN_ERR_CRTL;
704                         cf->data[1] = (txerr > rxerr)
705                                         ? CAN_ERR_CRTL_TX_WARNING
706                                         : CAN_ERR_CRTL_RX_WARNING;
707
708                         priv->can.can_stats.error_warning++;
709                         new_state = CAN_STATE_ERROR_WARNING;
710                 } else if (priv->can.state > CAN_STATE_ERROR_ACTIVE) {
711                         cf->can_id |= CAN_ERR_PROT;
712                         cf->data[2] = CAN_ERR_PROT_ACTIVE;
713
714                         new_state = CAN_STATE_ERROR_ACTIVE;
715                 }
716         }
717
718         if (!status) {
719                 cf->can_id |= CAN_ERR_PROT;
720                 cf->data[2] = CAN_ERR_PROT_ACTIVE;
721
722                 new_state = CAN_STATE_ERROR_ACTIVE;
723         }
724
725         if (priv->can.restart_ms &&
726             (priv->can.state >= CAN_STATE_BUS_OFF) &&
727             (new_state < CAN_STATE_BUS_OFF)) {
728                 cf->can_id |= CAN_ERR_RESTARTED;
729                 netif_carrier_on(priv->netdev);
730
731                 priv->can.can_stats.restarts++;
732         }
733
734         if (error_factor) {
735                 priv->can.can_stats.bus_error++;
736                 stats->rx_errors++;
737
738                 cf->can_id |= CAN_ERR_BUSERROR | CAN_ERR_PROT;
739
740                 if (error_factor & M16C_EF_ACKE)
741                         cf->data[3] |= (CAN_ERR_PROT_LOC_ACK);
742                 if (error_factor & M16C_EF_CRCE)
743                         cf->data[3] |= (CAN_ERR_PROT_LOC_CRC_SEQ |
744                                         CAN_ERR_PROT_LOC_CRC_DEL);
745                 if (error_factor & M16C_EF_FORME)
746                         cf->data[2] |= CAN_ERR_PROT_FORM;
747                 if (error_factor & M16C_EF_STFE)
748                         cf->data[2] |= CAN_ERR_PROT_STUFF;
749                 if (error_factor & M16C_EF_BITE0)
750                         cf->data[2] |= CAN_ERR_PROT_BIT0;
751                 if (error_factor & M16C_EF_BITE1)
752                         cf->data[2] |= CAN_ERR_PROT_BIT1;
753                 if (error_factor & M16C_EF_TRE)
754                         cf->data[2] |= CAN_ERR_PROT_TX;
755         }
756
757         cf->data[6] = txerr;
758         cf->data[7] = rxerr;
759
760         priv->bec.txerr = txerr;
761         priv->bec.rxerr = rxerr;
762
763         priv->can.state = new_state;
764
765         netif_rx(skb);
766
767         stats->rx_packets++;
768         stats->rx_bytes += cf->can_dlc;
769 }
770
771 static void kvaser_usb_rx_can_err(const struct kvaser_usb_net_priv *priv,
772                                   const struct kvaser_msg *msg)
773 {
774         struct can_frame *cf;
775         struct sk_buff *skb;
776         struct net_device_stats *stats = &priv->netdev->stats;
777
778         if (msg->u.rx_can.flag & (MSG_FLAG_ERROR_FRAME |
779                                          MSG_FLAG_NERR)) {
780                 netdev_err(priv->netdev, "Unknow error (flags: 0x%02x)\n",
781                            msg->u.rx_can.flag);
782
783                 stats->rx_errors++;
784                 return;
785         }
786
787         if (msg->u.rx_can.flag & MSG_FLAG_OVERRUN) {
788                 skb = alloc_can_err_skb(priv->netdev, &cf);
789                 if (!skb) {
790                         stats->rx_dropped++;
791                         return;
792                 }
793
794                 cf->can_id |= CAN_ERR_CRTL;
795                 cf->data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
796
797                 stats->rx_over_errors++;
798                 stats->rx_errors++;
799
800                 netif_rx(skb);
801
802                 stats->rx_packets++;
803                 stats->rx_bytes += cf->can_dlc;
804         }
805 }
806
807 static void kvaser_usb_rx_can_msg(const struct kvaser_usb *dev,
808                                   const struct kvaser_msg *msg)
809 {
810         struct kvaser_usb_net_priv *priv;
811         struct can_frame *cf;
812         struct sk_buff *skb;
813         struct net_device_stats *stats;
814         u8 channel = msg->u.rx_can.channel;
815
816         if (channel >= dev->nchannels) {
817                 dev_err(dev->udev->dev.parent,
818                         "Invalid channel number (%d)\n", channel);
819                 return;
820         }
821
822         priv = dev->nets[channel];
823         stats = &priv->netdev->stats;
824
825         if ((msg->u.rx_can.flag & MSG_FLAG_ERROR_FRAME) &&
826             (msg->id == CMD_LOG_MESSAGE)) {
827                 kvaser_usb_rx_error(dev, msg);
828                 return;
829         } else if (msg->u.rx_can.flag & (MSG_FLAG_ERROR_FRAME |
830                                          MSG_FLAG_NERR |
831                                          MSG_FLAG_OVERRUN)) {
832                 kvaser_usb_rx_can_err(priv, msg);
833                 return;
834         } else if (msg->u.rx_can.flag & ~MSG_FLAG_REMOTE_FRAME) {
835                 netdev_warn(priv->netdev,
836                             "Unhandled frame (flags: 0x%02x)",
837                             msg->u.rx_can.flag);
838                 return;
839         }
840
841         skb = alloc_can_skb(priv->netdev, &cf);
842         if (!skb) {
843                 stats->tx_dropped++;
844                 return;
845         }
846
847         if (msg->id == CMD_LOG_MESSAGE) {
848                 cf->can_id = le32_to_cpu(msg->u.log_message.id);
849                 if (cf->can_id & KVASER_EXTENDED_FRAME)
850                         cf->can_id &= CAN_EFF_MASK | CAN_EFF_FLAG;
851                 else
852                         cf->can_id &= CAN_SFF_MASK;
853
854                 cf->can_dlc = get_can_dlc(msg->u.log_message.dlc);
855
856                 if (msg->u.log_message.flags & MSG_FLAG_REMOTE_FRAME)
857                         cf->can_id |= CAN_RTR_FLAG;
858                 else
859                         memcpy(cf->data, &msg->u.log_message.data,
860                                cf->can_dlc);
861         } else {
862                 cf->can_id = ((msg->u.rx_can.msg[0] & 0x1f) << 6) |
863                              (msg->u.rx_can.msg[1] & 0x3f);
864
865                 if (msg->id == CMD_RX_EXT_MESSAGE) {
866                         cf->can_id <<= 18;
867                         cf->can_id |= ((msg->u.rx_can.msg[2] & 0x0f) << 14) |
868                                       ((msg->u.rx_can.msg[3] & 0xff) << 6) |
869                                       (msg->u.rx_can.msg[4] & 0x3f);
870                         cf->can_id |= CAN_EFF_FLAG;
871                 }
872
873                 cf->can_dlc = get_can_dlc(msg->u.rx_can.msg[5]);
874
875                 if (msg->u.rx_can.flag & MSG_FLAG_REMOTE_FRAME)
876                         cf->can_id |= CAN_RTR_FLAG;
877                 else
878                         memcpy(cf->data, &msg->u.rx_can.msg[6],
879                                cf->can_dlc);
880         }
881
882         netif_rx(skb);
883
884         stats->rx_packets++;
885         stats->rx_bytes += cf->can_dlc;
886 }
887
888 static void kvaser_usb_start_chip_reply(const struct kvaser_usb *dev,
889                                         const struct kvaser_msg *msg)
890 {
891         struct kvaser_usb_net_priv *priv;
892         u8 channel = msg->u.simple.channel;
893
894         if (channel >= dev->nchannels) {
895                 dev_err(dev->udev->dev.parent,
896                         "Invalid channel number (%d)\n", channel);
897                 return;
898         }
899
900         priv = dev->nets[channel];
901
902         if (completion_done(&priv->start_comp) &&
903             netif_queue_stopped(priv->netdev)) {
904                 netif_wake_queue(priv->netdev);
905         } else {
906                 netif_start_queue(priv->netdev);
907                 complete(&priv->start_comp);
908         }
909 }
910
911 static void kvaser_usb_stop_chip_reply(const struct kvaser_usb *dev,
912                                        const struct kvaser_msg *msg)
913 {
914         struct kvaser_usb_net_priv *priv;
915         u8 channel = msg->u.simple.channel;
916
917         if (channel >= dev->nchannels) {
918                 dev_err(dev->udev->dev.parent,
919                         "Invalid channel number (%d)\n", channel);
920                 return;
921         }
922
923         priv = dev->nets[channel];
924
925         complete(&priv->stop_comp);
926 }
927
928 static void kvaser_usb_handle_message(const struct kvaser_usb *dev,
929                                       const struct kvaser_msg *msg)
930 {
931         switch (msg->id) {
932         case CMD_START_CHIP_REPLY:
933                 kvaser_usb_start_chip_reply(dev, msg);
934                 break;
935
936         case CMD_STOP_CHIP_REPLY:
937                 kvaser_usb_stop_chip_reply(dev, msg);
938                 break;
939
940         case CMD_RX_STD_MESSAGE:
941         case CMD_RX_EXT_MESSAGE:
942         case CMD_LOG_MESSAGE:
943                 kvaser_usb_rx_can_msg(dev, msg);
944                 break;
945
946         case CMD_CHIP_STATE_EVENT:
947         case CMD_CAN_ERROR_EVENT:
948                 kvaser_usb_rx_error(dev, msg);
949                 break;
950
951         case CMD_TX_ACKNOWLEDGE:
952                 kvaser_usb_tx_acknowledge(dev, msg);
953                 break;
954
955         default:
956                 dev_warn(dev->udev->dev.parent,
957                          "Unhandled message (%d)\n", msg->id);
958                 break;
959         }
960 }
961
962 static void kvaser_usb_read_bulk_callback(struct urb *urb)
963 {
964         struct kvaser_usb *dev = urb->context;
965         struct kvaser_msg *msg;
966         int pos = 0;
967         int err, i;
968
969         switch (urb->status) {
970         case 0:
971                 break;
972         case -ENOENT:
973         case -ESHUTDOWN:
974                 return;
975         default:
976                 dev_info(dev->udev->dev.parent, "Rx URB aborted (%d)\n",
977                          urb->status);
978                 goto resubmit_urb;
979         }
980
981         while (pos <= urb->actual_length - MSG_HEADER_LEN) {
982                 msg = urb->transfer_buffer + pos;
983
984                 if (!msg->len)
985                         break;
986
987                 if (pos + msg->len > urb->actual_length) {
988                         dev_err(dev->udev->dev.parent, "Format error\n");
989                         break;
990                 }
991
992                 kvaser_usb_handle_message(dev, msg);
993
994                 pos += msg->len;
995         }
996
997 resubmit_urb:
998         usb_fill_bulk_urb(urb, dev->udev,
999                           usb_rcvbulkpipe(dev->udev,
1000                                           dev->bulk_in->bEndpointAddress),
1001                           urb->transfer_buffer, RX_BUFFER_SIZE,
1002                           kvaser_usb_read_bulk_callback, dev);
1003
1004         err = usb_submit_urb(urb, GFP_ATOMIC);
1005         if (err == -ENODEV) {
1006                 for (i = 0; i < dev->nchannels; i++) {
1007                         if (!dev->nets[i])
1008                                 continue;
1009
1010                         netif_device_detach(dev->nets[i]->netdev);
1011                 }
1012         } else if (err) {
1013                 dev_err(dev->udev->dev.parent,
1014                         "Failed resubmitting read bulk urb: %d\n", err);
1015         }
1016
1017         return;
1018 }
1019
1020 static int kvaser_usb_setup_rx_urbs(struct kvaser_usb *dev)
1021 {
1022         int i, err = 0;
1023
1024         if (dev->rxinitdone)
1025                 return 0;
1026
1027         for (i = 0; i < MAX_RX_URBS; i++) {
1028                 struct urb *urb = NULL;
1029                 u8 *buf = NULL;
1030                 dma_addr_t buf_dma;
1031
1032                 urb = usb_alloc_urb(0, GFP_KERNEL);
1033                 if (!urb) {
1034                         dev_warn(dev->udev->dev.parent,
1035                                  "No memory left for URBs\n");
1036                         err = -ENOMEM;
1037                         break;
1038                 }
1039
1040                 buf = usb_alloc_coherent(dev->udev, RX_BUFFER_SIZE,
1041                                          GFP_KERNEL, &buf_dma);
1042                 if (!buf) {
1043                         dev_warn(dev->udev->dev.parent,
1044                                  "No memory left for USB buffer\n");
1045                         usb_free_urb(urb);
1046                         err = -ENOMEM;
1047                         break;
1048                 }
1049
1050                 usb_fill_bulk_urb(urb, dev->udev,
1051                                   usb_rcvbulkpipe(dev->udev,
1052                                           dev->bulk_in->bEndpointAddress),
1053                                   buf, RX_BUFFER_SIZE,
1054                                   kvaser_usb_read_bulk_callback,
1055                                   dev);
1056                 urb->transfer_dma = buf_dma;
1057                 urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
1058                 usb_anchor_urb(urb, &dev->rx_submitted);
1059
1060                 err = usb_submit_urb(urb, GFP_KERNEL);
1061                 if (err) {
1062                         usb_unanchor_urb(urb);
1063                         usb_free_coherent(dev->udev, RX_BUFFER_SIZE, buf,
1064                                           buf_dma);
1065                         usb_free_urb(urb);
1066                         break;
1067                 }
1068
1069                 dev->rxbuf[i] = buf;
1070                 dev->rxbuf_dma[i] = buf_dma;
1071
1072                 usb_free_urb(urb);
1073         }
1074
1075         if (i == 0) {
1076                 dev_warn(dev->udev->dev.parent,
1077                          "Cannot setup read URBs, error %d\n", err);
1078                 return err;
1079         } else if (i < MAX_RX_URBS) {
1080                 dev_warn(dev->udev->dev.parent,
1081                          "RX performances may be slow\n");
1082         }
1083
1084         dev->rxinitdone = true;
1085
1086         return 0;
1087 }
1088
1089 static int kvaser_usb_set_opt_mode(const struct kvaser_usb_net_priv *priv)
1090 {
1091         struct kvaser_msg *msg;
1092         int rc;
1093
1094         msg = kmalloc(sizeof(*msg), GFP_KERNEL);
1095         if (!msg)
1096                 return -ENOMEM;
1097
1098         msg->id = CMD_SET_CTRL_MODE;
1099         msg->len = MSG_HEADER_LEN + sizeof(struct kvaser_msg_ctrl_mode);
1100         msg->u.ctrl_mode.tid = 0xff;
1101         msg->u.ctrl_mode.channel = priv->channel;
1102
1103         if (priv->can.ctrlmode & CAN_CTRLMODE_LISTENONLY)
1104                 msg->u.ctrl_mode.ctrl_mode = KVASER_CTRL_MODE_SILENT;
1105         else
1106                 msg->u.ctrl_mode.ctrl_mode = KVASER_CTRL_MODE_NORMAL;
1107
1108         rc = kvaser_usb_send_msg(priv->dev, msg);
1109
1110         kfree(msg);
1111         return rc;
1112 }
1113
1114 static int kvaser_usb_start_chip(struct kvaser_usb_net_priv *priv)
1115 {
1116         int err;
1117
1118         init_completion(&priv->start_comp);
1119
1120         err = kvaser_usb_send_simple_msg(priv->dev, CMD_START_CHIP,
1121                                          priv->channel);
1122         if (err)
1123                 return err;
1124
1125         if (!wait_for_completion_timeout(&priv->start_comp,
1126                                          msecs_to_jiffies(START_TIMEOUT)))
1127                 return -ETIMEDOUT;
1128
1129         return 0;
1130 }
1131
1132 static int kvaser_usb_open(struct net_device *netdev)
1133 {
1134         struct kvaser_usb_net_priv *priv = netdev_priv(netdev);
1135         struct kvaser_usb *dev = priv->dev;
1136         int err;
1137
1138         err = open_candev(netdev);
1139         if (err)
1140                 return err;
1141
1142         err = kvaser_usb_setup_rx_urbs(dev);
1143         if (err)
1144                 goto error;
1145
1146         err = kvaser_usb_set_opt_mode(priv);
1147         if (err)
1148                 goto error;
1149
1150         err = kvaser_usb_start_chip(priv);
1151         if (err) {
1152                 netdev_warn(netdev, "Cannot start device, error %d\n", err);
1153                 goto error;
1154         }
1155
1156         priv->can.state = CAN_STATE_ERROR_ACTIVE;
1157
1158         return 0;
1159
1160 error:
1161         close_candev(netdev);
1162         return err;
1163 }
1164
1165 static void kvaser_usb_unlink_all_urbs(struct kvaser_usb *dev)
1166 {
1167         int i;
1168
1169         usb_kill_anchored_urbs(&dev->rx_submitted);
1170
1171         for (i = 0; i < MAX_RX_URBS; i++)
1172                 usb_free_coherent(dev->udev, RX_BUFFER_SIZE,
1173                                   dev->rxbuf[i],
1174                                   dev->rxbuf_dma[i]);
1175
1176         for (i = 0; i < MAX_NET_DEVICES; i++) {
1177                 struct kvaser_usb_net_priv *priv = dev->nets[i];
1178
1179                 if (priv)
1180                         kvaser_usb_unlink_tx_urbs(priv);
1181         }
1182 }
1183
1184 static int kvaser_usb_stop_chip(struct kvaser_usb_net_priv *priv)
1185 {
1186         int err;
1187
1188         init_completion(&priv->stop_comp);
1189
1190         err = kvaser_usb_send_simple_msg(priv->dev, CMD_STOP_CHIP,
1191                                          priv->channel);
1192         if (err)
1193                 return err;
1194
1195         if (!wait_for_completion_timeout(&priv->stop_comp,
1196                                          msecs_to_jiffies(STOP_TIMEOUT)))
1197                 return -ETIMEDOUT;
1198
1199         return 0;
1200 }
1201
1202 static int kvaser_usb_flush_queue(struct kvaser_usb_net_priv *priv)
1203 {
1204         struct kvaser_msg *msg;
1205         int rc;
1206
1207         msg = kmalloc(sizeof(*msg), GFP_KERNEL);
1208         if (!msg)
1209                 return -ENOMEM;
1210
1211         msg->id = CMD_FLUSH_QUEUE;
1212         msg->len = MSG_HEADER_LEN + sizeof(struct kvaser_msg_flush_queue);
1213         msg->u.flush_queue.channel = priv->channel;
1214         msg->u.flush_queue.flags = 0x00;
1215
1216         rc = kvaser_usb_send_msg(priv->dev, msg);
1217
1218         kfree(msg);
1219         return rc;
1220 }
1221
1222 static int kvaser_usb_close(struct net_device *netdev)
1223 {
1224         struct kvaser_usb_net_priv *priv = netdev_priv(netdev);
1225         struct kvaser_usb *dev = priv->dev;
1226         int err;
1227
1228         netif_stop_queue(netdev);
1229
1230         err = kvaser_usb_flush_queue(priv);
1231         if (err)
1232                 netdev_warn(netdev, "Cannot flush queue, error %d\n", err);
1233
1234         if (kvaser_usb_send_simple_msg(dev, CMD_RESET_CHIP, priv->channel))
1235                 netdev_warn(netdev, "Cannot reset card, error %d\n", err);
1236
1237         err = kvaser_usb_stop_chip(priv);
1238         if (err)
1239                 netdev_warn(netdev, "Cannot stop device, error %d\n", err);
1240
1241         priv->can.state = CAN_STATE_STOPPED;
1242         close_candev(priv->netdev);
1243
1244         return 0;
1245 }
1246
1247 static void kvaser_usb_write_bulk_callback(struct urb *urb)
1248 {
1249         struct kvaser_usb_tx_urb_context *context = urb->context;
1250         struct kvaser_usb_net_priv *priv;
1251         struct net_device *netdev;
1252
1253         if (WARN_ON(!context))
1254                 return;
1255
1256         priv = context->priv;
1257         netdev = priv->netdev;
1258
1259         kfree(urb->transfer_buffer);
1260
1261         if (!netif_device_present(netdev))
1262                 return;
1263
1264         if (urb->status)
1265                 netdev_info(netdev, "Tx URB aborted (%d)\n", urb->status);
1266 }
1267
1268 static netdev_tx_t kvaser_usb_start_xmit(struct sk_buff *skb,
1269                                          struct net_device *netdev)
1270 {
1271         struct kvaser_usb_net_priv *priv = netdev_priv(netdev);
1272         struct kvaser_usb *dev = priv->dev;
1273         struct net_device_stats *stats = &netdev->stats;
1274         struct can_frame *cf = (struct can_frame *)skb->data;
1275         struct kvaser_usb_tx_urb_context *context = NULL;
1276         struct urb *urb;
1277         void *buf;
1278         struct kvaser_msg *msg;
1279         int i, err;
1280         int ret = NETDEV_TX_OK;
1281
1282         if (can_dropped_invalid_skb(netdev, skb))
1283                 return NETDEV_TX_OK;
1284
1285         urb = usb_alloc_urb(0, GFP_ATOMIC);
1286         if (!urb) {
1287                 netdev_err(netdev, "No memory left for URBs\n");
1288                 stats->tx_dropped++;
1289                 dev_kfree_skb(skb);
1290                 return NETDEV_TX_OK;
1291         }
1292
1293         buf = kmalloc(sizeof(struct kvaser_msg), GFP_ATOMIC);
1294         if (!buf) {
1295                 stats->tx_dropped++;
1296                 dev_kfree_skb(skb);
1297                 goto nobufmem;
1298         }
1299
1300         msg = buf;
1301         msg->len = MSG_HEADER_LEN + sizeof(struct kvaser_msg_tx_can);
1302         msg->u.tx_can.flags = 0;
1303         msg->u.tx_can.channel = priv->channel;
1304
1305         if (cf->can_id & CAN_EFF_FLAG) {
1306                 msg->id = CMD_TX_EXT_MESSAGE;
1307                 msg->u.tx_can.msg[0] = (cf->can_id >> 24) & 0x1f;
1308                 msg->u.tx_can.msg[1] = (cf->can_id >> 18) & 0x3f;
1309                 msg->u.tx_can.msg[2] = (cf->can_id >> 14) & 0x0f;
1310                 msg->u.tx_can.msg[3] = (cf->can_id >> 6) & 0xff;
1311                 msg->u.tx_can.msg[4] = cf->can_id & 0x3f;
1312         } else {
1313                 msg->id = CMD_TX_STD_MESSAGE;
1314                 msg->u.tx_can.msg[0] = (cf->can_id >> 6) & 0x1f;
1315                 msg->u.tx_can.msg[1] = cf->can_id & 0x3f;
1316         }
1317
1318         msg->u.tx_can.msg[5] = cf->can_dlc;
1319         memcpy(&msg->u.tx_can.msg[6], cf->data, cf->can_dlc);
1320
1321         if (cf->can_id & CAN_RTR_FLAG)
1322                 msg->u.tx_can.flags |= MSG_FLAG_REMOTE_FRAME;
1323
1324         for (i = 0; i < ARRAY_SIZE(priv->tx_contexts); i++) {
1325                 if (priv->tx_contexts[i].echo_index == MAX_TX_URBS) {
1326                         context = &priv->tx_contexts[i];
1327                         break;
1328                 }
1329         }
1330
1331         /* This should never happen; it implies a flow control bug */
1332         if (!context) {
1333                 netdev_warn(netdev, "cannot find free context\n");
1334                 ret =  NETDEV_TX_BUSY;
1335                 goto releasebuf;
1336         }
1337
1338         context->priv = priv;
1339         context->echo_index = i;
1340         context->dlc = cf->can_dlc;
1341
1342         msg->u.tx_can.tid = context->echo_index;
1343
1344         usb_fill_bulk_urb(urb, dev->udev,
1345                           usb_sndbulkpipe(dev->udev,
1346                                           dev->bulk_out->bEndpointAddress),
1347                           buf, msg->len,
1348                           kvaser_usb_write_bulk_callback, context);
1349         usb_anchor_urb(urb, &priv->tx_submitted);
1350
1351         can_put_echo_skb(skb, netdev, context->echo_index);
1352
1353         atomic_inc(&priv->active_tx_urbs);
1354
1355         if (atomic_read(&priv->active_tx_urbs) >= MAX_TX_URBS)
1356                 netif_stop_queue(netdev);
1357
1358         err = usb_submit_urb(urb, GFP_ATOMIC);
1359         if (unlikely(err)) {
1360                 can_free_echo_skb(netdev, context->echo_index);
1361
1362                 atomic_dec(&priv->active_tx_urbs);
1363                 usb_unanchor_urb(urb);
1364
1365                 stats->tx_dropped++;
1366
1367                 if (err == -ENODEV)
1368                         netif_device_detach(netdev);
1369                 else
1370                         netdev_warn(netdev, "Failed tx_urb %d\n", err);
1371
1372                 goto releasebuf;
1373         }
1374
1375         usb_free_urb(urb);
1376
1377         return NETDEV_TX_OK;
1378
1379 releasebuf:
1380         kfree(buf);
1381 nobufmem:
1382         usb_free_urb(urb);
1383         return ret;
1384 }
1385
1386 static const struct net_device_ops kvaser_usb_netdev_ops = {
1387         .ndo_open = kvaser_usb_open,
1388         .ndo_stop = kvaser_usb_close,
1389         .ndo_start_xmit = kvaser_usb_start_xmit,
1390 };
1391
1392 static const struct can_bittiming_const kvaser_usb_bittiming_const = {
1393         .name = "kvaser_usb",
1394         .tseg1_min = KVASER_USB_TSEG1_MIN,
1395         .tseg1_max = KVASER_USB_TSEG1_MAX,
1396         .tseg2_min = KVASER_USB_TSEG2_MIN,
1397         .tseg2_max = KVASER_USB_TSEG2_MAX,
1398         .sjw_max = KVASER_USB_SJW_MAX,
1399         .brp_min = KVASER_USB_BRP_MIN,
1400         .brp_max = KVASER_USB_BRP_MAX,
1401         .brp_inc = KVASER_USB_BRP_INC,
1402 };
1403
1404 static int kvaser_usb_set_bittiming(struct net_device *netdev)
1405 {
1406         struct kvaser_usb_net_priv *priv = netdev_priv(netdev);
1407         struct can_bittiming *bt = &priv->can.bittiming;
1408         struct kvaser_usb *dev = priv->dev;
1409         struct kvaser_msg *msg;
1410         int rc;
1411
1412         msg = kmalloc(sizeof(*msg), GFP_KERNEL);
1413         if (!msg)
1414                 return -ENOMEM;
1415
1416         msg->id = CMD_SET_BUS_PARAMS;
1417         msg->len = MSG_HEADER_LEN + sizeof(struct kvaser_msg_busparams);
1418         msg->u.busparams.channel = priv->channel;
1419         msg->u.busparams.tid = 0xff;
1420         msg->u.busparams.bitrate = cpu_to_le32(bt->bitrate);
1421         msg->u.busparams.sjw = bt->sjw;
1422         msg->u.busparams.tseg1 = bt->prop_seg + bt->phase_seg1;
1423         msg->u.busparams.tseg2 = bt->phase_seg2;
1424
1425         if (priv->can.ctrlmode & CAN_CTRLMODE_3_SAMPLES)
1426                 msg->u.busparams.no_samp = 3;
1427         else
1428                 msg->u.busparams.no_samp = 1;
1429
1430         rc = kvaser_usb_send_msg(dev, msg);
1431
1432         kfree(msg);
1433         return rc;
1434 }
1435
1436 static int kvaser_usb_set_mode(struct net_device *netdev,
1437                                enum can_mode mode)
1438 {
1439         struct kvaser_usb_net_priv *priv = netdev_priv(netdev);
1440         int err;
1441
1442         switch (mode) {
1443         case CAN_MODE_START:
1444                 err = kvaser_usb_simple_msg_async(priv, CMD_START_CHIP);
1445                 if (err)
1446                         return err;
1447                 break;
1448         default:
1449                 return -EOPNOTSUPP;
1450         }
1451
1452         return 0;
1453 }
1454
1455 static int kvaser_usb_get_berr_counter(const struct net_device *netdev,
1456                                        struct can_berr_counter *bec)
1457 {
1458         struct kvaser_usb_net_priv *priv = netdev_priv(netdev);
1459
1460         *bec = priv->bec;
1461
1462         return 0;
1463 }
1464
1465 static void kvaser_usb_remove_interfaces(struct kvaser_usb *dev)
1466 {
1467         int i;
1468
1469         for (i = 0; i < dev->nchannels; i++) {
1470                 if (!dev->nets[i])
1471                         continue;
1472
1473                 unregister_netdev(dev->nets[i]->netdev);
1474         }
1475
1476         kvaser_usb_unlink_all_urbs(dev);
1477
1478         for (i = 0; i < dev->nchannels; i++) {
1479                 if (!dev->nets[i])
1480                         continue;
1481
1482                 free_candev(dev->nets[i]->netdev);
1483         }
1484 }
1485
1486 static int kvaser_usb_init_one(struct usb_interface *intf,
1487                                const struct usb_device_id *id, int channel)
1488 {
1489         struct kvaser_usb *dev = usb_get_intfdata(intf);
1490         struct net_device *netdev;
1491         struct kvaser_usb_net_priv *priv;
1492         int i, err;
1493
1494         netdev = alloc_candev(sizeof(*priv), MAX_TX_URBS);
1495         if (!netdev) {
1496                 dev_err(&intf->dev, "Cannot alloc candev\n");
1497                 return -ENOMEM;
1498         }
1499
1500         priv = netdev_priv(netdev);
1501
1502         init_completion(&priv->start_comp);
1503         init_completion(&priv->stop_comp);
1504
1505         init_usb_anchor(&priv->tx_submitted);
1506         atomic_set(&priv->active_tx_urbs, 0);
1507
1508         for (i = 0; i < ARRAY_SIZE(priv->tx_contexts); i++)
1509                 priv->tx_contexts[i].echo_index = MAX_TX_URBS;
1510
1511         priv->dev = dev;
1512         priv->netdev = netdev;
1513         priv->channel = channel;
1514
1515         priv->can.state = CAN_STATE_STOPPED;
1516         priv->can.clock.freq = CAN_USB_CLOCK;
1517         priv->can.bittiming_const = &kvaser_usb_bittiming_const;
1518         priv->can.do_set_bittiming = kvaser_usb_set_bittiming;
1519         priv->can.do_set_mode = kvaser_usb_set_mode;
1520         if (id->driver_info & KVASER_HAS_TXRX_ERRORS)
1521                 priv->can.do_get_berr_counter = kvaser_usb_get_berr_counter;
1522         priv->can.ctrlmode_supported = CAN_CTRLMODE_3_SAMPLES;
1523         if (id->driver_info & KVASER_HAS_SILENT_MODE)
1524                 priv->can.ctrlmode_supported |= CAN_CTRLMODE_LISTENONLY;
1525
1526         netdev->flags |= IFF_ECHO;
1527
1528         netdev->netdev_ops = &kvaser_usb_netdev_ops;
1529
1530         SET_NETDEV_DEV(netdev, &intf->dev);
1531
1532         dev->nets[channel] = priv;
1533
1534         err = register_candev(netdev);
1535         if (err) {
1536                 dev_err(&intf->dev, "Failed to register can device\n");
1537                 free_candev(netdev);
1538                 dev->nets[channel] = NULL;
1539                 return err;
1540         }
1541
1542         netdev_dbg(netdev, "device registered\n");
1543
1544         return 0;
1545 }
1546
1547 static int kvaser_usb_get_endpoints(const struct usb_interface *intf,
1548                                     struct usb_endpoint_descriptor **in,
1549                                     struct usb_endpoint_descriptor **out)
1550 {
1551         const struct usb_host_interface *iface_desc;
1552         struct usb_endpoint_descriptor *endpoint;
1553         int i;
1554
1555         iface_desc = &intf->altsetting[0];
1556
1557         for (i = 0; i < iface_desc->desc.bNumEndpoints; ++i) {
1558                 endpoint = &iface_desc->endpoint[i].desc;
1559
1560                 if (!*in && usb_endpoint_is_bulk_in(endpoint))
1561                         *in = endpoint;
1562
1563                 if (!*out && usb_endpoint_is_bulk_out(endpoint))
1564                         *out = endpoint;
1565
1566                 /* use first bulk endpoint for in and out */
1567                 if (*in && *out)
1568                         return 0;
1569         }
1570
1571         return -ENODEV;
1572 }
1573
1574 static int kvaser_usb_probe(struct usb_interface *intf,
1575                             const struct usb_device_id *id)
1576 {
1577         struct kvaser_usb *dev;
1578         int err = -ENOMEM;
1579         int i;
1580
1581         dev = devm_kzalloc(&intf->dev, sizeof(*dev), GFP_KERNEL);
1582         if (!dev)
1583                 return -ENOMEM;
1584
1585         err = kvaser_usb_get_endpoints(intf, &dev->bulk_in, &dev->bulk_out);
1586         if (err) {
1587                 dev_err(&intf->dev, "Cannot get usb endpoint(s)");
1588                 return err;
1589         }
1590
1591         dev->udev = interface_to_usbdev(intf);
1592
1593         init_usb_anchor(&dev->rx_submitted);
1594
1595         usb_set_intfdata(intf, dev);
1596
1597         for (i = 0; i < MAX_NET_DEVICES; i++)
1598                 kvaser_usb_send_simple_msg(dev, CMD_RESET_CHIP, i);
1599
1600         err = kvaser_usb_get_software_info(dev);
1601         if (err) {
1602                 dev_err(&intf->dev,
1603                         "Cannot get software infos, error %d\n", err);
1604                 return err;
1605         }
1606
1607         err = kvaser_usb_get_card_info(dev);
1608         if (err) {
1609                 dev_err(&intf->dev,
1610                         "Cannot get card infos, error %d\n", err);
1611                 return err;
1612         }
1613
1614         dev_dbg(&intf->dev, "Firmware version: %d.%d.%d\n",
1615                 ((dev->fw_version >> 24) & 0xff),
1616                 ((dev->fw_version >> 16) & 0xff),
1617                 (dev->fw_version & 0xffff));
1618
1619         for (i = 0; i < dev->nchannels; i++) {
1620                 err = kvaser_usb_init_one(intf, id, i);
1621                 if (err) {
1622                         kvaser_usb_remove_interfaces(dev);
1623                         return err;
1624                 }
1625         }
1626
1627         return 0;
1628 }
1629
1630 static void kvaser_usb_disconnect(struct usb_interface *intf)
1631 {
1632         struct kvaser_usb *dev = usb_get_intfdata(intf);
1633
1634         usb_set_intfdata(intf, NULL);
1635
1636         if (!dev)
1637                 return;
1638
1639         kvaser_usb_remove_interfaces(dev);
1640 }
1641
1642 static struct usb_driver kvaser_usb_driver = {
1643         .name = "kvaser_usb",
1644         .probe = kvaser_usb_probe,
1645         .disconnect = kvaser_usb_disconnect,
1646         .id_table = kvaser_usb_table,
1647 };
1648
1649 module_usb_driver(kvaser_usb_driver);
1650
1651 MODULE_AUTHOR("Olivier Sobrie <olivier@sobrie.be>");
1652 MODULE_DESCRIPTION("CAN driver for Kvaser CAN/USB devices");
1653 MODULE_LICENSE("GPL v2");