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