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