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