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