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