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