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