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 char ifname[IFNAMSIZ];
86 /* Per-channel lock */
89 /* Keep track of how many things are using this struct.
90 * Once it reaches 0, we are in the process of cleaning up,
91 * and new operations will be cancelled immediately.
92 * Use atomic_t rather than refcount_t because we deliberately
93 * decrement to 0, and refcount_dec() spills a WARN_ONCE in
99 struct work_struct tx_work; /* Flushes TTY TX buffer */
100 unsigned char txbuf[32];
101 unsigned char *txhead; /* Pointer to next TX byte */
102 int txleft; /* Bytes left to TX */
105 unsigned char rxbuf[256];
118 /* The CAN frame and config the ELM327 is sending/using,
119 * or will send/use after finishing all cmds_todo */
120 struct can_frame can_frame;
121 unsigned short can_config;
122 unsigned long can_bitrate;
123 unsigned char can_bitrate_divisor;
124 int silent_monitoring;
126 /* Things we have yet to send */
127 char **next_init_cmd;
128 unsigned long cmds_todo;
132 /* A lock for all tty->disc_data handled by this ldisc.
133 * This is to prevent a case where tty->disc_data is set to NULL,
134 * yet someone is still trying to dereference it.
135 * Without this, we cannot do a clean shutdown.
137 static DEFINE_SPINLOCK(elmcan_discdata_lock);
142 /************************************************************************
143 * ELM327: Transmission *
145 * (all functions assume elm->lock taken) *
146 ************************************************************************/
148 static void elm327_send(struct elmcan *elm, const void *buf, size_t len)
152 memcpy(elm->txbuf, buf, len);
154 /* Order of next two lines is *very* important.
155 * When we are sending a little amount of data,
156 * the transfer may be completed inside the ops->write()
157 * routine, because it's running with interrupts enabled.
158 * In this case we *never* got WRITE_WAKEUP event,
159 * if we did not request it before write operation.
160 * 14 Oct 1994 Dmitry Gorodchanin.
162 set_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
163 actual = elm->tty->ops->write(elm->tty, elm->txbuf, len);
164 elm->txleft = len - actual;
165 elm->txhead = elm->txbuf + actual;
170 * Take the ELM327 out of almost any state and back into command mode
172 * Assumes elm->lock taken.
174 static void elm327_kick_into_cmd_mode(struct elmcan *elm)
176 if (elm->state != ELM_GETMAGICCHAR && elm->state != ELM_GETPROMPT) {
177 elm327_send(elm, ELM327_MAGIC_STRING, 1);
179 elm->state = ELM_GETMAGICCHAR;
186 * Schedule a CAN frame, and any necessary config changes,
187 * to be sent down the TTY.
189 * Assumes elm->lock taken.
191 static void elm327_send_frame(struct elmcan *elm, struct can_frame *frame)
193 /* Schedule any necessary changes in ELM327's CAN configuration */
194 if (elm->can_frame.can_id != frame->can_id) {
195 /* Set the new CAN ID for transmission. */
196 if ((frame->can_id & CAN_EFF_FLAG) ^ (elm->can_frame.can_id & CAN_EFF_FLAG)) {
197 elm->can_config = (frame->can_id & CAN_EFF_FLAG ? 0 : ELM327_CAN_CONFIG_SEND_SFF)
198 | ELM327_CAN_CONFIG_VARIABLE_DLC
199 | ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF
200 | elm->can_bitrate_divisor;
202 set_bit(ELM_TODO_CAN_CONFIG, &elm->cmds_todo);
205 if (frame->can_id & CAN_EFF_FLAG) {
206 clear_bit(ELM_TODO_CANID_11BIT, &elm->cmds_todo);
207 set_bit(ELM_TODO_CANID_29BIT_LOW, &elm->cmds_todo);
208 set_bit(ELM_TODO_CANID_29BIT_HIGH, &elm->cmds_todo);
210 set_bit(ELM_TODO_CANID_11BIT, &elm->cmds_todo);
211 clear_bit(ELM_TODO_CANID_29BIT_LOW, &elm->cmds_todo);
212 clear_bit(ELM_TODO_CANID_29BIT_HIGH, &elm->cmds_todo);
216 /* Schedule the CAN frame itself. */
217 elm->can_frame = *frame;
218 set_bit(ELM_TODO_CAN_DATA, &elm->cmds_todo);
220 elm327_kick_into_cmd_mode(elm);
225 /************************************************************************
226 * ELM327: Initialization sequence *
228 * (assumes elm->lock taken) *
229 ************************************************************************/
231 static char *elm327_init_script[] = {
232 "AT WS\r", /* v1.0: Warm Start */
233 "AT PP FF OFF\r", /* v1.0: All Programmable Parameters Off */
234 "AT M0\r", /* v1.0: Memory Off */
235 "AT AL\r", /* v1.0: Allow Long messages */
236 "AT BI\r", /* v1.0: Bypass Initialization */
237 "AT CAF0\r", /* v1.0: CAN Auto Formatting Off */
238 "AT CFC0\r", /* v1.0: CAN Flow Control Off */
239 "AT CF 000\r", /* v1.0: Reset CAN ID Filter */
240 "AT CM 000\r", /* v1.0: Reset CAN ID Mask */
241 "AT E1\r", /* v1.0: Echo On */
242 "AT H1\r", /* v1.0: Headers On */
243 "AT L0\r", /* v1.0: Linefeeds Off */
244 "AT SH 7DF\r", /* v1.0: Set CAN sending ID to 0x7df */
245 "AT ST FF\r", /* v1.0: Set maximum Timeout for response after TX */
246 "AT AT0\r", /* v1.2: Adaptive Timing Off */
247 "AT D1\r", /* v1.3: Print DLC On */
248 "AT S1\r", /* v1.3: Spaces On */
249 "AT TP B\r", /* v1.0: Try Protocol B */
254 static void elm327_init(struct elmcan *elm)
256 elm->state = ELM_NOTINIT;
257 elm->can_frame.can_id = 0x7df;
259 elm->drop_next_line = 0;
261 /* We can only set the bitrate as a fraction of 500000.
262 * The bit timing constants in elmcan_bittiming_const will
263 * limit the user to the right values.
265 elm->can_bitrate_divisor = 500000 / elm->can.bittiming.bitrate;
266 elm->can_config = ELM327_CAN_CONFIG_SEND_SFF
267 | ELM327_CAN_CONFIG_VARIABLE_DLC
268 | ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF
269 | elm->can_bitrate_divisor;
271 /* Configure ELM327 and then start monitoring */
272 elm->next_init_cmd = &elm327_init_script[0];
273 set_bit(ELM_TODO_INIT, &elm->cmds_todo);
274 set_bit(ELM_TODO_SILENT_MONITOR, &elm->cmds_todo);
275 set_bit(ELM_TODO_RESPONSES, &elm->cmds_todo);
276 set_bit(ELM_TODO_CAN_CONFIG, &elm->cmds_todo);
278 elm327_kick_into_cmd_mode(elm);
283 /************************************************************************
284 * ELM327: Reception -> netdev glue *
286 * (assumes elm->lock taken) *
287 ************************************************************************/
289 static void elm327_feed_frame_to_netdev(struct elmcan *elm, const struct can_frame *frame)
291 struct can_frame *cf;
294 if (!netif_running(elm->dev)) {
298 skb = alloc_can_skb(elm->dev, &cf);
303 memcpy(cf, frame, sizeof(struct can_frame));
305 elm->dev->stats.rx_packets++;
306 elm->dev->stats.rx_bytes += frame->can_dlc;
309 can_led_event(elm->dev, CAN_LED_EVENT_RX);
314 /************************************************************************
315 * ELM327: Panic handler *
317 * (assumes elm->lock taken) *
318 ************************************************************************/
320 static inline void elm327_panic(struct elmcan *elm)
322 struct can_frame frame = {0};
324 frame.can_id = CAN_ERR_FLAG | CAN_ERR_RESTARTED;
325 frame.can_dlc = CAN_ERR_DLC;
326 elm327_feed_frame_to_netdev(elm, &frame);
328 pr_err("ELM327 misbehaved. Re-initializing.\n");
330 elm->can.can_stats.restarts++;
336 /************************************************************************
337 * ELM327: Reception parser *
339 * (assumes elm->lock taken) *
340 ************************************************************************/
342 static void elm327_parse_error(struct elmcan *elm, int len)
344 struct can_frame frame = {0};
346 frame.can_id = CAN_ERR_FLAG;
347 frame.can_dlc = CAN_ERR_DLC;
351 if (!memcmp(elm->rxbuf, "UNABLE TO CONNECT", 17)) {
352 pr_err("The ELM327 reported UNABLE TO CONNECT. Please check your setup.\n");
356 if (!memcmp(elm->rxbuf, "BUFFER FULL", 11)) {
357 /* This case will only happen if the last data
359 * Otherwise, elm327_parse_frame() will emit the
360 * error frame instead.
362 frame.can_id |= CAN_ERR_CRTL;
363 frame.data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
367 if (!memcmp(elm->rxbuf, "BUS ERROR", 9)) {
368 frame.can_id |= CAN_ERR_BUSERROR;
370 if (!memcmp(elm->rxbuf, "CAN ERROR", 9)
371 || !memcmp(elm->rxbuf, "<RX ERROR", 9)) {
372 frame.can_id |= CAN_ERR_PROT;
376 if (!memcmp(elm->rxbuf, "BUS BUSY", 8)) {
377 frame.can_id |= CAN_ERR_PROT;
378 frame.data[2] = CAN_ERR_PROT_OVERLOAD;
380 if (!memcmp(elm->rxbuf, "FB ERROR", 8)) {
381 frame.can_id |= CAN_ERR_PROT;
382 frame.data[2] = CAN_ERR_PROT_TX;
386 if (!memcmp(elm->rxbuf, "ERR", 3)) {
387 pr_err("The ELM327 reported an ERR%c%c. Please power it off and on again.\n",
388 elm->rxbuf[3], elm->rxbuf[4]);
389 frame.can_id |= CAN_ERR_CRTL;
393 /* Don't emit an error frame if we're unsure */
397 elm327_feed_frame_to_netdev(elm, &frame);
401 static int elm327_parse_frame(struct elmcan *elm, int len)
403 struct can_frame frame = {0};
408 /* Find first non-hex and non-space character:
409 * - In the simplest case, there is none.
410 * - For RTR frames, 'R' is the first non-hex character.
411 * - An error message may replace the end of the data line.
413 for (hexlen = 0; hexlen <= len; hexlen++) {
414 if (hex_to_bin(elm->rxbuf[hexlen]) < 0
415 && elm->rxbuf[hexlen] != ' ') {
420 /* Use spaces in CAN ID to distinguish 29 or 11 bit address length.
421 * No out-of-bounds access:
422 * We use the fact that we can always read from elm->rxbuf.
424 if (elm->rxbuf[2] == ' ' && elm->rxbuf[5] == ' '
425 && elm->rxbuf[8] == ' ' && elm->rxbuf[11] == ' '
426 && elm->rxbuf[13] == ' ') {
427 frame.can_id = CAN_EFF_FLAG;
429 } else if (elm->rxbuf[3] == ' ' && elm->rxbuf[5] == ' ') {
433 /* This is not a well-formatted data line.
434 * Assume it's an error message.
439 if (hexlen < datastart) {
440 /* The line is too short to be a valid frame hex dump.
441 * Something interrupted the hex dump or it is invalid.
446 /* From here on all chars up to buf[hexlen] are hex or spaces,
447 * at well-defined offsets.
450 /* Read CAN data length */
451 frame.can_dlc = (hex_to_bin(elm->rxbuf[datastart - 2]) << 0);
454 if (frame.can_id & CAN_EFF_FLAG) {
455 frame.can_id |= (hex_to_bin(elm->rxbuf[0]) << 28)
456 | (hex_to_bin(elm->rxbuf[1]) << 24)
457 | (hex_to_bin(elm->rxbuf[3]) << 20)
458 | (hex_to_bin(elm->rxbuf[4]) << 16)
459 | (hex_to_bin(elm->rxbuf[6]) << 12)
460 | (hex_to_bin(elm->rxbuf[7]) << 8)
461 | (hex_to_bin(elm->rxbuf[9]) << 4)
462 | (hex_to_bin(elm->rxbuf[10]) << 0);
464 frame.can_id |= (hex_to_bin(elm->rxbuf[0]) << 8)
465 | (hex_to_bin(elm->rxbuf[1]) << 4)
466 | (hex_to_bin(elm->rxbuf[2]) << 0);
469 /* Check for RTR frame */
470 if (elm->rxfill >= hexlen + 3
471 && elm->rxbuf[hexlen + 0] == 'R'
472 && elm->rxbuf[hexlen + 1] == 'T'
473 && elm->rxbuf[hexlen + 2] == 'R') {
474 frame.can_id |= CAN_RTR_FLAG;
477 /* Is the line long enough to hold the advertised payload? */
478 if (!(frame.can_id & CAN_RTR_FLAG) && (hexlen < frame.can_dlc * 3 + datastart)) {
479 /* Incomplete frame. */
481 /* Probably the ELM327's RS232 TX buffer was full.
482 * Emit an error frame and exit.
484 frame.can_id = CAN_ERR_FLAG | CAN_ERR_CRTL;
485 frame.can_dlc = CAN_ERR_DLC;
486 frame.data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
487 elm327_feed_frame_to_netdev(elm, &frame);
489 /* Signal failure to parse.
490 * The line will be re-parsed as an error line, which will fail.
491 * However, this will correctly drop the state machine back into
497 /* Parse the data nibbles. */
498 for (i = 0; i < frame.can_dlc; i++) {
499 frame.data[i] = (hex_to_bin(elm->rxbuf[datastart+3*i]) << 4)
500 | (hex_to_bin(elm->rxbuf[datastart+3*i+1]) << 0);
503 /* Feed the frame to the network layer. */
504 elm327_feed_frame_to_netdev(elm, &frame);
510 static void elm327_parse_line(struct elmcan *elm, int len)
512 /* Skip empty lines */
517 /* Skip echo lines */
518 if (elm->drop_next_line) {
519 elm->drop_next_line = 0;
521 } else if (elm->rxbuf[0] == 'A' && elm->rxbuf[1] == 'T') {
525 /* Regular parsing */
528 if (elm327_parse_frame(elm, len)) {
529 /* Parse an error line. */
530 elm327_parse_error(elm, len);
532 /* After the error line, we expect a prompt. */
533 elm->state = ELM_GETPROMPT;
542 static void elm327_handle_prompt(struct elmcan *elm)
544 if (elm->cmds_todo) {
545 struct can_frame *frame = &elm->can_frame;
548 if (test_bit(ELM_TODO_INIT, &elm->cmds_todo)) {
549 elm327_send(elm, *elm->next_init_cmd, strlen(*elm->next_init_cmd));
550 elm->next_init_cmd++;
551 if (!(*elm->next_init_cmd)) {
552 clear_bit(ELM_TODO_INIT, &elm->cmds_todo);
553 pr_info("%s: Initialization finished.\n", elm->dev->name);
556 /* Some chips are unreliable and need extra time after
557 * init commands, as seen with a clone.
558 * So let's do a dummy get-cmd-prompt dance.
560 elm->state = ELM_NOTINIT;
561 elm327_kick_into_cmd_mode(elm);
562 } else if (test_and_clear_bit(ELM_TODO_SILENT_MONITOR, &elm->cmds_todo)) {
563 snprintf(txbuf, sizeof(txbuf), "ATCSM%i\r", !(!(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY)));
564 } else if (test_and_clear_bit(ELM_TODO_RESPONSES, &elm->cmds_todo)) {
565 snprintf(txbuf, sizeof(txbuf), "ATR%i\r", !(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY));
566 } else if (test_and_clear_bit(ELM_TODO_CAN_CONFIG, &elm->cmds_todo)) {
567 snprintf(txbuf, sizeof(txbuf), "ATPB%04X\r", elm->can_config);
568 } else if (test_and_clear_bit(ELM_TODO_CANID_29BIT_HIGH, &elm->cmds_todo)) {
569 snprintf(txbuf, sizeof(txbuf), "ATCP%02X\r", (frame->can_id & CAN_EFF_MASK) >> 24);
570 } else if (test_and_clear_bit(ELM_TODO_CANID_29BIT_LOW, &elm->cmds_todo)) {
571 snprintf(txbuf, sizeof(txbuf), "ATSH%06X\r", frame->can_id & CAN_EFF_MASK & ((1 << 24) - 1));
572 } else if (test_and_clear_bit(ELM_TODO_CANID_11BIT, &elm->cmds_todo)) {
573 snprintf(txbuf, sizeof(txbuf), "ATSH%03X\r", frame->can_id & CAN_SFF_MASK);
574 } else if (test_and_clear_bit(ELM_TODO_CAN_DATA, &elm->cmds_todo)) {
575 if (frame->can_id & CAN_RTR_FLAG) {
576 snprintf(txbuf, sizeof(txbuf), "ATRTR\r");
580 for (i = 0; i < frame->can_dlc; i++) {
581 sprintf(&txbuf[2*i], "%02X", frame->data[i]);
584 sprintf(&txbuf[2*i], "\r");
587 elm->drop_next_line = 1;
588 elm->state = ELM_RECEIVING;
591 elm327_send(elm, txbuf, strlen(txbuf));
593 /* Enter CAN monitor mode */
594 elm327_send(elm, "ATMA\r", 5);
595 elm->state = ELM_RECEIVING;
600 static void elm327_drop_bytes(struct elmcan *elm, int i)
602 memmove(&elm->rxbuf[0], &elm->rxbuf[i], sizeof(elm->rxbuf) - i);
607 static void elm327_parse_rxbuf(struct elmcan *elm)
611 switch (elm->state) {
616 case ELM_GETMAGICCHAR:
618 /* Wait for 'y' or '>' */
621 for (i = 0; i < elm->rxfill; i++) {
622 if (elm->rxbuf[i] == ELM327_MAGIC_CHAR) {
623 elm327_send(elm, "\r", 1);
624 elm->state = ELM_GETPROMPT;
627 } else if (elm->rxbuf[i] == ELM327_READY_CHAR) {
628 elm327_send(elm, ELM327_MAGIC_STRING, 1);
634 elm327_drop_bytes(elm, i);
641 if (elm->rxbuf[elm->rxfill - 1] == ELM327_READY_CHAR) {
642 elm327_handle_prompt(elm);
649 /* Find <CR> delimiting feedback lines. */
651 (len < elm->rxfill) && (elm->rxbuf[len] != '\r');
656 if (len == sizeof(elm->rxbuf)) {
657 /* Line exceeds buffer. It's probably all garbage.
658 * Did we even connect at the right baud rate?
660 pr_err("RX buffer overflow. Faulty ELM327 connected?\n");
662 } else if (len == elm->rxfill) {
663 if (elm->state == ELM_RECEIVING
664 && elm->rxbuf[elm->rxfill - 1] == ELM327_READY_CHAR) {
665 /* The ELM327's AT ST response timeout ran out,
666 * so we got a prompt.
667 * Clear RX buffer and restart listening.
671 elm327_handle_prompt(elm);
674 /* We haven't received a full line yet.
675 * Wait for more data.
681 /* We have a full line to parse. */
682 elm327_parse_line(elm, len);
684 /* Remove parsed data from RX buffer. */
685 elm327_drop_bytes(elm, len+1);
687 /* More data to parse? */
689 elm327_parse_rxbuf(elm);
698 /************************************************************************
701 * (takes elm->lock) *
702 ************************************************************************/
704 static int elmcan_netdev_init(struct net_device *dev)
706 struct elmcan *elm = netdev_priv(dev);
708 /* Copy the interface name here, so the SIOCGIFNAME case in
709 * elmcan_ldisc_ioctl() doesn't race against unregister_candev().
711 memcpy(elm->ifname, dev->name, IFNAMSIZ);
716 /* Netdevice DOWN -> UP routine */
717 static int elmcan_netdev_open(struct net_device *dev)
719 struct elmcan *elm = netdev_priv(dev);
722 spin_lock_bh(&elm->lock);
723 if (elm->tty == NULL) {
724 spin_unlock_bh(&elm->lock);
728 /* open_candev() checks for elm->can.bittiming.bitrate != 0 */
729 err = open_candev(dev);
731 spin_unlock_bh(&elm->lock);
735 /* Initialize the ELM327 */
737 spin_unlock_bh(&elm->lock);
739 can_led_event(dev, CAN_LED_EVENT_OPEN);
740 elm->can.state = CAN_STATE_ERROR_ACTIVE;
741 netif_start_queue(dev);
746 /* Netdevice UP -> DOWN routine */
747 static int elmcan_netdev_close(struct net_device *dev)
749 struct elmcan *elm = netdev_priv(dev);
751 spin_lock_bh(&elm->lock);
753 /* TTY discipline is running. */
755 /* Interrupt whatever we're doing right now */
756 elm327_send(elm, ELM327_MAGIC_STRING, 1);
758 /* Clear the wakeup bit, as the netdev will be down and thus
759 * the wakeup handler won't clear it
761 clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
763 spin_unlock_bh(&elm->lock);
765 flush_work(&elm->tx_work);
767 spin_unlock_bh(&elm->lock);
770 elm->can.state = CAN_STATE_STOPPED;
771 netif_stop_queue(dev);
773 can_led_event(dev, CAN_LED_EVENT_STOP);
778 /* Send a can_frame to a TTY queue. */
779 static netdev_tx_t elmcan_netdev_start_xmit(struct sk_buff *skb, struct net_device *dev)
781 struct elmcan *elm = netdev_priv(dev);
782 struct can_frame *frame = (struct can_frame *) skb->data;
784 if (skb->len != sizeof(struct can_frame))
787 if (!netif_running(dev)) {
788 pr_warn("%s: xmit: iface is down\n", dev->name);
792 /* BHs are already disabled, so no spin_lock_bh().
793 * See Documentation/networking/netdevices.txt
795 spin_lock(&elm->lock);
797 || elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY) {
798 spin_unlock(&elm->lock);
802 netif_stop_queue(dev);
804 elm327_send_frame(elm, frame);
805 spin_unlock(&elm->lock);
807 dev->stats.tx_packets++;
808 dev->stats.tx_bytes += frame->can_dlc;
810 can_led_event(dev, CAN_LED_EVENT_TX);
817 static int elmcan_netdev_change_mtu(struct net_device *dev, int new_mtu)
822 static const struct net_device_ops elmcan_netdev_ops = {
823 .ndo_init = elmcan_netdev_init,
824 .ndo_open = elmcan_netdev_open,
825 .ndo_stop = elmcan_netdev_close,
826 .ndo_start_xmit = elmcan_netdev_start_xmit,
827 .ndo_change_mtu = elmcan_netdev_change_mtu,
834 /************************************************************************
837 * (takes elm->lock) *
838 ************************************************************************/
841 * Get a reference to our struct, taking into account locks/refcounts.
842 * This is to ensure ordering in case we are shutting down, and to ensure
843 * there is a refcount at all (because tty->disc_data may be NULL).
845 static struct elmcan* get_elm(struct tty_struct *tty)
850 /* Lock all elmcan TTYs, so tty->disc_data can't become NULL
851 * the moment before we increase the reference counter.
853 spin_lock_bh(&elmcan_discdata_lock);
854 elm = (struct elmcan *) tty->disc_data;
857 spin_unlock_bh(&elmcan_discdata_lock);
861 got_ref = atomic_inc_not_zero(&elm->refcount);
862 spin_unlock_bh(&elmcan_discdata_lock);
871 static void put_elm(struct elmcan *elm)
873 atomic_dec(&elm->refcount);
879 * Handle the 'receiver data ready' interrupt.
880 * This function is called by the 'tty_io' module in the kernel when
881 * a block of ELM327 CAN data has been received, which can now be parsed
882 * and sent on to some IP layer for further processing. This will not
883 * be re-entered while running but other ldisc functions may be called
886 static void elmcan_ldisc_rx(struct tty_struct *tty,
887 const unsigned char *cp, char *fp, int count)
889 struct elmcan *elm = get_elm(tty);
894 /* Read the characters out of the buffer */
895 while (count-- && elm->rxfill < sizeof(elm->rxbuf)) {
897 pr_err("Error in received character stream. Check your wiring.");
899 spin_lock_bh(&elm->lock);
901 spin_unlock_bh(&elm->lock);
907 elm->rxbuf[elm->rxfill++] = *cp;
913 pr_err("Receive buffer overflowed. Bad chip or wiring?");
915 spin_lock_bh(&elm->lock);
917 spin_unlock_bh(&elm->lock);
923 spin_lock_bh(&elm->lock);
924 elm327_parse_rxbuf(elm);
925 spin_unlock_bh(&elm->lock);
931 * Write out remaining transmit buffer.
932 * Scheduled when TTY is writable.
934 static void elmcan_ldisc_tx_worker(struct work_struct *work)
936 /* No need to use get_elm() here, as we'll always flush workers
937 * befory destroying the elmcan object.
939 struct elmcan *elm = container_of(work, struct elmcan, tx_work);
942 spin_lock_bh(&elm->lock);
943 /* First make sure we're connected. */
944 if (!elm->tty || !netif_running(elm->dev)) {
945 spin_unlock_bh(&elm->lock);
949 if (elm->txleft <= 0) {
950 /* Our TTY write buffer is empty:
951 * We can start transmission of another packet
953 clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
954 spin_unlock_bh(&elm->lock);
955 netif_wake_queue(elm->dev);
959 actual = elm->tty->ops->write(elm->tty, elm->txhead, elm->txleft);
961 pr_err("Failed to write to tty for %s.\n", elm->dev->name);
965 elm->txleft -= actual;
966 elm->txhead += actual;
967 spin_unlock_bh(&elm->lock);
972 * Called by the driver when there's room for more data.
973 * Schedule the transmit.
975 static void elmcan_ldisc_tx_wakeup(struct tty_struct *tty)
977 struct elmcan *elm = get_elm(tty);
982 schedule_work(&elm->tx_work);
989 /* Some fake bit timings to allow bitrate setting */
990 static const struct can_bittiming_const elmcan_bittiming_const = {
1003 * Open the high-level part of the elmcan channel.
1004 * This function is called by the TTY module when the
1005 * elmcan line discipline is called for.
1007 * Called in process context serialized from other ldisc calls.
1009 static int elmcan_ldisc_open(struct tty_struct *tty)
1011 struct net_device *dev;
1015 if (!capable(CAP_NET_ADMIN))
1018 if (!tty->ops->write)
1022 /* OK. Find a free elmcan channel to use. */
1023 dev = alloc_candev(sizeof(struct elmcan), 0);
1026 elm = netdev_priv(dev);
1028 /* Configure TTY interface */
1029 tty->receive_room = 65536; /* We don't flow control */
1030 elm->txleft = 0; /* Clear TTY TX buffer */
1031 spin_lock_init(&elm->lock);
1032 atomic_set(&elm->refcount, 1);
1033 INIT_WORK(&elm->tx_work, elmcan_ldisc_tx_worker);
1035 /* Configure CAN metadata */
1036 elm->can.state = CAN_STATE_STOPPED;
1037 elm->can.clock.freq = 1000000;
1038 elm->can.bittiming_const = &elmcan_bittiming_const;
1039 elm->can.ctrlmode_supported = CAN_CTRLMODE_LISTENONLY;
1041 /* Configure netlink interface */
1043 dev->netdev_ops = &elmcan_netdev_ops;
1045 /* Mark ldisc channel as alive */
1047 tty->disc_data = elm;
1049 devm_can_led_init(elm->dev);
1052 err = register_candev(elm->dev);
1054 free_candev(elm->dev);
1058 netdev_info(elm->dev, "elmcan on %s.\n", tty->name);
1064 * Close down an elmcan channel.
1065 * This means flushing out any pending queues, and then returning.
1066 * This call is serialized against other ldisc functions:
1067 * Once this is called, no other ldisc function of ours is entered.
1069 * We also use this function for a hangup event.
1071 static void elmcan_ldisc_close(struct tty_struct *tty)
1073 /* Use get_elm() to synchronize against other users */
1074 struct elmcan *elm = get_elm(tty);
1079 /* Tear down network side.
1080 * unregister_netdev() calls .ndo_stop() so we don't have to.
1082 unregister_candev(elm->dev);
1084 /* Decrease the refcount twice, once for our own get_elm(),
1085 * and once to remove the count of 1 that we set in _open().
1086 * Once it reaches 0, we can safely destroy it.
1091 /* Spin until refcount reaches 0 */
1092 while(atomic_read(&elm->refcount) > 0)
1095 /* At this point, all ldisc calls to us will be no-ops.
1096 * Since the refcount is 0, they are bailing immediately.
1099 /* Mark channel as dead */
1100 spin_lock_bh(&elm->lock);
1101 tty->disc_data = NULL;
1103 spin_unlock_bh(&elm->lock);
1105 /* Flush TTY side */
1106 flush_work(&elm->tx_work);
1108 netdev_info(elm->dev, "elmcan off %s.\n", tty->name);
1110 /* Free our memory */
1111 free_candev(elm->dev);
1114 static int elmcan_ldisc_hangup(struct tty_struct *tty)
1116 elmcan_ldisc_close(tty);
1120 /* Perform I/O control on an active elmcan channel. */
1121 static int elmcan_ldisc_ioctl(struct tty_struct *tty, struct file *file,
1122 unsigned int cmd, unsigned long arg)
1124 struct elmcan *elm = get_elm(tty);
1127 /* First make sure we're connected. */
1133 tmp = strlen(elm->ifname) + 1;
1134 if (copy_to_user((void __user *)arg, elm->ifname, tmp)) {
1148 return tty_mode_ioctl(tty, file, cmd, arg);
1152 static struct tty_ldisc_ops elmcan_ldisc = {
1153 .owner = THIS_MODULE,
1154 .magic = TTY_LDISC_MAGIC,
1156 .receive_buf = elmcan_ldisc_rx,
1157 .write_wakeup = elmcan_ldisc_tx_wakeup,
1158 .open = elmcan_ldisc_open,
1159 .close = elmcan_ldisc_close,
1160 .hangup = elmcan_ldisc_hangup,
1161 .ioctl = elmcan_ldisc_ioctl,
1168 /************************************************************************
1169 * Module init/exit *
1170 ************************************************************************/
1172 static int __init elmcan_init(void)
1176 pr_info("ELM327 based best-effort CAN interface driver\n");
1177 pr_info("This device is severely limited as a CAN interface, see documentation.\n");
1179 /* Fill in our line protocol discipline, and register it */
1180 status = tty_register_ldisc(N_ELMCAN, &elmcan_ldisc);
1182 pr_err("can't register line discipline\n");
1187 static void __exit elmcan_exit(void)
1189 /* This will only be called when all channels have been closed by
1190 * userspace - tty_ldisc.c takes care of the module's refcount.
1194 status = tty_unregister_ldisc(N_ELMCAN);
1196 pr_err("Can't unregister line discipline (error: %d)\n", status);
1200 module_init(elmcan_init);
1201 module_exit(elmcan_exit);