xref: /linux/drivers/net/can/usb/peak_usb/pcan_usb_pro.c (revision 95298d63c67673c654c08952672d016212b26054)
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 
13 #include <linux/can.h>
14 #include <linux/can/dev.h>
15 #include <linux/can/error.h>
16 
17 #include "pcan_usb_core.h"
18 #include "pcan_usb_pro.h"
19 
20 MODULE_SUPPORTED_DEVICE("PEAK-System PCAN-USB Pro adapter");
21 
22 #define PCAN_USBPRO_CHANNEL_COUNT	2
23 
24 /* PCAN-USB Pro adapter internal clock (MHz) */
25 #define PCAN_USBPRO_CRYSTAL_HZ		56000000
26 
27 /* PCAN-USB Pro command timeout (ms.) */
28 #define PCAN_USBPRO_COMMAND_TIMEOUT	1000
29 
30 /* PCAN-USB Pro rx/tx buffers size */
31 #define PCAN_USBPRO_RX_BUFFER_SIZE	1024
32 #define PCAN_USBPRO_TX_BUFFER_SIZE	64
33 
34 #define PCAN_USBPRO_MSG_HEADER_LEN	4
35 
36 /* some commands responses need to be re-submitted */
37 #define PCAN_USBPRO_RSP_SUBMIT_MAX	2
38 
39 #define PCAN_USBPRO_RTR			0x01
40 #define PCAN_USBPRO_EXT			0x02
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 		/* fall through */
137 	case PCAN_USBPRO_TXMSG4:
138 		i += 4;
139 		/* fall through */
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 		*pm->u.rec_cnt = cpu_to_le32(le32_to_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 	if (device_id)
443 		*device_id = le32_to_cpu(pdn->serial_num);
444 
445 	return err;
446 }
447 
448 static int pcan_usb_pro_set_bittiming(struct peak_usb_device *dev,
449 				      struct can_bittiming *bt)
450 {
451 	u32 ccbt;
452 
453 	ccbt = (dev->can.ctrlmode & CAN_CTRLMODE_3_SAMPLES) ? 0x00800000 : 0;
454 	ccbt |= (bt->sjw - 1) << 24;
455 	ccbt |= (bt->phase_seg2 - 1) << 20;
456 	ccbt |= (bt->prop_seg + bt->phase_seg1 - 1) << 16; /* = tseg1 */
457 	ccbt |= bt->brp - 1;
458 
459 	netdev_info(dev->netdev, "setting ccbt=0x%08x\n", ccbt);
460 
461 	return pcan_usb_pro_set_bitrate(dev, ccbt);
462 }
463 
464 void pcan_usb_pro_restart_complete(struct urb *urb)
465 {
466 	/* can delete usb resources */
467 	peak_usb_async_complete(urb);
468 
469 	/* notify candev and netdev */
470 	peak_usb_restart_complete(urb->context);
471 }
472 
473 /*
474  * handle restart but in asynchronously way
475  */
476 static int pcan_usb_pro_restart_async(struct peak_usb_device *dev,
477 				      struct urb *urb, u8 *buf)
478 {
479 	struct pcan_usb_pro_msg um;
480 
481 	pcan_msg_init_empty(&um, buf, PCAN_USB_MAX_CMD_LEN);
482 	pcan_msg_add_rec(&um, PCAN_USBPRO_SETBUSACT, dev->ctrl_idx, 1);
483 
484 	usb_fill_bulk_urb(urb, dev->udev,
485 			usb_sndbulkpipe(dev->udev, PCAN_USBPRO_EP_CMDOUT),
486 			buf, PCAN_USB_MAX_CMD_LEN,
487 			pcan_usb_pro_restart_complete, dev);
488 
489 	return usb_submit_urb(urb, GFP_ATOMIC);
490 }
491 
492 static int pcan_usb_pro_drv_loaded(struct peak_usb_device *dev, int loaded)
493 {
494 	u8 *buffer;
495 	int err;
496 
497 	buffer = kzalloc(PCAN_USBPRO_FCT_DRVLD_REQ_LEN, GFP_KERNEL);
498 	if (!buffer)
499 		return -ENOMEM;
500 
501 	buffer[0] = 0;
502 	buffer[1] = !!loaded;
503 
504 	err = pcan_usb_pro_send_req(dev, PCAN_USBPRO_REQ_FCT,
505 				    PCAN_USBPRO_FCT_DRVLD, buffer,
506 				    PCAN_USBPRO_FCT_DRVLD_REQ_LEN);
507 	kfree(buffer);
508 
509 	return err;
510 }
511 
512 static inline
513 struct pcan_usb_pro_interface *pcan_usb_pro_dev_if(struct peak_usb_device *dev)
514 {
515 	struct pcan_usb_pro_device *pdev =
516 			container_of(dev, struct pcan_usb_pro_device, dev);
517 	return pdev->usb_if;
518 }
519 
520 static int pcan_usb_pro_handle_canmsg(struct pcan_usb_pro_interface *usb_if,
521 				      struct pcan_usb_pro_rxmsg *rx)
522 {
523 	const unsigned int ctrl_idx = (rx->len >> 4) & 0x0f;
524 	struct peak_usb_device *dev = usb_if->dev[ctrl_idx];
525 	struct net_device *netdev = dev->netdev;
526 	struct can_frame *can_frame;
527 	struct sk_buff *skb;
528 	struct skb_shared_hwtstamps *hwts;
529 
530 	skb = alloc_can_skb(netdev, &can_frame);
531 	if (!skb)
532 		return -ENOMEM;
533 
534 	can_frame->can_id = le32_to_cpu(rx->id);
535 	can_frame->can_dlc = rx->len & 0x0f;
536 
537 	if (rx->flags & PCAN_USBPRO_EXT)
538 		can_frame->can_id |= CAN_EFF_FLAG;
539 
540 	if (rx->flags & PCAN_USBPRO_RTR)
541 		can_frame->can_id |= CAN_RTR_FLAG;
542 	else
543 		memcpy(can_frame->data, rx->data, can_frame->can_dlc);
544 
545 	hwts = skb_hwtstamps(skb);
546 	peak_usb_get_ts_time(&usb_if->time_ref, le32_to_cpu(rx->ts32),
547 			     &hwts->hwtstamp);
548 
549 	netdev->stats.rx_packets++;
550 	netdev->stats.rx_bytes += can_frame->can_dlc;
551 	netif_rx(skb);
552 
553 	return 0;
554 }
555 
556 static int pcan_usb_pro_handle_error(struct pcan_usb_pro_interface *usb_if,
557 				     struct pcan_usb_pro_rxstatus *er)
558 {
559 	const u16 raw_status = le16_to_cpu(er->status);
560 	const unsigned int ctrl_idx = (er->channel >> 4) & 0x0f;
561 	struct peak_usb_device *dev = usb_if->dev[ctrl_idx];
562 	struct net_device *netdev = dev->netdev;
563 	struct can_frame *can_frame;
564 	enum can_state new_state = CAN_STATE_ERROR_ACTIVE;
565 	u8 err_mask = 0;
566 	struct sk_buff *skb;
567 	struct skb_shared_hwtstamps *hwts;
568 
569 	/* nothing should be sent while in BUS_OFF state */
570 	if (dev->can.state == CAN_STATE_BUS_OFF)
571 		return 0;
572 
573 	if (!raw_status) {
574 		/* no error bit (back to active state) */
575 		dev->can.state = CAN_STATE_ERROR_ACTIVE;
576 		return 0;
577 	}
578 
579 	if (raw_status & (PCAN_USBPRO_STATUS_OVERRUN |
580 			  PCAN_USBPRO_STATUS_QOVERRUN)) {
581 		/* trick to bypass next comparison and process other errors */
582 		new_state = CAN_STATE_MAX;
583 	}
584 
585 	if (raw_status & PCAN_USBPRO_STATUS_BUS) {
586 		new_state = CAN_STATE_BUS_OFF;
587 	} else if (raw_status & PCAN_USBPRO_STATUS_ERROR) {
588 		u32 rx_err_cnt = (le32_to_cpu(er->err_frm) & 0x00ff0000) >> 16;
589 		u32 tx_err_cnt = (le32_to_cpu(er->err_frm) & 0xff000000) >> 24;
590 
591 		if (rx_err_cnt > 127)
592 			err_mask |= CAN_ERR_CRTL_RX_PASSIVE;
593 		else if (rx_err_cnt > 96)
594 			err_mask |= CAN_ERR_CRTL_RX_WARNING;
595 
596 		if (tx_err_cnt > 127)
597 			err_mask |= CAN_ERR_CRTL_TX_PASSIVE;
598 		else if (tx_err_cnt > 96)
599 			err_mask |= CAN_ERR_CRTL_TX_WARNING;
600 
601 		if (err_mask & (CAN_ERR_CRTL_RX_WARNING |
602 				CAN_ERR_CRTL_TX_WARNING))
603 			new_state = CAN_STATE_ERROR_WARNING;
604 		else if (err_mask & (CAN_ERR_CRTL_RX_PASSIVE |
605 				     CAN_ERR_CRTL_TX_PASSIVE))
606 			new_state = CAN_STATE_ERROR_PASSIVE;
607 	}
608 
609 	/* donot post any error if current state didn't change */
610 	if (dev->can.state == new_state)
611 		return 0;
612 
613 	/* allocate an skb to store the error frame */
614 	skb = alloc_can_err_skb(netdev, &can_frame);
615 	if (!skb)
616 		return -ENOMEM;
617 
618 	switch (new_state) {
619 	case CAN_STATE_BUS_OFF:
620 		can_frame->can_id |= CAN_ERR_BUSOFF;
621 		dev->can.can_stats.bus_off++;
622 		can_bus_off(netdev);
623 		break;
624 
625 	case CAN_STATE_ERROR_PASSIVE:
626 		can_frame->can_id |= CAN_ERR_CRTL;
627 		can_frame->data[1] |= err_mask;
628 		dev->can.can_stats.error_passive++;
629 		break;
630 
631 	case CAN_STATE_ERROR_WARNING:
632 		can_frame->can_id |= CAN_ERR_CRTL;
633 		can_frame->data[1] |= err_mask;
634 		dev->can.can_stats.error_warning++;
635 		break;
636 
637 	case CAN_STATE_ERROR_ACTIVE:
638 		break;
639 
640 	default:
641 		/* CAN_STATE_MAX (trick to handle other errors) */
642 		if (raw_status & PCAN_USBPRO_STATUS_OVERRUN) {
643 			can_frame->can_id |= CAN_ERR_PROT;
644 			can_frame->data[2] |= CAN_ERR_PROT_OVERLOAD;
645 			netdev->stats.rx_over_errors++;
646 			netdev->stats.rx_errors++;
647 		}
648 
649 		if (raw_status & PCAN_USBPRO_STATUS_QOVERRUN) {
650 			can_frame->can_id |= CAN_ERR_CRTL;
651 			can_frame->data[1] |= CAN_ERR_CRTL_RX_OVERFLOW;
652 			netdev->stats.rx_over_errors++;
653 			netdev->stats.rx_errors++;
654 		}
655 
656 		new_state = CAN_STATE_ERROR_ACTIVE;
657 		break;
658 	}
659 
660 	dev->can.state = new_state;
661 
662 	hwts = skb_hwtstamps(skb);
663 	peak_usb_get_ts_time(&usb_if->time_ref, le32_to_cpu(er->ts32), &hwts->hwtstamp);
664 	netdev->stats.rx_packets++;
665 	netdev->stats.rx_bytes += can_frame->can_dlc;
666 	netif_rx(skb);
667 
668 	return 0;
669 }
670 
671 static void pcan_usb_pro_handle_ts(struct pcan_usb_pro_interface *usb_if,
672 				   struct pcan_usb_pro_rxts *ts)
673 {
674 	/* should wait until clock is stabilized */
675 	if (usb_if->cm_ignore_count > 0)
676 		usb_if->cm_ignore_count--;
677 	else
678 		peak_usb_set_ts_now(&usb_if->time_ref,
679 				    le32_to_cpu(ts->ts64[1]));
680 }
681 
682 /*
683  * callback for bulk IN urb
684  */
685 static int pcan_usb_pro_decode_buf(struct peak_usb_device *dev, struct urb *urb)
686 {
687 	struct pcan_usb_pro_interface *usb_if = pcan_usb_pro_dev_if(dev);
688 	struct net_device *netdev = dev->netdev;
689 	struct pcan_usb_pro_msg usb_msg;
690 	u8 *rec_ptr, *msg_end;
691 	u16 rec_cnt;
692 	int err = 0;
693 
694 	rec_ptr = pcan_msg_init(&usb_msg, urb->transfer_buffer,
695 					urb->actual_length);
696 	if (!rec_ptr) {
697 		netdev_err(netdev, "bad msg hdr len %d\n", urb->actual_length);
698 		return -EINVAL;
699 	}
700 
701 	/* loop reading all the records from the incoming message */
702 	msg_end = urb->transfer_buffer + urb->actual_length;
703 	rec_cnt = le16_to_cpu(*usb_msg.u.rec_cnt_rd);
704 	for (; rec_cnt > 0; rec_cnt--) {
705 		union pcan_usb_pro_rec *pr = (union pcan_usb_pro_rec *)rec_ptr;
706 		u16 sizeof_rec = pcan_usb_pro_sizeof_rec[pr->data_type];
707 
708 		if (!sizeof_rec) {
709 			netdev_err(netdev,
710 				   "got unsupported rec in usb msg:\n");
711 			err = -ENOTSUPP;
712 			break;
713 		}
714 
715 		/* check if the record goes out of current packet */
716 		if (rec_ptr + sizeof_rec > msg_end) {
717 			netdev_err(netdev,
718 				"got frag rec: should inc usb rx buf size\n");
719 			err = -EBADMSG;
720 			break;
721 		}
722 
723 		switch (pr->data_type) {
724 		case PCAN_USBPRO_RXMSG8:
725 		case PCAN_USBPRO_RXMSG4:
726 		case PCAN_USBPRO_RXMSG0:
727 		case PCAN_USBPRO_RXRTR:
728 			err = pcan_usb_pro_handle_canmsg(usb_if, &pr->rx_msg);
729 			if (err < 0)
730 				goto fail;
731 			break;
732 
733 		case PCAN_USBPRO_RXSTATUS:
734 			err = pcan_usb_pro_handle_error(usb_if, &pr->rx_status);
735 			if (err < 0)
736 				goto fail;
737 			break;
738 
739 		case PCAN_USBPRO_RXTS:
740 			pcan_usb_pro_handle_ts(usb_if, &pr->rx_ts);
741 			break;
742 
743 		default:
744 			netdev_err(netdev,
745 				   "unhandled rec type 0x%02x (%d): ignored\n",
746 				   pr->data_type, pr->data_type);
747 			break;
748 		}
749 
750 		rec_ptr += sizeof_rec;
751 	}
752 
753 fail:
754 	if (err)
755 		pcan_dump_mem("received msg",
756 			      urb->transfer_buffer, urb->actual_length);
757 
758 	return err;
759 }
760 
761 static int pcan_usb_pro_encode_msg(struct peak_usb_device *dev,
762 				   struct sk_buff *skb, u8 *obuf, size_t *size)
763 {
764 	struct can_frame *cf = (struct can_frame *)skb->data;
765 	u8 data_type, len, flags;
766 	struct pcan_usb_pro_msg usb_msg;
767 
768 	pcan_msg_init_empty(&usb_msg, obuf, *size);
769 
770 	if ((cf->can_id & CAN_RTR_FLAG) || (cf->can_dlc == 0))
771 		data_type = PCAN_USBPRO_TXMSG0;
772 	else if (cf->can_dlc <= 4)
773 		data_type = PCAN_USBPRO_TXMSG4;
774 	else
775 		data_type = PCAN_USBPRO_TXMSG8;
776 
777 	len = (dev->ctrl_idx << 4) | (cf->can_dlc & 0x0f);
778 
779 	flags = 0;
780 	if (cf->can_id & CAN_EFF_FLAG)
781 		flags |= 0x02;
782 	if (cf->can_id & CAN_RTR_FLAG)
783 		flags |= 0x01;
784 
785 	pcan_msg_add_rec(&usb_msg, data_type, 0, flags, len, cf->can_id,
786 			 cf->data);
787 
788 	*size = usb_msg.rec_buffer_len;
789 
790 	return 0;
791 }
792 
793 static int pcan_usb_pro_start(struct peak_usb_device *dev)
794 {
795 	struct pcan_usb_pro_device *pdev =
796 			container_of(dev, struct pcan_usb_pro_device, dev);
797 	int err;
798 
799 	err = pcan_usb_pro_set_silent(dev,
800 				dev->can.ctrlmode & CAN_CTRLMODE_LISTENONLY);
801 	if (err)
802 		return err;
803 
804 	/* filter mode: 0-> All OFF; 1->bypass */
805 	err = pcan_usb_pro_set_filter(dev, 1);
806 	if (err)
807 		return err;
808 
809 	/* opening first device: */
810 	if (pdev->usb_if->dev_opened_count == 0) {
811 		/* reset time_ref */
812 		peak_usb_init_time_ref(&pdev->usb_if->time_ref, &pcan_usb_pro);
813 
814 		/* ask device to send ts messages */
815 		err = pcan_usb_pro_set_ts(dev, 1);
816 	}
817 
818 	pdev->usb_if->dev_opened_count++;
819 
820 	return err;
821 }
822 
823 /*
824  * stop interface
825  * (last chance before set bus off)
826  */
827 static int pcan_usb_pro_stop(struct peak_usb_device *dev)
828 {
829 	struct pcan_usb_pro_device *pdev =
830 			container_of(dev, struct pcan_usb_pro_device, dev);
831 
832 	/* turn off ts msgs for that interface if no other dev opened */
833 	if (pdev->usb_if->dev_opened_count == 1)
834 		pcan_usb_pro_set_ts(dev, 0);
835 
836 	pdev->usb_if->dev_opened_count--;
837 
838 	return 0;
839 }
840 
841 /*
842  * called when probing to initialize a device object.
843  */
844 static int pcan_usb_pro_init(struct peak_usb_device *dev)
845 {
846 	struct pcan_usb_pro_device *pdev =
847 			container_of(dev, struct pcan_usb_pro_device, dev);
848 	struct pcan_usb_pro_interface *usb_if = NULL;
849 	struct pcan_usb_pro_fwinfo *fi = NULL;
850 	struct pcan_usb_pro_blinfo *bi = NULL;
851 	int err;
852 
853 	/* do this for 1st channel only */
854 	if (!dev->prev_siblings) {
855 		/* allocate netdevices common structure attached to first one */
856 		usb_if = kzalloc(sizeof(struct pcan_usb_pro_interface),
857 				 GFP_KERNEL);
858 		fi = kmalloc(sizeof(struct pcan_usb_pro_fwinfo), GFP_KERNEL);
859 		bi = kmalloc(sizeof(struct pcan_usb_pro_blinfo), GFP_KERNEL);
860 		if (!usb_if || !fi || !bi) {
861 			err = -ENOMEM;
862 			goto err_out;
863 		}
864 
865 		/* number of ts msgs to ignore before taking one into account */
866 		usb_if->cm_ignore_count = 5;
867 
868 		/*
869 		 * explicit use of dev_xxx() instead of netdev_xxx() here:
870 		 * information displayed are related to the device itself, not
871 		 * to the canx netdevices.
872 		 */
873 		err = pcan_usb_pro_send_req(dev, PCAN_USBPRO_REQ_INFO,
874 					    PCAN_USBPRO_INFO_FW,
875 					    fi, sizeof(*fi));
876 		if (err) {
877 			dev_err(dev->netdev->dev.parent,
878 				"unable to read %s firmware info (err %d)\n",
879 				pcan_usb_pro.name, err);
880 			goto err_out;
881 		}
882 
883 		err = pcan_usb_pro_send_req(dev, PCAN_USBPRO_REQ_INFO,
884 					    PCAN_USBPRO_INFO_BL,
885 					    bi, sizeof(*bi));
886 		if (err) {
887 			dev_err(dev->netdev->dev.parent,
888 				"unable to read %s bootloader info (err %d)\n",
889 				pcan_usb_pro.name, err);
890 			goto err_out;
891 		}
892 
893 		/* tell the device the can driver is running */
894 		err = pcan_usb_pro_drv_loaded(dev, 1);
895 		if (err)
896 			goto err_out;
897 
898 		dev_info(dev->netdev->dev.parent,
899 		     "PEAK-System %s hwrev %u serial %08X.%08X (%u channels)\n",
900 		     pcan_usb_pro.name,
901 		     bi->hw_rev, bi->serial_num_hi, bi->serial_num_lo,
902 		     pcan_usb_pro.ctrl_count);
903 	} else {
904 		usb_if = pcan_usb_pro_dev_if(dev->prev_siblings);
905 	}
906 
907 	pdev->usb_if = usb_if;
908 	usb_if->dev[dev->ctrl_idx] = dev;
909 
910 	/* set LED in default state (end of init phase) */
911 	pcan_usb_pro_set_led(dev, 0, 1);
912 
913 	kfree(bi);
914 	kfree(fi);
915 
916 	return 0;
917 
918  err_out:
919 	kfree(bi);
920 	kfree(fi);
921 	kfree(usb_if);
922 
923 	return err;
924 }
925 
926 static void pcan_usb_pro_exit(struct peak_usb_device *dev)
927 {
928 	struct pcan_usb_pro_device *pdev =
929 			container_of(dev, struct pcan_usb_pro_device, dev);
930 
931 	/*
932 	 * when rmmod called before unplug and if down, should reset things
933 	 * before leaving
934 	 */
935 	if (dev->can.state != CAN_STATE_STOPPED) {
936 		/* set bus off on the corresponding channel */
937 		pcan_usb_pro_set_bus(dev, 0);
938 	}
939 
940 	/* if channel #0 (only) */
941 	if (dev->ctrl_idx == 0) {
942 		/* turn off calibration message if any device were opened */
943 		if (pdev->usb_if->dev_opened_count > 0)
944 			pcan_usb_pro_set_ts(dev, 0);
945 
946 		/* tell the PCAN-USB Pro device the driver is being unloaded */
947 		pcan_usb_pro_drv_loaded(dev, 0);
948 	}
949 }
950 
951 /*
952  * called when PCAN-USB Pro adapter is unplugged
953  */
954 static void pcan_usb_pro_free(struct peak_usb_device *dev)
955 {
956 	/* last device: can free pcan_usb_pro_interface object now */
957 	if (!dev->prev_siblings && !dev->next_siblings)
958 		kfree(pcan_usb_pro_dev_if(dev));
959 }
960 
961 /*
962  * probe function for new PCAN-USB Pro usb interface
963  */
964 int pcan_usb_pro_probe(struct usb_interface *intf)
965 {
966 	struct usb_host_interface *if_desc;
967 	int i;
968 
969 	if_desc = intf->altsetting;
970 
971 	/* check interface endpoint addresses */
972 	for (i = 0; i < if_desc->desc.bNumEndpoints; i++) {
973 		struct usb_endpoint_descriptor *ep = &if_desc->endpoint[i].desc;
974 
975 		/*
976 		 * below is the list of valid ep addreses. Any other ep address
977 		 * is considered as not-CAN interface address => no dev created
978 		 */
979 		switch (ep->bEndpointAddress) {
980 		case PCAN_USBPRO_EP_CMDOUT:
981 		case PCAN_USBPRO_EP_CMDIN:
982 		case PCAN_USBPRO_EP_MSGOUT_0:
983 		case PCAN_USBPRO_EP_MSGOUT_1:
984 		case PCAN_USBPRO_EP_MSGIN:
985 		case PCAN_USBPRO_EP_UNUSED:
986 			break;
987 		default:
988 			return -ENODEV;
989 		}
990 	}
991 
992 	return 0;
993 }
994 
995 /*
996  * describe the PCAN-USB Pro adapter
997  */
998 static const struct can_bittiming_const pcan_usb_pro_const = {
999 	.name = "pcan_usb_pro",
1000 	.tseg1_min = 1,
1001 	.tseg1_max = 16,
1002 	.tseg2_min = 1,
1003 	.tseg2_max = 8,
1004 	.sjw_max = 4,
1005 	.brp_min = 1,
1006 	.brp_max = 1024,
1007 	.brp_inc = 1,
1008 };
1009 
1010 const struct peak_usb_adapter pcan_usb_pro = {
1011 	.name = "PCAN-USB Pro",
1012 	.device_id = PCAN_USBPRO_PRODUCT_ID,
1013 	.ctrl_count = PCAN_USBPRO_CHANNEL_COUNT,
1014 	.ctrlmode_supported = CAN_CTRLMODE_3_SAMPLES | CAN_CTRLMODE_LISTENONLY,
1015 	.clock = {
1016 		.freq = PCAN_USBPRO_CRYSTAL_HZ,
1017 	},
1018 	.bittiming_const = &pcan_usb_pro_const,
1019 
1020 	/* size of device private data */
1021 	.sizeof_dev_private = sizeof(struct pcan_usb_pro_device),
1022 
1023 	/* timestamps usage */
1024 	.ts_used_bits = 32,
1025 	.ts_period = 1000000, /* calibration period in ts. */
1026 	.us_per_ts_scale = 1, /* us = (ts * scale) >> shift */
1027 	.us_per_ts_shift = 0,
1028 
1029 	/* give here messages in/out endpoints */
1030 	.ep_msg_in = PCAN_USBPRO_EP_MSGIN,
1031 	.ep_msg_out = {PCAN_USBPRO_EP_MSGOUT_0, PCAN_USBPRO_EP_MSGOUT_1},
1032 
1033 	/* size of rx/tx usb buffers */
1034 	.rx_buffer_size = PCAN_USBPRO_RX_BUFFER_SIZE,
1035 	.tx_buffer_size = PCAN_USBPRO_TX_BUFFER_SIZE,
1036 
1037 	/* device callbacks */
1038 	.intf_probe = pcan_usb_pro_probe,
1039 	.dev_init = pcan_usb_pro_init,
1040 	.dev_exit = pcan_usb_pro_exit,
1041 	.dev_free = pcan_usb_pro_free,
1042 	.dev_set_bus = pcan_usb_pro_set_bus,
1043 	.dev_set_bittiming = pcan_usb_pro_set_bittiming,
1044 	.dev_get_device_id = pcan_usb_pro_get_device_id,
1045 	.dev_decode_buf = pcan_usb_pro_decode_buf,
1046 	.dev_encode_msg = pcan_usb_pro_encode_msg,
1047 	.dev_start = pcan_usb_pro_start,
1048 	.dev_stop = pcan_usb_pro_stop,
1049 	.dev_restart_async = pcan_usb_pro_restart_async,
1050 };
1051