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