76ec682e9450b6d93d16d199ba426b604a2ce944
[elmcan.git] / module / elmcan.c
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, even
6  * after almost none of their code is left.
7  */
8
9 #define pr_fmt(fmt) "[elmcan] " fmt
10
11 #include <linux/init.h>
12 #include <linux/module.h>
13 #include <linux/moduleparam.h>
14
15 #include <linux/atomic.h>
16 #include <linux/bitops.h>
17 #include <linux/ctype.h>
18 #include <linux/delay.h>
19 #include <linux/errno.h>
20 #include <linux/if_ether.h>
21 #include <linux/kernel.h>
22 #include <linux/list.h>
23 #include <linux/netdevice.h>
24 #include <linux/skbuff.h>
25 #include <linux/spinlock.h>
26 #include <linux/string.h>
27 #include <linux/tty.h>
28 #include <linux/tty_ldisc.h>
29 #include <linux/version.h>
30 #include <linux/workqueue.h>
31
32 #include <uapi/linux/tty.h>
33
34 #include <linux/can.h>
35 #include <linux/can/dev.h>
36 #include <linux/can/error.h>
37 #include <linux/can/led.h>
38 #include <linux/can/rx-offload.h>
39
40 MODULE_ALIAS_LDISC(N_DEVELOPMENT);
41 MODULE_DESCRIPTION("ELM327 based CAN interface");
42 MODULE_LICENSE("GPL");
43 MODULE_AUTHOR("Max Staudt <max-linux@enpas.org>");
44
45 /* Line discipline ID number.
46  * N_DEVELOPMENT will likely be defined from Linux 5.18 onwards:
47  * https://git.kernel.org/pub/scm/linux/kernel/git/gregkh/tty.git/commit/?h=tty-next&id=c2faf737abfb10f88f2d2612d573e9edc3c42c37
48  */
49 #ifndef N_DEVELOPMENT
50 #define N_DEVELOPMENT 29
51 #endif
52
53 #define ELM327_NAPI_WEIGHT 4
54
55 #define ELM327_SIZE_RXBUF 256
56 #define ELM327_SIZE_TXBUF 32
57
58 #define ELM327_CAN_CONFIG_SEND_SFF           0x8000
59 #define ELM327_CAN_CONFIG_VARIABLE_DLC       0x4000
60 #define ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF  0x2000
61 #define ELM327_CAN_CONFIG_BAUDRATE_MULT_8_7  0x1000
62
63 #define ELM327_MAGIC_CHAR 'y'
64 #define ELM327_MAGIC_STRING "y"
65 #define ELM327_READY_CHAR '>'
66
67 /* Bits in elm->cmds_todo */
68 enum ELM_TODO {
69         TODO_CAN_DATA = 0,
70         TODO_CANID_11BIT,
71         TODO_CANID_29BIT_LOW,
72         TODO_CANID_29BIT_HIGH,
73         TODO_CAN_CONFIG_PART2,
74         TODO_CAN_CONFIG,
75         TODO_RESPONSES,
76         TODO_SILENT_MONITOR,
77         TODO_INIT
78 };
79
80 struct elmcan {
81         /* This must be the first member when using alloc_candev() */
82         struct can_priv can;
83
84         struct can_rx_offload offload;
85
86         /* TTY and netdev devices that we're bridging */
87         struct tty_struct       *tty;
88         struct net_device       *dev;
89
90         /* Per-channel lock */
91         spinlock_t              lock;
92
93         /* Keep track of how many things are using this struct.
94          * Once it reaches 0, we are in the process of cleaning up,
95          * and new operations will be cancelled immediately.
96          * Use atomic_t rather than refcount_t because we deliberately
97          * decrement to 0, and refcount_dec() spills a WARN_ONCE in
98          * that case.
99          */
100         atomic_t                refcount;
101
102         /* Stop the channel on hardware failure.
103          * Once this is true, nothing will be sent to the TTY.
104          */
105         bool                    hw_failure;
106
107         /* TTY TX helpers */
108         struct work_struct      tx_work;        /* Flushes TTY TX buffer   */
109         unsigned char           *txbuf;
110         unsigned char           *txhead;        /* Pointer to next TX byte */
111         int                     txleft;         /* Bytes left to TX */
112
113         /* TTY RX helpers */
114         unsigned char rxbuf[ELM327_SIZE_RXBUF];
115         int rxfill;
116
117         /* State machine */
118         enum {
119                 ELM_NOTINIT = 0,
120                 ELM_GETMAGICCHAR,
121                 ELM_GETPROMPT,
122                 ELM_RECEIVING,
123         } state;
124
125         int drop_next_line;
126
127         /* The CAN frame and config the ELM327 is sending/using,
128          * or will send/use after finishing all cmds_todo
129          */
130         struct can_frame can_frame;
131         unsigned short can_config;
132         unsigned long can_bitrate;
133         unsigned char can_bitrate_divisor;
134         int silent_monitoring;
135
136         /* Things we have yet to send */
137         char **next_init_cmd;
138         unsigned long cmds_todo;
139 };
140
141 /* A lock for all tty->disc_data handled by this ldisc.
142  * This is to prevent a case where tty->disc_data is set to NULL,
143  * yet someone is still trying to dereference it.
144  * Without this, we cannot do a clean shutdown.
145  */
146 static DEFINE_SPINLOCK(elmcan_discdata_lock);
147
148 static inline void elm327_hw_failure(struct elmcan *elm);
149
150 /* Assumes elm->lock taken. */
151 static void elm327_send(struct elmcan *elm, const void *buf, size_t len)
152 {
153         int actual;
154
155         if (elm->hw_failure)
156                 return;
157
158         memcpy(elm->txbuf, buf, len);
159
160         /* Order of next two lines is *very* important.
161          * When we are sending a little amount of data,
162          * the transfer may be completed inside the ops->write()
163          * routine, because it's running with interrupts enabled.
164          * In this case we *never* got WRITE_WAKEUP event,
165          * if we did not request it before write operation.
166          *       14 Oct 1994  Dmitry Gorodchanin.
167          */
168         set_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
169         actual = elm->tty->ops->write(elm->tty, elm->txbuf, len);
170         if (actual < 0) {
171                 netdev_err(elm->dev,
172                            "Failed to write to tty %s.\n",
173                            elm->tty->name);
174                 elm327_hw_failure(elm);
175                 return;
176         }
177
178         elm->txleft = len - actual;
179         elm->txhead = elm->txbuf + actual;
180 }
181
182 /* Take the ELM327 out of almost any state and back into command mode.
183  * We send ELM327_MAGIC_CHAR which will either abort any running
184  * operation, or be echoed back to us in case we're already in command
185  * mode.
186  *
187  * Assumes elm->lock taken.
188  */
189 static void elm327_kick_into_cmd_mode(struct elmcan *elm)
190 {
191         if (elm->state != ELM_GETMAGICCHAR && elm->state != ELM_GETPROMPT) {
192                 elm327_send(elm, ELM327_MAGIC_STRING, 1);
193
194                 elm->state = ELM_GETMAGICCHAR;
195         }
196 }
197
198 /* Schedule a CAN frame and necessary config changes to be sent to the TTY.
199  *
200  * Assumes elm->lock taken.
201  */
202 static void elm327_send_frame(struct elmcan *elm, struct can_frame *frame)
203 {
204         /* Schedule any necessary changes in ELM327's CAN configuration */
205         if (elm->can_frame.can_id != frame->can_id) {
206                 /* Set the new CAN ID for transmission. */
207                 if ((frame->can_id & CAN_EFF_FLAG)
208                     ^ (elm->can_frame.can_id & CAN_EFF_FLAG)) {
209                         elm->can_config = (frame->can_id & CAN_EFF_FLAG
210                                                 ? 0
211                                                 : ELM327_CAN_CONFIG_SEND_SFF)
212                                         | ELM327_CAN_CONFIG_VARIABLE_DLC
213                                         | ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF
214                                         | elm->can_bitrate_divisor;
215
216                         set_bit(TODO_CAN_CONFIG, &elm->cmds_todo);
217                 }
218
219                 if (frame->can_id & CAN_EFF_FLAG) {
220                         clear_bit(TODO_CANID_11BIT, &elm->cmds_todo);
221                         set_bit(TODO_CANID_29BIT_LOW, &elm->cmds_todo);
222                         set_bit(TODO_CANID_29BIT_HIGH, &elm->cmds_todo);
223                 } else {
224                         set_bit(TODO_CANID_11BIT, &elm->cmds_todo);
225                         clear_bit(TODO_CANID_29BIT_LOW, &elm->cmds_todo);
226                         clear_bit(TODO_CANID_29BIT_HIGH, &elm->cmds_todo);
227                 }
228         }
229
230         /* Schedule the CAN frame itself. */
231         elm->can_frame = *frame;
232         set_bit(TODO_CAN_DATA, &elm->cmds_todo);
233
234         elm327_kick_into_cmd_mode(elm);
235 }
236
237 /* ELM327 initialization sequence.
238  *
239  * Assumes elm->lock taken.
240  */
241 static char *elm327_init_script[] = {
242         "AT WS\r",        /* v1.0: Warm Start */
243         "AT PP FF OFF\r", /* v1.0: All Programmable Parameters Off */
244         "AT M0\r",        /* v1.0: Memory Off */
245         "AT AL\r",        /* v1.0: Allow Long messages */
246         "AT BI\r",        /* v1.0: Bypass Initialization */
247         "AT CAF0\r",      /* v1.0: CAN Auto Formatting Off */
248         "AT CFC0\r",      /* v1.0: CAN Flow Control Off */
249         "AT CF 000\r",    /* v1.0: Reset CAN ID Filter */
250         "AT CM 000\r",    /* v1.0: Reset CAN ID Mask */
251         "AT E1\r",        /* v1.0: Echo On */
252         "AT H1\r",        /* v1.0: Headers On */
253         "AT L0\r",        /* v1.0: Linefeeds Off */
254         "AT SH 7DF\r",    /* v1.0: Set CAN sending ID to 0x7df */
255         "AT ST FF\r",     /* v1.0: Set maximum Timeout for response after TX */
256         "AT AT0\r",       /* v1.2: Adaptive Timing Off */
257         "AT D1\r",        /* v1.3: Print DLC On */
258         "AT S1\r",        /* v1.3: Spaces On */
259         "AT TP B\r",      /* v1.0: Try Protocol B */
260         NULL
261 };
262
263 static void elm327_init(struct elmcan *elm)
264 {
265         elm->state = ELM_NOTINIT;
266         elm->can_frame.can_id = 0x7df;
267         elm->rxfill = 0;
268         elm->drop_next_line = 0;
269
270         /* We can only set the bitrate as a fraction of 500000.
271          * The bit timing constants in elmcan_bittiming_const will
272          * limit the user to the right values.
273          */
274         elm->can_bitrate_divisor = 500000 / elm->can.bittiming.bitrate;
275         elm->can_config = ELM327_CAN_CONFIG_SEND_SFF
276                         | ELM327_CAN_CONFIG_VARIABLE_DLC
277                         | ELM327_CAN_CONFIG_RECV_BOTH_SFF_EFF
278                         | elm->can_bitrate_divisor;
279
280         /* Configure ELM327 and then start monitoring */
281         elm->next_init_cmd = &elm327_init_script[0];
282         set_bit(TODO_INIT, &elm->cmds_todo);
283         set_bit(TODO_SILENT_MONITOR, &elm->cmds_todo);
284         set_bit(TODO_RESPONSES, &elm->cmds_todo);
285         set_bit(TODO_CAN_CONFIG, &elm->cmds_todo);
286
287         elm327_kick_into_cmd_mode(elm);
288 }
289
290 /* Assumes elm->lock taken. */
291 static void elm327_feed_frame_to_netdev(struct elmcan *elm,
292                                         const struct can_frame *frame)
293 {
294         struct can_frame *cf;
295         struct sk_buff *skb;
296
297         if (!netif_running(elm->dev))
298                 return;
299
300         skb = alloc_can_skb(elm->dev, &cf);
301
302         if (!skb)
303                 return;
304
305         memcpy(cf, frame, sizeof(struct can_frame));
306
307         /* Queue for NAPI pickup.
308          * rx-offload will update stats and LEDs for us.
309          */
310         if (can_rx_offload_queue_tail(&elm->offload, skb))
311                 elm->dev->stats.rx_fifo_errors++;
312
313 #if LINUX_VERSION_CODE >= KERNEL_VERSION(5,15,0)
314         /* Wake NAPI */
315         can_rx_offload_irq_finish(&elm->offload);
316 #endif
317 }
318
319 /* Called when we're out of ideas and just want it all to end.
320  * Assumes elm->lock taken.
321  */
322 static inline void elm327_hw_failure(struct elmcan *elm)
323 {
324         struct can_frame frame;
325
326         memset(&frame, 0, sizeof(frame));
327         frame.can_id = CAN_ERR_FLAG;
328         frame.can_dlc = CAN_ERR_DLC;
329         frame.data[5] = 'R';
330         frame.data[6] = 'I';
331         frame.data[7] = 'P';
332         elm327_feed_frame_to_netdev(elm, &frame);
333
334         netdev_err(elm->dev, "ELM327 misbehaved. Blocking further communication.\n");
335
336         elm->hw_failure = true;
337         can_bus_off(elm->dev);
338 }
339
340 /* Compare a buffer to a fixed string */
341 static int _memstrcmp(const u8 *mem, const char *str)
342 {
343         return memcmp(mem, str, strlen(str));
344 }
345
346 /* Assumes elm->lock taken. */
347 static void elm327_parse_error(struct elmcan *elm, int len)
348 {
349         struct can_frame frame;
350
351         memset(&frame, 0, sizeof(frame));
352         frame.can_id = CAN_ERR_FLAG;
353         frame.can_dlc = CAN_ERR_DLC;
354
355         /* Filter possible error messages based on length of RX'd line */
356         switch (len) {
357         case 17:
358                 if (!_memstrcmp(elm->rxbuf, "UNABLE TO CONNECT")) {
359                         netdev_err(elm->dev,
360                                    "ELM327 reported UNABLE TO CONNECT. Please check your setup.\n");
361                 }
362                 break;
363         case 11:
364                 if (!_memstrcmp(elm->rxbuf, "BUFFER FULL")) {
365                         /* This case will only happen if the last data
366                          * line was complete.
367                          * Otherwise, elm327_parse_frame() will heuristically
368                          * emit this error frame instead.
369                          */
370                         frame.can_id |= CAN_ERR_CRTL;
371                         frame.data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
372                 }
373                 break;
374         case 9:
375                 if (!_memstrcmp(elm->rxbuf, "BUS ERROR"))
376                         frame.can_id |= CAN_ERR_BUSERROR;
377                 if (!_memstrcmp(elm->rxbuf, "CAN ERROR"))
378                         frame.can_id |= CAN_ERR_PROT;
379                 if (!_memstrcmp(elm->rxbuf, "<RX ERROR"))
380                         frame.can_id |= CAN_ERR_PROT;
381                 break;
382         case 8:
383                 if (!_memstrcmp(elm->rxbuf, "BUS BUSY")) {
384                         frame.can_id |= CAN_ERR_PROT;
385                         frame.data[2] = CAN_ERR_PROT_OVERLOAD;
386                 }
387                 if (!_memstrcmp(elm->rxbuf, "FB ERROR")) {
388                         frame.can_id |= CAN_ERR_PROT;
389                         frame.data[2] = CAN_ERR_PROT_TX;
390                 }
391                 break;
392         case 5: /* ERR is followed by two digits, hence line length 5 */
393                 if (!_memstrcmp(elm->rxbuf, "ERR")) {
394                         netdev_err(elm->dev, "ELM327 reported an ERR%c%c. Please power it off and on again.\n",
395                                    elm->rxbuf[3], elm->rxbuf[4]);
396                         frame.can_id |= CAN_ERR_CRTL;
397                 }
398                 break;
399         default:
400                 /* Something else has happened.
401                  * Maybe garbage on the UART line.
402                  * Emit a generic error frame.
403                  */
404                 break;
405         }
406
407         elm327_feed_frame_to_netdev(elm, &frame);
408 }
409
410 /* Parse CAN frames coming as ASCII from ELM327.
411  * They can be of various formats:
412  *
413  * 29-bit ID (EFF):  12 34 56 78 D PL PL PL PL PL PL PL PL
414  * 11-bit ID (!EFF): 123 D PL PL PL PL PL PL PL PL
415  *
416  * where D = DLC, PL = payload byte
417  *
418  * Instead of a payload, RTR indicates a remote request.
419  *
420  * We will use the spaces and line length to guess the format.
421  *
422  * Assumes elm->lock taken.
423  */
424 static int elm327_parse_frame(struct elmcan *elm, int len)
425 {
426         struct can_frame frame;
427         int hexlen;
428         int datastart;
429         int i;
430
431         memset(&frame, 0, sizeof(frame));
432
433         /* Find first non-hex and non-space character:
434          *  - In the simplest case, there is none.
435          *  - For RTR frames, 'R' is the first non-hex character.
436          *  - An error message may replace the end of the data line.
437          */
438         for (hexlen = 0; hexlen <= len; hexlen++) {
439                 if (hex_to_bin(elm->rxbuf[hexlen]) < 0 &&
440                     elm->rxbuf[hexlen] != ' ') {
441                         break;
442                 }
443         }
444
445         /* Sanity check whether the line is really a clean hexdump,
446          * or terminated by an error message, or contains garbage.
447          */
448         if (hexlen < len &&
449             !isdigit(elm->rxbuf[hexlen]) &&
450             !isupper(elm->rxbuf[hexlen]) &&
451             '<' != elm->rxbuf[hexlen] &&
452             ' ' != elm->rxbuf[hexlen]) {
453                 /* The line is likely garbled anyway, so bail.
454                  * The main code will restart listening.
455                  */
456                 return -ENODATA;
457         }
458
459         /* Use spaces in CAN ID to distinguish 29 or 11 bit address length.
460          * No out-of-bounds access:
461          * We use the fact that we can always read from elm->rxbuf.
462          */
463         if (elm->rxbuf[2] == ' ' && elm->rxbuf[5] == ' ' &&
464             elm->rxbuf[8] == ' ' && elm->rxbuf[11] == ' ' &&
465             elm->rxbuf[13] == ' ') {
466                 frame.can_id = CAN_EFF_FLAG;
467                 datastart = 14;
468         } else if (elm->rxbuf[3] == ' ' && elm->rxbuf[5] == ' ') {
469                 frame.can_id = 0;
470                 datastart = 6;
471         } else {
472                 /* This is not a well-formatted data line.
473                  * Assume it's an error message.
474                  */
475                 return -ENODATA;
476         }
477
478         if (hexlen < datastart) {
479                 /* The line is too short to be a valid frame hex dump.
480                  * Something interrupted the hex dump or it is invalid.
481                  */
482                 return -ENODATA;
483         }
484
485         /* From here on all chars up to buf[hexlen] are hex or spaces,
486          * at well-defined offsets.
487          */
488
489         /* Read CAN data length */
490         frame.can_dlc = (hex_to_bin(elm->rxbuf[datastart - 2]) << 0);
491
492         /* Read CAN ID */
493         if (frame.can_id & CAN_EFF_FLAG) {
494                 frame.can_id |= (hex_to_bin(elm->rxbuf[0]) << 28)
495                               | (hex_to_bin(elm->rxbuf[1]) << 24)
496                               | (hex_to_bin(elm->rxbuf[3]) << 20)
497                               | (hex_to_bin(elm->rxbuf[4]) << 16)
498                               | (hex_to_bin(elm->rxbuf[6]) << 12)
499                               | (hex_to_bin(elm->rxbuf[7]) << 8)
500                               | (hex_to_bin(elm->rxbuf[9]) << 4)
501                               | (hex_to_bin(elm->rxbuf[10]) << 0);
502         } else {
503                 frame.can_id |= (hex_to_bin(elm->rxbuf[0]) << 8)
504                               | (hex_to_bin(elm->rxbuf[1]) << 4)
505                               | (hex_to_bin(elm->rxbuf[2]) << 0);
506         }
507
508         /* Check for RTR frame */
509         if (elm->rxfill >= hexlen + 3 &&
510             !_memstrcmp(&elm->rxbuf[hexlen], "RTR")) {
511                 frame.can_id |= CAN_RTR_FLAG;
512         }
513
514         /* Is the line long enough to hold the advertised payload?
515          * Note: RTR frames have a DLC, but no actual payload.
516          */
517         if (!(frame.can_id & CAN_RTR_FLAG) &&
518             (hexlen < frame.can_dlc * 3 + datastart)) {
519                 /* Incomplete frame. */
520
521                 /* Probably the ELM327's RS232 TX buffer was full.
522                  * Emit an error frame and exit.
523                  */
524                 frame.can_id = CAN_ERR_FLAG | CAN_ERR_CRTL;
525                 frame.can_dlc = CAN_ERR_DLC;
526                 frame.data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
527                 elm327_feed_frame_to_netdev(elm, &frame);
528
529                 /* Signal failure to parse.
530                  * The line will be re-parsed as an error line, which will fail.
531                  * However, this will correctly drop the state machine back into
532                  * command mode.
533                  */
534                 return -ENODATA;
535         }
536
537         /* Parse the data nibbles. */
538         for (i = 0; i < frame.can_dlc; i++) {
539                 frame.data[i] = (hex_to_bin(elm->rxbuf[datastart + 3*i]) << 4)
540                               | (hex_to_bin(elm->rxbuf[datastart + 3*i + 1]));
541         }
542
543         /* Feed the frame to the network layer. */
544         elm327_feed_frame_to_netdev(elm, &frame);
545
546         return 0;
547 }
548
549 /* Assumes elm->lock taken. */
550 static void elm327_parse_line(struct elmcan *elm, int len)
551 {
552         /* Skip empty lines */
553         if (!len)
554                 return;
555
556         /* Skip echo lines */
557         if (elm->drop_next_line) {
558                 elm->drop_next_line = 0;
559                 return;
560         } else if (!_memstrcmp(elm->rxbuf, "AT")) {
561                 return;
562         }
563
564         /* Regular parsing */
565         switch (elm->state) {
566         case ELM_RECEIVING:
567                 if (elm327_parse_frame(elm, len)) {
568                         /* Parse an error line. */
569                         elm327_parse_error(elm, len);
570
571                         /* Start afresh. */
572                         elm327_kick_into_cmd_mode(elm);
573                 }
574                 break;
575         default:
576                 break;
577         }
578 }
579
580 /* Assumes elm->lock taken. */
581 static void elm327_handle_prompt(struct elmcan *elm)
582 {
583         struct can_frame *frame = &elm->can_frame;
584         char local_txbuf[20];
585
586         if (!elm->cmds_todo) {
587                 /* Enter CAN monitor mode */
588                 elm327_send(elm, "ATMA\r", 5);
589                 elm->state = ELM_RECEIVING;
590
591                 return;
592         }
593
594         /* Reconfigure ELM327 step by step as indicated by elm->cmds_todo */
595         if (test_bit(TODO_INIT, &elm->cmds_todo)) {
596                 strcpy(local_txbuf, *elm->next_init_cmd);
597
598                 elm->next_init_cmd++;
599                 if (!(*elm->next_init_cmd)) {
600                         clear_bit(TODO_INIT, &elm->cmds_todo);
601                         netdev_info(elm->dev, "Initialization finished.\n");
602                 }
603
604         } else if (test_and_clear_bit(TODO_SILENT_MONITOR, &elm->cmds_todo)) {
605                 sprintf(local_txbuf, "ATCSM%i\r",
606                         !(!(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY)));
607
608         } else if (test_and_clear_bit(TODO_RESPONSES, &elm->cmds_todo)) {
609                 sprintf(local_txbuf, "ATR%i\r",
610                         !(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY));
611
612         } else if (test_and_clear_bit(TODO_CAN_CONFIG, &elm->cmds_todo)) {
613                 sprintf(local_txbuf, "ATPC\r");
614                 set_bit(TODO_CAN_CONFIG_PART2, &elm->cmds_todo);
615
616         } else if (test_and_clear_bit(TODO_CAN_CONFIG_PART2, &elm->cmds_todo)) {
617                 sprintf(local_txbuf, "ATPB%04X\r",
618                         elm->can_config);
619
620         } else if (test_and_clear_bit(TODO_CANID_29BIT_HIGH, &elm->cmds_todo)) {
621                 sprintf(local_txbuf, "ATCP%02X\r",
622                         (frame->can_id & CAN_EFF_MASK) >> 24);
623
624         } else if (test_and_clear_bit(TODO_CANID_29BIT_LOW, &elm->cmds_todo)) {
625                 sprintf(local_txbuf, "ATSH%06X\r",
626                         frame->can_id & CAN_EFF_MASK & ((1 << 24) - 1));
627
628         } else if (test_and_clear_bit(TODO_CANID_11BIT, &elm->cmds_todo)) {
629                 sprintf(local_txbuf, "ATSH%03X\r",
630                         frame->can_id & CAN_SFF_MASK);
631
632         } else if (test_and_clear_bit(TODO_CAN_DATA, &elm->cmds_todo)) {
633                 if (frame->can_id & CAN_RTR_FLAG) {
634                         /* Send an RTR frame. Their DLC is fixed.
635                          * Some chips don't send them at all.
636                          */
637                         sprintf(local_txbuf, "ATRTR\r");
638                 } else {
639                         /* Send a regular CAN data frame */
640                         int i;
641
642                         for (i = 0; i < frame->can_dlc; i++) {
643                                 sprintf(&local_txbuf[2 * i], "%02X",
644                                         frame->data[i]);
645                         }
646
647                         sprintf(&local_txbuf[2 * i], "\r");
648                 }
649
650                 elm->drop_next_line = 1;
651                 elm->state = ELM_RECEIVING;
652         }
653
654         elm327_send(elm, local_txbuf, strlen(local_txbuf));
655 }
656
657 static bool elm327_is_ready_char(char c)
658 {
659         /* Bits 0xc0 are sometimes set (randomly), hence the mask.
660          * Probably bad hardware.
661          */
662         return (c & 0x3f) == ELM327_READY_CHAR;
663 }
664
665 /* Assumes elm->lock taken. */
666 static void elm327_drop_bytes(struct elmcan *elm, int i)
667 {
668         memmove(&elm->rxbuf[0], &elm->rxbuf[i], ELM327_SIZE_RXBUF - i);
669         elm->rxfill -= i;
670 }
671
672 /* Assumes elm->lock taken. */
673 static void elm327_parse_rxbuf(struct elmcan *elm)
674 {
675         int len;
676
677         switch (elm->state) {
678         case ELM_NOTINIT:
679                 elm->rxfill = 0;
680                 break;
681
682         case ELM_GETMAGICCHAR:
683         {
684                 /* Wait for 'y' or '>' */
685                 int i;
686
687                 for (i = 0; i < elm->rxfill; i++) {
688                         if (elm->rxbuf[i] == ELM327_MAGIC_CHAR) {
689                                 elm327_send(elm, "\r", 1);
690                                 elm->state = ELM_GETPROMPT;
691                                 i++;
692                                 break;
693                         } else if (elm327_is_ready_char(elm->rxbuf[i])) {
694                                 elm327_send(elm, ELM327_MAGIC_STRING, 1);
695                                 i++;
696                                 break;
697                         }
698                 }
699
700                 elm327_drop_bytes(elm, i);
701
702                 break;
703         }
704
705         case ELM_GETPROMPT:
706                 /* Wait for '>' */
707                 if (elm327_is_ready_char(elm->rxbuf[elm->rxfill - 1]))
708                         elm327_handle_prompt(elm);
709
710                 elm->rxfill = 0;
711                 break;
712
713         case ELM_RECEIVING:
714                 /* Find <CR> delimiting feedback lines. */
715                 for (len = 0;
716                      (len < elm->rxfill) && (elm->rxbuf[len] != '\r');
717                      len++) {
718                         /* empty loop */
719                 }
720
721                 if (len == ELM327_SIZE_RXBUF) {
722                         /* Line exceeds buffer. It's probably all garbage.
723                          * Did we even connect at the right baud rate?
724                          */
725                         netdev_err(elm->dev,
726                                    "RX buffer overflow. Faulty ELM327 or UART?\n");
727                         elm327_hw_failure(elm);
728                         break;
729                 } else if (len == elm->rxfill) {
730                         if (elm327_is_ready_char(elm->rxbuf[elm->rxfill - 1])) {
731                                 /* The ELM327's AT ST response timeout ran out,
732                                  * so we got a prompt.
733                                  * Clear RX buffer and restart listening.
734                                  */
735                                 elm->rxfill = 0;
736
737                                 elm327_handle_prompt(elm);
738                                 break;
739                         }
740
741                         /* No <CR> found - we haven't received a full line yet.
742                          * Wait for more data.
743                          */
744                         break;
745                 }
746
747                 /* We have a full line to parse. */
748                 elm327_parse_line(elm, len);
749
750                 /* Remove parsed data from RX buffer. */
751                 elm327_drop_bytes(elm, len + 1);
752
753                 /* More data to parse? */
754                 if (elm->rxfill)
755                         elm327_parse_rxbuf(elm);
756         }
757 }
758
759 /* Dummy needed to use can_rx_offload */
760 static struct sk_buff *elmcan_mailbox_read(struct can_rx_offload *offload,
761                                            unsigned int n, u32 *timestamp,
762                                            bool drop)
763 {
764         WARN_ON_ONCE(1); /* This function is a dummy, so don't call it! */
765
766         return ERR_PTR(-ENOBUFS);
767 }
768
769 static int elmcan_netdev_open(struct net_device *dev)
770 {
771         struct elmcan *elm = netdev_priv(dev);
772         int err;
773
774         spin_lock_bh(&elm->lock);
775         if (elm->hw_failure) {
776                 netdev_err(elm->dev, "Refusing to open interface after a hardware fault has been detected.\n");
777                 spin_unlock_bh(&elm->lock);
778                 return -EIO;
779         }
780
781         if (!elm->tty) {
782                 spin_unlock_bh(&elm->lock);
783                 return -ENODEV;
784         }
785
786         /* open_candev() checks for elm->can.bittiming.bitrate != 0 */
787         err = open_candev(dev);
788         if (err) {
789                 spin_unlock_bh(&elm->lock);
790                 return err;
791         }
792
793         elm327_init(elm);
794         spin_unlock_bh(&elm->lock);
795
796         elm->offload.mailbox_read = elmcan_mailbox_read;
797         err = can_rx_offload_add_fifo(dev, &elm->offload, ELM327_NAPI_WEIGHT);
798         if (err) {
799                 close_candev(dev);
800                 return err;
801         }
802
803         can_rx_offload_enable(&elm->offload);
804
805         can_led_event(dev, CAN_LED_EVENT_OPEN);
806         elm->can.state = CAN_STATE_ERROR_ACTIVE;
807         netif_start_queue(dev);
808
809         return 0;
810 }
811
812 static int elmcan_netdev_close(struct net_device *dev)
813 {
814         struct elmcan *elm = netdev_priv(dev);
815
816         netif_stop_queue(dev);
817
818         spin_lock_bh(&elm->lock);
819         if (elm->tty) {
820                 /* Interrupt whatever we're doing right now */
821                 elm327_send(elm, ELM327_MAGIC_STRING, 1);
822
823                 /* Clear the wakeup bit, as the netdev will be down and thus
824                  * the wakeup handler won't clear it
825                  */
826                 clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
827
828                 spin_unlock_bh(&elm->lock);
829
830                 flush_work(&elm->tx_work);
831         } else {
832                 spin_unlock_bh(&elm->lock);
833         }
834
835         can_rx_offload_disable(&elm->offload);
836         elm->can.state = CAN_STATE_STOPPED;
837         can_rx_offload_del(&elm->offload);
838         close_candev(dev);
839         can_led_event(dev, CAN_LED_EVENT_STOP);
840
841         return 0;
842 }
843
844 /* Send a can_frame to a TTY. */
845 static netdev_tx_t elmcan_netdev_start_xmit(struct sk_buff *skb,
846                                             struct net_device *dev)
847 {
848         struct elmcan *elm = netdev_priv(dev);
849         struct can_frame *frame = (struct can_frame *)skb->data;
850
851         if (skb->len != sizeof(struct can_frame))
852                 goto out;
853
854         if (!netif_running(dev))  {
855                 netdev_warn(elm->dev, "xmit: iface is down.\n");
856                 goto out;
857         }
858
859         /* BHs are already disabled, so no spin_lock_bh().
860          * See Documentation/networking/netdevices.txt
861          */
862         spin_lock(&elm->lock);
863
864         /* We shouldn't get here after a hardware fault:
865          * can_bus_off() calls netif_carrier_off()
866          */
867         WARN_ON_ONCE(elm->hw_failure);
868
869         if (!elm->tty ||
870             elm->hw_failure ||
871             elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY) {
872                 spin_unlock(&elm->lock);
873                 goto out;
874         }
875
876         netif_stop_queue(dev);
877
878         elm327_send_frame(elm, frame);
879         spin_unlock(&elm->lock);
880
881         dev->stats.tx_packets++;
882         dev->stats.tx_bytes += frame->can_dlc;
883
884         can_led_event(dev, CAN_LED_EVENT_TX);
885
886 out:
887         kfree_skb(skb);
888         return NETDEV_TX_OK;
889 }
890
891 static const struct net_device_ops elmcan_netdev_ops = {
892         .ndo_open       = elmcan_netdev_open,
893         .ndo_stop       = elmcan_netdev_close,
894         .ndo_start_xmit = elmcan_netdev_start_xmit,
895         .ndo_change_mtu = can_change_mtu,
896 };
897
898 /* Get a reference to our struct, taking into account locks/refcounts.
899  * This is to ensure ordering in case we are shutting down, and to ensure
900  * there is a refcount at all (otherwise tty->disc_data may be freed and
901  * before we increment the refcount).
902  * Use this for anything that can race against elmcan_ldisc_close().
903  */
904 static struct elmcan *get_elm(struct tty_struct *tty)
905 {
906         struct elmcan *elm;
907         bool got_ref;
908
909         spin_lock_bh(&elmcan_discdata_lock);
910         elm = (struct elmcan *)tty->disc_data;
911
912         if (!elm) {
913                 spin_unlock_bh(&elmcan_discdata_lock);
914                 return NULL;
915         }
916
917         got_ref = atomic_inc_not_zero(&elm->refcount);
918         spin_unlock_bh(&elmcan_discdata_lock);
919
920         if (!got_ref)
921                 return NULL;
922
923         return elm;
924 }
925
926 static void put_elm(struct elmcan *elm)
927 {
928         atomic_dec(&elm->refcount);
929 }
930
931 static bool elmcan_is_valid_rx_char(char c)
932 {
933         return (isdigit(c) ||
934                 isupper(c) ||
935                 c == ELM327_MAGIC_CHAR ||
936                 c == ELM327_READY_CHAR ||
937                 c == '<' ||
938                 c == 'a' ||
939                 c == 'b' ||
940                 c == 'v' ||
941                 c == '.' ||
942                 c == '?' ||
943                 c == '\r' ||
944                 c == ' ');
945 }
946
947 /* Handle incoming ELM327 ASCII data.
948  * This will not be re-entered while running, but other ldisc
949  * functions may be called in parallel.
950  */
951 #if LINUX_VERSION_CODE < KERNEL_VERSION(5,14,0)
952 static void elmcan_ldisc_rx(struct tty_struct *tty,
953                             const unsigned char *cp, char *fp, int count)
954 #else
955 static void elmcan_ldisc_rx(struct tty_struct *tty,
956                             const unsigned char *cp, const char *fp, int count)
957 #endif
958 {
959         struct elmcan *elm = get_elm(tty);
960
961         if (!elm)
962                 return;
963
964         spin_lock_bh(&elm->lock);
965
966         if (elm->hw_failure)
967                 goto out;
968
969         while (count-- && elm->rxfill < ELM327_SIZE_RXBUF) {
970                 if (fp && *fp++) {
971                         netdev_err(elm->dev, "Error in received character stream. Check your wiring.");
972
973                         elm327_hw_failure(elm);
974
975                         goto out;
976                 }
977
978                 /* Ignore NUL characters, which the PIC microcontroller may
979                  * inadvertently insert due to a known hardware bug.
980                  * See ELM327 documentation, which refers to a Microchip PIC
981                  * bug description.
982                  */
983                 if (*cp != 0) {
984                         /* Check for stray characters on the UART line.
985                          * Likely caused by bad hardware.
986                          */
987                         if (!elmcan_is_valid_rx_char(*cp)) {
988                                 netdev_err(elm->dev,
989                                            "Received illegal character %02x.\n",
990                                            *cp);
991                                 elm327_hw_failure(elm);
992
993                                 goto out;
994                         }
995
996                         elm->rxbuf[elm->rxfill++] = *cp;
997                 }
998
999                 cp++;
1000         }
1001
1002         if (count >= 0) {
1003                 netdev_err(elm->dev, "Receive buffer overflowed. Bad chip or wiring?");
1004
1005                 elm327_hw_failure(elm);
1006
1007                 goto out;
1008         }
1009
1010         elm327_parse_rxbuf(elm);
1011
1012 out:
1013         spin_unlock_bh(&elm->lock);
1014         put_elm(elm);
1015 }
1016
1017 /* Write out remaining transmit buffer.
1018  * Scheduled when TTY is writable.
1019  */
1020 static void elmcan_ldisc_tx_worker(struct work_struct *work)
1021 {
1022         /* No need to use get_elm() here, as we'll always flush workers
1023          * before destroying the elmcan object.
1024          */
1025         struct elmcan *elm = container_of(work, struct elmcan, tx_work);
1026         ssize_t actual;
1027
1028         spin_lock_bh(&elm->lock);
1029         if (elm->hw_failure) {
1030                 spin_unlock_bh(&elm->lock);
1031                 return;
1032         }
1033
1034         if (!elm->tty || !netif_running(elm->dev)) {
1035                 spin_unlock_bh(&elm->lock);
1036                 return;
1037         }
1038
1039         if (elm->txleft <= 0)  {
1040                 /* Our TTY write buffer is empty:
1041                  * Allow netdev to hand us another packet
1042                  */
1043                 clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
1044                 spin_unlock_bh(&elm->lock);
1045                 netif_wake_queue(elm->dev);
1046                 return;
1047         }
1048
1049         actual = elm->tty->ops->write(elm->tty, elm->txhead, elm->txleft);
1050         if (actual < 0) {
1051                 netdev_err(elm->dev,
1052                            "Failed to write to tty %s.\n",
1053                            elm->tty->name);
1054                 elm327_hw_failure(elm);
1055                 spin_unlock_bh(&elm->lock);
1056                 return;
1057         }
1058
1059         elm->txleft -= actual;
1060         elm->txhead += actual;
1061         spin_unlock_bh(&elm->lock);
1062 }
1063
1064 /* Called by the driver when there's room for more data. */
1065 static void elmcan_ldisc_tx_wakeup(struct tty_struct *tty)
1066 {
1067         struct elmcan *elm = get_elm(tty);
1068
1069         if (!elm)
1070                 return;
1071
1072         schedule_work(&elm->tx_work);
1073
1074         put_elm(elm);
1075 }
1076
1077 /* ELM327 can only handle bitrates that are integer divisors of 500 kHz,
1078  * or 7/8 of that. Divisors are 1 to 64.
1079  * Currently we don't implement support for 7/8 rates.
1080  */
1081 static const u32 elmcan_bitrate_const[64] = {
1082          7812,  7936,  8064,  8196,  8333,  8474,  8620,  8771,
1083          8928,  9090,  9259,  9433,  9615,  9803, 10000, 10204,
1084         10416, 10638, 10869, 11111, 11363, 11627, 11904, 12195,
1085         12500, 12820, 13157, 13513, 13888, 14285, 14705, 15151,
1086         15625, 16129, 16666, 17241, 17857, 18518, 19230, 20000,
1087         20833, 21739, 22727, 23809, 25000, 26315, 27777, 29411,
1088         31250, 33333, 35714, 38461, 41666, 45454, 50000, 55555,
1089         62500, 71428, 83333, 100000, 125000, 166666, 250000, 500000
1090 };
1091
1092 /* Dummy needed to use bitrate_const */
1093 static int elmcan_do_set_bittiming(struct net_device *netdev)
1094 {
1095         return 0;
1096 }
1097
1098 static int elmcan_ldisc_open(struct tty_struct *tty)
1099 {
1100         struct net_device *dev;
1101         struct elmcan *elm;
1102         int err;
1103
1104         if (!capable(CAP_NET_ADMIN))
1105                 return -EPERM;
1106
1107         if (!tty->ops->write)
1108                 return -EOPNOTSUPP;
1109
1110         dev = alloc_candev(sizeof(struct elmcan), 0);
1111         if (!dev)
1112                 return -ENFILE;
1113         elm = netdev_priv(dev);
1114
1115         elm->txbuf = kmalloc(ELM327_SIZE_TXBUF, GFP_KERNEL);
1116         if (!elm->txbuf) {
1117                 err = -ENOMEM;
1118                 goto out_err;
1119         }
1120
1121         /* Configure TTY interface */
1122         tty->receive_room = 65536; /* We don't flow control */
1123         elm->txleft = 0; /* Clear TTY TX buffer */
1124         spin_lock_init(&elm->lock);
1125         atomic_set(&elm->refcount, 1);
1126         INIT_WORK(&elm->tx_work, elmcan_ldisc_tx_worker);
1127
1128         /* Configure CAN metadata */
1129         elm->can.state = CAN_STATE_STOPPED;
1130         elm->can.bitrate_const = elmcan_bitrate_const;
1131         elm->can.bitrate_const_cnt = ARRAY_SIZE(elmcan_bitrate_const);
1132         elm->can.do_set_bittiming = elmcan_do_set_bittiming;
1133         elm->can.ctrlmode_supported = CAN_CTRLMODE_LISTENONLY;
1134
1135         /* Configure netdev interface */
1136         elm->dev = dev;
1137         dev->netdev_ops = &elmcan_netdev_ops;
1138
1139         /* Mark ldisc channel as alive */
1140         elm->tty = tty;
1141         tty->disc_data = elm;
1142
1143         devm_can_led_init(elm->dev);
1144
1145         /* Let 'er rip */
1146         err = register_candev(elm->dev);
1147         if (err)
1148                 goto out_err;
1149
1150         netdev_info(elm->dev, "elmcan on %s.\n", tty->name);
1151
1152         return 0;
1153
1154 out_err:
1155         kfree(elm->txbuf);
1156         free_candev(elm->dev);
1157         return err;
1158 }
1159
1160 /* Close down an elmcan channel.
1161  * This means flushing out any pending queues, and then returning.
1162  * This call is serialized against other ldisc functions:
1163  * Once this is called, no other ldisc function of ours is entered.
1164  *
1165  * We also use this function for a hangup event.
1166  */
1167 static void elmcan_ldisc_close(struct tty_struct *tty)
1168 {
1169         struct elmcan *elm = get_elm(tty);
1170
1171         if (!elm)
1172                 return;
1173
1174         /* unregister_netdev() calls .ndo_stop() so we don't have to. */
1175         unregister_candev(elm->dev);
1176
1177         /* Decrease the refcount twice, once for our own get_elm(),
1178          * and once to remove the count of 1 that we set in _open().
1179          * Once it reaches 0, we can safely destroy it.
1180          */
1181         put_elm(elm);
1182         put_elm(elm);
1183
1184         while (atomic_read(&elm->refcount) > 0)
1185                 msleep_interruptible(10);
1186
1187         /* At this point, all ldisc calls to us have become no-ops. */
1188
1189         flush_work(&elm->tx_work);
1190
1191         /* Mark channel as dead */
1192         spin_lock_bh(&elm->lock);
1193         tty->disc_data = NULL;
1194         elm->tty = NULL;
1195         spin_unlock_bh(&elm->lock);
1196
1197         netdev_info(elm->dev, "elmcan off %s.\n", tty->name);
1198
1199         kfree(elm->txbuf);
1200         free_candev(elm->dev);
1201 }
1202
1203 #if LINUX_VERSION_CODE < KERNEL_VERSION(5,16,0)
1204 static int elmcan_ldisc_hangup(struct tty_struct *tty)
1205 #else
1206 static void elmcan_ldisc_hangup(struct tty_struct *tty)
1207 #endif
1208 {
1209         elmcan_ldisc_close(tty);
1210 #if LINUX_VERSION_CODE < KERNEL_VERSION(5,16,0)
1211         return 0;
1212 #endif
1213 }
1214
1215 static int elmcan_ldisc_ioctl(struct tty_struct *tty,
1216 #if LINUX_VERSION_CODE < KERNEL_VERSION(5,17,0)
1217                               struct file *file,
1218 #endif
1219                               unsigned int cmd, unsigned long arg)
1220 {
1221         struct elmcan *elm = get_elm(tty);
1222         unsigned int tmp;
1223
1224         if (!elm)
1225                 return -EINVAL;
1226
1227         switch (cmd) {
1228         case SIOCGIFNAME:
1229                 tmp = strnlen(elm->dev->name, IFNAMSIZ - 1) + 1;
1230                 if (copy_to_user((void __user *)arg, elm->dev->name, tmp)) {
1231                         put_elm(elm);
1232                         return -EFAULT;
1233                 }
1234
1235                 put_elm(elm);
1236                 return 0;
1237
1238         case SIOCSIFHWADDR:
1239                 put_elm(elm);
1240                 return -EINVAL;
1241
1242         default:
1243                 put_elm(elm);
1244 #if LINUX_VERSION_CODE < KERNEL_VERSION(5,16,0)
1245                 return tty_mode_ioctl(tty, file, cmd, arg);
1246 #else
1247                 return tty_mode_ioctl(tty, cmd, arg);
1248 #endif
1249         }
1250 }
1251
1252 static struct tty_ldisc_ops elmcan_ldisc = {
1253         .owner          = THIS_MODULE,
1254         .name           = "elmcan",
1255         .num            = N_DEVELOPMENT,
1256         .receive_buf    = elmcan_ldisc_rx,
1257         .write_wakeup   = elmcan_ldisc_tx_wakeup,
1258         .open           = elmcan_ldisc_open,
1259         .close          = elmcan_ldisc_close,
1260         .hangup         = elmcan_ldisc_hangup,
1261         .ioctl          = elmcan_ldisc_ioctl,
1262 };
1263
1264 static int __init elmcan_init(void)
1265 {
1266         int status;
1267
1268 #if LINUX_VERSION_CODE < KERNEL_VERSION(5,14,0)
1269         status = tty_register_ldisc(N_DEVELOPMENT, &elmcan_ldisc);
1270 #else
1271         status = tty_register_ldisc(&elmcan_ldisc);
1272 #endif
1273         if (status)
1274                 pr_err("Can't register line discipline\n");
1275
1276         return status;
1277 }
1278
1279 static void __exit elmcan_exit(void)
1280 {
1281         /* This will only be called when all channels have been closed by
1282          * userspace - tty_ldisc.c takes care of the module's refcount.
1283          */
1284 #if LINUX_VERSION_CODE < KERNEL_VERSION(5,14,0)
1285         int status;
1286
1287         status = tty_unregister_ldisc(N_DEVELOPMENT);
1288         if (status)
1289                 pr_err("Can't unregister line discipline (error: %d)\n",
1290                        status);
1291 #else
1292         tty_unregister_ldisc(&elmcan_ldisc);
1293 #endif
1294 }
1295
1296 module_init(elmcan_init);
1297 module_exit(elmcan_exit);