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/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 return (c & 0x3f) == ELM327_READY_CHAR;
380 static void elm327_parse_error(struct elmcan *elm, int len)
382 struct can_frame frame;
384 memset(&frame, 0, sizeof(frame));
385 frame.can_id = CAN_ERR_FLAG;
386 frame.can_dlc = CAN_ERR_DLC;
390 if (!memcmp(elm->rxbuf, "UNABLE TO CONNECT", 17)) {
391 netdev_err(elm->dev, "The ELM327 reported UNABLE TO CONNECT. Please check your setup.\n");
395 if (!memcmp(elm->rxbuf, "BUFFER FULL", 11)) {
396 /* This case will only happen if the last data
398 * Otherwise, elm327_parse_frame() will emit the
399 * error frame instead.
401 frame.can_id |= CAN_ERR_CRTL;
402 frame.data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
406 if (!memcmp(elm->rxbuf, "BUS ERROR", 9)) {
407 frame.can_id |= CAN_ERR_BUSERROR;
409 if (!memcmp(elm->rxbuf, "CAN ERROR", 9)
410 || !memcmp(elm->rxbuf, "<RX ERROR", 9)) {
411 frame.can_id |= CAN_ERR_PROT;
415 if (!memcmp(elm->rxbuf, "BUS BUSY", 8)) {
416 frame.can_id |= CAN_ERR_PROT;
417 frame.data[2] = CAN_ERR_PROT_OVERLOAD;
419 if (!memcmp(elm->rxbuf, "FB ERROR", 8)) {
420 frame.can_id |= CAN_ERR_PROT;
421 frame.data[2] = CAN_ERR_PROT_TX;
425 if (!memcmp(elm->rxbuf, "ERR", 3)) {
426 netdev_err(elm->dev, "The ELM327 reported an ERR%c%c. Please power it off and on again.\n",
427 elm->rxbuf[3], elm->rxbuf[4]);
428 frame.can_id |= CAN_ERR_CRTL;
432 /* Don't emit an error frame if we're unsure */
436 elm327_feed_frame_to_netdev(elm, &frame);
440 static int elm327_parse_frame(struct elmcan *elm, int len)
442 struct can_frame frame;
447 memset(&frame, 0, sizeof(frame));
449 /* Find first non-hex and non-space character:
450 * - In the simplest case, there is none.
451 * - For RTR frames, 'R' is the first non-hex character.
452 * - An error message may replace the end of the data line.
454 for (hexlen = 0; hexlen <= len; hexlen++) {
455 if (hex_to_bin(elm->rxbuf[hexlen]) < 0
456 && elm->rxbuf[hexlen] != ' ') {
461 /* If we accept stray characters coming in:
462 * Check for stray characters on a payload line.
463 * No idea what causes this.
465 if (accept_flaky_uart
467 && !isdigit(elm->rxbuf[hexlen])
468 && !isupper(elm->rxbuf[hexlen])
469 && '<' != elm->rxbuf[hexlen]
470 && ' ' != elm->rxbuf[hexlen]) {
471 /* The line is likely garbled anyway, so bail.
472 * The main code will restart listening.
474 elm327_kick_into_cmd_mode(elm);
478 /* Use spaces in CAN ID to distinguish 29 or 11 bit address length.
479 * No out-of-bounds access:
480 * We use the fact that we can always read from elm->rxbuf.
482 if (elm->rxbuf[2] == ' ' && elm->rxbuf[5] == ' '
483 && elm->rxbuf[8] == ' ' && elm->rxbuf[11] == ' '
484 && elm->rxbuf[13] == ' ') {
485 frame.can_id = CAN_EFF_FLAG;
487 } else if (elm->rxbuf[3] == ' ' && elm->rxbuf[5] == ' ') {
491 /* This is not a well-formatted data line.
492 * Assume it's an error message.
497 if (hexlen < datastart) {
498 /* The line is too short to be a valid frame hex dump.
499 * Something interrupted the hex dump or it is invalid.
504 /* From here on all chars up to buf[hexlen] are hex or spaces,
505 * at well-defined offsets.
508 /* Read CAN data length */
509 frame.can_dlc = (hex_to_bin(elm->rxbuf[datastart - 2]) << 0);
512 if (frame.can_id & CAN_EFF_FLAG) {
513 frame.can_id |= (hex_to_bin(elm->rxbuf[0]) << 28)
514 | (hex_to_bin(elm->rxbuf[1]) << 24)
515 | (hex_to_bin(elm->rxbuf[3]) << 20)
516 | (hex_to_bin(elm->rxbuf[4]) << 16)
517 | (hex_to_bin(elm->rxbuf[6]) << 12)
518 | (hex_to_bin(elm->rxbuf[7]) << 8)
519 | (hex_to_bin(elm->rxbuf[9]) << 4)
520 | (hex_to_bin(elm->rxbuf[10]) << 0);
522 frame.can_id |= (hex_to_bin(elm->rxbuf[0]) << 8)
523 | (hex_to_bin(elm->rxbuf[1]) << 4)
524 | (hex_to_bin(elm->rxbuf[2]) << 0);
527 /* Check for RTR frame */
528 if (elm->rxfill >= hexlen + 3
529 && elm->rxbuf[hexlen + 0] == 'R'
530 && elm->rxbuf[hexlen + 1] == 'T'
531 && elm->rxbuf[hexlen + 2] == 'R') {
532 frame.can_id |= CAN_RTR_FLAG;
535 /* Is the line long enough to hold the advertised payload? */
536 if (!(frame.can_id & CAN_RTR_FLAG) && (hexlen < frame.can_dlc * 3 + datastart)) {
537 /* Incomplete frame. */
539 /* Probably the ELM327's RS232 TX buffer was full.
540 * Emit an error frame and exit.
542 frame.can_id = CAN_ERR_FLAG | CAN_ERR_CRTL;
543 frame.can_dlc = CAN_ERR_DLC;
544 frame.data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
545 elm327_feed_frame_to_netdev(elm, &frame);
547 /* Signal failure to parse.
548 * The line will be re-parsed as an error line, which will fail.
549 * However, this will correctly drop the state machine back into
555 /* Parse the data nibbles. */
556 for (i = 0; i < frame.can_dlc; i++) {
557 frame.data[i] = (hex_to_bin(elm->rxbuf[datastart+3*i]) << 4)
558 | (hex_to_bin(elm->rxbuf[datastart+3*i+1]) << 0);
561 /* Feed the frame to the network layer. */
562 elm327_feed_frame_to_netdev(elm, &frame);
568 static void elm327_parse_line(struct elmcan *elm, int len)
570 /* Skip empty lines */
575 /* Skip echo lines */
576 if (elm->drop_next_line) {
577 elm->drop_next_line = 0;
579 } else if (elm->rxbuf[0] == 'A' && elm->rxbuf[1] == 'T') {
583 /* Regular parsing */
586 if (elm327_parse_frame(elm, len)) {
587 /* Parse an error line. */
588 elm327_parse_error(elm, len);
591 elm327_kick_into_cmd_mode(elm);
600 static void elm327_handle_prompt(struct elmcan *elm)
602 if (elm->cmds_todo) {
603 struct can_frame *frame = &elm->can_frame;
604 char local_txbuf[20];
606 if (test_bit(ELM_TODO_INIT, &elm->cmds_todo)) {
607 elm327_send(elm, *elm->next_init_cmd, strlen(*elm->next_init_cmd));
608 elm->next_init_cmd++;
609 if (!(*elm->next_init_cmd)) {
610 clear_bit(ELM_TODO_INIT, &elm->cmds_todo);
611 netdev_info(elm->dev, "Initialization finished.\n");
614 /* Some chips are unreliable and need extra time after
615 * init commands, as seen with a clone.
616 * So let's do a dummy get-cmd-prompt dance.
618 elm->state = ELM_NOTINIT;
619 elm327_kick_into_cmd_mode(elm);
623 } else if (test_and_clear_bit(ELM_TODO_SILENT_MONITOR, &elm->cmds_todo)) {
624 sprintf(local_txbuf, "ATCSM%i\r",
625 !(!(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY)));
627 } else if (test_and_clear_bit(ELM_TODO_RESPONSES, &elm->cmds_todo)) {
628 sprintf(local_txbuf, "ATR%i\r",
629 !(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY));
631 } else if (test_and_clear_bit(ELM_TODO_CAN_CONFIG, &elm->cmds_todo)) {
632 sprintf(local_txbuf, "ATPC\r");
633 set_bit(ELM_TODO_CAN_CONFIG_PART2, &elm->cmds_todo);
635 } else if (test_and_clear_bit(ELM_TODO_CAN_CONFIG_PART2, &elm->cmds_todo)) {
636 sprintf(local_txbuf, "ATPB%04X\r",
639 } else if (test_and_clear_bit(ELM_TODO_CANID_29BIT_HIGH, &elm->cmds_todo)) {
640 sprintf(local_txbuf, "ATCP%02X\r",
641 (frame->can_id & CAN_EFF_MASK) >> 24);
643 } else if (test_and_clear_bit(ELM_TODO_CANID_29BIT_LOW, &elm->cmds_todo)) {
644 sprintf(local_txbuf, "ATSH%06X\r",
645 frame->can_id & CAN_EFF_MASK & ((1 << 24) - 1));
647 } else if (test_and_clear_bit(ELM_TODO_CANID_11BIT, &elm->cmds_todo)) {
648 sprintf(local_txbuf, "ATSH%03X\r",
649 frame->can_id & CAN_SFF_MASK);
651 } else if (test_and_clear_bit(ELM_TODO_CAN_DATA, &elm->cmds_todo)) {
652 if (frame->can_id & CAN_RTR_FLAG) {
653 /* Send an RTR frame. Their DLC is fixed.
654 * Some chips don't send them at all.
656 sprintf(local_txbuf, "ATRTR\r");
658 /* Send a regular CAN data frame */
661 for (i = 0; i < frame->can_dlc; i++) {
662 sprintf(&local_txbuf[2*i], "%02X",
666 sprintf(&local_txbuf[2*i], "\r");
669 elm->drop_next_line = 1;
670 elm->state = ELM_RECEIVING;
673 elm327_send(elm, local_txbuf, strlen(local_txbuf));
675 /* Enter CAN monitor mode */
676 elm327_send(elm, "ATMA\r", 5);
677 elm->state = ELM_RECEIVING;
682 static void elm327_drop_bytes(struct elmcan *elm, int i)
684 memmove(&elm->rxbuf[0], &elm->rxbuf[i], sizeof(elm->rxbuf) - i);
689 static void elm327_parse_rxbuf(struct elmcan *elm)
693 switch (elm->state) {
698 case ELM_GETMAGICCHAR:
700 /* Wait for 'y' or '>' */
703 for (i = 0; i < elm->rxfill; i++) {
704 if (elm->rxbuf[i] == ELM327_MAGIC_CHAR) {
705 elm327_send(elm, "\r", 1);
706 elm->state = ELM_GETPROMPT;
709 } else if (elm327_is_ready_char(elm->rxbuf[i])) {
710 /* Mask 0xc0 to work around hardware bugs */
711 elm327_send(elm, ELM327_MAGIC_STRING, 1);
717 elm327_drop_bytes(elm, i);
724 * Bits 0xc0 are sometimes set (randomly), hence the mask.
725 * Probably bad hardware.
727 if (elm327_is_ready_char(elm->rxbuf[elm->rxfill - 1])) {
728 elm327_handle_prompt(elm);
735 /* Find <CR> delimiting feedback lines. */
737 (len < elm->rxfill) && (elm->rxbuf[len] != '\r');
742 if (len == sizeof(elm->rxbuf)) {
743 /* Line exceeds buffer. It's probably all garbage.
744 * Did we even connect at the right baud rate?
746 netdev_err(elm->dev, "RX buffer overflow. Faulty ELM327 connected?\n");
747 elm327_hw_failure(elm);
749 } else if (len == elm->rxfill) {
750 if (elm->state == ELM_RECEIVING
751 && elm327_is_ready_char(elm->rxbuf[elm->rxfill - 1])) {
752 /* The ELM327's AT ST response timeout ran out,
753 * so we got a prompt.
754 * Clear RX buffer and restart listening.
758 elm327_handle_prompt(elm);
761 /* We haven't received a full line yet.
762 * Wait for more data.
768 /* We have a full line to parse. */
769 elm327_parse_line(elm, len);
771 /* Remove parsed data from RX buffer. */
772 elm327_drop_bytes(elm, len+1);
774 /* More data to parse? */
776 elm327_parse_rxbuf(elm);
785 /************************************************************************
788 * (takes elm->lock) *
789 ************************************************************************/
791 /* Netdevice DOWN -> UP routine */
792 static int elmcan_netdev_open(struct net_device *dev)
794 struct elmcan *elm = netdev_priv(dev);
797 spin_lock_bh(&elm->lock);
798 if (elm->hw_failure) {
799 netdev_err(elm->dev, "Refusing to open interface after "
800 "a hardware fault has been detected.\n");
801 spin_unlock_bh(&elm->lock);
805 if (elm->tty == NULL) {
806 spin_unlock_bh(&elm->lock);
810 /* open_candev() checks for elm->can.bittiming.bitrate != 0 */
811 err = open_candev(dev);
813 spin_unlock_bh(&elm->lock);
817 /* Initialize the ELM327 */
819 spin_unlock_bh(&elm->lock);
821 can_led_event(dev, CAN_LED_EVENT_OPEN);
822 elm->can.state = CAN_STATE_ERROR_ACTIVE;
823 netif_start_queue(dev);
828 /* Netdevice UP -> DOWN routine */
829 static int elmcan_netdev_close(struct net_device *dev)
831 struct elmcan *elm = netdev_priv(dev);
833 spin_lock_bh(&elm->lock);
835 /* TTY discipline is running. */
837 /* Interrupt whatever we're doing right now */
838 elm327_send(elm, ELM327_MAGIC_STRING, 1);
840 /* Clear the wakeup bit, as the netdev will be down and thus
841 * the wakeup handler won't clear it
843 clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
845 spin_unlock_bh(&elm->lock);
847 flush_work(&elm->tx_work);
849 spin_unlock_bh(&elm->lock);
852 elm->can.state = CAN_STATE_STOPPED;
853 netif_stop_queue(dev);
855 can_led_event(dev, CAN_LED_EVENT_STOP);
860 /* Send a can_frame to a TTY queue. */
861 static netdev_tx_t elmcan_netdev_start_xmit(struct sk_buff *skb, struct net_device *dev)
863 struct elmcan *elm = netdev_priv(dev);
864 struct can_frame *frame = (struct can_frame *) skb->data;
866 if (skb->len != sizeof(struct can_frame))
869 if (!netif_running(dev)) {
870 netdev_warn(elm->dev, "xmit: iface is down.\n");
874 /* BHs are already disabled, so no spin_lock_bh().
875 * See Documentation/networking/netdevices.txt
877 spin_lock(&elm->lock);
879 /* We shouldn't get here after a hardware fault:
880 * can_bus_off() calls netif_carrier_off()
882 BUG_ON(elm->hw_failure);
885 || elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY) {
886 spin_unlock(&elm->lock);
890 netif_stop_queue(dev);
892 elm327_send_frame(elm, frame);
893 spin_unlock(&elm->lock);
895 dev->stats.tx_packets++;
896 dev->stats.tx_bytes += frame->can_dlc;
898 can_led_event(dev, CAN_LED_EVENT_TX);
905 static int elmcan_netdev_change_mtu(struct net_device *dev, int new_mtu)
910 static const struct net_device_ops elmcan_netdev_ops = {
911 .ndo_open = elmcan_netdev_open,
912 .ndo_stop = elmcan_netdev_close,
913 .ndo_start_xmit = elmcan_netdev_start_xmit,
914 .ndo_change_mtu = elmcan_netdev_change_mtu,
921 /************************************************************************
924 * (takes elm->lock) *
925 ************************************************************************/
928 * Get a reference to our struct, taking into account locks/refcounts.
929 * This is to ensure ordering in case we are shutting down, and to ensure
930 * there is a refcount at all (because tty->disc_data may be NULL).
932 static struct elmcan* get_elm(struct tty_struct *tty)
937 /* Lock all elmcan TTYs, so tty->disc_data can't become NULL
938 * the moment before we increase the reference counter.
940 spin_lock_bh(&elmcan_discdata_lock);
941 elm = (struct elmcan *) tty->disc_data;
944 spin_unlock_bh(&elmcan_discdata_lock);
948 got_ref = atomic_inc_not_zero(&elm->refcount);
949 spin_unlock_bh(&elmcan_discdata_lock);
958 static void put_elm(struct elmcan *elm)
960 atomic_dec(&elm->refcount);
966 * Handle the 'receiver data ready' interrupt.
967 * This function is called by the 'tty_io' module in the kernel when
968 * a block of ELM327 CAN data has been received, which can now be parsed
969 * and sent on to some IP layer for further processing. This will not
970 * be re-entered while running but other ldisc functions may be called
973 static void elmcan_ldisc_rx(struct tty_struct *tty,
974 const unsigned char *cp, char *fp, int count)
976 struct elmcan *elm = get_elm(tty);
981 spin_lock_bh(&elm->lock);
982 if (elm->hw_failure) {
983 spin_unlock_bh(&elm->lock);
989 /* Read the characters out of the buffer */
990 while (count-- && elm->rxfill < sizeof(elm->rxbuf)) {
992 netdev_err(elm->dev, "Error in received character stream. Check your wiring.");
994 spin_lock_bh(&elm->lock);
995 elm327_hw_failure(elm);
996 spin_unlock_bh(&elm->lock);
1002 /* Ignore NUL characters, which the PIC microcontroller may
1003 * inadvertently insert due to a known hardware bug.
1004 * See ELM327 documentation, which refers to a Microchip PIC
1008 /* Check for stray characters on the UART line.
1009 * No idea what causes this.
1011 if (!accept_flaky_uart
1014 && ELM327_MAGIC_CHAR != *cp
1015 && ELM327_READY_CHAR != *cp
1024 /* We've received an invalid character, so bail.
1025 * There's something wrong with the ELM327, or
1026 * with the UART line.
1028 netdev_err(elm->dev,
1029 "Received illegal character %02x.\n",
1031 elm327_hw_failure(elm);
1032 spin_unlock_bh(&elm->lock);
1038 elm->rxbuf[elm->rxfill++] = *cp;
1045 netdev_err(elm->dev, "Receive buffer overflowed. Bad chip or wiring?");
1047 elm327_hw_failure(elm);
1048 spin_unlock_bh(&elm->lock);
1054 elm327_parse_rxbuf(elm);
1055 spin_unlock_bh(&elm->lock);
1061 * Write out remaining transmit buffer.
1062 * Scheduled when TTY is writable.
1064 static void elmcan_ldisc_tx_worker(struct work_struct *work)
1066 /* No need to use get_elm() here, as we'll always flush workers
1067 * befory destroying the elmcan object.
1069 struct elmcan *elm = container_of(work, struct elmcan, tx_work);
1072 spin_lock_bh(&elm->lock);
1073 if (elm->hw_failure) {
1074 spin_unlock_bh(&elm->lock);
1078 if (!elm->tty || !netif_running(elm->dev)) {
1079 spin_unlock_bh(&elm->lock);
1083 if (elm->txleft <= 0) {
1084 /* Our TTY write buffer is empty:
1085 * We can start transmission of another packet
1087 clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
1088 spin_unlock_bh(&elm->lock);
1089 netif_wake_queue(elm->dev);
1093 actual = elm->tty->ops->write(elm->tty, elm->txhead, elm->txleft);
1095 netdev_err(elm->dev, "Failed to write to tty %s.\n", elm->tty->name);
1096 elm327_hw_failure(elm);
1097 spin_unlock_bh(&elm->lock);
1101 elm->txleft -= actual;
1102 elm->txhead += actual;
1103 spin_unlock_bh(&elm->lock);
1108 * Called by the driver when there's room for more data.
1109 * Schedule the transmit.
1111 static void elmcan_ldisc_tx_wakeup(struct tty_struct *tty)
1113 struct elmcan *elm = get_elm(tty);
1118 schedule_work(&elm->tx_work);
1125 /* ELM327 can only handle bitrates that are integer divisors of 500 kHz,
1126 * or 7/8 of that. Divisors are 1 to 64.
1127 * Currently we don't implement support for 7/8 rates.
1129 static const u32 elmcan_bitrate_const[64] = {
1130 7812, 7936, 8064, 8196, 8333, 8474, 8620, 8771,
1131 8928, 9090, 9259, 9433, 9615, 9803, 10000, 10204,
1132 10416, 10638, 10869, 11111, 11363, 11627, 11904, 12195,
1133 12500, 12820, 13157, 13513, 13888, 14285, 14705, 15151,
1134 15625, 16129, 16666, 17241, 17857, 18518, 19230, 20000,
1135 20833, 21739, 22727, 23809, 25000, 26315, 27777, 29411,
1136 31250, 33333, 35714, 38461, 41666, 45454, 50000, 55555,
1137 62500, 71428, 83333, 100000, 125000, 166666, 250000, 500000
1140 /* Dummy function to claim we're changing the bitrate.
1141 * We actually do this when opening the net device.
1143 static int elmcan_do_set_bittiming(struct net_device *netdev)
1150 * Open the high-level part of the elmcan channel.
1151 * This function is called by the TTY module when the
1152 * elmcan line discipline is called for.
1154 * Called in process context serialized from other ldisc calls.
1156 static int elmcan_ldisc_open(struct tty_struct *tty)
1158 struct net_device *dev;
1162 if (!capable(CAP_NET_ADMIN))
1165 if (!tty->ops->write)
1169 /* OK. Find a free elmcan channel to use. */
1170 dev = alloc_candev(sizeof(struct elmcan), 0);
1173 elm = netdev_priv(dev);
1175 /* Configure TTY interface */
1176 tty->receive_room = 65536; /* We don't flow control */
1177 elm->txleft = 0; /* Clear TTY TX buffer */
1178 spin_lock_init(&elm->lock);
1179 atomic_set(&elm->refcount, 1);
1180 INIT_WORK(&elm->tx_work, elmcan_ldisc_tx_worker);
1182 /* Configure CAN metadata */
1183 elm->can.state = CAN_STATE_STOPPED;
1184 elm->can.bitrate_const = elmcan_bitrate_const;
1185 elm->can.bitrate_const_cnt = ARRAY_SIZE(elmcan_bitrate_const);
1186 elm->can.do_set_bittiming = elmcan_do_set_bittiming;
1187 elm->can.ctrlmode_supported = CAN_CTRLMODE_LISTENONLY;
1189 /* Configure netlink interface */
1191 dev->netdev_ops = &elmcan_netdev_ops;
1193 /* Mark ldisc channel as alive */
1195 tty->disc_data = elm;
1197 devm_can_led_init(elm->dev);
1200 err = register_candev(elm->dev);
1202 free_candev(elm->dev);
1206 netdev_info(elm->dev, "elmcan on %s.\n", tty->name);
1212 * Close down an elmcan channel.
1213 * This means flushing out any pending queues, and then returning.
1214 * This call is serialized against other ldisc functions:
1215 * Once this is called, no other ldisc function of ours is entered.
1217 * We also use this function for a hangup event.
1219 static void elmcan_ldisc_close(struct tty_struct *tty)
1221 /* Use get_elm() to synchronize against other users */
1222 struct elmcan *elm = get_elm(tty);
1227 /* Tear down network side.
1228 * unregister_netdev() calls .ndo_stop() so we don't have to.
1230 unregister_candev(elm->dev);
1232 /* Decrease the refcount twice, once for our own get_elm(),
1233 * and once to remove the count of 1 that we set in _open().
1234 * Once it reaches 0, we can safely destroy it.
1239 /* Spin until refcount reaches 0 */
1240 while(atomic_read(&elm->refcount) > 0)
1243 /* At this point, all ldisc calls to us will be no-ops.
1244 * Since the refcount is 0, they are bailing immediately.
1247 /* Mark channel as dead */
1248 spin_lock_bh(&elm->lock);
1249 tty->disc_data = NULL;
1251 spin_unlock_bh(&elm->lock);
1253 /* Flush TTY side */
1254 flush_work(&elm->tx_work);
1256 netdev_info(elm->dev, "elmcan off %s.\n", tty->name);
1258 /* Free our memory */
1259 free_candev(elm->dev);
1262 static int elmcan_ldisc_hangup(struct tty_struct *tty)
1264 elmcan_ldisc_close(tty);
1268 /* Perform I/O control on an active elmcan channel. */
1269 static int elmcan_ldisc_ioctl(struct tty_struct *tty, struct file *file,
1270 unsigned int cmd, unsigned long arg)
1272 struct elmcan *elm = get_elm(tty);
1280 tmp = strlen(elm->dev->name) + 1;
1281 if (copy_to_user((void __user *)arg, elm->dev->name, tmp)) {
1295 return tty_mode_ioctl(tty, file, cmd, arg);
1299 static struct tty_ldisc_ops elmcan_ldisc = {
1300 .owner = THIS_MODULE,
1301 .magic = TTY_LDISC_MAGIC,
1303 .receive_buf = elmcan_ldisc_rx,
1304 .write_wakeup = elmcan_ldisc_tx_wakeup,
1305 .open = elmcan_ldisc_open,
1306 .close = elmcan_ldisc_close,
1307 .hangup = elmcan_ldisc_hangup,
1308 .ioctl = elmcan_ldisc_ioctl,
1315 /************************************************************************
1316 * Module init/exit *
1317 ************************************************************************/
1319 static int __init elmcan_init(void)
1323 pr_info("ELM327 based best-effort CAN interface driver\n");
1324 pr_info("This device is severely limited as a CAN interface, see documentation.\n");
1326 /* Fill in our line protocol discipline, and register it */
1327 status = tty_register_ldisc(N_ELMCAN, &elmcan_ldisc);
1329 pr_err("can't register line discipline\n");
1334 static void __exit elmcan_exit(void)
1336 /* This will only be called when all channels have been closed by
1337 * userspace - tty_ldisc.c takes care of the module's refcount.
1341 status = tty_unregister_ldisc(N_ELMCAN);
1343 pr_err("Can't unregister line discipline (error: %d)\n", status);
1347 module_init(elmcan_init);
1348 module_exit(elmcan_exit);