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