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