can327.c 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149
  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 <[email protected]>
  8. * slcan.c Author : Oliver Hartkopp <[email protected]>
  9. * slip.c Authors : Laurence Culhane <[email protected]>
  10. * Fred N. van Kempen <[email protected]>
  11. */
  12. #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  13. #include <linux/init.h>
  14. #include <linux/module.h>
  15. #include <linux/bitops.h>
  16. #include <linux/ctype.h>
  17. #include <linux/errno.h>
  18. #include <linux/kernel.h>
  19. #include <linux/list.h>
  20. #include <linux/lockdep.h>
  21. #include <linux/netdevice.h>
  22. #include <linux/skbuff.h>
  23. #include <linux/spinlock.h>
  24. #include <linux/string.h>
  25. #include <linux/tty.h>
  26. #include <linux/tty_ldisc.h>
  27. #include <linux/workqueue.h>
  28. #include <uapi/linux/tty.h>
  29. #include <linux/can.h>
  30. #include <linux/can/dev.h>
  31. #include <linux/can/error.h>
  32. #include <linux/can/rx-offload.h>
  33. #define CAN327_NAPI_WEIGHT 4
  34. #define CAN327_SIZE_TXBUF 32
  35. #define CAN327_SIZE_RXBUF 1024
  36. #define CAN327_CAN_CONFIG_SEND_SFF 0x8000
  37. #define CAN327_CAN_CONFIG_VARIABLE_DLC 0x4000
  38. #define CAN327_CAN_CONFIG_RECV_BOTH_SFF_EFF 0x2000
  39. #define CAN327_CAN_CONFIG_BAUDRATE_MULT_8_7 0x1000
  40. #define CAN327_DUMMY_CHAR 'y'
  41. #define CAN327_DUMMY_STRING "y"
  42. #define CAN327_READY_CHAR '>'
  43. /* Bits in elm->cmds_todo */
  44. enum can327_tx_do {
  45. CAN327_TX_DO_CAN_DATA = 0,
  46. CAN327_TX_DO_CANID_11BIT,
  47. CAN327_TX_DO_CANID_29BIT_LOW,
  48. CAN327_TX_DO_CANID_29BIT_HIGH,
  49. CAN327_TX_DO_CAN_CONFIG_PART2,
  50. CAN327_TX_DO_CAN_CONFIG,
  51. CAN327_TX_DO_RESPONSES,
  52. CAN327_TX_DO_SILENT_MONITOR,
  53. CAN327_TX_DO_INIT,
  54. };
  55. struct can327 {
  56. /* This must be the first member when using alloc_candev() */
  57. struct can_priv can;
  58. struct can_rx_offload offload;
  59. /* TTY buffers */
  60. u8 txbuf[CAN327_SIZE_TXBUF];
  61. u8 rxbuf[CAN327_SIZE_RXBUF];
  62. /* Per-channel lock */
  63. spinlock_t lock;
  64. /* TTY and netdev devices that we're bridging */
  65. struct tty_struct *tty;
  66. struct net_device *dev;
  67. /* TTY buffer accounting */
  68. struct work_struct tx_work; /* Flushes TTY TX buffer */
  69. u8 *txhead; /* Next TX byte */
  70. size_t txleft; /* Bytes left to TX */
  71. int rxfill; /* Bytes already RX'd in buffer */
  72. /* State machine */
  73. enum {
  74. CAN327_STATE_NOTINIT = 0,
  75. CAN327_STATE_GETDUMMYCHAR,
  76. CAN327_STATE_GETPROMPT,
  77. CAN327_STATE_RECEIVING,
  78. } state;
  79. /* Things we have yet to send */
  80. char **next_init_cmd;
  81. unsigned long cmds_todo;
  82. /* The CAN frame and config the ELM327 is sending/using,
  83. * or will send/use after finishing all cmds_todo
  84. */
  85. struct can_frame can_frame_to_send;
  86. u16 can_config;
  87. u8 can_bitrate_divisor;
  88. /* Parser state */
  89. bool drop_next_line;
  90. /* Stop the channel on UART side hardware failure, e.g. stray
  91. * characters or neverending lines. This may be caused by bad
  92. * UART wiring, a bad ELM327, a bad UART bridge...
  93. * Once this is true, nothing will be sent to the TTY.
  94. */
  95. bool uart_side_failure;
  96. };
  97. static inline void can327_uart_side_failure(struct can327 *elm);
  98. static void can327_send(struct can327 *elm, const void *buf, size_t len)
  99. {
  100. int written;
  101. lockdep_assert_held(&elm->lock);
  102. if (elm->uart_side_failure)
  103. return;
  104. memcpy(elm->txbuf, buf, len);
  105. /* Order of next two lines is *very* important.
  106. * When we are sending a little amount of data,
  107. * the transfer may be completed inside the ops->write()
  108. * routine, because it's running with interrupts enabled.
  109. * In this case we *never* got WRITE_WAKEUP event,
  110. * if we did not request it before write operation.
  111. * 14 Oct 1994 Dmitry Gorodchanin.
  112. */
  113. set_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
  114. written = elm->tty->ops->write(elm->tty, elm->txbuf, len);
  115. if (written < 0) {
  116. netdev_err(elm->dev, "Failed to write to tty %s.\n",
  117. elm->tty->name);
  118. can327_uart_side_failure(elm);
  119. return;
  120. }
  121. elm->txleft = len - written;
  122. elm->txhead = elm->txbuf + written;
  123. }
  124. /* Take the ELM327 out of almost any state and back into command mode.
  125. * We send CAN327_DUMMY_CHAR which will either abort any running
  126. * operation, or be echoed back to us in case we're already in command
  127. * mode.
  128. */
  129. static void can327_kick_into_cmd_mode(struct can327 *elm)
  130. {
  131. lockdep_assert_held(&elm->lock);
  132. if (elm->state != CAN327_STATE_GETDUMMYCHAR &&
  133. elm->state != CAN327_STATE_GETPROMPT) {
  134. can327_send(elm, CAN327_DUMMY_STRING, 1);
  135. elm->state = CAN327_STATE_GETDUMMYCHAR;
  136. }
  137. }
  138. /* Schedule a CAN frame and necessary config changes to be sent to the TTY. */
  139. static void can327_send_frame(struct can327 *elm, struct can_frame *frame)
  140. {
  141. lockdep_assert_held(&elm->lock);
  142. /* Schedule any necessary changes in ELM327's CAN configuration */
  143. if (elm->can_frame_to_send.can_id != frame->can_id) {
  144. /* Set the new CAN ID for transmission. */
  145. if ((frame->can_id ^ elm->can_frame_to_send.can_id)
  146. & CAN_EFF_FLAG) {
  147. elm->can_config =
  148. (frame->can_id & CAN_EFF_FLAG ? 0 : CAN327_CAN_CONFIG_SEND_SFF) |
  149. CAN327_CAN_CONFIG_VARIABLE_DLC |
  150. CAN327_CAN_CONFIG_RECV_BOTH_SFF_EFF |
  151. elm->can_bitrate_divisor;
  152. set_bit(CAN327_TX_DO_CAN_CONFIG, &elm->cmds_todo);
  153. }
  154. if (frame->can_id & CAN_EFF_FLAG) {
  155. clear_bit(CAN327_TX_DO_CANID_11BIT, &elm->cmds_todo);
  156. set_bit(CAN327_TX_DO_CANID_29BIT_LOW, &elm->cmds_todo);
  157. set_bit(CAN327_TX_DO_CANID_29BIT_HIGH, &elm->cmds_todo);
  158. } else {
  159. set_bit(CAN327_TX_DO_CANID_11BIT, &elm->cmds_todo);
  160. clear_bit(CAN327_TX_DO_CANID_29BIT_LOW,
  161. &elm->cmds_todo);
  162. clear_bit(CAN327_TX_DO_CANID_29BIT_HIGH,
  163. &elm->cmds_todo);
  164. }
  165. }
  166. /* Schedule the CAN frame itself. */
  167. elm->can_frame_to_send = *frame;
  168. set_bit(CAN327_TX_DO_CAN_DATA, &elm->cmds_todo);
  169. can327_kick_into_cmd_mode(elm);
  170. }
  171. /* ELM327 initialisation sequence.
  172. * The line length is limited by the buffer in can327_handle_prompt().
  173. */
  174. static char *can327_init_script[] = {
  175. "AT WS\r", /* v1.0: Warm Start */
  176. "AT PP FF OFF\r", /* v1.0: All Programmable Parameters Off */
  177. "AT M0\r", /* v1.0: Memory Off */
  178. "AT AL\r", /* v1.0: Allow Long messages */
  179. "AT BI\r", /* v1.0: Bypass Initialisation */
  180. "AT CAF0\r", /* v1.0: CAN Auto Formatting Off */
  181. "AT CFC0\r", /* v1.0: CAN Flow Control Off */
  182. "AT CF 000\r", /* v1.0: Reset CAN ID Filter */
  183. "AT CM 000\r", /* v1.0: Reset CAN ID Mask */
  184. "AT E1\r", /* v1.0: Echo On */
  185. "AT H1\r", /* v1.0: Headers On */
  186. "AT L0\r", /* v1.0: Linefeeds Off */
  187. "AT SH 7DF\r", /* v1.0: Set CAN sending ID to 0x7df */
  188. "AT ST FF\r", /* v1.0: Set maximum Timeout for response after TX */
  189. "AT AT0\r", /* v1.2: Adaptive Timing Off */
  190. "AT D1\r", /* v1.3: Print DLC On */
  191. "AT S1\r", /* v1.3: Spaces On */
  192. "AT TP B\r", /* v1.0: Try Protocol B */
  193. NULL
  194. };
  195. static void can327_init_device(struct can327 *elm)
  196. {
  197. lockdep_assert_held(&elm->lock);
  198. elm->state = CAN327_STATE_NOTINIT;
  199. elm->can_frame_to_send.can_id = 0x7df; /* ELM327 HW default */
  200. elm->rxfill = 0;
  201. elm->drop_next_line = 0;
  202. /* We can only set the bitrate as a fraction of 500000.
  203. * The bitrates listed in can327_bitrate_const will
  204. * limit the user to the right values.
  205. */
  206. elm->can_bitrate_divisor = 500000 / elm->can.bittiming.bitrate;
  207. elm->can_config =
  208. CAN327_CAN_CONFIG_SEND_SFF | CAN327_CAN_CONFIG_VARIABLE_DLC |
  209. CAN327_CAN_CONFIG_RECV_BOTH_SFF_EFF | elm->can_bitrate_divisor;
  210. /* Configure ELM327 and then start monitoring */
  211. elm->next_init_cmd = &can327_init_script[0];
  212. set_bit(CAN327_TX_DO_INIT, &elm->cmds_todo);
  213. set_bit(CAN327_TX_DO_SILENT_MONITOR, &elm->cmds_todo);
  214. set_bit(CAN327_TX_DO_RESPONSES, &elm->cmds_todo);
  215. set_bit(CAN327_TX_DO_CAN_CONFIG, &elm->cmds_todo);
  216. can327_kick_into_cmd_mode(elm);
  217. }
  218. static void can327_feed_frame_to_netdev(struct can327 *elm, struct sk_buff *skb)
  219. {
  220. lockdep_assert_held(&elm->lock);
  221. if (!netif_running(elm->dev)) {
  222. kfree_skb(skb);
  223. return;
  224. }
  225. /* Queue for NAPI pickup.
  226. * rx-offload will update stats and LEDs for us.
  227. */
  228. if (can_rx_offload_queue_tail(&elm->offload, skb))
  229. elm->dev->stats.rx_fifo_errors++;
  230. /* Wake NAPI */
  231. can_rx_offload_irq_finish(&elm->offload);
  232. }
  233. /* Called when we're out of ideas and just want it all to end. */
  234. static inline void can327_uart_side_failure(struct can327 *elm)
  235. {
  236. struct can_frame *frame;
  237. struct sk_buff *skb;
  238. lockdep_assert_held(&elm->lock);
  239. elm->uart_side_failure = true;
  240. clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
  241. elm->can.can_stats.bus_off++;
  242. netif_stop_queue(elm->dev);
  243. elm->can.state = CAN_STATE_BUS_OFF;
  244. can_bus_off(elm->dev);
  245. netdev_err(elm->dev,
  246. "ELM327 misbehaved. Blocking further communication.\n");
  247. skb = alloc_can_err_skb(elm->dev, &frame);
  248. if (!skb)
  249. return;
  250. frame->can_id |= CAN_ERR_BUSOFF;
  251. can327_feed_frame_to_netdev(elm, skb);
  252. }
  253. /* Compares a byte buffer (non-NUL terminated) to the payload part of
  254. * a string, and returns true iff the buffer (content *and* length) is
  255. * exactly that string, without the terminating NUL byte.
  256. *
  257. * Example: If reference is "BUS ERROR", then this returns true iff nbytes == 9
  258. * and !memcmp(buf, "BUS ERROR", 9).
  259. *
  260. * The reason to use strings is so we can easily include them in the C
  261. * code, and to avoid hardcoding lengths.
  262. */
  263. static inline bool can327_rxbuf_cmp(const u8 *buf, size_t nbytes,
  264. const char *reference)
  265. {
  266. size_t ref_len = strlen(reference);
  267. return (nbytes == ref_len) && !memcmp(buf, reference, ref_len);
  268. }
  269. static void can327_parse_error(struct can327 *elm, size_t len)
  270. {
  271. struct can_frame *frame;
  272. struct sk_buff *skb;
  273. lockdep_assert_held(&elm->lock);
  274. skb = alloc_can_err_skb(elm->dev, &frame);
  275. if (!skb)
  276. /* It's okay to return here:
  277. * The outer parsing loop will drop this UART buffer.
  278. */
  279. return;
  280. /* Filter possible error messages based on length of RX'd line */
  281. if (can327_rxbuf_cmp(elm->rxbuf, len, "UNABLE TO CONNECT")) {
  282. netdev_err(elm->dev,
  283. "ELM327 reported UNABLE TO CONNECT. Please check your setup.\n");
  284. } else if (can327_rxbuf_cmp(elm->rxbuf, len, "BUFFER FULL")) {
  285. /* This will only happen if the last data line was complete.
  286. * Otherwise, can327_parse_frame() will heuristically
  287. * emit this kind of error frame instead.
  288. */
  289. frame->can_id |= CAN_ERR_CRTL;
  290. frame->data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
  291. } else if (can327_rxbuf_cmp(elm->rxbuf, len, "BUS ERROR")) {
  292. frame->can_id |= CAN_ERR_BUSERROR;
  293. } else if (can327_rxbuf_cmp(elm->rxbuf, len, "CAN ERROR")) {
  294. frame->can_id |= CAN_ERR_PROT;
  295. } else if (can327_rxbuf_cmp(elm->rxbuf, len, "<RX ERROR")) {
  296. frame->can_id |= CAN_ERR_PROT;
  297. } else if (can327_rxbuf_cmp(elm->rxbuf, len, "BUS BUSY")) {
  298. frame->can_id |= CAN_ERR_PROT;
  299. frame->data[2] = CAN_ERR_PROT_OVERLOAD;
  300. } else if (can327_rxbuf_cmp(elm->rxbuf, len, "FB ERROR")) {
  301. frame->can_id |= CAN_ERR_PROT;
  302. frame->data[2] = CAN_ERR_PROT_TX;
  303. } else if (len == 5 && !memcmp(elm->rxbuf, "ERR", 3)) {
  304. /* ERR is followed by two digits, hence line length 5 */
  305. netdev_err(elm->dev, "ELM327 reported an ERR%c%c. Please power it off and on again.\n",
  306. elm->rxbuf[3], elm->rxbuf[4]);
  307. frame->can_id |= CAN_ERR_CRTL;
  308. } else {
  309. /* Something else has happened.
  310. * Maybe garbage on the UART line.
  311. * Emit a generic error frame.
  312. */
  313. }
  314. can327_feed_frame_to_netdev(elm, skb);
  315. }
  316. /* Parse CAN frames coming as ASCII from ELM327.
  317. * They can be of various formats:
  318. *
  319. * 29-bit ID (EFF): 12 34 56 78 D PL PL PL PL PL PL PL PL
  320. * 11-bit ID (!EFF): 123 D PL PL PL PL PL PL PL PL
  321. *
  322. * where D = DLC, PL = payload byte
  323. *
  324. * Instead of a payload, RTR indicates a remote request.
  325. *
  326. * We will use the spaces and line length to guess the format.
  327. */
  328. static int can327_parse_frame(struct can327 *elm, size_t len)
  329. {
  330. struct can_frame *frame;
  331. struct sk_buff *skb;
  332. int hexlen;
  333. int datastart;
  334. int i;
  335. lockdep_assert_held(&elm->lock);
  336. skb = alloc_can_skb(elm->dev, &frame);
  337. if (!skb)
  338. return -ENOMEM;
  339. /* Find first non-hex and non-space character:
  340. * - In the simplest case, there is none.
  341. * - For RTR frames, 'R' is the first non-hex character.
  342. * - An error message may replace the end of the data line.
  343. */
  344. for (hexlen = 0; hexlen <= len; hexlen++) {
  345. if (hex_to_bin(elm->rxbuf[hexlen]) < 0 &&
  346. elm->rxbuf[hexlen] != ' ') {
  347. break;
  348. }
  349. }
  350. /* Sanity check whether the line is really a clean hexdump,
  351. * or terminated by an error message, or contains garbage.
  352. */
  353. if (hexlen < len && !isdigit(elm->rxbuf[hexlen]) &&
  354. !isupper(elm->rxbuf[hexlen]) && '<' != elm->rxbuf[hexlen] &&
  355. ' ' != elm->rxbuf[hexlen]) {
  356. /* The line is likely garbled anyway, so bail.
  357. * The main code will restart listening.
  358. */
  359. kfree_skb(skb);
  360. return -ENODATA;
  361. }
  362. /* Use spaces in CAN ID to distinguish 29 or 11 bit address length.
  363. * No out-of-bounds access:
  364. * We use the fact that we can always read from elm->rxbuf.
  365. */
  366. if (elm->rxbuf[2] == ' ' && elm->rxbuf[5] == ' ' &&
  367. elm->rxbuf[8] == ' ' && elm->rxbuf[11] == ' ' &&
  368. elm->rxbuf[13] == ' ') {
  369. frame->can_id = CAN_EFF_FLAG;
  370. datastart = 14;
  371. } else if (elm->rxbuf[3] == ' ' && elm->rxbuf[5] == ' ') {
  372. datastart = 6;
  373. } else {
  374. /* This is not a well-formatted data line.
  375. * Assume it's an error message.
  376. */
  377. kfree_skb(skb);
  378. return -ENODATA;
  379. }
  380. if (hexlen < datastart) {
  381. /* The line is too short to be a valid frame hex dump.
  382. * Something interrupted the hex dump or it is invalid.
  383. */
  384. kfree_skb(skb);
  385. return -ENODATA;
  386. }
  387. /* From here on all chars up to buf[hexlen] are hex or spaces,
  388. * at well-defined offsets.
  389. */
  390. /* Read CAN data length */
  391. frame->len = (hex_to_bin(elm->rxbuf[datastart - 2]) << 0);
  392. /* Read CAN ID */
  393. if (frame->can_id & CAN_EFF_FLAG) {
  394. frame->can_id |= (hex_to_bin(elm->rxbuf[0]) << 28) |
  395. (hex_to_bin(elm->rxbuf[1]) << 24) |
  396. (hex_to_bin(elm->rxbuf[3]) << 20) |
  397. (hex_to_bin(elm->rxbuf[4]) << 16) |
  398. (hex_to_bin(elm->rxbuf[6]) << 12) |
  399. (hex_to_bin(elm->rxbuf[7]) << 8) |
  400. (hex_to_bin(elm->rxbuf[9]) << 4) |
  401. (hex_to_bin(elm->rxbuf[10]) << 0);
  402. } else {
  403. frame->can_id |= (hex_to_bin(elm->rxbuf[0]) << 8) |
  404. (hex_to_bin(elm->rxbuf[1]) << 4) |
  405. (hex_to_bin(elm->rxbuf[2]) << 0);
  406. }
  407. /* Check for RTR frame */
  408. if (elm->rxfill >= hexlen + 3 &&
  409. !memcmp(&elm->rxbuf[hexlen], "RTR", 3)) {
  410. frame->can_id |= CAN_RTR_FLAG;
  411. }
  412. /* Is the line long enough to hold the advertised payload?
  413. * Note: RTR frames have a DLC, but no actual payload.
  414. */
  415. if (!(frame->can_id & CAN_RTR_FLAG) &&
  416. (hexlen < frame->len * 3 + datastart)) {
  417. /* Incomplete frame.
  418. * Probably the ELM327's RS232 TX buffer was full.
  419. * Emit an error frame and exit.
  420. */
  421. frame->can_id = CAN_ERR_FLAG | CAN_ERR_CRTL;
  422. frame->len = CAN_ERR_DLC;
  423. frame->data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
  424. can327_feed_frame_to_netdev(elm, skb);
  425. /* Signal failure to parse.
  426. * The line will be re-parsed as an error line, which will fail.
  427. * However, this will correctly drop the state machine back into
  428. * command mode.
  429. */
  430. return -ENODATA;
  431. }
  432. /* Parse the data nibbles. */
  433. for (i = 0; i < frame->len; i++) {
  434. frame->data[i] =
  435. (hex_to_bin(elm->rxbuf[datastart + 3 * i]) << 4) |
  436. (hex_to_bin(elm->rxbuf[datastart + 3 * i + 1]));
  437. }
  438. /* Feed the frame to the network layer. */
  439. can327_feed_frame_to_netdev(elm, skb);
  440. return 0;
  441. }
  442. static void can327_parse_line(struct can327 *elm, size_t len)
  443. {
  444. lockdep_assert_held(&elm->lock);
  445. /* Skip empty lines */
  446. if (!len)
  447. return;
  448. /* Skip echo lines */
  449. if (elm->drop_next_line) {
  450. elm->drop_next_line = 0;
  451. return;
  452. } else if (!memcmp(elm->rxbuf, "AT", 2)) {
  453. return;
  454. }
  455. /* Regular parsing */
  456. if (elm->state == CAN327_STATE_RECEIVING &&
  457. can327_parse_frame(elm, len)) {
  458. /* Parse an error line. */
  459. can327_parse_error(elm, len);
  460. /* Start afresh. */
  461. can327_kick_into_cmd_mode(elm);
  462. }
  463. }
  464. static void can327_handle_prompt(struct can327 *elm)
  465. {
  466. struct can_frame *frame = &elm->can_frame_to_send;
  467. /* Size this buffer for the largest ELM327 line we may generate,
  468. * which is currently an 8 byte CAN frame's payload hexdump.
  469. * Items in can327_init_script must fit here, too!
  470. */
  471. char local_txbuf[sizeof("0102030405060708\r")];
  472. lockdep_assert_held(&elm->lock);
  473. if (!elm->cmds_todo) {
  474. /* Enter CAN monitor mode */
  475. can327_send(elm, "ATMA\r", 5);
  476. elm->state = CAN327_STATE_RECEIVING;
  477. /* We will be in the default state once this command is
  478. * sent, so enable the TX packet queue.
  479. */
  480. netif_wake_queue(elm->dev);
  481. return;
  482. }
  483. /* Reconfigure ELM327 step by step as indicated by elm->cmds_todo */
  484. if (test_bit(CAN327_TX_DO_INIT, &elm->cmds_todo)) {
  485. snprintf(local_txbuf, sizeof(local_txbuf), "%s",
  486. *elm->next_init_cmd);
  487. elm->next_init_cmd++;
  488. if (!(*elm->next_init_cmd)) {
  489. clear_bit(CAN327_TX_DO_INIT, &elm->cmds_todo);
  490. /* Init finished. */
  491. }
  492. } else if (test_and_clear_bit(CAN327_TX_DO_SILENT_MONITOR, &elm->cmds_todo)) {
  493. snprintf(local_txbuf, sizeof(local_txbuf),
  494. "ATCSM%i\r",
  495. !!(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY));
  496. } else if (test_and_clear_bit(CAN327_TX_DO_RESPONSES, &elm->cmds_todo)) {
  497. snprintf(local_txbuf, sizeof(local_txbuf),
  498. "ATR%i\r",
  499. !(elm->can.ctrlmode & CAN_CTRLMODE_LISTENONLY));
  500. } else if (test_and_clear_bit(CAN327_TX_DO_CAN_CONFIG, &elm->cmds_todo)) {
  501. snprintf(local_txbuf, sizeof(local_txbuf),
  502. "ATPC\r");
  503. set_bit(CAN327_TX_DO_CAN_CONFIG_PART2, &elm->cmds_todo);
  504. } else if (test_and_clear_bit(CAN327_TX_DO_CAN_CONFIG_PART2, &elm->cmds_todo)) {
  505. snprintf(local_txbuf, sizeof(local_txbuf),
  506. "ATPB%04X\r",
  507. elm->can_config);
  508. } else if (test_and_clear_bit(CAN327_TX_DO_CANID_29BIT_HIGH, &elm->cmds_todo)) {
  509. snprintf(local_txbuf, sizeof(local_txbuf),
  510. "ATCP%02X\r",
  511. (frame->can_id & CAN_EFF_MASK) >> 24);
  512. } else if (test_and_clear_bit(CAN327_TX_DO_CANID_29BIT_LOW, &elm->cmds_todo)) {
  513. snprintf(local_txbuf, sizeof(local_txbuf),
  514. "ATSH%06X\r",
  515. frame->can_id & CAN_EFF_MASK & ((1 << 24) - 1));
  516. } else if (test_and_clear_bit(CAN327_TX_DO_CANID_11BIT, &elm->cmds_todo)) {
  517. snprintf(local_txbuf, sizeof(local_txbuf),
  518. "ATSH%03X\r",
  519. frame->can_id & CAN_SFF_MASK);
  520. } else if (test_and_clear_bit(CAN327_TX_DO_CAN_DATA, &elm->cmds_todo)) {
  521. if (frame->can_id & CAN_RTR_FLAG) {
  522. /* Send an RTR frame. Their DLC is fixed.
  523. * Some chips don't send them at all.
  524. */
  525. snprintf(local_txbuf, sizeof(local_txbuf), "ATRTR\r");
  526. } else {
  527. /* Send a regular CAN data frame */
  528. int i;
  529. for (i = 0; i < frame->len; i++) {
  530. snprintf(&local_txbuf[2 * i],
  531. sizeof(local_txbuf), "%02X",
  532. frame->data[i]);
  533. }
  534. snprintf(&local_txbuf[2 * i], sizeof(local_txbuf),
  535. "\r");
  536. }
  537. elm->drop_next_line = 1;
  538. elm->state = CAN327_STATE_RECEIVING;
  539. /* We will be in the default state once this command is
  540. * sent, so enable the TX packet queue.
  541. */
  542. netif_wake_queue(elm->dev);
  543. }
  544. can327_send(elm, local_txbuf, strlen(local_txbuf));
  545. }
  546. static bool can327_is_ready_char(char c)
  547. {
  548. /* Bits 0xc0 are sometimes set (randomly), hence the mask.
  549. * Probably bad hardware.
  550. */
  551. return (c & 0x3f) == CAN327_READY_CHAR;
  552. }
  553. static void can327_drop_bytes(struct can327 *elm, size_t i)
  554. {
  555. lockdep_assert_held(&elm->lock);
  556. memmove(&elm->rxbuf[0], &elm->rxbuf[i], CAN327_SIZE_RXBUF - i);
  557. elm->rxfill -= i;
  558. }
  559. static void can327_parse_rxbuf(struct can327 *elm, size_t first_new_char_idx)
  560. {
  561. size_t len, pos;
  562. lockdep_assert_held(&elm->lock);
  563. switch (elm->state) {
  564. case CAN327_STATE_NOTINIT:
  565. elm->rxfill = 0;
  566. break;
  567. case CAN327_STATE_GETDUMMYCHAR:
  568. /* Wait for 'y' or '>' */
  569. for (pos = 0; pos < elm->rxfill; pos++) {
  570. if (elm->rxbuf[pos] == CAN327_DUMMY_CHAR) {
  571. can327_send(elm, "\r", 1);
  572. elm->state = CAN327_STATE_GETPROMPT;
  573. pos++;
  574. break;
  575. } else if (can327_is_ready_char(elm->rxbuf[pos])) {
  576. can327_send(elm, CAN327_DUMMY_STRING, 1);
  577. pos++;
  578. break;
  579. }
  580. }
  581. can327_drop_bytes(elm, pos);
  582. break;
  583. case CAN327_STATE_GETPROMPT:
  584. /* Wait for '>' */
  585. if (can327_is_ready_char(elm->rxbuf[elm->rxfill - 1]))
  586. can327_handle_prompt(elm);
  587. elm->rxfill = 0;
  588. break;
  589. case CAN327_STATE_RECEIVING:
  590. /* Find <CR> delimiting feedback lines. */
  591. len = first_new_char_idx;
  592. while (len < elm->rxfill && elm->rxbuf[len] != '\r')
  593. len++;
  594. if (len == CAN327_SIZE_RXBUF) {
  595. /* Assume the buffer ran full with garbage.
  596. * Did we even connect at the right baud rate?
  597. */
  598. netdev_err(elm->dev,
  599. "RX buffer overflow. Faulty ELM327 or UART?\n");
  600. can327_uart_side_failure(elm);
  601. } else if (len == elm->rxfill) {
  602. if (can327_is_ready_char(elm->rxbuf[elm->rxfill - 1])) {
  603. /* The ELM327's AT ST response timeout ran out,
  604. * so we got a prompt.
  605. * Clear RX buffer and restart listening.
  606. */
  607. elm->rxfill = 0;
  608. can327_handle_prompt(elm);
  609. }
  610. /* No <CR> found - we haven't received a full line yet.
  611. * Wait for more data.
  612. */
  613. } else {
  614. /* We have a full line to parse. */
  615. can327_parse_line(elm, len);
  616. /* Remove parsed data from RX buffer. */
  617. can327_drop_bytes(elm, len + 1);
  618. /* More data to parse? */
  619. if (elm->rxfill)
  620. can327_parse_rxbuf(elm, 0);
  621. }
  622. }
  623. }
  624. static int can327_netdev_open(struct net_device *dev)
  625. {
  626. struct can327 *elm = netdev_priv(dev);
  627. int err;
  628. spin_lock_bh(&elm->lock);
  629. if (!elm->tty) {
  630. spin_unlock_bh(&elm->lock);
  631. return -ENODEV;
  632. }
  633. if (elm->uart_side_failure)
  634. netdev_warn(elm->dev,
  635. "Reopening netdev after a UART side fault has been detected.\n");
  636. /* Clear TTY buffers */
  637. elm->rxfill = 0;
  638. elm->txleft = 0;
  639. /* open_candev() checks for elm->can.bittiming.bitrate != 0 */
  640. err = open_candev(dev);
  641. if (err) {
  642. spin_unlock_bh(&elm->lock);
  643. return err;
  644. }
  645. can327_init_device(elm);
  646. spin_unlock_bh(&elm->lock);
  647. err = can_rx_offload_add_manual(dev, &elm->offload, CAN327_NAPI_WEIGHT);
  648. if (err) {
  649. close_candev(dev);
  650. return err;
  651. }
  652. can_rx_offload_enable(&elm->offload);
  653. elm->can.state = CAN_STATE_ERROR_ACTIVE;
  654. netif_start_queue(dev);
  655. return 0;
  656. }
  657. static int can327_netdev_close(struct net_device *dev)
  658. {
  659. struct can327 *elm = netdev_priv(dev);
  660. /* Interrupt whatever the ELM327 is doing right now */
  661. spin_lock_bh(&elm->lock);
  662. can327_send(elm, CAN327_DUMMY_STRING, 1);
  663. spin_unlock_bh(&elm->lock);
  664. netif_stop_queue(dev);
  665. /* We don't flush the UART TX queue here, as we want final stop
  666. * commands (like the above dummy char) to be flushed out.
  667. */
  668. can_rx_offload_disable(&elm->offload);
  669. elm->can.state = CAN_STATE_STOPPED;
  670. can_rx_offload_del(&elm->offload);
  671. close_candev(dev);
  672. return 0;
  673. }
  674. /* Send a can_frame to a TTY. */
  675. static netdev_tx_t can327_netdev_start_xmit(struct sk_buff *skb,
  676. struct net_device *dev)
  677. {
  678. struct can327 *elm = netdev_priv(dev);
  679. struct can_frame *frame = (struct can_frame *)skb->data;
  680. if (can_dev_dropped_skb(dev, skb))
  681. return NETDEV_TX_OK;
  682. /* We shouldn't get here after a hardware fault:
  683. * can_bus_off() calls netif_carrier_off()
  684. */
  685. if (elm->uart_side_failure) {
  686. WARN_ON_ONCE(elm->uart_side_failure);
  687. goto out;
  688. }
  689. netif_stop_queue(dev);
  690. /* BHs are already disabled, so no spin_lock_bh().
  691. * See Documentation/networking/netdevices.rst
  692. */
  693. spin_lock(&elm->lock);
  694. can327_send_frame(elm, frame);
  695. spin_unlock(&elm->lock);
  696. dev->stats.tx_packets++;
  697. dev->stats.tx_bytes += frame->can_id & CAN_RTR_FLAG ? 0 : frame->len;
  698. skb_tx_timestamp(skb);
  699. out:
  700. kfree_skb(skb);
  701. return NETDEV_TX_OK;
  702. }
  703. static const struct net_device_ops can327_netdev_ops = {
  704. .ndo_open = can327_netdev_open,
  705. .ndo_stop = can327_netdev_close,
  706. .ndo_start_xmit = can327_netdev_start_xmit,
  707. .ndo_change_mtu = can_change_mtu,
  708. };
  709. static const struct ethtool_ops can327_ethtool_ops = {
  710. .get_ts_info = ethtool_op_get_ts_info,
  711. };
  712. static bool can327_is_valid_rx_char(u8 c)
  713. {
  714. static const bool lut_char_is_valid['z'] = {
  715. ['\r'] = true,
  716. [' '] = true,
  717. ['.'] = true,
  718. ['0'] = true, true, true, true, true,
  719. ['5'] = true, true, true, true, true,
  720. ['<'] = true,
  721. [CAN327_READY_CHAR] = true,
  722. ['?'] = true,
  723. ['A'] = true, true, true, true, true, true, true,
  724. ['H'] = true, true, true, true, true, true, true,
  725. ['O'] = true, true, true, true, true, true, true,
  726. ['V'] = true, true, true, true, true,
  727. ['a'] = true,
  728. ['b'] = true,
  729. ['v'] = true,
  730. [CAN327_DUMMY_CHAR] = true,
  731. };
  732. BUILD_BUG_ON(CAN327_DUMMY_CHAR >= 'z');
  733. return (c < ARRAY_SIZE(lut_char_is_valid) && lut_char_is_valid[c]);
  734. }
  735. /* Handle incoming ELM327 ASCII data.
  736. * This will not be re-entered while running, but other ldisc
  737. * functions may be called in parallel.
  738. */
  739. static void can327_ldisc_rx(struct tty_struct *tty, const unsigned char *cp,
  740. const char *fp, int count)
  741. {
  742. struct can327 *elm = (struct can327 *)tty->disc_data;
  743. size_t first_new_char_idx;
  744. if (elm->uart_side_failure)
  745. return;
  746. spin_lock_bh(&elm->lock);
  747. /* Store old rxfill, so can327_parse_rxbuf() will have
  748. * the option of skipping already checked characters.
  749. */
  750. first_new_char_idx = elm->rxfill;
  751. while (count-- && elm->rxfill < CAN327_SIZE_RXBUF) {
  752. if (fp && *fp++) {
  753. netdev_err(elm->dev,
  754. "Error in received character stream. Check your wiring.");
  755. can327_uart_side_failure(elm);
  756. spin_unlock_bh(&elm->lock);
  757. return;
  758. }
  759. /* Ignore NUL characters, which the PIC microcontroller may
  760. * inadvertently insert due to a known hardware bug.
  761. * See ELM327 documentation, which refers to a Microchip PIC
  762. * bug description.
  763. */
  764. if (*cp) {
  765. /* Check for stray characters on the UART line.
  766. * Likely caused by bad hardware.
  767. */
  768. if (!can327_is_valid_rx_char(*cp)) {
  769. netdev_err(elm->dev,
  770. "Received illegal character %02x.\n",
  771. *cp);
  772. can327_uart_side_failure(elm);
  773. spin_unlock_bh(&elm->lock);
  774. return;
  775. }
  776. elm->rxbuf[elm->rxfill++] = *cp;
  777. }
  778. cp++;
  779. }
  780. if (count >= 0) {
  781. netdev_err(elm->dev,
  782. "Receive buffer overflowed. Bad chip or wiring? count = %i",
  783. count);
  784. can327_uart_side_failure(elm);
  785. spin_unlock_bh(&elm->lock);
  786. return;
  787. }
  788. can327_parse_rxbuf(elm, first_new_char_idx);
  789. spin_unlock_bh(&elm->lock);
  790. }
  791. /* Write out remaining transmit buffer.
  792. * Scheduled when TTY is writable.
  793. */
  794. static void can327_ldisc_tx_worker(struct work_struct *work)
  795. {
  796. struct can327 *elm = container_of(work, struct can327, tx_work);
  797. ssize_t written;
  798. if (elm->uart_side_failure)
  799. return;
  800. spin_lock_bh(&elm->lock);
  801. if (elm->txleft) {
  802. written = elm->tty->ops->write(elm->tty, elm->txhead,
  803. elm->txleft);
  804. if (written < 0) {
  805. netdev_err(elm->dev, "Failed to write to tty %s.\n",
  806. elm->tty->name);
  807. can327_uart_side_failure(elm);
  808. spin_unlock_bh(&elm->lock);
  809. return;
  810. }
  811. elm->txleft -= written;
  812. elm->txhead += written;
  813. }
  814. if (!elm->txleft)
  815. clear_bit(TTY_DO_WRITE_WAKEUP, &elm->tty->flags);
  816. spin_unlock_bh(&elm->lock);
  817. }
  818. /* Called by the driver when there's room for more data. */
  819. static void can327_ldisc_tx_wakeup(struct tty_struct *tty)
  820. {
  821. struct can327 *elm = (struct can327 *)tty->disc_data;
  822. schedule_work(&elm->tx_work);
  823. }
  824. /* ELM327 can only handle bitrates that are integer divisors of 500 kHz,
  825. * or 7/8 of that. Divisors are 1 to 64.
  826. * Currently we don't implement support for 7/8 rates.
  827. */
  828. static const u32 can327_bitrate_const[] = {
  829. 7812, 7936, 8064, 8196, 8333, 8474, 8620, 8771,
  830. 8928, 9090, 9259, 9433, 9615, 9803, 10000, 10204,
  831. 10416, 10638, 10869, 11111, 11363, 11627, 11904, 12195,
  832. 12500, 12820, 13157, 13513, 13888, 14285, 14705, 15151,
  833. 15625, 16129, 16666, 17241, 17857, 18518, 19230, 20000,
  834. 20833, 21739, 22727, 23809, 25000, 26315, 27777, 29411,
  835. 31250, 33333, 35714, 38461, 41666, 45454, 50000, 55555,
  836. 62500, 71428, 83333, 100000, 125000, 166666, 250000, 500000
  837. };
  838. static int can327_ldisc_open(struct tty_struct *tty)
  839. {
  840. struct net_device *dev;
  841. struct can327 *elm;
  842. int err;
  843. if (!capable(CAP_NET_ADMIN))
  844. return -EPERM;
  845. if (!tty->ops->write)
  846. return -EOPNOTSUPP;
  847. dev = alloc_candev(sizeof(struct can327), 0);
  848. if (!dev)
  849. return -ENFILE;
  850. elm = netdev_priv(dev);
  851. /* Configure TTY interface */
  852. tty->receive_room = 65536; /* We don't flow control */
  853. spin_lock_init(&elm->lock);
  854. INIT_WORK(&elm->tx_work, can327_ldisc_tx_worker);
  855. /* Configure CAN metadata */
  856. elm->can.bitrate_const = can327_bitrate_const;
  857. elm->can.bitrate_const_cnt = ARRAY_SIZE(can327_bitrate_const);
  858. elm->can.ctrlmode_supported = CAN_CTRLMODE_LISTENONLY;
  859. /* Configure netdev interface */
  860. elm->dev = dev;
  861. dev->netdev_ops = &can327_netdev_ops;
  862. dev->ethtool_ops = &can327_ethtool_ops;
  863. /* Mark ldisc channel as alive */
  864. elm->tty = tty;
  865. tty->disc_data = elm;
  866. /* Let 'er rip */
  867. err = register_candev(elm->dev);
  868. if (err) {
  869. free_candev(elm->dev);
  870. return err;
  871. }
  872. netdev_info(elm->dev, "can327 on %s.\n", tty->name);
  873. return 0;
  874. }
  875. /* Close down a can327 channel.
  876. * This means flushing out any pending queues, and then returning.
  877. * This call is serialized against other ldisc functions:
  878. * Once this is called, no other ldisc function of ours is entered.
  879. *
  880. * We also use this function for a hangup event.
  881. */
  882. static void can327_ldisc_close(struct tty_struct *tty)
  883. {
  884. struct can327 *elm = (struct can327 *)tty->disc_data;
  885. /* unregister_netdev() calls .ndo_stop() so we don't have to. */
  886. unregister_candev(elm->dev);
  887. /* Give UART one final chance to flush.
  888. * No need to clear TTY_DO_WRITE_WAKEUP since .write_wakeup() is
  889. * serialised against .close() and will not be called once we return.
  890. */
  891. flush_work(&elm->tx_work);
  892. /* Mark channel as dead */
  893. spin_lock_bh(&elm->lock);
  894. tty->disc_data = NULL;
  895. elm->tty = NULL;
  896. spin_unlock_bh(&elm->lock);
  897. netdev_info(elm->dev, "can327 off %s.\n", tty->name);
  898. free_candev(elm->dev);
  899. }
  900. static int can327_ldisc_ioctl(struct tty_struct *tty, unsigned int cmd,
  901. unsigned long arg)
  902. {
  903. struct can327 *elm = (struct can327 *)tty->disc_data;
  904. unsigned int tmp;
  905. switch (cmd) {
  906. case SIOCGIFNAME:
  907. tmp = strnlen(elm->dev->name, IFNAMSIZ - 1) + 1;
  908. if (copy_to_user((void __user *)arg, elm->dev->name, tmp))
  909. return -EFAULT;
  910. return 0;
  911. case SIOCSIFHWADDR:
  912. return -EINVAL;
  913. default:
  914. return tty_mode_ioctl(tty, cmd, arg);
  915. }
  916. }
  917. static struct tty_ldisc_ops can327_ldisc = {
  918. .owner = THIS_MODULE,
  919. .name = KBUILD_MODNAME,
  920. .num = N_CAN327,
  921. .receive_buf = can327_ldisc_rx,
  922. .write_wakeup = can327_ldisc_tx_wakeup,
  923. .open = can327_ldisc_open,
  924. .close = can327_ldisc_close,
  925. .ioctl = can327_ldisc_ioctl,
  926. };
  927. static int __init can327_init(void)
  928. {
  929. int status;
  930. status = tty_register_ldisc(&can327_ldisc);
  931. if (status)
  932. pr_err("Can't register line discipline\n");
  933. return status;
  934. }
  935. static void __exit can327_exit(void)
  936. {
  937. /* This will only be called when all channels have been closed by
  938. * userspace - tty_ldisc.c takes care of the module's refcount.
  939. */
  940. tty_unregister_ldisc(&can327_ldisc);
  941. }
  942. module_init(can327_init);
  943. module_exit(can327_exit);
  944. MODULE_ALIAS_LDISC(N_CAN327);
  945. MODULE_DESCRIPTION("ELM327 based CAN interface");
  946. MODULE_LICENSE("GPL");
  947. MODULE_AUTHOR("Max Staudt <[email protected]>");