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 *
127 ************************************************************************/
129 static void elm327_send(struct elmcan *elm, const void *buf, size_t len)
133 memcpy(elm->txbuf, buf, len);
135 /* Order of next two lines is *very* important.
136 * When we are sending a little amount of data,
137 * the transfer may be completed inside the ops->write()
138 * routine, because it's running with interrupts enabled.
139 * In this case we *never* got WRITE_WAKEUP event,
140 * if we did not request it before write operation.
141 * 14 Oct 1994 Dmitry Gorodchanin.
143 set_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
144 actual = elm->tty->ops->write(elm->tty, elm->txbuf, len);
145 elm->txleft = len - actual;
146 elm->txhead = elm->txbuf + actual;
150 static void elm327_kick_into_cmd_mode(struct elmcan *elm)
152 if (elm->state != ELM_GETMAGICCHAR && elm->state != ELM_GETPROMPT) {
153 elm327_send(elm, ELM327_MAGIC_STRING, 1);
155 elm->state = ELM_GETMAGICCHAR;
161 static void elm327_send_frame(struct elmcan *elm, struct can_frame *frame)
163 if (elm->can_frame.can_id != frame->can_id) {
164 /* Set the new CAN ID for transmission. */
165 if ((frame->can_id & CAN_EFF_FLAG) ^ (elm->can_frame.can_id & CAN_EFF_FLAG)) {
166 elm->can_config = (frame->can_id & CAN_EFF_FLAG ? 0 : ELM327_CAN_CONFIG_SEND_SFF)
167 | ELM327_CAN_CONFIG_VARIABLE_DLC
168 | ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF
169 | elm->can_bitrate_divisor;
171 set_bit(ELM_TODO_CAN_CONFIG, &elm->cmds_todo);
174 if (frame->can_id & CAN_EFF_FLAG) {
175 clear_bit(ELM_TODO_CANID_11BIT, &elm->cmds_todo);
176 set_bit(ELM_TODO_CANID_29BIT_LOW, &elm->cmds_todo);
177 set_bit(ELM_TODO_CANID_29BIT_HIGH, &elm->cmds_todo);
179 set_bit(ELM_TODO_CANID_11BIT, &elm->cmds_todo);
180 clear_bit(ELM_TODO_CANID_29BIT_LOW, &elm->cmds_todo);
181 clear_bit(ELM_TODO_CANID_29BIT_HIGH, &elm->cmds_todo);
185 elm->can_frame = *frame;
186 set_bit(ELM_TODO_CAN_DATA, &elm->cmds_todo);
188 elm327_kick_into_cmd_mode(elm);
193 /************************************************************************
194 * ELM327: Initialization sequence *
195 ************************************************************************/
197 static char *elm327_init_script[] = {
198 "AT WS\r", /* v1.0: Warm Start */
199 "AT PP FF OFF\r", /* v1.0: All Programmable Parameters Off */
200 "AT M0\r", /* v1.0: Memory Off */
201 "AT AL\r", /* v1.0: Allow Long messages */
202 "AT BI\r", /* v1.0: Bypass Initialization */
203 "AT CAF0\r", /* v1.0: CAN Auto Formatting Off */
204 "AT CFC0\r", /* v1.0: CAN Flow Control Off */
205 "AT CF 000\r", /* v1.0: Reset CAN ID Filter */
206 "AT CM 000\r", /* v1.0: Reset CAN ID Mask */
207 "AT E1\r", /* v1.0: Echo On */
208 "AT H1\r", /* v1.0: Headers On */
209 "AT L0\r", /* v1.0: Linefeeds Off */
210 "AT SH 7DF\r", /* v1.0: Set CAN sending ID to 0x7df */
211 "AT ST FF\r", /* v1.0: Set maximum Timeout for response after TX */
212 "AT AT0\r", /* v1.2: Adaptive Timing Off */
213 "AT D1\r", /* v1.3: Print DLC On */
214 "AT S1\r", /* v1.3: Spaces On */
215 "AT TP B\r", /* v1.0: Try Protocol B */
220 static void elm327_init(struct elmcan *elm)
222 elm->state = ELM_NOTINIT;
223 elm->can_frame.can_id = 0x7df;
225 elm->drop_next_line = 0;
227 /* We can only set the bitrate as a fraction of 500000.
228 * The bit timing constants in elmcan_bittiming_const will
229 * limit the user to the right values.
231 elm->can_bitrate_divisor = 500000 / elm->can.bittiming.bitrate;
232 elm->can_config = ELM327_CAN_CONFIG_SEND_SFF
233 | ELM327_CAN_CONFIG_VARIABLE_DLC
234 | ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF
235 | elm->can_bitrate_divisor;
237 /* Configure ELM327 and then start monitoring */
238 elm->next_init_cmd = &elm327_init_script[0];
239 set_bit(ELM_TODO_INIT, &elm->cmds_todo);
240 set_bit(ELM_TODO_SILENT_MONITOR, &elm->cmds_todo);
241 set_bit(ELM_TODO_RESPONSES, &elm->cmds_todo);
242 set_bit(ELM_TODO_CAN_CONFIG, &elm->cmds_todo);
244 elm327_kick_into_cmd_mode(elm);
249 /************************************************************************
250 * ELM327: Reception -> netdev glue *
251 ************************************************************************/
253 static void elm327_feed_frame_to_netdev(struct elmcan *elm, const struct can_frame *frame)
255 struct can_frame *cf;
258 if (!netif_running(elm->dev)) {
262 skb = alloc_can_skb(elm->dev, &cf);
267 memcpy(cf, frame, sizeof(struct can_frame));
269 elm->dev->stats.rx_packets++;
270 elm->dev->stats.rx_bytes += frame->can_dlc;
273 can_led_event(elm->dev, CAN_LED_EVENT_RX);
278 /************************************************************************
279 * ELM327: Panic handler *
280 ************************************************************************/
282 static inline void elm327_panic(struct elmcan *elm)
284 struct can_frame frame = {0};
286 frame.can_id = CAN_ERR_FLAG | CAN_ERR_RESTARTED;
287 frame.can_dlc = CAN_ERR_DLC;
288 elm327_feed_frame_to_netdev(elm, &frame);
290 pr_err("ELM327 misbehaved. Re-initializing.\n");
292 elm->can.can_stats.restarts++;
298 /************************************************************************
299 * ELM327: Reception parser *
300 ************************************************************************/
302 static void elm327_parse_error(struct elmcan *elm, int len)
304 struct can_frame frame = {0};
306 frame.can_id = CAN_ERR_FLAG;
307 frame.can_dlc = CAN_ERR_DLC;
311 if (!memcmp(elm->rxbuf, "UNABLE TO CONNECT", 17)) {
312 pr_err("The ELM327 reported UNABLE TO CONNECT. Please check your setup.\n");
316 if (!memcmp(elm->rxbuf, "BUFFER FULL", 11)) {
317 /* This case will only happen if the last data
319 * Otherwise, elm327_parse_frame() will emit the
320 * error frame instead.
322 frame.can_id |= CAN_ERR_CRTL;
323 frame.data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
327 if (!memcmp(elm->rxbuf, "BUS ERROR", 9)) {
328 frame.can_id |= CAN_ERR_BUSERROR;
330 if (!memcmp(elm->rxbuf, "CAN ERROR", 9)
331 || !memcmp(elm->rxbuf, "<RX ERROR", 9)) {
332 frame.can_id |= CAN_ERR_PROT;
336 if (!memcmp(elm->rxbuf, "BUS BUSY", 8)) {
337 frame.can_id |= CAN_ERR_PROT;
338 frame.data[2] = CAN_ERR_PROT_OVERLOAD;
340 if (!memcmp(elm->rxbuf, "FB ERROR", 8)) {
341 frame.can_id |= CAN_ERR_PROT;
342 frame.data[2] = CAN_ERR_PROT_TX;
346 if (!memcmp(elm->rxbuf, "ERR", 3)) {
347 pr_err("The ELM327 reported an ERR%c%c. Please power it off and on again.\n",
348 elm->rxbuf[3], elm->rxbuf[4]);
349 frame.can_id |= CAN_ERR_CRTL;
353 /* Don't emit an error frame if we're unsure */
357 elm327_feed_frame_to_netdev(elm, &frame);
361 static int elm327_parse_frame(struct elmcan *elm, int len)
363 struct can_frame frame = {0};
368 /* Find first non-hex and non-space character:
369 * - In the simplest case, there is none.
370 * - For RTR frames, 'R' is the first non-hex character.
371 * - An error message may replace the end of the data line.
373 for (hexlen = 0; hexlen <= len; hexlen++) {
374 if (hex_to_bin(elm->rxbuf[hexlen]) < 0
375 && elm->rxbuf[hexlen] != ' ') {
380 /* Use spaces in CAN ID to distinguish 29 or 11 bit address length.
381 * No out-of-bounds access:
382 * We use the fact that we can always read from elm->rxbuf. */
383 if (elm->rxbuf[2] == ' ' && elm->rxbuf[5] == ' '
384 && elm->rxbuf[8] == ' ' && elm->rxbuf[11] == ' '
385 && elm->rxbuf[13] == ' ') {
386 frame.can_id = CAN_EFF_FLAG;
388 } else if (elm->rxbuf[3] == ' ' && elm->rxbuf[5] == ' ') {
392 /* This is not a well-formatted data line.
393 * Assume it's an error message. */
397 if (hexlen < datastart) {
398 /* The line is too short to be a valid frame hex dump.
399 * Something interrupted the hex dump or it is invalid. */
403 /* From here on all chars up to buf[hexlen] are hex or spaces,
404 * at well-defined offsets. */
406 /* Read CAN data length */
407 frame.can_dlc = (hex_to_bin(elm->rxbuf[datastart - 2]) << 0);
410 if (frame.can_id & CAN_EFF_FLAG) {
411 frame.can_id |= (hex_to_bin(elm->rxbuf[0]) << 28)
412 | (hex_to_bin(elm->rxbuf[1]) << 24)
413 | (hex_to_bin(elm->rxbuf[3]) << 20)
414 | (hex_to_bin(elm->rxbuf[4]) << 16)
415 | (hex_to_bin(elm->rxbuf[6]) << 12)
416 | (hex_to_bin(elm->rxbuf[7]) << 8)
417 | (hex_to_bin(elm->rxbuf[9]) << 4)
418 | (hex_to_bin(elm->rxbuf[10]) << 0);
420 frame.can_id |= (hex_to_bin(elm->rxbuf[0]) << 8)
421 | (hex_to_bin(elm->rxbuf[1]) << 4)
422 | (hex_to_bin(elm->rxbuf[2]) << 0);
425 /* Check for RTR frame */
426 if (elm->rxfill >= hexlen + 3
427 && elm->rxbuf[hexlen + 0] == 'R'
428 && elm->rxbuf[hexlen + 1] == 'T'
429 && elm->rxbuf[hexlen + 2] == 'R') {
430 frame.can_id |= CAN_RTR_FLAG;
433 /* Is the line long enough to hold the advertised payload? */
434 if (!(frame.can_id & CAN_RTR_FLAG) && (hexlen < frame.can_dlc * 3 + datastart)) {
435 /* Incomplete frame. */
437 /* Probably the ELM327's RS232 TX buffer was full.
438 * Emit an error frame and exit. */
439 frame.can_id = CAN_ERR_FLAG | CAN_ERR_CRTL;
440 frame.can_dlc = CAN_ERR_DLC;
441 frame.data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
442 elm327_feed_frame_to_netdev(elm, &frame);
444 /* Signal failure to parse.
445 * The line will be re-parsed as an error line, which will fail.
446 * However, this will correctly drop the state machine back into
452 /* Parse the data nibbles. */
453 for (i = 0; i < frame.can_dlc; i++) {
454 frame.data[i] = (hex_to_bin(elm->rxbuf[datastart+3*i]) << 4)
455 | (hex_to_bin(elm->rxbuf[datastart+3*i+1]) << 0);
458 /* Feed the frame to the network layer. */
459 elm327_feed_frame_to_netdev(elm, &frame);
465 static void elm327_parse_line(struct elmcan *elm, int len)
467 /* Skip empty lines */
472 /* Skip echo lines */
473 if (elm->drop_next_line) {
474 elm->drop_next_line = 0;
476 } else if (elm->rxbuf[0] == 'A' && elm->rxbuf[1] == 'T') {
480 /* Regular parsing */
483 if (elm327_parse_frame(elm, len)) {
484 /* Parse an error line. */
485 elm327_parse_error(elm, len);
487 /* After the error line, we expect a prompt. */
488 elm->state = ELM_GETPROMPT;
497 static void elm327_handle_prompt(struct elmcan *elm)
499 if (elm->cmds_todo) {
500 struct can_frame *frame = &elm->can_frame;
503 if (test_bit(ELM_TODO_INIT, &elm->cmds_todo)) {
504 elm327_send(elm, *elm->next_init_cmd, strlen(*elm->next_init_cmd));
505 elm->next_init_cmd++;
506 if (!(*elm->next_init_cmd)) {
507 clear_bit(ELM_TODO_INIT, &elm->cmds_todo);
508 pr_info("%s: Initialization finished.\n", elm->dev->name);
511 /* Some chips are unreliable and need extra time after
512 * init commands, as seen with a clone.
513 * So let's do a dummy get-cmd-prompt dance. */
514 elm->state = ELM_NOTINIT;
515 elm327_kick_into_cmd_mode(elm);
516 } else if (test_and_clear_bit(ELM_TODO_SILENT_MONITOR, &elm->cmds_todo)) {
517 snprintf(txbuf, sizeof(txbuf), "ATCSM%i\r", !(!(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY)));
518 } else if (test_and_clear_bit(ELM_TODO_RESPONSES, &elm->cmds_todo)) {
519 snprintf(txbuf, sizeof(txbuf), "ATR%i\r", !(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY));
520 } else if (test_and_clear_bit(ELM_TODO_CAN_CONFIG, &elm->cmds_todo)) {
521 snprintf(txbuf, sizeof(txbuf), "ATPB%04X\r", elm->can_config);
522 } else if (test_and_clear_bit(ELM_TODO_CANID_29BIT_HIGH, &elm->cmds_todo)) {
523 snprintf(txbuf, sizeof(txbuf), "ATCP%02X\r", (frame->can_id & CAN_EFF_MASK) >> 24);
524 } else if (test_and_clear_bit(ELM_TODO_CANID_29BIT_LOW, &elm->cmds_todo)) {
525 snprintf(txbuf, sizeof(txbuf), "ATSH%06X\r", frame->can_id & CAN_EFF_MASK & ((1 << 24) - 1));
526 } else if (test_and_clear_bit(ELM_TODO_CANID_11BIT, &elm->cmds_todo)) {
527 snprintf(txbuf, sizeof(txbuf), "ATSH%03X\r", frame->can_id & CAN_SFF_MASK);
528 } else if (test_and_clear_bit(ELM_TODO_CAN_DATA, &elm->cmds_todo)) {
529 if (frame->can_id & CAN_RTR_FLAG) {
530 snprintf(txbuf, sizeof(txbuf), "ATRTR\r");
534 for (i = 0; i < frame->can_dlc; i++) {
535 sprintf(&txbuf[2*i], "%02X", frame->data[i]);
538 sprintf(&txbuf[2*i], "\r");
541 elm->drop_next_line = 1;
542 elm->state = ELM_RECEIVING;
545 elm327_send(elm, txbuf, strlen(txbuf));
547 /* Enter CAN monitor mode */
548 elm327_send(elm, "ATMA\r", 5);
549 elm->state = ELM_RECEIVING;
554 static void elm327_drop_bytes(struct elmcan *elm, int i)
556 memmove(&elm->rxbuf[0], &elm->rxbuf[i], sizeof(elm->rxbuf) - i);
561 static void elm327_parse_rxbuf(struct elmcan *elm)
565 switch (elm->state) {
570 case ELM_GETMAGICCHAR:
572 /* Wait for 'y' or '>' */
575 for (i = 0; i < elm->rxfill; i++) {
576 if (elm->rxbuf[i] == ELM327_MAGIC_CHAR) {
577 elm327_send(elm, "\r", 1);
578 elm->state = ELM_GETPROMPT;
581 } else if (elm->rxbuf[i] == '>') {
582 elm327_send(elm, ELM327_MAGIC_STRING, 1);
588 elm327_drop_bytes(elm, i);
595 if (elm->rxbuf[elm->rxfill - 1] == '>') {
596 elm327_handle_prompt(elm);
603 /* Find <CR> delimiting feedback lines. */
605 (len < elm->rxfill) && (elm->rxbuf[len] != '\r');
610 if (len == sizeof(elm->rxbuf)) {
611 /* Line exceeds buffer. It's probably all garbage.
612 * Did we even connect at the right baud rate? */
613 pr_err("RX buffer overflow. Faulty ELM327 connected?\n");
615 } else if (len == elm->rxfill) {
616 if (elm->state == ELM_RECEIVING
617 && elm->rxbuf[elm->rxfill - 1] == '>') {
618 /* The ELM327's AT ST response timeout ran out,
619 * so we got a prompt.
620 * Clear RX buffer and restart listening. */
623 elm327_handle_prompt(elm);
626 /* We haven't received a full line yet. Wait for more data. */
631 /* We have a full line to parse. */
632 elm327_parse_line(elm, len);
634 /* Remove parsed data from RX buffer. */
635 elm327_drop_bytes(elm, len+1);
637 /* More data to parse? */
639 elm327_parse_rxbuf(elm);
648 /************************************************************************
650 ************************************************************************/
652 /* Netdevice DOWN -> UP routine */
653 static int elmcan_netdev_open(struct net_device *dev)
655 struct elmcan *elm = netdev_priv(dev);
658 spin_lock_bh(&elm->lock);
659 if (elm->tty == NULL) {
660 spin_unlock_bh(&elm->lock);
664 /* open_candev() checks for elm->can.bittiming.bitrate != 0 */
665 err = open_candev(dev);
667 spin_unlock_bh(&elm->lock);
671 /* Initialize the ELM327 */
673 spin_unlock_bh(&elm->lock);
675 can_led_event(dev, CAN_LED_EVENT_OPEN);
676 elm->can.state = CAN_STATE_ERROR_ACTIVE;
677 netif_start_queue(dev);
682 /* Netdevice UP -> DOWN routine */
683 static int elmcan_netdev_close(struct net_device *dev)
685 struct elmcan *elm = netdev_priv(dev);
687 spin_lock_bh(&elm->lock);
689 /* TTY discipline is running. */
691 /* Interrupt whatever we're doing right now */
692 elm327_send(elm, ELM327_MAGIC_STRING, 1);
694 /* Clear the wakeup bit, as the netdev will be down and thus
695 * the wakeup handler won't clear it
697 clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
699 spin_unlock_bh(&elm->lock);
701 flush_work(&elm->tx_work);
703 spin_unlock_bh(&elm->lock);
706 elm->can.state = CAN_STATE_STOPPED;
707 netif_stop_queue(dev);
709 can_led_event(dev, CAN_LED_EVENT_STOP);
714 /* Send a can_frame to a TTY queue. */
715 static netdev_tx_t elmcan_netdev_start_xmit(struct sk_buff *skb, struct net_device *dev)
717 struct elmcan *elm = netdev_priv(dev);
718 struct can_frame *frame = (struct can_frame *) skb->data;
720 if (skb->len != sizeof(struct can_frame))
723 if (!netif_running(dev)) {
724 pr_warn("%s: xmit: iface is down\n", dev->name);
728 /* BHs are already disabled, so no spin_lock_bh().
729 * See Documentation/networking/netdevices.txt
731 spin_lock(&elm->lock);
733 || elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY) {
734 spin_unlock(&elm->lock);
738 netif_stop_queue(dev);
740 elm327_send_frame(elm, frame);
741 spin_unlock(&elm->lock);
743 dev->stats.tx_packets++;
744 dev->stats.tx_bytes += frame->can_dlc;
746 can_led_event(dev, CAN_LED_EVENT_TX);
753 static int elmcan_netdev_change_mtu(struct net_device *dev, int new_mtu)
758 static const struct net_device_ops elmcan_netdev_ops = {
759 .ndo_open = elmcan_netdev_open,
760 .ndo_stop = elmcan_netdev_close,
761 .ndo_start_xmit = elmcan_netdev_start_xmit,
762 .ndo_change_mtu = elmcan_netdev_change_mtu,
769 /************************************************************************
771 ************************************************************************/
774 * Handle the 'receiver data ready' interrupt.
775 * This function is called by the 'tty_io' module in the kernel when
776 * a block of ELM327 CAN data has been received, which can now be parsed
777 * and sent on to some IP layer for further processing. This will not
778 * be re-entered while running but other ldisc functions may be called
781 static void elmcan_ldisc_rx(struct tty_struct *tty,
782 const unsigned char *cp, char *fp, int count)
784 struct elmcan *elm = (struct elmcan *) tty->disc_data;
789 /* Read the characters out of the buffer */
790 while (count-- && elm->rxfill < sizeof(elm->rxbuf)) {
792 pr_err("Error in received character stream. Check your wiring.");
794 spin_lock_bh(&elm->lock);
796 spin_unlock_bh(&elm->lock);
800 elm->rxbuf[elm->rxfill++] = *cp;
806 pr_err("Receive buffer overflowed. Bad chip or wiring?");
808 spin_lock_bh(&elm->lock);
810 spin_unlock_bh(&elm->lock);
814 spin_lock_bh(&elm->lock);
815 elm327_parse_rxbuf(elm);
816 spin_unlock_bh(&elm->lock);
819 /* Write out remaining transmit buffer.
820 * Scheduled when TTY is writable.
822 static void elmcan_ldisc_tx_worker(struct work_struct *work)
824 struct elmcan *elm = container_of(work, struct elmcan, tx_work);
827 spin_lock_bh(&elm->lock);
828 /* First make sure we're connected. */
829 if (!elm->tty || !netif_running(elm->dev)) {
830 spin_unlock_bh(&elm->lock);
834 if (elm->txleft <= 0) {
835 /* Our TTY write buffer is empty:
836 * We can start transmission of another packet
838 clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
839 spin_unlock_bh(&elm->lock);
840 netif_wake_queue(elm->dev);
844 actual = elm->tty->ops->write(elm->tty, elm->txhead, elm->txleft);
846 pr_err("Failed to write to tty for %s.\n", elm->dev->name);
850 elm->txleft -= actual;
851 elm->txhead += actual;
852 spin_unlock_bh(&elm->lock);
857 * Called by the driver when there's room for more data.
858 * Schedule the transmit.
860 static void elmcan_ldisc_tx_wakeup(struct tty_struct *tty)
862 struct elmcan *elm = tty->disc_data;
864 schedule_work(&elm->tx_work);
869 /* Some fake bit timings to allow bitrate setting */
870 static const struct can_bittiming_const elmcan_bittiming_const = {
883 * Open the high-level part of the elmcan channel.
884 * This function is called by the TTY module when the
885 * elmcan line discipline is called for.
887 * Called in process context serialized from other ldisc calls.
889 static int elmcan_ldisc_open(struct tty_struct *tty)
891 struct net_device *dev;
895 if (!capable(CAP_NET_ADMIN))
898 if (!tty->ops->write)
901 elm = tty->disc_data;
903 /* First make sure we're not already connected.
904 * Also, protect against simlutaneous open calls. */
905 spin_lock_bh(&elmcan_open_lock);
907 spin_unlock_bh(&elmcan_open_lock);
910 spin_unlock_bh(&elmcan_open_lock);
912 /* OK. Find a free elmcan channel to use. */
913 dev = alloc_candev(sizeof(struct elmcan), 0);
916 elm = netdev_priv(dev);
918 /* Configure TTY interface */
919 tty->receive_room = 65536; /* We don't flow control */
920 elm->txleft = 0; /* Clear TTY TX buffer */
921 spin_lock_init(&elm->lock);
922 INIT_WORK(&elm->tx_work, elmcan_ldisc_tx_worker);
924 /* Configure CAN metadata */
925 elm->can.state = CAN_STATE_STOPPED;
926 elm->can.clock.freq = 1000000;
927 elm->can.bittiming_const = &elmcan_bittiming_const;
928 elm->can.ctrlmode_supported = CAN_CTRLMODE_LISTENONLY;
930 /* Configure netlink interface */
932 dev->netdev_ops = &elmcan_netdev_ops;
934 /* Mark ldisc channel as alive */
936 tty->disc_data = elm;
938 devm_can_led_init(elm->dev);
941 err = register_candev(elm->dev);
943 free_candev(elm->dev);
951 * Close down an elmcan channel.
952 * This means flushing out any pending queues, and then returning. This
953 * call is serialized against other ldisc functions.
955 * We also use this method for a hangup event.
957 static void elmcan_ldisc_close(struct tty_struct *tty)
959 struct elmcan *elm = (struct elmcan *) tty->disc_data;
961 /* First make sure we're connected. */
965 /* Flush network side */
966 unregister_candev(elm->dev);
968 /* Mark channel as dead */
969 spin_lock_bh(&elm->lock);
970 tty->disc_data = NULL;
972 spin_unlock_bh(&elm->lock);
975 flush_work(&elm->tx_work);
977 /* Free our memory */
978 free_candev(elm->dev);
981 static int elmcan_ldisc_hangup(struct tty_struct *tty)
983 elmcan_ldisc_close(tty);
987 /* Perform I/O control on an active elmcan channel. */
988 static int elmcan_ldisc_ioctl(struct tty_struct *tty, struct file *file,
989 unsigned int cmd, unsigned long arg)
991 struct elmcan *elm = (struct elmcan *) tty->disc_data;
994 /* First make sure we're connected. */
1000 tmp = strlen(elm->dev->name) + 1;
1001 if (copy_to_user((void __user *)arg, elm->dev->name, tmp))
1009 return tty_mode_ioctl(tty, file, cmd, arg);
1013 static struct tty_ldisc_ops elmcan_ldisc = {
1014 .owner = THIS_MODULE,
1015 .magic = TTY_LDISC_MAGIC,
1017 .receive_buf = elmcan_ldisc_rx,
1018 .write_wakeup = elmcan_ldisc_tx_wakeup,
1019 .open = elmcan_ldisc_open,
1020 .close = elmcan_ldisc_close,
1021 .hangup = elmcan_ldisc_hangup,
1022 .ioctl = elmcan_ldisc_ioctl,
1029 /************************************************************************
1030 * Module init/exit *
1031 ************************************************************************/
1033 static int __init elmcan_init(void)
1037 pr_info("ELM327 based best-effort CAN interface driver\n");
1038 pr_info("This device is severely limited as a CAN interface, see documentation.\n");
1040 /* Fill in our line protocol discipline, and register it */
1041 status = tty_register_ldisc(N_ELMCAN, &elmcan_ldisc);
1043 pr_err("can't register line discipline\n");
1048 static void __exit elmcan_exit(void)
1050 /* This will only be called when all channels have been closed by
1051 * userspace - tty_ldisc.c takes care of the module's refcount.
1055 status = tty_unregister_ldisc(N_ELMCAN);
1057 pr_err("Can't unregister line discipline (error: %d)\n", status);
1061 module_init(elmcan_init);
1062 module_exit(elmcan_exit);