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