1 // SPDX-License-Identifier: GPL-2.0
3 * elmcan.c - ELM327 based CAN interface driver
4 * (tty line discipline)
6 * This file is derived from linux/drivers/net/can/slcan.c
8 * elmcan.c Author : Max Staudt <max-linux@enpas.org>
9 * slcan.c Author : Oliver Hartkopp <socketcan@hartkopp.net>
10 * slip.c Authors : Laurence Culhane <loz@holmes.demon.co.uk>
11 * Fred N. van Kempen <waltje@uwalt.nl.mugnet.org>
15 #define pr_fmt(fmt) "[elmcan] " fmt
18 #include <linux/init.h>
19 #include <linux/module.h>
20 #include <linux/moduleparam.h>
22 #include <linux/atomic.h>
23 #include <linux/bitops.h>
24 #include <linux/ctype.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 /* If this is enabled, we'll try to make the best of the situation
49 * even if we receive unexpected characters on the line.
51 * Handle with care, it's likely your hardware is unreliable!
53 static bool accept_flaky_uart;
54 module_param_named(accept_flaky_uart, accept_flaky_uart, bool, 0444);
55 MODULE_PARM_DESC(accept_flaky_uart, "Don't bail at the first invalid character. Behavior undefined.");
58 /* Line discipline ID number */
63 #define ELM327_CAN_CONFIG_SEND_SFF 0x8000
64 #define ELM327_CAN_CONFIG_VARIABLE_DLC 0x4000
65 #define ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF 0x2000
66 #define ELM327_CAN_CONFIG_BAUDRATE_MULT_8_7 0x1000
68 #define ELM327_MAGIC_CHAR 'y'
69 #define ELM327_MAGIC_STRING "y"
70 #define ELM327_READY_CHAR '>'
73 /* Bits in elm->cmds_todo */
75 ELM_TODO_CAN_DATA = 0,
77 ELM_TODO_CANID_29BIT_LOW,
78 ELM_TODO_CANID_29BIT_HIGH,
79 ELM_TODO_CAN_CONFIG_PART2,
82 ELM_TODO_SILENT_MONITOR,
88 /* This must be the first member when using alloc_candev() */
91 /* TTY and netdev devices that we're bridging */
92 struct tty_struct *tty;
93 struct net_device *dev;
95 /* Per-channel lock */
98 /* Keep track of how many things are using this struct.
99 * Once it reaches 0, we are in the process of cleaning up,
100 * and new operations will be cancelled immediately.
101 * Use atomic_t rather than refcount_t because we deliberately
102 * decrement to 0, and refcount_dec() spills a WARN_ONCE in
107 /* Stop the channel on hardware failure.
108 * Once this is true, nothing will be sent to the TTY.
113 struct work_struct tx_work; /* Flushes TTY TX buffer */
114 unsigned char txbuf[32];
115 unsigned char *txhead; /* Pointer to next TX byte */
116 int txleft; /* Bytes left to TX */
119 unsigned char rxbuf[256];
132 /* The CAN frame and config the ELM327 is sending/using,
133 * 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)
172 memcpy(elm->txbuf, buf, len);
174 /* Order of next two lines is *very* important.
175 * When we are sending a little amount of data,
176 * the transfer may be completed inside the ops->write()
177 * routine, because it's running with interrupts enabled.
178 * In this case we *never* got WRITE_WAKEUP event,
179 * if we did not request it before write operation.
180 * 14 Oct 1994 Dmitry Gorodchanin.
182 set_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
183 actual = elm->tty->ops->write(elm->tty, elm->txbuf, len);
186 "Failed to write to tty %s.\n",
188 elm327_hw_failure(elm);
192 elm->txleft = len - actual;
193 elm->txhead = elm->txbuf + actual;
197 /* Take the ELM327 out of almost any state and back into command mode.
198 * We send ELM327_MAGIC_CHAR which will either abort any running
199 * operation, or be echoed back to us in case we're already in command
202 static void elm327_kick_into_cmd_mode(struct elmcan *elm)
204 if (elm->state != ELM_GETMAGICCHAR && elm->state != ELM_GETPROMPT) {
205 elm327_send(elm, ELM327_MAGIC_STRING, 1);
207 elm->state = ELM_GETMAGICCHAR;
212 /* Schedule a CAN frame and necessary config changes to be sent to the TTY. */
213 static void elm327_send_frame(struct elmcan *elm, struct can_frame *frame)
215 /* Schedule any necessary changes in ELM327's CAN configuration */
216 if (elm->can_frame.can_id != frame->can_id) {
217 /* Set the new CAN ID for transmission. */
218 if ((frame->can_id & CAN_EFF_FLAG)
219 ^ (elm->can_frame.can_id & CAN_EFF_FLAG)) {
220 elm->can_config = (frame->can_id & CAN_EFF_FLAG
222 : ELM327_CAN_CONFIG_SEND_SFF)
223 | ELM327_CAN_CONFIG_VARIABLE_DLC
224 | ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF
225 | elm->can_bitrate_divisor;
227 set_bit(ELM_TODO_CAN_CONFIG, &elm->cmds_todo);
230 if (frame->can_id & CAN_EFF_FLAG) {
231 clear_bit(ELM_TODO_CANID_11BIT, &elm->cmds_todo);
232 set_bit(ELM_TODO_CANID_29BIT_LOW, &elm->cmds_todo);
233 set_bit(ELM_TODO_CANID_29BIT_HIGH, &elm->cmds_todo);
235 set_bit(ELM_TODO_CANID_11BIT, &elm->cmds_todo);
236 clear_bit(ELM_TODO_CANID_29BIT_LOW, &elm->cmds_todo);
237 clear_bit(ELM_TODO_CANID_29BIT_HIGH, &elm->cmds_todo);
241 /* Schedule the CAN frame itself. */
242 elm->can_frame = *frame;
243 set_bit(ELM_TODO_CAN_DATA, &elm->cmds_todo);
245 elm327_kick_into_cmd_mode(elm);
250 /***********************************************************************
251 * ELM327: Initialization sequence *
253 * (assumes elm->lock taken) *
254 ***********************************************************************/
256 static char *elm327_init_script[] = {
257 "AT WS\r", /* v1.0: Warm Start */
258 "AT PP FF OFF\r", /* v1.0: All Programmable Parameters Off */
259 "AT M0\r", /* v1.0: Memory Off */
260 "AT AL\r", /* v1.0: Allow Long messages */
261 "AT BI\r", /* v1.0: Bypass Initialization */
262 "AT CAF0\r", /* v1.0: CAN Auto Formatting Off */
263 "AT CFC0\r", /* v1.0: CAN Flow Control Off */
264 "AT CF 000\r", /* v1.0: Reset CAN ID Filter */
265 "AT CM 000\r", /* v1.0: Reset CAN ID Mask */
266 "AT E1\r", /* v1.0: Echo On */
267 "AT H1\r", /* v1.0: Headers On */
268 "AT L0\r", /* v1.0: Linefeeds Off */
269 "AT SH 7DF\r", /* v1.0: Set CAN sending ID to 0x7df */
270 "AT ST FF\r", /* v1.0: Set maximum Timeout for response after TX */
271 "AT AT0\r", /* v1.2: Adaptive Timing Off */
272 "AT D1\r", /* v1.3: Print DLC On */
273 "AT S1\r", /* v1.3: Spaces On */
274 "AT TP B\r", /* v1.0: Try Protocol B */
279 static void elm327_init(struct elmcan *elm)
281 elm->state = ELM_NOTINIT;
282 elm->can_frame.can_id = 0x7df;
284 elm->drop_next_line = 0;
286 /* We can only set the bitrate as a fraction of 500000.
287 * The bit timing constants in elmcan_bittiming_const will
288 * limit the user to the right values.
290 elm->can_bitrate_divisor = 500000 / elm->can.bittiming.bitrate;
291 elm->can_config = ELM327_CAN_CONFIG_SEND_SFF
292 | ELM327_CAN_CONFIG_VARIABLE_DLC
293 | ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF
294 | elm->can_bitrate_divisor;
296 /* Configure ELM327 and then start monitoring */
297 elm->next_init_cmd = &elm327_init_script[0];
298 set_bit(ELM_TODO_INIT, &elm->cmds_todo);
299 set_bit(ELM_TODO_SILENT_MONITOR, &elm->cmds_todo);
300 set_bit(ELM_TODO_RESPONSES, &elm->cmds_todo);
301 set_bit(ELM_TODO_CAN_CONFIG, &elm->cmds_todo);
303 elm327_kick_into_cmd_mode(elm);
308 /***********************************************************************
309 * ELM327: Reception -> netdev glue *
311 * (assumes elm->lock taken) *
312 ***********************************************************************/
314 static void elm327_feed_frame_to_netdev(struct elmcan *elm,
315 const struct can_frame *frame)
317 struct can_frame *cf;
320 if (!netif_running(elm->dev))
323 skb = alloc_can_skb(elm->dev, &cf);
328 memcpy(cf, frame, sizeof(struct can_frame));
330 elm->dev->stats.rx_packets++;
331 elm->dev->stats.rx_bytes += frame->can_dlc;
334 can_led_event(elm->dev, CAN_LED_EVENT_RX);
339 /***********************************************************************
340 * ELM327: "Panic" handler *
342 * (assumes elm->lock taken) *
343 ***********************************************************************/
345 /* Called when we're out of ideas and just want it all to end. */
346 static inline void elm327_hw_failure(struct elmcan *elm)
348 struct can_frame frame;
350 memset(&frame, 0, sizeof(frame));
351 frame.can_id = CAN_ERR_FLAG;
352 frame.can_dlc = CAN_ERR_DLC;
356 elm327_feed_frame_to_netdev(elm, &frame);
358 netdev_err(elm->dev, "ELM327 misbehaved. Blocking further communication.\n");
360 elm->hw_failure = true;
361 can_bus_off(elm->dev);
366 /************************************************************************
367 * ELM327: Reception parser *
369 * (assumes elm->lock taken) *
370 ************************************************************************/
372 static void elm327_parse_error(struct elmcan *elm, int len)
374 struct can_frame frame;
376 memset(&frame, 0, sizeof(frame));
377 frame.can_id = CAN_ERR_FLAG;
378 frame.can_dlc = CAN_ERR_DLC;
382 if (!memcmp(elm->rxbuf, "UNABLE TO CONNECT", 17)) {
384 "The ELM327 reported UNABLE TO CONNECT. Please check your setup.\n");
388 if (!memcmp(elm->rxbuf, "BUFFER FULL", 11)) {
389 /* This case will only happen if the last data
391 * Otherwise, elm327_parse_frame() will heuristically
392 * emit this error frame instead.
394 frame.can_id |= CAN_ERR_CRTL;
395 frame.data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
399 if (!memcmp(elm->rxbuf, "BUS ERROR", 9))
400 frame.can_id |= CAN_ERR_BUSERROR;
401 if (!memcmp(elm->rxbuf, "CAN ERROR", 9))
402 frame.can_id |= CAN_ERR_PROT;
403 if (!memcmp(elm->rxbuf, "<RX ERROR", 9))
404 frame.can_id |= CAN_ERR_PROT;
407 if (!memcmp(elm->rxbuf, "BUS BUSY", 8)) {
408 frame.can_id |= CAN_ERR_PROT;
409 frame.data[2] = CAN_ERR_PROT_OVERLOAD;
411 if (!memcmp(elm->rxbuf, "FB ERROR", 8)) {
412 frame.can_id |= CAN_ERR_PROT;
413 frame.data[2] = CAN_ERR_PROT_TX;
417 if (!memcmp(elm->rxbuf, "ERR", 3)) {
418 netdev_err(elm->dev, "The ELM327 reported an ERR%c%c. Please power it off and on again.\n",
419 elm->rxbuf[3], elm->rxbuf[4]);
420 frame.can_id |= CAN_ERR_CRTL;
424 /* Don't emit an error frame if we're unsure */
428 elm327_feed_frame_to_netdev(elm, &frame);
432 /* Parse CAN frames coming as ASCII from ELM327.
433 * They can be of various formats:
435 * 29-bit ID (EFF): 12 34 56 78 D PL PL PL PL PL PL PL PL
436 * 11-bit ID (!EFF): 123 D PL PL PL PL PL PL PL PL
438 * where D = DLC, PL = payload byte
440 * Instead of a payload, RTR indicates a remote request.
442 * We will use the spaces and line length to guess the format.
444 static int elm327_parse_frame(struct elmcan *elm, int len)
446 struct can_frame frame;
451 memset(&frame, 0, sizeof(frame));
453 /* Find first non-hex and non-space character:
454 * - In the simplest case, there is none.
455 * - For RTR frames, 'R' is the first non-hex character.
456 * - An error message may replace the end of the data line.
458 for (hexlen = 0; hexlen <= len; hexlen++) {
459 if (hex_to_bin(elm->rxbuf[hexlen]) < 0
460 && elm->rxbuf[hexlen] != ' ') {
465 /* If we accept stray characters coming in:
466 * Check for stray characters on a payload line.
467 * No idea what causes this.
469 if (accept_flaky_uart
471 && !isdigit(elm->rxbuf[hexlen])
472 && !isupper(elm->rxbuf[hexlen])
473 && '<' != elm->rxbuf[hexlen]
474 && ' ' != elm->rxbuf[hexlen]) {
475 /* The line is likely garbled anyway, so bail.
476 * The main code will restart listening.
478 elm327_kick_into_cmd_mode(elm);
482 /* Use spaces in CAN ID to distinguish 29 or 11 bit address length.
483 * No out-of-bounds access:
484 * We use the fact that we can always read from elm->rxbuf.
486 if (elm->rxbuf[2] == ' ' && elm->rxbuf[5] == ' '
487 && elm->rxbuf[8] == ' ' && elm->rxbuf[11] == ' '
488 && elm->rxbuf[13] == ' ') {
489 frame.can_id = CAN_EFF_FLAG;
491 } else if (elm->rxbuf[3] == ' ' && elm->rxbuf[5] == ' ') {
495 /* This is not a well-formatted data line.
496 * Assume it's an error message.
501 if (hexlen < datastart) {
502 /* The line is too short to be a valid frame hex dump.
503 * Something interrupted the hex dump or it is invalid.
508 /* From here on all chars up to buf[hexlen] are hex or spaces,
509 * at well-defined offsets.
512 /* Read CAN data length */
513 frame.can_dlc = (hex_to_bin(elm->rxbuf[datastart - 2]) << 0);
516 if (frame.can_id & CAN_EFF_FLAG) {
517 frame.can_id |= (hex_to_bin(elm->rxbuf[0]) << 28)
518 | (hex_to_bin(elm->rxbuf[1]) << 24)
519 | (hex_to_bin(elm->rxbuf[3]) << 20)
520 | (hex_to_bin(elm->rxbuf[4]) << 16)
521 | (hex_to_bin(elm->rxbuf[6]) << 12)
522 | (hex_to_bin(elm->rxbuf[7]) << 8)
523 | (hex_to_bin(elm->rxbuf[9]) << 4)
524 | (hex_to_bin(elm->rxbuf[10]) << 0);
526 frame.can_id |= (hex_to_bin(elm->rxbuf[0]) << 8)
527 | (hex_to_bin(elm->rxbuf[1]) << 4)
528 | (hex_to_bin(elm->rxbuf[2]) << 0);
531 /* Check for RTR frame */
532 if (elm->rxfill >= hexlen + 3
533 && !memcmp(&elm->rxbuf[hexlen], "RTR", 3)) {
534 frame.can_id |= CAN_RTR_FLAG;
537 /* Is the line long enough to hold the advertised payload?
538 * Note: RTR frames have a DLC, but no actual payload.
540 if (!(frame.can_id & CAN_RTR_FLAG)
541 && (hexlen < frame.can_dlc * 3 + datastart)) {
542 /* Incomplete frame. */
544 /* Probably the ELM327's RS232 TX buffer was full.
545 * Emit an error frame and exit.
547 frame.can_id = CAN_ERR_FLAG | CAN_ERR_CRTL;
548 frame.can_dlc = CAN_ERR_DLC;
549 frame.data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
550 elm327_feed_frame_to_netdev(elm, &frame);
552 /* Signal failure to parse.
553 * The line will be re-parsed as an error line, which will fail.
554 * However, this will correctly drop the state machine back into
560 /* Parse the data nibbles. */
561 for (i = 0; i < frame.can_dlc; i++) {
562 frame.data[i] = (hex_to_bin(elm->rxbuf[datastart+3*i]) << 4)
563 | (hex_to_bin(elm->rxbuf[datastart+3*i+1]) << 0);
566 /* Feed the frame to the network layer. */
567 elm327_feed_frame_to_netdev(elm, &frame);
573 static void elm327_parse_line(struct elmcan *elm, int len)
575 /* Skip empty lines */
579 /* Skip echo lines */
580 if (elm->drop_next_line) {
581 elm->drop_next_line = 0;
583 } else if (elm->rxbuf[0] == 'A' && elm->rxbuf[1] == 'T') {
587 /* Regular parsing */
588 switch (elm->state) {
590 if (elm327_parse_frame(elm, len)) {
591 /* Parse an error line. */
592 elm327_parse_error(elm, len);
595 elm327_kick_into_cmd_mode(elm);
603 static void elm327_handle_prompt(struct elmcan *elm)
605 struct can_frame *frame = &elm->can_frame;
606 char local_txbuf[20];
608 if (!elm->cmds_todo) {
609 /* Enter CAN monitor mode */
610 elm327_send(elm, "ATMA\r", 5);
611 elm->state = ELM_RECEIVING;
616 /* Reconfigure ELM327 step by step as indicated by elm->cmds_todo */
617 if (test_bit(ELM_TODO_INIT, &elm->cmds_todo)) {
618 strcpy(local_txbuf, *elm->next_init_cmd);
620 elm->next_init_cmd++;
621 if (!(*elm->next_init_cmd)) {
622 clear_bit(ELM_TODO_INIT, &elm->cmds_todo);
623 netdev_info(elm->dev, "Initialization finished.\n");
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));
680 static bool elm327_is_ready_char(char c)
682 /* Bits 0xc0 are sometimes set (randomly), hence the mask.
683 * Probably bad hardware.
685 return (c & 0x3f) == ELM327_READY_CHAR;
688 static void elm327_drop_bytes(struct elmcan *elm, int i)
690 memmove(&elm->rxbuf[0], &elm->rxbuf[i], sizeof(elm->rxbuf) - i);
694 static void elm327_parse_rxbuf(struct elmcan *elm)
698 switch (elm->state) {
703 case ELM_GETMAGICCHAR:
705 /* Wait for 'y' or '>' */
708 for (i = 0; i < elm->rxfill; i++) {
709 if (elm->rxbuf[i] == ELM327_MAGIC_CHAR) {
710 elm327_send(elm, "\r", 1);
711 elm->state = ELM_GETPROMPT;
714 } else if (elm327_is_ready_char(elm->rxbuf[i])) {
715 elm327_send(elm, ELM327_MAGIC_STRING, 1);
721 elm327_drop_bytes(elm, i);
728 if (elm327_is_ready_char(elm->rxbuf[elm->rxfill - 1]))
729 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?
747 "RX buffer overflow. Faulty ELM327 or UART?\n");
748 elm327_hw_failure(elm);
750 } else if (len == elm->rxfill) {
751 if (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);
762 /* No <CR> found - we haven't received a full line yet.
763 * 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);
784 /***********************************************************************
787 * (takes elm->lock) *
788 ***********************************************************************/
790 static int elmcan_netdev_open(struct net_device *dev)
792 struct elmcan *elm = netdev_priv(dev);
795 spin_lock_bh(&elm->lock);
796 if (elm->hw_failure) {
797 netdev_err(elm->dev, "Refusing to open interface after a hardware fault has been detected.\n");
798 spin_unlock_bh(&elm->lock);
802 if (elm->tty == NULL) {
803 spin_unlock_bh(&elm->lock);
807 /* open_candev() checks for elm->can.bittiming.bitrate != 0 */
808 err = open_candev(dev);
810 spin_unlock_bh(&elm->lock);
815 spin_unlock_bh(&elm->lock);
817 can_led_event(dev, CAN_LED_EVENT_OPEN);
818 elm->can.state = CAN_STATE_ERROR_ACTIVE;
819 netif_start_queue(dev);
824 static int elmcan_netdev_close(struct net_device *dev)
826 struct elmcan *elm = netdev_priv(dev);
828 spin_lock_bh(&elm->lock);
830 /* Interrupt whatever we're doing right now */
831 elm327_send(elm, ELM327_MAGIC_STRING, 1);
833 /* Clear the wakeup bit, as the netdev will be down and thus
834 * the wakeup handler won't clear it
836 clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
838 spin_unlock_bh(&elm->lock);
840 flush_work(&elm->tx_work);
842 spin_unlock_bh(&elm->lock);
845 elm->can.state = CAN_STATE_STOPPED;
846 netif_stop_queue(dev);
848 can_led_event(dev, CAN_LED_EVENT_STOP);
853 /* Send a can_frame to a TTY. */
854 static netdev_tx_t elmcan_netdev_start_xmit(struct sk_buff *skb,
855 struct net_device *dev)
857 struct elmcan *elm = netdev_priv(dev);
858 struct can_frame *frame = (struct can_frame *) skb->data;
860 if (skb->len != sizeof(struct can_frame))
863 if (!netif_running(dev)) {
864 netdev_warn(elm->dev, "xmit: iface is down.\n");
868 /* BHs are already disabled, so no spin_lock_bh().
869 * See Documentation/networking/netdevices.txt
871 spin_lock(&elm->lock);
873 /* We shouldn't get here after a hardware fault:
874 * can_bus_off() calls netif_carrier_off()
876 WARN_ON(elm->hw_failure);
880 || elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY) {
881 spin_unlock(&elm->lock);
885 netif_stop_queue(dev);
887 elm327_send_frame(elm, frame);
888 spin_unlock(&elm->lock);
890 dev->stats.tx_packets++;
891 dev->stats.tx_bytes += frame->can_dlc;
893 can_led_event(dev, CAN_LED_EVENT_TX);
901 static const struct net_device_ops elmcan_netdev_ops = {
902 .ndo_open = elmcan_netdev_open,
903 .ndo_stop = elmcan_netdev_close,
904 .ndo_start_xmit = elmcan_netdev_start_xmit,
905 .ndo_change_mtu = can_change_mtu,
912 /***********************************************************************
915 * (takes elm->lock) *
916 ***********************************************************************/
918 /* Get a reference to our struct, taking into account locks/refcounts.
919 * This is to ensure ordering in case we are shutting down, and to ensure
920 * there is a refcount at all (otherwise tty->disc_data may be freed and
921 * before we increment the refcount).
922 * Use this for anything that can race against elmcan_ldisc_close().
924 static struct elmcan *get_elm(struct tty_struct *tty)
929 spin_lock_bh(&elmcan_discdata_lock);
930 elm = (struct elmcan *) tty->disc_data;
933 spin_unlock_bh(&elmcan_discdata_lock);
937 got_ref = atomic_inc_not_zero(&elm->refcount);
938 spin_unlock_bh(&elmcan_discdata_lock);
946 static void put_elm(struct elmcan *elm)
948 atomic_dec(&elm->refcount);
952 static bool elmcan_is_valid_rx_char(char c)
954 return (accept_flaky_uart
957 || ELM327_MAGIC_CHAR == c
958 || ELM327_READY_CHAR == c
969 /* Handle incoming ELM327 ASCII data.
970 * This will not be re-entered while running, but other ldisc
971 * functions may be called in parallel.
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);
983 if (elm->hw_failure) {
987 while (count-- && elm->rxfill < sizeof(elm->rxbuf)) {
989 netdev_err(elm->dev, "Error in received character stream. Check your wiring.");
991 elm327_hw_failure(elm);
996 /* Ignore NUL characters, which the PIC microcontroller may
997 * inadvertently insert due to a known hardware bug.
998 * See ELM327 documentation, which refers to a Microchip PIC
1002 /* Check for stray characters on the UART line.
1003 * Likely caused by bad hardware.
1005 if (!elmcan_is_valid_rx_char(*cp)) {
1006 netdev_err(elm->dev,
1007 "Received illegal character %02x.\n",
1009 elm327_hw_failure(elm);
1014 elm->rxbuf[elm->rxfill++] = *cp;
1021 netdev_err(elm->dev, "Receive buffer overflowed. Bad chip or wiring?");
1023 elm327_hw_failure(elm);
1028 elm327_parse_rxbuf(elm);
1031 spin_unlock_bh(&elm->lock);
1036 /* Write out remaining transmit buffer.
1037 * Scheduled when TTY is writable.
1039 static void elmcan_ldisc_tx_worker(struct work_struct *work)
1041 /* No need to use get_elm() here, as we'll always flush workers
1042 * before destroying the elmcan object.
1044 struct elmcan *elm = container_of(work, struct elmcan, tx_work);
1047 spin_lock_bh(&elm->lock);
1048 if (elm->hw_failure) {
1049 spin_unlock_bh(&elm->lock);
1053 if (!elm->tty || !netif_running(elm->dev)) {
1054 spin_unlock_bh(&elm->lock);
1058 if (elm->txleft <= 0) {
1059 /* Our TTY write buffer is empty:
1060 * Allow netdev to hand us another packet
1062 clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
1063 spin_unlock_bh(&elm->lock);
1064 netif_wake_queue(elm->dev);
1068 actual = elm->tty->ops->write(elm->tty, elm->txhead, elm->txleft);
1070 netdev_err(elm->dev,
1071 "Failed to write to tty %s.\n",
1073 elm327_hw_failure(elm);
1074 spin_unlock_bh(&elm->lock);
1078 elm->txleft -= actual;
1079 elm->txhead += actual;
1080 spin_unlock_bh(&elm->lock);
1083 /* Called by the driver when there's room for more data. */
1084 static void elmcan_ldisc_tx_wakeup(struct tty_struct *tty)
1086 struct elmcan *elm = get_elm(tty);
1091 schedule_work(&elm->tx_work);
1097 /* ELM327 can only handle bitrates that are integer divisors of 500 kHz,
1098 * or 7/8 of that. Divisors are 1 to 64.
1099 * Currently we don't implement support for 7/8 rates.
1101 static const u32 elmcan_bitrate_const[64] = {
1102 7812, 7936, 8064, 8196, 8333, 8474, 8620, 8771,
1103 8928, 9090, 9259, 9433, 9615, 9803, 10000, 10204,
1104 10416, 10638, 10869, 11111, 11363, 11627, 11904, 12195,
1105 12500, 12820, 13157, 13513, 13888, 14285, 14705, 15151,
1106 15625, 16129, 16666, 17241, 17857, 18518, 19230, 20000,
1107 20833, 21739, 22727, 23809, 25000, 26315, 27777, 29411,
1108 31250, 33333, 35714, 38461, 41666, 45454, 50000, 55555,
1109 62500, 71428, 83333, 100000, 125000, 166666, 250000, 500000
1113 /* Dummy needed to use bitrate_const */
1114 static int elmcan_do_set_bittiming(struct net_device *netdev)
1122 static int elmcan_ldisc_open(struct tty_struct *tty)
1124 struct net_device *dev;
1128 if (!capable(CAP_NET_ADMIN))
1131 if (!tty->ops->write)
1135 dev = alloc_candev(sizeof(struct elmcan), 0);
1138 elm = netdev_priv(dev);
1140 /* Configure TTY interface */
1141 tty->receive_room = 65536; /* We don't flow control */
1142 elm->txleft = 0; /* Clear TTY TX buffer */
1143 spin_lock_init(&elm->lock);
1144 atomic_set(&elm->refcount, 1);
1145 INIT_WORK(&elm->tx_work, elmcan_ldisc_tx_worker);
1147 /* Configure CAN metadata */
1148 elm->can.state = CAN_STATE_STOPPED;
1149 elm->can.bitrate_const = elmcan_bitrate_const;
1150 elm->can.bitrate_const_cnt = ARRAY_SIZE(elmcan_bitrate_const);
1151 elm->can.do_set_bittiming = elmcan_do_set_bittiming;
1152 elm->can.ctrlmode_supported = CAN_CTRLMODE_LISTENONLY;
1154 /* Configure netlink interface */
1156 dev->netdev_ops = &elmcan_netdev_ops;
1158 /* Mark ldisc channel as alive */
1160 tty->disc_data = elm;
1162 devm_can_led_init(elm->dev);
1165 err = register_candev(elm->dev);
1167 free_candev(elm->dev);
1171 netdev_info(elm->dev, "elmcan on %s.\n", tty->name);
1176 /* Close down an elmcan channel.
1177 * This means flushing out any pending queues, and then returning.
1178 * This call is serialized against other ldisc functions:
1179 * Once this is called, no other ldisc function of ours is entered.
1181 * We also use this function for a hangup event.
1183 static void elmcan_ldisc_close(struct tty_struct *tty)
1185 struct elmcan *elm = get_elm(tty);
1190 /* unregister_netdev() calls .ndo_stop() so we don't have to. */
1191 unregister_candev(elm->dev);
1193 /* Decrease the refcount twice, once for our own get_elm(),
1194 * and once to remove the count of 1 that we set in _open().
1195 * Once it reaches 0, we can safely destroy it.
1200 while (atomic_read(&elm->refcount) > 0)
1201 msleep_interruptible(10);
1203 /* At this point, all ldisc calls to us have become no-ops. */
1205 /* Mark channel as dead */
1206 spin_lock_bh(&elm->lock);
1207 tty->disc_data = NULL;
1209 spin_unlock_bh(&elm->lock);
1211 flush_work(&elm->tx_work);
1213 netdev_info(elm->dev, "elmcan off %s.\n", tty->name);
1215 free_candev(elm->dev);
1218 static int elmcan_ldisc_hangup(struct tty_struct *tty)
1220 elmcan_ldisc_close(tty);
1224 static int elmcan_ldisc_ioctl(struct tty_struct *tty, struct file *file,
1225 unsigned int cmd, unsigned long arg)
1227 struct elmcan *elm = get_elm(tty);
1235 tmp = strnlen(elm->dev->name, IFNAMSIZ - 1) + 1;
1236 if (copy_to_user((void __user *)arg, elm->dev->name, tmp)) {
1250 return tty_mode_ioctl(tty, file, cmd, arg);
1254 static struct tty_ldisc_ops elmcan_ldisc = {
1255 .owner = THIS_MODULE,
1256 .magic = TTY_LDISC_MAGIC,
1258 .receive_buf = elmcan_ldisc_rx,
1259 .write_wakeup = elmcan_ldisc_tx_wakeup,
1260 .open = elmcan_ldisc_open,
1261 .close = elmcan_ldisc_close,
1262 .hangup = elmcan_ldisc_hangup,
1263 .ioctl = elmcan_ldisc_ioctl,
1268 static int __init elmcan_init(void)
1272 pr_info("ELM327 based best-effort CAN interface driver\n");
1273 pr_info("This device is severely limited as a CAN interface, see documentation.\n");
1275 status = tty_register_ldisc(N_ELMCAN, &elmcan_ldisc);
1277 pr_err("can't register line discipline\n");
1282 static void __exit elmcan_exit(void)
1284 /* This will only be called when all channels have been closed by
1285 * userspace - tty_ldisc.c takes care of the module's refcount.
1289 status = tty_unregister_ldisc(N_ELMCAN);
1291 pr_err("Can't unregister line discipline (error: %d)\n",
1295 module_init(elmcan_init);
1296 module_exit(elmcan_exit);