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