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