1/*
2 * CAN driver for EMS Dr. Thomas Wuensche CPC-USB/ARM7
3 *
4 * Copyright (C) 2004-2009 EMS Dr. Thomas Wuensche
5 *
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published
8 * by the Free Software Foundation; version 2 of the License.
9 *
10 * This program is distributed in the hope that it will be useful, but
11 * WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 * General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
18 */
19#include <linux/init.h>
20#include <linux/signal.h>
21#include <linux/slab.h>
22#include <linux/module.h>
23#include <linux/netdevice.h>
24#include <linux/usb.h>
25
26#include <linux/can.h>
27#include <linux/can/dev.h>
28#include <linux/can/error.h>
29
30MODULE_AUTHOR("Sebastian Haas <haas@ems-wuensche.com>");
31MODULE_DESCRIPTION("CAN driver for EMS Dr. Thomas Wuensche CAN/USB interfaces");
32MODULE_LICENSE("GPL v2");
33
34/* Control-Values for CPC_Control() Command Subject Selection */
35#define CONTR_CAN_MESSAGE 0x04
36#define CONTR_CAN_STATE   0x0C
37#define CONTR_BUS_ERROR   0x1C
38
39/* Control Command Actions */
40#define CONTR_CONT_OFF 0
41#define CONTR_CONT_ON  1
42#define CONTR_ONCE     2
43
44/* Messages from CPC to PC */
45#define CPC_MSG_TYPE_CAN_FRAME       1  /* CAN data frame */
46#define CPC_MSG_TYPE_RTR_FRAME       8  /* CAN remote frame */
47#define CPC_MSG_TYPE_CAN_PARAMS      12 /* Actual CAN parameters */
48#define CPC_MSG_TYPE_CAN_STATE       14 /* CAN state message */
49#define CPC_MSG_TYPE_EXT_CAN_FRAME   16 /* Extended CAN data frame */
50#define CPC_MSG_TYPE_EXT_RTR_FRAME   17 /* Extended remote frame */
51#define CPC_MSG_TYPE_CONTROL         19 /* change interface behavior */
52#define CPC_MSG_TYPE_CONFIRM         20 /* command processed confirmation */
53#define CPC_MSG_TYPE_OVERRUN         21 /* overrun events */
54#define CPC_MSG_TYPE_CAN_FRAME_ERROR 23 /* detected bus errors */
55#define CPC_MSG_TYPE_ERR_COUNTER     25 /* RX/TX error counter */
56
57/* Messages from the PC to the CPC interface  */
58#define CPC_CMD_TYPE_CAN_FRAME     1   /* CAN data frame */
59#define CPC_CMD_TYPE_CONTROL       3   /* control of interface behavior */
60#define CPC_CMD_TYPE_CAN_PARAMS    6   /* set CAN parameters */
61#define CPC_CMD_TYPE_RTR_FRAME     13  /* CAN remote frame */
62#define CPC_CMD_TYPE_CAN_STATE     14  /* CAN state message */
63#define CPC_CMD_TYPE_EXT_CAN_FRAME 15  /* Extended CAN data frame */
64#define CPC_CMD_TYPE_EXT_RTR_FRAME 16  /* Extended CAN remote frame */
65#define CPC_CMD_TYPE_CAN_EXIT      200 /* exit the CAN */
66
67#define CPC_CMD_TYPE_INQ_ERR_COUNTER 25 /* request the CAN error counters */
68#define CPC_CMD_TYPE_CLEAR_MSG_QUEUE 8  /* clear CPC_MSG queue */
69#define CPC_CMD_TYPE_CLEAR_CMD_QUEUE 28 /* clear CPC_CMD queue */
70
71#define CPC_CC_TYPE_SJA1000 2 /* Philips basic CAN controller */
72
73#define CPC_CAN_ECODE_ERRFRAME 0x01 /* Ecode type */
74
75/* Overrun types */
76#define CPC_OVR_EVENT_CAN       0x01
77#define CPC_OVR_EVENT_CANSTATE  0x02
78#define CPC_OVR_EVENT_BUSERROR  0x04
79
80/*
81 * If the CAN controller lost a message we indicate it with the highest bit
82 * set in the count field.
83 */
84#define CPC_OVR_HW 0x80
85
86/* Size of the "struct ems_cpc_msg" without the union */
87#define CPC_MSG_HEADER_LEN   11
88#define CPC_CAN_MSG_MIN_SIZE 5
89
90/* Define these values to match your devices */
91#define USB_CPCUSB_VENDOR_ID 0x12D6
92
93#define USB_CPCUSB_ARM7_PRODUCT_ID 0x0444
94
95/* Mode register NXP LPC2119/SJA1000 CAN Controller */
96#define SJA1000_MOD_NORMAL 0x00
97#define SJA1000_MOD_RM     0x01
98
99/* ECC register NXP LPC2119/SJA1000 CAN Controller */
100#define SJA1000_ECC_SEG   0x1F
101#define SJA1000_ECC_DIR   0x20
102#define SJA1000_ECC_ERR   0x06
103#define SJA1000_ECC_BIT   0x00
104#define SJA1000_ECC_FORM  0x40
105#define SJA1000_ECC_STUFF 0x80
106#define SJA1000_ECC_MASK  0xc0
107
108/* Status register content */
109#define SJA1000_SR_BS 0x80
110#define SJA1000_SR_ES 0x40
111
112#define SJA1000_DEFAULT_OUTPUT_CONTROL 0xDA
113
114/*
115 * The device actually uses a 16MHz clock to generate the CAN clock
116 * but it expects SJA1000 bit settings based on 8MHz (is internally
117 * converted).
118 */
119#define EMS_USB_ARM7_CLOCK 8000000
120
121/*
122 * CAN-Message representation in a CPC_MSG. Message object type is
123 * CPC_MSG_TYPE_CAN_FRAME or CPC_MSG_TYPE_RTR_FRAME or
124 * CPC_MSG_TYPE_EXT_CAN_FRAME or CPC_MSG_TYPE_EXT_RTR_FRAME.
125 */
126struct cpc_can_msg {
127	u32 id;
128	u8 length;
129	u8 msg[8];
130};
131
132/* Representation of the CAN parameters for the SJA1000 controller */
133struct cpc_sja1000_params {
134	u8 mode;
135	u8 acc_code0;
136	u8 acc_code1;
137	u8 acc_code2;
138	u8 acc_code3;
139	u8 acc_mask0;
140	u8 acc_mask1;
141	u8 acc_mask2;
142	u8 acc_mask3;
143	u8 btr0;
144	u8 btr1;
145	u8 outp_contr;
146};
147
148/* CAN params message representation */
149struct cpc_can_params {
150	u8 cc_type;
151
152	/* Will support M16C CAN controller in the future */
153	union {
154		struct cpc_sja1000_params sja1000;
155	} cc_params;
156};
157
158/* Structure for confirmed message handling */
159struct cpc_confirm {
160	u8 error; /* error code */
161};
162
163/* Structure for overrun conditions */
164struct cpc_overrun {
165	u8 event;
166	u8 count;
167};
168
169/* SJA1000 CAN errors (compatible to NXP LPC2119) */
170struct cpc_sja1000_can_error {
171	u8 ecc;
172	u8 rxerr;
173	u8 txerr;
174};
175
176/* structure for CAN error conditions */
177struct cpc_can_error {
178	u8 ecode;
179
180	struct {
181		u8 cc_type;
182
183		/* Other controllers may also provide error code capture regs */
184		union {
185			struct cpc_sja1000_can_error sja1000;
186		} regs;
187	} cc;
188};
189
190/*
191 * Structure containing RX/TX error counter. This structure is used to request
192 * the values of the CAN controllers TX and RX error counter.
193 */
194struct cpc_can_err_counter {
195	u8 rx;
196	u8 tx;
197};
198
199/* Main message type used between library and application */
200struct __packed ems_cpc_msg {
201	u8 type;	/* type of message */
202	u8 length;	/* length of data within union 'msg' */
203	u8 msgid;	/* confirmation handle */
204	u32 ts_sec;	/* timestamp in seconds */
205	u32 ts_nsec;	/* timestamp in nano seconds */
206
207	union {
208		u8 generic[64];
209		struct cpc_can_msg can_msg;
210		struct cpc_can_params can_params;
211		struct cpc_confirm confirmation;
212		struct cpc_overrun overrun;
213		struct cpc_can_error error;
214		struct cpc_can_err_counter err_counter;
215		u8 can_state;
216	} msg;
217};
218
219/*
220 * Table of devices that work with this driver
221 * NOTE: This driver supports only CPC-USB/ARM7 (LPC2119) yet.
222 */
223static struct usb_device_id ems_usb_table[] = {
224	{USB_DEVICE(USB_CPCUSB_VENDOR_ID, USB_CPCUSB_ARM7_PRODUCT_ID)},
225	{} /* Terminating entry */
226};
227
228MODULE_DEVICE_TABLE(usb, ems_usb_table);
229
230#define RX_BUFFER_SIZE      64
231#define CPC_HEADER_SIZE     4
232#define INTR_IN_BUFFER_SIZE 4
233
234#define MAX_RX_URBS 10
235#define MAX_TX_URBS 10
236
237struct ems_usb;
238
239struct ems_tx_urb_context {
240	struct ems_usb *dev;
241
242	u32 echo_index;
243	u8 dlc;
244};
245
246struct ems_usb {
247	struct can_priv can; /* must be the first member */
248	int open_time;
249
250	struct sk_buff *echo_skb[MAX_TX_URBS];
251
252	struct usb_device *udev;
253	struct net_device *netdev;
254
255	atomic_t active_tx_urbs;
256	struct usb_anchor tx_submitted;
257	struct ems_tx_urb_context tx_contexts[MAX_TX_URBS];
258
259	struct usb_anchor rx_submitted;
260
261	struct urb *intr_urb;
262
263	u8 *tx_msg_buffer;
264
265	u8 *intr_in_buffer;
266	unsigned int free_slots; /* remember number of available slots */
267
268	struct ems_cpc_msg active_params; /* active controller parameters */
269};
270
271static void ems_usb_read_interrupt_callback(struct urb *urb)
272{
273	struct ems_usb *dev = urb->context;
274	struct net_device *netdev = dev->netdev;
275	int err;
276
277	if (!netif_device_present(netdev))
278		return;
279
280	switch (urb->status) {
281	case 0:
282		dev->free_slots = dev->intr_in_buffer[1];
283		break;
284
285	case -ECONNRESET: /* unlink */
286	case -ENOENT:
287	case -ESHUTDOWN:
288		return;
289
290	default:
291		netdev_info(netdev, "Rx interrupt aborted %d\n", urb->status);
292		break;
293	}
294
295	err = usb_submit_urb(urb, GFP_ATOMIC);
296
297	if (err == -ENODEV)
298		netif_device_detach(netdev);
299	else if (err)
300		netdev_err(netdev, "failed resubmitting intr urb: %d\n", err);
301}
302
303static void ems_usb_rx_can_msg(struct ems_usb *dev, struct ems_cpc_msg *msg)
304{
305	struct can_frame *cf;
306	struct sk_buff *skb;
307	int i;
308	struct net_device_stats *stats = &dev->netdev->stats;
309
310	skb = alloc_can_skb(dev->netdev, &cf);
311	if (skb == NULL)
312		return;
313
314	cf->can_id = le32_to_cpu(msg->msg.can_msg.id);
315	cf->can_dlc = get_can_dlc(msg->msg.can_msg.length & 0xF);
316
317	if (msg->type == CPC_MSG_TYPE_EXT_CAN_FRAME ||
318	    msg->type == CPC_MSG_TYPE_EXT_RTR_FRAME)
319		cf->can_id |= CAN_EFF_FLAG;
320
321	if (msg->type == CPC_MSG_TYPE_RTR_FRAME ||
322	    msg->type == CPC_MSG_TYPE_EXT_RTR_FRAME) {
323		cf->can_id |= CAN_RTR_FLAG;
324	} else {
325		for (i = 0; i < cf->can_dlc; i++)
326			cf->data[i] = msg->msg.can_msg.msg[i];
327	}
328
329	netif_rx(skb);
330
331	stats->rx_packets++;
332	stats->rx_bytes += cf->can_dlc;
333}
334
335static void ems_usb_rx_err(struct ems_usb *dev, struct ems_cpc_msg *msg)
336{
337	struct can_frame *cf;
338	struct sk_buff *skb;
339	struct net_device_stats *stats = &dev->netdev->stats;
340
341	skb = alloc_can_err_skb(dev->netdev, &cf);
342	if (skb == NULL)
343		return;
344
345	if (msg->type == CPC_MSG_TYPE_CAN_STATE) {
346		u8 state = msg->msg.can_state;
347
348		if (state & SJA1000_SR_BS) {
349			dev->can.state = CAN_STATE_BUS_OFF;
350			cf->can_id |= CAN_ERR_BUSOFF;
351
352			can_bus_off(dev->netdev);
353		} else if (state & SJA1000_SR_ES) {
354			dev->can.state = CAN_STATE_ERROR_WARNING;
355			dev->can.can_stats.error_warning++;
356		} else {
357			dev->can.state = CAN_STATE_ERROR_ACTIVE;
358			dev->can.can_stats.error_passive++;
359		}
360	} else if (msg->type == CPC_MSG_TYPE_CAN_FRAME_ERROR) {
361		u8 ecc = msg->msg.error.cc.regs.sja1000.ecc;
362		u8 txerr = msg->msg.error.cc.regs.sja1000.txerr;
363		u8 rxerr = msg->msg.error.cc.regs.sja1000.rxerr;
364
365		/* bus error interrupt */
366		dev->can.can_stats.bus_error++;
367		stats->rx_errors++;
368
369		cf->can_id |= CAN_ERR_PROT | CAN_ERR_BUSERROR;
370
371		switch (ecc & SJA1000_ECC_MASK) {
372		case SJA1000_ECC_BIT:
373			cf->data[2] |= CAN_ERR_PROT_BIT;
374			break;
375		case SJA1000_ECC_FORM:
376			cf->data[2] |= CAN_ERR_PROT_FORM;
377			break;
378		case SJA1000_ECC_STUFF:
379			cf->data[2] |= CAN_ERR_PROT_STUFF;
380			break;
381		default:
382			cf->data[2] |= CAN_ERR_PROT_UNSPEC;
383			cf->data[3] = ecc & SJA1000_ECC_SEG;
384			break;
385		}
386
387		/* Error occurred during transmission? */
388		if ((ecc & SJA1000_ECC_DIR) == 0)
389			cf->data[2] |= CAN_ERR_PROT_TX;
390
391		if (dev->can.state == CAN_STATE_ERROR_WARNING ||
392		    dev->can.state == CAN_STATE_ERROR_PASSIVE) {
393			cf->data[1] = (txerr > rxerr) ?
394			    CAN_ERR_CRTL_TX_PASSIVE : CAN_ERR_CRTL_RX_PASSIVE;
395		}
396	} else if (msg->type == CPC_MSG_TYPE_OVERRUN) {
397		cf->can_id |= CAN_ERR_CRTL;
398		cf->data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
399
400		stats->rx_over_errors++;
401		stats->rx_errors++;
402	}
403
404	netif_rx(skb);
405
406	stats->rx_packets++;
407	stats->rx_bytes += cf->can_dlc;
408}
409
410/*
411 * callback for bulk IN urb
412 */
413static void ems_usb_read_bulk_callback(struct urb *urb)
414{
415	struct ems_usb *dev = urb->context;
416	struct net_device *netdev;
417	int retval;
418
419	netdev = dev->netdev;
420
421	if (!netif_device_present(netdev))
422		return;
423
424	switch (urb->status) {
425	case 0: /* success */
426		break;
427
428	case -ENOENT:
429		return;
430
431	default:
432		netdev_info(netdev, "Rx URB aborted (%d)\n", urb->status);
433		goto resubmit_urb;
434	}
435
436	if (urb->actual_length > CPC_HEADER_SIZE) {
437		struct ems_cpc_msg *msg;
438		u8 *ibuf = urb->transfer_buffer;
439		u8 msg_count, again, start;
440
441		msg_count = ibuf[0] & ~0x80;
442		again = ibuf[0] & 0x80;
443
444		start = CPC_HEADER_SIZE;
445
446		while (msg_count) {
447			msg = (struct ems_cpc_msg *)&ibuf[start];
448
449			switch (msg->type) {
450			case CPC_MSG_TYPE_CAN_STATE:
451				/* Process CAN state changes */
452				ems_usb_rx_err(dev, msg);
453				break;
454
455			case CPC_MSG_TYPE_CAN_FRAME:
456			case CPC_MSG_TYPE_EXT_CAN_FRAME:
457			case CPC_MSG_TYPE_RTR_FRAME:
458			case CPC_MSG_TYPE_EXT_RTR_FRAME:
459				ems_usb_rx_can_msg(dev, msg);
460				break;
461
462			case CPC_MSG_TYPE_CAN_FRAME_ERROR:
463				/* Process errorframe */
464				ems_usb_rx_err(dev, msg);
465				break;
466
467			case CPC_MSG_TYPE_OVERRUN:
468				/* Message lost while receiving */
469				ems_usb_rx_err(dev, msg);
470				break;
471			}
472
473			start += CPC_MSG_HEADER_LEN + msg->length;
474			msg_count--;
475
476			if (start > urb->transfer_buffer_length) {
477				netdev_err(netdev, "format error\n");
478				break;
479			}
480		}
481	}
482
483resubmit_urb:
484	usb_fill_bulk_urb(urb, dev->udev, usb_rcvbulkpipe(dev->udev, 2),
485			  urb->transfer_buffer, RX_BUFFER_SIZE,
486			  ems_usb_read_bulk_callback, dev);
487
488	retval = usb_submit_urb(urb, GFP_ATOMIC);
489
490	if (retval == -ENODEV)
491		netif_device_detach(netdev);
492	else if (retval)
493		netdev_err(netdev,
494			   "failed resubmitting read bulk urb: %d\n", retval);
495}
496
497/*
498 * callback for bulk IN urb
499 */
500static void ems_usb_write_bulk_callback(struct urb *urb)
501{
502	struct ems_tx_urb_context *context = urb->context;
503	struct ems_usb *dev;
504	struct net_device *netdev;
505
506	BUG_ON(!context);
507
508	dev = context->dev;
509	netdev = dev->netdev;
510
511	/* free up our allocated buffer */
512	usb_free_coherent(urb->dev, urb->transfer_buffer_length,
513			  urb->transfer_buffer, urb->transfer_dma);
514
515	atomic_dec(&dev->active_tx_urbs);
516
517	if (!netif_device_present(netdev))
518		return;
519
520	if (urb->status)
521		netdev_info(netdev, "Tx URB aborted (%d)\n", urb->status);
522
523	netdev->trans_start = jiffies;
524
525	/* transmission complete interrupt */
526	netdev->stats.tx_packets++;
527	netdev->stats.tx_bytes += context->dlc;
528
529	can_get_echo_skb(netdev, context->echo_index);
530
531	/* Release context */
532	context->echo_index = MAX_TX_URBS;
533
534	if (netif_queue_stopped(netdev))
535		netif_wake_queue(netdev);
536}
537
538/*
539 * Send the given CPC command synchronously
540 */
541static int ems_usb_command_msg(struct ems_usb *dev, struct ems_cpc_msg *msg)
542{
543	int actual_length;
544
545	/* Copy payload */
546	memcpy(&dev->tx_msg_buffer[CPC_HEADER_SIZE], msg,
547	       msg->length + CPC_MSG_HEADER_LEN);
548
549	/* Clear header */
550	memset(&dev->tx_msg_buffer[0], 0, CPC_HEADER_SIZE);
551
552	return usb_bulk_msg(dev->udev, usb_sndbulkpipe(dev->udev, 2),
553			    &dev->tx_msg_buffer[0],
554			    msg->length + CPC_MSG_HEADER_LEN + CPC_HEADER_SIZE,
555			    &actual_length, 1000);
556}
557
558/*
559 * Change CAN controllers' mode register
560 */
561static int ems_usb_write_mode(struct ems_usb *dev, u8 mode)
562{
563	dev->active_params.msg.can_params.cc_params.sja1000.mode = mode;
564
565	return ems_usb_command_msg(dev, &dev->active_params);
566}
567
568/*
569 * Send a CPC_Control command to change behaviour when interface receives a CAN
570 * message, bus error or CAN state changed notifications.
571 */
572static int ems_usb_control_cmd(struct ems_usb *dev, u8 val)
573{
574	struct ems_cpc_msg cmd;
575
576	cmd.type = CPC_CMD_TYPE_CONTROL;
577	cmd.length = CPC_MSG_HEADER_LEN + 1;
578
579	cmd.msgid = 0;
580
581	cmd.msg.generic[0] = val;
582
583	return ems_usb_command_msg(dev, &cmd);
584}
585
586/*
587 * Start interface
588 */
589static int ems_usb_start(struct ems_usb *dev)
590{
591	struct net_device *netdev = dev->netdev;
592	int err, i;
593
594	dev->intr_in_buffer[0] = 0;
595	dev->free_slots = 15; /* initial size */
596
597	for (i = 0; i < MAX_RX_URBS; i++) {
598		struct urb *urb = NULL;
599		u8 *buf = NULL;
600
601		/* create a URB, and a buffer for it */
602		urb = usb_alloc_urb(0, GFP_KERNEL);
603		if (!urb) {
604			netdev_err(netdev, "No memory left for URBs\n");
605			err = -ENOMEM;
606			break;
607		}
608
609		buf = usb_alloc_coherent(dev->udev, RX_BUFFER_SIZE, GFP_KERNEL,
610					 &urb->transfer_dma);
611		if (!buf) {
612			netdev_err(netdev, "No memory left for USB buffer\n");
613			usb_free_urb(urb);
614			err = -ENOMEM;
615			break;
616		}
617
618		usb_fill_bulk_urb(urb, dev->udev, usb_rcvbulkpipe(dev->udev, 2),
619				  buf, RX_BUFFER_SIZE,
620				  ems_usb_read_bulk_callback, dev);
621		urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
622		usb_anchor_urb(urb, &dev->rx_submitted);
623
624		err = usb_submit_urb(urb, GFP_KERNEL);
625		if (err) {
626			usb_unanchor_urb(urb);
627			usb_free_coherent(dev->udev, RX_BUFFER_SIZE, buf,
628					  urb->transfer_dma);
629			break;
630		}
631
632		/* Drop reference, USB core will take care of freeing it */
633		usb_free_urb(urb);
634	}
635
636	/* Did we submit any URBs */
637	if (i == 0) {
638		netdev_warn(netdev, "couldn't setup read URBs\n");
639		return err;
640	}
641
642	/* Warn if we've couldn't transmit all the URBs */
643	if (i < MAX_RX_URBS)
644		netdev_warn(netdev, "rx performance may be slow\n");
645
646	/* Setup and start interrupt URB */
647	usb_fill_int_urb(dev->intr_urb, dev->udev,
648			 usb_rcvintpipe(dev->udev, 1),
649			 dev->intr_in_buffer,
650			 INTR_IN_BUFFER_SIZE,
651			 ems_usb_read_interrupt_callback, dev, 1);
652
653	err = usb_submit_urb(dev->intr_urb, GFP_KERNEL);
654	if (err) {
655		netdev_warn(netdev, "intr URB submit failed: %d\n", err);
656
657		return err;
658	}
659
660	/* CPC-USB will transfer received message to host */
661	err = ems_usb_control_cmd(dev, CONTR_CAN_MESSAGE | CONTR_CONT_ON);
662	if (err)
663		goto failed;
664
665	/* CPC-USB will transfer CAN state changes to host */
666	err = ems_usb_control_cmd(dev, CONTR_CAN_STATE | CONTR_CONT_ON);
667	if (err)
668		goto failed;
669
670	/* CPC-USB will transfer bus errors to host */
671	err = ems_usb_control_cmd(dev, CONTR_BUS_ERROR | CONTR_CONT_ON);
672	if (err)
673		goto failed;
674
675	err = ems_usb_write_mode(dev, SJA1000_MOD_NORMAL);
676	if (err)
677		goto failed;
678
679	dev->can.state = CAN_STATE_ERROR_ACTIVE;
680
681	return 0;
682
683failed:
684	netdev_warn(netdev, "couldn't submit control: %d\n", err);
685
686	return err;
687}
688
689static void unlink_all_urbs(struct ems_usb *dev)
690{
691	int i;
692
693	usb_unlink_urb(dev->intr_urb);
694
695	usb_kill_anchored_urbs(&dev->rx_submitted);
696
697	usb_kill_anchored_urbs(&dev->tx_submitted);
698	atomic_set(&dev->active_tx_urbs, 0);
699
700	for (i = 0; i < MAX_TX_URBS; i++)
701		dev->tx_contexts[i].echo_index = MAX_TX_URBS;
702}
703
704static int ems_usb_open(struct net_device *netdev)
705{
706	struct ems_usb *dev = netdev_priv(netdev);
707	int err;
708
709	err = ems_usb_write_mode(dev, SJA1000_MOD_RM);
710	if (err)
711		return err;
712
713	/* common open */
714	err = open_candev(netdev);
715	if (err)
716		return err;
717
718	/* finally start device */
719	err = ems_usb_start(dev);
720	if (err) {
721		if (err == -ENODEV)
722			netif_device_detach(dev->netdev);
723
724		netdev_warn(netdev, "couldn't start device: %d\n", err);
725
726		close_candev(netdev);
727
728		return err;
729	}
730
731	dev->open_time = jiffies;
732
733	netif_start_queue(netdev);
734
735	return 0;
736}
737
738static netdev_tx_t ems_usb_start_xmit(struct sk_buff *skb, struct net_device *netdev)
739{
740	struct ems_usb *dev = netdev_priv(netdev);
741	struct ems_tx_urb_context *context = NULL;
742	struct net_device_stats *stats = &netdev->stats;
743	struct can_frame *cf = (struct can_frame *)skb->data;
744	struct ems_cpc_msg *msg;
745	struct urb *urb;
746	u8 *buf;
747	int i, err;
748	size_t size = CPC_HEADER_SIZE + CPC_MSG_HEADER_LEN
749			+ sizeof(struct cpc_can_msg);
750
751	if (can_dropped_invalid_skb(netdev, skb))
752		return NETDEV_TX_OK;
753
754	/* create a URB, and a buffer for it, and copy the data to the URB */
755	urb = usb_alloc_urb(0, GFP_ATOMIC);
756	if (!urb) {
757		netdev_err(netdev, "No memory left for URBs\n");
758		goto nomem;
759	}
760
761	buf = usb_alloc_coherent(dev->udev, size, GFP_ATOMIC, &urb->transfer_dma);
762	if (!buf) {
763		netdev_err(netdev, "No memory left for USB buffer\n");
764		usb_free_urb(urb);
765		goto nomem;
766	}
767
768	msg = (struct ems_cpc_msg *)&buf[CPC_HEADER_SIZE];
769
770	msg->msg.can_msg.id = cf->can_id & CAN_ERR_MASK;
771	msg->msg.can_msg.length = cf->can_dlc;
772
773	if (cf->can_id & CAN_RTR_FLAG) {
774		msg->type = cf->can_id & CAN_EFF_FLAG ?
775			CPC_CMD_TYPE_EXT_RTR_FRAME : CPC_CMD_TYPE_RTR_FRAME;
776
777		msg->length = CPC_CAN_MSG_MIN_SIZE;
778	} else {
779		msg->type = cf->can_id & CAN_EFF_FLAG ?
780			CPC_CMD_TYPE_EXT_CAN_FRAME : CPC_CMD_TYPE_CAN_FRAME;
781
782		for (i = 0; i < cf->can_dlc; i++)
783			msg->msg.can_msg.msg[i] = cf->data[i];
784
785		msg->length = CPC_CAN_MSG_MIN_SIZE + cf->can_dlc;
786	}
787
788	/* Respect byte order */
789	msg->msg.can_msg.id = cpu_to_le32(msg->msg.can_msg.id);
790
791	for (i = 0; i < MAX_TX_URBS; i++) {
792		if (dev->tx_contexts[i].echo_index == MAX_TX_URBS) {
793			context = &dev->tx_contexts[i];
794			break;
795		}
796	}
797
798	/*
799	 * May never happen! When this happens we'd more URBs in flight as
800	 * allowed (MAX_TX_URBS).
801	 */
802	if (!context) {
803		usb_unanchor_urb(urb);
804		usb_free_coherent(dev->udev, size, buf, urb->transfer_dma);
805
806		netdev_warn(netdev, "couldn't find free context\n");
807
808		return NETDEV_TX_BUSY;
809	}
810
811	context->dev = dev;
812	context->echo_index = i;
813	context->dlc = cf->can_dlc;
814
815	usb_fill_bulk_urb(urb, dev->udev, usb_sndbulkpipe(dev->udev, 2), buf,
816			  size, ems_usb_write_bulk_callback, context);
817	urb->transfer_flags |= URB_NO_TRANSFER_DMA_MAP;
818	usb_anchor_urb(urb, &dev->tx_submitted);
819
820	can_put_echo_skb(skb, netdev, context->echo_index);
821
822	atomic_inc(&dev->active_tx_urbs);
823
824	err = usb_submit_urb(urb, GFP_ATOMIC);
825	if (unlikely(err)) {
826		can_free_echo_skb(netdev, context->echo_index);
827
828		usb_unanchor_urb(urb);
829		usb_free_coherent(dev->udev, size, buf, urb->transfer_dma);
830		dev_kfree_skb(skb);
831
832		atomic_dec(&dev->active_tx_urbs);
833
834		if (err == -ENODEV) {
835			netif_device_detach(netdev);
836		} else {
837			netdev_warn(netdev, "failed tx_urb %d\n", err);
838
839			stats->tx_dropped++;
840		}
841	} else {
842		netdev->trans_start = jiffies;
843
844		/* Slow down tx path */
845		if (atomic_read(&dev->active_tx_urbs) >= MAX_TX_URBS ||
846		    dev->free_slots < 5) {
847			netif_stop_queue(netdev);
848		}
849	}
850
851	/*
852	 * Release our reference to this URB, the USB core will eventually free
853	 * it entirely.
854	 */
855	usb_free_urb(urb);
856
857	return NETDEV_TX_OK;
858
859nomem:
860	dev_kfree_skb(skb);
861	stats->tx_dropped++;
862
863	return NETDEV_TX_OK;
864}
865
866static int ems_usb_close(struct net_device *netdev)
867{
868	struct ems_usb *dev = netdev_priv(netdev);
869
870	/* Stop polling */
871	unlink_all_urbs(dev);
872
873	netif_stop_queue(netdev);
874
875	/* Set CAN controller to reset mode */
876	if (ems_usb_write_mode(dev, SJA1000_MOD_RM))
877		netdev_warn(netdev, "couldn't stop device");
878
879	close_candev(netdev);
880
881	dev->open_time = 0;
882
883	return 0;
884}
885
886static const struct net_device_ops ems_usb_netdev_ops = {
887	.ndo_open = ems_usb_open,
888	.ndo_stop = ems_usb_close,
889	.ndo_start_xmit = ems_usb_start_xmit,
890};
891
892static struct can_bittiming_const ems_usb_bittiming_const = {
893	.name = "ems_usb",
894	.tseg1_min = 1,
895	.tseg1_max = 16,
896	.tseg2_min = 1,
897	.tseg2_max = 8,
898	.sjw_max = 4,
899	.brp_min = 1,
900	.brp_max = 64,
901	.brp_inc = 1,
902};
903
904static int ems_usb_set_mode(struct net_device *netdev, enum can_mode mode)
905{
906	struct ems_usb *dev = netdev_priv(netdev);
907
908	if (!dev->open_time)
909		return -EINVAL;
910
911	switch (mode) {
912	case CAN_MODE_START:
913		if (ems_usb_write_mode(dev, SJA1000_MOD_NORMAL))
914			netdev_warn(netdev, "couldn't start device");
915
916		if (netif_queue_stopped(netdev))
917			netif_wake_queue(netdev);
918		break;
919
920	default:
921		return -EOPNOTSUPP;
922	}
923
924	return 0;
925}
926
927static int ems_usb_set_bittiming(struct net_device *netdev)
928{
929	struct ems_usb *dev = netdev_priv(netdev);
930	struct can_bittiming *bt = &dev->can.bittiming;
931	u8 btr0, btr1;
932
933	btr0 = ((bt->brp - 1) & 0x3f) | (((bt->sjw - 1) & 0x3) << 6);
934	btr1 = ((bt->prop_seg + bt->phase_seg1 - 1) & 0xf) |
935		(((bt->phase_seg2 - 1) & 0x7) << 4);
936	if (dev->can.ctrlmode & CAN_CTRLMODE_3_SAMPLES)
937		btr1 |= 0x80;
938
939	netdev_info(netdev, "setting BTR0=0x%02x BTR1=0x%02x\n", btr0, btr1);
940
941	dev->active_params.msg.can_params.cc_params.sja1000.btr0 = btr0;
942	dev->active_params.msg.can_params.cc_params.sja1000.btr1 = btr1;
943
944	return ems_usb_command_msg(dev, &dev->active_params);
945}
946
947static void init_params_sja1000(struct ems_cpc_msg *msg)
948{
949	struct cpc_sja1000_params *sja1000 =
950		&msg->msg.can_params.cc_params.sja1000;
951
952	msg->type = CPC_CMD_TYPE_CAN_PARAMS;
953	msg->length = sizeof(struct cpc_can_params);
954	msg->msgid = 0;
955
956	msg->msg.can_params.cc_type = CPC_CC_TYPE_SJA1000;
957
958	/* Acceptance filter open */
959	sja1000->acc_code0 = 0x00;
960	sja1000->acc_code1 = 0x00;
961	sja1000->acc_code2 = 0x00;
962	sja1000->acc_code3 = 0x00;
963
964	/* Acceptance filter open */
965	sja1000->acc_mask0 = 0xFF;
966	sja1000->acc_mask1 = 0xFF;
967	sja1000->acc_mask2 = 0xFF;
968	sja1000->acc_mask3 = 0xFF;
969
970	sja1000->btr0 = 0;
971	sja1000->btr1 = 0;
972
973	sja1000->outp_contr = SJA1000_DEFAULT_OUTPUT_CONTROL;
974	sja1000->mode = SJA1000_MOD_RM;
975}
976
977/*
978 * probe function for new CPC-USB devices
979 */
980static int ems_usb_probe(struct usb_interface *intf,
981			 const struct usb_device_id *id)
982{
983	struct net_device *netdev;
984	struct ems_usb *dev;
985	int i, err = -ENOMEM;
986
987	netdev = alloc_candev(sizeof(struct ems_usb), MAX_TX_URBS);
988	if (!netdev) {
989		dev_err(&intf->dev, "ems_usb: Couldn't alloc candev\n");
990		return -ENOMEM;
991	}
992
993	dev = netdev_priv(netdev);
994
995	dev->udev = interface_to_usbdev(intf);
996	dev->netdev = netdev;
997
998	dev->can.state = CAN_STATE_STOPPED;
999	dev->can.clock.freq = EMS_USB_ARM7_CLOCK;
1000	dev->can.bittiming_const = &ems_usb_bittiming_const;
1001	dev->can.do_set_bittiming = ems_usb_set_bittiming;
1002	dev->can.do_set_mode = ems_usb_set_mode;
1003	dev->can.ctrlmode_supported = CAN_CTRLMODE_3_SAMPLES;
1004
1005	netdev->netdev_ops = &ems_usb_netdev_ops;
1006
1007	netdev->flags |= IFF_ECHO; /* we support local echo */
1008
1009	init_usb_anchor(&dev->rx_submitted);
1010
1011	init_usb_anchor(&dev->tx_submitted);
1012	atomic_set(&dev->active_tx_urbs, 0);
1013
1014	for (i = 0; i < MAX_TX_URBS; i++)
1015		dev->tx_contexts[i].echo_index = MAX_TX_URBS;
1016
1017	dev->intr_urb = usb_alloc_urb(0, GFP_KERNEL);
1018	if (!dev->intr_urb) {
1019		dev_err(&intf->dev, "Couldn't alloc intr URB\n");
1020		goto cleanup_candev;
1021	}
1022
1023	dev->intr_in_buffer = kzalloc(INTR_IN_BUFFER_SIZE, GFP_KERNEL);
1024	if (!dev->intr_in_buffer) {
1025		dev_err(&intf->dev, "Couldn't alloc Intr buffer\n");
1026		goto cleanup_intr_urb;
1027	}
1028
1029	dev->tx_msg_buffer = kzalloc(CPC_HEADER_SIZE +
1030				     sizeof(struct ems_cpc_msg), GFP_KERNEL);
1031	if (!dev->tx_msg_buffer) {
1032		dev_err(&intf->dev, "Couldn't alloc Tx buffer\n");
1033		goto cleanup_intr_in_buffer;
1034	}
1035
1036	usb_set_intfdata(intf, dev);
1037
1038	SET_NETDEV_DEV(netdev, &intf->dev);
1039
1040	init_params_sja1000(&dev->active_params);
1041
1042	err = ems_usb_command_msg(dev, &dev->active_params);
1043	if (err) {
1044		netdev_err(netdev, "couldn't initialize controller: %d\n", err);
1045		goto cleanup_tx_msg_buffer;
1046	}
1047
1048	err = register_candev(netdev);
1049	if (err) {
1050		netdev_err(netdev, "couldn't register CAN device: %d\n", err);
1051		goto cleanup_tx_msg_buffer;
1052	}
1053
1054	return 0;
1055
1056cleanup_tx_msg_buffer:
1057	kfree(dev->tx_msg_buffer);
1058
1059cleanup_intr_in_buffer:
1060	kfree(dev->intr_in_buffer);
1061
1062cleanup_intr_urb:
1063	usb_free_urb(dev->intr_urb);
1064
1065cleanup_candev:
1066	free_candev(netdev);
1067
1068	return err;
1069}
1070
1071/*
1072 * called by the usb core when the device is removed from the system
1073 */
1074static void ems_usb_disconnect(struct usb_interface *intf)
1075{
1076	struct ems_usb *dev = usb_get_intfdata(intf);
1077
1078	usb_set_intfdata(intf, NULL);
1079
1080	if (dev) {
1081		unregister_netdev(dev->netdev);
1082		free_candev(dev->netdev);
1083
1084		unlink_all_urbs(dev);
1085
1086		usb_free_urb(dev->intr_urb);
1087
1088		kfree(dev->intr_in_buffer);
1089	}
1090}
1091
1092/* usb specific object needed to register this driver with the usb subsystem */
1093static struct usb_driver ems_usb_driver = {
1094	.name = "ems_usb",
1095	.probe = ems_usb_probe,
1096	.disconnect = ems_usb_disconnect,
1097	.id_table = ems_usb_table,
1098};
1099
1100module_usb_driver(ems_usb_driver);
1101