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