941 lines · c
1/*2 * slcan.c - serial line CAN interface driver (using tty line discipline)3 *4 * This file is derived from linux/drivers/net/slip/slip.c and got5 * inspiration from linux/drivers/net/can/can327.c for the rework made6 * on the line discipline code.7 *8 * slip.c Authors : Laurence Culhane <loz@holmes.demon.co.uk>9 * Fred N. van Kempen <waltje@uwalt.nl.mugnet.org>10 * slcan.c Author : Oliver Hartkopp <socketcan@hartkopp.net>11 * can327.c Author : Max Staudt <max-linux@enpas.org>12 *13 * This program is free software; you can redistribute it and/or modify it14 * under the terms of the GNU General Public License as published by the15 * Free Software Foundation; either version 2 of the License, or (at your16 * option) any later version.17 *18 * This program is distributed in the hope that it will be useful, but19 * WITHOUT ANY WARRANTY; without even the implied warranty of20 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU21 * General Public License for more details.22 *23 * You should have received a copy of the GNU General Public License along24 * with this program; if not, see http://www.gnu.org/licenses/gpl.html25 *26 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS27 * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT28 * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR29 * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT30 * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,31 * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT32 * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,33 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY34 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT35 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE36 * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH37 * DAMAGE.38 *39 */40 41#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt42 43#include <linux/module.h>44 45#include <linux/uaccess.h>46#include <linux/bitops.h>47#include <linux/string.h>48#include <linux/tty.h>49#include <linux/errno.h>50#include <linux/netdevice.h>51#include <linux/skbuff.h>52#include <linux/rtnetlink.h>53#include <linux/init.h>54#include <linux/kernel.h>55#include <linux/workqueue.h>56#include <linux/can.h>57#include <linux/can/dev.h>58#include <linux/can/skb.h>59 60#include "slcan.h"61 62MODULE_ALIAS_LDISC(N_SLCAN);63MODULE_DESCRIPTION("serial line CAN interface");64MODULE_LICENSE("GPL");65MODULE_AUTHOR("Oliver Hartkopp <socketcan@hartkopp.net>");66MODULE_AUTHOR("Dario Binacchi <dario.binacchi@amarulasolutions.com>");67 68/* maximum rx buffer len: extended CAN frame with timestamp */69#define SLCAN_MTU (sizeof("T1111222281122334455667788EA5F\r") + 1)70 71#define SLCAN_CMD_LEN 172#define SLCAN_SFF_ID_LEN 373#define SLCAN_EFF_ID_LEN 874#define SLCAN_STATE_LEN 175#define SLCAN_STATE_BE_RXCNT_LEN 376#define SLCAN_STATE_BE_TXCNT_LEN 377#define SLCAN_STATE_FRAME_LEN (1 + SLCAN_CMD_LEN + \78 SLCAN_STATE_BE_RXCNT_LEN + \79 SLCAN_STATE_BE_TXCNT_LEN)80struct slcan {81 struct can_priv can;82 83 /* Various fields. */84 struct tty_struct *tty; /* ptr to TTY structure */85 struct net_device *dev; /* easy for intr handling */86 spinlock_t lock;87 struct work_struct tx_work; /* Flushes transmit buffer */88 89 /* These are pointers to the malloc()ed frame buffers. */90 unsigned char rbuff[SLCAN_MTU]; /* receiver buffer */91 int rcount; /* received chars counter */92 unsigned char xbuff[SLCAN_MTU]; /* transmitter buffer*/93 unsigned char *xhead; /* pointer to next XMIT byte */94 int xleft; /* bytes left in XMIT queue */95 96 unsigned long flags; /* Flag values/ mode etc */97#define SLF_ERROR 0 /* Parity, etc. error */98#define SLF_XCMD 1 /* Command transmission */99 unsigned long cmd_flags; /* Command flags */100#define CF_ERR_RST 0 /* Reset errors on open */101 wait_queue_head_t xcmd_wait; /* Wait queue for commands */102 /* transmission */103};104 105static const u32 slcan_bitrate_const[] = {106 10000, 20000, 50000, 100000, 125000,107 250000, 500000, 800000, 1000000108};109 110bool slcan_err_rst_on_open(struct net_device *ndev)111{112 struct slcan *sl = netdev_priv(ndev);113 114 return !!test_bit(CF_ERR_RST, &sl->cmd_flags);115}116 117int slcan_enable_err_rst_on_open(struct net_device *ndev, bool on)118{119 struct slcan *sl = netdev_priv(ndev);120 121 if (netif_running(ndev))122 return -EBUSY;123 124 if (on)125 set_bit(CF_ERR_RST, &sl->cmd_flags);126 else127 clear_bit(CF_ERR_RST, &sl->cmd_flags);128 129 return 0;130}131 132/*************************************************************************133 * SLCAN ENCAPSULATION FORMAT *134 *************************************************************************/135 136/* A CAN frame has a can_id (11 bit standard frame format OR 29 bit extended137 * frame format) a data length code (len) which can be from 0 to 8138 * and up to <len> data bytes as payload.139 * Additionally a CAN frame may become a remote transmission frame if the140 * RTR-bit is set. This causes another ECU to send a CAN frame with the141 * given can_id.142 *143 * The SLCAN ASCII representation of these different frame types is:144 * <type> <id> <dlc> <data>*145 *146 * Extended frames (29 bit) are defined by capital characters in the type.147 * RTR frames are defined as 'r' types - normal frames have 't' type:148 * t => 11 bit data frame149 * r => 11 bit RTR frame150 * T => 29 bit data frame151 * R => 29 bit RTR frame152 *153 * The <id> is 3 (standard) or 8 (extended) bytes in ASCII Hex (base64).154 * The <dlc> is a one byte ASCII number ('0' - '8')155 * The <data> section has at much ASCII Hex bytes as defined by the <dlc>156 *157 * Examples:158 *159 * t1230 : can_id 0x123, len 0, no data160 * t4563112233 : can_id 0x456, len 3, data 0x11 0x22 0x33161 * T12ABCDEF2AA55 : extended can_id 0x12ABCDEF, len 2, data 0xAA 0x55162 * r1230 : can_id 0x123, len 0, no data, remote transmission request163 *164 */165 166/*************************************************************************167 * STANDARD SLCAN DECAPSULATION *168 *************************************************************************/169 170/* Send one completely decapsulated can_frame to the network layer */171static void slcan_bump_frame(struct slcan *sl)172{173 struct sk_buff *skb;174 struct can_frame *cf;175 int i, tmp;176 u32 tmpid;177 char *cmd = sl->rbuff;178 179 skb = alloc_can_skb(sl->dev, &cf);180 if (unlikely(!skb)) {181 sl->dev->stats.rx_dropped++;182 return;183 }184 185 switch (*cmd) {186 case 'r':187 cf->can_id = CAN_RTR_FLAG;188 fallthrough;189 case 't':190 /* store dlc ASCII value and terminate SFF CAN ID string */191 cf->len = sl->rbuff[SLCAN_CMD_LEN + SLCAN_SFF_ID_LEN];192 sl->rbuff[SLCAN_CMD_LEN + SLCAN_SFF_ID_LEN] = 0;193 /* point to payload data behind the dlc */194 cmd += SLCAN_CMD_LEN + SLCAN_SFF_ID_LEN + 1;195 break;196 case 'R':197 cf->can_id = CAN_RTR_FLAG;198 fallthrough;199 case 'T':200 cf->can_id |= CAN_EFF_FLAG;201 /* store dlc ASCII value and terminate EFF CAN ID string */202 cf->len = sl->rbuff[SLCAN_CMD_LEN + SLCAN_EFF_ID_LEN];203 sl->rbuff[SLCAN_CMD_LEN + SLCAN_EFF_ID_LEN] = 0;204 /* point to payload data behind the dlc */205 cmd += SLCAN_CMD_LEN + SLCAN_EFF_ID_LEN + 1;206 break;207 default:208 goto decode_failed;209 }210 211 if (kstrtou32(sl->rbuff + SLCAN_CMD_LEN, 16, &tmpid))212 goto decode_failed;213 214 cf->can_id |= tmpid;215 216 /* get len from sanitized ASCII value */217 if (cf->len >= '0' && cf->len < '9')218 cf->len -= '0';219 else220 goto decode_failed;221 222 /* RTR frames may have a dlc > 0 but they never have any data bytes */223 if (!(cf->can_id & CAN_RTR_FLAG)) {224 for (i = 0; i < cf->len; i++) {225 tmp = hex_to_bin(*cmd++);226 if (tmp < 0)227 goto decode_failed;228 229 cf->data[i] = (tmp << 4);230 tmp = hex_to_bin(*cmd++);231 if (tmp < 0)232 goto decode_failed;233 234 cf->data[i] |= tmp;235 }236 }237 238 sl->dev->stats.rx_packets++;239 if (!(cf->can_id & CAN_RTR_FLAG))240 sl->dev->stats.rx_bytes += cf->len;241 242 netif_rx(skb);243 return;244 245decode_failed:246 sl->dev->stats.rx_errors++;247 dev_kfree_skb(skb);248}249 250/* A change state frame must contain state info and receive and transmit251 * error counters.252 *253 * Examples:254 *255 * sb256256 : state bus-off: rx counter 256, tx counter 256256 * sa057033 : state active, rx counter 57, tx counter 33257 */258static void slcan_bump_state(struct slcan *sl)259{260 struct net_device *dev = sl->dev;261 struct sk_buff *skb;262 struct can_frame *cf;263 char *cmd = sl->rbuff;264 u32 rxerr, txerr;265 enum can_state state, rx_state, tx_state;266 267 switch (cmd[1]) {268 case 'a':269 state = CAN_STATE_ERROR_ACTIVE;270 break;271 case 'w':272 state = CAN_STATE_ERROR_WARNING;273 break;274 case 'p':275 state = CAN_STATE_ERROR_PASSIVE;276 break;277 case 'b':278 state = CAN_STATE_BUS_OFF;279 break;280 default:281 return;282 }283 284 if (state == sl->can.state || sl->rcount < SLCAN_STATE_FRAME_LEN)285 return;286 287 cmd += SLCAN_STATE_BE_RXCNT_LEN + SLCAN_CMD_LEN + 1;288 cmd[SLCAN_STATE_BE_TXCNT_LEN] = 0;289 if (kstrtou32(cmd, 10, &txerr))290 return;291 292 *cmd = 0;293 cmd -= SLCAN_STATE_BE_RXCNT_LEN;294 if (kstrtou32(cmd, 10, &rxerr))295 return;296 297 skb = alloc_can_err_skb(dev, &cf);298 299 tx_state = txerr >= rxerr ? state : 0;300 rx_state = txerr <= rxerr ? state : 0;301 can_change_state(dev, cf, tx_state, rx_state);302 303 if (state == CAN_STATE_BUS_OFF) {304 can_bus_off(dev);305 } else if (skb) {306 cf->can_id |= CAN_ERR_CNT;307 cf->data[6] = txerr;308 cf->data[7] = rxerr;309 }310 311 if (skb)312 netif_rx(skb);313}314 315/* An error frame can contain more than one type of error.316 *317 * Examples:318 *319 * e1a : len 1, errors: ACK error320 * e3bcO: len 3, errors: Bit0 error, CRC error, Tx overrun error321 */322static void slcan_bump_err(struct slcan *sl)323{324 struct net_device *dev = sl->dev;325 struct sk_buff *skb;326 struct can_frame *cf;327 char *cmd = sl->rbuff;328 bool rx_errors = false, tx_errors = false, rx_over_errors = false;329 int i, len;330 331 /* get len from sanitized ASCII value */332 len = cmd[1];333 if (len >= '0' && len < '9')334 len -= '0';335 else336 return;337 338 if ((len + SLCAN_CMD_LEN + 1) > sl->rcount)339 return;340 341 skb = alloc_can_err_skb(dev, &cf);342 343 if (skb)344 cf->can_id |= CAN_ERR_PROT | CAN_ERR_BUSERROR;345 346 cmd += SLCAN_CMD_LEN + 1;347 for (i = 0; i < len; i++, cmd++) {348 switch (*cmd) {349 case 'a':350 netdev_dbg(dev, "ACK error\n");351 tx_errors = true;352 if (skb) {353 cf->can_id |= CAN_ERR_ACK;354 cf->data[3] = CAN_ERR_PROT_LOC_ACK;355 }356 357 break;358 case 'b':359 netdev_dbg(dev, "Bit0 error\n");360 tx_errors = true;361 if (skb)362 cf->data[2] |= CAN_ERR_PROT_BIT0;363 364 break;365 case 'B':366 netdev_dbg(dev, "Bit1 error\n");367 tx_errors = true;368 if (skb)369 cf->data[2] |= CAN_ERR_PROT_BIT1;370 371 break;372 case 'c':373 netdev_dbg(dev, "CRC error\n");374 rx_errors = true;375 if (skb) {376 cf->data[2] |= CAN_ERR_PROT_BIT;377 cf->data[3] = CAN_ERR_PROT_LOC_CRC_SEQ;378 }379 380 break;381 case 'f':382 netdev_dbg(dev, "Form Error\n");383 rx_errors = true;384 if (skb)385 cf->data[2] |= CAN_ERR_PROT_FORM;386 387 break;388 case 'o':389 netdev_dbg(dev, "Rx overrun error\n");390 rx_over_errors = true;391 rx_errors = true;392 if (skb) {393 cf->can_id |= CAN_ERR_CRTL;394 cf->data[1] = CAN_ERR_CRTL_RX_OVERFLOW;395 }396 397 break;398 case 'O':399 netdev_dbg(dev, "Tx overrun error\n");400 tx_errors = true;401 if (skb) {402 cf->can_id |= CAN_ERR_CRTL;403 cf->data[1] = CAN_ERR_CRTL_TX_OVERFLOW;404 }405 406 break;407 case 's':408 netdev_dbg(dev, "Stuff error\n");409 rx_errors = true;410 if (skb)411 cf->data[2] |= CAN_ERR_PROT_STUFF;412 413 break;414 default:415 if (skb)416 dev_kfree_skb(skb);417 418 return;419 }420 }421 422 if (rx_errors)423 dev->stats.rx_errors++;424 425 if (rx_over_errors)426 dev->stats.rx_over_errors++;427 428 if (tx_errors)429 dev->stats.tx_errors++;430 431 if (skb)432 netif_rx(skb);433}434 435static void slcan_bump(struct slcan *sl)436{437 switch (sl->rbuff[0]) {438 case 'r':439 fallthrough;440 case 't':441 fallthrough;442 case 'R':443 fallthrough;444 case 'T':445 return slcan_bump_frame(sl);446 case 'e':447 return slcan_bump_err(sl);448 case 's':449 return slcan_bump_state(sl);450 default:451 return;452 }453}454 455/* parse tty input stream */456static void slcan_unesc(struct slcan *sl, unsigned char s)457{458 if ((s == '\r') || (s == '\a')) { /* CR or BEL ends the pdu */459 if (!test_and_clear_bit(SLF_ERROR, &sl->flags) &&460 sl->rcount > 4)461 slcan_bump(sl);462 463 sl->rcount = 0;464 } else {465 if (!test_bit(SLF_ERROR, &sl->flags)) {466 if (sl->rcount < SLCAN_MTU) {467 sl->rbuff[sl->rcount++] = s;468 return;469 }470 471 sl->dev->stats.rx_over_errors++;472 set_bit(SLF_ERROR, &sl->flags);473 }474 }475}476 477/*************************************************************************478 * STANDARD SLCAN ENCAPSULATION *479 *************************************************************************/480 481/* Encapsulate one can_frame and stuff into a TTY queue. */482static void slcan_encaps(struct slcan *sl, struct can_frame *cf)483{484 int actual, i;485 unsigned char *pos;486 unsigned char *endpos;487 canid_t id = cf->can_id;488 489 pos = sl->xbuff;490 491 if (cf->can_id & CAN_RTR_FLAG)492 *pos = 'R'; /* becomes 'r' in standard frame format (SFF) */493 else494 *pos = 'T'; /* becomes 't' in standard frame format (SSF) */495 496 /* determine number of chars for the CAN-identifier */497 if (cf->can_id & CAN_EFF_FLAG) {498 id &= CAN_EFF_MASK;499 endpos = pos + SLCAN_EFF_ID_LEN;500 } else {501 *pos |= 0x20; /* convert R/T to lower case for SFF */502 id &= CAN_SFF_MASK;503 endpos = pos + SLCAN_SFF_ID_LEN;504 }505 506 /* build 3 (SFF) or 8 (EFF) digit CAN identifier */507 pos++;508 while (endpos >= pos) {509 *endpos-- = hex_asc_upper[id & 0xf];510 id >>= 4;511 }512 513 pos += (cf->can_id & CAN_EFF_FLAG) ?514 SLCAN_EFF_ID_LEN : SLCAN_SFF_ID_LEN;515 516 *pos++ = cf->len + '0';517 518 /* RTR frames may have a dlc > 0 but they never have any data bytes */519 if (!(cf->can_id & CAN_RTR_FLAG)) {520 for (i = 0; i < cf->len; i++)521 pos = hex_byte_pack_upper(pos, cf->data[i]);522 523 sl->dev->stats.tx_bytes += cf->len;524 }525 526 *pos++ = '\r';527 528 /* Order of next two lines is *very* important.529 * When we are sending a little amount of data,530 * the transfer may be completed inside the ops->write()531 * routine, because it's running with interrupts enabled.532 * In this case we *never* got WRITE_WAKEUP event,533 * if we did not request it before write operation.534 * 14 Oct 1994 Dmitry Gorodchanin.535 */536 set_bit(TTY_DO_WRITE_WAKEUP, &sl->tty->flags);537 actual = sl->tty->ops->write(sl->tty, sl->xbuff, pos - sl->xbuff);538 sl->xleft = (pos - sl->xbuff) - actual;539 sl->xhead = sl->xbuff + actual;540}541 542/* Write out any remaining transmit buffer. Scheduled when tty is writable */543static void slcan_transmit(struct work_struct *work)544{545 struct slcan *sl = container_of(work, struct slcan, tx_work);546 int actual;547 548 spin_lock_bh(&sl->lock);549 /* First make sure we're connected. */550 if (unlikely(!netif_running(sl->dev)) &&551 likely(!test_bit(SLF_XCMD, &sl->flags))) {552 spin_unlock_bh(&sl->lock);553 return;554 }555 556 if (sl->xleft <= 0) {557 if (unlikely(test_bit(SLF_XCMD, &sl->flags))) {558 clear_bit(SLF_XCMD, &sl->flags);559 clear_bit(TTY_DO_WRITE_WAKEUP, &sl->tty->flags);560 spin_unlock_bh(&sl->lock);561 wake_up(&sl->xcmd_wait);562 return;563 }564 565 /* Now serial buffer is almost free & we can start566 * transmission of another packet567 */568 sl->dev->stats.tx_packets++;569 clear_bit(TTY_DO_WRITE_WAKEUP, &sl->tty->flags);570 spin_unlock_bh(&sl->lock);571 netif_wake_queue(sl->dev);572 return;573 }574 575 actual = sl->tty->ops->write(sl->tty, sl->xhead, sl->xleft);576 sl->xleft -= actual;577 sl->xhead += actual;578 spin_unlock_bh(&sl->lock);579}580 581/* Called by the driver when there's room for more data.582 * Schedule the transmit.583 */584static void slcan_write_wakeup(struct tty_struct *tty)585{586 struct slcan *sl = tty->disc_data;587 588 schedule_work(&sl->tx_work);589}590 591/* Send a can_frame to a TTY queue. */592static netdev_tx_t slcan_netdev_xmit(struct sk_buff *skb,593 struct net_device *dev)594{595 struct slcan *sl = netdev_priv(dev);596 597 if (can_dev_dropped_skb(dev, skb))598 return NETDEV_TX_OK;599 600 spin_lock(&sl->lock);601 if (!netif_running(dev)) {602 spin_unlock(&sl->lock);603 netdev_warn(dev, "xmit: iface is down\n");604 goto out;605 }606 if (!sl->tty) {607 spin_unlock(&sl->lock);608 goto out;609 }610 611 netif_stop_queue(sl->dev);612 slcan_encaps(sl, (struct can_frame *)skb->data); /* encaps & send */613 spin_unlock(&sl->lock);614 615 skb_tx_timestamp(skb);616 617out:618 kfree_skb(skb);619 return NETDEV_TX_OK;620}621 622/******************************************623 * Routines looking at netdevice side.624 ******************************************/625 626static int slcan_transmit_cmd(struct slcan *sl, const unsigned char *cmd)627{628 int ret, actual, n;629 630 spin_lock(&sl->lock);631 if (!sl->tty) {632 spin_unlock(&sl->lock);633 return -ENODEV;634 }635 636 n = scnprintf(sl->xbuff, sizeof(sl->xbuff), "%s", cmd);637 set_bit(TTY_DO_WRITE_WAKEUP, &sl->tty->flags);638 actual = sl->tty->ops->write(sl->tty, sl->xbuff, n);639 sl->xleft = n - actual;640 sl->xhead = sl->xbuff + actual;641 set_bit(SLF_XCMD, &sl->flags);642 spin_unlock(&sl->lock);643 ret = wait_event_interruptible_timeout(sl->xcmd_wait,644 !test_bit(SLF_XCMD, &sl->flags),645 HZ);646 clear_bit(SLF_XCMD, &sl->flags);647 if (ret == -ERESTARTSYS)648 return ret;649 650 if (ret == 0)651 return -ETIMEDOUT;652 653 return 0;654}655 656/* Netdevice UP -> DOWN routine */657static int slcan_netdev_close(struct net_device *dev)658{659 struct slcan *sl = netdev_priv(dev);660 int err;661 662 if (sl->can.bittiming.bitrate &&663 sl->can.bittiming.bitrate != CAN_BITRATE_UNKNOWN) {664 err = slcan_transmit_cmd(sl, "C\r");665 if (err)666 netdev_warn(dev,667 "failed to send close command 'C\\r'\n");668 }669 670 /* TTY discipline is running. */671 clear_bit(TTY_DO_WRITE_WAKEUP, &sl->tty->flags);672 flush_work(&sl->tx_work);673 674 netif_stop_queue(dev);675 sl->rcount = 0;676 sl->xleft = 0;677 close_candev(dev);678 sl->can.state = CAN_STATE_STOPPED;679 if (sl->can.bittiming.bitrate == CAN_BITRATE_UNKNOWN)680 sl->can.bittiming.bitrate = CAN_BITRATE_UNSET;681 682 return 0;683}684 685/* Netdevice DOWN -> UP routine */686static int slcan_netdev_open(struct net_device *dev)687{688 struct slcan *sl = netdev_priv(dev);689 unsigned char cmd[SLCAN_MTU];690 int err, s;691 692 /* The baud rate is not set with the command693 * `ip link set <iface> type can bitrate <baud>' and therefore694 * can.bittiming.bitrate is CAN_BITRATE_UNSET (0), causing695 * open_candev() to fail. So let's set to a fake value.696 */697 if (sl->can.bittiming.bitrate == CAN_BITRATE_UNSET)698 sl->can.bittiming.bitrate = CAN_BITRATE_UNKNOWN;699 700 err = open_candev(dev);701 if (err) {702 netdev_err(dev, "failed to open can device\n");703 return err;704 }705 706 if (sl->can.bittiming.bitrate != CAN_BITRATE_UNKNOWN) {707 for (s = 0; s < ARRAY_SIZE(slcan_bitrate_const); s++) {708 if (sl->can.bittiming.bitrate == slcan_bitrate_const[s])709 break;710 }711 712 /* The CAN framework has already validate the bitrate value,713 * so we can avoid to check if `s' has been properly set.714 */715 snprintf(cmd, sizeof(cmd), "C\rS%d\r", s);716 err = slcan_transmit_cmd(sl, cmd);717 if (err) {718 netdev_err(dev,719 "failed to send bitrate command 'C\\rS%d\\r'\n",720 s);721 goto cmd_transmit_failed;722 }723 724 if (test_bit(CF_ERR_RST, &sl->cmd_flags)) {725 err = slcan_transmit_cmd(sl, "F\r");726 if (err) {727 netdev_err(dev,728 "failed to send error command 'F\\r'\n");729 goto cmd_transmit_failed;730 }731 }732 733 if (sl->can.ctrlmode & CAN_CTRLMODE_LISTENONLY) {734 err = slcan_transmit_cmd(sl, "L\r");735 if (err) {736 netdev_err(dev,737 "failed to send listen-only command 'L\\r'\n");738 goto cmd_transmit_failed;739 }740 } else {741 err = slcan_transmit_cmd(sl, "O\r");742 if (err) {743 netdev_err(dev,744 "failed to send open command 'O\\r'\n");745 goto cmd_transmit_failed;746 }747 }748 }749 750 sl->can.state = CAN_STATE_ERROR_ACTIVE;751 netif_start_queue(dev);752 return 0;753 754cmd_transmit_failed:755 close_candev(dev);756 return err;757}758 759static const struct net_device_ops slcan_netdev_ops = {760 .ndo_open = slcan_netdev_open,761 .ndo_stop = slcan_netdev_close,762 .ndo_start_xmit = slcan_netdev_xmit,763 .ndo_change_mtu = can_change_mtu,764};765 766/******************************************767 * Routines looking at TTY side.768 ******************************************/769 770/* Handle the 'receiver data ready' interrupt.771 * This function is called by the 'tty_io' module in the kernel when772 * a block of SLCAN data has been received, which can now be decapsulated773 * and sent on to some IP layer for further processing. This will not774 * be re-entered while running but other ldisc functions may be called775 * in parallel776 */777static void slcan_receive_buf(struct tty_struct *tty, const u8 *cp,778 const u8 *fp, size_t count)779{780 struct slcan *sl = tty->disc_data;781 782 if (!netif_running(sl->dev))783 return;784 785 /* Read the characters out of the buffer */786 while (count--) {787 if (fp && *fp++) {788 if (!test_and_set_bit(SLF_ERROR, &sl->flags))789 sl->dev->stats.rx_errors++;790 cp++;791 continue;792 }793 slcan_unesc(sl, *cp++);794 }795}796 797/* Open the high-level part of the SLCAN channel.798 * This function is called by the TTY module when the799 * SLCAN line discipline is called for.800 *801 * Called in process context serialized from other ldisc calls.802 */803static int slcan_open(struct tty_struct *tty)804{805 struct net_device *dev;806 struct slcan *sl;807 int err;808 809 if (!capable(CAP_NET_ADMIN))810 return -EPERM;811 812 if (!tty->ops->write)813 return -EOPNOTSUPP;814 815 dev = alloc_candev(sizeof(*sl), 1);816 if (!dev)817 return -ENFILE;818 819 sl = netdev_priv(dev);820 821 /* Configure TTY interface */822 tty->receive_room = 65536; /* We don't flow control */823 sl->rcount = 0;824 sl->xleft = 0;825 spin_lock_init(&sl->lock);826 INIT_WORK(&sl->tx_work, slcan_transmit);827 init_waitqueue_head(&sl->xcmd_wait);828 829 /* Configure CAN metadata */830 sl->can.bitrate_const = slcan_bitrate_const;831 sl->can.bitrate_const_cnt = ARRAY_SIZE(slcan_bitrate_const);832 sl->can.ctrlmode_supported = CAN_CTRLMODE_LISTENONLY;833 834 /* Configure netdev interface */835 sl->dev = dev;836 dev->netdev_ops = &slcan_netdev_ops;837 dev->ethtool_ops = &slcan_ethtool_ops;838 839 /* Mark ldisc channel as alive */840 sl->tty = tty;841 tty->disc_data = sl;842 843 err = register_candev(dev);844 if (err) {845 free_candev(dev);846 pr_err("can't register candev\n");847 return err;848 }849 850 netdev_info(dev, "slcan on %s.\n", tty->name);851 /* TTY layer expects 0 on success */852 return 0;853}854 855/* Close down a SLCAN channel.856 * This means flushing out any pending queues, and then returning. This857 * call is serialized against other ldisc functions.858 * Once this is called, no other ldisc function of ours is entered.859 *860 * We also use this method for a hangup event.861 */862static void slcan_close(struct tty_struct *tty)863{864 struct slcan *sl = tty->disc_data;865 866 unregister_candev(sl->dev);867 868 /*869 * The netdev needn't be UP (so .ndo_stop() is not called). Hence make870 * sure this is not running before freeing it up.871 */872 flush_work(&sl->tx_work);873 874 /* Mark channel as dead */875 spin_lock_bh(&sl->lock);876 tty->disc_data = NULL;877 sl->tty = NULL;878 spin_unlock_bh(&sl->lock);879 880 netdev_info(sl->dev, "slcan off %s.\n", tty->name);881 free_candev(sl->dev);882}883 884/* Perform I/O control on an active SLCAN channel. */885static int slcan_ioctl(struct tty_struct *tty, unsigned int cmd,886 unsigned long arg)887{888 struct slcan *sl = tty->disc_data;889 unsigned int tmp;890 891 switch (cmd) {892 case SIOCGIFNAME:893 tmp = strlen(sl->dev->name) + 1;894 if (copy_to_user((void __user *)arg, sl->dev->name, tmp))895 return -EFAULT;896 return 0;897 898 case SIOCSIFHWADDR:899 return -EINVAL;900 901 default:902 return tty_mode_ioctl(tty, cmd, arg);903 }904}905 906static struct tty_ldisc_ops slcan_ldisc = {907 .owner = THIS_MODULE,908 .num = N_SLCAN,909 .name = KBUILD_MODNAME,910 .open = slcan_open,911 .close = slcan_close,912 .ioctl = slcan_ioctl,913 .receive_buf = slcan_receive_buf,914 .write_wakeup = slcan_write_wakeup,915};916 917static int __init slcan_init(void)918{919 int status;920 921 pr_info("serial line CAN interface driver\n");922 923 /* Fill in our line protocol discipline, and register it */924 status = tty_register_ldisc(&slcan_ldisc);925 if (status)926 pr_err("can't register line discipline\n");927 928 return status;929}930 931static void __exit slcan_exit(void)932{933 /* This will only be called when all channels have been closed by934 * userspace - tty_ldisc.c takes care of the module's refcount.935 */936 tty_unregister_ldisc(&slcan_ldisc);937}938 939module_init(slcan_init);940module_exit(slcan_exit);941