1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * CAN driver for PEAK System PCAN-USB adapter
4  * Derived from the PCAN project file driver/src/pcan_usb.c
5  *
6  * Copyright (C) 2003-2010 PEAK System-Technik GmbH
7  * Copyright (C) 2011-2012 Stephane Grosjean <s.grosjean@peak-system.com>
8  *
9  * Many thanks to Klaus Hitschler <klaus.hitschler@gmx.de>
10  */
11 #include <linux/netdevice.h>
12 #include <linux/usb.h>
13 #include <linux/module.h>
14 #include <linux/ethtool.h>
15 
16 #include <linux/can.h>
17 #include <linux/can/dev.h>
18 #include <linux/can/error.h>
19 
20 #include "pcan_usb_core.h"
21 
22 /* PCAN-USB Endpoints */
23 #define PCAN_USB_EP_CMDOUT		1
24 #define PCAN_USB_EP_CMDIN		(PCAN_USB_EP_CMDOUT | USB_DIR_IN)
25 #define PCAN_USB_EP_MSGOUT		2
26 #define PCAN_USB_EP_MSGIN		(PCAN_USB_EP_MSGOUT | USB_DIR_IN)
27 
28 /* PCAN-USB command struct */
29 #define PCAN_USB_CMD_FUNC		0
30 #define PCAN_USB_CMD_NUM		1
31 #define PCAN_USB_CMD_ARGS		2
32 #define PCAN_USB_CMD_ARGS_LEN		14
33 #define PCAN_USB_CMD_LEN		(PCAN_USB_CMD_ARGS + \
34 					 PCAN_USB_CMD_ARGS_LEN)
35 
36 /* PCAN-USB commands */
37 #define PCAN_USB_CMD_BITRATE	1
38 #define PCAN_USB_CMD_SET_BUS	3
39 #define PCAN_USB_CMD_DEVID	4
40 #define PCAN_USB_CMD_SN		6
41 #define PCAN_USB_CMD_REGISTER	9
42 #define PCAN_USB_CMD_EXT_VCC	10
43 #define PCAN_USB_CMD_ERR_FR	11
44 #define PCAN_USB_CMD_LED	12
45 
46 /* PCAN_USB_CMD_SET_BUS number arg */
47 #define PCAN_USB_BUS_XCVER		2
48 #define PCAN_USB_BUS_SILENT_MODE	3
49 
50 /* PCAN_USB_CMD_xxx functions */
51 #define PCAN_USB_GET		1
52 #define PCAN_USB_SET		2
53 
54 /* PCAN-USB command timeout (ms.) */
55 #define PCAN_USB_COMMAND_TIMEOUT	1000
56 
57 /* PCAN-USB startup timeout (ms.) */
58 #define PCAN_USB_STARTUP_TIMEOUT	10
59 
60 /* PCAN-USB rx/tx buffers size */
61 #define PCAN_USB_RX_BUFFER_SIZE		64
62 #define PCAN_USB_TX_BUFFER_SIZE		64
63 
64 #define PCAN_USB_MSG_HEADER_LEN		2
65 
66 /* PCAN-USB adapter internal clock (MHz) */
67 #define PCAN_USB_CRYSTAL_HZ		16000000
68 
69 /* PCAN-USB USB message record status/len field */
70 #define PCAN_USB_STATUSLEN_TIMESTAMP	(1 << 7)
71 #define PCAN_USB_STATUSLEN_INTERNAL	(1 << 6)
72 #define PCAN_USB_STATUSLEN_EXT_ID	(1 << 5)
73 #define PCAN_USB_STATUSLEN_RTR		(1 << 4)
74 #define PCAN_USB_STATUSLEN_DLC		(0xf)
75 
76 /* PCAN-USB error flags */
77 #define PCAN_USB_ERROR_TXFULL		0x01
78 #define PCAN_USB_ERROR_RXQOVR		0x02
79 #define PCAN_USB_ERROR_BUS_LIGHT	0x04
80 #define PCAN_USB_ERROR_BUS_HEAVY	0x08
81 #define PCAN_USB_ERROR_BUS_OFF		0x10
82 #define PCAN_USB_ERROR_RXQEMPTY		0x20
83 #define PCAN_USB_ERROR_QOVR		0x40
84 #define PCAN_USB_ERROR_TXQFULL		0x80
85 
86 #define PCAN_USB_ERROR_BUS		(PCAN_USB_ERROR_BUS_LIGHT | \
87 					 PCAN_USB_ERROR_BUS_HEAVY | \
88 					 PCAN_USB_ERROR_BUS_OFF)
89 
90 /* SJA1000 modes */
91 #define SJA1000_MODE_NORMAL		0x00
92 #define SJA1000_MODE_INIT		0x01
93 
94 /*
95  * tick duration = 42.666 us =>
96  * (tick_number * 44739243) >> 20 ~ (tick_number * 42666) / 1000
97  * accuracy = 10^-7
98  */
99 #define PCAN_USB_TS_DIV_SHIFTER		20
100 #define PCAN_USB_TS_US_PER_TICK		44739243
101 
102 /* PCAN-USB messages record types */
103 #define PCAN_USB_REC_ERROR		1
104 #define PCAN_USB_REC_ANALOG		2
105 #define PCAN_USB_REC_BUSLOAD		3
106 #define PCAN_USB_REC_TS			4
107 #define PCAN_USB_REC_BUSEVT		5
108 
109 /* CAN bus events notifications selection mask */
110 #define PCAN_USB_ERR_RXERR		0x02	/* ask for rxerr counter */
111 #define PCAN_USB_ERR_TXERR		0x04	/* ask for txerr counter */
112 
113 /* This mask generates an usb packet each time the state of the bus changes.
114  * In other words, its interest is to know which side among rx and tx is
115  * responsible of the change of the bus state.
116  */
117 #define PCAN_USB_BERR_MASK	(PCAN_USB_ERR_RXERR | PCAN_USB_ERR_TXERR)
118 
119 /* identify bus event packets with rx/tx error counters */
120 #define PCAN_USB_ERR_CNT_DEC		0x00	/* counters are decreasing */
121 #define PCAN_USB_ERR_CNT_INC		0x80	/* counters are increasing */
122 
123 /* private to PCAN-USB adapter */
124 struct pcan_usb {
125 	struct peak_usb_device dev;
126 	struct peak_time_ref time_ref;
127 	struct timer_list restart_timer;
128 	struct can_berr_counter bec;
129 };
130 
131 /* incoming message context for decoding */
132 struct pcan_usb_msg_context {
133 	u16 ts16;
134 	u8 prev_ts8;
135 	u8 *ptr;
136 	u8 *end;
137 	u8 rec_cnt;
138 	u8 rec_idx;
139 	u8 rec_ts_idx;
140 	struct net_device *netdev;
141 	struct pcan_usb *pdev;
142 };
143 
144 /*
145  * send a command
146  */
147 static int pcan_usb_send_cmd(struct peak_usb_device *dev, u8 f, u8 n, u8 *p)
148 {
149 	int err;
150 	int actual_length;
151 
152 	/* usb device unregistered? */
153 	if (!(dev->state & PCAN_USB_STATE_CONNECTED))
154 		return 0;
155 
156 	dev->cmd_buf[PCAN_USB_CMD_FUNC] = f;
157 	dev->cmd_buf[PCAN_USB_CMD_NUM] = n;
158 
159 	if (p)
160 		memcpy(dev->cmd_buf + PCAN_USB_CMD_ARGS,
161 			p, PCAN_USB_CMD_ARGS_LEN);
162 
163 	err = usb_bulk_msg(dev->udev,
164 			usb_sndbulkpipe(dev->udev, PCAN_USB_EP_CMDOUT),
165 			dev->cmd_buf, PCAN_USB_CMD_LEN, &actual_length,
166 			PCAN_USB_COMMAND_TIMEOUT);
167 	if (err)
168 		netdev_err(dev->netdev,
169 			"sending cmd f=0x%x n=0x%x failure: %d\n",
170 			f, n, err);
171 	return err;
172 }
173 
174 /*
175  * send a command then wait for its response
176  */
177 static int pcan_usb_wait_rsp(struct peak_usb_device *dev, u8 f, u8 n, u8 *p)
178 {
179 	int err;
180 	int actual_length;
181 
182 	/* usb device unregistered? */
183 	if (!(dev->state & PCAN_USB_STATE_CONNECTED))
184 		return 0;
185 
186 	/* first, send command */
187 	err = pcan_usb_send_cmd(dev, f, n, NULL);
188 	if (err)
189 		return err;
190 
191 	err = usb_bulk_msg(dev->udev,
192 		usb_rcvbulkpipe(dev->udev, PCAN_USB_EP_CMDIN),
193 		dev->cmd_buf, PCAN_USB_CMD_LEN, &actual_length,
194 		PCAN_USB_COMMAND_TIMEOUT);
195 	if (err)
196 		netdev_err(dev->netdev,
197 			"waiting rsp f=0x%x n=0x%x failure: %d\n", f, n, err);
198 	else if (p)
199 		memcpy(p, dev->cmd_buf + PCAN_USB_CMD_ARGS,
200 			PCAN_USB_CMD_ARGS_LEN);
201 
202 	return err;
203 }
204 
205 static int pcan_usb_set_sja1000(struct peak_usb_device *dev, u8 mode)
206 {
207 	u8 args[PCAN_USB_CMD_ARGS_LEN] = {
208 		[1] = mode,
209 	};
210 
211 	return pcan_usb_send_cmd(dev, PCAN_USB_CMD_REGISTER, PCAN_USB_SET,
212 				 args);
213 }
214 
215 static int pcan_usb_set_bus(struct peak_usb_device *dev, u8 onoff)
216 {
217 	u8 args[PCAN_USB_CMD_ARGS_LEN] = {
218 		[0] = !!onoff,
219 	};
220 
221 	return pcan_usb_send_cmd(dev, PCAN_USB_CMD_SET_BUS, PCAN_USB_BUS_XCVER,
222 				 args);
223 }
224 
225 static int pcan_usb_set_silent(struct peak_usb_device *dev, u8 onoff)
226 {
227 	u8 args[PCAN_USB_CMD_ARGS_LEN] = {
228 		[0] = !!onoff,
229 	};
230 
231 	return pcan_usb_send_cmd(dev, PCAN_USB_CMD_SET_BUS,
232 				 PCAN_USB_BUS_SILENT_MODE, args);
233 }
234 
235 /* send the cmd to be notified from bus errors */
236 static int pcan_usb_set_err_frame(struct peak_usb_device *dev, u8 err_mask)
237 {
238 	u8 args[PCAN_USB_CMD_ARGS_LEN] = {
239 		[0] = err_mask,
240 	};
241 
242 	return pcan_usb_send_cmd(dev, PCAN_USB_CMD_ERR_FR, PCAN_USB_SET, args);
243 }
244 
245 static int pcan_usb_set_ext_vcc(struct peak_usb_device *dev, u8 onoff)
246 {
247 	u8 args[PCAN_USB_CMD_ARGS_LEN] = {
248 		[0] = !!onoff,
249 	};
250 
251 	return pcan_usb_send_cmd(dev, PCAN_USB_CMD_EXT_VCC, PCAN_USB_SET, args);
252 }
253 
254 static int pcan_usb_set_led(struct peak_usb_device *dev, u8 onoff)
255 {
256 	u8 args[PCAN_USB_CMD_ARGS_LEN] = {
257 		[0] = !!onoff,
258 	};
259 
260 	return pcan_usb_send_cmd(dev, PCAN_USB_CMD_LED, PCAN_USB_SET, args);
261 }
262 
263 /*
264  * set bittiming value to can
265  */
266 static int pcan_usb_set_bittiming(struct peak_usb_device *dev,
267 				  struct can_bittiming *bt)
268 {
269 	u8 args[PCAN_USB_CMD_ARGS_LEN];
270 	u8 btr0, btr1;
271 
272 	btr0 = ((bt->brp - 1) & 0x3f) | (((bt->sjw - 1) & 0x3) << 6);
273 	btr1 = ((bt->prop_seg + bt->phase_seg1 - 1) & 0xf) |
274 		(((bt->phase_seg2 - 1) & 0x7) << 4);
275 	if (dev->can.ctrlmode & CAN_CTRLMODE_3_SAMPLES)
276 		btr1 |= 0x80;
277 
278 	netdev_info(dev->netdev, "setting BTR0=0x%02x BTR1=0x%02x\n",
279 		btr0, btr1);
280 
281 	args[0] = btr1;
282 	args[1] = btr0;
283 
284 	return pcan_usb_send_cmd(dev, PCAN_USB_CMD_BITRATE, PCAN_USB_SET, args);
285 }
286 
287 /*
288  * init/reset can
289  */
290 static int pcan_usb_write_mode(struct peak_usb_device *dev, u8 onoff)
291 {
292 	int err;
293 
294 	err = pcan_usb_set_bus(dev, onoff);
295 	if (err)
296 		return err;
297 
298 	if (!onoff) {
299 		err = pcan_usb_set_sja1000(dev, SJA1000_MODE_INIT);
300 	} else {
301 		/* the PCAN-USB needs time to init */
302 		set_current_state(TASK_INTERRUPTIBLE);
303 		schedule_timeout(msecs_to_jiffies(PCAN_USB_STARTUP_TIMEOUT));
304 	}
305 
306 	return err;
307 }
308 
309 /*
310  * handle end of waiting for the device to reset
311  */
312 static void pcan_usb_restart(struct timer_list *t)
313 {
314 	struct pcan_usb *pdev = from_timer(pdev, t, restart_timer);
315 	struct peak_usb_device *dev = &pdev->dev;
316 
317 	/* notify candev and netdev */
318 	peak_usb_restart_complete(dev);
319 }
320 
321 /*
322  * handle the submission of the restart urb
323  */
324 static void pcan_usb_restart_pending(struct urb *urb)
325 {
326 	struct pcan_usb *pdev = urb->context;
327 
328 	/* the PCAN-USB needs time to restart */
329 	mod_timer(&pdev->restart_timer,
330 			jiffies + msecs_to_jiffies(PCAN_USB_STARTUP_TIMEOUT));
331 
332 	/* can delete usb resources */
333 	peak_usb_async_complete(urb);
334 }
335 
336 /*
337  * handle asynchronous restart
338  */
339 static int pcan_usb_restart_async(struct peak_usb_device *dev, struct urb *urb,
340 				  u8 *buf)
341 {
342 	struct pcan_usb *pdev = container_of(dev, struct pcan_usb, dev);
343 
344 	if (timer_pending(&pdev->restart_timer))
345 		return -EBUSY;
346 
347 	/* set bus on */
348 	buf[PCAN_USB_CMD_FUNC] = 3;
349 	buf[PCAN_USB_CMD_NUM] = 2;
350 	buf[PCAN_USB_CMD_ARGS] = 1;
351 
352 	usb_fill_bulk_urb(urb, dev->udev,
353 			usb_sndbulkpipe(dev->udev, PCAN_USB_EP_CMDOUT),
354 			buf, PCAN_USB_CMD_LEN,
355 			pcan_usb_restart_pending, pdev);
356 
357 	return usb_submit_urb(urb, GFP_ATOMIC);
358 }
359 
360 /*
361  * read serial number from device
362  */
363 static int pcan_usb_get_serial(struct peak_usb_device *dev, u32 *serial_number)
364 {
365 	u8 args[PCAN_USB_CMD_ARGS_LEN];
366 	int err;
367 
368 	err = pcan_usb_wait_rsp(dev, PCAN_USB_CMD_SN, PCAN_USB_GET, args);
369 	if (err)
370 		return err;
371 	*serial_number = le32_to_cpup((__le32 *)args);
372 
373 	return 0;
374 }
375 
376 /*
377  * read device id from device
378  */
379 static int pcan_usb_get_device_id(struct peak_usb_device *dev, u32 *device_id)
380 {
381 	u8 args[PCAN_USB_CMD_ARGS_LEN];
382 	int err;
383 
384 	err = pcan_usb_wait_rsp(dev, PCAN_USB_CMD_DEVID, PCAN_USB_GET, args);
385 	if (err)
386 		netdev_err(dev->netdev, "getting device id failure: %d\n", err);
387 
388 	*device_id = args[0];
389 
390 	return err;
391 }
392 
393 /*
394  * update current time ref with received timestamp
395  */
396 static int pcan_usb_update_ts(struct pcan_usb_msg_context *mc)
397 {
398 	if ((mc->ptr + 2) > mc->end)
399 		return -EINVAL;
400 
401 	mc->ts16 = get_unaligned_le16(mc->ptr);
402 
403 	if (mc->rec_idx > 0)
404 		peak_usb_update_ts_now(&mc->pdev->time_ref, mc->ts16);
405 	else
406 		peak_usb_set_ts_now(&mc->pdev->time_ref, mc->ts16);
407 
408 	return 0;
409 }
410 
411 /*
412  * decode received timestamp
413  */
414 static int pcan_usb_decode_ts(struct pcan_usb_msg_context *mc, u8 first_packet)
415 {
416 	/* only 1st packet supplies a word timestamp */
417 	if (first_packet) {
418 		if ((mc->ptr + 2) > mc->end)
419 			return -EINVAL;
420 
421 		mc->ts16 = get_unaligned_le16(mc->ptr);
422 		mc->prev_ts8 = mc->ts16 & 0x00ff;
423 
424 		mc->ptr += 2;
425 	} else {
426 		u8 ts8;
427 
428 		if ((mc->ptr + 1) > mc->end)
429 			return -EINVAL;
430 
431 		ts8 = *mc->ptr++;
432 
433 		if (ts8 < mc->prev_ts8)
434 			mc->ts16 += 0x100;
435 
436 		mc->ts16 &= 0xff00;
437 		mc->ts16 |= ts8;
438 		mc->prev_ts8 = ts8;
439 	}
440 
441 	return 0;
442 }
443 
444 static int pcan_usb_decode_error(struct pcan_usb_msg_context *mc, u8 n,
445 				 u8 status_len)
446 {
447 	struct sk_buff *skb;
448 	struct can_frame *cf;
449 	enum can_state new_state;
450 
451 	/* ignore this error until 1st ts received */
452 	if (n == PCAN_USB_ERROR_QOVR)
453 		if (!mc->pdev->time_ref.tick_count)
454 			return 0;
455 
456 	new_state = mc->pdev->dev.can.state;
457 
458 	switch (mc->pdev->dev.can.state) {
459 	case CAN_STATE_ERROR_ACTIVE:
460 		if (n & PCAN_USB_ERROR_BUS_LIGHT) {
461 			new_state = CAN_STATE_ERROR_WARNING;
462 			break;
463 		}
464 		fallthrough;
465 
466 	case CAN_STATE_ERROR_WARNING:
467 		if (n & PCAN_USB_ERROR_BUS_HEAVY) {
468 			new_state = CAN_STATE_ERROR_PASSIVE;
469 			break;
470 		}
471 		if (n & PCAN_USB_ERROR_BUS_OFF) {
472 			new_state = CAN_STATE_BUS_OFF;
473 			break;
474 		}
475 		if (n & ~PCAN_USB_ERROR_BUS) {
476 			/*
477 			 * trick to bypass next comparison and process other
478 			 * errors
479 			 */
480 			new_state = CAN_STATE_MAX;
481 			break;
482 		}
483 		if ((n & PCAN_USB_ERROR_BUS_LIGHT) == 0) {
484 			/* no error (back to active state) */
485 			new_state = CAN_STATE_ERROR_ACTIVE;
486 			break;
487 		}
488 		break;
489 
490 	case CAN_STATE_ERROR_PASSIVE:
491 		if (n & PCAN_USB_ERROR_BUS_OFF) {
492 			new_state = CAN_STATE_BUS_OFF;
493 			break;
494 		}
495 		if (n & PCAN_USB_ERROR_BUS_LIGHT) {
496 			new_state = CAN_STATE_ERROR_WARNING;
497 			break;
498 		}
499 		if (n & ~PCAN_USB_ERROR_BUS) {
500 			/*
501 			 * trick to bypass next comparison and process other
502 			 * errors
503 			 */
504 			new_state = CAN_STATE_MAX;
505 			break;
506 		}
507 
508 		if ((n & PCAN_USB_ERROR_BUS_HEAVY) == 0) {
509 			/* no error (back to warning state) */
510 			new_state = CAN_STATE_ERROR_WARNING;
511 			break;
512 		}
513 		break;
514 
515 	default:
516 		/* do nothing waiting for restart */
517 		return 0;
518 	}
519 
520 	/* donot post any error if current state didn't change */
521 	if (mc->pdev->dev.can.state == new_state)
522 		return 0;
523 
524 	/* allocate an skb to store the error frame */
525 	skb = alloc_can_err_skb(mc->netdev, &cf);
526 	if (!skb)
527 		return -ENOMEM;
528 
529 	switch (new_state) {
530 	case CAN_STATE_BUS_OFF:
531 		cf->can_id |= CAN_ERR_BUSOFF;
532 		mc->pdev->dev.can.can_stats.bus_off++;
533 		can_bus_off(mc->netdev);
534 		break;
535 
536 	case CAN_STATE_ERROR_PASSIVE:
537 		cf->can_id |= CAN_ERR_CRTL;
538 		cf->data[1] = (mc->pdev->bec.txerr > mc->pdev->bec.rxerr) ?
539 				CAN_ERR_CRTL_TX_PASSIVE :
540 				CAN_ERR_CRTL_RX_PASSIVE;
541 		cf->data[6] = mc->pdev->bec.txerr;
542 		cf->data[7] = mc->pdev->bec.rxerr;
543 
544 		mc->pdev->dev.can.can_stats.error_passive++;
545 		break;
546 
547 	case CAN_STATE_ERROR_WARNING:
548 		cf->can_id |= CAN_ERR_CRTL;
549 		cf->data[1] = (mc->pdev->bec.txerr > mc->pdev->bec.rxerr) ?
550 				CAN_ERR_CRTL_TX_WARNING :
551 				CAN_ERR_CRTL_RX_WARNING;
552 		cf->data[6] = mc->pdev->bec.txerr;
553 		cf->data[7] = mc->pdev->bec.rxerr;
554 
555 		mc->pdev->dev.can.can_stats.error_warning++;
556 		break;
557 
558 	case CAN_STATE_ERROR_ACTIVE:
559 		cf->can_id |= CAN_ERR_CRTL;
560 		cf->data[1] = CAN_ERR_CRTL_ACTIVE;
561 
562 		/* sync local copies of rxerr/txerr counters */
563 		mc->pdev->bec.txerr = 0;
564 		mc->pdev->bec.rxerr = 0;
565 		break;
566 
567 	default:
568 		/* CAN_STATE_MAX (trick to handle other errors) */
569 		if (n & PCAN_USB_ERROR_TXQFULL)
570 			netdev_dbg(mc->netdev, "device Tx queue full)\n");
571 
572 		if (n & PCAN_USB_ERROR_RXQOVR) {
573 			netdev_dbg(mc->netdev, "data overrun interrupt\n");
574 			cf->can_id |= CAN_ERR_CRTL;
575 			cf->data[1] |= CAN_ERR_CRTL_RX_OVERFLOW;
576 			mc->netdev->stats.rx_over_errors++;
577 			mc->netdev->stats.rx_errors++;
578 		}
579 
580 		cf->data[6] = mc->pdev->bec.txerr;
581 		cf->data[7] = mc->pdev->bec.rxerr;
582 
583 		new_state = mc->pdev->dev.can.state;
584 		break;
585 	}
586 
587 	mc->pdev->dev.can.state = new_state;
588 
589 	if (status_len & PCAN_USB_STATUSLEN_TIMESTAMP) {
590 		struct skb_shared_hwtstamps *hwts = skb_hwtstamps(skb);
591 
592 		peak_usb_get_ts_time(&mc->pdev->time_ref, mc->ts16,
593 				     &hwts->hwtstamp);
594 	}
595 
596 	mc->netdev->stats.rx_packets++;
597 	mc->netdev->stats.rx_bytes += cf->len;
598 	netif_rx(skb);
599 
600 	return 0;
601 }
602 
603 /* decode bus event usb packet: first byte contains rxerr while 2nd one contains
604  * txerr.
605  */
606 static int pcan_usb_handle_bus_evt(struct pcan_usb_msg_context *mc, u8 ir)
607 {
608 	struct pcan_usb *pdev = mc->pdev;
609 
610 	/* acccording to the content of the packet */
611 	switch (ir) {
612 	case PCAN_USB_ERR_CNT_DEC:
613 	case PCAN_USB_ERR_CNT_INC:
614 
615 		/* save rx/tx error counters from in the device context */
616 		pdev->bec.rxerr = mc->ptr[1];
617 		pdev->bec.txerr = mc->ptr[2];
618 		break;
619 
620 	default:
621 		/* reserved */
622 		break;
623 	}
624 
625 	return 0;
626 }
627 
628 /*
629  * decode non-data usb message
630  */
631 static int pcan_usb_decode_status(struct pcan_usb_msg_context *mc,
632 				  u8 status_len)
633 {
634 	u8 rec_len = status_len & PCAN_USB_STATUSLEN_DLC;
635 	u8 f, n;
636 	int err;
637 
638 	/* check whether function and number can be read */
639 	if ((mc->ptr + 2) > mc->end)
640 		return -EINVAL;
641 
642 	f = mc->ptr[PCAN_USB_CMD_FUNC];
643 	n = mc->ptr[PCAN_USB_CMD_NUM];
644 	mc->ptr += PCAN_USB_CMD_ARGS;
645 
646 	if (status_len & PCAN_USB_STATUSLEN_TIMESTAMP) {
647 		int err = pcan_usb_decode_ts(mc, !mc->rec_ts_idx);
648 
649 		if (err)
650 			return err;
651 
652 		/* Next packet in the buffer will have a timestamp on a single
653 		 * byte
654 		 */
655 		mc->rec_ts_idx++;
656 	}
657 
658 	switch (f) {
659 	case PCAN_USB_REC_ERROR:
660 		err = pcan_usb_decode_error(mc, n, status_len);
661 		if (err)
662 			return err;
663 		break;
664 
665 	case PCAN_USB_REC_ANALOG:
666 		/* analog values (ignored) */
667 		rec_len = 2;
668 		break;
669 
670 	case PCAN_USB_REC_BUSLOAD:
671 		/* bus load (ignored) */
672 		rec_len = 1;
673 		break;
674 
675 	case PCAN_USB_REC_TS:
676 		/* only timestamp */
677 		if (pcan_usb_update_ts(mc))
678 			return -EINVAL;
679 		break;
680 
681 	case PCAN_USB_REC_BUSEVT:
682 		/* bus event notifications (get rxerr/txerr) */
683 		err = pcan_usb_handle_bus_evt(mc, n);
684 		if (err)
685 			return err;
686 		break;
687 	default:
688 		netdev_err(mc->netdev, "unexpected function %u\n", f);
689 		break;
690 	}
691 
692 	if ((mc->ptr + rec_len) > mc->end)
693 		return -EINVAL;
694 
695 	mc->ptr += rec_len;
696 
697 	return 0;
698 }
699 
700 /*
701  * decode data usb message
702  */
703 static int pcan_usb_decode_data(struct pcan_usb_msg_context *mc, u8 status_len)
704 {
705 	u8 rec_len = status_len & PCAN_USB_STATUSLEN_DLC;
706 	struct sk_buff *skb;
707 	struct can_frame *cf;
708 	struct skb_shared_hwtstamps *hwts;
709 
710 	skb = alloc_can_skb(mc->netdev, &cf);
711 	if (!skb)
712 		return -ENOMEM;
713 
714 	if (status_len & PCAN_USB_STATUSLEN_EXT_ID) {
715 		if ((mc->ptr + 4) > mc->end)
716 			goto decode_failed;
717 
718 		cf->can_id = get_unaligned_le32(mc->ptr) >> 3 | CAN_EFF_FLAG;
719 		mc->ptr += 4;
720 	} else {
721 		if ((mc->ptr + 2) > mc->end)
722 			goto decode_failed;
723 
724 		cf->can_id = get_unaligned_le16(mc->ptr) >> 5;
725 		mc->ptr += 2;
726 	}
727 
728 	can_frame_set_cc_len(cf, rec_len, mc->pdev->dev.can.ctrlmode);
729 
730 	/* Only first packet timestamp is a word */
731 	if (pcan_usb_decode_ts(mc, !mc->rec_ts_idx))
732 		goto decode_failed;
733 
734 	/* Next packet in the buffer will have a timestamp on a single byte */
735 	mc->rec_ts_idx++;
736 
737 	/* read data */
738 	memset(cf->data, 0x0, sizeof(cf->data));
739 	if (status_len & PCAN_USB_STATUSLEN_RTR) {
740 		cf->can_id |= CAN_RTR_FLAG;
741 	} else {
742 		if ((mc->ptr + rec_len) > mc->end)
743 			goto decode_failed;
744 
745 		memcpy(cf->data, mc->ptr, cf->len);
746 		mc->ptr += rec_len;
747 	}
748 
749 	/* convert timestamp into kernel time */
750 	hwts = skb_hwtstamps(skb);
751 	peak_usb_get_ts_time(&mc->pdev->time_ref, mc->ts16, &hwts->hwtstamp);
752 
753 	/* update statistics */
754 	mc->netdev->stats.rx_packets++;
755 	mc->netdev->stats.rx_bytes += cf->len;
756 	/* push the skb */
757 	netif_rx(skb);
758 
759 	return 0;
760 
761 decode_failed:
762 	dev_kfree_skb(skb);
763 	return -EINVAL;
764 }
765 
766 /*
767  * process incoming message
768  */
769 static int pcan_usb_decode_msg(struct peak_usb_device *dev, u8 *ibuf, u32 lbuf)
770 {
771 	struct pcan_usb_msg_context mc = {
772 		.rec_cnt = ibuf[1],
773 		.ptr = ibuf + PCAN_USB_MSG_HEADER_LEN,
774 		.end = ibuf + lbuf,
775 		.netdev = dev->netdev,
776 		.pdev = container_of(dev, struct pcan_usb, dev),
777 	};
778 	int err;
779 
780 	for (err = 0; mc.rec_idx < mc.rec_cnt && !err; mc.rec_idx++) {
781 		u8 sl = *mc.ptr++;
782 
783 		/* handle status and error frames here */
784 		if (sl & PCAN_USB_STATUSLEN_INTERNAL) {
785 			err = pcan_usb_decode_status(&mc, sl);
786 		/* handle normal can frames here */
787 		} else {
788 			err = pcan_usb_decode_data(&mc, sl);
789 		}
790 	}
791 
792 	return err;
793 }
794 
795 /*
796  * process any incoming buffer
797  */
798 static int pcan_usb_decode_buf(struct peak_usb_device *dev, struct urb *urb)
799 {
800 	int err = 0;
801 
802 	if (urb->actual_length > PCAN_USB_MSG_HEADER_LEN) {
803 		err = pcan_usb_decode_msg(dev, urb->transfer_buffer,
804 			urb->actual_length);
805 
806 	} else if (urb->actual_length > 0) {
807 		netdev_err(dev->netdev, "usb message length error (%u)\n",
808 			urb->actual_length);
809 		err = -EINVAL;
810 	}
811 
812 	return err;
813 }
814 
815 /*
816  * process outgoing packet
817  */
818 static int pcan_usb_encode_msg(struct peak_usb_device *dev, struct sk_buff *skb,
819 			       u8 *obuf, size_t *size)
820 {
821 	struct net_device *netdev = dev->netdev;
822 	struct net_device_stats *stats = &netdev->stats;
823 	struct can_frame *cf = (struct can_frame *)skb->data;
824 	u8 *pc;
825 
826 	obuf[0] = 2;
827 	obuf[1] = 1;
828 
829 	pc = obuf + PCAN_USB_MSG_HEADER_LEN;
830 
831 	/* status/len byte */
832 	*pc = can_get_cc_dlc(cf, dev->can.ctrlmode);
833 
834 	if (cf->can_id & CAN_RTR_FLAG)
835 		*pc |= PCAN_USB_STATUSLEN_RTR;
836 
837 	/* can id */
838 	if (cf->can_id & CAN_EFF_FLAG) {
839 		*pc |= PCAN_USB_STATUSLEN_EXT_ID;
840 		pc++;
841 
842 		put_unaligned_le32((cf->can_id & CAN_ERR_MASK) << 3, pc);
843 		pc += 4;
844 	} else {
845 		pc++;
846 
847 		put_unaligned_le16((cf->can_id & CAN_ERR_MASK) << 5, pc);
848 		pc += 2;
849 	}
850 
851 	/* can data */
852 	if (!(cf->can_id & CAN_RTR_FLAG)) {
853 		memcpy(pc, cf->data, cf->len);
854 		pc += cf->len;
855 	}
856 
857 	obuf[(*size)-1] = (u8)(stats->tx_packets & 0xff);
858 
859 	return 0;
860 }
861 
862 /* socket callback used to copy berr counters values received through USB */
863 static int pcan_usb_get_berr_counter(const struct net_device *netdev,
864 				     struct can_berr_counter *bec)
865 {
866 	struct peak_usb_device *dev = netdev_priv(netdev);
867 	struct pcan_usb *pdev = container_of(dev, struct pcan_usb, dev);
868 
869 	*bec = pdev->bec;
870 
871 	/* must return 0 */
872 	return 0;
873 }
874 
875 /*
876  * start interface
877  */
878 static int pcan_usb_start(struct peak_usb_device *dev)
879 {
880 	struct pcan_usb *pdev = container_of(dev, struct pcan_usb, dev);
881 	int err;
882 
883 	/* number of bits used in timestamps read from adapter struct */
884 	peak_usb_init_time_ref(&pdev->time_ref, &pcan_usb);
885 
886 	pdev->bec.rxerr = 0;
887 	pdev->bec.txerr = 0;
888 
889 	/* be notified on error counter changes (if requested by user) */
890 	if (dev->can.ctrlmode & CAN_CTRLMODE_BERR_REPORTING) {
891 		err = pcan_usb_set_err_frame(dev, PCAN_USB_BERR_MASK);
892 		if (err)
893 			netdev_warn(dev->netdev,
894 				    "Asking for BERR reporting error %u\n",
895 				    err);
896 	}
897 
898 	/* if revision greater than 3, can put silent mode on/off */
899 	if (dev->device_rev > 3) {
900 		err = pcan_usb_set_silent(dev,
901 				dev->can.ctrlmode & CAN_CTRLMODE_LISTENONLY);
902 		if (err)
903 			return err;
904 	}
905 
906 	return pcan_usb_set_ext_vcc(dev, 0);
907 }
908 
909 static int pcan_usb_init(struct peak_usb_device *dev)
910 {
911 	struct pcan_usb *pdev = container_of(dev, struct pcan_usb, dev);
912 	u32 serial_number;
913 	int err;
914 
915 	/* initialize a timer needed to wait for hardware restart */
916 	timer_setup(&pdev->restart_timer, pcan_usb_restart, 0);
917 
918 	/*
919 	 * explicit use of dev_xxx() instead of netdev_xxx() here:
920 	 * information displayed are related to the device itself, not
921 	 * to the canx netdevice.
922 	 */
923 	err = pcan_usb_get_serial(dev, &serial_number);
924 	if (err) {
925 		dev_err(dev->netdev->dev.parent,
926 			"unable to read %s serial number (err %d)\n",
927 			pcan_usb.name, err);
928 		return err;
929 	}
930 
931 	dev_info(dev->netdev->dev.parent,
932 		 "PEAK-System %s adapter hwrev %u serial %08X (%u channel)\n",
933 		 pcan_usb.name, dev->device_rev, serial_number,
934 		 pcan_usb.ctrl_count);
935 
936 	return 0;
937 }
938 
939 /*
940  * probe function for new PCAN-USB usb interface
941  */
942 static int pcan_usb_probe(struct usb_interface *intf)
943 {
944 	struct usb_host_interface *if_desc;
945 	int i;
946 
947 	if_desc = intf->altsetting;
948 
949 	/* check interface endpoint addresses */
950 	for (i = 0; i < if_desc->desc.bNumEndpoints; i++) {
951 		struct usb_endpoint_descriptor *ep = &if_desc->endpoint[i].desc;
952 
953 		switch (ep->bEndpointAddress) {
954 		case PCAN_USB_EP_CMDOUT:
955 		case PCAN_USB_EP_CMDIN:
956 		case PCAN_USB_EP_MSGOUT:
957 		case PCAN_USB_EP_MSGIN:
958 			break;
959 		default:
960 			return -ENODEV;
961 		}
962 	}
963 
964 	return 0;
965 }
966 
967 static int pcan_usb_set_phys_id(struct net_device *netdev,
968 				enum ethtool_phys_id_state state)
969 {
970 	struct peak_usb_device *dev = netdev_priv(netdev);
971 	int err = 0;
972 
973 	switch (state) {
974 	case ETHTOOL_ID_ACTIVE:
975 		/* call ON/OFF twice a second */
976 		return 2;
977 
978 	case ETHTOOL_ID_OFF:
979 		err = pcan_usb_set_led(dev, 0);
980 		break;
981 
982 	case ETHTOOL_ID_ON:
983 		fallthrough;
984 
985 	case ETHTOOL_ID_INACTIVE:
986 		/* restore LED default */
987 		err = pcan_usb_set_led(dev, 1);
988 		break;
989 
990 	default:
991 		break;
992 	}
993 
994 	return err;
995 }
996 
997 static const struct ethtool_ops pcan_usb_ethtool_ops = {
998 	.set_phys_id = pcan_usb_set_phys_id,
999 };
1000 
1001 /*
1002  * describe the PCAN-USB adapter
1003  */
1004 static const struct can_bittiming_const pcan_usb_const = {
1005 	.name = "pcan_usb",
1006 	.tseg1_min = 1,
1007 	.tseg1_max = 16,
1008 	.tseg2_min = 1,
1009 	.tseg2_max = 8,
1010 	.sjw_max = 4,
1011 	.brp_min = 1,
1012 	.brp_max = 64,
1013 	.brp_inc = 1,
1014 };
1015 
1016 const struct peak_usb_adapter pcan_usb = {
1017 	.name = "PCAN-USB",
1018 	.device_id = PCAN_USB_PRODUCT_ID,
1019 	.ctrl_count = 1,
1020 	.ctrlmode_supported = CAN_CTRLMODE_3_SAMPLES | CAN_CTRLMODE_LISTENONLY |
1021 			      CAN_CTRLMODE_BERR_REPORTING |
1022 			      CAN_CTRLMODE_CC_LEN8_DLC,
1023 	.clock = {
1024 		.freq = PCAN_USB_CRYSTAL_HZ / 2,
1025 	},
1026 	.bittiming_const = &pcan_usb_const,
1027 
1028 	/* size of device private data */
1029 	.sizeof_dev_private = sizeof(struct pcan_usb),
1030 
1031 	.ethtool_ops = &pcan_usb_ethtool_ops,
1032 
1033 	/* timestamps usage */
1034 	.ts_used_bits = 16,
1035 	.us_per_ts_scale = PCAN_USB_TS_US_PER_TICK, /* us=(ts*scale) */
1036 	.us_per_ts_shift = PCAN_USB_TS_DIV_SHIFTER, /*  >> shift     */
1037 
1038 	/* give here messages in/out endpoints */
1039 	.ep_msg_in = PCAN_USB_EP_MSGIN,
1040 	.ep_msg_out = {PCAN_USB_EP_MSGOUT},
1041 
1042 	/* size of rx/tx usb buffers */
1043 	.rx_buffer_size = PCAN_USB_RX_BUFFER_SIZE,
1044 	.tx_buffer_size = PCAN_USB_TX_BUFFER_SIZE,
1045 
1046 	/* device callbacks */
1047 	.intf_probe = pcan_usb_probe,
1048 	.dev_init = pcan_usb_init,
1049 	.dev_set_bus = pcan_usb_write_mode,
1050 	.dev_set_bittiming = pcan_usb_set_bittiming,
1051 	.dev_get_device_id = pcan_usb_get_device_id,
1052 	.dev_decode_buf = pcan_usb_decode_buf,
1053 	.dev_encode_msg = pcan_usb_encode_msg,
1054 	.dev_start = pcan_usb_start,
1055 	.dev_restart_async = pcan_usb_restart_async,
1056 	.do_get_berr_counter = pcan_usb_get_berr_counter,
1057 };
1058