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