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