xref: /linux/drivers/net/can/can327.c (revision ca220141fa8ebae09765a242076b2b77338106b0)
1 // SPDX-License-Identifier: GPL-2.0
2 /* ELM327 based CAN interface driver (tty line discipline)
3  *
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.
6  *
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>
11  */
12 
13 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
14 
15 #include <linux/init.h>
16 #include <linux/module.h>
17 
18 #include <linux/bitops.h>
19 #include <linux/ctype.h>
20 #include <linux/errno.h>
21 #include <linux/hex.h>
22 #include <linux/kernel.h>
23 #include <linux/list.h>
24 #include <linux/lockdep.h>
25 #include <linux/netdevice.h>
26 #include <linux/skbuff.h>
27 #include <linux/spinlock.h>
28 #include <linux/string.h>
29 #include <linux/tty.h>
30 #include <linux/tty_ldisc.h>
31 #include <linux/workqueue.h>
32 
33 #include <uapi/linux/tty.h>
34 
35 #include <linux/can.h>
36 #include <linux/can/dev.h>
37 #include <linux/can/error.h>
38 #include <linux/can/rx-offload.h>
39 
40 #define CAN327_NAPI_WEIGHT 4
41 
42 #define CAN327_SIZE_TXBUF 32
43 #define CAN327_SIZE_RXBUF 1024
44 
45 #define CAN327_CAN_CONFIG_SEND_SFF 0x8000
46 #define CAN327_CAN_CONFIG_VARIABLE_DLC 0x4000
47 #define CAN327_CAN_CONFIG_RECV_BOTH_SFF_EFF 0x2000
48 #define CAN327_CAN_CONFIG_BAUDRATE_MULT_8_7 0x1000
49 
50 #define CAN327_DUMMY_CHAR 'y'
51 #define CAN327_DUMMY_STRING "y"
52 #define CAN327_READY_CHAR '>'
53 
54 /* Bits in elm->cmds_todo */
55 enum can327_tx_do {
56 	CAN327_TX_DO_CAN_DATA = 0,
57 	CAN327_TX_DO_CANID_11BIT,
58 	CAN327_TX_DO_CANID_29BIT_LOW,
59 	CAN327_TX_DO_CANID_29BIT_HIGH,
60 	CAN327_TX_DO_CAN_CONFIG_PART2,
61 	CAN327_TX_DO_CAN_CONFIG,
62 	CAN327_TX_DO_RESPONSES,
63 	CAN327_TX_DO_SILENT_MONITOR,
64 	CAN327_TX_DO_INIT,
65 };
66 
67 struct can327 {
68 	/* This must be the first member when using alloc_candev() */
69 	struct can_priv can;
70 
71 	struct can_rx_offload offload;
72 
73 	/* TTY buffers */
74 	u8 txbuf[CAN327_SIZE_TXBUF];
75 	u8 rxbuf[CAN327_SIZE_RXBUF];
76 
77 	/* Per-channel lock */
78 	spinlock_t lock;
79 
80 	/* TTY and netdev devices that we're bridging */
81 	struct tty_struct *tty;
82 	struct net_device *dev;
83 
84 	/* TTY buffer accounting */
85 	struct work_struct tx_work;	/* Flushes TTY TX buffer */
86 	u8 *txhead;			/* Next TX byte */
87 	size_t txleft;			/* Bytes left to TX */
88 	int rxfill;			/* Bytes already RX'd in buffer */
89 
90 	/* State machine */
91 	enum {
92 		CAN327_STATE_NOTINIT = 0,
93 		CAN327_STATE_GETDUMMYCHAR,
94 		CAN327_STATE_GETPROMPT,
95 		CAN327_STATE_RECEIVING,
96 	} state;
97 
98 	/* Things we have yet to send */
99 	char **next_init_cmd;
100 	unsigned long cmds_todo;
101 
102 	/* The CAN frame and config the ELM327 is sending/using,
103 	 * or will send/use after finishing all cmds_todo
104 	 */
105 	struct can_frame can_frame_to_send;
106 	u16 can_config;
107 	u8 can_bitrate_divisor;
108 
109 	/* Parser state */
110 	bool drop_next_line;
111 
112 	/* Stop the channel on UART side hardware failure, e.g. stray
113 	 * characters or neverending lines. This may be caused by bad
114 	 * UART wiring, a bad ELM327, a bad UART bridge...
115 	 * Once this is true, nothing will be sent to the TTY.
116 	 */
117 	bool uart_side_failure;
118 };
119 
120 static inline void can327_uart_side_failure(struct can327 *elm);
121 
122 static void can327_send(struct can327 *elm, const void *buf, size_t len)
123 {
124 	int written;
125 
126 	lockdep_assert_held(&elm->lock);
127 
128 	if (elm->uart_side_failure)
129 		return;
130 
131 	memcpy(elm->txbuf, buf, len);
132 
133 	/* Order of next two lines is *very* important.
134 	 * When we are sending a little amount of data,
135 	 * the transfer may be completed inside the ops->write()
136 	 * routine, because it's running with interrupts enabled.
137 	 * In this case we *never* got WRITE_WAKEUP event,
138 	 * if we did not request it before write operation.
139 	 *       14 Oct 1994  Dmitry Gorodchanin.
140 	 */
141 	set_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
142 	written = elm->tty->ops->write(elm->tty, elm->txbuf, len);
143 	if (written < 0) {
144 		netdev_err(elm->dev, "Failed to write to tty %s.\n",
145 			   elm->tty->name);
146 		can327_uart_side_failure(elm);
147 		return;
148 	}
149 
150 	elm->txleft = len - written;
151 	elm->txhead = elm->txbuf + written;
152 }
153 
154 /* Take the ELM327 out of almost any state and back into command mode.
155  * We send CAN327_DUMMY_CHAR which will either abort any running
156  * operation, or be echoed back to us in case we're already in command
157  * mode.
158  */
159 static void can327_kick_into_cmd_mode(struct can327 *elm)
160 {
161 	lockdep_assert_held(&elm->lock);
162 
163 	if (elm->state != CAN327_STATE_GETDUMMYCHAR &&
164 	    elm->state != CAN327_STATE_GETPROMPT) {
165 		can327_send(elm, CAN327_DUMMY_STRING, 1);
166 
167 		elm->state = CAN327_STATE_GETDUMMYCHAR;
168 	}
169 }
170 
171 /* Schedule a CAN frame and necessary config changes to be sent to the TTY. */
172 static void can327_send_frame(struct can327 *elm, struct can_frame *frame)
173 {
174 	lockdep_assert_held(&elm->lock);
175 
176 	/* Schedule any necessary changes in ELM327's CAN configuration */
177 	if (elm->can_frame_to_send.can_id != frame->can_id) {
178 		/* Set the new CAN ID for transmission. */
179 		if ((frame->can_id ^ elm->can_frame_to_send.can_id)
180 		    & CAN_EFF_FLAG) {
181 			elm->can_config =
182 				(frame->can_id & CAN_EFF_FLAG ? 0 : CAN327_CAN_CONFIG_SEND_SFF) |
183 				CAN327_CAN_CONFIG_VARIABLE_DLC |
184 				CAN327_CAN_CONFIG_RECV_BOTH_SFF_EFF |
185 				elm->can_bitrate_divisor;
186 
187 			set_bit(CAN327_TX_DO_CAN_CONFIG, &elm->cmds_todo);
188 		}
189 
190 		if (frame->can_id & CAN_EFF_FLAG) {
191 			clear_bit(CAN327_TX_DO_CANID_11BIT, &elm->cmds_todo);
192 			set_bit(CAN327_TX_DO_CANID_29BIT_LOW, &elm->cmds_todo);
193 			set_bit(CAN327_TX_DO_CANID_29BIT_HIGH, &elm->cmds_todo);
194 		} else {
195 			set_bit(CAN327_TX_DO_CANID_11BIT, &elm->cmds_todo);
196 			clear_bit(CAN327_TX_DO_CANID_29BIT_LOW,
197 				  &elm->cmds_todo);
198 			clear_bit(CAN327_TX_DO_CANID_29BIT_HIGH,
199 				  &elm->cmds_todo);
200 		}
201 	}
202 
203 	/* Schedule the CAN frame itself. */
204 	elm->can_frame_to_send = *frame;
205 	set_bit(CAN327_TX_DO_CAN_DATA, &elm->cmds_todo);
206 
207 	can327_kick_into_cmd_mode(elm);
208 }
209 
210 /* ELM327 initialisation sequence.
211  * The line length is limited by the buffer in can327_handle_prompt().
212  */
213 static char *can327_init_script[] = {
214 	"AT WS\r",        /* v1.0: Warm Start */
215 	"AT PP FF OFF\r", /* v1.0: All Programmable Parameters Off */
216 	"AT M0\r",        /* v1.0: Memory Off */
217 	"AT AL\r",        /* v1.0: Allow Long messages */
218 	"AT BI\r",        /* v1.0: Bypass Initialisation */
219 	"AT CAF0\r",      /* v1.0: CAN Auto Formatting Off */
220 	"AT CFC0\r",      /* v1.0: CAN Flow Control Off */
221 	"AT CF 000\r",    /* v1.0: Reset CAN ID Filter */
222 	"AT CM 000\r",    /* v1.0: Reset CAN ID Mask */
223 	"AT E1\r",        /* v1.0: Echo On */
224 	"AT H1\r",        /* v1.0: Headers On */
225 	"AT L0\r",        /* v1.0: Linefeeds Off */
226 	"AT SH 7DF\r",    /* v1.0: Set CAN sending ID to 0x7df */
227 	"AT ST FF\r",     /* v1.0: Set maximum Timeout for response after TX */
228 	"AT AT0\r",       /* v1.2: Adaptive Timing Off */
229 	"AT D1\r",        /* v1.3: Print DLC On */
230 	"AT S1\r",        /* v1.3: Spaces On */
231 	"AT TP B\r",      /* v1.0: Try Protocol B */
232 	NULL
233 };
234 
235 static void can327_init_device(struct can327 *elm)
236 {
237 	lockdep_assert_held(&elm->lock);
238 
239 	elm->state = CAN327_STATE_NOTINIT;
240 	elm->can_frame_to_send.can_id = 0x7df; /* ELM327 HW default */
241 	elm->rxfill = 0;
242 	elm->drop_next_line = 0;
243 
244 	/* We can only set the bitrate as a fraction of 500000.
245 	 * The bitrates listed in can327_bitrate_const will
246 	 * limit the user to the right values.
247 	 */
248 	elm->can_bitrate_divisor = 500000 / elm->can.bittiming.bitrate;
249 	elm->can_config =
250 		CAN327_CAN_CONFIG_SEND_SFF | CAN327_CAN_CONFIG_VARIABLE_DLC |
251 		CAN327_CAN_CONFIG_RECV_BOTH_SFF_EFF | elm->can_bitrate_divisor;
252 
253 	/* Configure ELM327 and then start monitoring */
254 	elm->next_init_cmd = &can327_init_script[0];
255 	set_bit(CAN327_TX_DO_INIT, &elm->cmds_todo);
256 	set_bit(CAN327_TX_DO_SILENT_MONITOR, &elm->cmds_todo);
257 	set_bit(CAN327_TX_DO_RESPONSES, &elm->cmds_todo);
258 	set_bit(CAN327_TX_DO_CAN_CONFIG, &elm->cmds_todo);
259 
260 	can327_kick_into_cmd_mode(elm);
261 }
262 
263 static void can327_feed_frame_to_netdev(struct can327 *elm, struct sk_buff *skb)
264 {
265 	lockdep_assert_held(&elm->lock);
266 
267 	if (!netif_running(elm->dev)) {
268 		kfree_skb(skb);
269 		return;
270 	}
271 
272 	/* Queue for NAPI pickup.
273 	 * rx-offload will update stats and LEDs for us.
274 	 */
275 	if (can_rx_offload_queue_tail(&elm->offload, skb))
276 		elm->dev->stats.rx_fifo_errors++;
277 
278 	/* Wake NAPI */
279 	can_rx_offload_irq_finish(&elm->offload);
280 }
281 
282 /* Called when we're out of ideas and just want it all to end. */
283 static inline void can327_uart_side_failure(struct can327 *elm)
284 {
285 	struct can_frame *frame;
286 	struct sk_buff *skb;
287 
288 	lockdep_assert_held(&elm->lock);
289 
290 	elm->uart_side_failure = true;
291 
292 	clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
293 
294 	elm->can.can_stats.bus_off++;
295 	netif_stop_queue(elm->dev);
296 	elm->can.state = CAN_STATE_BUS_OFF;
297 	can_bus_off(elm->dev);
298 
299 	netdev_err(elm->dev,
300 		   "ELM327 misbehaved. Blocking further communication.\n");
301 
302 	skb = alloc_can_err_skb(elm->dev, &frame);
303 	if (!skb)
304 		return;
305 
306 	frame->can_id |= CAN_ERR_BUSOFF;
307 	can327_feed_frame_to_netdev(elm, skb);
308 }
309 
310 /* Compares a byte buffer (non-NUL terminated) to the payload part of
311  * a string, and returns true iff the buffer (content *and* length) is
312  * exactly that string, without the terminating NUL byte.
313  *
314  * Example: If reference is "BUS ERROR", then this returns true iff nbytes == 9
315  *          and !memcmp(buf, "BUS ERROR", 9).
316  *
317  * The reason to use strings is so we can easily include them in the C
318  * code, and to avoid hardcoding lengths.
319  */
320 static inline bool can327_rxbuf_cmp(const u8 *buf, size_t nbytes,
321 				    const char *reference)
322 {
323 	size_t ref_len = strlen(reference);
324 
325 	return (nbytes == ref_len) && !memcmp(buf, reference, ref_len);
326 }
327 
328 static void can327_parse_error(struct can327 *elm, size_t len)
329 {
330 	struct can_frame *frame;
331 	struct sk_buff *skb;
332 
333 	lockdep_assert_held(&elm->lock);
334 
335 	skb = alloc_can_err_skb(elm->dev, &frame);
336 	if (!skb)
337 		/* It's okay to return here:
338 		 * The outer parsing loop will drop this UART buffer.
339 		 */
340 		return;
341 
342 	/* Filter possible error messages based on length of RX'd line */
343 	if (can327_rxbuf_cmp(elm->rxbuf, len, "UNABLE TO CONNECT")) {
344 		netdev_err(elm->dev,
345 			   "ELM327 reported UNABLE TO CONNECT. Please check your setup.\n");
346 	} else if (can327_rxbuf_cmp(elm->rxbuf, len, "BUFFER FULL")) {
347 		/* This will only happen if the last data line was complete.
348 		 * Otherwise, can327_parse_frame() will heuristically
349 		 * emit this kind of error frame instead.
350 		 */
351 		frame->can_id |= CAN_ERR_CRTL;
352 		frame->data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
353 	} else if (can327_rxbuf_cmp(elm->rxbuf, len, "BUS ERROR")) {
354 		frame->can_id |= CAN_ERR_BUSERROR;
355 	} else if (can327_rxbuf_cmp(elm->rxbuf, len, "CAN ERROR")) {
356 		frame->can_id |= CAN_ERR_PROT;
357 	} else if (can327_rxbuf_cmp(elm->rxbuf, len, "<RX ERROR")) {
358 		frame->can_id |= CAN_ERR_PROT;
359 	} else if (can327_rxbuf_cmp(elm->rxbuf, len, "BUS BUSY")) {
360 		frame->can_id |= CAN_ERR_PROT;
361 		frame->data[2] = CAN_ERR_PROT_OVERLOAD;
362 	} else if (can327_rxbuf_cmp(elm->rxbuf, len, "FB ERROR")) {
363 		frame->can_id |= CAN_ERR_PROT;
364 		frame->data[2] = CAN_ERR_PROT_TX;
365 	} else if (len == 5 && !memcmp(elm->rxbuf, "ERR", 3)) {
366 		/* ERR is followed by two digits, hence line length 5 */
367 		netdev_err(elm->dev, "ELM327 reported an ERR%c%c. Please power it off and on again.\n",
368 			   elm->rxbuf[3], elm->rxbuf[4]);
369 		frame->can_id |= CAN_ERR_CRTL;
370 	} else {
371 		/* Something else has happened.
372 		 * Maybe garbage on the UART line.
373 		 * Emit a generic error frame.
374 		 */
375 	}
376 
377 	can327_feed_frame_to_netdev(elm, skb);
378 }
379 
380 /* Parse CAN frames coming as ASCII from ELM327.
381  * They can be of various formats:
382  *
383  * 29-bit ID (EFF):  12 34 56 78 D PL PL PL PL PL PL PL PL
384  * 11-bit ID (!EFF): 123 D PL PL PL PL PL PL PL PL
385  *
386  * where D = DLC, PL = payload byte
387  *
388  * Instead of a payload, RTR indicates a remote request.
389  *
390  * We will use the spaces and line length to guess the format.
391  */
392 static int can327_parse_frame(struct can327 *elm, size_t len)
393 {
394 	struct can_frame *frame;
395 	struct sk_buff *skb;
396 	int hexlen;
397 	int datastart;
398 	int i;
399 
400 	lockdep_assert_held(&elm->lock);
401 
402 	skb = alloc_can_skb(elm->dev, &frame);
403 	if (!skb)
404 		return -ENOMEM;
405 
406 	/* Find first non-hex and non-space character:
407 	 *  - In the simplest case, there is none.
408 	 *  - For RTR frames, 'R' is the first non-hex character.
409 	 *  - An error message may replace the end of the data line.
410 	 */
411 	for (hexlen = 0; hexlen <= len; hexlen++) {
412 		if (hex_to_bin(elm->rxbuf[hexlen]) < 0 &&
413 		    elm->rxbuf[hexlen] != ' ') {
414 			break;
415 		}
416 	}
417 
418 	/* Sanity check whether the line is really a clean hexdump,
419 	 * or terminated by an error message, or contains garbage.
420 	 */
421 	if (hexlen < len && !isdigit(elm->rxbuf[hexlen]) &&
422 	    !isupper(elm->rxbuf[hexlen]) && '<' != elm->rxbuf[hexlen] &&
423 	    ' ' != elm->rxbuf[hexlen]) {
424 		/* The line is likely garbled anyway, so bail.
425 		 * The main code will restart listening.
426 		 */
427 		kfree_skb(skb);
428 		return -ENODATA;
429 	}
430 
431 	/* Use spaces in CAN ID to distinguish 29 or 11 bit address length.
432 	 * No out-of-bounds access:
433 	 * We use the fact that we can always read from elm->rxbuf.
434 	 */
435 	if (elm->rxbuf[2] == ' ' && elm->rxbuf[5] == ' ' &&
436 	    elm->rxbuf[8] == ' ' && elm->rxbuf[11] == ' ' &&
437 	    elm->rxbuf[13] == ' ') {
438 		frame->can_id = CAN_EFF_FLAG;
439 		datastart = 14;
440 	} else if (elm->rxbuf[3] == ' ' && elm->rxbuf[5] == ' ') {
441 		datastart = 6;
442 	} else {
443 		/* This is not a well-formatted data line.
444 		 * Assume it's an error message.
445 		 */
446 		kfree_skb(skb);
447 		return -ENODATA;
448 	}
449 
450 	if (hexlen < datastart) {
451 		/* The line is too short to be a valid frame hex dump.
452 		 * Something interrupted the hex dump or it is invalid.
453 		 */
454 		kfree_skb(skb);
455 		return -ENODATA;
456 	}
457 
458 	/* From here on all chars up to buf[hexlen] are hex or spaces,
459 	 * at well-defined offsets.
460 	 */
461 
462 	/* Read CAN data length */
463 	frame->len = (hex_to_bin(elm->rxbuf[datastart - 2]) << 0);
464 
465 	/* Read CAN ID */
466 	if (frame->can_id & CAN_EFF_FLAG) {
467 		frame->can_id |= (hex_to_bin(elm->rxbuf[0]) << 28) |
468 				 (hex_to_bin(elm->rxbuf[1]) << 24) |
469 				 (hex_to_bin(elm->rxbuf[3]) << 20) |
470 				 (hex_to_bin(elm->rxbuf[4]) << 16) |
471 				 (hex_to_bin(elm->rxbuf[6]) << 12) |
472 				 (hex_to_bin(elm->rxbuf[7]) << 8) |
473 				 (hex_to_bin(elm->rxbuf[9]) << 4) |
474 				 (hex_to_bin(elm->rxbuf[10]) << 0);
475 	} else {
476 		frame->can_id |= (hex_to_bin(elm->rxbuf[0]) << 8) |
477 				 (hex_to_bin(elm->rxbuf[1]) << 4) |
478 				 (hex_to_bin(elm->rxbuf[2]) << 0);
479 	}
480 
481 	/* Check for RTR frame */
482 	if (elm->rxfill >= hexlen + 3 &&
483 	    !memcmp(&elm->rxbuf[hexlen], "RTR", 3)) {
484 		frame->can_id |= CAN_RTR_FLAG;
485 	}
486 
487 	/* Is the line long enough to hold the advertised payload?
488 	 * Note: RTR frames have a DLC, but no actual payload.
489 	 */
490 	if (!(frame->can_id & CAN_RTR_FLAG) &&
491 	    (hexlen < frame->len * 3 + datastart)) {
492 		/* Incomplete frame.
493 		 * Probably the ELM327's RS232 TX buffer was full.
494 		 * Emit an error frame and exit.
495 		 */
496 		frame->can_id = CAN_ERR_FLAG | CAN_ERR_CRTL;
497 		frame->len = CAN_ERR_DLC;
498 		frame->data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
499 		can327_feed_frame_to_netdev(elm, skb);
500 
501 		/* Signal failure to parse.
502 		 * The line will be re-parsed as an error line, which will fail.
503 		 * However, this will correctly drop the state machine back into
504 		 * command mode.
505 		 */
506 		return -ENODATA;
507 	}
508 
509 	/* Parse the data nibbles. */
510 	for (i = 0; i < frame->len; i++) {
511 		frame->data[i] =
512 			(hex_to_bin(elm->rxbuf[datastart + 3 * i]) << 4) |
513 			(hex_to_bin(elm->rxbuf[datastart + 3 * i + 1]));
514 	}
515 
516 	/* Feed the frame to the network layer. */
517 	can327_feed_frame_to_netdev(elm, skb);
518 
519 	return 0;
520 }
521 
522 static void can327_parse_line(struct can327 *elm, size_t len)
523 {
524 	lockdep_assert_held(&elm->lock);
525 
526 	/* Skip empty lines */
527 	if (!len)
528 		return;
529 
530 	/* Skip echo lines */
531 	if (elm->drop_next_line) {
532 		elm->drop_next_line = 0;
533 		return;
534 	} else if (!memcmp(elm->rxbuf, "AT", 2)) {
535 		return;
536 	}
537 
538 	/* Regular parsing */
539 	if (elm->state == CAN327_STATE_RECEIVING &&
540 	    can327_parse_frame(elm, len)) {
541 		/* Parse an error line. */
542 		can327_parse_error(elm, len);
543 
544 		/* Start afresh. */
545 		can327_kick_into_cmd_mode(elm);
546 	}
547 }
548 
549 static void can327_handle_prompt(struct can327 *elm)
550 {
551 	struct can_frame *frame = &elm->can_frame_to_send;
552 	/* Size this buffer for the largest ELM327 line we may generate,
553 	 * which is currently an 8 byte CAN frame's payload hexdump.
554 	 * Items in can327_init_script must fit here, too!
555 	 */
556 	char local_txbuf[sizeof("0102030405060708\r")];
557 
558 	lockdep_assert_held(&elm->lock);
559 
560 	if (!elm->cmds_todo) {
561 		/* Enter CAN monitor mode */
562 		can327_send(elm, "ATMA\r", 5);
563 		elm->state = CAN327_STATE_RECEIVING;
564 
565 		/* We will be in the default state once this command is
566 		 * sent, so enable the TX packet queue.
567 		 */
568 		netif_wake_queue(elm->dev);
569 
570 		return;
571 	}
572 
573 	/* Reconfigure ELM327 step by step as indicated by elm->cmds_todo */
574 	if (test_bit(CAN327_TX_DO_INIT, &elm->cmds_todo)) {
575 		snprintf(local_txbuf, sizeof(local_txbuf), "%s",
576 			 *elm->next_init_cmd);
577 
578 		elm->next_init_cmd++;
579 		if (!(*elm->next_init_cmd)) {
580 			clear_bit(CAN327_TX_DO_INIT, &elm->cmds_todo);
581 			/* Init finished. */
582 		}
583 
584 	} else if (test_and_clear_bit(CAN327_TX_DO_SILENT_MONITOR, &elm->cmds_todo)) {
585 		snprintf(local_txbuf, sizeof(local_txbuf),
586 			 "ATCSM%i\r",
587 			 !!(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY));
588 
589 	} else if (test_and_clear_bit(CAN327_TX_DO_RESPONSES, &elm->cmds_todo)) {
590 		snprintf(local_txbuf, sizeof(local_txbuf),
591 			 "ATR%i\r",
592 			 !(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY));
593 
594 	} else if (test_and_clear_bit(CAN327_TX_DO_CAN_CONFIG, &elm->cmds_todo)) {
595 		snprintf(local_txbuf, sizeof(local_txbuf),
596 			 "ATPC\r");
597 		set_bit(CAN327_TX_DO_CAN_CONFIG_PART2, &elm->cmds_todo);
598 
599 	} else if (test_and_clear_bit(CAN327_TX_DO_CAN_CONFIG_PART2, &elm->cmds_todo)) {
600 		snprintf(local_txbuf, sizeof(local_txbuf),
601 			 "ATPB%04X\r",
602 			 elm->can_config);
603 
604 	} else if (test_and_clear_bit(CAN327_TX_DO_CANID_29BIT_HIGH, &elm->cmds_todo)) {
605 		snprintf(local_txbuf, sizeof(local_txbuf),
606 			 "ATCP%02X\r",
607 			 (frame->can_id & CAN_EFF_MASK) >> 24);
608 
609 	} else if (test_and_clear_bit(CAN327_TX_DO_CANID_29BIT_LOW, &elm->cmds_todo)) {
610 		snprintf(local_txbuf, sizeof(local_txbuf),
611 			 "ATSH%06X\r",
612 			 frame->can_id & CAN_EFF_MASK & ((1 << 24) - 1));
613 
614 	} else if (test_and_clear_bit(CAN327_TX_DO_CANID_11BIT, &elm->cmds_todo)) {
615 		snprintf(local_txbuf, sizeof(local_txbuf),
616 			 "ATSH%03X\r",
617 			 frame->can_id & CAN_SFF_MASK);
618 
619 	} else if (test_and_clear_bit(CAN327_TX_DO_CAN_DATA, &elm->cmds_todo)) {
620 		if (frame->can_id & CAN_RTR_FLAG) {
621 			/* Send an RTR frame. Their DLC is fixed.
622 			 * Some chips don't send them at all.
623 			 */
624 			snprintf(local_txbuf, sizeof(local_txbuf), "ATRTR\r");
625 		} else {
626 			/* Send a regular CAN data frame */
627 			int i;
628 
629 			for (i = 0; i < frame->len; i++) {
630 				snprintf(&local_txbuf[2 * i],
631 					 sizeof(local_txbuf), "%02X",
632 					 frame->data[i]);
633 			}
634 
635 			snprintf(&local_txbuf[2 * i], sizeof(local_txbuf),
636 				 "\r");
637 		}
638 
639 		elm->drop_next_line = 1;
640 		elm->state = CAN327_STATE_RECEIVING;
641 
642 		/* We will be in the default state once this command is
643 		 * sent, so enable the TX packet queue.
644 		 */
645 		netif_wake_queue(elm->dev);
646 	}
647 
648 	can327_send(elm, local_txbuf, strlen(local_txbuf));
649 }
650 
651 static bool can327_is_ready_char(char c)
652 {
653 	/* Bits 0xc0 are sometimes set (randomly), hence the mask.
654 	 * Probably bad hardware.
655 	 */
656 	return (c & 0x3f) == CAN327_READY_CHAR;
657 }
658 
659 static void can327_drop_bytes(struct can327 *elm, size_t i)
660 {
661 	lockdep_assert_held(&elm->lock);
662 
663 	memmove(&elm->rxbuf[0], &elm->rxbuf[i], CAN327_SIZE_RXBUF - i);
664 	elm->rxfill -= i;
665 }
666 
667 static void can327_parse_rxbuf(struct can327 *elm, size_t first_new_char_idx)
668 {
669 	size_t len, pos;
670 
671 	lockdep_assert_held(&elm->lock);
672 
673 	switch (elm->state) {
674 	case CAN327_STATE_NOTINIT:
675 		elm->rxfill = 0;
676 		break;
677 
678 	case CAN327_STATE_GETDUMMYCHAR:
679 		/* Wait for 'y' or '>' */
680 		for (pos = 0; pos < elm->rxfill; pos++) {
681 			if (elm->rxbuf[pos] == CAN327_DUMMY_CHAR) {
682 				can327_send(elm, "\r", 1);
683 				elm->state = CAN327_STATE_GETPROMPT;
684 				pos++;
685 				break;
686 			} else if (can327_is_ready_char(elm->rxbuf[pos])) {
687 				can327_send(elm, CAN327_DUMMY_STRING, 1);
688 				pos++;
689 				break;
690 			}
691 		}
692 
693 		can327_drop_bytes(elm, pos);
694 		break;
695 
696 	case CAN327_STATE_GETPROMPT:
697 		/* Wait for '>' */
698 		if (can327_is_ready_char(elm->rxbuf[elm->rxfill - 1]))
699 			can327_handle_prompt(elm);
700 
701 		elm->rxfill = 0;
702 		break;
703 
704 	case CAN327_STATE_RECEIVING:
705 		/* Find <CR> delimiting feedback lines. */
706 		len = first_new_char_idx;
707 		while (len < elm->rxfill && elm->rxbuf[len] != '\r')
708 			len++;
709 
710 		if (len == CAN327_SIZE_RXBUF) {
711 			/* Assume the buffer ran full with garbage.
712 			 * Did we even connect at the right baud rate?
713 			 */
714 			netdev_err(elm->dev,
715 				   "RX buffer overflow. Faulty ELM327 or UART?\n");
716 			can327_uart_side_failure(elm);
717 		} else if (len == elm->rxfill) {
718 			if (can327_is_ready_char(elm->rxbuf[elm->rxfill - 1])) {
719 				/* The ELM327's AT ST response timeout ran out,
720 				 * so we got a prompt.
721 				 * Clear RX buffer and restart listening.
722 				 */
723 				elm->rxfill = 0;
724 
725 				can327_handle_prompt(elm);
726 			}
727 
728 			/* No <CR> found - we haven't received a full line yet.
729 			 * Wait for more data.
730 			 */
731 		} else {
732 			/* We have a full line to parse. */
733 			can327_parse_line(elm, len);
734 
735 			/* Remove parsed data from RX buffer. */
736 			can327_drop_bytes(elm, len + 1);
737 
738 			/* More data to parse? */
739 			if (elm->rxfill)
740 				can327_parse_rxbuf(elm, 0);
741 		}
742 	}
743 }
744 
745 static int can327_netdev_open(struct net_device *dev)
746 {
747 	struct can327 *elm = netdev_priv(dev);
748 	int err;
749 
750 	spin_lock_bh(&elm->lock);
751 
752 	if (!elm->tty) {
753 		spin_unlock_bh(&elm->lock);
754 		return -ENODEV;
755 	}
756 
757 	if (elm->uart_side_failure)
758 		netdev_warn(elm->dev,
759 			    "Reopening netdev after a UART side fault has been detected.\n");
760 
761 	/* Clear TTY buffers */
762 	elm->rxfill = 0;
763 	elm->txleft = 0;
764 
765 	/* open_candev() checks for elm->can.bittiming.bitrate != 0 */
766 	err = open_candev(dev);
767 	if (err) {
768 		spin_unlock_bh(&elm->lock);
769 		return err;
770 	}
771 
772 	can327_init_device(elm);
773 	spin_unlock_bh(&elm->lock);
774 
775 	err = can_rx_offload_add_manual(dev, &elm->offload, CAN327_NAPI_WEIGHT);
776 	if (err) {
777 		close_candev(dev);
778 		return err;
779 	}
780 
781 	can_rx_offload_enable(&elm->offload);
782 
783 	elm->can.state = CAN_STATE_ERROR_ACTIVE;
784 	netif_start_queue(dev);
785 
786 	return 0;
787 }
788 
789 static int can327_netdev_close(struct net_device *dev)
790 {
791 	struct can327 *elm = netdev_priv(dev);
792 
793 	/* Interrupt whatever the ELM327 is doing right now */
794 	spin_lock_bh(&elm->lock);
795 	can327_send(elm, CAN327_DUMMY_STRING, 1);
796 	spin_unlock_bh(&elm->lock);
797 
798 	netif_stop_queue(dev);
799 
800 	/* We don't flush the UART TX queue here, as we want final stop
801 	 * commands (like the above dummy char) to be flushed out.
802 	 */
803 
804 	can_rx_offload_disable(&elm->offload);
805 	elm->can.state = CAN_STATE_STOPPED;
806 	can_rx_offload_del(&elm->offload);
807 	close_candev(dev);
808 
809 	return 0;
810 }
811 
812 /* Send a can_frame to a TTY. */
813 static netdev_tx_t can327_netdev_start_xmit(struct sk_buff *skb,
814 					    struct net_device *dev)
815 {
816 	struct can327 *elm = netdev_priv(dev);
817 	struct can_frame *frame = (struct can_frame *)skb->data;
818 
819 	if (can_dev_dropped_skb(dev, skb))
820 		return NETDEV_TX_OK;
821 
822 	/* We shouldn't get here after a hardware fault:
823 	 * can_bus_off() calls netif_carrier_off()
824 	 */
825 	if (elm->uart_side_failure) {
826 		WARN_ON_ONCE(elm->uart_side_failure);
827 		goto out;
828 	}
829 
830 	netif_stop_queue(dev);
831 
832 	/* BHs are already disabled, so no spin_lock_bh().
833 	 * See Documentation/networking/netdevices.rst
834 	 */
835 	spin_lock(&elm->lock);
836 	can327_send_frame(elm, frame);
837 	spin_unlock(&elm->lock);
838 
839 	dev->stats.tx_packets++;
840 	dev->stats.tx_bytes += frame->can_id & CAN_RTR_FLAG ? 0 : frame->len;
841 
842 	skb_tx_timestamp(skb);
843 
844 out:
845 	kfree_skb(skb);
846 	return NETDEV_TX_OK;
847 }
848 
849 static const struct net_device_ops can327_netdev_ops = {
850 	.ndo_open = can327_netdev_open,
851 	.ndo_stop = can327_netdev_close,
852 	.ndo_start_xmit = can327_netdev_start_xmit,
853 };
854 
855 static const struct ethtool_ops can327_ethtool_ops = {
856 	.get_ts_info = ethtool_op_get_ts_info,
857 };
858 
859 static bool can327_is_valid_rx_char(u8 c)
860 {
861 	static const bool lut_char_is_valid['z'] = {
862 		['\r'] = true,
863 		[' '] = true,
864 		['.'] = true,
865 		['0'] = true, true, true, true, true,
866 		['5'] = true, true, true, true, true,
867 		['<'] = true,
868 		[CAN327_READY_CHAR] = true,
869 		['?'] = 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,
874 		['a'] = true,
875 		['b'] = true,
876 		['v'] = true,
877 		[CAN327_DUMMY_CHAR] = true,
878 	};
879 	BUILD_BUG_ON(CAN327_DUMMY_CHAR >= 'z');
880 
881 	return (c < ARRAY_SIZE(lut_char_is_valid) && lut_char_is_valid[c]);
882 }
883 
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.
887  */
888 static void can327_ldisc_rx(struct tty_struct *tty, const u8 *cp,
889 			    const u8 *fp, size_t count)
890 {
891 	struct can327 *elm = tty->disc_data;
892 	size_t first_new_char_idx;
893 
894 	if (elm->uart_side_failure)
895 		return;
896 
897 	spin_lock_bh(&elm->lock);
898 
899 	/* Store old rxfill, so can327_parse_rxbuf() will have
900 	 * the option of skipping already checked characters.
901 	 */
902 	first_new_char_idx = elm->rxfill;
903 
904 	while (count--) {
905 		if (elm->rxfill >= CAN327_SIZE_RXBUF) {
906 			netdev_err(elm->dev,
907 				   "Receive buffer overflowed. Bad chip or wiring? count = %zu",
908 				   count);
909 			goto uart_failure;
910 		}
911 		if (fp && *fp++) {
912 			netdev_err(elm->dev,
913 				   "Error in received character stream. Check your wiring.");
914 			goto uart_failure;
915 		}
916 
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
920 		 * bug description.
921 		 */
922 		if (*cp) {
923 			/* Check for stray characters on the UART line.
924 			 * Likely caused by bad hardware.
925 			 */
926 			if (!can327_is_valid_rx_char(*cp)) {
927 				netdev_err(elm->dev,
928 					   "Received illegal character %02x.\n",
929 					   *cp);
930 				goto uart_failure;
931 			}
932 
933 			elm->rxbuf[elm->rxfill++] = *cp;
934 		}
935 
936 		cp++;
937 	}
938 
939 	can327_parse_rxbuf(elm, first_new_char_idx);
940 	spin_unlock_bh(&elm->lock);
941 
942 	return;
943 uart_failure:
944 	can327_uart_side_failure(elm);
945 	spin_unlock_bh(&elm->lock);
946 }
947 
948 /* Write out remaining transmit buffer.
949  * Scheduled when TTY is writable.
950  */
951 static void can327_ldisc_tx_worker(struct work_struct *work)
952 {
953 	struct can327 *elm = container_of(work, struct can327, tx_work);
954 	ssize_t written;
955 
956 	if (elm->uart_side_failure)
957 		return;
958 
959 	spin_lock_bh(&elm->lock);
960 
961 	if (elm->txleft) {
962 		written = elm->tty->ops->write(elm->tty, elm->txhead,
963 					       elm->txleft);
964 		if (written < 0) {
965 			netdev_err(elm->dev, "Failed to write to tty %s.\n",
966 				   elm->tty->name);
967 			can327_uart_side_failure(elm);
968 
969 			spin_unlock_bh(&elm->lock);
970 			return;
971 		}
972 
973 		elm->txleft -= written;
974 		elm->txhead += written;
975 	}
976 
977 	if (!elm->txleft)
978 		clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
979 
980 	spin_unlock_bh(&elm->lock);
981 }
982 
983 /* Called by the driver when there's room for more data. */
984 static void can327_ldisc_tx_wakeup(struct tty_struct *tty)
985 {
986 	struct can327 *elm = tty->disc_data;
987 
988 	schedule_work(&elm->tx_work);
989 }
990 
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.
994  */
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
1004 };
1005 
1006 static int can327_ldisc_open(struct tty_struct *tty)
1007 {
1008 	struct net_device *dev;
1009 	struct can327 *elm;
1010 	int err;
1011 
1012 	if (!capable(CAP_NET_ADMIN))
1013 		return -EPERM;
1014 
1015 	if (!tty->ops->write)
1016 		return -EOPNOTSUPP;
1017 
1018 	dev = alloc_candev(sizeof(struct can327), 0);
1019 	if (!dev)
1020 		return -ENFILE;
1021 	elm = netdev_priv(dev);
1022 
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);
1027 
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;
1032 
1033 	/* Configure netdev interface */
1034 	elm->dev = dev;
1035 	dev->netdev_ops = &can327_netdev_ops;
1036 	dev->ethtool_ops = &can327_ethtool_ops;
1037 
1038 	/* Mark ldisc channel as alive */
1039 	elm->tty = tty;
1040 	tty->disc_data = elm;
1041 
1042 	/* Let 'er rip */
1043 	err = register_candev(elm->dev);
1044 	if (err) {
1045 		free_candev(elm->dev);
1046 		return err;
1047 	}
1048 
1049 	netdev_info(elm->dev, "can327 on %s.\n", tty->name);
1050 
1051 	return 0;
1052 }
1053 
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.
1058  *
1059  * We also use this function for a hangup event.
1060  */
1061 static void can327_ldisc_close(struct tty_struct *tty)
1062 {
1063 	struct can327 *elm = tty->disc_data;
1064 
1065 	/* unregister_netdev() calls .ndo_stop() so we don't have to. */
1066 	unregister_candev(elm->dev);
1067 
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.
1071 	 */
1072 	flush_work(&elm->tx_work);
1073 
1074 	/* Mark channel as dead */
1075 	spin_lock_bh(&elm->lock);
1076 	tty->disc_data = NULL;
1077 	elm->tty = NULL;
1078 	spin_unlock_bh(&elm->lock);
1079 
1080 	netdev_info(elm->dev, "can327 off %s.\n", tty->name);
1081 
1082 	free_candev(elm->dev);
1083 }
1084 
1085 static int can327_ldisc_ioctl(struct tty_struct *tty, unsigned int cmd,
1086 			      unsigned long arg)
1087 {
1088 	struct can327 *elm = tty->disc_data;
1089 	unsigned int tmp;
1090 
1091 	switch (cmd) {
1092 	case SIOCGIFNAME:
1093 		tmp = strnlen(elm->dev->name, IFNAMSIZ - 1) + 1;
1094 		if (copy_to_user((void __user *)arg, elm->dev->name, tmp))
1095 			return -EFAULT;
1096 		return 0;
1097 
1098 	case SIOCSIFHWADDR:
1099 		return -EINVAL;
1100 
1101 	default:
1102 		return tty_mode_ioctl(tty, cmd, arg);
1103 	}
1104 }
1105 
1106 static struct tty_ldisc_ops can327_ldisc = {
1107 	.owner = THIS_MODULE,
1108 	.name = KBUILD_MODNAME,
1109 	.num = N_CAN327,
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,
1115 };
1116 
1117 static int __init can327_init(void)
1118 {
1119 	int status;
1120 
1121 	status = tty_register_ldisc(&can327_ldisc);
1122 	if (status)
1123 		pr_err("Can't register line discipline\n");
1124 
1125 	return status;
1126 }
1127 
1128 static void __exit can327_exit(void)
1129 {
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.
1132 	 */
1133 	tty_unregister_ldisc(&can327_ldisc);
1134 }
1135 
1136 module_init(can327_init);
1137 module_exit(can327_exit);
1138 
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>");
1143