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