1 // SPDX-License-Identifier: GPL-2.0
2 /* ELM327 based CAN interface driver (tty line discipline)
4 * This driver started as a derivative of linux/drivers/net/can/slcan.c
5 * and my thanks go to the original authors for their inspiration.
7 * can327.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>
13 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
15 #include <linux/init.h>
16 #include <linux/module.h>
18 #include <linux/bitops.h>
19 #include <linux/ctype.h>
20 #include <linux/errno.h>
21 #include <linux/kernel.h>
22 #include <linux/list.h>
23 #include <linux/lockdep.h>
24 #include <linux/netdevice.h>
25 #include <linux/skbuff.h>
26 #include <linux/spinlock.h>
27 #include <linux/string.h>
28 #include <linux/tty.h>
29 #include <linux/tty_ldisc.h>
30 #include <linux/workqueue.h>
32 #include <uapi/linux/tty.h>
34 #include <linux/can.h>
35 #include <linux/can/dev.h>
36 #include <linux/can/error.h>
37 #include <linux/can/rx-offload.h>
39 #define CAN327_NAPI_WEIGHT 4
41 #define CAN327_SIZE_TXBUF 32
42 #define CAN327_SIZE_RXBUF 1024
44 #define CAN327_CAN_CONFIG_SEND_SFF 0x8000
45 #define CAN327_CAN_CONFIG_VARIABLE_DLC 0x4000
46 #define CAN327_CAN_CONFIG_RECV_BOTH_SFF_EFF 0x2000
47 #define CAN327_CAN_CONFIG_BAUDRATE_MULT_8_7 0x1000
49 #define CAN327_DUMMY_CHAR 'y'
50 #define CAN327_DUMMY_STRING "y"
51 #define CAN327_READY_CHAR '>'
53 /* Bits in elm->cmds_todo */
55 CAN327_TX_DO_CAN_DATA
= 0,
56 CAN327_TX_DO_CANID_11BIT
,
57 CAN327_TX_DO_CANID_29BIT_LOW
,
58 CAN327_TX_DO_CANID_29BIT_HIGH
,
59 CAN327_TX_DO_CAN_CONFIG_PART2
,
60 CAN327_TX_DO_CAN_CONFIG
,
61 CAN327_TX_DO_RESPONSES
,
62 CAN327_TX_DO_SILENT_MONITOR
,
67 /* This must be the first member when using alloc_candev() */
70 struct can_rx_offload offload
;
73 u8 txbuf
[CAN327_SIZE_TXBUF
];
74 u8 rxbuf
[CAN327_SIZE_RXBUF
];
76 /* Per-channel lock */
79 /* TTY and netdev devices that we're bridging */
80 struct tty_struct
*tty
;
81 struct net_device
*dev
;
83 /* TTY buffer accounting */
84 struct work_struct tx_work
; /* Flushes TTY TX buffer */
85 u8
*txhead
; /* Next TX byte */
86 size_t txleft
; /* Bytes left to TX */
87 int rxfill
; /* Bytes already RX'd in buffer */
91 CAN327_STATE_NOTINIT
= 0,
92 CAN327_STATE_GETDUMMYCHAR
,
93 CAN327_STATE_GETPROMPT
,
94 CAN327_STATE_RECEIVING
,
97 /* Things we have yet to send */
99 unsigned long cmds_todo
;
101 /* The CAN frame and config the ELM327 is sending/using,
102 * or will send/use after finishing all cmds_todo
104 struct can_frame can_frame_to_send
;
106 u8 can_bitrate_divisor
;
111 /* Stop the channel on UART side hardware failure, e.g. stray
112 * characters or neverending lines. This may be caused by bad
113 * UART wiring, a bad ELM327, a bad UART bridge...
114 * Once this is true, nothing will be sent to the TTY.
116 bool uart_side_failure
;
119 static inline void can327_uart_side_failure(struct can327
*elm
);
121 static void can327_send(struct can327
*elm
, const void *buf
, size_t len
)
125 lockdep_assert_held(&elm
->lock
);
127 if (elm
->uart_side_failure
)
130 memcpy(elm
->txbuf
, buf
, len
);
132 /* Order of next two lines is *very* important.
133 * When we are sending a little amount of data,
134 * the transfer may be completed inside the ops->write()
135 * routine, because it's running with interrupts enabled.
136 * In this case we *never* got WRITE_WAKEUP event,
137 * if we did not request it before write operation.
138 * 14 Oct 1994 Dmitry Gorodchanin.
140 set_bit(TTY_DO_WRITE_WAKEUP
, &elm
->tty
->flags
);
141 written
= elm
->tty
->ops
->write(elm
->tty
, elm
->txbuf
, len
);
143 netdev_err(elm
->dev
, "Failed to write to tty %s.\n",
145 can327_uart_side_failure(elm
);
149 elm
->txleft
= len
- written
;
150 elm
->txhead
= elm
->txbuf
+ written
;
153 /* Take the ELM327 out of almost any state and back into command mode.
154 * We send CAN327_DUMMY_CHAR which will either abort any running
155 * operation, or be echoed back to us in case we're already in command
158 static void can327_kick_into_cmd_mode(struct can327
*elm
)
160 lockdep_assert_held(&elm
->lock
);
162 if (elm
->state
!= CAN327_STATE_GETDUMMYCHAR
&&
163 elm
->state
!= CAN327_STATE_GETPROMPT
) {
164 can327_send(elm
, CAN327_DUMMY_STRING
, 1);
166 elm
->state
= CAN327_STATE_GETDUMMYCHAR
;
170 /* Schedule a CAN frame and necessary config changes to be sent to the TTY. */
171 static void can327_send_frame(struct can327
*elm
, struct can_frame
*frame
)
173 lockdep_assert_held(&elm
->lock
);
175 /* Schedule any necessary changes in ELM327's CAN configuration */
176 if (elm
->can_frame_to_send
.can_id
!= frame
->can_id
) {
177 /* Set the new CAN ID for transmission. */
178 if ((frame
->can_id
^ elm
->can_frame_to_send
.can_id
)
181 (frame
->can_id
& CAN_EFF_FLAG
? 0 : CAN327_CAN_CONFIG_SEND_SFF
) |
182 CAN327_CAN_CONFIG_VARIABLE_DLC
|
183 CAN327_CAN_CONFIG_RECV_BOTH_SFF_EFF
|
184 elm
->can_bitrate_divisor
;
186 set_bit(CAN327_TX_DO_CAN_CONFIG
, &elm
->cmds_todo
);
189 if (frame
->can_id
& CAN_EFF_FLAG
) {
190 clear_bit(CAN327_TX_DO_CANID_11BIT
, &elm
->cmds_todo
);
191 set_bit(CAN327_TX_DO_CANID_29BIT_LOW
, &elm
->cmds_todo
);
192 set_bit(CAN327_TX_DO_CANID_29BIT_HIGH
, &elm
->cmds_todo
);
194 set_bit(CAN327_TX_DO_CANID_11BIT
, &elm
->cmds_todo
);
195 clear_bit(CAN327_TX_DO_CANID_29BIT_LOW
,
197 clear_bit(CAN327_TX_DO_CANID_29BIT_HIGH
,
202 /* Schedule the CAN frame itself. */
203 elm
->can_frame_to_send
= *frame
;
204 set_bit(CAN327_TX_DO_CAN_DATA
, &elm
->cmds_todo
);
206 can327_kick_into_cmd_mode(elm
);
209 /* ELM327 initialisation sequence.
210 * The line length is limited by the buffer in can327_handle_prompt().
212 static char *can327_init_script
[] = {
213 "AT WS\r", /* v1.0: Warm Start */
214 "AT PP FF OFF\r", /* v1.0: All Programmable Parameters Off */
215 "AT M0\r", /* v1.0: Memory Off */
216 "AT AL\r", /* v1.0: Allow Long messages */
217 "AT BI\r", /* v1.0: Bypass Initialisation */
218 "AT CAF0\r", /* v1.0: CAN Auto Formatting Off */
219 "AT CFC0\r", /* v1.0: CAN Flow Control Off */
220 "AT CF 000\r", /* v1.0: Reset CAN ID Filter */
221 "AT CM 000\r", /* v1.0: Reset CAN ID Mask */
222 "AT E1\r", /* v1.0: Echo On */
223 "AT H1\r", /* v1.0: Headers On */
224 "AT L0\r", /* v1.0: Linefeeds Off */
225 "AT SH 7DF\r", /* v1.0: Set CAN sending ID to 0x7df */
226 "AT ST FF\r", /* v1.0: Set maximum Timeout for response after TX */
227 "AT AT0\r", /* v1.2: Adaptive Timing Off */
228 "AT D1\r", /* v1.3: Print DLC On */
229 "AT S1\r", /* v1.3: Spaces On */
230 "AT TP B\r", /* v1.0: Try Protocol B */
234 static void can327_init_device(struct can327
*elm
)
236 lockdep_assert_held(&elm
->lock
);
238 elm
->state
= CAN327_STATE_NOTINIT
;
239 elm
->can_frame_to_send
.can_id
= 0x7df; /* ELM327 HW default */
241 elm
->drop_next_line
= 0;
243 /* We can only set the bitrate as a fraction of 500000.
244 * The bitrates listed in can327_bitrate_const will
245 * limit the user to the right values.
247 elm
->can_bitrate_divisor
= 500000 / elm
->can
.bittiming
.bitrate
;
249 CAN327_CAN_CONFIG_SEND_SFF
| CAN327_CAN_CONFIG_VARIABLE_DLC
|
250 CAN327_CAN_CONFIG_RECV_BOTH_SFF_EFF
| elm
->can_bitrate_divisor
;
252 /* Configure ELM327 and then start monitoring */
253 elm
->next_init_cmd
= &can327_init_script
[0];
254 set_bit(CAN327_TX_DO_INIT
, &elm
->cmds_todo
);
255 set_bit(CAN327_TX_DO_SILENT_MONITOR
, &elm
->cmds_todo
);
256 set_bit(CAN327_TX_DO_RESPONSES
, &elm
->cmds_todo
);
257 set_bit(CAN327_TX_DO_CAN_CONFIG
, &elm
->cmds_todo
);
259 can327_kick_into_cmd_mode(elm
);
262 static void can327_feed_frame_to_netdev(struct can327
*elm
, struct sk_buff
*skb
)
264 lockdep_assert_held(&elm
->lock
);
266 if (!netif_running(elm
->dev
)) {
271 /* Queue for NAPI pickup.
272 * rx-offload will update stats and LEDs for us.
274 if (can_rx_offload_queue_tail(&elm
->offload
, skb
))
275 elm
->dev
->stats
.rx_fifo_errors
++;
278 can_rx_offload_irq_finish(&elm
->offload
);
281 /* Called when we're out of ideas and just want it all to end. */
282 static inline void can327_uart_side_failure(struct can327
*elm
)
284 struct can_frame
*frame
;
287 lockdep_assert_held(&elm
->lock
);
289 elm
->uart_side_failure
= true;
291 clear_bit(TTY_DO_WRITE_WAKEUP
, &elm
->tty
->flags
);
293 elm
->can
.can_stats
.bus_off
++;
294 netif_stop_queue(elm
->dev
);
295 elm
->can
.state
= CAN_STATE_BUS_OFF
;
296 can_bus_off(elm
->dev
);
299 "ELM327 misbehaved. Blocking further communication.\n");
301 skb
= alloc_can_err_skb(elm
->dev
, &frame
);
305 frame
->can_id
|= CAN_ERR_BUSOFF
;
306 can327_feed_frame_to_netdev(elm
, skb
);
309 /* Compares a byte buffer (non-NUL terminated) to the payload part of
310 * a string, and returns true iff the buffer (content *and* length) is
311 * exactly that string, without the terminating NUL byte.
313 * Example: If reference is "BUS ERROR", then this returns true iff nbytes == 9
314 * and !memcmp(buf, "BUS ERROR", 9).
316 * The reason to use strings is so we can easily include them in the C
317 * code, and to avoid hardcoding lengths.
319 static inline bool can327_rxbuf_cmp(const u8
*buf
, size_t nbytes
,
320 const char *reference
)
322 size_t ref_len
= strlen(reference
);
324 return (nbytes
== ref_len
) && !memcmp(buf
, reference
, ref_len
);
327 static void can327_parse_error(struct can327
*elm
, size_t len
)
329 struct can_frame
*frame
;
332 lockdep_assert_held(&elm
->lock
);
334 skb
= alloc_can_err_skb(elm
->dev
, &frame
);
336 /* It's okay to return here:
337 * The outer parsing loop will drop this UART buffer.
341 /* Filter possible error messages based on length of RX'd line */
342 if (can327_rxbuf_cmp(elm
->rxbuf
, len
, "UNABLE TO CONNECT")) {
344 "ELM327 reported UNABLE TO CONNECT. Please check your setup.\n");
345 } else if (can327_rxbuf_cmp(elm
->rxbuf
, len
, "BUFFER FULL")) {
346 /* This will only happen if the last data line was complete.
347 * Otherwise, can327_parse_frame() will heuristically
348 * emit this kind of error frame instead.
350 frame
->can_id
|= CAN_ERR_CRTL
;
351 frame
->data
[1] = CAN_ERR_CRTL_RX_OVERFLOW
;
352 } else if (can327_rxbuf_cmp(elm
->rxbuf
, len
, "BUS ERROR")) {
353 frame
->can_id
|= CAN_ERR_BUSERROR
;
354 } else if (can327_rxbuf_cmp(elm
->rxbuf
, len
, "CAN ERROR")) {
355 frame
->can_id
|= CAN_ERR_PROT
;
356 } else if (can327_rxbuf_cmp(elm
->rxbuf
, len
, "<RX ERROR")) {
357 frame
->can_id
|= CAN_ERR_PROT
;
358 } else if (can327_rxbuf_cmp(elm
->rxbuf
, len
, "BUS BUSY")) {
359 frame
->can_id
|= CAN_ERR_PROT
;
360 frame
->data
[2] = CAN_ERR_PROT_OVERLOAD
;
361 } else if (can327_rxbuf_cmp(elm
->rxbuf
, len
, "FB ERROR")) {
362 frame
->can_id
|= CAN_ERR_PROT
;
363 frame
->data
[2] = CAN_ERR_PROT_TX
;
364 } else if (len
== 5 && !memcmp(elm
->rxbuf
, "ERR", 3)) {
365 /* ERR is followed by two digits, hence line length 5 */
366 netdev_err(elm
->dev
, "ELM327 reported an ERR%c%c. Please power it off and on again.\n",
367 elm
->rxbuf
[3], elm
->rxbuf
[4]);
368 frame
->can_id
|= CAN_ERR_CRTL
;
370 /* Something else has happened.
371 * Maybe garbage on the UART line.
372 * Emit a generic error frame.
376 can327_feed_frame_to_netdev(elm
, skb
);
379 /* Parse CAN frames coming as ASCII from ELM327.
380 * They can be of various formats:
382 * 29-bit ID (EFF): 12 34 56 78 D PL PL PL PL PL PL PL PL
383 * 11-bit ID (!EFF): 123 D PL PL PL PL PL PL PL PL
385 * where D = DLC, PL = payload byte
387 * Instead of a payload, RTR indicates a remote request.
389 * We will use the spaces and line length to guess the format.
391 static int can327_parse_frame(struct can327
*elm
, size_t len
)
393 struct can_frame
*frame
;
399 lockdep_assert_held(&elm
->lock
);
401 skb
= alloc_can_skb(elm
->dev
, &frame
);
405 /* Find first non-hex and non-space character:
406 * - In the simplest case, there is none.
407 * - For RTR frames, 'R' is the first non-hex character.
408 * - An error message may replace the end of the data line.
410 for (hexlen
= 0; hexlen
<= len
; hexlen
++) {
411 if (hex_to_bin(elm
->rxbuf
[hexlen
]) < 0 &&
412 elm
->rxbuf
[hexlen
] != ' ') {
417 /* Sanity check whether the line is really a clean hexdump,
418 * or terminated by an error message, or contains garbage.
420 if (hexlen
< len
&& !isdigit(elm
->rxbuf
[hexlen
]) &&
421 !isupper(elm
->rxbuf
[hexlen
]) && '<' != elm
->rxbuf
[hexlen
] &&
422 ' ' != elm
->rxbuf
[hexlen
]) {
423 /* The line is likely garbled anyway, so bail.
424 * The main code will restart listening.
430 /* Use spaces in CAN ID to distinguish 29 or 11 bit address length.
431 * No out-of-bounds access:
432 * We use the fact that we can always read from elm->rxbuf.
434 if (elm
->rxbuf
[2] == ' ' && elm
->rxbuf
[5] == ' ' &&
435 elm
->rxbuf
[8] == ' ' && elm
->rxbuf
[11] == ' ' &&
436 elm
->rxbuf
[13] == ' ') {
437 frame
->can_id
= CAN_EFF_FLAG
;
439 } else if (elm
->rxbuf
[3] == ' ' && elm
->rxbuf
[5] == ' ') {
442 /* This is not a well-formatted data line.
443 * Assume it's an error message.
449 if (hexlen
< datastart
) {
450 /* The line is too short to be a valid frame hex dump.
451 * Something interrupted the hex dump or it is invalid.
457 /* From here on all chars up to buf[hexlen] are hex or spaces,
458 * at well-defined offsets.
461 /* Read CAN data length */
462 frame
->len
= (hex_to_bin(elm
->rxbuf
[datastart
- 2]) << 0);
465 if (frame
->can_id
& CAN_EFF_FLAG
) {
466 frame
->can_id
|= (hex_to_bin(elm
->rxbuf
[0]) << 28) |
467 (hex_to_bin(elm
->rxbuf
[1]) << 24) |
468 (hex_to_bin(elm
->rxbuf
[3]) << 20) |
469 (hex_to_bin(elm
->rxbuf
[4]) << 16) |
470 (hex_to_bin(elm
->rxbuf
[6]) << 12) |
471 (hex_to_bin(elm
->rxbuf
[7]) << 8) |
472 (hex_to_bin(elm
->rxbuf
[9]) << 4) |
473 (hex_to_bin(elm
->rxbuf
[10]) << 0);
475 frame
->can_id
|= (hex_to_bin(elm
->rxbuf
[0]) << 8) |
476 (hex_to_bin(elm
->rxbuf
[1]) << 4) |
477 (hex_to_bin(elm
->rxbuf
[2]) << 0);
480 /* Check for RTR frame */
481 if (elm
->rxfill
>= hexlen
+ 3 &&
482 !memcmp(&elm
->rxbuf
[hexlen
], "RTR", 3)) {
483 frame
->can_id
|= CAN_RTR_FLAG
;
486 /* Is the line long enough to hold the advertised payload?
487 * Note: RTR frames have a DLC, but no actual payload.
489 if (!(frame
->can_id
& CAN_RTR_FLAG
) &&
490 (hexlen
< frame
->len
* 3 + datastart
)) {
492 * Probably the ELM327's RS232 TX buffer was full.
493 * Emit an error frame and exit.
495 frame
->can_id
= CAN_ERR_FLAG
| CAN_ERR_CRTL
;
496 frame
->len
= CAN_ERR_DLC
;
497 frame
->data
[1] = CAN_ERR_CRTL_RX_OVERFLOW
;
498 can327_feed_frame_to_netdev(elm
, skb
);
500 /* Signal failure to parse.
501 * The line will be re-parsed as an error line, which will fail.
502 * However, this will correctly drop the state machine back into
508 /* Parse the data nibbles. */
509 for (i
= 0; i
< frame
->len
; i
++) {
511 (hex_to_bin(elm
->rxbuf
[datastart
+ 3 * i
]) << 4) |
512 (hex_to_bin(elm
->rxbuf
[datastart
+ 3 * i
+ 1]));
515 /* Feed the frame to the network layer. */
516 can327_feed_frame_to_netdev(elm
, skb
);
521 static void can327_parse_line(struct can327
*elm
, size_t len
)
523 lockdep_assert_held(&elm
->lock
);
525 /* Skip empty lines */
529 /* Skip echo lines */
530 if (elm
->drop_next_line
) {
531 elm
->drop_next_line
= 0;
533 } else if (!memcmp(elm
->rxbuf
, "AT", 2)) {
537 /* Regular parsing */
538 if (elm
->state
== CAN327_STATE_RECEIVING
&&
539 can327_parse_frame(elm
, len
)) {
540 /* Parse an error line. */
541 can327_parse_error(elm
, len
);
544 can327_kick_into_cmd_mode(elm
);
548 static void can327_handle_prompt(struct can327
*elm
)
550 struct can_frame
*frame
= &elm
->can_frame_to_send
;
551 /* Size this buffer for the largest ELM327 line we may generate,
552 * which is currently an 8 byte CAN frame's payload hexdump.
553 * Items in can327_init_script must fit here, too!
555 char local_txbuf
[sizeof("0102030405060708\r")];
557 lockdep_assert_held(&elm
->lock
);
559 if (!elm
->cmds_todo
) {
560 /* Enter CAN monitor mode */
561 can327_send(elm
, "ATMA\r", 5);
562 elm
->state
= CAN327_STATE_RECEIVING
;
564 /* We will be in the default state once this command is
565 * sent, so enable the TX packet queue.
567 netif_wake_queue(elm
->dev
);
572 /* Reconfigure ELM327 step by step as indicated by elm->cmds_todo */
573 if (test_bit(CAN327_TX_DO_INIT
, &elm
->cmds_todo
)) {
574 snprintf(local_txbuf
, sizeof(local_txbuf
), "%s",
575 *elm
->next_init_cmd
);
577 elm
->next_init_cmd
++;
578 if (!(*elm
->next_init_cmd
)) {
579 clear_bit(CAN327_TX_DO_INIT
, &elm
->cmds_todo
);
583 } else if (test_and_clear_bit(CAN327_TX_DO_SILENT_MONITOR
, &elm
->cmds_todo
)) {
584 snprintf(local_txbuf
, sizeof(local_txbuf
),
586 !!(elm
->can
.ctrlmode
& CAN_CTRLMODE_LISTENONLY
));
588 } else if (test_and_clear_bit(CAN327_TX_DO_RESPONSES
, &elm
->cmds_todo
)) {
589 snprintf(local_txbuf
, sizeof(local_txbuf
),
591 !(elm
->can
.ctrlmode
& CAN_CTRLMODE_LISTENONLY
));
593 } else if (test_and_clear_bit(CAN327_TX_DO_CAN_CONFIG
, &elm
->cmds_todo
)) {
594 snprintf(local_txbuf
, sizeof(local_txbuf
),
596 set_bit(CAN327_TX_DO_CAN_CONFIG_PART2
, &elm
->cmds_todo
);
598 } else if (test_and_clear_bit(CAN327_TX_DO_CAN_CONFIG_PART2
, &elm
->cmds_todo
)) {
599 snprintf(local_txbuf
, sizeof(local_txbuf
),
603 } else if (test_and_clear_bit(CAN327_TX_DO_CANID_29BIT_HIGH
, &elm
->cmds_todo
)) {
604 snprintf(local_txbuf
, sizeof(local_txbuf
),
606 (frame
->can_id
& CAN_EFF_MASK
) >> 24);
608 } else if (test_and_clear_bit(CAN327_TX_DO_CANID_29BIT_LOW
, &elm
->cmds_todo
)) {
609 snprintf(local_txbuf
, sizeof(local_txbuf
),
611 frame
->can_id
& CAN_EFF_MASK
& ((1 << 24) - 1));
613 } else if (test_and_clear_bit(CAN327_TX_DO_CANID_11BIT
, &elm
->cmds_todo
)) {
614 snprintf(local_txbuf
, sizeof(local_txbuf
),
616 frame
->can_id
& CAN_SFF_MASK
);
618 } else if (test_and_clear_bit(CAN327_TX_DO_CAN_DATA
, &elm
->cmds_todo
)) {
619 if (frame
->can_id
& CAN_RTR_FLAG
) {
620 /* Send an RTR frame. Their DLC is fixed.
621 * Some chips don't send them at all.
623 snprintf(local_txbuf
, sizeof(local_txbuf
), "ATRTR\r");
625 /* Send a regular CAN data frame */
628 for (i
= 0; i
< frame
->len
; i
++) {
629 snprintf(&local_txbuf
[2 * i
],
630 sizeof(local_txbuf
), "%02X",
634 snprintf(&local_txbuf
[2 * i
], sizeof(local_txbuf
),
638 elm
->drop_next_line
= 1;
639 elm
->state
= CAN327_STATE_RECEIVING
;
641 /* We will be in the default state once this command is
642 * sent, so enable the TX packet queue.
644 netif_wake_queue(elm
->dev
);
647 can327_send(elm
, local_txbuf
, strlen(local_txbuf
));
650 static bool can327_is_ready_char(char c
)
652 /* Bits 0xc0 are sometimes set (randomly), hence the mask.
653 * Probably bad hardware.
655 return (c
& 0x3f) == CAN327_READY_CHAR
;
658 static void can327_drop_bytes(struct can327
*elm
, size_t i
)
660 lockdep_assert_held(&elm
->lock
);
662 memmove(&elm
->rxbuf
[0], &elm
->rxbuf
[i
], CAN327_SIZE_RXBUF
- i
);
666 static void can327_parse_rxbuf(struct can327
*elm
, size_t first_new_char_idx
)
670 lockdep_assert_held(&elm
->lock
);
672 switch (elm
->state
) {
673 case CAN327_STATE_NOTINIT
:
677 case CAN327_STATE_GETDUMMYCHAR
:
678 /* Wait for 'y' or '>' */
679 for (pos
= 0; pos
< elm
->rxfill
; pos
++) {
680 if (elm
->rxbuf
[pos
] == CAN327_DUMMY_CHAR
) {
681 can327_send(elm
, "\r", 1);
682 elm
->state
= CAN327_STATE_GETPROMPT
;
685 } else if (can327_is_ready_char(elm
->rxbuf
[pos
])) {
686 can327_send(elm
, CAN327_DUMMY_STRING
, 1);
692 can327_drop_bytes(elm
, pos
);
695 case CAN327_STATE_GETPROMPT
:
697 if (can327_is_ready_char(elm
->rxbuf
[elm
->rxfill
- 1]))
698 can327_handle_prompt(elm
);
703 case CAN327_STATE_RECEIVING
:
704 /* Find <CR> delimiting feedback lines. */
705 len
= first_new_char_idx
;
706 while (len
< elm
->rxfill
&& elm
->rxbuf
[len
] != '\r')
709 if (len
== CAN327_SIZE_RXBUF
) {
710 /* Assume the buffer ran full with garbage.
711 * Did we even connect at the right baud rate?
714 "RX buffer overflow. Faulty ELM327 or UART?\n");
715 can327_uart_side_failure(elm
);
716 } else if (len
== elm
->rxfill
) {
717 if (can327_is_ready_char(elm
->rxbuf
[elm
->rxfill
- 1])) {
718 /* The ELM327's AT ST response timeout ran out,
719 * so we got a prompt.
720 * Clear RX buffer and restart listening.
724 can327_handle_prompt(elm
);
727 /* No <CR> found - we haven't received a full line yet.
728 * Wait for more data.
731 /* We have a full line to parse. */
732 can327_parse_line(elm
, len
);
734 /* Remove parsed data from RX buffer. */
735 can327_drop_bytes(elm
, len
+ 1);
737 /* More data to parse? */
739 can327_parse_rxbuf(elm
, 0);
744 static int can327_netdev_open(struct net_device
*dev
)
746 struct can327
*elm
= netdev_priv(dev
);
749 spin_lock_bh(&elm
->lock
);
752 spin_unlock_bh(&elm
->lock
);
756 if (elm
->uart_side_failure
)
757 netdev_warn(elm
->dev
,
758 "Reopening netdev after a UART side fault has been detected.\n");
760 /* Clear TTY buffers */
764 /* open_candev() checks for elm->can.bittiming.bitrate != 0 */
765 err
= open_candev(dev
);
767 spin_unlock_bh(&elm
->lock
);
771 can327_init_device(elm
);
772 spin_unlock_bh(&elm
->lock
);
774 err
= can_rx_offload_add_manual(dev
, &elm
->offload
, CAN327_NAPI_WEIGHT
);
780 can_rx_offload_enable(&elm
->offload
);
782 elm
->can
.state
= CAN_STATE_ERROR_ACTIVE
;
783 netif_start_queue(dev
);
788 static int can327_netdev_close(struct net_device
*dev
)
790 struct can327
*elm
= netdev_priv(dev
);
792 /* Interrupt whatever the ELM327 is doing right now */
793 spin_lock_bh(&elm
->lock
);
794 can327_send(elm
, CAN327_DUMMY_STRING
, 1);
795 spin_unlock_bh(&elm
->lock
);
797 netif_stop_queue(dev
);
799 /* We don't flush the UART TX queue here, as we want final stop
800 * commands (like the above dummy char) to be flushed out.
803 can_rx_offload_disable(&elm
->offload
);
804 elm
->can
.state
= CAN_STATE_STOPPED
;
805 can_rx_offload_del(&elm
->offload
);
811 /* Send a can_frame to a TTY. */
812 static netdev_tx_t
can327_netdev_start_xmit(struct sk_buff
*skb
,
813 struct net_device
*dev
)
815 struct can327
*elm
= netdev_priv(dev
);
816 struct can_frame
*frame
= (struct can_frame
*)skb
->data
;
818 if (can_dev_dropped_skb(dev
, skb
))
821 /* We shouldn't get here after a hardware fault:
822 * can_bus_off() calls netif_carrier_off()
824 if (elm
->uart_side_failure
) {
825 WARN_ON_ONCE(elm
->uart_side_failure
);
829 netif_stop_queue(dev
);
831 /* BHs are already disabled, so no spin_lock_bh().
832 * See Documentation/networking/netdevices.rst
834 spin_lock(&elm
->lock
);
835 can327_send_frame(elm
, frame
);
836 spin_unlock(&elm
->lock
);
838 dev
->stats
.tx_packets
++;
839 dev
->stats
.tx_bytes
+= frame
->can_id
& CAN_RTR_FLAG
? 0 : frame
->len
;
841 skb_tx_timestamp(skb
);
848 static const struct net_device_ops can327_netdev_ops
= {
849 .ndo_open
= can327_netdev_open
,
850 .ndo_stop
= can327_netdev_close
,
851 .ndo_start_xmit
= can327_netdev_start_xmit
,
852 .ndo_change_mtu
= can_change_mtu
,
855 static const struct ethtool_ops can327_ethtool_ops
= {
856 .get_ts_info
= ethtool_op_get_ts_info
,
859 static bool can327_is_valid_rx_char(u8 c
)
861 static const bool lut_char_is_valid
['z'] = {
865 ['0'] = true, true, true, true, true,
866 ['5'] = true, true, true, true, true,
868 [CAN327_READY_CHAR
] = true,
870 ['A'] = true, true, true, true, true, true, true,
871 ['H'] = true, true, true, true, true, true, true,
872 ['O'] = true, true, true, true, true, true, true,
873 ['V'] = true, true, true, true, true,
877 [CAN327_DUMMY_CHAR
] = true,
879 BUILD_BUG_ON(CAN327_DUMMY_CHAR
>= 'z');
881 return (c
< ARRAY_SIZE(lut_char_is_valid
) && lut_char_is_valid
[c
]);
884 /* Handle incoming ELM327 ASCII data.
885 * This will not be re-entered while running, but other ldisc
886 * functions may be called in parallel.
888 static void can327_ldisc_rx(struct tty_struct
*tty
, const u8
*cp
,
889 const u8
*fp
, size_t count
)
891 struct can327
*elm
= tty
->disc_data
;
892 size_t first_new_char_idx
;
894 if (elm
->uart_side_failure
)
897 spin_lock_bh(&elm
->lock
);
899 /* Store old rxfill, so can327_parse_rxbuf() will have
900 * the option of skipping already checked characters.
902 first_new_char_idx
= elm
->rxfill
;
905 if (elm
->rxfill
>= CAN327_SIZE_RXBUF
) {
907 "Receive buffer overflowed. Bad chip or wiring? count = %zu",
913 "Error in received character stream. Check your wiring.");
917 /* Ignore NUL characters, which the PIC microcontroller may
918 * inadvertently insert due to a known hardware bug.
919 * See ELM327 documentation, which refers to a Microchip PIC
923 /* Check for stray characters on the UART line.
924 * Likely caused by bad hardware.
926 if (!can327_is_valid_rx_char(*cp
)) {
928 "Received illegal character %02x.\n",
933 elm
->rxbuf
[elm
->rxfill
++] = *cp
;
939 can327_parse_rxbuf(elm
, first_new_char_idx
);
940 spin_unlock_bh(&elm
->lock
);
944 can327_uart_side_failure(elm
);
945 spin_unlock_bh(&elm
->lock
);
948 /* Write out remaining transmit buffer.
949 * Scheduled when TTY is writable.
951 static void can327_ldisc_tx_worker(struct work_struct
*work
)
953 struct can327
*elm
= container_of(work
, struct can327
, tx_work
);
956 if (elm
->uart_side_failure
)
959 spin_lock_bh(&elm
->lock
);
962 written
= elm
->tty
->ops
->write(elm
->tty
, elm
->txhead
,
965 netdev_err(elm
->dev
, "Failed to write to tty %s.\n",
967 can327_uart_side_failure(elm
);
969 spin_unlock_bh(&elm
->lock
);
973 elm
->txleft
-= written
;
974 elm
->txhead
+= written
;
978 clear_bit(TTY_DO_WRITE_WAKEUP
, &elm
->tty
->flags
);
980 spin_unlock_bh(&elm
->lock
);
983 /* Called by the driver when there's room for more data. */
984 static void can327_ldisc_tx_wakeup(struct tty_struct
*tty
)
986 struct can327
*elm
= tty
->disc_data
;
988 schedule_work(&elm
->tx_work
);
991 /* ELM327 can only handle bitrates that are integer divisors of 500 kHz,
992 * or 7/8 of that. Divisors are 1 to 64.
993 * Currently we don't implement support for 7/8 rates.
995 static const u32 can327_bitrate_const
[] = {
996 7812, 7936, 8064, 8196, 8333, 8474, 8620, 8771,
997 8928, 9090, 9259, 9433, 9615, 9803, 10000, 10204,
998 10416, 10638, 10869, 11111, 11363, 11627, 11904, 12195,
999 12500, 12820, 13157, 13513, 13888, 14285, 14705, 15151,
1000 15625, 16129, 16666, 17241, 17857, 18518, 19230, 20000,
1001 20833, 21739, 22727, 23809, 25000, 26315, 27777, 29411,
1002 31250, 33333, 35714, 38461, 41666, 45454, 50000, 55555,
1003 62500, 71428, 83333, 100000, 125000, 166666, 250000, 500000
1006 static int can327_ldisc_open(struct tty_struct
*tty
)
1008 struct net_device
*dev
;
1012 if (!capable(CAP_NET_ADMIN
))
1015 if (!tty
->ops
->write
)
1018 dev
= alloc_candev(sizeof(struct can327
), 0);
1021 elm
= netdev_priv(dev
);
1023 /* Configure TTY interface */
1024 tty
->receive_room
= 65536; /* We don't flow control */
1025 spin_lock_init(&elm
->lock
);
1026 INIT_WORK(&elm
->tx_work
, can327_ldisc_tx_worker
);
1028 /* Configure CAN metadata */
1029 elm
->can
.bitrate_const
= can327_bitrate_const
;
1030 elm
->can
.bitrate_const_cnt
= ARRAY_SIZE(can327_bitrate_const
);
1031 elm
->can
.ctrlmode_supported
= CAN_CTRLMODE_LISTENONLY
;
1033 /* Configure netdev interface */
1035 dev
->netdev_ops
= &can327_netdev_ops
;
1036 dev
->ethtool_ops
= &can327_ethtool_ops
;
1038 /* Mark ldisc channel as alive */
1040 tty
->disc_data
= elm
;
1043 err
= register_candev(elm
->dev
);
1045 free_candev(elm
->dev
);
1049 netdev_info(elm
->dev
, "can327 on %s.\n", tty
->name
);
1054 /* Close down a can327 channel.
1055 * This means flushing out any pending queues, and then returning.
1056 * This call is serialized against other ldisc functions:
1057 * Once this is called, no other ldisc function of ours is entered.
1059 * We also use this function for a hangup event.
1061 static void can327_ldisc_close(struct tty_struct
*tty
)
1063 struct can327
*elm
= tty
->disc_data
;
1065 /* unregister_netdev() calls .ndo_stop() so we don't have to. */
1066 unregister_candev(elm
->dev
);
1068 /* Give UART one final chance to flush.
1069 * No need to clear TTY_DO_WRITE_WAKEUP since .write_wakeup() is
1070 * serialised against .close() and will not be called once we return.
1072 flush_work(&elm
->tx_work
);
1074 /* Mark channel as dead */
1075 spin_lock_bh(&elm
->lock
);
1076 tty
->disc_data
= NULL
;
1078 spin_unlock_bh(&elm
->lock
);
1080 netdev_info(elm
->dev
, "can327 off %s.\n", tty
->name
);
1082 free_candev(elm
->dev
);
1085 static int can327_ldisc_ioctl(struct tty_struct
*tty
, unsigned int cmd
,
1088 struct can327
*elm
= tty
->disc_data
;
1093 tmp
= strnlen(elm
->dev
->name
, IFNAMSIZ
- 1) + 1;
1094 if (copy_to_user((void __user
*)arg
, elm
->dev
->name
, tmp
))
1102 return tty_mode_ioctl(tty
, cmd
, arg
);
1106 static struct tty_ldisc_ops can327_ldisc
= {
1107 .owner
= THIS_MODULE
,
1108 .name
= KBUILD_MODNAME
,
1110 .receive_buf
= can327_ldisc_rx
,
1111 .write_wakeup
= can327_ldisc_tx_wakeup
,
1112 .open
= can327_ldisc_open
,
1113 .close
= can327_ldisc_close
,
1114 .ioctl
= can327_ldisc_ioctl
,
1117 static int __init
can327_init(void)
1121 status
= tty_register_ldisc(&can327_ldisc
);
1123 pr_err("Can't register line discipline\n");
1128 static void __exit
can327_exit(void)
1130 /* This will only be called when all channels have been closed by
1131 * userspace - tty_ldisc.c takes care of the module's refcount.
1133 tty_unregister_ldisc(&can327_ldisc
);
1136 module_init(can327_init
);
1137 module_exit(can327_exit
);
1139 MODULE_ALIAS_LDISC(N_CAN327
);
1140 MODULE_DESCRIPTION("ELM327 based CAN interface");
1141 MODULE_LICENSE("GPL");
1142 MODULE_AUTHOR("Max Staudt <max@enpas.org>");