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