1 // SPDX-License-Identifier: GPL-2.0
2 /* elmcan.c - ELM327 based CAN interface driver
3 * (tty line discipline)
5 * This driver started as a derivative of linux/drivers/net/can/slcan.c
6 * and my thanks go to the original authors for their inspiration.
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>
13 * This code barely bears any resemblance to slcan anymore, and whatever
14 * may be left is Linux specific boilerplate anyway, however I am leaving
15 * the GPL-2.0 identifier at the top just to be sure.
17 * Please feel free to use my own code, especially the ELM327 communication
18 * logic, in accordance with SPDX-License-Identifier BSD-3-Clause to port
19 * this driver to other systems.
24 #define pr_fmt(fmt) "[elmcan] " fmt
26 #include <linux/init.h>
27 #include <linux/module.h>
28 #include <linux/moduleparam.h>
30 #include <linux/atomic.h>
31 #include <linux/bitops.h>
32 #include <linux/ctype.h>
33 #include <linux/delay.h>
34 #include <linux/errno.h>
35 #include <linux/if_ether.h>
36 #include <linux/kernel.h>
37 #include <linux/list.h>
38 #include <linux/netdevice.h>
39 #include <linux/skbuff.h>
40 #include <linux/spinlock.h>
41 #include <linux/string.h>
42 #include <linux/tty.h>
43 #include <linux/version.h>
44 #include <linux/workqueue.h>
46 #include <linux/can.h>
47 #include <linux/can/dev.h>
48 #include <linux/can/error.h>
49 #include <linux/can/led.h>
50 #include <linux/can/rx-offload.h>
52 MODULE_ALIAS_LDISC(N_ELMCAN);
53 MODULE_DESCRIPTION("ELM327 based CAN interface");
54 MODULE_LICENSE("GPL");
55 MODULE_AUTHOR("Max Staudt <max-linux@enpas.org>");
57 /* If this is enabled, we'll try to make the best of the situation
58 * even if we receive unexpected characters on the line.
60 * Handle with care, it's likely your hardware is unreliable!
62 static bool accept_flaky_uart;
63 module_param_named(accept_flaky_uart, accept_flaky_uart, bool, 0444);
64 MODULE_PARM_DESC(accept_flaky_uart, "Don't bail at the first invalid character. Behavior undefined.");
66 /* Line discipline ID number */
71 #define ELM327_NAPI_WEIGHT 4
73 #define ELM327_SIZE_RXBUF 256
74 #define ELM327_SIZE_TXBUF 32
76 #define ELM327_CAN_CONFIG_SEND_SFF 0x8000
77 #define ELM327_CAN_CONFIG_VARIABLE_DLC 0x4000
78 #define ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF 0x2000
79 #define ELM327_CAN_CONFIG_BAUDRATE_MULT_8_7 0x1000
81 #define ELM327_MAGIC_CHAR 'y'
82 #define ELM327_MAGIC_STRING "y"
83 #define ELM327_READY_CHAR '>'
85 /* Bits in elm->cmds_todo */
90 TODO_CANID_29BIT_HIGH,
91 TODO_CAN_CONFIG_PART2,
99 /* This must be the first member when using alloc_candev() */
102 struct can_rx_offload offload;
104 /* TTY and netdev devices that we're bridging */
105 struct tty_struct *tty;
106 struct net_device *dev;
108 /* Per-channel lock */
111 /* Keep track of how many things are using this struct.
112 * Once it reaches 0, we are in the process of cleaning up,
113 * and new operations will be cancelled immediately.
114 * Use atomic_t rather than refcount_t because we deliberately
115 * decrement to 0, and refcount_dec() spills a WARN_ONCE in
120 /* Stop the channel on hardware failure.
121 * Once this is true, nothing will be sent to the TTY.
126 struct work_struct tx_work; /* Flushes TTY TX buffer */
127 unsigned char *txbuf;
128 unsigned char *txhead; /* Pointer to next TX byte */
129 int txleft; /* Bytes left to TX */
132 unsigned char rxbuf[ELM327_SIZE_RXBUF];
145 /* The CAN frame and config the ELM327 is sending/using,
146 * or will send/use after finishing all cmds_todo
148 struct can_frame can_frame;
149 unsigned short can_config;
150 unsigned long can_bitrate;
151 unsigned char can_bitrate_divisor;
152 int silent_monitoring;
154 /* Things we have yet to send */
155 char **next_init_cmd;
156 unsigned long cmds_todo;
159 /* A lock for all tty->disc_data handled by this ldisc.
160 * This is to prevent a case where tty->disc_data is set to NULL,
161 * yet someone is still trying to dereference it.
162 * Without this, we cannot do a clean shutdown.
164 static DEFINE_SPINLOCK(elmcan_discdata_lock);
166 static inline void elm327_hw_failure(struct elmcan *elm);
168 /***********************************************************************
169 * ELM327: Transmission *
171 * (all functions assume elm->lock taken) *
172 ***********************************************************************/
174 static void elm327_send(struct elmcan *elm, const void *buf, size_t len)
181 memcpy(elm->txbuf, buf, len);
183 /* Order of next two lines is *very* important.
184 * When we are sending a little amount of data,
185 * the transfer may be completed inside the ops->write()
186 * routine, because it's running with interrupts enabled.
187 * In this case we *never* got WRITE_WAKEUP event,
188 * if we did not request it before write operation.
189 * 14 Oct 1994 Dmitry Gorodchanin.
191 set_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
192 actual = elm->tty->ops->write(elm->tty, elm->txbuf, len);
195 "Failed to write to tty %s.\n",
197 elm327_hw_failure(elm);
201 elm->txleft = len - actual;
202 elm->txhead = elm->txbuf + actual;
205 /* Take the ELM327 out of almost any state and back into command mode.
206 * We send ELM327_MAGIC_CHAR which will either abort any running
207 * operation, or be echoed back to us in case we're already in command
210 static void elm327_kick_into_cmd_mode(struct elmcan *elm)
212 if (elm->state != ELM_GETMAGICCHAR && elm->state != ELM_GETPROMPT) {
213 elm327_send(elm, ELM327_MAGIC_STRING, 1);
215 elm->state = ELM_GETMAGICCHAR;
219 /* Schedule a CAN frame and necessary config changes to be sent to the TTY. */
220 static void elm327_send_frame(struct elmcan *elm, struct can_frame *frame)
222 /* Schedule any necessary changes in ELM327's CAN configuration */
223 if (elm->can_frame.can_id != frame->can_id) {
224 /* Set the new CAN ID for transmission. */
225 if ((frame->can_id & CAN_EFF_FLAG)
226 ^ (elm->can_frame.can_id & CAN_EFF_FLAG)) {
227 elm->can_config = (frame->can_id & CAN_EFF_FLAG
229 : ELM327_CAN_CONFIG_SEND_SFF)
230 | ELM327_CAN_CONFIG_VARIABLE_DLC
231 | ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF
232 | elm->can_bitrate_divisor;
234 set_bit(TODO_CAN_CONFIG, &elm->cmds_todo);
237 if (frame->can_id & CAN_EFF_FLAG) {
238 clear_bit(TODO_CANID_11BIT, &elm->cmds_todo);
239 set_bit(TODO_CANID_29BIT_LOW, &elm->cmds_todo);
240 set_bit(TODO_CANID_29BIT_HIGH, &elm->cmds_todo);
242 set_bit(TODO_CANID_11BIT, &elm->cmds_todo);
243 clear_bit(TODO_CANID_29BIT_LOW, &elm->cmds_todo);
244 clear_bit(TODO_CANID_29BIT_HIGH, &elm->cmds_todo);
248 /* Schedule the CAN frame itself. */
249 elm->can_frame = *frame;
250 set_bit(TODO_CAN_DATA, &elm->cmds_todo);
252 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 */
283 static void elm327_init(struct elmcan *elm)
285 elm->state = ELM_NOTINIT;
286 elm->can_frame.can_id = 0x7df;
288 elm->drop_next_line = 0;
290 /* We can only set the bitrate as a fraction of 500000.
291 * The bit timing constants in elmcan_bittiming_const will
292 * limit the user to the right values.
294 elm->can_bitrate_divisor = 500000 / elm->can.bittiming.bitrate;
295 elm->can_config = ELM327_CAN_CONFIG_SEND_SFF
296 | ELM327_CAN_CONFIG_VARIABLE_DLC
297 | ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF
298 | elm->can_bitrate_divisor;
300 /* Configure ELM327 and then start monitoring */
301 elm->next_init_cmd = &elm327_init_script[0];
302 set_bit(TODO_INIT, &elm->cmds_todo);
303 set_bit(TODO_SILENT_MONITOR, &elm->cmds_todo);
304 set_bit(TODO_RESPONSES, &elm->cmds_todo);
305 set_bit(TODO_CAN_CONFIG, &elm->cmds_todo);
307 elm327_kick_into_cmd_mode(elm);
310 /***********************************************************************
311 * ELM327: Reception -> netdev glue *
313 * (assumes elm->lock taken) *
314 ***********************************************************************/
316 static void elm327_feed_frame_to_netdev(struct elmcan *elm,
317 const struct can_frame *frame)
319 struct can_frame *cf;
322 if (!netif_running(elm->dev))
325 skb = alloc_can_skb(elm->dev, &cf);
330 memcpy(cf, frame, sizeof(struct can_frame));
332 /* Queue for NAPI pickup.
333 * rx-offload will update stats and LEDs for us.
335 if (can_rx_offload_queue_tail(&elm->offload, skb))
336 elm->dev->stats.rx_fifo_errors++;
338 #if LINUX_VERSION_CODE >= KERNEL_VERSION(5,15,0)
340 can_rx_offload_irq_finish(&elm->offload);
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);
369 /***********************************************************************
370 * ELM327: Reception parser *
372 * (assumes elm->lock taken) *
373 ***********************************************************************/
375 static void elm327_parse_error(struct elmcan *elm, int len)
377 struct can_frame frame;
379 memset(&frame, 0, sizeof(frame));
380 frame.can_id = CAN_ERR_FLAG;
381 frame.can_dlc = CAN_ERR_DLC;
385 if (!memcmp(elm->rxbuf, "UNABLE TO CONNECT", 17)) {
387 "ELM327 reported UNABLE TO CONNECT. Please check your setup.\n");
391 if (!memcmp(elm->rxbuf, "BUFFER FULL", 11)) {
392 /* This case will only happen if the last data
394 * Otherwise, elm327_parse_frame() will heuristically
395 * emit this error frame instead.
397 frame.can_id |= CAN_ERR_CRTL;
398 frame.data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
402 if (!memcmp(elm->rxbuf, "BUS ERROR", 9))
403 frame.can_id |= CAN_ERR_BUSERROR;
404 if (!memcmp(elm->rxbuf, "CAN ERROR", 9))
405 frame.can_id |= CAN_ERR_PROT;
406 if (!memcmp(elm->rxbuf, "<RX ERROR", 9))
407 frame.can_id |= CAN_ERR_PROT;
410 if (!memcmp(elm->rxbuf, "BUS BUSY", 8)) {
411 frame.can_id |= CAN_ERR_PROT;
412 frame.data[2] = CAN_ERR_PROT_OVERLOAD;
414 if (!memcmp(elm->rxbuf, "FB ERROR", 8)) {
415 frame.can_id |= CAN_ERR_PROT;
416 frame.data[2] = CAN_ERR_PROT_TX;
420 if (!memcmp(elm->rxbuf, "ERR", 3)) {
421 netdev_err(elm->dev, "ELM327 reported an ERR%c%c. Please power it off and on again.\n",
422 elm->rxbuf[3], elm->rxbuf[4]);
423 frame.can_id |= CAN_ERR_CRTL;
427 /* Don't emit an error frame if we're unsure */
431 elm327_feed_frame_to_netdev(elm, &frame);
434 /* Parse CAN frames coming as ASCII from ELM327.
435 * They can be of various formats:
437 * 29-bit ID (EFF): 12 34 56 78 D PL PL PL PL PL PL PL PL
438 * 11-bit ID (!EFF): 123 D PL PL PL PL PL PL PL PL
440 * where D = DLC, PL = payload byte
442 * Instead of a payload, RTR indicates a remote request.
444 * We will use the spaces and line length to guess the format.
446 static int elm327_parse_frame(struct elmcan *elm, int len)
448 struct can_frame frame;
453 memset(&frame, 0, sizeof(frame));
455 /* Find first non-hex and non-space character:
456 * - In the simplest case, there is none.
457 * - For RTR frames, 'R' is the first non-hex character.
458 * - An error message may replace the end of the data line.
460 for (hexlen = 0; hexlen <= len; hexlen++) {
461 if (hex_to_bin(elm->rxbuf[hexlen]) < 0 &&
462 elm->rxbuf[hexlen] != ' ') {
467 /* If we accept stray characters coming in:
468 * Check for stray characters on a payload line.
469 * No idea what causes this.
471 if (accept_flaky_uart &&
473 !isdigit(elm->rxbuf[hexlen]) &&
474 !isupper(elm->rxbuf[hexlen]) &&
475 '<' != elm->rxbuf[hexlen] &&
476 ' ' != elm->rxbuf[hexlen]) {
477 /* The line is likely garbled anyway, so bail.
478 * The main code will restart listening.
480 elm327_kick_into_cmd_mode(elm);
484 /* Use spaces in CAN ID to distinguish 29 or 11 bit address length.
485 * No out-of-bounds access:
486 * We use the fact that we can always read from elm->rxbuf.
488 if (elm->rxbuf[2] == ' ' && elm->rxbuf[5] == ' ' &&
489 elm->rxbuf[8] == ' ' && elm->rxbuf[11] == ' ' &&
490 elm->rxbuf[13] == ' ') {
491 frame.can_id = CAN_EFF_FLAG;
493 } else if (elm->rxbuf[3] == ' ' && elm->rxbuf[5] == ' ') {
497 /* This is not a well-formatted data line.
498 * Assume it's an error message.
503 if (hexlen < datastart) {
504 /* The line is too short to be a valid frame hex dump.
505 * Something interrupted the hex dump or it is invalid.
510 /* From here on all chars up to buf[hexlen] are hex or spaces,
511 * at well-defined offsets.
514 /* Read CAN data length */
515 frame.can_dlc = (hex_to_bin(elm->rxbuf[datastart - 2]) << 0);
518 if (frame.can_id & CAN_EFF_FLAG) {
519 frame.can_id |= (hex_to_bin(elm->rxbuf[0]) << 28)
520 | (hex_to_bin(elm->rxbuf[1]) << 24)
521 | (hex_to_bin(elm->rxbuf[3]) << 20)
522 | (hex_to_bin(elm->rxbuf[4]) << 16)
523 | (hex_to_bin(elm->rxbuf[6]) << 12)
524 | (hex_to_bin(elm->rxbuf[7]) << 8)
525 | (hex_to_bin(elm->rxbuf[9]) << 4)
526 | (hex_to_bin(elm->rxbuf[10]) << 0);
528 frame.can_id |= (hex_to_bin(elm->rxbuf[0]) << 8)
529 | (hex_to_bin(elm->rxbuf[1]) << 4)
530 | (hex_to_bin(elm->rxbuf[2]) << 0);
533 /* Check for RTR frame */
534 if (elm->rxfill >= hexlen + 3 &&
535 !memcmp(&elm->rxbuf[hexlen], "RTR", 3)) {
536 frame.can_id |= CAN_RTR_FLAG;
539 /* Is the line long enough to hold the advertised payload?
540 * Note: RTR frames have a DLC, but no actual payload.
542 if (!(frame.can_id & CAN_RTR_FLAG) &&
543 (hexlen < frame.can_dlc * 3 + datastart)) {
544 /* Incomplete frame. */
546 /* Probably the ELM327's RS232 TX buffer was full.
547 * Emit an error frame and exit.
549 frame.can_id = CAN_ERR_FLAG | CAN_ERR_CRTL;
550 frame.can_dlc = CAN_ERR_DLC;
551 frame.data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
552 elm327_feed_frame_to_netdev(elm, &frame);
554 /* Signal failure to parse.
555 * The line will be re-parsed as an error line, which will fail.
556 * However, this will correctly drop the state machine back into
562 /* Parse the data nibbles. */
563 for (i = 0; i < frame.can_dlc; i++) {
564 frame.data[i] = (hex_to_bin(elm->rxbuf[datastart + 3*i]) << 4)
565 | (hex_to_bin(elm->rxbuf[datastart + 3*i + 1]));
568 /* Feed the frame to the network layer. */
569 elm327_feed_frame_to_netdev(elm, &frame);
574 static void elm327_parse_line(struct elmcan *elm, int len)
576 /* Skip empty lines */
580 /* Skip echo lines */
581 if (elm->drop_next_line) {
582 elm->drop_next_line = 0;
584 } else if (elm->rxbuf[0] == 'A' && elm->rxbuf[1] == 'T') {
588 /* Regular parsing */
589 switch (elm->state) {
591 if (elm327_parse_frame(elm, len)) {
592 /* Parse an error line. */
593 elm327_parse_error(elm, len);
596 elm327_kick_into_cmd_mode(elm);
604 static void elm327_handle_prompt(struct elmcan *elm)
606 struct can_frame *frame = &elm->can_frame;
607 char local_txbuf[20];
609 if (!elm->cmds_todo) {
610 /* Enter CAN monitor mode */
611 elm327_send(elm, "ATMA\r", 5);
612 elm->state = ELM_RECEIVING;
617 /* Reconfigure ELM327 step by step as indicated by elm->cmds_todo */
618 if (test_bit(TODO_INIT, &elm->cmds_todo)) {
619 strcpy(local_txbuf, *elm->next_init_cmd);
621 elm->next_init_cmd++;
622 if (!(*elm->next_init_cmd)) {
623 clear_bit(TODO_INIT, &elm->cmds_todo);
624 netdev_info(elm->dev, "Initialization finished.\n");
627 } else if (test_and_clear_bit(TODO_SILENT_MONITOR, &elm->cmds_todo)) {
628 sprintf(local_txbuf, "ATCSM%i\r",
629 !(!(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY)));
631 } else if (test_and_clear_bit(TODO_RESPONSES, &elm->cmds_todo)) {
632 sprintf(local_txbuf, "ATR%i\r",
633 !(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY));
635 } else if (test_and_clear_bit(TODO_CAN_CONFIG, &elm->cmds_todo)) {
636 sprintf(local_txbuf, "ATPC\r");
637 set_bit(TODO_CAN_CONFIG_PART2, &elm->cmds_todo);
639 } else if (test_and_clear_bit(TODO_CAN_CONFIG_PART2, &elm->cmds_todo)) {
640 sprintf(local_txbuf, "ATPB%04X\r",
643 } else if (test_and_clear_bit(TODO_CANID_29BIT_HIGH, &elm->cmds_todo)) {
644 sprintf(local_txbuf, "ATCP%02X\r",
645 (frame->can_id & CAN_EFF_MASK) >> 24);
647 } else if (test_and_clear_bit(TODO_CANID_29BIT_LOW, &elm->cmds_todo)) {
648 sprintf(local_txbuf, "ATSH%06X\r",
649 frame->can_id & CAN_EFF_MASK & ((1 << 24) - 1));
651 } else if (test_and_clear_bit(TODO_CANID_11BIT, &elm->cmds_todo)) {
652 sprintf(local_txbuf, "ATSH%03X\r",
653 frame->can_id & CAN_SFF_MASK);
655 } else if (test_and_clear_bit(TODO_CAN_DATA, &elm->cmds_todo)) {
656 if (frame->can_id & CAN_RTR_FLAG) {
657 /* Send an RTR frame. Their DLC is fixed.
658 * Some chips don't send them at all.
660 sprintf(local_txbuf, "ATRTR\r");
662 /* Send a regular CAN data frame */
665 for (i = 0; i < frame->can_dlc; i++) {
666 sprintf(&local_txbuf[2 * i], "%02X",
670 sprintf(&local_txbuf[2 * i], "\r");
673 elm->drop_next_line = 1;
674 elm->state = ELM_RECEIVING;
677 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], ELM327_SIZE_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 == ELM327_SIZE_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);
780 /***********************************************************************
783 * (takes elm->lock) *
784 ***********************************************************************/
786 /* Dummy needed to use can_rx_offload */
787 static struct sk_buff *elmcan_mailbox_read(struct can_rx_offload *offload,
788 unsigned int n, u32 *timestamp,
791 WARN_ON_ONCE(1); /* This function is a dummy, so don't call it! */
793 return ERR_PTR(-ENOBUFS);
796 static int elmcan_netdev_open(struct net_device *dev)
798 struct elmcan *elm = netdev_priv(dev);
801 spin_lock_bh(&elm->lock);
802 if (elm->hw_failure) {
803 netdev_err(elm->dev, "Refusing to open interface after a hardware fault has been detected.\n");
804 spin_unlock_bh(&elm->lock);
809 spin_unlock_bh(&elm->lock);
813 /* open_candev() checks for elm->can.bittiming.bitrate != 0 */
814 err = open_candev(dev);
816 spin_unlock_bh(&elm->lock);
821 spin_unlock_bh(&elm->lock);
823 elm->offload.mailbox_read = elmcan_mailbox_read;
824 err = can_rx_offload_add_fifo(dev, &elm->offload, ELM327_NAPI_WEIGHT);
830 can_rx_offload_enable(&elm->offload);
832 can_led_event(dev, CAN_LED_EVENT_OPEN);
833 elm->can.state = CAN_STATE_ERROR_ACTIVE;
834 netif_start_queue(dev);
839 static int elmcan_netdev_close(struct net_device *dev)
841 struct elmcan *elm = netdev_priv(dev);
843 netif_stop_queue(dev);
845 spin_lock_bh(&elm->lock);
847 /* Interrupt whatever we're doing right now */
848 elm327_send(elm, ELM327_MAGIC_STRING, 1);
850 /* Clear the wakeup bit, as the netdev will be down and thus
851 * the wakeup handler won't clear it
853 clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
855 spin_unlock_bh(&elm->lock);
857 flush_work(&elm->tx_work);
859 spin_unlock_bh(&elm->lock);
862 can_rx_offload_disable(&elm->offload);
863 elm->can.state = CAN_STATE_STOPPED;
864 can_rx_offload_del(&elm->offload);
866 can_led_event(dev, CAN_LED_EVENT_STOP);
871 /* Send a can_frame to a TTY. */
872 static netdev_tx_t elmcan_netdev_start_xmit(struct sk_buff *skb,
873 struct net_device *dev)
875 struct elmcan *elm = netdev_priv(dev);
876 struct can_frame *frame = (struct can_frame *)skb->data;
878 if (skb->len != sizeof(struct can_frame))
881 if (!netif_running(dev)) {
882 netdev_warn(elm->dev, "xmit: iface is down.\n");
886 /* BHs are already disabled, so no spin_lock_bh().
887 * See Documentation/networking/netdevices.txt
889 spin_lock(&elm->lock);
891 /* We shouldn't get here after a hardware fault:
892 * can_bus_off() calls netif_carrier_off()
894 WARN_ON_ONCE(elm->hw_failure);
898 elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY) {
899 spin_unlock(&elm->lock);
903 netif_stop_queue(dev);
905 elm327_send_frame(elm, frame);
906 spin_unlock(&elm->lock);
908 dev->stats.tx_packets++;
909 dev->stats.tx_bytes += frame->can_dlc;
911 can_led_event(dev, CAN_LED_EVENT_TX);
918 static const struct net_device_ops elmcan_netdev_ops = {
919 .ndo_open = elmcan_netdev_open,
920 .ndo_stop = elmcan_netdev_close,
921 .ndo_start_xmit = elmcan_netdev_start_xmit,
922 .ndo_change_mtu = can_change_mtu,
925 /***********************************************************************
928 * (takes elm->lock) *
929 ***********************************************************************/
931 /* Get a reference to our struct, taking into account locks/refcounts.
932 * This is to ensure ordering in case we are shutting down, and to ensure
933 * there is a refcount at all (otherwise tty->disc_data may be freed and
934 * before we increment the refcount).
935 * Use this for anything that can race against elmcan_ldisc_close().
937 static struct elmcan *get_elm(struct tty_struct *tty)
942 spin_lock_bh(&elmcan_discdata_lock);
943 elm = (struct elmcan *)tty->disc_data;
946 spin_unlock_bh(&elmcan_discdata_lock);
950 got_ref = atomic_inc_not_zero(&elm->refcount);
951 spin_unlock_bh(&elmcan_discdata_lock);
959 static void put_elm(struct elmcan *elm)
961 atomic_dec(&elm->refcount);
964 static bool elmcan_is_valid_rx_char(char c)
966 return (accept_flaky_uart ||
969 c == ELM327_MAGIC_CHAR ||
970 c == ELM327_READY_CHAR ||
981 /* Handle incoming ELM327 ASCII data.
982 * This will not be re-entered while running, but other ldisc
983 * functions may be called in parallel.
985 static void elmcan_ldisc_rx(struct tty_struct *tty,
986 const unsigned char *cp, char *fp, int count)
988 struct elmcan *elm = get_elm(tty);
993 spin_lock_bh(&elm->lock);
998 while (count-- && elm->rxfill < ELM327_SIZE_RXBUF) {
1000 netdev_err(elm->dev, "Error in received character stream. Check your wiring.");
1002 elm327_hw_failure(elm);
1007 /* Ignore NUL characters, which the PIC microcontroller may
1008 * inadvertently insert due to a known hardware bug.
1009 * See ELM327 documentation, which refers to a Microchip PIC
1013 /* Check for stray characters on the UART line.
1014 * Likely caused by bad hardware.
1016 if (!elmcan_is_valid_rx_char(*cp)) {
1017 netdev_err(elm->dev,
1018 "Received illegal character %02x.\n",
1020 elm327_hw_failure(elm);
1025 elm->rxbuf[elm->rxfill++] = *cp;
1032 netdev_err(elm->dev, "Receive buffer overflowed. Bad chip or wiring?");
1034 elm327_hw_failure(elm);
1039 elm327_parse_rxbuf(elm);
1042 spin_unlock_bh(&elm->lock);
1046 /* Write out remaining transmit buffer.
1047 * Scheduled when TTY is writable.
1049 static void elmcan_ldisc_tx_worker(struct work_struct *work)
1051 /* No need to use get_elm() here, as we'll always flush workers
1052 * before destroying the elmcan object.
1054 struct elmcan *elm = container_of(work, struct elmcan, tx_work);
1057 spin_lock_bh(&elm->lock);
1058 if (elm->hw_failure) {
1059 spin_unlock_bh(&elm->lock);
1063 if (!elm->tty || !netif_running(elm->dev)) {
1064 spin_unlock_bh(&elm->lock);
1068 if (elm->txleft <= 0) {
1069 /* Our TTY write buffer is empty:
1070 * Allow netdev to hand us another packet
1072 clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
1073 spin_unlock_bh(&elm->lock);
1074 netif_wake_queue(elm->dev);
1078 actual = elm->tty->ops->write(elm->tty, elm->txhead, elm->txleft);
1080 netdev_err(elm->dev,
1081 "Failed to write to tty %s.\n",
1083 elm327_hw_failure(elm);
1084 spin_unlock_bh(&elm->lock);
1088 elm->txleft -= actual;
1089 elm->txhead += actual;
1090 spin_unlock_bh(&elm->lock);
1093 /* Called by the driver when there's room for more data. */
1094 static void elmcan_ldisc_tx_wakeup(struct tty_struct *tty)
1096 struct elmcan *elm = get_elm(tty);
1101 schedule_work(&elm->tx_work);
1106 /* ELM327 can only handle bitrates that are integer divisors of 500 kHz,
1107 * or 7/8 of that. Divisors are 1 to 64.
1108 * Currently we don't implement support for 7/8 rates.
1110 static const u32 elmcan_bitrate_const[64] = {
1111 7812, 7936, 8064, 8196, 8333, 8474, 8620, 8771,
1112 8928, 9090, 9259, 9433, 9615, 9803, 10000, 10204,
1113 10416, 10638, 10869, 11111, 11363, 11627, 11904, 12195,
1114 12500, 12820, 13157, 13513, 13888, 14285, 14705, 15151,
1115 15625, 16129, 16666, 17241, 17857, 18518, 19230, 20000,
1116 20833, 21739, 22727, 23809, 25000, 26315, 27777, 29411,
1117 31250, 33333, 35714, 38461, 41666, 45454, 50000, 55555,
1118 62500, 71428, 83333, 100000, 125000, 166666, 250000, 500000
1121 /* Dummy needed to use bitrate_const */
1122 static int elmcan_do_set_bittiming(struct net_device *netdev)
1129 static int elmcan_ldisc_open(struct tty_struct *tty)
1131 struct net_device *dev;
1135 if (!capable(CAP_NET_ADMIN))
1138 if (!tty->ops->write)
1141 dev = alloc_candev(sizeof(struct elmcan), 0);
1144 elm = netdev_priv(dev);
1146 elm->txbuf = kmalloc(ELM327_SIZE_TXBUF, GFP_KERNEL);
1152 /* Configure TTY interface */
1153 tty->receive_room = 65536; /* We don't flow control */
1154 elm->txleft = 0; /* Clear TTY TX buffer */
1155 spin_lock_init(&elm->lock);
1156 atomic_set(&elm->refcount, 1);
1157 INIT_WORK(&elm->tx_work, elmcan_ldisc_tx_worker);
1159 /* Configure CAN metadata */
1160 elm->can.state = CAN_STATE_STOPPED;
1161 elm->can.bitrate_const = elmcan_bitrate_const;
1162 elm->can.bitrate_const_cnt = ARRAY_SIZE(elmcan_bitrate_const);
1163 elm->can.do_set_bittiming = elmcan_do_set_bittiming;
1164 elm->can.ctrlmode_supported = CAN_CTRLMODE_LISTENONLY;
1166 /* Configure netlink interface */
1168 dev->netdev_ops = &elmcan_netdev_ops;
1170 /* Mark ldisc channel as alive */
1172 tty->disc_data = elm;
1174 devm_can_led_init(elm->dev);
1177 err = register_candev(elm->dev);
1181 netdev_info(elm->dev, "elmcan on %s.\n", tty->name);
1187 free_candev(elm->dev);
1191 /* Close down an elmcan channel.
1192 * This means flushing out any pending queues, and then returning.
1193 * This call is serialized against other ldisc functions:
1194 * Once this is called, no other ldisc function of ours is entered.
1196 * We also use this function for a hangup event.
1198 static void elmcan_ldisc_close(struct tty_struct *tty)
1200 struct elmcan *elm = get_elm(tty);
1205 /* unregister_netdev() calls .ndo_stop() so we don't have to. */
1206 unregister_candev(elm->dev);
1208 /* Decrease the refcount twice, once for our own get_elm(),
1209 * and once to remove the count of 1 that we set in _open().
1210 * Once it reaches 0, we can safely destroy it.
1215 while (atomic_read(&elm->refcount) > 0)
1216 msleep_interruptible(10);
1218 /* At this point, all ldisc calls to us have become no-ops. */
1220 flush_work(&elm->tx_work);
1222 /* Mark channel as dead */
1223 spin_lock_bh(&elm->lock);
1224 tty->disc_data = NULL;
1226 spin_unlock_bh(&elm->lock);
1228 netdev_info(elm->dev, "elmcan off %s.\n", tty->name);
1231 free_candev(elm->dev);
1234 static int elmcan_ldisc_hangup(struct tty_struct *tty)
1236 elmcan_ldisc_close(tty);
1240 static int elmcan_ldisc_ioctl(struct tty_struct *tty, struct file *file,
1241 unsigned int cmd, unsigned long arg)
1243 struct elmcan *elm = get_elm(tty);
1251 tmp = strnlen(elm->dev->name, IFNAMSIZ - 1) + 1;
1252 if (copy_to_user((void __user *)arg, elm->dev->name, tmp)) {
1266 return tty_mode_ioctl(tty, file, cmd, arg);
1270 static struct tty_ldisc_ops elmcan_ldisc = {
1271 .owner = THIS_MODULE,
1273 .receive_buf = elmcan_ldisc_rx,
1274 .write_wakeup = elmcan_ldisc_tx_wakeup,
1275 .open = elmcan_ldisc_open,
1276 .close = elmcan_ldisc_close,
1277 .hangup = elmcan_ldisc_hangup,
1278 .ioctl = elmcan_ldisc_ioctl,
1281 static int __init elmcan_init(void)
1285 pr_info("ELM327 based best effort CAN interface driver\n");
1286 pr_info("This device is severely limited as a CAN interface, see documentation.\n");
1288 status = tty_register_ldisc(N_ELMCAN, &elmcan_ldisc);
1290 pr_err("Can't register line discipline\n");
1295 static void __exit elmcan_exit(void)
1297 /* This will only be called when all channels have been closed by
1298 * userspace - tty_ldisc.c takes care of the module's refcount.
1302 status = tty_unregister_ldisc(N_ELMCAN);
1304 pr_err("Can't unregister line discipline (error: %d)\n",
1308 module_init(elmcan_init);
1309 module_exit(elmcan_exit);