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