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"
62 /* Bits in elm->cmds_todo */
64 ELM_TODO_CAN_DATA = 0,
66 ELM_TODO_CANID_29BIT_LOW,
67 ELM_TODO_CANID_29BIT_HIGH,
70 ELM_TODO_SILENT_MONITOR,
76 /* This must be the first member when using alloc_candev() */
79 /* TTY and netdev devices that we're bridging */
80 struct tty_struct *tty;
81 struct net_device *dev;
83 char ifname[IFNAMSIZ];
85 /* Per-channel lock */
88 /* Keep track of how many things are using this struct.
89 * Once it reaches 0, we are in the process of cleaning up,
90 * and new operations will be cancelled immediately.
91 * Use atomic_t rather than refcount_t because we deliberately
92 * decrement to 0, and refcount_dec() spills a WARN_ONCE in
98 struct work_struct tx_work; /* Flushes TTY TX buffer */
99 unsigned char txbuf[32];
100 unsigned char *txhead; /* Pointer to next TX byte */
101 int txleft; /* Bytes left to TX */
104 unsigned char rxbuf[256];
117 /* The CAN frame and config the ELM327 is sending/using,
118 * or will send/use after finishing all cmds_todo */
119 struct can_frame can_frame;
120 unsigned short can_config;
121 unsigned long can_bitrate;
122 unsigned char can_bitrate_divisor;
123 int silent_monitoring;
125 /* Things we have yet to send */
126 char **next_init_cmd;
127 unsigned long cmds_todo;
131 /* A lock for all tty->disc_data handled by this ldisc.
132 * This is to prevent a case where tty->disc_data is set to NULL,
133 * yet someone is still trying to dereference it.
134 * Without this, we cannot do a clean shutdown.
136 static DEFINE_SPINLOCK(elmcan_discdata_lock);
141 /************************************************************************
142 * ELM327: Transmission *
144 * (all functions assume elm->lock taken) *
145 ************************************************************************/
147 static void elm327_send(struct elmcan *elm, const void *buf, size_t len)
151 memcpy(elm->txbuf, buf, len);
153 /* Order of next two lines is *very* important.
154 * When we are sending a little amount of data,
155 * the transfer may be completed inside the ops->write()
156 * routine, because it's running with interrupts enabled.
157 * In this case we *never* got WRITE_WAKEUP event,
158 * if we did not request it before write operation.
159 * 14 Oct 1994 Dmitry Gorodchanin.
161 set_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
162 actual = elm->tty->ops->write(elm->tty, elm->txbuf, len);
163 elm->txleft = len - actual;
164 elm->txhead = elm->txbuf + actual;
169 * Take the ELM327 out of almost any state and back into command mode
171 * Assumes elm->lock taken.
173 static void elm327_kick_into_cmd_mode(struct elmcan *elm)
175 if (elm->state != ELM_GETMAGICCHAR && elm->state != ELM_GETPROMPT) {
176 elm327_send(elm, ELM327_MAGIC_STRING, 1);
178 elm->state = ELM_GETMAGICCHAR;
185 * Schedule a CAN frame, and any necessary config changes,
186 * to be sent down the TTY.
188 * Assumes elm->lock taken.
190 static void elm327_send_frame(struct elmcan *elm, struct can_frame *frame)
192 /* Schedule any necessary changes in ELM327's CAN configuration */
193 if (elm->can_frame.can_id != frame->can_id) {
194 /* Set the new CAN ID for transmission. */
195 if ((frame->can_id & CAN_EFF_FLAG) ^ (elm->can_frame.can_id & CAN_EFF_FLAG)) {
196 elm->can_config = (frame->can_id & CAN_EFF_FLAG ? 0 : ELM327_CAN_CONFIG_SEND_SFF)
197 | ELM327_CAN_CONFIG_VARIABLE_DLC
198 | ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF
199 | elm->can_bitrate_divisor;
201 set_bit(ELM_TODO_CAN_CONFIG, &elm->cmds_todo);
204 if (frame->can_id & CAN_EFF_FLAG) {
205 clear_bit(ELM_TODO_CANID_11BIT, &elm->cmds_todo);
206 set_bit(ELM_TODO_CANID_29BIT_LOW, &elm->cmds_todo);
207 set_bit(ELM_TODO_CANID_29BIT_HIGH, &elm->cmds_todo);
209 set_bit(ELM_TODO_CANID_11BIT, &elm->cmds_todo);
210 clear_bit(ELM_TODO_CANID_29BIT_LOW, &elm->cmds_todo);
211 clear_bit(ELM_TODO_CANID_29BIT_HIGH, &elm->cmds_todo);
215 /* Schedule the CAN frame itself. */
216 elm->can_frame = *frame;
217 set_bit(ELM_TODO_CAN_DATA, &elm->cmds_todo);
219 elm327_kick_into_cmd_mode(elm);
224 /************************************************************************
225 * ELM327: Initialization sequence *
227 * (assumes elm->lock taken) *
228 ************************************************************************/
230 static char *elm327_init_script[] = {
231 "AT WS\r", /* v1.0: Warm Start */
232 "AT PP FF OFF\r", /* v1.0: All Programmable Parameters Off */
233 "AT M0\r", /* v1.0: Memory Off */
234 "AT AL\r", /* v1.0: Allow Long messages */
235 "AT BI\r", /* v1.0: Bypass Initialization */
236 "AT CAF0\r", /* v1.0: CAN Auto Formatting Off */
237 "AT CFC0\r", /* v1.0: CAN Flow Control Off */
238 "AT CF 000\r", /* v1.0: Reset CAN ID Filter */
239 "AT CM 000\r", /* v1.0: Reset CAN ID Mask */
240 "AT E1\r", /* v1.0: Echo On */
241 "AT H1\r", /* v1.0: Headers On */
242 "AT L0\r", /* v1.0: Linefeeds Off */
243 "AT SH 7DF\r", /* v1.0: Set CAN sending ID to 0x7df */
244 "AT ST FF\r", /* v1.0: Set maximum Timeout for response after TX */
245 "AT AT0\r", /* v1.2: Adaptive Timing Off */
246 "AT D1\r", /* v1.3: Print DLC On */
247 "AT S1\r", /* v1.3: Spaces On */
248 "AT TP B\r", /* v1.0: Try Protocol B */
253 static void elm327_init(struct elmcan *elm)
255 elm->state = ELM_NOTINIT;
256 elm->can_frame.can_id = 0x7df;
258 elm->drop_next_line = 0;
260 /* We can only set the bitrate as a fraction of 500000.
261 * The bit timing constants in elmcan_bittiming_const will
262 * limit the user to the right values.
264 elm->can_bitrate_divisor = 500000 / elm->can.bittiming.bitrate;
265 elm->can_config = ELM327_CAN_CONFIG_SEND_SFF
266 | ELM327_CAN_CONFIG_VARIABLE_DLC
267 | ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF
268 | elm->can_bitrate_divisor;
270 /* Configure ELM327 and then start monitoring */
271 elm->next_init_cmd = &elm327_init_script[0];
272 set_bit(ELM_TODO_INIT, &elm->cmds_todo);
273 set_bit(ELM_TODO_SILENT_MONITOR, &elm->cmds_todo);
274 set_bit(ELM_TODO_RESPONSES, &elm->cmds_todo);
275 set_bit(ELM_TODO_CAN_CONFIG, &elm->cmds_todo);
277 elm327_kick_into_cmd_mode(elm);
282 /************************************************************************
283 * ELM327: Reception -> netdev glue *
285 * (assumes elm->lock taken) *
286 ************************************************************************/
288 static void elm327_feed_frame_to_netdev(struct elmcan *elm, const struct can_frame *frame)
290 struct can_frame *cf;
293 if (!netif_running(elm->dev)) {
297 skb = alloc_can_skb(elm->dev, &cf);
302 memcpy(cf, frame, sizeof(struct can_frame));
304 elm->dev->stats.rx_packets++;
305 elm->dev->stats.rx_bytes += frame->can_dlc;
308 can_led_event(elm->dev, CAN_LED_EVENT_RX);
313 /************************************************************************
314 * ELM327: Panic handler *
316 * (assumes elm->lock taken) *
317 ************************************************************************/
319 static inline void elm327_panic(struct elmcan *elm)
321 struct can_frame frame = {0};
323 frame.can_id = CAN_ERR_FLAG | CAN_ERR_RESTARTED;
324 frame.can_dlc = CAN_ERR_DLC;
325 elm327_feed_frame_to_netdev(elm, &frame);
327 pr_err("ELM327 misbehaved. Re-initializing.\n");
329 elm->can.can_stats.restarts++;
335 /************************************************************************
336 * ELM327: Reception parser *
338 * (assumes elm->lock taken) *
339 ************************************************************************/
341 static void elm327_parse_error(struct elmcan *elm, int len)
343 struct can_frame frame = {0};
345 frame.can_id = CAN_ERR_FLAG;
346 frame.can_dlc = CAN_ERR_DLC;
350 if (!memcmp(elm->rxbuf, "UNABLE TO CONNECT", 17)) {
351 pr_err("The ELM327 reported UNABLE TO CONNECT. Please check your setup.\n");
355 if (!memcmp(elm->rxbuf, "BUFFER FULL", 11)) {
356 /* This case will only happen if the last data
358 * Otherwise, elm327_parse_frame() will emit the
359 * error frame instead.
361 frame.can_id |= CAN_ERR_CRTL;
362 frame.data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
366 if (!memcmp(elm->rxbuf, "BUS ERROR", 9)) {
367 frame.can_id |= CAN_ERR_BUSERROR;
369 if (!memcmp(elm->rxbuf, "CAN ERROR", 9)
370 || !memcmp(elm->rxbuf, "<RX ERROR", 9)) {
371 frame.can_id |= CAN_ERR_PROT;
375 if (!memcmp(elm->rxbuf, "BUS BUSY", 8)) {
376 frame.can_id |= CAN_ERR_PROT;
377 frame.data[2] = CAN_ERR_PROT_OVERLOAD;
379 if (!memcmp(elm->rxbuf, "FB ERROR", 8)) {
380 frame.can_id |= CAN_ERR_PROT;
381 frame.data[2] = CAN_ERR_PROT_TX;
385 if (!memcmp(elm->rxbuf, "ERR", 3)) {
386 pr_err("The ELM327 reported an ERR%c%c. Please power it off and on again.\n",
387 elm->rxbuf[3], elm->rxbuf[4]);
388 frame.can_id |= CAN_ERR_CRTL;
392 /* Don't emit an error frame if we're unsure */
396 elm327_feed_frame_to_netdev(elm, &frame);
400 static int elm327_parse_frame(struct elmcan *elm, int len)
402 struct can_frame frame = {0};
407 /* Find first non-hex and non-space character:
408 * - In the simplest case, there is none.
409 * - For RTR frames, 'R' is the first non-hex character.
410 * - An error message may replace the end of the data line.
412 for (hexlen = 0; hexlen <= len; hexlen++) {
413 if (hex_to_bin(elm->rxbuf[hexlen]) < 0
414 && elm->rxbuf[hexlen] != ' ') {
419 /* Use spaces in CAN ID to distinguish 29 or 11 bit address length.
420 * No out-of-bounds access:
421 * We use the fact that we can always read from elm->rxbuf.
423 if (elm->rxbuf[2] == ' ' && elm->rxbuf[5] == ' '
424 && elm->rxbuf[8] == ' ' && elm->rxbuf[11] == ' '
425 && elm->rxbuf[13] == ' ') {
426 frame.can_id = CAN_EFF_FLAG;
428 } else if (elm->rxbuf[3] == ' ' && elm->rxbuf[5] == ' ') {
432 /* This is not a well-formatted data line.
433 * Assume it's an error message.
438 if (hexlen < datastart) {
439 /* The line is too short to be a valid frame hex dump.
440 * Something interrupted the hex dump or it is invalid.
445 /* From here on all chars up to buf[hexlen] are hex or spaces,
446 * at well-defined offsets.
449 /* Read CAN data length */
450 frame.can_dlc = (hex_to_bin(elm->rxbuf[datastart - 2]) << 0);
453 if (frame.can_id & CAN_EFF_FLAG) {
454 frame.can_id |= (hex_to_bin(elm->rxbuf[0]) << 28)
455 | (hex_to_bin(elm->rxbuf[1]) << 24)
456 | (hex_to_bin(elm->rxbuf[3]) << 20)
457 | (hex_to_bin(elm->rxbuf[4]) << 16)
458 | (hex_to_bin(elm->rxbuf[6]) << 12)
459 | (hex_to_bin(elm->rxbuf[7]) << 8)
460 | (hex_to_bin(elm->rxbuf[9]) << 4)
461 | (hex_to_bin(elm->rxbuf[10]) << 0);
463 frame.can_id |= (hex_to_bin(elm->rxbuf[0]) << 8)
464 | (hex_to_bin(elm->rxbuf[1]) << 4)
465 | (hex_to_bin(elm->rxbuf[2]) << 0);
468 /* Check for RTR frame */
469 if (elm->rxfill >= hexlen + 3
470 && elm->rxbuf[hexlen + 0] == 'R'
471 && elm->rxbuf[hexlen + 1] == 'T'
472 && elm->rxbuf[hexlen + 2] == 'R') {
473 frame.can_id |= CAN_RTR_FLAG;
476 /* Is the line long enough to hold the advertised payload? */
477 if (!(frame.can_id & CAN_RTR_FLAG) && (hexlen < frame.can_dlc * 3 + datastart)) {
478 /* Incomplete frame. */
480 /* Probably the ELM327's RS232 TX buffer was full.
481 * Emit an error frame and exit.
483 frame.can_id = CAN_ERR_FLAG | CAN_ERR_CRTL;
484 frame.can_dlc = CAN_ERR_DLC;
485 frame.data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
486 elm327_feed_frame_to_netdev(elm, &frame);
488 /* Signal failure to parse.
489 * The line will be re-parsed as an error line, which will fail.
490 * However, this will correctly drop the state machine back into
496 /* Parse the data nibbles. */
497 for (i = 0; i < frame.can_dlc; i++) {
498 frame.data[i] = (hex_to_bin(elm->rxbuf[datastart+3*i]) << 4)
499 | (hex_to_bin(elm->rxbuf[datastart+3*i+1]) << 0);
502 /* Feed the frame to the network layer. */
503 elm327_feed_frame_to_netdev(elm, &frame);
509 static void elm327_parse_line(struct elmcan *elm, int len)
511 /* Skip empty lines */
516 /* Skip echo lines */
517 if (elm->drop_next_line) {
518 elm->drop_next_line = 0;
520 } else if (elm->rxbuf[0] == 'A' && elm->rxbuf[1] == 'T') {
524 /* Regular parsing */
527 if (elm327_parse_frame(elm, len)) {
528 /* Parse an error line. */
529 elm327_parse_error(elm, len);
531 /* After the error line, we expect a prompt. */
532 elm->state = ELM_GETPROMPT;
541 static void elm327_handle_prompt(struct elmcan *elm)
543 if (elm->cmds_todo) {
544 struct can_frame *frame = &elm->can_frame;
547 if (test_bit(ELM_TODO_INIT, &elm->cmds_todo)) {
548 elm327_send(elm, *elm->next_init_cmd, strlen(*elm->next_init_cmd));
549 elm->next_init_cmd++;
550 if (!(*elm->next_init_cmd)) {
551 clear_bit(ELM_TODO_INIT, &elm->cmds_todo);
552 pr_info("%s: Initialization finished.\n", elm->dev->name);
555 /* Some chips are unreliable and need extra time after
556 * init commands, as seen with a clone.
557 * So let's do a dummy get-cmd-prompt dance.
559 elm->state = ELM_NOTINIT;
560 elm327_kick_into_cmd_mode(elm);
561 } else if (test_and_clear_bit(ELM_TODO_SILENT_MONITOR, &elm->cmds_todo)) {
562 snprintf(txbuf, sizeof(txbuf), "ATCSM%i\r", !(!(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY)));
563 } else if (test_and_clear_bit(ELM_TODO_RESPONSES, &elm->cmds_todo)) {
564 snprintf(txbuf, sizeof(txbuf), "ATR%i\r", !(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY));
565 } else if (test_and_clear_bit(ELM_TODO_CAN_CONFIG, &elm->cmds_todo)) {
566 snprintf(txbuf, sizeof(txbuf), "ATPB%04X\r", elm->can_config);
567 } else if (test_and_clear_bit(ELM_TODO_CANID_29BIT_HIGH, &elm->cmds_todo)) {
568 snprintf(txbuf, sizeof(txbuf), "ATCP%02X\r", (frame->can_id & CAN_EFF_MASK) >> 24);
569 } else if (test_and_clear_bit(ELM_TODO_CANID_29BIT_LOW, &elm->cmds_todo)) {
570 snprintf(txbuf, sizeof(txbuf), "ATSH%06X\r", frame->can_id & CAN_EFF_MASK & ((1 << 24) - 1));
571 } else if (test_and_clear_bit(ELM_TODO_CANID_11BIT, &elm->cmds_todo)) {
572 snprintf(txbuf, sizeof(txbuf), "ATSH%03X\r", frame->can_id & CAN_SFF_MASK);
573 } else if (test_and_clear_bit(ELM_TODO_CAN_DATA, &elm->cmds_todo)) {
574 if (frame->can_id & CAN_RTR_FLAG) {
575 snprintf(txbuf, sizeof(txbuf), "ATRTR\r");
579 for (i = 0; i < frame->can_dlc; i++) {
580 sprintf(&txbuf[2*i], "%02X", frame->data[i]);
583 sprintf(&txbuf[2*i], "\r");
586 elm->drop_next_line = 1;
587 elm->state = ELM_RECEIVING;
590 elm327_send(elm, txbuf, strlen(txbuf));
592 /* Enter CAN monitor mode */
593 elm327_send(elm, "ATMA\r", 5);
594 elm->state = ELM_RECEIVING;
599 static void elm327_drop_bytes(struct elmcan *elm, int i)
601 memmove(&elm->rxbuf[0], &elm->rxbuf[i], sizeof(elm->rxbuf) - i);
606 static void elm327_parse_rxbuf(struct elmcan *elm)
610 switch (elm->state) {
615 case ELM_GETMAGICCHAR:
617 /* Wait for 'y' or '>' */
620 for (i = 0; i < elm->rxfill; i++) {
621 if (elm->rxbuf[i] == ELM327_MAGIC_CHAR) {
622 elm327_send(elm, "\r", 1);
623 elm->state = ELM_GETPROMPT;
626 } else if (elm->rxbuf[i] == '>') {
627 elm327_send(elm, ELM327_MAGIC_STRING, 1);
633 elm327_drop_bytes(elm, i);
640 if (elm->rxbuf[elm->rxfill - 1] == '>') {
641 elm327_handle_prompt(elm);
648 /* Find <CR> delimiting feedback lines. */
650 (len < elm->rxfill) && (elm->rxbuf[len] != '\r');
655 if (len == sizeof(elm->rxbuf)) {
656 /* Line exceeds buffer. It's probably all garbage.
657 * Did we even connect at the right baud rate?
659 pr_err("RX buffer overflow. Faulty ELM327 connected?\n");
661 } else if (len == elm->rxfill) {
662 if (elm->state == ELM_RECEIVING
663 && elm->rxbuf[elm->rxfill - 1] == '>') {
664 /* The ELM327's AT ST response timeout ran out,
665 * so we got a prompt.
666 * Clear RX buffer and restart listening.
670 elm327_handle_prompt(elm);
673 /* We haven't received a full line yet.
674 * Wait for more data.
680 /* We have a full line to parse. */
681 elm327_parse_line(elm, len);
683 /* Remove parsed data from RX buffer. */
684 elm327_drop_bytes(elm, len+1);
686 /* More data to parse? */
688 elm327_parse_rxbuf(elm);
697 /************************************************************************
700 * (takes elm->lock) *
701 ************************************************************************/
703 static int elmcan_netdev_init(struct net_device *dev)
705 struct elmcan *elm = netdev_priv(dev);
707 /* Copy the interface name here, so the SIOCGIFNAME case in
708 * elmcan_ldisc_ioctl() doesn't race against unregister_candev().
710 memcpy(elm->ifname, dev->name, IFNAMSIZ);
715 /* Netdevice DOWN -> UP routine */
716 static int elmcan_netdev_open(struct net_device *dev)
718 struct elmcan *elm = netdev_priv(dev);
721 spin_lock_bh(&elm->lock);
722 if (elm->tty == NULL) {
723 spin_unlock_bh(&elm->lock);
727 /* open_candev() checks for elm->can.bittiming.bitrate != 0 */
728 err = open_candev(dev);
730 spin_unlock_bh(&elm->lock);
734 /* Initialize the ELM327 */
736 spin_unlock_bh(&elm->lock);
738 can_led_event(dev, CAN_LED_EVENT_OPEN);
739 elm->can.state = CAN_STATE_ERROR_ACTIVE;
740 netif_start_queue(dev);
745 /* Netdevice UP -> DOWN routine */
746 static int elmcan_netdev_close(struct net_device *dev)
748 struct elmcan *elm = netdev_priv(dev);
750 spin_lock_bh(&elm->lock);
752 /* TTY discipline is running. */
754 /* Interrupt whatever we're doing right now */
755 elm327_send(elm, ELM327_MAGIC_STRING, 1);
757 /* Clear the wakeup bit, as the netdev will be down and thus
758 * the wakeup handler won't clear it
760 clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
762 spin_unlock_bh(&elm->lock);
764 flush_work(&elm->tx_work);
766 spin_unlock_bh(&elm->lock);
769 elm->can.state = CAN_STATE_STOPPED;
770 netif_stop_queue(dev);
772 can_led_event(dev, CAN_LED_EVENT_STOP);
777 /* Send a can_frame to a TTY queue. */
778 static netdev_tx_t elmcan_netdev_start_xmit(struct sk_buff *skb, struct net_device *dev)
780 struct elmcan *elm = netdev_priv(dev);
781 struct can_frame *frame = (struct can_frame *) skb->data;
783 if (skb->len != sizeof(struct can_frame))
786 if (!netif_running(dev)) {
787 pr_warn("%s: xmit: iface is down\n", dev->name);
791 /* BHs are already disabled, so no spin_lock_bh().
792 * See Documentation/networking/netdevices.txt
794 spin_lock(&elm->lock);
796 || elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY) {
797 spin_unlock(&elm->lock);
801 netif_stop_queue(dev);
803 elm327_send_frame(elm, frame);
804 spin_unlock(&elm->lock);
806 dev->stats.tx_packets++;
807 dev->stats.tx_bytes += frame->can_dlc;
809 can_led_event(dev, CAN_LED_EVENT_TX);
816 static int elmcan_netdev_change_mtu(struct net_device *dev, int new_mtu)
821 static const struct net_device_ops elmcan_netdev_ops = {
822 .ndo_init = elmcan_netdev_init,
823 .ndo_open = elmcan_netdev_open,
824 .ndo_stop = elmcan_netdev_close,
825 .ndo_start_xmit = elmcan_netdev_start_xmit,
826 .ndo_change_mtu = elmcan_netdev_change_mtu,
833 /************************************************************************
836 * (takes elm->lock) *
837 ************************************************************************/
840 * Get a reference to our struct, taking into account locks/refcounts.
841 * This is to ensure ordering in case we are shutting down, and to ensure
842 * there is a refcount at all (because tty->disc_data may be NULL).
844 static struct elmcan* get_elm(struct tty_struct *tty)
849 /* Lock all elmcan TTYs, so tty->disc_data can't become NULL
850 * the moment before we increase the reference counter.
852 spin_lock_bh(&elmcan_discdata_lock);
853 elm = (struct elmcan *) tty->disc_data;
856 spin_unlock_bh(&elmcan_discdata_lock);
860 got_ref = atomic_inc_not_zero(&elm->refcount);
861 spin_unlock_bh(&elmcan_discdata_lock);
870 static void put_elm(struct elmcan *elm)
872 atomic_dec(&elm->refcount);
878 * Handle the 'receiver data ready' interrupt.
879 * This function is called by the 'tty_io' module in the kernel when
880 * a block of ELM327 CAN data has been received, which can now be parsed
881 * and sent on to some IP layer for further processing. This will not
882 * be re-entered while running but other ldisc functions may be called
885 static void elmcan_ldisc_rx(struct tty_struct *tty,
886 const unsigned char *cp, char *fp, int count)
888 struct elmcan *elm = get_elm(tty);
893 /* Read the characters out of the buffer */
894 while (count-- && elm->rxfill < sizeof(elm->rxbuf)) {
896 pr_err("Error in received character stream. Check your wiring.");
898 spin_lock_bh(&elm->lock);
900 spin_unlock_bh(&elm->lock);
906 elm->rxbuf[elm->rxfill++] = *cp;
912 pr_err("Receive buffer overflowed. Bad chip or wiring?");
914 spin_lock_bh(&elm->lock);
916 spin_unlock_bh(&elm->lock);
922 spin_lock_bh(&elm->lock);
923 elm327_parse_rxbuf(elm);
924 spin_unlock_bh(&elm->lock);
930 * Write out remaining transmit buffer.
931 * Scheduled when TTY is writable.
933 static void elmcan_ldisc_tx_worker(struct work_struct *work)
935 /* No need to use get_elm() here, as we'll always flush workers
936 * befory destroying the elmcan object.
938 struct elmcan *elm = container_of(work, struct elmcan, tx_work);
941 spin_lock_bh(&elm->lock);
942 /* First make sure we're connected. */
943 if (!elm->tty || !netif_running(elm->dev)) {
944 spin_unlock_bh(&elm->lock);
948 if (elm->txleft <= 0) {
949 /* Our TTY write buffer is empty:
950 * We can start transmission of another packet
952 clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
953 spin_unlock_bh(&elm->lock);
954 netif_wake_queue(elm->dev);
958 actual = elm->tty->ops->write(elm->tty, elm->txhead, elm->txleft);
960 pr_err("Failed to write to tty for %s.\n", elm->dev->name);
964 elm->txleft -= actual;
965 elm->txhead += actual;
966 spin_unlock_bh(&elm->lock);
971 * Called by the driver when there's room for more data.
972 * Schedule the transmit.
974 static void elmcan_ldisc_tx_wakeup(struct tty_struct *tty)
976 struct elmcan *elm = get_elm(tty);
981 schedule_work(&elm->tx_work);
988 /* Some fake bit timings to allow bitrate setting */
989 static const struct can_bittiming_const elmcan_bittiming_const = {
1002 * Open the high-level part of the elmcan channel.
1003 * This function is called by the TTY module when the
1004 * elmcan line discipline is called for.
1006 * Called in process context serialized from other ldisc calls.
1008 static int elmcan_ldisc_open(struct tty_struct *tty)
1010 struct net_device *dev;
1014 if (!capable(CAP_NET_ADMIN))
1017 if (!tty->ops->write)
1021 /* OK. Find a free elmcan channel to use. */
1022 dev = alloc_candev(sizeof(struct elmcan), 0);
1025 elm = netdev_priv(dev);
1027 /* Configure TTY interface */
1028 tty->receive_room = 65536; /* We don't flow control */
1029 elm->txleft = 0; /* Clear TTY TX buffer */
1030 spin_lock_init(&elm->lock);
1031 atomic_set(&elm->refcount, 1);
1032 INIT_WORK(&elm->tx_work, elmcan_ldisc_tx_worker);
1034 /* Configure CAN metadata */
1035 elm->can.state = CAN_STATE_STOPPED;
1036 elm->can.clock.freq = 1000000;
1037 elm->can.bittiming_const = &elmcan_bittiming_const;
1038 elm->can.ctrlmode_supported = CAN_CTRLMODE_LISTENONLY;
1040 /* Configure netlink interface */
1042 dev->netdev_ops = &elmcan_netdev_ops;
1044 /* Mark ldisc channel as alive */
1046 tty->disc_data = elm;
1048 devm_can_led_init(elm->dev);
1051 err = register_candev(elm->dev);
1053 free_candev(elm->dev);
1057 netdev_info(elm->dev, "elmcan on %s.\n", tty->name);
1063 * Close down an elmcan channel.
1064 * This means flushing out any pending queues, and then returning.
1065 * This call is serialized against other ldisc functions:
1066 * Once this is called, no other ldisc function of ours is entered.
1068 * We also use this function for a hangup event.
1070 static void elmcan_ldisc_close(struct tty_struct *tty)
1072 /* Use get_elm() to synchronize against other users */
1073 struct elmcan *elm = get_elm(tty);
1078 /* Tear down network side.
1079 * unregister_netdev() calls .ndo_stop() so we don't have to.
1081 unregister_candev(elm->dev);
1083 /* Decrease the refcount twice, once for our own get_elm(),
1084 * and once to remove the count of 1 that we set in _open().
1085 * Once it reaches 0, we can safely destroy it.
1090 /* Spin until refcount reaches 0 */
1091 while(atomic_read(&elm->refcount) > 0)
1094 /* At this point, all ldisc calls to us will be no-ops.
1095 * Since the refcount is 0, they are bailing immediately.
1098 /* Mark channel as dead */
1099 spin_lock_bh(&elm->lock);
1100 tty->disc_data = NULL;
1102 spin_unlock_bh(&elm->lock);
1104 /* Flush TTY side */
1105 flush_work(&elm->tx_work);
1107 netdev_info(elm->dev, "elmcan off %s.\n", tty->name);
1109 /* Free our memory */
1110 free_candev(elm->dev);
1113 static int elmcan_ldisc_hangup(struct tty_struct *tty)
1115 elmcan_ldisc_close(tty);
1119 /* Perform I/O control on an active elmcan channel. */
1120 static int elmcan_ldisc_ioctl(struct tty_struct *tty, struct file *file,
1121 unsigned int cmd, unsigned long arg)
1123 struct elmcan *elm = get_elm(tty);
1126 /* First make sure we're connected. */
1132 tmp = strlen(elm->ifname) + 1;
1133 if (copy_to_user((void __user *)arg, elm->ifname, tmp)) {
1147 return tty_mode_ioctl(tty, file, cmd, arg);
1151 static struct tty_ldisc_ops elmcan_ldisc = {
1152 .owner = THIS_MODULE,
1153 .magic = TTY_LDISC_MAGIC,
1155 .receive_buf = elmcan_ldisc_rx,
1156 .write_wakeup = elmcan_ldisc_tx_wakeup,
1157 .open = elmcan_ldisc_open,
1158 .close = elmcan_ldisc_close,
1159 .hangup = elmcan_ldisc_hangup,
1160 .ioctl = elmcan_ldisc_ioctl,
1167 /************************************************************************
1168 * Module init/exit *
1169 ************************************************************************/
1171 static int __init elmcan_init(void)
1175 pr_info("ELM327 based best-effort CAN interface driver\n");
1176 pr_info("This device is severely limited as a CAN interface, see documentation.\n");
1178 /* Fill in our line protocol discipline, and register it */
1179 status = tty_register_ldisc(N_ELMCAN, &elmcan_ldisc);
1181 pr_err("can't register line discipline\n");
1186 static void __exit elmcan_exit(void)
1188 /* This will only be called when all channels have been closed by
1189 * userspace - tty_ldisc.c takes care of the module's refcount.
1193 status = tty_unregister_ldisc(N_ELMCAN);
1195 pr_err("Can't unregister line discipline (error: %d)\n", status);
1199 module_init(elmcan_init);
1200 module_exit(elmcan_exit);