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/bitops.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>
41 MODULE_ALIAS_LDISC(N_ELMCAN);
42 MODULE_DESCRIPTION("ELM327 based CAN interface");
43 MODULE_LICENSE("GPL");
44 MODULE_AUTHOR("Max Staudt <max-linux@enpas.org>");
46 /* Line discipline ID number */
51 #define ELM327_CAN_CONFIG_SEND_SFF 0x8000
52 #define ELM327_CAN_CONFIG_VARIABLE_DLC 0x4000
53 #define ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF 0x2000
54 #define ELM327_CAN_CONFIG_BAUDRATE_MULT_8_7 0x1000
56 #define ELM327_MAGIC_CHAR 'y'
57 #define ELM327_MAGIC_STRING "y"
60 /* Bits in elm->cmds_todo */
62 ELM_TODO_CAN_DATA = 0,
64 ELM_TODO_CANID_29BIT_LOW,
65 ELM_TODO_CANID_29BIT_HIGH,
68 ELM_TODO_SILENT_MONITOR,
74 /* This must be the first member when using alloc_candev() */
77 /* TTY and netdev devices that we're bridging */
78 struct tty_struct *tty;
79 struct net_device *dev;
83 /* Per-channel lock */
87 struct work_struct tx_work; /* Flushes TTY TX buffer */
88 unsigned char txbuf[32];
89 unsigned char *txhead; /* Pointer to next TX byte */
90 int txleft; /* Bytes left to TX */
93 unsigned char rxbuf[256];
106 /* The CAN frame and config the ELM327 is sending/using,
107 * or will send/use after finishing all cmds_todo */
108 struct can_frame can_frame;
109 unsigned short can_config;
110 unsigned long can_bitrate;
111 unsigned char can_bitrate_divisor;
112 int silent_monitoring;
114 /* Things we have yet to send */
115 char **next_init_cmd;
116 unsigned long cmds_todo;
120 static DEFINE_SPINLOCK(elmcan_open_lock);
125 /************************************************************************
126 * ELM327: Transmission *
128 * (all functions assume elm->lock taken) *
129 ************************************************************************/
131 static void elm327_send(struct elmcan *elm, const void *buf, size_t len)
135 memcpy(elm->txbuf, buf, len);
137 /* Order of next two lines is *very* important.
138 * When we are sending a little amount of data,
139 * the transfer may be completed inside the ops->write()
140 * routine, because it's running with interrupts enabled.
141 * In this case we *never* got WRITE_WAKEUP event,
142 * if we did not request it before write operation.
143 * 14 Oct 1994 Dmitry Gorodchanin.
145 set_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
146 actual = elm->tty->ops->write(elm->tty, elm->txbuf, len);
147 elm->txleft = len - actual;
148 elm->txhead = elm->txbuf + actual;
153 * Take the ELM327 out of almost any state and back into command mode
155 * Assumes elm->lock taken.
157 static void elm327_kick_into_cmd_mode(struct elmcan *elm)
159 if (elm->state != ELM_GETMAGICCHAR && elm->state != ELM_GETPROMPT) {
160 elm327_send(elm, ELM327_MAGIC_STRING, 1);
162 elm->state = ELM_GETMAGICCHAR;
169 * Schedule a CAN frame, and any necessary config changes,
170 * to be sent down the TTY.
172 * Assumes elm->lock taken.
174 static void elm327_send_frame(struct elmcan *elm, struct can_frame *frame)
176 /* Schedule any necessary changes in ELM327's CAN configuration */
177 if (elm->can_frame.can_id != frame->can_id) {
178 /* Set the new CAN ID for transmission. */
179 if ((frame->can_id & CAN_EFF_FLAG) ^ (elm->can_frame.can_id & CAN_EFF_FLAG)) {
180 elm->can_config = (frame->can_id & CAN_EFF_FLAG ? 0 : ELM327_CAN_CONFIG_SEND_SFF)
181 | ELM327_CAN_CONFIG_VARIABLE_DLC
182 | ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF
183 | elm->can_bitrate_divisor;
185 set_bit(ELM_TODO_CAN_CONFIG, &elm->cmds_todo);
188 if (frame->can_id & CAN_EFF_FLAG) {
189 clear_bit(ELM_TODO_CANID_11BIT, &elm->cmds_todo);
190 set_bit(ELM_TODO_CANID_29BIT_LOW, &elm->cmds_todo);
191 set_bit(ELM_TODO_CANID_29BIT_HIGH, &elm->cmds_todo);
193 set_bit(ELM_TODO_CANID_11BIT, &elm->cmds_todo);
194 clear_bit(ELM_TODO_CANID_29BIT_LOW, &elm->cmds_todo);
195 clear_bit(ELM_TODO_CANID_29BIT_HIGH, &elm->cmds_todo);
199 /* Schedule the CAN frame itself. */
200 elm->can_frame = *frame;
201 set_bit(ELM_TODO_CAN_DATA, &elm->cmds_todo);
203 elm327_kick_into_cmd_mode(elm);
208 /************************************************************************
209 * ELM327: Initialization sequence *
211 * (assumes elm->lock taken) *
212 ************************************************************************/
214 static char *elm327_init_script[] = {
215 "AT WS\r", /* v1.0: Warm Start */
216 "AT PP FF OFF\r", /* v1.0: All Programmable Parameters Off */
217 "AT M0\r", /* v1.0: Memory Off */
218 "AT AL\r", /* v1.0: Allow Long messages */
219 "AT BI\r", /* v1.0: Bypass Initialization */
220 "AT CAF0\r", /* v1.0: CAN Auto Formatting Off */
221 "AT CFC0\r", /* v1.0: CAN Flow Control Off */
222 "AT CF 000\r", /* v1.0: Reset CAN ID Filter */
223 "AT CM 000\r", /* v1.0: Reset CAN ID Mask */
224 "AT E1\r", /* v1.0: Echo On */
225 "AT H1\r", /* v1.0: Headers On */
226 "AT L0\r", /* v1.0: Linefeeds Off */
227 "AT SH 7DF\r", /* v1.0: Set CAN sending ID to 0x7df */
228 "AT ST FF\r", /* v1.0: Set maximum Timeout for response after TX */
229 "AT AT0\r", /* v1.2: Adaptive Timing Off */
230 "AT D1\r", /* v1.3: Print DLC On */
231 "AT S1\r", /* v1.3: Spaces On */
232 "AT TP B\r", /* v1.0: Try Protocol B */
237 static void elm327_init(struct elmcan *elm)
239 elm->state = ELM_NOTINIT;
240 elm->can_frame.can_id = 0x7df;
242 elm->drop_next_line = 0;
244 /* We can only set the bitrate as a fraction of 500000.
245 * The bit timing constants in elmcan_bittiming_const will
246 * limit the user to the right values.
248 elm->can_bitrate_divisor = 500000 / elm->can.bittiming.bitrate;
249 elm->can_config = ELM327_CAN_CONFIG_SEND_SFF
250 | ELM327_CAN_CONFIG_VARIABLE_DLC
251 | ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF
252 | elm->can_bitrate_divisor;
254 /* Configure ELM327 and then start monitoring */
255 elm->next_init_cmd = &elm327_init_script[0];
256 set_bit(ELM_TODO_INIT, &elm->cmds_todo);
257 set_bit(ELM_TODO_SILENT_MONITOR, &elm->cmds_todo);
258 set_bit(ELM_TODO_RESPONSES, &elm->cmds_todo);
259 set_bit(ELM_TODO_CAN_CONFIG, &elm->cmds_todo);
261 elm327_kick_into_cmd_mode(elm);
266 /************************************************************************
267 * ELM327: Reception -> netdev glue *
269 * (assumes elm->lock taken) *
270 ************************************************************************/
272 static void elm327_feed_frame_to_netdev(struct elmcan *elm, const struct can_frame *frame)
274 struct can_frame *cf;
277 if (!netif_running(elm->dev)) {
281 skb = alloc_can_skb(elm->dev, &cf);
286 memcpy(cf, frame, sizeof(struct can_frame));
288 elm->dev->stats.rx_packets++;
289 elm->dev->stats.rx_bytes += frame->can_dlc;
292 can_led_event(elm->dev, CAN_LED_EVENT_RX);
297 /************************************************************************
298 * ELM327: Panic handler *
300 * (assumes elm->lock taken) *
301 ************************************************************************/
303 static inline void elm327_panic(struct elmcan *elm)
305 struct can_frame frame = {0};
307 frame.can_id = CAN_ERR_FLAG | CAN_ERR_RESTARTED;
308 frame.can_dlc = CAN_ERR_DLC;
309 elm327_feed_frame_to_netdev(elm, &frame);
311 pr_err("ELM327 misbehaved. Re-initializing.\n");
313 elm->can.can_stats.restarts++;
319 /************************************************************************
320 * ELM327: Reception parser *
322 * (assumes elm->lock taken) *
323 ************************************************************************/
325 static void elm327_parse_error(struct elmcan *elm, int len)
327 struct can_frame frame = {0};
329 frame.can_id = CAN_ERR_FLAG;
330 frame.can_dlc = CAN_ERR_DLC;
334 if (!memcmp(elm->rxbuf, "UNABLE TO CONNECT", 17)) {
335 pr_err("The ELM327 reported UNABLE TO CONNECT. Please check your setup.\n");
339 if (!memcmp(elm->rxbuf, "BUFFER FULL", 11)) {
340 /* This case will only happen if the last data
342 * Otherwise, elm327_parse_frame() will emit the
343 * error frame instead.
345 frame.can_id |= CAN_ERR_CRTL;
346 frame.data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
350 if (!memcmp(elm->rxbuf, "BUS ERROR", 9)) {
351 frame.can_id |= CAN_ERR_BUSERROR;
353 if (!memcmp(elm->rxbuf, "CAN ERROR", 9)
354 || !memcmp(elm->rxbuf, "<RX ERROR", 9)) {
355 frame.can_id |= CAN_ERR_PROT;
359 if (!memcmp(elm->rxbuf, "BUS BUSY", 8)) {
360 frame.can_id |= CAN_ERR_PROT;
361 frame.data[2] = CAN_ERR_PROT_OVERLOAD;
363 if (!memcmp(elm->rxbuf, "FB ERROR", 8)) {
364 frame.can_id |= CAN_ERR_PROT;
365 frame.data[2] = CAN_ERR_PROT_TX;
369 if (!memcmp(elm->rxbuf, "ERR", 3)) {
370 pr_err("The ELM327 reported an ERR%c%c. Please power it off and on again.\n",
371 elm->rxbuf[3], elm->rxbuf[4]);
372 frame.can_id |= CAN_ERR_CRTL;
376 /* Don't emit an error frame if we're unsure */
380 elm327_feed_frame_to_netdev(elm, &frame);
384 static int elm327_parse_frame(struct elmcan *elm, int len)
386 struct can_frame frame = {0};
391 /* Find first non-hex and non-space character:
392 * - In the simplest case, there is none.
393 * - For RTR frames, 'R' is the first non-hex character.
394 * - An error message may replace the end of the data line.
396 for (hexlen = 0; hexlen <= len; hexlen++) {
397 if (hex_to_bin(elm->rxbuf[hexlen]) < 0
398 && elm->rxbuf[hexlen] != ' ') {
403 /* Use spaces in CAN ID to distinguish 29 or 11 bit address length.
404 * No out-of-bounds access:
405 * We use the fact that we can always read from elm->rxbuf.
407 if (elm->rxbuf[2] == ' ' && elm->rxbuf[5] == ' '
408 && elm->rxbuf[8] == ' ' && elm->rxbuf[11] == ' '
409 && elm->rxbuf[13] == ' ') {
410 frame.can_id = CAN_EFF_FLAG;
412 } else if (elm->rxbuf[3] == ' ' && elm->rxbuf[5] == ' ') {
416 /* This is not a well-formatted data line.
417 * Assume it's an error message.
422 if (hexlen < datastart) {
423 /* The line is too short to be a valid frame hex dump.
424 * Something interrupted the hex dump or it is invalid.
429 /* From here on all chars up to buf[hexlen] are hex or spaces,
430 * at well-defined offsets.
433 /* Read CAN data length */
434 frame.can_dlc = (hex_to_bin(elm->rxbuf[datastart - 2]) << 0);
437 if (frame.can_id & CAN_EFF_FLAG) {
438 frame.can_id |= (hex_to_bin(elm->rxbuf[0]) << 28)
439 | (hex_to_bin(elm->rxbuf[1]) << 24)
440 | (hex_to_bin(elm->rxbuf[3]) << 20)
441 | (hex_to_bin(elm->rxbuf[4]) << 16)
442 | (hex_to_bin(elm->rxbuf[6]) << 12)
443 | (hex_to_bin(elm->rxbuf[7]) << 8)
444 | (hex_to_bin(elm->rxbuf[9]) << 4)
445 | (hex_to_bin(elm->rxbuf[10]) << 0);
447 frame.can_id |= (hex_to_bin(elm->rxbuf[0]) << 8)
448 | (hex_to_bin(elm->rxbuf[1]) << 4)
449 | (hex_to_bin(elm->rxbuf[2]) << 0);
452 /* Check for RTR frame */
453 if (elm->rxfill >= hexlen + 3
454 && elm->rxbuf[hexlen + 0] == 'R'
455 && elm->rxbuf[hexlen + 1] == 'T'
456 && elm->rxbuf[hexlen + 2] == 'R') {
457 frame.can_id |= CAN_RTR_FLAG;
460 /* Is the line long enough to hold the advertised payload? */
461 if (!(frame.can_id & CAN_RTR_FLAG) && (hexlen < frame.can_dlc * 3 + datastart)) {
462 /* Incomplete frame. */
464 /* Probably the ELM327's RS232 TX buffer was full.
465 * Emit an error frame and exit.
467 frame.can_id = CAN_ERR_FLAG | CAN_ERR_CRTL;
468 frame.can_dlc = CAN_ERR_DLC;
469 frame.data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
470 elm327_feed_frame_to_netdev(elm, &frame);
472 /* Signal failure to parse.
473 * The line will be re-parsed as an error line, which will fail.
474 * However, this will correctly drop the state machine back into
480 /* Parse the data nibbles. */
481 for (i = 0; i < frame.can_dlc; i++) {
482 frame.data[i] = (hex_to_bin(elm->rxbuf[datastart+3*i]) << 4)
483 | (hex_to_bin(elm->rxbuf[datastart+3*i+1]) << 0);
486 /* Feed the frame to the network layer. */
487 elm327_feed_frame_to_netdev(elm, &frame);
493 static void elm327_parse_line(struct elmcan *elm, int len)
495 /* Skip empty lines */
500 /* Skip echo lines */
501 if (elm->drop_next_line) {
502 elm->drop_next_line = 0;
504 } else if (elm->rxbuf[0] == 'A' && elm->rxbuf[1] == 'T') {
508 /* Regular parsing */
511 if (elm327_parse_frame(elm, len)) {
512 /* Parse an error line. */
513 elm327_parse_error(elm, len);
515 /* After the error line, we expect a prompt. */
516 elm->state = ELM_GETPROMPT;
525 static void elm327_handle_prompt(struct elmcan *elm)
527 if (elm->cmds_todo) {
528 struct can_frame *frame = &elm->can_frame;
531 if (test_bit(ELM_TODO_INIT, &elm->cmds_todo)) {
532 elm327_send(elm, *elm->next_init_cmd, strlen(*elm->next_init_cmd));
533 elm->next_init_cmd++;
534 if (!(*elm->next_init_cmd)) {
535 clear_bit(ELM_TODO_INIT, &elm->cmds_todo);
536 pr_info("%s: Initialization finished.\n", elm->dev->name);
539 /* Some chips are unreliable and need extra time after
540 * init commands, as seen with a clone.
541 * So let's do a dummy get-cmd-prompt dance.
543 elm->state = ELM_NOTINIT;
544 elm327_kick_into_cmd_mode(elm);
545 } else if (test_and_clear_bit(ELM_TODO_SILENT_MONITOR, &elm->cmds_todo)) {
546 snprintf(txbuf, sizeof(txbuf), "ATCSM%i\r", !(!(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY)));
547 } else if (test_and_clear_bit(ELM_TODO_RESPONSES, &elm->cmds_todo)) {
548 snprintf(txbuf, sizeof(txbuf), "ATR%i\r", !(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY));
549 } else if (test_and_clear_bit(ELM_TODO_CAN_CONFIG, &elm->cmds_todo)) {
550 snprintf(txbuf, sizeof(txbuf), "ATPB%04X\r", elm->can_config);
551 } else if (test_and_clear_bit(ELM_TODO_CANID_29BIT_HIGH, &elm->cmds_todo)) {
552 snprintf(txbuf, sizeof(txbuf), "ATCP%02X\r", (frame->can_id & CAN_EFF_MASK) >> 24);
553 } else if (test_and_clear_bit(ELM_TODO_CANID_29BIT_LOW, &elm->cmds_todo)) {
554 snprintf(txbuf, sizeof(txbuf), "ATSH%06X\r", frame->can_id & CAN_EFF_MASK & ((1 << 24) - 1));
555 } else if (test_and_clear_bit(ELM_TODO_CANID_11BIT, &elm->cmds_todo)) {
556 snprintf(txbuf, sizeof(txbuf), "ATSH%03X\r", frame->can_id & CAN_SFF_MASK);
557 } else if (test_and_clear_bit(ELM_TODO_CAN_DATA, &elm->cmds_todo)) {
558 if (frame->can_id & CAN_RTR_FLAG) {
559 snprintf(txbuf, sizeof(txbuf), "ATRTR\r");
563 for (i = 0; i < frame->can_dlc; i++) {
564 sprintf(&txbuf[2*i], "%02X", frame->data[i]);
567 sprintf(&txbuf[2*i], "\r");
570 elm->drop_next_line = 1;
571 elm->state = ELM_RECEIVING;
574 elm327_send(elm, txbuf, strlen(txbuf));
576 /* Enter CAN monitor mode */
577 elm327_send(elm, "ATMA\r", 5);
578 elm->state = ELM_RECEIVING;
583 static void elm327_drop_bytes(struct elmcan *elm, int i)
585 memmove(&elm->rxbuf[0], &elm->rxbuf[i], sizeof(elm->rxbuf) - i);
590 static void elm327_parse_rxbuf(struct elmcan *elm)
594 switch (elm->state) {
599 case ELM_GETMAGICCHAR:
601 /* Wait for 'y' or '>' */
604 for (i = 0; i < elm->rxfill; i++) {
605 if (elm->rxbuf[i] == ELM327_MAGIC_CHAR) {
606 elm327_send(elm, "\r", 1);
607 elm->state = ELM_GETPROMPT;
610 } else if (elm->rxbuf[i] == '>') {
611 elm327_send(elm, ELM327_MAGIC_STRING, 1);
617 elm327_drop_bytes(elm, i);
624 if (elm->rxbuf[elm->rxfill - 1] == '>') {
625 elm327_handle_prompt(elm);
632 /* Find <CR> delimiting feedback lines. */
634 (len < elm->rxfill) && (elm->rxbuf[len] != '\r');
639 if (len == sizeof(elm->rxbuf)) {
640 /* Line exceeds buffer. It's probably all garbage.
641 * Did we even connect at the right baud rate?
643 pr_err("RX buffer overflow. Faulty ELM327 connected?\n");
645 } else if (len == elm->rxfill) {
646 if (elm->state == ELM_RECEIVING
647 && elm->rxbuf[elm->rxfill - 1] == '>') {
648 /* The ELM327's AT ST response timeout ran out,
649 * so we got a prompt.
650 * Clear RX buffer and restart listening.
654 elm327_handle_prompt(elm);
657 /* We haven't received a full line yet.
658 * Wait for more data.
664 /* We have a full line to parse. */
665 elm327_parse_line(elm, len);
667 /* Remove parsed data from RX buffer. */
668 elm327_drop_bytes(elm, len+1);
670 /* More data to parse? */
672 elm327_parse_rxbuf(elm);
681 /************************************************************************
684 * (takes elm->lock) *
685 ************************************************************************/
687 /* Netdevice DOWN -> UP routine */
688 static int elmcan_netdev_open(struct net_device *dev)
690 struct elmcan *elm = netdev_priv(dev);
693 spin_lock_bh(&elm->lock);
694 if (elm->tty == NULL) {
695 spin_unlock_bh(&elm->lock);
699 /* open_candev() checks for elm->can.bittiming.bitrate != 0 */
700 err = open_candev(dev);
702 spin_unlock_bh(&elm->lock);
706 /* Initialize the ELM327 */
708 spin_unlock_bh(&elm->lock);
710 can_led_event(dev, CAN_LED_EVENT_OPEN);
711 elm->can.state = CAN_STATE_ERROR_ACTIVE;
712 netif_start_queue(dev);
717 /* Netdevice UP -> DOWN routine */
718 static int elmcan_netdev_close(struct net_device *dev)
720 struct elmcan *elm = netdev_priv(dev);
722 spin_lock_bh(&elm->lock);
724 /* TTY discipline is running. */
726 /* Interrupt whatever we're doing right now */
727 elm327_send(elm, ELM327_MAGIC_STRING, 1);
729 /* Clear the wakeup bit, as the netdev will be down and thus
730 * the wakeup handler won't clear it
732 clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
734 spin_unlock_bh(&elm->lock);
736 flush_work(&elm->tx_work);
738 spin_unlock_bh(&elm->lock);
741 elm->can.state = CAN_STATE_STOPPED;
742 netif_stop_queue(dev);
744 can_led_event(dev, CAN_LED_EVENT_STOP);
749 /* Send a can_frame to a TTY queue. */
750 static netdev_tx_t elmcan_netdev_start_xmit(struct sk_buff *skb, struct net_device *dev)
752 struct elmcan *elm = netdev_priv(dev);
753 struct can_frame *frame = (struct can_frame *) skb->data;
755 if (skb->len != sizeof(struct can_frame))
758 if (!netif_running(dev)) {
759 pr_warn("%s: xmit: iface is down\n", dev->name);
763 /* BHs are already disabled, so no spin_lock_bh().
764 * See Documentation/networking/netdevices.txt
766 spin_lock(&elm->lock);
768 || elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY) {
769 spin_unlock(&elm->lock);
773 netif_stop_queue(dev);
775 elm327_send_frame(elm, frame);
776 spin_unlock(&elm->lock);
778 dev->stats.tx_packets++;
779 dev->stats.tx_bytes += frame->can_dlc;
781 can_led_event(dev, CAN_LED_EVENT_TX);
788 static int elmcan_netdev_change_mtu(struct net_device *dev, int new_mtu)
793 static const struct net_device_ops elmcan_netdev_ops = {
794 .ndo_open = elmcan_netdev_open,
795 .ndo_stop = elmcan_netdev_close,
796 .ndo_start_xmit = elmcan_netdev_start_xmit,
797 .ndo_change_mtu = elmcan_netdev_change_mtu,
804 /************************************************************************
807 * (takes elm->lock) *
808 ************************************************************************/
811 * Handle the 'receiver data ready' interrupt.
812 * This function is called by the 'tty_io' module in the kernel when
813 * a block of ELM327 CAN data has been received, which can now be parsed
814 * and sent on to some IP layer for further processing. This will not
815 * be re-entered while running but other ldisc functions may be called
818 static void elmcan_ldisc_rx(struct tty_struct *tty,
819 const unsigned char *cp, char *fp, int count)
821 struct elmcan *elm = (struct elmcan *) tty->disc_data;
826 /* Read the characters out of the buffer */
827 while (count-- && elm->rxfill < sizeof(elm->rxbuf)) {
829 pr_err("Error in received character stream. Check your wiring.");
831 spin_lock_bh(&elm->lock);
833 spin_unlock_bh(&elm->lock);
837 elm->rxbuf[elm->rxfill++] = *cp;
843 pr_err("Receive buffer overflowed. Bad chip or wiring?");
845 spin_lock_bh(&elm->lock);
847 spin_unlock_bh(&elm->lock);
851 spin_lock_bh(&elm->lock);
852 elm327_parse_rxbuf(elm);
853 spin_unlock_bh(&elm->lock);
857 * Write out remaining transmit buffer.
858 * Scheduled when TTY is writable.
860 static void elmcan_ldisc_tx_worker(struct work_struct *work)
862 struct elmcan *elm = container_of(work, struct elmcan, tx_work);
865 spin_lock_bh(&elm->lock);
866 /* First make sure we're connected. */
867 if (!elm->tty || !netif_running(elm->dev)) {
868 spin_unlock_bh(&elm->lock);
872 if (elm->txleft <= 0) {
873 /* Our TTY write buffer is empty:
874 * We can start transmission of another packet
876 clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
877 spin_unlock_bh(&elm->lock);
878 netif_wake_queue(elm->dev);
882 actual = elm->tty->ops->write(elm->tty, elm->txhead, elm->txleft);
884 pr_err("Failed to write to tty for %s.\n", elm->dev->name);
888 elm->txleft -= actual;
889 elm->txhead += actual;
890 spin_unlock_bh(&elm->lock);
895 * Called by the driver when there's room for more data.
896 * Schedule the transmit.
898 static void elmcan_ldisc_tx_wakeup(struct tty_struct *tty)
900 struct elmcan *elm = tty->disc_data;
902 schedule_work(&elm->tx_work);
907 /* Some fake bit timings to allow bitrate setting */
908 static const struct can_bittiming_const elmcan_bittiming_const = {
921 * Open the high-level part of the elmcan channel.
922 * This function is called by the TTY module when the
923 * elmcan line discipline is called for.
925 * Called in process context serialized from other ldisc calls.
927 static int elmcan_ldisc_open(struct tty_struct *tty)
929 struct net_device *dev;
933 if (!capable(CAP_NET_ADMIN))
936 if (!tty->ops->write)
939 elm = tty->disc_data;
941 /* First make sure we're not already connected.
942 * Also, protect against simlutaneous open calls. */
943 spin_lock_bh(&elmcan_open_lock);
945 spin_unlock_bh(&elmcan_open_lock);
948 spin_unlock_bh(&elmcan_open_lock);
950 /* OK. Find a free elmcan channel to use. */
951 dev = alloc_candev(sizeof(struct elmcan), 0);
954 elm = netdev_priv(dev);
956 /* Configure TTY interface */
957 tty->receive_room = 65536; /* We don't flow control */
958 elm->txleft = 0; /* Clear TTY TX buffer */
959 spin_lock_init(&elm->lock);
960 INIT_WORK(&elm->tx_work, elmcan_ldisc_tx_worker);
962 /* Configure CAN metadata */
963 elm->can.state = CAN_STATE_STOPPED;
964 elm->can.clock.freq = 1000000;
965 elm->can.bittiming_const = &elmcan_bittiming_const;
966 elm->can.ctrlmode_supported = CAN_CTRLMODE_LISTENONLY;
968 /* Configure netlink interface */
970 dev->netdev_ops = &elmcan_netdev_ops;
972 /* Mark ldisc channel as alive */
974 tty->disc_data = elm;
976 devm_can_led_init(elm->dev);
979 err = register_candev(elm->dev);
981 free_candev(elm->dev);
989 * Close down an elmcan channel.
990 * This means flushing out any pending queues, and then returning.
991 * This call is serialized against other ldisc functions:
992 * Once this is called, no other ldisc function of ours is entered.
994 * We also use this function for a hangup event.
996 static void elmcan_ldisc_close(struct tty_struct *tty)
998 struct elmcan *elm = (struct elmcan *) tty->disc_data;
1000 /* First make sure we're connected. */
1004 /* Flush network side */
1005 unregister_candev(elm->dev);
1007 /* Mark channel as dead */
1008 spin_lock_bh(&elm->lock);
1009 tty->disc_data = NULL;
1011 spin_unlock_bh(&elm->lock);
1013 /* Flush TTY side */
1014 flush_work(&elm->tx_work);
1016 /* Free our memory */
1017 free_candev(elm->dev);
1020 static int elmcan_ldisc_hangup(struct tty_struct *tty)
1022 elmcan_ldisc_close(tty);
1026 /* Perform I/O control on an active elmcan channel. */
1027 static int elmcan_ldisc_ioctl(struct tty_struct *tty, struct file *file,
1028 unsigned int cmd, unsigned long arg)
1030 struct elmcan *elm = (struct elmcan *) tty->disc_data;
1033 /* First make sure we're connected. */
1039 tmp = strlen(elm->dev->name) + 1;
1040 if (copy_to_user((void __user *)arg, elm->dev->name, tmp))
1048 return tty_mode_ioctl(tty, file, cmd, arg);
1052 static struct tty_ldisc_ops elmcan_ldisc = {
1053 .owner = THIS_MODULE,
1054 .magic = TTY_LDISC_MAGIC,
1056 .receive_buf = elmcan_ldisc_rx,
1057 .write_wakeup = elmcan_ldisc_tx_wakeup,
1058 .open = elmcan_ldisc_open,
1059 .close = elmcan_ldisc_close,
1060 .hangup = elmcan_ldisc_hangup,
1061 .ioctl = elmcan_ldisc_ioctl,
1068 /************************************************************************
1069 * Module init/exit *
1070 ************************************************************************/
1072 static int __init elmcan_init(void)
1076 pr_info("ELM327 based best-effort CAN interface driver\n");
1077 pr_info("This device is severely limited as a CAN interface, see documentation.\n");
1079 /* Fill in our line protocol discipline, and register it */
1080 status = tty_register_ldisc(N_ELMCAN, &elmcan_ldisc);
1082 pr_err("can't register line discipline\n");
1087 static void __exit elmcan_exit(void)
1089 /* This will only be called when all channels have been closed by
1090 * userspace - tty_ldisc.c takes care of the module's refcount.
1094 status = tty_unregister_ldisc(N_ELMCAN);
1096 pr_err("Can't unregister line discipline (error: %d)\n", status);
1100 module_init(elmcan_init);
1101 module_exit(elmcan_exit);