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 
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
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  */
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  */
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  */
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  */
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 /*
218  * post received skb after having set any hw timestamp
219  */
220 int peak_usb_netif_rx(struct sk_buff *skb,
221 		      struct peak_time_ref *time_ref, u32 ts_low)
222 {
223 	struct skb_shared_hwtstamps *hwts = skb_hwtstamps(skb);
224 
225 	peak_usb_get_ts_time(time_ref, ts_low, &hwts->hwtstamp);
226 
227 	return netif_rx(skb);
228 }
229 
230 /* post received skb with native 64-bit hw timestamp */
231 int peak_usb_netif_rx_64(struct sk_buff *skb, u32 ts_low, u32 ts_high)
232 {
233 	struct skb_shared_hwtstamps *hwts = skb_hwtstamps(skb);
234 	u64 ns_ts;
235 
236 	ns_ts = (u64)ts_high << 32 | ts_low;
237 	ns_ts *= NSEC_PER_USEC;
238 	hwts->hwtstamp = ns_to_ktime(ns_ts);
239 
240 	return netif_rx(skb);
241 }
242 
243 /*
244  * callback for bulk Rx urb
245  */
246 static void peak_usb_read_bulk_callback(struct urb *urb)
247 {
248 	struct peak_usb_device *dev = urb->context;
249 	struct net_device *netdev;
250 	int err;
251 
252 	netdev = dev->netdev;
253 
254 	if (!netif_device_present(netdev))
255 		return;
256 
257 	/* check reception status */
258 	switch (urb->status) {
259 	case 0:
260 		/* success */
261 		break;
262 
263 	case -EILSEQ:
264 	case -ENOENT:
265 	case -ECONNRESET:
266 	case -ESHUTDOWN:
267 		return;
268 
269 	default:
270 		if (net_ratelimit())
271 			netdev_err(netdev,
272 				   "Rx urb aborted (%d)\n", urb->status);
273 		goto resubmit_urb;
274 	}
275 
276 	/* protect from any incoming empty msgs */
277 	if ((urb->actual_length > 0) && (dev->adapter->dev_decode_buf)) {
278 		/* handle these kinds of msgs only if _start callback called */
279 		if (dev->state & PCAN_USB_STATE_STARTED) {
280 			err = dev->adapter->dev_decode_buf(dev, urb);
281 			if (err)
282 				pcan_dump_mem("received usb message",
283 					      urb->transfer_buffer,
284 					      urb->transfer_buffer_length);
285 		}
286 	}
287 
288 resubmit_urb:
289 	usb_fill_bulk_urb(urb, dev->udev,
290 		usb_rcvbulkpipe(dev->udev, dev->ep_msg_in),
291 		urb->transfer_buffer, dev->adapter->rx_buffer_size,
292 		peak_usb_read_bulk_callback, dev);
293 
294 	usb_anchor_urb(urb, &dev->rx_submitted);
295 	err = usb_submit_urb(urb, GFP_ATOMIC);
296 	if (!err)
297 		return;
298 
299 	usb_unanchor_urb(urb);
300 
301 	if (err == -ENODEV)
302 		netif_device_detach(netdev);
303 	else
304 		netdev_err(netdev, "failed resubmitting read bulk urb: %d\n",
305 			   err);
306 }
307 
308 /*
309  * callback for bulk Tx urb
310  */
311 static void peak_usb_write_bulk_callback(struct urb *urb)
312 {
313 	struct peak_tx_urb_context *context = urb->context;
314 	struct peak_usb_device *dev;
315 	struct net_device *netdev;
316 	int tx_bytes;
317 
318 	BUG_ON(!context);
319 
320 	dev = context->dev;
321 	netdev = dev->netdev;
322 
323 	atomic_dec(&dev->active_tx_urbs);
324 
325 	if (!netif_device_present(netdev))
326 		return;
327 
328 	/* check tx status */
329 	switch (urb->status) {
330 	case 0:
331 		/* prevent tx timeout */
332 		netif_trans_update(netdev);
333 		break;
334 
335 	case -EPROTO:
336 	case -ENOENT:
337 	case -ECONNRESET:
338 	case -ESHUTDOWN:
339 		break;
340 
341 	default:
342 		if (net_ratelimit())
343 			netdev_err(netdev, "Tx urb aborted (%d)\n",
344 				   urb->status);
345 		break;
346 	}
347 
348 	/* should always release echo skb and corresponding context */
349 	tx_bytes = can_get_echo_skb(netdev, context->echo_index, NULL);
350 	context->echo_index = PCAN_USB_MAX_TX_URBS;
351 
352 	if (!urb->status) {
353 		/* transmission complete */
354 		netdev->stats.tx_packets++;
355 		netdev->stats.tx_bytes += tx_bytes;
356 
357 		/* do wakeup tx queue in case of success only */
358 		netif_wake_queue(netdev);
359 	}
360 }
361 
362 /*
363  * called by netdev to send one skb on the CAN interface.
364  */
365 static netdev_tx_t peak_usb_ndo_start_xmit(struct sk_buff *skb,
366 					   struct net_device *netdev)
367 {
368 	struct peak_usb_device *dev = netdev_priv(netdev);
369 	struct peak_tx_urb_context *context = NULL;
370 	struct net_device_stats *stats = &netdev->stats;
371 	struct urb *urb;
372 	u8 *obuf;
373 	int i, err;
374 	size_t size = dev->adapter->tx_buffer_size;
375 
376 	if (can_dev_dropped_skb(netdev, skb))
377 		return NETDEV_TX_OK;
378 
379 	for (i = 0; i < PCAN_USB_MAX_TX_URBS; i++)
380 		if (dev->tx_contexts[i].echo_index == PCAN_USB_MAX_TX_URBS) {
381 			context = dev->tx_contexts + i;
382 			break;
383 		}
384 
385 	if (!context) {
386 		/* should not occur except during restart */
387 		return NETDEV_TX_BUSY;
388 	}
389 
390 	urb = context->urb;
391 	obuf = urb->transfer_buffer;
392 
393 	err = dev->adapter->dev_encode_msg(dev, skb, obuf, &size);
394 	if (err) {
395 		if (net_ratelimit())
396 			netdev_err(netdev, "packet dropped\n");
397 		dev_kfree_skb(skb);
398 		stats->tx_dropped++;
399 		return NETDEV_TX_OK;
400 	}
401 
402 	context->echo_index = i;
403 
404 	usb_anchor_urb(urb, &dev->tx_submitted);
405 
406 	can_put_echo_skb(skb, netdev, context->echo_index, 0);
407 
408 	atomic_inc(&dev->active_tx_urbs);
409 
410 	err = usb_submit_urb(urb, GFP_ATOMIC);
411 	if (err) {
412 		can_free_echo_skb(netdev, context->echo_index, NULL);
413 
414 		usb_unanchor_urb(urb);
415 
416 		/* this context is not used in fact */
417 		context->echo_index = PCAN_USB_MAX_TX_URBS;
418 
419 		atomic_dec(&dev->active_tx_urbs);
420 
421 		switch (err) {
422 		case -ENODEV:
423 			netif_device_detach(netdev);
424 			break;
425 		default:
426 			netdev_warn(netdev, "tx urb submitting failed err=%d\n",
427 				    err);
428 			fallthrough;
429 		case -ENOENT:
430 			/* cable unplugged */
431 			stats->tx_dropped++;
432 		}
433 	} else {
434 		netif_trans_update(netdev);
435 
436 		/* slow down tx path */
437 		if (atomic_read(&dev->active_tx_urbs) >= PCAN_USB_MAX_TX_URBS)
438 			netif_stop_queue(netdev);
439 	}
440 
441 	return NETDEV_TX_OK;
442 }
443 
444 /*
445  * start the CAN interface.
446  * Rx and Tx urbs are allocated here. Rx urbs are submitted here.
447  */
448 static int peak_usb_start(struct peak_usb_device *dev)
449 {
450 	struct net_device *netdev = dev->netdev;
451 	int err, i;
452 
453 	for (i = 0; i < PCAN_USB_MAX_RX_URBS; i++) {
454 		struct urb *urb;
455 		u8 *buf;
456 
457 		/* create a URB, and a buffer for it, to receive usb messages */
458 		urb = usb_alloc_urb(0, GFP_KERNEL);
459 		if (!urb) {
460 			err = -ENOMEM;
461 			break;
462 		}
463 
464 		buf = kmalloc(dev->adapter->rx_buffer_size, GFP_KERNEL);
465 		if (!buf) {
466 			usb_free_urb(urb);
467 			err = -ENOMEM;
468 			break;
469 		}
470 
471 		usb_fill_bulk_urb(urb, dev->udev,
472 			usb_rcvbulkpipe(dev->udev, dev->ep_msg_in),
473 			buf, dev->adapter->rx_buffer_size,
474 			peak_usb_read_bulk_callback, dev);
475 
476 		/* ask last usb_free_urb() to also kfree() transfer_buffer */
477 		urb->transfer_flags |= URB_FREE_BUFFER;
478 		usb_anchor_urb(urb, &dev->rx_submitted);
479 
480 		err = usb_submit_urb(urb, GFP_KERNEL);
481 		if (err) {
482 			if (err == -ENODEV)
483 				netif_device_detach(dev->netdev);
484 
485 			usb_unanchor_urb(urb);
486 			kfree(buf);
487 			usb_free_urb(urb);
488 			break;
489 		}
490 
491 		/* drop reference, USB core will take care of freeing it */
492 		usb_free_urb(urb);
493 	}
494 
495 	/* did we submit any URBs? Warn if we was not able to submit all urbs */
496 	if (i < PCAN_USB_MAX_RX_URBS) {
497 		if (i == 0) {
498 			netdev_err(netdev, "couldn't setup any rx URB\n");
499 			return err;
500 		}
501 
502 		netdev_warn(netdev, "rx performance may be slow\n");
503 	}
504 
505 	/* pre-alloc tx buffers and corresponding urbs */
506 	for (i = 0; i < PCAN_USB_MAX_TX_URBS; i++) {
507 		struct peak_tx_urb_context *context;
508 		struct urb *urb;
509 		u8 *buf;
510 
511 		/* create a URB and a buffer for it, to transmit usb messages */
512 		urb = usb_alloc_urb(0, GFP_KERNEL);
513 		if (!urb) {
514 			err = -ENOMEM;
515 			break;
516 		}
517 
518 		buf = kmalloc(dev->adapter->tx_buffer_size, GFP_KERNEL);
519 		if (!buf) {
520 			usb_free_urb(urb);
521 			err = -ENOMEM;
522 			break;
523 		}
524 
525 		context = dev->tx_contexts + i;
526 		context->dev = dev;
527 		context->urb = urb;
528 
529 		usb_fill_bulk_urb(urb, dev->udev,
530 			usb_sndbulkpipe(dev->udev, dev->ep_msg_out),
531 			buf, dev->adapter->tx_buffer_size,
532 			peak_usb_write_bulk_callback, context);
533 
534 		/* ask last usb_free_urb() to also kfree() transfer_buffer */
535 		urb->transfer_flags |= URB_FREE_BUFFER;
536 	}
537 
538 	/* warn if we were not able to allocate enough tx contexts */
539 	if (i < PCAN_USB_MAX_TX_URBS) {
540 		if (i == 0) {
541 			netdev_err(netdev, "couldn't setup any tx URB\n");
542 			goto err_tx;
543 		}
544 
545 		netdev_warn(netdev, "tx performance may be slow\n");
546 	}
547 
548 	if (dev->adapter->dev_start) {
549 		err = dev->adapter->dev_start(dev);
550 		if (err)
551 			goto err_adapter;
552 	}
553 
554 	dev->state |= PCAN_USB_STATE_STARTED;
555 
556 	/* can set bus on now */
557 	if (dev->adapter->dev_set_bus) {
558 		err = dev->adapter->dev_set_bus(dev, 1);
559 		if (err)
560 			goto err_adapter;
561 	}
562 
563 	dev->can.state = CAN_STATE_ERROR_ACTIVE;
564 
565 	return 0;
566 
567 err_adapter:
568 	if (err == -ENODEV)
569 		netif_device_detach(dev->netdev);
570 
571 	netdev_warn(netdev, "couldn't submit control: %d\n", err);
572 
573 	for (i = 0; i < PCAN_USB_MAX_TX_URBS; i++) {
574 		usb_free_urb(dev->tx_contexts[i].urb);
575 		dev->tx_contexts[i].urb = NULL;
576 	}
577 err_tx:
578 	usb_kill_anchored_urbs(&dev->rx_submitted);
579 
580 	return err;
581 }
582 
583 /*
584  * called by netdev to open the corresponding CAN interface.
585  */
586 static int peak_usb_ndo_open(struct net_device *netdev)
587 {
588 	struct peak_usb_device *dev = netdev_priv(netdev);
589 	int err;
590 
591 	/* common open */
592 	err = open_candev(netdev);
593 	if (err)
594 		return err;
595 
596 	/* finally start device */
597 	err = peak_usb_start(dev);
598 	if (err) {
599 		netdev_err(netdev, "couldn't start device: %d\n", err);
600 		close_candev(netdev);
601 		return err;
602 	}
603 
604 	netif_start_queue(netdev);
605 
606 	return 0;
607 }
608 
609 /*
610  * unlink in-flight Rx and Tx urbs and free their memory.
611  */
612 static void peak_usb_unlink_all_urbs(struct peak_usb_device *dev)
613 {
614 	int i;
615 
616 	/* free all Rx (submitted) urbs */
617 	usb_kill_anchored_urbs(&dev->rx_submitted);
618 
619 	/* free unsubmitted Tx urbs first */
620 	for (i = 0; i < PCAN_USB_MAX_TX_URBS; i++) {
621 		struct urb *urb = dev->tx_contexts[i].urb;
622 
623 		if (!urb ||
624 		    dev->tx_contexts[i].echo_index != PCAN_USB_MAX_TX_URBS) {
625 			/*
626 			 * this urb is already released or always submitted,
627 			 * let usb core free by itself
628 			 */
629 			continue;
630 		}
631 
632 		usb_free_urb(urb);
633 		dev->tx_contexts[i].urb = NULL;
634 	}
635 
636 	/* then free all submitted Tx urbs */
637 	usb_kill_anchored_urbs(&dev->tx_submitted);
638 	atomic_set(&dev->active_tx_urbs, 0);
639 }
640 
641 /*
642  * called by netdev to close the corresponding CAN interface.
643  */
644 static int peak_usb_ndo_stop(struct net_device *netdev)
645 {
646 	struct peak_usb_device *dev = netdev_priv(netdev);
647 
648 	dev->state &= ~PCAN_USB_STATE_STARTED;
649 	netif_stop_queue(netdev);
650 
651 	close_candev(netdev);
652 
653 	dev->can.state = CAN_STATE_STOPPED;
654 
655 	/* unlink all pending urbs and free used memory */
656 	peak_usb_unlink_all_urbs(dev);
657 
658 	if (dev->adapter->dev_stop)
659 		dev->adapter->dev_stop(dev);
660 
661 	/* can set bus off now */
662 	if (dev->adapter->dev_set_bus) {
663 		int err = dev->adapter->dev_set_bus(dev, 0);
664 
665 		if (err)
666 			return err;
667 	}
668 
669 	return 0;
670 }
671 
672 /*
673  * handle end of waiting for the device to reset
674  */
675 void peak_usb_restart_complete(struct peak_usb_device *dev)
676 {
677 	/* finally MUST update can state */
678 	dev->can.state = CAN_STATE_ERROR_ACTIVE;
679 
680 	/* netdev queue can be awaken now */
681 	netif_wake_queue(dev->netdev);
682 }
683 
684 void peak_usb_async_complete(struct urb *urb)
685 {
686 	kfree(urb->transfer_buffer);
687 	usb_free_urb(urb);
688 }
689 
690 /*
691  * device (auto-)restart mechanism runs in a timer context =>
692  * MUST handle restart with asynchronous usb transfers
693  */
694 static int peak_usb_restart(struct peak_usb_device *dev)
695 {
696 	struct urb *urb;
697 	int err;
698 	u8 *buf;
699 
700 	/*
701 	 * if device doesn't define any asynchronous restart handler, simply
702 	 * wake the netdev queue up
703 	 */
704 	if (!dev->adapter->dev_restart_async) {
705 		peak_usb_restart_complete(dev);
706 		return 0;
707 	}
708 
709 	/* first allocate a urb to handle the asynchronous steps */
710 	urb = usb_alloc_urb(0, GFP_ATOMIC);
711 	if (!urb)
712 		return -ENOMEM;
713 
714 	/* also allocate enough space for the commands to send */
715 	buf = kmalloc(PCAN_USB_MAX_CMD_LEN, GFP_ATOMIC);
716 	if (!buf) {
717 		usb_free_urb(urb);
718 		return -ENOMEM;
719 	}
720 
721 	/* call the device specific handler for the restart */
722 	err = dev->adapter->dev_restart_async(dev, urb, buf);
723 	if (!err)
724 		return 0;
725 
726 	kfree(buf);
727 	usb_free_urb(urb);
728 
729 	return err;
730 }
731 
732 /*
733  * candev callback used to change CAN mode.
734  * Warning: this is called from a timer context!
735  */
736 static int peak_usb_set_mode(struct net_device *netdev, enum can_mode mode)
737 {
738 	struct peak_usb_device *dev = netdev_priv(netdev);
739 	int err = 0;
740 
741 	switch (mode) {
742 	case CAN_MODE_START:
743 		err = peak_usb_restart(dev);
744 		if (err)
745 			netdev_err(netdev, "couldn't start device (err %d)\n",
746 				   err);
747 		break;
748 
749 	default:
750 		return -EOPNOTSUPP;
751 	}
752 
753 	return err;
754 }
755 
756 /*
757  * candev callback used to set device nominal/arbitration bitrate.
758  */
759 static int peak_usb_set_bittiming(struct net_device *netdev)
760 {
761 	struct peak_usb_device *dev = netdev_priv(netdev);
762 	const struct peak_usb_adapter *pa = dev->adapter;
763 
764 	if (pa->dev_set_bittiming) {
765 		struct can_bittiming *bt = &dev->can.bittiming;
766 		int err = pa->dev_set_bittiming(dev, bt);
767 
768 		if (err)
769 			netdev_info(netdev, "couldn't set bitrate (err %d)\n",
770 				    err);
771 		return err;
772 	}
773 
774 	return 0;
775 }
776 
777 /*
778  * candev callback used to set device data bitrate.
779  */
780 static int peak_usb_set_data_bittiming(struct net_device *netdev)
781 {
782 	struct peak_usb_device *dev = netdev_priv(netdev);
783 	const struct peak_usb_adapter *pa = dev->adapter;
784 
785 	if (pa->dev_set_data_bittiming) {
786 		struct can_bittiming *bt = &dev->can.data_bittiming;
787 		int err = pa->dev_set_data_bittiming(dev, bt);
788 
789 		if (err)
790 			netdev_info(netdev,
791 				    "couldn't set data bitrate (err %d)\n",
792 				    err);
793 
794 		return err;
795 	}
796 
797 	return 0;
798 }
799 
800 static int peak_eth_ioctl(struct net_device *netdev, struct ifreq *ifr, int cmd)
801 {
802 	struct hwtstamp_config hwts_cfg = { 0 };
803 
804 	switch (cmd) {
805 	case SIOCSHWTSTAMP: /* set */
806 		if (copy_from_user(&hwts_cfg, ifr->ifr_data, sizeof(hwts_cfg)))
807 			return -EFAULT;
808 		if (hwts_cfg.tx_type == HWTSTAMP_TX_OFF &&
809 		    hwts_cfg.rx_filter == HWTSTAMP_FILTER_ALL)
810 			return 0;
811 		return -ERANGE;
812 
813 	case SIOCGHWTSTAMP: /* get */
814 		hwts_cfg.tx_type = HWTSTAMP_TX_OFF;
815 		hwts_cfg.rx_filter = HWTSTAMP_FILTER_ALL;
816 		if (copy_to_user(ifr->ifr_data, &hwts_cfg, sizeof(hwts_cfg)))
817 			return -EFAULT;
818 		return 0;
819 
820 	default:
821 		return -EOPNOTSUPP;
822 	}
823 }
824 
825 static const struct net_device_ops peak_usb_netdev_ops = {
826 	.ndo_open = peak_usb_ndo_open,
827 	.ndo_stop = peak_usb_ndo_stop,
828 	.ndo_eth_ioctl = peak_eth_ioctl,
829 	.ndo_start_xmit = peak_usb_ndo_start_xmit,
830 	.ndo_change_mtu = can_change_mtu,
831 };
832 
833 /* CAN-USB devices generally handle 32-bit CAN channel IDs.
834  * In case one doesn't, then it have to overload this function.
835  */
836 int peak_usb_get_eeprom_len(struct net_device *netdev)
837 {
838 	return sizeof(u32);
839 }
840 
841 /* Every CAN-USB device exports the dev_get_can_channel_id() operation. It is used
842  * here to fill the data buffer with the user defined CAN channel ID.
843  */
844 int peak_usb_get_eeprom(struct net_device *netdev,
845 			struct ethtool_eeprom *eeprom, u8 *data)
846 {
847 	struct peak_usb_device *dev = netdev_priv(netdev);
848 	u32 ch_id;
849 	__le32 ch_id_le;
850 	int err;
851 
852 	err = dev->adapter->dev_get_can_channel_id(dev, &ch_id);
853 	if (err)
854 		return err;
855 
856 	/* ethtool operates on individual bytes. The byte order of the CAN
857 	 * channel id in memory depends on the kernel architecture. We
858 	 * convert the CAN channel id back to the native byte order of the PEAK
859 	 * device itself to ensure that the order is consistent for all
860 	 * host architectures.
861 	 */
862 	ch_id_le = cpu_to_le32(ch_id);
863 	memcpy(data, (u8 *)&ch_id_le + eeprom->offset, eeprom->len);
864 
865 	/* update cached value */
866 	dev->can_channel_id = ch_id;
867 	return err;
868 }
869 
870 /* Every CAN-USB device exports the dev_get_can_channel_id()/dev_set_can_channel_id()
871  * operations. They are used here to set the new user defined CAN channel ID.
872  */
873 int peak_usb_set_eeprom(struct net_device *netdev,
874 			struct ethtool_eeprom *eeprom, u8 *data)
875 {
876 	struct peak_usb_device *dev = netdev_priv(netdev);
877 	u32 ch_id;
878 	__le32 ch_id_le;
879 	int err;
880 
881 	/* first, read the current user defined CAN channel ID */
882 	err = dev->adapter->dev_get_can_channel_id(dev, &ch_id);
883 	if (err) {
884 		netdev_err(netdev, "Failed to init CAN channel id (err %d)\n", err);
885 		return err;
886 	}
887 
888 	/* do update the value with user given bytes.
889 	 * ethtool operates on individual bytes. The byte order of the CAN
890 	 * channel ID in memory depends on the kernel architecture. We
891 	 * convert the CAN channel ID back to the native byte order of the PEAK
892 	 * device itself to ensure that the order is consistent for all
893 	 * host architectures.
894 	 */
895 	ch_id_le = cpu_to_le32(ch_id);
896 	memcpy((u8 *)&ch_id_le + eeprom->offset, data, eeprom->len);
897 	ch_id = le32_to_cpu(ch_id_le);
898 
899 	/* flash the new value now */
900 	err = dev->adapter->dev_set_can_channel_id(dev, ch_id);
901 	if (err) {
902 		netdev_err(netdev, "Failed to write new CAN channel id (err %d)\n",
903 			   err);
904 		return err;
905 	}
906 
907 	/* update cached value with the new one */
908 	dev->can_channel_id = ch_id;
909 
910 	return 0;
911 }
912 
913 int pcan_get_ts_info(struct net_device *dev, struct ethtool_ts_info *info)
914 {
915 	info->so_timestamping =
916 		SOF_TIMESTAMPING_TX_SOFTWARE |
917 		SOF_TIMESTAMPING_RX_SOFTWARE |
918 		SOF_TIMESTAMPING_SOFTWARE |
919 		SOF_TIMESTAMPING_RX_HARDWARE |
920 		SOF_TIMESTAMPING_RAW_HARDWARE;
921 	info->phc_index = -1;
922 	info->tx_types = BIT(HWTSTAMP_TX_OFF);
923 	info->rx_filters = BIT(HWTSTAMP_FILTER_ALL);
924 
925 	return 0;
926 }
927 
928 /*
929  * create one device which is attached to CAN controller #ctrl_idx of the
930  * usb adapter.
931  */
932 static int peak_usb_create_dev(const struct peak_usb_adapter *peak_usb_adapter,
933 			       struct usb_interface *intf, int ctrl_idx)
934 {
935 	struct usb_device *usb_dev = interface_to_usbdev(intf);
936 	int sizeof_candev = peak_usb_adapter->sizeof_dev_private;
937 	struct peak_usb_device *dev;
938 	struct net_device *netdev;
939 	int i, err;
940 	u16 tmp16;
941 
942 	if (sizeof_candev < sizeof(struct peak_usb_device))
943 		sizeof_candev = sizeof(struct peak_usb_device);
944 
945 	netdev = alloc_candev(sizeof_candev, PCAN_USB_MAX_TX_URBS);
946 	if (!netdev) {
947 		dev_err(&intf->dev, "%s: couldn't alloc candev\n",
948 			PCAN_USB_DRIVER_NAME);
949 		return -ENOMEM;
950 	}
951 
952 	dev = netdev_priv(netdev);
953 
954 	/* allocate a buffer large enough to send commands */
955 	dev->cmd_buf = kzalloc(PCAN_USB_MAX_CMD_LEN, GFP_KERNEL);
956 	if (!dev->cmd_buf) {
957 		err = -ENOMEM;
958 		goto lbl_free_candev;
959 	}
960 
961 	dev->udev = usb_dev;
962 	dev->netdev = netdev;
963 	dev->adapter = peak_usb_adapter;
964 	dev->ctrl_idx = ctrl_idx;
965 	dev->state = PCAN_USB_STATE_CONNECTED;
966 
967 	dev->ep_msg_in = peak_usb_adapter->ep_msg_in;
968 	dev->ep_msg_out = peak_usb_adapter->ep_msg_out[ctrl_idx];
969 
970 	dev->can.clock = peak_usb_adapter->clock;
971 	dev->can.bittiming_const = peak_usb_adapter->bittiming_const;
972 	dev->can.do_set_bittiming = peak_usb_set_bittiming;
973 	dev->can.data_bittiming_const = peak_usb_adapter->data_bittiming_const;
974 	dev->can.do_set_data_bittiming = peak_usb_set_data_bittiming;
975 	dev->can.do_set_mode = peak_usb_set_mode;
976 	dev->can.do_get_berr_counter = peak_usb_adapter->do_get_berr_counter;
977 	dev->can.ctrlmode_supported = peak_usb_adapter->ctrlmode_supported;
978 
979 	netdev->netdev_ops = &peak_usb_netdev_ops;
980 
981 	netdev->flags |= IFF_ECHO; /* we support local echo */
982 
983 	/* add ethtool support */
984 	netdev->ethtool_ops = peak_usb_adapter->ethtool_ops;
985 
986 	/* register peak_usb sysfs files */
987 	netdev->sysfs_groups[0] = &peak_usb_sysfs_group;
988 
989 	init_usb_anchor(&dev->rx_submitted);
990 
991 	init_usb_anchor(&dev->tx_submitted);
992 	atomic_set(&dev->active_tx_urbs, 0);
993 
994 	for (i = 0; i < PCAN_USB_MAX_TX_URBS; i++)
995 		dev->tx_contexts[i].echo_index = PCAN_USB_MAX_TX_URBS;
996 
997 	dev->prev_siblings = usb_get_intfdata(intf);
998 	usb_set_intfdata(intf, dev);
999 
1000 	SET_NETDEV_DEV(netdev, &intf->dev);
1001 	netdev->dev_id = ctrl_idx;
1002 
1003 	err = register_candev(netdev);
1004 	if (err) {
1005 		dev_err(&intf->dev, "couldn't register CAN device: %d\n", err);
1006 		goto lbl_restore_intf_data;
1007 	}
1008 
1009 	if (dev->prev_siblings)
1010 		(dev->prev_siblings)->next_siblings = dev;
1011 
1012 	/* keep hw revision into the netdevice */
1013 	tmp16 = le16_to_cpu(usb_dev->descriptor.bcdDevice);
1014 	dev->device_rev = tmp16 >> 8;
1015 
1016 	if (dev->adapter->dev_init) {
1017 		err = dev->adapter->dev_init(dev);
1018 		if (err)
1019 			goto lbl_unregister_candev;
1020 	}
1021 
1022 	/* set bus off */
1023 	if (dev->adapter->dev_set_bus) {
1024 		err = dev->adapter->dev_set_bus(dev, 0);
1025 		if (err)
1026 			goto adap_dev_free;
1027 	}
1028 
1029 	/* get CAN channel id early */
1030 	dev->adapter->dev_get_can_channel_id(dev, &dev->can_channel_id);
1031 
1032 	netdev_info(netdev, "attached to %s channel %u (device 0x%08X)\n",
1033 		    peak_usb_adapter->name, ctrl_idx, dev->can_channel_id);
1034 
1035 	return 0;
1036 
1037 adap_dev_free:
1038 	if (dev->adapter->dev_free)
1039 		dev->adapter->dev_free(dev);
1040 
1041 lbl_unregister_candev:
1042 	unregister_candev(netdev);
1043 
1044 lbl_restore_intf_data:
1045 	usb_set_intfdata(intf, dev->prev_siblings);
1046 	kfree(dev->cmd_buf);
1047 
1048 lbl_free_candev:
1049 	free_candev(netdev);
1050 
1051 	return err;
1052 }
1053 
1054 /*
1055  * called by the usb core when the device is unplugged from the system
1056  */
1057 static void peak_usb_disconnect(struct usb_interface *intf)
1058 {
1059 	struct peak_usb_device *dev;
1060 	struct peak_usb_device *dev_prev_siblings;
1061 
1062 	/* unregister as many netdev devices as siblings */
1063 	for (dev = usb_get_intfdata(intf); dev; dev = dev_prev_siblings) {
1064 		struct net_device *netdev = dev->netdev;
1065 		char name[IFNAMSIZ];
1066 
1067 		dev_prev_siblings = dev->prev_siblings;
1068 		dev->state &= ~PCAN_USB_STATE_CONNECTED;
1069 		strscpy(name, netdev->name, IFNAMSIZ);
1070 
1071 		unregister_candev(netdev);
1072 
1073 		kfree(dev->cmd_buf);
1074 		dev->next_siblings = NULL;
1075 		if (dev->adapter->dev_free)
1076 			dev->adapter->dev_free(dev);
1077 
1078 		free_candev(netdev);
1079 		dev_info(&intf->dev, "%s removed\n", name);
1080 	}
1081 
1082 	usb_set_intfdata(intf, NULL);
1083 }
1084 
1085 /*
1086  * probe function for new PEAK-System devices
1087  */
1088 static int peak_usb_probe(struct usb_interface *intf,
1089 			  const struct usb_device_id *id)
1090 {
1091 	const struct peak_usb_adapter *peak_usb_adapter;
1092 	int i, err = -ENOMEM;
1093 
1094 	/* get corresponding PCAN-USB adapter */
1095 	peak_usb_adapter = (const struct peak_usb_adapter *)id->driver_info;
1096 
1097 	/* got corresponding adapter: check if it handles current interface */
1098 	if (peak_usb_adapter->intf_probe) {
1099 		err = peak_usb_adapter->intf_probe(intf);
1100 		if (err)
1101 			return err;
1102 	}
1103 
1104 	for (i = 0; i < peak_usb_adapter->ctrl_count; i++) {
1105 		err = peak_usb_create_dev(peak_usb_adapter, intf, i);
1106 		if (err) {
1107 			/* deregister already created devices */
1108 			peak_usb_disconnect(intf);
1109 			break;
1110 		}
1111 	}
1112 
1113 	return err;
1114 }
1115 
1116 /* usb specific object needed to register this driver with the usb subsystem */
1117 static struct usb_driver peak_usb_driver = {
1118 	.name = PCAN_USB_DRIVER_NAME,
1119 	.disconnect = peak_usb_disconnect,
1120 	.probe = peak_usb_probe,
1121 	.id_table = peak_usb_table,
1122 };
1123 
1124 static int __init peak_usb_init(void)
1125 {
1126 	int err;
1127 
1128 	/* register this driver with the USB subsystem */
1129 	err = usb_register(&peak_usb_driver);
1130 	if (err)
1131 		pr_err("%s: usb_register failed (err %d)\n",
1132 			PCAN_USB_DRIVER_NAME, err);
1133 
1134 	return err;
1135 }
1136 
1137 static int peak_usb_do_device_exit(struct device *d, void *arg)
1138 {
1139 	struct usb_interface *intf = to_usb_interface(d);
1140 	struct peak_usb_device *dev;
1141 
1142 	/* stop as many netdev devices as siblings */
1143 	for (dev = usb_get_intfdata(intf); dev; dev = dev->prev_siblings) {
1144 		struct net_device *netdev = dev->netdev;
1145 
1146 		if (netif_device_present(netdev))
1147 			if (dev->adapter->dev_exit)
1148 				dev->adapter->dev_exit(dev);
1149 	}
1150 
1151 	return 0;
1152 }
1153 
1154 static void __exit peak_usb_exit(void)
1155 {
1156 	int err;
1157 
1158 	/* last chance do send any synchronous commands here */
1159 	err = driver_for_each_device(&peak_usb_driver.drvwrap.driver, NULL,
1160 				     NULL, peak_usb_do_device_exit);
1161 	if (err)
1162 		pr_err("%s: failed to stop all can devices (err %d)\n",
1163 			PCAN_USB_DRIVER_NAME, err);
1164 
1165 	/* deregister this driver with the USB subsystem */
1166 	usb_deregister(&peak_usb_driver);
1167 
1168 	pr_info("%s: PCAN-USB interfaces driver unloaded\n",
1169 		PCAN_USB_DRIVER_NAME);
1170 }
1171 
1172 module_init(peak_usb_init);
1173 module_exit(peak_usb_exit);
1174