1 // SPDX-License-Identifier: GPL-2.0
2 /* elmcan.c - ELM327 based CAN interface driver
3 * (tty line discipline)
5 * This file is derived from linux/drivers/net/can/slcan.c
7 * elmcan.c Author : Max Staudt <max-linux@enpas.org>
8 * slcan.c Author : Oliver Hartkopp <socketcan@hartkopp.net>
9 * slip.c Authors : Laurence Culhane <loz@holmes.demon.co.uk>
10 * Fred N. van Kempen <waltje@uwalt.nl.mugnet.org>
14 #define pr_fmt(fmt) "[elmcan] " fmt
16 #include <linux/init.h>
17 #include <linux/module.h>
18 #include <linux/moduleparam.h>
20 #include <linux/atomic.h>
21 #include <linux/bitops.h>
22 #include <linux/ctype.h>
23 #include <linux/delay.h>
24 #include <linux/errno.h>
25 #include <linux/if_ether.h>
26 #include <linux/kernel.h>
27 #include <linux/list.h>
28 #include <linux/netdevice.h>
29 #include <linux/skbuff.h>
30 #include <linux/spinlock.h>
31 #include <linux/string.h>
32 #include <linux/tty.h>
33 #include <linux/workqueue.h>
35 #include <linux/can.h>
36 #include <linux/can/dev.h>
37 #include <linux/can/error.h>
38 #include <linux/can/led.h>
40 MODULE_ALIAS_LDISC(N_ELMCAN);
41 MODULE_DESCRIPTION("ELM327 based CAN interface");
42 MODULE_LICENSE("GPL");
43 MODULE_AUTHOR("Max Staudt <max-linux@enpas.org>");
45 /* If this is enabled, we'll try to make the best of the situation
46 * even if we receive unexpected characters on the line.
48 * Handle with care, it's likely your hardware is unreliable!
50 static bool accept_flaky_uart;
51 module_param_named(accept_flaky_uart, accept_flaky_uart, bool, 0444);
52 MODULE_PARM_DESC(accept_flaky_uart, "Don't bail at the first invalid character. Behavior undefined.");
54 /* Line discipline ID number */
59 #define ELM327_SIZE_RXBUF 256
60 #define ELM327_SIZE_TXBUF 32
62 #define ELM327_CAN_CONFIG_SEND_SFF 0x8000
63 #define ELM327_CAN_CONFIG_VARIABLE_DLC 0x4000
64 #define ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF 0x2000
65 #define ELM327_CAN_CONFIG_BAUDRATE_MULT_8_7 0x1000
67 #define ELM327_MAGIC_CHAR 'y'
68 #define ELM327_MAGIC_STRING "y"
69 #define ELM327_READY_CHAR '>'
71 /* Bits in elm->cmds_todo */
76 TODO_CANID_29BIT_HIGH,
77 TODO_CAN_CONFIG_PART2,
85 /* This must be the first member when using alloc_candev() */
88 /* TTY and netdev devices that we're bridging */
89 struct tty_struct *tty;
90 struct net_device *dev;
92 /* Per-channel lock */
95 /* Keep track of how many things are using this struct.
96 * Once it reaches 0, we are in the process of cleaning up,
97 * and new operations will be cancelled immediately.
98 * Use atomic_t rather than refcount_t because we deliberately
99 * decrement to 0, and refcount_dec() spills a WARN_ONCE in
104 /* Stop the channel on hardware failure.
105 * Once this is true, nothing will be sent to the TTY.
110 struct work_struct tx_work; /* Flushes TTY TX buffer */
111 unsigned char *txbuf;
112 unsigned char *txhead; /* Pointer to next TX byte */
113 int txleft; /* Bytes left to TX */
116 unsigned char rxbuf[ELM327_SIZE_RXBUF];
129 /* The CAN frame and config the ELM327 is sending/using,
130 * or will send/use after finishing all cmds_todo
132 struct can_frame can_frame;
133 unsigned short can_config;
134 unsigned long can_bitrate;
135 unsigned char can_bitrate_divisor;
136 int silent_monitoring;
138 /* Things we have yet to send */
139 char **next_init_cmd;
140 unsigned long cmds_todo;
143 /* A lock for all tty->disc_data handled by this ldisc.
144 * This is to prevent a case where tty->disc_data is set to NULL,
145 * yet someone is still trying to dereference it.
146 * Without this, we cannot do a clean shutdown.
148 static DEFINE_SPINLOCK(elmcan_discdata_lock);
150 static inline void elm327_hw_failure(struct elmcan *elm);
152 /***********************************************************************
153 * ELM327: Transmission *
155 * (all functions assume elm->lock taken) *
156 ***********************************************************************/
158 static void elm327_send(struct elmcan *elm, const void *buf, size_t len)
165 memcpy(elm->txbuf, buf, len);
167 /* Order of next two lines is *very* important.
168 * When we are sending a little amount of data,
169 * the transfer may be completed inside the ops->write()
170 * routine, because it's running with interrupts enabled.
171 * In this case we *never* got WRITE_WAKEUP event,
172 * if we did not request it before write operation.
173 * 14 Oct 1994 Dmitry Gorodchanin.
175 set_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
176 actual = elm->tty->ops->write(elm->tty, elm->txbuf, len);
179 "Failed to write to tty %s.\n",
181 elm327_hw_failure(elm);
185 elm->txleft = len - actual;
186 elm->txhead = elm->txbuf + actual;
189 /* Take the ELM327 out of almost any state and back into command mode.
190 * We send ELM327_MAGIC_CHAR which will either abort any running
191 * operation, or be echoed back to us in case we're already in command
194 static void elm327_kick_into_cmd_mode(struct elmcan *elm)
196 if (elm->state != ELM_GETMAGICCHAR && elm->state != ELM_GETPROMPT) {
197 elm327_send(elm, ELM327_MAGIC_STRING, 1);
199 elm->state = ELM_GETMAGICCHAR;
203 /* Schedule a CAN frame and necessary config changes to be sent to the TTY. */
204 static void elm327_send_frame(struct elmcan *elm, struct can_frame *frame)
206 /* Schedule any necessary changes in ELM327's CAN configuration */
207 if (elm->can_frame.can_id != frame->can_id) {
208 /* Set the new CAN ID for transmission. */
209 if ((frame->can_id & CAN_EFF_FLAG)
210 ^ (elm->can_frame.can_id & CAN_EFF_FLAG)) {
211 elm->can_config = (frame->can_id & CAN_EFF_FLAG
213 : ELM327_CAN_CONFIG_SEND_SFF)
214 | ELM327_CAN_CONFIG_VARIABLE_DLC
215 | ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF
216 | elm->can_bitrate_divisor;
218 set_bit(TODO_CAN_CONFIG, &elm->cmds_todo);
221 if (frame->can_id & CAN_EFF_FLAG) {
222 clear_bit(TODO_CANID_11BIT, &elm->cmds_todo);
223 set_bit(TODO_CANID_29BIT_LOW, &elm->cmds_todo);
224 set_bit(TODO_CANID_29BIT_HIGH, &elm->cmds_todo);
226 set_bit(TODO_CANID_11BIT, &elm->cmds_todo);
227 clear_bit(TODO_CANID_29BIT_LOW, &elm->cmds_todo);
228 clear_bit(TODO_CANID_29BIT_HIGH, &elm->cmds_todo);
232 /* Schedule the CAN frame itself. */
233 elm->can_frame = *frame;
234 set_bit(TODO_CAN_DATA, &elm->cmds_todo);
236 elm327_kick_into_cmd_mode(elm);
239 /***********************************************************************
240 * ELM327: Initialization sequence *
242 * (assumes elm->lock taken) *
243 ***********************************************************************/
245 static char *elm327_init_script[] = {
246 "AT WS\r", /* v1.0: Warm Start */
247 "AT PP FF OFF\r", /* v1.0: All Programmable Parameters Off */
248 "AT M0\r", /* v1.0: Memory Off */
249 "AT AL\r", /* v1.0: Allow Long messages */
250 "AT BI\r", /* v1.0: Bypass Initialization */
251 "AT CAF0\r", /* v1.0: CAN Auto Formatting Off */
252 "AT CFC0\r", /* v1.0: CAN Flow Control Off */
253 "AT CF 000\r", /* v1.0: Reset CAN ID Filter */
254 "AT CM 000\r", /* v1.0: Reset CAN ID Mask */
255 "AT E1\r", /* v1.0: Echo On */
256 "AT H1\r", /* v1.0: Headers On */
257 "AT L0\r", /* v1.0: Linefeeds Off */
258 "AT SH 7DF\r", /* v1.0: Set CAN sending ID to 0x7df */
259 "AT ST FF\r", /* v1.0: Set maximum Timeout for response after TX */
260 "AT AT0\r", /* v1.2: Adaptive Timing Off */
261 "AT D1\r", /* v1.3: Print DLC On */
262 "AT S1\r", /* v1.3: Spaces On */
263 "AT TP B\r", /* v1.0: Try Protocol B */
267 static void elm327_init(struct elmcan *elm)
269 elm->state = ELM_NOTINIT;
270 elm->can_frame.can_id = 0x7df;
272 elm->drop_next_line = 0;
274 /* We can only set the bitrate as a fraction of 500000.
275 * The bit timing constants in elmcan_bittiming_const will
276 * limit the user to the right values.
278 elm->can_bitrate_divisor = 500000 / elm->can.bittiming.bitrate;
279 elm->can_config = ELM327_CAN_CONFIG_SEND_SFF
280 | ELM327_CAN_CONFIG_VARIABLE_DLC
281 | ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF
282 | elm->can_bitrate_divisor;
284 /* Configure ELM327 and then start monitoring */
285 elm->next_init_cmd = &elm327_init_script[0];
286 set_bit(TODO_INIT, &elm->cmds_todo);
287 set_bit(TODO_SILENT_MONITOR, &elm->cmds_todo);
288 set_bit(TODO_RESPONSES, &elm->cmds_todo);
289 set_bit(TODO_CAN_CONFIG, &elm->cmds_todo);
291 elm327_kick_into_cmd_mode(elm);
294 /***********************************************************************
295 * ELM327: Reception -> netdev glue *
297 * (assumes elm->lock taken) *
298 ***********************************************************************/
300 static void elm327_feed_frame_to_netdev(struct elmcan *elm,
301 const struct can_frame *frame)
303 struct can_frame *cf;
306 if (!netif_running(elm->dev))
309 skb = alloc_can_skb(elm->dev, &cf);
314 memcpy(cf, frame, sizeof(struct can_frame));
316 elm->dev->stats.rx_packets++;
317 elm->dev->stats.rx_bytes += frame->can_dlc;
320 can_led_event(elm->dev, CAN_LED_EVENT_RX);
323 /***********************************************************************
324 * ELM327: "Panic" handler *
326 * (assumes elm->lock taken) *
327 ***********************************************************************/
329 /* Called when we're out of ideas and just want it all to end. */
330 static inline void elm327_hw_failure(struct elmcan *elm)
332 struct can_frame frame;
334 memset(&frame, 0, sizeof(frame));
335 frame.can_id = CAN_ERR_FLAG;
336 frame.can_dlc = CAN_ERR_DLC;
340 elm327_feed_frame_to_netdev(elm, &frame);
342 netdev_err(elm->dev, "ELM327 misbehaved. Blocking further communication.\n");
344 elm->hw_failure = true;
345 can_bus_off(elm->dev);
348 /***********************************************************************
349 * ELM327: Reception parser *
351 * (assumes elm->lock taken) *
352 ***********************************************************************/
354 static void elm327_parse_error(struct elmcan *elm, int len)
356 struct can_frame frame;
358 memset(&frame, 0, sizeof(frame));
359 frame.can_id = CAN_ERR_FLAG;
360 frame.can_dlc = CAN_ERR_DLC;
364 if (!memcmp(elm->rxbuf, "UNABLE TO CONNECT", 17)) {
366 "The ELM327 reported UNABLE TO CONNECT. Please check your setup.\n");
370 if (!memcmp(elm->rxbuf, "BUFFER FULL", 11)) {
371 /* This case will only happen if the last data
373 * Otherwise, elm327_parse_frame() will heuristically
374 * emit this error frame instead.
376 frame.can_id |= CAN_ERR_CRTL;
377 frame.data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
381 if (!memcmp(elm->rxbuf, "BUS ERROR", 9))
382 frame.can_id |= CAN_ERR_BUSERROR;
383 if (!memcmp(elm->rxbuf, "CAN ERROR", 9))
384 frame.can_id |= CAN_ERR_PROT;
385 if (!memcmp(elm->rxbuf, "<RX ERROR", 9))
386 frame.can_id |= CAN_ERR_PROT;
389 if (!memcmp(elm->rxbuf, "BUS BUSY", 8)) {
390 frame.can_id |= CAN_ERR_PROT;
391 frame.data[2] = CAN_ERR_PROT_OVERLOAD;
393 if (!memcmp(elm->rxbuf, "FB ERROR", 8)) {
394 frame.can_id |= CAN_ERR_PROT;
395 frame.data[2] = CAN_ERR_PROT_TX;
399 if (!memcmp(elm->rxbuf, "ERR", 3)) {
400 netdev_err(elm->dev, "The ELM327 reported an ERR%c%c. Please power it off and on again.\n",
401 elm->rxbuf[3], elm->rxbuf[4]);
402 frame.can_id |= CAN_ERR_CRTL;
406 /* Don't emit an error frame if we're unsure */
410 elm327_feed_frame_to_netdev(elm, &frame);
413 /* Parse CAN frames coming as ASCII from ELM327.
414 * They can be of various formats:
416 * 29-bit ID (EFF): 12 34 56 78 D PL PL PL PL PL PL PL PL
417 * 11-bit ID (!EFF): 123 D PL PL PL PL PL PL PL PL
419 * where D = DLC, PL = payload byte
421 * Instead of a payload, RTR indicates a remote request.
423 * We will use the spaces and line length to guess the format.
425 static int elm327_parse_frame(struct elmcan *elm, int len)
427 struct can_frame frame;
432 memset(&frame, 0, sizeof(frame));
434 /* Find first non-hex and non-space character:
435 * - In the simplest case, there is none.
436 * - For RTR frames, 'R' is the first non-hex character.
437 * - An error message may replace the end of the data line.
439 for (hexlen = 0; hexlen <= len; hexlen++) {
440 if (hex_to_bin(elm->rxbuf[hexlen]) < 0 &&
441 elm->rxbuf[hexlen] != ' ') {
446 /* If we accept stray characters coming in:
447 * Check for stray characters on a payload line.
448 * No idea what causes this.
450 if (accept_flaky_uart &&
452 !isdigit(elm->rxbuf[hexlen]) &&
453 !isupper(elm->rxbuf[hexlen]) &&
454 '<' != elm->rxbuf[hexlen] &&
455 ' ' != elm->rxbuf[hexlen]) {
456 /* The line is likely garbled anyway, so bail.
457 * The main code will restart listening.
459 elm327_kick_into_cmd_mode(elm);
463 /* Use spaces in CAN ID to distinguish 29 or 11 bit address length.
464 * No out-of-bounds access:
465 * We use the fact that we can always read from elm->rxbuf.
467 if (elm->rxbuf[2] == ' ' && elm->rxbuf[5] == ' ' &&
468 elm->rxbuf[8] == ' ' && elm->rxbuf[11] == ' ' &&
469 elm->rxbuf[13] == ' ') {
470 frame.can_id = CAN_EFF_FLAG;
472 } else if (elm->rxbuf[3] == ' ' && elm->rxbuf[5] == ' ') {
476 /* This is not a well-formatted data line.
477 * Assume it's an error message.
482 if (hexlen < datastart) {
483 /* The line is too short to be a valid frame hex dump.
484 * Something interrupted the hex dump or it is invalid.
489 /* From here on all chars up to buf[hexlen] are hex or spaces,
490 * at well-defined offsets.
493 /* Read CAN data length */
494 frame.can_dlc = (hex_to_bin(elm->rxbuf[datastart - 2]) << 0);
497 if (frame.can_id & CAN_EFF_FLAG) {
498 frame.can_id |= (hex_to_bin(elm->rxbuf[0]) << 28)
499 | (hex_to_bin(elm->rxbuf[1]) << 24)
500 | (hex_to_bin(elm->rxbuf[3]) << 20)
501 | (hex_to_bin(elm->rxbuf[4]) << 16)
502 | (hex_to_bin(elm->rxbuf[6]) << 12)
503 | (hex_to_bin(elm->rxbuf[7]) << 8)
504 | (hex_to_bin(elm->rxbuf[9]) << 4)
505 | (hex_to_bin(elm->rxbuf[10]) << 0);
507 frame.can_id |= (hex_to_bin(elm->rxbuf[0]) << 8)
508 | (hex_to_bin(elm->rxbuf[1]) << 4)
509 | (hex_to_bin(elm->rxbuf[2]) << 0);
512 /* Check for RTR frame */
513 if (elm->rxfill >= hexlen + 3 &&
514 !memcmp(&elm->rxbuf[hexlen], "RTR", 3)) {
515 frame.can_id |= CAN_RTR_FLAG;
518 /* Is the line long enough to hold the advertised payload?
519 * Note: RTR frames have a DLC, but no actual payload.
521 if (!(frame.can_id & CAN_RTR_FLAG) &&
522 (hexlen < frame.can_dlc * 3 + datastart)) {
523 /* Incomplete frame. */
525 /* Probably the ELM327's RS232 TX buffer was full.
526 * Emit an error frame and exit.
528 frame.can_id = CAN_ERR_FLAG | CAN_ERR_CRTL;
529 frame.can_dlc = CAN_ERR_DLC;
530 frame.data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
531 elm327_feed_frame_to_netdev(elm, &frame);
533 /* Signal failure to parse.
534 * The line will be re-parsed as an error line, which will fail.
535 * However, this will correctly drop the state machine back into
541 /* Parse the data nibbles. */
542 for (i = 0; i < frame.can_dlc; i++) {
543 frame.data[i] = (hex_to_bin(elm->rxbuf[datastart + 3*i]) << 4)
544 | (hex_to_bin(elm->rxbuf[datastart + 3*i + 1]));
547 /* Feed the frame to the network layer. */
548 elm327_feed_frame_to_netdev(elm, &frame);
553 static void elm327_parse_line(struct elmcan *elm, int len)
555 /* Skip empty lines */
559 /* Skip echo lines */
560 if (elm->drop_next_line) {
561 elm->drop_next_line = 0;
563 } else if (elm->rxbuf[0] == 'A' && elm->rxbuf[1] == 'T') {
567 /* Regular parsing */
568 switch (elm->state) {
570 if (elm327_parse_frame(elm, len)) {
571 /* Parse an error line. */
572 elm327_parse_error(elm, len);
575 elm327_kick_into_cmd_mode(elm);
583 static void elm327_handle_prompt(struct elmcan *elm)
585 struct can_frame *frame = &elm->can_frame;
586 char local_txbuf[20];
588 if (!elm->cmds_todo) {
589 /* Enter CAN monitor mode */
590 elm327_send(elm, "ATMA\r", 5);
591 elm->state = ELM_RECEIVING;
596 /* Reconfigure ELM327 step by step as indicated by elm->cmds_todo */
597 if (test_bit(TODO_INIT, &elm->cmds_todo)) {
598 strcpy(local_txbuf, *elm->next_init_cmd);
600 elm->next_init_cmd++;
601 if (!(*elm->next_init_cmd)) {
602 clear_bit(TODO_INIT, &elm->cmds_todo);
603 netdev_info(elm->dev, "Initialization finished.\n");
606 } else if (test_and_clear_bit(TODO_SILENT_MONITOR, &elm->cmds_todo)) {
607 sprintf(local_txbuf, "ATCSM%i\r",
608 !(!(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY)));
610 } else if (test_and_clear_bit(TODO_RESPONSES, &elm->cmds_todo)) {
611 sprintf(local_txbuf, "ATR%i\r",
612 !(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY));
614 } else if (test_and_clear_bit(TODO_CAN_CONFIG, &elm->cmds_todo)) {
615 sprintf(local_txbuf, "ATPC\r");
616 set_bit(TODO_CAN_CONFIG_PART2, &elm->cmds_todo);
618 } else if (test_and_clear_bit(TODO_CAN_CONFIG_PART2, &elm->cmds_todo)) {
619 sprintf(local_txbuf, "ATPB%04X\r",
622 } else if (test_and_clear_bit(TODO_CANID_29BIT_HIGH, &elm->cmds_todo)) {
623 sprintf(local_txbuf, "ATCP%02X\r",
624 (frame->can_id & CAN_EFF_MASK) >> 24);
626 } else if (test_and_clear_bit(TODO_CANID_29BIT_LOW, &elm->cmds_todo)) {
627 sprintf(local_txbuf, "ATSH%06X\r",
628 frame->can_id & CAN_EFF_MASK & ((1 << 24) - 1));
630 } else if (test_and_clear_bit(TODO_CANID_11BIT, &elm->cmds_todo)) {
631 sprintf(local_txbuf, "ATSH%03X\r",
632 frame->can_id & CAN_SFF_MASK);
634 } else if (test_and_clear_bit(TODO_CAN_DATA, &elm->cmds_todo)) {
635 if (frame->can_id & CAN_RTR_FLAG) {
636 /* Send an RTR frame. Their DLC is fixed.
637 * Some chips don't send them at all.
639 sprintf(local_txbuf, "ATRTR\r");
641 /* Send a regular CAN data frame */
644 for (i = 0; i < frame->can_dlc; i++) {
645 sprintf(&local_txbuf[2 * i], "%02X",
649 sprintf(&local_txbuf[2 * i], "\r");
652 elm->drop_next_line = 1;
653 elm->state = ELM_RECEIVING;
656 elm327_send(elm, local_txbuf, strlen(local_txbuf));
659 static bool elm327_is_ready_char(char c)
661 /* Bits 0xc0 are sometimes set (randomly), hence the mask.
662 * Probably bad hardware.
664 return (c & 0x3f) == ELM327_READY_CHAR;
667 static void elm327_drop_bytes(struct elmcan *elm, int i)
669 memmove(&elm->rxbuf[0], &elm->rxbuf[i], ELM327_SIZE_RXBUF - i);
673 static void elm327_parse_rxbuf(struct elmcan *elm)
677 switch (elm->state) {
682 case ELM_GETMAGICCHAR:
684 /* Wait for 'y' or '>' */
687 for (i = 0; i < elm->rxfill; i++) {
688 if (elm->rxbuf[i] == ELM327_MAGIC_CHAR) {
689 elm327_send(elm, "\r", 1);
690 elm->state = ELM_GETPROMPT;
693 } else if (elm327_is_ready_char(elm->rxbuf[i])) {
694 elm327_send(elm, ELM327_MAGIC_STRING, 1);
700 elm327_drop_bytes(elm, i);
707 if (elm327_is_ready_char(elm->rxbuf[elm->rxfill - 1]))
708 elm327_handle_prompt(elm);
714 /* Find <CR> delimiting feedback lines. */
716 (len < elm->rxfill) && (elm->rxbuf[len] != '\r');
721 if (len == ELM327_SIZE_RXBUF) {
722 /* Line exceeds buffer. It's probably all garbage.
723 * Did we even connect at the right baud rate?
726 "RX buffer overflow. Faulty ELM327 or UART?\n");
727 elm327_hw_failure(elm);
729 } else if (len == elm->rxfill) {
730 if (elm327_is_ready_char(elm->rxbuf[elm->rxfill - 1])) {
731 /* The ELM327's AT ST response timeout ran out,
732 * so we got a prompt.
733 * Clear RX buffer and restart listening.
737 elm327_handle_prompt(elm);
741 /* No <CR> found - we haven't received a full line yet.
742 * Wait for more data.
747 /* We have a full line to parse. */
748 elm327_parse_line(elm, len);
750 /* Remove parsed data from RX buffer. */
751 elm327_drop_bytes(elm, len + 1);
753 /* More data to parse? */
755 elm327_parse_rxbuf(elm);
759 /***********************************************************************
762 * (takes elm->lock) *
763 ***********************************************************************/
765 static int elmcan_netdev_open(struct net_device *dev)
767 struct elmcan *elm = netdev_priv(dev);
770 spin_lock_bh(&elm->lock);
771 if (elm->hw_failure) {
772 netdev_err(elm->dev, "Refusing to open interface after a hardware fault has been detected.\n");
773 spin_unlock_bh(&elm->lock);
778 spin_unlock_bh(&elm->lock);
782 /* open_candev() checks for elm->can.bittiming.bitrate != 0 */
783 err = open_candev(dev);
785 spin_unlock_bh(&elm->lock);
790 spin_unlock_bh(&elm->lock);
792 can_led_event(dev, CAN_LED_EVENT_OPEN);
793 elm->can.state = CAN_STATE_ERROR_ACTIVE;
794 netif_start_queue(dev);
799 static int elmcan_netdev_close(struct net_device *dev)
801 struct elmcan *elm = netdev_priv(dev);
803 spin_lock_bh(&elm->lock);
805 /* Interrupt whatever we're doing right now */
806 elm327_send(elm, ELM327_MAGIC_STRING, 1);
808 /* Clear the wakeup bit, as the netdev will be down and thus
809 * the wakeup handler won't clear it
811 clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
813 spin_unlock_bh(&elm->lock);
815 flush_work(&elm->tx_work);
817 spin_unlock_bh(&elm->lock);
820 elm->can.state = CAN_STATE_STOPPED;
821 netif_stop_queue(dev);
823 can_led_event(dev, CAN_LED_EVENT_STOP);
828 /* Send a can_frame to a TTY. */
829 static netdev_tx_t elmcan_netdev_start_xmit(struct sk_buff *skb,
830 struct net_device *dev)
832 struct elmcan *elm = netdev_priv(dev);
833 struct can_frame *frame = (struct can_frame *)skb->data;
835 if (skb->len != sizeof(struct can_frame))
838 if (!netif_running(dev)) {
839 netdev_warn(elm->dev, "xmit: iface is down.\n");
843 /* BHs are already disabled, so no spin_lock_bh().
844 * See Documentation/networking/netdevices.txt
846 spin_lock(&elm->lock);
848 /* We shouldn't get here after a hardware fault:
849 * can_bus_off() calls netif_carrier_off()
851 WARN_ON(elm->hw_failure);
855 elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY) {
856 spin_unlock(&elm->lock);
860 netif_stop_queue(dev);
862 elm327_send_frame(elm, frame);
863 spin_unlock(&elm->lock);
865 dev->stats.tx_packets++;
866 dev->stats.tx_bytes += frame->can_dlc;
868 can_led_event(dev, CAN_LED_EVENT_TX);
875 static const struct net_device_ops elmcan_netdev_ops = {
876 .ndo_open = elmcan_netdev_open,
877 .ndo_stop = elmcan_netdev_close,
878 .ndo_start_xmit = elmcan_netdev_start_xmit,
879 .ndo_change_mtu = can_change_mtu,
882 /***********************************************************************
885 * (takes elm->lock) *
886 ***********************************************************************/
888 /* Get a reference to our struct, taking into account locks/refcounts.
889 * This is to ensure ordering in case we are shutting down, and to ensure
890 * there is a refcount at all (otherwise tty->disc_data may be freed and
891 * before we increment the refcount).
892 * Use this for anything that can race against elmcan_ldisc_close().
894 static struct elmcan *get_elm(struct tty_struct *tty)
899 spin_lock_bh(&elmcan_discdata_lock);
900 elm = (struct elmcan *)tty->disc_data;
903 spin_unlock_bh(&elmcan_discdata_lock);
907 got_ref = atomic_inc_not_zero(&elm->refcount);
908 spin_unlock_bh(&elmcan_discdata_lock);
916 static void put_elm(struct elmcan *elm)
918 atomic_dec(&elm->refcount);
921 static bool elmcan_is_valid_rx_char(char c)
923 return (accept_flaky_uart ||
926 c == ELM327_MAGIC_CHAR ||
927 c == ELM327_READY_CHAR ||
938 /* Handle incoming ELM327 ASCII data.
939 * This will not be re-entered while running, but other ldisc
940 * functions may be called in parallel.
942 static void elmcan_ldisc_rx(struct tty_struct *tty,
943 const unsigned char *cp, char *fp, int count)
945 struct elmcan *elm = get_elm(tty);
950 spin_lock_bh(&elm->lock);
955 while (count-- && elm->rxfill < ELM327_SIZE_RXBUF) {
957 netdev_err(elm->dev, "Error in received character stream. Check your wiring.");
959 elm327_hw_failure(elm);
964 /* Ignore NUL characters, which the PIC microcontroller may
965 * inadvertently insert due to a known hardware bug.
966 * See ELM327 documentation, which refers to a Microchip PIC
970 /* Check for stray characters on the UART line.
971 * Likely caused by bad hardware.
973 if (!elmcan_is_valid_rx_char(*cp)) {
975 "Received illegal character %02x.\n",
977 elm327_hw_failure(elm);
982 elm->rxbuf[elm->rxfill++] = *cp;
989 netdev_err(elm->dev, "Receive buffer overflowed. Bad chip or wiring?");
991 elm327_hw_failure(elm);
996 elm327_parse_rxbuf(elm);
999 spin_unlock_bh(&elm->lock);
1003 /* Write out remaining transmit buffer.
1004 * Scheduled when TTY is writable.
1006 static void elmcan_ldisc_tx_worker(struct work_struct *work)
1008 /* No need to use get_elm() here, as we'll always flush workers
1009 * before destroying the elmcan object.
1011 struct elmcan *elm = container_of(work, struct elmcan, tx_work);
1014 spin_lock_bh(&elm->lock);
1015 if (elm->hw_failure) {
1016 spin_unlock_bh(&elm->lock);
1020 if (!elm->tty || !netif_running(elm->dev)) {
1021 spin_unlock_bh(&elm->lock);
1025 if (elm->txleft <= 0) {
1026 /* Our TTY write buffer is empty:
1027 * Allow netdev to hand us another packet
1029 clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
1030 spin_unlock_bh(&elm->lock);
1031 netif_wake_queue(elm->dev);
1035 actual = elm->tty->ops->write(elm->tty, elm->txhead, elm->txleft);
1037 netdev_err(elm->dev,
1038 "Failed to write to tty %s.\n",
1040 elm327_hw_failure(elm);
1041 spin_unlock_bh(&elm->lock);
1045 elm->txleft -= actual;
1046 elm->txhead += actual;
1047 spin_unlock_bh(&elm->lock);
1050 /* Called by the driver when there's room for more data. */
1051 static void elmcan_ldisc_tx_wakeup(struct tty_struct *tty)
1053 struct elmcan *elm = get_elm(tty);
1058 schedule_work(&elm->tx_work);
1063 /* ELM327 can only handle bitrates that are integer divisors of 500 kHz,
1064 * or 7/8 of that. Divisors are 1 to 64.
1065 * Currently we don't implement support for 7/8 rates.
1067 static const u32 elmcan_bitrate_const[64] = {
1068 7812, 7936, 8064, 8196, 8333, 8474, 8620, 8771,
1069 8928, 9090, 9259, 9433, 9615, 9803, 10000, 10204,
1070 10416, 10638, 10869, 11111, 11363, 11627, 11904, 12195,
1071 12500, 12820, 13157, 13513, 13888, 14285, 14705, 15151,
1072 15625, 16129, 16666, 17241, 17857, 18518, 19230, 20000,
1073 20833, 21739, 22727, 23809, 25000, 26315, 27777, 29411,
1074 31250, 33333, 35714, 38461, 41666, 45454, 50000, 55555,
1075 62500, 71428, 83333, 100000, 125000, 166666, 250000, 500000
1078 /* Dummy needed to use bitrate_const */
1079 static int elmcan_do_set_bittiming(struct net_device *netdev)
1086 static int elmcan_ldisc_open(struct tty_struct *tty)
1088 struct net_device *dev;
1092 if (!capable(CAP_NET_ADMIN))
1095 if (!tty->ops->write)
1098 dev = alloc_candev(sizeof(struct elmcan), 0);
1101 elm = netdev_priv(dev);
1103 elm->txbuf = kmalloc(ELM327_SIZE_TXBUF, GFP_KERNEL);
1109 /* Configure TTY interface */
1110 tty->receive_room = 65536; /* We don't flow control */
1111 elm->txleft = 0; /* Clear TTY TX buffer */
1112 spin_lock_init(&elm->lock);
1113 atomic_set(&elm->refcount, 1);
1114 INIT_WORK(&elm->tx_work, elmcan_ldisc_tx_worker);
1116 /* Configure CAN metadata */
1117 elm->can.state = CAN_STATE_STOPPED;
1118 elm->can.bitrate_const = elmcan_bitrate_const;
1119 elm->can.bitrate_const_cnt = ARRAY_SIZE(elmcan_bitrate_const);
1120 elm->can.do_set_bittiming = elmcan_do_set_bittiming;
1121 elm->can.ctrlmode_supported = CAN_CTRLMODE_LISTENONLY;
1123 /* Configure netlink interface */
1125 dev->netdev_ops = &elmcan_netdev_ops;
1127 /* Mark ldisc channel as alive */
1129 tty->disc_data = elm;
1131 devm_can_led_init(elm->dev);
1134 err = register_candev(elm->dev);
1138 netdev_info(elm->dev, "elmcan on %s.\n", tty->name);
1144 free_candev(elm->dev);
1148 /* Close down an elmcan channel.
1149 * This means flushing out any pending queues, and then returning.
1150 * This call is serialized against other ldisc functions:
1151 * Once this is called, no other ldisc function of ours is entered.
1153 * We also use this function for a hangup event.
1155 static void elmcan_ldisc_close(struct tty_struct *tty)
1157 struct elmcan *elm = get_elm(tty);
1162 /* unregister_netdev() calls .ndo_stop() so we don't have to. */
1163 unregister_candev(elm->dev);
1165 /* Decrease the refcount twice, once for our own get_elm(),
1166 * and once to remove the count of 1 that we set in _open().
1167 * Once it reaches 0, we can safely destroy it.
1172 while (atomic_read(&elm->refcount) > 0)
1173 msleep_interruptible(10);
1175 /* At this point, all ldisc calls to us have become no-ops. */
1177 flush_work(&elm->tx_work);
1179 /* Mark channel as dead */
1180 spin_lock_bh(&elm->lock);
1181 tty->disc_data = NULL;
1183 spin_unlock_bh(&elm->lock);
1185 netdev_info(elm->dev, "elmcan off %s.\n", tty->name);
1188 free_candev(elm->dev);
1191 static int elmcan_ldisc_hangup(struct tty_struct *tty)
1193 elmcan_ldisc_close(tty);
1197 static int elmcan_ldisc_ioctl(struct tty_struct *tty, struct file *file,
1198 unsigned int cmd, unsigned long arg)
1200 struct elmcan *elm = get_elm(tty);
1208 tmp = strnlen(elm->dev->name, IFNAMSIZ - 1) + 1;
1209 if (copy_to_user((void __user *)arg, elm->dev->name, tmp)) {
1223 return tty_mode_ioctl(tty, file, cmd, arg);
1227 static struct tty_ldisc_ops elmcan_ldisc = {
1228 .owner = THIS_MODULE,
1230 .receive_buf = elmcan_ldisc_rx,
1231 .write_wakeup = elmcan_ldisc_tx_wakeup,
1232 .open = elmcan_ldisc_open,
1233 .close = elmcan_ldisc_close,
1234 .hangup = elmcan_ldisc_hangup,
1235 .ioctl = elmcan_ldisc_ioctl,
1238 static int __init elmcan_init(void)
1242 pr_info("ELM327 based best-effort CAN interface driver\n");
1243 pr_info("This device is severely limited as a CAN interface, see documentation.\n");
1245 status = tty_register_ldisc(N_ELMCAN, &elmcan_ldisc);
1247 pr_err("can't register line discipline\n");
1252 static void __exit elmcan_exit(void)
1254 /* This will only be called when all channels have been closed by
1255 * userspace - tty_ldisc.c takes care of the module's refcount.
1259 status = tty_unregister_ldisc(N_ELMCAN);
1261 pr_err("Can't unregister line discipline (error: %d)\n",
1265 module_init(elmcan_init);
1266 module_exit(elmcan_exit);