xref: /linux/drivers/net/can/usb/gs_usb.c (revision bb1c928df78ee6e3665a0d013e74108cc9abf34b)
1 /* CAN driver for Geschwister Schneider USB/CAN devices
2  * and bytewerk.org candleLight USB CAN interfaces.
3  *
4  * Copyright (C) 2013-2016 Geschwister Schneider Technologie-,
5  * Entwicklungs- und Vertriebs UG (Haftungsbeschränkt).
6  * Copyright (C) 2016 Hubert Denkmair
7  *
8  * Many thanks to all socketcan devs!
9  *
10  * This program is free software; you can redistribute it and/or modify it
11  * under the terms of the GNU General Public License as published
12  * by the Free Software Foundation; version 2 of the License.
13  *
14  * This program is distributed in the hope that it will be useful, but
15  * WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17  * General Public License for more details.
18  */
19 
20 #include <linux/init.h>
21 #include <linux/signal.h>
22 #include <linux/module.h>
23 #include <linux/netdevice.h>
24 #include <linux/usb.h>
25 
26 #include <linux/can.h>
27 #include <linux/can/dev.h>
28 #include <linux/can/error.h>
29 
30 /* Device specific constants */
31 #define USB_GSUSB_1_VENDOR_ID      0x1d50
32 #define USB_GSUSB_1_PRODUCT_ID     0x606f
33 
34 #define USB_CANDLELIGHT_VENDOR_ID  0x1209
35 #define USB_CANDLELIGHT_PRODUCT_ID 0x2323
36 
37 #define GSUSB_ENDPOINT_IN          1
38 #define GSUSB_ENDPOINT_OUT         2
39 
40 /* Device specific constants */
41 enum gs_usb_breq {
42 	GS_USB_BREQ_HOST_FORMAT = 0,
43 	GS_USB_BREQ_BITTIMING,
44 	GS_USB_BREQ_MODE,
45 	GS_USB_BREQ_BERR,
46 	GS_USB_BREQ_BT_CONST,
47 	GS_USB_BREQ_DEVICE_CONFIG,
48 	GS_USB_BREQ_TIMESTAMP,
49 	GS_USB_BREQ_IDENTIFY,
50 };
51 
52 enum gs_can_mode {
53 	/* reset a channel. turns it off */
54 	GS_CAN_MODE_RESET = 0,
55 	/* starts a channel */
56 	GS_CAN_MODE_START
57 };
58 
59 enum gs_can_state {
60 	GS_CAN_STATE_ERROR_ACTIVE = 0,
61 	GS_CAN_STATE_ERROR_WARNING,
62 	GS_CAN_STATE_ERROR_PASSIVE,
63 	GS_CAN_STATE_BUS_OFF,
64 	GS_CAN_STATE_STOPPED,
65 	GS_CAN_STATE_SLEEPING
66 };
67 
68 enum gs_can_identify_mode {
69 	GS_CAN_IDENTIFY_OFF = 0,
70 	GS_CAN_IDENTIFY_ON
71 };
72 
73 /* data types passed between host and device */
74 struct gs_host_config {
75 	u32 byte_order;
76 } __packed;
77 /* All data exchanged between host and device is exchanged in host byte order,
78  * thanks to the struct gs_host_config byte_order member, which is sent first
79  * to indicate the desired byte order.
80  */
81 
82 struct gs_device_config {
83 	u8 reserved1;
84 	u8 reserved2;
85 	u8 reserved3;
86 	u8 icount;
87 	u32 sw_version;
88 	u32 hw_version;
89 } __packed;
90 
91 #define GS_CAN_MODE_NORMAL               0
92 #define GS_CAN_MODE_LISTEN_ONLY          BIT(0)
93 #define GS_CAN_MODE_LOOP_BACK            BIT(1)
94 #define GS_CAN_MODE_TRIPLE_SAMPLE        BIT(2)
95 #define GS_CAN_MODE_ONE_SHOT             BIT(3)
96 
97 struct gs_device_mode {
98 	u32 mode;
99 	u32 flags;
100 } __packed;
101 
102 struct gs_device_state {
103 	u32 state;
104 	u32 rxerr;
105 	u32 txerr;
106 } __packed;
107 
108 struct gs_device_bittiming {
109 	u32 prop_seg;
110 	u32 phase_seg1;
111 	u32 phase_seg2;
112 	u32 sjw;
113 	u32 brp;
114 } __packed;
115 
116 struct gs_identify_mode {
117 	u32 mode;
118 } __packed;
119 
120 #define GS_CAN_FEATURE_LISTEN_ONLY      BIT(0)
121 #define GS_CAN_FEATURE_LOOP_BACK        BIT(1)
122 #define GS_CAN_FEATURE_TRIPLE_SAMPLE    BIT(2)
123 #define GS_CAN_FEATURE_ONE_SHOT         BIT(3)
124 #define GS_CAN_FEATURE_HW_TIMESTAMP     BIT(4)
125 #define GS_CAN_FEATURE_IDENTIFY         BIT(5)
126 
127 struct gs_device_bt_const {
128 	u32 feature;
129 	u32 fclk_can;
130 	u32 tseg1_min;
131 	u32 tseg1_max;
132 	u32 tseg2_min;
133 	u32 tseg2_max;
134 	u32 sjw_max;
135 	u32 brp_min;
136 	u32 brp_max;
137 	u32 brp_inc;
138 } __packed;
139 
140 #define GS_CAN_FLAG_OVERFLOW 1
141 
142 struct gs_host_frame {
143 	u32 echo_id;
144 	u32 can_id;
145 
146 	u8 can_dlc;
147 	u8 channel;
148 	u8 flags;
149 	u8 reserved;
150 
151 	u8 data[8];
152 } __packed;
153 /* The GS USB devices make use of the same flags and masks as in
154  * linux/can.h and linux/can/error.h, and no additional mapping is necessary.
155  */
156 
157 /* Only send a max of GS_MAX_TX_URBS frames per channel at a time. */
158 #define GS_MAX_TX_URBS 10
159 /* Only launch a max of GS_MAX_RX_URBS usb requests at a time. */
160 #define GS_MAX_RX_URBS 30
161 /* Maximum number of interfaces the driver supports per device.
162  * Current hardware only supports 2 interfaces. The future may vary.
163  */
164 #define GS_MAX_INTF 2
165 
166 struct gs_tx_context {
167 	struct gs_can *dev;
168 	unsigned int echo_id;
169 };
170 
171 struct gs_can {
172 	struct can_priv can; /* must be the first member */
173 
174 	struct gs_usb *parent;
175 
176 	struct net_device *netdev;
177 	struct usb_device *udev;
178 	struct usb_interface *iface;
179 
180 	struct can_bittiming_const bt_const;
181 	unsigned int channel;	/* channel number */
182 
183 	/* This lock prevents a race condition between xmit and receive. */
184 	spinlock_t tx_ctx_lock;
185 	struct gs_tx_context tx_context[GS_MAX_TX_URBS];
186 
187 	struct usb_anchor tx_submitted;
188 	atomic_t active_tx_urbs;
189 };
190 
191 /* usb interface struct */
192 struct gs_usb {
193 	struct gs_can *canch[GS_MAX_INTF];
194 	struct usb_anchor rx_submitted;
195 	atomic_t active_channels;
196 	struct usb_device *udev;
197 };
198 
199 /* 'allocate' a tx context.
200  * returns a valid tx context or NULL if there is no space.
201  */
202 static struct gs_tx_context *gs_alloc_tx_context(struct gs_can *dev)
203 {
204 	int i = 0;
205 	unsigned long flags;
206 
207 	spin_lock_irqsave(&dev->tx_ctx_lock, flags);
208 
209 	for (; i < GS_MAX_TX_URBS; i++) {
210 		if (dev->tx_context[i].echo_id == GS_MAX_TX_URBS) {
211 			dev->tx_context[i].echo_id = i;
212 			spin_unlock_irqrestore(&dev->tx_ctx_lock, flags);
213 			return &dev->tx_context[i];
214 		}
215 	}
216 
217 	spin_unlock_irqrestore(&dev->tx_ctx_lock, flags);
218 	return NULL;
219 }
220 
221 /* releases a tx context
222  */
223 static void gs_free_tx_context(struct gs_tx_context *txc)
224 {
225 	txc->echo_id = GS_MAX_TX_URBS;
226 }
227 
228 /* Get a tx context by id.
229  */
230 static struct gs_tx_context *gs_get_tx_context(struct gs_can *dev,
231 					       unsigned int id)
232 {
233 	unsigned long flags;
234 
235 	if (id < GS_MAX_TX_URBS) {
236 		spin_lock_irqsave(&dev->tx_ctx_lock, flags);
237 		if (dev->tx_context[id].echo_id == id) {
238 			spin_unlock_irqrestore(&dev->tx_ctx_lock, flags);
239 			return &dev->tx_context[id];
240 		}
241 		spin_unlock_irqrestore(&dev->tx_ctx_lock, flags);
242 	}
243 	return NULL;
244 }
245 
246 static int gs_cmd_reset(struct gs_usb *gsusb, struct gs_can *gsdev)
247 {
248 	struct gs_device_mode *dm;
249 	struct usb_interface *intf = gsdev->iface;
250 	int rc;
251 
252 	dm = kzalloc(sizeof(*dm), GFP_KERNEL);
253 	if (!dm)
254 		return -ENOMEM;
255 
256 	dm->mode = GS_CAN_MODE_RESET;
257 
258 	rc = usb_control_msg(interface_to_usbdev(intf),
259 			     usb_sndctrlpipe(interface_to_usbdev(intf), 0),
260 			     GS_USB_BREQ_MODE,
261 			     USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_INTERFACE,
262 			     gsdev->channel,
263 			     0,
264 			     dm,
265 			     sizeof(*dm),
266 			     1000);
267 
268 	kfree(dm);
269 
270 	return rc;
271 }
272 
273 static void gs_update_state(struct gs_can *dev, struct can_frame *cf)
274 {
275 	struct can_device_stats *can_stats = &dev->can.can_stats;
276 
277 	if (cf->can_id & CAN_ERR_RESTARTED) {
278 		dev->can.state = CAN_STATE_ERROR_ACTIVE;
279 		can_stats->restarts++;
280 	} else if (cf->can_id & CAN_ERR_BUSOFF) {
281 		dev->can.state = CAN_STATE_BUS_OFF;
282 		can_stats->bus_off++;
283 	} else if (cf->can_id & CAN_ERR_CRTL) {
284 		if ((cf->data[1] & CAN_ERR_CRTL_TX_WARNING) ||
285 		    (cf->data[1] & CAN_ERR_CRTL_RX_WARNING)) {
286 			dev->can.state = CAN_STATE_ERROR_WARNING;
287 			can_stats->error_warning++;
288 		} else if ((cf->data[1] & CAN_ERR_CRTL_TX_PASSIVE) ||
289 			   (cf->data[1] & CAN_ERR_CRTL_RX_PASSIVE)) {
290 			dev->can.state = CAN_STATE_ERROR_PASSIVE;
291 			can_stats->error_passive++;
292 		} else {
293 			dev->can.state = CAN_STATE_ERROR_ACTIVE;
294 		}
295 	}
296 }
297 
298 static void gs_usb_receive_bulk_callback(struct urb *urb)
299 {
300 	struct gs_usb *usbcan = urb->context;
301 	struct gs_can *dev;
302 	struct net_device *netdev;
303 	int rc;
304 	struct net_device_stats *stats;
305 	struct gs_host_frame *hf = urb->transfer_buffer;
306 	struct gs_tx_context *txc;
307 	struct can_frame *cf;
308 	struct sk_buff *skb;
309 
310 	BUG_ON(!usbcan);
311 
312 	switch (urb->status) {
313 	case 0: /* success */
314 		break;
315 	case -ENOENT:
316 	case -ESHUTDOWN:
317 		return;
318 	default:
319 		/* do not resubmit aborted urbs. eg: when device goes down */
320 		return;
321 	}
322 
323 	/* device reports out of range channel id */
324 	if (hf->channel >= GS_MAX_INTF)
325 		goto resubmit_urb;
326 
327 	dev = usbcan->canch[hf->channel];
328 
329 	netdev = dev->netdev;
330 	stats = &netdev->stats;
331 
332 	if (!netif_device_present(netdev))
333 		return;
334 
335 	if (hf->echo_id == -1) { /* normal rx */
336 		skb = alloc_can_skb(dev->netdev, &cf);
337 		if (!skb)
338 			return;
339 
340 		cf->can_id = hf->can_id;
341 
342 		cf->can_dlc = get_can_dlc(hf->can_dlc);
343 		memcpy(cf->data, hf->data, 8);
344 
345 		/* ERROR frames tell us information about the controller */
346 		if (hf->can_id & CAN_ERR_FLAG)
347 			gs_update_state(dev, cf);
348 
349 		netdev->stats.rx_packets++;
350 		netdev->stats.rx_bytes += hf->can_dlc;
351 
352 		netif_rx(skb);
353 	} else { /* echo_id == hf->echo_id */
354 		if (hf->echo_id >= GS_MAX_TX_URBS) {
355 			netdev_err(netdev,
356 				   "Unexpected out of range echo id %d\n",
357 				   hf->echo_id);
358 			goto resubmit_urb;
359 		}
360 
361 		netdev->stats.tx_packets++;
362 		netdev->stats.tx_bytes += hf->can_dlc;
363 
364 		txc = gs_get_tx_context(dev, hf->echo_id);
365 
366 		/* bad devices send bad echo_ids. */
367 		if (!txc) {
368 			netdev_err(netdev,
369 				   "Unexpected unused echo id %d\n",
370 				   hf->echo_id);
371 			goto resubmit_urb;
372 		}
373 
374 		can_get_echo_skb(netdev, hf->echo_id);
375 
376 		gs_free_tx_context(txc);
377 
378 		netif_wake_queue(netdev);
379 	}
380 
381 	if (hf->flags & GS_CAN_FLAG_OVERFLOW) {
382 		skb = alloc_can_err_skb(netdev, &cf);
383 		if (!skb)
384 			goto resubmit_urb;
385 
386 		cf->can_id |= CAN_ERR_CRTL;
387 		cf->can_dlc = CAN_ERR_DLC;
388 		cf->data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
389 		stats->rx_over_errors++;
390 		stats->rx_errors++;
391 		netif_rx(skb);
392 	}
393 
394  resubmit_urb:
395 	usb_fill_bulk_urb(urb,
396 			  usbcan->udev,
397 			  usb_rcvbulkpipe(usbcan->udev, GSUSB_ENDPOINT_IN),
398 			  hf,
399 			  sizeof(struct gs_host_frame),
400 			  gs_usb_receive_bulk_callback,
401 			  usbcan
402 			  );
403 
404 	rc = usb_submit_urb(urb, GFP_ATOMIC);
405 
406 	/* USB failure take down all interfaces */
407 	if (rc == -ENODEV) {
408 		for (rc = 0; rc < GS_MAX_INTF; rc++) {
409 			if (usbcan->canch[rc])
410 				netif_device_detach(usbcan->canch[rc]->netdev);
411 		}
412 	}
413 }
414 
415 static int gs_usb_set_bittiming(struct net_device *netdev)
416 {
417 	struct gs_can *dev = netdev_priv(netdev);
418 	struct can_bittiming *bt = &dev->can.bittiming;
419 	struct usb_interface *intf = dev->iface;
420 	int rc;
421 	struct gs_device_bittiming *dbt;
422 
423 	dbt = kmalloc(sizeof(*dbt), GFP_KERNEL);
424 	if (!dbt)
425 		return -ENOMEM;
426 
427 	dbt->prop_seg = bt->prop_seg;
428 	dbt->phase_seg1 = bt->phase_seg1;
429 	dbt->phase_seg2 = bt->phase_seg2;
430 	dbt->sjw = bt->sjw;
431 	dbt->brp = bt->brp;
432 
433 	/* request bit timings */
434 	rc = usb_control_msg(interface_to_usbdev(intf),
435 			     usb_sndctrlpipe(interface_to_usbdev(intf), 0),
436 			     GS_USB_BREQ_BITTIMING,
437 			     USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_INTERFACE,
438 			     dev->channel,
439 			     0,
440 			     dbt,
441 			     sizeof(*dbt),
442 			     1000);
443 
444 	kfree(dbt);
445 
446 	if (rc < 0)
447 		dev_err(netdev->dev.parent, "Couldn't set bittimings (err=%d)",
448 			rc);
449 
450 	return rc;
451 }
452 
453 static void gs_usb_xmit_callback(struct urb *urb)
454 {
455 	struct gs_tx_context *txc = urb->context;
456 	struct gs_can *dev = txc->dev;
457 	struct net_device *netdev = dev->netdev;
458 
459 	if (urb->status)
460 		netdev_info(netdev, "usb xmit fail %d\n", txc->echo_id);
461 
462 	usb_free_coherent(urb->dev,
463 			  urb->transfer_buffer_length,
464 			  urb->transfer_buffer,
465 			  urb->transfer_dma);
466 
467 	atomic_dec(&dev->active_tx_urbs);
468 
469 	if (!netif_device_present(netdev))
470 		return;
471 
472 	if (netif_queue_stopped(netdev))
473 		netif_wake_queue(netdev);
474 }
475 
476 static netdev_tx_t gs_can_start_xmit(struct sk_buff *skb,
477 				     struct net_device *netdev)
478 {
479 	struct gs_can *dev = netdev_priv(netdev);
480 	struct net_device_stats *stats = &dev->netdev->stats;
481 	struct urb *urb;
482 	struct gs_host_frame *hf;
483 	struct can_frame *cf;
484 	int rc;
485 	unsigned int idx;
486 	struct gs_tx_context *txc;
487 
488 	if (can_dropped_invalid_skb(netdev, skb))
489 		return NETDEV_TX_OK;
490 
491 	/* find an empty context to keep track of transmission */
492 	txc = gs_alloc_tx_context(dev);
493 	if (!txc)
494 		return NETDEV_TX_BUSY;
495 
496 	/* create a URB, and a buffer for it */
497 	urb = usb_alloc_urb(0, GFP_ATOMIC);
498 	if (!urb)
499 		goto nomem_urb;
500 
501 	hf = usb_alloc_coherent(dev->udev, sizeof(*hf), GFP_ATOMIC,
502 				&urb->transfer_dma);
503 	if (!hf) {
504 		netdev_err(netdev, "No memory left for USB buffer\n");
505 		goto nomem_hf;
506 	}
507 
508 	idx = txc->echo_id;
509 
510 	if (idx >= GS_MAX_TX_URBS) {
511 		netdev_err(netdev, "Invalid tx context %d\n", idx);
512 		goto badidx;
513 	}
514 
515 	hf->echo_id = idx;
516 	hf->channel = dev->channel;
517 
518 	cf = (struct can_frame *)skb->data;
519 
520 	hf->can_id = cf->can_id;
521 	hf->can_dlc = cf->can_dlc;
522 	memcpy(hf->data, cf->data, cf->can_dlc);
523 
524 	usb_fill_bulk_urb(urb, dev->udev,
525 			  usb_sndbulkpipe(dev->udev, GSUSB_ENDPOINT_OUT),
526 			  hf,
527 			  sizeof(*hf),
528 			  gs_usb_xmit_callback,
529 			  txc);
530 
531 	urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
532 	usb_anchor_urb(urb, &dev->tx_submitted);
533 
534 	can_put_echo_skb(skb, netdev, idx);
535 
536 	atomic_inc(&dev->active_tx_urbs);
537 
538 	rc = usb_submit_urb(urb, GFP_ATOMIC);
539 	if (unlikely(rc)) {			/* usb send failed */
540 		atomic_dec(&dev->active_tx_urbs);
541 
542 		can_free_echo_skb(netdev, idx);
543 		gs_free_tx_context(txc);
544 
545 		usb_unanchor_urb(urb);
546 		usb_free_coherent(dev->udev,
547 				  sizeof(*hf),
548 				  hf,
549 				  urb->transfer_dma);
550 
551 		if (rc == -ENODEV) {
552 			netif_device_detach(netdev);
553 		} else {
554 			netdev_err(netdev, "usb_submit failed (err=%d)\n", rc);
555 			stats->tx_dropped++;
556 		}
557 	} else {
558 		/* Slow down tx path */
559 		if (atomic_read(&dev->active_tx_urbs) >= GS_MAX_TX_URBS)
560 			netif_stop_queue(netdev);
561 	}
562 
563 	/* let usb core take care of this urb */
564 	usb_free_urb(urb);
565 
566 	return NETDEV_TX_OK;
567 
568  badidx:
569 	usb_free_coherent(dev->udev,
570 			  sizeof(*hf),
571 			  hf,
572 			  urb->transfer_dma);
573  nomem_hf:
574 	usb_free_urb(urb);
575 
576  nomem_urb:
577 	gs_free_tx_context(txc);
578 	dev_kfree_skb(skb);
579 	stats->tx_dropped++;
580 	return NETDEV_TX_OK;
581 }
582 
583 static int gs_can_open(struct net_device *netdev)
584 {
585 	struct gs_can *dev = netdev_priv(netdev);
586 	struct gs_usb *parent = dev->parent;
587 	int rc, i;
588 	struct gs_device_mode *dm;
589 	u32 ctrlmode;
590 
591 	rc = open_candev(netdev);
592 	if (rc)
593 		return rc;
594 
595 	if (atomic_add_return(1, &parent->active_channels) == 1) {
596 		for (i = 0; i < GS_MAX_RX_URBS; i++) {
597 			struct urb *urb;
598 			u8 *buf;
599 
600 			/* alloc rx urb */
601 			urb = usb_alloc_urb(0, GFP_KERNEL);
602 			if (!urb)
603 				return -ENOMEM;
604 
605 			/* alloc rx buffer */
606 			buf = usb_alloc_coherent(dev->udev,
607 						 sizeof(struct gs_host_frame),
608 						 GFP_KERNEL,
609 						 &urb->transfer_dma);
610 			if (!buf) {
611 				netdev_err(netdev,
612 					   "No memory left for USB buffer\n");
613 				usb_free_urb(urb);
614 				return -ENOMEM;
615 			}
616 
617 			/* fill, anchor, and submit rx urb */
618 			usb_fill_bulk_urb(urb,
619 					  dev->udev,
620 					  usb_rcvbulkpipe(dev->udev,
621 							  GSUSB_ENDPOINT_IN),
622 					  buf,
623 					  sizeof(struct gs_host_frame),
624 					  gs_usb_receive_bulk_callback,
625 					  parent);
626 			urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
627 
628 			usb_anchor_urb(urb, &parent->rx_submitted);
629 
630 			rc = usb_submit_urb(urb, GFP_KERNEL);
631 			if (rc) {
632 				if (rc == -ENODEV)
633 					netif_device_detach(dev->netdev);
634 
635 				netdev_err(netdev,
636 					   "usb_submit failed (err=%d)\n",
637 					   rc);
638 
639 				usb_unanchor_urb(urb);
640 				break;
641 			}
642 
643 			/* Drop reference,
644 			 * USB core will take care of freeing it
645 			 */
646 			usb_free_urb(urb);
647 		}
648 	}
649 
650 	dm = kmalloc(sizeof(*dm), GFP_KERNEL);
651 	if (!dm)
652 		return -ENOMEM;
653 
654 	/* flags */
655 	ctrlmode = dev->can.ctrlmode;
656 	dm->flags = 0;
657 
658 	if (ctrlmode & CAN_CTRLMODE_LOOPBACK)
659 		dm->flags |= GS_CAN_MODE_LOOP_BACK;
660 	else if (ctrlmode & CAN_CTRLMODE_LISTENONLY)
661 		dm->flags |= GS_CAN_MODE_LISTEN_ONLY;
662 
663 	/* Controller is not allowed to retry TX
664 	 * this mode is unavailable on atmels uc3c hardware
665 	 */
666 	if (ctrlmode & CAN_CTRLMODE_ONE_SHOT)
667 		dm->flags |= GS_CAN_MODE_ONE_SHOT;
668 
669 	if (ctrlmode & CAN_CTRLMODE_3_SAMPLES)
670 		dm->flags |= GS_CAN_MODE_TRIPLE_SAMPLE;
671 
672 	/* finally start device */
673 	dm->mode = GS_CAN_MODE_START;
674 	rc = usb_control_msg(interface_to_usbdev(dev->iface),
675 			     usb_sndctrlpipe(interface_to_usbdev(dev->iface), 0),
676 			     GS_USB_BREQ_MODE,
677 			     USB_DIR_OUT | USB_TYPE_VENDOR |
678 			     USB_RECIP_INTERFACE,
679 			     dev->channel,
680 			     0,
681 			     dm,
682 			     sizeof(*dm),
683 			     1000);
684 
685 	if (rc < 0) {
686 		netdev_err(netdev, "Couldn't start device (err=%d)\n", rc);
687 		kfree(dm);
688 		return rc;
689 	}
690 
691 	kfree(dm);
692 
693 	dev->can.state = CAN_STATE_ERROR_ACTIVE;
694 
695 	if (!(dev->can.ctrlmode & CAN_CTRLMODE_LISTENONLY))
696 		netif_start_queue(netdev);
697 
698 	return 0;
699 }
700 
701 static int gs_can_close(struct net_device *netdev)
702 {
703 	int rc;
704 	struct gs_can *dev = netdev_priv(netdev);
705 	struct gs_usb *parent = dev->parent;
706 
707 	netif_stop_queue(netdev);
708 
709 	/* Stop polling */
710 	if (atomic_dec_and_test(&parent->active_channels))
711 		usb_kill_anchored_urbs(&parent->rx_submitted);
712 
713 	/* Stop sending URBs */
714 	usb_kill_anchored_urbs(&dev->tx_submitted);
715 	atomic_set(&dev->active_tx_urbs, 0);
716 
717 	/* reset the device */
718 	rc = gs_cmd_reset(parent, dev);
719 	if (rc < 0)
720 		netdev_warn(netdev, "Couldn't shutdown device (err=%d)", rc);
721 
722 	/* reset tx contexts */
723 	for (rc = 0; rc < GS_MAX_TX_URBS; rc++) {
724 		dev->tx_context[rc].dev = dev;
725 		dev->tx_context[rc].echo_id = GS_MAX_TX_URBS;
726 	}
727 
728 	/* close the netdev */
729 	close_candev(netdev);
730 
731 	return 0;
732 }
733 
734 static const struct net_device_ops gs_usb_netdev_ops = {
735 	.ndo_open = gs_can_open,
736 	.ndo_stop = gs_can_close,
737 	.ndo_start_xmit = gs_can_start_xmit,
738 	.ndo_change_mtu = can_change_mtu,
739 };
740 
741 static int gs_usb_set_identify(struct net_device *netdev, bool do_identify)
742 {
743 	struct gs_can *dev = netdev_priv(netdev);
744 	struct gs_identify_mode *imode;
745 	int rc;
746 
747 	imode = kmalloc(sizeof(*imode), GFP_KERNEL);
748 
749 	if (!imode)
750 		return -ENOMEM;
751 
752 	if (do_identify)
753 		imode->mode = GS_CAN_IDENTIFY_ON;
754 	else
755 		imode->mode = GS_CAN_IDENTIFY_OFF;
756 
757 	rc = usb_control_msg(interface_to_usbdev(dev->iface),
758 			     usb_sndctrlpipe(interface_to_usbdev(dev->iface),
759 					     0),
760 			     GS_USB_BREQ_IDENTIFY,
761 			     USB_DIR_OUT | USB_TYPE_VENDOR |
762 			     USB_RECIP_INTERFACE,
763 			     dev->channel,
764 			     0,
765 			     imode,
766 			     sizeof(*imode),
767 			     100);
768 
769 	kfree(imode);
770 
771 	return (rc > 0) ? 0 : rc;
772 }
773 
774 /* blink LED's for finding the this interface */
775 static int gs_usb_set_phys_id(struct net_device *dev,
776 			      enum ethtool_phys_id_state state)
777 {
778 	int rc = 0;
779 
780 	switch (state) {
781 	case ETHTOOL_ID_ACTIVE:
782 		rc = gs_usb_set_identify(dev, GS_CAN_IDENTIFY_ON);
783 		break;
784 	case ETHTOOL_ID_INACTIVE:
785 		rc = gs_usb_set_identify(dev, GS_CAN_IDENTIFY_OFF);
786 		break;
787 	default:
788 		break;
789 	}
790 
791 	return rc;
792 }
793 
794 static const struct ethtool_ops gs_usb_ethtool_ops = {
795 	.set_phys_id = gs_usb_set_phys_id,
796 };
797 
798 static struct gs_can *gs_make_candev(unsigned int channel,
799 				     struct usb_interface *intf,
800 				     struct gs_device_config *dconf)
801 {
802 	struct gs_can *dev;
803 	struct net_device *netdev;
804 	int rc;
805 	struct gs_device_bt_const *bt_const;
806 
807 	bt_const = kmalloc(sizeof(*bt_const), GFP_KERNEL);
808 	if (!bt_const)
809 		return ERR_PTR(-ENOMEM);
810 
811 	/* fetch bit timing constants */
812 	rc = usb_control_msg(interface_to_usbdev(intf),
813 			     usb_rcvctrlpipe(interface_to_usbdev(intf), 0),
814 			     GS_USB_BREQ_BT_CONST,
815 			     USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_INTERFACE,
816 			     channel,
817 			     0,
818 			     bt_const,
819 			     sizeof(*bt_const),
820 			     1000);
821 
822 	if (rc < 0) {
823 		dev_err(&intf->dev,
824 			"Couldn't get bit timing const for channel (err=%d)\n",
825 			rc);
826 		kfree(bt_const);
827 		return ERR_PTR(rc);
828 	}
829 
830 	/* create netdev */
831 	netdev = alloc_candev(sizeof(struct gs_can), GS_MAX_TX_URBS);
832 	if (!netdev) {
833 		dev_err(&intf->dev, "Couldn't allocate candev\n");
834 		kfree(bt_const);
835 		return ERR_PTR(-ENOMEM);
836 	}
837 
838 	dev = netdev_priv(netdev);
839 
840 	netdev->netdev_ops = &gs_usb_netdev_ops;
841 
842 	netdev->flags |= IFF_ECHO; /* we support full roundtrip echo */
843 
844 	/* dev settup */
845 	strcpy(dev->bt_const.name, "gs_usb");
846 	dev->bt_const.tseg1_min = bt_const->tseg1_min;
847 	dev->bt_const.tseg1_max = bt_const->tseg1_max;
848 	dev->bt_const.tseg2_min = bt_const->tseg2_min;
849 	dev->bt_const.tseg2_max = bt_const->tseg2_max;
850 	dev->bt_const.sjw_max = bt_const->sjw_max;
851 	dev->bt_const.brp_min = bt_const->brp_min;
852 	dev->bt_const.brp_max = bt_const->brp_max;
853 	dev->bt_const.brp_inc = bt_const->brp_inc;
854 
855 	dev->udev = interface_to_usbdev(intf);
856 	dev->iface = intf;
857 	dev->netdev = netdev;
858 	dev->channel = channel;
859 
860 	init_usb_anchor(&dev->tx_submitted);
861 	atomic_set(&dev->active_tx_urbs, 0);
862 	spin_lock_init(&dev->tx_ctx_lock);
863 	for (rc = 0; rc < GS_MAX_TX_URBS; rc++) {
864 		dev->tx_context[rc].dev = dev;
865 		dev->tx_context[rc].echo_id = GS_MAX_TX_URBS;
866 	}
867 
868 	/* can settup */
869 	dev->can.state = CAN_STATE_STOPPED;
870 	dev->can.clock.freq = bt_const->fclk_can;
871 	dev->can.bittiming_const = &dev->bt_const;
872 	dev->can.do_set_bittiming = gs_usb_set_bittiming;
873 
874 	dev->can.ctrlmode_supported = 0;
875 
876 	if (bt_const->feature & GS_CAN_FEATURE_LISTEN_ONLY)
877 		dev->can.ctrlmode_supported |= CAN_CTRLMODE_LISTENONLY;
878 
879 	if (bt_const->feature & GS_CAN_FEATURE_LOOP_BACK)
880 		dev->can.ctrlmode_supported |= CAN_CTRLMODE_LOOPBACK;
881 
882 	if (bt_const->feature & GS_CAN_FEATURE_TRIPLE_SAMPLE)
883 		dev->can.ctrlmode_supported |= CAN_CTRLMODE_3_SAMPLES;
884 
885 	if (bt_const->feature & GS_CAN_FEATURE_ONE_SHOT)
886 		dev->can.ctrlmode_supported |= CAN_CTRLMODE_ONE_SHOT;
887 
888 	SET_NETDEV_DEV(netdev, &intf->dev);
889 
890 	if (dconf->sw_version > 1)
891 		if (bt_const->feature & GS_CAN_FEATURE_IDENTIFY)
892 			netdev->ethtool_ops = &gs_usb_ethtool_ops;
893 
894 	kfree(bt_const);
895 
896 	rc = register_candev(dev->netdev);
897 	if (rc) {
898 		free_candev(dev->netdev);
899 		dev_err(&intf->dev, "Couldn't register candev (err=%d)\n", rc);
900 		return ERR_PTR(rc);
901 	}
902 
903 	return dev;
904 }
905 
906 static void gs_destroy_candev(struct gs_can *dev)
907 {
908 	unregister_candev(dev->netdev);
909 	usb_kill_anchored_urbs(&dev->tx_submitted);
910 	free_candev(dev->netdev);
911 }
912 
913 static int gs_usb_probe(struct usb_interface *intf,
914 			const struct usb_device_id *id)
915 {
916 	struct gs_usb *dev;
917 	int rc = -ENOMEM;
918 	unsigned int icount, i;
919 	struct gs_host_config *hconf;
920 	struct gs_device_config *dconf;
921 
922 	hconf = kmalloc(sizeof(*hconf), GFP_KERNEL);
923 	if (!hconf)
924 		return -ENOMEM;
925 
926 	hconf->byte_order = 0x0000beef;
927 
928 	/* send host config */
929 	rc = usb_control_msg(interface_to_usbdev(intf),
930 			     usb_sndctrlpipe(interface_to_usbdev(intf), 0),
931 			     GS_USB_BREQ_HOST_FORMAT,
932 			     USB_DIR_OUT | USB_TYPE_VENDOR | USB_RECIP_INTERFACE,
933 			     1,
934 			     intf->altsetting[0].desc.bInterfaceNumber,
935 			     hconf,
936 			     sizeof(*hconf),
937 			     1000);
938 
939 	kfree(hconf);
940 
941 	if (rc < 0) {
942 		dev_err(&intf->dev, "Couldn't send data format (err=%d)\n",
943 			rc);
944 		return rc;
945 	}
946 
947 	dconf = kmalloc(sizeof(*dconf), GFP_KERNEL);
948 	if (!dconf)
949 		return -ENOMEM;
950 
951 	/* read device config */
952 	rc = usb_control_msg(interface_to_usbdev(intf),
953 			     usb_rcvctrlpipe(interface_to_usbdev(intf), 0),
954 			     GS_USB_BREQ_DEVICE_CONFIG,
955 			     USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_INTERFACE,
956 			     1,
957 			     intf->altsetting[0].desc.bInterfaceNumber,
958 			     dconf,
959 			     sizeof(*dconf),
960 			     1000);
961 	if (rc < 0) {
962 		dev_err(&intf->dev, "Couldn't get device config: (err=%d)\n",
963 			rc);
964 		kfree(dconf);
965 		return rc;
966 	}
967 
968 	icount = dconf->icount + 1;
969 	dev_info(&intf->dev, "Configuring for %d interfaces\n", icount);
970 
971 	if (icount > GS_MAX_INTF) {
972 		dev_err(&intf->dev,
973 			"Driver cannot handle more that %d CAN interfaces\n",
974 			GS_MAX_INTF);
975 		kfree(dconf);
976 		return -EINVAL;
977 	}
978 
979 	dev = kzalloc(sizeof(*dev), GFP_KERNEL);
980 	if (!dev) {
981 		kfree(dconf);
982 		return -ENOMEM;
983 	}
984 
985 	init_usb_anchor(&dev->rx_submitted);
986 
987 	atomic_set(&dev->active_channels, 0);
988 
989 	usb_set_intfdata(intf, dev);
990 	dev->udev = interface_to_usbdev(intf);
991 
992 	for (i = 0; i < icount; i++) {
993 		dev->canch[i] = gs_make_candev(i, intf, dconf);
994 		if (IS_ERR_OR_NULL(dev->canch[i])) {
995 			/* save error code to return later */
996 			rc = PTR_ERR(dev->canch[i]);
997 
998 			/* on failure destroy previously created candevs */
999 			icount = i;
1000 			for (i = 0; i < icount; i++)
1001 				gs_destroy_candev(dev->canch[i]);
1002 
1003 			usb_kill_anchored_urbs(&dev->rx_submitted);
1004 			kfree(dconf);
1005 			kfree(dev);
1006 			return rc;
1007 		}
1008 		dev->canch[i]->parent = dev;
1009 	}
1010 
1011 	kfree(dconf);
1012 
1013 	return 0;
1014 }
1015 
1016 static void gs_usb_disconnect(struct usb_interface *intf)
1017 {
1018 	unsigned i;
1019 	struct gs_usb *dev = usb_get_intfdata(intf);
1020 	usb_set_intfdata(intf, NULL);
1021 
1022 	if (!dev) {
1023 		dev_err(&intf->dev, "Disconnect (nodata)\n");
1024 		return;
1025 	}
1026 
1027 	for (i = 0; i < GS_MAX_INTF; i++)
1028 		if (dev->canch[i])
1029 			gs_destroy_candev(dev->canch[i]);
1030 
1031 	usb_kill_anchored_urbs(&dev->rx_submitted);
1032 	kfree(dev);
1033 }
1034 
1035 static const struct usb_device_id gs_usb_table[] = {
1036 	{ USB_DEVICE_INTERFACE_NUMBER(USB_GSUSB_1_VENDOR_ID,
1037 				      USB_GSUSB_1_PRODUCT_ID, 0) },
1038 	{ USB_DEVICE_INTERFACE_NUMBER(USB_CANDLELIGHT_VENDOR_ID,
1039 				      USB_CANDLELIGHT_PRODUCT_ID, 0) },
1040 	{} /* Terminating entry */
1041 };
1042 
1043 MODULE_DEVICE_TABLE(usb, gs_usb_table);
1044 
1045 static struct usb_driver gs_usb_driver = {
1046 	.name       = "gs_usb",
1047 	.probe      = gs_usb_probe,
1048 	.disconnect = gs_usb_disconnect,
1049 	.id_table   = gs_usb_table,
1050 };
1051 
1052 module_usb_driver(gs_usb_driver);
1053 
1054 MODULE_AUTHOR("Maximilian Schneider <mws@schneidersoft.net>");
1055 MODULE_DESCRIPTION(
1056 "Socket CAN device driver for Geschwister Schneider Technologie-, "
1057 "Entwicklungs- und Vertriebs UG. USB2.0 to CAN interfaces\n"
1058 "and bytewerk.org candleLight USB CAN interfaces.");
1059 MODULE_LICENSE("GPL v2");
1060