xref: /linux/drivers/net/can/usb/peak_usb/pcan_usb_core.c (revision 9410645520e9b820069761f3450ef6661418e279)
1 // SPDX-License-Identifier: GPL-2.0-only
2 /*
3  * CAN driver for PEAK System USB adapters
4  * Derived from the PCAN project file driver/src/pcan_usb_core.c
5  *
6  * Copyright (C) 2003-2010 PEAK System-Technik GmbH
7  * Copyright (C) 2010-2012 Stephane Grosjean <s.grosjean@peak-system.com>
8  *
9  * Many thanks to Klaus Hitschler <klaus.hitschler@gmx.de>
10  */
11 #include <linux/device.h>
12 #include <linux/ethtool.h>
13 #include <linux/init.h>
14 #include <linux/module.h>
15 #include <linux/netdevice.h>
16 #include <linux/signal.h>
17 #include <linux/slab.h>
18 #include <linux/sysfs.h>
19 #include <linux/usb.h>
20 
21 #include <linux/can.h>
22 #include <linux/can/dev.h>
23 #include <linux/can/error.h>
24 
25 #include "pcan_usb_core.h"
26 
27 MODULE_AUTHOR("Stephane Grosjean <s.grosjean@peak-system.com>");
28 MODULE_DESCRIPTION("CAN driver for PEAK-System USB adapters");
29 MODULE_LICENSE("GPL v2");
30 
31 /* Table of devices that work with this driver */
32 static const struct usb_device_id peak_usb_table[] = {
33 	{
34 		USB_DEVICE(PCAN_USB_VENDOR_ID, PCAN_USB_PRODUCT_ID),
35 		.driver_info = (kernel_ulong_t)&pcan_usb,
36 	}, {
37 		USB_DEVICE(PCAN_USB_VENDOR_ID, PCAN_USBPRO_PRODUCT_ID),
38 		.driver_info = (kernel_ulong_t)&pcan_usb_pro,
39 	}, {
40 		USB_DEVICE(PCAN_USB_VENDOR_ID, PCAN_USBFD_PRODUCT_ID),
41 		.driver_info = (kernel_ulong_t)&pcan_usb_fd,
42 	}, {
43 		USB_DEVICE(PCAN_USB_VENDOR_ID, PCAN_USBPROFD_PRODUCT_ID),
44 		.driver_info = (kernel_ulong_t)&pcan_usb_pro_fd,
45 	}, {
46 		USB_DEVICE(PCAN_USB_VENDOR_ID, PCAN_USBCHIP_PRODUCT_ID),
47 		.driver_info = (kernel_ulong_t)&pcan_usb_chip,
48 	}, {
49 		USB_DEVICE(PCAN_USB_VENDOR_ID, PCAN_USBX6_PRODUCT_ID),
50 		.driver_info = (kernel_ulong_t)&pcan_usb_x6,
51 	}, {
52 		/* Terminating entry */
53 	}
54 };
55 
56 MODULE_DEVICE_TABLE(usb, peak_usb_table);
57 
can_channel_id_show(struct device * dev,struct device_attribute * attr,char * buf)58 static ssize_t can_channel_id_show(struct device *dev, struct device_attribute *attr, char *buf)
59 {
60 	struct net_device *netdev = to_net_dev(dev);
61 	struct peak_usb_device *peak_dev = netdev_priv(netdev);
62 
63 	return sysfs_emit(buf, "%08X\n", peak_dev->can_channel_id);
64 }
65 static DEVICE_ATTR_RO(can_channel_id);
66 
67 /* mutable to avoid cast in attribute_group */
68 static struct attribute *peak_usb_sysfs_attrs[] = {
69 	&dev_attr_can_channel_id.attr,
70 	NULL,
71 };
72 
73 static const struct attribute_group peak_usb_sysfs_group = {
74 	.name	= "peak_usb",
75 	.attrs	= peak_usb_sysfs_attrs,
76 };
77 
78 /*
79  * dump memory
80  */
81 #define DUMP_WIDTH	16
pcan_dump_mem(const char * prompt,const void * p,int l)82 void pcan_dump_mem(const char *prompt, const void *p, int l)
83 {
84 	pr_info("%s dumping %s (%d bytes):\n",
85 		PCAN_USB_DRIVER_NAME, prompt ? prompt : "memory", l);
86 	print_hex_dump(KERN_INFO, PCAN_USB_DRIVER_NAME " ", DUMP_PREFIX_NONE,
87 		       DUMP_WIDTH, 1, p, l, false);
88 }
89 
90 /*
91  * initialize a time_ref object with usb adapter own settings
92  */
peak_usb_init_time_ref(struct peak_time_ref * time_ref,const struct peak_usb_adapter * adapter)93 void peak_usb_init_time_ref(struct peak_time_ref *time_ref,
94 			    const struct peak_usb_adapter *adapter)
95 {
96 	if (time_ref) {
97 		memset(time_ref, 0, sizeof(struct peak_time_ref));
98 		time_ref->adapter = adapter;
99 	}
100 }
101 
102 /*
103  * sometimes, another now may be  more recent than current one...
104  */
peak_usb_update_ts_now(struct peak_time_ref * time_ref,u32 ts_now)105 void peak_usb_update_ts_now(struct peak_time_ref *time_ref, u32 ts_now)
106 {
107 	time_ref->ts_dev_2 = ts_now;
108 
109 	/* should wait at least two passes before computing */
110 	if (ktime_to_ns(time_ref->tv_host) > 0) {
111 		u32 delta_ts = time_ref->ts_dev_2 - time_ref->ts_dev_1;
112 
113 		if (time_ref->ts_dev_2 < time_ref->ts_dev_1)
114 			delta_ts &= (1 << time_ref->adapter->ts_used_bits) - 1;
115 
116 		time_ref->ts_total += delta_ts;
117 	}
118 }
119 
120 /*
121  * register device timestamp as now
122  */
peak_usb_set_ts_now(struct peak_time_ref * time_ref,u32 ts_now)123 void peak_usb_set_ts_now(struct peak_time_ref *time_ref, u32 ts_now)
124 {
125 	if (ktime_to_ns(time_ref->tv_host_0) == 0) {
126 		/* use monotonic clock to correctly compute further deltas */
127 		time_ref->tv_host_0 = ktime_get();
128 		time_ref->tv_host = ktime_set(0, 0);
129 	} else {
130 		/*
131 		 * delta_us should not be >= 2^32 => delta should be < 4294s
132 		 * handle 32-bits wrapping here: if count of s. reaches 4200,
133 		 * reset counters and change time base
134 		 */
135 		if (ktime_to_ns(time_ref->tv_host)) {
136 			ktime_t delta = ktime_sub(time_ref->tv_host,
137 						  time_ref->tv_host_0);
138 			if (ktime_to_ns(delta) > (4200ull * NSEC_PER_SEC)) {
139 				time_ref->tv_host_0 = time_ref->tv_host;
140 				time_ref->ts_total = 0;
141 			}
142 		}
143 
144 		time_ref->tv_host = ktime_get();
145 		time_ref->tick_count++;
146 	}
147 
148 	time_ref->ts_dev_1 = time_ref->ts_dev_2;
149 	peak_usb_update_ts_now(time_ref, ts_now);
150 }
151 
152 /*
153  * compute time according to current ts and time_ref data
154  */
peak_usb_get_ts_time(struct peak_time_ref * time_ref,u32 ts,ktime_t * time)155 void peak_usb_get_ts_time(struct peak_time_ref *time_ref, u32 ts, ktime_t *time)
156 {
157 	/* protect from getting time before setting now */
158 	if (ktime_to_ns(time_ref->tv_host)) {
159 		u64 delta_us;
160 		s64 delta_ts = 0;
161 
162 		/* General case: dev_ts_1 < dev_ts_2 < ts, with:
163 		 *
164 		 * - dev_ts_1 = previous sync timestamp
165 		 * - dev_ts_2 = last sync timestamp
166 		 * - ts = event timestamp
167 		 * - ts_period = known sync period (theoretical)
168 		 *             ~ dev_ts2 - dev_ts1
169 		 * *but*:
170 		 *
171 		 * - time counters wrap (see adapter->ts_used_bits)
172 		 * - sometimes, dev_ts_1 < ts < dev_ts2
173 		 *
174 		 * "normal" case (sync time counters increase):
175 		 * must take into account case when ts wraps (tsw)
176 		 *
177 		 *      < ts_period > <          >
178 		 *     |             |            |
179 		 *  ---+--------+----+-------0-+--+-->
180 		 *     ts_dev_1 |    ts_dev_2  |
181 		 *              ts             tsw
182 		 */
183 		if (time_ref->ts_dev_1 < time_ref->ts_dev_2) {
184 			/* case when event time (tsw) wraps */
185 			if (ts < time_ref->ts_dev_1)
186 				delta_ts = BIT_ULL(time_ref->adapter->ts_used_bits);
187 
188 		/* Otherwise, sync time counter (ts_dev_2) has wrapped:
189 		 * handle case when event time (tsn) hasn't.
190 		 *
191 		 *      < ts_period > <          >
192 		 *     |             |            |
193 		 *  ---+--------+--0-+---------+--+-->
194 		 *     ts_dev_1 |    ts_dev_2  |
195 		 *              tsn            ts
196 		 */
197 		} else if (time_ref->ts_dev_1 < ts) {
198 			delta_ts = -BIT_ULL(time_ref->adapter->ts_used_bits);
199 		}
200 
201 		/* add delay between last sync and event timestamps */
202 		delta_ts += (signed int)(ts - time_ref->ts_dev_2);
203 
204 		/* add time from beginning to last sync */
205 		delta_ts += time_ref->ts_total;
206 
207 		/* convert ticks number into microseconds */
208 		delta_us = delta_ts * time_ref->adapter->us_per_ts_scale;
209 		delta_us >>= time_ref->adapter->us_per_ts_shift;
210 
211 		*time = ktime_add_us(time_ref->tv_host_0, delta_us);
212 	} else {
213 		*time = ktime_get();
214 	}
215 }
216 
217 /* post received skb with native 64-bit hw timestamp */
peak_usb_netif_rx_64(struct sk_buff * skb,u32 ts_low,u32 ts_high)218 int peak_usb_netif_rx_64(struct sk_buff *skb, u32 ts_low, u32 ts_high)
219 {
220 	struct skb_shared_hwtstamps *hwts = skb_hwtstamps(skb);
221 	u64 ns_ts;
222 
223 	ns_ts = (u64)ts_high << 32 | ts_low;
224 	ns_ts *= NSEC_PER_USEC;
225 	hwts->hwtstamp = ns_to_ktime(ns_ts);
226 
227 	return netif_rx(skb);
228 }
229 
230 /*
231  * callback for bulk Rx urb
232  */
peak_usb_read_bulk_callback(struct urb * urb)233 static void peak_usb_read_bulk_callback(struct urb *urb)
234 {
235 	struct peak_usb_device *dev = urb->context;
236 	struct net_device *netdev;
237 	int err;
238 
239 	netdev = dev->netdev;
240 
241 	if (!netif_device_present(netdev))
242 		return;
243 
244 	/* check reception status */
245 	switch (urb->status) {
246 	case 0:
247 		/* success */
248 		break;
249 
250 	case -EILSEQ:
251 	case -ENOENT:
252 	case -ECONNRESET:
253 	case -ESHUTDOWN:
254 		return;
255 
256 	default:
257 		if (net_ratelimit())
258 			netdev_err(netdev,
259 				   "Rx urb aborted (%d)\n", urb->status);
260 		goto resubmit_urb;
261 	}
262 
263 	/* protect from any incoming empty msgs */
264 	if ((urb->actual_length > 0) && (dev->adapter->dev_decode_buf)) {
265 		/* handle these kinds of msgs only if _start callback called */
266 		if (dev->state & PCAN_USB_STATE_STARTED) {
267 			err = dev->adapter->dev_decode_buf(dev, urb);
268 			if (err)
269 				pcan_dump_mem("received usb message",
270 					      urb->transfer_buffer,
271 					      urb->transfer_buffer_length);
272 		}
273 	}
274 
275 resubmit_urb:
276 	usb_fill_bulk_urb(urb, dev->udev,
277 		usb_rcvbulkpipe(dev->udev, dev->ep_msg_in),
278 		urb->transfer_buffer, dev->adapter->rx_buffer_size,
279 		peak_usb_read_bulk_callback, dev);
280 
281 	usb_anchor_urb(urb, &dev->rx_submitted);
282 	err = usb_submit_urb(urb, GFP_ATOMIC);
283 	if (!err)
284 		return;
285 
286 	usb_unanchor_urb(urb);
287 
288 	if (err == -ENODEV)
289 		netif_device_detach(netdev);
290 	else
291 		netdev_err(netdev, "failed resubmitting read bulk urb: %d\n",
292 			   err);
293 }
294 
295 /*
296  * callback for bulk Tx urb
297  */
peak_usb_write_bulk_callback(struct urb * urb)298 static void peak_usb_write_bulk_callback(struct urb *urb)
299 {
300 	struct peak_tx_urb_context *context = urb->context;
301 	struct peak_usb_device *dev;
302 	struct net_device *netdev;
303 	int tx_bytes;
304 
305 	BUG_ON(!context);
306 
307 	dev = context->dev;
308 	netdev = dev->netdev;
309 
310 	atomic_dec(&dev->active_tx_urbs);
311 
312 	if (!netif_device_present(netdev))
313 		return;
314 
315 	/* check tx status */
316 	switch (urb->status) {
317 	case 0:
318 		/* prevent tx timeout */
319 		netif_trans_update(netdev);
320 		break;
321 
322 	case -EPROTO:
323 	case -ENOENT:
324 	case -ECONNRESET:
325 	case -ESHUTDOWN:
326 		break;
327 
328 	default:
329 		if (net_ratelimit())
330 			netdev_err(netdev, "Tx urb aborted (%d)\n",
331 				   urb->status);
332 		break;
333 	}
334 
335 	/* should always release echo skb and corresponding context */
336 	tx_bytes = can_get_echo_skb(netdev, context->echo_index, NULL);
337 	context->echo_index = PCAN_USB_MAX_TX_URBS;
338 
339 	if (!urb->status) {
340 		/* transmission complete */
341 		netdev->stats.tx_packets++;
342 		netdev->stats.tx_bytes += tx_bytes;
343 
344 		/* do wakeup tx queue in case of success only */
345 		netif_wake_queue(netdev);
346 	}
347 }
348 
349 /*
350  * called by netdev to send one skb on the CAN interface.
351  */
peak_usb_ndo_start_xmit(struct sk_buff * skb,struct net_device * netdev)352 static netdev_tx_t peak_usb_ndo_start_xmit(struct sk_buff *skb,
353 					   struct net_device *netdev)
354 {
355 	struct peak_usb_device *dev = netdev_priv(netdev);
356 	struct peak_tx_urb_context *context = NULL;
357 	struct net_device_stats *stats = &netdev->stats;
358 	struct urb *urb;
359 	u8 *obuf;
360 	int i, err;
361 	size_t size = dev->adapter->tx_buffer_size;
362 
363 	if (can_dev_dropped_skb(netdev, skb))
364 		return NETDEV_TX_OK;
365 
366 	for (i = 0; i < PCAN_USB_MAX_TX_URBS; i++)
367 		if (dev->tx_contexts[i].echo_index == PCAN_USB_MAX_TX_URBS) {
368 			context = dev->tx_contexts + i;
369 			break;
370 		}
371 
372 	if (!context) {
373 		/* should not occur except during restart */
374 		return NETDEV_TX_BUSY;
375 	}
376 
377 	urb = context->urb;
378 	obuf = urb->transfer_buffer;
379 
380 	err = dev->adapter->dev_encode_msg(dev, skb, obuf, &size);
381 	if (err) {
382 		if (net_ratelimit())
383 			netdev_err(netdev, "packet dropped\n");
384 		dev_kfree_skb(skb);
385 		stats->tx_dropped++;
386 		return NETDEV_TX_OK;
387 	}
388 
389 	context->echo_index = i;
390 
391 	usb_anchor_urb(urb, &dev->tx_submitted);
392 
393 	can_put_echo_skb(skb, netdev, context->echo_index, 0);
394 
395 	atomic_inc(&dev->active_tx_urbs);
396 
397 	err = usb_submit_urb(urb, GFP_ATOMIC);
398 	if (err) {
399 		can_free_echo_skb(netdev, context->echo_index, NULL);
400 
401 		usb_unanchor_urb(urb);
402 
403 		/* this context is not used in fact */
404 		context->echo_index = PCAN_USB_MAX_TX_URBS;
405 
406 		atomic_dec(&dev->active_tx_urbs);
407 
408 		switch (err) {
409 		case -ENODEV:
410 			netif_device_detach(netdev);
411 			break;
412 		default:
413 			netdev_warn(netdev, "tx urb submitting failed err=%d\n",
414 				    err);
415 			fallthrough;
416 		case -ENOENT:
417 			/* cable unplugged */
418 			stats->tx_dropped++;
419 		}
420 	} else {
421 		netif_trans_update(netdev);
422 
423 		/* slow down tx path */
424 		if (atomic_read(&dev->active_tx_urbs) >= PCAN_USB_MAX_TX_URBS)
425 			netif_stop_queue(netdev);
426 	}
427 
428 	return NETDEV_TX_OK;
429 }
430 
431 /*
432  * start the CAN interface.
433  * Rx and Tx urbs are allocated here. Rx urbs are submitted here.
434  */
peak_usb_start(struct peak_usb_device * dev)435 static int peak_usb_start(struct peak_usb_device *dev)
436 {
437 	struct net_device *netdev = dev->netdev;
438 	int err, i;
439 
440 	for (i = 0; i < PCAN_USB_MAX_RX_URBS; i++) {
441 		struct urb *urb;
442 		u8 *buf;
443 
444 		/* create a URB, and a buffer for it, to receive usb messages */
445 		urb = usb_alloc_urb(0, GFP_KERNEL);
446 		if (!urb) {
447 			err = -ENOMEM;
448 			break;
449 		}
450 
451 		buf = kmalloc(dev->adapter->rx_buffer_size, GFP_KERNEL);
452 		if (!buf) {
453 			usb_free_urb(urb);
454 			err = -ENOMEM;
455 			break;
456 		}
457 
458 		usb_fill_bulk_urb(urb, dev->udev,
459 			usb_rcvbulkpipe(dev->udev, dev->ep_msg_in),
460 			buf, dev->adapter->rx_buffer_size,
461 			peak_usb_read_bulk_callback, dev);
462 
463 		/* ask last usb_free_urb() to also kfree() transfer_buffer */
464 		urb->transfer_flags |= URB_FREE_BUFFER;
465 		usb_anchor_urb(urb, &dev->rx_submitted);
466 
467 		err = usb_submit_urb(urb, GFP_KERNEL);
468 		if (err) {
469 			if (err == -ENODEV)
470 				netif_device_detach(dev->netdev);
471 
472 			usb_unanchor_urb(urb);
473 			kfree(buf);
474 			usb_free_urb(urb);
475 			break;
476 		}
477 
478 		/* drop reference, USB core will take care of freeing it */
479 		usb_free_urb(urb);
480 	}
481 
482 	/* did we submit any URBs? Warn if we was not able to submit all urbs */
483 	if (i < PCAN_USB_MAX_RX_URBS) {
484 		if (i == 0) {
485 			netdev_err(netdev, "couldn't setup any rx URB\n");
486 			return err;
487 		}
488 
489 		netdev_warn(netdev, "rx performance may be slow\n");
490 	}
491 
492 	/* pre-alloc tx buffers and corresponding urbs */
493 	for (i = 0; i < PCAN_USB_MAX_TX_URBS; i++) {
494 		struct peak_tx_urb_context *context;
495 		struct urb *urb;
496 		u8 *buf;
497 
498 		/* create a URB and a buffer for it, to transmit usb messages */
499 		urb = usb_alloc_urb(0, GFP_KERNEL);
500 		if (!urb) {
501 			err = -ENOMEM;
502 			break;
503 		}
504 
505 		buf = kmalloc(dev->adapter->tx_buffer_size, GFP_KERNEL);
506 		if (!buf) {
507 			usb_free_urb(urb);
508 			err = -ENOMEM;
509 			break;
510 		}
511 
512 		context = dev->tx_contexts + i;
513 		context->dev = dev;
514 		context->urb = urb;
515 
516 		usb_fill_bulk_urb(urb, dev->udev,
517 			usb_sndbulkpipe(dev->udev, dev->ep_msg_out),
518 			buf, dev->adapter->tx_buffer_size,
519 			peak_usb_write_bulk_callback, context);
520 
521 		/* ask last usb_free_urb() to also kfree() transfer_buffer */
522 		urb->transfer_flags |= URB_FREE_BUFFER;
523 	}
524 
525 	/* warn if we were not able to allocate enough tx contexts */
526 	if (i < PCAN_USB_MAX_TX_URBS) {
527 		if (i == 0) {
528 			netdev_err(netdev, "couldn't setup any tx URB\n");
529 			goto err_tx;
530 		}
531 
532 		netdev_warn(netdev, "tx performance may be slow\n");
533 	}
534 
535 	if (dev->adapter->dev_start) {
536 		err = dev->adapter->dev_start(dev);
537 		if (err)
538 			goto err_adapter;
539 	}
540 
541 	dev->state |= PCAN_USB_STATE_STARTED;
542 
543 	/* can set bus on now */
544 	if (dev->adapter->dev_set_bus) {
545 		err = dev->adapter->dev_set_bus(dev, 1);
546 		if (err)
547 			goto err_adapter;
548 	}
549 
550 	dev->can.state = CAN_STATE_ERROR_ACTIVE;
551 
552 	return 0;
553 
554 err_adapter:
555 	if (err == -ENODEV)
556 		netif_device_detach(dev->netdev);
557 
558 	netdev_warn(netdev, "couldn't submit control: %d\n", err);
559 
560 	for (i = 0; i < PCAN_USB_MAX_TX_URBS; i++) {
561 		usb_free_urb(dev->tx_contexts[i].urb);
562 		dev->tx_contexts[i].urb = NULL;
563 	}
564 err_tx:
565 	usb_kill_anchored_urbs(&dev->rx_submitted);
566 
567 	return err;
568 }
569 
570 /*
571  * called by netdev to open the corresponding CAN interface.
572  */
peak_usb_ndo_open(struct net_device * netdev)573 static int peak_usb_ndo_open(struct net_device *netdev)
574 {
575 	struct peak_usb_device *dev = netdev_priv(netdev);
576 	int err;
577 
578 	/* common open */
579 	err = open_candev(netdev);
580 	if (err)
581 		return err;
582 
583 	/* finally start device */
584 	err = peak_usb_start(dev);
585 	if (err) {
586 		netdev_err(netdev, "couldn't start device: %d\n", err);
587 		close_candev(netdev);
588 		return err;
589 	}
590 
591 	netif_start_queue(netdev);
592 
593 	return 0;
594 }
595 
596 /*
597  * unlink in-flight Rx and Tx urbs and free their memory.
598  */
peak_usb_unlink_all_urbs(struct peak_usb_device * dev)599 static void peak_usb_unlink_all_urbs(struct peak_usb_device *dev)
600 {
601 	int i;
602 
603 	/* free all Rx (submitted) urbs */
604 	usb_kill_anchored_urbs(&dev->rx_submitted);
605 
606 	/* free unsubmitted Tx urbs first */
607 	for (i = 0; i < PCAN_USB_MAX_TX_URBS; i++) {
608 		struct urb *urb = dev->tx_contexts[i].urb;
609 
610 		if (!urb ||
611 		    dev->tx_contexts[i].echo_index != PCAN_USB_MAX_TX_URBS) {
612 			/*
613 			 * this urb is already released or always submitted,
614 			 * let usb core free by itself
615 			 */
616 			continue;
617 		}
618 
619 		usb_free_urb(urb);
620 		dev->tx_contexts[i].urb = NULL;
621 	}
622 
623 	/* then free all submitted Tx urbs */
624 	usb_kill_anchored_urbs(&dev->tx_submitted);
625 	atomic_set(&dev->active_tx_urbs, 0);
626 }
627 
628 /*
629  * called by netdev to close the corresponding CAN interface.
630  */
peak_usb_ndo_stop(struct net_device * netdev)631 static int peak_usb_ndo_stop(struct net_device *netdev)
632 {
633 	struct peak_usb_device *dev = netdev_priv(netdev);
634 
635 	dev->state &= ~PCAN_USB_STATE_STARTED;
636 	netif_stop_queue(netdev);
637 
638 	close_candev(netdev);
639 
640 	dev->can.state = CAN_STATE_STOPPED;
641 
642 	/* unlink all pending urbs and free used memory */
643 	peak_usb_unlink_all_urbs(dev);
644 
645 	if (dev->adapter->dev_stop)
646 		dev->adapter->dev_stop(dev);
647 
648 	/* can set bus off now */
649 	if (dev->adapter->dev_set_bus) {
650 		int err = dev->adapter->dev_set_bus(dev, 0);
651 
652 		if (err)
653 			return err;
654 	}
655 
656 	return 0;
657 }
658 
659 /*
660  * handle end of waiting for the device to reset
661  */
peak_usb_restart_complete(struct peak_usb_device * dev)662 void peak_usb_restart_complete(struct peak_usb_device *dev)
663 {
664 	/* finally MUST update can state */
665 	dev->can.state = CAN_STATE_ERROR_ACTIVE;
666 
667 	/* netdev queue can be awaken now */
668 	netif_wake_queue(dev->netdev);
669 }
670 
peak_usb_async_complete(struct urb * urb)671 void peak_usb_async_complete(struct urb *urb)
672 {
673 	kfree(urb->transfer_buffer);
674 	usb_free_urb(urb);
675 }
676 
677 /*
678  * device (auto-)restart mechanism runs in a timer context =>
679  * MUST handle restart with asynchronous usb transfers
680  */
peak_usb_restart(struct peak_usb_device * dev)681 static int peak_usb_restart(struct peak_usb_device *dev)
682 {
683 	struct urb *urb;
684 	int err;
685 	u8 *buf;
686 
687 	/*
688 	 * if device doesn't define any asynchronous restart handler, simply
689 	 * wake the netdev queue up
690 	 */
691 	if (!dev->adapter->dev_restart_async) {
692 		peak_usb_restart_complete(dev);
693 		return 0;
694 	}
695 
696 	/* first allocate a urb to handle the asynchronous steps */
697 	urb = usb_alloc_urb(0, GFP_ATOMIC);
698 	if (!urb)
699 		return -ENOMEM;
700 
701 	/* also allocate enough space for the commands to send */
702 	buf = kmalloc(PCAN_USB_MAX_CMD_LEN, GFP_ATOMIC);
703 	if (!buf) {
704 		usb_free_urb(urb);
705 		return -ENOMEM;
706 	}
707 
708 	/* call the device specific handler for the restart */
709 	err = dev->adapter->dev_restart_async(dev, urb, buf);
710 	if (!err)
711 		return 0;
712 
713 	kfree(buf);
714 	usb_free_urb(urb);
715 
716 	return err;
717 }
718 
719 /*
720  * candev callback used to change CAN mode.
721  * Warning: this is called from a timer context!
722  */
peak_usb_set_mode(struct net_device * netdev,enum can_mode mode)723 static int peak_usb_set_mode(struct net_device *netdev, enum can_mode mode)
724 {
725 	struct peak_usb_device *dev = netdev_priv(netdev);
726 	int err = 0;
727 
728 	switch (mode) {
729 	case CAN_MODE_START:
730 		err = peak_usb_restart(dev);
731 		if (err)
732 			netdev_err(netdev, "couldn't start device (err %d)\n",
733 				   err);
734 		break;
735 
736 	default:
737 		return -EOPNOTSUPP;
738 	}
739 
740 	return err;
741 }
742 
743 /*
744  * candev callback used to set device nominal/arbitration bitrate.
745  */
peak_usb_set_bittiming(struct net_device * netdev)746 static int peak_usb_set_bittiming(struct net_device *netdev)
747 {
748 	struct peak_usb_device *dev = netdev_priv(netdev);
749 	const struct peak_usb_adapter *pa = dev->adapter;
750 
751 	if (pa->dev_set_bittiming) {
752 		struct can_bittiming *bt = &dev->can.bittiming;
753 		int err = pa->dev_set_bittiming(dev, bt);
754 
755 		if (err)
756 			netdev_info(netdev, "couldn't set bitrate (err %d)\n",
757 				    err);
758 		return err;
759 	}
760 
761 	return 0;
762 }
763 
764 /*
765  * candev callback used to set device data bitrate.
766  */
peak_usb_set_data_bittiming(struct net_device * netdev)767 static int peak_usb_set_data_bittiming(struct net_device *netdev)
768 {
769 	struct peak_usb_device *dev = netdev_priv(netdev);
770 	const struct peak_usb_adapter *pa = dev->adapter;
771 
772 	if (pa->dev_set_data_bittiming) {
773 		struct can_bittiming *bt = &dev->can.data_bittiming;
774 		int err = pa->dev_set_data_bittiming(dev, bt);
775 
776 		if (err)
777 			netdev_info(netdev,
778 				    "couldn't set data bitrate (err %d)\n",
779 				    err);
780 
781 		return err;
782 	}
783 
784 	return 0;
785 }
786 
peak_eth_ioctl(struct net_device * netdev,struct ifreq * ifr,int cmd)787 static int peak_eth_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
788 {
789 	struct hwtstamp_config hwts_cfg = { 0 };
790 
791 	switch (cmd) {
792 	case SIOCSHWTSTAMP: /* set */
793 		if (copy_from_user(&hwts_cfg, ifr->ifr_data, sizeof(hwts_cfg)))
794 			return -EFAULT;
795 		if (hwts_cfg.tx_type == HWTSTAMP_TX_OFF &&
796 		    hwts_cfg.rx_filter == HWTSTAMP_FILTER_ALL)
797 			return 0;
798 		return -ERANGE;
799 
800 	case SIOCGHWTSTAMP: /* get */
801 		hwts_cfg.tx_type = HWTSTAMP_TX_OFF;
802 		hwts_cfg.rx_filter = HWTSTAMP_FILTER_ALL;
803 		if (copy_to_user(ifr->ifr_data, &hwts_cfg, sizeof(hwts_cfg)))
804 			return -EFAULT;
805 		return 0;
806 
807 	default:
808 		return -EOPNOTSUPP;
809 	}
810 }
811 
812 static const struct net_device_ops peak_usb_netdev_ops = {
813 	.ndo_open = peak_usb_ndo_open,
814 	.ndo_stop = peak_usb_ndo_stop,
815 	.ndo_eth_ioctl = peak_eth_ioctl,
816 	.ndo_start_xmit = peak_usb_ndo_start_xmit,
817 	.ndo_change_mtu = can_change_mtu,
818 };
819 
820 /* CAN-USB devices generally handle 32-bit CAN channel IDs.
821  * In case one doesn't, then it have to overload this function.
822  */
peak_usb_get_eeprom_len(struct net_device * netdev)823 int peak_usb_get_eeprom_len(struct net_device *netdev)
824 {
825 	return sizeof(u32);
826 }
827 
828 /* Every CAN-USB device exports the dev_get_can_channel_id() operation. It is used
829  * here to fill the data buffer with the user defined CAN channel ID.
830  */
peak_usb_get_eeprom(struct net_device * netdev,struct ethtool_eeprom * eeprom,u8 * data)831 int peak_usb_get_eeprom(struct net_device *netdev,
832 			struct ethtool_eeprom *eeprom, u8 *data)
833 {
834 	struct peak_usb_device *dev = netdev_priv(netdev);
835 	u32 ch_id;
836 	__le32 ch_id_le;
837 	int err;
838 
839 	err = dev->adapter->dev_get_can_channel_id(dev, &ch_id);
840 	if (err)
841 		return err;
842 
843 	/* ethtool operates on individual bytes. The byte order of the CAN
844 	 * channel id in memory depends on the kernel architecture. We
845 	 * convert the CAN channel id back to the native byte order of the PEAK
846 	 * device itself to ensure that the order is consistent for all
847 	 * host architectures.
848 	 */
849 	ch_id_le = cpu_to_le32(ch_id);
850 	memcpy(data, (u8 *)&ch_id_le + eeprom->offset, eeprom->len);
851 
852 	/* update cached value */
853 	dev->can_channel_id = ch_id;
854 	return err;
855 }
856 
857 /* Every CAN-USB device exports the dev_get_can_channel_id()/dev_set_can_channel_id()
858  * operations. They are used here to set the new user defined CAN channel ID.
859  */
peak_usb_set_eeprom(struct net_device * netdev,struct ethtool_eeprom * eeprom,u8 * data)860 int peak_usb_set_eeprom(struct net_device *netdev,
861 			struct ethtool_eeprom *eeprom, u8 *data)
862 {
863 	struct peak_usb_device *dev = netdev_priv(netdev);
864 	u32 ch_id;
865 	__le32 ch_id_le;
866 	int err;
867 
868 	/* first, read the current user defined CAN channel ID */
869 	err = dev->adapter->dev_get_can_channel_id(dev, &ch_id);
870 	if (err) {
871 		netdev_err(netdev, "Failed to init CAN channel id (err %d)\n", err);
872 		return err;
873 	}
874 
875 	/* do update the value with user given bytes.
876 	 * ethtool operates on individual bytes. The byte order of the CAN
877 	 * channel ID in memory depends on the kernel architecture. We
878 	 * convert the CAN channel ID back to the native byte order of the PEAK
879 	 * device itself to ensure that the order is consistent for all
880 	 * host architectures.
881 	 */
882 	ch_id_le = cpu_to_le32(ch_id);
883 	memcpy((u8 *)&ch_id_le + eeprom->offset, data, eeprom->len);
884 	ch_id = le32_to_cpu(ch_id_le);
885 
886 	/* flash the new value now */
887 	err = dev->adapter->dev_set_can_channel_id(dev, ch_id);
888 	if (err) {
889 		netdev_err(netdev, "Failed to write new CAN channel id (err %d)\n",
890 			   err);
891 		return err;
892 	}
893 
894 	/* update cached value with the new one */
895 	dev->can_channel_id = ch_id;
896 
897 	return 0;
898 }
899 
pcan_get_ts_info(struct net_device * dev,struct kernel_ethtool_ts_info * info)900 int pcan_get_ts_info(struct net_device *dev, struct kernel_ethtool_ts_info *info)
901 {
902 	info->so_timestamping =
903 		SOF_TIMESTAMPING_TX_SOFTWARE |
904 		SOF_TIMESTAMPING_RX_HARDWARE |
905 		SOF_TIMESTAMPING_RAW_HARDWARE;
906 	info->tx_types = BIT(HWTSTAMP_TX_OFF);
907 	info->rx_filters = BIT(HWTSTAMP_FILTER_ALL);
908 
909 	return 0;
910 }
911 
912 /*
913  * create one device which is attached to CAN controller #ctrl_idx of the
914  * usb adapter.
915  */
peak_usb_create_dev(const struct peak_usb_adapter * peak_usb_adapter,struct usb_interface * intf,int ctrl_idx)916 static int peak_usb_create_dev(const struct peak_usb_adapter *peak_usb_adapter,
917 			       struct usb_interface *intf, int ctrl_idx)
918 {
919 	struct usb_device *usb_dev = interface_to_usbdev(intf);
920 	int sizeof_candev = peak_usb_adapter->sizeof_dev_private;
921 	struct peak_usb_device *dev;
922 	struct net_device *netdev;
923 	int i, err;
924 	u16 tmp16;
925 
926 	if (sizeof_candev < sizeof(struct peak_usb_device))
927 		sizeof_candev = sizeof(struct peak_usb_device);
928 
929 	netdev = alloc_candev(sizeof_candev, PCAN_USB_MAX_TX_URBS);
930 	if (!netdev) {
931 		dev_err(&intf->dev, "%s: couldn't alloc candev\n",
932 			PCAN_USB_DRIVER_NAME);
933 		return -ENOMEM;
934 	}
935 
936 	dev = netdev_priv(netdev);
937 
938 	/* allocate a buffer large enough to send commands */
939 	dev->cmd_buf = kzalloc(PCAN_USB_MAX_CMD_LEN, GFP_KERNEL);
940 	if (!dev->cmd_buf) {
941 		err = -ENOMEM;
942 		goto lbl_free_candev;
943 	}
944 
945 	dev->udev = usb_dev;
946 	dev->netdev = netdev;
947 	dev->adapter = peak_usb_adapter;
948 	dev->ctrl_idx = ctrl_idx;
949 	dev->state = PCAN_USB_STATE_CONNECTED;
950 
951 	dev->ep_msg_in = peak_usb_adapter->ep_msg_in;
952 	dev->ep_msg_out = peak_usb_adapter->ep_msg_out[ctrl_idx];
953 
954 	dev->can.clock = peak_usb_adapter->clock;
955 	dev->can.bittiming_const = peak_usb_adapter->bittiming_const;
956 	dev->can.do_set_bittiming = peak_usb_set_bittiming;
957 	dev->can.data_bittiming_const = peak_usb_adapter->data_bittiming_const;
958 	dev->can.do_set_data_bittiming = peak_usb_set_data_bittiming;
959 	dev->can.do_set_mode = peak_usb_set_mode;
960 	dev->can.do_get_berr_counter = peak_usb_adapter->do_get_berr_counter;
961 	dev->can.ctrlmode_supported = peak_usb_adapter->ctrlmode_supported;
962 
963 	netdev->netdev_ops = &peak_usb_netdev_ops;
964 
965 	netdev->flags |= IFF_ECHO; /* we support local echo */
966 
967 	/* add ethtool support */
968 	netdev->ethtool_ops = peak_usb_adapter->ethtool_ops;
969 
970 	/* register peak_usb sysfs files */
971 	netdev->sysfs_groups[0] = &peak_usb_sysfs_group;
972 
973 	init_usb_anchor(&dev->rx_submitted);
974 
975 	init_usb_anchor(&dev->tx_submitted);
976 	atomic_set(&dev->active_tx_urbs, 0);
977 
978 	for (i = 0; i < PCAN_USB_MAX_TX_URBS; i++)
979 		dev->tx_contexts[i].echo_index = PCAN_USB_MAX_TX_URBS;
980 
981 	dev->prev_siblings = usb_get_intfdata(intf);
982 	usb_set_intfdata(intf, dev);
983 
984 	SET_NETDEV_DEV(netdev, &intf->dev);
985 	netdev->dev_id = ctrl_idx;
986 
987 	err = register_candev(netdev);
988 	if (err) {
989 		dev_err(&intf->dev, "couldn't register CAN device: %d\n", err);
990 		goto lbl_restore_intf_data;
991 	}
992 
993 	if (dev->prev_siblings)
994 		(dev->prev_siblings)->next_siblings = dev;
995 
996 	/* keep hw revision into the netdevice */
997 	tmp16 = le16_to_cpu(usb_dev->descriptor.bcdDevice);
998 	dev->device_rev = tmp16 >> 8;
999 
1000 	if (dev->adapter->dev_init) {
1001 		err = dev->adapter->dev_init(dev);
1002 		if (err)
1003 			goto lbl_unregister_candev;
1004 	}
1005 
1006 	/* set bus off */
1007 	if (dev->adapter->dev_set_bus) {
1008 		err = dev->adapter->dev_set_bus(dev, 0);
1009 		if (err)
1010 			goto adap_dev_free;
1011 	}
1012 
1013 	/* get CAN channel id early */
1014 	dev->adapter->dev_get_can_channel_id(dev, &dev->can_channel_id);
1015 
1016 	netdev_info(netdev, "attached to %s channel %u (device 0x%08X)\n",
1017 		    peak_usb_adapter->name, ctrl_idx, dev->can_channel_id);
1018 
1019 	return 0;
1020 
1021 adap_dev_free:
1022 	if (dev->adapter->dev_free)
1023 		dev->adapter->dev_free(dev);
1024 
1025 lbl_unregister_candev:
1026 	unregister_candev(netdev);
1027 
1028 lbl_restore_intf_data:
1029 	usb_set_intfdata(intf, dev->prev_siblings);
1030 	kfree(dev->cmd_buf);
1031 
1032 lbl_free_candev:
1033 	free_candev(netdev);
1034 
1035 	return err;
1036 }
1037 
1038 /*
1039  * called by the usb core when the device is unplugged from the system
1040  */
peak_usb_disconnect(struct usb_interface * intf)1041 static void peak_usb_disconnect(struct usb_interface *intf)
1042 {
1043 	struct peak_usb_device *dev;
1044 	struct peak_usb_device *dev_prev_siblings;
1045 
1046 	/* unregister as many netdev devices as siblings */
1047 	for (dev = usb_get_intfdata(intf); dev; dev = dev_prev_siblings) {
1048 		struct net_device *netdev = dev->netdev;
1049 		char name[IFNAMSIZ];
1050 
1051 		dev_prev_siblings = dev->prev_siblings;
1052 		dev->state &= ~PCAN_USB_STATE_CONNECTED;
1053 		strscpy(name, netdev->name, IFNAMSIZ);
1054 
1055 		unregister_candev(netdev);
1056 
1057 		kfree(dev->cmd_buf);
1058 		dev->next_siblings = NULL;
1059 		if (dev->adapter->dev_free)
1060 			dev->adapter->dev_free(dev);
1061 
1062 		free_candev(netdev);
1063 		dev_info(&intf->dev, "%s removed\n", name);
1064 	}
1065 
1066 	usb_set_intfdata(intf, NULL);
1067 }
1068 
1069 /*
1070  * probe function for new PEAK-System devices
1071  */
peak_usb_probe(struct usb_interface * intf,const struct usb_device_id * id)1072 static int peak_usb_probe(struct usb_interface *intf,
1073 			  const struct usb_device_id *id)
1074 {
1075 	const struct peak_usb_adapter *peak_usb_adapter;
1076 	int i, err = -ENOMEM;
1077 
1078 	/* get corresponding PCAN-USB adapter */
1079 	peak_usb_adapter = (const struct peak_usb_adapter *)id->driver_info;
1080 
1081 	/* got corresponding adapter: check if it handles current interface */
1082 	if (peak_usb_adapter->intf_probe) {
1083 		err = peak_usb_adapter->intf_probe(intf);
1084 		if (err)
1085 			return err;
1086 	}
1087 
1088 	for (i = 0; i < peak_usb_adapter->ctrl_count; i++) {
1089 		err = peak_usb_create_dev(peak_usb_adapter, intf, i);
1090 		if (err) {
1091 			/* deregister already created devices */
1092 			peak_usb_disconnect(intf);
1093 			break;
1094 		}
1095 	}
1096 
1097 	return err;
1098 }
1099 
1100 /* usb specific object needed to register this driver with the usb subsystem */
1101 static struct usb_driver peak_usb_driver = {
1102 	.name = PCAN_USB_DRIVER_NAME,
1103 	.disconnect = peak_usb_disconnect,
1104 	.probe = peak_usb_probe,
1105 	.id_table = peak_usb_table,
1106 };
1107 
peak_usb_init(void)1108 static int __init peak_usb_init(void)
1109 {
1110 	int err;
1111 
1112 	/* register this driver with the USB subsystem */
1113 	err = usb_register(&peak_usb_driver);
1114 	if (err)
1115 		pr_err("%s: usb_register failed (err %d)\n",
1116 			PCAN_USB_DRIVER_NAME, err);
1117 
1118 	return err;
1119 }
1120 
peak_usb_do_device_exit(struct device * d,void * arg)1121 static int peak_usb_do_device_exit(struct device *d, void *arg)
1122 {
1123 	struct usb_interface *intf = to_usb_interface(d);
1124 	struct peak_usb_device *dev;
1125 
1126 	/* stop as many netdev devices as siblings */
1127 	for (dev = usb_get_intfdata(intf); dev; dev = dev->prev_siblings) {
1128 		struct net_device *netdev = dev->netdev;
1129 
1130 		if (netif_device_present(netdev))
1131 			if (dev->adapter->dev_exit)
1132 				dev->adapter->dev_exit(dev);
1133 	}
1134 
1135 	return 0;
1136 }
1137 
peak_usb_exit(void)1138 static void __exit peak_usb_exit(void)
1139 {
1140 	int err;
1141 
1142 	/* last chance do send any synchronous commands here */
1143 	err = driver_for_each_device(&peak_usb_driver.driver, NULL,
1144 				     NULL, peak_usb_do_device_exit);
1145 	if (err)
1146 		pr_err("%s: failed to stop all can devices (err %d)\n",
1147 			PCAN_USB_DRIVER_NAME, err);
1148 
1149 	/* deregister this driver with the USB subsystem */
1150 	usb_deregister(&peak_usb_driver);
1151 
1152 	pr_info("%s: PCAN-USB interfaces driver unloaded\n",
1153 		PCAN_USB_DRIVER_NAME);
1154 }
1155 
1156 module_init(peak_usb_init);
1157 module_exit(peak_usb_exit);
1158