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