Back to home page

OSCL-LXR

 
 

    


0001 /*
0002  * slcan.c - serial line CAN interface driver (using tty line discipline)
0003  *
0004  * This file is derived from linux/drivers/net/slip/slip.c and got
0005  * inspiration from linux/drivers/net/can/can327.c for the rework made
0006  * on the line discipline code.
0007  *
0008  * slip.c Authors  : Laurence Culhane <loz@holmes.demon.co.uk>
0009  *                   Fred N. van Kempen <waltje@uwalt.nl.mugnet.org>
0010  * slcan.c Author  : Oliver Hartkopp <socketcan@hartkopp.net>
0011  * can327.c Author : Max Staudt <max-linux@enpas.org>
0012  *
0013  * This program is free software; you can redistribute it and/or modify it
0014  * under the terms of the GNU General Public License as published by the
0015  * Free Software Foundation; either version 2 of the License, or (at your
0016  * option) any later version.
0017  *
0018  * This program is distributed in the hope that it will be useful, but
0019  * WITHOUT ANY WARRANTY; without even the implied warranty of
0020  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
0021  * General Public License for more details.
0022  *
0023  * You should have received a copy of the GNU General Public License along
0024  * with this program; if not, see http://www.gnu.org/licenses/gpl.html
0025  *
0026  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
0027  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
0028  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
0029  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
0030  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
0031  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
0032  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
0033  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
0034  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
0035  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
0036  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
0037  * DAMAGE.
0038  *
0039  */
0040 
0041 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
0042 
0043 #include <linux/module.h>
0044 
0045 #include <linux/uaccess.h>
0046 #include <linux/bitops.h>
0047 #include <linux/string.h>
0048 #include <linux/tty.h>
0049 #include <linux/errno.h>
0050 #include <linux/netdevice.h>
0051 #include <linux/skbuff.h>
0052 #include <linux/rtnetlink.h>
0053 #include <linux/init.h>
0054 #include <linux/kernel.h>
0055 #include <linux/workqueue.h>
0056 #include <linux/can.h>
0057 #include <linux/can/dev.h>
0058 #include <linux/can/skb.h>
0059 
0060 #include "slcan.h"
0061 
0062 MODULE_ALIAS_LDISC(N_SLCAN);
0063 MODULE_DESCRIPTION("serial line CAN interface");
0064 MODULE_LICENSE("GPL");
0065 MODULE_AUTHOR("Oliver Hartkopp <socketcan@hartkopp.net>");
0066 MODULE_AUTHOR("Dario Binacchi <dario.binacchi@amarulasolutions.com>");
0067 
0068 /* maximum rx buffer len: extended CAN frame with timestamp */
0069 #define SLCAN_MTU (sizeof("T1111222281122334455667788EA5F\r") + 1)
0070 
0071 #define SLCAN_CMD_LEN 1
0072 #define SLCAN_SFF_ID_LEN 3
0073 #define SLCAN_EFF_ID_LEN 8
0074 #define SLCAN_STATE_LEN 1
0075 #define SLCAN_STATE_BE_RXCNT_LEN 3
0076 #define SLCAN_STATE_BE_TXCNT_LEN 3
0077 #define SLCAN_STATE_FRAME_LEN       (1 + SLCAN_CMD_LEN + \
0078                      SLCAN_STATE_BE_RXCNT_LEN + \
0079                      SLCAN_STATE_BE_TXCNT_LEN)
0080 struct slcan {
0081     struct can_priv         can;
0082 
0083     /* Various fields. */
0084     struct tty_struct   *tty;       /* ptr to TTY structure      */
0085     struct net_device   *dev;       /* easy for intr handling    */
0086     spinlock_t      lock;
0087     struct work_struct  tx_work;    /* Flushes transmit buffer   */
0088 
0089     /* These are pointers to the malloc()ed frame buffers. */
0090     unsigned char       rbuff[SLCAN_MTU];   /* receiver buffer   */
0091     int         rcount;         /* received chars counter    */
0092     unsigned char       xbuff[SLCAN_MTU];   /* transmitter buffer*/
0093     unsigned char       *xhead;         /* pointer to next XMIT byte */
0094     int         xleft;          /* bytes left in XMIT queue  */
0095 
0096     unsigned long       flags;      /* Flag values/ mode etc     */
0097 #define SLF_ERROR       0               /* Parity, etc. error        */
0098 #define SLF_XCMD        1               /* Command transmission      */
0099     unsigned long           cmd_flags;      /* Command flags             */
0100 #define CF_ERR_RST      0               /* Reset errors on open      */
0101     wait_queue_head_t       xcmd_wait;      /* Wait queue for commands   */
0102                         /* transmission              */
0103 };
0104 
0105 static const u32 slcan_bitrate_const[] = {
0106     10000, 20000, 50000, 100000, 125000,
0107     250000, 500000, 800000, 1000000
0108 };
0109 
0110 bool slcan_err_rst_on_open(struct net_device *ndev)
0111 {
0112     struct slcan *sl = netdev_priv(ndev);
0113 
0114     return !!test_bit(CF_ERR_RST, &sl->cmd_flags);
0115 }
0116 
0117 int slcan_enable_err_rst_on_open(struct net_device *ndev, bool on)
0118 {
0119     struct slcan *sl = netdev_priv(ndev);
0120 
0121     if (netif_running(ndev))
0122         return -EBUSY;
0123 
0124     if (on)
0125         set_bit(CF_ERR_RST, &sl->cmd_flags);
0126     else
0127         clear_bit(CF_ERR_RST, &sl->cmd_flags);
0128 
0129     return 0;
0130 }
0131 
0132 /*************************************************************************
0133  *          SLCAN ENCAPSULATION FORMAT           *
0134  *************************************************************************/
0135 
0136 /* A CAN frame has a can_id (11 bit standard frame format OR 29 bit extended
0137  * frame format) a data length code (len) which can be from 0 to 8
0138  * and up to <len> data bytes as payload.
0139  * Additionally a CAN frame may become a remote transmission frame if the
0140  * RTR-bit is set. This causes another ECU to send a CAN frame with the
0141  * given can_id.
0142  *
0143  * The SLCAN ASCII representation of these different frame types is:
0144  * <type> <id> <dlc> <data>*
0145  *
0146  * Extended frames (29 bit) are defined by capital characters in the type.
0147  * RTR frames are defined as 'r' types - normal frames have 't' type:
0148  * t => 11 bit data frame
0149  * r => 11 bit RTR frame
0150  * T => 29 bit data frame
0151  * R => 29 bit RTR frame
0152  *
0153  * The <id> is 3 (standard) or 8 (extended) bytes in ASCII Hex (base64).
0154  * The <dlc> is a one byte ASCII number ('0' - '8')
0155  * The <data> section has at much ASCII Hex bytes as defined by the <dlc>
0156  *
0157  * Examples:
0158  *
0159  * t1230 : can_id 0x123, len 0, no data
0160  * t4563112233 : can_id 0x456, len 3, data 0x11 0x22 0x33
0161  * T12ABCDEF2AA55 : extended can_id 0x12ABCDEF, len 2, data 0xAA 0x55
0162  * r1230 : can_id 0x123, len 0, no data, remote transmission request
0163  *
0164  */
0165 
0166 /*************************************************************************
0167  *          STANDARD SLCAN DECAPSULATION             *
0168  *************************************************************************/
0169 
0170 /* Send one completely decapsulated can_frame to the network layer */
0171 static void slcan_bump_frame(struct slcan *sl)
0172 {
0173     struct sk_buff *skb;
0174     struct can_frame *cf;
0175     int i, tmp;
0176     u32 tmpid;
0177     char *cmd = sl->rbuff;
0178 
0179     skb = alloc_can_skb(sl->dev, &cf);
0180     if (unlikely(!skb)) {
0181         sl->dev->stats.rx_dropped++;
0182         return;
0183     }
0184 
0185     switch (*cmd) {
0186     case 'r':
0187         cf->can_id = CAN_RTR_FLAG;
0188         fallthrough;
0189     case 't':
0190         /* store dlc ASCII value and terminate SFF CAN ID string */
0191         cf->len = sl->rbuff[SLCAN_CMD_LEN + SLCAN_SFF_ID_LEN];
0192         sl->rbuff[SLCAN_CMD_LEN + SLCAN_SFF_ID_LEN] = 0;
0193         /* point to payload data behind the dlc */
0194         cmd += SLCAN_CMD_LEN + SLCAN_SFF_ID_LEN + 1;
0195         break;
0196     case 'R':
0197         cf->can_id = CAN_RTR_FLAG;
0198         fallthrough;
0199     case 'T':
0200         cf->can_id |= CAN_EFF_FLAG;
0201         /* store dlc ASCII value and terminate EFF CAN ID string */
0202         cf->len = sl->rbuff[SLCAN_CMD_LEN + SLCAN_EFF_ID_LEN];
0203         sl->rbuff[SLCAN_CMD_LEN + SLCAN_EFF_ID_LEN] = 0;
0204         /* point to payload data behind the dlc */
0205         cmd += SLCAN_CMD_LEN + SLCAN_EFF_ID_LEN + 1;
0206         break;
0207     default:
0208         goto decode_failed;
0209     }
0210 
0211     if (kstrtou32(sl->rbuff + SLCAN_CMD_LEN, 16, &tmpid))
0212         goto decode_failed;
0213 
0214     cf->can_id |= tmpid;
0215 
0216     /* get len from sanitized ASCII value */
0217     if (cf->len >= '0' && cf->len < '9')
0218         cf->len -= '0';
0219     else
0220         goto decode_failed;
0221 
0222     /* RTR frames may have a dlc > 0 but they never have any data bytes */
0223     if (!(cf->can_id & CAN_RTR_FLAG)) {
0224         for (i = 0; i < cf->len; i++) {
0225             tmp = hex_to_bin(*cmd++);
0226             if (tmp < 0)
0227                 goto decode_failed;
0228 
0229             cf->data[i] = (tmp << 4);
0230             tmp = hex_to_bin(*cmd++);
0231             if (tmp < 0)
0232                 goto decode_failed;
0233 
0234             cf->data[i] |= tmp;
0235         }
0236     }
0237 
0238     sl->dev->stats.rx_packets++;
0239     if (!(cf->can_id & CAN_RTR_FLAG))
0240         sl->dev->stats.rx_bytes += cf->len;
0241 
0242     netif_rx(skb);
0243     return;
0244 
0245 decode_failed:
0246     sl->dev->stats.rx_errors++;
0247     dev_kfree_skb(skb);
0248 }
0249 
0250 /* A change state frame must contain state info and receive and transmit
0251  * error counters.
0252  *
0253  * Examples:
0254  *
0255  * sb256256 : state bus-off: rx counter 256, tx counter 256
0256  * sa057033 : state active, rx counter 57, tx counter 33
0257  */
0258 static void slcan_bump_state(struct slcan *sl)
0259 {
0260     struct net_device *dev = sl->dev;
0261     struct sk_buff *skb;
0262     struct can_frame *cf;
0263     char *cmd = sl->rbuff;
0264     u32 rxerr, txerr;
0265     enum can_state state, rx_state, tx_state;
0266 
0267     switch (cmd[1]) {
0268     case 'a':
0269         state = CAN_STATE_ERROR_ACTIVE;
0270         break;
0271     case 'w':
0272         state = CAN_STATE_ERROR_WARNING;
0273         break;
0274     case 'p':
0275         state = CAN_STATE_ERROR_PASSIVE;
0276         break;
0277     case 'b':
0278         state = CAN_STATE_BUS_OFF;
0279         break;
0280     default:
0281         return;
0282     }
0283 
0284     if (state == sl->can.state || sl->rcount < SLCAN_STATE_FRAME_LEN)
0285         return;
0286 
0287     cmd += SLCAN_STATE_BE_RXCNT_LEN + SLCAN_CMD_LEN + 1;
0288     cmd[SLCAN_STATE_BE_TXCNT_LEN] = 0;
0289     if (kstrtou32(cmd, 10, &txerr))
0290         return;
0291 
0292     *cmd = 0;
0293     cmd -= SLCAN_STATE_BE_RXCNT_LEN;
0294     if (kstrtou32(cmd, 10, &rxerr))
0295         return;
0296 
0297     skb = alloc_can_err_skb(dev, &cf);
0298 
0299     tx_state = txerr >= rxerr ? state : 0;
0300     rx_state = txerr <= rxerr ? state : 0;
0301     can_change_state(dev, cf, tx_state, rx_state);
0302 
0303     if (state == CAN_STATE_BUS_OFF) {
0304         can_bus_off(dev);
0305     } else if (skb) {
0306         cf->can_id |= CAN_ERR_CNT;
0307         cf->data[6] = txerr;
0308         cf->data[7] = rxerr;
0309     }
0310 
0311     if (skb)
0312         netif_rx(skb);
0313 }
0314 
0315 /* An error frame can contain more than one type of error.
0316  *
0317  * Examples:
0318  *
0319  * e1a : len 1, errors: ACK error
0320  * e3bcO: len 3, errors: Bit0 error, CRC error, Tx overrun error
0321  */
0322 static void slcan_bump_err(struct slcan *sl)
0323 {
0324     struct net_device *dev = sl->dev;
0325     struct sk_buff *skb;
0326     struct can_frame *cf;
0327     char *cmd = sl->rbuff;
0328     bool rx_errors = false, tx_errors = false, rx_over_errors = false;
0329     int i, len;
0330 
0331     /* get len from sanitized ASCII value */
0332     len = cmd[1];
0333     if (len >= '0' && len < '9')
0334         len -= '0';
0335     else
0336         return;
0337 
0338     if ((len + SLCAN_CMD_LEN + 1) > sl->rcount)
0339         return;
0340 
0341     skb = alloc_can_err_skb(dev, &cf);
0342 
0343     if (skb)
0344         cf->can_id |= CAN_ERR_PROT | CAN_ERR_BUSERROR;
0345 
0346     cmd += SLCAN_CMD_LEN + 1;
0347     for (i = 0; i < len; i++, cmd++) {
0348         switch (*cmd) {
0349         case 'a':
0350             netdev_dbg(dev, "ACK error\n");
0351             tx_errors = true;
0352             if (skb) {
0353                 cf->can_id |= CAN_ERR_ACK;
0354                 cf->data[3] = CAN_ERR_PROT_LOC_ACK;
0355             }
0356 
0357             break;
0358         case 'b':
0359             netdev_dbg(dev, "Bit0 error\n");
0360             tx_errors = true;
0361             if (skb)
0362                 cf->data[2] |= CAN_ERR_PROT_BIT0;
0363 
0364             break;
0365         case 'B':
0366             netdev_dbg(dev, "Bit1 error\n");
0367             tx_errors = true;
0368             if (skb)
0369                 cf->data[2] |= CAN_ERR_PROT_BIT1;
0370 
0371             break;
0372         case 'c':
0373             netdev_dbg(dev, "CRC error\n");
0374             rx_errors = true;
0375             if (skb) {
0376                 cf->data[2] |= CAN_ERR_PROT_BIT;
0377                 cf->data[3] = CAN_ERR_PROT_LOC_CRC_SEQ;
0378             }
0379 
0380             break;
0381         case 'f':
0382             netdev_dbg(dev, "Form Error\n");
0383             rx_errors = true;
0384             if (skb)
0385                 cf->data[2] |= CAN_ERR_PROT_FORM;
0386 
0387             break;
0388         case 'o':
0389             netdev_dbg(dev, "Rx overrun error\n");
0390             rx_over_errors = true;
0391             rx_errors = true;
0392             if (skb) {
0393                 cf->can_id |= CAN_ERR_CRTL;
0394                 cf->data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
0395             }
0396 
0397             break;
0398         case 'O':
0399             netdev_dbg(dev, "Tx overrun error\n");
0400             tx_errors = true;
0401             if (skb) {
0402                 cf->can_id |= CAN_ERR_CRTL;
0403                 cf->data[1] = CAN_ERR_CRTL_TX_OVERFLOW;
0404             }
0405 
0406             break;
0407         case 's':
0408             netdev_dbg(dev, "Stuff error\n");
0409             rx_errors = true;
0410             if (skb)
0411                 cf->data[2] |= CAN_ERR_PROT_STUFF;
0412 
0413             break;
0414         default:
0415             if (skb)
0416                 dev_kfree_skb(skb);
0417 
0418             return;
0419         }
0420     }
0421 
0422     if (rx_errors)
0423         dev->stats.rx_errors++;
0424 
0425     if (rx_over_errors)
0426         dev->stats.rx_over_errors++;
0427 
0428     if (tx_errors)
0429         dev->stats.tx_errors++;
0430 
0431     if (skb)
0432         netif_rx(skb);
0433 }
0434 
0435 static void slcan_bump(struct slcan *sl)
0436 {
0437     switch (sl->rbuff[0]) {
0438     case 'r':
0439         fallthrough;
0440     case 't':
0441         fallthrough;
0442     case 'R':
0443         fallthrough;
0444     case 'T':
0445         return slcan_bump_frame(sl);
0446     case 'e':
0447         return slcan_bump_err(sl);
0448     case 's':
0449         return slcan_bump_state(sl);
0450     default:
0451         return;
0452     }
0453 }
0454 
0455 /* parse tty input stream */
0456 static void slcan_unesc(struct slcan *sl, unsigned char s)
0457 {
0458     if ((s == '\r') || (s == '\a')) { /* CR or BEL ends the pdu */
0459         if (!test_and_clear_bit(SLF_ERROR, &sl->flags) &&
0460             sl->rcount > 4)
0461             slcan_bump(sl);
0462 
0463         sl->rcount = 0;
0464     } else {
0465         if (!test_bit(SLF_ERROR, &sl->flags))  {
0466             if (sl->rcount < SLCAN_MTU)  {
0467                 sl->rbuff[sl->rcount++] = s;
0468                 return;
0469             }
0470 
0471             sl->dev->stats.rx_over_errors++;
0472             set_bit(SLF_ERROR, &sl->flags);
0473         }
0474     }
0475 }
0476 
0477 /*************************************************************************
0478  *          STANDARD SLCAN ENCAPSULATION             *
0479  *************************************************************************/
0480 
0481 /* Encapsulate one can_frame and stuff into a TTY queue. */
0482 static void slcan_encaps(struct slcan *sl, struct can_frame *cf)
0483 {
0484     int actual, i;
0485     unsigned char *pos;
0486     unsigned char *endpos;
0487     canid_t id = cf->can_id;
0488 
0489     pos = sl->xbuff;
0490 
0491     if (cf->can_id & CAN_RTR_FLAG)
0492         *pos = 'R'; /* becomes 'r' in standard frame format (SFF) */
0493     else
0494         *pos = 'T'; /* becomes 't' in standard frame format (SSF) */
0495 
0496     /* determine number of chars for the CAN-identifier */
0497     if (cf->can_id & CAN_EFF_FLAG) {
0498         id &= CAN_EFF_MASK;
0499         endpos = pos + SLCAN_EFF_ID_LEN;
0500     } else {
0501         *pos |= 0x20; /* convert R/T to lower case for SFF */
0502         id &= CAN_SFF_MASK;
0503         endpos = pos + SLCAN_SFF_ID_LEN;
0504     }
0505 
0506     /* build 3 (SFF) or 8 (EFF) digit CAN identifier */
0507     pos++;
0508     while (endpos >= pos) {
0509         *endpos-- = hex_asc_upper[id & 0xf];
0510         id >>= 4;
0511     }
0512 
0513     pos += (cf->can_id & CAN_EFF_FLAG) ?
0514         SLCAN_EFF_ID_LEN : SLCAN_SFF_ID_LEN;
0515 
0516     *pos++ = cf->len + '0';
0517 
0518     /* RTR frames may have a dlc > 0 but they never have any data bytes */
0519     if (!(cf->can_id & CAN_RTR_FLAG)) {
0520         for (i = 0; i < cf->len; i++)
0521             pos = hex_byte_pack_upper(pos, cf->data[i]);
0522 
0523         sl->dev->stats.tx_bytes += cf->len;
0524     }
0525 
0526     *pos++ = '\r';
0527 
0528     /* Order of next two lines is *very* important.
0529      * When we are sending a little amount of data,
0530      * the transfer may be completed inside the ops->write()
0531      * routine, because it's running with interrupts enabled.
0532      * In this case we *never* got WRITE_WAKEUP event,
0533      * if we did not request it before write operation.
0534      *       14 Oct 1994  Dmitry Gorodchanin.
0535      */
0536     set_bit(TTY_DO_WRITE_WAKEUP, &sl->tty->flags);
0537     actual = sl->tty->ops->write(sl->tty, sl->xbuff, pos - sl->xbuff);
0538     sl->xleft = (pos - sl->xbuff) - actual;
0539     sl->xhead = sl->xbuff + actual;
0540 }
0541 
0542 /* Write out any remaining transmit buffer. Scheduled when tty is writable */
0543 static void slcan_transmit(struct work_struct *work)
0544 {
0545     struct slcan *sl = container_of(work, struct slcan, tx_work);
0546     int actual;
0547 
0548     spin_lock_bh(&sl->lock);
0549     /* First make sure we're connected. */
0550     if (unlikely(!netif_running(sl->dev)) &&
0551         likely(!test_bit(SLF_XCMD, &sl->flags))) {
0552         spin_unlock_bh(&sl->lock);
0553         return;
0554     }
0555 
0556     if (sl->xleft <= 0)  {
0557         if (unlikely(test_bit(SLF_XCMD, &sl->flags))) {
0558             clear_bit(SLF_XCMD, &sl->flags);
0559             clear_bit(TTY_DO_WRITE_WAKEUP, &sl->tty->flags);
0560             spin_unlock_bh(&sl->lock);
0561             wake_up(&sl->xcmd_wait);
0562             return;
0563         }
0564 
0565         /* Now serial buffer is almost free & we can start
0566          * transmission of another packet
0567          */
0568         sl->dev->stats.tx_packets++;
0569         clear_bit(TTY_DO_WRITE_WAKEUP, &sl->tty->flags);
0570         spin_unlock_bh(&sl->lock);
0571         netif_wake_queue(sl->dev);
0572         return;
0573     }
0574 
0575     actual = sl->tty->ops->write(sl->tty, sl->xhead, sl->xleft);
0576     sl->xleft -= actual;
0577     sl->xhead += actual;
0578     spin_unlock_bh(&sl->lock);
0579 }
0580 
0581 /* Called by the driver when there's room for more data.
0582  * Schedule the transmit.
0583  */
0584 static void slcan_write_wakeup(struct tty_struct *tty)
0585 {
0586     struct slcan *sl = (struct slcan *)tty->disc_data;
0587 
0588     schedule_work(&sl->tx_work);
0589 }
0590 
0591 /* Send a can_frame to a TTY queue. */
0592 static netdev_tx_t slcan_netdev_xmit(struct sk_buff *skb,
0593                      struct net_device *dev)
0594 {
0595     struct slcan *sl = netdev_priv(dev);
0596 
0597     if (can_dropped_invalid_skb(dev, skb))
0598         return NETDEV_TX_OK;
0599 
0600     spin_lock(&sl->lock);
0601     if (!netif_running(dev))  {
0602         spin_unlock(&sl->lock);
0603         netdev_warn(dev, "xmit: iface is down\n");
0604         goto out;
0605     }
0606     if (!sl->tty) {
0607         spin_unlock(&sl->lock);
0608         goto out;
0609     }
0610 
0611     netif_stop_queue(sl->dev);
0612     slcan_encaps(sl, (struct can_frame *)skb->data); /* encaps & send */
0613     spin_unlock(&sl->lock);
0614 
0615     skb_tx_timestamp(skb);
0616 
0617 out:
0618     kfree_skb(skb);
0619     return NETDEV_TX_OK;
0620 }
0621 
0622 /******************************************
0623  *   Routines looking at netdevice side.
0624  ******************************************/
0625 
0626 static int slcan_transmit_cmd(struct slcan *sl, const unsigned char *cmd)
0627 {
0628     int ret, actual, n;
0629 
0630     spin_lock(&sl->lock);
0631     if (!sl->tty) {
0632         spin_unlock(&sl->lock);
0633         return -ENODEV;
0634     }
0635 
0636     n = scnprintf(sl->xbuff, sizeof(sl->xbuff), "%s", cmd);
0637     set_bit(TTY_DO_WRITE_WAKEUP, &sl->tty->flags);
0638     actual = sl->tty->ops->write(sl->tty, sl->xbuff, n);
0639     sl->xleft = n - actual;
0640     sl->xhead = sl->xbuff + actual;
0641     set_bit(SLF_XCMD, &sl->flags);
0642     spin_unlock(&sl->lock);
0643     ret = wait_event_interruptible_timeout(sl->xcmd_wait,
0644                            !test_bit(SLF_XCMD, &sl->flags),
0645                            HZ);
0646     clear_bit(SLF_XCMD, &sl->flags);
0647     if (ret == -ERESTARTSYS)
0648         return ret;
0649 
0650     if (ret == 0)
0651         return -ETIMEDOUT;
0652 
0653     return 0;
0654 }
0655 
0656 /* Netdevice UP -> DOWN routine */
0657 static int slcan_netdev_close(struct net_device *dev)
0658 {
0659     struct slcan *sl = netdev_priv(dev);
0660     int err;
0661 
0662     if (sl->can.bittiming.bitrate &&
0663         sl->can.bittiming.bitrate != CAN_BITRATE_UNKNOWN) {
0664         err = slcan_transmit_cmd(sl, "C\r");
0665         if (err)
0666             netdev_warn(dev,
0667                     "failed to send close command 'C\\r'\n");
0668     }
0669 
0670     /* TTY discipline is running. */
0671     clear_bit(TTY_DO_WRITE_WAKEUP, &sl->tty->flags);
0672     flush_work(&sl->tx_work);
0673 
0674     netif_stop_queue(dev);
0675     sl->rcount   = 0;
0676     sl->xleft    = 0;
0677     close_candev(dev);
0678     sl->can.state = CAN_STATE_STOPPED;
0679     if (sl->can.bittiming.bitrate == CAN_BITRATE_UNKNOWN)
0680         sl->can.bittiming.bitrate = CAN_BITRATE_UNSET;
0681 
0682     return 0;
0683 }
0684 
0685 /* Netdevice DOWN -> UP routine */
0686 static int slcan_netdev_open(struct net_device *dev)
0687 {
0688     struct slcan *sl = netdev_priv(dev);
0689     unsigned char cmd[SLCAN_MTU];
0690     int err, s;
0691 
0692     /* The baud rate is not set with the command
0693      * `ip link set <iface> type can bitrate <baud>' and therefore
0694      * can.bittiming.bitrate is CAN_BITRATE_UNSET (0), causing
0695      * open_candev() to fail. So let's set to a fake value.
0696      */
0697     if (sl->can.bittiming.bitrate == CAN_BITRATE_UNSET)
0698         sl->can.bittiming.bitrate = CAN_BITRATE_UNKNOWN;
0699 
0700     err = open_candev(dev);
0701     if (err) {
0702         netdev_err(dev, "failed to open can device\n");
0703         return err;
0704     }
0705 
0706     if (sl->can.bittiming.bitrate != CAN_BITRATE_UNKNOWN) {
0707         for (s = 0; s < ARRAY_SIZE(slcan_bitrate_const); s++) {
0708             if (sl->can.bittiming.bitrate == slcan_bitrate_const[s])
0709                 break;
0710         }
0711 
0712         /* The CAN framework has already validate the bitrate value,
0713          * so we can avoid to check if `s' has been properly set.
0714          */
0715         snprintf(cmd, sizeof(cmd), "C\rS%d\r", s);
0716         err = slcan_transmit_cmd(sl, cmd);
0717         if (err) {
0718             netdev_err(dev,
0719                    "failed to send bitrate command 'C\\rS%d\\r'\n",
0720                    s);
0721             goto cmd_transmit_failed;
0722         }
0723 
0724         if (test_bit(CF_ERR_RST, &sl->cmd_flags)) {
0725             err = slcan_transmit_cmd(sl, "F\r");
0726             if (err) {
0727                 netdev_err(dev,
0728                        "failed to send error command 'F\\r'\n");
0729                 goto cmd_transmit_failed;
0730             }
0731         }
0732 
0733         if (sl->can.ctrlmode & CAN_CTRLMODE_LISTENONLY) {
0734             err = slcan_transmit_cmd(sl, "L\r");
0735             if (err) {
0736                 netdev_err(dev,
0737                        "failed to send listen-only command 'L\\r'\n");
0738                 goto cmd_transmit_failed;
0739             }
0740         } else {
0741             err = slcan_transmit_cmd(sl, "O\r");
0742             if (err) {
0743                 netdev_err(dev,
0744                        "failed to send open command 'O\\r'\n");
0745                 goto cmd_transmit_failed;
0746             }
0747         }
0748     }
0749 
0750     sl->can.state = CAN_STATE_ERROR_ACTIVE;
0751     netif_start_queue(dev);
0752     return 0;
0753 
0754 cmd_transmit_failed:
0755     close_candev(dev);
0756     return err;
0757 }
0758 
0759 static const struct net_device_ops slcan_netdev_ops = {
0760     .ndo_open               = slcan_netdev_open,
0761     .ndo_stop               = slcan_netdev_close,
0762     .ndo_start_xmit         = slcan_netdev_xmit,
0763     .ndo_change_mtu         = can_change_mtu,
0764 };
0765 
0766 /******************************************
0767  *  Routines looking at TTY side.
0768  ******************************************/
0769 
0770 /* Handle the 'receiver data ready' interrupt.
0771  * This function is called by the 'tty_io' module in the kernel when
0772  * a block of SLCAN data has been received, which can now be decapsulated
0773  * and sent on to some IP layer for further processing. This will not
0774  * be re-entered while running but other ldisc functions may be called
0775  * in parallel
0776  */
0777 static void slcan_receive_buf(struct tty_struct *tty,
0778                   const unsigned char *cp, const char *fp,
0779                   int count)
0780 {
0781     struct slcan *sl = (struct slcan *)tty->disc_data;
0782 
0783     if (!netif_running(sl->dev))
0784         return;
0785 
0786     /* Read the characters out of the buffer */
0787     while (count--) {
0788         if (fp && *fp++) {
0789             if (!test_and_set_bit(SLF_ERROR, &sl->flags))
0790                 sl->dev->stats.rx_errors++;
0791             cp++;
0792             continue;
0793         }
0794         slcan_unesc(sl, *cp++);
0795     }
0796 }
0797 
0798 /* Open the high-level part of the SLCAN channel.
0799  * This function is called by the TTY module when the
0800  * SLCAN line discipline is called for.
0801  *
0802  * Called in process context serialized from other ldisc calls.
0803  */
0804 static int slcan_open(struct tty_struct *tty)
0805 {
0806     struct net_device *dev;
0807     struct slcan *sl;
0808     int err;
0809 
0810     if (!capable(CAP_NET_ADMIN))
0811         return -EPERM;
0812 
0813     if (!tty->ops->write)
0814         return -EOPNOTSUPP;
0815 
0816     dev = alloc_candev(sizeof(*sl), 1);
0817     if (!dev)
0818         return -ENFILE;
0819 
0820     sl = netdev_priv(dev);
0821 
0822     /* Configure TTY interface */
0823     tty->receive_room = 65536; /* We don't flow control */
0824     sl->rcount = 0;
0825     sl->xleft = 0;
0826     spin_lock_init(&sl->lock);
0827     INIT_WORK(&sl->tx_work, slcan_transmit);
0828     init_waitqueue_head(&sl->xcmd_wait);
0829 
0830     /* Configure CAN metadata */
0831     sl->can.bitrate_const = slcan_bitrate_const;
0832     sl->can.bitrate_const_cnt = ARRAY_SIZE(slcan_bitrate_const);
0833     sl->can.ctrlmode_supported = CAN_CTRLMODE_LISTENONLY;
0834 
0835     /* Configure netdev interface */
0836     sl->dev = dev;
0837     dev->netdev_ops = &slcan_netdev_ops;
0838     dev->ethtool_ops = &slcan_ethtool_ops;
0839 
0840     /* Mark ldisc channel as alive */
0841     sl->tty = tty;
0842     tty->disc_data = sl;
0843 
0844     err = register_candev(dev);
0845     if (err) {
0846         free_candev(dev);
0847         pr_err("can't register candev\n");
0848         return err;
0849     }
0850 
0851     netdev_info(dev, "slcan on %s.\n", tty->name);
0852     /* TTY layer expects 0 on success */
0853     return 0;
0854 }
0855 
0856 /* Close down a SLCAN channel.
0857  * This means flushing out any pending queues, and then returning. This
0858  * call is serialized against other ldisc functions.
0859  * Once this is called, no other ldisc function of ours is entered.
0860  *
0861  * We also use this method for a hangup event.
0862  */
0863 static void slcan_close(struct tty_struct *tty)
0864 {
0865     struct slcan *sl = (struct slcan *)tty->disc_data;
0866 
0867     /* unregister_netdev() calls .ndo_stop() so we don't have to.
0868      * Our .ndo_stop() also flushes the TTY write wakeup handler,
0869      * so we can safely set sl->tty = NULL after this.
0870      */
0871     unregister_candev(sl->dev);
0872 
0873     /* Mark channel as dead */
0874     spin_lock_bh(&sl->lock);
0875     tty->disc_data = NULL;
0876     sl->tty = NULL;
0877     spin_unlock_bh(&sl->lock);
0878 
0879     netdev_info(sl->dev, "slcan off %s.\n", tty->name);
0880     free_candev(sl->dev);
0881 }
0882 
0883 /* Perform I/O control on an active SLCAN channel. */
0884 static int slcan_ioctl(struct tty_struct *tty, unsigned int cmd,
0885                unsigned long arg)
0886 {
0887     struct slcan *sl = (struct slcan *)tty->disc_data;
0888     unsigned int tmp;
0889 
0890     switch (cmd) {
0891     case SIOCGIFNAME:
0892         tmp = strlen(sl->dev->name) + 1;
0893         if (copy_to_user((void __user *)arg, sl->dev->name, tmp))
0894             return -EFAULT;
0895         return 0;
0896 
0897     case SIOCSIFHWADDR:
0898         return -EINVAL;
0899 
0900     default:
0901         return tty_mode_ioctl(tty, cmd, arg);
0902     }
0903 }
0904 
0905 static struct tty_ldisc_ops slcan_ldisc = {
0906     .owner      = THIS_MODULE,
0907     .num        = N_SLCAN,
0908     .name       = KBUILD_MODNAME,
0909     .open       = slcan_open,
0910     .close      = slcan_close,
0911     .ioctl      = slcan_ioctl,
0912     .receive_buf    = slcan_receive_buf,
0913     .write_wakeup   = slcan_write_wakeup,
0914 };
0915 
0916 static int __init slcan_init(void)
0917 {
0918     int status;
0919 
0920     pr_info("serial line CAN interface driver\n");
0921 
0922     /* Fill in our line protocol discipline, and register it */
0923     status = tty_register_ldisc(&slcan_ldisc);
0924     if (status)
0925         pr_err("can't register line discipline\n");
0926 
0927     return status;
0928 }
0929 
0930 static void __exit slcan_exit(void)
0931 {
0932     /* This will only be called when all channels have been closed by
0933      * userspace - tty_ldisc.c takes care of the module's refcount.
0934      */
0935     tty_unregister_ldisc(&slcan_ldisc);
0936 }
0937 
0938 module_init(slcan_init);
0939 module_exit(slcan_exit);