xref: /linux/drivers/net/can/usb/usb_8dev.c (revision a1c3be890440a1769ed6f822376a3e3ab0d42994)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * CAN driver for "8 devices" USB2CAN converter
4  *
5  * Copyright (C) 2012 Bernd Krumboeck (krumboeck@universalnet.at)
6  *
7  * This driver is inspired by the 3.2.0 version of drivers/net/can/usb/ems_usb.c
8  * and drivers/net/can/usb/esd_usb2.c
9  *
10  * Many thanks to Gerhard Bertelsmann (info@gerhard-bertelsmann.de)
11  * for testing and fixing this driver. Also many thanks to "8 devices",
12  * who were very cooperative and answered my questions.
13  */
14 
15 #include <linux/signal.h>
16 #include <linux/slab.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 #include <linux/can/led.h>
25 
26 /* driver constants */
27 #define MAX_RX_URBS			20
28 #define MAX_TX_URBS			20
29 #define RX_BUFFER_SIZE			64
30 
31 /* vendor and product id */
32 #define USB_8DEV_VENDOR_ID		0x0483
33 #define USB_8DEV_PRODUCT_ID		0x1234
34 
35 /* endpoints */
36 enum usb_8dev_endpoint {
37 	USB_8DEV_ENDP_DATA_RX = 1,
38 	USB_8DEV_ENDP_DATA_TX,
39 	USB_8DEV_ENDP_CMD_RX,
40 	USB_8DEV_ENDP_CMD_TX
41 };
42 
43 /* device CAN clock */
44 #define USB_8DEV_ABP_CLOCK		32000000
45 
46 /* setup flags */
47 #define USB_8DEV_SILENT			0x01
48 #define USB_8DEV_LOOPBACK		0x02
49 #define USB_8DEV_DISABLE_AUTO_RESTRANS	0x04
50 #define USB_8DEV_STATUS_FRAME		0x08
51 
52 /* commands */
53 enum usb_8dev_cmd {
54 	USB_8DEV_RESET = 1,
55 	USB_8DEV_OPEN,
56 	USB_8DEV_CLOSE,
57 	USB_8DEV_SET_SPEED,
58 	USB_8DEV_SET_MASK_FILTER,
59 	USB_8DEV_GET_STATUS,
60 	USB_8DEV_GET_STATISTICS,
61 	USB_8DEV_GET_SERIAL,
62 	USB_8DEV_GET_SOFTW_VER,
63 	USB_8DEV_GET_HARDW_VER,
64 	USB_8DEV_RESET_TIMESTAMP,
65 	USB_8DEV_GET_SOFTW_HARDW_VER
66 };
67 
68 /* command options */
69 #define USB_8DEV_BAUD_MANUAL		0x09
70 #define USB_8DEV_CMD_START		0x11
71 #define USB_8DEV_CMD_END		0x22
72 
73 #define USB_8DEV_CMD_SUCCESS		0
74 #define USB_8DEV_CMD_ERROR		255
75 
76 #define USB_8DEV_CMD_TIMEOUT		1000
77 
78 /* frames */
79 #define USB_8DEV_DATA_START		0x55
80 #define USB_8DEV_DATA_END		0xAA
81 
82 #define USB_8DEV_TYPE_CAN_FRAME		0
83 #define USB_8DEV_TYPE_ERROR_FRAME	3
84 
85 #define USB_8DEV_EXTID			0x01
86 #define USB_8DEV_RTR			0x02
87 #define USB_8DEV_ERR_FLAG		0x04
88 
89 /* status */
90 #define USB_8DEV_STATUSMSG_OK		0x00  /* Normal condition. */
91 #define USB_8DEV_STATUSMSG_OVERRUN	0x01  /* Overrun occurred when sending */
92 #define USB_8DEV_STATUSMSG_BUSLIGHT	0x02  /* Error counter has reached 96 */
93 #define USB_8DEV_STATUSMSG_BUSHEAVY	0x03  /* Error count. has reached 128 */
94 #define USB_8DEV_STATUSMSG_BUSOFF	0x04  /* Device is in BUSOFF */
95 #define USB_8DEV_STATUSMSG_STUFF	0x20  /* Stuff Error */
96 #define USB_8DEV_STATUSMSG_FORM		0x21  /* Form Error */
97 #define USB_8DEV_STATUSMSG_ACK		0x23  /* Ack Error */
98 #define USB_8DEV_STATUSMSG_BIT0		0x24  /* Bit1 Error */
99 #define USB_8DEV_STATUSMSG_BIT1		0x25  /* Bit0 Error */
100 #define USB_8DEV_STATUSMSG_CRC		0x27  /* CRC Error */
101 
102 #define USB_8DEV_RP_MASK		0x7F  /* Mask for Receive Error Bit */
103 
104 
105 /* table of devices that work with this driver */
106 static const struct usb_device_id usb_8dev_table[] = {
107 	{ USB_DEVICE(USB_8DEV_VENDOR_ID, USB_8DEV_PRODUCT_ID) },
108 	{ }					/* Terminating entry */
109 };
110 
111 MODULE_DEVICE_TABLE(usb, usb_8dev_table);
112 
113 struct usb_8dev_tx_urb_context {
114 	struct usb_8dev_priv *priv;
115 
116 	u32 echo_index;
117 	u8 dlc;
118 };
119 
120 /* Structure to hold all of our device specific stuff */
121 struct usb_8dev_priv {
122 	struct can_priv can; /* must be the first member */
123 
124 	struct sk_buff *echo_skb[MAX_TX_URBS];
125 
126 	struct usb_device *udev;
127 	struct net_device *netdev;
128 
129 	atomic_t active_tx_urbs;
130 	struct usb_anchor tx_submitted;
131 	struct usb_8dev_tx_urb_context tx_contexts[MAX_TX_URBS];
132 
133 	struct usb_anchor rx_submitted;
134 
135 	struct can_berr_counter bec;
136 
137 	u8 *cmd_msg_buffer;
138 
139 	struct mutex usb_8dev_cmd_lock;
140 
141 };
142 
143 /* tx frame */
144 struct __packed usb_8dev_tx_msg {
145 	u8 begin;
146 	u8 flags;	/* RTR and EXT_ID flag */
147 	__be32 id;	/* upper 3 bits not used */
148 	u8 dlc;		/* data length code 0-8 bytes */
149 	u8 data[8];	/* 64-bit data */
150 	u8 end;
151 };
152 
153 /* rx frame */
154 struct __packed usb_8dev_rx_msg {
155 	u8 begin;
156 	u8 type;		/* frame type */
157 	u8 flags;		/* RTR and EXT_ID flag */
158 	__be32 id;		/* upper 3 bits not used */
159 	u8 dlc;			/* data length code 0-8 bytes */
160 	u8 data[8];		/* 64-bit data */
161 	__be32 timestamp;	/* 32-bit timestamp */
162 	u8 end;
163 };
164 
165 /* command frame */
166 struct __packed usb_8dev_cmd_msg {
167 	u8 begin;
168 	u8 channel;	/* unknown - always 0 */
169 	u8 command;	/* command to execute */
170 	u8 opt1;	/* optional parameter / return value */
171 	u8 opt2;	/* optional parameter 2 */
172 	u8 data[10];	/* optional parameter and data */
173 	u8 end;
174 };
175 
176 static int usb_8dev_send_cmd_msg(struct usb_8dev_priv *priv, u8 *msg, int size)
177 {
178 	int actual_length;
179 
180 	return usb_bulk_msg(priv->udev,
181 			    usb_sndbulkpipe(priv->udev, USB_8DEV_ENDP_CMD_TX),
182 			    msg, size, &actual_length, USB_8DEV_CMD_TIMEOUT);
183 }
184 
185 static int usb_8dev_wait_cmd_msg(struct usb_8dev_priv *priv, u8 *msg, int size,
186 				int *actual_length)
187 {
188 	return usb_bulk_msg(priv->udev,
189 			    usb_rcvbulkpipe(priv->udev, USB_8DEV_ENDP_CMD_RX),
190 			    msg, size, actual_length, USB_8DEV_CMD_TIMEOUT);
191 }
192 
193 /* Send command to device and receive result.
194  * Command was successful when opt1 = 0.
195  */
196 static int usb_8dev_send_cmd(struct usb_8dev_priv *priv,
197 			     struct usb_8dev_cmd_msg *out,
198 			     struct usb_8dev_cmd_msg *in)
199 {
200 	int err;
201 	int num_bytes_read;
202 	struct net_device *netdev;
203 
204 	netdev = priv->netdev;
205 
206 	out->begin = USB_8DEV_CMD_START;
207 	out->end = USB_8DEV_CMD_END;
208 
209 	mutex_lock(&priv->usb_8dev_cmd_lock);
210 
211 	memcpy(priv->cmd_msg_buffer, out,
212 		sizeof(struct usb_8dev_cmd_msg));
213 
214 	err = usb_8dev_send_cmd_msg(priv, priv->cmd_msg_buffer,
215 				    sizeof(struct usb_8dev_cmd_msg));
216 	if (err < 0) {
217 		netdev_err(netdev, "sending command message failed\n");
218 		goto failed;
219 	}
220 
221 	err = usb_8dev_wait_cmd_msg(priv, priv->cmd_msg_buffer,
222 				    sizeof(struct usb_8dev_cmd_msg),
223 				    &num_bytes_read);
224 	if (err < 0) {
225 		netdev_err(netdev, "no command message answer\n");
226 		goto failed;
227 	}
228 
229 	memcpy(in, priv->cmd_msg_buffer, sizeof(struct usb_8dev_cmd_msg));
230 
231 	if (in->begin != USB_8DEV_CMD_START || in->end != USB_8DEV_CMD_END ||
232 			num_bytes_read != 16 || in->opt1 != 0)
233 		err = -EPROTO;
234 
235 failed:
236 	mutex_unlock(&priv->usb_8dev_cmd_lock);
237 	return err;
238 }
239 
240 /* Send open command to device */
241 static int usb_8dev_cmd_open(struct usb_8dev_priv *priv)
242 {
243 	struct can_bittiming *bt = &priv->can.bittiming;
244 	struct usb_8dev_cmd_msg outmsg;
245 	struct usb_8dev_cmd_msg inmsg;
246 	u32 ctrlmode = priv->can.ctrlmode;
247 	u32 flags = USB_8DEV_STATUS_FRAME;
248 	__be32 beflags;
249 	__be16 bebrp;
250 
251 	memset(&outmsg, 0, sizeof(outmsg));
252 	outmsg.command = USB_8DEV_OPEN;
253 	outmsg.opt1 = USB_8DEV_BAUD_MANUAL;
254 	outmsg.data[0] = bt->prop_seg + bt->phase_seg1;
255 	outmsg.data[1] = bt->phase_seg2;
256 	outmsg.data[2] = bt->sjw;
257 
258 	/* BRP */
259 	bebrp = cpu_to_be16((u16)bt->brp);
260 	memcpy(&outmsg.data[3], &bebrp, sizeof(bebrp));
261 
262 	/* flags */
263 	if (ctrlmode & CAN_CTRLMODE_LOOPBACK)
264 		flags |= USB_8DEV_LOOPBACK;
265 	if (ctrlmode & CAN_CTRLMODE_LISTENONLY)
266 		flags |= USB_8DEV_SILENT;
267 	if (ctrlmode & CAN_CTRLMODE_ONE_SHOT)
268 		flags |= USB_8DEV_DISABLE_AUTO_RESTRANS;
269 
270 	beflags = cpu_to_be32(flags);
271 	memcpy(&outmsg.data[5], &beflags, sizeof(beflags));
272 
273 	return usb_8dev_send_cmd(priv, &outmsg, &inmsg);
274 }
275 
276 /* Send close command to device */
277 static int usb_8dev_cmd_close(struct usb_8dev_priv *priv)
278 {
279 	struct usb_8dev_cmd_msg inmsg;
280 	struct usb_8dev_cmd_msg outmsg = {
281 		.channel = 0,
282 		.command = USB_8DEV_CLOSE,
283 		.opt1 = 0,
284 		.opt2 = 0
285 	};
286 
287 	return usb_8dev_send_cmd(priv, &outmsg, &inmsg);
288 }
289 
290 /* Get firmware and hardware version */
291 static int usb_8dev_cmd_version(struct usb_8dev_priv *priv, u32 *res)
292 {
293 	struct usb_8dev_cmd_msg	inmsg;
294 	struct usb_8dev_cmd_msg	outmsg = {
295 		.channel = 0,
296 		.command = USB_8DEV_GET_SOFTW_HARDW_VER,
297 		.opt1 = 0,
298 		.opt2 = 0
299 	};
300 
301 	int err = usb_8dev_send_cmd(priv, &outmsg, &inmsg);
302 	if (err)
303 		return err;
304 
305 	*res = be32_to_cpup((__be32 *)inmsg.data);
306 
307 	return err;
308 }
309 
310 /* Set network device mode
311  *
312  * Maybe we should leave this function empty, because the device
313  * set mode variable with open command.
314  */
315 static int usb_8dev_set_mode(struct net_device *netdev, enum can_mode mode)
316 {
317 	struct usb_8dev_priv *priv = netdev_priv(netdev);
318 	int err = 0;
319 
320 	switch (mode) {
321 	case CAN_MODE_START:
322 		err = usb_8dev_cmd_open(priv);
323 		if (err)
324 			netdev_warn(netdev, "couldn't start device");
325 		break;
326 
327 	default:
328 		return -EOPNOTSUPP;
329 	}
330 
331 	return err;
332 }
333 
334 /* Read error/status frames */
335 static void usb_8dev_rx_err_msg(struct usb_8dev_priv *priv,
336 				struct usb_8dev_rx_msg *msg)
337 {
338 	struct can_frame *cf;
339 	struct sk_buff *skb;
340 	struct net_device_stats *stats = &priv->netdev->stats;
341 
342 	/* Error message:
343 	 * byte 0: Status
344 	 * byte 1: bit   7: Receive Passive
345 	 * byte 1: bit 0-6: Receive Error Counter
346 	 * byte 2: Transmit Error Counter
347 	 * byte 3: Always 0 (maybe reserved for future use)
348 	 */
349 
350 	u8 state = msg->data[0];
351 	u8 rxerr = msg->data[1] & USB_8DEV_RP_MASK;
352 	u8 txerr = msg->data[2];
353 	int rx_errors = 0;
354 	int tx_errors = 0;
355 
356 	skb = alloc_can_err_skb(priv->netdev, &cf);
357 	if (!skb)
358 		return;
359 
360 	switch (state) {
361 	case USB_8DEV_STATUSMSG_OK:
362 		priv->can.state = CAN_STATE_ERROR_ACTIVE;
363 		cf->can_id |= CAN_ERR_PROT;
364 		cf->data[2] = CAN_ERR_PROT_ACTIVE;
365 		break;
366 	case USB_8DEV_STATUSMSG_BUSOFF:
367 		priv->can.state = CAN_STATE_BUS_OFF;
368 		cf->can_id |= CAN_ERR_BUSOFF;
369 		priv->can.can_stats.bus_off++;
370 		can_bus_off(priv->netdev);
371 		break;
372 	case USB_8DEV_STATUSMSG_OVERRUN:
373 	case USB_8DEV_STATUSMSG_BUSLIGHT:
374 	case USB_8DEV_STATUSMSG_BUSHEAVY:
375 		cf->can_id |= CAN_ERR_CRTL;
376 		break;
377 	default:
378 		priv->can.state = CAN_STATE_ERROR_WARNING;
379 		cf->can_id |= CAN_ERR_PROT | CAN_ERR_BUSERROR;
380 		priv->can.can_stats.bus_error++;
381 		break;
382 	}
383 
384 	switch (state) {
385 	case USB_8DEV_STATUSMSG_OK:
386 	case USB_8DEV_STATUSMSG_BUSOFF:
387 		break;
388 	case USB_8DEV_STATUSMSG_ACK:
389 		cf->can_id |= CAN_ERR_ACK;
390 		tx_errors = 1;
391 		break;
392 	case USB_8DEV_STATUSMSG_CRC:
393 		cf->data[3] = CAN_ERR_PROT_LOC_CRC_SEQ;
394 		rx_errors = 1;
395 		break;
396 	case USB_8DEV_STATUSMSG_BIT0:
397 		cf->data[2] |= CAN_ERR_PROT_BIT0;
398 		tx_errors = 1;
399 		break;
400 	case USB_8DEV_STATUSMSG_BIT1:
401 		cf->data[2] |= CAN_ERR_PROT_BIT1;
402 		tx_errors = 1;
403 		break;
404 	case USB_8DEV_STATUSMSG_FORM:
405 		cf->data[2] |= CAN_ERR_PROT_FORM;
406 		rx_errors = 1;
407 		break;
408 	case USB_8DEV_STATUSMSG_STUFF:
409 		cf->data[2] |= CAN_ERR_PROT_STUFF;
410 		rx_errors = 1;
411 		break;
412 	case USB_8DEV_STATUSMSG_OVERRUN:
413 		cf->data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
414 		stats->rx_over_errors++;
415 		rx_errors = 1;
416 		break;
417 	case USB_8DEV_STATUSMSG_BUSLIGHT:
418 		priv->can.state = CAN_STATE_ERROR_WARNING;
419 		cf->data[1] = (txerr > rxerr) ?
420 			CAN_ERR_CRTL_TX_WARNING :
421 			CAN_ERR_CRTL_RX_WARNING;
422 		priv->can.can_stats.error_warning++;
423 		break;
424 	case USB_8DEV_STATUSMSG_BUSHEAVY:
425 		priv->can.state = CAN_STATE_ERROR_PASSIVE;
426 		cf->data[1] = (txerr > rxerr) ?
427 			CAN_ERR_CRTL_TX_PASSIVE :
428 			CAN_ERR_CRTL_RX_PASSIVE;
429 		priv->can.can_stats.error_passive++;
430 		break;
431 	default:
432 		netdev_warn(priv->netdev,
433 			    "Unknown status/error message (%d)\n", state);
434 		break;
435 	}
436 
437 	if (tx_errors) {
438 		cf->data[2] |= CAN_ERR_PROT_TX;
439 		stats->tx_errors++;
440 	}
441 
442 	if (rx_errors)
443 		stats->rx_errors++;
444 
445 	cf->data[6] = txerr;
446 	cf->data[7] = rxerr;
447 
448 	priv->bec.txerr = txerr;
449 	priv->bec.rxerr = rxerr;
450 
451 	stats->rx_packets++;
452 	stats->rx_bytes += cf->len;
453 	netif_rx(skb);
454 }
455 
456 /* Read data and status frames */
457 static void usb_8dev_rx_can_msg(struct usb_8dev_priv *priv,
458 				struct usb_8dev_rx_msg *msg)
459 {
460 	struct can_frame *cf;
461 	struct sk_buff *skb;
462 	struct net_device_stats *stats = &priv->netdev->stats;
463 
464 	if (msg->type == USB_8DEV_TYPE_ERROR_FRAME &&
465 		   msg->flags == USB_8DEV_ERR_FLAG) {
466 		usb_8dev_rx_err_msg(priv, msg);
467 	} else if (msg->type == USB_8DEV_TYPE_CAN_FRAME) {
468 		skb = alloc_can_skb(priv->netdev, &cf);
469 		if (!skb)
470 			return;
471 
472 		cf->can_id = be32_to_cpu(msg->id);
473 		can_frame_set_cc_len(cf, msg->dlc & 0xF, priv->can.ctrlmode);
474 
475 		if (msg->flags & USB_8DEV_EXTID)
476 			cf->can_id |= CAN_EFF_FLAG;
477 
478 		if (msg->flags & USB_8DEV_RTR)
479 			cf->can_id |= CAN_RTR_FLAG;
480 		else
481 			memcpy(cf->data, msg->data, cf->len);
482 
483 		stats->rx_packets++;
484 		stats->rx_bytes += cf->len;
485 		netif_rx(skb);
486 
487 		can_led_event(priv->netdev, CAN_LED_EVENT_RX);
488 	} else {
489 		netdev_warn(priv->netdev, "frame type %d unknown",
490 			 msg->type);
491 	}
492 
493 }
494 
495 /* Callback for reading data from device
496  *
497  * Check urb status, call read function and resubmit urb read operation.
498  */
499 static void usb_8dev_read_bulk_callback(struct urb *urb)
500 {
501 	struct usb_8dev_priv *priv = urb->context;
502 	struct net_device *netdev;
503 	int retval;
504 	int pos = 0;
505 
506 	netdev = priv->netdev;
507 
508 	if (!netif_device_present(netdev))
509 		return;
510 
511 	switch (urb->status) {
512 	case 0: /* success */
513 		break;
514 
515 	case -ENOENT:
516 	case -EPIPE:
517 	case -EPROTO:
518 	case -ESHUTDOWN:
519 		return;
520 
521 	default:
522 		netdev_info(netdev, "Rx URB aborted (%d)\n",
523 			 urb->status);
524 		goto resubmit_urb;
525 	}
526 
527 	while (pos < urb->actual_length) {
528 		struct usb_8dev_rx_msg *msg;
529 
530 		if (pos + sizeof(struct usb_8dev_rx_msg) > urb->actual_length) {
531 			netdev_err(priv->netdev, "format error\n");
532 			break;
533 		}
534 
535 		msg = (struct usb_8dev_rx_msg *)(urb->transfer_buffer + pos);
536 		usb_8dev_rx_can_msg(priv, msg);
537 
538 		pos += sizeof(struct usb_8dev_rx_msg);
539 	}
540 
541 resubmit_urb:
542 	usb_fill_bulk_urb(urb, priv->udev,
543 			  usb_rcvbulkpipe(priv->udev, USB_8DEV_ENDP_DATA_RX),
544 			  urb->transfer_buffer, RX_BUFFER_SIZE,
545 			  usb_8dev_read_bulk_callback, priv);
546 
547 	retval = usb_submit_urb(urb, GFP_ATOMIC);
548 
549 	if (retval == -ENODEV)
550 		netif_device_detach(netdev);
551 	else if (retval)
552 		netdev_err(netdev,
553 			"failed resubmitting read bulk urb: %d\n", retval);
554 }
555 
556 /* Callback handler for write operations
557  *
558  * Free allocated buffers, check transmit status and
559  * calculate statistic.
560  */
561 static void usb_8dev_write_bulk_callback(struct urb *urb)
562 {
563 	struct usb_8dev_tx_urb_context *context = urb->context;
564 	struct usb_8dev_priv *priv;
565 	struct net_device *netdev;
566 
567 	BUG_ON(!context);
568 
569 	priv = context->priv;
570 	netdev = priv->netdev;
571 
572 	/* free up our allocated buffer */
573 	usb_free_coherent(urb->dev, urb->transfer_buffer_length,
574 			  urb->transfer_buffer, urb->transfer_dma);
575 
576 	atomic_dec(&priv->active_tx_urbs);
577 
578 	if (!netif_device_present(netdev))
579 		return;
580 
581 	if (urb->status)
582 		netdev_info(netdev, "Tx URB aborted (%d)\n",
583 			 urb->status);
584 
585 	netdev->stats.tx_packets++;
586 	netdev->stats.tx_bytes += context->dlc;
587 
588 	can_get_echo_skb(netdev, context->echo_index, NULL);
589 
590 	can_led_event(netdev, CAN_LED_EVENT_TX);
591 
592 	/* Release context */
593 	context->echo_index = MAX_TX_URBS;
594 
595 	netif_wake_queue(netdev);
596 }
597 
598 /* Send data to device */
599 static netdev_tx_t usb_8dev_start_xmit(struct sk_buff *skb,
600 				      struct net_device *netdev)
601 {
602 	struct usb_8dev_priv *priv = netdev_priv(netdev);
603 	struct net_device_stats *stats = &netdev->stats;
604 	struct can_frame *cf = (struct can_frame *) skb->data;
605 	struct usb_8dev_tx_msg *msg;
606 	struct urb *urb;
607 	struct usb_8dev_tx_urb_context *context = NULL;
608 	u8 *buf;
609 	int i, err;
610 	size_t size = sizeof(struct usb_8dev_tx_msg);
611 
612 	if (can_dropped_invalid_skb(netdev, skb))
613 		return NETDEV_TX_OK;
614 
615 	/* create a URB, and a buffer for it, and copy the data to the URB */
616 	urb = usb_alloc_urb(0, GFP_ATOMIC);
617 	if (!urb)
618 		goto nomem;
619 
620 	buf = usb_alloc_coherent(priv->udev, size, GFP_ATOMIC,
621 				 &urb->transfer_dma);
622 	if (!buf) {
623 		netdev_err(netdev, "No memory left for USB buffer\n");
624 		goto nomembuf;
625 	}
626 
627 	memset(buf, 0, size);
628 
629 	msg = (struct usb_8dev_tx_msg *)buf;
630 	msg->begin = USB_8DEV_DATA_START;
631 	msg->flags = 0x00;
632 
633 	if (cf->can_id & CAN_RTR_FLAG)
634 		msg->flags |= USB_8DEV_RTR;
635 
636 	if (cf->can_id & CAN_EFF_FLAG)
637 		msg->flags |= USB_8DEV_EXTID;
638 
639 	msg->id = cpu_to_be32(cf->can_id & CAN_ERR_MASK);
640 	msg->dlc = can_get_cc_dlc(cf, priv->can.ctrlmode);
641 	memcpy(msg->data, cf->data, cf->len);
642 	msg->end = USB_8DEV_DATA_END;
643 
644 	for (i = 0; i < MAX_TX_URBS; i++) {
645 		if (priv->tx_contexts[i].echo_index == MAX_TX_URBS) {
646 			context = &priv->tx_contexts[i];
647 			break;
648 		}
649 	}
650 
651 	/* May never happen! When this happens we'd more URBs in flight as
652 	 * allowed (MAX_TX_URBS).
653 	 */
654 	if (!context)
655 		goto nofreecontext;
656 
657 	context->priv = priv;
658 	context->echo_index = i;
659 	context->dlc = cf->len;
660 
661 	usb_fill_bulk_urb(urb, priv->udev,
662 			  usb_sndbulkpipe(priv->udev, USB_8DEV_ENDP_DATA_TX),
663 			  buf, size, usb_8dev_write_bulk_callback, context);
664 	urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
665 	usb_anchor_urb(urb, &priv->tx_submitted);
666 
667 	can_put_echo_skb(skb, netdev, context->echo_index, 0);
668 
669 	atomic_inc(&priv->active_tx_urbs);
670 
671 	err = usb_submit_urb(urb, GFP_ATOMIC);
672 	if (unlikely(err))
673 		goto failed;
674 	else if (atomic_read(&priv->active_tx_urbs) >= MAX_TX_URBS)
675 		/* Slow down tx path */
676 		netif_stop_queue(netdev);
677 
678 	/* Release our reference to this URB, the USB core will eventually free
679 	 * it entirely.
680 	 */
681 	usb_free_urb(urb);
682 
683 	return NETDEV_TX_OK;
684 
685 nofreecontext:
686 	usb_free_coherent(priv->udev, size, buf, urb->transfer_dma);
687 	usb_free_urb(urb);
688 
689 	netdev_warn(netdev, "couldn't find free context");
690 
691 	return NETDEV_TX_BUSY;
692 
693 failed:
694 	can_free_echo_skb(netdev, context->echo_index);
695 
696 	usb_unanchor_urb(urb);
697 	usb_free_coherent(priv->udev, size, buf, urb->transfer_dma);
698 
699 	atomic_dec(&priv->active_tx_urbs);
700 
701 	if (err == -ENODEV)
702 		netif_device_detach(netdev);
703 	else
704 		netdev_warn(netdev, "failed tx_urb %d\n", err);
705 
706 nomembuf:
707 	usb_free_urb(urb);
708 
709 nomem:
710 	dev_kfree_skb(skb);
711 	stats->tx_dropped++;
712 
713 	return NETDEV_TX_OK;
714 }
715 
716 static int usb_8dev_get_berr_counter(const struct net_device *netdev,
717 				     struct can_berr_counter *bec)
718 {
719 	struct usb_8dev_priv *priv = netdev_priv(netdev);
720 
721 	bec->txerr = priv->bec.txerr;
722 	bec->rxerr = priv->bec.rxerr;
723 
724 	return 0;
725 }
726 
727 /* Start USB device */
728 static int usb_8dev_start(struct usb_8dev_priv *priv)
729 {
730 	struct net_device *netdev = priv->netdev;
731 	int err, i;
732 
733 	for (i = 0; i < MAX_RX_URBS; i++) {
734 		struct urb *urb = NULL;
735 		u8 *buf;
736 
737 		/* create a URB, and a buffer for it */
738 		urb = usb_alloc_urb(0, GFP_KERNEL);
739 		if (!urb) {
740 			err = -ENOMEM;
741 			break;
742 		}
743 
744 		buf = usb_alloc_coherent(priv->udev, RX_BUFFER_SIZE, GFP_KERNEL,
745 					 &urb->transfer_dma);
746 		if (!buf) {
747 			netdev_err(netdev, "No memory left for USB buffer\n");
748 			usb_free_urb(urb);
749 			err = -ENOMEM;
750 			break;
751 		}
752 
753 		usb_fill_bulk_urb(urb, priv->udev,
754 				  usb_rcvbulkpipe(priv->udev,
755 						  USB_8DEV_ENDP_DATA_RX),
756 				  buf, RX_BUFFER_SIZE,
757 				  usb_8dev_read_bulk_callback, priv);
758 		urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
759 		usb_anchor_urb(urb, &priv->rx_submitted);
760 
761 		err = usb_submit_urb(urb, GFP_KERNEL);
762 		if (err) {
763 			usb_unanchor_urb(urb);
764 			usb_free_coherent(priv->udev, RX_BUFFER_SIZE, buf,
765 					  urb->transfer_dma);
766 			usb_free_urb(urb);
767 			break;
768 		}
769 
770 		/* Drop reference, USB core will take care of freeing it */
771 		usb_free_urb(urb);
772 	}
773 
774 	/* Did we submit any URBs */
775 	if (i == 0) {
776 		netdev_warn(netdev, "couldn't setup read URBs\n");
777 		return err;
778 	}
779 
780 	/* Warn if we've couldn't transmit all the URBs */
781 	if (i < MAX_RX_URBS)
782 		netdev_warn(netdev, "rx performance may be slow\n");
783 
784 	err = usb_8dev_cmd_open(priv);
785 	if (err)
786 		goto failed;
787 
788 	priv->can.state = CAN_STATE_ERROR_ACTIVE;
789 
790 	return 0;
791 
792 failed:
793 	if (err == -ENODEV)
794 		netif_device_detach(priv->netdev);
795 
796 	netdev_warn(netdev, "couldn't submit control: %d\n", err);
797 
798 	return err;
799 }
800 
801 /* Open USB device */
802 static int usb_8dev_open(struct net_device *netdev)
803 {
804 	struct usb_8dev_priv *priv = netdev_priv(netdev);
805 	int err;
806 
807 	/* common open */
808 	err = open_candev(netdev);
809 	if (err)
810 		return err;
811 
812 	can_led_event(netdev, CAN_LED_EVENT_OPEN);
813 
814 	/* finally start device */
815 	err = usb_8dev_start(priv);
816 	if (err) {
817 		if (err == -ENODEV)
818 			netif_device_detach(priv->netdev);
819 
820 		netdev_warn(netdev, "couldn't start device: %d\n",
821 			 err);
822 
823 		close_candev(netdev);
824 
825 		return err;
826 	}
827 
828 	netif_start_queue(netdev);
829 
830 	return 0;
831 }
832 
833 static void unlink_all_urbs(struct usb_8dev_priv *priv)
834 {
835 	int i;
836 
837 	usb_kill_anchored_urbs(&priv->rx_submitted);
838 
839 	usb_kill_anchored_urbs(&priv->tx_submitted);
840 	atomic_set(&priv->active_tx_urbs, 0);
841 
842 	for (i = 0; i < MAX_TX_URBS; i++)
843 		priv->tx_contexts[i].echo_index = MAX_TX_URBS;
844 }
845 
846 /* Close USB device */
847 static int usb_8dev_close(struct net_device *netdev)
848 {
849 	struct usb_8dev_priv *priv = netdev_priv(netdev);
850 	int err = 0;
851 
852 	/* Send CLOSE command to CAN controller */
853 	err = usb_8dev_cmd_close(priv);
854 	if (err)
855 		netdev_warn(netdev, "couldn't stop device");
856 
857 	priv->can.state = CAN_STATE_STOPPED;
858 
859 	netif_stop_queue(netdev);
860 
861 	/* Stop polling */
862 	unlink_all_urbs(priv);
863 
864 	close_candev(netdev);
865 
866 	can_led_event(netdev, CAN_LED_EVENT_STOP);
867 
868 	return err;
869 }
870 
871 static const struct net_device_ops usb_8dev_netdev_ops = {
872 	.ndo_open = usb_8dev_open,
873 	.ndo_stop = usb_8dev_close,
874 	.ndo_start_xmit = usb_8dev_start_xmit,
875 	.ndo_change_mtu = can_change_mtu,
876 };
877 
878 static const struct can_bittiming_const usb_8dev_bittiming_const = {
879 	.name = "usb_8dev",
880 	.tseg1_min = 1,
881 	.tseg1_max = 16,
882 	.tseg2_min = 1,
883 	.tseg2_max = 8,
884 	.sjw_max = 4,
885 	.brp_min = 1,
886 	.brp_max = 1024,
887 	.brp_inc = 1,
888 };
889 
890 /* Probe USB device
891  *
892  * Check device and firmware.
893  * Set supported modes and bittiming constants.
894  * Allocate some memory.
895  */
896 static int usb_8dev_probe(struct usb_interface *intf,
897 			 const struct usb_device_id *id)
898 {
899 	struct net_device *netdev;
900 	struct usb_8dev_priv *priv;
901 	int i, err = -ENOMEM;
902 	u32 version;
903 	char buf[18];
904 	struct usb_device *usbdev = interface_to_usbdev(intf);
905 
906 	/* product id looks strange, better we also check iProduct string */
907 	if (usb_string(usbdev, usbdev->descriptor.iProduct, buf,
908 		       sizeof(buf)) > 0 && strcmp(buf, "USB2CAN converter")) {
909 		dev_info(&usbdev->dev, "ignoring: not an USB2CAN converter\n");
910 		return -ENODEV;
911 	}
912 
913 	netdev = alloc_candev(sizeof(struct usb_8dev_priv), MAX_TX_URBS);
914 	if (!netdev) {
915 		dev_err(&intf->dev, "Couldn't alloc candev\n");
916 		return -ENOMEM;
917 	}
918 
919 	priv = netdev_priv(netdev);
920 
921 	priv->udev = usbdev;
922 	priv->netdev = netdev;
923 
924 	priv->can.state = CAN_STATE_STOPPED;
925 	priv->can.clock.freq = USB_8DEV_ABP_CLOCK;
926 	priv->can.bittiming_const = &usb_8dev_bittiming_const;
927 	priv->can.do_set_mode = usb_8dev_set_mode;
928 	priv->can.do_get_berr_counter = usb_8dev_get_berr_counter;
929 	priv->can.ctrlmode_supported = CAN_CTRLMODE_LOOPBACK |
930 				      CAN_CTRLMODE_LISTENONLY |
931 				      CAN_CTRLMODE_ONE_SHOT |
932 				      CAN_CTRLMODE_CC_LEN8_DLC;
933 
934 	netdev->netdev_ops = &usb_8dev_netdev_ops;
935 
936 	netdev->flags |= IFF_ECHO; /* we support local echo */
937 
938 	init_usb_anchor(&priv->rx_submitted);
939 
940 	init_usb_anchor(&priv->tx_submitted);
941 	atomic_set(&priv->active_tx_urbs, 0);
942 
943 	for (i = 0; i < MAX_TX_URBS; i++)
944 		priv->tx_contexts[i].echo_index = MAX_TX_URBS;
945 
946 	priv->cmd_msg_buffer = devm_kzalloc(&intf->dev, sizeof(struct usb_8dev_cmd_msg),
947 					    GFP_KERNEL);
948 	if (!priv->cmd_msg_buffer)
949 		goto cleanup_candev;
950 
951 	usb_set_intfdata(intf, priv);
952 
953 	SET_NETDEV_DEV(netdev, &intf->dev);
954 
955 	mutex_init(&priv->usb_8dev_cmd_lock);
956 
957 	err = register_candev(netdev);
958 	if (err) {
959 		netdev_err(netdev,
960 			"couldn't register CAN device: %d\n", err);
961 		goto cleanup_candev;
962 	}
963 
964 	err = usb_8dev_cmd_version(priv, &version);
965 	if (err) {
966 		netdev_err(netdev, "can't get firmware version\n");
967 		goto cleanup_unregister_candev;
968 	} else {
969 		netdev_info(netdev,
970 			 "firmware: %d.%d, hardware: %d.%d\n",
971 			 (version>>24) & 0xff, (version>>16) & 0xff,
972 			 (version>>8) & 0xff, version & 0xff);
973 	}
974 
975 	devm_can_led_init(netdev);
976 
977 	return 0;
978 
979 cleanup_unregister_candev:
980 	unregister_netdev(priv->netdev);
981 
982 cleanup_candev:
983 	free_candev(netdev);
984 
985 	return err;
986 
987 }
988 
989 /* Called by the usb core when driver is unloaded or device is removed */
990 static void usb_8dev_disconnect(struct usb_interface *intf)
991 {
992 	struct usb_8dev_priv *priv = usb_get_intfdata(intf);
993 
994 	usb_set_intfdata(intf, NULL);
995 
996 	if (priv) {
997 		netdev_info(priv->netdev, "device disconnected\n");
998 
999 		unregister_netdev(priv->netdev);
1000 		unlink_all_urbs(priv);
1001 		free_candev(priv->netdev);
1002 	}
1003 
1004 }
1005 
1006 static struct usb_driver usb_8dev_driver = {
1007 	.name =		"usb_8dev",
1008 	.probe =	usb_8dev_probe,
1009 	.disconnect =	usb_8dev_disconnect,
1010 	.id_table =	usb_8dev_table,
1011 };
1012 
1013 module_usb_driver(usb_8dev_driver);
1014 
1015 MODULE_AUTHOR("Bernd Krumboeck <krumboeck@universalnet.at>");
1016 MODULE_DESCRIPTION("CAN driver for 8 devices USB2CAN interfaces");
1017 MODULE_LICENSE("GPL v2");
1018