xref: /openbmc/linux/drivers/net/can/usb/ucan.c (revision a44e4f3a)
1 // SPDX-License-Identifier: GPL-2.0
2 
3 /* Driver for Theobroma Systems UCAN devices, Protocol Version 3
4  *
5  * Copyright (C) 2018 Theobroma Systems Design und Consulting GmbH
6  *
7  *
8  * General Description:
9  *
10  * The USB Device uses three Endpoints:
11  *
12  *   CONTROL Endpoint: Is used the setup the device (start, stop,
13  *   info, configure).
14  *
15  *   IN Endpoint: The device sends CAN Frame Messages and Device
16  *   Information using the IN endpoint.
17  *
18  *   OUT Endpoint: The driver sends configuration requests, and CAN
19  *   Frames on the out endpoint.
20  *
21  * Error Handling:
22  *
23  *   If error reporting is turned on the device encodes error into CAN
24  *   error frames (see uapi/linux/can/error.h) and sends it using the
25  *   IN Endpoint. The driver updates statistics and forward it.
26  */
27 
28 #include <linux/can.h>
29 #include <linux/can/dev.h>
30 #include <linux/can/error.h>
31 #include <linux/module.h>
32 #include <linux/netdevice.h>
33 #include <linux/signal.h>
34 #include <linux/skbuff.h>
35 #include <linux/slab.h>
36 #include <linux/usb.h>
37 
38 #define UCAN_DRIVER_NAME "ucan"
39 #define UCAN_MAX_RX_URBS 8
40 /* the CAN controller needs a while to enable/disable the bus */
41 #define UCAN_USB_CTL_PIPE_TIMEOUT 1000
42 /* this driver currently supports protocol version 3 only */
43 #define UCAN_PROTOCOL_VERSION_MIN 3
44 #define UCAN_PROTOCOL_VERSION_MAX 3
45 
46 /* UCAN Message Definitions
47  * ------------------------
48  *
49  *  ucan_message_out_t and ucan_message_in_t define the messages
50  *  transmitted on the OUT and IN endpoint.
51  *
52  *  Multibyte fields are transmitted with little endianness
53  *
54  *  INTR Endpoint: a single uint32_t storing the current space in the fifo
55  *
56  *  OUT Endpoint: single message of type ucan_message_out_t is
57  *    transmitted on the out endpoint
58  *
59  *  IN Endpoint: multiple messages ucan_message_in_t concateted in
60  *    the following way:
61  *
62  *	m[n].len <=> the length if message n(including the header in bytes)
63  *	m[n] is is aligned to a 4 byte boundary, hence
64  *	  offset(m[0])	 := 0;
65  *	  offset(m[n+1]) := offset(m[n]) + (m[n].len + 3) & 3
66  *
67  *	this implies that
68  *	  offset(m[n]) % 4 <=> 0
69  */
70 
71 /* Device Global Commands */
72 enum {
73 	UCAN_DEVICE_GET_FW_STRING = 0,
74 };
75 
76 /* UCAN Commands */
77 enum {
78 	/* start the can transceiver - val defines the operation mode */
79 	UCAN_COMMAND_START = 0,
80 	/* cancel pending transmissions and stop the can transceiver */
81 	UCAN_COMMAND_STOP = 1,
82 	/* send can transceiver into low-power sleep mode */
83 	UCAN_COMMAND_SLEEP = 2,
84 	/* wake up can transceiver from low-power sleep mode */
85 	UCAN_COMMAND_WAKEUP = 3,
86 	/* reset the can transceiver */
87 	UCAN_COMMAND_RESET = 4,
88 	/* get piece of info from the can transceiver - subcmd defines what
89 	 * piece
90 	 */
91 	UCAN_COMMAND_GET = 5,
92 	/* clear or disable hardware filter - subcmd defines which of the two */
93 	UCAN_COMMAND_FILTER = 6,
94 	/* Setup bittiming */
95 	UCAN_COMMAND_SET_BITTIMING = 7,
96 	/* recover from bus-off state */
97 	UCAN_COMMAND_RESTART = 8,
98 };
99 
100 /* UCAN_COMMAND_START and UCAN_COMMAND_GET_INFO operation modes (bitmap).
101  * Undefined bits must be set to 0.
102  */
103 enum {
104 	UCAN_MODE_LOOPBACK = BIT(0),
105 	UCAN_MODE_SILENT = BIT(1),
106 	UCAN_MODE_3_SAMPLES = BIT(2),
107 	UCAN_MODE_ONE_SHOT = BIT(3),
108 	UCAN_MODE_BERR_REPORT = BIT(4),
109 };
110 
111 /* UCAN_COMMAND_GET subcommands */
112 enum {
113 	UCAN_COMMAND_GET_INFO = 0,
114 	UCAN_COMMAND_GET_PROTOCOL_VERSION = 1,
115 };
116 
117 /* UCAN_COMMAND_FILTER subcommands */
118 enum {
119 	UCAN_FILTER_CLEAR = 0,
120 	UCAN_FILTER_DISABLE = 1,
121 	UCAN_FILTER_ENABLE = 2,
122 };
123 
124 /* OUT endpoint message types */
125 enum {
126 	UCAN_OUT_TX = 2,     /* transmit a CAN frame */
127 };
128 
129 /* IN endpoint message types */
130 enum {
131 	UCAN_IN_TX_COMPLETE = 1,  /* CAN frame transmission completed */
132 	UCAN_IN_RX = 2,           /* CAN frame received */
133 };
134 
135 struct ucan_ctl_cmd_start {
136 	__le16 mode;         /* OR-ing any of UCAN_MODE_* */
137 } __packed;
138 
139 struct ucan_ctl_cmd_set_bittiming {
140 	__le32 tq;           /* Time quanta (TQ) in nanoseconds */
141 	__le16 brp;          /* TQ Prescaler */
142 	__le16 sample_point; /* Samplepoint on tenth percent */
143 	u8 prop_seg;         /* Propagation segment in TQs */
144 	u8 phase_seg1;       /* Phase buffer segment 1 in TQs */
145 	u8 phase_seg2;       /* Phase buffer segment 2 in TQs */
146 	u8 sjw;              /* Synchronisation jump width in TQs */
147 } __packed;
148 
149 struct ucan_ctl_cmd_device_info {
150 	__le32 freq;         /* Clock Frequency for tq generation */
151 	u8 tx_fifo;          /* Size of the transmission fifo */
152 	u8 sjw_max;          /* can_bittiming fields... */
153 	u8 tseg1_min;
154 	u8 tseg1_max;
155 	u8 tseg2_min;
156 	u8 tseg2_max;
157 	__le16 brp_inc;
158 	__le32 brp_min;
159 	__le32 brp_max;      /* ...can_bittiming fields */
160 	__le16 ctrlmodes;    /* supported control modes */
161 	__le16 hwfilter;     /* Number of HW filter banks */
162 	__le16 rxmboxes;     /* Number of receive Mailboxes */
163 } __packed;
164 
165 struct ucan_ctl_cmd_get_protocol_version {
166 	__le32 version;
167 } __packed;
168 
169 union ucan_ctl_payload {
170 	/* Setup Bittiming
171 	 * bmRequest == UCAN_COMMAND_START
172 	 */
173 	struct ucan_ctl_cmd_start cmd_start;
174 	/* Setup Bittiming
175 	 * bmRequest == UCAN_COMMAND_SET_BITTIMING
176 	 */
177 	struct ucan_ctl_cmd_set_bittiming cmd_set_bittiming;
178 	/* Get Device Information
179 	 * bmRequest == UCAN_COMMAND_GET; wValue = UCAN_COMMAND_GET_INFO
180 	 */
181 	struct ucan_ctl_cmd_device_info cmd_get_device_info;
182 	/* Get Protocol Version
183 	 * bmRequest == UCAN_COMMAND_GET;
184 	 * wValue = UCAN_COMMAND_GET_PROTOCOL_VERSION
185 	 */
186 	struct ucan_ctl_cmd_get_protocol_version cmd_get_protocol_version;
187 
188 	u8 raw[128];
189 } __packed;
190 
191 enum {
192 	UCAN_TX_COMPLETE_SUCCESS = BIT(0),
193 };
194 
195 /* Transmission Complete within ucan_message_in */
196 struct ucan_tx_complete_entry_t {
197 	u8 echo_index;
198 	u8 flags;
199 } __packed __aligned(0x2);
200 
201 /* CAN Data message format within ucan_message_in/out */
202 struct ucan_can_msg {
203 	/* note DLC is computed by
204 	 *    msg.len - sizeof (msg.len)
205 	 *            - sizeof (msg.type)
206 	 *            - sizeof (msg.can_msg.id)
207 	 */
208 	__le32 id;
209 
210 	union {
211 		u8 data[CAN_MAX_DLEN];  /* Data of CAN frames */
212 		u8 dlc;                 /* RTR dlc */
213 	};
214 } __packed;
215 
216 /* OUT Endpoint, outbound messages */
217 struct ucan_message_out {
218 	__le16 len; /* Length of the content include header */
219 	u8 type;    /* UCAN_OUT_TX and friends */
220 	u8 subtype; /* command sub type */
221 
222 	union {
223 		/* Transmit CAN frame
224 		 * (type == UCAN_TX) && ((msg.can_msg.id & CAN_RTR_FLAG) == 0)
225 		 * subtype stores the echo id
226 		 */
227 		struct ucan_can_msg can_msg;
228 	} msg;
229 } __packed __aligned(0x4);
230 
231 /* IN Endpoint, inbound messages */
232 struct ucan_message_in {
233 	__le16 len; /* Length of the content include header */
234 	u8 type;    /* UCAN_IN_RX and friends */
235 	u8 subtype; /* command sub type */
236 
237 	union {
238 		/* CAN Frame received
239 		 * (type == UCAN_IN_RX)
240 		 * && ((msg.can_msg.id & CAN_RTR_FLAG) == 0)
241 		 */
242 		struct ucan_can_msg can_msg;
243 
244 		/* CAN transmission complete
245 		 * (type == UCAN_IN_TX_COMPLETE)
246 		 */
247 		struct ucan_tx_complete_entry_t can_tx_complete_msg[0];
248 	} __aligned(0x4) msg;
249 } __packed;
250 
251 /* Macros to calculate message lengths */
252 #define UCAN_OUT_HDR_SIZE offsetof(struct ucan_message_out, msg)
253 
254 #define UCAN_IN_HDR_SIZE offsetof(struct ucan_message_in, msg)
255 #define UCAN_IN_LEN(member) (UCAN_OUT_HDR_SIZE + sizeof(member))
256 
257 struct ucan_priv;
258 
259 /* Context Information for transmission URBs */
260 struct ucan_urb_context {
261 	struct ucan_priv *up;
262 	u8 dlc;
263 	bool allocated;
264 };
265 
266 /* Information reported by the USB device */
267 struct ucan_device_info {
268 	struct can_bittiming_const bittiming_const;
269 	u8 tx_fifo;
270 };
271 
272 /* Driver private data */
273 struct ucan_priv {
274 	/* must be the first member */
275 	struct can_priv can;
276 
277 	/* linux USB device structures */
278 	struct usb_device *udev;
279 	struct usb_interface *intf;
280 	struct net_device *netdev;
281 
282 	/* lock for can->echo_skb (used around
283 	 * can_put/get/free_echo_skb
284 	 */
285 	spinlock_t echo_skb_lock;
286 
287 	/* usb device information information */
288 	u8 intf_index;
289 	u8 in_ep_addr;
290 	u8 out_ep_addr;
291 	u16 in_ep_size;
292 
293 	/* transmission and reception buffers */
294 	struct usb_anchor rx_urbs;
295 	struct usb_anchor tx_urbs;
296 
297 	union ucan_ctl_payload *ctl_msg_buffer;
298 	struct ucan_device_info device_info;
299 
300 	/* transmission control information and locks */
301 	spinlock_t context_lock;
302 	unsigned int available_tx_urbs;
303 	struct ucan_urb_context *context_array;
304 };
305 
306 static u8 ucan_get_can_dlc(struct ucan_can_msg *msg, u16 len)
307 {
308 	if (le32_to_cpu(msg->id) & CAN_RTR_FLAG)
309 		return get_can_dlc(msg->dlc);
310 	else
311 		return get_can_dlc(len - (UCAN_IN_HDR_SIZE + sizeof(msg->id)));
312 }
313 
314 static void ucan_release_context_array(struct ucan_priv *up)
315 {
316 	if (!up->context_array)
317 		return;
318 
319 	/* lock is not needed because, driver is currently opening or closing */
320 	up->available_tx_urbs = 0;
321 
322 	kfree(up->context_array);
323 	up->context_array = NULL;
324 }
325 
326 static int ucan_alloc_context_array(struct ucan_priv *up)
327 {
328 	int i;
329 
330 	/* release contexts if any */
331 	ucan_release_context_array(up);
332 
333 	up->context_array = kcalloc(up->device_info.tx_fifo,
334 				    sizeof(*up->context_array),
335 				    GFP_KERNEL);
336 	if (!up->context_array) {
337 		netdev_err(up->netdev,
338 			   "Not enough memory to allocate tx contexts\n");
339 		return -ENOMEM;
340 	}
341 
342 	for (i = 0; i < up->device_info.tx_fifo; i++) {
343 		up->context_array[i].allocated = false;
344 		up->context_array[i].up = up;
345 	}
346 
347 	/* lock is not needed because, driver is currently opening */
348 	up->available_tx_urbs = up->device_info.tx_fifo;
349 
350 	return 0;
351 }
352 
353 static struct ucan_urb_context *ucan_alloc_context(struct ucan_priv *up)
354 {
355 	int i;
356 	unsigned long flags;
357 	struct ucan_urb_context *ret = NULL;
358 
359 	if (WARN_ON_ONCE(!up->context_array))
360 		return NULL;
361 
362 	/* execute context operation atomically */
363 	spin_lock_irqsave(&up->context_lock, flags);
364 
365 	for (i = 0; i < up->device_info.tx_fifo; i++) {
366 		if (!up->context_array[i].allocated) {
367 			/* update context */
368 			ret = &up->context_array[i];
369 			up->context_array[i].allocated = true;
370 
371 			/* stop queue if necessary */
372 			up->available_tx_urbs--;
373 			if (!up->available_tx_urbs)
374 				netif_stop_queue(up->netdev);
375 
376 			break;
377 		}
378 	}
379 
380 	spin_unlock_irqrestore(&up->context_lock, flags);
381 	return ret;
382 }
383 
384 static bool ucan_release_context(struct ucan_priv *up,
385 				 struct ucan_urb_context *ctx)
386 {
387 	unsigned long flags;
388 	bool ret = false;
389 
390 	if (WARN_ON_ONCE(!up->context_array))
391 		return false;
392 
393 	/* execute context operation atomically */
394 	spin_lock_irqsave(&up->context_lock, flags);
395 
396 	/* context was not allocated, maybe the device sent garbage */
397 	if (ctx->allocated) {
398 		ctx->allocated = false;
399 
400 		/* check if the queue needs to be woken */
401 		if (!up->available_tx_urbs)
402 			netif_wake_queue(up->netdev);
403 		up->available_tx_urbs++;
404 
405 		ret = true;
406 	}
407 
408 	spin_unlock_irqrestore(&up->context_lock, flags);
409 	return ret;
410 }
411 
412 static int ucan_ctrl_command_out(struct ucan_priv *up,
413 				 u8 cmd, u16 subcmd, u16 datalen)
414 {
415 	return usb_control_msg(up->udev,
416 			       usb_sndctrlpipe(up->udev, 0),
417 			       cmd,
418 			       USB_DIR_OUT | USB_TYPE_VENDOR |
419 						USB_RECIP_INTERFACE,
420 			       subcmd,
421 			       up->intf_index,
422 			       up->ctl_msg_buffer,
423 			       datalen,
424 			       UCAN_USB_CTL_PIPE_TIMEOUT);
425 }
426 
427 static int ucan_device_request_in(struct ucan_priv *up,
428 				  u8 cmd, u16 subcmd, u16 datalen)
429 {
430 	return usb_control_msg(up->udev,
431 			       usb_rcvctrlpipe(up->udev, 0),
432 			       cmd,
433 			       USB_DIR_IN | USB_TYPE_VENDOR | USB_RECIP_DEVICE,
434 			       subcmd,
435 			       0,
436 			       up->ctl_msg_buffer,
437 			       datalen,
438 			       UCAN_USB_CTL_PIPE_TIMEOUT);
439 }
440 
441 /* Parse the device information structure reported by the device and
442  * setup private variables accordingly
443  */
444 static void ucan_parse_device_info(struct ucan_priv *up,
445 				   struct ucan_ctl_cmd_device_info *device_info)
446 {
447 	struct can_bittiming_const *bittiming =
448 		&up->device_info.bittiming_const;
449 	u16 ctrlmodes;
450 
451 	/* store the data */
452 	up->can.clock.freq = le32_to_cpu(device_info->freq);
453 	up->device_info.tx_fifo = device_info->tx_fifo;
454 	strcpy(bittiming->name, "ucan");
455 	bittiming->tseg1_min = device_info->tseg1_min;
456 	bittiming->tseg1_max = device_info->tseg1_max;
457 	bittiming->tseg2_min = device_info->tseg2_min;
458 	bittiming->tseg2_max = device_info->tseg2_max;
459 	bittiming->sjw_max = device_info->sjw_max;
460 	bittiming->brp_min = le32_to_cpu(device_info->brp_min);
461 	bittiming->brp_max = le32_to_cpu(device_info->brp_max);
462 	bittiming->brp_inc = le16_to_cpu(device_info->brp_inc);
463 
464 	ctrlmodes = le16_to_cpu(device_info->ctrlmodes);
465 
466 	up->can.ctrlmode_supported = 0;
467 
468 	if (ctrlmodes & UCAN_MODE_LOOPBACK)
469 		up->can.ctrlmode_supported |= CAN_CTRLMODE_LOOPBACK;
470 	if (ctrlmodes & UCAN_MODE_SILENT)
471 		up->can.ctrlmode_supported |= CAN_CTRLMODE_LISTENONLY;
472 	if (ctrlmodes & UCAN_MODE_3_SAMPLES)
473 		up->can.ctrlmode_supported |= CAN_CTRLMODE_3_SAMPLES;
474 	if (ctrlmodes & UCAN_MODE_ONE_SHOT)
475 		up->can.ctrlmode_supported |= CAN_CTRLMODE_ONE_SHOT;
476 	if (ctrlmodes & UCAN_MODE_BERR_REPORT)
477 		up->can.ctrlmode_supported |= CAN_CTRLMODE_BERR_REPORTING;
478 }
479 
480 /* Handle a CAN error frame that we have received from the device.
481  * Returns true if the can state has changed.
482  */
483 static bool ucan_handle_error_frame(struct ucan_priv *up,
484 				    struct ucan_message_in *m,
485 				    canid_t canid)
486 {
487 	enum can_state new_state = up->can.state;
488 	struct net_device_stats *net_stats = &up->netdev->stats;
489 	struct can_device_stats *can_stats = &up->can.can_stats;
490 
491 	if (canid & CAN_ERR_LOSTARB)
492 		can_stats->arbitration_lost++;
493 
494 	if (canid & CAN_ERR_BUSERROR)
495 		can_stats->bus_error++;
496 
497 	if (canid & CAN_ERR_ACK)
498 		net_stats->tx_errors++;
499 
500 	if (canid & CAN_ERR_BUSOFF)
501 		new_state = CAN_STATE_BUS_OFF;
502 
503 	/* controller problems, details in data[1] */
504 	if (canid & CAN_ERR_CRTL) {
505 		u8 d1 = m->msg.can_msg.data[1];
506 
507 		if (d1 & CAN_ERR_CRTL_RX_OVERFLOW)
508 			net_stats->rx_over_errors++;
509 
510 		/* controller state bits: if multiple are set the worst wins */
511 		if (d1 & CAN_ERR_CRTL_ACTIVE)
512 			new_state = CAN_STATE_ERROR_ACTIVE;
513 
514 		if (d1 & (CAN_ERR_CRTL_RX_WARNING | CAN_ERR_CRTL_TX_WARNING))
515 			new_state = CAN_STATE_ERROR_WARNING;
516 
517 		if (d1 & (CAN_ERR_CRTL_RX_PASSIVE | CAN_ERR_CRTL_TX_PASSIVE))
518 			new_state = CAN_STATE_ERROR_PASSIVE;
519 	}
520 
521 	/* protocol error, details in data[2] */
522 	if (canid & CAN_ERR_PROT) {
523 		u8 d2 = m->msg.can_msg.data[2];
524 
525 		if (d2 & CAN_ERR_PROT_TX)
526 			net_stats->tx_errors++;
527 		else
528 			net_stats->rx_errors++;
529 	}
530 
531 	/* no state change - we are done */
532 	if (up->can.state == new_state)
533 		return false;
534 
535 	/* we switched into a better state */
536 	if (up->can.state > new_state) {
537 		up->can.state = new_state;
538 		return true;
539 	}
540 
541 	/* we switched into a worse state */
542 	up->can.state = new_state;
543 	switch (new_state) {
544 	case CAN_STATE_BUS_OFF:
545 		can_stats->bus_off++;
546 		can_bus_off(up->netdev);
547 		break;
548 	case CAN_STATE_ERROR_PASSIVE:
549 		can_stats->error_passive++;
550 		break;
551 	case CAN_STATE_ERROR_WARNING:
552 		can_stats->error_warning++;
553 		break;
554 	default:
555 		break;
556 	}
557 	return true;
558 }
559 
560 /* Callback on reception of a can frame via the IN endpoint
561  *
562  * This function allocates an skb and transferres it to the Linux
563  * network stack
564  */
565 static void ucan_rx_can_msg(struct ucan_priv *up, struct ucan_message_in *m)
566 {
567 	int len;
568 	canid_t canid;
569 	struct can_frame *cf;
570 	struct sk_buff *skb;
571 	struct net_device_stats *stats = &up->netdev->stats;
572 
573 	/* get the contents of the length field */
574 	len = le16_to_cpu(m->len);
575 
576 	/* check sanity */
577 	if (len < UCAN_IN_HDR_SIZE + sizeof(m->msg.can_msg.id)) {
578 		netdev_warn(up->netdev, "invalid input message len: %d\n", len);
579 		return;
580 	}
581 
582 	/* handle error frames */
583 	canid = le32_to_cpu(m->msg.can_msg.id);
584 	if (canid & CAN_ERR_FLAG) {
585 		bool busstate_changed = ucan_handle_error_frame(up, m, canid);
586 
587 		/* if berr-reporting is off only state changes get through */
588 		if (!(up->can.ctrlmode & CAN_CTRLMODE_BERR_REPORTING) &&
589 		    !busstate_changed)
590 			return;
591 	} else {
592 		canid_t canid_mask;
593 		/* compute the mask for canid */
594 		canid_mask = CAN_RTR_FLAG;
595 		if (canid & CAN_EFF_FLAG)
596 			canid_mask |= CAN_EFF_MASK | CAN_EFF_FLAG;
597 		else
598 			canid_mask |= CAN_SFF_MASK;
599 
600 		if (canid & ~canid_mask)
601 			netdev_warn(up->netdev,
602 				    "unexpected bits set (canid %x, mask %x)",
603 				    canid, canid_mask);
604 
605 		canid &= canid_mask;
606 	}
607 
608 	/* allocate skb */
609 	skb = alloc_can_skb(up->netdev, &cf);
610 	if (!skb)
611 		return;
612 
613 	/* fill the can frame */
614 	cf->can_id = canid;
615 
616 	/* compute DLC taking RTR_FLAG into account */
617 	cf->can_dlc = ucan_get_can_dlc(&m->msg.can_msg, len);
618 
619 	/* copy the payload of non RTR frames */
620 	if (!(cf->can_id & CAN_RTR_FLAG) || (cf->can_id & CAN_ERR_FLAG))
621 		memcpy(cf->data, m->msg.can_msg.data, cf->can_dlc);
622 
623 	/* don't count error frames as real packets */
624 	stats->rx_packets++;
625 	stats->rx_bytes += cf->can_dlc;
626 
627 	/* pass it to Linux */
628 	netif_rx(skb);
629 }
630 
631 /* callback indicating completed transmission */
632 static void ucan_tx_complete_msg(struct ucan_priv *up,
633 				 struct ucan_message_in *m)
634 {
635 	unsigned long flags;
636 	u16 count, i;
637 	u8 echo_index, dlc;
638 	u16 len = le16_to_cpu(m->len);
639 
640 	struct ucan_urb_context *context;
641 
642 	if (len < UCAN_IN_HDR_SIZE || (len % 2 != 0)) {
643 		netdev_err(up->netdev, "invalid tx complete length\n");
644 		return;
645 	}
646 
647 	count = (len - UCAN_IN_HDR_SIZE) / 2;
648 	for (i = 0; i < count; i++) {
649 		/* we did not submit such echo ids */
650 		echo_index = m->msg.can_tx_complete_msg[i].echo_index;
651 		if (echo_index >= up->device_info.tx_fifo) {
652 			up->netdev->stats.tx_errors++;
653 			netdev_err(up->netdev,
654 				   "invalid echo_index %d received\n",
655 				   echo_index);
656 			continue;
657 		}
658 
659 		/* gather information from the context */
660 		context = &up->context_array[echo_index];
661 		dlc = READ_ONCE(context->dlc);
662 
663 		/* Release context and restart queue if necessary.
664 		 * Also check if the context was allocated
665 		 */
666 		if (!ucan_release_context(up, context))
667 			continue;
668 
669 		spin_lock_irqsave(&up->echo_skb_lock, flags);
670 		if (m->msg.can_tx_complete_msg[i].flags &
671 		    UCAN_TX_COMPLETE_SUCCESS) {
672 			/* update statistics */
673 			up->netdev->stats.tx_packets++;
674 			up->netdev->stats.tx_bytes += dlc;
675 			can_get_echo_skb(up->netdev, echo_index);
676 		} else {
677 			up->netdev->stats.tx_dropped++;
678 			can_free_echo_skb(up->netdev, echo_index);
679 		}
680 		spin_unlock_irqrestore(&up->echo_skb_lock, flags);
681 	}
682 }
683 
684 /* callback on reception of a USB message */
685 static void ucan_read_bulk_callback(struct urb *urb)
686 {
687 	int ret;
688 	int pos;
689 	struct ucan_priv *up = urb->context;
690 	struct net_device *netdev = up->netdev;
691 	struct ucan_message_in *m;
692 
693 	/* the device is not up and the driver should not receive any
694 	 * data on the bulk in pipe
695 	 */
696 	if (WARN_ON(!up->context_array)) {
697 		usb_free_coherent(up->udev,
698 				  up->in_ep_size,
699 				  urb->transfer_buffer,
700 				  urb->transfer_dma);
701 		return;
702 	}
703 
704 	/* check URB status */
705 	switch (urb->status) {
706 	case 0:
707 		break;
708 	case -ENOENT:
709 	case -EPIPE:
710 	case -EPROTO:
711 	case -ESHUTDOWN:
712 	case -ETIME:
713 		/* urb is not resubmitted -> free dma data */
714 		usb_free_coherent(up->udev,
715 				  up->in_ep_size,
716 				  urb->transfer_buffer,
717 				  urb->transfer_dma);
718 		netdev_dbg(up->netdev, "not resubmitting urb; status: %d\n",
719 			   urb->status);
720 		return;
721 	default:
722 		goto resubmit;
723 	}
724 
725 	/* sanity check */
726 	if (!netif_device_present(netdev))
727 		return;
728 
729 	/* iterate over input */
730 	pos = 0;
731 	while (pos < urb->actual_length) {
732 		int len;
733 
734 		/* check sanity (length of header) */
735 		if ((urb->actual_length - pos) < UCAN_IN_HDR_SIZE) {
736 			netdev_warn(up->netdev,
737 				    "invalid message (short; no hdr; l:%d)\n",
738 				    urb->actual_length);
739 			goto resubmit;
740 		}
741 
742 		/* setup the message address */
743 		m = (struct ucan_message_in *)
744 			((u8 *)urb->transfer_buffer + pos);
745 		len = le16_to_cpu(m->len);
746 
747 		/* check sanity (length of content) */
748 		if (urb->actual_length - pos < len) {
749 			netdev_warn(up->netdev,
750 				    "invalid message (short; no data; l:%d)\n",
751 				    urb->actual_length);
752 			print_hex_dump(KERN_WARNING,
753 				       "raw data: ",
754 				       DUMP_PREFIX_ADDRESS,
755 				       16,
756 				       1,
757 				       urb->transfer_buffer,
758 				       urb->actual_length,
759 				       true);
760 
761 			goto resubmit;
762 		}
763 
764 		switch (m->type) {
765 		case UCAN_IN_RX:
766 			ucan_rx_can_msg(up, m);
767 			break;
768 		case UCAN_IN_TX_COMPLETE:
769 			ucan_tx_complete_msg(up, m);
770 			break;
771 		default:
772 			netdev_warn(up->netdev,
773 				    "invalid message (type; t:%d)\n",
774 				    m->type);
775 			break;
776 		}
777 
778 		/* proceed to next message */
779 		pos += len;
780 		/* align to 4 byte boundary */
781 		pos = round_up(pos, 4);
782 	}
783 
784 resubmit:
785 	/* resubmit urb when done */
786 	usb_fill_bulk_urb(urb, up->udev,
787 			  usb_rcvbulkpipe(up->udev,
788 					  up->in_ep_addr),
789 			  urb->transfer_buffer,
790 			  up->in_ep_size,
791 			  ucan_read_bulk_callback,
792 			  up);
793 
794 	usb_anchor_urb(urb, &up->rx_urbs);
795 	ret = usb_submit_urb(urb, GFP_KERNEL);
796 
797 	if (ret < 0) {
798 		netdev_err(up->netdev,
799 			   "failed resubmitting read bulk urb: %d\n",
800 			   ret);
801 
802 		usb_unanchor_urb(urb);
803 		usb_free_coherent(up->udev,
804 				  up->in_ep_size,
805 				  urb->transfer_buffer,
806 				  urb->transfer_dma);
807 
808 		if (ret == -ENODEV)
809 			netif_device_detach(netdev);
810 	}
811 }
812 
813 /* callback after transmission of a USB message */
814 static void ucan_write_bulk_callback(struct urb *urb)
815 {
816 	unsigned long flags;
817 	struct ucan_priv *up;
818 	struct ucan_urb_context *context = urb->context;
819 
820 	/* get the urb context */
821 	if (WARN_ON_ONCE(!context))
822 		return;
823 
824 	/* free up our allocated buffer */
825 	usb_free_coherent(urb->dev,
826 			  sizeof(struct ucan_message_out),
827 			  urb->transfer_buffer,
828 			  urb->transfer_dma);
829 
830 	up = context->up;
831 	if (WARN_ON_ONCE(!up))
832 		return;
833 
834 	/* sanity check */
835 	if (!netif_device_present(up->netdev))
836 		return;
837 
838 	/* transmission failed (USB - the device will not send a TX complete) */
839 	if (urb->status) {
840 		netdev_warn(up->netdev,
841 			    "failed to transmit USB message to device: %d\n",
842 			     urb->status);
843 
844 		/* update counters an cleanup */
845 		spin_lock_irqsave(&up->echo_skb_lock, flags);
846 		can_free_echo_skb(up->netdev, context - up->context_array);
847 		spin_unlock_irqrestore(&up->echo_skb_lock, flags);
848 
849 		up->netdev->stats.tx_dropped++;
850 
851 		/* release context and restart the queue if necessary */
852 		if (!ucan_release_context(up, context))
853 			netdev_err(up->netdev,
854 				   "urb failed, failed to release context\n");
855 	}
856 }
857 
858 static void ucan_cleanup_rx_urbs(struct ucan_priv *up, struct urb **urbs)
859 {
860 	int i;
861 
862 	for (i = 0; i < UCAN_MAX_RX_URBS; i++) {
863 		if (urbs[i]) {
864 			usb_unanchor_urb(urbs[i]);
865 			usb_free_coherent(up->udev,
866 					  up->in_ep_size,
867 					  urbs[i]->transfer_buffer,
868 					  urbs[i]->transfer_dma);
869 			usb_free_urb(urbs[i]);
870 		}
871 	}
872 
873 	memset(urbs, 0, sizeof(*urbs) * UCAN_MAX_RX_URBS);
874 }
875 
876 static int ucan_prepare_and_anchor_rx_urbs(struct ucan_priv *up,
877 					   struct urb **urbs)
878 {
879 	int i;
880 
881 	memset(urbs, 0, sizeof(*urbs) * UCAN_MAX_RX_URBS);
882 
883 	for (i = 0; i < UCAN_MAX_RX_URBS; i++) {
884 		void *buf;
885 
886 		urbs[i] = usb_alloc_urb(0, GFP_KERNEL);
887 		if (!urbs[i])
888 			goto err;
889 
890 		buf = usb_alloc_coherent(up->udev,
891 					 up->in_ep_size,
892 					 GFP_KERNEL, &urbs[i]->transfer_dma);
893 		if (!buf) {
894 			/* cleanup this urb */
895 			usb_free_urb(urbs[i]);
896 			urbs[i] = NULL;
897 			goto err;
898 		}
899 
900 		usb_fill_bulk_urb(urbs[i], up->udev,
901 				  usb_rcvbulkpipe(up->udev,
902 						  up->in_ep_addr),
903 				  buf,
904 				  up->in_ep_size,
905 				  ucan_read_bulk_callback,
906 				  up);
907 
908 		urbs[i]->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
909 
910 		usb_anchor_urb(urbs[i], &up->rx_urbs);
911 	}
912 	return 0;
913 
914 err:
915 	/* cleanup other unsubmitted urbs */
916 	ucan_cleanup_rx_urbs(up, urbs);
917 	return -ENOMEM;
918 }
919 
920 /* Submits rx urbs with the semantic: Either submit all, or cleanup
921  * everything. I case of errors submitted urbs are killed and all urbs in
922  * the array are freed. I case of no errors every entry in the urb
923  * array is set to NULL.
924  */
925 static int ucan_submit_rx_urbs(struct ucan_priv *up, struct urb **urbs)
926 {
927 	int i, ret;
928 
929 	/* Iterate over all urbs to submit. On success remove the urb
930 	 * from the list.
931 	 */
932 	for (i = 0; i < UCAN_MAX_RX_URBS; i++) {
933 		ret = usb_submit_urb(urbs[i], GFP_KERNEL);
934 		if (ret) {
935 			netdev_err(up->netdev,
936 				   "could not submit urb; code: %d\n",
937 				   ret);
938 			goto err;
939 		}
940 
941 		/* Anchor URB and drop reference, USB core will take
942 		 * care of freeing it
943 		 */
944 		usb_free_urb(urbs[i]);
945 		urbs[i] = NULL;
946 	}
947 	return 0;
948 
949 err:
950 	/* Cleanup unsubmitted urbs */
951 	ucan_cleanup_rx_urbs(up, urbs);
952 
953 	/* Kill urbs that are already submitted */
954 	usb_kill_anchored_urbs(&up->rx_urbs);
955 
956 	return ret;
957 }
958 
959 /* Open the network device */
960 static int ucan_open(struct net_device *netdev)
961 {
962 	int ret, ret_cleanup;
963 	u16 ctrlmode;
964 	struct urb *urbs[UCAN_MAX_RX_URBS];
965 	struct ucan_priv *up = netdev_priv(netdev);
966 
967 	ret = ucan_alloc_context_array(up);
968 	if (ret)
969 		return ret;
970 
971 	/* Allocate and prepare IN URBS - allocated and anchored
972 	 * urbs are stored in urbs[] for clean
973 	 */
974 	ret = ucan_prepare_and_anchor_rx_urbs(up, urbs);
975 	if (ret)
976 		goto err_contexts;
977 
978 	/* Check the control mode */
979 	ctrlmode = 0;
980 	if (up->can.ctrlmode & CAN_CTRLMODE_LOOPBACK)
981 		ctrlmode |= UCAN_MODE_LOOPBACK;
982 	if (up->can.ctrlmode & CAN_CTRLMODE_LISTENONLY)
983 		ctrlmode |= UCAN_MODE_SILENT;
984 	if (up->can.ctrlmode & CAN_CTRLMODE_3_SAMPLES)
985 		ctrlmode |= UCAN_MODE_3_SAMPLES;
986 	if (up->can.ctrlmode & CAN_CTRLMODE_ONE_SHOT)
987 		ctrlmode |= UCAN_MODE_ONE_SHOT;
988 
989 	/* Enable this in any case - filtering is down within the
990 	 * receive path
991 	 */
992 	ctrlmode |= UCAN_MODE_BERR_REPORT;
993 	up->ctl_msg_buffer->cmd_start.mode = cpu_to_le16(ctrlmode);
994 
995 	/* Driver is ready to receive data - start the USB device */
996 	ret = ucan_ctrl_command_out(up, UCAN_COMMAND_START, 0, 2);
997 	if (ret < 0) {
998 		netdev_err(up->netdev,
999 			   "could not start device, code: %d\n",
1000 			   ret);
1001 		goto err_reset;
1002 	}
1003 
1004 	/* Call CAN layer open */
1005 	ret = open_candev(netdev);
1006 	if (ret)
1007 		goto err_stop;
1008 
1009 	/* Driver is ready to receive data. Submit RX URBS */
1010 	ret = ucan_submit_rx_urbs(up, urbs);
1011 	if (ret)
1012 		goto err_stop;
1013 
1014 	up->can.state = CAN_STATE_ERROR_ACTIVE;
1015 
1016 	/* Start the network queue */
1017 	netif_start_queue(netdev);
1018 
1019 	return 0;
1020 
1021 err_stop:
1022 	/* The device have started already stop it */
1023 	ret_cleanup = ucan_ctrl_command_out(up, UCAN_COMMAND_STOP, 0, 0);
1024 	if (ret_cleanup < 0)
1025 		netdev_err(up->netdev,
1026 			   "could not stop device, code: %d\n",
1027 			   ret_cleanup);
1028 
1029 err_reset:
1030 	/* The device might have received data, reset it for
1031 	 * consistent state
1032 	 */
1033 	ret_cleanup = ucan_ctrl_command_out(up, UCAN_COMMAND_RESET, 0, 0);
1034 	if (ret_cleanup < 0)
1035 		netdev_err(up->netdev,
1036 			   "could not reset device, code: %d\n",
1037 			   ret_cleanup);
1038 
1039 	/* clean up unsubmitted urbs */
1040 	ucan_cleanup_rx_urbs(up, urbs);
1041 
1042 err_contexts:
1043 	ucan_release_context_array(up);
1044 	return ret;
1045 }
1046 
1047 static struct urb *ucan_prepare_tx_urb(struct ucan_priv *up,
1048 				       struct ucan_urb_context *context,
1049 				       struct can_frame *cf,
1050 				       u8 echo_index)
1051 {
1052 	int mlen;
1053 	struct urb *urb;
1054 	struct ucan_message_out *m;
1055 
1056 	/* create a URB, and a buffer for it, and copy the data to the URB */
1057 	urb = usb_alloc_urb(0, GFP_ATOMIC);
1058 	if (!urb) {
1059 		netdev_err(up->netdev, "no memory left for URBs\n");
1060 		return NULL;
1061 	}
1062 
1063 	m = usb_alloc_coherent(up->udev,
1064 			       sizeof(struct ucan_message_out),
1065 			       GFP_ATOMIC,
1066 			       &urb->transfer_dma);
1067 	if (!m) {
1068 		netdev_err(up->netdev, "no memory left for USB buffer\n");
1069 		usb_free_urb(urb);
1070 		return NULL;
1071 	}
1072 
1073 	/* build the USB message */
1074 	m->type = UCAN_OUT_TX;
1075 	m->msg.can_msg.id = cpu_to_le32(cf->can_id);
1076 
1077 	if (cf->can_id & CAN_RTR_FLAG) {
1078 		mlen = UCAN_OUT_HDR_SIZE +
1079 			offsetof(struct ucan_can_msg, dlc) +
1080 			sizeof(m->msg.can_msg.dlc);
1081 		m->msg.can_msg.dlc = cf->can_dlc;
1082 	} else {
1083 		mlen = UCAN_OUT_HDR_SIZE +
1084 			sizeof(m->msg.can_msg.id) + cf->can_dlc;
1085 		memcpy(m->msg.can_msg.data, cf->data, cf->can_dlc);
1086 	}
1087 	m->len = cpu_to_le16(mlen);
1088 
1089 	context->dlc = cf->can_dlc;
1090 
1091 	m->subtype = echo_index;
1092 
1093 	/* build the urb */
1094 	usb_fill_bulk_urb(urb, up->udev,
1095 			  usb_sndbulkpipe(up->udev,
1096 					  up->out_ep_addr),
1097 			  m, mlen, ucan_write_bulk_callback, context);
1098 	urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
1099 
1100 	return urb;
1101 }
1102 
1103 static void ucan_clean_up_tx_urb(struct ucan_priv *up, struct urb *urb)
1104 {
1105 	usb_free_coherent(up->udev, sizeof(struct ucan_message_out),
1106 			  urb->transfer_buffer, urb->transfer_dma);
1107 	usb_free_urb(urb);
1108 }
1109 
1110 /* callback when Linux needs to send a can frame */
1111 static netdev_tx_t ucan_start_xmit(struct sk_buff *skb,
1112 				   struct net_device *netdev)
1113 {
1114 	unsigned long flags;
1115 	int ret;
1116 	u8 echo_index;
1117 	struct urb *urb;
1118 	struct ucan_urb_context *context;
1119 	struct ucan_priv *up = netdev_priv(netdev);
1120 	struct can_frame *cf = (struct can_frame *)skb->data;
1121 
1122 	/* check skb */
1123 	if (can_dropped_invalid_skb(netdev, skb))
1124 		return NETDEV_TX_OK;
1125 
1126 	/* allocate a context and slow down tx path, if fifo state is low */
1127 	context = ucan_alloc_context(up);
1128 	echo_index = context - up->context_array;
1129 
1130 	if (WARN_ON_ONCE(!context))
1131 		return NETDEV_TX_BUSY;
1132 
1133 	/* prepare urb for transmission */
1134 	urb = ucan_prepare_tx_urb(up, context, cf, echo_index);
1135 	if (!urb)
1136 		goto drop;
1137 
1138 	/* put the skb on can loopback stack */
1139 	spin_lock_irqsave(&up->echo_skb_lock, flags);
1140 	can_put_echo_skb(skb, up->netdev, echo_index);
1141 	spin_unlock_irqrestore(&up->echo_skb_lock, flags);
1142 
1143 	/* transmit it */
1144 	usb_anchor_urb(urb, &up->tx_urbs);
1145 	ret = usb_submit_urb(urb, GFP_ATOMIC);
1146 
1147 	/* cleanup urb */
1148 	if (ret) {
1149 		/* on error, clean up */
1150 		usb_unanchor_urb(urb);
1151 		ucan_clean_up_tx_urb(up, urb);
1152 		if (!ucan_release_context(up, context))
1153 			netdev_err(up->netdev,
1154 				   "xmit err: failed to release context\n");
1155 
1156 		/* remove the skb from the echo stack - this also
1157 		 * frees the skb
1158 		 */
1159 		spin_lock_irqsave(&up->echo_skb_lock, flags);
1160 		can_free_echo_skb(up->netdev, echo_index);
1161 		spin_unlock_irqrestore(&up->echo_skb_lock, flags);
1162 
1163 		if (ret == -ENODEV) {
1164 			netif_device_detach(up->netdev);
1165 		} else {
1166 			netdev_warn(up->netdev,
1167 				    "xmit err: failed to submit urb %d\n",
1168 				    ret);
1169 			up->netdev->stats.tx_dropped++;
1170 		}
1171 		return NETDEV_TX_OK;
1172 	}
1173 
1174 	netif_trans_update(netdev);
1175 
1176 	/* release ref, as we do not need the urb anymore */
1177 	usb_free_urb(urb);
1178 
1179 	return NETDEV_TX_OK;
1180 
1181 drop:
1182 	if (!ucan_release_context(up, context))
1183 		netdev_err(up->netdev,
1184 			   "xmit drop: failed to release context\n");
1185 	dev_kfree_skb(skb);
1186 	up->netdev->stats.tx_dropped++;
1187 
1188 	return NETDEV_TX_OK;
1189 }
1190 
1191 /* Device goes down
1192  *
1193  * Clean up used resources
1194  */
1195 static int ucan_close(struct net_device *netdev)
1196 {
1197 	int ret;
1198 	struct ucan_priv *up = netdev_priv(netdev);
1199 
1200 	up->can.state = CAN_STATE_STOPPED;
1201 
1202 	/* stop sending data */
1203 	usb_kill_anchored_urbs(&up->tx_urbs);
1204 
1205 	/* stop receiving data */
1206 	usb_kill_anchored_urbs(&up->rx_urbs);
1207 
1208 	/* stop and reset can device */
1209 	ret = ucan_ctrl_command_out(up, UCAN_COMMAND_STOP, 0, 0);
1210 	if (ret < 0)
1211 		netdev_err(up->netdev,
1212 			   "could not stop device, code: %d\n",
1213 			   ret);
1214 
1215 	ret = ucan_ctrl_command_out(up, UCAN_COMMAND_RESET, 0, 0);
1216 	if (ret < 0)
1217 		netdev_err(up->netdev,
1218 			   "could not reset device, code: %d\n",
1219 			   ret);
1220 
1221 	netif_stop_queue(netdev);
1222 
1223 	ucan_release_context_array(up);
1224 
1225 	close_candev(up->netdev);
1226 	return 0;
1227 }
1228 
1229 /* CAN driver callbacks */
1230 static const struct net_device_ops ucan_netdev_ops = {
1231 	.ndo_open = ucan_open,
1232 	.ndo_stop = ucan_close,
1233 	.ndo_start_xmit = ucan_start_xmit,
1234 	.ndo_change_mtu = can_change_mtu,
1235 };
1236 
1237 /* Request to set bittiming
1238  *
1239  * This function generates an USB set bittiming message and transmits
1240  * it to the device
1241  */
1242 static int ucan_set_bittiming(struct net_device *netdev)
1243 {
1244 	int ret;
1245 	struct ucan_priv *up = netdev_priv(netdev);
1246 	struct ucan_ctl_cmd_set_bittiming *cmd_set_bittiming;
1247 
1248 	cmd_set_bittiming = &up->ctl_msg_buffer->cmd_set_bittiming;
1249 	cmd_set_bittiming->tq = cpu_to_le32(up->can.bittiming.tq);
1250 	cmd_set_bittiming->brp = cpu_to_le16(up->can.bittiming.brp);
1251 	cmd_set_bittiming->sample_point =
1252 	    cpu_to_le16(up->can.bittiming.sample_point);
1253 	cmd_set_bittiming->prop_seg = up->can.bittiming.prop_seg;
1254 	cmd_set_bittiming->phase_seg1 = up->can.bittiming.phase_seg1;
1255 	cmd_set_bittiming->phase_seg2 = up->can.bittiming.phase_seg2;
1256 	cmd_set_bittiming->sjw = up->can.bittiming.sjw;
1257 
1258 	ret = ucan_ctrl_command_out(up, UCAN_COMMAND_SET_BITTIMING, 0,
1259 				    sizeof(*cmd_set_bittiming));
1260 	return (ret < 0) ? ret : 0;
1261 }
1262 
1263 /* Restart the device to get it out of BUS-OFF state.
1264  * Called when the user runs "ip link set can1 type can restart".
1265  */
1266 static int ucan_set_mode(struct net_device *netdev, enum can_mode mode)
1267 {
1268 	int ret;
1269 	unsigned long flags;
1270 	struct ucan_priv *up = netdev_priv(netdev);
1271 
1272 	switch (mode) {
1273 	case CAN_MODE_START:
1274 		netdev_dbg(up->netdev, "restarting device\n");
1275 
1276 		ret = ucan_ctrl_command_out(up, UCAN_COMMAND_RESTART, 0, 0);
1277 		up->can.state = CAN_STATE_ERROR_ACTIVE;
1278 
1279 		/* check if queue can be restarted,
1280 		 * up->available_tx_urbs must be protected by the
1281 		 * lock
1282 		 */
1283 		spin_lock_irqsave(&up->context_lock, flags);
1284 
1285 		if (up->available_tx_urbs > 0)
1286 			netif_wake_queue(up->netdev);
1287 
1288 		spin_unlock_irqrestore(&up->context_lock, flags);
1289 
1290 		return ret;
1291 	default:
1292 		return -EOPNOTSUPP;
1293 	}
1294 }
1295 
1296 /* Probe the device, reset it and gather general device information */
1297 static int ucan_probe(struct usb_interface *intf,
1298 		      const struct usb_device_id *id)
1299 {
1300 	int ret;
1301 	int i;
1302 	u32 protocol_version;
1303 	struct usb_device *udev;
1304 	struct net_device *netdev;
1305 	struct usb_host_interface *iface_desc;
1306 	struct ucan_priv *up;
1307 	struct usb_endpoint_descriptor *ep;
1308 	u16 in_ep_size;
1309 	u16 out_ep_size;
1310 	u8 in_ep_addr;
1311 	u8 out_ep_addr;
1312 	union ucan_ctl_payload *ctl_msg_buffer;
1313 	char firmware_str[sizeof(union ucan_ctl_payload) + 1];
1314 
1315 	udev = interface_to_usbdev(intf);
1316 
1317 	/* Stage 1 - Interface Parsing
1318 	 * ---------------------------
1319 	 *
1320 	 * Identifie the device USB interface descriptor and its
1321 	 * endpoints. Probing is aborted on errors.
1322 	 */
1323 
1324 	/* check if the interface is sane */
1325 	iface_desc = intf->cur_altsetting;
1326 	if (!iface_desc)
1327 		return -ENODEV;
1328 
1329 	dev_info(&udev->dev,
1330 		 "%s: probing device on interface #%d\n",
1331 		 UCAN_DRIVER_NAME,
1332 		 iface_desc->desc.bInterfaceNumber);
1333 
1334 	/* interface sanity check */
1335 	if (iface_desc->desc.bNumEndpoints != 2) {
1336 		dev_err(&udev->dev,
1337 			"%s: invalid EP count (%d)",
1338 			UCAN_DRIVER_NAME, iface_desc->desc.bNumEndpoints);
1339 		goto err_firmware_needs_update;
1340 	}
1341 
1342 	/* check interface endpoints */
1343 	in_ep_addr = 0;
1344 	out_ep_addr = 0;
1345 	in_ep_size = 0;
1346 	out_ep_size = 0;
1347 	for (i = 0; i < iface_desc->desc.bNumEndpoints; i++) {
1348 		ep = &iface_desc->endpoint[i].desc;
1349 
1350 		if (((ep->bEndpointAddress & USB_ENDPOINT_DIR_MASK) != 0) &&
1351 		    ((ep->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
1352 		     USB_ENDPOINT_XFER_BULK)) {
1353 			/* In Endpoint */
1354 			in_ep_addr = ep->bEndpointAddress;
1355 			in_ep_addr &= USB_ENDPOINT_NUMBER_MASK;
1356 			in_ep_size = le16_to_cpu(ep->wMaxPacketSize);
1357 		} else if (((ep->bEndpointAddress & USB_ENDPOINT_DIR_MASK) ==
1358 			    0) &&
1359 			   ((ep->bmAttributes & USB_ENDPOINT_XFERTYPE_MASK) ==
1360 			    USB_ENDPOINT_XFER_BULK)) {
1361 			/* Out Endpoint */
1362 			out_ep_addr = ep->bEndpointAddress;
1363 			out_ep_addr &= USB_ENDPOINT_NUMBER_MASK;
1364 			out_ep_size = le16_to_cpu(ep->wMaxPacketSize);
1365 		}
1366 	}
1367 
1368 	/* check if interface is sane */
1369 	if (!in_ep_addr || !out_ep_addr) {
1370 		dev_err(&udev->dev, "%s: invalid endpoint configuration\n",
1371 			UCAN_DRIVER_NAME);
1372 		goto err_firmware_needs_update;
1373 	}
1374 	if (in_ep_size < sizeof(struct ucan_message_in)) {
1375 		dev_err(&udev->dev, "%s: invalid in_ep MaxPacketSize\n",
1376 			UCAN_DRIVER_NAME);
1377 		goto err_firmware_needs_update;
1378 	}
1379 	if (out_ep_size < sizeof(struct ucan_message_out)) {
1380 		dev_err(&udev->dev, "%s: invalid out_ep MaxPacketSize\n",
1381 			UCAN_DRIVER_NAME);
1382 		goto err_firmware_needs_update;
1383 	}
1384 
1385 	/* Stage 2 - Device Identification
1386 	 * -------------------------------
1387 	 *
1388 	 * The device interface seems to be a ucan device. Do further
1389 	 * compatibility checks. On error probing is aborted, on
1390 	 * success this stage leaves the ctl_msg_buffer with the
1391 	 * reported contents of a GET_INFO command (supported
1392 	 * bittimings, tx_fifo depth). This information is used in
1393 	 * Stage 3 for the final driver initialisation.
1394 	 */
1395 
1396 	/* Prepare Memory for control transferes */
1397 	ctl_msg_buffer = devm_kzalloc(&udev->dev,
1398 				      sizeof(union ucan_ctl_payload),
1399 				      GFP_KERNEL);
1400 	if (!ctl_msg_buffer) {
1401 		dev_err(&udev->dev,
1402 			"%s: failed to allocate control pipe memory\n",
1403 			UCAN_DRIVER_NAME);
1404 		return -ENOMEM;
1405 	}
1406 
1407 	/* get protocol version
1408 	 *
1409 	 * note: ucan_ctrl_command_* wrappers cannot be used yet
1410 	 * because `up` is initialised in Stage 3
1411 	 */
1412 	ret = usb_control_msg(udev,
1413 			      usb_rcvctrlpipe(udev, 0),
1414 			      UCAN_COMMAND_GET,
1415 			      USB_DIR_IN | USB_TYPE_VENDOR |
1416 					USB_RECIP_INTERFACE,
1417 			      UCAN_COMMAND_GET_PROTOCOL_VERSION,
1418 			      iface_desc->desc.bInterfaceNumber,
1419 			      ctl_msg_buffer,
1420 			      sizeof(union ucan_ctl_payload),
1421 			      UCAN_USB_CTL_PIPE_TIMEOUT);
1422 
1423 	/* older firmware version do not support this command - those
1424 	 * are not supported by this drive
1425 	 */
1426 	if (ret != 4) {
1427 		dev_err(&udev->dev,
1428 			"%s: could not read protocol version, ret=%d\n",
1429 			UCAN_DRIVER_NAME, ret);
1430 		if (ret >= 0)
1431 			ret = -EINVAL;
1432 		goto err_firmware_needs_update;
1433 	}
1434 
1435 	/* this driver currently supports protocol version 3 only */
1436 	protocol_version =
1437 		le32_to_cpu(ctl_msg_buffer->cmd_get_protocol_version.version);
1438 	if (protocol_version < UCAN_PROTOCOL_VERSION_MIN ||
1439 	    protocol_version > UCAN_PROTOCOL_VERSION_MAX) {
1440 		dev_err(&udev->dev,
1441 			"%s: device protocol version %d is not supported\n",
1442 			UCAN_DRIVER_NAME, protocol_version);
1443 		goto err_firmware_needs_update;
1444 	}
1445 
1446 	/* request the device information and store it in ctl_msg_buffer
1447 	 *
1448 	 * note: ucan_ctrl_command_* wrappers connot be used yet
1449 	 * because `up` is initialised in Stage 3
1450 	 */
1451 	ret = usb_control_msg(udev,
1452 			      usb_rcvctrlpipe(udev, 0),
1453 			      UCAN_COMMAND_GET,
1454 			      USB_DIR_IN | USB_TYPE_VENDOR |
1455 					USB_RECIP_INTERFACE,
1456 			      UCAN_COMMAND_GET_INFO,
1457 			      iface_desc->desc.bInterfaceNumber,
1458 			      ctl_msg_buffer,
1459 			      sizeof(ctl_msg_buffer->cmd_get_device_info),
1460 			      UCAN_USB_CTL_PIPE_TIMEOUT);
1461 
1462 	if (ret < 0) {
1463 		dev_err(&udev->dev, "%s: failed to retrieve device info\n",
1464 			UCAN_DRIVER_NAME);
1465 		goto err_firmware_needs_update;
1466 	}
1467 	if (ret < sizeof(ctl_msg_buffer->cmd_get_device_info)) {
1468 		dev_err(&udev->dev, "%s: device reported invalid device info\n",
1469 			UCAN_DRIVER_NAME);
1470 		goto err_firmware_needs_update;
1471 	}
1472 	if (ctl_msg_buffer->cmd_get_device_info.tx_fifo == 0) {
1473 		dev_err(&udev->dev,
1474 			"%s: device reported invalid tx-fifo size\n",
1475 			UCAN_DRIVER_NAME);
1476 		goto err_firmware_needs_update;
1477 	}
1478 
1479 	/* Stage 3 - Driver Initialisation
1480 	 * -------------------------------
1481 	 *
1482 	 * Register device to Linux, prepare private structures and
1483 	 * reset the device.
1484 	 */
1485 
1486 	/* allocate driver resources */
1487 	netdev = alloc_candev(sizeof(struct ucan_priv),
1488 			      ctl_msg_buffer->cmd_get_device_info.tx_fifo);
1489 	if (!netdev) {
1490 		dev_err(&udev->dev,
1491 			"%s: cannot allocate candev\n", UCAN_DRIVER_NAME);
1492 		return -ENOMEM;
1493 	}
1494 
1495 	up = netdev_priv(netdev);
1496 
1497 	/* initialze data */
1498 	up->udev = udev;
1499 	up->intf = intf;
1500 	up->netdev = netdev;
1501 	up->intf_index = iface_desc->desc.bInterfaceNumber;
1502 	up->in_ep_addr = in_ep_addr;
1503 	up->out_ep_addr = out_ep_addr;
1504 	up->in_ep_size = in_ep_size;
1505 	up->ctl_msg_buffer = ctl_msg_buffer;
1506 	up->context_array = NULL;
1507 	up->available_tx_urbs = 0;
1508 
1509 	up->can.state = CAN_STATE_STOPPED;
1510 	up->can.bittiming_const = &up->device_info.bittiming_const;
1511 	up->can.do_set_bittiming = ucan_set_bittiming;
1512 	up->can.do_set_mode = &ucan_set_mode;
1513 	spin_lock_init(&up->context_lock);
1514 	spin_lock_init(&up->echo_skb_lock);
1515 	netdev->netdev_ops = &ucan_netdev_ops;
1516 
1517 	usb_set_intfdata(intf, up);
1518 	SET_NETDEV_DEV(netdev, &intf->dev);
1519 
1520 	/* parse device information
1521 	 * the data retrieved in Stage 2 is still available in
1522 	 * up->ctl_msg_buffer
1523 	 */
1524 	ucan_parse_device_info(up, &ctl_msg_buffer->cmd_get_device_info);
1525 
1526 	/* just print some device information - if available */
1527 	ret = ucan_device_request_in(up, UCAN_DEVICE_GET_FW_STRING, 0,
1528 				     sizeof(union ucan_ctl_payload));
1529 	if (ret > 0) {
1530 		/* copy string while ensuring zero terminiation */
1531 		strncpy(firmware_str, up->ctl_msg_buffer->raw,
1532 			sizeof(union ucan_ctl_payload));
1533 		firmware_str[sizeof(union ucan_ctl_payload)] = '\0';
1534 	} else {
1535 		strcpy(firmware_str, "unknown");
1536 	}
1537 
1538 	/* device is compatible, reset it */
1539 	ret = ucan_ctrl_command_out(up, UCAN_COMMAND_RESET, 0, 0);
1540 	if (ret < 0)
1541 		goto err_free_candev;
1542 
1543 	init_usb_anchor(&up->rx_urbs);
1544 	init_usb_anchor(&up->tx_urbs);
1545 
1546 	up->can.state = CAN_STATE_STOPPED;
1547 
1548 	/* register the device */
1549 	ret = register_candev(netdev);
1550 	if (ret)
1551 		goto err_free_candev;
1552 
1553 	/* initialisation complete, log device info */
1554 	netdev_info(up->netdev, "registered device\n");
1555 	netdev_info(up->netdev, "firmware string: %s\n", firmware_str);
1556 
1557 	/* success */
1558 	return 0;
1559 
1560 err_free_candev:
1561 	free_candev(netdev);
1562 	return ret;
1563 
1564 err_firmware_needs_update:
1565 	dev_err(&udev->dev,
1566 		"%s: probe failed; try to update the device firmware\n",
1567 		UCAN_DRIVER_NAME);
1568 	return -ENODEV;
1569 }
1570 
1571 /* disconnect the device */
1572 static void ucan_disconnect(struct usb_interface *intf)
1573 {
1574 	struct ucan_priv *up = usb_get_intfdata(intf);
1575 
1576 	usb_set_intfdata(intf, NULL);
1577 
1578 	if (up) {
1579 		unregister_netdev(up->netdev);
1580 		free_candev(up->netdev);
1581 	}
1582 }
1583 
1584 static struct usb_device_id ucan_table[] = {
1585 	/* Mule (soldered onto compute modules) */
1586 	{USB_DEVICE_INTERFACE_NUMBER(0x2294, 0x425a, 0)},
1587 	/* Seal (standalone USB stick) */
1588 	{USB_DEVICE_INTERFACE_NUMBER(0x2294, 0x425b, 0)},
1589 	{} /* Terminating entry */
1590 };
1591 
1592 MODULE_DEVICE_TABLE(usb, ucan_table);
1593 /* driver callbacks */
1594 static struct usb_driver ucan_driver = {
1595 	.name = UCAN_DRIVER_NAME,
1596 	.probe = ucan_probe,
1597 	.disconnect = ucan_disconnect,
1598 	.id_table = ucan_table,
1599 };
1600 
1601 module_usb_driver(ucan_driver);
1602 
1603 MODULE_LICENSE("GPL v2");
1604 MODULE_AUTHOR("Martin Elshuber <martin.elshuber@theobroma-systems.com>");
1605 MODULE_AUTHOR("Jakob Unterwurzacher <jakob.unterwurzacher@theobroma-systems.com>");
1606 MODULE_DESCRIPTION("Driver for Theobroma Systems UCAN devices");
1607