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