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 <max-linux@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/ctype.h>
26 #include <linux/delay.h>
27 #include <linux/errno.h>
28 #include <linux/if_ether.h>
29 #include <linux/kernel.h>
30 #include <linux/list.h>
31 #include <linux/netdevice.h>
32 #include <linux/skbuff.h>
33 #include <linux/spinlock.h>
34 #include <linux/string.h>
35 #include <linux/tty.h>
36 #include <linux/workqueue.h>
38 #include <linux/can.h>
39 #include <linux/can/dev.h>
40 #include <linux/can/error.h>
41 #include <linux/can/led.h>
44 MODULE_ALIAS_LDISC(N_ELMCAN);
45 MODULE_DESCRIPTION("ELM327 based CAN interface");
46 MODULE_LICENSE("GPL");
47 MODULE_AUTHOR("Max Staudt <max-linux@enpas.org>");
49 /* If this is enabled, we'll try to make the best of the situation
50 * even if we receive unexpected characters on the line.
52 * Handle with care, it's likely your hardware is unreliable!
54 static bool accept_flaky_uart = false;
55 module_param_named(accept_flaky_uart, accept_flaky_uart, bool, 0444);
56 MODULE_PARM_DESC(accept_flaky_uart, "Don't bail at the first invalid character. Behavior undefined.");
59 /* Line discipline ID number */
64 #define ELM327_CAN_CONFIG_SEND_SFF 0x8000
65 #define ELM327_CAN_CONFIG_VARIABLE_DLC 0x4000
66 #define ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF 0x2000
67 #define ELM327_CAN_CONFIG_BAUDRATE_MULT_8_7 0x1000
69 #define ELM327_MAGIC_CHAR 'y'
70 #define ELM327_MAGIC_STRING "y"
71 #define ELM327_READY_CHAR '>'
74 /* Bits in elm->cmds_todo */
76 ELM_TODO_CAN_DATA = 0,
78 ELM_TODO_CANID_29BIT_LOW,
79 ELM_TODO_CANID_29BIT_HIGH,
80 ELM_TODO_CAN_CONFIG_PART2,
83 ELM_TODO_SILENT_MONITOR,
89 /* This must be the first member when using alloc_candev() */
92 /* TTY and netdev devices that we're bridging */
93 struct tty_struct *tty;
94 struct net_device *dev;
96 /* Per-channel lock */
99 /* Keep track of how many things are using this struct.
100 * Once it reaches 0, we are in the process of cleaning up,
101 * and new operations will be cancelled immediately.
102 * Use atomic_t rather than refcount_t because we deliberately
103 * decrement to 0, and refcount_dec() spills a WARN_ONCE in
108 /* Stop the channel on hardware failure.
109 * Once this is true, nothing will be sent to the TTY.
114 struct work_struct tx_work; /* Flushes TTY TX buffer */
115 unsigned char txbuf[32];
116 unsigned char *txhead; /* Pointer to next TX byte */
117 int txleft; /* Bytes left to TX */
120 unsigned char rxbuf[256];
133 /* The CAN frame and config the ELM327 is sending/using,
134 * or will send/use after finishing all cmds_todo */
135 struct can_frame can_frame;
136 unsigned short can_config;
137 unsigned long can_bitrate;
138 unsigned char can_bitrate_divisor;
139 int silent_monitoring;
141 /* Things we have yet to send */
142 char **next_init_cmd;
143 unsigned long cmds_todo;
147 /* A lock for all tty->disc_data handled by this ldisc.
148 * This is to prevent a case where tty->disc_data is set to NULL,
149 * yet someone is still trying to dereference it.
150 * Without this, we cannot do a clean shutdown.
152 static DEFINE_SPINLOCK(elmcan_discdata_lock);
155 static inline void elm327_hw_failure(struct elmcan *elm);
159 /************************************************************************
160 * ELM327: Transmission *
162 * (all functions assume elm->lock taken) *
163 ************************************************************************/
165 static void elm327_send(struct elmcan *elm, const void *buf, size_t len)
169 if (elm->hw_failure) {
173 memcpy(elm->txbuf, buf, len);
175 /* Order of next two lines is *very* important.
176 * When we are sending a little amount of data,
177 * the transfer may be completed inside the ops->write()
178 * routine, because it's running with interrupts enabled.
179 * In this case we *never* got WRITE_WAKEUP event,
180 * if we did not request it before write operation.
181 * 14 Oct 1994 Dmitry Gorodchanin.
183 set_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
184 actual = elm->tty->ops->write(elm->tty, elm->txbuf, len);
186 netdev_err(elm->dev, "Failed to write to tty %s.\n", elm->tty->name);
187 elm327_hw_failure(elm);
191 elm->txleft = len - actual;
192 elm->txhead = elm->txbuf + actual;
197 * Take the ELM327 out of almost any state and back into command mode
199 * Assumes elm->lock taken.
201 static void elm327_kick_into_cmd_mode(struct elmcan *elm)
203 if (elm->state != ELM_GETMAGICCHAR && elm->state != ELM_GETPROMPT) {
204 elm327_send(elm, ELM327_MAGIC_STRING, 1);
206 elm->state = ELM_GETMAGICCHAR;
212 * Schedule a CAN frame, and any necessary config changes,
213 * to be sent down the TTY.
215 * Assumes elm->lock taken.
217 static void elm327_send_frame(struct elmcan *elm, struct can_frame *frame)
219 /* Schedule any necessary changes in ELM327's CAN configuration */
220 if (elm->can_frame.can_id != frame->can_id) {
221 /* Set the new CAN ID for transmission. */
222 if ((frame->can_id & CAN_EFF_FLAG) ^ (elm->can_frame.can_id & CAN_EFF_FLAG)) {
223 elm->can_config = (frame->can_id & CAN_EFF_FLAG ? 0 : ELM327_CAN_CONFIG_SEND_SFF)
224 | ELM327_CAN_CONFIG_VARIABLE_DLC
225 | ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF
226 | elm->can_bitrate_divisor;
228 set_bit(ELM_TODO_CAN_CONFIG, &elm->cmds_todo);
231 if (frame->can_id & CAN_EFF_FLAG) {
232 clear_bit(ELM_TODO_CANID_11BIT, &elm->cmds_todo);
233 set_bit(ELM_TODO_CANID_29BIT_LOW, &elm->cmds_todo);
234 set_bit(ELM_TODO_CANID_29BIT_HIGH, &elm->cmds_todo);
236 set_bit(ELM_TODO_CANID_11BIT, &elm->cmds_todo);
237 clear_bit(ELM_TODO_CANID_29BIT_LOW, &elm->cmds_todo);
238 clear_bit(ELM_TODO_CANID_29BIT_HIGH, &elm->cmds_todo);
242 /* Schedule the CAN frame itself. */
243 elm->can_frame = *frame;
244 set_bit(ELM_TODO_CAN_DATA, &elm->cmds_todo);
246 elm327_kick_into_cmd_mode(elm);
251 /************************************************************************
252 * ELM327: Initialization sequence *
254 * (assumes elm->lock taken) *
255 ************************************************************************/
257 static char *elm327_init_script[] = {
258 "AT WS\r", /* v1.0: Warm Start */
259 "AT PP FF OFF\r", /* v1.0: All Programmable Parameters Off */
260 "AT M0\r", /* v1.0: Memory Off */
261 "AT AL\r", /* v1.0: Allow Long messages */
262 "AT BI\r", /* v1.0: Bypass Initialization */
263 "AT CAF0\r", /* v1.0: CAN Auto Formatting Off */
264 "AT CFC0\r", /* v1.0: CAN Flow Control Off */
265 "AT CF 000\r", /* v1.0: Reset CAN ID Filter */
266 "AT CM 000\r", /* v1.0: Reset CAN ID Mask */
267 "AT E1\r", /* v1.0: Echo On */
268 "AT H1\r", /* v1.0: Headers On */
269 "AT L0\r", /* v1.0: Linefeeds Off */
270 "AT SH 7DF\r", /* v1.0: Set CAN sending ID to 0x7df */
271 "AT ST FF\r", /* v1.0: Set maximum Timeout for response after TX */
272 "AT AT0\r", /* v1.2: Adaptive Timing Off */
273 "AT D1\r", /* v1.3: Print DLC On */
274 "AT S1\r", /* v1.3: Spaces On */
275 "AT TP B\r", /* v1.0: Try Protocol B */
280 static void elm327_init(struct elmcan *elm)
282 elm->state = ELM_NOTINIT;
283 elm->can_frame.can_id = 0x7df;
285 elm->drop_next_line = 0;
287 /* We can only set the bitrate as a fraction of 500000.
288 * The bit timing constants in elmcan_bittiming_const will
289 * limit the user to the right values.
291 elm->can_bitrate_divisor = 500000 / elm->can.bittiming.bitrate;
292 elm->can_config = ELM327_CAN_CONFIG_SEND_SFF
293 | ELM327_CAN_CONFIG_VARIABLE_DLC
294 | ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF
295 | elm->can_bitrate_divisor;
297 /* Configure ELM327 and then start monitoring */
298 elm->next_init_cmd = &elm327_init_script[0];
299 set_bit(ELM_TODO_INIT, &elm->cmds_todo);
300 set_bit(ELM_TODO_SILENT_MONITOR, &elm->cmds_todo);
301 set_bit(ELM_TODO_RESPONSES, &elm->cmds_todo);
302 set_bit(ELM_TODO_CAN_CONFIG, &elm->cmds_todo);
304 elm327_kick_into_cmd_mode(elm);
309 /************************************************************************
310 * ELM327: Reception -> netdev glue *
312 * (assumes elm->lock taken) *
313 ************************************************************************/
315 static void elm327_feed_frame_to_netdev(struct elmcan *elm, const struct can_frame *frame)
317 struct can_frame *cf;
320 if (!netif_running(elm->dev)) {
324 skb = alloc_can_skb(elm->dev, &cf);
329 memcpy(cf, frame, sizeof(struct can_frame));
331 elm->dev->stats.rx_packets++;
332 elm->dev->stats.rx_bytes += frame->can_dlc;
335 can_led_event(elm->dev, CAN_LED_EVENT_RX);
340 /************************************************************************
341 * ELM327: "Panic" handler *
343 * (assumes elm->lock taken) *
344 ************************************************************************/
346 /* Called when we're out of ideas and just want it all to end. */
347 static inline void elm327_hw_failure(struct elmcan *elm)
349 struct can_frame frame;
351 memset(&frame, 0, sizeof(frame));
352 frame.can_id = CAN_ERR_FLAG;
353 frame.can_dlc = CAN_ERR_DLC;
357 elm327_feed_frame_to_netdev(elm, &frame);
359 netdev_err(elm->dev, "ELM327 misbehaved. "
360 "Blocking further communication.\n");
362 elm->hw_failure = true;
363 can_bus_off(elm->dev);
368 /************************************************************************
369 * ELM327: Reception parser *
371 * (assumes elm->lock taken) *
372 ************************************************************************/
374 static bool elm327_is_ready_char(char c)
376 /* Bits 0xc0 are sometimes set (randomly), hence the mask.
377 * Probably bad hardware.
379 return (c & 0x3f) == ELM327_READY_CHAR;
383 static void elm327_parse_error(struct elmcan *elm, int len)
385 struct can_frame frame;
387 memset(&frame, 0, sizeof(frame));
388 frame.can_id = CAN_ERR_FLAG;
389 frame.can_dlc = CAN_ERR_DLC;
393 if (!memcmp(elm->rxbuf, "UNABLE TO CONNECT", 17)) {
394 netdev_err(elm->dev, "The ELM327 reported UNABLE TO CONNECT. Please check your setup.\n");
398 if (!memcmp(elm->rxbuf, "BUFFER FULL", 11)) {
399 /* This case will only happen if the last data
401 * Otherwise, elm327_parse_frame() will emit the
402 * error frame instead.
404 frame.can_id |= CAN_ERR_CRTL;
405 frame.data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
409 if (!memcmp(elm->rxbuf, "BUS ERROR", 9)) {
410 frame.can_id |= CAN_ERR_BUSERROR;
412 if (!memcmp(elm->rxbuf, "CAN ERROR", 9)
413 || !memcmp(elm->rxbuf, "<RX ERROR", 9)) {
414 frame.can_id |= CAN_ERR_PROT;
418 if (!memcmp(elm->rxbuf, "BUS BUSY", 8)) {
419 frame.can_id |= CAN_ERR_PROT;
420 frame.data[2] = CAN_ERR_PROT_OVERLOAD;
422 if (!memcmp(elm->rxbuf, "FB ERROR", 8)) {
423 frame.can_id |= CAN_ERR_PROT;
424 frame.data[2] = CAN_ERR_PROT_TX;
428 if (!memcmp(elm->rxbuf, "ERR", 3)) {
429 netdev_err(elm->dev, "The ELM327 reported an ERR%c%c. Please power it off and on again.\n",
430 elm->rxbuf[3], elm->rxbuf[4]);
431 frame.can_id |= CAN_ERR_CRTL;
435 /* Don't emit an error frame if we're unsure */
439 elm327_feed_frame_to_netdev(elm, &frame);
443 static int elm327_parse_frame(struct elmcan *elm, int len)
445 struct can_frame frame;
450 memset(&frame, 0, sizeof(frame));
452 /* Find first non-hex and non-space character:
453 * - In the simplest case, there is none.
454 * - For RTR frames, 'R' is the first non-hex character.
455 * - An error message may replace the end of the data line.
457 for (hexlen = 0; hexlen <= len; hexlen++) {
458 if (hex_to_bin(elm->rxbuf[hexlen]) < 0
459 && elm->rxbuf[hexlen] != ' ') {
464 /* If we accept stray characters coming in:
465 * Check for stray characters on a payload line.
466 * No idea what causes this.
468 if (accept_flaky_uart
470 && !isdigit(elm->rxbuf[hexlen])
471 && !isupper(elm->rxbuf[hexlen])
472 && '<' != elm->rxbuf[hexlen]
473 && ' ' != elm->rxbuf[hexlen]) {
474 /* The line is likely garbled anyway, so bail.
475 * The main code will restart listening.
477 elm327_kick_into_cmd_mode(elm);
481 /* Use spaces in CAN ID to distinguish 29 or 11 bit address length.
482 * No out-of-bounds access:
483 * We use the fact that we can always read from elm->rxbuf.
485 if (elm->rxbuf[2] == ' ' && elm->rxbuf[5] == ' '
486 && elm->rxbuf[8] == ' ' && elm->rxbuf[11] == ' '
487 && elm->rxbuf[13] == ' ') {
488 frame.can_id = CAN_EFF_FLAG;
490 } else if (elm->rxbuf[3] == ' ' && elm->rxbuf[5] == ' ') {
494 /* This is not a well-formatted data line.
495 * Assume it's an error message.
500 if (hexlen < datastart) {
501 /* The line is too short to be a valid frame hex dump.
502 * Something interrupted the hex dump or it is invalid.
507 /* From here on all chars up to buf[hexlen] are hex or spaces,
508 * at well-defined offsets.
511 /* Read CAN data length */
512 frame.can_dlc = (hex_to_bin(elm->rxbuf[datastart - 2]) << 0);
515 if (frame.can_id & CAN_EFF_FLAG) {
516 frame.can_id |= (hex_to_bin(elm->rxbuf[0]) << 28)
517 | (hex_to_bin(elm->rxbuf[1]) << 24)
518 | (hex_to_bin(elm->rxbuf[3]) << 20)
519 | (hex_to_bin(elm->rxbuf[4]) << 16)
520 | (hex_to_bin(elm->rxbuf[6]) << 12)
521 | (hex_to_bin(elm->rxbuf[7]) << 8)
522 | (hex_to_bin(elm->rxbuf[9]) << 4)
523 | (hex_to_bin(elm->rxbuf[10]) << 0);
525 frame.can_id |= (hex_to_bin(elm->rxbuf[0]) << 8)
526 | (hex_to_bin(elm->rxbuf[1]) << 4)
527 | (hex_to_bin(elm->rxbuf[2]) << 0);
530 /* Check for RTR frame */
531 if (elm->rxfill >= hexlen + 3
532 && elm->rxbuf[hexlen + 0] == 'R'
533 && elm->rxbuf[hexlen + 1] == 'T'
534 && elm->rxbuf[hexlen + 2] == 'R') {
535 frame.can_id |= CAN_RTR_FLAG;
538 /* Is the line long enough to hold the advertised payload? */
539 if (!(frame.can_id & CAN_RTR_FLAG) && (hexlen < frame.can_dlc * 3 + datastart)) {
540 /* Incomplete frame. */
542 /* Probably the ELM327's RS232 TX buffer was full.
543 * Emit an error frame and exit.
545 frame.can_id = CAN_ERR_FLAG | CAN_ERR_CRTL;
546 frame.can_dlc = CAN_ERR_DLC;
547 frame.data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
548 elm327_feed_frame_to_netdev(elm, &frame);
550 /* Signal failure to parse.
551 * The line will be re-parsed as an error line, which will fail.
552 * However, this will correctly drop the state machine back into
558 /* Parse the data nibbles. */
559 for (i = 0; i < frame.can_dlc; i++) {
560 frame.data[i] = (hex_to_bin(elm->rxbuf[datastart+3*i]) << 4)
561 | (hex_to_bin(elm->rxbuf[datastart+3*i+1]) << 0);
564 /* Feed the frame to the network layer. */
565 elm327_feed_frame_to_netdev(elm, &frame);
571 static void elm327_parse_line(struct elmcan *elm, int len)
573 /* Skip empty lines */
578 /* Skip echo lines */
579 if (elm->drop_next_line) {
580 elm->drop_next_line = 0;
582 } else if (elm->rxbuf[0] == 'A' && elm->rxbuf[1] == 'T') {
586 /* Regular parsing */
589 if (elm327_parse_frame(elm, len)) {
590 /* Parse an error line. */
591 elm327_parse_error(elm, len);
594 elm327_kick_into_cmd_mode(elm);
603 static void elm327_handle_prompt(struct elmcan *elm)
605 if (elm->cmds_todo) {
606 struct can_frame *frame = &elm->can_frame;
607 char local_txbuf[20];
609 if (test_bit(ELM_TODO_INIT, &elm->cmds_todo)) {
610 elm327_send(elm, *elm->next_init_cmd, strlen(*elm->next_init_cmd));
611 elm->next_init_cmd++;
612 if (!(*elm->next_init_cmd)) {
613 clear_bit(ELM_TODO_INIT, &elm->cmds_todo);
614 netdev_info(elm->dev, "Initialization finished.\n");
617 /* Some chips are unreliable and need extra time after
618 * init commands, as seen with a clone.
619 * So let's do a dummy get-cmd-prompt dance.
621 elm->state = ELM_NOTINIT;
622 elm327_kick_into_cmd_mode(elm);
626 } else if (test_and_clear_bit(ELM_TODO_SILENT_MONITOR, &elm->cmds_todo)) {
627 sprintf(local_txbuf, "ATCSM%i\r",
628 !(!(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY)));
630 } else if (test_and_clear_bit(ELM_TODO_RESPONSES, &elm->cmds_todo)) {
631 sprintf(local_txbuf, "ATR%i\r",
632 !(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY));
634 } else if (test_and_clear_bit(ELM_TODO_CAN_CONFIG, &elm->cmds_todo)) {
635 sprintf(local_txbuf, "ATPC\r");
636 set_bit(ELM_TODO_CAN_CONFIG_PART2, &elm->cmds_todo);
638 } else if (test_and_clear_bit(ELM_TODO_CAN_CONFIG_PART2, &elm->cmds_todo)) {
639 sprintf(local_txbuf, "ATPB%04X\r",
642 } else if (test_and_clear_bit(ELM_TODO_CANID_29BIT_HIGH, &elm->cmds_todo)) {
643 sprintf(local_txbuf, "ATCP%02X\r",
644 (frame->can_id & CAN_EFF_MASK) >> 24);
646 } else if (test_and_clear_bit(ELM_TODO_CANID_29BIT_LOW, &elm->cmds_todo)) {
647 sprintf(local_txbuf, "ATSH%06X\r",
648 frame->can_id & CAN_EFF_MASK & ((1 << 24) - 1));
650 } else if (test_and_clear_bit(ELM_TODO_CANID_11BIT, &elm->cmds_todo)) {
651 sprintf(local_txbuf, "ATSH%03X\r",
652 frame->can_id & CAN_SFF_MASK);
654 } else if (test_and_clear_bit(ELM_TODO_CAN_DATA, &elm->cmds_todo)) {
655 if (frame->can_id & CAN_RTR_FLAG) {
656 /* Send an RTR frame. Their DLC is fixed.
657 * Some chips don't send them at all.
659 sprintf(local_txbuf, "ATRTR\r");
661 /* Send a regular CAN data frame */
664 for (i = 0; i < frame->can_dlc; i++) {
665 sprintf(&local_txbuf[2*i], "%02X",
669 sprintf(&local_txbuf[2*i], "\r");
672 elm->drop_next_line = 1;
673 elm->state = ELM_RECEIVING;
676 elm327_send(elm, local_txbuf, strlen(local_txbuf));
678 /* Enter CAN monitor mode */
679 elm327_send(elm, "ATMA\r", 5);
680 elm->state = ELM_RECEIVING;
685 static void elm327_drop_bytes(struct elmcan *elm, int i)
687 memmove(&elm->rxbuf[0], &elm->rxbuf[i], sizeof(elm->rxbuf) - i);
692 static void elm327_parse_rxbuf(struct elmcan *elm)
696 switch (elm->state) {
701 case ELM_GETMAGICCHAR:
703 /* Wait for 'y' or '>' */
706 for (i = 0; i < elm->rxfill; i++) {
707 if (elm->rxbuf[i] == ELM327_MAGIC_CHAR) {
708 elm327_send(elm, "\r", 1);
709 elm->state = ELM_GETPROMPT;
712 } else if (elm327_is_ready_char(elm->rxbuf[i])) {
713 elm327_send(elm, ELM327_MAGIC_STRING, 1);
719 elm327_drop_bytes(elm, i);
726 if (elm327_is_ready_char(elm->rxbuf[elm->rxfill - 1])) {
727 elm327_handle_prompt(elm);
734 /* Find <CR> delimiting feedback lines. */
736 (len < elm->rxfill) && (elm->rxbuf[len] != '\r');
741 if (len == sizeof(elm->rxbuf)) {
742 /* Line exceeds buffer. It's probably all garbage.
743 * Did we even connect at the right baud rate?
745 netdev_err(elm->dev, "RX buffer overflow. Faulty ELM327 connected?\n");
746 elm327_hw_failure(elm);
748 } else if (len == elm->rxfill) {
749 if (elm->state == ELM_RECEIVING
750 && elm327_is_ready_char(elm->rxbuf[elm->rxfill - 1])) {
751 /* The ELM327's AT ST response timeout ran out,
752 * so we got a prompt.
753 * Clear RX buffer and restart listening.
757 elm327_handle_prompt(elm);
760 /* We haven't received a full line yet.
761 * Wait for more data.
767 /* We have a full line to parse. */
768 elm327_parse_line(elm, len);
770 /* Remove parsed data from RX buffer. */
771 elm327_drop_bytes(elm, len+1);
773 /* More data to parse? */
775 elm327_parse_rxbuf(elm);
784 /************************************************************************
787 * (takes elm->lock) *
788 ************************************************************************/
790 /* Netdevice DOWN -> UP routine */
791 static int elmcan_netdev_open(struct net_device *dev)
793 struct elmcan *elm = netdev_priv(dev);
796 spin_lock_bh(&elm->lock);
797 if (elm->hw_failure) {
798 netdev_err(elm->dev, "Refusing to open interface after "
799 "a hardware fault has been detected.\n");
800 spin_unlock_bh(&elm->lock);
804 if (elm->tty == NULL) {
805 spin_unlock_bh(&elm->lock);
809 /* open_candev() checks for elm->can.bittiming.bitrate != 0 */
810 err = open_candev(dev);
812 spin_unlock_bh(&elm->lock);
816 /* Initialize the ELM327 */
818 spin_unlock_bh(&elm->lock);
820 can_led_event(dev, CAN_LED_EVENT_OPEN);
821 elm->can.state = CAN_STATE_ERROR_ACTIVE;
822 netif_start_queue(dev);
827 /* Netdevice UP -> DOWN routine */
828 static int elmcan_netdev_close(struct net_device *dev)
830 struct elmcan *elm = netdev_priv(dev);
832 spin_lock_bh(&elm->lock);
834 /* TTY discipline is running. */
836 /* Interrupt whatever we're doing right now */
837 elm327_send(elm, ELM327_MAGIC_STRING, 1);
839 /* Clear the wakeup bit, as the netdev will be down and thus
840 * the wakeup handler won't clear it
842 clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
844 spin_unlock_bh(&elm->lock);
846 flush_work(&elm->tx_work);
848 spin_unlock_bh(&elm->lock);
851 elm->can.state = CAN_STATE_STOPPED;
852 netif_stop_queue(dev);
854 can_led_event(dev, CAN_LED_EVENT_STOP);
859 /* Send a can_frame to a TTY queue. */
860 static netdev_tx_t elmcan_netdev_start_xmit(struct sk_buff *skb, struct net_device *dev)
862 struct elmcan *elm = netdev_priv(dev);
863 struct can_frame *frame = (struct can_frame *) skb->data;
865 if (skb->len != sizeof(struct can_frame))
868 if (!netif_running(dev)) {
869 netdev_warn(elm->dev, "xmit: iface is down.\n");
873 /* BHs are already disabled, so no spin_lock_bh().
874 * See Documentation/networking/netdevices.txt
876 spin_lock(&elm->lock);
878 /* We shouldn't get here after a hardware fault:
879 * can_bus_off() calls netif_carrier_off()
881 BUG_ON(elm->hw_failure);
884 || elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY) {
885 spin_unlock(&elm->lock);
889 netif_stop_queue(dev);
891 elm327_send_frame(elm, frame);
892 spin_unlock(&elm->lock);
894 dev->stats.tx_packets++;
895 dev->stats.tx_bytes += frame->can_dlc;
897 can_led_event(dev, CAN_LED_EVENT_TX);
904 static int elmcan_netdev_change_mtu(struct net_device *dev, int new_mtu)
909 static const struct net_device_ops elmcan_netdev_ops = {
910 .ndo_open = elmcan_netdev_open,
911 .ndo_stop = elmcan_netdev_close,
912 .ndo_start_xmit = elmcan_netdev_start_xmit,
913 .ndo_change_mtu = elmcan_netdev_change_mtu,
920 /************************************************************************
923 * (takes elm->lock) *
924 ************************************************************************/
927 * Get a reference to our struct, taking into account locks/refcounts.
928 * This is to ensure ordering in case we are shutting down, and to ensure
929 * there is a refcount at all (because tty->disc_data may be NULL).
931 static struct elmcan* get_elm(struct tty_struct *tty)
936 /* Lock all elmcan TTYs, so tty->disc_data can't become NULL
937 * the moment before we increase the reference counter.
939 spin_lock_bh(&elmcan_discdata_lock);
940 elm = (struct elmcan *) tty->disc_data;
943 spin_unlock_bh(&elmcan_discdata_lock);
947 got_ref = atomic_inc_not_zero(&elm->refcount);
948 spin_unlock_bh(&elmcan_discdata_lock);
957 static void put_elm(struct elmcan *elm)
959 atomic_dec(&elm->refcount);
965 * Handle the 'receiver data ready' interrupt.
966 * This function is called by the 'tty_io' module in the kernel when
967 * a block of ELM327 CAN data has been received, which can now be parsed
968 * and sent on to some IP layer for further processing. This will not
969 * be re-entered while running but other ldisc functions may be called
972 static void elmcan_ldisc_rx(struct tty_struct *tty,
973 const unsigned char *cp, char *fp, int count)
975 struct elmcan *elm = get_elm(tty);
980 spin_lock_bh(&elm->lock);
981 if (elm->hw_failure) {
982 spin_unlock_bh(&elm->lock);
988 /* Read the characters out of the buffer */
989 while (count-- && elm->rxfill < sizeof(elm->rxbuf)) {
991 netdev_err(elm->dev, "Error in received character stream. Check your wiring.");
993 spin_lock_bh(&elm->lock);
994 elm327_hw_failure(elm);
995 spin_unlock_bh(&elm->lock);
1001 /* Ignore NUL characters, which the PIC microcontroller may
1002 * inadvertently insert due to a known hardware bug.
1003 * See ELM327 documentation, which refers to a Microchip PIC
1007 /* Check for stray characters on the UART line.
1008 * No idea what causes this.
1010 if (!accept_flaky_uart
1013 && ELM327_MAGIC_CHAR != *cp
1014 && ELM327_READY_CHAR != *cp
1023 /* We've received an invalid character, so bail.
1024 * There's something wrong with the ELM327, or
1025 * with the UART line.
1027 netdev_err(elm->dev,
1028 "Received illegal character %02x.\n",
1030 elm327_hw_failure(elm);
1031 spin_unlock_bh(&elm->lock);
1037 elm->rxbuf[elm->rxfill++] = *cp;
1044 netdev_err(elm->dev, "Receive buffer overflowed. Bad chip or wiring?");
1046 elm327_hw_failure(elm);
1047 spin_unlock_bh(&elm->lock);
1053 elm327_parse_rxbuf(elm);
1054 spin_unlock_bh(&elm->lock);
1060 * Write out remaining transmit buffer.
1061 * Scheduled when TTY is writable.
1063 static void elmcan_ldisc_tx_worker(struct work_struct *work)
1065 /* No need to use get_elm() here, as we'll always flush workers
1066 * befory destroying the elmcan object.
1068 struct elmcan *elm = container_of(work, struct elmcan, tx_work);
1071 spin_lock_bh(&elm->lock);
1072 if (elm->hw_failure) {
1073 spin_unlock_bh(&elm->lock);
1077 if (!elm->tty || !netif_running(elm->dev)) {
1078 spin_unlock_bh(&elm->lock);
1082 if (elm->txleft <= 0) {
1083 /* Our TTY write buffer is empty:
1084 * We can start transmission of another packet
1086 clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
1087 spin_unlock_bh(&elm->lock);
1088 netif_wake_queue(elm->dev);
1092 actual = elm->tty->ops->write(elm->tty, elm->txhead, elm->txleft);
1094 netdev_err(elm->dev, "Failed to write to tty %s.\n", elm->tty->name);
1095 elm327_hw_failure(elm);
1096 spin_unlock_bh(&elm->lock);
1100 elm->txleft -= actual;
1101 elm->txhead += actual;
1102 spin_unlock_bh(&elm->lock);
1107 * Called by the driver when there's room for more data.
1108 * Schedule the transmit.
1110 static void elmcan_ldisc_tx_wakeup(struct tty_struct *tty)
1112 struct elmcan *elm = get_elm(tty);
1117 schedule_work(&elm->tx_work);
1124 /* ELM327 can only handle bitrates that are integer divisors of 500 kHz,
1125 * or 7/8 of that. Divisors are 1 to 64.
1126 * Currently we don't implement support for 7/8 rates.
1128 static const u32 elmcan_bitrate_const[64] = {
1129 7812, 7936, 8064, 8196, 8333, 8474, 8620, 8771,
1130 8928, 9090, 9259, 9433, 9615, 9803, 10000, 10204,
1131 10416, 10638, 10869, 11111, 11363, 11627, 11904, 12195,
1132 12500, 12820, 13157, 13513, 13888, 14285, 14705, 15151,
1133 15625, 16129, 16666, 17241, 17857, 18518, 19230, 20000,
1134 20833, 21739, 22727, 23809, 25000, 26315, 27777, 29411,
1135 31250, 33333, 35714, 38461, 41666, 45454, 50000, 55555,
1136 62500, 71428, 83333, 100000, 125000, 166666, 250000, 500000
1139 /* Dummy function to claim we're changing the bitrate.
1140 * We actually do this when opening the net device.
1142 static int elmcan_do_set_bittiming(struct net_device *netdev)
1149 * Open the high-level part of the elmcan channel.
1150 * This function is called by the TTY module when the
1151 * elmcan line discipline is called for.
1153 * Called in process context serialized from other ldisc calls.
1155 static int elmcan_ldisc_open(struct tty_struct *tty)
1157 struct net_device *dev;
1161 if (!capable(CAP_NET_ADMIN))
1164 if (!tty->ops->write)
1168 /* OK. Find a free elmcan channel to use. */
1169 dev = alloc_candev(sizeof(struct elmcan), 0);
1172 elm = netdev_priv(dev);
1174 /* Configure TTY interface */
1175 tty->receive_room = 65536; /* We don't flow control */
1176 elm->txleft = 0; /* Clear TTY TX buffer */
1177 spin_lock_init(&elm->lock);
1178 atomic_set(&elm->refcount, 1);
1179 INIT_WORK(&elm->tx_work, elmcan_ldisc_tx_worker);
1181 /* Configure CAN metadata */
1182 elm->can.state = CAN_STATE_STOPPED;
1183 elm->can.bitrate_const = elmcan_bitrate_const;
1184 elm->can.bitrate_const_cnt = ARRAY_SIZE(elmcan_bitrate_const);
1185 elm->can.do_set_bittiming = elmcan_do_set_bittiming;
1186 elm->can.ctrlmode_supported = CAN_CTRLMODE_LISTENONLY;
1188 /* Configure netlink interface */
1190 dev->netdev_ops = &elmcan_netdev_ops;
1192 /* Mark ldisc channel as alive */
1194 tty->disc_data = elm;
1196 devm_can_led_init(elm->dev);
1199 err = register_candev(elm->dev);
1201 free_candev(elm->dev);
1205 netdev_info(elm->dev, "elmcan on %s.\n", tty->name);
1211 * Close down an elmcan channel.
1212 * This means flushing out any pending queues, and then returning.
1213 * This call is serialized against other ldisc functions:
1214 * Once this is called, no other ldisc function of ours is entered.
1216 * We also use this function for a hangup event.
1218 static void elmcan_ldisc_close(struct tty_struct *tty)
1220 /* Use get_elm() to synchronize against other users */
1221 struct elmcan *elm = get_elm(tty);
1226 /* Tear down network side.
1227 * unregister_netdev() calls .ndo_stop() so we don't have to.
1229 unregister_candev(elm->dev);
1231 /* Decrease the refcount twice, once for our own get_elm(),
1232 * and once to remove the count of 1 that we set in _open().
1233 * Once it reaches 0, we can safely destroy it.
1238 /* Spin until refcount reaches 0 */
1239 while(atomic_read(&elm->refcount) > 0)
1242 /* At this point, all ldisc calls to us will be no-ops.
1243 * Since the refcount is 0, they are bailing immediately.
1246 /* Mark channel as dead */
1247 spin_lock_bh(&elm->lock);
1248 tty->disc_data = NULL;
1250 spin_unlock_bh(&elm->lock);
1252 /* Flush TTY side */
1253 flush_work(&elm->tx_work);
1255 netdev_info(elm->dev, "elmcan off %s.\n", tty->name);
1257 /* Free our memory */
1258 free_candev(elm->dev);
1261 static int elmcan_ldisc_hangup(struct tty_struct *tty)
1263 elmcan_ldisc_close(tty);
1267 /* Perform I/O control on an active elmcan channel. */
1268 static int elmcan_ldisc_ioctl(struct tty_struct *tty, struct file *file,
1269 unsigned int cmd, unsigned long arg)
1271 struct elmcan *elm = get_elm(tty);
1279 tmp = strlen(elm->dev->name) + 1;
1280 if (copy_to_user((void __user *)arg, elm->dev->name, tmp)) {
1294 return tty_mode_ioctl(tty, file, cmd, arg);
1298 static struct tty_ldisc_ops elmcan_ldisc = {
1299 .owner = THIS_MODULE,
1300 .magic = TTY_LDISC_MAGIC,
1302 .receive_buf = elmcan_ldisc_rx,
1303 .write_wakeup = elmcan_ldisc_tx_wakeup,
1304 .open = elmcan_ldisc_open,
1305 .close = elmcan_ldisc_close,
1306 .hangup = elmcan_ldisc_hangup,
1307 .ioctl = elmcan_ldisc_ioctl,
1314 /************************************************************************
1315 * Module init/exit *
1316 ************************************************************************/
1318 static int __init elmcan_init(void)
1322 pr_info("ELM327 based best-effort CAN interface driver\n");
1323 pr_info("This device is severely limited as a CAN interface, see documentation.\n");
1325 /* Fill in our line protocol discipline, and register it */
1326 status = tty_register_ldisc(N_ELMCAN, &elmcan_ldisc);
1328 pr_err("can't register line discipline\n");
1333 static void __exit elmcan_exit(void)
1335 /* This will only be called when all channels have been closed by
1336 * userspace - tty_ldisc.c takes care of the module's refcount.
1340 status = tty_unregister_ldisc(N_ELMCAN);
1342 pr_err("Can't unregister line discipline (error: %d)\n", status);
1346 module_init(elmcan_init);
1347 module_exit(elmcan_exit);