2 * elmcan.c - ELM327 based CAN interface driver
3 * (tty line discipline)
5 * This file is derived from linux/drivers/net/can/slcan.c
7 * elmcan.c Author : Max Staudt <elmcan@enpas.org>
8 * slcan.c Author : Oliver Hartkopp <socketcan@hartkopp.net>
9 * slip.c Authors : Laurence Culhane <loz@holmes.demon.co.uk>
10 * Fred N. van Kempen <waltje@uwalt.nl.mugnet.org>
12 * SPDX-License-Identifier: GPL-2.0
16 #define pr_fmt(fmt) "[elmcan] " fmt
19 #include <linux/init.h>
20 #include <linux/module.h>
21 #include <linux/moduleparam.h>
23 #include <linux/atomic.h>
24 #include <linux/bitops.h>
25 #include <linux/delay.h>
26 #include <linux/errno.h>
27 #include <linux/if_ether.h>
28 #include <linux/kernel.h>
29 #include <linux/list.h>
30 #include <linux/netdevice.h>
31 #include <linux/skbuff.h>
32 #include <linux/spinlock.h>
33 #include <linux/string.h>
34 #include <linux/tty.h>
35 #include <linux/workqueue.h>
37 #include <linux/can.h>
38 #include <linux/can/dev.h>
39 #include <linux/can/error.h>
40 #include <linux/can/led.h>
43 MODULE_ALIAS_LDISC(N_ELMCAN);
44 MODULE_DESCRIPTION("ELM327 based CAN interface");
45 MODULE_LICENSE("GPL");
46 MODULE_AUTHOR("Max Staudt <max-linux@enpas.org>");
48 /* Line discipline ID number */
53 #define ELM327_CAN_CONFIG_SEND_SFF 0x8000
54 #define ELM327_CAN_CONFIG_VARIABLE_DLC 0x4000
55 #define ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF 0x2000
56 #define ELM327_CAN_CONFIG_BAUDRATE_MULT_8_7 0x1000
58 #define ELM327_MAGIC_CHAR 'y'
59 #define ELM327_MAGIC_STRING "y"
60 #define ELM327_READY_CHAR '>'
63 /* Bits in elm->cmds_todo */
65 ELM_TODO_CAN_DATA = 0,
67 ELM_TODO_CANID_29BIT_LOW,
68 ELM_TODO_CANID_29BIT_HIGH,
71 ELM_TODO_SILENT_MONITOR,
77 /* This must be the first member when using alloc_candev() */
80 /* TTY and netdev devices that we're bridging */
81 struct tty_struct *tty;
82 struct net_device *dev;
84 char ifname[IFNAMSIZ];
86 /* Per-channel lock */
89 /* Keep track of how many things are using this struct.
90 * Once it reaches 0, we are in the process of cleaning up,
91 * and new operations will be cancelled immediately.
92 * Use atomic_t rather than refcount_t because we deliberately
93 * decrement to 0, and refcount_dec() spills a WARN_ONCE in
99 struct work_struct tx_work; /* Flushes TTY TX buffer */
100 unsigned char txbuf[32];
101 unsigned char *txhead; /* Pointer to next TX byte */
102 int txleft; /* Bytes left to TX */
105 unsigned char rxbuf[256];
118 /* The CAN frame and config the ELM327 is sending/using,
119 * or will send/use after finishing all cmds_todo */
120 struct can_frame can_frame;
121 unsigned short can_config;
122 unsigned long can_bitrate;
123 unsigned char can_bitrate_divisor;
124 int silent_monitoring;
126 /* Things we have yet to send */
127 char **next_init_cmd;
128 unsigned long cmds_todo;
132 /* A lock for all tty->disc_data handled by this ldisc.
133 * This is to prevent a case where tty->disc_data is set to NULL,
134 * yet someone is still trying to dereference it.
135 * Without this, we cannot do a clean shutdown.
137 static DEFINE_SPINLOCK(elmcan_discdata_lock);
140 static inline void elm327_hw_failure(struct elmcan *elm);
144 /************************************************************************
145 * ELM327: Transmission *
147 * (all functions assume elm->lock taken) *
148 ************************************************************************/
150 static void elm327_send(struct elmcan *elm, const void *buf, size_t len)
154 memcpy(elm->txbuf, buf, len);
156 /* Order of next two lines is *very* important.
157 * When we are sending a little amount of data,
158 * the transfer may be completed inside the ops->write()
159 * routine, because it's running with interrupts enabled.
160 * In this case we *never* got WRITE_WAKEUP event,
161 * if we did not request it before write operation.
162 * 14 Oct 1994 Dmitry Gorodchanin.
164 set_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
165 actual = elm->tty->ops->write(elm->tty, elm->txbuf, len);
167 netdev_err(elm->dev, "Failed to write to tty %s.\n", elm->tty->name);
168 elm327_hw_failure(elm);
171 elm->txleft = len - actual;
172 elm->txhead = elm->txbuf + actual;
177 * Take the ELM327 out of almost any state and back into command mode
179 * Assumes elm->lock taken.
181 static void elm327_kick_into_cmd_mode(struct elmcan *elm)
183 if (elm->state != ELM_GETMAGICCHAR && elm->state != ELM_GETPROMPT) {
184 elm327_send(elm, ELM327_MAGIC_STRING, 1);
186 elm->state = ELM_GETMAGICCHAR;
193 * Schedule a CAN frame, and any necessary config changes,
194 * to be sent down the TTY.
196 * Assumes elm->lock taken.
198 static void elm327_send_frame(struct elmcan *elm, struct can_frame *frame)
200 /* Schedule any necessary changes in ELM327's CAN configuration */
201 if (elm->can_frame.can_id != frame->can_id) {
202 /* Set the new CAN ID for transmission. */
203 if ((frame->can_id & CAN_EFF_FLAG) ^ (elm->can_frame.can_id & CAN_EFF_FLAG)) {
204 elm->can_config = (frame->can_id & CAN_EFF_FLAG ? 0 : ELM327_CAN_CONFIG_SEND_SFF)
205 | ELM327_CAN_CONFIG_VARIABLE_DLC
206 | ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF
207 | elm->can_bitrate_divisor;
209 set_bit(ELM_TODO_CAN_CONFIG, &elm->cmds_todo);
212 if (frame->can_id & CAN_EFF_FLAG) {
213 clear_bit(ELM_TODO_CANID_11BIT, &elm->cmds_todo);
214 set_bit(ELM_TODO_CANID_29BIT_LOW, &elm->cmds_todo);
215 set_bit(ELM_TODO_CANID_29BIT_HIGH, &elm->cmds_todo);
217 set_bit(ELM_TODO_CANID_11BIT, &elm->cmds_todo);
218 clear_bit(ELM_TODO_CANID_29BIT_LOW, &elm->cmds_todo);
219 clear_bit(ELM_TODO_CANID_29BIT_HIGH, &elm->cmds_todo);
223 /* Schedule the CAN frame itself. */
224 elm->can_frame = *frame;
225 set_bit(ELM_TODO_CAN_DATA, &elm->cmds_todo);
227 elm327_kick_into_cmd_mode(elm);
232 /************************************************************************
233 * ELM327: Initialization sequence *
235 * (assumes elm->lock taken) *
236 ************************************************************************/
238 static char *elm327_init_script[] = {
239 "AT WS\r", /* v1.0: Warm Start */
240 "AT PP FF OFF\r", /* v1.0: All Programmable Parameters Off */
241 "AT M0\r", /* v1.0: Memory Off */
242 "AT AL\r", /* v1.0: Allow Long messages */
243 "AT BI\r", /* v1.0: Bypass Initialization */
244 "AT CAF0\r", /* v1.0: CAN Auto Formatting Off */
245 "AT CFC0\r", /* v1.0: CAN Flow Control Off */
246 "AT CF 000\r", /* v1.0: Reset CAN ID Filter */
247 "AT CM 000\r", /* v1.0: Reset CAN ID Mask */
248 "AT E1\r", /* v1.0: Echo On */
249 "AT H1\r", /* v1.0: Headers On */
250 "AT L0\r", /* v1.0: Linefeeds Off */
251 "AT SH 7DF\r", /* v1.0: Set CAN sending ID to 0x7df */
252 "AT ST FF\r", /* v1.0: Set maximum Timeout for response after TX */
253 "AT AT0\r", /* v1.2: Adaptive Timing Off */
254 "AT D1\r", /* v1.3: Print DLC On */
255 "AT S1\r", /* v1.3: Spaces On */
256 "AT TP B\r", /* v1.0: Try Protocol B */
261 static void elm327_init(struct elmcan *elm)
263 elm->state = ELM_NOTINIT;
264 elm->can_frame.can_id = 0x7df;
266 elm->drop_next_line = 0;
268 /* We can only set the bitrate as a fraction of 500000.
269 * The bit timing constants in elmcan_bittiming_const will
270 * limit the user to the right values.
272 elm->can_bitrate_divisor = 500000 / elm->can.bittiming.bitrate;
273 elm->can_config = ELM327_CAN_CONFIG_SEND_SFF
274 | ELM327_CAN_CONFIG_VARIABLE_DLC
275 | ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF
276 | elm->can_bitrate_divisor;
278 /* Configure ELM327 and then start monitoring */
279 elm->next_init_cmd = &elm327_init_script[0];
280 set_bit(ELM_TODO_INIT, &elm->cmds_todo);
281 set_bit(ELM_TODO_SILENT_MONITOR, &elm->cmds_todo);
282 set_bit(ELM_TODO_RESPONSES, &elm->cmds_todo);
283 set_bit(ELM_TODO_CAN_CONFIG, &elm->cmds_todo);
285 elm327_kick_into_cmd_mode(elm);
290 /************************************************************************
291 * ELM327: Reception -> netdev glue *
293 * (assumes elm->lock taken) *
294 ************************************************************************/
296 static void elm327_feed_frame_to_netdev(struct elmcan *elm, const struct can_frame *frame)
298 struct can_frame *cf;
301 if (!netif_running(elm->dev)) {
305 skb = alloc_can_skb(elm->dev, &cf);
310 memcpy(cf, frame, sizeof(struct can_frame));
312 elm->dev->stats.rx_packets++;
313 elm->dev->stats.rx_bytes += frame->can_dlc;
316 can_led_event(elm->dev, CAN_LED_EVENT_RX);
321 /************************************************************************
322 * ELM327: "Panic" handler *
324 * (assumes elm->lock taken) *
325 ************************************************************************/
327 /* Called when we're out of ideas and just want it all to end. */
328 static inline void elm327_hw_failure(struct elmcan *elm)
330 struct can_frame frame = {0};
332 frame.can_id = CAN_ERR_FLAG | CAN_ERR_RESTARTED;
333 frame.can_dlc = CAN_ERR_DLC;
334 elm327_feed_frame_to_netdev(elm, &frame);
336 pr_err("ELM327 misbehaved. Re-initializing.\n");
338 elm->can.can_stats.restarts++;
344 /************************************************************************
345 * ELM327: Reception parser *
347 * (assumes elm->lock taken) *
348 ************************************************************************/
350 static void elm327_parse_error(struct elmcan *elm, int len)
352 struct can_frame frame = {0};
354 frame.can_id = CAN_ERR_FLAG;
355 frame.can_dlc = CAN_ERR_DLC;
359 if (!memcmp(elm->rxbuf, "UNABLE TO CONNECT", 17)) {
360 pr_err("The ELM327 reported UNABLE TO CONNECT. Please check your setup.\n");
364 if (!memcmp(elm->rxbuf, "BUFFER FULL", 11)) {
365 /* This case will only happen if the last data
367 * Otherwise, elm327_parse_frame() will emit the
368 * error frame instead.
370 frame.can_id |= CAN_ERR_CRTL;
371 frame.data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
375 if (!memcmp(elm->rxbuf, "BUS ERROR", 9)) {
376 frame.can_id |= CAN_ERR_BUSERROR;
378 if (!memcmp(elm->rxbuf, "CAN ERROR", 9)
379 || !memcmp(elm->rxbuf, "<RX ERROR", 9)) {
380 frame.can_id |= CAN_ERR_PROT;
384 if (!memcmp(elm->rxbuf, "BUS BUSY", 8)) {
385 frame.can_id |= CAN_ERR_PROT;
386 frame.data[2] = CAN_ERR_PROT_OVERLOAD;
388 if (!memcmp(elm->rxbuf, "FB ERROR", 8)) {
389 frame.can_id |= CAN_ERR_PROT;
390 frame.data[2] = CAN_ERR_PROT_TX;
394 if (!memcmp(elm->rxbuf, "ERR", 3)) {
395 pr_err("The ELM327 reported an ERR%c%c. Please power it off and on again.\n",
396 elm->rxbuf[3], elm->rxbuf[4]);
397 frame.can_id |= CAN_ERR_CRTL;
401 /* Don't emit an error frame if we're unsure */
405 elm327_feed_frame_to_netdev(elm, &frame);
409 static int elm327_parse_frame(struct elmcan *elm, int len)
411 struct can_frame frame = {0};
416 /* Find first non-hex and non-space character:
417 * - In the simplest case, there is none.
418 * - For RTR frames, 'R' is the first non-hex character.
419 * - An error message may replace the end of the data line.
421 for (hexlen = 0; hexlen <= len; hexlen++) {
422 if (hex_to_bin(elm->rxbuf[hexlen]) < 0
423 && elm->rxbuf[hexlen] != ' ') {
428 /* Use spaces in CAN ID to distinguish 29 or 11 bit address length.
429 * No out-of-bounds access:
430 * We use the fact that we can always read from elm->rxbuf.
432 if (elm->rxbuf[2] == ' ' && elm->rxbuf[5] == ' '
433 && elm->rxbuf[8] == ' ' && elm->rxbuf[11] == ' '
434 && elm->rxbuf[13] == ' ') {
435 frame.can_id = CAN_EFF_FLAG;
437 } else if (elm->rxbuf[3] == ' ' && elm->rxbuf[5] == ' ') {
441 /* This is not a well-formatted data line.
442 * Assume it's an error message.
447 if (hexlen < datastart) {
448 /* The line is too short to be a valid frame hex dump.
449 * Something interrupted the hex dump or it is invalid.
454 /* From here on all chars up to buf[hexlen] are hex or spaces,
455 * at well-defined offsets.
458 /* Read CAN data length */
459 frame.can_dlc = (hex_to_bin(elm->rxbuf[datastart - 2]) << 0);
462 if (frame.can_id & CAN_EFF_FLAG) {
463 frame.can_id |= (hex_to_bin(elm->rxbuf[0]) << 28)
464 | (hex_to_bin(elm->rxbuf[1]) << 24)
465 | (hex_to_bin(elm->rxbuf[3]) << 20)
466 | (hex_to_bin(elm->rxbuf[4]) << 16)
467 | (hex_to_bin(elm->rxbuf[6]) << 12)
468 | (hex_to_bin(elm->rxbuf[7]) << 8)
469 | (hex_to_bin(elm->rxbuf[9]) << 4)
470 | (hex_to_bin(elm->rxbuf[10]) << 0);
472 frame.can_id |= (hex_to_bin(elm->rxbuf[0]) << 8)
473 | (hex_to_bin(elm->rxbuf[1]) << 4)
474 | (hex_to_bin(elm->rxbuf[2]) << 0);
477 /* Check for RTR frame */
478 if (elm->rxfill >= hexlen + 3
479 && elm->rxbuf[hexlen + 0] == 'R'
480 && elm->rxbuf[hexlen + 1] == 'T'
481 && elm->rxbuf[hexlen + 2] == 'R') {
482 frame.can_id |= CAN_RTR_FLAG;
485 /* Is the line long enough to hold the advertised payload? */
486 if (!(frame.can_id & CAN_RTR_FLAG) && (hexlen < frame.can_dlc * 3 + datastart)) {
487 /* Incomplete frame. */
489 /* Probably the ELM327's RS232 TX buffer was full.
490 * Emit an error frame and exit.
492 frame.can_id = CAN_ERR_FLAG | CAN_ERR_CRTL;
493 frame.can_dlc = CAN_ERR_DLC;
494 frame.data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
495 elm327_feed_frame_to_netdev(elm, &frame);
497 /* Signal failure to parse.
498 * The line will be re-parsed as an error line, which will fail.
499 * However, this will correctly drop the state machine back into
505 /* Parse the data nibbles. */
506 for (i = 0; i < frame.can_dlc; i++) {
507 frame.data[i] = (hex_to_bin(elm->rxbuf[datastart+3*i]) << 4)
508 | (hex_to_bin(elm->rxbuf[datastart+3*i+1]) << 0);
511 /* Feed the frame to the network layer. */
512 elm327_feed_frame_to_netdev(elm, &frame);
518 static void elm327_parse_line(struct elmcan *elm, int len)
520 /* Skip empty lines */
525 /* Skip echo lines */
526 if (elm->drop_next_line) {
527 elm->drop_next_line = 0;
529 } else if (elm->rxbuf[0] == 'A' && elm->rxbuf[1] == 'T') {
533 /* Regular parsing */
536 if (elm327_parse_frame(elm, len)) {
537 /* Parse an error line. */
538 elm327_parse_error(elm, len);
540 /* After the error line, we expect a prompt. */
541 elm->state = ELM_GETPROMPT;
550 static void elm327_handle_prompt(struct elmcan *elm)
552 if (elm->cmds_todo) {
553 struct can_frame *frame = &elm->can_frame;
556 if (test_bit(ELM_TODO_INIT, &elm->cmds_todo)) {
557 elm327_send(elm, *elm->next_init_cmd, strlen(*elm->next_init_cmd));
558 elm->next_init_cmd++;
559 if (!(*elm->next_init_cmd)) {
560 clear_bit(ELM_TODO_INIT, &elm->cmds_todo);
561 netdev_info(elm->dev, "Initialization finished.\n");
564 /* Some chips are unreliable and need extra time after
565 * init commands, as seen with a clone.
566 * So let's do a dummy get-cmd-prompt dance.
568 elm->state = ELM_NOTINIT;
569 elm327_kick_into_cmd_mode(elm);
570 } else if (test_and_clear_bit(ELM_TODO_SILENT_MONITOR, &elm->cmds_todo)) {
571 snprintf(txbuf, sizeof(txbuf), "ATCSM%i\r", !(!(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY)));
572 } else if (test_and_clear_bit(ELM_TODO_RESPONSES, &elm->cmds_todo)) {
573 snprintf(txbuf, sizeof(txbuf), "ATR%i\r", !(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY));
574 } else if (test_and_clear_bit(ELM_TODO_CAN_CONFIG, &elm->cmds_todo)) {
575 snprintf(txbuf, sizeof(txbuf), "ATPB%04X\r", elm->can_config);
576 } else if (test_and_clear_bit(ELM_TODO_CANID_29BIT_HIGH, &elm->cmds_todo)) {
577 snprintf(txbuf, sizeof(txbuf), "ATCP%02X\r", (frame->can_id & CAN_EFF_MASK) >> 24);
578 } else if (test_and_clear_bit(ELM_TODO_CANID_29BIT_LOW, &elm->cmds_todo)) {
579 snprintf(txbuf, sizeof(txbuf), "ATSH%06X\r", frame->can_id & CAN_EFF_MASK & ((1 << 24) - 1));
580 } else if (test_and_clear_bit(ELM_TODO_CANID_11BIT, &elm->cmds_todo)) {
581 snprintf(txbuf, sizeof(txbuf), "ATSH%03X\r", frame->can_id & CAN_SFF_MASK);
582 } else if (test_and_clear_bit(ELM_TODO_CAN_DATA, &elm->cmds_todo)) {
583 if (frame->can_id & CAN_RTR_FLAG) {
584 snprintf(txbuf, sizeof(txbuf), "ATRTR\r");
588 for (i = 0; i < frame->can_dlc; i++) {
589 sprintf(&txbuf[2*i], "%02X", frame->data[i]);
592 sprintf(&txbuf[2*i], "\r");
595 elm->drop_next_line = 1;
596 elm->state = ELM_RECEIVING;
599 elm327_send(elm, txbuf, strlen(txbuf));
601 /* Enter CAN monitor mode */
602 elm327_send(elm, "ATMA\r", 5);
603 elm->state = ELM_RECEIVING;
608 static void elm327_drop_bytes(struct elmcan *elm, int i)
610 memmove(&elm->rxbuf[0], &elm->rxbuf[i], sizeof(elm->rxbuf) - i);
615 static void elm327_parse_rxbuf(struct elmcan *elm)
619 switch (elm->state) {
624 case ELM_GETMAGICCHAR:
626 /* Wait for 'y' or '>' */
629 for (i = 0; i < elm->rxfill; i++) {
630 if (elm->rxbuf[i] == ELM327_MAGIC_CHAR) {
631 elm327_send(elm, "\r", 1);
632 elm->state = ELM_GETPROMPT;
635 } else if (elm->rxbuf[i] == ELM327_READY_CHAR) {
636 elm327_send(elm, ELM327_MAGIC_STRING, 1);
642 elm327_drop_bytes(elm, i);
649 if (elm->rxbuf[elm->rxfill - 1] == ELM327_READY_CHAR) {
650 elm327_handle_prompt(elm);
657 /* Find <CR> delimiting feedback lines. */
659 (len < elm->rxfill) && (elm->rxbuf[len] != '\r');
664 if (len == sizeof(elm->rxbuf)) {
665 /* Line exceeds buffer. It's probably all garbage.
666 * Did we even connect at the right baud rate?
668 pr_err("RX buffer overflow. Faulty ELM327 connected?\n");
669 elm327_hw_failure(elm);
670 } else if (len == elm->rxfill) {
671 if (elm->state == ELM_RECEIVING
672 && elm->rxbuf[elm->rxfill - 1] == ELM327_READY_CHAR) {
673 /* The ELM327's AT ST response timeout ran out,
674 * so we got a prompt.
675 * Clear RX buffer and restart listening.
679 elm327_handle_prompt(elm);
682 /* We haven't received a full line yet.
683 * Wait for more data.
689 /* We have a full line to parse. */
690 elm327_parse_line(elm, len);
692 /* Remove parsed data from RX buffer. */
693 elm327_drop_bytes(elm, len+1);
695 /* More data to parse? */
697 elm327_parse_rxbuf(elm);
706 /************************************************************************
709 * (takes elm->lock) *
710 ************************************************************************/
712 static int elmcan_netdev_init(struct net_device *dev)
714 struct elmcan *elm = netdev_priv(dev);
716 /* Copy the interface name here, so the SIOCGIFNAME case in
717 * elmcan_ldisc_ioctl() doesn't race against unregister_candev().
719 memcpy(elm->ifname, dev->name, IFNAMSIZ);
724 /* Netdevice DOWN -> UP routine */
725 static int elmcan_netdev_open(struct net_device *dev)
727 struct elmcan *elm = netdev_priv(dev);
730 spin_lock_bh(&elm->lock);
731 if (elm->tty == NULL) {
732 spin_unlock_bh(&elm->lock);
736 /* open_candev() checks for elm->can.bittiming.bitrate != 0 */
737 err = open_candev(dev);
739 spin_unlock_bh(&elm->lock);
743 /* Initialize the ELM327 */
745 spin_unlock_bh(&elm->lock);
747 can_led_event(dev, CAN_LED_EVENT_OPEN);
748 elm->can.state = CAN_STATE_ERROR_ACTIVE;
749 netif_start_queue(dev);
754 /* Netdevice UP -> DOWN routine */
755 static int elmcan_netdev_close(struct net_device *dev)
757 struct elmcan *elm = netdev_priv(dev);
759 spin_lock_bh(&elm->lock);
761 /* TTY discipline is running. */
763 /* Interrupt whatever we're doing right now */
764 elm327_send(elm, ELM327_MAGIC_STRING, 1);
766 /* Clear the wakeup bit, as the netdev will be down and thus
767 * the wakeup handler won't clear it
769 clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
771 spin_unlock_bh(&elm->lock);
773 flush_work(&elm->tx_work);
775 spin_unlock_bh(&elm->lock);
778 elm->can.state = CAN_STATE_STOPPED;
779 netif_stop_queue(dev);
781 can_led_event(dev, CAN_LED_EVENT_STOP);
786 /* Send a can_frame to a TTY queue. */
787 static netdev_tx_t elmcan_netdev_start_xmit(struct sk_buff *skb, struct net_device *dev)
789 struct elmcan *elm = netdev_priv(dev);
790 struct can_frame *frame = (struct can_frame *) skb->data;
792 if (skb->len != sizeof(struct can_frame))
795 if (!netif_running(dev)) {
796 netdev_warn(elm->dev, "xmit: iface is down.\n");
800 /* BHs are already disabled, so no spin_lock_bh().
801 * See Documentation/networking/netdevices.txt
803 spin_lock(&elm->lock);
805 || elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY) {
806 spin_unlock(&elm->lock);
810 netif_stop_queue(dev);
812 elm327_send_frame(elm, frame);
813 spin_unlock(&elm->lock);
815 dev->stats.tx_packets++;
816 dev->stats.tx_bytes += frame->can_dlc;
818 can_led_event(dev, CAN_LED_EVENT_TX);
825 static int elmcan_netdev_change_mtu(struct net_device *dev, int new_mtu)
830 static const struct net_device_ops elmcan_netdev_ops = {
831 .ndo_init = elmcan_netdev_init,
832 .ndo_open = elmcan_netdev_open,
833 .ndo_stop = elmcan_netdev_close,
834 .ndo_start_xmit = elmcan_netdev_start_xmit,
835 .ndo_change_mtu = elmcan_netdev_change_mtu,
842 /************************************************************************
845 * (takes elm->lock) *
846 ************************************************************************/
849 * Get a reference to our struct, taking into account locks/refcounts.
850 * This is to ensure ordering in case we are shutting down, and to ensure
851 * there is a refcount at all (because tty->disc_data may be NULL).
853 static struct elmcan* get_elm(struct tty_struct *tty)
858 /* Lock all elmcan TTYs, so tty->disc_data can't become NULL
859 * the moment before we increase the reference counter.
861 spin_lock_bh(&elmcan_discdata_lock);
862 elm = (struct elmcan *) tty->disc_data;
865 spin_unlock_bh(&elmcan_discdata_lock);
869 got_ref = atomic_inc_not_zero(&elm->refcount);
870 spin_unlock_bh(&elmcan_discdata_lock);
879 static void put_elm(struct elmcan *elm)
881 atomic_dec(&elm->refcount);
887 * Handle the 'receiver data ready' interrupt.
888 * This function is called by the 'tty_io' module in the kernel when
889 * a block of ELM327 CAN data has been received, which can now be parsed
890 * and sent on to some IP layer for further processing. This will not
891 * be re-entered while running but other ldisc functions may be called
894 static void elmcan_ldisc_rx(struct tty_struct *tty,
895 const unsigned char *cp, char *fp, int count)
897 struct elmcan *elm = get_elm(tty);
902 /* Read the characters out of the buffer */
903 while (count-- && elm->rxfill < sizeof(elm->rxbuf)) {
905 pr_err("Error in received character stream. Check your wiring.");
907 spin_lock_bh(&elm->lock);
908 elm327_hw_failure(elm);
909 spin_unlock_bh(&elm->lock);
915 elm->rxbuf[elm->rxfill++] = *cp;
921 pr_err("Receive buffer overflowed. Bad chip or wiring?");
923 spin_lock_bh(&elm->lock);
924 elm327_hw_failure(elm);
925 spin_unlock_bh(&elm->lock);
931 spin_lock_bh(&elm->lock);
932 elm327_parse_rxbuf(elm);
933 spin_unlock_bh(&elm->lock);
939 * Write out remaining transmit buffer.
940 * Scheduled when TTY is writable.
942 static void elmcan_ldisc_tx_worker(struct work_struct *work)
944 /* No need to use get_elm() here, as we'll always flush workers
945 * befory destroying the elmcan object.
947 struct elmcan *elm = container_of(work, struct elmcan, tx_work);
950 spin_lock_bh(&elm->lock);
951 /* First make sure we're connected. */
952 if (!elm->tty || !netif_running(elm->dev)) {
953 spin_unlock_bh(&elm->lock);
957 if (elm->txleft <= 0) {
958 /* Our TTY write buffer is empty:
959 * We can start transmission of another packet
961 clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
962 spin_unlock_bh(&elm->lock);
963 netif_wake_queue(elm->dev);
967 actual = elm->tty->ops->write(elm->tty, elm->txhead, elm->txleft);
969 netdev_err(elm->dev, "Failed to write to tty %s.\n", elm->tty->name);
970 elm327_hw_failure(elm);
973 elm->txleft -= actual;
974 elm->txhead += actual;
975 spin_unlock_bh(&elm->lock);
980 * Called by the driver when there's room for more data.
981 * Schedule the transmit.
983 static void elmcan_ldisc_tx_wakeup(struct tty_struct *tty)
985 struct elmcan *elm = get_elm(tty);
990 schedule_work(&elm->tx_work);
997 /* Some fake bit timings to allow bitrate setting */
998 static const struct can_bittiming_const elmcan_bittiming_const = {
1011 * Open the high-level part of the elmcan channel.
1012 * This function is called by the TTY module when the
1013 * elmcan line discipline is called for.
1015 * Called in process context serialized from other ldisc calls.
1017 static int elmcan_ldisc_open(struct tty_struct *tty)
1019 struct net_device *dev;
1023 if (!capable(CAP_NET_ADMIN))
1026 if (!tty->ops->write)
1030 /* OK. Find a free elmcan channel to use. */
1031 dev = alloc_candev(sizeof(struct elmcan), 0);
1034 elm = netdev_priv(dev);
1036 /* Configure TTY interface */
1037 tty->receive_room = 65536; /* We don't flow control */
1038 elm->txleft = 0; /* Clear TTY TX buffer */
1039 spin_lock_init(&elm->lock);
1040 atomic_set(&elm->refcount, 1);
1041 INIT_WORK(&elm->tx_work, elmcan_ldisc_tx_worker);
1043 /* Configure CAN metadata */
1044 elm->can.state = CAN_STATE_STOPPED;
1045 elm->can.clock.freq = 1000000;
1046 elm->can.bittiming_const = &elmcan_bittiming_const;
1047 elm->can.ctrlmode_supported = CAN_CTRLMODE_LISTENONLY;
1049 /* Configure netlink interface */
1051 dev->netdev_ops = &elmcan_netdev_ops;
1053 /* Mark ldisc channel as alive */
1055 tty->disc_data = elm;
1057 devm_can_led_init(elm->dev);
1060 err = register_candev(elm->dev);
1062 free_candev(elm->dev);
1066 netdev_info(elm->dev, "elmcan on %s.\n", tty->name);
1072 * Close down an elmcan channel.
1073 * This means flushing out any pending queues, and then returning.
1074 * This call is serialized against other ldisc functions:
1075 * Once this is called, no other ldisc function of ours is entered.
1077 * We also use this function for a hangup event.
1079 static void elmcan_ldisc_close(struct tty_struct *tty)
1081 /* Use get_elm() to synchronize against other users */
1082 struct elmcan *elm = get_elm(tty);
1087 /* Tear down network side.
1088 * unregister_netdev() calls .ndo_stop() so we don't have to.
1090 unregister_candev(elm->dev);
1092 /* Decrease the refcount twice, once for our own get_elm(),
1093 * and once to remove the count of 1 that we set in _open().
1094 * Once it reaches 0, we can safely destroy it.
1099 /* Spin until refcount reaches 0 */
1100 while(atomic_read(&elm->refcount) > 0)
1103 /* At this point, all ldisc calls to us will be no-ops.
1104 * Since the refcount is 0, they are bailing immediately.
1107 /* Mark channel as dead */
1108 spin_lock_bh(&elm->lock);
1109 tty->disc_data = NULL;
1111 spin_unlock_bh(&elm->lock);
1113 /* Flush TTY side */
1114 flush_work(&elm->tx_work);
1116 netdev_info(elm->dev, "elmcan off %s.\n", tty->name);
1118 /* Free our memory */
1119 free_candev(elm->dev);
1122 static int elmcan_ldisc_hangup(struct tty_struct *tty)
1124 elmcan_ldisc_close(tty);
1128 /* Perform I/O control on an active elmcan channel. */
1129 static int elmcan_ldisc_ioctl(struct tty_struct *tty, struct file *file,
1130 unsigned int cmd, unsigned long arg)
1132 struct elmcan *elm = get_elm(tty);
1135 /* First make sure we're connected. */
1141 tmp = strlen(elm->ifname) + 1;
1142 if (copy_to_user((void __user *)arg, elm->ifname, tmp)) {
1156 return tty_mode_ioctl(tty, file, cmd, arg);
1160 static struct tty_ldisc_ops elmcan_ldisc = {
1161 .owner = THIS_MODULE,
1162 .magic = TTY_LDISC_MAGIC,
1164 .receive_buf = elmcan_ldisc_rx,
1165 .write_wakeup = elmcan_ldisc_tx_wakeup,
1166 .open = elmcan_ldisc_open,
1167 .close = elmcan_ldisc_close,
1168 .hangup = elmcan_ldisc_hangup,
1169 .ioctl = elmcan_ldisc_ioctl,
1176 /************************************************************************
1177 * Module init/exit *
1178 ************************************************************************/
1180 static int __init elmcan_init(void)
1184 pr_info("ELM327 based best-effort CAN interface driver\n");
1185 pr_info("This device is severely limited as a CAN interface, see documentation.\n");
1187 /* Fill in our line protocol discipline, and register it */
1188 status = tty_register_ldisc(N_ELMCAN, &elmcan_ldisc);
1190 pr_err("can't register line discipline\n");
1195 static void __exit elmcan_exit(void)
1197 /* This will only be called when all channels have been closed by
1198 * userspace - tty_ldisc.c takes care of the module's refcount.
1202 status = tty_unregister_ldisc(N_ELMCAN);
1204 pr_err("Can't unregister line discipline (error: %d)\n", status);
1208 module_init(elmcan_init);
1209 module_exit(elmcan_exit);