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