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