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