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