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