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