1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * CAN driver for PEAK System PCAN-USB Pro adapter
4  * Derived from the PCAN project file driver/src/pcan_usbpro.c
5  *
6  * Copyright (C) 2003-2011 PEAK System-Technik GmbH
7  * Copyright (C) 2011-2012 Stephane Grosjean <s.grosjean@peak-system.com>
8  */
9 #include <linux/netdevice.h>
10 #include <linux/usb.h>
11 #include <linux/module.h>
12 #include <linux/ethtool.h>
13 
14 #include <linux/can.h>
15 #include <linux/can/dev.h>
16 #include <linux/can/error.h>
17 
18 #include "pcan_usb_core.h"
19 #include "pcan_usb_pro.h"
20 
21 #define PCAN_USBPRO_CHANNEL_COUNT	2
22 
23 /* PCAN-USB Pro adapter internal clock (MHz) */
24 #define PCAN_USBPRO_CRYSTAL_HZ		56000000
25 
26 /* PCAN-USB Pro command timeout (ms.) */
27 #define PCAN_USBPRO_COMMAND_TIMEOUT	1000
28 
29 /* PCAN-USB Pro rx/tx buffers size */
30 #define PCAN_USBPRO_RX_BUFFER_SIZE	1024
31 #define PCAN_USBPRO_TX_BUFFER_SIZE	64
32 
33 #define PCAN_USBPRO_MSG_HEADER_LEN	4
34 
35 /* some commands responses need to be re-submitted */
36 #define PCAN_USBPRO_RSP_SUBMIT_MAX	2
37 
38 #define PCAN_USBPRO_RTR			0x01
39 #define PCAN_USBPRO_EXT			0x02
40 #define PCAN_USBPRO_SS			0x08
41 
42 #define PCAN_USBPRO_CMD_BUFFER_SIZE	512
43 
44 /* handle device specific info used by the netdevices */
45 struct pcan_usb_pro_interface {
46 	struct peak_usb_device *dev[PCAN_USBPRO_CHANNEL_COUNT];
47 	struct peak_time_ref time_ref;
48 	int cm_ignore_count;
49 	int dev_opened_count;
50 };
51 
52 /* device information */
53 struct pcan_usb_pro_device {
54 	struct peak_usb_device dev;
55 	struct pcan_usb_pro_interface *usb_if;
56 	u32 cached_ccbt;
57 };
58 
59 /* internal structure used to handle messages sent to bulk urb */
60 struct pcan_usb_pro_msg {
61 	u8 *rec_ptr;
62 	int rec_buffer_size;
63 	int rec_buffer_len;
64 	union {
65 		__le16 *rec_cnt_rd;
66 		__le32 *rec_cnt;
67 		u8 *rec_buffer;
68 	} u;
69 };
70 
71 /* records sizes table indexed on message id. (8-bits value) */
72 static u16 pcan_usb_pro_sizeof_rec[256] = {
73 	[PCAN_USBPRO_SETBTR] = sizeof(struct pcan_usb_pro_btr),
74 	[PCAN_USBPRO_SETBUSACT] = sizeof(struct pcan_usb_pro_busact),
75 	[PCAN_USBPRO_SETSILENT] = sizeof(struct pcan_usb_pro_silent),
76 	[PCAN_USBPRO_SETFILTR] = sizeof(struct pcan_usb_pro_filter),
77 	[PCAN_USBPRO_SETTS] = sizeof(struct pcan_usb_pro_setts),
78 	[PCAN_USBPRO_GETDEVID] = sizeof(struct pcan_usb_pro_devid),
79 	[PCAN_USBPRO_SETLED] = sizeof(struct pcan_usb_pro_setled),
80 	[PCAN_USBPRO_RXMSG8] = sizeof(struct pcan_usb_pro_rxmsg),
81 	[PCAN_USBPRO_RXMSG4] = sizeof(struct pcan_usb_pro_rxmsg) - 4,
82 	[PCAN_USBPRO_RXMSG0] = sizeof(struct pcan_usb_pro_rxmsg) - 8,
83 	[PCAN_USBPRO_RXRTR] = sizeof(struct pcan_usb_pro_rxmsg) - 8,
84 	[PCAN_USBPRO_RXSTATUS] = sizeof(struct pcan_usb_pro_rxstatus),
85 	[PCAN_USBPRO_RXTS] = sizeof(struct pcan_usb_pro_rxts),
86 	[PCAN_USBPRO_TXMSG8] = sizeof(struct pcan_usb_pro_txmsg),
87 	[PCAN_USBPRO_TXMSG4] = sizeof(struct pcan_usb_pro_txmsg) - 4,
88 	[PCAN_USBPRO_TXMSG0] = sizeof(struct pcan_usb_pro_txmsg) - 8,
89 };
90 
91 /*
92  * initialize PCAN-USB Pro message data structure
93  */
94 static u8 *pcan_msg_init(struct pcan_usb_pro_msg *pm, void *buffer_addr,
95 			 int buffer_size)
96 {
97 	if (buffer_size < PCAN_USBPRO_MSG_HEADER_LEN)
98 		return NULL;
99 
100 	pm->u.rec_buffer = (u8 *)buffer_addr;
101 	pm->rec_buffer_size = pm->rec_buffer_len = buffer_size;
102 	pm->rec_ptr = pm->u.rec_buffer + PCAN_USBPRO_MSG_HEADER_LEN;
103 
104 	return pm->rec_ptr;
105 }
106 
107 static u8 *pcan_msg_init_empty(struct pcan_usb_pro_msg *pm,
108 			       void *buffer_addr, int buffer_size)
109 {
110 	u8 *pr = pcan_msg_init(pm, buffer_addr, buffer_size);
111 
112 	if (pr) {
113 		pm->rec_buffer_len = PCAN_USBPRO_MSG_HEADER_LEN;
114 		*pm->u.rec_cnt = 0;
115 	}
116 	return pr;
117 }
118 
119 /*
120  * add one record to a message being built
121  */
122 static int pcan_msg_add_rec(struct pcan_usb_pro_msg *pm, int id, ...)
123 {
124 	int len, i;
125 	u8 *pc;
126 	va_list ap;
127 
128 	va_start(ap, id);
129 
130 	pc = pm->rec_ptr + 1;
131 
132 	i = 0;
133 	switch (id) {
134 	case PCAN_USBPRO_TXMSG8:
135 		i += 4;
136 		fallthrough;
137 	case PCAN_USBPRO_TXMSG4:
138 		i += 4;
139 		fallthrough;
140 	case PCAN_USBPRO_TXMSG0:
141 		*pc++ = va_arg(ap, int);
142 		*pc++ = va_arg(ap, int);
143 		*pc++ = va_arg(ap, int);
144 		*(__le32 *)pc = cpu_to_le32(va_arg(ap, u32));
145 		pc += 4;
146 		memcpy(pc, va_arg(ap, int *), i);
147 		pc += i;
148 		break;
149 
150 	case PCAN_USBPRO_SETBTR:
151 	case PCAN_USBPRO_GETDEVID:
152 		*pc++ = va_arg(ap, int);
153 		pc += 2;
154 		*(__le32 *)pc = cpu_to_le32(va_arg(ap, u32));
155 		pc += 4;
156 		break;
157 
158 	case PCAN_USBPRO_SETFILTR:
159 	case PCAN_USBPRO_SETBUSACT:
160 	case PCAN_USBPRO_SETSILENT:
161 		*pc++ = va_arg(ap, int);
162 		*(__le16 *)pc = cpu_to_le16(va_arg(ap, int));
163 		pc += 2;
164 		break;
165 
166 	case PCAN_USBPRO_SETLED:
167 		*pc++ = va_arg(ap, int);
168 		*(__le16 *)pc = cpu_to_le16(va_arg(ap, int));
169 		pc += 2;
170 		*(__le32 *)pc = cpu_to_le32(va_arg(ap, u32));
171 		pc += 4;
172 		break;
173 
174 	case PCAN_USBPRO_SETTS:
175 		pc++;
176 		*(__le16 *)pc = cpu_to_le16(va_arg(ap, int));
177 		pc += 2;
178 		break;
179 
180 	default:
181 		pr_err("%s: %s(): unknown data type %02Xh (%d)\n",
182 			PCAN_USB_DRIVER_NAME, __func__, id, id);
183 		pc--;
184 		break;
185 	}
186 
187 	len = pc - pm->rec_ptr;
188 	if (len > 0) {
189 		le32_add_cpu(pm->u.rec_cnt, 1);
190 		*pm->rec_ptr = id;
191 
192 		pm->rec_ptr = pc;
193 		pm->rec_buffer_len += len;
194 	}
195 
196 	va_end(ap);
197 
198 	return len;
199 }
200 
201 /*
202  * send PCAN-USB Pro command synchronously
203  */
204 static int pcan_usb_pro_send_cmd(struct peak_usb_device *dev,
205 				 struct pcan_usb_pro_msg *pum)
206 {
207 	int actual_length;
208 	int err;
209 
210 	/* usb device unregistered? */
211 	if (!(dev->state & PCAN_USB_STATE_CONNECTED))
212 		return 0;
213 
214 	err = usb_bulk_msg(dev->udev,
215 		usb_sndbulkpipe(dev->udev, PCAN_USBPRO_EP_CMDOUT),
216 		pum->u.rec_buffer, pum->rec_buffer_len,
217 		&actual_length, PCAN_USBPRO_COMMAND_TIMEOUT);
218 	if (err)
219 		netdev_err(dev->netdev, "sending command failure: %d\n", err);
220 
221 	return err;
222 }
223 
224 /*
225  * wait for PCAN-USB Pro command response
226  */
227 static int pcan_usb_pro_wait_rsp(struct peak_usb_device *dev,
228 				 struct pcan_usb_pro_msg *pum)
229 {
230 	u8 req_data_type, req_channel;
231 	int actual_length;
232 	int i, err = 0;
233 
234 	/* usb device unregistered? */
235 	if (!(dev->state & PCAN_USB_STATE_CONNECTED))
236 		return 0;
237 
238 	req_data_type = pum->u.rec_buffer[4];
239 	req_channel = pum->u.rec_buffer[5];
240 
241 	*pum->u.rec_cnt = 0;
242 	for (i = 0; !err && i < PCAN_USBPRO_RSP_SUBMIT_MAX; i++) {
243 		struct pcan_usb_pro_msg rsp;
244 		union pcan_usb_pro_rec *pr;
245 		u32 r, rec_cnt;
246 		u16 rec_len;
247 		u8 *pc;
248 
249 		err = usb_bulk_msg(dev->udev,
250 			usb_rcvbulkpipe(dev->udev, PCAN_USBPRO_EP_CMDIN),
251 			pum->u.rec_buffer, pum->rec_buffer_len,
252 			&actual_length, PCAN_USBPRO_COMMAND_TIMEOUT);
253 		if (err) {
254 			netdev_err(dev->netdev, "waiting rsp error %d\n", err);
255 			break;
256 		}
257 
258 		if (actual_length == 0)
259 			continue;
260 
261 		err = -EBADMSG;
262 		if (actual_length < PCAN_USBPRO_MSG_HEADER_LEN) {
263 			netdev_err(dev->netdev,
264 				   "got abnormal too small rsp (len=%d)\n",
265 				   actual_length);
266 			break;
267 		}
268 
269 		pc = pcan_msg_init(&rsp, pum->u.rec_buffer,
270 			actual_length);
271 
272 		rec_cnt = le32_to_cpu(*rsp.u.rec_cnt);
273 
274 		/* loop on records stored into message */
275 		for (r = 0; r < rec_cnt; r++) {
276 			pr = (union pcan_usb_pro_rec *)pc;
277 			rec_len = pcan_usb_pro_sizeof_rec[pr->data_type];
278 			if (!rec_len) {
279 				netdev_err(dev->netdev,
280 					   "got unprocessed record in msg\n");
281 				pcan_dump_mem("rcvd rsp msg", pum->u.rec_buffer,
282 					      actual_length);
283 				break;
284 			}
285 
286 			/* check if response corresponds to request */
287 			if (pr->data_type != req_data_type)
288 				netdev_err(dev->netdev,
289 					   "got unwanted rsp %xh: ignored\n",
290 					   pr->data_type);
291 
292 			/* check if channel in response corresponds too */
293 			else if ((req_channel != 0xff) &&
294 				(pr->bus_act.channel != req_channel))
295 				netdev_err(dev->netdev,
296 					"got rsp %xh but on chan%u: ignored\n",
297 					req_data_type, pr->bus_act.channel);
298 
299 			/* got the response */
300 			else
301 				return 0;
302 
303 			/* otherwise, go on with next record in message */
304 			pc += rec_len;
305 		}
306 	}
307 
308 	return (i >= PCAN_USBPRO_RSP_SUBMIT_MAX) ? -ERANGE : err;
309 }
310 
311 int pcan_usb_pro_send_req(struct peak_usb_device *dev, int req_id,
312 			  int req_value, void *req_addr, int req_size)
313 {
314 	int err;
315 	u8 req_type;
316 	unsigned int p;
317 
318 	/* usb device unregistered? */
319 	if (!(dev->state & PCAN_USB_STATE_CONNECTED))
320 		return 0;
321 
322 	req_type = USB_TYPE_VENDOR | USB_RECIP_OTHER;
323 
324 	switch (req_id) {
325 	case PCAN_USBPRO_REQ_FCT:
326 		p = usb_sndctrlpipe(dev->udev, 0);
327 		break;
328 
329 	default:
330 		p = usb_rcvctrlpipe(dev->udev, 0);
331 		req_type |= USB_DIR_IN;
332 		memset(req_addr, '\0', req_size);
333 		break;
334 	}
335 
336 	err = usb_control_msg(dev->udev, p, req_id, req_type, req_value, 0,
337 			      req_addr, req_size, 2 * USB_CTRL_GET_TIMEOUT);
338 	if (err < 0) {
339 		netdev_info(dev->netdev,
340 			    "unable to request usb[type=%d value=%d] err=%d\n",
341 			    req_id, req_value, err);
342 		return err;
343 	}
344 
345 	return 0;
346 }
347 
348 static int pcan_usb_pro_set_ts(struct peak_usb_device *dev, u16 onoff)
349 {
350 	struct pcan_usb_pro_msg um;
351 
352 	pcan_msg_init_empty(&um, dev->cmd_buf, PCAN_USB_MAX_CMD_LEN);
353 	pcan_msg_add_rec(&um, PCAN_USBPRO_SETTS, onoff);
354 
355 	return pcan_usb_pro_send_cmd(dev, &um);
356 }
357 
358 static int pcan_usb_pro_set_bitrate(struct peak_usb_device *dev, u32 ccbt)
359 {
360 	struct pcan_usb_pro_device *pdev =
361 			container_of(dev, struct pcan_usb_pro_device, dev);
362 	struct pcan_usb_pro_msg um;
363 
364 	pcan_msg_init_empty(&um, dev->cmd_buf, PCAN_USB_MAX_CMD_LEN);
365 	pcan_msg_add_rec(&um, PCAN_USBPRO_SETBTR, dev->ctrl_idx, ccbt);
366 
367 	/* cache the CCBT value to reuse it before next buson */
368 	pdev->cached_ccbt = ccbt;
369 
370 	return pcan_usb_pro_send_cmd(dev, &um);
371 }
372 
373 static int pcan_usb_pro_set_bus(struct peak_usb_device *dev, u8 onoff)
374 {
375 	struct pcan_usb_pro_msg um;
376 
377 	/* if bus=on, be sure the bitrate being set before! */
378 	if (onoff) {
379 		struct pcan_usb_pro_device *pdev =
380 			     container_of(dev, struct pcan_usb_pro_device, dev);
381 
382 		pcan_usb_pro_set_bitrate(dev, pdev->cached_ccbt);
383 	}
384 
385 	pcan_msg_init_empty(&um, dev->cmd_buf, PCAN_USB_MAX_CMD_LEN);
386 	pcan_msg_add_rec(&um, PCAN_USBPRO_SETBUSACT, dev->ctrl_idx, onoff);
387 
388 	return pcan_usb_pro_send_cmd(dev, &um);
389 }
390 
391 static int pcan_usb_pro_set_silent(struct peak_usb_device *dev, u8 onoff)
392 {
393 	struct pcan_usb_pro_msg um;
394 
395 	pcan_msg_init_empty(&um, dev->cmd_buf, PCAN_USB_MAX_CMD_LEN);
396 	pcan_msg_add_rec(&um, PCAN_USBPRO_SETSILENT, dev->ctrl_idx, onoff);
397 
398 	return pcan_usb_pro_send_cmd(dev, &um);
399 }
400 
401 static int pcan_usb_pro_set_filter(struct peak_usb_device *dev, u16 filter_mode)
402 {
403 	struct pcan_usb_pro_msg um;
404 
405 	pcan_msg_init_empty(&um, dev->cmd_buf, PCAN_USB_MAX_CMD_LEN);
406 	pcan_msg_add_rec(&um, PCAN_USBPRO_SETFILTR, dev->ctrl_idx, filter_mode);
407 
408 	return pcan_usb_pro_send_cmd(dev, &um);
409 }
410 
411 static int pcan_usb_pro_set_led(struct peak_usb_device *dev, u8 mode,
412 				u32 timeout)
413 {
414 	struct pcan_usb_pro_msg um;
415 
416 	pcan_msg_init_empty(&um, dev->cmd_buf, PCAN_USB_MAX_CMD_LEN);
417 	pcan_msg_add_rec(&um, PCAN_USBPRO_SETLED, dev->ctrl_idx, mode, timeout);
418 
419 	return pcan_usb_pro_send_cmd(dev, &um);
420 }
421 
422 static int pcan_usb_pro_get_device_id(struct peak_usb_device *dev,
423 				      u32 *device_id)
424 {
425 	struct pcan_usb_pro_devid *pdn;
426 	struct pcan_usb_pro_msg um;
427 	int err;
428 	u8 *pc;
429 
430 	pc = pcan_msg_init_empty(&um, dev->cmd_buf, PCAN_USB_MAX_CMD_LEN);
431 	pcan_msg_add_rec(&um, PCAN_USBPRO_GETDEVID, dev->ctrl_idx);
432 
433 	err =  pcan_usb_pro_send_cmd(dev, &um);
434 	if (err)
435 		return err;
436 
437 	err = pcan_usb_pro_wait_rsp(dev, &um);
438 	if (err)
439 		return err;
440 
441 	pdn = (struct pcan_usb_pro_devid *)pc;
442 	*device_id = le32_to_cpu(pdn->serial_num);
443 
444 	return err;
445 }
446 
447 static int pcan_usb_pro_set_bittiming(struct peak_usb_device *dev,
448 				      struct can_bittiming *bt)
449 {
450 	u32 ccbt;
451 
452 	ccbt = (dev->can.ctrlmode & CAN_CTRLMODE_3_SAMPLES) ? 0x00800000 : 0;
453 	ccbt |= (bt->sjw - 1) << 24;
454 	ccbt |= (bt->phase_seg2 - 1) << 20;
455 	ccbt |= (bt->prop_seg + bt->phase_seg1 - 1) << 16; /* = tseg1 */
456 	ccbt |= bt->brp - 1;
457 
458 	netdev_info(dev->netdev, "setting ccbt=0x%08x\n", ccbt);
459 
460 	return pcan_usb_pro_set_bitrate(dev, ccbt);
461 }
462 
463 void pcan_usb_pro_restart_complete(struct urb *urb)
464 {
465 	/* can delete usb resources */
466 	peak_usb_async_complete(urb);
467 
468 	/* notify candev and netdev */
469 	peak_usb_restart_complete(urb->context);
470 }
471 
472 /*
473  * handle restart but in asynchronously way
474  */
475 static int pcan_usb_pro_restart_async(struct peak_usb_device *dev,
476 				      struct urb *urb, u8 *buf)
477 {
478 	struct pcan_usb_pro_msg um;
479 
480 	pcan_msg_init_empty(&um, buf, PCAN_USB_MAX_CMD_LEN);
481 	pcan_msg_add_rec(&um, PCAN_USBPRO_SETBUSACT, dev->ctrl_idx, 1);
482 
483 	usb_fill_bulk_urb(urb, dev->udev,
484 			usb_sndbulkpipe(dev->udev, PCAN_USBPRO_EP_CMDOUT),
485 			buf, PCAN_USB_MAX_CMD_LEN,
486 			pcan_usb_pro_restart_complete, dev);
487 
488 	return usb_submit_urb(urb, GFP_ATOMIC);
489 }
490 
491 static int pcan_usb_pro_drv_loaded(struct peak_usb_device *dev, int loaded)
492 {
493 	u8 *buffer;
494 	int err;
495 
496 	buffer = kzalloc(PCAN_USBPRO_FCT_DRVLD_REQ_LEN, GFP_KERNEL);
497 	if (!buffer)
498 		return -ENOMEM;
499 
500 	buffer[0] = 0;
501 	buffer[1] = !!loaded;
502 
503 	err = pcan_usb_pro_send_req(dev, PCAN_USBPRO_REQ_FCT,
504 				    PCAN_USBPRO_FCT_DRVLD, buffer,
505 				    PCAN_USBPRO_FCT_DRVLD_REQ_LEN);
506 	kfree(buffer);
507 
508 	return err;
509 }
510 
511 static inline
512 struct pcan_usb_pro_interface *pcan_usb_pro_dev_if(struct peak_usb_device *dev)
513 {
514 	struct pcan_usb_pro_device *pdev =
515 			container_of(dev, struct pcan_usb_pro_device, dev);
516 	return pdev->usb_if;
517 }
518 
519 static int pcan_usb_pro_handle_canmsg(struct pcan_usb_pro_interface *usb_if,
520 				      struct pcan_usb_pro_rxmsg *rx)
521 {
522 	const unsigned int ctrl_idx = (rx->len >> 4) & 0x0f;
523 	struct peak_usb_device *dev = usb_if->dev[ctrl_idx];
524 	struct net_device *netdev = dev->netdev;
525 	struct can_frame *can_frame;
526 	struct sk_buff *skb;
527 	struct skb_shared_hwtstamps *hwts;
528 
529 	skb = alloc_can_skb(netdev, &can_frame);
530 	if (!skb)
531 		return -ENOMEM;
532 
533 	can_frame->can_id = le32_to_cpu(rx->id);
534 	can_frame->len = rx->len & 0x0f;
535 
536 	if (rx->flags & PCAN_USBPRO_EXT)
537 		can_frame->can_id |= CAN_EFF_FLAG;
538 
539 	if (rx->flags & PCAN_USBPRO_RTR) {
540 		can_frame->can_id |= CAN_RTR_FLAG;
541 	} else {
542 		memcpy(can_frame->data, rx->data, can_frame->len);
543 
544 		netdev->stats.rx_bytes += can_frame->len;
545 	}
546 	netdev->stats.rx_packets++;
547 
548 	hwts = skb_hwtstamps(skb);
549 	peak_usb_get_ts_time(&usb_if->time_ref, le32_to_cpu(rx->ts32),
550 			     &hwts->hwtstamp);
551 
552 	netif_rx(skb);
553 
554 	return 0;
555 }
556 
557 static int pcan_usb_pro_handle_error(struct pcan_usb_pro_interface *usb_if,
558 				     struct pcan_usb_pro_rxstatus *er)
559 {
560 	const u16 raw_status = le16_to_cpu(er->status);
561 	const unsigned int ctrl_idx = (er->channel >> 4) & 0x0f;
562 	struct peak_usb_device *dev = usb_if->dev[ctrl_idx];
563 	struct net_device *netdev = dev->netdev;
564 	struct can_frame *can_frame;
565 	enum can_state new_state = CAN_STATE_ERROR_ACTIVE;
566 	u8 err_mask = 0;
567 	struct sk_buff *skb;
568 	struct skb_shared_hwtstamps *hwts;
569 
570 	/* nothing should be sent while in BUS_OFF state */
571 	if (dev->can.state == CAN_STATE_BUS_OFF)
572 		return 0;
573 
574 	if (!raw_status) {
575 		/* no error bit (back to active state) */
576 		dev->can.state = CAN_STATE_ERROR_ACTIVE;
577 		return 0;
578 	}
579 
580 	if (raw_status & (PCAN_USBPRO_STATUS_OVERRUN |
581 			  PCAN_USBPRO_STATUS_QOVERRUN)) {
582 		/* trick to bypass next comparison and process other errors */
583 		new_state = CAN_STATE_MAX;
584 	}
585 
586 	if (raw_status & PCAN_USBPRO_STATUS_BUS) {
587 		new_state = CAN_STATE_BUS_OFF;
588 	} else if (raw_status & PCAN_USBPRO_STATUS_ERROR) {
589 		u32 rx_err_cnt = (le32_to_cpu(er->err_frm) & 0x00ff0000) >> 16;
590 		u32 tx_err_cnt = (le32_to_cpu(er->err_frm) & 0xff000000) >> 24;
591 
592 		if (rx_err_cnt > 127)
593 			err_mask |= CAN_ERR_CRTL_RX_PASSIVE;
594 		else if (rx_err_cnt > 96)
595 			err_mask |= CAN_ERR_CRTL_RX_WARNING;
596 
597 		if (tx_err_cnt > 127)
598 			err_mask |= CAN_ERR_CRTL_TX_PASSIVE;
599 		else if (tx_err_cnt > 96)
600 			err_mask |= CAN_ERR_CRTL_TX_WARNING;
601 
602 		if (err_mask & (CAN_ERR_CRTL_RX_WARNING |
603 				CAN_ERR_CRTL_TX_WARNING))
604 			new_state = CAN_STATE_ERROR_WARNING;
605 		else if (err_mask & (CAN_ERR_CRTL_RX_PASSIVE |
606 				     CAN_ERR_CRTL_TX_PASSIVE))
607 			new_state = CAN_STATE_ERROR_PASSIVE;
608 	}
609 
610 	/* donot post any error if current state didn't change */
611 	if (dev->can.state == new_state)
612 		return 0;
613 
614 	/* allocate an skb to store the error frame */
615 	skb = alloc_can_err_skb(netdev, &can_frame);
616 	if (!skb)
617 		return -ENOMEM;
618 
619 	switch (new_state) {
620 	case CAN_STATE_BUS_OFF:
621 		can_frame->can_id |= CAN_ERR_BUSOFF;
622 		dev->can.can_stats.bus_off++;
623 		can_bus_off(netdev);
624 		break;
625 
626 	case CAN_STATE_ERROR_PASSIVE:
627 		can_frame->can_id |= CAN_ERR_CRTL;
628 		can_frame->data[1] |= err_mask;
629 		dev->can.can_stats.error_passive++;
630 		break;
631 
632 	case CAN_STATE_ERROR_WARNING:
633 		can_frame->can_id |= CAN_ERR_CRTL;
634 		can_frame->data[1] |= err_mask;
635 		dev->can.can_stats.error_warning++;
636 		break;
637 
638 	case CAN_STATE_ERROR_ACTIVE:
639 		break;
640 
641 	default:
642 		/* CAN_STATE_MAX (trick to handle other errors) */
643 		if (raw_status & PCAN_USBPRO_STATUS_OVERRUN) {
644 			can_frame->can_id |= CAN_ERR_PROT;
645 			can_frame->data[2] |= CAN_ERR_PROT_OVERLOAD;
646 			netdev->stats.rx_over_errors++;
647 			netdev->stats.rx_errors++;
648 		}
649 
650 		if (raw_status & PCAN_USBPRO_STATUS_QOVERRUN) {
651 			can_frame->can_id |= CAN_ERR_CRTL;
652 			can_frame->data[1] |= CAN_ERR_CRTL_RX_OVERFLOW;
653 			netdev->stats.rx_over_errors++;
654 			netdev->stats.rx_errors++;
655 		}
656 
657 		new_state = CAN_STATE_ERROR_ACTIVE;
658 		break;
659 	}
660 
661 	dev->can.state = new_state;
662 
663 	hwts = skb_hwtstamps(skb);
664 	peak_usb_get_ts_time(&usb_if->time_ref, le32_to_cpu(er->ts32), &hwts->hwtstamp);
665 	netif_rx(skb);
666 
667 	return 0;
668 }
669 
670 static void pcan_usb_pro_handle_ts(struct pcan_usb_pro_interface *usb_if,
671 				   struct pcan_usb_pro_rxts *ts)
672 {
673 	/* should wait until clock is stabilized */
674 	if (usb_if->cm_ignore_count > 0)
675 		usb_if->cm_ignore_count--;
676 	else
677 		peak_usb_set_ts_now(&usb_if->time_ref,
678 				    le32_to_cpu(ts->ts64[1]));
679 }
680 
681 /*
682  * callback for bulk IN urb
683  */
684 static int pcan_usb_pro_decode_buf(struct peak_usb_device *dev, struct urb *urb)
685 {
686 	struct pcan_usb_pro_interface *usb_if = pcan_usb_pro_dev_if(dev);
687 	struct net_device *netdev = dev->netdev;
688 	struct pcan_usb_pro_msg usb_msg;
689 	u8 *rec_ptr, *msg_end;
690 	u16 rec_cnt;
691 	int err = 0;
692 
693 	rec_ptr = pcan_msg_init(&usb_msg, urb->transfer_buffer,
694 					urb->actual_length);
695 	if (!rec_ptr) {
696 		netdev_err(netdev, "bad msg hdr len %d\n", urb->actual_length);
697 		return -EINVAL;
698 	}
699 
700 	/* loop reading all the records from the incoming message */
701 	msg_end = urb->transfer_buffer + urb->actual_length;
702 	rec_cnt = le16_to_cpu(*usb_msg.u.rec_cnt_rd);
703 	for (; rec_cnt > 0; rec_cnt--) {
704 		union pcan_usb_pro_rec *pr = (union pcan_usb_pro_rec *)rec_ptr;
705 		u16 sizeof_rec = pcan_usb_pro_sizeof_rec[pr->data_type];
706 
707 		if (!sizeof_rec) {
708 			netdev_err(netdev,
709 				   "got unsupported rec in usb msg:\n");
710 			err = -ENOTSUPP;
711 			break;
712 		}
713 
714 		/* check if the record goes out of current packet */
715 		if (rec_ptr + sizeof_rec > msg_end) {
716 			netdev_err(netdev,
717 				"got frag rec: should inc usb rx buf size\n");
718 			err = -EBADMSG;
719 			break;
720 		}
721 
722 		switch (pr->data_type) {
723 		case PCAN_USBPRO_RXMSG8:
724 		case PCAN_USBPRO_RXMSG4:
725 		case PCAN_USBPRO_RXMSG0:
726 		case PCAN_USBPRO_RXRTR:
727 			err = pcan_usb_pro_handle_canmsg(usb_if, &pr->rx_msg);
728 			if (err < 0)
729 				goto fail;
730 			break;
731 
732 		case PCAN_USBPRO_RXSTATUS:
733 			err = pcan_usb_pro_handle_error(usb_if, &pr->rx_status);
734 			if (err < 0)
735 				goto fail;
736 			break;
737 
738 		case PCAN_USBPRO_RXTS:
739 			pcan_usb_pro_handle_ts(usb_if, &pr->rx_ts);
740 			break;
741 
742 		default:
743 			netdev_err(netdev,
744 				   "unhandled rec type 0x%02x (%d): ignored\n",
745 				   pr->data_type, pr->data_type);
746 			break;
747 		}
748 
749 		rec_ptr += sizeof_rec;
750 	}
751 
752 fail:
753 	if (err)
754 		pcan_dump_mem("received msg",
755 			      urb->transfer_buffer, urb->actual_length);
756 
757 	return err;
758 }
759 
760 static int pcan_usb_pro_encode_msg(struct peak_usb_device *dev,
761 				   struct sk_buff *skb, u8 *obuf, size_t *size)
762 {
763 	struct can_frame *cf = (struct can_frame *)skb->data;
764 	u8 data_type, len, flags;
765 	struct pcan_usb_pro_msg usb_msg;
766 
767 	pcan_msg_init_empty(&usb_msg, obuf, *size);
768 
769 	if ((cf->can_id & CAN_RTR_FLAG) || (cf->len == 0))
770 		data_type = PCAN_USBPRO_TXMSG0;
771 	else if (cf->len <= 4)
772 		data_type = PCAN_USBPRO_TXMSG4;
773 	else
774 		data_type = PCAN_USBPRO_TXMSG8;
775 
776 	len = (dev->ctrl_idx << 4) | (cf->len & 0x0f);
777 
778 	flags = 0;
779 	if (cf->can_id & CAN_EFF_FLAG)
780 		flags |= PCAN_USBPRO_EXT;
781 	if (cf->can_id & CAN_RTR_FLAG)
782 		flags |= PCAN_USBPRO_RTR;
783 
784 	/* Single-Shot frame */
785 	if (dev->can.ctrlmode & CAN_CTRLMODE_ONE_SHOT)
786 		flags |= PCAN_USBPRO_SS;
787 
788 	pcan_msg_add_rec(&usb_msg, data_type, 0, flags, len, cf->can_id,
789 			 cf->data);
790 
791 	*size = usb_msg.rec_buffer_len;
792 
793 	return 0;
794 }
795 
796 static int pcan_usb_pro_start(struct peak_usb_device *dev)
797 {
798 	struct pcan_usb_pro_device *pdev =
799 			container_of(dev, struct pcan_usb_pro_device, dev);
800 	int err;
801 
802 	err = pcan_usb_pro_set_silent(dev,
803 				dev->can.ctrlmode & CAN_CTRLMODE_LISTENONLY);
804 	if (err)
805 		return err;
806 
807 	/* filter mode: 0-> All OFF; 1->bypass */
808 	err = pcan_usb_pro_set_filter(dev, 1);
809 	if (err)
810 		return err;
811 
812 	/* opening first device: */
813 	if (pdev->usb_if->dev_opened_count == 0) {
814 		/* reset time_ref */
815 		peak_usb_init_time_ref(&pdev->usb_if->time_ref, &pcan_usb_pro);
816 
817 		/* ask device to send ts messages */
818 		err = pcan_usb_pro_set_ts(dev, 1);
819 	}
820 
821 	pdev->usb_if->dev_opened_count++;
822 
823 	return err;
824 }
825 
826 /*
827  * stop interface
828  * (last chance before set bus off)
829  */
830 static int pcan_usb_pro_stop(struct peak_usb_device *dev)
831 {
832 	struct pcan_usb_pro_device *pdev =
833 			container_of(dev, struct pcan_usb_pro_device, dev);
834 
835 	/* turn off ts msgs for that interface if no other dev opened */
836 	if (pdev->usb_if->dev_opened_count == 1)
837 		pcan_usb_pro_set_ts(dev, 0);
838 
839 	pdev->usb_if->dev_opened_count--;
840 
841 	return 0;
842 }
843 
844 /*
845  * called when probing to initialize a device object.
846  */
847 static int pcan_usb_pro_init(struct peak_usb_device *dev)
848 {
849 	struct pcan_usb_pro_device *pdev =
850 			container_of(dev, struct pcan_usb_pro_device, dev);
851 	struct pcan_usb_pro_interface *usb_if = NULL;
852 	struct pcan_usb_pro_fwinfo *fi = NULL;
853 	struct pcan_usb_pro_blinfo *bi = NULL;
854 	int err;
855 
856 	/* do this for 1st channel only */
857 	if (!dev->prev_siblings) {
858 		/* allocate netdevices common structure attached to first one */
859 		usb_if = kzalloc(sizeof(struct pcan_usb_pro_interface),
860 				 GFP_KERNEL);
861 		fi = kmalloc(sizeof(struct pcan_usb_pro_fwinfo), GFP_KERNEL);
862 		bi = kmalloc(sizeof(struct pcan_usb_pro_blinfo), GFP_KERNEL);
863 		if (!usb_if || !fi || !bi) {
864 			err = -ENOMEM;
865 			goto err_out;
866 		}
867 
868 		/* number of ts msgs to ignore before taking one into account */
869 		usb_if->cm_ignore_count = 5;
870 
871 		/*
872 		 * explicit use of dev_xxx() instead of netdev_xxx() here:
873 		 * information displayed are related to the device itself, not
874 		 * to the canx netdevices.
875 		 */
876 		err = pcan_usb_pro_send_req(dev, PCAN_USBPRO_REQ_INFO,
877 					    PCAN_USBPRO_INFO_FW,
878 					    fi, sizeof(*fi));
879 		if (err) {
880 			dev_err(dev->netdev->dev.parent,
881 				"unable to read %s firmware info (err %d)\n",
882 				pcan_usb_pro.name, err);
883 			goto err_out;
884 		}
885 
886 		err = pcan_usb_pro_send_req(dev, PCAN_USBPRO_REQ_INFO,
887 					    PCAN_USBPRO_INFO_BL,
888 					    bi, sizeof(*bi));
889 		if (err) {
890 			dev_err(dev->netdev->dev.parent,
891 				"unable to read %s bootloader info (err %d)\n",
892 				pcan_usb_pro.name, err);
893 			goto err_out;
894 		}
895 
896 		/* tell the device the can driver is running */
897 		err = pcan_usb_pro_drv_loaded(dev, 1);
898 		if (err)
899 			goto err_out;
900 
901 		dev_info(dev->netdev->dev.parent,
902 		     "PEAK-System %s hwrev %u serial %08X.%08X (%u channels)\n",
903 		     pcan_usb_pro.name,
904 		     bi->hw_rev, bi->serial_num_hi, bi->serial_num_lo,
905 		     pcan_usb_pro.ctrl_count);
906 	} else {
907 		usb_if = pcan_usb_pro_dev_if(dev->prev_siblings);
908 	}
909 
910 	pdev->usb_if = usb_if;
911 	usb_if->dev[dev->ctrl_idx] = dev;
912 
913 	/* set LED in default state (end of init phase) */
914 	pcan_usb_pro_set_led(dev, PCAN_USBPRO_LED_DEVICE, 1);
915 
916 	kfree(bi);
917 	kfree(fi);
918 
919 	return 0;
920 
921  err_out:
922 	kfree(bi);
923 	kfree(fi);
924 	kfree(usb_if);
925 
926 	return err;
927 }
928 
929 static void pcan_usb_pro_exit(struct peak_usb_device *dev)
930 {
931 	struct pcan_usb_pro_device *pdev =
932 			container_of(dev, struct pcan_usb_pro_device, dev);
933 
934 	/*
935 	 * when rmmod called before unplug and if down, should reset things
936 	 * before leaving
937 	 */
938 	if (dev->can.state != CAN_STATE_STOPPED) {
939 		/* set bus off on the corresponding channel */
940 		pcan_usb_pro_set_bus(dev, 0);
941 	}
942 
943 	/* if channel #0 (only) */
944 	if (dev->ctrl_idx == 0) {
945 		/* turn off calibration message if any device were opened */
946 		if (pdev->usb_if->dev_opened_count > 0)
947 			pcan_usb_pro_set_ts(dev, 0);
948 
949 		/* tell the PCAN-USB Pro device the driver is being unloaded */
950 		pcan_usb_pro_drv_loaded(dev, 0);
951 	}
952 }
953 
954 /*
955  * called when PCAN-USB Pro adapter is unplugged
956  */
957 static void pcan_usb_pro_free(struct peak_usb_device *dev)
958 {
959 	/* last device: can free pcan_usb_pro_interface object now */
960 	if (!dev->prev_siblings && !dev->next_siblings)
961 		kfree(pcan_usb_pro_dev_if(dev));
962 }
963 
964 /*
965  * probe function for new PCAN-USB Pro usb interface
966  */
967 int pcan_usb_pro_probe(struct usb_interface *intf)
968 {
969 	struct usb_host_interface *if_desc;
970 	int i;
971 
972 	if_desc = intf->altsetting;
973 
974 	/* check interface endpoint addresses */
975 	for (i = 0; i < if_desc->desc.bNumEndpoints; i++) {
976 		struct usb_endpoint_descriptor *ep = &if_desc->endpoint[i].desc;
977 
978 		/*
979 		 * below is the list of valid ep addresses. Any other ep address
980 		 * is considered as not-CAN interface address => no dev created
981 		 */
982 		switch (ep->bEndpointAddress) {
983 		case PCAN_USBPRO_EP_CMDOUT:
984 		case PCAN_USBPRO_EP_CMDIN:
985 		case PCAN_USBPRO_EP_MSGOUT_0:
986 		case PCAN_USBPRO_EP_MSGOUT_1:
987 		case PCAN_USBPRO_EP_MSGIN:
988 		case PCAN_USBPRO_EP_UNUSED:
989 			break;
990 		default:
991 			return -ENODEV;
992 		}
993 	}
994 
995 	return 0;
996 }
997 
998 static int pcan_usb_pro_set_phys_id(struct net_device *netdev,
999 				    enum ethtool_phys_id_state state)
1000 {
1001 	struct peak_usb_device *dev = netdev_priv(netdev);
1002 	int err = 0;
1003 
1004 	switch (state) {
1005 	case ETHTOOL_ID_ACTIVE:
1006 		/* fast blinking forever */
1007 		err = pcan_usb_pro_set_led(dev, PCAN_USBPRO_LED_BLINK_FAST,
1008 					   0xffffffff);
1009 		break;
1010 
1011 	case ETHTOOL_ID_INACTIVE:
1012 		/* restore LED default */
1013 		err = pcan_usb_pro_set_led(dev, PCAN_USBPRO_LED_DEVICE, 1);
1014 		break;
1015 
1016 	default:
1017 		break;
1018 	}
1019 
1020 	return err;
1021 }
1022 
1023 static const struct ethtool_ops pcan_usb_pro_ethtool_ops = {
1024 	.set_phys_id = pcan_usb_pro_set_phys_id,
1025 };
1026 
1027 /*
1028  * describe the PCAN-USB Pro adapter
1029  */
1030 static const struct can_bittiming_const pcan_usb_pro_const = {
1031 	.name = "pcan_usb_pro",
1032 	.tseg1_min = 1,
1033 	.tseg1_max = 16,
1034 	.tseg2_min = 1,
1035 	.tseg2_max = 8,
1036 	.sjw_max = 4,
1037 	.brp_min = 1,
1038 	.brp_max = 1024,
1039 	.brp_inc = 1,
1040 };
1041 
1042 const struct peak_usb_adapter pcan_usb_pro = {
1043 	.name = "PCAN-USB Pro",
1044 	.device_id = PCAN_USBPRO_PRODUCT_ID,
1045 	.ctrl_count = PCAN_USBPRO_CHANNEL_COUNT,
1046 	.ctrlmode_supported = CAN_CTRLMODE_3_SAMPLES | CAN_CTRLMODE_LISTENONLY |
1047 			      CAN_CTRLMODE_ONE_SHOT,
1048 	.clock = {
1049 		.freq = PCAN_USBPRO_CRYSTAL_HZ,
1050 	},
1051 	.bittiming_const = &pcan_usb_pro_const,
1052 
1053 	/* size of device private data */
1054 	.sizeof_dev_private = sizeof(struct pcan_usb_pro_device),
1055 
1056 	.ethtool_ops = &pcan_usb_pro_ethtool_ops,
1057 
1058 	/* timestamps usage */
1059 	.ts_used_bits = 32,
1060 	.us_per_ts_scale = 1, /* us = (ts * scale) >> shift */
1061 	.us_per_ts_shift = 0,
1062 
1063 	/* give here messages in/out endpoints */
1064 	.ep_msg_in = PCAN_USBPRO_EP_MSGIN,
1065 	.ep_msg_out = {PCAN_USBPRO_EP_MSGOUT_0, PCAN_USBPRO_EP_MSGOUT_1},
1066 
1067 	/* size of rx/tx usb buffers */
1068 	.rx_buffer_size = PCAN_USBPRO_RX_BUFFER_SIZE,
1069 	.tx_buffer_size = PCAN_USBPRO_TX_BUFFER_SIZE,
1070 
1071 	/* device callbacks */
1072 	.intf_probe = pcan_usb_pro_probe,
1073 	.dev_init = pcan_usb_pro_init,
1074 	.dev_exit = pcan_usb_pro_exit,
1075 	.dev_free = pcan_usb_pro_free,
1076 	.dev_set_bus = pcan_usb_pro_set_bus,
1077 	.dev_set_bittiming = pcan_usb_pro_set_bittiming,
1078 	.dev_get_device_id = pcan_usb_pro_get_device_id,
1079 	.dev_decode_buf = pcan_usb_pro_decode_buf,
1080 	.dev_encode_msg = pcan_usb_pro_encode_msg,
1081 	.dev_start = pcan_usb_pro_start,
1082 	.dev_stop = pcan_usb_pro_stop,
1083 	.dev_restart_async = pcan_usb_pro_restart_async,
1084 };
1085