Back to home page

OSCL-LXR

 
 

    


0001 // SPDX-License-Identifier: GPL-2.0
0002 /* ELM327 based CAN interface driver (tty line discipline)
0003  *
0004  * This driver started as a derivative of linux/drivers/net/can/slcan.c
0005  * and my thanks go to the original authors for their inspiration.
0006  *
0007  * can327.c Author : Max Staudt <max-linux@enpas.org>
0008  * slcan.c Author  : Oliver Hartkopp <socketcan@hartkopp.net>
0009  * slip.c Authors  : Laurence Culhane <loz@holmes.demon.co.uk>
0010  *                   Fred N. van Kempen <waltje@uwalt.nl.mugnet.org>
0011  */
0012 
0013 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
0014 
0015 #include <linux/init.h>
0016 #include <linux/module.h>
0017 
0018 #include <linux/bitops.h>
0019 #include <linux/ctype.h>
0020 #include <linux/errno.h>
0021 #include <linux/kernel.h>
0022 #include <linux/list.h>
0023 #include <linux/lockdep.h>
0024 #include <linux/netdevice.h>
0025 #include <linux/skbuff.h>
0026 #include <linux/spinlock.h>
0027 #include <linux/string.h>
0028 #include <linux/tty.h>
0029 #include <linux/tty_ldisc.h>
0030 #include <linux/workqueue.h>
0031 
0032 #include <uapi/linux/tty.h>
0033 
0034 #include <linux/can.h>
0035 #include <linux/can/dev.h>
0036 #include <linux/can/error.h>
0037 #include <linux/can/rx-offload.h>
0038 
0039 #define CAN327_NAPI_WEIGHT 4
0040 
0041 #define CAN327_SIZE_TXBUF 32
0042 #define CAN327_SIZE_RXBUF 1024
0043 
0044 #define CAN327_CAN_CONFIG_SEND_SFF 0x8000
0045 #define CAN327_CAN_CONFIG_VARIABLE_DLC 0x4000
0046 #define CAN327_CAN_CONFIG_RECV_BOTH_SFF_EFF 0x2000
0047 #define CAN327_CAN_CONFIG_BAUDRATE_MULT_8_7 0x1000
0048 
0049 #define CAN327_DUMMY_CHAR 'y'
0050 #define CAN327_DUMMY_STRING "y"
0051 #define CAN327_READY_CHAR '>'
0052 
0053 /* Bits in elm->cmds_todo */
0054 enum can327_tx_do {
0055     CAN327_TX_DO_CAN_DATA = 0,
0056     CAN327_TX_DO_CANID_11BIT,
0057     CAN327_TX_DO_CANID_29BIT_LOW,
0058     CAN327_TX_DO_CANID_29BIT_HIGH,
0059     CAN327_TX_DO_CAN_CONFIG_PART2,
0060     CAN327_TX_DO_CAN_CONFIG,
0061     CAN327_TX_DO_RESPONSES,
0062     CAN327_TX_DO_SILENT_MONITOR,
0063     CAN327_TX_DO_INIT,
0064 };
0065 
0066 struct can327 {
0067     /* This must be the first member when using alloc_candev() */
0068     struct can_priv can;
0069 
0070     struct can_rx_offload offload;
0071 
0072     /* TTY buffers */
0073     u8 txbuf[CAN327_SIZE_TXBUF];
0074     u8 rxbuf[CAN327_SIZE_RXBUF];
0075 
0076     /* Per-channel lock */
0077     spinlock_t lock;
0078 
0079     /* TTY and netdev devices that we're bridging */
0080     struct tty_struct *tty;
0081     struct net_device *dev;
0082 
0083     /* TTY buffer accounting */
0084     struct work_struct tx_work; /* Flushes TTY TX buffer */
0085     u8 *txhead;         /* Next TX byte */
0086     size_t txleft;          /* Bytes left to TX */
0087     int rxfill;         /* Bytes already RX'd in buffer */
0088 
0089     /* State machine */
0090     enum {
0091         CAN327_STATE_NOTINIT = 0,
0092         CAN327_STATE_GETDUMMYCHAR,
0093         CAN327_STATE_GETPROMPT,
0094         CAN327_STATE_RECEIVING,
0095     } state;
0096 
0097     /* Things we have yet to send */
0098     char **next_init_cmd;
0099     unsigned long cmds_todo;
0100 
0101     /* The CAN frame and config the ELM327 is sending/using,
0102      * or will send/use after finishing all cmds_todo
0103      */
0104     struct can_frame can_frame_to_send;
0105     u16 can_config;
0106     u8 can_bitrate_divisor;
0107 
0108     /* Parser state */
0109     bool drop_next_line;
0110 
0111     /* Stop the channel on UART side hardware failure, e.g. stray
0112      * characters or neverending lines. This may be caused by bad
0113      * UART wiring, a bad ELM327, a bad UART bridge...
0114      * Once this is true, nothing will be sent to the TTY.
0115      */
0116     bool uart_side_failure;
0117 };
0118 
0119 static inline void can327_uart_side_failure(struct can327 *elm);
0120 
0121 static void can327_send(struct can327 *elm, const void *buf, size_t len)
0122 {
0123     int written;
0124 
0125     lockdep_assert_held(&elm->lock);
0126 
0127     if (elm->uart_side_failure)
0128         return;
0129 
0130     memcpy(elm->txbuf, buf, len);
0131 
0132     /* Order of next two lines is *very* important.
0133      * When we are sending a little amount of data,
0134      * the transfer may be completed inside the ops->write()
0135      * routine, because it's running with interrupts enabled.
0136      * In this case we *never* got WRITE_WAKEUP event,
0137      * if we did not request it before write operation.
0138      *       14 Oct 1994  Dmitry Gorodchanin.
0139      */
0140     set_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
0141     written = elm->tty->ops->write(elm->tty, elm->txbuf, len);
0142     if (written < 0) {
0143         netdev_err(elm->dev, "Failed to write to tty %s.\n",
0144                elm->tty->name);
0145         can327_uart_side_failure(elm);
0146         return;
0147     }
0148 
0149     elm->txleft = len - written;
0150     elm->txhead = elm->txbuf + written;
0151 }
0152 
0153 /* Take the ELM327 out of almost any state and back into command mode.
0154  * We send CAN327_DUMMY_CHAR which will either abort any running
0155  * operation, or be echoed back to us in case we're already in command
0156  * mode.
0157  */
0158 static void can327_kick_into_cmd_mode(struct can327 *elm)
0159 {
0160     lockdep_assert_held(&elm->lock);
0161 
0162     if (elm->state != CAN327_STATE_GETDUMMYCHAR &&
0163         elm->state != CAN327_STATE_GETPROMPT) {
0164         can327_send(elm, CAN327_DUMMY_STRING, 1);
0165 
0166         elm->state = CAN327_STATE_GETDUMMYCHAR;
0167     }
0168 }
0169 
0170 /* Schedule a CAN frame and necessary config changes to be sent to the TTY. */
0171 static void can327_send_frame(struct can327 *elm, struct can_frame *frame)
0172 {
0173     lockdep_assert_held(&elm->lock);
0174 
0175     /* Schedule any necessary changes in ELM327's CAN configuration */
0176     if (elm->can_frame_to_send.can_id != frame->can_id) {
0177         /* Set the new CAN ID for transmission. */
0178         if ((frame->can_id ^ elm->can_frame_to_send.can_id)
0179             & CAN_EFF_FLAG) {
0180             elm->can_config =
0181                 (frame->can_id & CAN_EFF_FLAG ? 0 : CAN327_CAN_CONFIG_SEND_SFF) |
0182                 CAN327_CAN_CONFIG_VARIABLE_DLC |
0183                 CAN327_CAN_CONFIG_RECV_BOTH_SFF_EFF |
0184                 elm->can_bitrate_divisor;
0185 
0186             set_bit(CAN327_TX_DO_CAN_CONFIG, &elm->cmds_todo);
0187         }
0188 
0189         if (frame->can_id & CAN_EFF_FLAG) {
0190             clear_bit(CAN327_TX_DO_CANID_11BIT, &elm->cmds_todo);
0191             set_bit(CAN327_TX_DO_CANID_29BIT_LOW, &elm->cmds_todo);
0192             set_bit(CAN327_TX_DO_CANID_29BIT_HIGH, &elm->cmds_todo);
0193         } else {
0194             set_bit(CAN327_TX_DO_CANID_11BIT, &elm->cmds_todo);
0195             clear_bit(CAN327_TX_DO_CANID_29BIT_LOW,
0196                   &elm->cmds_todo);
0197             clear_bit(CAN327_TX_DO_CANID_29BIT_HIGH,
0198                   &elm->cmds_todo);
0199         }
0200     }
0201 
0202     /* Schedule the CAN frame itself. */
0203     elm->can_frame_to_send = *frame;
0204     set_bit(CAN327_TX_DO_CAN_DATA, &elm->cmds_todo);
0205 
0206     can327_kick_into_cmd_mode(elm);
0207 }
0208 
0209 /* ELM327 initialisation sequence.
0210  * The line length is limited by the buffer in can327_handle_prompt().
0211  */
0212 static char *can327_init_script[] = {
0213     "AT WS\r",        /* v1.0: Warm Start */
0214     "AT PP FF OFF\r", /* v1.0: All Programmable Parameters Off */
0215     "AT M0\r",        /* v1.0: Memory Off */
0216     "AT AL\r",        /* v1.0: Allow Long messages */
0217     "AT BI\r",        /* v1.0: Bypass Initialisation */
0218     "AT CAF0\r",      /* v1.0: CAN Auto Formatting Off */
0219     "AT CFC0\r",      /* v1.0: CAN Flow Control Off */
0220     "AT CF 000\r",    /* v1.0: Reset CAN ID Filter */
0221     "AT CM 000\r",    /* v1.0: Reset CAN ID Mask */
0222     "AT E1\r",        /* v1.0: Echo On */
0223     "AT H1\r",        /* v1.0: Headers On */
0224     "AT L0\r",        /* v1.0: Linefeeds Off */
0225     "AT SH 7DF\r",    /* v1.0: Set CAN sending ID to 0x7df */
0226     "AT ST FF\r",     /* v1.0: Set maximum Timeout for response after TX */
0227     "AT AT0\r",       /* v1.2: Adaptive Timing Off */
0228     "AT D1\r",        /* v1.3: Print DLC On */
0229     "AT S1\r",        /* v1.3: Spaces On */
0230     "AT TP B\r",      /* v1.0: Try Protocol B */
0231     NULL
0232 };
0233 
0234 static void can327_init_device(struct can327 *elm)
0235 {
0236     lockdep_assert_held(&elm->lock);
0237 
0238     elm->state = CAN327_STATE_NOTINIT;
0239     elm->can_frame_to_send.can_id = 0x7df; /* ELM327 HW default */
0240     elm->rxfill = 0;
0241     elm->drop_next_line = 0;
0242 
0243     /* We can only set the bitrate as a fraction of 500000.
0244      * The bitrates listed in can327_bitrate_const will
0245      * limit the user to the right values.
0246      */
0247     elm->can_bitrate_divisor = 500000 / elm->can.bittiming.bitrate;
0248     elm->can_config =
0249         CAN327_CAN_CONFIG_SEND_SFF | CAN327_CAN_CONFIG_VARIABLE_DLC |
0250         CAN327_CAN_CONFIG_RECV_BOTH_SFF_EFF | elm->can_bitrate_divisor;
0251 
0252     /* Configure ELM327 and then start monitoring */
0253     elm->next_init_cmd = &can327_init_script[0];
0254     set_bit(CAN327_TX_DO_INIT, &elm->cmds_todo);
0255     set_bit(CAN327_TX_DO_SILENT_MONITOR, &elm->cmds_todo);
0256     set_bit(CAN327_TX_DO_RESPONSES, &elm->cmds_todo);
0257     set_bit(CAN327_TX_DO_CAN_CONFIG, &elm->cmds_todo);
0258 
0259     can327_kick_into_cmd_mode(elm);
0260 }
0261 
0262 static void can327_feed_frame_to_netdev(struct can327 *elm, struct sk_buff *skb)
0263 {
0264     lockdep_assert_held(&elm->lock);
0265 
0266     if (!netif_running(elm->dev))
0267         return;
0268 
0269     /* Queue for NAPI pickup.
0270      * rx-offload will update stats and LEDs for us.
0271      */
0272     if (can_rx_offload_queue_tail(&elm->offload, skb))
0273         elm->dev->stats.rx_fifo_errors++;
0274 
0275     /* Wake NAPI */
0276     can_rx_offload_irq_finish(&elm->offload);
0277 }
0278 
0279 /* Called when we're out of ideas and just want it all to end. */
0280 static inline void can327_uart_side_failure(struct can327 *elm)
0281 {
0282     struct can_frame *frame;
0283     struct sk_buff *skb;
0284 
0285     lockdep_assert_held(&elm->lock);
0286 
0287     elm->uart_side_failure = true;
0288 
0289     clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
0290 
0291     elm->can.can_stats.bus_off++;
0292     netif_stop_queue(elm->dev);
0293     elm->can.state = CAN_STATE_BUS_OFF;
0294     can_bus_off(elm->dev);
0295 
0296     netdev_err(elm->dev,
0297            "ELM327 misbehaved. Blocking further communication.\n");
0298 
0299     skb = alloc_can_err_skb(elm->dev, &frame);
0300     if (!skb)
0301         return;
0302 
0303     frame->can_id |= CAN_ERR_BUSOFF;
0304     can327_feed_frame_to_netdev(elm, skb);
0305 }
0306 
0307 /* Compares a byte buffer (non-NUL terminated) to the payload part of
0308  * a string, and returns true iff the buffer (content *and* length) is
0309  * exactly that string, without the terminating NUL byte.
0310  *
0311  * Example: If reference is "BUS ERROR", then this returns true iff nbytes == 9
0312  *          and !memcmp(buf, "BUS ERROR", 9).
0313  *
0314  * The reason to use strings is so we can easily include them in the C
0315  * code, and to avoid hardcoding lengths.
0316  */
0317 static inline bool can327_rxbuf_cmp(const u8 *buf, size_t nbytes,
0318                     const char *reference)
0319 {
0320     size_t ref_len = strlen(reference);
0321 
0322     return (nbytes == ref_len) && !memcmp(buf, reference, ref_len);
0323 }
0324 
0325 static void can327_parse_error(struct can327 *elm, size_t len)
0326 {
0327     struct can_frame *frame;
0328     struct sk_buff *skb;
0329 
0330     lockdep_assert_held(&elm->lock);
0331 
0332     skb = alloc_can_err_skb(elm->dev, &frame);
0333     if (!skb)
0334         /* It's okay to return here:
0335          * The outer parsing loop will drop this UART buffer.
0336          */
0337         return;
0338 
0339     /* Filter possible error messages based on length of RX'd line */
0340     if (can327_rxbuf_cmp(elm->rxbuf, len, "UNABLE TO CONNECT")) {
0341         netdev_err(elm->dev,
0342                "ELM327 reported UNABLE TO CONNECT. Please check your setup.\n");
0343     } else if (can327_rxbuf_cmp(elm->rxbuf, len, "BUFFER FULL")) {
0344         /* This will only happen if the last data line was complete.
0345          * Otherwise, can327_parse_frame() will heuristically
0346          * emit this kind of error frame instead.
0347          */
0348         frame->can_id |= CAN_ERR_CRTL;
0349         frame->data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
0350     } else if (can327_rxbuf_cmp(elm->rxbuf, len, "BUS ERROR")) {
0351         frame->can_id |= CAN_ERR_BUSERROR;
0352     } else if (can327_rxbuf_cmp(elm->rxbuf, len, "CAN ERROR")) {
0353         frame->can_id |= CAN_ERR_PROT;
0354     } else if (can327_rxbuf_cmp(elm->rxbuf, len, "<RX ERROR")) {
0355         frame->can_id |= CAN_ERR_PROT;
0356     } else if (can327_rxbuf_cmp(elm->rxbuf, len, "BUS BUSY")) {
0357         frame->can_id |= CAN_ERR_PROT;
0358         frame->data[2] = CAN_ERR_PROT_OVERLOAD;
0359     } else if (can327_rxbuf_cmp(elm->rxbuf, len, "FB ERROR")) {
0360         frame->can_id |= CAN_ERR_PROT;
0361         frame->data[2] = CAN_ERR_PROT_TX;
0362     } else if (len == 5 && !memcmp(elm->rxbuf, "ERR", 3)) {
0363         /* ERR is followed by two digits, hence line length 5 */
0364         netdev_err(elm->dev, "ELM327 reported an ERR%c%c. Please power it off and on again.\n",
0365                elm->rxbuf[3], elm->rxbuf[4]);
0366         frame->can_id |= CAN_ERR_CRTL;
0367     } else {
0368         /* Something else has happened.
0369          * Maybe garbage on the UART line.
0370          * Emit a generic error frame.
0371          */
0372     }
0373 
0374     can327_feed_frame_to_netdev(elm, skb);
0375 }
0376 
0377 /* Parse CAN frames coming as ASCII from ELM327.
0378  * They can be of various formats:
0379  *
0380  * 29-bit ID (EFF):  12 34 56 78 D PL PL PL PL PL PL PL PL
0381  * 11-bit ID (!EFF): 123 D PL PL PL PL PL PL PL PL
0382  *
0383  * where D = DLC, PL = payload byte
0384  *
0385  * Instead of a payload, RTR indicates a remote request.
0386  *
0387  * We will use the spaces and line length to guess the format.
0388  */
0389 static int can327_parse_frame(struct can327 *elm, size_t len)
0390 {
0391     struct can_frame *frame;
0392     struct sk_buff *skb;
0393     int hexlen;
0394     int datastart;
0395     int i;
0396 
0397     lockdep_assert_held(&elm->lock);
0398 
0399     skb = alloc_can_skb(elm->dev, &frame);
0400     if (!skb)
0401         return -ENOMEM;
0402 
0403     /* Find first non-hex and non-space character:
0404      *  - In the simplest case, there is none.
0405      *  - For RTR frames, 'R' is the first non-hex character.
0406      *  - An error message may replace the end of the data line.
0407      */
0408     for (hexlen = 0; hexlen <= len; hexlen++) {
0409         if (hex_to_bin(elm->rxbuf[hexlen]) < 0 &&
0410             elm->rxbuf[hexlen] != ' ') {
0411             break;
0412         }
0413     }
0414 
0415     /* Sanity check whether the line is really a clean hexdump,
0416      * or terminated by an error message, or contains garbage.
0417      */
0418     if (hexlen < len && !isdigit(elm->rxbuf[hexlen]) &&
0419         !isupper(elm->rxbuf[hexlen]) && '<' != elm->rxbuf[hexlen] &&
0420         ' ' != elm->rxbuf[hexlen]) {
0421         /* The line is likely garbled anyway, so bail.
0422          * The main code will restart listening.
0423          */
0424         kfree_skb(skb);
0425         return -ENODATA;
0426     }
0427 
0428     /* Use spaces in CAN ID to distinguish 29 or 11 bit address length.
0429      * No out-of-bounds access:
0430      * We use the fact that we can always read from elm->rxbuf.
0431      */
0432     if (elm->rxbuf[2] == ' ' && elm->rxbuf[5] == ' ' &&
0433         elm->rxbuf[8] == ' ' && elm->rxbuf[11] == ' ' &&
0434         elm->rxbuf[13] == ' ') {
0435         frame->can_id = CAN_EFF_FLAG;
0436         datastart = 14;
0437     } else if (elm->rxbuf[3] == ' ' && elm->rxbuf[5] == ' ') {
0438         datastart = 6;
0439     } else {
0440         /* This is not a well-formatted data line.
0441          * Assume it's an error message.
0442          */
0443         kfree_skb(skb);
0444         return -ENODATA;
0445     }
0446 
0447     if (hexlen < datastart) {
0448         /* The line is too short to be a valid frame hex dump.
0449          * Something interrupted the hex dump or it is invalid.
0450          */
0451         kfree_skb(skb);
0452         return -ENODATA;
0453     }
0454 
0455     /* From here on all chars up to buf[hexlen] are hex or spaces,
0456      * at well-defined offsets.
0457      */
0458 
0459     /* Read CAN data length */
0460     frame->len = (hex_to_bin(elm->rxbuf[datastart - 2]) << 0);
0461 
0462     /* Read CAN ID */
0463     if (frame->can_id & CAN_EFF_FLAG) {
0464         frame->can_id |= (hex_to_bin(elm->rxbuf[0]) << 28) |
0465                  (hex_to_bin(elm->rxbuf[1]) << 24) |
0466                  (hex_to_bin(elm->rxbuf[3]) << 20) |
0467                  (hex_to_bin(elm->rxbuf[4]) << 16) |
0468                  (hex_to_bin(elm->rxbuf[6]) << 12) |
0469                  (hex_to_bin(elm->rxbuf[7]) << 8) |
0470                  (hex_to_bin(elm->rxbuf[9]) << 4) |
0471                  (hex_to_bin(elm->rxbuf[10]) << 0);
0472     } else {
0473         frame->can_id |= (hex_to_bin(elm->rxbuf[0]) << 8) |
0474                  (hex_to_bin(elm->rxbuf[1]) << 4) |
0475                  (hex_to_bin(elm->rxbuf[2]) << 0);
0476     }
0477 
0478     /* Check for RTR frame */
0479     if (elm->rxfill >= hexlen + 3 &&
0480         !memcmp(&elm->rxbuf[hexlen], "RTR", 3)) {
0481         frame->can_id |= CAN_RTR_FLAG;
0482     }
0483 
0484     /* Is the line long enough to hold the advertised payload?
0485      * Note: RTR frames have a DLC, but no actual payload.
0486      */
0487     if (!(frame->can_id & CAN_RTR_FLAG) &&
0488         (hexlen < frame->len * 3 + datastart)) {
0489         /* Incomplete frame.
0490          * Probably the ELM327's RS232 TX buffer was full.
0491          * Emit an error frame and exit.
0492          */
0493         frame->can_id = CAN_ERR_FLAG | CAN_ERR_CRTL;
0494         frame->len = CAN_ERR_DLC;
0495         frame->data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
0496         can327_feed_frame_to_netdev(elm, skb);
0497 
0498         /* Signal failure to parse.
0499          * The line will be re-parsed as an error line, which will fail.
0500          * However, this will correctly drop the state machine back into
0501          * command mode.
0502          */
0503         return -ENODATA;
0504     }
0505 
0506     /* Parse the data nibbles. */
0507     for (i = 0; i < frame->len; i++) {
0508         frame->data[i] =
0509             (hex_to_bin(elm->rxbuf[datastart + 3 * i]) << 4) |
0510             (hex_to_bin(elm->rxbuf[datastart + 3 * i + 1]));
0511     }
0512 
0513     /* Feed the frame to the network layer. */
0514     can327_feed_frame_to_netdev(elm, skb);
0515 
0516     return 0;
0517 }
0518 
0519 static void can327_parse_line(struct can327 *elm, size_t len)
0520 {
0521     lockdep_assert_held(&elm->lock);
0522 
0523     /* Skip empty lines */
0524     if (!len)
0525         return;
0526 
0527     /* Skip echo lines */
0528     if (elm->drop_next_line) {
0529         elm->drop_next_line = 0;
0530         return;
0531     } else if (!memcmp(elm->rxbuf, "AT", 2)) {
0532         return;
0533     }
0534 
0535     /* Regular parsing */
0536     if (elm->state == CAN327_STATE_RECEIVING &&
0537         can327_parse_frame(elm, len)) {
0538         /* Parse an error line. */
0539         can327_parse_error(elm, len);
0540 
0541         /* Start afresh. */
0542         can327_kick_into_cmd_mode(elm);
0543     }
0544 }
0545 
0546 static void can327_handle_prompt(struct can327 *elm)
0547 {
0548     struct can_frame *frame = &elm->can_frame_to_send;
0549     /* Size this buffer for the largest ELM327 line we may generate,
0550      * which is currently an 8 byte CAN frame's payload hexdump.
0551      * Items in can327_init_script must fit here, too!
0552      */
0553     char local_txbuf[sizeof("0102030405060708\r")];
0554 
0555     lockdep_assert_held(&elm->lock);
0556 
0557     if (!elm->cmds_todo) {
0558         /* Enter CAN monitor mode */
0559         can327_send(elm, "ATMA\r", 5);
0560         elm->state = CAN327_STATE_RECEIVING;
0561 
0562         /* We will be in the default state once this command is
0563          * sent, so enable the TX packet queue.
0564          */
0565         netif_wake_queue(elm->dev);
0566 
0567         return;
0568     }
0569 
0570     /* Reconfigure ELM327 step by step as indicated by elm->cmds_todo */
0571     if (test_bit(CAN327_TX_DO_INIT, &elm->cmds_todo)) {
0572         snprintf(local_txbuf, sizeof(local_txbuf), "%s",
0573              *elm->next_init_cmd);
0574 
0575         elm->next_init_cmd++;
0576         if (!(*elm->next_init_cmd)) {
0577             clear_bit(CAN327_TX_DO_INIT, &elm->cmds_todo);
0578             /* Init finished. */
0579         }
0580 
0581     } else if (test_and_clear_bit(CAN327_TX_DO_SILENT_MONITOR, &elm->cmds_todo)) {
0582         snprintf(local_txbuf, sizeof(local_txbuf),
0583              "ATCSM%i\r",
0584              !!(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY));
0585 
0586     } else if (test_and_clear_bit(CAN327_TX_DO_RESPONSES, &elm->cmds_todo)) {
0587         snprintf(local_txbuf, sizeof(local_txbuf),
0588              "ATR%i\r",
0589              !(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY));
0590 
0591     } else if (test_and_clear_bit(CAN327_TX_DO_CAN_CONFIG, &elm->cmds_todo)) {
0592         snprintf(local_txbuf, sizeof(local_txbuf),
0593              "ATPC\r");
0594         set_bit(CAN327_TX_DO_CAN_CONFIG_PART2, &elm->cmds_todo);
0595 
0596     } else if (test_and_clear_bit(CAN327_TX_DO_CAN_CONFIG_PART2, &elm->cmds_todo)) {
0597         snprintf(local_txbuf, sizeof(local_txbuf),
0598              "ATPB%04X\r",
0599              elm->can_config);
0600 
0601     } else if (test_and_clear_bit(CAN327_TX_DO_CANID_29BIT_HIGH, &elm->cmds_todo)) {
0602         snprintf(local_txbuf, sizeof(local_txbuf),
0603              "ATCP%02X\r",
0604              (frame->can_id & CAN_EFF_MASK) >> 24);
0605 
0606     } else if (test_and_clear_bit(CAN327_TX_DO_CANID_29BIT_LOW, &elm->cmds_todo)) {
0607         snprintf(local_txbuf, sizeof(local_txbuf),
0608              "ATSH%06X\r",
0609              frame->can_id & CAN_EFF_MASK & ((1 << 24) - 1));
0610 
0611     } else if (test_and_clear_bit(CAN327_TX_DO_CANID_11BIT, &elm->cmds_todo)) {
0612         snprintf(local_txbuf, sizeof(local_txbuf),
0613              "ATSH%03X\r",
0614              frame->can_id & CAN_SFF_MASK);
0615 
0616     } else if (test_and_clear_bit(CAN327_TX_DO_CAN_DATA, &elm->cmds_todo)) {
0617         if (frame->can_id & CAN_RTR_FLAG) {
0618             /* Send an RTR frame. Their DLC is fixed.
0619              * Some chips don't send them at all.
0620              */
0621             snprintf(local_txbuf, sizeof(local_txbuf), "ATRTR\r");
0622         } else {
0623             /* Send a regular CAN data frame */
0624             int i;
0625 
0626             for (i = 0; i < frame->len; i++) {
0627                 snprintf(&local_txbuf[2 * i],
0628                      sizeof(local_txbuf), "%02X",
0629                      frame->data[i]);
0630             }
0631 
0632             snprintf(&local_txbuf[2 * i], sizeof(local_txbuf),
0633                  "\r");
0634         }
0635 
0636         elm->drop_next_line = 1;
0637         elm->state = CAN327_STATE_RECEIVING;
0638 
0639         /* We will be in the default state once this command is
0640          * sent, so enable the TX packet queue.
0641          */
0642         netif_wake_queue(elm->dev);
0643     }
0644 
0645     can327_send(elm, local_txbuf, strlen(local_txbuf));
0646 }
0647 
0648 static bool can327_is_ready_char(char c)
0649 {
0650     /* Bits 0xc0 are sometimes set (randomly), hence the mask.
0651      * Probably bad hardware.
0652      */
0653     return (c & 0x3f) == CAN327_READY_CHAR;
0654 }
0655 
0656 static void can327_drop_bytes(struct can327 *elm, size_t i)
0657 {
0658     lockdep_assert_held(&elm->lock);
0659 
0660     memmove(&elm->rxbuf[0], &elm->rxbuf[i], CAN327_SIZE_RXBUF - i);
0661     elm->rxfill -= i;
0662 }
0663 
0664 static void can327_parse_rxbuf(struct can327 *elm, size_t first_new_char_idx)
0665 {
0666     size_t len, pos;
0667 
0668     lockdep_assert_held(&elm->lock);
0669 
0670     switch (elm->state) {
0671     case CAN327_STATE_NOTINIT:
0672         elm->rxfill = 0;
0673         break;
0674 
0675     case CAN327_STATE_GETDUMMYCHAR:
0676         /* Wait for 'y' or '>' */
0677         for (pos = 0; pos < elm->rxfill; pos++) {
0678             if (elm->rxbuf[pos] == CAN327_DUMMY_CHAR) {
0679                 can327_send(elm, "\r", 1);
0680                 elm->state = CAN327_STATE_GETPROMPT;
0681                 pos++;
0682                 break;
0683             } else if (can327_is_ready_char(elm->rxbuf[pos])) {
0684                 can327_send(elm, CAN327_DUMMY_STRING, 1);
0685                 pos++;
0686                 break;
0687             }
0688         }
0689 
0690         can327_drop_bytes(elm, pos);
0691         break;
0692 
0693     case CAN327_STATE_GETPROMPT:
0694         /* Wait for '>' */
0695         if (can327_is_ready_char(elm->rxbuf[elm->rxfill - 1]))
0696             can327_handle_prompt(elm);
0697 
0698         elm->rxfill = 0;
0699         break;
0700 
0701     case CAN327_STATE_RECEIVING:
0702         /* Find <CR> delimiting feedback lines. */
0703         len = first_new_char_idx;
0704         while (len < elm->rxfill && elm->rxbuf[len] != '\r')
0705             len++;
0706 
0707         if (len == CAN327_SIZE_RXBUF) {
0708             /* Assume the buffer ran full with garbage.
0709              * Did we even connect at the right baud rate?
0710              */
0711             netdev_err(elm->dev,
0712                    "RX buffer overflow. Faulty ELM327 or UART?\n");
0713             can327_uart_side_failure(elm);
0714         } else if (len == elm->rxfill) {
0715             if (can327_is_ready_char(elm->rxbuf[elm->rxfill - 1])) {
0716                 /* The ELM327's AT ST response timeout ran out,
0717                  * so we got a prompt.
0718                  * Clear RX buffer and restart listening.
0719                  */
0720                 elm->rxfill = 0;
0721 
0722                 can327_handle_prompt(elm);
0723             }
0724 
0725             /* No <CR> found - we haven't received a full line yet.
0726              * Wait for more data.
0727              */
0728         } else {
0729             /* We have a full line to parse. */
0730             can327_parse_line(elm, len);
0731 
0732             /* Remove parsed data from RX buffer. */
0733             can327_drop_bytes(elm, len + 1);
0734 
0735             /* More data to parse? */
0736             if (elm->rxfill)
0737                 can327_parse_rxbuf(elm, 0);
0738         }
0739     }
0740 }
0741 
0742 static int can327_netdev_open(struct net_device *dev)
0743 {
0744     struct can327 *elm = netdev_priv(dev);
0745     int err;
0746 
0747     spin_lock_bh(&elm->lock);
0748 
0749     if (!elm->tty) {
0750         spin_unlock_bh(&elm->lock);
0751         return -ENODEV;
0752     }
0753 
0754     if (elm->uart_side_failure)
0755         netdev_warn(elm->dev,
0756                 "Reopening netdev after a UART side fault has been detected.\n");
0757 
0758     /* Clear TTY buffers */
0759     elm->rxfill = 0;
0760     elm->txleft = 0;
0761 
0762     /* open_candev() checks for elm->can.bittiming.bitrate != 0 */
0763     err = open_candev(dev);
0764     if (err) {
0765         spin_unlock_bh(&elm->lock);
0766         return err;
0767     }
0768 
0769     can327_init_device(elm);
0770     spin_unlock_bh(&elm->lock);
0771 
0772     err = can_rx_offload_add_manual(dev, &elm->offload, CAN327_NAPI_WEIGHT);
0773     if (err) {
0774         close_candev(dev);
0775         return err;
0776     }
0777 
0778     can_rx_offload_enable(&elm->offload);
0779 
0780     elm->can.state = CAN_STATE_ERROR_ACTIVE;
0781     netif_start_queue(dev);
0782 
0783     return 0;
0784 }
0785 
0786 static int can327_netdev_close(struct net_device *dev)
0787 {
0788     struct can327 *elm = netdev_priv(dev);
0789 
0790     /* Interrupt whatever the ELM327 is doing right now */
0791     spin_lock_bh(&elm->lock);
0792     can327_send(elm, CAN327_DUMMY_STRING, 1);
0793     spin_unlock_bh(&elm->lock);
0794 
0795     netif_stop_queue(dev);
0796 
0797     /* Give UART one final chance to flush. */
0798     clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
0799     flush_work(&elm->tx_work);
0800 
0801     can_rx_offload_disable(&elm->offload);
0802     elm->can.state = CAN_STATE_STOPPED;
0803     can_rx_offload_del(&elm->offload);
0804     close_candev(dev);
0805 
0806     return 0;
0807 }
0808 
0809 /* Send a can_frame to a TTY. */
0810 static netdev_tx_t can327_netdev_start_xmit(struct sk_buff *skb,
0811                         struct net_device *dev)
0812 {
0813     struct can327 *elm = netdev_priv(dev);
0814     struct can_frame *frame = (struct can_frame *)skb->data;
0815 
0816     if (can_dropped_invalid_skb(dev, skb))
0817         return NETDEV_TX_OK;
0818 
0819     /* We shouldn't get here after a hardware fault:
0820      * can_bus_off() calls netif_carrier_off()
0821      */
0822     if (elm->uart_side_failure) {
0823         WARN_ON_ONCE(elm->uart_side_failure);
0824         goto out;
0825     }
0826 
0827     netif_stop_queue(dev);
0828 
0829     /* BHs are already disabled, so no spin_lock_bh().
0830      * See Documentation/networking/netdevices.rst
0831      */
0832     spin_lock(&elm->lock);
0833     can327_send_frame(elm, frame);
0834     spin_unlock(&elm->lock);
0835 
0836     dev->stats.tx_packets++;
0837     dev->stats.tx_bytes += frame->can_id & CAN_RTR_FLAG ? 0 : frame->len;
0838 
0839     skb_tx_timestamp(skb);
0840 
0841 out:
0842     kfree_skb(skb);
0843     return NETDEV_TX_OK;
0844 }
0845 
0846 static const struct net_device_ops can327_netdev_ops = {
0847     .ndo_open = can327_netdev_open,
0848     .ndo_stop = can327_netdev_close,
0849     .ndo_start_xmit = can327_netdev_start_xmit,
0850     .ndo_change_mtu = can_change_mtu,
0851 };
0852 
0853 static const struct ethtool_ops can327_ethtool_ops = {
0854     .get_ts_info = ethtool_op_get_ts_info,
0855 };
0856 
0857 static bool can327_is_valid_rx_char(u8 c)
0858 {
0859     static const bool lut_char_is_valid['z'] = {
0860         ['\r'] = true,
0861         [' '] = true,
0862         ['.'] = true,
0863         ['0'] = true, true, true, true, true,
0864         ['5'] = true, true, true, true, true,
0865         ['<'] = true,
0866         [CAN327_READY_CHAR] = true,
0867         ['?'] = true,
0868         ['A'] = true, true, true, true, true, true, true,
0869         ['H'] = true, true, true, true, true, true, true,
0870         ['O'] = true, true, true, true, true, true, true,
0871         ['V'] = true, true, true, true, true,
0872         ['a'] = true,
0873         ['b'] = true,
0874         ['v'] = true,
0875         [CAN327_DUMMY_CHAR] = true,
0876     };
0877     BUILD_BUG_ON(CAN327_DUMMY_CHAR >= 'z');
0878 
0879     return (c < ARRAY_SIZE(lut_char_is_valid) && lut_char_is_valid[c]);
0880 }
0881 
0882 /* Handle incoming ELM327 ASCII data.
0883  * This will not be re-entered while running, but other ldisc
0884  * functions may be called in parallel.
0885  */
0886 static void can327_ldisc_rx(struct tty_struct *tty, const unsigned char *cp,
0887                 const char *fp, int count)
0888 {
0889     struct can327 *elm = (struct can327 *)tty->disc_data;
0890     size_t first_new_char_idx;
0891 
0892     if (elm->uart_side_failure)
0893         return;
0894 
0895     spin_lock_bh(&elm->lock);
0896 
0897     /* Store old rxfill, so can327_parse_rxbuf() will have
0898      * the option of skipping already checked characters.
0899      */
0900     first_new_char_idx = elm->rxfill;
0901 
0902     while (count-- && elm->rxfill < CAN327_SIZE_RXBUF) {
0903         if (fp && *fp++) {
0904             netdev_err(elm->dev,
0905                    "Error in received character stream. Check your wiring.");
0906 
0907             can327_uart_side_failure(elm);
0908 
0909             spin_unlock_bh(&elm->lock);
0910             return;
0911         }
0912 
0913         /* Ignore NUL characters, which the PIC microcontroller may
0914          * inadvertently insert due to a known hardware bug.
0915          * See ELM327 documentation, which refers to a Microchip PIC
0916          * bug description.
0917          */
0918         if (*cp) {
0919             /* Check for stray characters on the UART line.
0920              * Likely caused by bad hardware.
0921              */
0922             if (!can327_is_valid_rx_char(*cp)) {
0923                 netdev_err(elm->dev,
0924                        "Received illegal character %02x.\n",
0925                        *cp);
0926                 can327_uart_side_failure(elm);
0927 
0928                 spin_unlock_bh(&elm->lock);
0929                 return;
0930             }
0931 
0932             elm->rxbuf[elm->rxfill++] = *cp;
0933         }
0934 
0935         cp++;
0936     }
0937 
0938     if (count >= 0) {
0939         netdev_err(elm->dev,
0940                "Receive buffer overflowed. Bad chip or wiring? count = %i",
0941                count);
0942 
0943         can327_uart_side_failure(elm);
0944 
0945         spin_unlock_bh(&elm->lock);
0946         return;
0947     }
0948 
0949     can327_parse_rxbuf(elm, first_new_char_idx);
0950     spin_unlock_bh(&elm->lock);
0951 }
0952 
0953 /* Write out remaining transmit buffer.
0954  * Scheduled when TTY is writable.
0955  */
0956 static void can327_ldisc_tx_worker(struct work_struct *work)
0957 {
0958     struct can327 *elm = container_of(work, struct can327, tx_work);
0959     ssize_t written;
0960 
0961     if (elm->uart_side_failure)
0962         return;
0963 
0964     spin_lock_bh(&elm->lock);
0965 
0966     if (elm->txleft) {
0967         written = elm->tty->ops->write(elm->tty, elm->txhead,
0968                            elm->txleft);
0969         if (written < 0) {
0970             netdev_err(elm->dev, "Failed to write to tty %s.\n",
0971                    elm->tty->name);
0972             can327_uart_side_failure(elm);
0973 
0974             spin_unlock_bh(&elm->lock);
0975             return;
0976         }
0977 
0978         elm->txleft -= written;
0979         elm->txhead += written;
0980     }
0981 
0982     if (!elm->txleft)
0983         clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
0984 
0985     spin_unlock_bh(&elm->lock);
0986 }
0987 
0988 /* Called by the driver when there's room for more data. */
0989 static void can327_ldisc_tx_wakeup(struct tty_struct *tty)
0990 {
0991     struct can327 *elm = (struct can327 *)tty->disc_data;
0992 
0993     schedule_work(&elm->tx_work);
0994 }
0995 
0996 /* ELM327 can only handle bitrates that are integer divisors of 500 kHz,
0997  * or 7/8 of that. Divisors are 1 to 64.
0998  * Currently we don't implement support for 7/8 rates.
0999  */
1000 static const u32 can327_bitrate_const[] = {
1001     7812,  7936,  8064,  8196,   8333,   8474,   8620,   8771,
1002     8928,  9090,  9259,  9433,   9615,   9803,   10000,  10204,
1003     10416, 10638, 10869, 11111,  11363,  11627,  11904,  12195,
1004     12500, 12820, 13157, 13513,  13888,  14285,  14705,  15151,
1005     15625, 16129, 16666, 17241,  17857,  18518,  19230,  20000,
1006     20833, 21739, 22727, 23809,  25000,  26315,  27777,  29411,
1007     31250, 33333, 35714, 38461,  41666,  45454,  50000,  55555,
1008     62500, 71428, 83333, 100000, 125000, 166666, 250000, 500000
1009 };
1010 
1011 static int can327_ldisc_open(struct tty_struct *tty)
1012 {
1013     struct net_device *dev;
1014     struct can327 *elm;
1015     int err;
1016 
1017     if (!capable(CAP_NET_ADMIN))
1018         return -EPERM;
1019 
1020     if (!tty->ops->write)
1021         return -EOPNOTSUPP;
1022 
1023     dev = alloc_candev(sizeof(struct can327), 0);
1024     if (!dev)
1025         return -ENFILE;
1026     elm = netdev_priv(dev);
1027 
1028     /* Configure TTY interface */
1029     tty->receive_room = 65536; /* We don't flow control */
1030     spin_lock_init(&elm->lock);
1031     INIT_WORK(&elm->tx_work, can327_ldisc_tx_worker);
1032 
1033     /* Configure CAN metadata */
1034     elm->can.bitrate_const = can327_bitrate_const;
1035     elm->can.bitrate_const_cnt = ARRAY_SIZE(can327_bitrate_const);
1036     elm->can.ctrlmode_supported = CAN_CTRLMODE_LISTENONLY;
1037 
1038     /* Configure netdev interface */
1039     elm->dev = dev;
1040     dev->netdev_ops = &can327_netdev_ops;
1041     dev->ethtool_ops = &can327_ethtool_ops;
1042 
1043     /* Mark ldisc channel as alive */
1044     elm->tty = tty;
1045     tty->disc_data = elm;
1046 
1047     /* Let 'er rip */
1048     err = register_candev(elm->dev);
1049     if (err) {
1050         free_candev(elm->dev);
1051         return err;
1052     }
1053 
1054     netdev_info(elm->dev, "can327 on %s.\n", tty->name);
1055 
1056     return 0;
1057 }
1058 
1059 /* Close down a can327 channel.
1060  * This means flushing out any pending queues, and then returning.
1061  * This call is serialized against other ldisc functions:
1062  * Once this is called, no other ldisc function of ours is entered.
1063  *
1064  * We also use this function for a hangup event.
1065  */
1066 static void can327_ldisc_close(struct tty_struct *tty)
1067 {
1068     struct can327 *elm = (struct can327 *)tty->disc_data;
1069 
1070     /* unregister_netdev() calls .ndo_stop() so we don't have to.
1071      * Our .ndo_stop() also flushes the TTY write wakeup handler,
1072      * so we can safely set elm->tty = NULL after this.
1073      */
1074     unregister_candev(elm->dev);
1075 
1076     /* Mark channel as dead */
1077     spin_lock_bh(&elm->lock);
1078     tty->disc_data = NULL;
1079     elm->tty = NULL;
1080     spin_unlock_bh(&elm->lock);
1081 
1082     netdev_info(elm->dev, "can327 off %s.\n", tty->name);
1083 
1084     free_candev(elm->dev);
1085 }
1086 
1087 static int can327_ldisc_ioctl(struct tty_struct *tty, unsigned int cmd,
1088                   unsigned long arg)
1089 {
1090     struct can327 *elm = (struct can327 *)tty->disc_data;
1091     unsigned int tmp;
1092 
1093     switch (cmd) {
1094     case SIOCGIFNAME:
1095         tmp = strnlen(elm->dev->name, IFNAMSIZ - 1) + 1;
1096         if (copy_to_user((void __user *)arg, elm->dev->name, tmp))
1097             return -EFAULT;
1098         return 0;
1099 
1100     case SIOCSIFHWADDR:
1101         return -EINVAL;
1102 
1103     default:
1104         return tty_mode_ioctl(tty, cmd, arg);
1105     }
1106 }
1107 
1108 static struct tty_ldisc_ops can327_ldisc = {
1109     .owner = THIS_MODULE,
1110     .name = KBUILD_MODNAME,
1111     .num = N_CAN327,
1112     .receive_buf = can327_ldisc_rx,
1113     .write_wakeup = can327_ldisc_tx_wakeup,
1114     .open = can327_ldisc_open,
1115     .close = can327_ldisc_close,
1116     .ioctl = can327_ldisc_ioctl,
1117 };
1118 
1119 static int __init can327_init(void)
1120 {
1121     int status;
1122 
1123     status = tty_register_ldisc(&can327_ldisc);
1124     if (status)
1125         pr_err("Can't register line discipline\n");
1126 
1127     return status;
1128 }
1129 
1130 static void __exit can327_exit(void)
1131 {
1132     /* This will only be called when all channels have been closed by
1133      * userspace - tty_ldisc.c takes care of the module's refcount.
1134      */
1135     tty_unregister_ldisc(&can327_ldisc);
1136 }
1137 
1138 module_init(can327_init);
1139 module_exit(can327_exit);
1140 
1141 MODULE_ALIAS_LDISC(N_CAN327);
1142 MODULE_DESCRIPTION("ELM327 based CAN interface");
1143 MODULE_LICENSE("GPL");
1144 MODULE_AUTHOR("Max Staudt <max@enpas.org>");