ead3afefcf19d20a1a06dd0d4aad06e81e8d1bdb
[linux-2.6-block.git] / drivers / net / can / slcan / slcan-core.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
5  *
6  * slip.c Authors  : Laurence Culhane <loz@holmes.demon.co.uk>
7  *                   Fred N. van Kempen <waltje@uwalt.nl.mugnet.org>
8  * slcan.c Author  : Oliver Hartkopp <socketcan@hartkopp.net>
9  *
10  * This program is free software; you can redistribute it and/or modify it
11  * under the terms of the GNU General Public License as published by the
12  * Free Software Foundation; either version 2 of the License, or (at your
13  * option) any later version.
14  *
15  * This program is distributed in the hope that it will be useful, but
16  * WITHOUT ANY WARRANTY; without even the implied warranty of
17  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18  * General Public License for more details.
19  *
20  * You should have received a copy of the GNU General Public License along
21  * with this program; if not, see http://www.gnu.org/licenses/gpl.html
22  *
23  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
24  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
25  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
26  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
27  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
28  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
29  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
30  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
31  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
32  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
33  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
34  * DAMAGE.
35  *
36  */
37
38 #include <linux/module.h>
39 #include <linux/moduleparam.h>
40
41 #include <linux/uaccess.h>
42 #include <linux/bitops.h>
43 #include <linux/string.h>
44 #include <linux/tty.h>
45 #include <linux/errno.h>
46 #include <linux/netdevice.h>
47 #include <linux/skbuff.h>
48 #include <linux/rtnetlink.h>
49 #include <linux/if_arp.h>
50 #include <linux/if_ether.h>
51 #include <linux/sched.h>
52 #include <linux/delay.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
62 MODULE_ALIAS_LDISC(N_SLCAN);
63 MODULE_DESCRIPTION("serial line CAN interface");
64 MODULE_LICENSE("GPL");
65 MODULE_AUTHOR("Oliver Hartkopp <socketcan@hartkopp.net>");
66
67 #define SLCAN_MAGIC 0x53CA
68
69 static int maxdev = 10;         /* MAX number of SLCAN channels;
70                                  * This can be overridden with
71                                  * insmod slcan.ko maxdev=nnn
72                                  */
73 module_param(maxdev, int, 0);
74 MODULE_PARM_DESC(maxdev, "Maximum number of slcan interfaces");
75
76 /* maximum rx buffer len: extended CAN frame with timestamp */
77 #define SLC_MTU (sizeof("T1111222281122334455667788EA5F\r")+1)
78
79 #define SLC_CMD_LEN 1
80 #define SLC_SFF_ID_LEN 3
81 #define SLC_EFF_ID_LEN 8
82 #define SLC_STATE_LEN 1
83 #define SLC_STATE_BE_RXCNT_LEN 3
84 #define SLC_STATE_BE_TXCNT_LEN 3
85 #define SLC_STATE_FRAME_LEN       (1 + SLC_CMD_LEN + SLC_STATE_BE_RXCNT_LEN + \
86                                    SLC_STATE_BE_TXCNT_LEN)
87 struct slcan {
88         struct can_priv         can;
89         int                     magic;
90
91         /* Various fields. */
92         struct tty_struct       *tty;           /* ptr to TTY structure      */
93         struct net_device       *dev;           /* easy for intr handling    */
94         spinlock_t              lock;
95         struct work_struct      tx_work;        /* Flushes transmit buffer   */
96
97         /* These are pointers to the malloc()ed frame buffers. */
98         unsigned char           rbuff[SLC_MTU]; /* receiver buffer           */
99         int                     rcount;         /* received chars counter    */
100         unsigned char           xbuff[SLC_MTU]; /* transmitter buffer        */
101         unsigned char           *xhead;         /* pointer to next XMIT byte */
102         int                     xleft;          /* bytes left in XMIT queue  */
103
104         unsigned long           flags;          /* Flag values/ mode etc     */
105 #define SLF_INUSE               0               /* Channel in use            */
106 #define SLF_ERROR               1               /* Parity, etc. error        */
107 #define SLF_XCMD                2               /* Command transmission      */
108         unsigned long           cmd_flags;      /* Command flags             */
109 #define CF_ERR_RST              0               /* Reset errors on open      */
110         wait_queue_head_t       xcmd_wait;      /* Wait queue for commands   */
111                                                 /* transmission              */
112 };
113
114 static struct net_device **slcan_devs;
115
116 static const u32 slcan_bitrate_const[] = {
117         10000, 20000, 50000, 100000, 125000,
118         250000, 500000, 800000, 1000000
119 };
120
121 bool slcan_err_rst_on_open(struct net_device *ndev)
122 {
123         struct slcan *sl = netdev_priv(ndev);
124
125         return !!test_bit(CF_ERR_RST, &sl->cmd_flags);
126 }
127
128 int slcan_enable_err_rst_on_open(struct net_device *ndev, bool on)
129 {
130         struct slcan *sl = netdev_priv(ndev);
131
132         if (netif_running(ndev))
133                 return -EBUSY;
134
135         if (on)
136                 set_bit(CF_ERR_RST, &sl->cmd_flags);
137         else
138                 clear_bit(CF_ERR_RST, &sl->cmd_flags);
139
140         return 0;
141 }
142
143 /*************************************************************************
144  *                      SLCAN ENCAPSULATION FORMAT                       *
145  *************************************************************************/
146
147 /* A CAN frame has a can_id (11 bit standard frame format OR 29 bit extended
148  * frame format) a data length code (len) which can be from 0 to 8
149  * and up to <len> data bytes as payload.
150  * Additionally a CAN frame may become a remote transmission frame if the
151  * RTR-bit is set. This causes another ECU to send a CAN frame with the
152  * given can_id.
153  *
154  * The SLCAN ASCII representation of these different frame types is:
155  * <type> <id> <dlc> <data>*
156  *
157  * Extended frames (29 bit) are defined by capital characters in the type.
158  * RTR frames are defined as 'r' types - normal frames have 't' type:
159  * t => 11 bit data frame
160  * r => 11 bit RTR frame
161  * T => 29 bit data frame
162  * R => 29 bit RTR frame
163  *
164  * The <id> is 3 (standard) or 8 (extended) bytes in ASCII Hex (base64).
165  * The <dlc> is a one byte ASCII number ('0' - '8')
166  * The <data> section has at much ASCII Hex bytes as defined by the <dlc>
167  *
168  * Examples:
169  *
170  * t1230 : can_id 0x123, len 0, no data
171  * t4563112233 : can_id 0x456, len 3, data 0x11 0x22 0x33
172  * T12ABCDEF2AA55 : extended can_id 0x12ABCDEF, len 2, data 0xAA 0x55
173  * r1230 : can_id 0x123, len 0, no data, remote transmission request
174  *
175  */
176
177 /*************************************************************************
178  *                      STANDARD SLCAN DECAPSULATION                     *
179  *************************************************************************/
180
181 /* Send one completely decapsulated can_frame to the network layer */
182 static void slc_bump_frame(struct slcan *sl)
183 {
184         struct sk_buff *skb;
185         struct can_frame *cf;
186         int i, tmp;
187         u32 tmpid;
188         char *cmd = sl->rbuff;
189
190         skb = alloc_can_skb(sl->dev, &cf);
191         if (unlikely(!skb)) {
192                 sl->dev->stats.rx_dropped++;
193                 return;
194         }
195
196         switch (*cmd) {
197         case 'r':
198                 cf->can_id = CAN_RTR_FLAG;
199                 fallthrough;
200         case 't':
201                 /* store dlc ASCII value and terminate SFF CAN ID string */
202                 cf->len = sl->rbuff[SLC_CMD_LEN + SLC_SFF_ID_LEN];
203                 sl->rbuff[SLC_CMD_LEN + SLC_SFF_ID_LEN] = 0;
204                 /* point to payload data behind the dlc */
205                 cmd += SLC_CMD_LEN + SLC_SFF_ID_LEN + 1;
206                 break;
207         case 'R':
208                 cf->can_id = CAN_RTR_FLAG;
209                 fallthrough;
210         case 'T':
211                 cf->can_id |= CAN_EFF_FLAG;
212                 /* store dlc ASCII value and terminate EFF CAN ID string */
213                 cf->len = sl->rbuff[SLC_CMD_LEN + SLC_EFF_ID_LEN];
214                 sl->rbuff[SLC_CMD_LEN + SLC_EFF_ID_LEN] = 0;
215                 /* point to payload data behind the dlc */
216                 cmd += SLC_CMD_LEN + SLC_EFF_ID_LEN + 1;
217                 break;
218         default:
219                 goto decode_failed;
220         }
221
222         if (kstrtou32(sl->rbuff + SLC_CMD_LEN, 16, &tmpid))
223                 goto decode_failed;
224
225         cf->can_id |= tmpid;
226
227         /* get len from sanitized ASCII value */
228         if (cf->len >= '0' && cf->len < '9')
229                 cf->len -= '0';
230         else
231                 goto decode_failed;
232
233         /* RTR frames may have a dlc > 0 but they never have any data bytes */
234         if (!(cf->can_id & CAN_RTR_FLAG)) {
235                 for (i = 0; i < cf->len; i++) {
236                         tmp = hex_to_bin(*cmd++);
237                         if (tmp < 0)
238                                 goto decode_failed;
239
240                         cf->data[i] = (tmp << 4);
241                         tmp = hex_to_bin(*cmd++);
242                         if (tmp < 0)
243                                 goto decode_failed;
244
245                         cf->data[i] |= tmp;
246                 }
247         }
248
249         sl->dev->stats.rx_packets++;
250         if (!(cf->can_id & CAN_RTR_FLAG))
251                 sl->dev->stats.rx_bytes += cf->len;
252
253         netif_rx(skb);
254         return;
255
256 decode_failed:
257         sl->dev->stats.rx_errors++;
258         dev_kfree_skb(skb);
259 }
260
261 /* A change state frame must contain state info and receive and transmit
262  * error counters.
263  *
264  * Examples:
265  *
266  * sb256256 : state bus-off: rx counter 256, tx counter 256
267  * sa057033 : state active, rx counter 57, tx counter 33
268  */
269 static void slc_bump_state(struct slcan *sl)
270 {
271         struct net_device *dev = sl->dev;
272         struct sk_buff *skb;
273         struct can_frame *cf;
274         char *cmd = sl->rbuff;
275         u32 rxerr, txerr;
276         enum can_state state, rx_state, tx_state;
277
278         switch (cmd[1]) {
279         case 'a':
280                 state = CAN_STATE_ERROR_ACTIVE;
281                 break;
282         case 'w':
283                 state = CAN_STATE_ERROR_WARNING;
284                 break;
285         case 'p':
286                 state = CAN_STATE_ERROR_PASSIVE;
287                 break;
288         case 'b':
289                 state = CAN_STATE_BUS_OFF;
290                 break;
291         default:
292                 return;
293         }
294
295         if (state == sl->can.state || sl->rcount < SLC_STATE_FRAME_LEN)
296                 return;
297
298         cmd += SLC_STATE_BE_RXCNT_LEN + SLC_CMD_LEN + 1;
299         cmd[SLC_STATE_BE_TXCNT_LEN] = 0;
300         if (kstrtou32(cmd, 10, &txerr))
301                 return;
302
303         *cmd = 0;
304         cmd -= SLC_STATE_BE_RXCNT_LEN;
305         if (kstrtou32(cmd, 10, &rxerr))
306                 return;
307
308         skb = alloc_can_err_skb(dev, &cf);
309         if (skb) {
310                 cf->data[6] = txerr;
311                 cf->data[7] = rxerr;
312         } else {
313                 cf = NULL;
314         }
315
316         tx_state = txerr >= rxerr ? state : 0;
317         rx_state = txerr <= rxerr ? state : 0;
318         can_change_state(dev, cf, tx_state, rx_state);
319
320         if (state == CAN_STATE_BUS_OFF)
321                 can_bus_off(dev);
322
323         if (skb)
324                 netif_rx(skb);
325 }
326
327 /* An error frame can contain more than one type of error.
328  *
329  * Examples:
330  *
331  * e1a : len 1, errors: ACK error
332  * e3bcO: len 3, errors: Bit0 error, CRC error, Tx overrun error
333  */
334 static void slc_bump_err(struct slcan *sl)
335 {
336         struct net_device *dev = sl->dev;
337         struct sk_buff *skb;
338         struct can_frame *cf;
339         char *cmd = sl->rbuff;
340         bool rx_errors = false, tx_errors = false, rx_over_errors = false;
341         int i, len;
342
343         /* get len from sanitized ASCII value */
344         len = cmd[1];
345         if (len >= '0' && len < '9')
346                 len -= '0';
347         else
348                 return;
349
350         if ((len + SLC_CMD_LEN + 1) > sl->rcount)
351                 return;
352
353         skb = alloc_can_err_skb(dev, &cf);
354
355         if (skb)
356                 cf->can_id |= CAN_ERR_PROT | CAN_ERR_BUSERROR;
357
358         cmd += SLC_CMD_LEN + 1;
359         for (i = 0; i < len; i++, cmd++) {
360                 switch (*cmd) {
361                 case 'a':
362                         netdev_dbg(dev, "ACK error\n");
363                         tx_errors = true;
364                         if (skb) {
365                                 cf->can_id |= CAN_ERR_ACK;
366                                 cf->data[3] = CAN_ERR_PROT_LOC_ACK;
367                         }
368
369                         break;
370                 case 'b':
371                         netdev_dbg(dev, "Bit0 error\n");
372                         tx_errors = true;
373                         if (skb)
374                                 cf->data[2] |= CAN_ERR_PROT_BIT0;
375
376                         break;
377                 case 'B':
378                         netdev_dbg(dev, "Bit1 error\n");
379                         tx_errors = true;
380                         if (skb)
381                                 cf->data[2] |= CAN_ERR_PROT_BIT1;
382
383                         break;
384                 case 'c':
385                         netdev_dbg(dev, "CRC error\n");
386                         rx_errors = true;
387                         if (skb) {
388                                 cf->data[2] |= CAN_ERR_PROT_BIT;
389                                 cf->data[3] = CAN_ERR_PROT_LOC_CRC_SEQ;
390                         }
391
392                         break;
393                 case 'f':
394                         netdev_dbg(dev, "Form Error\n");
395                         rx_errors = true;
396                         if (skb)
397                                 cf->data[2] |= CAN_ERR_PROT_FORM;
398
399                         break;
400                 case 'o':
401                         netdev_dbg(dev, "Rx overrun error\n");
402                         rx_over_errors = true;
403                         rx_errors = true;
404                         if (skb) {
405                                 cf->can_id |= CAN_ERR_CRTL;
406                                 cf->data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
407                         }
408
409                         break;
410                 case 'O':
411                         netdev_dbg(dev, "Tx overrun error\n");
412                         tx_errors = true;
413                         if (skb) {
414                                 cf->can_id |= CAN_ERR_CRTL;
415                                 cf->data[1] = CAN_ERR_CRTL_TX_OVERFLOW;
416                         }
417
418                         break;
419                 case 's':
420                         netdev_dbg(dev, "Stuff error\n");
421                         rx_errors = true;
422                         if (skb)
423                                 cf->data[2] |= CAN_ERR_PROT_STUFF;
424
425                         break;
426                 default:
427                         if (skb)
428                                 dev_kfree_skb(skb);
429
430                         return;
431                 }
432         }
433
434         if (rx_errors)
435                 dev->stats.rx_errors++;
436
437         if (rx_over_errors)
438                 dev->stats.rx_over_errors++;
439
440         if (tx_errors)
441                 dev->stats.tx_errors++;
442
443         if (skb)
444                 netif_rx(skb);
445 }
446
447 static void slc_bump(struct slcan *sl)
448 {
449         switch (sl->rbuff[0]) {
450         case 'r':
451                 fallthrough;
452         case 't':
453                 fallthrough;
454         case 'R':
455                 fallthrough;
456         case 'T':
457                 return slc_bump_frame(sl);
458         case 'e':
459                 return slc_bump_err(sl);
460         case 's':
461                 return slc_bump_state(sl);
462         default:
463                 return;
464         }
465 }
466
467 /* parse tty input stream */
468 static void slcan_unesc(struct slcan *sl, unsigned char s)
469 {
470         if ((s == '\r') || (s == '\a')) { /* CR or BEL ends the pdu */
471                 if (!test_and_clear_bit(SLF_ERROR, &sl->flags) &&
472                     (sl->rcount > 4))  {
473                         slc_bump(sl);
474                 }
475                 sl->rcount = 0;
476         } else {
477                 if (!test_bit(SLF_ERROR, &sl->flags))  {
478                         if (sl->rcount < SLC_MTU)  {
479                                 sl->rbuff[sl->rcount++] = s;
480                                 return;
481                         } else {
482                                 sl->dev->stats.rx_over_errors++;
483                                 set_bit(SLF_ERROR, &sl->flags);
484                         }
485                 }
486         }
487 }
488
489 /*************************************************************************
490  *                      STANDARD SLCAN ENCAPSULATION                     *
491  *************************************************************************/
492
493 /* Encapsulate one can_frame and stuff into a TTY queue. */
494 static void slc_encaps(struct slcan *sl, struct can_frame *cf)
495 {
496         int actual, i;
497         unsigned char *pos;
498         unsigned char *endpos;
499         canid_t id = cf->can_id;
500
501         pos = sl->xbuff;
502
503         if (cf->can_id & CAN_RTR_FLAG)
504                 *pos = 'R'; /* becomes 'r' in standard frame format (SFF) */
505         else
506                 *pos = 'T'; /* becomes 't' in standard frame format (SSF) */
507
508         /* determine number of chars for the CAN-identifier */
509         if (cf->can_id & CAN_EFF_FLAG) {
510                 id &= CAN_EFF_MASK;
511                 endpos = pos + SLC_EFF_ID_LEN;
512         } else {
513                 *pos |= 0x20; /* convert R/T to lower case for SFF */
514                 id &= CAN_SFF_MASK;
515                 endpos = pos + SLC_SFF_ID_LEN;
516         }
517
518         /* build 3 (SFF) or 8 (EFF) digit CAN identifier */
519         pos++;
520         while (endpos >= pos) {
521                 *endpos-- = hex_asc_upper[id & 0xf];
522                 id >>= 4;
523         }
524
525         pos += (cf->can_id & CAN_EFF_FLAG) ? SLC_EFF_ID_LEN : SLC_SFF_ID_LEN;
526
527         *pos++ = cf->len + '0';
528
529         /* RTR frames may have a dlc > 0 but they never have any data bytes */
530         if (!(cf->can_id & CAN_RTR_FLAG)) {
531                 for (i = 0; i < cf->len; i++)
532                         pos = hex_byte_pack_upper(pos, cf->data[i]);
533
534                 sl->dev->stats.tx_bytes += cf->len;
535         }
536
537         *pos++ = '\r';
538
539         /* Order of next two lines is *very* important.
540          * When we are sending a little amount of data,
541          * the transfer may be completed inside the ops->write()
542          * routine, because it's running with interrupts enabled.
543          * In this case we *never* got WRITE_WAKEUP event,
544          * if we did not request it before write operation.
545          *       14 Oct 1994  Dmitry Gorodchanin.
546          */
547         set_bit(TTY_DO_WRITE_WAKEUP, &sl->tty->flags);
548         actual = sl->tty->ops->write(sl->tty, sl->xbuff, pos - sl->xbuff);
549         sl->xleft = (pos - sl->xbuff) - actual;
550         sl->xhead = sl->xbuff + actual;
551 }
552
553 /* Write out any remaining transmit buffer. Scheduled when tty is writable */
554 static void slcan_transmit(struct work_struct *work)
555 {
556         struct slcan *sl = container_of(work, struct slcan, tx_work);
557         int actual;
558
559         spin_lock_bh(&sl->lock);
560         /* First make sure we're connected. */
561         if (!sl->tty || sl->magic != SLCAN_MAGIC ||
562             (unlikely(!netif_running(sl->dev)) &&
563              likely(!test_bit(SLF_XCMD, &sl->flags)))) {
564                 spin_unlock_bh(&sl->lock);
565                 return;
566         }
567
568         if (sl->xleft <= 0)  {
569                 if (unlikely(test_bit(SLF_XCMD, &sl->flags))) {
570                         clear_bit(SLF_XCMD, &sl->flags);
571                         clear_bit(TTY_DO_WRITE_WAKEUP, &sl->tty->flags);
572                         spin_unlock_bh(&sl->lock);
573                         wake_up(&sl->xcmd_wait);
574                         return;
575                 }
576
577                 /* Now serial buffer is almost free & we can start
578                  * transmission of another packet
579                  */
580                 sl->dev->stats.tx_packets++;
581                 clear_bit(TTY_DO_WRITE_WAKEUP, &sl->tty->flags);
582                 spin_unlock_bh(&sl->lock);
583                 netif_wake_queue(sl->dev);
584                 return;
585         }
586
587         actual = sl->tty->ops->write(sl->tty, sl->xhead, sl->xleft);
588         sl->xleft -= actual;
589         sl->xhead += actual;
590         spin_unlock_bh(&sl->lock);
591 }
592
593 /* Called by the driver when there's room for more data.
594  * Schedule the transmit.
595  */
596 static void slcan_write_wakeup(struct tty_struct *tty)
597 {
598         struct slcan *sl;
599
600         rcu_read_lock();
601         sl = rcu_dereference(tty->disc_data);
602         if (sl)
603                 schedule_work(&sl->tx_work);
604         rcu_read_unlock();
605 }
606
607 /* Send a can_frame to a TTY queue. */
608 static netdev_tx_t slc_xmit(struct sk_buff *skb, struct net_device *dev)
609 {
610         struct slcan *sl = netdev_priv(dev);
611
612         if (can_dropped_invalid_skb(dev, skb))
613                 return NETDEV_TX_OK;
614
615         spin_lock(&sl->lock);
616         if (!netif_running(dev))  {
617                 spin_unlock(&sl->lock);
618                 netdev_warn(dev, "xmit: iface is down\n");
619                 goto out;
620         }
621         if (sl->tty == NULL) {
622                 spin_unlock(&sl->lock);
623                 goto out;
624         }
625
626         netif_stop_queue(sl->dev);
627         slc_encaps(sl, (struct can_frame *) skb->data); /* encaps & send */
628         spin_unlock(&sl->lock);
629
630 out:
631         kfree_skb(skb);
632         return NETDEV_TX_OK;
633 }
634
635 /******************************************
636  *   Routines looking at netdevice side.
637  ******************************************/
638
639 static int slcan_transmit_cmd(struct slcan *sl, const unsigned char *cmd)
640 {
641         int ret, actual, n;
642
643         spin_lock(&sl->lock);
644         if (!sl->tty) {
645                 spin_unlock(&sl->lock);
646                 return -ENODEV;
647         }
648
649         n = scnprintf(sl->xbuff, sizeof(sl->xbuff), "%s", cmd);
650         set_bit(TTY_DO_WRITE_WAKEUP, &sl->tty->flags);
651         actual = sl->tty->ops->write(sl->tty, sl->xbuff, n);
652         sl->xleft = n - actual;
653         sl->xhead = sl->xbuff + actual;
654         set_bit(SLF_XCMD, &sl->flags);
655         spin_unlock(&sl->lock);
656         ret = wait_event_interruptible_timeout(sl->xcmd_wait,
657                                                !test_bit(SLF_XCMD, &sl->flags),
658                                                HZ);
659         clear_bit(SLF_XCMD, &sl->flags);
660         if (ret == -ERESTARTSYS)
661                 return ret;
662
663         if (ret == 0)
664                 return -ETIMEDOUT;
665
666         return 0;
667 }
668
669 /* Netdevice UP -> DOWN routine */
670 static int slc_close(struct net_device *dev)
671 {
672         struct slcan *sl = netdev_priv(dev);
673         int err;
674
675         spin_lock_bh(&sl->lock);
676         if (sl->tty) {
677                 if (sl->can.bittiming.bitrate &&
678                     sl->can.bittiming.bitrate != CAN_BITRATE_UNKNOWN) {
679                         spin_unlock_bh(&sl->lock);
680                         err = slcan_transmit_cmd(sl, "C\r");
681                         spin_lock_bh(&sl->lock);
682                         if (err)
683                                 netdev_warn(dev,
684                                             "failed to send close command 'C\\r'\n");
685                 }
686
687                 /* TTY discipline is running. */
688                 clear_bit(TTY_DO_WRITE_WAKEUP, &sl->tty->flags);
689         }
690         netif_stop_queue(dev);
691         close_candev(dev);
692         sl->can.state = CAN_STATE_STOPPED;
693         if (sl->can.bittiming.bitrate == CAN_BITRATE_UNKNOWN)
694                 sl->can.bittiming.bitrate = CAN_BITRATE_UNSET;
695
696         sl->rcount   = 0;
697         sl->xleft    = 0;
698         spin_unlock_bh(&sl->lock);
699
700         return 0;
701 }
702
703 /* Netdevice DOWN -> UP routine */
704 static int slc_open(struct net_device *dev)
705 {
706         struct slcan *sl = netdev_priv(dev);
707         unsigned char cmd[SLC_MTU];
708         int err, s;
709
710         if (sl->tty == NULL)
711                 return -ENODEV;
712
713         /* The baud rate is not set with the command
714          * `ip link set <iface> type can bitrate <baud>' and therefore
715          * can.bittiming.bitrate is CAN_BITRATE_UNSET (0), causing
716          * open_candev() to fail. So let's set to a fake value.
717          */
718         if (sl->can.bittiming.bitrate == CAN_BITRATE_UNSET)
719                 sl->can.bittiming.bitrate = CAN_BITRATE_UNKNOWN;
720
721         err = open_candev(dev);
722         if (err) {
723                 netdev_err(dev, "failed to open can device\n");
724                 return err;
725         }
726
727         sl->flags &= BIT(SLF_INUSE);
728
729         if (sl->can.bittiming.bitrate != CAN_BITRATE_UNKNOWN) {
730                 for (s = 0; s < ARRAY_SIZE(slcan_bitrate_const); s++) {
731                         if (sl->can.bittiming.bitrate == slcan_bitrate_const[s])
732                                 break;
733                 }
734
735                 /* The CAN framework has already validate the bitrate value,
736                  * so we can avoid to check if `s' has been properly set.
737                  */
738                 snprintf(cmd, sizeof(cmd), "C\rS%d\r", s);
739                 err = slcan_transmit_cmd(sl, cmd);
740                 if (err) {
741                         netdev_err(dev,
742                                    "failed to send bitrate command 'C\\rS%d\\r'\n",
743                                    s);
744                         goto cmd_transmit_failed;
745                 }
746
747                 if (test_bit(CF_ERR_RST, &sl->cmd_flags)) {
748                         err = slcan_transmit_cmd(sl, "F\r");
749                         if (err) {
750                                 netdev_err(dev,
751                                            "failed to send error command 'F\\r'\n");
752                                 goto cmd_transmit_failed;
753                         }
754                 }
755
756                 err = slcan_transmit_cmd(sl, "O\r");
757                 if (err) {
758                         netdev_err(dev, "failed to send open command 'O\\r'\n");
759                         goto cmd_transmit_failed;
760                 }
761         }
762
763         sl->can.state = CAN_STATE_ERROR_ACTIVE;
764         netif_start_queue(dev);
765         return 0;
766
767 cmd_transmit_failed:
768         close_candev(dev);
769         return err;
770 }
771
772 static void slc_dealloc(struct slcan *sl)
773 {
774         int i = sl->dev->base_addr;
775
776         free_candev(sl->dev);
777         slcan_devs[i] = NULL;
778 }
779
780 static int slcan_change_mtu(struct net_device *dev, int new_mtu)
781 {
782         return -EINVAL;
783 }
784
785 static const struct net_device_ops slc_netdev_ops = {
786         .ndo_open               = slc_open,
787         .ndo_stop               = slc_close,
788         .ndo_start_xmit         = slc_xmit,
789         .ndo_change_mtu         = slcan_change_mtu,
790 };
791
792 /******************************************
793  *  Routines looking at TTY side.
794  ******************************************/
795
796 /* Handle the 'receiver data ready' interrupt.
797  * This function is called by the 'tty_io' module in the kernel when
798  * a block of SLCAN data has been received, which can now be decapsulated
799  * and sent on to some IP layer for further processing. This will not
800  * be re-entered while running but other ldisc functions may be called
801  * in parallel
802  */
803 static void slcan_receive_buf(struct tty_struct *tty,
804                               const unsigned char *cp, const char *fp,
805                               int count)
806 {
807         struct slcan *sl = (struct slcan *) tty->disc_data;
808
809         if (!sl || sl->magic != SLCAN_MAGIC || !netif_running(sl->dev))
810                 return;
811
812         /* Read the characters out of the buffer */
813         while (count--) {
814                 if (fp && *fp++) {
815                         if (!test_and_set_bit(SLF_ERROR, &sl->flags))
816                                 sl->dev->stats.rx_errors++;
817                         cp++;
818                         continue;
819                 }
820                 slcan_unesc(sl, *cp++);
821         }
822 }
823
824 /************************************
825  *  slcan_open helper routines.
826  ************************************/
827
828 /* Collect hanged up channels */
829 static void slc_sync(void)
830 {
831         int i;
832         struct net_device *dev;
833         struct slcan      *sl;
834
835         for (i = 0; i < maxdev; i++) {
836                 dev = slcan_devs[i];
837                 if (dev == NULL)
838                         break;
839
840                 sl = netdev_priv(dev);
841                 if (sl->tty)
842                         continue;
843                 if (dev->flags & IFF_UP)
844                         dev_close(dev);
845         }
846 }
847
848 /* Find a free SLCAN channel, and link in this `tty' line. */
849 static struct slcan *slc_alloc(void)
850 {
851         int i;
852         struct net_device *dev = NULL;
853         struct slcan       *sl;
854
855         for (i = 0; i < maxdev; i++) {
856                 dev = slcan_devs[i];
857                 if (dev == NULL)
858                         break;
859
860         }
861
862         /* Sorry, too many, all slots in use */
863         if (i >= maxdev)
864                 return NULL;
865
866         dev = alloc_candev(sizeof(*sl), 1);
867         if (!dev)
868                 return NULL;
869
870         snprintf(dev->name, sizeof(dev->name), "slcan%d", i);
871         dev->netdev_ops = &slc_netdev_ops;
872         dev->base_addr  = i;
873         slcan_set_ethtool_ops(dev);
874         sl = netdev_priv(dev);
875
876         /* Initialize channel control data */
877         sl->magic = SLCAN_MAGIC;
878         sl->dev = dev;
879         sl->can.bitrate_const = slcan_bitrate_const;
880         sl->can.bitrate_const_cnt = ARRAY_SIZE(slcan_bitrate_const);
881         spin_lock_init(&sl->lock);
882         INIT_WORK(&sl->tx_work, slcan_transmit);
883         init_waitqueue_head(&sl->xcmd_wait);
884         slcan_devs[i] = dev;
885
886         return sl;
887 }
888
889 /* Open the high-level part of the SLCAN channel.
890  * This function is called by the TTY module when the
891  * SLCAN line discipline is called for.  Because we are
892  * sure the tty line exists, we only have to link it to
893  * a free SLCAN channel...
894  *
895  * Called in process context serialized from other ldisc calls.
896  */
897 static int slcan_open(struct tty_struct *tty)
898 {
899         struct slcan *sl;
900         int err;
901
902         if (!capable(CAP_NET_ADMIN))
903                 return -EPERM;
904
905         if (tty->ops->write == NULL)
906                 return -EOPNOTSUPP;
907
908         /* RTnetlink lock is misused here to serialize concurrent
909          * opens of slcan channels. There are better ways, but it is
910          * the simplest one.
911          */
912         rtnl_lock();
913
914         /* Collect hanged up channels. */
915         slc_sync();
916
917         sl = tty->disc_data;
918
919         err = -EEXIST;
920         /* First make sure we're not already connected. */
921         if (sl && sl->magic == SLCAN_MAGIC)
922                 goto err_exit;
923
924         /* OK.  Find a free SLCAN channel to use. */
925         err = -ENFILE;
926         sl = slc_alloc();
927         if (sl == NULL)
928                 goto err_exit;
929
930         sl->tty = tty;
931         tty->disc_data = sl;
932
933         if (!test_bit(SLF_INUSE, &sl->flags)) {
934                 /* Perform the low-level SLCAN initialization. */
935                 sl->rcount   = 0;
936                 sl->xleft    = 0;
937
938                 set_bit(SLF_INUSE, &sl->flags);
939
940                 rtnl_unlock();
941                 err = register_candev(sl->dev);
942                 if (err) {
943                         pr_err("slcan: can't register candev\n");
944                         goto err_free_chan;
945                 }
946         } else {
947                 rtnl_unlock();
948         }
949
950         tty->receive_room = 65536;      /* We don't flow control */
951
952         /* TTY layer expects 0 on success */
953         return 0;
954
955 err_free_chan:
956         rtnl_lock();
957         sl->tty = NULL;
958         tty->disc_data = NULL;
959         clear_bit(SLF_INUSE, &sl->flags);
960         slc_dealloc(sl);
961         rtnl_unlock();
962         return err;
963
964 err_exit:
965         rtnl_unlock();
966
967         /* Count references from TTY module */
968         return err;
969 }
970
971 /* Close down a SLCAN channel.
972  * This means flushing out any pending queues, and then returning. This
973  * call is serialized against other ldisc functions.
974  *
975  * We also use this method for a hangup event.
976  */
977 static void slcan_close(struct tty_struct *tty)
978 {
979         struct slcan *sl = (struct slcan *) tty->disc_data;
980
981         /* First make sure we're connected. */
982         if (!sl || sl->magic != SLCAN_MAGIC || sl->tty != tty)
983                 return;
984
985         spin_lock_bh(&sl->lock);
986         rcu_assign_pointer(tty->disc_data, NULL);
987         sl->tty = NULL;
988         spin_unlock_bh(&sl->lock);
989
990         synchronize_rcu();
991         flush_work(&sl->tx_work);
992
993         slc_close(sl->dev);
994         unregister_candev(sl->dev);
995         rtnl_lock();
996         slc_dealloc(sl);
997         rtnl_unlock();
998 }
999
1000 static void slcan_hangup(struct tty_struct *tty)
1001 {
1002         slcan_close(tty);
1003 }
1004
1005 /* Perform I/O control on an active SLCAN channel. */
1006 static int slcan_ioctl(struct tty_struct *tty, unsigned int cmd,
1007                        unsigned long arg)
1008 {
1009         struct slcan *sl = (struct slcan *) tty->disc_data;
1010         unsigned int tmp;
1011
1012         /* First make sure we're connected. */
1013         if (!sl || sl->magic != SLCAN_MAGIC)
1014                 return -EINVAL;
1015
1016         switch (cmd) {
1017         case SIOCGIFNAME:
1018                 tmp = strlen(sl->dev->name) + 1;
1019                 if (copy_to_user((void __user *)arg, sl->dev->name, tmp))
1020                         return -EFAULT;
1021                 return 0;
1022
1023         case SIOCSIFHWADDR:
1024                 return -EINVAL;
1025
1026         default:
1027                 return tty_mode_ioctl(tty, cmd, arg);
1028         }
1029 }
1030
1031 static struct tty_ldisc_ops slc_ldisc = {
1032         .owner          = THIS_MODULE,
1033         .num            = N_SLCAN,
1034         .name           = "slcan",
1035         .open           = slcan_open,
1036         .close          = slcan_close,
1037         .hangup         = slcan_hangup,
1038         .ioctl          = slcan_ioctl,
1039         .receive_buf    = slcan_receive_buf,
1040         .write_wakeup   = slcan_write_wakeup,
1041 };
1042
1043 static int __init slcan_init(void)
1044 {
1045         int status;
1046
1047         if (maxdev < 4)
1048                 maxdev = 4; /* Sanity */
1049
1050         pr_info("slcan: serial line CAN interface driver\n");
1051         pr_info("slcan: %d dynamic interface channels.\n", maxdev);
1052
1053         slcan_devs = kcalloc(maxdev, sizeof(struct net_device *), GFP_KERNEL);
1054         if (!slcan_devs)
1055                 return -ENOMEM;
1056
1057         /* Fill in our line protocol discipline, and register it */
1058         status = tty_register_ldisc(&slc_ldisc);
1059         if (status)  {
1060                 pr_err("slcan: can't register line discipline\n");
1061                 kfree(slcan_devs);
1062         }
1063         return status;
1064 }
1065
1066 static void __exit slcan_exit(void)
1067 {
1068         int i;
1069         struct net_device *dev;
1070         struct slcan *sl;
1071         unsigned long timeout = jiffies + HZ;
1072         int busy = 0;
1073
1074         if (slcan_devs == NULL)
1075                 return;
1076
1077         /* First of all: check for active disciplines and hangup them.
1078          */
1079         do {
1080                 if (busy)
1081                         msleep_interruptible(100);
1082
1083                 busy = 0;
1084                 for (i = 0; i < maxdev; i++) {
1085                         dev = slcan_devs[i];
1086                         if (!dev)
1087                                 continue;
1088                         sl = netdev_priv(dev);
1089                         spin_lock_bh(&sl->lock);
1090                         if (sl->tty) {
1091                                 busy++;
1092                                 tty_hangup(sl->tty);
1093                         }
1094                         spin_unlock_bh(&sl->lock);
1095                 }
1096         } while (busy && time_before(jiffies, timeout));
1097
1098         /* FIXME: hangup is async so we should wait when doing this second
1099          * phase
1100          */
1101
1102         for (i = 0; i < maxdev; i++) {
1103                 dev = slcan_devs[i];
1104                 if (!dev)
1105                         continue;
1106
1107                 sl = netdev_priv(dev);
1108                 if (sl->tty) {
1109                         netdev_err(dev, "tty discipline still running\n");
1110                 }
1111
1112                 slc_close(dev);
1113                 unregister_candev(dev);
1114                 slc_dealloc(sl);
1115         }
1116
1117         kfree(slcan_devs);
1118         slcan_devs = NULL;
1119
1120         tty_unregister_ldisc(&slc_ldisc);
1121 }
1122
1123 module_init(slcan_init);
1124 module_exit(slcan_exit);