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