1 // SPDX-License-Identifier: GPL-2.0
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 <max-linux@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>
14 #define pr_fmt(fmt) "[elmcan] " fmt
16 #include <linux/init.h>
17 #include <linux/module.h>
18 #include <linux/moduleparam.h>
20 #include <linux/atomic.h>
21 #include <linux/bitops.h>
22 #include <linux/ctype.h>
23 #include <linux/delay.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/version.h>
34 #include <linux/workqueue.h>
36 #include <linux/can.h>
37 #include <linux/can/dev.h>
38 #include <linux/can/error.h>
39 #include <linux/can/led.h>
40 #include <linux/can/rx-offload.h>
42 MODULE_ALIAS_LDISC(N_ELMCAN);
43 MODULE_DESCRIPTION("ELM327 based CAN interface");
44 MODULE_LICENSE("GPL");
45 MODULE_AUTHOR("Max Staudt <max-linux@enpas.org>");
47 /* If this is enabled, we'll try to make the best of the situation
48 * even if we receive unexpected characters on the line.
50 * Handle with care, it's likely your hardware is unreliable!
52 static bool accept_flaky_uart;
53 module_param_named(accept_flaky_uart, accept_flaky_uart, bool, 0444);
54 MODULE_PARM_DESC(accept_flaky_uart, "Don't bail at the first invalid character. Behavior undefined.");
56 /* Line discipline ID number */
61 #define ELM327_NAPI_WEIGHT 4
63 #define ELM327_SIZE_RXBUF 256
64 #define ELM327_SIZE_TXBUF 32
66 #define ELM327_CAN_CONFIG_SEND_SFF 0x8000
67 #define ELM327_CAN_CONFIG_VARIABLE_DLC 0x4000
68 #define ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF 0x2000
69 #define ELM327_CAN_CONFIG_BAUDRATE_MULT_8_7 0x1000
71 #define ELM327_MAGIC_CHAR 'y'
72 #define ELM327_MAGIC_STRING "y"
73 #define ELM327_READY_CHAR '>'
75 /* Bits in elm->cmds_todo */
80 TODO_CANID_29BIT_HIGH,
81 TODO_CAN_CONFIG_PART2,
89 /* This must be the first member when using alloc_candev() */
92 struct can_rx_offload offload;
94 /* TTY and netdev devices that we're bridging */
95 struct tty_struct *tty;
96 struct net_device *dev;
98 /* Per-channel lock */
101 /* Keep track of how many things are using this struct.
102 * Once it reaches 0, we are in the process of cleaning up,
103 * and new operations will be cancelled immediately.
104 * Use atomic_t rather than refcount_t because we deliberately
105 * decrement to 0, and refcount_dec() spills a WARN_ONCE in
110 /* Stop the channel on hardware failure.
111 * Once this is true, nothing will be sent to the TTY.
116 struct work_struct tx_work; /* Flushes TTY TX buffer */
117 unsigned char *txbuf;
118 unsigned char *txhead; /* Pointer to next TX byte */
119 int txleft; /* Bytes left to TX */
122 unsigned char rxbuf[ELM327_SIZE_RXBUF];
135 /* The CAN frame and config the ELM327 is sending/using,
136 * or will send/use after finishing all cmds_todo
138 struct can_frame can_frame;
139 unsigned short can_config;
140 unsigned long can_bitrate;
141 unsigned char can_bitrate_divisor;
142 int silent_monitoring;
144 /* Things we have yet to send */
145 char **next_init_cmd;
146 unsigned long cmds_todo;
149 /* A lock for all tty->disc_data handled by this ldisc.
150 * This is to prevent a case where tty->disc_data is set to NULL,
151 * yet someone is still trying to dereference it.
152 * Without this, we cannot do a clean shutdown.
154 static DEFINE_SPINLOCK(elmcan_discdata_lock);
156 static inline void elm327_hw_failure(struct elmcan *elm);
158 /***********************************************************************
159 * ELM327: Transmission *
161 * (all functions assume elm->lock taken) *
162 ***********************************************************************/
164 static void elm327_send(struct elmcan *elm, const void *buf, size_t len)
171 memcpy(elm->txbuf, buf, len);
173 /* Order of next two lines is *very* important.
174 * When we are sending a little amount of data,
175 * the transfer may be completed inside the ops->write()
176 * routine, because it's running with interrupts enabled.
177 * In this case we *never* got WRITE_WAKEUP event,
178 * if we did not request it before write operation.
179 * 14 Oct 1994 Dmitry Gorodchanin.
181 set_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
182 actual = elm->tty->ops->write(elm->tty, elm->txbuf, len);
185 "Failed to write to tty %s.\n",
187 elm327_hw_failure(elm);
191 elm->txleft = len - actual;
192 elm->txhead = elm->txbuf + actual;
195 /* Take the ELM327 out of almost any state and back into command mode.
196 * We send ELM327_MAGIC_CHAR which will either abort any running
197 * operation, or be echoed back to us in case we're already in command
200 static void elm327_kick_into_cmd_mode(struct elmcan *elm)
202 if (elm->state != ELM_GETMAGICCHAR && elm->state != ELM_GETPROMPT) {
203 elm327_send(elm, ELM327_MAGIC_STRING, 1);
205 elm->state = ELM_GETMAGICCHAR;
209 /* Schedule a CAN frame and necessary config changes to be sent to the TTY. */
210 static void elm327_send_frame(struct elmcan *elm, struct can_frame *frame)
212 /* Schedule any necessary changes in ELM327's CAN configuration */
213 if (elm->can_frame.can_id != frame->can_id) {
214 /* Set the new CAN ID for transmission. */
215 if ((frame->can_id & CAN_EFF_FLAG)
216 ^ (elm->can_frame.can_id & CAN_EFF_FLAG)) {
217 elm->can_config = (frame->can_id & CAN_EFF_FLAG
219 : ELM327_CAN_CONFIG_SEND_SFF)
220 | ELM327_CAN_CONFIG_VARIABLE_DLC
221 | ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF
222 | elm->can_bitrate_divisor;
224 set_bit(TODO_CAN_CONFIG, &elm->cmds_todo);
227 if (frame->can_id & CAN_EFF_FLAG) {
228 clear_bit(TODO_CANID_11BIT, &elm->cmds_todo);
229 set_bit(TODO_CANID_29BIT_LOW, &elm->cmds_todo);
230 set_bit(TODO_CANID_29BIT_HIGH, &elm->cmds_todo);
232 set_bit(TODO_CANID_11BIT, &elm->cmds_todo);
233 clear_bit(TODO_CANID_29BIT_LOW, &elm->cmds_todo);
234 clear_bit(TODO_CANID_29BIT_HIGH, &elm->cmds_todo);
238 /* Schedule the CAN frame itself. */
239 elm->can_frame = *frame;
240 set_bit(TODO_CAN_DATA, &elm->cmds_todo);
242 elm327_kick_into_cmd_mode(elm);
245 /***********************************************************************
246 * ELM327: Initialization sequence *
248 * (assumes elm->lock taken) *
249 ***********************************************************************/
251 static char *elm327_init_script[] = {
252 "AT WS\r", /* v1.0: Warm Start */
253 "AT PP FF OFF\r", /* v1.0: All Programmable Parameters Off */
254 "AT M0\r", /* v1.0: Memory Off */
255 "AT AL\r", /* v1.0: Allow Long messages */
256 "AT BI\r", /* v1.0: Bypass Initialization */
257 "AT CAF0\r", /* v1.0: CAN Auto Formatting Off */
258 "AT CFC0\r", /* v1.0: CAN Flow Control Off */
259 "AT CF 000\r", /* v1.0: Reset CAN ID Filter */
260 "AT CM 000\r", /* v1.0: Reset CAN ID Mask */
261 "AT E1\r", /* v1.0: Echo On */
262 "AT H1\r", /* v1.0: Headers On */
263 "AT L0\r", /* v1.0: Linefeeds Off */
264 "AT SH 7DF\r", /* v1.0: Set CAN sending ID to 0x7df */
265 "AT ST FF\r", /* v1.0: Set maximum Timeout for response after TX */
266 "AT AT0\r", /* v1.2: Adaptive Timing Off */
267 "AT D1\r", /* v1.3: Print DLC On */
268 "AT S1\r", /* v1.3: Spaces On */
269 "AT TP B\r", /* v1.0: Try Protocol B */
273 static void elm327_init(struct elmcan *elm)
275 elm->state = ELM_NOTINIT;
276 elm->can_frame.can_id = 0x7df;
278 elm->drop_next_line = 0;
280 /* We can only set the bitrate as a fraction of 500000.
281 * The bit timing constants in elmcan_bittiming_const will
282 * limit the user to the right values.
284 elm->can_bitrate_divisor = 500000 / elm->can.bittiming.bitrate;
285 elm->can_config = ELM327_CAN_CONFIG_SEND_SFF
286 | ELM327_CAN_CONFIG_VARIABLE_DLC
287 | ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF
288 | elm->can_bitrate_divisor;
290 /* Configure ELM327 and then start monitoring */
291 elm->next_init_cmd = &elm327_init_script[0];
292 set_bit(TODO_INIT, &elm->cmds_todo);
293 set_bit(TODO_SILENT_MONITOR, &elm->cmds_todo);
294 set_bit(TODO_RESPONSES, &elm->cmds_todo);
295 set_bit(TODO_CAN_CONFIG, &elm->cmds_todo);
297 elm327_kick_into_cmd_mode(elm);
300 /***********************************************************************
301 * ELM327: Reception -> netdev glue *
303 * (assumes elm->lock taken) *
304 ***********************************************************************/
306 static void elm327_feed_frame_to_netdev(struct elmcan *elm,
307 const struct can_frame *frame)
309 struct can_frame *cf;
312 if (!netif_running(elm->dev))
315 skb = alloc_can_skb(elm->dev, &cf);
320 memcpy(cf, frame, sizeof(struct can_frame));
322 /* Queue for NAPI pickup.
323 * rx-offload will update stats and LEDs for us.
325 if (can_rx_offload_queue_tail(&elm->offload, skb))
326 elm->dev->stats.rx_fifo_errors++;
328 #if LINUX_VERSION_CODE >= KERNEL_VERSION(5,15,0)
330 can_rx_offload_irq_finish(&elm->offload);
334 /***********************************************************************
335 * ELM327: "Panic" handler *
337 * (assumes elm->lock taken) *
338 ***********************************************************************/
340 /* Called when we're out of ideas and just want it all to end. */
341 static inline void elm327_hw_failure(struct elmcan *elm)
343 struct can_frame frame;
345 memset(&frame, 0, sizeof(frame));
346 frame.can_id = CAN_ERR_FLAG;
347 frame.can_dlc = CAN_ERR_DLC;
351 elm327_feed_frame_to_netdev(elm, &frame);
353 netdev_err(elm->dev, "ELM327 misbehaved. Blocking further communication.\n");
355 elm->hw_failure = true;
356 can_bus_off(elm->dev);
359 /***********************************************************************
360 * ELM327: Reception parser *
362 * (assumes elm->lock taken) *
363 ***********************************************************************/
365 static void elm327_parse_error(struct elmcan *elm, int len)
367 struct can_frame frame;
369 memset(&frame, 0, sizeof(frame));
370 frame.can_id = CAN_ERR_FLAG;
371 frame.can_dlc = CAN_ERR_DLC;
375 if (!memcmp(elm->rxbuf, "UNABLE TO CONNECT", 17)) {
377 "ELM327 reported UNABLE TO CONNECT. Please check your setup.\n");
381 if (!memcmp(elm->rxbuf, "BUFFER FULL", 11)) {
382 /* This case will only happen if the last data
384 * Otherwise, elm327_parse_frame() will heuristically
385 * emit this error frame instead.
387 frame.can_id |= CAN_ERR_CRTL;
388 frame.data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
392 if (!memcmp(elm->rxbuf, "BUS ERROR", 9))
393 frame.can_id |= CAN_ERR_BUSERROR;
394 if (!memcmp(elm->rxbuf, "CAN ERROR", 9))
395 frame.can_id |= CAN_ERR_PROT;
396 if (!memcmp(elm->rxbuf, "<RX ERROR", 9))
397 frame.can_id |= CAN_ERR_PROT;
400 if (!memcmp(elm->rxbuf, "BUS BUSY", 8)) {
401 frame.can_id |= CAN_ERR_PROT;
402 frame.data[2] = CAN_ERR_PROT_OVERLOAD;
404 if (!memcmp(elm->rxbuf, "FB ERROR", 8)) {
405 frame.can_id |= CAN_ERR_PROT;
406 frame.data[2] = CAN_ERR_PROT_TX;
410 if (!memcmp(elm->rxbuf, "ERR", 3)) {
411 netdev_err(elm->dev, "ELM327 reported an ERR%c%c. Please power it off and on again.\n",
412 elm->rxbuf[3], elm->rxbuf[4]);
413 frame.can_id |= CAN_ERR_CRTL;
417 /* Don't emit an error frame if we're unsure */
421 elm327_feed_frame_to_netdev(elm, &frame);
424 /* Parse CAN frames coming as ASCII from ELM327.
425 * They can be of various formats:
427 * 29-bit ID (EFF): 12 34 56 78 D PL PL PL PL PL PL PL PL
428 * 11-bit ID (!EFF): 123 D PL PL PL PL PL PL PL PL
430 * where D = DLC, PL = payload byte
432 * Instead of a payload, RTR indicates a remote request.
434 * We will use the spaces and line length to guess the format.
436 static int elm327_parse_frame(struct elmcan *elm, int len)
438 struct can_frame frame;
443 memset(&frame, 0, sizeof(frame));
445 /* Find first non-hex and non-space character:
446 * - In the simplest case, there is none.
447 * - For RTR frames, 'R' is the first non-hex character.
448 * - An error message may replace the end of the data line.
450 for (hexlen = 0; hexlen <= len; hexlen++) {
451 if (hex_to_bin(elm->rxbuf[hexlen]) < 0 &&
452 elm->rxbuf[hexlen] != ' ') {
457 /* If we accept stray characters coming in:
458 * Check for stray characters on a payload line.
459 * No idea what causes this.
461 if (accept_flaky_uart &&
463 !isdigit(elm->rxbuf[hexlen]) &&
464 !isupper(elm->rxbuf[hexlen]) &&
465 '<' != elm->rxbuf[hexlen] &&
466 ' ' != elm->rxbuf[hexlen]) {
467 /* The line is likely garbled anyway, so bail.
468 * The main code will restart listening.
470 elm327_kick_into_cmd_mode(elm);
474 /* Use spaces in CAN ID to distinguish 29 or 11 bit address length.
475 * No out-of-bounds access:
476 * We use the fact that we can always read from elm->rxbuf.
478 if (elm->rxbuf[2] == ' ' && elm->rxbuf[5] == ' ' &&
479 elm->rxbuf[8] == ' ' && elm->rxbuf[11] == ' ' &&
480 elm->rxbuf[13] == ' ') {
481 frame.can_id = CAN_EFF_FLAG;
483 } else if (elm->rxbuf[3] == ' ' && elm->rxbuf[5] == ' ') {
487 /* This is not a well-formatted data line.
488 * Assume it's an error message.
493 if (hexlen < datastart) {
494 /* The line is too short to be a valid frame hex dump.
495 * Something interrupted the hex dump or it is invalid.
500 /* From here on all chars up to buf[hexlen] are hex or spaces,
501 * at well-defined offsets.
504 /* Read CAN data length */
505 frame.can_dlc = (hex_to_bin(elm->rxbuf[datastart - 2]) << 0);
508 if (frame.can_id & CAN_EFF_FLAG) {
509 frame.can_id |= (hex_to_bin(elm->rxbuf[0]) << 28)
510 | (hex_to_bin(elm->rxbuf[1]) << 24)
511 | (hex_to_bin(elm->rxbuf[3]) << 20)
512 | (hex_to_bin(elm->rxbuf[4]) << 16)
513 | (hex_to_bin(elm->rxbuf[6]) << 12)
514 | (hex_to_bin(elm->rxbuf[7]) << 8)
515 | (hex_to_bin(elm->rxbuf[9]) << 4)
516 | (hex_to_bin(elm->rxbuf[10]) << 0);
518 frame.can_id |= (hex_to_bin(elm->rxbuf[0]) << 8)
519 | (hex_to_bin(elm->rxbuf[1]) << 4)
520 | (hex_to_bin(elm->rxbuf[2]) << 0);
523 /* Check for RTR frame */
524 if (elm->rxfill >= hexlen + 3 &&
525 !memcmp(&elm->rxbuf[hexlen], "RTR", 3)) {
526 frame.can_id |= CAN_RTR_FLAG;
529 /* Is the line long enough to hold the advertised payload?
530 * Note: RTR frames have a DLC, but no actual payload.
532 if (!(frame.can_id & CAN_RTR_FLAG) &&
533 (hexlen < frame.can_dlc * 3 + datastart)) {
534 /* Incomplete frame. */
536 /* Probably the ELM327's RS232 TX buffer was full.
537 * Emit an error frame and exit.
539 frame.can_id = CAN_ERR_FLAG | CAN_ERR_CRTL;
540 frame.can_dlc = CAN_ERR_DLC;
541 frame.data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
542 elm327_feed_frame_to_netdev(elm, &frame);
544 /* Signal failure to parse.
545 * The line will be re-parsed as an error line, which will fail.
546 * However, this will correctly drop the state machine back into
552 /* Parse the data nibbles. */
553 for (i = 0; i < frame.can_dlc; i++) {
554 frame.data[i] = (hex_to_bin(elm->rxbuf[datastart + 3*i]) << 4)
555 | (hex_to_bin(elm->rxbuf[datastart + 3*i + 1]));
558 /* Feed the frame to the network layer. */
559 elm327_feed_frame_to_netdev(elm, &frame);
564 static void elm327_parse_line(struct elmcan *elm, int len)
566 /* Skip empty lines */
570 /* Skip echo lines */
571 if (elm->drop_next_line) {
572 elm->drop_next_line = 0;
574 } else if (elm->rxbuf[0] == 'A' && elm->rxbuf[1] == 'T') {
578 /* Regular parsing */
579 switch (elm->state) {
581 if (elm327_parse_frame(elm, len)) {
582 /* Parse an error line. */
583 elm327_parse_error(elm, len);
586 elm327_kick_into_cmd_mode(elm);
594 static void elm327_handle_prompt(struct elmcan *elm)
596 struct can_frame *frame = &elm->can_frame;
597 char local_txbuf[20];
599 if (!elm->cmds_todo) {
600 /* Enter CAN monitor mode */
601 elm327_send(elm, "ATMA\r", 5);
602 elm->state = ELM_RECEIVING;
607 /* Reconfigure ELM327 step by step as indicated by elm->cmds_todo */
608 if (test_bit(TODO_INIT, &elm->cmds_todo)) {
609 strcpy(local_txbuf, *elm->next_init_cmd);
611 elm->next_init_cmd++;
612 if (!(*elm->next_init_cmd)) {
613 clear_bit(TODO_INIT, &elm->cmds_todo);
614 netdev_info(elm->dev, "Initialization finished.\n");
617 } else if (test_and_clear_bit(TODO_SILENT_MONITOR, &elm->cmds_todo)) {
618 sprintf(local_txbuf, "ATCSM%i\r",
619 !(!(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY)));
621 } else if (test_and_clear_bit(TODO_RESPONSES, &elm->cmds_todo)) {
622 sprintf(local_txbuf, "ATR%i\r",
623 !(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY));
625 } else if (test_and_clear_bit(TODO_CAN_CONFIG, &elm->cmds_todo)) {
626 sprintf(local_txbuf, "ATPC\r");
627 set_bit(TODO_CAN_CONFIG_PART2, &elm->cmds_todo);
629 } else if (test_and_clear_bit(TODO_CAN_CONFIG_PART2, &elm->cmds_todo)) {
630 sprintf(local_txbuf, "ATPB%04X\r",
633 } else if (test_and_clear_bit(TODO_CANID_29BIT_HIGH, &elm->cmds_todo)) {
634 sprintf(local_txbuf, "ATCP%02X\r",
635 (frame->can_id & CAN_EFF_MASK) >> 24);
637 } else if (test_and_clear_bit(TODO_CANID_29BIT_LOW, &elm->cmds_todo)) {
638 sprintf(local_txbuf, "ATSH%06X\r",
639 frame->can_id & CAN_EFF_MASK & ((1 << 24) - 1));
641 } else if (test_and_clear_bit(TODO_CANID_11BIT, &elm->cmds_todo)) {
642 sprintf(local_txbuf, "ATSH%03X\r",
643 frame->can_id & CAN_SFF_MASK);
645 } else if (test_and_clear_bit(TODO_CAN_DATA, &elm->cmds_todo)) {
646 if (frame->can_id & CAN_RTR_FLAG) {
647 /* Send an RTR frame. Their DLC is fixed.
648 * Some chips don't send them at all.
650 sprintf(local_txbuf, "ATRTR\r");
652 /* Send a regular CAN data frame */
655 for (i = 0; i < frame->can_dlc; i++) {
656 sprintf(&local_txbuf[2 * i], "%02X",
660 sprintf(&local_txbuf[2 * i], "\r");
663 elm->drop_next_line = 1;
664 elm->state = ELM_RECEIVING;
667 elm327_send(elm, local_txbuf, strlen(local_txbuf));
670 static bool elm327_is_ready_char(char c)
672 /* Bits 0xc0 are sometimes set (randomly), hence the mask.
673 * Probably bad hardware.
675 return (c & 0x3f) == ELM327_READY_CHAR;
678 static void elm327_drop_bytes(struct elmcan *elm, int i)
680 memmove(&elm->rxbuf[0], &elm->rxbuf[i], ELM327_SIZE_RXBUF - i);
684 static void elm327_parse_rxbuf(struct elmcan *elm)
688 switch (elm->state) {
693 case ELM_GETMAGICCHAR:
695 /* Wait for 'y' or '>' */
698 for (i = 0; i < elm->rxfill; i++) {
699 if (elm->rxbuf[i] == ELM327_MAGIC_CHAR) {
700 elm327_send(elm, "\r", 1);
701 elm->state = ELM_GETPROMPT;
704 } else if (elm327_is_ready_char(elm->rxbuf[i])) {
705 elm327_send(elm, ELM327_MAGIC_STRING, 1);
711 elm327_drop_bytes(elm, i);
718 if (elm327_is_ready_char(elm->rxbuf[elm->rxfill - 1]))
719 elm327_handle_prompt(elm);
725 /* Find <CR> delimiting feedback lines. */
727 (len < elm->rxfill) && (elm->rxbuf[len] != '\r');
732 if (len == ELM327_SIZE_RXBUF) {
733 /* Line exceeds buffer. It's probably all garbage.
734 * Did we even connect at the right baud rate?
737 "RX buffer overflow. Faulty ELM327 or UART?\n");
738 elm327_hw_failure(elm);
740 } else if (len == elm->rxfill) {
741 if (elm327_is_ready_char(elm->rxbuf[elm->rxfill - 1])) {
742 /* The ELM327's AT ST response timeout ran out,
743 * so we got a prompt.
744 * Clear RX buffer and restart listening.
748 elm327_handle_prompt(elm);
752 /* No <CR> found - we haven't received a full line yet.
753 * Wait for more data.
758 /* We have a full line to parse. */
759 elm327_parse_line(elm, len);
761 /* Remove parsed data from RX buffer. */
762 elm327_drop_bytes(elm, len + 1);
764 /* More data to parse? */
766 elm327_parse_rxbuf(elm);
770 /***********************************************************************
773 * (takes elm->lock) *
774 ***********************************************************************/
776 /* Dummy needed to use can_rx_offload */
777 static struct sk_buff *elmcan_mailbox_read(struct can_rx_offload *offload,
778 unsigned int n, u32 *timestamp,
781 WARN_ON(1); /* This function is a dummy, so don't call it! */
783 return ERR_PTR(-ENOBUFS);
786 static int elmcan_netdev_open(struct net_device *dev)
788 struct elmcan *elm = netdev_priv(dev);
791 spin_lock_bh(&elm->lock);
792 if (elm->hw_failure) {
793 netdev_err(elm->dev, "Refusing to open interface after a hardware fault has been detected.\n");
794 spin_unlock_bh(&elm->lock);
799 spin_unlock_bh(&elm->lock);
803 /* open_candev() checks for elm->can.bittiming.bitrate != 0 */
804 err = open_candev(dev);
806 spin_unlock_bh(&elm->lock);
811 spin_unlock_bh(&elm->lock);
813 elm->offload.mailbox_read = elmcan_mailbox_read;
814 err = can_rx_offload_add_fifo(dev, &elm->offload, ELM327_NAPI_WEIGHT);
820 can_rx_offload_enable(&elm->offload);
822 can_led_event(dev, CAN_LED_EVENT_OPEN);
823 elm->can.state = CAN_STATE_ERROR_ACTIVE;
824 netif_start_queue(dev);
829 static int elmcan_netdev_close(struct net_device *dev)
831 struct elmcan *elm = netdev_priv(dev);
833 netif_stop_queue(dev);
835 spin_lock_bh(&elm->lock);
837 /* Interrupt whatever we're doing right now */
838 elm327_send(elm, ELM327_MAGIC_STRING, 1);
840 /* Clear the wakeup bit, as the netdev will be down and thus
841 * the wakeup handler won't clear it
843 clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
845 spin_unlock_bh(&elm->lock);
847 flush_work(&elm->tx_work);
849 spin_unlock_bh(&elm->lock);
852 can_rx_offload_disable(&elm->offload);
853 elm->can.state = CAN_STATE_STOPPED;
854 can_rx_offload_del(&elm->offload);
856 can_led_event(dev, CAN_LED_EVENT_STOP);
861 /* Send a can_frame to a TTY. */
862 static netdev_tx_t elmcan_netdev_start_xmit(struct sk_buff *skb,
863 struct net_device *dev)
865 struct elmcan *elm = netdev_priv(dev);
866 struct can_frame *frame = (struct can_frame *)skb->data;
868 if (skb->len != sizeof(struct can_frame))
871 if (!netif_running(dev)) {
872 netdev_warn(elm->dev, "xmit: iface is down.\n");
876 /* BHs are already disabled, so no spin_lock_bh().
877 * See Documentation/networking/netdevices.txt
879 spin_lock(&elm->lock);
881 /* We shouldn't get here after a hardware fault:
882 * can_bus_off() calls netif_carrier_off()
884 WARN_ON(elm->hw_failure);
888 elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY) {
889 spin_unlock(&elm->lock);
893 netif_stop_queue(dev);
895 elm327_send_frame(elm, frame);
896 spin_unlock(&elm->lock);
898 dev->stats.tx_packets++;
899 dev->stats.tx_bytes += frame->can_dlc;
901 can_led_event(dev, CAN_LED_EVENT_TX);
908 static const struct net_device_ops elmcan_netdev_ops = {
909 .ndo_open = elmcan_netdev_open,
910 .ndo_stop = elmcan_netdev_close,
911 .ndo_start_xmit = elmcan_netdev_start_xmit,
912 .ndo_change_mtu = can_change_mtu,
915 /***********************************************************************
918 * (takes elm->lock) *
919 ***********************************************************************/
921 /* Get a reference to our struct, taking into account locks/refcounts.
922 * This is to ensure ordering in case we are shutting down, and to ensure
923 * there is a refcount at all (otherwise tty->disc_data may be freed and
924 * before we increment the refcount).
925 * Use this for anything that can race against elmcan_ldisc_close().
927 static struct elmcan *get_elm(struct tty_struct *tty)
932 spin_lock_bh(&elmcan_discdata_lock);
933 elm = (struct elmcan *)tty->disc_data;
936 spin_unlock_bh(&elmcan_discdata_lock);
940 got_ref = atomic_inc_not_zero(&elm->refcount);
941 spin_unlock_bh(&elmcan_discdata_lock);
949 static void put_elm(struct elmcan *elm)
951 atomic_dec(&elm->refcount);
954 static bool elmcan_is_valid_rx_char(char c)
956 return (accept_flaky_uart ||
959 c == ELM327_MAGIC_CHAR ||
960 c == ELM327_READY_CHAR ||
971 /* Handle incoming ELM327 ASCII data.
972 * This will not be re-entered while running, but other ldisc
973 * functions may be called in parallel.
975 static void elmcan_ldisc_rx(struct tty_struct *tty,
976 const unsigned char *cp, char *fp, int count)
978 struct elmcan *elm = get_elm(tty);
983 spin_lock_bh(&elm->lock);
988 while (count-- && elm->rxfill < ELM327_SIZE_RXBUF) {
990 netdev_err(elm->dev, "Error in received character stream. Check your wiring.");
992 elm327_hw_failure(elm);
997 /* Ignore NUL characters, which the PIC microcontroller may
998 * inadvertently insert due to a known hardware bug.
999 * See ELM327 documentation, which refers to a Microchip PIC
1003 /* Check for stray characters on the UART line.
1004 * Likely caused by bad hardware.
1006 if (!elmcan_is_valid_rx_char(*cp)) {
1007 netdev_err(elm->dev,
1008 "Received illegal character %02x.\n",
1010 elm327_hw_failure(elm);
1015 elm->rxbuf[elm->rxfill++] = *cp;
1022 netdev_err(elm->dev, "Receive buffer overflowed. Bad chip or wiring?");
1024 elm327_hw_failure(elm);
1029 elm327_parse_rxbuf(elm);
1032 spin_unlock_bh(&elm->lock);
1036 /* Write out remaining transmit buffer.
1037 * Scheduled when TTY is writable.
1039 static void elmcan_ldisc_tx_worker(struct work_struct *work)
1041 /* No need to use get_elm() here, as we'll always flush workers
1042 * before destroying the elmcan object.
1044 struct elmcan *elm = container_of(work, struct elmcan, tx_work);
1047 spin_lock_bh(&elm->lock);
1048 if (elm->hw_failure) {
1049 spin_unlock_bh(&elm->lock);
1053 if (!elm->tty || !netif_running(elm->dev)) {
1054 spin_unlock_bh(&elm->lock);
1058 if (elm->txleft <= 0) {
1059 /* Our TTY write buffer is empty:
1060 * Allow netdev to hand us another packet
1062 clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
1063 spin_unlock_bh(&elm->lock);
1064 netif_wake_queue(elm->dev);
1068 actual = elm->tty->ops->write(elm->tty, elm->txhead, elm->txleft);
1070 netdev_err(elm->dev,
1071 "Failed to write to tty %s.\n",
1073 elm327_hw_failure(elm);
1074 spin_unlock_bh(&elm->lock);
1078 elm->txleft -= actual;
1079 elm->txhead += actual;
1080 spin_unlock_bh(&elm->lock);
1083 /* Called by the driver when there's room for more data. */
1084 static void elmcan_ldisc_tx_wakeup(struct tty_struct *tty)
1086 struct elmcan *elm = get_elm(tty);
1091 schedule_work(&elm->tx_work);
1096 /* ELM327 can only handle bitrates that are integer divisors of 500 kHz,
1097 * or 7/8 of that. Divisors are 1 to 64.
1098 * Currently we don't implement support for 7/8 rates.
1100 static const u32 elmcan_bitrate_const[64] = {
1101 7812, 7936, 8064, 8196, 8333, 8474, 8620, 8771,
1102 8928, 9090, 9259, 9433, 9615, 9803, 10000, 10204,
1103 10416, 10638, 10869, 11111, 11363, 11627, 11904, 12195,
1104 12500, 12820, 13157, 13513, 13888, 14285, 14705, 15151,
1105 15625, 16129, 16666, 17241, 17857, 18518, 19230, 20000,
1106 20833, 21739, 22727, 23809, 25000, 26315, 27777, 29411,
1107 31250, 33333, 35714, 38461, 41666, 45454, 50000, 55555,
1108 62500, 71428, 83333, 100000, 125000, 166666, 250000, 500000
1111 /* Dummy needed to use bitrate_const */
1112 static int elmcan_do_set_bittiming(struct net_device *netdev)
1119 static int elmcan_ldisc_open(struct tty_struct *tty)
1121 struct net_device *dev;
1125 if (!capable(CAP_NET_ADMIN))
1128 if (!tty->ops->write)
1131 dev = alloc_candev(sizeof(struct elmcan), 0);
1134 elm = netdev_priv(dev);
1136 elm->txbuf = kmalloc(ELM327_SIZE_TXBUF, GFP_KERNEL);
1142 /* Configure TTY interface */
1143 tty->receive_room = 65536; /* We don't flow control */
1144 elm->txleft = 0; /* Clear TTY TX buffer */
1145 spin_lock_init(&elm->lock);
1146 atomic_set(&elm->refcount, 1);
1147 INIT_WORK(&elm->tx_work, elmcan_ldisc_tx_worker);
1149 /* Configure CAN metadata */
1150 elm->can.state = CAN_STATE_STOPPED;
1151 elm->can.bitrate_const = elmcan_bitrate_const;
1152 elm->can.bitrate_const_cnt = ARRAY_SIZE(elmcan_bitrate_const);
1153 elm->can.do_set_bittiming = elmcan_do_set_bittiming;
1154 elm->can.ctrlmode_supported = CAN_CTRLMODE_LISTENONLY;
1156 /* Configure netlink interface */
1158 dev->netdev_ops = &elmcan_netdev_ops;
1160 /* Mark ldisc channel as alive */
1162 tty->disc_data = elm;
1164 devm_can_led_init(elm->dev);
1167 err = register_candev(elm->dev);
1171 netdev_info(elm->dev, "elmcan on %s.\n", tty->name);
1177 free_candev(elm->dev);
1181 /* Close down an elmcan channel.
1182 * This means flushing out any pending queues, and then returning.
1183 * This call is serialized against other ldisc functions:
1184 * Once this is called, no other ldisc function of ours is entered.
1186 * We also use this function for a hangup event.
1188 static void elmcan_ldisc_close(struct tty_struct *tty)
1190 struct elmcan *elm = get_elm(tty);
1195 /* unregister_netdev() calls .ndo_stop() so we don't have to. */
1196 unregister_candev(elm->dev);
1198 /* Decrease the refcount twice, once for our own get_elm(),
1199 * and once to remove the count of 1 that we set in _open().
1200 * Once it reaches 0, we can safely destroy it.
1205 while (atomic_read(&elm->refcount) > 0)
1206 msleep_interruptible(10);
1208 /* At this point, all ldisc calls to us have become no-ops. */
1210 flush_work(&elm->tx_work);
1212 /* Mark channel as dead */
1213 spin_lock_bh(&elm->lock);
1214 tty->disc_data = NULL;
1216 spin_unlock_bh(&elm->lock);
1218 netdev_info(elm->dev, "elmcan off %s.\n", tty->name);
1221 free_candev(elm->dev);
1224 static int elmcan_ldisc_hangup(struct tty_struct *tty)
1226 elmcan_ldisc_close(tty);
1230 static int elmcan_ldisc_ioctl(struct tty_struct *tty, struct file *file,
1231 unsigned int cmd, unsigned long arg)
1233 struct elmcan *elm = get_elm(tty);
1241 tmp = strnlen(elm->dev->name, IFNAMSIZ - 1) + 1;
1242 if (copy_to_user((void __user *)arg, elm->dev->name, tmp)) {
1256 return tty_mode_ioctl(tty, file, cmd, arg);
1260 static struct tty_ldisc_ops elmcan_ldisc = {
1261 .owner = THIS_MODULE,
1263 .receive_buf = elmcan_ldisc_rx,
1264 .write_wakeup = elmcan_ldisc_tx_wakeup,
1265 .open = elmcan_ldisc_open,
1266 .close = elmcan_ldisc_close,
1267 .hangup = elmcan_ldisc_hangup,
1268 .ioctl = elmcan_ldisc_ioctl,
1271 static int __init elmcan_init(void)
1275 pr_info("ELM327 based best-effort CAN interface driver\n");
1276 pr_info("This device is severely limited as a CAN interface, see documentation.\n");
1278 status = tty_register_ldisc(N_ELMCAN, &elmcan_ldisc);
1280 pr_err("Can't register line discipline\n");
1285 static void __exit elmcan_exit(void)
1287 /* This will only be called when all channels have been closed by
1288 * userspace - tty_ldisc.c takes care of the module's refcount.
1292 status = tty_unregister_ldisc(N_ELMCAN);
1294 pr_err("Can't unregister line discipline (error: %d)\n",
1298 module_init(elmcan_init);
1299 module_exit(elmcan_exit);