]> rtime.felk.cvut.cz Git - socketcan-devel.git/blob - kernel/2.6/drivers/net/can/slcan.c
Fix crash on re-attaching slcan netdevices ...
[socketcan-devel.git] / kernel / 2.6 / drivers / net / can / slcan.c
1 /*
2  * slcan.c - serial line CAN interface driver (using tty line discipline)
3  *
4  * Copyright (c) 2007 Volkswagen Group Electronic Research
5  * All rights reserved.
6  *
7  * Redistribution and use in source and binary forms, with or without
8  * modification, are permitted provided that the following conditions
9  * are met:
10  * 1. Redistributions of source code must retain the above copyright
11  *    notice, this list of conditions and the following disclaimer.
12  * 2. Redistributions in binary form must reproduce the above copyright
13  *    notice, this list of conditions and the following disclaimer in the
14  *    documentation and/or other materials provided with the distribution.
15  * 3. Neither the name of Volkswagen nor the names of its contributors
16  *    may be used to endorse or promote products derived from this software
17  *    without specific prior written permission.
18  *
19  * Alternatively, provided that this notice is retained in full, this
20  * software may be distributed under the terms of the GNU General
21  * Public License ("GPL") version 2, in which case the provisions of the
22  * GPL apply INSTEAD OF those given above.
23  *
24  * The provided data structures and external interfaces from this code
25  * are not restricted to be used by modules with a GPL compatible license.
26  *
27  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
28  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
29  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
30  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
31  * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
32  * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
33  * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
34  * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
35  * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
36  * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
37  * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
38  * DAMAGE.
39  *
40  * Send feedback to <socketcan-users@lists.berlios.de>
41  *
42  */
43
44 /*
45  * This file is derived from linux/drivers/net/slip.c
46  *
47  * Therefore it has the same (strange?) behaviour not to unregister the
48  * netdevice when detaching the tty. Is there any better solution?
49  *
50  * Do not try to attach, detach and re-attach a tty for this reason ...
51  *
52  * slip.c Authors: Laurence Culhane, <loz@holmes.demon.co.uk>
53  *                 Fred N. van Kempen, <waltje@uwalt.nl.mugnet.org>
54  */
55
56 #include <linux/version.h>
57 #include <linux/module.h>
58 #include <linux/moduleparam.h>
59
60 #include <asm/system.h>
61 #if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,17)
62 #include <linux/uaccess.h>
63 #else
64 #include <asm/uaccess.h>
65 #endif
66 #include <linux/bitops.h>
67 #include <linux/string.h>
68 #include <linux/mm.h>
69 #include <linux/interrupt.h>
70 #include <linux/in.h>
71 #include <linux/tty.h>
72 #include <linux/errno.h>
73 #include <linux/netdevice.h>
74 #include <linux/etherdevice.h>
75 #include <linux/skbuff.h>
76 #include <linux/rtnetlink.h>
77 #include <linux/if_arp.h>
78 #include <linux/if_ether.h>
79 #include <linux/if_slip.h>
80 #include <linux/delay.h>
81 #include <linux/init.h>
82
83 #include <linux/can.h>
84
85 #include <linux/can/version.h> /* for RCSID. Removed by mkpatch script */
86 RCSID("$Id$");
87
88 static __initdata const char banner[] =
89         KERN_INFO "slcan: serial line CAN interface driver\n";
90
91 MODULE_ALIAS_LDISC(N_SLCAN);
92 MODULE_DESCRIPTION("serial line CAN interface");
93 MODULE_LICENSE("Dual BSD/GPL");
94 MODULE_AUTHOR("Oliver Hartkopp <oliver.hartkopp@volkswagen.de>");
95
96 #ifdef CONFIG_CAN_DEBUG_DEVICES
97 static int debug;
98 module_param(debug, int, S_IRUGO);
99 #define DBG(args...)       (debug & 1 ? \
100                                (printk(KERN_DEBUG "slcan %s: ", __func__), \
101                                 printk(args)) : 0)
102 #else
103 #define DBG(args...)
104 #endif
105
106 #ifndef N_SLCAN
107 #error Your kernel does not support tty line discipline N_SLCAN
108 #endif
109 /*
110  * As there is currently no line discipline N_SLCAN in the mainstream kernel
111  * you will have to modify two kernel includes & recompile the kernel.
112  *
113  * Add this in include/asm/termios.h after the definition of N_HCI:
114  *        #define N_SLCAN         16
115  *
116  * Increment NR_LDICS in include/linux/tty.h from 16 to 17
117  *
118  * NEW: Since Kernel 2.6.21 you only have to change include/linux/tty.h
119  *
120  */
121
122 #define SLC_CHECK_TRANSMIT
123 #define SLCAN_MAGIC 0x53CA
124
125 static int maxdev = 10;         /* MAX number of SLCAN channels;
126                                    This can be overridden with
127                                    insmod slcan.ko maxdev=nnn   */
128 module_param(maxdev, int, 0);
129 MODULE_PARM_DESC(maxdev, "Maximum number of slcan interfaces");
130
131 /* maximum rx buffer len: extended CAN frame with timestamp */
132 #define SLC_MTU (sizeof("T1111222281122334455667788EA5F\r")+1)
133
134 struct slcan {
135         int                     magic;
136
137         /* Various fields. */
138         struct tty_struct       *tty;           /* ptr to TTY structure      */
139         struct net_device       *dev;           /* easy for intr handling    */
140         spinlock_t              lock;
141
142         /* These are pointers to the malloc()ed frame buffers. */
143         unsigned char           rbuff[SLC_MTU]; /* receiver buffer           */
144         int                     rcount;         /* received chars counter    */
145         unsigned char           xbuff[SLC_MTU]; /* transmitter buffer        */
146         unsigned char           *xhead;         /* pointer to next XMIT byte */
147         int                     xleft;          /* bytes left in XMIT queue  */
148
149 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,23)
150         /* SLCAN interface statistics. */
151         struct net_device_stats stats;
152 #endif
153
154         unsigned long           flags;          /* Flag values/ mode etc     */
155 #define SLF_INUSE               0               /* Channel in use            */
156 #define SLF_ERROR               1               /* Parity, etc. error        */
157
158         unsigned char           leased;
159         dev_t                   line;
160         pid_t                   pid;
161 };
162
163 static struct net_device **slcan_devs;
164
165
166 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,23)
167 /* Netdevice get statistics request */
168 static struct net_device_stats *slc_get_stats(struct net_device *dev)
169 {
170         struct slcan *sl = netdev_priv(dev);
171
172         return &sl->stats;
173 }
174 #endif
175
176  /************************************************************************
177   *                     SLCAN ENCAPSULATION FORMAT                       *
178   ************************************************************************/
179
180 /*
181  * A CAN frame has a can_id (11 bit standard frame format OR 29 bit extended
182  * frame format) a data length code (can_dlc) which can be from 0 to 8
183  * and up to <can_dlc> data bytes as payload.
184  * Additionally a CAN frame may become a remote transmission frame if the
185  * RTR-bit is set. This causes another ECU to send a CAN frame with the
186  * given can_id.
187  *
188  * The SLCAN ASCII representation of these different frame types is:
189  * <type> <id> <dlc> <data>*
190  *
191  * Extended frames (29 bit) are defined by capital characters in the type.
192  * RTR frames are defined as 'r' types - normal frames have 't' type:
193  * t => 11 bit data frame
194  * r => 11 bit RTR frame
195  * T => 29 bit data frame
196  * R => 29 bit RTR frame
197  *
198  * The <id> is 3 (standard) or 8 (extended) bytes in ASCII Hex (base64).
199  * The <dlc> is a one byte ASCII number ('0' - '8')
200  * The <data> section has at much ASCII Hex bytes as defined by the <dlc>
201  *
202  * Examples:
203  *
204  * t1230 : can_id 0x123, can_dlc 0, no data
205  * t4563112233 : can_id 0x456, can_dlc 3, data 0x11 0x22 0x33
206  * T12ABCDEF2AA55 : extended can_id 0x12ABCDEF, can_dlc 2, data 0xAA 0x55
207  * r1230 : can_id 0x123, can_dlc 0, no data, remote transmission request
208  *
209  */
210
211  /************************************************************************
212   *                     STANDARD SLCAN DECAPSULATION                     *
213   ************************************************************************/
214
215 static int asc2nibble(char c)
216 {
217
218         if ((c >= '0') && (c <= '9'))
219                 return c - '0';
220
221         if ((c >= 'A') && (c <= 'F'))
222                 return c - 'A' + 10;
223
224         if ((c >= 'a') && (c <= 'f'))
225                 return c - 'a' + 10;
226
227         return 16; /* error */
228 }
229
230 /* Send one completely decapsulated can_frame to the network layer */
231 static void slc_bump(struct slcan *sl)
232 {
233 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,23)
234         struct net_device_stats *stats = slc_get_stats(sl->dev);
235 #else
236         struct net_device_stats *stats = &sl->dev->stats;
237 #endif
238         struct sk_buff *skb;
239         struct can_frame cf;
240         int i, dlc_pos, tmp;
241         char cmd = sl->rbuff[0];
242
243         if ((cmd != 't') && (cmd != 'T') && (cmd != 'r') && (cmd != 'R'))
244                 return;
245
246         if (cmd & 0x20) /* tiny chars 'r' 't' => standard frame format */
247                 dlc_pos = 4; /* dlc position tiiid */
248         else
249                 dlc_pos = 9; /* dlc position Tiiiiiiiid */
250
251         if (!((sl->rbuff[dlc_pos] >= '0') && (sl->rbuff[dlc_pos] < '9')))
252                 return;
253
254         cf.can_dlc = sl->rbuff[dlc_pos] & 0x0F; /* get can_dlc */
255
256         sl->rbuff[dlc_pos] = 0; /* terminate can_id string */
257
258 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,25)
259         cf.can_id = simple_strtoul(sl->rbuff+1, NULL, 16);
260 #else
261         if (strict_strtoul(sl->rbuff+1, 16, (unsigned long *) &cf.can_id))
262                 return;
263 #endif
264
265         if (!(cmd & 0x20)) /* NO tiny chars => extended frame format */
266                 cf.can_id |= CAN_EFF_FLAG;
267
268         if ((cmd | 0x20) == 'r') /* RTR frame */
269                 cf.can_id |= CAN_RTR_FLAG;
270
271         *(u64 *) (&cf.data) = 0; /* clear payload */
272
273         for (i = 0, dlc_pos++; i < cf.can_dlc; i++) {
274
275                 tmp = asc2nibble(sl->rbuff[dlc_pos++]);
276                 if (tmp > 0x0F)
277                         return;
278                 cf.data[i] = (tmp << 4);
279                 tmp = asc2nibble(sl->rbuff[dlc_pos++]);
280                 if (tmp > 0x0F)
281                         return;
282                 cf.data[i] |= tmp;
283         }
284
285
286         skb = dev_alloc_skb(sizeof(struct can_frame));
287         if (!skb)
288                 return;
289
290         skb->dev = sl->dev;
291         skb->protocol = htons(ETH_P_CAN);
292         skb->pkt_type = PACKET_BROADCAST;
293         skb->ip_summed = CHECKSUM_UNNECESSARY;
294         memcpy(skb_put(skb, sizeof(struct can_frame)),
295                &cf, sizeof(struct can_frame));
296         netif_rx(skb);
297
298         sl->dev->last_rx = jiffies;
299         stats->rx_packets++;
300         stats->rx_bytes += cf.can_dlc;
301 }
302
303 /* parse tty input stream */
304 static void slcan_unesc(struct slcan *sl, unsigned char s)
305 {
306 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,23)
307         struct net_device_stats *stats = slc_get_stats(sl->dev);
308 #else
309         struct net_device_stats *stats = &sl->dev->stats;
310 #endif
311
312         if ((s == '\r') || (s == '\a')) { /* CR or BEL ends the pdu */
313                 if (!test_and_clear_bit(SLF_ERROR, &sl->flags) &&
314                     (sl->rcount > 4))  {
315                         slc_bump(sl);
316                 }
317                 sl->rcount = 0;
318         } else {
319                 if (!test_bit(SLF_ERROR, &sl->flags))  {
320                         if (sl->rcount < SLC_MTU)  {
321                                 sl->rbuff[sl->rcount++] = s;
322                                 return;
323                         } else {
324                                 stats->rx_over_errors++;
325                                 set_bit(SLF_ERROR, &sl->flags);
326                         }
327                 }
328         }
329 }
330
331  /************************************************************************
332   *                     STANDARD SLCAN ENCAPSULATION                     *
333   ************************************************************************/
334
335 /* Encapsulate one can_frame and stuff into a TTY queue. */
336 static void slc_encaps(struct slcan *sl, struct can_frame *cf)
337 {
338 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,23)
339         struct net_device_stats *stats = slc_get_stats(sl->dev);
340 #else
341         struct net_device_stats *stats = &sl->dev->stats;
342 #endif
343         int actual, idx, i;
344         char cmd;
345
346         if (cf->can_id & CAN_RTR_FLAG)
347                 cmd = 'R'; /* becomes 'r' in standard frame format */
348         else
349                 cmd = 'T'; /* becomes 't' in standard frame format */
350
351         if (cf->can_id & CAN_EFF_FLAG)
352                 sprintf(sl->xbuff, "%c%08X%d", cmd,
353                         cf->can_id & CAN_EFF_MASK, cf->can_dlc);
354         else
355                 sprintf(sl->xbuff, "%c%03X%d", cmd | 0x20,
356                         cf->can_id & CAN_SFF_MASK, cf->can_dlc);
357
358         idx = strlen(sl->xbuff);
359
360         for (i = 0; i < cf->can_dlc; i++)
361                 sprintf(&sl->xbuff[idx + 2*i], "%02X", cf->data[i]);
362
363         DBG("ASCII frame = '%s'\n", sl->xbuff);
364
365         strcat(sl->xbuff, "\r"); /* add terminating character */
366
367         /* Order of next two lines is *very* important.
368          * When we are sending a little amount of data,
369          * the transfer may be completed inside driver.write()
370          * routine, because it's running with interrupts enabled.
371          * In this case we *never* got WRITE_WAKEUP event,
372          * if we did not request it before write operation.
373          *       14 Oct 1994  Dmitry Gorodchanin.
374          */
375         sl->tty->flags |= (1 << TTY_DO_WRITE_WAKEUP);
376 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,26)
377         actual = sl->tty->driver->write(sl->tty, sl->xbuff, strlen(sl->xbuff));
378 #else
379         actual = sl->tty->ops->write(sl->tty, sl->xbuff, strlen(sl->xbuff));
380 #endif
381 #ifdef SLC_CHECK_TRANSMIT
382         sl->dev->trans_start = jiffies;
383 #endif
384         sl->xleft = strlen(sl->xbuff) - actual;
385         sl->xhead = sl->xbuff + actual;
386         stats->tx_bytes += cf->can_dlc;
387 }
388
389 /*
390  * Called by the driver when there's room for more data.  If we have
391  * more packets to send, we send them here.
392  */
393 static void slcan_write_wakeup(struct tty_struct *tty)
394 {
395         int actual;
396         struct slcan *sl = (struct slcan *) tty->disc_data;
397 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,23)
398         struct net_device_stats *stats = slc_get_stats(sl->dev);
399 #else
400         struct net_device_stats *stats = &sl->dev->stats;
401 #endif
402
403         /* First make sure we're connected. */
404         if (!sl || sl->magic != SLCAN_MAGIC || !netif_running(sl->dev))
405                 return;
406
407         if (sl->xleft <= 0)  {
408                 /* Now serial buffer is almost free & we can start
409                  * transmission of another packet */
410                 stats->tx_packets++;
411                 tty->flags &= ~(1 << TTY_DO_WRITE_WAKEUP);
412                 netif_wake_queue(sl->dev);
413                 return;
414         }
415
416 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,26)
417         actual = tty->driver->write(tty, sl->xhead, sl->xleft);
418 #else
419         actual = tty->ops->write(tty, sl->xhead, sl->xleft);
420 #endif
421         sl->xleft -= actual;
422         sl->xhead += actual;
423 }
424
425 static void slc_tx_timeout(struct net_device *dev)
426 {
427         struct slcan *sl = netdev_priv(dev);
428
429         spin_lock(&sl->lock);
430
431         if (netif_queue_stopped(dev)) {
432                 if (!netif_running(dev))
433                         goto out;
434
435                 /* May be we must check transmitter timeout here ?
436                  *      14 Oct 1994 Dmitry Gorodchanin.
437                  */
438 #ifdef SLC_CHECK_TRANSMIT
439                 if (time_before(jiffies, dev->trans_start + 20 * HZ))  {
440                         /* 20 sec timeout not reached */
441                         goto out;
442                 }
443                 printk(KERN_WARNING "%s: transmit timed out, %s?\n", dev->name,
444 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,26)
445                        (sl->tty->driver->chars_in_buffer(sl->tty) || sl->xleft)
446 #else
447                        (tty_chars_in_buffer(sl->tty) || sl->xleft)
448 #endif
449                        ? "bad line quality" : "driver error");
450                 sl->xleft = 0;
451                 sl->tty->flags &= ~(1 << TTY_DO_WRITE_WAKEUP);
452                 netif_wake_queue(sl->dev);
453 #endif
454         }
455 out:
456         spin_unlock(&sl->lock);
457 }
458
459
460 /******************************************
461  *   Routines looking at netdevice side.
462  ******************************************/
463
464 /* Send a can_frame to a TTY queue. */
465 static int slc_xmit(struct sk_buff *skb, struct net_device *dev)
466 {
467         struct slcan *sl = netdev_priv(dev);
468
469         if (skb->len != sizeof(struct can_frame))
470                 goto out;
471
472         spin_lock(&sl->lock);
473         if (!netif_running(dev))  {
474                 spin_unlock(&sl->lock);
475                 printk(KERN_WARNING "%s: xmit: iface is down\n", dev->name);
476                 goto out;
477         }
478
479         if (sl->tty == NULL) {
480                 spin_unlock(&sl->lock);
481                 goto out;
482         }
483
484         netif_stop_queue(sl->dev);
485         slc_encaps(sl, (struct can_frame *) skb->data); /* encaps & send */
486         spin_unlock(&sl->lock);
487
488 out:
489         kfree_skb(skb);
490         return 0;
491 }
492
493
494 /* Netdevice UP -> DOWN routine */
495 static int slc_close(struct net_device *dev)
496 {
497         struct slcan *sl = netdev_priv(dev);
498
499         spin_lock_bh(&sl->lock);
500         if (sl->tty) {
501                 /* TTY discipline is running. */
502                 sl->tty->flags &= ~(1 << TTY_DO_WRITE_WAKEUP);
503         }
504         netif_stop_queue(dev);
505         sl->rcount   = 0;
506         sl->xleft    = 0;
507         spin_unlock_bh(&sl->lock);
508
509         return 0;
510 }
511
512 /* Netdevice DOWN -> UP routine */
513 static int slc_open(struct net_device *dev)
514 {
515         struct slcan *sl = netdev_priv(dev);
516
517         if (sl->tty == NULL)
518                 return -ENODEV;
519
520         sl->flags &= (1 << SLF_INUSE);
521         netif_start_queue(dev);
522         return 0;
523 }
524
525 /* Netdevice register callback */
526 static void slc_setup(struct net_device *dev)
527 {
528         dev->open               = slc_open;
529         dev->destructor         = free_netdev;
530         dev->stop               = slc_close;
531 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,23)
532         dev->get_stats          = slc_get_stats;
533 #endif
534         dev->hard_start_xmit    = slc_xmit;
535
536         dev->hard_header_len    = 0;
537         dev->addr_len           = 0;
538         dev->tx_queue_len       = 10;
539
540         dev->mtu                = sizeof(struct can_frame);
541         dev->type               = ARPHRD_CAN;
542 #ifdef SLC_CHECK_TRANSMIT
543         dev->tx_timeout         = slc_tx_timeout;
544         dev->watchdog_timeo     = 20*HZ;
545 #endif
546
547         /* New-style flags. */
548         dev->flags              = IFF_NOARP;
549         dev->features           = NETIF_F_NO_CSUM;
550 }
551
552 /******************************************
553  * Routines looking at TTY side.
554  ******************************************/
555
556 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,16)
557 static int slcan_receive_room(struct tty_struct *tty)
558 {
559         return 65536;  /* We can handle an infinite amount of data. :-) */
560 }
561 #endif
562
563 /*
564  * Handle the 'receiver data ready' interrupt.
565  * This function is called by the 'tty_io' module in the kernel when
566  * a block of SLCAN data has been received, which can now be decapsulated
567  * and sent on to some IP layer for further processing. This will not
568  * be re-entered while running but other ldisc functions may be called
569  * in parallel
570  */
571
572 static void slcan_receive_buf(struct tty_struct *tty,
573                               const unsigned char *cp, char *fp, int count)
574 {
575         struct slcan *sl = (struct slcan *) tty->disc_data;
576 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,23)
577         struct net_device_stats *stats = slc_get_stats(sl->dev);
578 #else
579         struct net_device_stats *stats = &sl->dev->stats;
580 #endif
581
582         if (!sl || sl->magic != SLCAN_MAGIC ||
583             !netif_running(sl->dev))
584                 return;
585
586         /* Read the characters out of the buffer */
587         while (count--) {
588                 if (fp && *fp++) {
589                         if (!test_and_set_bit(SLF_ERROR, &sl->flags))
590                                 stats->rx_errors++;
591                         cp++;
592                         continue;
593                 }
594                 slcan_unesc(sl, *cp++);
595         }
596 }
597
598 /************************************
599  *  slcan_open helper routines.
600  ************************************/
601
602 /* Collect hanged up channels */
603
604 static void slc_sync(void)
605 {
606         int i;
607         struct net_device *dev;
608         struct slcan      *sl;
609
610         for (i = 0; i < maxdev; i++) {
611                 dev = slcan_devs[i];
612                 if (dev == NULL)
613                         break;
614
615                 sl = netdev_priv(dev);
616                 if (sl->tty || sl->leased)
617                         continue;
618                 if (dev->flags&IFF_UP)
619                         dev_close(dev);
620         }
621 }
622
623
624 /* Find a free SLCAN channel, and link in this `tty' line. */
625 static struct slcan *slc_alloc(dev_t line)
626 {
627         int i;
628         int sel = -1;
629         int score = -1;
630         struct net_device *dev = NULL;
631         struct slcan       *sl;
632
633         if (slcan_devs == NULL)
634                 return NULL;    /* Master array missing ! */
635
636         for (i = 0; i < maxdev; i++) {
637                 dev = slcan_devs[i];
638                 if (dev == NULL)
639                         break;
640
641                 sl = netdev_priv(dev);
642                 if (sl->leased) {
643                         if (sl->line != line)
644                                 continue;
645                         if (sl->tty)
646                                 return NULL;
647
648                         /* Clear ESCAPE & ERROR flags */
649                         sl->flags &= (1 << SLF_INUSE);
650                         return sl;
651                 }
652
653                 if (sl->tty)
654                         continue;
655
656                 if (current->pid == sl->pid) {
657                         if (sl->line == line && score < 3) {
658                                 sel = i;
659                                 score = 3;
660                                 continue;
661                         }
662                         if (score < 2) {
663                                 sel = i;
664                                 score = 2;
665                         }
666                         continue;
667                 }
668                 if (sl->line == line && score < 1) {
669                         sel = i;
670                         score = 1;
671                         continue;
672                 }
673                 if (score < 0) {
674                         sel = i;
675                         score = 0;
676                 }
677         }
678
679         if (sel >= 0) {
680                 i = sel;
681                 dev = slcan_devs[i];
682                 if (score > 1) {
683                         sl = netdev_priv(dev);
684                         sl->flags &= (1 << SLF_INUSE);
685                         return sl;
686                 }
687         }
688
689         /* Sorry, too many, all slots in use */
690         if (i >= maxdev)
691                 return NULL;
692
693         if (dev) {
694                 sl = netdev_priv(dev);
695                 if (test_bit(SLF_INUSE, &sl->flags)) {
696                         unregister_netdevice(dev);
697                         dev = NULL;
698                         slcan_devs[i] = NULL;
699                 }
700         }
701
702         if (!dev) {
703                 char name[IFNAMSIZ];
704                 sprintf(name, "slc%d", i);
705
706                 dev = alloc_netdev(sizeof(*sl), name, slc_setup);
707                 if (!dev)
708                         return NULL;
709                 dev->base_addr  = i;
710         }
711
712         sl = netdev_priv(dev);
713
714         /* Initialize channel control data */
715         sl->magic       = SLCAN_MAGIC;
716         sl->dev         = dev;
717         spin_lock_init(&sl->lock);
718         slcan_devs[i] = dev;
719
720         return sl;
721 }
722
723 /*
724  * Open the high-level part of the SLCAN channel.
725  * This function is called by the TTY module when the
726  * SLCAN line discipline is called for.  Because we are
727  * sure the tty line exists, we only have to link it to
728  * a free SLCAN channel...
729  *
730  * Called in process context serialized from other ldisc calls.
731  */
732
733 static int slcan_open(struct tty_struct *tty)
734 {
735         struct slcan *sl;
736         int err;
737
738         if (!capable(CAP_NET_ADMIN))
739                 return -EPERM;
740
741 #if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,25)
742         if (tty->ops->write == NULL)
743                 return -EOPNOTSUPP;
744 #endif
745
746         /* RTnetlink lock is misused here to serialize concurrent
747            opens of slcan channels. There are better ways, but it is
748            the simplest one.
749          */
750         rtnl_lock();
751
752         /* Collect hanged up channels. */
753         slc_sync();
754
755         sl = (struct slcan *) tty->disc_data;
756
757         err = -EEXIST;
758         /* First make sure we're not already connected. */
759         if (sl && sl->magic == SLCAN_MAGIC)
760                 goto err_exit;
761
762         /* OK.  Find a free SLCAN channel to use. */
763         err = -ENFILE;
764         sl = slc_alloc(tty_devnum(tty));
765         if (sl == NULL)
766                 goto err_exit;
767
768         sl->tty = tty;
769         tty->disc_data = sl;
770         sl->line = tty_devnum(tty);
771         sl->pid = current->pid;
772
773 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,16)
774         /* FIXME: already done before we were called - seems this can go */
775         if (tty->driver->flush_buffer)
776                 tty->driver->flush_buffer(tty);
777 #endif
778
779         if (!test_bit(SLF_INUSE, &sl->flags)) {
780                 /* Perform the low-level SLCAN initialization. */
781                 sl->rcount   = 0;
782                 sl->xleft    = 0;
783
784                 set_bit(SLF_INUSE, &sl->flags);
785
786                 err = register_netdevice(sl->dev);
787                 if (err)
788                         goto err_free_chan;
789         }
790
791         /* Done.  We have linked the TTY line to a channel. */
792         rtnl_unlock();
793
794 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,16)
795         tty->receive_room = 65536;      /* We don't flow control */
796 #endif
797
798         return sl->dev->base_addr;
799
800 err_free_chan:
801         sl->tty = NULL;
802         tty->disc_data = NULL;
803         clear_bit(SLF_INUSE, &sl->flags);
804
805 err_exit:
806         rtnl_unlock();
807
808         /* Count references from TTY module */
809         return err;
810 }
811
812 /*
813
814   FIXME: 1,2 are fixed 3 was never true anyway.
815
816    Let me to blame a bit.
817    1. TTY module calls this funstion on soft interrupt.
818    2. TTY module calls this function WITH MASKED INTERRUPTS!
819    3. TTY module does not notify us about line discipline
820       shutdown,
821
822    Seems, now it is clean. The solution is to consider netdevice and
823    line discipline sides as two independent threads.
824
825    By-product (not desired): slc? does not feel hangups and remains open.
826    It is supposed, that user level program (dip, diald, slattach...)
827    will catch SIGHUP and make the rest of work.
828
829    I see no way to make more with current tty code. --ANK
830  */
831
832 /*
833  * Close down a SLCAN channel.
834  * This means flushing out any pending queues, and then returning. This
835  * call is serialized against other ldisc functions.
836  */
837 static void slcan_close(struct tty_struct *tty)
838 {
839         struct slcan *sl = (struct slcan *) tty->disc_data;
840
841         /* First make sure we're connected. */
842         if (!sl || sl->magic != SLCAN_MAGIC || sl->tty != tty)
843                 return;
844
845         tty->disc_data = NULL;
846         sl->tty = NULL;
847         if (!sl->leased)
848                 sl->line = 0;
849
850         /* Count references from TTY module */
851 }
852
853 /* Perform I/O control on an active SLCAN channel. */
854 static int slcan_ioctl(struct tty_struct *tty, struct file *file,
855                        unsigned int cmd, unsigned long arg)
856 {
857         struct slcan *sl = (struct slcan *) tty->disc_data;
858         unsigned int tmp;
859
860         /* First make sure we're connected. */
861         if (!sl || sl->magic != SLCAN_MAGIC)
862                 return -EINVAL;
863
864         switch (cmd) {
865         case SIOCGIFNAME:
866                 tmp = strlen(sl->dev->name) + 1;
867                 if (copy_to_user((void __user *)arg, sl->dev->name, tmp))
868                         return -EFAULT;
869                 return 0;
870
871         case SIOCSIFHWADDR:
872                 return -EINVAL;
873
874 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,27)
875         /* Allow stty to read, but not set, the serial port */
876         case TCGETS:
877         case TCGETA:
878                 return n_tty_ioctl(tty, file, cmd, arg);
879
880         default:
881                 return -ENOIOCTLCMD;
882 #else
883         default:
884                 return tty_mode_ioctl(tty, file, cmd, arg);
885 #endif
886         }
887 }
888
889 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,27)
890 static struct tty_ldisc slc_ldisc = {
891 #else
892 static struct tty_ldisc_ops slc_ldisc = {
893 #endif
894         .owner          = THIS_MODULE,
895         .magic          = TTY_LDISC_MAGIC,
896         .name           = "slcan",
897         .open           = slcan_open,
898         .close          = slcan_close,
899         .ioctl          = slcan_ioctl,
900         .receive_buf    = slcan_receive_buf,
901 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,16)
902         .receive_room   = slcan_receive_room,
903 #endif
904         .write_wakeup   = slcan_write_wakeup,
905 };
906
907 /************************************
908  * general slcan module init/exit
909  ************************************/
910
911 static int __init slcan_init(void)
912 {
913         int status;
914
915         if (maxdev < 4)
916                 maxdev = 4; /* Sanity */
917
918         printk(banner);
919         printk(KERN_INFO "slcan: %d dynamic interface channels.\n", maxdev);
920
921         slcan_devs = kmalloc(sizeof(struct net_device *)*maxdev, GFP_KERNEL);
922         if (!slcan_devs) {
923                 printk(KERN_ERR "slcan: can't allocate slcan device array!\n");
924                 return -ENOMEM;
925         }
926
927         /* Clear the pointer array, we allocate devices when we need them */
928         memset(slcan_devs, 0, sizeof(struct net_device *)*maxdev);
929
930         /* Fill in our line protocol discipline, and register it */
931         status = tty_register_ldisc(N_SLCAN, &slc_ldisc);
932         if (status != 0)  {
933                 printk(KERN_ERR "slcan: can't register line discipline\n");
934                 kfree(slcan_devs);
935         }
936         return status;
937 }
938
939 static void __exit slcan_exit(void)
940 {
941         int i;
942         struct net_device *dev;
943         struct slcan *sl;
944         unsigned long timeout = jiffies + HZ;
945         int busy = 0;
946
947         if (slcan_devs == NULL)
948                 return;
949
950         /* First of all: check for active disciplines and hangup them.
951          */
952         do {
953                 if (busy)
954                         msleep_interruptible(100);
955
956                 busy = 0;
957                 for (i = 0; i < maxdev; i++) {
958                         dev = slcan_devs[i];
959                         if (!dev)
960                                 continue;
961                         sl = netdev_priv(dev);
962                         spin_lock_bh(&sl->lock);
963                         if (sl->tty) {
964                                 busy++;
965                                 tty_hangup(sl->tty);
966                         }
967                         spin_unlock_bh(&sl->lock);
968                 }
969         } while (busy && time_before(jiffies, timeout));
970
971
972         for (i = 0; i < maxdev; i++) {
973                 dev = slcan_devs[i];
974                 if (!dev)
975                         continue;
976                 slcan_devs[i] = NULL;
977
978                 sl = netdev_priv(dev);
979                 if (sl->tty) {
980                         printk(KERN_ERR "%s: tty discipline still running\n",
981                                dev->name);
982                         /* Intentionally leak the control block. */
983                         dev->destructor = NULL;
984                 }
985
986                 unregister_netdev(dev);
987         }
988
989         kfree(slcan_devs);
990         slcan_devs = NULL;
991
992         i = tty_unregister_ldisc(N_SLCAN);
993         if (i)
994                 printk(KERN_ERR "slcan: can't unregister ldisc (err %d)\n", i);
995 }
996
997 module_init(slcan_init);
998 module_exit(slcan_exit);