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