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