2 * elmcan.c - ELM327 based CAN interface driver
3 * (tty line discipline)
5 * This file is derived from linux/drivers/net/can/slcan.c
7 * elmcan.c Author : Max Staudt <elmcan@enpas.org>
8 * slcan.c Author : Oliver Hartkopp <socketcan@hartkopp.net>
9 * slip.c Authors : Laurence Culhane <loz@holmes.demon.co.uk>
10 * Fred N. van Kempen <waltje@uwalt.nl.mugnet.org>
12 * SPDX-License-Identifier: GPL-2.0
16 #define pr_fmt(fmt) "[elmcan] " fmt
19 #include <linux/init.h>
20 #include <linux/module.h>
21 #include <linux/moduleparam.h>
23 #include <linux/atomic.h>
24 #include <linux/bitops.h>
25 #include <linux/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 /* Line discipline ID number */
53 #define ELM327_CAN_CONFIG_SEND_SFF 0x8000
54 #define ELM327_CAN_CONFIG_VARIABLE_DLC 0x4000
55 #define ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF 0x2000
56 #define ELM327_CAN_CONFIG_BAUDRATE_MULT_8_7 0x1000
58 #define ELM327_MAGIC_CHAR 'y'
59 #define ELM327_MAGIC_STRING "y"
60 #define ELM327_READY_CHAR '>'
63 /* Bits in elm->cmds_todo */
65 ELM_TODO_CAN_DATA = 0,
67 ELM_TODO_CANID_29BIT_LOW,
68 ELM_TODO_CANID_29BIT_HIGH,
71 ELM_TODO_SILENT_MONITOR,
77 /* This must be the first member when using alloc_candev() */
80 /* TTY and netdev devices that we're bridging */
81 struct tty_struct *tty;
82 struct net_device *dev;
84 /* Per-channel lock */
87 /* Keep track of how many things are using this struct.
88 * Once it reaches 0, we are in the process of cleaning up,
89 * and new operations will be cancelled immediately.
90 * Use atomic_t rather than refcount_t because we deliberately
91 * decrement to 0, and refcount_dec() spills a WARN_ONCE in
96 /* Stop the channel on hardware failure.
97 * Once this is true, nothing will be sent to the TTY.
102 struct work_struct tx_work; /* Flushes TTY TX buffer */
103 unsigned char txbuf[32];
104 unsigned char *txhead; /* Pointer to next TX byte */
105 int txleft; /* Bytes left to TX */
108 unsigned char rxbuf[256];
121 /* The CAN frame and config the ELM327 is sending/using,
122 * or will send/use after finishing all cmds_todo */
123 struct can_frame can_frame;
124 unsigned short can_config;
125 unsigned long can_bitrate;
126 unsigned char can_bitrate_divisor;
127 int silent_monitoring;
129 /* Things we have yet to send */
130 char **next_init_cmd;
131 unsigned long cmds_todo;
135 /* A lock for all tty->disc_data handled by this ldisc.
136 * This is to prevent a case where tty->disc_data is set to NULL,
137 * yet someone is still trying to dereference it.
138 * Without this, we cannot do a clean shutdown.
140 static DEFINE_SPINLOCK(elmcan_discdata_lock);
143 static inline void elm327_hw_failure(struct elmcan *elm);
147 /************************************************************************
148 * ELM327: Transmission *
150 * (all functions assume elm->lock taken) *
151 ************************************************************************/
153 static void elm327_send(struct elmcan *elm, const void *buf, size_t len)
157 if (elm->hw_failure) {
161 memcpy(elm->txbuf, buf, len);
163 /* Order of next two lines is *very* important.
164 * When we are sending a little amount of data,
165 * the transfer may be completed inside the ops->write()
166 * routine, because it's running with interrupts enabled.
167 * In this case we *never* got WRITE_WAKEUP event,
168 * if we did not request it before write operation.
169 * 14 Oct 1994 Dmitry Gorodchanin.
171 set_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
172 actual = elm->tty->ops->write(elm->tty, elm->txbuf, len);
174 netdev_err(elm->dev, "Failed to write to tty %s.\n", elm->tty->name);
175 elm327_hw_failure(elm);
179 elm->txleft = len - actual;
180 elm->txhead = elm->txbuf + actual;
185 * Take the ELM327 out of almost any state and back into command mode
187 * Assumes elm->lock taken.
189 static void elm327_kick_into_cmd_mode(struct elmcan *elm)
191 if (elm->state != ELM_GETMAGICCHAR && elm->state != ELM_GETPROMPT) {
192 elm327_send(elm, ELM327_MAGIC_STRING, 1);
194 elm->state = ELM_GETMAGICCHAR;
201 * Schedule a CAN frame, and any necessary config changes,
202 * to be sent down the TTY.
204 * Assumes elm->lock taken.
206 static void elm327_send_frame(struct elmcan *elm, struct can_frame *frame)
208 /* Schedule any necessary changes in ELM327's CAN configuration */
209 if (elm->can_frame.can_id != frame->can_id) {
210 /* Set the new CAN ID for transmission. */
211 if ((frame->can_id & CAN_EFF_FLAG) ^ (elm->can_frame.can_id & CAN_EFF_FLAG)) {
212 elm->can_config = (frame->can_id & CAN_EFF_FLAG ? 0 : ELM327_CAN_CONFIG_SEND_SFF)
213 | ELM327_CAN_CONFIG_VARIABLE_DLC
214 | ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF
215 | elm->can_bitrate_divisor;
217 set_bit(ELM_TODO_CAN_CONFIG, &elm->cmds_todo);
220 if (frame->can_id & CAN_EFF_FLAG) {
221 clear_bit(ELM_TODO_CANID_11BIT, &elm->cmds_todo);
222 set_bit(ELM_TODO_CANID_29BIT_LOW, &elm->cmds_todo);
223 set_bit(ELM_TODO_CANID_29BIT_HIGH, &elm->cmds_todo);
225 set_bit(ELM_TODO_CANID_11BIT, &elm->cmds_todo);
226 clear_bit(ELM_TODO_CANID_29BIT_LOW, &elm->cmds_todo);
227 clear_bit(ELM_TODO_CANID_29BIT_HIGH, &elm->cmds_todo);
231 /* Schedule the CAN frame itself. */
232 elm->can_frame = *frame;
233 set_bit(ELM_TODO_CAN_DATA, &elm->cmds_todo);
235 elm327_kick_into_cmd_mode(elm);
240 /************************************************************************
241 * ELM327: Initialization sequence *
243 * (assumes elm->lock taken) *
244 ************************************************************************/
246 static char *elm327_init_script[] = {
247 "AT WS\r", /* v1.0: Warm Start */
248 "AT PP FF OFF\r", /* v1.0: All Programmable Parameters Off */
249 "AT M0\r", /* v1.0: Memory Off */
250 "AT AL\r", /* v1.0: Allow Long messages */
251 "AT BI\r", /* v1.0: Bypass Initialization */
252 "AT CAF0\r", /* v1.0: CAN Auto Formatting Off */
253 "AT CFC0\r", /* v1.0: CAN Flow Control Off */
254 "AT CF 000\r", /* v1.0: Reset CAN ID Filter */
255 "AT CM 000\r", /* v1.0: Reset CAN ID Mask */
256 "AT E1\r", /* v1.0: Echo On */
257 "AT H1\r", /* v1.0: Headers On */
258 "AT L0\r", /* v1.0: Linefeeds Off */
259 "AT SH 7DF\r", /* v1.0: Set CAN sending ID to 0x7df */
260 "AT ST FF\r", /* v1.0: Set maximum Timeout for response after TX */
261 "AT AT0\r", /* v1.2: Adaptive Timing Off */
262 "AT D1\r", /* v1.3: Print DLC On */
263 "AT S1\r", /* v1.3: Spaces On */
264 "AT TP B\r", /* v1.0: Try Protocol B */
269 static void elm327_init(struct elmcan *elm)
271 elm->state = ELM_NOTINIT;
272 elm->can_frame.can_id = 0x7df;
274 elm->drop_next_line = 0;
276 /* We can only set the bitrate as a fraction of 500000.
277 * The bit timing constants in elmcan_bittiming_const will
278 * limit the user to the right values.
280 elm->can_bitrate_divisor = 500000 / elm->can.bittiming.bitrate;
281 elm->can_config = ELM327_CAN_CONFIG_SEND_SFF
282 | ELM327_CAN_CONFIG_VARIABLE_DLC
283 | ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF
284 | elm->can_bitrate_divisor;
286 /* Configure ELM327 and then start monitoring */
287 elm->next_init_cmd = &elm327_init_script[0];
288 set_bit(ELM_TODO_INIT, &elm->cmds_todo);
289 set_bit(ELM_TODO_SILENT_MONITOR, &elm->cmds_todo);
290 set_bit(ELM_TODO_RESPONSES, &elm->cmds_todo);
291 set_bit(ELM_TODO_CAN_CONFIG, &elm->cmds_todo);
293 elm327_kick_into_cmd_mode(elm);
298 /************************************************************************
299 * ELM327: Reception -> netdev glue *
301 * (assumes elm->lock taken) *
302 ************************************************************************/
304 static void elm327_feed_frame_to_netdev(struct elmcan *elm, const struct can_frame *frame)
306 struct can_frame *cf;
309 if (!netif_running(elm->dev)) {
313 skb = alloc_can_skb(elm->dev, &cf);
318 memcpy(cf, frame, sizeof(struct can_frame));
320 elm->dev->stats.rx_packets++;
321 elm->dev->stats.rx_bytes += frame->can_dlc;
324 can_led_event(elm->dev, CAN_LED_EVENT_RX);
329 /************************************************************************
330 * ELM327: "Panic" handler *
332 * (assumes elm->lock taken) *
333 ************************************************************************/
335 /* Called when we're out of ideas and just want it all to end. */
336 static inline void elm327_hw_failure(struct elmcan *elm)
338 struct can_frame frame = {0};
340 frame.can_id = CAN_ERR_FLAG;
341 frame.can_dlc = CAN_ERR_DLC;
345 elm327_feed_frame_to_netdev(elm, &frame);
347 netdev_err(elm->dev, "ELM327 misbehaved. "
348 "Blocking further communication.\n");
350 elm->hw_failure = true;
351 can_bus_off(elm->dev);
356 /************************************************************************
357 * ELM327: Reception parser *
359 * (assumes elm->lock taken) *
360 ************************************************************************/
362 static void elm327_parse_error(struct elmcan *elm, int len)
364 struct can_frame frame = {0};
366 frame.can_id = CAN_ERR_FLAG;
367 frame.can_dlc = CAN_ERR_DLC;
371 if (!memcmp(elm->rxbuf, "UNABLE TO CONNECT", 17)) {
372 netdev_err(elm->dev, "The ELM327 reported UNABLE TO CONNECT. Please check your setup.\n");
376 if (!memcmp(elm->rxbuf, "BUFFER FULL", 11)) {
377 /* This case will only happen if the last data
379 * Otherwise, elm327_parse_frame() will emit the
380 * error frame instead.
382 frame.can_id |= CAN_ERR_CRTL;
383 frame.data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
387 if (!memcmp(elm->rxbuf, "BUS ERROR", 9)) {
388 frame.can_id |= CAN_ERR_BUSERROR;
390 if (!memcmp(elm->rxbuf, "CAN ERROR", 9)
391 || !memcmp(elm->rxbuf, "<RX ERROR", 9)) {
392 frame.can_id |= CAN_ERR_PROT;
396 if (!memcmp(elm->rxbuf, "BUS BUSY", 8)) {
397 frame.can_id |= CAN_ERR_PROT;
398 frame.data[2] = CAN_ERR_PROT_OVERLOAD;
400 if (!memcmp(elm->rxbuf, "FB ERROR", 8)) {
401 frame.can_id |= CAN_ERR_PROT;
402 frame.data[2] = CAN_ERR_PROT_TX;
406 if (!memcmp(elm->rxbuf, "ERR", 3)) {
407 netdev_err(elm->dev, "The ELM327 reported an ERR%c%c. Please power it off and on again.\n",
408 elm->rxbuf[3], elm->rxbuf[4]);
409 frame.can_id |= CAN_ERR_CRTL;
413 /* Don't emit an error frame if we're unsure */
417 elm327_feed_frame_to_netdev(elm, &frame);
421 static int elm327_parse_frame(struct elmcan *elm, int len)
423 struct can_frame frame = {0};
428 /* Find first non-hex and non-space character:
429 * - In the simplest case, there is none.
430 * - For RTR frames, 'R' is the first non-hex character.
431 * - An error message may replace the end of the data line.
433 for (hexlen = 0; hexlen <= len; hexlen++) {
434 if (hex_to_bin(elm->rxbuf[hexlen]) < 0
435 && elm->rxbuf[hexlen] != ' ') {
440 /* Use spaces in CAN ID to distinguish 29 or 11 bit address length.
441 * No out-of-bounds access:
442 * We use the fact that we can always read from elm->rxbuf.
444 if (elm->rxbuf[2] == ' ' && elm->rxbuf[5] == ' '
445 && elm->rxbuf[8] == ' ' && elm->rxbuf[11] == ' '
446 && elm->rxbuf[13] == ' ') {
447 frame.can_id = CAN_EFF_FLAG;
449 } else if (elm->rxbuf[3] == ' ' && elm->rxbuf[5] == ' ') {
453 /* This is not a well-formatted data line.
454 * Assume it's an error message.
459 if (hexlen < datastart) {
460 /* The line is too short to be a valid frame hex dump.
461 * Something interrupted the hex dump or it is invalid.
466 /* From here on all chars up to buf[hexlen] are hex or spaces,
467 * at well-defined offsets.
470 /* Read CAN data length */
471 frame.can_dlc = (hex_to_bin(elm->rxbuf[datastart - 2]) << 0);
474 if (frame.can_id & CAN_EFF_FLAG) {
475 frame.can_id |= (hex_to_bin(elm->rxbuf[0]) << 28)
476 | (hex_to_bin(elm->rxbuf[1]) << 24)
477 | (hex_to_bin(elm->rxbuf[3]) << 20)
478 | (hex_to_bin(elm->rxbuf[4]) << 16)
479 | (hex_to_bin(elm->rxbuf[6]) << 12)
480 | (hex_to_bin(elm->rxbuf[7]) << 8)
481 | (hex_to_bin(elm->rxbuf[9]) << 4)
482 | (hex_to_bin(elm->rxbuf[10]) << 0);
484 frame.can_id |= (hex_to_bin(elm->rxbuf[0]) << 8)
485 | (hex_to_bin(elm->rxbuf[1]) << 4)
486 | (hex_to_bin(elm->rxbuf[2]) << 0);
489 /* Check for RTR frame */
490 if (elm->rxfill >= hexlen + 3
491 && elm->rxbuf[hexlen + 0] == 'R'
492 && elm->rxbuf[hexlen + 1] == 'T'
493 && elm->rxbuf[hexlen + 2] == 'R') {
494 frame.can_id |= CAN_RTR_FLAG;
497 /* Is the line long enough to hold the advertised payload? */
498 if (!(frame.can_id & CAN_RTR_FLAG) && (hexlen < frame.can_dlc * 3 + datastart)) {
499 /* Incomplete frame. */
501 /* Probably the ELM327's RS232 TX buffer was full.
502 * Emit an error frame and exit.
504 frame.can_id = CAN_ERR_FLAG | CAN_ERR_CRTL;
505 frame.can_dlc = CAN_ERR_DLC;
506 frame.data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
507 elm327_feed_frame_to_netdev(elm, &frame);
509 /* Signal failure to parse.
510 * The line will be re-parsed as an error line, which will fail.
511 * However, this will correctly drop the state machine back into
517 /* Parse the data nibbles. */
518 for (i = 0; i < frame.can_dlc; i++) {
519 frame.data[i] = (hex_to_bin(elm->rxbuf[datastart+3*i]) << 4)
520 | (hex_to_bin(elm->rxbuf[datastart+3*i+1]) << 0);
523 /* Feed the frame to the network layer. */
524 elm327_feed_frame_to_netdev(elm, &frame);
530 static void elm327_parse_line(struct elmcan *elm, int len)
532 /* Skip empty lines */
537 /* Skip echo lines */
538 if (elm->drop_next_line) {
539 elm->drop_next_line = 0;
541 } else if (elm->rxbuf[0] == 'A' && elm->rxbuf[1] == 'T') {
545 /* Regular parsing */
548 if (elm327_parse_frame(elm, len)) {
549 /* Parse an error line. */
550 elm327_parse_error(elm, len);
552 /* After the error line, we expect a prompt. */
553 elm->state = ELM_GETPROMPT;
562 static void elm327_handle_prompt(struct elmcan *elm)
564 if (elm->cmds_todo) {
565 struct can_frame *frame = &elm->can_frame;
568 if (test_bit(ELM_TODO_INIT, &elm->cmds_todo)) {
569 elm327_send(elm, *elm->next_init_cmd, strlen(*elm->next_init_cmd));
570 elm->next_init_cmd++;
571 if (!(*elm->next_init_cmd)) {
572 clear_bit(ELM_TODO_INIT, &elm->cmds_todo);
573 netdev_info(elm->dev, "Initialization finished.\n");
576 /* Some chips are unreliable and need extra time after
577 * init commands, as seen with a clone.
578 * So let's do a dummy get-cmd-prompt dance.
580 elm->state = ELM_NOTINIT;
581 elm327_kick_into_cmd_mode(elm);
582 } else if (test_and_clear_bit(ELM_TODO_SILENT_MONITOR, &elm->cmds_todo)) {
583 snprintf(txbuf, sizeof(txbuf), "ATCSM%i\r", !(!(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY)));
584 } else if (test_and_clear_bit(ELM_TODO_RESPONSES, &elm->cmds_todo)) {
585 snprintf(txbuf, sizeof(txbuf), "ATR%i\r", !(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY));
586 } else if (test_and_clear_bit(ELM_TODO_CAN_CONFIG, &elm->cmds_todo)) {
587 snprintf(txbuf, sizeof(txbuf), "ATPB%04X\r", elm->can_config);
588 } else if (test_and_clear_bit(ELM_TODO_CANID_29BIT_HIGH, &elm->cmds_todo)) {
589 snprintf(txbuf, sizeof(txbuf), "ATCP%02X\r", (frame->can_id & CAN_EFF_MASK) >> 24);
590 } else if (test_and_clear_bit(ELM_TODO_CANID_29BIT_LOW, &elm->cmds_todo)) {
591 snprintf(txbuf, sizeof(txbuf), "ATSH%06X\r", frame->can_id & CAN_EFF_MASK & ((1 << 24) - 1));
592 } else if (test_and_clear_bit(ELM_TODO_CANID_11BIT, &elm->cmds_todo)) {
593 snprintf(txbuf, sizeof(txbuf), "ATSH%03X\r", frame->can_id & CAN_SFF_MASK);
594 } else if (test_and_clear_bit(ELM_TODO_CAN_DATA, &elm->cmds_todo)) {
595 if (frame->can_id & CAN_RTR_FLAG) {
596 snprintf(txbuf, sizeof(txbuf), "ATRTR\r");
600 for (i = 0; i < frame->can_dlc; i++) {
601 sprintf(&txbuf[2*i], "%02X", frame->data[i]);
604 sprintf(&txbuf[2*i], "\r");
607 elm->drop_next_line = 1;
608 elm->state = ELM_RECEIVING;
611 elm327_send(elm, txbuf, strlen(txbuf));
613 /* Enter CAN monitor mode */
614 elm327_send(elm, "ATMA\r", 5);
615 elm->state = ELM_RECEIVING;
620 static void elm327_drop_bytes(struct elmcan *elm, int i)
622 memmove(&elm->rxbuf[0], &elm->rxbuf[i], sizeof(elm->rxbuf) - i);
627 static void elm327_parse_rxbuf(struct elmcan *elm)
631 switch (elm->state) {
636 case ELM_GETMAGICCHAR:
638 /* Wait for 'y' or '>' */
641 for (i = 0; i < elm->rxfill; i++) {
642 if (elm->rxbuf[i] == ELM327_MAGIC_CHAR) {
643 elm327_send(elm, "\r", 1);
644 elm->state = ELM_GETPROMPT;
647 } else if (elm->rxbuf[i] == ELM327_READY_CHAR) {
648 elm327_send(elm, ELM327_MAGIC_STRING, 1);
654 elm327_drop_bytes(elm, i);
661 if (elm->rxbuf[elm->rxfill - 1] == ELM327_READY_CHAR) {
662 elm327_handle_prompt(elm);
669 /* Find <CR> delimiting feedback lines. */
671 (len < elm->rxfill) && (elm->rxbuf[len] != '\r');
676 if (len == sizeof(elm->rxbuf)) {
677 /* Line exceeds buffer. It's probably all garbage.
678 * Did we even connect at the right baud rate?
680 netdev_err(elm->dev, "RX buffer overflow. Faulty ELM327 connected?\n");
681 elm327_hw_failure(elm);
683 } else if (len == elm->rxfill) {
684 if (elm->state == ELM_RECEIVING
685 && elm->rxbuf[elm->rxfill - 1] == ELM327_READY_CHAR) {
686 /* The ELM327's AT ST response timeout ran out,
687 * so we got a prompt.
688 * Clear RX buffer and restart listening.
692 elm327_handle_prompt(elm);
695 /* We haven't received a full line yet.
696 * Wait for more data.
702 /* We have a full line to parse. */
703 elm327_parse_line(elm, len);
705 /* Remove parsed data from RX buffer. */
706 elm327_drop_bytes(elm, len+1);
708 /* More data to parse? */
710 elm327_parse_rxbuf(elm);
719 /************************************************************************
722 * (takes elm->lock) *
723 ************************************************************************/
725 /* Netdevice DOWN -> UP routine */
726 static int elmcan_netdev_open(struct net_device *dev)
728 struct elmcan *elm = netdev_priv(dev);
731 spin_lock_bh(&elm->lock);
732 if (elm->hw_failure) {
733 netdev_err(elm->dev, "Refusing to open interface after "
734 "a hardware fault has been detected.\n");
735 spin_unlock_bh(&elm->lock);
739 if (elm->tty == NULL) {
740 spin_unlock_bh(&elm->lock);
744 /* open_candev() checks for elm->can.bittiming.bitrate != 0 */
745 err = open_candev(dev);
747 spin_unlock_bh(&elm->lock);
751 /* Initialize the ELM327 */
753 spin_unlock_bh(&elm->lock);
755 can_led_event(dev, CAN_LED_EVENT_OPEN);
756 elm->can.state = CAN_STATE_ERROR_ACTIVE;
757 netif_start_queue(dev);
762 /* Netdevice UP -> DOWN routine */
763 static int elmcan_netdev_close(struct net_device *dev)
765 struct elmcan *elm = netdev_priv(dev);
767 spin_lock_bh(&elm->lock);
769 /* TTY discipline is running. */
771 /* Interrupt whatever we're doing right now */
772 elm327_send(elm, ELM327_MAGIC_STRING, 1);
774 /* Clear the wakeup bit, as the netdev will be down and thus
775 * the wakeup handler won't clear it
777 clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
779 spin_unlock_bh(&elm->lock);
781 flush_work(&elm->tx_work);
783 spin_unlock_bh(&elm->lock);
786 elm->can.state = CAN_STATE_STOPPED;
787 netif_stop_queue(dev);
789 can_led_event(dev, CAN_LED_EVENT_STOP);
794 /* Send a can_frame to a TTY queue. */
795 static netdev_tx_t elmcan_netdev_start_xmit(struct sk_buff *skb, struct net_device *dev)
797 struct elmcan *elm = netdev_priv(dev);
798 struct can_frame *frame = (struct can_frame *) skb->data;
800 if (skb->len != sizeof(struct can_frame))
803 if (!netif_running(dev)) {
804 netdev_warn(elm->dev, "xmit: iface is down.\n");
808 /* BHs are already disabled, so no spin_lock_bh().
809 * See Documentation/networking/netdevices.txt
811 spin_lock(&elm->lock);
813 /* We shouldn't get here after a hardware fault:
814 * can_bus_off() calls netif_carrier_off()
816 BUG_ON(elm->hw_failure);
819 || elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY) {
820 spin_unlock(&elm->lock);
824 netif_stop_queue(dev);
826 elm327_send_frame(elm, frame);
827 spin_unlock(&elm->lock);
829 dev->stats.tx_packets++;
830 dev->stats.tx_bytes += frame->can_dlc;
832 can_led_event(dev, CAN_LED_EVENT_TX);
839 static int elmcan_netdev_change_mtu(struct net_device *dev, int new_mtu)
844 static const struct net_device_ops elmcan_netdev_ops = {
845 .ndo_open = elmcan_netdev_open,
846 .ndo_stop = elmcan_netdev_close,
847 .ndo_start_xmit = elmcan_netdev_start_xmit,
848 .ndo_change_mtu = elmcan_netdev_change_mtu,
855 /************************************************************************
858 * (takes elm->lock) *
859 ************************************************************************/
862 * Get a reference to our struct, taking into account locks/refcounts.
863 * This is to ensure ordering in case we are shutting down, and to ensure
864 * there is a refcount at all (because tty->disc_data may be NULL).
866 static struct elmcan* get_elm(struct tty_struct *tty)
871 /* Lock all elmcan TTYs, so tty->disc_data can't become NULL
872 * the moment before we increase the reference counter.
874 spin_lock_bh(&elmcan_discdata_lock);
875 elm = (struct elmcan *) tty->disc_data;
878 spin_unlock_bh(&elmcan_discdata_lock);
882 got_ref = atomic_inc_not_zero(&elm->refcount);
883 spin_unlock_bh(&elmcan_discdata_lock);
892 static void put_elm(struct elmcan *elm)
894 atomic_dec(&elm->refcount);
900 * Handle the 'receiver data ready' interrupt.
901 * This function is called by the 'tty_io' module in the kernel when
902 * a block of ELM327 CAN data has been received, which can now be parsed
903 * and sent on to some IP layer for further processing. This will not
904 * be re-entered while running but other ldisc functions may be called
907 static void elmcan_ldisc_rx(struct tty_struct *tty,
908 const unsigned char *cp, char *fp, int count)
910 struct elmcan *elm = get_elm(tty);
915 /* Read the characters out of the buffer */
916 while (count-- && elm->rxfill < sizeof(elm->rxbuf)) {
918 netdev_err(elm->dev, "Error in received character stream. Check your wiring.");
920 spin_lock_bh(&elm->lock);
921 elm327_hw_failure(elm);
922 spin_unlock_bh(&elm->lock);
928 elm->rxbuf[elm->rxfill++] = *cp;
934 netdev_err(elm->dev, "Receive buffer overflowed. Bad chip or wiring?");
936 spin_lock_bh(&elm->lock);
937 elm327_hw_failure(elm);
938 spin_unlock_bh(&elm->lock);
944 spin_lock_bh(&elm->lock);
945 elm327_parse_rxbuf(elm);
946 spin_unlock_bh(&elm->lock);
952 * Write out remaining transmit buffer.
953 * Scheduled when TTY is writable.
955 static void elmcan_ldisc_tx_worker(struct work_struct *work)
957 /* No need to use get_elm() here, as we'll always flush workers
958 * befory destroying the elmcan object.
960 struct elmcan *elm = container_of(work, struct elmcan, tx_work);
963 spin_lock_bh(&elm->lock);
964 if (elm->hw_failure) {
965 spin_unlock_bh(&elm->lock);
969 if (!elm->tty || !netif_running(elm->dev)) {
970 spin_unlock_bh(&elm->lock);
974 if (elm->txleft <= 0) {
975 /* Our TTY write buffer is empty:
976 * We can start transmission of another packet
978 clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
979 spin_unlock_bh(&elm->lock);
980 netif_wake_queue(elm->dev);
984 actual = elm->tty->ops->write(elm->tty, elm->txhead, elm->txleft);
986 netdev_err(elm->dev, "Failed to write to tty %s.\n", elm->tty->name);
987 elm327_hw_failure(elm);
988 spin_unlock_bh(&elm->lock);
992 elm->txleft -= actual;
993 elm->txhead += actual;
994 spin_unlock_bh(&elm->lock);
999 * Called by the driver when there's room for more data.
1000 * Schedule the transmit.
1002 static void elmcan_ldisc_tx_wakeup(struct tty_struct *tty)
1004 struct elmcan *elm = get_elm(tty);
1009 schedule_work(&elm->tx_work);
1016 /* Some fake bit timings to allow bitrate setting */
1017 static const struct can_bittiming_const elmcan_bittiming_const = {
1030 * Open the high-level part of the elmcan channel.
1031 * This function is called by the TTY module when the
1032 * elmcan line discipline is called for.
1034 * Called in process context serialized from other ldisc calls.
1036 static int elmcan_ldisc_open(struct tty_struct *tty)
1038 struct net_device *dev;
1042 if (!capable(CAP_NET_ADMIN))
1045 if (!tty->ops->write)
1049 /* OK. Find a free elmcan channel to use. */
1050 dev = alloc_candev(sizeof(struct elmcan), 0);
1053 elm = netdev_priv(dev);
1055 /* Configure TTY interface */
1056 tty->receive_room = 65536; /* We don't flow control */
1057 elm->txleft = 0; /* Clear TTY TX buffer */
1058 spin_lock_init(&elm->lock);
1059 atomic_set(&elm->refcount, 1);
1060 INIT_WORK(&elm->tx_work, elmcan_ldisc_tx_worker);
1062 /* Configure CAN metadata */
1063 elm->can.state = CAN_STATE_STOPPED;
1064 elm->can.clock.freq = 1000000;
1065 elm->can.bittiming_const = &elmcan_bittiming_const;
1066 elm->can.ctrlmode_supported = CAN_CTRLMODE_LISTENONLY;
1068 /* Configure netlink interface */
1070 dev->netdev_ops = &elmcan_netdev_ops;
1072 /* Mark ldisc channel as alive */
1074 tty->disc_data = elm;
1076 devm_can_led_init(elm->dev);
1079 err = register_candev(elm->dev);
1081 free_candev(elm->dev);
1085 netdev_info(elm->dev, "elmcan on %s.\n", tty->name);
1091 * Close down an elmcan channel.
1092 * This means flushing out any pending queues, and then returning.
1093 * This call is serialized against other ldisc functions:
1094 * Once this is called, no other ldisc function of ours is entered.
1096 * We also use this function for a hangup event.
1098 static void elmcan_ldisc_close(struct tty_struct *tty)
1100 /* Use get_elm() to synchronize against other users */
1101 struct elmcan *elm = get_elm(tty);
1106 /* Tear down network side.
1107 * unregister_netdev() calls .ndo_stop() so we don't have to.
1109 unregister_candev(elm->dev);
1111 /* Decrease the refcount twice, once for our own get_elm(),
1112 * and once to remove the count of 1 that we set in _open().
1113 * Once it reaches 0, we can safely destroy it.
1118 /* Spin until refcount reaches 0 */
1119 while(atomic_read(&elm->refcount) > 0)
1122 /* At this point, all ldisc calls to us will be no-ops.
1123 * Since the refcount is 0, they are bailing immediately.
1126 /* Mark channel as dead */
1127 spin_lock_bh(&elm->lock);
1128 tty->disc_data = NULL;
1130 spin_unlock_bh(&elm->lock);
1132 /* Flush TTY side */
1133 flush_work(&elm->tx_work);
1135 netdev_info(elm->dev, "elmcan off %s.\n", tty->name);
1137 /* Free our memory */
1138 free_candev(elm->dev);
1141 static int elmcan_ldisc_hangup(struct tty_struct *tty)
1143 elmcan_ldisc_close(tty);
1147 /* Perform I/O control on an active elmcan channel. */
1148 static int elmcan_ldisc_ioctl(struct tty_struct *tty, struct file *file,
1149 unsigned int cmd, unsigned long arg)
1151 struct elmcan *elm = get_elm(tty);
1159 tmp = strlen(elm->dev->name) + 1;
1160 if (copy_to_user((void __user *)arg, elm->dev->name, tmp)) {
1174 return tty_mode_ioctl(tty, file, cmd, arg);
1178 static struct tty_ldisc_ops elmcan_ldisc = {
1179 .owner = THIS_MODULE,
1180 .magic = TTY_LDISC_MAGIC,
1182 .receive_buf = elmcan_ldisc_rx,
1183 .write_wakeup = elmcan_ldisc_tx_wakeup,
1184 .open = elmcan_ldisc_open,
1185 .close = elmcan_ldisc_close,
1186 .hangup = elmcan_ldisc_hangup,
1187 .ioctl = elmcan_ldisc_ioctl,
1194 /************************************************************************
1195 * Module init/exit *
1196 ************************************************************************/
1198 static int __init elmcan_init(void)
1202 pr_info("ELM327 based best-effort CAN interface driver\n");
1203 pr_info("This device is severely limited as a CAN interface, see documentation.\n");
1205 /* Fill in our line protocol discipline, and register it */
1206 status = tty_register_ldisc(N_ELMCAN, &elmcan_ldisc);
1208 pr_err("can't register line discipline\n");
1213 static void __exit elmcan_exit(void)
1215 /* This will only be called when all channels have been closed by
1216 * userspace - tty_ldisc.c takes care of the module's refcount.
1220 status = tty_unregister_ldisc(N_ELMCAN);
1222 pr_err("Can't unregister line discipline (error: %d)\n", status);
1226 module_init(elmcan_init);
1227 module_exit(elmcan_exit);