xref: /openbmc/linux/drivers/net/can/usb/esd_usb.c (revision 4cfb9080)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * CAN driver for esd electronics gmbh CAN-USB/2 and CAN-USB/Micro
4  *
5  * Copyright (C) 2010-2012 esd electronic system design gmbh, Matthias Fuchs <socketcan@esd.eu>
6  * Copyright (C) 2022-2023 esd electronics gmbh, Frank Jungclaus <frank.jungclaus@esd.eu>
7  */
8 
9 #include <linux/can.h>
10 #include <linux/can/dev.h>
11 #include <linux/can/error.h>
12 #include <linux/ethtool.h>
13 #include <linux/module.h>
14 #include <linux/netdevice.h>
15 #include <linux/signal.h>
16 #include <linux/slab.h>
17 #include <linux/units.h>
18 #include <linux/usb.h>
19 
20 MODULE_AUTHOR("Matthias Fuchs <socketcan@esd.eu>");
21 MODULE_AUTHOR("Frank Jungclaus <frank.jungclaus@esd.eu>");
22 MODULE_DESCRIPTION("CAN driver for esd electronics gmbh CAN-USB/2 and CAN-USB/Micro interfaces");
23 MODULE_LICENSE("GPL v2");
24 
25 /* USB vendor and product ID */
26 #define ESD_USB_ESDGMBH_VENDOR_ID	0x0ab4
27 #define ESD_USB_CANUSB2_PRODUCT_ID	0x0010
28 #define ESD_USB_CANUSBM_PRODUCT_ID	0x0011
29 
30 /* CAN controller clock frequencies */
31 #define ESD_USB_2_CAN_CLOCK	(60 * MEGA) /* Hz */
32 #define ESD_USB_M_CAN_CLOCK	(36 * MEGA) /* Hz */
33 
34 /* Maximum number of CAN nets */
35 #define ESD_USB_MAX_NETS	2
36 
37 /* USB commands */
38 #define ESD_USB_CMD_VERSION		1 /* also used for VERSION_REPLY */
39 #define ESD_USB_CMD_CAN_RX		2 /* device to host only */
40 #define ESD_USB_CMD_CAN_TX		3 /* also used for TX_DONE */
41 #define ESD_USB_CMD_SETBAUD		4 /* also used for SETBAUD_REPLY */
42 #define ESD_USB_CMD_TS			5 /* also used for TS_REPLY */
43 #define ESD_USB_CMD_IDADD		6 /* also used for IDADD_REPLY */
44 
45 /* esd CAN message flags - dlc field */
46 #define ESD_USB_RTR	BIT(4)
47 
48 /* esd CAN message flags - id field */
49 #define ESD_USB_EXTID	BIT(29)
50 #define ESD_USB_EVENT	BIT(30)
51 #define ESD_USB_IDMASK	GENMASK(28, 0)
52 
53 /* esd CAN event ids */
54 #define ESD_USB_EV_CAN_ERROR_EXT	2 /* CAN controller specific diagnostic data */
55 
56 /* baudrate message flags */
57 #define ESD_USB_LOM	BIT(30) /* Listen Only Mode */
58 #define ESD_USB_UBR	BIT(31) /* User Bit Rate (controller BTR) in bits 0..27 */
59 #define ESD_USB_NO_BAUDRATE	GENMASK(30, 0) /* bit rate unconfigured */
60 
61 /* bit timing esd CAN-USB */
62 #define ESD_USB_2_TSEG1_SHIFT	16
63 #define ESD_USB_2_TSEG2_SHIFT	20
64 #define ESD_USB_2_SJW_SHIFT	14
65 #define ESD_USB_M_SJW_SHIFT	24
66 #define ESD_USB_TRIPLE_SAMPLES	BIT(23)
67 
68 /* esd IDADD message */
69 #define ESD_USB_ID_ENABLE	BIT(7)
70 #define ESD_USB_MAX_ID_SEGMENT	64
71 
72 /* SJA1000 ECC register (emulated by usb firmware) */
73 #define ESD_USB_SJA1000_ECC_SEG		GENMASK(4, 0)
74 #define ESD_USB_SJA1000_ECC_DIR		BIT(5)
75 #define ESD_USB_SJA1000_ECC_ERR		BIT(2, 1)
76 #define ESD_USB_SJA1000_ECC_BIT		0x00
77 #define ESD_USB_SJA1000_ECC_FORM	BIT(6)
78 #define ESD_USB_SJA1000_ECC_STUFF	BIT(7)
79 #define ESD_USB_SJA1000_ECC_MASK	GENMASK(7, 6)
80 
81 /* esd bus state event codes */
82 #define ESD_USB_BUSSTATE_MASK	GENMASK(7, 6)
83 #define ESD_USB_BUSSTATE_WARN	BIT(6)
84 #define ESD_USB_BUSSTATE_ERRPASSIVE	BIT(7)
85 #define ESD_USB_BUSSTATE_BUSOFF	GENMASK(7, 6)
86 
87 #define ESD_USB_RX_BUFFER_SIZE		1024
88 #define ESD_USB_MAX_RX_URBS		4
89 #define ESD_USB_MAX_TX_URBS		16 /* must be power of 2 */
90 
91 struct esd_usb_header_msg {
92 	u8 len; /* total message length in 32bit words */
93 	u8 cmd;
94 	u8 rsvd[2];
95 };
96 
97 struct esd_usb_version_msg {
98 	u8 len; /* total message length in 32bit words */
99 	u8 cmd;
100 	u8 rsvd;
101 	u8 flags;
102 	__le32 drv_version;
103 };
104 
105 struct esd_usb_version_reply_msg {
106 	u8 len; /* total message length in 32bit words */
107 	u8 cmd;
108 	u8 nets;
109 	u8 features;
110 	__le32 version;
111 	u8 name[16];
112 	__le32 rsvd;
113 	__le32 ts;
114 };
115 
116 struct esd_usb_rx_msg {
117 	u8 len; /* total message length in 32bit words */
118 	u8 cmd;
119 	u8 net;
120 	u8 dlc;
121 	__le32 ts;
122 	__le32 id; /* upper 3 bits contain flags */
123 	union {
124 		u8 data[CAN_MAX_DLEN];
125 		struct {
126 			u8 status; /* CAN Controller Status */
127 			u8 ecc;    /* Error Capture Register */
128 			u8 rec;    /* RX Error Counter */
129 			u8 tec;    /* TX Error Counter */
130 		} ev_can_err_ext;  /* For ESD_EV_CAN_ERROR_EXT */
131 	};
132 };
133 
134 struct esd_usb_tx_msg {
135 	u8 len; /* total message length in 32bit words */
136 	u8 cmd;
137 	u8 net;
138 	u8 dlc;
139 	u32 hnd;	/* opaque handle, not used by device */
140 	__le32 id; /* upper 3 bits contain flags */
141 	u8 data[CAN_MAX_DLEN];
142 };
143 
144 struct esd_usb_tx_done_msg {
145 	u8 len; /* total message length in 32bit words */
146 	u8 cmd;
147 	u8 net;
148 	u8 status;
149 	u32 hnd;	/* opaque handle, not used by device */
150 	__le32 ts;
151 };
152 
153 struct esd_usb_id_filter_msg {
154 	u8 len; /* total message length in 32bit words */
155 	u8 cmd;
156 	u8 net;
157 	u8 option;
158 	__le32 mask[ESD_USB_MAX_ID_SEGMENT + 1]; /* +1 for 29bit extended IDs */
159 };
160 
161 struct esd_usb_set_baudrate_msg {
162 	u8 len; /* total message length in 32bit words */
163 	u8 cmd;
164 	u8 net;
165 	u8 rsvd;
166 	__le32 baud;
167 };
168 
169 /* Main message type used between library and application */
170 union __packed esd_usb_msg {
171 	struct esd_usb_header_msg hdr;
172 	struct esd_usb_version_msg version;
173 	struct esd_usb_version_reply_msg version_reply;
174 	struct esd_usb_rx_msg rx;
175 	struct esd_usb_tx_msg tx;
176 	struct esd_usb_tx_done_msg txdone;
177 	struct esd_usb_set_baudrate_msg setbaud;
178 	struct esd_usb_id_filter_msg filter;
179 };
180 
181 static struct usb_device_id esd_usb_table[] = {
182 	{USB_DEVICE(ESD_USB_ESDGMBH_VENDOR_ID, ESD_USB_CANUSB2_PRODUCT_ID)},
183 	{USB_DEVICE(ESD_USB_ESDGMBH_VENDOR_ID, ESD_USB_CANUSBM_PRODUCT_ID)},
184 	{}
185 };
186 MODULE_DEVICE_TABLE(usb, esd_usb_table);
187 
188 struct esd_usb_net_priv;
189 
190 struct esd_tx_urb_context {
191 	struct esd_usb_net_priv *priv;
192 	u32 echo_index;
193 };
194 
195 struct esd_usb {
196 	struct usb_device *udev;
197 	struct esd_usb_net_priv *nets[ESD_USB_MAX_NETS];
198 
199 	struct usb_anchor rx_submitted;
200 
201 	int net_count;
202 	u32 version;
203 	int rxinitdone;
204 	void *rxbuf[ESD_USB_MAX_RX_URBS];
205 	dma_addr_t rxbuf_dma[ESD_USB_MAX_RX_URBS];
206 };
207 
208 struct esd_usb_net_priv {
209 	struct can_priv can; /* must be the first member */
210 
211 	atomic_t active_tx_jobs;
212 	struct usb_anchor tx_submitted;
213 	struct esd_tx_urb_context tx_contexts[ESD_USB_MAX_TX_URBS];
214 
215 	struct esd_usb *usb;
216 	struct net_device *netdev;
217 	int index;
218 	u8 old_state;
219 	struct can_berr_counter bec;
220 };
221 
222 static void esd_usb_rx_event(struct esd_usb_net_priv *priv,
223 			     union esd_usb_msg *msg)
224 {
225 	struct net_device_stats *stats = &priv->netdev->stats;
226 	struct can_frame *cf;
227 	struct sk_buff *skb;
228 	u32 id = le32_to_cpu(msg->rx.id) & ESD_USB_IDMASK;
229 
230 	if (id == ESD_USB_EV_CAN_ERROR_EXT) {
231 		u8 state = msg->rx.ev_can_err_ext.status;
232 		u8 ecc = msg->rx.ev_can_err_ext.ecc;
233 
234 		priv->bec.rxerr = msg->rx.ev_can_err_ext.rec;
235 		priv->bec.txerr = msg->rx.ev_can_err_ext.tec;
236 
237 		netdev_dbg(priv->netdev,
238 			   "CAN_ERR_EV_EXT: dlc=%#02x state=%02x ecc=%02x rec=%02x tec=%02x\n",
239 			   msg->rx.dlc, state, ecc,
240 			   priv->bec.rxerr, priv->bec.txerr);
241 
242 		/* if berr-reporting is off, only pass through on state change ... */
243 		if (!(priv->can.ctrlmode & CAN_CTRLMODE_BERR_REPORTING) &&
244 		    state == priv->old_state)
245 			return;
246 
247 		skb = alloc_can_err_skb(priv->netdev, &cf);
248 		if (!skb)
249 			stats->rx_dropped++;
250 
251 		if (state != priv->old_state) {
252 			enum can_state tx_state, rx_state;
253 			enum can_state new_state = CAN_STATE_ERROR_ACTIVE;
254 
255 			priv->old_state = state;
256 
257 			switch (state & ESD_USB_BUSSTATE_MASK) {
258 			case ESD_USB_BUSSTATE_BUSOFF:
259 				new_state = CAN_STATE_BUS_OFF;
260 				can_bus_off(priv->netdev);
261 				break;
262 			case ESD_USB_BUSSTATE_WARN:
263 				new_state = CAN_STATE_ERROR_WARNING;
264 				break;
265 			case ESD_USB_BUSSTATE_ERRPASSIVE:
266 				new_state = CAN_STATE_ERROR_PASSIVE;
267 				break;
268 			default:
269 				new_state = CAN_STATE_ERROR_ACTIVE;
270 				priv->bec.txerr = 0;
271 				priv->bec.rxerr = 0;
272 				break;
273 			}
274 
275 			if (new_state != priv->can.state) {
276 				tx_state = (priv->bec.txerr >= priv->bec.rxerr) ? new_state : 0;
277 				rx_state = (priv->bec.txerr <= priv->bec.rxerr) ? new_state : 0;
278 				can_change_state(priv->netdev, cf,
279 						 tx_state, rx_state);
280 			}
281 		} else if (skb) {
282 			priv->can.can_stats.bus_error++;
283 			stats->rx_errors++;
284 
285 			cf->can_id |= CAN_ERR_PROT | CAN_ERR_BUSERROR;
286 
287 			switch (ecc & ESD_USB_SJA1000_ECC_MASK) {
288 			case ESD_USB_SJA1000_ECC_BIT:
289 				cf->data[2] |= CAN_ERR_PROT_BIT;
290 				break;
291 			case ESD_USB_SJA1000_ECC_FORM:
292 				cf->data[2] |= CAN_ERR_PROT_FORM;
293 				break;
294 			case ESD_USB_SJA1000_ECC_STUFF:
295 				cf->data[2] |= CAN_ERR_PROT_STUFF;
296 				break;
297 			default:
298 				break;
299 			}
300 
301 			/* Error occurred during transmission? */
302 			if (!(ecc & ESD_USB_SJA1000_ECC_DIR))
303 				cf->data[2] |= CAN_ERR_PROT_TX;
304 
305 			/* Bit stream position in CAN frame as the error was detected */
306 			cf->data[3] = ecc & ESD_USB_SJA1000_ECC_SEG;
307 		}
308 
309 		if (skb) {
310 			cf->can_id |= CAN_ERR_CNT;
311 			cf->data[6] = priv->bec.txerr;
312 			cf->data[7] = priv->bec.rxerr;
313 
314 			netif_rx(skb);
315 		}
316 	}
317 }
318 
319 static void esd_usb_rx_can_msg(struct esd_usb_net_priv *priv,
320 			       union esd_usb_msg *msg)
321 {
322 	struct net_device_stats *stats = &priv->netdev->stats;
323 	struct can_frame *cf;
324 	struct sk_buff *skb;
325 	int i;
326 	u32 id;
327 
328 	if (!netif_device_present(priv->netdev))
329 		return;
330 
331 	id = le32_to_cpu(msg->rx.id);
332 
333 	if (id & ESD_USB_EVENT) {
334 		esd_usb_rx_event(priv, msg);
335 	} else {
336 		skb = alloc_can_skb(priv->netdev, &cf);
337 		if (skb == NULL) {
338 			stats->rx_dropped++;
339 			return;
340 		}
341 
342 		cf->can_id = id & ESD_USB_IDMASK;
343 		can_frame_set_cc_len(cf, msg->rx.dlc & ~ESD_USB_RTR,
344 				     priv->can.ctrlmode);
345 
346 		if (id & ESD_USB_EXTID)
347 			cf->can_id |= CAN_EFF_FLAG;
348 
349 		if (msg->rx.dlc & ESD_USB_RTR) {
350 			cf->can_id |= CAN_RTR_FLAG;
351 		} else {
352 			for (i = 0; i < cf->len; i++)
353 				cf->data[i] = msg->rx.data[i];
354 
355 			stats->rx_bytes += cf->len;
356 		}
357 		stats->rx_packets++;
358 
359 		netif_rx(skb);
360 	}
361 }
362 
363 static void esd_usb_tx_done_msg(struct esd_usb_net_priv *priv,
364 				union esd_usb_msg *msg)
365 {
366 	struct net_device_stats *stats = &priv->netdev->stats;
367 	struct net_device *netdev = priv->netdev;
368 	struct esd_tx_urb_context *context;
369 
370 	if (!netif_device_present(netdev))
371 		return;
372 
373 	context = &priv->tx_contexts[msg->txdone.hnd & (ESD_USB_MAX_TX_URBS - 1)];
374 
375 	if (!msg->txdone.status) {
376 		stats->tx_packets++;
377 		stats->tx_bytes += can_get_echo_skb(netdev, context->echo_index,
378 						    NULL);
379 	} else {
380 		stats->tx_errors++;
381 		can_free_echo_skb(netdev, context->echo_index, NULL);
382 	}
383 
384 	/* Release context */
385 	context->echo_index = ESD_USB_MAX_TX_URBS;
386 	atomic_dec(&priv->active_tx_jobs);
387 
388 	netif_wake_queue(netdev);
389 }
390 
391 static void esd_usb_read_bulk_callback(struct urb *urb)
392 {
393 	struct esd_usb *dev = urb->context;
394 	int retval;
395 	int pos = 0;
396 	int i;
397 
398 	switch (urb->status) {
399 	case 0: /* success */
400 		break;
401 
402 	case -ENOENT:
403 	case -EPIPE:
404 	case -EPROTO:
405 	case -ESHUTDOWN:
406 		return;
407 
408 	default:
409 		dev_info(dev->udev->dev.parent,
410 			 "Rx URB aborted (%d)\n", urb->status);
411 		goto resubmit_urb;
412 	}
413 
414 	while (pos < urb->actual_length) {
415 		union esd_usb_msg *msg;
416 
417 		msg = (union esd_usb_msg *)(urb->transfer_buffer + pos);
418 
419 		switch (msg->hdr.cmd) {
420 		case ESD_USB_CMD_CAN_RX:
421 			if (msg->rx.net >= dev->net_count) {
422 				dev_err(dev->udev->dev.parent, "format error\n");
423 				break;
424 			}
425 
426 			esd_usb_rx_can_msg(dev->nets[msg->rx.net], msg);
427 			break;
428 
429 		case ESD_USB_CMD_CAN_TX:
430 			if (msg->txdone.net >= dev->net_count) {
431 				dev_err(dev->udev->dev.parent, "format error\n");
432 				break;
433 			}
434 
435 			esd_usb_tx_done_msg(dev->nets[msg->txdone.net],
436 					    msg);
437 			break;
438 		}
439 
440 		pos += msg->hdr.len * sizeof(u32); /* convert to # of bytes */
441 
442 		if (pos > urb->actual_length) {
443 			dev_err(dev->udev->dev.parent, "format error\n");
444 			break;
445 		}
446 	}
447 
448 resubmit_urb:
449 	usb_fill_bulk_urb(urb, dev->udev, usb_rcvbulkpipe(dev->udev, 1),
450 			  urb->transfer_buffer, ESD_USB_RX_BUFFER_SIZE,
451 			  esd_usb_read_bulk_callback, dev);
452 
453 	retval = usb_submit_urb(urb, GFP_ATOMIC);
454 	if (retval == -ENODEV) {
455 		for (i = 0; i < dev->net_count; i++) {
456 			if (dev->nets[i])
457 				netif_device_detach(dev->nets[i]->netdev);
458 		}
459 	} else if (retval) {
460 		dev_err(dev->udev->dev.parent,
461 			"failed resubmitting read bulk urb: %d\n", retval);
462 	}
463 }
464 
465 /* callback for bulk IN urb */
466 static void esd_usb_write_bulk_callback(struct urb *urb)
467 {
468 	struct esd_tx_urb_context *context = urb->context;
469 	struct esd_usb_net_priv *priv;
470 	struct net_device *netdev;
471 	size_t size = sizeof(union esd_usb_msg);
472 
473 	WARN_ON(!context);
474 
475 	priv = context->priv;
476 	netdev = priv->netdev;
477 
478 	/* free up our allocated buffer */
479 	usb_free_coherent(urb->dev, size,
480 			  urb->transfer_buffer, urb->transfer_dma);
481 
482 	if (!netif_device_present(netdev))
483 		return;
484 
485 	if (urb->status)
486 		netdev_info(netdev, "Tx URB aborted (%d)\n", urb->status);
487 
488 	netif_trans_update(netdev);
489 }
490 
491 static ssize_t firmware_show(struct device *d,
492 			     struct device_attribute *attr, char *buf)
493 {
494 	struct usb_interface *intf = to_usb_interface(d);
495 	struct esd_usb *dev = usb_get_intfdata(intf);
496 
497 	return sprintf(buf, "%d.%d.%d\n",
498 		       (dev->version >> 12) & 0xf,
499 		       (dev->version >> 8) & 0xf,
500 		       dev->version & 0xff);
501 }
502 static DEVICE_ATTR_RO(firmware);
503 
504 static ssize_t hardware_show(struct device *d,
505 			     struct device_attribute *attr, char *buf)
506 {
507 	struct usb_interface *intf = to_usb_interface(d);
508 	struct esd_usb *dev = usb_get_intfdata(intf);
509 
510 	return sprintf(buf, "%d.%d.%d\n",
511 		       (dev->version >> 28) & 0xf,
512 		       (dev->version >> 24) & 0xf,
513 		       (dev->version >> 16) & 0xff);
514 }
515 static DEVICE_ATTR_RO(hardware);
516 
517 static ssize_t nets_show(struct device *d,
518 			 struct device_attribute *attr, char *buf)
519 {
520 	struct usb_interface *intf = to_usb_interface(d);
521 	struct esd_usb *dev = usb_get_intfdata(intf);
522 
523 	return sprintf(buf, "%d", dev->net_count);
524 }
525 static DEVICE_ATTR_RO(nets);
526 
527 static int esd_usb_send_msg(struct esd_usb *dev, union esd_usb_msg *msg)
528 {
529 	int actual_length;
530 
531 	return usb_bulk_msg(dev->udev,
532 			    usb_sndbulkpipe(dev->udev, 2),
533 			    msg,
534 			    msg->hdr.len * sizeof(u32), /* convert to # of bytes */
535 			    &actual_length,
536 			    1000);
537 }
538 
539 static int esd_usb_wait_msg(struct esd_usb *dev,
540 			    union esd_usb_msg *msg)
541 {
542 	int actual_length;
543 
544 	return usb_bulk_msg(dev->udev,
545 			    usb_rcvbulkpipe(dev->udev, 1),
546 			    msg,
547 			    sizeof(*msg),
548 			    &actual_length,
549 			    1000);
550 }
551 
552 static int esd_usb_setup_rx_urbs(struct esd_usb *dev)
553 {
554 	int i, err = 0;
555 
556 	if (dev->rxinitdone)
557 		return 0;
558 
559 	for (i = 0; i < ESD_USB_MAX_RX_URBS; i++) {
560 		struct urb *urb = NULL;
561 		u8 *buf = NULL;
562 		dma_addr_t buf_dma;
563 
564 		/* create a URB, and a buffer for it */
565 		urb = usb_alloc_urb(0, GFP_KERNEL);
566 		if (!urb) {
567 			err = -ENOMEM;
568 			break;
569 		}
570 
571 		buf = usb_alloc_coherent(dev->udev, ESD_USB_RX_BUFFER_SIZE, GFP_KERNEL,
572 					 &buf_dma);
573 		if (!buf) {
574 			dev_warn(dev->udev->dev.parent,
575 				 "No memory left for USB buffer\n");
576 			err = -ENOMEM;
577 			goto freeurb;
578 		}
579 
580 		urb->transfer_dma = buf_dma;
581 
582 		usb_fill_bulk_urb(urb, dev->udev,
583 				  usb_rcvbulkpipe(dev->udev, 1),
584 				  buf, ESD_USB_RX_BUFFER_SIZE,
585 				  esd_usb_read_bulk_callback, dev);
586 		urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
587 		usb_anchor_urb(urb, &dev->rx_submitted);
588 
589 		err = usb_submit_urb(urb, GFP_KERNEL);
590 		if (err) {
591 			usb_unanchor_urb(urb);
592 			usb_free_coherent(dev->udev, ESD_USB_RX_BUFFER_SIZE, buf,
593 					  urb->transfer_dma);
594 			goto freeurb;
595 		}
596 
597 		dev->rxbuf[i] = buf;
598 		dev->rxbuf_dma[i] = buf_dma;
599 
600 freeurb:
601 		/* Drop reference, USB core will take care of freeing it */
602 		usb_free_urb(urb);
603 		if (err)
604 			break;
605 	}
606 
607 	/* Did we submit any URBs */
608 	if (i == 0) {
609 		dev_err(dev->udev->dev.parent, "couldn't setup read URBs\n");
610 		return err;
611 	}
612 
613 	/* Warn if we've couldn't transmit all the URBs */
614 	if (i < ESD_USB_MAX_RX_URBS) {
615 		dev_warn(dev->udev->dev.parent,
616 			 "rx performance may be slow\n");
617 	}
618 
619 	dev->rxinitdone = 1;
620 	return 0;
621 }
622 
623 /* Start interface */
624 static int esd_usb_start(struct esd_usb_net_priv *priv)
625 {
626 	struct esd_usb *dev = priv->usb;
627 	struct net_device *netdev = priv->netdev;
628 	union esd_usb_msg *msg;
629 	int err, i;
630 
631 	msg = kmalloc(sizeof(*msg), GFP_KERNEL);
632 	if (!msg) {
633 		err = -ENOMEM;
634 		goto out;
635 	}
636 
637 	/* Enable all IDs
638 	 * The IDADD message takes up to 64 32 bit bitmasks (2048 bits).
639 	 * Each bit represents one 11 bit CAN identifier. A set bit
640 	 * enables reception of the corresponding CAN identifier. A cleared
641 	 * bit disabled this identifier. An additional bitmask value
642 	 * following the CAN 2.0A bits is used to enable reception of
643 	 * extended CAN frames. Only the LSB of this final mask is checked
644 	 * for the complete 29 bit ID range. The IDADD message also allows
645 	 * filter configuration for an ID subset. In this case you can add
646 	 * the number of the starting bitmask (0..64) to the filter.option
647 	 * field followed by only some bitmasks.
648 	 */
649 	msg->hdr.cmd = ESD_USB_CMD_IDADD;
650 	msg->hdr.len = sizeof(struct esd_usb_id_filter_msg) / sizeof(u32); /* # of 32bit words */
651 	msg->filter.net = priv->index;
652 	msg->filter.option = ESD_USB_ID_ENABLE; /* start with segment 0 */
653 	for (i = 0; i < ESD_USB_MAX_ID_SEGMENT; i++)
654 		msg->filter.mask[i] = cpu_to_le32(GENMASK(31, 0));
655 	/* enable 29bit extended IDs */
656 	msg->filter.mask[ESD_USB_MAX_ID_SEGMENT] = cpu_to_le32(BIT(0));
657 
658 	err = esd_usb_send_msg(dev, msg);
659 	if (err)
660 		goto out;
661 
662 	err = esd_usb_setup_rx_urbs(dev);
663 	if (err)
664 		goto out;
665 
666 	priv->can.state = CAN_STATE_ERROR_ACTIVE;
667 
668 out:
669 	if (err == -ENODEV)
670 		netif_device_detach(netdev);
671 	if (err)
672 		netdev_err(netdev, "couldn't start device: %d\n", err);
673 
674 	kfree(msg);
675 	return err;
676 }
677 
678 static void unlink_all_urbs(struct esd_usb *dev)
679 {
680 	struct esd_usb_net_priv *priv;
681 	int i, j;
682 
683 	usb_kill_anchored_urbs(&dev->rx_submitted);
684 
685 	for (i = 0; i < ESD_USB_MAX_RX_URBS; ++i)
686 		usb_free_coherent(dev->udev, ESD_USB_RX_BUFFER_SIZE,
687 				  dev->rxbuf[i], dev->rxbuf_dma[i]);
688 
689 	for (i = 0; i < dev->net_count; i++) {
690 		priv = dev->nets[i];
691 		if (priv) {
692 			usb_kill_anchored_urbs(&priv->tx_submitted);
693 			atomic_set(&priv->active_tx_jobs, 0);
694 
695 			for (j = 0; j < ESD_USB_MAX_TX_URBS; j++)
696 				priv->tx_contexts[j].echo_index = ESD_USB_MAX_TX_URBS;
697 		}
698 	}
699 }
700 
701 static int esd_usb_open(struct net_device *netdev)
702 {
703 	struct esd_usb_net_priv *priv = netdev_priv(netdev);
704 	int err;
705 
706 	/* common open */
707 	err = open_candev(netdev);
708 	if (err)
709 		return err;
710 
711 	/* finally start device */
712 	err = esd_usb_start(priv);
713 	if (err) {
714 		netdev_warn(netdev, "couldn't start device: %d\n", err);
715 		close_candev(netdev);
716 		return err;
717 	}
718 
719 	netif_start_queue(netdev);
720 
721 	return 0;
722 }
723 
724 static netdev_tx_t esd_usb_start_xmit(struct sk_buff *skb,
725 				      struct net_device *netdev)
726 {
727 	struct esd_usb_net_priv *priv = netdev_priv(netdev);
728 	struct esd_usb *dev = priv->usb;
729 	struct esd_tx_urb_context *context = NULL;
730 	struct net_device_stats *stats = &netdev->stats;
731 	struct can_frame *cf = (struct can_frame *)skb->data;
732 	union esd_usb_msg *msg;
733 	struct urb *urb;
734 	u8 *buf;
735 	int i, err;
736 	int ret = NETDEV_TX_OK;
737 	size_t size = sizeof(union esd_usb_msg);
738 
739 	if (can_dev_dropped_skb(netdev, skb))
740 		return NETDEV_TX_OK;
741 
742 	/* create a URB, and a buffer for it, and copy the data to the URB */
743 	urb = usb_alloc_urb(0, GFP_ATOMIC);
744 	if (!urb) {
745 		stats->tx_dropped++;
746 		dev_kfree_skb(skb);
747 		goto nourbmem;
748 	}
749 
750 	buf = usb_alloc_coherent(dev->udev, size, GFP_ATOMIC,
751 				 &urb->transfer_dma);
752 	if (!buf) {
753 		netdev_err(netdev, "No memory left for USB buffer\n");
754 		stats->tx_dropped++;
755 		dev_kfree_skb(skb);
756 		goto nobufmem;
757 	}
758 
759 	msg = (union esd_usb_msg *)buf;
760 
761 	/* minimal length as # of 32bit words */
762 	msg->hdr.len = offsetof(struct esd_usb_tx_msg, data) / sizeof(u32);
763 	msg->hdr.cmd = ESD_USB_CMD_CAN_TX;
764 	msg->tx.net = priv->index;
765 	msg->tx.dlc = can_get_cc_dlc(cf, priv->can.ctrlmode);
766 	msg->tx.id = cpu_to_le32(cf->can_id & CAN_ERR_MASK);
767 
768 	if (cf->can_id & CAN_RTR_FLAG)
769 		msg->tx.dlc |= ESD_USB_RTR;
770 
771 	if (cf->can_id & CAN_EFF_FLAG)
772 		msg->tx.id |= cpu_to_le32(ESD_USB_EXTID);
773 
774 	for (i = 0; i < cf->len; i++)
775 		msg->tx.data[i] = cf->data[i];
776 
777 	/* round up, then divide by 4 to add the payload length as # of 32bit words */
778 	msg->hdr.len += DIV_ROUND_UP(cf->len, sizeof(u32));
779 
780 	for (i = 0; i < ESD_USB_MAX_TX_URBS; i++) {
781 		if (priv->tx_contexts[i].echo_index == ESD_USB_MAX_TX_URBS) {
782 			context = &priv->tx_contexts[i];
783 			break;
784 		}
785 	}
786 
787 	/* This may never happen */
788 	if (!context) {
789 		netdev_warn(netdev, "couldn't find free context\n");
790 		ret = NETDEV_TX_BUSY;
791 		goto releasebuf;
792 	}
793 
794 	context->priv = priv;
795 	context->echo_index = i;
796 
797 	/* hnd must not be 0 - MSB is stripped in txdone handling */
798 	msg->tx.hnd = BIT(31) | i; /* returned in TX done message */
799 
800 	usb_fill_bulk_urb(urb, dev->udev, usb_sndbulkpipe(dev->udev, 2), buf,
801 			  msg->hdr.len * sizeof(u32), /* convert to # of bytes */
802 			  esd_usb_write_bulk_callback, context);
803 
804 	urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
805 
806 	usb_anchor_urb(urb, &priv->tx_submitted);
807 
808 	can_put_echo_skb(skb, netdev, context->echo_index, 0);
809 
810 	atomic_inc(&priv->active_tx_jobs);
811 
812 	/* Slow down tx path */
813 	if (atomic_read(&priv->active_tx_jobs) >= ESD_USB_MAX_TX_URBS)
814 		netif_stop_queue(netdev);
815 
816 	err = usb_submit_urb(urb, GFP_ATOMIC);
817 	if (err) {
818 		can_free_echo_skb(netdev, context->echo_index, NULL);
819 
820 		atomic_dec(&priv->active_tx_jobs);
821 		usb_unanchor_urb(urb);
822 
823 		stats->tx_dropped++;
824 
825 		if (err == -ENODEV)
826 			netif_device_detach(netdev);
827 		else
828 			netdev_warn(netdev, "failed tx_urb %d\n", err);
829 
830 		goto releasebuf;
831 	}
832 
833 	netif_trans_update(netdev);
834 
835 	/* Release our reference to this URB, the USB core will eventually free
836 	 * it entirely.
837 	 */
838 	usb_free_urb(urb);
839 
840 	return NETDEV_TX_OK;
841 
842 releasebuf:
843 	usb_free_coherent(dev->udev, size, buf, urb->transfer_dma);
844 
845 nobufmem:
846 	usb_free_urb(urb);
847 
848 nourbmem:
849 	return ret;
850 }
851 
852 static int esd_usb_close(struct net_device *netdev)
853 {
854 	struct esd_usb_net_priv *priv = netdev_priv(netdev);
855 	union esd_usb_msg *msg;
856 	int i;
857 
858 	msg = kmalloc(sizeof(*msg), GFP_KERNEL);
859 	if (!msg)
860 		return -ENOMEM;
861 
862 	/* Disable all IDs (see esd_usb_start()) */
863 	msg->hdr.cmd = ESD_USB_CMD_IDADD;
864 	msg->hdr.len = sizeof(struct esd_usb_id_filter_msg) / sizeof(u32);/* # of 32bit words */
865 	msg->filter.net = priv->index;
866 	msg->filter.option = ESD_USB_ID_ENABLE; /* start with segment 0 */
867 	for (i = 0; i <= ESD_USB_MAX_ID_SEGMENT; i++)
868 		msg->filter.mask[i] = 0;
869 	if (esd_usb_send_msg(priv->usb, msg) < 0)
870 		netdev_err(netdev, "sending idadd message failed\n");
871 
872 	/* set CAN controller to reset mode */
873 	msg->hdr.len = sizeof(struct esd_usb_set_baudrate_msg) / sizeof(u32); /* # of 32bit words */
874 	msg->hdr.cmd = ESD_USB_CMD_SETBAUD;
875 	msg->setbaud.net = priv->index;
876 	msg->setbaud.rsvd = 0;
877 	msg->setbaud.baud = cpu_to_le32(ESD_USB_NO_BAUDRATE);
878 	if (esd_usb_send_msg(priv->usb, msg) < 0)
879 		netdev_err(netdev, "sending setbaud message failed\n");
880 
881 	priv->can.state = CAN_STATE_STOPPED;
882 
883 	netif_stop_queue(netdev);
884 
885 	close_candev(netdev);
886 
887 	kfree(msg);
888 
889 	return 0;
890 }
891 
892 static const struct net_device_ops esd_usb_netdev_ops = {
893 	.ndo_open = esd_usb_open,
894 	.ndo_stop = esd_usb_close,
895 	.ndo_start_xmit = esd_usb_start_xmit,
896 	.ndo_change_mtu = can_change_mtu,
897 };
898 
899 static const struct ethtool_ops esd_usb_ethtool_ops = {
900 	.get_ts_info = ethtool_op_get_ts_info,
901 };
902 
903 static const struct can_bittiming_const esd_usb_2_bittiming_const = {
904 	.name = "esd_usb_2",
905 	.tseg1_min = 1,
906 	.tseg1_max = 16,
907 	.tseg2_min = 1,
908 	.tseg2_max = 8,
909 	.sjw_max = 4,
910 	.brp_min = 1,
911 	.brp_max = 1024,
912 	.brp_inc = 1,
913 };
914 
915 static int esd_usb_2_set_bittiming(struct net_device *netdev)
916 {
917 	const struct can_bittiming_const *btc = &esd_usb_2_bittiming_const;
918 	struct esd_usb_net_priv *priv = netdev_priv(netdev);
919 	struct can_bittiming *bt = &priv->can.bittiming;
920 	union esd_usb_msg *msg;
921 	int err;
922 	u32 canbtr;
923 	int sjw_shift;
924 
925 	canbtr = ESD_USB_UBR;
926 	if (priv->can.ctrlmode & CAN_CTRLMODE_LISTENONLY)
927 		canbtr |= ESD_USB_LOM;
928 
929 	canbtr |= (bt->brp - 1) & (btc->brp_max - 1);
930 
931 	if (le16_to_cpu(priv->usb->udev->descriptor.idProduct) ==
932 	    ESD_USB_CANUSBM_PRODUCT_ID)
933 		sjw_shift = ESD_USB_M_SJW_SHIFT;
934 	else
935 		sjw_shift = ESD_USB_2_SJW_SHIFT;
936 
937 	canbtr |= ((bt->sjw - 1) & (btc->sjw_max - 1))
938 		<< sjw_shift;
939 	canbtr |= ((bt->prop_seg + bt->phase_seg1 - 1)
940 		   & (btc->tseg1_max - 1))
941 		<< ESD_USB_2_TSEG1_SHIFT;
942 	canbtr |= ((bt->phase_seg2 - 1) & (btc->tseg2_max - 1))
943 		<< ESD_USB_2_TSEG2_SHIFT;
944 	if (priv->can.ctrlmode & CAN_CTRLMODE_3_SAMPLES)
945 		canbtr |= ESD_USB_TRIPLE_SAMPLES;
946 
947 	msg = kmalloc(sizeof(*msg), GFP_KERNEL);
948 	if (!msg)
949 		return -ENOMEM;
950 
951 	msg->hdr.len = sizeof(struct esd_usb_set_baudrate_msg) / sizeof(u32); /* # of 32bit words */
952 	msg->hdr.cmd = ESD_USB_CMD_SETBAUD;
953 	msg->setbaud.net = priv->index;
954 	msg->setbaud.rsvd = 0;
955 	msg->setbaud.baud = cpu_to_le32(canbtr);
956 
957 	netdev_dbg(netdev, "setting BTR=%#x\n", canbtr);
958 
959 	err = esd_usb_send_msg(priv->usb, msg);
960 
961 	kfree(msg);
962 	return err;
963 }
964 
965 static int esd_usb_get_berr_counter(const struct net_device *netdev,
966 				    struct can_berr_counter *bec)
967 {
968 	struct esd_usb_net_priv *priv = netdev_priv(netdev);
969 
970 	bec->txerr = priv->bec.txerr;
971 	bec->rxerr = priv->bec.rxerr;
972 
973 	return 0;
974 }
975 
976 static int esd_usb_set_mode(struct net_device *netdev, enum can_mode mode)
977 {
978 	switch (mode) {
979 	case CAN_MODE_START:
980 		netif_wake_queue(netdev);
981 		break;
982 
983 	default:
984 		return -EOPNOTSUPP;
985 	}
986 
987 	return 0;
988 }
989 
990 static int esd_usb_probe_one_net(struct usb_interface *intf, int index)
991 {
992 	struct esd_usb *dev = usb_get_intfdata(intf);
993 	struct net_device *netdev;
994 	struct esd_usb_net_priv *priv;
995 	int err = 0;
996 	int i;
997 
998 	netdev = alloc_candev(sizeof(*priv), ESD_USB_MAX_TX_URBS);
999 	if (!netdev) {
1000 		dev_err(&intf->dev, "couldn't alloc candev\n");
1001 		err = -ENOMEM;
1002 		goto done;
1003 	}
1004 
1005 	priv = netdev_priv(netdev);
1006 
1007 	init_usb_anchor(&priv->tx_submitted);
1008 	atomic_set(&priv->active_tx_jobs, 0);
1009 
1010 	for (i = 0; i < ESD_USB_MAX_TX_URBS; i++)
1011 		priv->tx_contexts[i].echo_index = ESD_USB_MAX_TX_URBS;
1012 
1013 	priv->usb = dev;
1014 	priv->netdev = netdev;
1015 	priv->index = index;
1016 
1017 	priv->can.state = CAN_STATE_STOPPED;
1018 	priv->can.ctrlmode_supported = CAN_CTRLMODE_LISTENONLY |
1019 		CAN_CTRLMODE_CC_LEN8_DLC |
1020 		CAN_CTRLMODE_BERR_REPORTING;
1021 
1022 	if (le16_to_cpu(dev->udev->descriptor.idProduct) ==
1023 	    ESD_USB_CANUSBM_PRODUCT_ID)
1024 		priv->can.clock.freq = ESD_USB_M_CAN_CLOCK;
1025 	else {
1026 		priv->can.clock.freq = ESD_USB_2_CAN_CLOCK;
1027 		priv->can.ctrlmode_supported |= CAN_CTRLMODE_3_SAMPLES;
1028 	}
1029 
1030 	priv->can.bittiming_const = &esd_usb_2_bittiming_const;
1031 	priv->can.do_set_bittiming = esd_usb_2_set_bittiming;
1032 	priv->can.do_set_mode = esd_usb_set_mode;
1033 	priv->can.do_get_berr_counter = esd_usb_get_berr_counter;
1034 
1035 	netdev->flags |= IFF_ECHO; /* we support local echo */
1036 
1037 	netdev->netdev_ops = &esd_usb_netdev_ops;
1038 	netdev->ethtool_ops = &esd_usb_ethtool_ops;
1039 
1040 	SET_NETDEV_DEV(netdev, &intf->dev);
1041 	netdev->dev_id = index;
1042 
1043 	err = register_candev(netdev);
1044 	if (err) {
1045 		dev_err(&intf->dev, "couldn't register CAN device: %d\n", err);
1046 		free_candev(netdev);
1047 		err = -ENOMEM;
1048 		goto done;
1049 	}
1050 
1051 	dev->nets[index] = priv;
1052 	netdev_info(netdev, "device %s registered\n", netdev->name);
1053 
1054 done:
1055 	return err;
1056 }
1057 
1058 /* probe function for new USB devices
1059  *
1060  * check version information and number of available
1061  * CAN interfaces
1062  */
1063 static int esd_usb_probe(struct usb_interface *intf,
1064 			 const struct usb_device_id *id)
1065 {
1066 	struct esd_usb *dev;
1067 	union esd_usb_msg *msg;
1068 	int i, err;
1069 
1070 	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
1071 	if (!dev) {
1072 		err = -ENOMEM;
1073 		goto done;
1074 	}
1075 
1076 	dev->udev = interface_to_usbdev(intf);
1077 
1078 	init_usb_anchor(&dev->rx_submitted);
1079 
1080 	usb_set_intfdata(intf, dev);
1081 
1082 	msg = kmalloc(sizeof(*msg), GFP_KERNEL);
1083 	if (!msg) {
1084 		err = -ENOMEM;
1085 		goto free_msg;
1086 	}
1087 
1088 	/* query number of CAN interfaces (nets) */
1089 	msg->hdr.cmd = ESD_USB_CMD_VERSION;
1090 	msg->hdr.len = sizeof(struct esd_usb_version_msg) / sizeof(u32); /* # of 32bit words */
1091 	msg->version.rsvd = 0;
1092 	msg->version.flags = 0;
1093 	msg->version.drv_version = 0;
1094 
1095 	err = esd_usb_send_msg(dev, msg);
1096 	if (err < 0) {
1097 		dev_err(&intf->dev, "sending version message failed\n");
1098 		goto free_msg;
1099 	}
1100 
1101 	err = esd_usb_wait_msg(dev, msg);
1102 	if (err < 0) {
1103 		dev_err(&intf->dev, "no version message answer\n");
1104 		goto free_msg;
1105 	}
1106 
1107 	dev->net_count = (int)msg->version_reply.nets;
1108 	dev->version = le32_to_cpu(msg->version_reply.version);
1109 
1110 	if (device_create_file(&intf->dev, &dev_attr_firmware))
1111 		dev_err(&intf->dev,
1112 			"Couldn't create device file for firmware\n");
1113 
1114 	if (device_create_file(&intf->dev, &dev_attr_hardware))
1115 		dev_err(&intf->dev,
1116 			"Couldn't create device file for hardware\n");
1117 
1118 	if (device_create_file(&intf->dev, &dev_attr_nets))
1119 		dev_err(&intf->dev,
1120 			"Couldn't create device file for nets\n");
1121 
1122 	/* do per device probing */
1123 	for (i = 0; i < dev->net_count; i++)
1124 		esd_usb_probe_one_net(intf, i);
1125 
1126 free_msg:
1127 	kfree(msg);
1128 	if (err)
1129 		kfree(dev);
1130 done:
1131 	return err;
1132 }
1133 
1134 /* called by the usb core when the device is removed from the system */
1135 static void esd_usb_disconnect(struct usb_interface *intf)
1136 {
1137 	struct esd_usb *dev = usb_get_intfdata(intf);
1138 	struct net_device *netdev;
1139 	int i;
1140 
1141 	device_remove_file(&intf->dev, &dev_attr_firmware);
1142 	device_remove_file(&intf->dev, &dev_attr_hardware);
1143 	device_remove_file(&intf->dev, &dev_attr_nets);
1144 
1145 	usb_set_intfdata(intf, NULL);
1146 
1147 	if (dev) {
1148 		for (i = 0; i < dev->net_count; i++) {
1149 			if (dev->nets[i]) {
1150 				netdev = dev->nets[i]->netdev;
1151 				unregister_netdev(netdev);
1152 				free_candev(netdev);
1153 			}
1154 		}
1155 		unlink_all_urbs(dev);
1156 		kfree(dev);
1157 	}
1158 }
1159 
1160 /* usb specific object needed to register this driver with the usb subsystem */
1161 static struct usb_driver esd_usb_driver = {
1162 	.name = KBUILD_MODNAME,
1163 	.probe = esd_usb_probe,
1164 	.disconnect = esd_usb_disconnect,
1165 	.id_table = esd_usb_table,
1166 };
1167 
1168 module_usb_driver(esd_usb_driver);
1169