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