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