0ff9cff132e85c8e58e1227fb02a40c5eb0dd249
[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 <max-linux@enpas.org>
8  * slcan.c Author  : Oliver Hartkopp <socketcan@hartkopp.net>
9  * slip.c Authors  : Laurence Culhane <loz@holmes.demon.co.uk>
10  *                   Fred N. van Kempen <waltje@uwalt.nl.mugnet.org>
11  *
12  * 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         /* Bits 0xc0 are sometimes set (randomly), hence the mask.
377          * Probably bad hardware.
378          */
379         return (c & 0x3f) == ELM327_READY_CHAR;
380 }
381
382
383 static void elm327_parse_error(struct elmcan *elm, int len)
384 {
385         struct can_frame frame;
386
387         memset(&frame, 0, sizeof(frame));
388         frame.can_id = CAN_ERR_FLAG;
389         frame.can_dlc = CAN_ERR_DLC;
390
391         switch(len) {
392                 case 17:
393                         if (!memcmp(elm->rxbuf, "UNABLE TO CONNECT", 17)) {
394                                 netdev_err(elm->dev, "The ELM327 reported UNABLE TO CONNECT. Please check your setup.\n");
395                         }
396                         break;
397                 case 11:
398                         if (!memcmp(elm->rxbuf, "BUFFER FULL", 11)) {
399                                 /* This case will only happen if the last data
400                                  * line was complete.
401                                  * Otherwise, elm327_parse_frame() will emit the
402                                  * error frame instead.
403                                  */
404                                 frame.can_id |= CAN_ERR_CRTL;
405                                 frame.data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
406                         }
407                         break;
408                 case 9:
409                         if (!memcmp(elm->rxbuf, "BUS ERROR", 9)) {
410                                 frame.can_id |= CAN_ERR_BUSERROR;
411                         }
412                         if (!memcmp(elm->rxbuf, "CAN ERROR", 9)
413                                 || !memcmp(elm->rxbuf, "<RX ERROR", 9)) {
414                                 frame.can_id |= CAN_ERR_PROT;
415                         }
416                         break;
417                 case 8:
418                         if (!memcmp(elm->rxbuf, "BUS BUSY", 8)) {
419                                 frame.can_id |= CAN_ERR_PROT;
420                                 frame.data[2] = CAN_ERR_PROT_OVERLOAD;
421                         }
422                         if (!memcmp(elm->rxbuf, "FB ERROR", 8)) {
423                                 frame.can_id |= CAN_ERR_PROT;
424                                 frame.data[2] = CAN_ERR_PROT_TX;
425                         }
426                         break;
427                 case 5:
428                         if (!memcmp(elm->rxbuf, "ERR", 3)) {
429                                 netdev_err(elm->dev, "The ELM327 reported an ERR%c%c. Please power it off and on again.\n",
430                                         elm->rxbuf[3], elm->rxbuf[4]);
431                                 frame.can_id |= CAN_ERR_CRTL;
432                         }
433                         break;
434                 default:
435                         /* Don't emit an error frame if we're unsure */
436                         return;
437         }
438
439         elm327_feed_frame_to_netdev(elm, &frame);
440 }
441
442
443 static int elm327_parse_frame(struct elmcan *elm, int len)
444 {
445         struct can_frame frame;
446         int hexlen;
447         int datastart;
448         int i;
449
450         memset(&frame, 0, sizeof(frame));
451
452         /* Find first non-hex and non-space character:
453          *  - In the simplest case, there is none.
454          *  - For RTR frames, 'R' is the first non-hex character.
455          *  - An error message may replace the end of the data line.
456          */
457         for (hexlen = 0; hexlen <= len; hexlen++) {
458                 if (hex_to_bin(elm->rxbuf[hexlen]) < 0
459                     && elm->rxbuf[hexlen] != ' ') {
460                         break;
461                 }
462         }
463
464         /* If we accept stray characters coming in:
465          * Check for stray characters on a payload line.
466          * No idea what causes this.
467          */
468         if (accept_flaky_uart
469             && hexlen < len
470             && !isdigit(elm->rxbuf[hexlen])
471             && !isupper(elm->rxbuf[hexlen])
472             && '<' != elm->rxbuf[hexlen]
473             && ' ' != elm->rxbuf[hexlen]) {
474                 /* The line is likely garbled anyway, so bail.
475                  * The main code will restart listening.
476                  */
477                 elm327_kick_into_cmd_mode(elm);
478                 return 3;
479         }
480
481         /* Use spaces in CAN ID to distinguish 29 or 11 bit address length.
482          * No out-of-bounds access:
483          * We use the fact that we can always read from elm->rxbuf.
484          */
485         if (elm->rxbuf[2] == ' ' && elm->rxbuf[5] == ' '
486                 && elm->rxbuf[8] == ' ' && elm->rxbuf[11] == ' '
487                 && elm->rxbuf[13] == ' ') {
488                 frame.can_id = CAN_EFF_FLAG;
489                 datastart = 14;
490         } else if (elm->rxbuf[3] == ' ' && elm->rxbuf[5] == ' ') {
491                 frame.can_id = 0;
492                 datastart = 6;
493         } else {
494                 /* This is not a well-formatted data line.
495                  * Assume it's an error message.
496                  */
497                 return 1;
498         }
499
500         if (hexlen < datastart) {
501                 /* The line is too short to be a valid frame hex dump.
502                  * Something interrupted the hex dump or it is invalid.
503                  */
504                 return 1;
505         }
506
507         /* From here on all chars up to buf[hexlen] are hex or spaces,
508          * at well-defined offsets.
509          */
510
511         /* Read CAN data length */
512         frame.can_dlc = (hex_to_bin(elm->rxbuf[datastart - 2]) << 0);
513
514         /* Read CAN ID */
515         if (frame.can_id & CAN_EFF_FLAG) {
516                 frame.can_id |= (hex_to_bin(elm->rxbuf[0]) << 28)
517                               | (hex_to_bin(elm->rxbuf[1]) << 24)
518                               | (hex_to_bin(elm->rxbuf[3]) << 20)
519                               | (hex_to_bin(elm->rxbuf[4]) << 16)
520                               | (hex_to_bin(elm->rxbuf[6]) << 12)
521                               | (hex_to_bin(elm->rxbuf[7]) << 8)
522                               | (hex_to_bin(elm->rxbuf[9]) << 4)
523                               | (hex_to_bin(elm->rxbuf[10]) << 0);
524         } else {
525                 frame.can_id |= (hex_to_bin(elm->rxbuf[0]) << 8)
526                               | (hex_to_bin(elm->rxbuf[1]) << 4)
527                               | (hex_to_bin(elm->rxbuf[2]) << 0);
528         }
529
530         /* Check for RTR frame */
531         if (elm->rxfill >= hexlen + 3
532             && elm->rxbuf[hexlen + 0] == 'R'
533             && elm->rxbuf[hexlen + 1] == 'T'
534             && elm->rxbuf[hexlen + 2] == 'R') {
535                 frame.can_id |= CAN_RTR_FLAG;
536         }
537
538         /* Is the line long enough to hold the advertised payload? */
539         if (!(frame.can_id & CAN_RTR_FLAG) && (hexlen < frame.can_dlc * 3 + datastart)) {
540                 /* Incomplete frame. */
541
542                 /* Probably the ELM327's RS232 TX buffer was full.
543                  * Emit an error frame and exit.
544                  */
545                 frame.can_id = CAN_ERR_FLAG | CAN_ERR_CRTL;
546                 frame.can_dlc = CAN_ERR_DLC;
547                 frame.data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
548                 elm327_feed_frame_to_netdev(elm, &frame);
549
550                 /* Signal failure to parse.
551                  * The line will be re-parsed as an error line, which will fail.
552                  * However, this will correctly drop the state machine back into
553                  * command mode.
554                  */
555                 return 2;
556         }
557
558         /* Parse the data nibbles. */
559         for (i = 0; i < frame.can_dlc; i++) {
560                 frame.data[i] = (hex_to_bin(elm->rxbuf[datastart+3*i]) << 4)
561                                 | (hex_to_bin(elm->rxbuf[datastart+3*i+1]) << 0);
562         }
563
564         /* Feed the frame to the network layer. */
565         elm327_feed_frame_to_netdev(elm, &frame);
566
567         return 0;
568 }
569
570
571 static void elm327_parse_line(struct elmcan *elm, int len)
572 {
573         /* Skip empty lines */
574         if (!len) {
575                 return;
576         }
577
578         /* Skip echo lines */
579         if (elm->drop_next_line) {
580                 elm->drop_next_line = 0;
581                 return;
582         } else if (elm->rxbuf[0] == 'A' && elm->rxbuf[1] == 'T') {
583                 return;
584         }
585
586         /* Regular parsing */
587         switch(elm->state) {
588                 case ELM_RECEIVING:
589                         if (elm327_parse_frame(elm, len)) {
590                                 /* Parse an error line. */
591                                 elm327_parse_error(elm, len);
592
593                                 /* Start afresh. */
594                                 elm327_kick_into_cmd_mode(elm);
595                         }
596                         break;
597                 default:
598                         break;
599         }
600 }
601
602
603 static void elm327_handle_prompt(struct elmcan *elm)
604 {
605         if (elm->cmds_todo) {
606                 struct can_frame *frame = &elm->can_frame;
607                 char local_txbuf[20];
608
609                 if (test_bit(ELM_TODO_INIT, &elm->cmds_todo)) {
610                         elm327_send(elm, *elm->next_init_cmd, strlen(*elm->next_init_cmd));
611                         elm->next_init_cmd++;
612                         if (!(*elm->next_init_cmd)) {
613                                 clear_bit(ELM_TODO_INIT, &elm->cmds_todo);
614                                 netdev_info(elm->dev, "Initialization finished.\n");
615                         }
616
617                         /* Some chips are unreliable and need extra time after
618                          * init commands, as seen with a clone.
619                          * So let's do a dummy get-cmd-prompt dance.
620                          */
621                         elm->state = ELM_NOTINIT;
622                         elm327_kick_into_cmd_mode(elm);
623
624                         return;
625
626                 } else if (test_and_clear_bit(ELM_TODO_SILENT_MONITOR, &elm->cmds_todo)) {
627                         sprintf(local_txbuf, "ATCSM%i\r",
628                                 !(!(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY)));
629
630                 } else if (test_and_clear_bit(ELM_TODO_RESPONSES, &elm->cmds_todo)) {
631                         sprintf(local_txbuf, "ATR%i\r",
632                                 !(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY));
633
634                 } else if (test_and_clear_bit(ELM_TODO_CAN_CONFIG, &elm->cmds_todo)) {
635                         sprintf(local_txbuf, "ATPC\r");
636                         set_bit(ELM_TODO_CAN_CONFIG_PART2, &elm->cmds_todo);
637
638                 } else if (test_and_clear_bit(ELM_TODO_CAN_CONFIG_PART2, &elm->cmds_todo)) {
639                         sprintf(local_txbuf, "ATPB%04X\r",
640                                 elm->can_config);
641
642                 } else if (test_and_clear_bit(ELM_TODO_CANID_29BIT_HIGH, &elm->cmds_todo)) {
643                         sprintf(local_txbuf, "ATCP%02X\r",
644                                 (frame->can_id & CAN_EFF_MASK) >> 24);
645
646                 } else if (test_and_clear_bit(ELM_TODO_CANID_29BIT_LOW, &elm->cmds_todo)) {
647                         sprintf(local_txbuf, "ATSH%06X\r",
648                                 frame->can_id & CAN_EFF_MASK & ((1 << 24) - 1));
649
650                 } else if (test_and_clear_bit(ELM_TODO_CANID_11BIT, &elm->cmds_todo)) {
651                         sprintf(local_txbuf, "ATSH%03X\r",
652                                 frame->can_id & CAN_SFF_MASK);
653
654                 } else if (test_and_clear_bit(ELM_TODO_CAN_DATA, &elm->cmds_todo)) {
655                         if (frame->can_id & CAN_RTR_FLAG) {
656                                 /* Send an RTR frame. Their DLC is fixed.
657                                  * Some chips don't send them at all.
658                                  */
659                                 sprintf(local_txbuf, "ATRTR\r");
660                         } else {
661                                 /* Send a regular CAN data frame */
662                                 int i;
663
664                                 for (i = 0; i < frame->can_dlc; i++) {
665                                         sprintf(&local_txbuf[2*i], "%02X",
666                                                 frame->data[i]);
667                                 }
668
669                                 sprintf(&local_txbuf[2*i], "\r");
670                         }
671
672                         elm->drop_next_line = 1;
673                         elm->state = ELM_RECEIVING;
674                 }
675
676                 elm327_send(elm, local_txbuf, strlen(local_txbuf));
677         } else {
678                 /* Enter CAN monitor mode */
679                 elm327_send(elm, "ATMA\r", 5);
680                 elm->state = ELM_RECEIVING;
681         }
682 }
683
684
685 static void elm327_drop_bytes(struct elmcan *elm, int i)
686 {
687         memmove(&elm->rxbuf[0], &elm->rxbuf[i], sizeof(elm->rxbuf) - i);
688         elm->rxfill -= i;
689 }
690
691
692 static void elm327_parse_rxbuf(struct elmcan *elm)
693 {
694         int len;
695
696         switch (elm->state) {
697         case ELM_NOTINIT:
698                 elm->rxfill = 0;
699                 return;
700
701         case ELM_GETMAGICCHAR:
702         {
703                 /* Wait for 'y' or '>' */
704                 int i;
705
706                 for (i = 0; i < elm->rxfill; i++) {
707                         if (elm->rxbuf[i] == ELM327_MAGIC_CHAR) {
708                                 elm327_send(elm, "\r", 1);
709                                 elm->state = ELM_GETPROMPT;
710                                 i++;
711                                 break;
712                         } else if (elm327_is_ready_char(elm->rxbuf[i])) {
713                                 elm327_send(elm, ELM327_MAGIC_STRING, 1);
714                                 i++;
715                                 break;
716                         }
717                 }
718
719                 elm327_drop_bytes(elm, i);
720
721                 return;
722         }
723
724         case ELM_GETPROMPT:
725                 /* Wait for '>' */
726                 if (elm327_is_ready_char(elm->rxbuf[elm->rxfill - 1])) {
727                         elm327_handle_prompt(elm);
728                 }
729
730                 elm->rxfill = 0;
731                 return;
732
733         case ELM_RECEIVING:
734                 /* Find <CR> delimiting feedback lines. */
735                 for (len = 0;
736                      (len < elm->rxfill) && (elm->rxbuf[len] != '\r');
737                      len++) {
738                         /* empty loop */
739                 }
740
741                 if (len == sizeof(elm->rxbuf)) {
742                         /* Line exceeds buffer. It's probably all garbage.
743                          * Did we even connect at the right baud rate?
744                          */
745                         netdev_err(elm->dev, "RX buffer overflow. Faulty ELM327 connected?\n");
746                         elm327_hw_failure(elm);
747                         return;
748                 } else if (len == elm->rxfill) {
749                         if (elm->state == ELM_RECEIVING
750                                 && elm327_is_ready_char(elm->rxbuf[elm->rxfill - 1])) {
751                                 /* The ELM327's AT ST response timeout ran out,
752                                  * so we got a prompt.
753                                  * Clear RX buffer and restart listening.
754                                  */
755                                 elm->rxfill = 0;
756
757                                 elm327_handle_prompt(elm);
758                                 return;
759                         } else {
760                                 /* We haven't received a full line yet.
761                                  * Wait for more data.
762                                  */
763                                 return;
764                         }
765                 }
766
767                 /* We have a full line to parse. */
768                 elm327_parse_line(elm, len);
769
770                 /* Remove parsed data from RX buffer. */
771                 elm327_drop_bytes(elm, len+1);
772
773                 /* More data to parse? */
774                 if (elm->rxfill) {
775                         elm327_parse_rxbuf(elm);
776                 }
777         }
778 }
779
780
781
782
783
784  /************************************************************************
785   *             netdev                                          *
786   *                                                             *
787   * (takes elm->lock)                                           *
788   ************************************************************************/
789
790 /* Netdevice DOWN -> UP routine */
791 static int elmcan_netdev_open(struct net_device *dev)
792 {
793         struct elmcan *elm = netdev_priv(dev);
794         int err;
795
796         spin_lock_bh(&elm->lock);
797         if (elm->hw_failure) {
798                 netdev_err(elm->dev, "Refusing to open interface after "
799                                 "a hardware fault has been detected.\n");
800                 spin_unlock_bh(&elm->lock);
801                 return -EIO;
802         }
803
804         if (elm->tty == NULL) {
805                 spin_unlock_bh(&elm->lock);
806                 return -ENODEV;
807         }
808
809         /* open_candev() checks for elm->can.bittiming.bitrate != 0 */
810         err = open_candev(dev);
811         if (err) {
812                 spin_unlock_bh(&elm->lock);
813                 return err;
814         }
815
816         /* Initialize the ELM327 */
817         elm327_init(elm);
818         spin_unlock_bh(&elm->lock);
819
820         can_led_event(dev, CAN_LED_EVENT_OPEN);
821         elm->can.state = CAN_STATE_ERROR_ACTIVE;
822         netif_start_queue(dev);
823
824         return 0;
825 }
826
827 /* Netdevice UP -> DOWN routine */
828 static int elmcan_netdev_close(struct net_device *dev)
829 {
830         struct elmcan *elm = netdev_priv(dev);
831
832         spin_lock_bh(&elm->lock);
833         if (elm->tty) {
834                 /* TTY discipline is running. */
835
836                 /* Interrupt whatever we're doing right now */
837                 elm327_send(elm, ELM327_MAGIC_STRING, 1);
838
839                 /* Clear the wakeup bit, as the netdev will be down and thus
840                  * the wakeup handler won't clear it
841                  */
842                 clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
843
844                 spin_unlock_bh(&elm->lock);
845
846                 flush_work(&elm->tx_work);
847         } else {
848                 spin_unlock_bh(&elm->lock);
849         }
850
851         elm->can.state = CAN_STATE_STOPPED;
852         netif_stop_queue(dev);
853         close_candev(dev);
854         can_led_event(dev, CAN_LED_EVENT_STOP);
855
856         return 0;
857 }
858
859 /* Send a can_frame to a TTY queue. */
860 static netdev_tx_t elmcan_netdev_start_xmit(struct sk_buff *skb, struct net_device *dev)
861 {
862         struct elmcan *elm = netdev_priv(dev);
863         struct can_frame *frame = (struct can_frame *) skb->data;
864
865         if (skb->len != sizeof(struct can_frame))
866                 goto out;
867
868         if (!netif_running(dev))  {
869                 netdev_warn(elm->dev, "xmit: iface is down.\n");
870                 goto out;
871         }
872
873         /* BHs are already disabled, so no spin_lock_bh().
874          * See Documentation/networking/netdevices.txt
875          */
876         spin_lock(&elm->lock);
877
878         /* We shouldn't get here after a hardware fault:
879          * can_bus_off() calls netif_carrier_off()
880          */
881         BUG_ON(elm->hw_failure);
882
883         if (elm->tty == NULL
884                 || elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY) {
885                 spin_unlock(&elm->lock);
886                 goto out;
887         }
888
889         netif_stop_queue(dev);
890
891         elm327_send_frame(elm, frame);
892         spin_unlock(&elm->lock);
893
894         dev->stats.tx_packets++;
895         dev->stats.tx_bytes += frame->can_dlc;
896
897         can_led_event(dev, CAN_LED_EVENT_TX);
898
899 out:
900         kfree_skb(skb);
901         return NETDEV_TX_OK;
902 }
903
904 static int elmcan_netdev_change_mtu(struct net_device *dev, int new_mtu)
905 {
906         return -EINVAL;
907 }
908
909 static const struct net_device_ops elmcan_netdev_ops = {
910         .ndo_open       = elmcan_netdev_open,
911         .ndo_stop       = elmcan_netdev_close,
912         .ndo_start_xmit = elmcan_netdev_start_xmit,
913         .ndo_change_mtu = elmcan_netdev_change_mtu,
914 };
915
916
917
918
919
920  /************************************************************************
921   *             Line discipline                                 *
922   *                                                             *
923   * (takes elm->lock)                                           *
924   ************************************************************************/
925
926 /*
927  * Get a reference to our struct, taking into account locks/refcounts.
928  * This is to ensure ordering in case we are shutting down, and to ensure
929  * there is a refcount at all (because tty->disc_data may be NULL).
930  */
931 static struct elmcan* get_elm(struct tty_struct *tty)
932 {
933         struct elmcan *elm;
934         bool got_ref;
935
936         /* Lock all elmcan TTYs, so tty->disc_data can't become NULL
937          * the moment before we increase the reference counter.
938          */
939         spin_lock_bh(&elmcan_discdata_lock);
940         elm = (struct elmcan *) tty->disc_data;
941
942         if (!elm) {
943                 spin_unlock_bh(&elmcan_discdata_lock);
944                 return NULL;
945         }
946
947         got_ref = atomic_inc_not_zero(&elm->refcount);
948         spin_unlock_bh(&elmcan_discdata_lock);
949
950         if (!got_ref) {
951                 return NULL;
952         }
953
954         return elm;
955 }
956
957 static void put_elm(struct elmcan *elm)
958 {
959         atomic_dec(&elm->refcount);
960 }
961
962
963
964 /*
965  * Handle the 'receiver data ready' interrupt.
966  * This function is called by the 'tty_io' module in the kernel when
967  * a block of ELM327 CAN data has been received, which can now be parsed
968  * and sent on to some IP layer for further processing. This will not
969  * be re-entered while running but other ldisc functions may be called
970  * in parallel
971  */
972 static void elmcan_ldisc_rx(struct tty_struct *tty,
973                         const unsigned char *cp, char *fp, int count)
974 {
975         struct elmcan *elm = get_elm(tty);
976
977         if (!elm)
978                 return;
979
980         spin_lock_bh(&elm->lock);
981         if (elm->hw_failure) {
982                 spin_unlock_bh(&elm->lock);
983
984                 put_elm(elm);
985                 return;
986         }
987
988         /* Read the characters out of the buffer */
989         while (count-- && elm->rxfill < sizeof(elm->rxbuf)) {
990                 if (fp && *fp++) {
991                         netdev_err(elm->dev, "Error in received character stream. Check your wiring.");
992
993                         spin_lock_bh(&elm->lock);
994                         elm327_hw_failure(elm);
995                         spin_unlock_bh(&elm->lock);
996
997                         put_elm(elm);
998                         return;
999                 }
1000
1001                 /* Ignore NUL characters, which the PIC microcontroller may
1002                  * inadvertently insert due to a known hardware bug.
1003                  * See ELM327 documentation, which refers to a Microchip PIC
1004                  * bug description.
1005                  */
1006                 if (*cp != 0) {
1007                         /* Check for stray characters on the UART line.
1008                          * No idea what causes this.
1009                          */
1010                         if (!accept_flaky_uart
1011                             && !isdigit(*cp)
1012                             && !isupper(*cp)
1013                             && ELM327_MAGIC_CHAR != *cp
1014                             && ELM327_READY_CHAR != *cp
1015                             && '<' != *cp
1016                             && 'a' != *cp
1017                             && 'b' != *cp
1018                             && 'v' != *cp
1019                             && '.' != *cp
1020                             && '?' != *cp
1021                             && '\r' != *cp
1022                             && ' ' != *cp) {
1023                                 /* We've received an invalid character, so bail.
1024                                  * There's something wrong with the ELM327, or
1025                                  * with the UART line.
1026                                  */
1027                                 netdev_err(elm->dev,
1028                                         "Received illegal character %02x.\n",
1029                                         *cp);
1030                                 elm327_hw_failure(elm);
1031                                 spin_unlock_bh(&elm->lock);
1032
1033                                 put_elm(elm);
1034                                 return;
1035                         }
1036
1037                         elm->rxbuf[elm->rxfill++] = *cp;
1038                 }
1039
1040                 cp++;
1041         }
1042
1043         if (count >= 0) {
1044                 netdev_err(elm->dev, "Receive buffer overflowed. Bad chip or wiring?");
1045
1046                 elm327_hw_failure(elm);
1047                 spin_unlock_bh(&elm->lock);
1048
1049                 put_elm(elm);
1050                 return;
1051         }
1052
1053         elm327_parse_rxbuf(elm);
1054         spin_unlock_bh(&elm->lock);
1055
1056         put_elm(elm);
1057 }
1058
1059 /*
1060  * Write out remaining transmit buffer.
1061  * Scheduled when TTY is writable.
1062  */
1063 static void elmcan_ldisc_tx_worker(struct work_struct *work)
1064 {
1065         /* No need to use get_elm() here, as we'll always flush workers
1066          * befory destroying the elmcan object.
1067          */
1068         struct elmcan *elm = container_of(work, struct elmcan, tx_work);
1069         ssize_t actual;
1070
1071         spin_lock_bh(&elm->lock);
1072         if (elm->hw_failure) {
1073                 spin_unlock_bh(&elm->lock);
1074                 return;
1075         }
1076
1077         if (!elm->tty || !netif_running(elm->dev)) {
1078                 spin_unlock_bh(&elm->lock);
1079                 return;
1080         }
1081
1082         if (elm->txleft <= 0)  {
1083                 /* Our TTY write buffer is empty:
1084                  * We can start transmission of another packet
1085                  */
1086                 clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
1087                 spin_unlock_bh(&elm->lock);
1088                 netif_wake_queue(elm->dev);
1089                 return;
1090         }
1091
1092         actual = elm->tty->ops->write(elm->tty, elm->txhead, elm->txleft);
1093         if (actual < 0) {
1094                 netdev_err(elm->dev, "Failed to write to tty %s.\n", elm->tty->name);
1095                 elm327_hw_failure(elm);
1096                 spin_unlock_bh(&elm->lock);
1097                 return;
1098         }
1099
1100         elm->txleft -= actual;
1101         elm->txhead += actual;
1102         spin_unlock_bh(&elm->lock);
1103 }
1104
1105
1106 /*
1107  * Called by the driver when there's room for more data.
1108  * Schedule the transmit.
1109  */
1110 static void elmcan_ldisc_tx_wakeup(struct tty_struct *tty)
1111 {
1112         struct elmcan *elm = get_elm(tty);
1113
1114         if (!elm)
1115                 return;
1116
1117         schedule_work(&elm->tx_work);
1118
1119         put_elm(elm);
1120 }
1121
1122
1123
1124 /* ELM327 can only handle bitrates that are integer divisors of 500 kHz,
1125  * or 7/8 of that. Divisors are 1 to 64.
1126  * Currently we don't implement support for 7/8 rates.
1127  */
1128 static const u32 elmcan_bitrate_const[64] = {
1129         7812, 7936, 8064, 8196, 8333, 8474, 8620, 8771,
1130         8928, 9090, 9259, 9433, 9615, 9803, 10000, 10204,
1131         10416, 10638, 10869, 11111, 11363, 11627, 11904, 12195,
1132         12500, 12820, 13157, 13513, 13888, 14285, 14705, 15151,
1133         15625, 16129, 16666, 17241, 17857, 18518, 19230, 20000,
1134         20833, 21739, 22727, 23809, 25000, 26315, 27777, 29411,
1135         31250, 33333, 35714, 38461, 41666, 45454, 50000, 55555,
1136         62500, 71428, 83333, 100000, 125000, 166666, 250000, 500000
1137 };
1138
1139 /* Dummy function to claim we're changing the bitrate.
1140  * We actually do this when opening the net device.
1141  */
1142 static int elmcan_do_set_bittiming(struct net_device *netdev)
1143 {
1144         return 0;
1145 }
1146
1147
1148 /*
1149  * Open the high-level part of the elmcan channel.
1150  * This function is called by the TTY module when the
1151  * elmcan line discipline is called for.
1152  *
1153  * Called in process context serialized from other ldisc calls.
1154  */
1155 static int elmcan_ldisc_open(struct tty_struct *tty)
1156 {
1157         struct net_device *dev;
1158         struct elmcan *elm;
1159         int err;
1160
1161         if (!capable(CAP_NET_ADMIN))
1162                 return -EPERM;
1163
1164         if (!tty->ops->write)
1165                 return -EOPNOTSUPP;
1166
1167
1168         /* OK.  Find a free elmcan channel to use. */
1169         dev = alloc_candev(sizeof(struct elmcan), 0);
1170         if (!dev)
1171                 return -ENFILE;
1172         elm = netdev_priv(dev);
1173
1174         /* Configure TTY interface */
1175         tty->receive_room = 65536; /* We don't flow control */
1176         elm->txleft = 0; /* Clear TTY TX buffer */
1177         spin_lock_init(&elm->lock);
1178         atomic_set(&elm->refcount, 1);
1179         INIT_WORK(&elm->tx_work, elmcan_ldisc_tx_worker);
1180
1181         /* Configure CAN metadata */
1182         elm->can.state = CAN_STATE_STOPPED;
1183         elm->can.bitrate_const = elmcan_bitrate_const;
1184         elm->can.bitrate_const_cnt = ARRAY_SIZE(elmcan_bitrate_const);
1185         elm->can.do_set_bittiming = elmcan_do_set_bittiming;
1186         elm->can.ctrlmode_supported = CAN_CTRLMODE_LISTENONLY;
1187
1188         /* Configure netlink interface */
1189         elm->dev = dev;
1190         dev->netdev_ops = &elmcan_netdev_ops;
1191
1192         /* Mark ldisc channel as alive */
1193         elm->tty = tty;
1194         tty->disc_data = elm;
1195
1196         devm_can_led_init(elm->dev);
1197
1198         /* Let 'er rip */
1199         err = register_candev(elm->dev);
1200         if (err) {
1201                 free_candev(elm->dev);
1202                 return err;
1203         }
1204
1205         netdev_info(elm->dev, "elmcan on %s.\n", tty->name);
1206
1207         return 0;
1208 }
1209
1210 /*
1211  * Close down an elmcan channel.
1212  * This means flushing out any pending queues, and then returning.
1213  * This call is serialized against other ldisc functions:
1214  * Once this is called, no other ldisc function of ours is entered.
1215  *
1216  * We also use this function for a hangup event.
1217  */
1218 static void elmcan_ldisc_close(struct tty_struct *tty)
1219 {
1220         /* Use get_elm() to synchronize against other users */
1221         struct elmcan *elm = get_elm(tty);
1222
1223         if (!elm)
1224                 return;
1225
1226         /* Tear down network side.
1227          * unregister_netdev() calls .ndo_stop() so we don't have to.
1228          */
1229         unregister_candev(elm->dev);
1230
1231         /* Decrease the refcount twice, once for our own get_elm(),
1232          * and once to remove the count of 1 that we set in _open().
1233          * Once it reaches 0, we can safely destroy it.
1234          */
1235         put_elm(elm);
1236         put_elm(elm);
1237
1238         /* Spin until refcount reaches 0 */
1239         while(atomic_read(&elm->refcount) > 0)
1240                 msleep(1);
1241
1242         /* At this point, all ldisc calls to us will be no-ops.
1243          * Since the refcount is 0, they are bailing immediately.
1244          */
1245
1246         /* Mark channel as dead */
1247         spin_lock_bh(&elm->lock);
1248         tty->disc_data = NULL;
1249         elm->tty = NULL;
1250         spin_unlock_bh(&elm->lock);
1251
1252         /* Flush TTY side */
1253         flush_work(&elm->tx_work);
1254
1255         netdev_info(elm->dev, "elmcan off %s.\n", tty->name);
1256
1257         /* Free our memory */
1258         free_candev(elm->dev);
1259 }
1260
1261 static int elmcan_ldisc_hangup(struct tty_struct *tty)
1262 {
1263         elmcan_ldisc_close(tty);
1264         return 0;
1265 }
1266
1267 /* Perform I/O control on an active elmcan channel. */
1268 static int elmcan_ldisc_ioctl(struct tty_struct *tty, struct file *file,
1269                         unsigned int cmd, unsigned long arg)
1270 {
1271         struct elmcan *elm = get_elm(tty);
1272         unsigned int tmp;
1273
1274         if (!elm)
1275                 return -EINVAL;
1276
1277         switch (cmd) {
1278         case SIOCGIFNAME:
1279                 tmp = strlen(elm->dev->name) + 1;
1280                 if (copy_to_user((void __user *)arg, elm->dev->name, tmp)) {
1281                         put_elm(elm);
1282                         return -EFAULT;
1283                 }
1284
1285                 put_elm(elm);
1286                 return 0;
1287
1288         case SIOCSIFHWADDR:
1289                 put_elm(elm);
1290                 return -EINVAL;
1291
1292         default:
1293                 put_elm(elm);
1294                 return tty_mode_ioctl(tty, file, cmd, arg);
1295         }
1296 }
1297
1298 static struct tty_ldisc_ops elmcan_ldisc = {
1299         .owner          = THIS_MODULE,
1300         .magic          = TTY_LDISC_MAGIC,
1301         .name           = "elmcan",
1302         .receive_buf    = elmcan_ldisc_rx,
1303         .write_wakeup   = elmcan_ldisc_tx_wakeup,
1304         .open           = elmcan_ldisc_open,
1305         .close          = elmcan_ldisc_close,
1306         .hangup         = elmcan_ldisc_hangup,
1307         .ioctl          = elmcan_ldisc_ioctl,
1308 };
1309
1310
1311
1312
1313
1314  /************************************************************************
1315   *             Module init/exit                                *
1316   ************************************************************************/
1317
1318 static int __init elmcan_init(void)
1319 {
1320         int status;
1321
1322         pr_info("ELM327 based best-effort CAN interface driver\n");
1323         pr_info("This device is severely limited as a CAN interface, see documentation.\n");
1324
1325         /* Fill in our line protocol discipline, and register it */
1326         status = tty_register_ldisc(N_ELMCAN, &elmcan_ldisc);
1327         if (status) {
1328                 pr_err("can't register line discipline\n");
1329         }
1330         return status;
1331 }
1332
1333 static void __exit elmcan_exit(void)
1334 {
1335         /* This will only be called when all channels have been closed by
1336          * userspace - tty_ldisc.c takes care of the module's refcount.
1337          */
1338         int status;
1339
1340         status = tty_unregister_ldisc(N_ELMCAN);
1341         if (status) {
1342                 pr_err("Can't unregister line discipline (error: %d)\n", status);
1343         }
1344 }
1345
1346 module_init(elmcan_init);
1347 module_exit(elmcan_exit);