Linux kernel mirror (for testing) git.kernel.org/pub/scm/linux/kernel/git/torvalds/linux.git
kernel os linux

can: can327: CAN/ldisc driver for ELM327 based OBD-II adapters

This is the can327 driver. It does a surprisingly good job at turning
ELM327 based OBD-II interfaces into cheap CAN interfaces for simple
homebrew projects.

Please see the included documentation for details and limitations:
Documentation/networking/device_drivers/can/can327.rst

Link: https://lore.kernel.org/all/20220618195031.10975-1-max@enpas.org
Signed-off-by: Max Staudt <max@enpas.org>
Reviewed-by: Vincent Mailhol <mailhol.vincent@wanadoo.fr>
[mkl: minor coding style improvements]
Signed-off-by: Marc Kleine-Budde <mkl@pengutronix.de>

authored by

Max Staudt and committed by
Marc Kleine-Budde
43da2f07 713eb3c1

+1495
+331
Documentation/networking/device_drivers/can/can327.rst
··· 1 + .. SPDX-License-Identifier: (GPL-2.0-only OR BSD-3-Clause) 2 + 3 + can327: ELM327 driver for Linux SocketCAN 4 + ========================================== 5 + 6 + Authors 7 + -------- 8 + 9 + Max Staudt <max@enpas.org> 10 + 11 + 12 + 13 + Motivation 14 + ----------- 15 + 16 + This driver aims to lower the initial cost for hackers interested in 17 + working with CAN buses. 18 + 19 + CAN adapters are expensive, few, and far between. 20 + ELM327 interfaces are cheap and plentiful. 21 + Let's use ELM327s as CAN adapters. 22 + 23 + 24 + 25 + Introduction 26 + ------------- 27 + 28 + This driver is an effort to turn abundant ELM327 based OBD interfaces 29 + into full fledged (as far as possible) CAN interfaces. 30 + 31 + Since the ELM327 was never meant to be a stand alone CAN controller, 32 + the driver has to switch between its modes as quickly as possible in 33 + order to fake full-duplex operation. 34 + 35 + As such, can327 is a best effort driver. However, this is more than 36 + enough to implement simple request-response protocols (such as OBD II), 37 + and to monitor broadcast messages on a bus (such as in a vehicle). 38 + 39 + Most ELM327s come as nondescript serial devices, attached via USB or 40 + Bluetooth. The driver cannot recognize them by itself, and as such it 41 + is up to the user to attach it in form of a TTY line discipline 42 + (similar to PPP, SLIP, slcan, ...). 43 + 44 + This driver is meant for ELM327 versions 1.4b and up, see below for 45 + known limitations in older controllers and clones. 46 + 47 + 48 + 49 + Data sheet 50 + ----------- 51 + 52 + The official data sheets can be found at ELM electronics' home page: 53 + 54 + https://www.elmelectronics.com/ 55 + 56 + 57 + 58 + How to attach the line discipline 59 + ---------------------------------- 60 + 61 + Every ELM327 chip is factory programmed to operate at a serial setting 62 + of 38400 baud/s, 8 data bits, no parity, 1 stopbit. 63 + 64 + If you have kept this default configuration, the line discipline can 65 + be attached on a command prompt as follows:: 66 + 67 + sudo ldattach \ 68 + --debug \ 69 + --speed 38400 \ 70 + --eightbits \ 71 + --noparity \ 72 + --onestopbit \ 73 + --iflag -ICRNL,INLCR,-IXOFF \ 74 + 30 \ 75 + /dev/ttyUSB0 76 + 77 + To change the ELM327's serial settings, please refer to its data 78 + sheet. This needs to be done before attaching the line discipline. 79 + 80 + Once the ldisc is attached, the CAN interface starts out unconfigured. 81 + Set the speed before starting it:: 82 + 83 + # The interface needs to be down to change parameters 84 + sudo ip link set can0 down 85 + sudo ip link set can0 type can bitrate 500000 86 + sudo ip link set can0 up 87 + 88 + 500000 bit/s is a common rate for OBD-II diagnostics. 89 + If you're connecting straight to a car's OBD port, this is the speed 90 + that most cars (but not all!) expect. 91 + 92 + After this, you can set out as usual with candump, cansniffer, etc. 93 + 94 + 95 + 96 + How to check the controller version 97 + ------------------------------------ 98 + 99 + Use a terminal program to attach to the controller. 100 + 101 + After issuing the "``AT WS``" command, the controller will respond with 102 + its version:: 103 + 104 + >AT WS 105 + 106 + 107 + ELM327 v1.4b 108 + 109 + > 110 + 111 + Note that clones may claim to be any version they like. 112 + It is not indicative of their actual feature set. 113 + 114 + 115 + 116 + 117 + Communication example 118 + ---------------------- 119 + 120 + This is a short and incomplete introduction on how to talk to an ELM327. 121 + It is here to guide understanding of the controller's and the driver's 122 + limitation (listed below) as well as manual testing. 123 + 124 + 125 + The ELM327 has two modes: 126 + 127 + - Command mode 128 + - Reception mode 129 + 130 + In command mode, it expects one command per line, terminated by CR. 131 + By default, the prompt is a "``>``", after which a command can be 132 + entered:: 133 + 134 + >ATE1 135 + OK 136 + > 137 + 138 + The init script in the driver switches off several configuration options 139 + that are only meaningful in the original OBD scenario the chip is meant 140 + for, and are actually a hindrance for can327. 141 + 142 + 143 + When a command is not recognized, such as by an older version of the 144 + ELM327, a question mark is printed as a response instead of OK:: 145 + 146 + >ATUNKNOWN 147 + ? 148 + > 149 + 150 + At present, can327 does not evaluate this response. See the section 151 + below on known limitations for details. 152 + 153 + 154 + When a CAN frame is to be sent, the target address is configured, after 155 + which the frame is sent as a command that consists of the data's hex 156 + dump:: 157 + 158 + >ATSH123 159 + OK 160 + >DEADBEEF12345678 161 + OK 162 + > 163 + 164 + The above interaction sends the SFF frame "``DE AD BE EF 12 34 56 78``" 165 + with (11 bit) CAN ID ``0x123``. 166 + For this to function, the controller must be configured for SFF sending 167 + mode (using "``AT PB``", see code or datasheet). 168 + 169 + 170 + Once a frame has been sent and wait-for-reply mode is on (``ATR1``, 171 + configured on ``listen-only=off``), or when the reply timeout expires 172 + and the driver sets the controller into monitoring mode (``ATMA``), 173 + the ELM327 will send one line for each received CAN frame, consisting 174 + of CAN ID, DLC, and data:: 175 + 176 + 123 8 DEADBEEF12345678 177 + 178 + For EFF (29 bit) CAN frames, the address format is slightly different, 179 + which can327 uses to tell the two apart:: 180 + 181 + 12 34 56 78 8 DEADBEEF12345678 182 + 183 + The ELM327 will receive both SFF and EFF frames - the current CAN 184 + config (``ATPB``) does not matter. 185 + 186 + 187 + If the ELM327's internal UART sending buffer runs full, it will abort 188 + the monitoring mode, print "BUFFER FULL" and drop back into command 189 + mode. Note that in this case, unlike with other error messages, the 190 + error message may appear on the same line as the last (usually 191 + incomplete) data frame:: 192 + 193 + 12 34 56 78 8 DEADBEEF123 BUFFER FULL 194 + 195 + 196 + 197 + Known limitations of the controller 198 + ------------------------------------ 199 + 200 + - Clone devices ("v1.5" and others) 201 + 202 + Sending RTR frames is not supported and will be dropped silently. 203 + 204 + Receiving RTR with DLC 8 will appear to be a regular frame with 205 + the last received frame's DLC and payload. 206 + 207 + "``AT CSM``" (CAN Silent Monitoring, i.e. don't send CAN ACKs) is 208 + not supported, and is hard coded to ON. Thus, frames are not ACKed 209 + while listening: "``AT MA``" (Monitor All) will always be "silent". 210 + However, immediately after sending a frame, the ELM327 will be in 211 + "receive reply" mode, in which it *does* ACK any received frames. 212 + Once the bus goes silent, or an error occurs (such as BUFFER FULL), 213 + or the receive reply timeout runs out, the ELM327 will end reply 214 + reception mode on its own and can327 will fall back to "``AT MA``" 215 + in order to keep monitoring the bus. 216 + 217 + Other limitations may apply, depending on the clone and the quality 218 + of its firmware. 219 + 220 + 221 + - All versions 222 + 223 + No full duplex operation is supported. The driver will switch 224 + between input/output mode as quickly as possible. 225 + 226 + The length of outgoing RTR frames cannot be set. In fact, some 227 + clones (tested with one identifying as "``v1.5``") are unable to 228 + send RTR frames at all. 229 + 230 + We don't have a way to get real-time notifications on CAN errors. 231 + While there is a command (``AT CS``) to retrieve some basic stats, 232 + we don't poll it as it would force us to interrupt reception mode. 233 + 234 + 235 + - Versions prior to 1.4b 236 + 237 + These versions do not send CAN ACKs when in monitoring mode (AT MA). 238 + However, they do send ACKs while waiting for a reply immediately 239 + after sending a frame. The driver maximizes this time to make the 240 + controller as useful as possible. 241 + 242 + Starting with version 1.4b, the ELM327 supports the "``AT CSM``" 243 + command, and the "listen-only" CAN option will take effect. 244 + 245 + 246 + - Versions prior to 1.4 247 + 248 + These chips do not support the "``AT PB``" command, and thus cannot 249 + change bitrate or SFF/EFF mode on-the-fly. This will have to be 250 + programmed by the user before attaching the line discipline. See the 251 + data sheet for details. 252 + 253 + 254 + - Versions prior to 1.3 255 + 256 + These chips cannot be used at all with can327. They do not support 257 + the "``AT D1``" command, which is necessary to avoid parsing conflicts 258 + on incoming data, as well as distinction of RTR frame lengths. 259 + 260 + Specifically, this allows for easy distinction of SFF and EFF 261 + frames, and to check whether frames are complete. While it is possible 262 + to deduce the type and length from the length of the line the ELM327 263 + sends us, this method fails when the ELM327's UART output buffer 264 + overruns. It may abort sending in the middle of the line, which will 265 + then be mistaken for something else. 266 + 267 + 268 + 269 + Known limitations of the driver 270 + -------------------------------- 271 + 272 + - No 8/7 timing. 273 + 274 + ELM327 can only set CAN bitrates that are of the form 500000/n, where 275 + n is an integer divisor. 276 + However there is an exception: With a separate flag, it may set the 277 + speed to be 8/7 of the speed indicated by the divisor. 278 + This mode is not currently implemented. 279 + 280 + - No evaluation of command responses. 281 + 282 + The ELM327 will reply with OK when a command is understood, and with ? 283 + when it is not. The driver does not currently check this, and simply 284 + assumes that the chip understands every command. 285 + The driver is built such that functionality degrades gracefully 286 + nevertheless. See the section on known limitations of the controller. 287 + 288 + - No use of hardware CAN ID filtering 289 + 290 + An ELM327's UART sending buffer will easily overflow on heavy CAN bus 291 + load, resulting in the "``BUFFER FULL``" message. Using the hardware 292 + filters available through "``AT CF xxx``" and "``AT CM xxx``" would be 293 + helpful here, however SocketCAN does not currently provide a facility 294 + to make use of such hardware features. 295 + 296 + 297 + 298 + Rationale behind the chosen configuration 299 + ------------------------------------------ 300 + 301 + ``AT E1`` 302 + Echo on 303 + 304 + We need this to be able to get a prompt reliably. 305 + 306 + ``AT S1`` 307 + Spaces on 308 + 309 + We need this to distinguish 11/29 bit CAN addresses received. 310 + 311 + Note: 312 + We can usually do this using the line length (odd/even), 313 + but this fails if the line is not transmitted fully to 314 + the host (BUFFER FULL). 315 + 316 + ``AT D1`` 317 + DLC on 318 + 319 + We need this to tell the "length" of RTR frames. 320 + 321 + 322 + 323 + A note on CAN bus termination 324 + ------------------------------ 325 + 326 + Your adapter may have resistors soldered in which are meant to terminate 327 + the bus. This is correct when it is plugged into a OBD-II socket, but 328 + not helpful when trying to tap into the middle of an existing CAN bus. 329 + 330 + If communications don't work with the adapter connected, check for the 331 + termination resistors on its PCB and try removing them.
+1
Documentation/networking/device_drivers/can/index.rst
··· 10 10 .. toctree:: 11 11 :maxdepth: 2 12 12 13 + can327 13 14 ctu/ctucanfd-driver 14 15 freescale/flexcan 15 16
+7
MAINTAINERS
··· 7315 7315 S: Maintained 7316 7316 F: drivers/net/ethernet/ibm/ehea/ 7317 7317 7318 + ELM327 CAN NETWORK DRIVER 7319 + M: Max Staudt <max@enpas.org> 7320 + L: linux-can@vger.kernel.org 7321 + S: Maintained 7322 + F: Documentation/networking/device_drivers/can/can327.rst 7323 + F: drivers/net/can/can327.c 7324 + 7318 7325 EM28XX VIDEO4LINUX DRIVER 7319 7326 M: Mauro Carvalho Chehab <mchehab@kernel.org> 7320 7327 L: linux-media@vger.kernel.org
+18
drivers/net/can/Kconfig
··· 113 113 This is a driver for the SoC CAN controller in Atmel's AT91SAM9263 114 114 and AT91SAM9X5 processors. 115 115 116 + config CAN_CAN327 117 + tristate "Serial / USB serial ELM327 based OBD-II Interfaces (can327)" 118 + depends on TTY 119 + select CAN_RX_OFFLOAD 120 + help 121 + CAN driver for several 'low cost' OBD-II interfaces based on the 122 + ELM327 OBD-II interpreter chip. 123 + 124 + This is a best effort driver - the ELM327 interface was never 125 + designed to be used as a standalone CAN interface. However, it can 126 + still be used for simple request-response protocols (such as OBD II), 127 + and to monitor broadcast messages on a bus (such as in a vehicle). 128 + 129 + Please refer to the documentation for information on how to use it: 130 + Documentation/networking/device_drivers/can/can327.rst 131 + 132 + If this driver is built as a module, it will be called can327. 133 + 116 134 config CAN_FLEXCAN 117 135 tristate "Support for Freescale FLEXCAN based chips" 118 136 depends on OF || COLDFIRE || COMPILE_TEST
+1
drivers/net/can/Makefile
··· 14 14 obj-y += softing/ 15 15 16 16 obj-$(CONFIG_CAN_AT91) += at91_can.o 17 + obj-$(CONFIG_CAN_CAN327) += can327.o 17 18 obj-$(CONFIG_CAN_CC770) += cc770/ 18 19 obj-$(CONFIG_CAN_C_CAN) += c_can/ 19 20 obj-$(CONFIG_CAN_CTUCANFD) += ctucanfd/
+1137
drivers/net/can/can327.c
··· 1 + // SPDX-License-Identifier: GPL-2.0 2 + /* ELM327 based CAN interface driver (tty line discipline) 3 + * 4 + * This driver started as a derivative of linux/drivers/net/can/slcan.c 5 + * and my thanks go to the original authors for their inspiration. 6 + * 7 + * can327.c Author : Max Staudt <max-linux@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 + 13 + #define pr_fmt(fmt) "can327: " fmt 14 + 15 + #include <linux/init.h> 16 + #include <linux/module.h> 17 + 18 + #include <linux/bitops.h> 19 + #include <linux/ctype.h> 20 + #include <linux/errno.h> 21 + #include <linux/kernel.h> 22 + #include <linux/list.h> 23 + #include <linux/lockdep.h> 24 + #include <linux/netdevice.h> 25 + #include <linux/skbuff.h> 26 + #include <linux/spinlock.h> 27 + #include <linux/string.h> 28 + #include <linux/tty.h> 29 + #include <linux/tty_ldisc.h> 30 + #include <linux/workqueue.h> 31 + 32 + #include <uapi/linux/tty.h> 33 + 34 + #include <linux/can.h> 35 + #include <linux/can/dev.h> 36 + #include <linux/can/error.h> 37 + #include <linux/can/rx-offload.h> 38 + 39 + #define CAN327_NAPI_WEIGHT 4 40 + 41 + #define CAN327_SIZE_TXBUF 32 42 + #define CAN327_SIZE_RXBUF 1024 43 + 44 + #define CAN327_CAN_CONFIG_SEND_SFF 0x8000 45 + #define CAN327_CAN_CONFIG_VARIABLE_DLC 0x4000 46 + #define CAN327_CAN_CONFIG_RECV_BOTH_SFF_EFF 0x2000 47 + #define CAN327_CAN_CONFIG_BAUDRATE_MULT_8_7 0x1000 48 + 49 + #define CAN327_DUMMY_CHAR 'y' 50 + #define CAN327_DUMMY_STRING "y" 51 + #define CAN327_READY_CHAR '>' 52 + 53 + /* Bits in elm->cmds_todo */ 54 + enum can327_tx_do { 55 + CAN327_TX_DO_CAN_DATA = 0, 56 + CAN327_TX_DO_CANID_11BIT, 57 + CAN327_TX_DO_CANID_29BIT_LOW, 58 + CAN327_TX_DO_CANID_29BIT_HIGH, 59 + CAN327_TX_DO_CAN_CONFIG_PART2, 60 + CAN327_TX_DO_CAN_CONFIG, 61 + CAN327_TX_DO_RESPONSES, 62 + CAN327_TX_DO_SILENT_MONITOR, 63 + CAN327_TX_DO_INIT, 64 + }; 65 + 66 + struct can327 { 67 + /* This must be the first member when using alloc_candev() */ 68 + struct can_priv can; 69 + 70 + struct can_rx_offload offload; 71 + 72 + /* TTY buffers */ 73 + u8 txbuf[CAN327_SIZE_TXBUF]; 74 + u8 rxbuf[CAN327_SIZE_RXBUF]; 75 + 76 + /* Per-channel lock */ 77 + spinlock_t lock; 78 + 79 + /* TTY and netdev devices that we're bridging */ 80 + struct tty_struct *tty; 81 + struct net_device *dev; 82 + 83 + /* TTY buffer accounting */ 84 + struct work_struct tx_work; /* Flushes TTY TX buffer */ 85 + u8 *txhead; /* Next TX byte */ 86 + size_t txleft; /* Bytes left to TX */ 87 + int rxfill; /* Bytes already RX'd in buffer */ 88 + 89 + /* State machine */ 90 + enum { 91 + CAN327_STATE_NOTINIT = 0, 92 + CAN327_STATE_GETDUMMYCHAR, 93 + CAN327_STATE_GETPROMPT, 94 + CAN327_STATE_RECEIVING, 95 + } state; 96 + 97 + /* Things we have yet to send */ 98 + char **next_init_cmd; 99 + unsigned long cmds_todo; 100 + 101 + /* The CAN frame and config the ELM327 is sending/using, 102 + * or will send/use after finishing all cmds_todo 103 + */ 104 + struct can_frame can_frame_to_send; 105 + u16 can_config; 106 + u8 can_bitrate_divisor; 107 + 108 + /* Parser state */ 109 + bool drop_next_line; 110 + 111 + /* Stop the channel on UART side hardware failure, e.g. stray 112 + * characters or neverending lines. This may be caused by bad 113 + * UART wiring, a bad ELM327, a bad UART bridge... 114 + * Once this is true, nothing will be sent to the TTY. 115 + */ 116 + bool uart_side_failure; 117 + }; 118 + 119 + static inline void can327_uart_side_failure(struct can327 *elm); 120 + 121 + static void can327_send(struct can327 *elm, const void *buf, size_t len) 122 + { 123 + int written; 124 + 125 + lockdep_assert_held(&elm->lock); 126 + 127 + if (elm->uart_side_failure) 128 + return; 129 + 130 + memcpy(elm->txbuf, buf, len); 131 + 132 + /* Order of next two lines is *very* important. 133 + * When we are sending a little amount of data, 134 + * the transfer may be completed inside the ops->write() 135 + * routine, because it's running with interrupts enabled. 136 + * In this case we *never* got WRITE_WAKEUP event, 137 + * if we did not request it before write operation. 138 + * 14 Oct 1994 Dmitry Gorodchanin. 139 + */ 140 + set_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags); 141 + written = elm->tty->ops->write(elm->tty, elm->txbuf, len); 142 + if (written < 0) { 143 + netdev_err(elm->dev, "Failed to write to tty %s.\n", 144 + elm->tty->name); 145 + can327_uart_side_failure(elm); 146 + return; 147 + } 148 + 149 + elm->txleft = len - written; 150 + elm->txhead = elm->txbuf + written; 151 + } 152 + 153 + /* Take the ELM327 out of almost any state and back into command mode. 154 + * We send CAN327_DUMMY_CHAR which will either abort any running 155 + * operation, or be echoed back to us in case we're already in command 156 + * mode. 157 + */ 158 + static void can327_kick_into_cmd_mode(struct can327 *elm) 159 + { 160 + lockdep_assert_held(&elm->lock); 161 + 162 + if (elm->state != CAN327_STATE_GETDUMMYCHAR && 163 + elm->state != CAN327_STATE_GETPROMPT) { 164 + can327_send(elm, CAN327_DUMMY_STRING, 1); 165 + 166 + elm->state = CAN327_STATE_GETDUMMYCHAR; 167 + } 168 + } 169 + 170 + /* Schedule a CAN frame and necessary config changes to be sent to the TTY. */ 171 + static void can327_send_frame(struct can327 *elm, struct can_frame *frame) 172 + { 173 + lockdep_assert_held(&elm->lock); 174 + 175 + /* Schedule any necessary changes in ELM327's CAN configuration */ 176 + if (elm->can_frame_to_send.can_id != frame->can_id) { 177 + /* Set the new CAN ID for transmission. */ 178 + if ((frame->can_id ^ elm->can_frame_to_send.can_id) 179 + & CAN_EFF_FLAG) { 180 + elm->can_config = 181 + (frame->can_id & CAN_EFF_FLAG ? 0 : CAN327_CAN_CONFIG_SEND_SFF) | 182 + CAN327_CAN_CONFIG_VARIABLE_DLC | 183 + CAN327_CAN_CONFIG_RECV_BOTH_SFF_EFF | 184 + elm->can_bitrate_divisor; 185 + 186 + set_bit(CAN327_TX_DO_CAN_CONFIG, &elm->cmds_todo); 187 + } 188 + 189 + if (frame->can_id & CAN_EFF_FLAG) { 190 + clear_bit(CAN327_TX_DO_CANID_11BIT, &elm->cmds_todo); 191 + set_bit(CAN327_TX_DO_CANID_29BIT_LOW, &elm->cmds_todo); 192 + set_bit(CAN327_TX_DO_CANID_29BIT_HIGH, &elm->cmds_todo); 193 + } else { 194 + set_bit(CAN327_TX_DO_CANID_11BIT, &elm->cmds_todo); 195 + clear_bit(CAN327_TX_DO_CANID_29BIT_LOW, 196 + &elm->cmds_todo); 197 + clear_bit(CAN327_TX_DO_CANID_29BIT_HIGH, 198 + &elm->cmds_todo); 199 + } 200 + } 201 + 202 + /* Schedule the CAN frame itself. */ 203 + elm->can_frame_to_send = *frame; 204 + set_bit(CAN327_TX_DO_CAN_DATA, &elm->cmds_todo); 205 + 206 + can327_kick_into_cmd_mode(elm); 207 + } 208 + 209 + /* ELM327 initialisation sequence. 210 + * The line length is limited by the buffer in can327_handle_prompt(). 211 + */ 212 + static char *can327_init_script[] = { 213 + "AT WS\r", /* v1.0: Warm Start */ 214 + "AT PP FF OFF\r", /* v1.0: All Programmable Parameters Off */ 215 + "AT M0\r", /* v1.0: Memory Off */ 216 + "AT AL\r", /* v1.0: Allow Long messages */ 217 + "AT BI\r", /* v1.0: Bypass Initialisation */ 218 + "AT CAF0\r", /* v1.0: CAN Auto Formatting Off */ 219 + "AT CFC0\r", /* v1.0: CAN Flow Control Off */ 220 + "AT CF 000\r", /* v1.0: Reset CAN ID Filter */ 221 + "AT CM 000\r", /* v1.0: Reset CAN ID Mask */ 222 + "AT E1\r", /* v1.0: Echo On */ 223 + "AT H1\r", /* v1.0: Headers On */ 224 + "AT L0\r", /* v1.0: Linefeeds Off */ 225 + "AT SH 7DF\r", /* v1.0: Set CAN sending ID to 0x7df */ 226 + "AT ST FF\r", /* v1.0: Set maximum Timeout for response after TX */ 227 + "AT AT0\r", /* v1.2: Adaptive Timing Off */ 228 + "AT D1\r", /* v1.3: Print DLC On */ 229 + "AT S1\r", /* v1.3: Spaces On */ 230 + "AT TP B\r", /* v1.0: Try Protocol B */ 231 + NULL 232 + }; 233 + 234 + static void can327_init_device(struct can327 *elm) 235 + { 236 + lockdep_assert_held(&elm->lock); 237 + 238 + elm->state = CAN327_STATE_NOTINIT; 239 + elm->can_frame_to_send.can_id = 0x7df; /* ELM327 HW default */ 240 + elm->rxfill = 0; 241 + elm->drop_next_line = 0; 242 + 243 + /* We can only set the bitrate as a fraction of 500000. 244 + * The bitrates listed in can327_bitrate_const will 245 + * limit the user to the right values. 246 + */ 247 + elm->can_bitrate_divisor = 500000 / elm->can.bittiming.bitrate; 248 + elm->can_config = 249 + CAN327_CAN_CONFIG_SEND_SFF | CAN327_CAN_CONFIG_VARIABLE_DLC | 250 + CAN327_CAN_CONFIG_RECV_BOTH_SFF_EFF | elm->can_bitrate_divisor; 251 + 252 + /* Configure ELM327 and then start monitoring */ 253 + elm->next_init_cmd = &can327_init_script[0]; 254 + set_bit(CAN327_TX_DO_INIT, &elm->cmds_todo); 255 + set_bit(CAN327_TX_DO_SILENT_MONITOR, &elm->cmds_todo); 256 + set_bit(CAN327_TX_DO_RESPONSES, &elm->cmds_todo); 257 + set_bit(CAN327_TX_DO_CAN_CONFIG, &elm->cmds_todo); 258 + 259 + can327_kick_into_cmd_mode(elm); 260 + } 261 + 262 + static void can327_feed_frame_to_netdev(struct can327 *elm, struct sk_buff *skb) 263 + { 264 + lockdep_assert_held(&elm->lock); 265 + 266 + if (!netif_running(elm->dev)) 267 + return; 268 + 269 + /* Queue for NAPI pickup. 270 + * rx-offload will update stats and LEDs for us. 271 + */ 272 + if (can_rx_offload_queue_tail(&elm->offload, skb)) 273 + elm->dev->stats.rx_fifo_errors++; 274 + 275 + /* Wake NAPI */ 276 + can_rx_offload_irq_finish(&elm->offload); 277 + } 278 + 279 + /* Called when we're out of ideas and just want it all to end. */ 280 + static inline void can327_uart_side_failure(struct can327 *elm) 281 + { 282 + struct can_frame *frame; 283 + struct sk_buff *skb; 284 + 285 + lockdep_assert_held(&elm->lock); 286 + 287 + elm->uart_side_failure = true; 288 + 289 + clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags); 290 + 291 + elm->can.can_stats.bus_off++; 292 + netif_stop_queue(elm->dev); 293 + elm->can.state = CAN_STATE_BUS_OFF; 294 + can_bus_off(elm->dev); 295 + 296 + netdev_err(elm->dev, 297 + "ELM327 misbehaved. Blocking further communication.\n"); 298 + 299 + skb = alloc_can_err_skb(elm->dev, &frame); 300 + if (!skb) 301 + return; 302 + 303 + frame->can_id |= CAN_ERR_BUSOFF; 304 + can327_feed_frame_to_netdev(elm, skb); 305 + } 306 + 307 + /* Compares a byte buffer (non-NUL terminated) to the payload part of 308 + * a string, and returns true iff the buffer (content *and* length) is 309 + * exactly that string, without the terminating NUL byte. 310 + * 311 + * Example: If reference is "BUS ERROR", then this returns true iff nbytes == 9 312 + * and !memcmp(buf, "BUS ERROR", 9). 313 + * 314 + * The reason to use strings is so we can easily include them in the C 315 + * code, and to avoid hardcoding lengths. 316 + */ 317 + static inline bool can327_rxbuf_cmp(const u8 *buf, size_t nbytes, 318 + const char *reference) 319 + { 320 + size_t ref_len = strlen(reference); 321 + 322 + return (nbytes == ref_len) && !memcmp(buf, reference, ref_len); 323 + } 324 + 325 + static void can327_parse_error(struct can327 *elm, size_t len) 326 + { 327 + struct can_frame *frame; 328 + struct sk_buff *skb; 329 + 330 + lockdep_assert_held(&elm->lock); 331 + 332 + skb = alloc_can_err_skb(elm->dev, &frame); 333 + if (!skb) 334 + /* It's okay to return here: 335 + * The outer parsing loop will drop this UART buffer. 336 + */ 337 + return; 338 + 339 + /* Filter possible error messages based on length of RX'd line */ 340 + if (can327_rxbuf_cmp(elm->rxbuf, len, "UNABLE TO CONNECT")) { 341 + netdev_err(elm->dev, 342 + "ELM327 reported UNABLE TO CONNECT. Please check your setup.\n"); 343 + } else if (can327_rxbuf_cmp(elm->rxbuf, len, "BUFFER FULL")) { 344 + /* This will only happen if the last data line was complete. 345 + * Otherwise, can327_parse_frame() will heuristically 346 + * emit this kind of error frame instead. 347 + */ 348 + frame->can_id |= CAN_ERR_CRTL; 349 + frame->data[1] = CAN_ERR_CRTL_RX_OVERFLOW; 350 + } else if (can327_rxbuf_cmp(elm->rxbuf, len, "BUS ERROR")) { 351 + frame->can_id |= CAN_ERR_BUSERROR; 352 + } else if (can327_rxbuf_cmp(elm->rxbuf, len, "CAN ERROR")) { 353 + frame->can_id |= CAN_ERR_PROT; 354 + } else if (can327_rxbuf_cmp(elm->rxbuf, len, "<RX ERROR")) { 355 + frame->can_id |= CAN_ERR_PROT; 356 + } else if (can327_rxbuf_cmp(elm->rxbuf, len, "BUS BUSY")) { 357 + frame->can_id |= CAN_ERR_PROT; 358 + frame->data[2] = CAN_ERR_PROT_OVERLOAD; 359 + } else if (can327_rxbuf_cmp(elm->rxbuf, len, "FB ERROR")) { 360 + frame->can_id |= CAN_ERR_PROT; 361 + frame->data[2] = CAN_ERR_PROT_TX; 362 + } else if (len == 5 && !memcmp(elm->rxbuf, "ERR", 3)) { 363 + /* ERR is followed by two digits, hence line length 5 */ 364 + netdev_err(elm->dev, "ELM327 reported an ERR%c%c. Please power it off and on again.\n", 365 + elm->rxbuf[3], elm->rxbuf[4]); 366 + frame->can_id |= CAN_ERR_CRTL; 367 + } else { 368 + /* Something else has happened. 369 + * Maybe garbage on the UART line. 370 + * Emit a generic error frame. 371 + */ 372 + } 373 + 374 + can327_feed_frame_to_netdev(elm, skb); 375 + } 376 + 377 + /* Parse CAN frames coming as ASCII from ELM327. 378 + * They can be of various formats: 379 + * 380 + * 29-bit ID (EFF): 12 34 56 78 D PL PL PL PL PL PL PL PL 381 + * 11-bit ID (!EFF): 123 D PL PL PL PL PL PL PL PL 382 + * 383 + * where D = DLC, PL = payload byte 384 + * 385 + * Instead of a payload, RTR indicates a remote request. 386 + * 387 + * We will use the spaces and line length to guess the format. 388 + */ 389 + static int can327_parse_frame(struct can327 *elm, size_t len) 390 + { 391 + struct can_frame *frame; 392 + struct sk_buff *skb; 393 + int hexlen; 394 + int datastart; 395 + int i; 396 + 397 + lockdep_assert_held(&elm->lock); 398 + 399 + skb = alloc_can_skb(elm->dev, &frame); 400 + if (!skb) 401 + return -ENOMEM; 402 + 403 + /* Find first non-hex and non-space character: 404 + * - In the simplest case, there is none. 405 + * - For RTR frames, 'R' is the first non-hex character. 406 + * - An error message may replace the end of the data line. 407 + */ 408 + for (hexlen = 0; hexlen <= len; hexlen++) { 409 + if (hex_to_bin(elm->rxbuf[hexlen]) < 0 && 410 + elm->rxbuf[hexlen] != ' ') { 411 + break; 412 + } 413 + } 414 + 415 + /* Sanity check whether the line is really a clean hexdump, 416 + * or terminated by an error message, or contains garbage. 417 + */ 418 + if (hexlen < len && !isdigit(elm->rxbuf[hexlen]) && 419 + !isupper(elm->rxbuf[hexlen]) && '<' != elm->rxbuf[hexlen] && 420 + ' ' != elm->rxbuf[hexlen]) { 421 + /* The line is likely garbled anyway, so bail. 422 + * The main code will restart listening. 423 + */ 424 + kfree_skb(skb); 425 + return -ENODATA; 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 + datastart = 6; 439 + } else { 440 + /* This is not a well-formatted data line. 441 + * Assume it's an error message. 442 + */ 443 + kfree_skb(skb); 444 + return -ENODATA; 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 + kfree_skb(skb); 452 + return -ENODATA; 453 + } 454 + 455 + /* From here on all chars up to buf[hexlen] are hex or spaces, 456 + * at well-defined offsets. 457 + */ 458 + 459 + /* Read CAN data length */ 460 + frame->len = (hex_to_bin(elm->rxbuf[datastart - 2]) << 0); 461 + 462 + /* Read CAN ID */ 463 + if (frame->can_id & CAN_EFF_FLAG) { 464 + frame->can_id |= (hex_to_bin(elm->rxbuf[0]) << 28) | 465 + (hex_to_bin(elm->rxbuf[1]) << 24) | 466 + (hex_to_bin(elm->rxbuf[3]) << 20) | 467 + (hex_to_bin(elm->rxbuf[4]) << 16) | 468 + (hex_to_bin(elm->rxbuf[6]) << 12) | 469 + (hex_to_bin(elm->rxbuf[7]) << 8) | 470 + (hex_to_bin(elm->rxbuf[9]) << 4) | 471 + (hex_to_bin(elm->rxbuf[10]) << 0); 472 + } else { 473 + frame->can_id |= (hex_to_bin(elm->rxbuf[0]) << 8) | 474 + (hex_to_bin(elm->rxbuf[1]) << 4) | 475 + (hex_to_bin(elm->rxbuf[2]) << 0); 476 + } 477 + 478 + /* Check for RTR frame */ 479 + if (elm->rxfill >= hexlen + 3 && 480 + !memcmp(&elm->rxbuf[hexlen], "RTR", 3)) { 481 + frame->can_id |= CAN_RTR_FLAG; 482 + } 483 + 484 + /* Is the line long enough to hold the advertised payload? 485 + * Note: RTR frames have a DLC, but no actual payload. 486 + */ 487 + if (!(frame->can_id & CAN_RTR_FLAG) && 488 + (hexlen < frame->len * 3 + datastart)) { 489 + /* Incomplete frame. 490 + * Probably the ELM327's RS232 TX buffer was full. 491 + * Emit an error frame and exit. 492 + */ 493 + frame->can_id = CAN_ERR_FLAG | CAN_ERR_CRTL; 494 + frame->len = CAN_ERR_DLC; 495 + frame->data[1] = CAN_ERR_CRTL_RX_OVERFLOW; 496 + can327_feed_frame_to_netdev(elm, skb); 497 + 498 + /* Signal failure to parse. 499 + * The line will be re-parsed as an error line, which will fail. 500 + * However, this will correctly drop the state machine back into 501 + * command mode. 502 + */ 503 + return -ENODATA; 504 + } 505 + 506 + /* Parse the data nibbles. */ 507 + for (i = 0; i < frame->len; i++) { 508 + frame->data[i] = 509 + (hex_to_bin(elm->rxbuf[datastart + 3 * i]) << 4) | 510 + (hex_to_bin(elm->rxbuf[datastart + 3 * i + 1])); 511 + } 512 + 513 + /* Feed the frame to the network layer. */ 514 + can327_feed_frame_to_netdev(elm, skb); 515 + 516 + return 0; 517 + } 518 + 519 + static void can327_parse_line(struct can327 *elm, size_t len) 520 + { 521 + lockdep_assert_held(&elm->lock); 522 + 523 + /* Skip empty lines */ 524 + if (!len) 525 + return; 526 + 527 + /* Skip echo lines */ 528 + if (elm->drop_next_line) { 529 + elm->drop_next_line = 0; 530 + return; 531 + } else if (!memcmp(elm->rxbuf, "AT", 2)) { 532 + return; 533 + } 534 + 535 + /* Regular parsing */ 536 + if (elm->state == CAN327_STATE_RECEIVING && 537 + can327_parse_frame(elm, len)) { 538 + /* Parse an error line. */ 539 + can327_parse_error(elm, len); 540 + 541 + /* Start afresh. */ 542 + can327_kick_into_cmd_mode(elm); 543 + } 544 + } 545 + 546 + static void can327_handle_prompt(struct can327 *elm) 547 + { 548 + struct can_frame *frame = &elm->can_frame_to_send; 549 + /* Size this buffer for the largest ELM327 line we may generate, 550 + * which is currently an 8 byte CAN frame's payload hexdump. 551 + * Items in can327_init_script must fit here, too! 552 + */ 553 + char local_txbuf[sizeof("0102030405060708\r")]; 554 + 555 + lockdep_assert_held(&elm->lock); 556 + 557 + if (!elm->cmds_todo) { 558 + /* Enter CAN monitor mode */ 559 + can327_send(elm, "ATMA\r", 5); 560 + elm->state = CAN327_STATE_RECEIVING; 561 + 562 + /* We will be in the default state once this command is 563 + * sent, so enable the TX packet queue. 564 + */ 565 + netif_wake_queue(elm->dev); 566 + 567 + return; 568 + } 569 + 570 + /* Reconfigure ELM327 step by step as indicated by elm->cmds_todo */ 571 + if (test_bit(CAN327_TX_DO_INIT, &elm->cmds_todo)) { 572 + snprintf(local_txbuf, sizeof(local_txbuf), "%s", 573 + *elm->next_init_cmd); 574 + 575 + elm->next_init_cmd++; 576 + if (!(*elm->next_init_cmd)) { 577 + clear_bit(CAN327_TX_DO_INIT, &elm->cmds_todo); 578 + /* Init finished. */ 579 + } 580 + 581 + } else if (test_and_clear_bit(CAN327_TX_DO_SILENT_MONITOR, &elm->cmds_todo)) { 582 + snprintf(local_txbuf, sizeof(local_txbuf), 583 + "ATCSM%i\r", 584 + !!(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY)); 585 + 586 + } else if (test_and_clear_bit(CAN327_TX_DO_RESPONSES, &elm->cmds_todo)) { 587 + snprintf(local_txbuf, sizeof(local_txbuf), 588 + "ATR%i\r", 589 + !(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY)); 590 + 591 + } else if (test_and_clear_bit(CAN327_TX_DO_CAN_CONFIG, &elm->cmds_todo)) { 592 + snprintf(local_txbuf, sizeof(local_txbuf), 593 + "ATPC\r"); 594 + set_bit(CAN327_TX_DO_CAN_CONFIG_PART2, &elm->cmds_todo); 595 + 596 + } else if (test_and_clear_bit(CAN327_TX_DO_CAN_CONFIG_PART2, &elm->cmds_todo)) { 597 + snprintf(local_txbuf, sizeof(local_txbuf), 598 + "ATPB%04X\r", 599 + elm->can_config); 600 + 601 + } else if (test_and_clear_bit(CAN327_TX_DO_CANID_29BIT_HIGH, &elm->cmds_todo)) { 602 + snprintf(local_txbuf, sizeof(local_txbuf), 603 + "ATCP%02X\r", 604 + (frame->can_id & CAN_EFF_MASK) >> 24); 605 + 606 + } else if (test_and_clear_bit(CAN327_TX_DO_CANID_29BIT_LOW, &elm->cmds_todo)) { 607 + snprintf(local_txbuf, sizeof(local_txbuf), 608 + "ATSH%06X\r", 609 + frame->can_id & CAN_EFF_MASK & ((1 << 24) - 1)); 610 + 611 + } else if (test_and_clear_bit(CAN327_TX_DO_CANID_11BIT, &elm->cmds_todo)) { 612 + snprintf(local_txbuf, sizeof(local_txbuf), 613 + "ATSH%03X\r", 614 + frame->can_id & CAN_SFF_MASK); 615 + 616 + } else if (test_and_clear_bit(CAN327_TX_DO_CAN_DATA, &elm->cmds_todo)) { 617 + if (frame->can_id & CAN_RTR_FLAG) { 618 + /* Send an RTR frame. Their DLC is fixed. 619 + * Some chips don't send them at all. 620 + */ 621 + snprintf(local_txbuf, sizeof(local_txbuf), "ATRTR\r"); 622 + } else { 623 + /* Send a regular CAN data frame */ 624 + int i; 625 + 626 + for (i = 0; i < frame->len; i++) { 627 + snprintf(&local_txbuf[2 * i], 628 + sizeof(local_txbuf), "%02X", 629 + frame->data[i]); 630 + } 631 + 632 + snprintf(&local_txbuf[2 * i], sizeof(local_txbuf), 633 + "\r"); 634 + } 635 + 636 + elm->drop_next_line = 1; 637 + elm->state = CAN327_STATE_RECEIVING; 638 + 639 + /* We will be in the default state once this command is 640 + * sent, so enable the TX packet queue. 641 + */ 642 + netif_wake_queue(elm->dev); 643 + } 644 + 645 + can327_send(elm, local_txbuf, strlen(local_txbuf)); 646 + } 647 + 648 + static bool can327_is_ready_char(char c) 649 + { 650 + /* Bits 0xc0 are sometimes set (randomly), hence the mask. 651 + * Probably bad hardware. 652 + */ 653 + return (c & 0x3f) == CAN327_READY_CHAR; 654 + } 655 + 656 + static void can327_drop_bytes(struct can327 *elm, size_t i) 657 + { 658 + lockdep_assert_held(&elm->lock); 659 + 660 + memmove(&elm->rxbuf[0], &elm->rxbuf[i], CAN327_SIZE_RXBUF - i); 661 + elm->rxfill -= i; 662 + } 663 + 664 + static void can327_parse_rxbuf(struct can327 *elm, size_t first_new_char_idx) 665 + { 666 + size_t len, pos; 667 + 668 + lockdep_assert_held(&elm->lock); 669 + 670 + switch (elm->state) { 671 + case CAN327_STATE_NOTINIT: 672 + elm->rxfill = 0; 673 + break; 674 + 675 + case CAN327_STATE_GETDUMMYCHAR: 676 + /* Wait for 'y' or '>' */ 677 + for (pos = 0; pos < elm->rxfill; pos++) { 678 + if (elm->rxbuf[pos] == CAN327_DUMMY_CHAR) { 679 + can327_send(elm, "\r", 1); 680 + elm->state = CAN327_STATE_GETPROMPT; 681 + pos++; 682 + break; 683 + } else if (can327_is_ready_char(elm->rxbuf[pos])) { 684 + can327_send(elm, CAN327_DUMMY_STRING, 1); 685 + pos++; 686 + break; 687 + } 688 + } 689 + 690 + can327_drop_bytes(elm, pos); 691 + break; 692 + 693 + case CAN327_STATE_GETPROMPT: 694 + /* Wait for '>' */ 695 + if (can327_is_ready_char(elm->rxbuf[elm->rxfill - 1])) 696 + can327_handle_prompt(elm); 697 + 698 + elm->rxfill = 0; 699 + break; 700 + 701 + case CAN327_STATE_RECEIVING: 702 + /* Find <CR> delimiting feedback lines. */ 703 + len = first_new_char_idx; 704 + while (len < elm->rxfill && elm->rxbuf[len] != '\r') 705 + len++; 706 + 707 + if (len == CAN327_SIZE_RXBUF) { 708 + /* Assume the buffer ran full with garbage. 709 + * Did we even connect at the right baud rate? 710 + */ 711 + netdev_err(elm->dev, 712 + "RX buffer overflow. Faulty ELM327 or UART?\n"); 713 + can327_uart_side_failure(elm); 714 + } else if (len == elm->rxfill) { 715 + if (can327_is_ready_char(elm->rxbuf[elm->rxfill - 1])) { 716 + /* The ELM327's AT ST response timeout ran out, 717 + * so we got a prompt. 718 + * Clear RX buffer and restart listening. 719 + */ 720 + elm->rxfill = 0; 721 + 722 + can327_handle_prompt(elm); 723 + } 724 + 725 + /* No <CR> found - we haven't received a full line yet. 726 + * Wait for more data. 727 + */ 728 + } else { 729 + /* We have a full line to parse. */ 730 + can327_parse_line(elm, len); 731 + 732 + /* Remove parsed data from RX buffer. */ 733 + can327_drop_bytes(elm, len + 1); 734 + 735 + /* More data to parse? */ 736 + if (elm->rxfill) 737 + can327_parse_rxbuf(elm, 0); 738 + } 739 + } 740 + } 741 + 742 + static int can327_netdev_open(struct net_device *dev) 743 + { 744 + struct can327 *elm = netdev_priv(dev); 745 + int err; 746 + 747 + spin_lock_bh(&elm->lock); 748 + 749 + if (!elm->tty) { 750 + spin_unlock_bh(&elm->lock); 751 + return -ENODEV; 752 + } 753 + 754 + if (elm->uart_side_failure) 755 + netdev_warn(elm->dev, 756 + "Reopening netdev after a UART side fault has been detected.\n"); 757 + 758 + /* Clear TTY buffers */ 759 + elm->rxfill = 0; 760 + elm->txleft = 0; 761 + 762 + /* open_candev() checks for elm->can.bittiming.bitrate != 0 */ 763 + err = open_candev(dev); 764 + if (err) { 765 + spin_unlock_bh(&elm->lock); 766 + return err; 767 + } 768 + 769 + can327_init_device(elm); 770 + spin_unlock_bh(&elm->lock); 771 + 772 + err = can_rx_offload_add_manual(dev, &elm->offload, CAN327_NAPI_WEIGHT); 773 + if (err) { 774 + close_candev(dev); 775 + return err; 776 + } 777 + 778 + can_rx_offload_enable(&elm->offload); 779 + 780 + elm->can.state = CAN_STATE_ERROR_ACTIVE; 781 + netif_start_queue(dev); 782 + 783 + return 0; 784 + } 785 + 786 + static int can327_netdev_close(struct net_device *dev) 787 + { 788 + struct can327 *elm = netdev_priv(dev); 789 + 790 + /* Interrupt whatever the ELM327 is doing right now */ 791 + spin_lock_bh(&elm->lock); 792 + can327_send(elm, CAN327_DUMMY_STRING, 1); 793 + spin_unlock_bh(&elm->lock); 794 + 795 + netif_stop_queue(dev); 796 + 797 + /* Give UART one final chance to flush. */ 798 + clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags); 799 + flush_work(&elm->tx_work); 800 + 801 + can_rx_offload_disable(&elm->offload); 802 + elm->can.state = CAN_STATE_STOPPED; 803 + can_rx_offload_del(&elm->offload); 804 + close_candev(dev); 805 + 806 + return 0; 807 + } 808 + 809 + /* Send a can_frame to a TTY. */ 810 + static netdev_tx_t can327_netdev_start_xmit(struct sk_buff *skb, 811 + struct net_device *dev) 812 + { 813 + struct can327 *elm = netdev_priv(dev); 814 + struct can_frame *frame = (struct can_frame *)skb->data; 815 + 816 + if (can_dropped_invalid_skb(dev, skb)) 817 + return NETDEV_TX_OK; 818 + 819 + /* We shouldn't get here after a hardware fault: 820 + * can_bus_off() calls netif_carrier_off() 821 + */ 822 + if (elm->uart_side_failure) { 823 + WARN_ON_ONCE(elm->uart_side_failure); 824 + goto out; 825 + } 826 + 827 + netif_stop_queue(dev); 828 + 829 + /* BHs are already disabled, so no spin_lock_bh(). 830 + * See Documentation/networking/netdevices.txt 831 + */ 832 + spin_lock(&elm->lock); 833 + can327_send_frame(elm, frame); 834 + spin_unlock(&elm->lock); 835 + 836 + dev->stats.tx_packets++; 837 + dev->stats.tx_bytes += frame->can_id & CAN_RTR_FLAG ? 0 : frame->len; 838 + 839 + out: 840 + kfree_skb(skb); 841 + return NETDEV_TX_OK; 842 + } 843 + 844 + static const struct net_device_ops can327_netdev_ops = { 845 + .ndo_open = can327_netdev_open, 846 + .ndo_stop = can327_netdev_close, 847 + .ndo_start_xmit = can327_netdev_start_xmit, 848 + .ndo_change_mtu = can_change_mtu, 849 + }; 850 + 851 + static bool can327_is_valid_rx_char(u8 c) 852 + { 853 + static const bool lut_char_is_valid['z'] = { 854 + ['\r'] = true, 855 + [' '] = true, 856 + ['.'] = true, 857 + ['0'] = true, true, true, true, true, 858 + ['5'] = true, true, true, true, true, 859 + ['<'] = true, 860 + [CAN327_READY_CHAR] = true, 861 + ['?'] = true, 862 + ['A'] = true, true, true, true, true, true, true, 863 + ['H'] = true, true, true, true, true, true, true, 864 + ['O'] = true, true, true, true, true, true, true, 865 + ['V'] = true, true, true, true, true, 866 + ['a'] = true, 867 + ['b'] = true, 868 + ['v'] = true, 869 + [CAN327_DUMMY_CHAR] = true, 870 + }; 871 + BUILD_BUG_ON(CAN327_DUMMY_CHAR >= 'z'); 872 + 873 + return (c < ARRAY_SIZE(lut_char_is_valid) && lut_char_is_valid[c]); 874 + } 875 + 876 + /* Handle incoming ELM327 ASCII data. 877 + * This will not be re-entered while running, but other ldisc 878 + * functions may be called in parallel. 879 + */ 880 + static void can327_ldisc_rx(struct tty_struct *tty, const unsigned char *cp, 881 + const char *fp, int count) 882 + { 883 + struct can327 *elm = (struct can327 *)tty->disc_data; 884 + size_t first_new_char_idx; 885 + 886 + if (elm->uart_side_failure) 887 + return; 888 + 889 + spin_lock_bh(&elm->lock); 890 + 891 + /* Store old rxfill, so can327_parse_rxbuf() will have 892 + * the option of skipping already checked characters. 893 + */ 894 + first_new_char_idx = elm->rxfill; 895 + 896 + while (count-- && elm->rxfill < CAN327_SIZE_RXBUF) { 897 + if (fp && *fp++) { 898 + netdev_err(elm->dev, 899 + "Error in received character stream. Check your wiring."); 900 + 901 + can327_uart_side_failure(elm); 902 + 903 + spin_unlock_bh(&elm->lock); 904 + return; 905 + } 906 + 907 + /* Ignore NUL characters, which the PIC microcontroller may 908 + * inadvertently insert due to a known hardware bug. 909 + * See ELM327 documentation, which refers to a Microchip PIC 910 + * bug description. 911 + */ 912 + if (*cp) { 913 + /* Check for stray characters on the UART line. 914 + * Likely caused by bad hardware. 915 + */ 916 + if (!can327_is_valid_rx_char(*cp)) { 917 + netdev_err(elm->dev, 918 + "Received illegal character %02x.\n", 919 + *cp); 920 + can327_uart_side_failure(elm); 921 + 922 + spin_unlock_bh(&elm->lock); 923 + return; 924 + } 925 + 926 + elm->rxbuf[elm->rxfill++] = *cp; 927 + } 928 + 929 + cp++; 930 + } 931 + 932 + if (count >= 0) { 933 + netdev_err(elm->dev, 934 + "Receive buffer overflowed. Bad chip or wiring? count = %i", 935 + count); 936 + 937 + can327_uart_side_failure(elm); 938 + 939 + spin_unlock_bh(&elm->lock); 940 + return; 941 + } 942 + 943 + can327_parse_rxbuf(elm, first_new_char_idx); 944 + spin_unlock_bh(&elm->lock); 945 + } 946 + 947 + /* Write out remaining transmit buffer. 948 + * Scheduled when TTY is writable. 949 + */ 950 + static void can327_ldisc_tx_worker(struct work_struct *work) 951 + { 952 + struct can327 *elm = container_of(work, struct can327, tx_work); 953 + ssize_t written; 954 + 955 + if (elm->uart_side_failure) 956 + return; 957 + 958 + spin_lock_bh(&elm->lock); 959 + 960 + if (elm->txleft) { 961 + written = elm->tty->ops->write(elm->tty, elm->txhead, 962 + elm->txleft); 963 + if (written < 0) { 964 + netdev_err(elm->dev, "Failed to write to tty %s.\n", 965 + elm->tty->name); 966 + can327_uart_side_failure(elm); 967 + 968 + spin_unlock_bh(&elm->lock); 969 + return; 970 + } 971 + 972 + elm->txleft -= written; 973 + elm->txhead += written; 974 + } 975 + 976 + if (!elm->txleft) 977 + clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags); 978 + 979 + spin_unlock_bh(&elm->lock); 980 + } 981 + 982 + /* Called by the driver when there's room for more data. */ 983 + static void can327_ldisc_tx_wakeup(struct tty_struct *tty) 984 + { 985 + struct can327 *elm = (struct can327 *)tty->disc_data; 986 + 987 + schedule_work(&elm->tx_work); 988 + } 989 + 990 + /* ELM327 can only handle bitrates that are integer divisors of 500 kHz, 991 + * or 7/8 of that. Divisors are 1 to 64. 992 + * Currently we don't implement support for 7/8 rates. 993 + */ 994 + static const u32 can327_bitrate_const[] = { 995 + 7812, 7936, 8064, 8196, 8333, 8474, 8620, 8771, 996 + 8928, 9090, 9259, 9433, 9615, 9803, 10000, 10204, 997 + 10416, 10638, 10869, 11111, 11363, 11627, 11904, 12195, 998 + 12500, 12820, 13157, 13513, 13888, 14285, 14705, 15151, 999 + 15625, 16129, 16666, 17241, 17857, 18518, 19230, 20000, 1000 + 20833, 21739, 22727, 23809, 25000, 26315, 27777, 29411, 1001 + 31250, 33333, 35714, 38461, 41666, 45454, 50000, 55555, 1002 + 62500, 71428, 83333, 100000, 125000, 166666, 250000, 500000 1003 + }; 1004 + 1005 + static int can327_ldisc_open(struct tty_struct *tty) 1006 + { 1007 + struct net_device *dev; 1008 + struct can327 *elm; 1009 + int err; 1010 + 1011 + if (!capable(CAP_NET_ADMIN)) 1012 + return -EPERM; 1013 + 1014 + if (!tty->ops->write) 1015 + return -EOPNOTSUPP; 1016 + 1017 + dev = alloc_candev(sizeof(struct can327), 0); 1018 + if (!dev) 1019 + return -ENFILE; 1020 + elm = netdev_priv(dev); 1021 + 1022 + /* Configure TTY interface */ 1023 + tty->receive_room = 65536; /* We don't flow control */ 1024 + spin_lock_init(&elm->lock); 1025 + INIT_WORK(&elm->tx_work, can327_ldisc_tx_worker); 1026 + 1027 + /* Configure CAN metadata */ 1028 + elm->can.bitrate_const = can327_bitrate_const; 1029 + elm->can.bitrate_const_cnt = ARRAY_SIZE(can327_bitrate_const); 1030 + elm->can.ctrlmode_supported = CAN_CTRLMODE_LISTENONLY; 1031 + 1032 + /* Configure netdev interface */ 1033 + elm->dev = dev; 1034 + dev->netdev_ops = &can327_netdev_ops; 1035 + 1036 + /* Mark ldisc channel as alive */ 1037 + elm->tty = tty; 1038 + tty->disc_data = elm; 1039 + 1040 + /* Let 'er rip */ 1041 + err = register_candev(elm->dev); 1042 + if (err) { 1043 + free_candev(elm->dev); 1044 + return err; 1045 + } 1046 + 1047 + netdev_info(elm->dev, "can327 on %s.\n", tty->name); 1048 + 1049 + return 0; 1050 + } 1051 + 1052 + /* Close down a can327 channel. 1053 + * This means flushing out any pending queues, and then returning. 1054 + * This call is serialized against other ldisc functions: 1055 + * Once this is called, no other ldisc function of ours is entered. 1056 + * 1057 + * We also use this function for a hangup event. 1058 + */ 1059 + static void can327_ldisc_close(struct tty_struct *tty) 1060 + { 1061 + struct can327 *elm = (struct can327 *)tty->disc_data; 1062 + 1063 + /* unregister_netdev() calls .ndo_stop() so we don't have to. 1064 + * Our .ndo_stop() also flushes the TTY write wakeup handler, 1065 + * so we can safely set elm->tty = NULL after this. 1066 + */ 1067 + unregister_candev(elm->dev); 1068 + 1069 + /* Mark channel as dead */ 1070 + spin_lock_bh(&elm->lock); 1071 + tty->disc_data = NULL; 1072 + elm->tty = NULL; 1073 + spin_unlock_bh(&elm->lock); 1074 + 1075 + netdev_info(elm->dev, "can327 off %s.\n", tty->name); 1076 + 1077 + free_candev(elm->dev); 1078 + } 1079 + 1080 + static int can327_ldisc_ioctl(struct tty_struct *tty, unsigned int cmd, 1081 + unsigned long arg) 1082 + { 1083 + struct can327 *elm = (struct can327 *)tty->disc_data; 1084 + unsigned int tmp; 1085 + 1086 + switch (cmd) { 1087 + case SIOCGIFNAME: 1088 + tmp = strnlen(elm->dev->name, IFNAMSIZ - 1) + 1; 1089 + if (copy_to_user((void __user *)arg, elm->dev->name, tmp)) 1090 + return -EFAULT; 1091 + return 0; 1092 + 1093 + case SIOCSIFHWADDR: 1094 + return -EINVAL; 1095 + 1096 + default: 1097 + return tty_mode_ioctl(tty, cmd, arg); 1098 + } 1099 + } 1100 + 1101 + static struct tty_ldisc_ops can327_ldisc = { 1102 + .owner = THIS_MODULE, 1103 + .name = "can327", 1104 + .num = N_CAN327, 1105 + .receive_buf = can327_ldisc_rx, 1106 + .write_wakeup = can327_ldisc_tx_wakeup, 1107 + .open = can327_ldisc_open, 1108 + .close = can327_ldisc_close, 1109 + .ioctl = can327_ldisc_ioctl, 1110 + }; 1111 + 1112 + static int __init can327_init(void) 1113 + { 1114 + int status; 1115 + 1116 + status = tty_register_ldisc(&can327_ldisc); 1117 + if (status) 1118 + pr_err("Can't register line discipline\n"); 1119 + 1120 + return status; 1121 + } 1122 + 1123 + static void __exit can327_exit(void) 1124 + { 1125 + /* This will only be called when all channels have been closed by 1126 + * userspace - tty_ldisc.c takes care of the module's refcount. 1127 + */ 1128 + tty_unregister_ldisc(&can327_ldisc); 1129 + } 1130 + 1131 + module_init(can327_init); 1132 + module_exit(can327_exit); 1133 + 1134 + MODULE_ALIAS_LDISC(N_CAN327); 1135 + MODULE_DESCRIPTION("ELM327 based CAN interface"); 1136 + MODULE_LICENSE("GPL"); 1137 + MODULE_AUTHOR("Max Staudt <max@enpas.org>");