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