xref: /openbmc/linux/drivers/net/can/slcan/slcan-core.c (revision f05643a0)
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 module_param(maxdev, int, 0);
73 MODULE_PARM_DESC(maxdev, "Maximum number of slcan interfaces");
74 
75 /* maximum rx buffer len: extended CAN frame with timestamp */
76 #define SLC_MTU (sizeof("T1111222281122334455667788EA5F\r")+1)
77 
78 #define SLC_CMD_LEN 1
79 #define SLC_SFF_ID_LEN 3
80 #define SLC_EFF_ID_LEN 8
81 #define SLC_STATE_LEN 1
82 #define SLC_STATE_BE_RXCNT_LEN 3
83 #define SLC_STATE_BE_TXCNT_LEN 3
84 #define SLC_STATE_FRAME_LEN       (1 + SLC_CMD_LEN + SLC_STATE_BE_RXCNT_LEN + \
85 				   SLC_STATE_BE_TXCNT_LEN)
86 struct slcan {
87 	struct can_priv         can;
88 	int			magic;
89 
90 	/* Various fields. */
91 	struct tty_struct	*tty;		/* ptr to TTY structure	     */
92 	struct net_device	*dev;		/* easy for intr handling    */
93 	spinlock_t		lock;
94 	struct work_struct	tx_work;	/* Flushes transmit buffer   */
95 
96 	/* These are pointers to the malloc()ed frame buffers. */
97 	unsigned char		rbuff[SLC_MTU];	/* receiver buffer	     */
98 	int			rcount;         /* received chars counter    */
99 	unsigned char		xbuff[SLC_MTU];	/* transmitter buffer	     */
100 	unsigned char		*xhead;         /* pointer to next XMIT byte */
101 	int			xleft;          /* bytes left in XMIT queue  */
102 
103 	unsigned long		flags;		/* Flag values/ mode etc     */
104 #define SLF_INUSE		0		/* Channel in use            */
105 #define SLF_ERROR		1               /* Parity, etc. error        */
106 #define SLF_XCMD		2               /* Command transmission      */
107 	unsigned long           cmd_flags;      /* Command flags             */
108 #define CF_ERR_RST		0               /* Reset errors on open      */
109 	wait_queue_head_t       xcmd_wait;      /* Wait queue for commands   */
110 						/* transmission              */
111 };
112 
113 static struct net_device **slcan_devs;
114 
115 static const u32 slcan_bitrate_const[] = {
116 	10000, 20000, 50000, 100000, 125000,
117 	250000, 500000, 800000, 1000000
118 };
119 
120 bool slcan_err_rst_on_open(struct net_device *ndev)
121 {
122 	struct slcan *sl = netdev_priv(ndev);
123 
124 	return !!test_bit(CF_ERR_RST, &sl->cmd_flags);
125 }
126 
127 int slcan_enable_err_rst_on_open(struct net_device *ndev, bool on)
128 {
129 	struct slcan *sl = netdev_priv(ndev);
130 
131 	if (netif_running(ndev))
132 		return -EBUSY;
133 
134 	if (on)
135 		set_bit(CF_ERR_RST, &sl->cmd_flags);
136 	else
137 		clear_bit(CF_ERR_RST, &sl->cmd_flags);
138 
139 	return 0;
140 }
141 
142  /************************************************************************
143   *			SLCAN ENCAPSULATION FORMAT			 *
144   ************************************************************************/
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 		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 /*
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 /******************************************
637  *   Routines looking at netdevice side.
638  ******************************************/
639 
640 static int slcan_transmit_cmd(struct slcan *sl, const unsigned char *cmd)
641 {
642 	int ret, actual, n;
643 
644 	spin_lock(&sl->lock);
645 	if (!sl->tty) {
646 		spin_unlock(&sl->lock);
647 		return -ENODEV;
648 	}
649 
650 	n = snprintf(sl->xbuff, sizeof(sl->xbuff), "%s", cmd);
651 	set_bit(TTY_DO_WRITE_WAKEUP, &sl->tty->flags);
652 	actual = sl->tty->ops->write(sl->tty, sl->xbuff, n);
653 	sl->xleft = n - actual;
654 	sl->xhead = sl->xbuff + actual;
655 	set_bit(SLF_XCMD, &sl->flags);
656 	spin_unlock(&sl->lock);
657 	ret = wait_event_interruptible_timeout(sl->xcmd_wait,
658 					       !test_bit(SLF_XCMD, &sl->flags),
659 					       HZ);
660 	clear_bit(SLF_XCMD, &sl->flags);
661 	if (ret == -ERESTARTSYS)
662 		return ret;
663 
664 	if (ret == 0)
665 		return -ETIMEDOUT;
666 
667 	return 0;
668 }
669 
670 /* Netdevice UP -> DOWN routine */
671 static int slc_close(struct net_device *dev)
672 {
673 	struct slcan *sl = netdev_priv(dev);
674 	int err;
675 
676 	spin_lock_bh(&sl->lock);
677 	if (sl->tty) {
678 		if (sl->can.bittiming.bitrate &&
679 		    sl->can.bittiming.bitrate != CAN_BITRATE_UNKNOWN) {
680 			spin_unlock_bh(&sl->lock);
681 			err = slcan_transmit_cmd(sl, "C\r");
682 			spin_lock_bh(&sl->lock);
683 			if (err)
684 				netdev_warn(dev,
685 					    "failed to send close command 'C\\r'\n");
686 		}
687 
688 		/* TTY discipline is running. */
689 		clear_bit(TTY_DO_WRITE_WAKEUP, &sl->tty->flags);
690 	}
691 	netif_stop_queue(dev);
692 	close_candev(dev);
693 	sl->can.state = CAN_STATE_STOPPED;
694 	if (sl->can.bittiming.bitrate == CAN_BITRATE_UNKNOWN)
695 		sl->can.bittiming.bitrate = CAN_BITRATE_UNSET;
696 
697 	sl->rcount   = 0;
698 	sl->xleft    = 0;
699 	spin_unlock_bh(&sl->lock);
700 
701 	return 0;
702 }
703 
704 /* Netdevice DOWN -> UP routine */
705 static int slc_open(struct net_device *dev)
706 {
707 	struct slcan *sl = netdev_priv(dev);
708 	unsigned char cmd[SLC_MTU];
709 	int err, s;
710 
711 	if (sl->tty == NULL)
712 		return -ENODEV;
713 
714 	/* The baud rate is not set with the command
715 	 * `ip link set <iface> type can bitrate <baud>' and therefore
716 	 * can.bittiming.bitrate is CAN_BITRATE_UNSET (0), causing
717 	 * open_candev() to fail. So let's set to a fake value.
718 	 */
719 	if (sl->can.bittiming.bitrate == CAN_BITRATE_UNSET)
720 		sl->can.bittiming.bitrate = CAN_BITRATE_UNKNOWN;
721 
722 	err = open_candev(dev);
723 	if (err) {
724 		netdev_err(dev, "failed to open can device\n");
725 		return err;
726 	}
727 
728 	sl->flags &= BIT(SLF_INUSE);
729 
730 	if (sl->can.bittiming.bitrate != CAN_BITRATE_UNKNOWN) {
731 		for (s = 0; s < ARRAY_SIZE(slcan_bitrate_const); s++) {
732 			if (sl->can.bittiming.bitrate == slcan_bitrate_const[s])
733 				break;
734 		}
735 
736 		/* The CAN framework has already validate the bitrate value,
737 		 * so we can avoid to check if `s' has been properly set.
738 		 */
739 
740 		snprintf(cmd, sizeof(cmd), "C\rS%d\r", s);
741 		err = slcan_transmit_cmd(sl, cmd);
742 		if (err) {
743 			netdev_err(dev,
744 				   "failed to send bitrate command 'C\\rS%d\\r'\n",
745 				   s);
746 			goto cmd_transmit_failed;
747 		}
748 
749 		if (test_bit(CF_ERR_RST, &sl->cmd_flags)) {
750 			err = slcan_transmit_cmd(sl, "F\r");
751 			if (err) {
752 				netdev_err(dev,
753 					   "failed to send error command 'F\\r'\n");
754 				goto cmd_transmit_failed;
755 			}
756 		}
757 
758 		err = slcan_transmit_cmd(sl, "O\r");
759 		if (err) {
760 			netdev_err(dev, "failed to send open command 'O\\r'\n");
761 			goto cmd_transmit_failed;
762 		}
763 	}
764 
765 	sl->can.state = CAN_STATE_ERROR_ACTIVE;
766 	netif_start_queue(dev);
767 	return 0;
768 
769 cmd_transmit_failed:
770 	close_candev(dev);
771 	return err;
772 }
773 
774 static void slc_dealloc(struct slcan *sl)
775 {
776 	int i = sl->dev->base_addr;
777 
778 	free_candev(sl->dev);
779 	slcan_devs[i] = NULL;
780 }
781 
782 static int slcan_change_mtu(struct net_device *dev, int new_mtu)
783 {
784 	return -EINVAL;
785 }
786 
787 static const struct net_device_ops slc_netdev_ops = {
788 	.ndo_open               = slc_open,
789 	.ndo_stop               = slc_close,
790 	.ndo_start_xmit         = slc_xmit,
791 	.ndo_change_mtu         = slcan_change_mtu,
792 };
793 
794 /******************************************
795   Routines looking at TTY side.
796  ******************************************/
797 
798 /*
799  * Handle the 'receiver data ready' interrupt.
800  * This function is called by the 'tty_io' module in the kernel when
801  * a block of SLCAN data has been received, which can now be decapsulated
802  * and sent on to some IP layer for further processing. This will not
803  * be re-entered while running but other ldisc functions may be called
804  * in parallel
805  */
806 
807 static void slcan_receive_buf(struct tty_struct *tty,
808 			      const unsigned char *cp, const char *fp,
809 			      int count)
810 {
811 	struct slcan *sl = (struct slcan *) tty->disc_data;
812 
813 	if (!sl || sl->magic != SLCAN_MAGIC || !netif_running(sl->dev))
814 		return;
815 
816 	/* Read the characters out of the buffer */
817 	while (count--) {
818 		if (fp && *fp++) {
819 			if (!test_and_set_bit(SLF_ERROR, &sl->flags))
820 				sl->dev->stats.rx_errors++;
821 			cp++;
822 			continue;
823 		}
824 		slcan_unesc(sl, *cp++);
825 	}
826 }
827 
828 /************************************
829  *  slcan_open helper routines.
830  ************************************/
831 
832 /* Collect hanged up channels */
833 static void slc_sync(void)
834 {
835 	int i;
836 	struct net_device *dev;
837 	struct slcan	  *sl;
838 
839 	for (i = 0; i < maxdev; i++) {
840 		dev = slcan_devs[i];
841 		if (dev == NULL)
842 			break;
843 
844 		sl = netdev_priv(dev);
845 		if (sl->tty)
846 			continue;
847 		if (dev->flags & IFF_UP)
848 			dev_close(dev);
849 	}
850 }
851 
852 /* Find a free SLCAN channel, and link in this `tty' line. */
853 static struct slcan *slc_alloc(void)
854 {
855 	int i;
856 	struct net_device *dev = NULL;
857 	struct slcan       *sl;
858 
859 	for (i = 0; i < maxdev; i++) {
860 		dev = slcan_devs[i];
861 		if (dev == NULL)
862 			break;
863 
864 	}
865 
866 	/* Sorry, too many, all slots in use */
867 	if (i >= maxdev)
868 		return NULL;
869 
870 	dev = alloc_candev(sizeof(*sl), 1);
871 	if (!dev)
872 		return NULL;
873 
874 	snprintf(dev->name, sizeof(dev->name), "slcan%d", i);
875 	dev->netdev_ops = &slc_netdev_ops;
876 	dev->base_addr  = i;
877 	slcan_set_ethtool_ops(dev);
878 	sl = netdev_priv(dev);
879 
880 	/* Initialize channel control data */
881 	sl->magic = SLCAN_MAGIC;
882 	sl->dev	= dev;
883 	sl->can.bitrate_const = slcan_bitrate_const;
884 	sl->can.bitrate_const_cnt = ARRAY_SIZE(slcan_bitrate_const);
885 	spin_lock_init(&sl->lock);
886 	INIT_WORK(&sl->tx_work, slcan_transmit);
887 	init_waitqueue_head(&sl->xcmd_wait);
888 	slcan_devs[i] = dev;
889 
890 	return sl;
891 }
892 
893 /*
894  * Open the high-level part of the SLCAN channel.
895  * This function is called by the TTY module when the
896  * SLCAN line discipline is called for.  Because we are
897  * sure the tty line exists, we only have to link it to
898  * a free SLCAN channel...
899  *
900  * Called in process context serialized from other ldisc calls.
901  */
902 
903 static int slcan_open(struct tty_struct *tty)
904 {
905 	struct slcan *sl;
906 	int err;
907 
908 	if (!capable(CAP_NET_ADMIN))
909 		return -EPERM;
910 
911 	if (tty->ops->write == NULL)
912 		return -EOPNOTSUPP;
913 
914 	/* RTnetlink lock is misused here to serialize concurrent
915 	   opens of slcan channels. There are better ways, but it is
916 	   the simplest one.
917 	 */
918 	rtnl_lock();
919 
920 	/* Collect hanged up channels. */
921 	slc_sync();
922 
923 	sl = tty->disc_data;
924 
925 	err = -EEXIST;
926 	/* First make sure we're not already connected. */
927 	if (sl && sl->magic == SLCAN_MAGIC)
928 		goto err_exit;
929 
930 	/* OK.  Find a free SLCAN channel to use. */
931 	err = -ENFILE;
932 	sl = slc_alloc();
933 	if (sl == NULL)
934 		goto err_exit;
935 
936 	sl->tty = tty;
937 	tty->disc_data = sl;
938 
939 	if (!test_bit(SLF_INUSE, &sl->flags)) {
940 		/* Perform the low-level SLCAN initialization. */
941 		sl->rcount   = 0;
942 		sl->xleft    = 0;
943 
944 		set_bit(SLF_INUSE, &sl->flags);
945 
946 		rtnl_unlock();
947 		err = register_candev(sl->dev);
948 		if (err) {
949 			pr_err("slcan: can't register candev\n");
950 			goto err_free_chan;
951 		}
952 	} else {
953 		rtnl_unlock();
954 	}
955 
956 	tty->receive_room = 65536;	/* We don't flow control */
957 
958 	/* TTY layer expects 0 on success */
959 	return 0;
960 
961 err_free_chan:
962 	rtnl_lock();
963 	sl->tty = NULL;
964 	tty->disc_data = NULL;
965 	clear_bit(SLF_INUSE, &sl->flags);
966 	slc_dealloc(sl);
967 	rtnl_unlock();
968 	return err;
969 
970 err_exit:
971 	rtnl_unlock();
972 
973 	/* Count references from TTY module */
974 	return err;
975 }
976 
977 /*
978  * Close down a SLCAN channel.
979  * This means flushing out any pending queues, and then returning. This
980  * call is serialized against other ldisc functions.
981  *
982  * We also use this method for a hangup event.
983  */
984 
985 static void slcan_close(struct tty_struct *tty)
986 {
987 	struct slcan *sl = (struct slcan *) tty->disc_data;
988 
989 	/* First make sure we're connected. */
990 	if (!sl || sl->magic != SLCAN_MAGIC || sl->tty != tty)
991 		return;
992 
993 	spin_lock_bh(&sl->lock);
994 	rcu_assign_pointer(tty->disc_data, NULL);
995 	sl->tty = NULL;
996 	spin_unlock_bh(&sl->lock);
997 
998 	synchronize_rcu();
999 	flush_work(&sl->tx_work);
1000 
1001 	slc_close(sl->dev);
1002 	unregister_candev(sl->dev);
1003 	rtnl_lock();
1004 	slc_dealloc(sl);
1005 	rtnl_unlock();
1006 }
1007 
1008 static void slcan_hangup(struct tty_struct *tty)
1009 {
1010 	slcan_close(tty);
1011 }
1012 
1013 /* Perform I/O control on an active SLCAN channel. */
1014 static int slcan_ioctl(struct tty_struct *tty, unsigned int cmd,
1015 		       unsigned long arg)
1016 {
1017 	struct slcan *sl = (struct slcan *) tty->disc_data;
1018 	unsigned int tmp;
1019 
1020 	/* First make sure we're connected. */
1021 	if (!sl || sl->magic != SLCAN_MAGIC)
1022 		return -EINVAL;
1023 
1024 	switch (cmd) {
1025 	case SIOCGIFNAME:
1026 		tmp = strlen(sl->dev->name) + 1;
1027 		if (copy_to_user((void __user *)arg, sl->dev->name, tmp))
1028 			return -EFAULT;
1029 		return 0;
1030 
1031 	case SIOCSIFHWADDR:
1032 		return -EINVAL;
1033 
1034 	default:
1035 		return tty_mode_ioctl(tty, cmd, arg);
1036 	}
1037 }
1038 
1039 static struct tty_ldisc_ops slc_ldisc = {
1040 	.owner		= THIS_MODULE,
1041 	.num		= N_SLCAN,
1042 	.name		= "slcan",
1043 	.open		= slcan_open,
1044 	.close		= slcan_close,
1045 	.hangup		= slcan_hangup,
1046 	.ioctl		= slcan_ioctl,
1047 	.receive_buf	= slcan_receive_buf,
1048 	.write_wakeup	= slcan_write_wakeup,
1049 };
1050 
1051 static int __init slcan_init(void)
1052 {
1053 	int status;
1054 
1055 	if (maxdev < 4)
1056 		maxdev = 4; /* Sanity */
1057 
1058 	pr_info("slcan: serial line CAN interface driver\n");
1059 	pr_info("slcan: %d dynamic interface channels.\n", maxdev);
1060 
1061 	slcan_devs = kcalloc(maxdev, sizeof(struct net_device *), GFP_KERNEL);
1062 	if (!slcan_devs)
1063 		return -ENOMEM;
1064 
1065 	/* Fill in our line protocol discipline, and register it */
1066 	status = tty_register_ldisc(&slc_ldisc);
1067 	if (status)  {
1068 		printk(KERN_ERR "slcan: can't register line discipline\n");
1069 		kfree(slcan_devs);
1070 	}
1071 	return status;
1072 }
1073 
1074 static void __exit slcan_exit(void)
1075 {
1076 	int i;
1077 	struct net_device *dev;
1078 	struct slcan *sl;
1079 	unsigned long timeout = jiffies + HZ;
1080 	int busy = 0;
1081 
1082 	if (slcan_devs == NULL)
1083 		return;
1084 
1085 	/* First of all: check for active disciplines and hangup them.
1086 	 */
1087 	do {
1088 		if (busy)
1089 			msleep_interruptible(100);
1090 
1091 		busy = 0;
1092 		for (i = 0; i < maxdev; i++) {
1093 			dev = slcan_devs[i];
1094 			if (!dev)
1095 				continue;
1096 			sl = netdev_priv(dev);
1097 			spin_lock_bh(&sl->lock);
1098 			if (sl->tty) {
1099 				busy++;
1100 				tty_hangup(sl->tty);
1101 			}
1102 			spin_unlock_bh(&sl->lock);
1103 		}
1104 	} while (busy && time_before(jiffies, timeout));
1105 
1106 	/* FIXME: hangup is async so we should wait when doing this second
1107 	   phase */
1108 
1109 	for (i = 0; i < maxdev; i++) {
1110 		dev = slcan_devs[i];
1111 		if (!dev)
1112 			continue;
1113 
1114 		sl = netdev_priv(dev);
1115 		if (sl->tty) {
1116 			netdev_err(dev, "tty discipline still running\n");
1117 		}
1118 
1119 		slc_close(dev);
1120 		unregister_candev(dev);
1121 		slc_dealloc(sl);
1122 	}
1123 
1124 	kfree(slcan_devs);
1125 	slcan_devs = NULL;
1126 
1127 	tty_unregister_ldisc(&slc_ldisc);
1128 }
1129 
1130 module_init(slcan_init);
1131 module_exit(slcan_exit);
1132