xref: /linux/drivers/net/can/slcan/slcan-core.c (revision 3e5c291c7942d0909a48bc5ec1b9bba136465166)
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 
310 	tx_state = txerr >= rxerr ? state : 0;
311 	rx_state = txerr <= rxerr ? state : 0;
312 	can_change_state(dev, cf, tx_state, rx_state);
313 
314 	if (state == CAN_STATE_BUS_OFF) {
315 		can_bus_off(dev);
316 	} else if (skb) {
317 		cf->can_id |= CAN_ERR_CNT;
318 		cf->data[6] = txerr;
319 		cf->data[7] = rxerr;
320 	}
321 
322 	if (skb)
323 		netif_rx(skb);
324 }
325 
326 /* An error frame can contain more than one type of error.
327  *
328  * Examples:
329  *
330  * e1a : len 1, errors: ACK error
331  * e3bcO: len 3, errors: Bit0 error, CRC error, Tx overrun error
332  */
333 static void slc_bump_err(struct slcan *sl)
334 {
335 	struct net_device *dev = sl->dev;
336 	struct sk_buff *skb;
337 	struct can_frame *cf;
338 	char *cmd = sl->rbuff;
339 	bool rx_errors = false, tx_errors = false, rx_over_errors = false;
340 	int i, len;
341 
342 	/* get len from sanitized ASCII value */
343 	len = cmd[1];
344 	if (len >= '0' && len < '9')
345 		len -= '0';
346 	else
347 		return;
348 
349 	if ((len + SLC_CMD_LEN + 1) > sl->rcount)
350 		return;
351 
352 	skb = alloc_can_err_skb(dev, &cf);
353 
354 	if (skb)
355 		cf->can_id |= CAN_ERR_PROT | CAN_ERR_BUSERROR;
356 
357 	cmd += SLC_CMD_LEN + 1;
358 	for (i = 0; i < len; i++, cmd++) {
359 		switch (*cmd) {
360 		case 'a':
361 			netdev_dbg(dev, "ACK error\n");
362 			tx_errors = true;
363 			if (skb) {
364 				cf->can_id |= CAN_ERR_ACK;
365 				cf->data[3] = CAN_ERR_PROT_LOC_ACK;
366 			}
367 
368 			break;
369 		case 'b':
370 			netdev_dbg(dev, "Bit0 error\n");
371 			tx_errors = true;
372 			if (skb)
373 				cf->data[2] |= CAN_ERR_PROT_BIT0;
374 
375 			break;
376 		case 'B':
377 			netdev_dbg(dev, "Bit1 error\n");
378 			tx_errors = true;
379 			if (skb)
380 				cf->data[2] |= CAN_ERR_PROT_BIT1;
381 
382 			break;
383 		case 'c':
384 			netdev_dbg(dev, "CRC error\n");
385 			rx_errors = true;
386 			if (skb) {
387 				cf->data[2] |= CAN_ERR_PROT_BIT;
388 				cf->data[3] = CAN_ERR_PROT_LOC_CRC_SEQ;
389 			}
390 
391 			break;
392 		case 'f':
393 			netdev_dbg(dev, "Form Error\n");
394 			rx_errors = true;
395 			if (skb)
396 				cf->data[2] |= CAN_ERR_PROT_FORM;
397 
398 			break;
399 		case 'o':
400 			netdev_dbg(dev, "Rx overrun error\n");
401 			rx_over_errors = true;
402 			rx_errors = true;
403 			if (skb) {
404 				cf->can_id |= CAN_ERR_CRTL;
405 				cf->data[1] = CAN_ERR_CRTL_RX_OVERFLOW;
406 			}
407 
408 			break;
409 		case 'O':
410 			netdev_dbg(dev, "Tx overrun error\n");
411 			tx_errors = true;
412 			if (skb) {
413 				cf->can_id |= CAN_ERR_CRTL;
414 				cf->data[1] = CAN_ERR_CRTL_TX_OVERFLOW;
415 			}
416 
417 			break;
418 		case 's':
419 			netdev_dbg(dev, "Stuff error\n");
420 			rx_errors = true;
421 			if (skb)
422 				cf->data[2] |= CAN_ERR_PROT_STUFF;
423 
424 			break;
425 		default:
426 			if (skb)
427 				dev_kfree_skb(skb);
428 
429 			return;
430 		}
431 	}
432 
433 	if (rx_errors)
434 		dev->stats.rx_errors++;
435 
436 	if (rx_over_errors)
437 		dev->stats.rx_over_errors++;
438 
439 	if (tx_errors)
440 		dev->stats.tx_errors++;
441 
442 	if (skb)
443 		netif_rx(skb);
444 }
445 
446 static void slc_bump(struct slcan *sl)
447 {
448 	switch (sl->rbuff[0]) {
449 	case 'r':
450 		fallthrough;
451 	case 't':
452 		fallthrough;
453 	case 'R':
454 		fallthrough;
455 	case 'T':
456 		return slc_bump_frame(sl);
457 	case 'e':
458 		return slc_bump_err(sl);
459 	case 's':
460 		return slc_bump_state(sl);
461 	default:
462 		return;
463 	}
464 }
465 
466 /* parse tty input stream */
467 static void slcan_unesc(struct slcan *sl, unsigned char s)
468 {
469 	if ((s == '\r') || (s == '\a')) { /* CR or BEL ends the pdu */
470 		if (!test_and_clear_bit(SLF_ERROR, &sl->flags) &&
471 		    sl->rcount > 4)
472 			slc_bump(sl);
473 
474 		sl->rcount = 0;
475 	} else {
476 		if (!test_bit(SLF_ERROR, &sl->flags))  {
477 			if (sl->rcount < SLC_MTU)  {
478 				sl->rbuff[sl->rcount++] = s;
479 				return;
480 			}
481 
482 			sl->dev->stats.rx_over_errors++;
483 			set_bit(SLF_ERROR, &sl->flags);
484 		}
485 	}
486 }
487 
488 /*************************************************************************
489  *			STANDARD SLCAN ENCAPSULATION			 *
490  *************************************************************************/
491 
492 /* Encapsulate one can_frame and stuff into a TTY queue. */
493 static void slc_encaps(struct slcan *sl, struct can_frame *cf)
494 {
495 	int actual, i;
496 	unsigned char *pos;
497 	unsigned char *endpos;
498 	canid_t id = cf->can_id;
499 
500 	pos = sl->xbuff;
501 
502 	if (cf->can_id & CAN_RTR_FLAG)
503 		*pos = 'R'; /* becomes 'r' in standard frame format (SFF) */
504 	else
505 		*pos = 'T'; /* becomes 't' in standard frame format (SSF) */
506 
507 	/* determine number of chars for the CAN-identifier */
508 	if (cf->can_id & CAN_EFF_FLAG) {
509 		id &= CAN_EFF_MASK;
510 		endpos = pos + SLC_EFF_ID_LEN;
511 	} else {
512 		*pos |= 0x20; /* convert R/T to lower case for SFF */
513 		id &= CAN_SFF_MASK;
514 		endpos = pos + SLC_SFF_ID_LEN;
515 	}
516 
517 	/* build 3 (SFF) or 8 (EFF) digit CAN identifier */
518 	pos++;
519 	while (endpos >= pos) {
520 		*endpos-- = hex_asc_upper[id & 0xf];
521 		id >>= 4;
522 	}
523 
524 	pos += (cf->can_id & CAN_EFF_FLAG) ? SLC_EFF_ID_LEN : SLC_SFF_ID_LEN;
525 
526 	*pos++ = cf->len + '0';
527 
528 	/* RTR frames may have a dlc > 0 but they never have any data bytes */
529 	if (!(cf->can_id & CAN_RTR_FLAG)) {
530 		for (i = 0; i < cf->len; i++)
531 			pos = hex_byte_pack_upper(pos, cf->data[i]);
532 
533 		sl->dev->stats.tx_bytes += cf->len;
534 	}
535 
536 	*pos++ = '\r';
537 
538 	/* Order of next two lines is *very* important.
539 	 * When we are sending a little amount of data,
540 	 * the transfer may be completed inside the ops->write()
541 	 * routine, because it's running with interrupts enabled.
542 	 * In this case we *never* got WRITE_WAKEUP event,
543 	 * if we did not request it before write operation.
544 	 *       14 Oct 1994  Dmitry Gorodchanin.
545 	 */
546 	set_bit(TTY_DO_WRITE_WAKEUP, &sl->tty->flags);
547 	actual = sl->tty->ops->write(sl->tty, sl->xbuff, pos - sl->xbuff);
548 	sl->xleft = (pos - sl->xbuff) - actual;
549 	sl->xhead = sl->xbuff + actual;
550 }
551 
552 /* Write out any remaining transmit buffer. Scheduled when tty is writable */
553 static void slcan_transmit(struct work_struct *work)
554 {
555 	struct slcan *sl = container_of(work, struct slcan, tx_work);
556 	int actual;
557 
558 	spin_lock_bh(&sl->lock);
559 	/* First make sure we're connected. */
560 	if (!sl->tty || sl->magic != SLCAN_MAGIC ||
561 	    (unlikely(!netif_running(sl->dev)) &&
562 	     likely(!test_bit(SLF_XCMD, &sl->flags)))) {
563 		spin_unlock_bh(&sl->lock);
564 		return;
565 	}
566 
567 	if (sl->xleft <= 0)  {
568 		if (unlikely(test_bit(SLF_XCMD, &sl->flags))) {
569 			clear_bit(SLF_XCMD, &sl->flags);
570 			clear_bit(TTY_DO_WRITE_WAKEUP, &sl->tty->flags);
571 			spin_unlock_bh(&sl->lock);
572 			wake_up(&sl->xcmd_wait);
573 			return;
574 		}
575 
576 		/* Now serial buffer is almost free & we can start
577 		 * transmission of another packet
578 		 */
579 		sl->dev->stats.tx_packets++;
580 		clear_bit(TTY_DO_WRITE_WAKEUP, &sl->tty->flags);
581 		spin_unlock_bh(&sl->lock);
582 		netif_wake_queue(sl->dev);
583 		return;
584 	}
585 
586 	actual = sl->tty->ops->write(sl->tty, sl->xhead, sl->xleft);
587 	sl->xleft -= actual;
588 	sl->xhead += actual;
589 	spin_unlock_bh(&sl->lock);
590 }
591 
592 /* Called by the driver when there's room for more data.
593  * Schedule the transmit.
594  */
595 static void slcan_write_wakeup(struct tty_struct *tty)
596 {
597 	struct slcan *sl;
598 
599 	rcu_read_lock();
600 	sl = rcu_dereference(tty->disc_data);
601 	if (sl)
602 		schedule_work(&sl->tx_work);
603 	rcu_read_unlock();
604 }
605 
606 /* Send a can_frame to a TTY queue. */
607 static netdev_tx_t slc_xmit(struct sk_buff *skb, struct net_device *dev)
608 {
609 	struct slcan *sl = netdev_priv(dev);
610 
611 	if (can_dropped_invalid_skb(dev, skb))
612 		return NETDEV_TX_OK;
613 
614 	spin_lock(&sl->lock);
615 	if (!netif_running(dev))  {
616 		spin_unlock(&sl->lock);
617 		netdev_warn(dev, "xmit: iface is down\n");
618 		goto out;
619 	}
620 	if (!sl->tty) {
621 		spin_unlock(&sl->lock);
622 		goto out;
623 	}
624 
625 	netif_stop_queue(sl->dev);
626 	slc_encaps(sl, (struct can_frame *)skb->data); /* encaps & send */
627 	spin_unlock(&sl->lock);
628 
629 out:
630 	kfree_skb(skb);
631 	return NETDEV_TX_OK;
632 }
633 
634 /******************************************
635  *   Routines looking at netdevice side.
636  ******************************************/
637 
638 static int slcan_transmit_cmd(struct slcan *sl, const unsigned char *cmd)
639 {
640 	int ret, actual, n;
641 
642 	spin_lock(&sl->lock);
643 	if (!sl->tty) {
644 		spin_unlock(&sl->lock);
645 		return -ENODEV;
646 	}
647 
648 	n = scnprintf(sl->xbuff, sizeof(sl->xbuff), "%s", cmd);
649 	set_bit(TTY_DO_WRITE_WAKEUP, &sl->tty->flags);
650 	actual = sl->tty->ops->write(sl->tty, sl->xbuff, n);
651 	sl->xleft = n - actual;
652 	sl->xhead = sl->xbuff + actual;
653 	set_bit(SLF_XCMD, &sl->flags);
654 	spin_unlock(&sl->lock);
655 	ret = wait_event_interruptible_timeout(sl->xcmd_wait,
656 					       !test_bit(SLF_XCMD, &sl->flags),
657 					       HZ);
658 	clear_bit(SLF_XCMD, &sl->flags);
659 	if (ret == -ERESTARTSYS)
660 		return ret;
661 
662 	if (ret == 0)
663 		return -ETIMEDOUT;
664 
665 	return 0;
666 }
667 
668 /* Netdevice UP -> DOWN routine */
669 static int slc_close(struct net_device *dev)
670 {
671 	struct slcan *sl = netdev_priv(dev);
672 	int err;
673 
674 	spin_lock_bh(&sl->lock);
675 	if (sl->tty) {
676 		if (sl->can.bittiming.bitrate &&
677 		    sl->can.bittiming.bitrate != CAN_BITRATE_UNKNOWN) {
678 			spin_unlock_bh(&sl->lock);
679 			err = slcan_transmit_cmd(sl, "C\r");
680 			spin_lock_bh(&sl->lock);
681 			if (err)
682 				netdev_warn(dev,
683 					    "failed to send close command 'C\\r'\n");
684 		}
685 
686 		/* TTY discipline is running. */
687 		clear_bit(TTY_DO_WRITE_WAKEUP, &sl->tty->flags);
688 	}
689 	netif_stop_queue(dev);
690 	sl->rcount   = 0;
691 	sl->xleft    = 0;
692 	spin_unlock_bh(&sl->lock);
693 	close_candev(dev);
694 	sl->can.state = CAN_STATE_STOPPED;
695 	if (sl->can.bittiming.bitrate == CAN_BITRATE_UNKNOWN)
696 		sl->can.bittiming.bitrate = CAN_BITRATE_UNSET;
697 
698 	return 0;
699 }
700 
701 /* Netdevice DOWN -> UP routine */
702 static int slc_open(struct net_device *dev)
703 {
704 	struct slcan *sl = netdev_priv(dev);
705 	unsigned char cmd[SLC_MTU];
706 	int err, s;
707 
708 	if (!sl->tty)
709 		return -ENODEV;
710 
711 	/* The baud rate is not set with the command
712 	 * `ip link set <iface> type can bitrate <baud>' and therefore
713 	 * can.bittiming.bitrate is CAN_BITRATE_UNSET (0), causing
714 	 * open_candev() to fail. So let's set to a fake value.
715 	 */
716 	if (sl->can.bittiming.bitrate == CAN_BITRATE_UNSET)
717 		sl->can.bittiming.bitrate = CAN_BITRATE_UNKNOWN;
718 
719 	err = open_candev(dev);
720 	if (err) {
721 		netdev_err(dev, "failed to open can device\n");
722 		return err;
723 	}
724 
725 	sl->flags &= BIT(SLF_INUSE);
726 
727 	if (sl->can.bittiming.bitrate != CAN_BITRATE_UNKNOWN) {
728 		for (s = 0; s < ARRAY_SIZE(slcan_bitrate_const); s++) {
729 			if (sl->can.bittiming.bitrate == slcan_bitrate_const[s])
730 				break;
731 		}
732 
733 		/* The CAN framework has already validate the bitrate value,
734 		 * so we can avoid to check if `s' has been properly set.
735 		 */
736 		snprintf(cmd, sizeof(cmd), "C\rS%d\r", s);
737 		err = slcan_transmit_cmd(sl, cmd);
738 		if (err) {
739 			netdev_err(dev,
740 				   "failed to send bitrate command 'C\\rS%d\\r'\n",
741 				   s);
742 			goto cmd_transmit_failed;
743 		}
744 
745 		if (test_bit(CF_ERR_RST, &sl->cmd_flags)) {
746 			err = slcan_transmit_cmd(sl, "F\r");
747 			if (err) {
748 				netdev_err(dev,
749 					   "failed to send error command 'F\\r'\n");
750 				goto cmd_transmit_failed;
751 			}
752 		}
753 
754 		err = slcan_transmit_cmd(sl, "O\r");
755 		if (err) {
756 			netdev_err(dev, "failed to send open command 'O\\r'\n");
757 			goto cmd_transmit_failed;
758 		}
759 	}
760 
761 	sl->can.state = CAN_STATE_ERROR_ACTIVE;
762 	netif_start_queue(dev);
763 	return 0;
764 
765 cmd_transmit_failed:
766 	close_candev(dev);
767 	return err;
768 }
769 
770 static void slc_dealloc(struct slcan *sl)
771 {
772 	int i = sl->dev->base_addr;
773 
774 	free_candev(sl->dev);
775 	slcan_devs[i] = NULL;
776 }
777 
778 static int slcan_change_mtu(struct net_device *dev, int new_mtu)
779 {
780 	return -EINVAL;
781 }
782 
783 static const struct net_device_ops slc_netdev_ops = {
784 	.ndo_open               = slc_open,
785 	.ndo_stop               = slc_close,
786 	.ndo_start_xmit         = slc_xmit,
787 	.ndo_change_mtu         = slcan_change_mtu,
788 };
789 
790 /******************************************
791  *  Routines looking at TTY side.
792  ******************************************/
793 
794 /* Handle the 'receiver data ready' interrupt.
795  * This function is called by the 'tty_io' module in the kernel when
796  * a block of SLCAN data has been received, which can now be decapsulated
797  * and sent on to some IP layer for further processing. This will not
798  * be re-entered while running but other ldisc functions may be called
799  * in parallel
800  */
801 static void slcan_receive_buf(struct tty_struct *tty,
802 			      const unsigned char *cp, const char *fp,
803 			      int count)
804 {
805 	struct slcan *sl = (struct slcan *)tty->disc_data;
806 
807 	if (!sl || sl->magic != SLCAN_MAGIC || !netif_running(sl->dev))
808 		return;
809 
810 	/* Read the characters out of the buffer */
811 	while (count--) {
812 		if (fp && *fp++) {
813 			if (!test_and_set_bit(SLF_ERROR, &sl->flags))
814 				sl->dev->stats.rx_errors++;
815 			cp++;
816 			continue;
817 		}
818 		slcan_unesc(sl, *cp++);
819 	}
820 }
821 
822 /************************************
823  *  slcan_open helper routines.
824  ************************************/
825 
826 /* Collect hanged up channels */
827 static void slc_sync(void)
828 {
829 	int i;
830 	struct net_device *dev;
831 	struct slcan	  *sl;
832 
833 	for (i = 0; i < maxdev; i++) {
834 		dev = slcan_devs[i];
835 		if (!dev)
836 			break;
837 
838 		sl = netdev_priv(dev);
839 		if (sl->tty)
840 			continue;
841 		if (dev->flags & IFF_UP)
842 			dev_close(dev);
843 	}
844 }
845 
846 /* Find a free SLCAN channel, and link in this `tty' line. */
847 static struct slcan *slc_alloc(void)
848 {
849 	int i;
850 	struct net_device *dev = NULL;
851 	struct slcan       *sl;
852 
853 	for (i = 0; i < maxdev; i++) {
854 		dev = slcan_devs[i];
855 		if (!dev)
856 			break;
857 	}
858 
859 	/* Sorry, too many, all slots in use */
860 	if (i >= maxdev)
861 		return NULL;
862 
863 	dev = alloc_candev(sizeof(*sl), 1);
864 	if (!dev)
865 		return NULL;
866 
867 	snprintf(dev->name, sizeof(dev->name), "slcan%d", i);
868 	dev->netdev_ops = &slc_netdev_ops;
869 	dev->base_addr  = i;
870 	slcan_set_ethtool_ops(dev);
871 	sl = netdev_priv(dev);
872 
873 	/* Initialize channel control data */
874 	sl->magic = SLCAN_MAGIC;
875 	sl->dev	= dev;
876 	sl->can.bitrate_const = slcan_bitrate_const;
877 	sl->can.bitrate_const_cnt = ARRAY_SIZE(slcan_bitrate_const);
878 	spin_lock_init(&sl->lock);
879 	INIT_WORK(&sl->tx_work, slcan_transmit);
880 	init_waitqueue_head(&sl->xcmd_wait);
881 	slcan_devs[i] = dev;
882 
883 	return sl;
884 }
885 
886 /* Open the high-level part of the SLCAN channel.
887  * This function is called by the TTY module when the
888  * SLCAN line discipline is called for.  Because we are
889  * sure the tty line exists, we only have to link it to
890  * a free SLCAN channel...
891  *
892  * Called in process context serialized from other ldisc calls.
893  */
894 static int slcan_open(struct tty_struct *tty)
895 {
896 	struct slcan *sl;
897 	int err;
898 
899 	if (!capable(CAP_NET_ADMIN))
900 		return -EPERM;
901 
902 	if (!tty->ops->write)
903 		return -EOPNOTSUPP;
904 
905 	/* RTnetlink lock is misused here to serialize concurrent
906 	 * opens of slcan channels. There are better ways, but it is
907 	 * the simplest one.
908 	 */
909 	rtnl_lock();
910 
911 	/* Collect hanged up channels. */
912 	slc_sync();
913 
914 	sl = tty->disc_data;
915 
916 	err = -EEXIST;
917 	/* First make sure we're not already connected. */
918 	if (sl && sl->magic == SLCAN_MAGIC)
919 		goto err_exit;
920 
921 	/* OK.  Find a free SLCAN channel to use. */
922 	err = -ENFILE;
923 	sl = slc_alloc();
924 	if (!sl)
925 		goto err_exit;
926 
927 	sl->tty = tty;
928 	tty->disc_data = sl;
929 
930 	if (!test_bit(SLF_INUSE, &sl->flags)) {
931 		/* Perform the low-level SLCAN initialization. */
932 		sl->rcount   = 0;
933 		sl->xleft    = 0;
934 
935 		set_bit(SLF_INUSE, &sl->flags);
936 
937 		rtnl_unlock();
938 		err = register_candev(sl->dev);
939 		if (err) {
940 			pr_err("slcan: can't register candev\n");
941 			goto err_free_chan;
942 		}
943 	} else {
944 		rtnl_unlock();
945 	}
946 
947 	tty->receive_room = 65536;	/* We don't flow control */
948 
949 	/* TTY layer expects 0 on success */
950 	return 0;
951 
952 err_free_chan:
953 	rtnl_lock();
954 	sl->tty = NULL;
955 	tty->disc_data = NULL;
956 	clear_bit(SLF_INUSE, &sl->flags);
957 	slc_dealloc(sl);
958 	rtnl_unlock();
959 	return err;
960 
961 err_exit:
962 	rtnl_unlock();
963 
964 	/* Count references from TTY module */
965 	return err;
966 }
967 
968 /* Close down a SLCAN channel.
969  * This means flushing out any pending queues, and then returning. This
970  * call is serialized against other ldisc functions.
971  *
972  * We also use this method for a hangup event.
973  */
974 static void slcan_close(struct tty_struct *tty)
975 {
976 	struct slcan *sl = (struct slcan *)tty->disc_data;
977 
978 	/* First make sure we're connected. */
979 	if (!sl || sl->magic != SLCAN_MAGIC || sl->tty != tty)
980 		return;
981 
982 	spin_lock_bh(&sl->lock);
983 	rcu_assign_pointer(tty->disc_data, NULL);
984 	sl->tty = NULL;
985 	spin_unlock_bh(&sl->lock);
986 
987 	synchronize_rcu();
988 	flush_work(&sl->tx_work);
989 
990 	slc_close(sl->dev);
991 	unregister_candev(sl->dev);
992 	rtnl_lock();
993 	slc_dealloc(sl);
994 	rtnl_unlock();
995 }
996 
997 static void slcan_hangup(struct tty_struct *tty)
998 {
999 	slcan_close(tty);
1000 }
1001 
1002 /* Perform I/O control on an active SLCAN channel. */
1003 static int slcan_ioctl(struct tty_struct *tty, unsigned int cmd,
1004 		       unsigned long arg)
1005 {
1006 	struct slcan *sl = (struct slcan *)tty->disc_data;
1007 	unsigned int tmp;
1008 
1009 	/* First make sure we're connected. */
1010 	if (!sl || sl->magic != SLCAN_MAGIC)
1011 		return -EINVAL;
1012 
1013 	switch (cmd) {
1014 	case SIOCGIFNAME:
1015 		tmp = strlen(sl->dev->name) + 1;
1016 		if (copy_to_user((void __user *)arg, sl->dev->name, tmp))
1017 			return -EFAULT;
1018 		return 0;
1019 
1020 	case SIOCSIFHWADDR:
1021 		return -EINVAL;
1022 
1023 	default:
1024 		return tty_mode_ioctl(tty, cmd, arg);
1025 	}
1026 }
1027 
1028 static struct tty_ldisc_ops slc_ldisc = {
1029 	.owner		= THIS_MODULE,
1030 	.num		= N_SLCAN,
1031 	.name		= "slcan",
1032 	.open		= slcan_open,
1033 	.close		= slcan_close,
1034 	.hangup		= slcan_hangup,
1035 	.ioctl		= slcan_ioctl,
1036 	.receive_buf	= slcan_receive_buf,
1037 	.write_wakeup	= slcan_write_wakeup,
1038 };
1039 
1040 static int __init slcan_init(void)
1041 {
1042 	int status;
1043 
1044 	if (maxdev < 4)
1045 		maxdev = 4; /* Sanity */
1046 
1047 	pr_info("slcan: serial line CAN interface driver\n");
1048 	pr_info("slcan: %d dynamic interface channels.\n", maxdev);
1049 
1050 	slcan_devs = kcalloc(maxdev, sizeof(struct net_device *), GFP_KERNEL);
1051 	if (!slcan_devs)
1052 		return -ENOMEM;
1053 
1054 	/* Fill in our line protocol discipline, and register it */
1055 	status = tty_register_ldisc(&slc_ldisc);
1056 	if (status)  {
1057 		pr_err("slcan: can't register line discipline\n");
1058 		kfree(slcan_devs);
1059 	}
1060 	return status;
1061 }
1062 
1063 static void __exit slcan_exit(void)
1064 {
1065 	int i;
1066 	struct net_device *dev;
1067 	struct slcan *sl;
1068 	unsigned long timeout = jiffies + HZ;
1069 	int busy = 0;
1070 
1071 	if (!slcan_devs)
1072 		return;
1073 
1074 	/* First of all: check for active disciplines and hangup them.
1075 	 */
1076 	do {
1077 		if (busy)
1078 			msleep_interruptible(100);
1079 
1080 		busy = 0;
1081 		for (i = 0; i < maxdev; i++) {
1082 			dev = slcan_devs[i];
1083 			if (!dev)
1084 				continue;
1085 			sl = netdev_priv(dev);
1086 			spin_lock_bh(&sl->lock);
1087 			if (sl->tty) {
1088 				busy++;
1089 				tty_hangup(sl->tty);
1090 			}
1091 			spin_unlock_bh(&sl->lock);
1092 		}
1093 	} while (busy && time_before(jiffies, timeout));
1094 
1095 	/* FIXME: hangup is async so we should wait when doing this second
1096 	 * phase
1097 	 */
1098 
1099 	for (i = 0; i < maxdev; i++) {
1100 		dev = slcan_devs[i];
1101 		if (!dev)
1102 			continue;
1103 
1104 		sl = netdev_priv(dev);
1105 		if (sl->tty)
1106 			netdev_err(dev, "tty discipline still running\n");
1107 
1108 		slc_close(dev);
1109 		unregister_candev(dev);
1110 		slc_dealloc(sl);
1111 	}
1112 
1113 	kfree(slcan_devs);
1114 	slcan_devs = NULL;
1115 
1116 	tty_unregister_ldisc(&slc_ldisc);
1117 }
1118 
1119 module_init(slcan_init);
1120 module_exit(slcan_exit);
1121