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;
198 * Take the ELM327 out of almost any state and back into command mode
200 * Assumes elm->lock taken.
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;
213 * Schedule a CAN frame, and any necessary config changes,
214 * to be sent down the TTY.
216 * Assumes elm->lock taken.
218 static void elm327_send_frame(struct elmcan *elm, struct can_frame *frame)
220 /* Schedule any necessary changes in ELM327's CAN configuration */
221 if (elm->can_frame.can_id != frame->can_id) {
222 /* Set the new CAN ID for transmission. */
223 if ((frame->can_id & CAN_EFF_FLAG)
224 ^ (elm->can_frame.can_id & CAN_EFF_FLAG)) {
225 elm->can_config = (frame->can_id & CAN_EFF_FLAG
227 : ELM327_CAN_CONFIG_SEND_SFF)
228 | ELM327_CAN_CONFIG_VARIABLE_DLC
229 | ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF
230 | elm->can_bitrate_divisor;
232 set_bit(ELM_TODO_CAN_CONFIG, &elm->cmds_todo);
235 if (frame->can_id & CAN_EFF_FLAG) {
236 clear_bit(ELM_TODO_CANID_11BIT, &elm->cmds_todo);
237 set_bit(ELM_TODO_CANID_29BIT_LOW, &elm->cmds_todo);
238 set_bit(ELM_TODO_CANID_29BIT_HIGH, &elm->cmds_todo);
240 set_bit(ELM_TODO_CANID_11BIT, &elm->cmds_todo);
241 clear_bit(ELM_TODO_CANID_29BIT_LOW, &elm->cmds_todo);
242 clear_bit(ELM_TODO_CANID_29BIT_HIGH, &elm->cmds_todo);
246 /* Schedule the CAN frame itself. */
247 elm->can_frame = *frame;
248 set_bit(ELM_TODO_CAN_DATA, &elm->cmds_todo);
250 elm327_kick_into_cmd_mode(elm);
255 /************************************************************************
256 * ELM327: Initialization sequence *
258 * (assumes elm->lock taken) *
259 ************************************************************************/
261 static char *elm327_init_script[] = {
262 "AT WS\r", /* v1.0: Warm Start */
263 "AT PP FF OFF\r", /* v1.0: All Programmable Parameters Off */
264 "AT M0\r", /* v1.0: Memory Off */
265 "AT AL\r", /* v1.0: Allow Long messages */
266 "AT BI\r", /* v1.0: Bypass Initialization */
267 "AT CAF0\r", /* v1.0: CAN Auto Formatting Off */
268 "AT CFC0\r", /* v1.0: CAN Flow Control Off */
269 "AT CF 000\r", /* v1.0: Reset CAN ID Filter */
270 "AT CM 000\r", /* v1.0: Reset CAN ID Mask */
271 "AT E1\r", /* v1.0: Echo On */
272 "AT H1\r", /* v1.0: Headers On */
273 "AT L0\r", /* v1.0: Linefeeds Off */
274 "AT SH 7DF\r", /* v1.0: Set CAN sending ID to 0x7df */
275 "AT ST FF\r", /* v1.0: Set maximum Timeout for response after TX */
276 "AT AT0\r", /* v1.2: Adaptive Timing Off */
277 "AT D1\r", /* v1.3: Print DLC On */
278 "AT S1\r", /* v1.3: Spaces On */
279 "AT TP B\r", /* v1.0: Try Protocol B */
284 static void elm327_init(struct elmcan *elm)
286 elm->state = ELM_NOTINIT;
287 elm->can_frame.can_id = 0x7df;
289 elm->drop_next_line = 0;
291 /* We can only set the bitrate as a fraction of 500000.
292 * The bit timing constants in elmcan_bittiming_const will
293 * limit the user to the right values.
295 elm->can_bitrate_divisor = 500000 / elm->can.bittiming.bitrate;
296 elm->can_config = ELM327_CAN_CONFIG_SEND_SFF
297 | ELM327_CAN_CONFIG_VARIABLE_DLC
298 | ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF
299 | elm->can_bitrate_divisor;
301 /* Configure ELM327 and then start monitoring */
302 elm->next_init_cmd = &elm327_init_script[0];
303 set_bit(ELM_TODO_INIT, &elm->cmds_todo);
304 set_bit(ELM_TODO_SILENT_MONITOR, &elm->cmds_todo);
305 set_bit(ELM_TODO_RESPONSES, &elm->cmds_todo);
306 set_bit(ELM_TODO_CAN_CONFIG, &elm->cmds_todo);
308 elm327_kick_into_cmd_mode(elm);
313 /************************************************************************
314 * ELM327: Reception -> netdev glue *
316 * (assumes elm->lock taken) *
317 ************************************************************************/
319 static void elm327_feed_frame_to_netdev(struct elmcan *elm,
320 const struct can_frame *frame)
322 struct can_frame *cf;
325 if (!netif_running(elm->dev))
328 skb = alloc_can_skb(elm->dev, &cf);
333 memcpy(cf, frame, sizeof(struct can_frame));
335 elm->dev->stats.rx_packets++;
336 elm->dev->stats.rx_bytes += frame->can_dlc;
339 can_led_event(elm->dev, CAN_LED_EVENT_RX);
344 /************************************************************************
345 * ELM327: "Panic" handler *
347 * (assumes elm->lock taken) *
348 ************************************************************************/
350 /* Called when we're out of ideas and just want it all to end. */
351 static inline void elm327_hw_failure(struct elmcan *elm)
353 struct can_frame frame;
355 memset(&frame, 0, sizeof(frame));
356 frame.can_id = CAN_ERR_FLAG;
357 frame.can_dlc = CAN_ERR_DLC;
361 elm327_feed_frame_to_netdev(elm, &frame);
363 netdev_err(elm->dev, "ELM327 misbehaved. Blocking further communication.\n");
365 elm->hw_failure = true;
366 can_bus_off(elm->dev);
371 /************************************************************************
372 * ELM327: Reception parser *
374 * (assumes elm->lock taken) *
375 ************************************************************************/
377 static void elm327_parse_error(struct elmcan *elm, int len)
379 struct can_frame frame;
381 memset(&frame, 0, sizeof(frame));
382 frame.can_id = CAN_ERR_FLAG;
383 frame.can_dlc = CAN_ERR_DLC;
387 if (!memcmp(elm->rxbuf, "UNABLE TO CONNECT", 17)) {
389 "The ELM327 reported UNABLE TO CONNECT. Please check your setup.\n");
393 if (!memcmp(elm->rxbuf, "BUFFER FULL", 11)) {
394 /* This case will only happen if the last data
396 * Otherwise, elm327_parse_frame() will emit the
397 * error frame instead.
399 frame.can_id |= CAN_ERR_CRTL;
400 frame.data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
404 if (!memcmp(elm->rxbuf, "BUS ERROR", 9))
405 frame.can_id |= CAN_ERR_BUSERROR;
406 if (!memcmp(elm->rxbuf, "CAN ERROR", 9))
407 frame.can_id |= CAN_ERR_PROT;
408 if (!memcmp(elm->rxbuf, "<RX ERROR", 9))
409 frame.can_id |= CAN_ERR_PROT;
412 if (!memcmp(elm->rxbuf, "BUS BUSY", 8)) {
413 frame.can_id |= CAN_ERR_PROT;
414 frame.data[2] = CAN_ERR_PROT_OVERLOAD;
416 if (!memcmp(elm->rxbuf, "FB ERROR", 8)) {
417 frame.can_id |= CAN_ERR_PROT;
418 frame.data[2] = CAN_ERR_PROT_TX;
422 if (!memcmp(elm->rxbuf, "ERR", 3)) {
423 netdev_err(elm->dev, "The ELM327 reported an ERR%c%c. Please power it off and on again.\n",
424 elm->rxbuf[3], elm->rxbuf[4]);
425 frame.can_id |= CAN_ERR_CRTL;
429 /* Don't emit an error frame if we're unsure */
433 elm327_feed_frame_to_netdev(elm, &frame);
437 static int elm327_parse_frame(struct elmcan *elm, int len)
439 struct can_frame frame;
444 memset(&frame, 0, sizeof(frame));
446 /* Find first non-hex and non-space character:
447 * - In the simplest case, there is none.
448 * - For RTR frames, 'R' is the first non-hex character.
449 * - An error message may replace the end of the data line.
451 for (hexlen = 0; hexlen <= len; hexlen++) {
452 if (hex_to_bin(elm->rxbuf[hexlen]) < 0
453 && elm->rxbuf[hexlen] != ' ') {
458 /* If we accept stray characters coming in:
459 * Check for stray characters on a payload line.
460 * No idea what causes this.
462 if (accept_flaky_uart
464 && !isdigit(elm->rxbuf[hexlen])
465 && !isupper(elm->rxbuf[hexlen])
466 && '<' != elm->rxbuf[hexlen]
467 && ' ' != elm->rxbuf[hexlen]) {
468 /* The line is likely garbled anyway, so bail.
469 * The main code will restart listening.
471 elm327_kick_into_cmd_mode(elm);
475 /* Use spaces in CAN ID to distinguish 29 or 11 bit address length.
476 * No out-of-bounds access:
477 * We use the fact that we can always read from elm->rxbuf.
479 if (elm->rxbuf[2] == ' ' && elm->rxbuf[5] == ' '
480 && elm->rxbuf[8] == ' ' && elm->rxbuf[11] == ' '
481 && elm->rxbuf[13] == ' ') {
482 frame.can_id = CAN_EFF_FLAG;
484 } else if (elm->rxbuf[3] == ' ' && elm->rxbuf[5] == ' ') {
488 /* This is not a well-formatted data line.
489 * Assume it's an error message.
494 if (hexlen < datastart) {
495 /* The line is too short to be a valid frame hex dump.
496 * Something interrupted the hex dump or it is invalid.
501 /* From here on all chars up to buf[hexlen] are hex or spaces,
502 * at well-defined offsets.
505 /* Read CAN data length */
506 frame.can_dlc = (hex_to_bin(elm->rxbuf[datastart - 2]) << 0);
509 if (frame.can_id & CAN_EFF_FLAG) {
510 frame.can_id |= (hex_to_bin(elm->rxbuf[0]) << 28)
511 | (hex_to_bin(elm->rxbuf[1]) << 24)
512 | (hex_to_bin(elm->rxbuf[3]) << 20)
513 | (hex_to_bin(elm->rxbuf[4]) << 16)
514 | (hex_to_bin(elm->rxbuf[6]) << 12)
515 | (hex_to_bin(elm->rxbuf[7]) << 8)
516 | (hex_to_bin(elm->rxbuf[9]) << 4)
517 | (hex_to_bin(elm->rxbuf[10]) << 0);
519 frame.can_id |= (hex_to_bin(elm->rxbuf[0]) << 8)
520 | (hex_to_bin(elm->rxbuf[1]) << 4)
521 | (hex_to_bin(elm->rxbuf[2]) << 0);
524 /* Check for RTR frame */
525 if (elm->rxfill >= hexlen + 3
526 && elm->rxbuf[hexlen + 0] == 'R'
527 && elm->rxbuf[hexlen + 1] == 'T'
528 && elm->rxbuf[hexlen + 2] == 'R') {
529 frame.can_id |= CAN_RTR_FLAG;
532 /* Is the line long enough to hold the advertised payload? */
533 if (!(frame.can_id & CAN_RTR_FLAG)
534 && (hexlen < frame.can_dlc * 3 + datastart)) {
535 /* Incomplete frame. */
537 /* Probably the ELM327's RS232 TX buffer was full.
538 * Emit an error frame and exit.
540 frame.can_id = CAN_ERR_FLAG | CAN_ERR_CRTL;
541 frame.can_dlc = CAN_ERR_DLC;
542 frame.data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
543 elm327_feed_frame_to_netdev(elm, &frame);
545 /* Signal failure to parse.
546 * The line will be re-parsed as an error line, which will fail.
547 * However, this will correctly drop the state machine back into
553 /* Parse the data nibbles. */
554 for (i = 0; i < frame.can_dlc; i++) {
555 frame.data[i] = (hex_to_bin(elm->rxbuf[datastart+3*i]) << 4)
556 | (hex_to_bin(elm->rxbuf[datastart+3*i+1]) << 0);
559 /* Feed the frame to the network layer. */
560 elm327_feed_frame_to_netdev(elm, &frame);
566 static void elm327_parse_line(struct elmcan *elm, int len)
568 /* Skip empty lines */
572 /* Skip echo lines */
573 if (elm->drop_next_line) {
574 elm->drop_next_line = 0;
576 } else if (elm->rxbuf[0] == 'A' && elm->rxbuf[1] == 'T') {
580 /* Regular parsing */
581 switch (elm->state) {
583 if (elm327_parse_frame(elm, len)) {
584 /* Parse an error line. */
585 elm327_parse_error(elm, len);
588 elm327_kick_into_cmd_mode(elm);
597 static void elm327_handle_prompt(struct elmcan *elm)
599 struct can_frame *frame = &elm->can_frame;
600 char local_txbuf[20];
602 if (!elm->cmds_todo) {
603 /* Enter CAN monitor mode */
604 elm327_send(elm, "ATMA\r", 5);
605 elm->state = ELM_RECEIVING;
610 /* Reconfigure ELM327 step by step as indicated by elm->cmds_todo */
611 if (test_bit(ELM_TODO_INIT, &elm->cmds_todo)) {
612 strcpy(local_txbuf, *elm->next_init_cmd);
614 elm->next_init_cmd++;
615 if (!(*elm->next_init_cmd)) {
616 clear_bit(ELM_TODO_INIT, &elm->cmds_todo);
617 netdev_info(elm->dev, "Initialization finished.\n");
620 } else if (test_and_clear_bit(ELM_TODO_SILENT_MONITOR, &elm->cmds_todo)) {
621 sprintf(local_txbuf, "ATCSM%i\r",
622 !(!(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY)));
624 } else if (test_and_clear_bit(ELM_TODO_RESPONSES, &elm->cmds_todo)) {
625 sprintf(local_txbuf, "ATR%i\r",
626 !(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY));
628 } else if (test_and_clear_bit(ELM_TODO_CAN_CONFIG, &elm->cmds_todo)) {
629 sprintf(local_txbuf, "ATPC\r");
630 set_bit(ELM_TODO_CAN_CONFIG_PART2, &elm->cmds_todo);
632 } else if (test_and_clear_bit(ELM_TODO_CAN_CONFIG_PART2, &elm->cmds_todo)) {
633 sprintf(local_txbuf, "ATPB%04X\r",
636 } else if (test_and_clear_bit(ELM_TODO_CANID_29BIT_HIGH, &elm->cmds_todo)) {
637 sprintf(local_txbuf, "ATCP%02X\r",
638 (frame->can_id & CAN_EFF_MASK) >> 24);
640 } else if (test_and_clear_bit(ELM_TODO_CANID_29BIT_LOW, &elm->cmds_todo)) {
641 sprintf(local_txbuf, "ATSH%06X\r",
642 frame->can_id & CAN_EFF_MASK & ((1 << 24) - 1));
644 } else if (test_and_clear_bit(ELM_TODO_CANID_11BIT, &elm->cmds_todo)) {
645 sprintf(local_txbuf, "ATSH%03X\r",
646 frame->can_id & CAN_SFF_MASK);
648 } else if (test_and_clear_bit(ELM_TODO_CAN_DATA, &elm->cmds_todo)) {
649 if (frame->can_id & CAN_RTR_FLAG) {
650 /* Send an RTR frame. Their DLC is fixed.
651 * Some chips don't send them at all.
653 sprintf(local_txbuf, "ATRTR\r");
655 /* Send a regular CAN data frame */
658 for (i = 0; i < frame->can_dlc; i++) {
659 sprintf(&local_txbuf[2*i], "%02X",
663 sprintf(&local_txbuf[2*i], "\r");
666 elm->drop_next_line = 1;
667 elm->state = ELM_RECEIVING;
670 elm327_send(elm, local_txbuf, strlen(local_txbuf));
674 static bool elm327_is_ready_char(char c)
676 /* Bits 0xc0 are sometimes set (randomly), hence the mask.
677 * Probably bad hardware.
679 return (c & 0x3f) == ELM327_READY_CHAR;
683 static void elm327_drop_bytes(struct elmcan *elm, int i)
685 memmove(&elm->rxbuf[0], &elm->rxbuf[i], sizeof(elm->rxbuf) - i);
690 static void elm327_parse_rxbuf(struct elmcan *elm)
694 switch (elm->state) {
699 case ELM_GETMAGICCHAR:
701 /* Wait for 'y' or '>' */
704 for (i = 0; i < elm->rxfill; i++) {
705 if (elm->rxbuf[i] == ELM327_MAGIC_CHAR) {
706 elm327_send(elm, "\r", 1);
707 elm->state = ELM_GETPROMPT;
710 } else if (elm327_is_ready_char(elm->rxbuf[i])) {
711 elm327_send(elm, ELM327_MAGIC_STRING, 1);
717 elm327_drop_bytes(elm, i);
724 if (elm327_is_ready_char(elm->rxbuf[elm->rxfill - 1]))
725 elm327_handle_prompt(elm);
731 /* Find <CR> delimiting feedback lines. */
733 (len < elm->rxfill) && (elm->rxbuf[len] != '\r');
738 if (len == sizeof(elm->rxbuf)) {
739 /* Line exceeds buffer. It's probably all garbage.
740 * Did we even connect at the right baud rate?
743 "RX buffer overflow. Faulty ELM327 or UART?\n");
744 elm327_hw_failure(elm);
746 } else if (len == elm->rxfill) {
747 if (elm327_is_ready_char(elm->rxbuf[elm->rxfill - 1])) {
748 /* The ELM327's AT ST response timeout ran out,
749 * so we got a prompt.
750 * Clear RX buffer and restart listening.
754 elm327_handle_prompt(elm);
758 /* No <CR> found - we haven't received a full line yet.
759 * Wait for more data.
764 /* We have a full line to parse. */
765 elm327_parse_line(elm, len);
767 /* Remove parsed data from RX buffer. */
768 elm327_drop_bytes(elm, len+1);
770 /* More data to parse? */
772 elm327_parse_rxbuf(elm);
780 /************************************************************************
783 * (takes elm->lock) *
784 ************************************************************************/
786 /* Netdevice DOWN -> UP routine */
787 static int elmcan_netdev_open(struct net_device *dev)
789 struct elmcan *elm = netdev_priv(dev);
792 spin_lock_bh(&elm->lock);
793 if (elm->hw_failure) {
794 netdev_err(elm->dev, "Refusing to open interface after a hardware fault has been detected.\n");
795 spin_unlock_bh(&elm->lock);
799 if (elm->tty == NULL) {
800 spin_unlock_bh(&elm->lock);
804 /* open_candev() checks for elm->can.bittiming.bitrate != 0 */
805 err = open_candev(dev);
807 spin_unlock_bh(&elm->lock);
811 /* Initialize the ELM327 */
813 spin_unlock_bh(&elm->lock);
815 can_led_event(dev, CAN_LED_EVENT_OPEN);
816 elm->can.state = CAN_STATE_ERROR_ACTIVE;
817 netif_start_queue(dev);
822 /* Netdevice UP -> DOWN routine */
823 static int elmcan_netdev_close(struct net_device *dev)
825 struct elmcan *elm = netdev_priv(dev);
827 spin_lock_bh(&elm->lock);
829 /* TTY discipline is running. */
831 /* Interrupt whatever we're doing right now */
832 elm327_send(elm, ELM327_MAGIC_STRING, 1);
834 /* Clear the wakeup bit, as the netdev will be down and thus
835 * the wakeup handler won't clear it
837 clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
839 spin_unlock_bh(&elm->lock);
841 flush_work(&elm->tx_work);
843 spin_unlock_bh(&elm->lock);
846 elm->can.state = CAN_STATE_STOPPED;
847 netif_stop_queue(dev);
849 can_led_event(dev, CAN_LED_EVENT_STOP);
854 /* Send a can_frame to a TTY queue. */
855 static netdev_tx_t elmcan_netdev_start_xmit(struct sk_buff *skb,
856 struct net_device *dev)
858 struct elmcan *elm = netdev_priv(dev);
859 struct can_frame *frame = (struct can_frame *) skb->data;
861 if (skb->len != sizeof(struct can_frame))
864 if (!netif_running(dev)) {
865 netdev_warn(elm->dev, "xmit: iface is down.\n");
869 /* BHs are already disabled, so no spin_lock_bh().
870 * See Documentation/networking/netdevices.txt
872 spin_lock(&elm->lock);
874 /* We shouldn't get here after a hardware fault:
875 * can_bus_off() calls netif_carrier_off()
877 BUG_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);
900 static int elmcan_netdev_change_mtu(struct net_device *dev, int new_mtu)
905 static const struct net_device_ops elmcan_netdev_ops = {
906 .ndo_open = elmcan_netdev_open,
907 .ndo_stop = elmcan_netdev_close,
908 .ndo_start_xmit = elmcan_netdev_start_xmit,
909 .ndo_change_mtu = elmcan_netdev_change_mtu,
916 /************************************************************************
919 * (takes elm->lock) *
920 ************************************************************************/
923 * Get a reference to our struct, taking into account locks/refcounts.
924 * This is to ensure ordering in case we are shutting down, and to ensure
925 * there is a refcount at all (because tty->disc_data may be NULL).
927 static struct elmcan *get_elm(struct tty_struct *tty)
932 /* Lock all elmcan TTYs, so tty->disc_data can't become NULL
933 * the moment before we increase the reference counter.
935 spin_lock_bh(&elmcan_discdata_lock);
936 elm = (struct elmcan *) tty->disc_data;
939 spin_unlock_bh(&elmcan_discdata_lock);
943 got_ref = atomic_inc_not_zero(&elm->refcount);
944 spin_unlock_bh(&elmcan_discdata_lock);
952 static void put_elm(struct elmcan *elm)
954 atomic_dec(&elm->refcount);
960 * Handle the 'receiver data ready' interrupt.
961 * This function is called by the 'tty_io' module in the kernel when
962 * a block of ELM327 CAN data has been received, which can now be parsed
963 * and sent on to some IP layer for further processing. This will not
964 * be re-entered while running but other ldisc functions may be called
967 static void elmcan_ldisc_rx(struct tty_struct *tty,
968 const unsigned char *cp, char *fp, int count)
970 struct elmcan *elm = get_elm(tty);
975 spin_lock_bh(&elm->lock);
976 if (elm->hw_failure) {
977 spin_unlock_bh(&elm->lock);
983 /* Read the characters out of the buffer */
984 while (count-- && elm->rxfill < sizeof(elm->rxbuf)) {
986 netdev_err(elm->dev, "Error in received character stream. Check your wiring.");
988 elm327_hw_failure(elm);
989 spin_unlock_bh(&elm->lock);
995 /* Ignore NUL characters, which the PIC microcontroller may
996 * inadvertently insert due to a known hardware bug.
997 * See ELM327 documentation, which refers to a Microchip PIC
1001 /* Check for stray characters on the UART line.
1002 * No idea what causes this.
1004 if (!accept_flaky_uart
1007 && ELM327_MAGIC_CHAR != *cp
1008 && ELM327_READY_CHAR != *cp
1017 /* We've received an invalid character, so bail.
1018 * There's something wrong with the ELM327, or
1019 * with the UART line.
1021 netdev_err(elm->dev,
1022 "Received illegal character %02x.\n",
1024 elm327_hw_failure(elm);
1025 spin_unlock_bh(&elm->lock);
1031 elm->rxbuf[elm->rxfill++] = *cp;
1038 netdev_err(elm->dev, "Receive buffer overflowed. Bad chip or wiring?");
1040 elm327_hw_failure(elm);
1041 spin_unlock_bh(&elm->lock);
1047 elm327_parse_rxbuf(elm);
1048 spin_unlock_bh(&elm->lock);
1054 * Write out remaining transmit buffer.
1055 * Scheduled when TTY is writable.
1057 static void elmcan_ldisc_tx_worker(struct work_struct *work)
1059 /* No need to use get_elm() here, as we'll always flush workers
1060 * befory destroying the elmcan object.
1062 struct elmcan *elm = container_of(work, struct elmcan, tx_work);
1065 spin_lock_bh(&elm->lock);
1066 if (elm->hw_failure) {
1067 spin_unlock_bh(&elm->lock);
1071 if (!elm->tty || !netif_running(elm->dev)) {
1072 spin_unlock_bh(&elm->lock);
1076 if (elm->txleft <= 0) {
1077 /* Our TTY write buffer is empty:
1078 * We can start transmission of another packet
1080 clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
1081 spin_unlock_bh(&elm->lock);
1082 netif_wake_queue(elm->dev);
1086 actual = elm->tty->ops->write(elm->tty, elm->txhead, elm->txleft);
1088 netdev_err(elm->dev,
1089 "Failed to write to tty %s.\n",
1091 elm327_hw_failure(elm);
1092 spin_unlock_bh(&elm->lock);
1096 elm->txleft -= actual;
1097 elm->txhead += actual;
1098 spin_unlock_bh(&elm->lock);
1103 * Called by the driver when there's room for more data.
1104 * Schedule the transmit.
1106 static void elmcan_ldisc_tx_wakeup(struct tty_struct *tty)
1108 struct elmcan *elm = get_elm(tty);
1113 schedule_work(&elm->tx_work);
1120 /* ELM327 can only handle bitrates that are integer divisors of 500 kHz,
1121 * or 7/8 of that. Divisors are 1 to 64.
1122 * Currently we don't implement support for 7/8 rates.
1124 static const u32 elmcan_bitrate_const[64] = {
1125 7812, 7936, 8064, 8196, 8333, 8474, 8620, 8771,
1126 8928, 9090, 9259, 9433, 9615, 9803, 10000, 10204,
1127 10416, 10638, 10869, 11111, 11363, 11627, 11904, 12195,
1128 12500, 12820, 13157, 13513, 13888, 14285, 14705, 15151,
1129 15625, 16129, 16666, 17241, 17857, 18518, 19230, 20000,
1130 20833, 21739, 22727, 23809, 25000, 26315, 27777, 29411,
1131 31250, 33333, 35714, 38461, 41666, 45454, 50000, 55555,
1132 62500, 71428, 83333, 100000, 125000, 166666, 250000, 500000
1135 /* Dummy function to claim we're changing the bitrate.
1136 * We actually do this when opening the net device.
1138 static int elmcan_do_set_bittiming(struct net_device *netdev)
1145 * Open the high-level part of the elmcan channel.
1146 * This function is called by the TTY module when the
1147 * elmcan line discipline is called for.
1149 * Called in process context serialized from other ldisc calls.
1151 static int elmcan_ldisc_open(struct tty_struct *tty)
1153 struct net_device *dev;
1157 if (!capable(CAP_NET_ADMIN))
1160 if (!tty->ops->write)
1164 /* OK. Find a free elmcan channel to use. */
1165 dev = alloc_candev(sizeof(struct elmcan), 0);
1168 elm = netdev_priv(dev);
1170 /* Configure TTY interface */
1171 tty->receive_room = 65536; /* We don't flow control */
1172 elm->txleft = 0; /* Clear TTY TX buffer */
1173 spin_lock_init(&elm->lock);
1174 atomic_set(&elm->refcount, 1);
1175 INIT_WORK(&elm->tx_work, elmcan_ldisc_tx_worker);
1177 /* Configure CAN metadata */
1178 elm->can.state = CAN_STATE_STOPPED;
1179 elm->can.bitrate_const = elmcan_bitrate_const;
1180 elm->can.bitrate_const_cnt = ARRAY_SIZE(elmcan_bitrate_const);
1181 elm->can.do_set_bittiming = elmcan_do_set_bittiming;
1182 elm->can.ctrlmode_supported = CAN_CTRLMODE_LISTENONLY;
1184 /* Configure netlink interface */
1186 dev->netdev_ops = &elmcan_netdev_ops;
1188 /* Mark ldisc channel as alive */
1190 tty->disc_data = elm;
1192 devm_can_led_init(elm->dev);
1195 err = register_candev(elm->dev);
1197 free_candev(elm->dev);
1201 netdev_info(elm->dev, "elmcan on %s.\n", tty->name);
1207 * Close down an elmcan channel.
1208 * This means flushing out any pending queues, and then returning.
1209 * This call is serialized against other ldisc functions:
1210 * Once this is called, no other ldisc function of ours is entered.
1212 * We also use this function for a hangup event.
1214 static void elmcan_ldisc_close(struct tty_struct *tty)
1216 /* Use get_elm() to synchronize against other users */
1217 struct elmcan *elm = get_elm(tty);
1222 /* Tear down network side.
1223 * unregister_netdev() calls .ndo_stop() so we don't have to.
1225 unregister_candev(elm->dev);
1227 /* Decrease the refcount twice, once for our own get_elm(),
1228 * and once to remove the count of 1 that we set in _open().
1229 * Once it reaches 0, we can safely destroy it.
1234 /* Spin until refcount reaches 0 */
1235 while (atomic_read(&elm->refcount) > 0)
1236 msleep_interruptible(10);
1238 /* At this point, all ldisc calls to us will be no-ops.
1239 * Since the refcount is 0, they are bailing immediately.
1242 /* Mark channel as dead */
1243 spin_lock_bh(&elm->lock);
1244 tty->disc_data = NULL;
1246 spin_unlock_bh(&elm->lock);
1248 /* Flush TTY side */
1249 flush_work(&elm->tx_work);
1251 netdev_info(elm->dev, "elmcan off %s.\n", tty->name);
1253 /* Free our memory */
1254 free_candev(elm->dev);
1257 static int elmcan_ldisc_hangup(struct tty_struct *tty)
1259 elmcan_ldisc_close(tty);
1263 /* Perform I/O control on an active elmcan channel. */
1264 static int elmcan_ldisc_ioctl(struct tty_struct *tty, struct file *file,
1265 unsigned int cmd, unsigned long arg)
1267 struct elmcan *elm = get_elm(tty);
1275 tmp = strnlen(elm->dev->name, IFNAMSIZ - 1) + 1;
1276 if (copy_to_user((void __user *)arg, elm->dev->name, tmp)) {
1290 return tty_mode_ioctl(tty, file, cmd, arg);
1294 static struct tty_ldisc_ops elmcan_ldisc = {
1295 .owner = THIS_MODULE,
1296 .magic = TTY_LDISC_MAGIC,
1298 .receive_buf = elmcan_ldisc_rx,
1299 .write_wakeup = elmcan_ldisc_tx_wakeup,
1300 .open = elmcan_ldisc_open,
1301 .close = elmcan_ldisc_close,
1302 .hangup = elmcan_ldisc_hangup,
1303 .ioctl = elmcan_ldisc_ioctl,
1310 /************************************************************************
1311 * Module init/exit *
1312 ************************************************************************/
1314 static int __init elmcan_init(void)
1318 pr_info("ELM327 based best-effort CAN interface driver\n");
1319 pr_info("This device is severely limited as a CAN interface, see documentation.\n");
1321 /* Fill in our line protocol discipline, and register it */
1322 status = tty_register_ldisc(N_ELMCAN, &elmcan_ldisc);
1324 pr_err("can't register line discipline\n");
1329 static void __exit elmcan_exit(void)
1331 /* This will only be called when all channels have been closed by
1332 * userspace - tty_ldisc.c takes care of the module's refcount.
1336 status = tty_unregister_ldisc(N_ELMCAN);
1338 pr_err("Can't unregister line discipline (error: %d)\n",
1342 module_init(elmcan_init);
1343 module_exit(elmcan_exit);