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