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