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