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