]> rtime.felk.cvut.cz Git - socketcan-devel.git/blob - kernel/2.6/drivers/net/can/slcan.c
merged branches/netlink in rev. 1037 back to trunk.
[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/string.h>
61 #include <linux/mm.h>
62 #include <linux/interrupt.h>
63 #include <linux/in.h>
64 #include <linux/tty.h>
65 #include <linux/errno.h>
66 #include <linux/netdevice.h>
67 #include <linux/etherdevice.h>
68 #include <linux/skbuff.h>
69 #include <linux/rtnetlink.h>
70 #include <linux/if_arp.h>
71 #include <linux/if_ether.h>
72 #include <linux/if_slip.h>
73 #include <linux/delay.h>
74 #include <linux/init.h>
75
76 #include <socketcan/can.h>
77
78 #include <socketcan/can/version.h> /* for RCSID. Removed by mkpatch script */
79 RCSID("$Id$");
80
81 static __initdata const char banner[] =
82         KERN_INFO "slcan: serial line CAN interface driver\n";
83
84 MODULE_ALIAS_LDISC(N_SLCAN);
85 MODULE_DESCRIPTION("serial line CAN interface");
86 MODULE_LICENSE("GPL");
87 MODULE_AUTHOR("Oliver Hartkopp <oliver.hartkopp@volkswagen.de>");
88
89 #ifdef CONFIG_CAN_DEBUG_DEVICES
90 static int debug;
91 module_param(debug, int, S_IRUGO);
92 #define DBG(args...)       (debug & 1 ? \
93                                (printk(KERN_DEBUG "slcan %s: ", __func__), \
94                                 printk(args)) : 0)
95 #else
96 #define DBG(args...)
97 #endif
98
99 #ifndef N_SLCAN
100 #error Your kernel does not support tty line discipline N_SLCAN
101 #endif
102 /*
103  * As there is currently no line discipline N_SLCAN in the mainstream kernel
104  * you will have to modify two kernel includes & recompile the kernel.
105  *
106  * Add this in include/asm/termios.h after the definition of N_HCI:
107  *        #define N_SLCAN         16
108  *
109  * Increment NR_LDICS in include/linux/tty.h from 16 to 17
110  *
111  * NEW: Since Kernel 2.6.21 you only have to change include/linux/tty.h
112  *
113  * HACK for precompiled Kernels:
114  *
115  * In order to use the slcan driver without rebuilding the kernel, the slcan
116  * driver must be compiled to use an existing line discipline.
117  * The N_MOUSE line discipline is documented to be free for custom use and
118  * using it *should* not cause any side effect.
119  *
120  * Then, before compiling the slcan driver, add a -DN_SLCAN=N_MOUSE  
121  * compilation option in its Makefile. The slcan_attach tool must(!!) also be
122  * rebuild to use the right value for N_SLCAN. This workaround will allow  
123  * to use the slcan driver with an existing kernel.
124  */
125
126 #define SLC_CHECK_TRANSMIT
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         sl->dev->last_rx = jiffies;
305         stats->rx_packets++;
306         stats->rx_bytes += cf.can_dlc;
307 }
308
309 /* parse tty input stream */
310 static void slcan_unesc(struct slcan *sl, unsigned char s)
311 {
312 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,23)
313         struct net_device_stats *stats = slc_get_stats(sl->dev);
314 #else
315         struct net_device_stats *stats = &sl->dev->stats;
316 #endif
317
318         if ((s == '\r') || (s == '\a')) { /* CR or BEL ends the pdu */
319                 if (!test_and_clear_bit(SLF_ERROR, &sl->flags) &&
320                     (sl->rcount > 4))  {
321                         slc_bump(sl);
322                 }
323                 sl->rcount = 0;
324         } else {
325                 if (!test_bit(SLF_ERROR, &sl->flags))  {
326                         if (sl->rcount < SLC_MTU)  {
327                                 sl->rbuff[sl->rcount++] = s;
328                                 return;
329                         } else {
330                                 stats->rx_over_errors++;
331                                 set_bit(SLF_ERROR, &sl->flags);
332                         }
333                 }
334         }
335 }
336
337  /************************************************************************
338   *                     STANDARD SLCAN ENCAPSULATION                     *
339   ************************************************************************/
340
341 /* Encapsulate one can_frame and stuff into a TTY queue. */
342 static void slc_encaps(struct slcan *sl, struct can_frame *cf)
343 {
344 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,23)
345         struct net_device_stats *stats = slc_get_stats(sl->dev);
346 #else
347         struct net_device_stats *stats = &sl->dev->stats;
348 #endif
349         int actual, idx, i;
350         char cmd;
351
352         if (cf->can_id & CAN_RTR_FLAG)
353                 cmd = 'R'; /* becomes 'r' in standard frame format */
354         else
355                 cmd = 'T'; /* becomes 't' in standard frame format */
356
357         if (cf->can_id & CAN_EFF_FLAG)
358                 sprintf(sl->xbuff, "%c%08X%d", cmd,
359                         cf->can_id & CAN_EFF_MASK, cf->can_dlc);
360         else
361                 sprintf(sl->xbuff, "%c%03X%d", cmd | 0x20,
362                         cf->can_id & CAN_SFF_MASK, cf->can_dlc);
363
364         idx = strlen(sl->xbuff);
365
366         for (i = 0; i < cf->can_dlc; i++)
367                 sprintf(&sl->xbuff[idx + 2*i], "%02X", cf->data[i]);
368
369         DBG("ASCII frame = '%s'\n", sl->xbuff);
370
371         strcat(sl->xbuff, "\r"); /* add terminating character */
372
373         /* Order of next two lines is *very* important.
374          * When we are sending a little amount of data,
375          * the transfer may be completed inside driver.write()
376          * routine, because it's running with interrupts enabled.
377          * In this case we *never* got WRITE_WAKEUP event,
378          * if we did not request it before write operation.
379          *       14 Oct 1994  Dmitry Gorodchanin.
380          */
381         sl->tty->flags |= (1 << TTY_DO_WRITE_WAKEUP);
382 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,26)
383         actual = sl->tty->driver->write(sl->tty, sl->xbuff, strlen(sl->xbuff));
384 #else
385         actual = sl->tty->ops->write(sl->tty, sl->xbuff, strlen(sl->xbuff));
386 #endif
387 #ifdef SLC_CHECK_TRANSMIT
388         sl->dev->trans_start = jiffies;
389 #endif
390         sl->xleft = strlen(sl->xbuff) - actual;
391         sl->xhead = sl->xbuff + actual;
392         stats->tx_bytes += cf->can_dlc;
393 }
394
395 /*
396  * Called by the driver when there's room for more data.  If we have
397  * more packets to send, we send them here.
398  */
399 static void slcan_write_wakeup(struct tty_struct *tty)
400 {
401         int actual;
402         struct slcan *sl = (struct slcan *) tty->disc_data;
403 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,23)
404         struct net_device_stats *stats = slc_get_stats(sl->dev);
405 #else
406         struct net_device_stats *stats = &sl->dev->stats;
407 #endif
408
409         /* First make sure we're connected. */
410         if (!sl || sl->magic != SLCAN_MAGIC || !netif_running(sl->dev))
411                 return;
412
413         if (sl->xleft <= 0)  {
414                 /* Now serial buffer is almost free & we can start
415                  * transmission of another packet */
416                 stats->tx_packets++;
417                 tty->flags &= ~(1 << TTY_DO_WRITE_WAKEUP);
418                 netif_wake_queue(sl->dev);
419                 return;
420         }
421
422 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,26)
423         actual = tty->driver->write(tty, sl->xhead, sl->xleft);
424 #else
425         actual = tty->ops->write(tty, sl->xhead, sl->xleft);
426 #endif
427         sl->xleft -= actual;
428         sl->xhead += actual;
429 }
430
431 static void slc_tx_timeout(struct net_device *dev)
432 {
433         struct slcan *sl = netdev_priv(dev);
434
435         spin_lock(&sl->lock);
436
437         if (netif_queue_stopped(dev)) {
438                 if (!netif_running(dev))
439                         goto out;
440
441                 /* May be we must check transmitter timeout here ?
442                  *      14 Oct 1994 Dmitry Gorodchanin.
443                  */
444 #ifdef SLC_CHECK_TRANSMIT
445                 if (time_before(jiffies, dev->trans_start + 20 * HZ))  {
446                         /* 20 sec timeout not reached */
447                         goto out;
448                 }
449                 printk(KERN_WARNING "%s: transmit timed out, %s?\n", dev->name,
450 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,26)
451                        (sl->tty->driver->chars_in_buffer(sl->tty) || sl->xleft)
452 #else
453                        (tty_chars_in_buffer(sl->tty) || sl->xleft)
454 #endif
455                        ? "bad line quality" : "driver error");
456                 sl->xleft = 0;
457                 sl->tty->flags &= ~(1 << TTY_DO_WRITE_WAKEUP);
458                 netif_wake_queue(sl->dev);
459 #endif
460         }
461 out:
462         spin_unlock(&sl->lock);
463 }
464
465
466 /******************************************
467  *   Routines looking at netdevice side.
468  ******************************************/
469
470 /* Send a can_frame to a TTY queue. */
471 static int slc_xmit(struct sk_buff *skb, struct net_device *dev)
472 {
473         struct slcan *sl = netdev_priv(dev);
474
475         if (skb->len != sizeof(struct can_frame))
476                 goto out;
477
478         spin_lock(&sl->lock);
479         if (!netif_running(dev))  {
480                 spin_unlock(&sl->lock);
481                 printk(KERN_WARNING "%s: xmit: iface is down\n", dev->name);
482                 goto out;
483         }
484
485         if (sl->tty == NULL) {
486                 spin_unlock(&sl->lock);
487                 goto out;
488         }
489
490         netif_stop_queue(sl->dev);
491         slc_encaps(sl, (struct can_frame *) skb->data); /* encaps & send */
492         spin_unlock(&sl->lock);
493
494 out:
495         kfree_skb(skb);
496         return 0;
497 }
498
499
500 /* Netdevice UP -> DOWN routine */
501 static int slc_close(struct net_device *dev)
502 {
503         struct slcan *sl = netdev_priv(dev);
504
505         spin_lock_bh(&sl->lock);
506         if (sl->tty) {
507                 /* TTY discipline is running. */
508                 sl->tty->flags &= ~(1 << TTY_DO_WRITE_WAKEUP);
509         }
510         netif_stop_queue(dev);
511         sl->rcount   = 0;
512         sl->xleft    = 0;
513         spin_unlock_bh(&sl->lock);
514
515         return 0;
516 }
517
518 /* Netdevice DOWN -> UP routine */
519 static int slc_open(struct net_device *dev)
520 {
521         struct slcan *sl = netdev_priv(dev);
522
523         if (sl->tty == NULL)
524                 return -ENODEV;
525
526         sl->flags &= (1 << SLF_INUSE);
527         netif_start_queue(dev);
528         return 0;
529 }
530
531 #if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,28)
532 static const struct net_device_ops slc_netdev_ops = {
533         .ndo_open               = slc_open,
534         .ndo_stop               = slc_close,
535         .ndo_start_xmit         = slc_xmit,
536 #ifdef SLC_CHECK_TRANSMIT
537         .ndo_tx_timeout         = slc_tx_timeout,
538 #endif
539 };
540 #endif
541
542 /* Netdevice register callback */
543 static void slc_setup(struct net_device *dev)
544 {
545 #if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,28)
546         dev->netdev_ops = &slc_netdev_ops;
547 #else
548         dev->open               = slc_open;
549         dev->stop               = slc_close;
550         dev->hard_start_xmit    = slc_xmit;
551 #endif
552         dev->destructor         = free_netdev;
553 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,23)
554         dev->get_stats          = slc_get_stats;
555 #endif
556
557         dev->hard_header_len    = 0;
558         dev->addr_len           = 0;
559         dev->tx_queue_len       = 10;
560
561         dev->mtu                = sizeof(struct can_frame);
562         dev->type               = ARPHRD_CAN;
563 #ifdef SLC_CHECK_TRANSMIT
564 #if LINUX_VERSION_CODE <= KERNEL_VERSION(2,6,28)
565         dev->tx_timeout         = slc_tx_timeout;
566 #endif
567         dev->watchdog_timeo     = 20*HZ;
568 #endif
569
570         /* New-style flags. */
571         dev->flags              = IFF_NOARP;
572         dev->features           = NETIF_F_NO_CSUM;
573 }
574
575 /******************************************
576  * Routines looking at TTY side.
577  ******************************************/
578
579 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,16)
580 static int slcan_receive_room(struct tty_struct *tty)
581 {
582         return 65536;  /* We can handle an infinite amount of data. :-) */
583 }
584 #endif
585
586 /*
587  * Handle the 'receiver data ready' interrupt.
588  * This function is called by the 'tty_io' module in the kernel when
589  * a block of SLCAN data has been received, which can now be decapsulated
590  * and sent on to some IP layer for further processing. This will not
591  * be re-entered while running but other ldisc functions may be called
592  * in parallel
593  */
594
595 static void slcan_receive_buf(struct tty_struct *tty,
596                               const unsigned char *cp, char *fp, int count)
597 {
598         struct slcan *sl = (struct slcan *) tty->disc_data;
599 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,23)
600         struct net_device_stats *stats = slc_get_stats(sl->dev);
601 #else
602         struct net_device_stats *stats = &sl->dev->stats;
603 #endif
604
605         if (!sl || sl->magic != SLCAN_MAGIC ||
606             !netif_running(sl->dev))
607                 return;
608
609         /* Read the characters out of the buffer */
610         while (count--) {
611                 if (fp && *fp++) {
612                         if (!test_and_set_bit(SLF_ERROR, &sl->flags))
613                                 stats->rx_errors++;
614                         cp++;
615                         continue;
616                 }
617                 slcan_unesc(sl, *cp++);
618         }
619 }
620
621 /************************************
622  *  slcan_open helper routines.
623  ************************************/
624
625 /* Collect hanged up channels */
626
627 static void slc_sync(void)
628 {
629         int i;
630         struct net_device *dev;
631         struct slcan      *sl;
632
633         for (i = 0; i < maxdev; i++) {
634                 dev = slcan_devs[i];
635                 if (dev == NULL)
636                         break;
637
638                 sl = netdev_priv(dev);
639                 if (sl->tty || sl->leased)
640                         continue;
641                 if (dev->flags&IFF_UP)
642                         dev_close(dev);
643         }
644 }
645
646
647 /* Find a free SLCAN channel, and link in this `tty' line. */
648 static struct slcan *slc_alloc(dev_t line)
649 {
650         int i;
651         int sel = -1;
652         int score = -1;
653         struct net_device *dev = NULL;
654         struct slcan       *sl;
655
656         if (slcan_devs == NULL)
657                 return NULL;    /* Master array missing ! */
658
659         for (i = 0; i < maxdev; i++) {
660                 dev = slcan_devs[i];
661                 if (dev == NULL)
662                         break;
663
664                 sl = netdev_priv(dev);
665                 if (sl->leased) {
666                         if (sl->line != line)
667                                 continue;
668                         if (sl->tty)
669                                 return NULL;
670
671                         /* Clear ESCAPE & ERROR flags */
672                         sl->flags &= (1 << SLF_INUSE);
673                         return sl;
674                 }
675
676                 if (sl->tty)
677                         continue;
678
679                 if (current->pid == sl->pid) {
680                         if (sl->line == line && score < 3) {
681                                 sel = i;
682                                 score = 3;
683                                 continue;
684                         }
685                         if (score < 2) {
686                                 sel = i;
687                                 score = 2;
688                         }
689                         continue;
690                 }
691                 if (sl->line == line && score < 1) {
692                         sel = i;
693                         score = 1;
694                         continue;
695                 }
696                 if (score < 0) {
697                         sel = i;
698                         score = 0;
699                 }
700         }
701
702         if (sel >= 0) {
703                 i = sel;
704                 dev = slcan_devs[i];
705                 if (score > 1) {
706                         sl = netdev_priv(dev);
707                         sl->flags &= (1 << SLF_INUSE);
708                         return sl;
709                 }
710         }
711
712         /* Sorry, too many, all slots in use */
713         if (i >= maxdev)
714                 return NULL;
715
716         if (dev) {
717                 sl = netdev_priv(dev);
718                 if (test_bit(SLF_INUSE, &sl->flags)) {
719                         unregister_netdevice(dev);
720                         dev = NULL;
721                         slcan_devs[i] = NULL;
722                 }
723         }
724
725         if (!dev) {
726                 char name[IFNAMSIZ];
727                 sprintf(name, "slc%d", i);
728
729                 dev = alloc_netdev(sizeof(*sl), name, slc_setup);
730                 if (!dev)
731                         return NULL;
732                 dev->base_addr  = i;
733         }
734
735         sl = netdev_priv(dev);
736
737         /* Initialize channel control data */
738         sl->magic       = SLCAN_MAGIC;
739         sl->dev         = dev;
740         spin_lock_init(&sl->lock);
741         slcan_devs[i] = dev;
742
743         return sl;
744 }
745
746 /*
747  * Open the high-level part of the SLCAN channel.
748  * This function is called by the TTY module when the
749  * SLCAN line discipline is called for.  Because we are
750  * sure the tty line exists, we only have to link it to
751  * a free SLCAN channel...
752  *
753  * Called in process context serialized from other ldisc calls.
754  */
755
756 static int slcan_open(struct tty_struct *tty)
757 {
758         struct slcan *sl;
759         int err;
760
761         if (!capable(CAP_NET_ADMIN))
762                 return -EPERM;
763
764 #if LINUX_VERSION_CODE > KERNEL_VERSION(2,6,25)
765         if (tty->ops->write == NULL)
766                 return -EOPNOTSUPP;
767 #endif
768
769         /* RTnetlink lock is misused here to serialize concurrent
770            opens of slcan channels. There are better ways, but it is
771            the simplest one.
772          */
773         rtnl_lock();
774
775         /* Collect hanged up channels. */
776         slc_sync();
777
778         sl = (struct slcan *) tty->disc_data;
779
780         err = -EEXIST;
781         /* First make sure we're not already connected. */
782         if (sl && sl->magic == SLCAN_MAGIC)
783                 goto err_exit;
784
785         /* OK.  Find a free SLCAN channel to use. */
786         err = -ENFILE;
787         sl = slc_alloc(tty_devnum(tty));
788         if (sl == NULL)
789                 goto err_exit;
790
791         sl->tty = tty;
792         tty->disc_data = sl;
793         sl->line = tty_devnum(tty);
794         sl->pid = current->pid;
795
796 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,16)
797         /* FIXME: already done before we were called - seems this can go */
798         if (tty->driver->flush_buffer)
799                 tty->driver->flush_buffer(tty);
800 #endif
801
802         if (!test_bit(SLF_INUSE, &sl->flags)) {
803                 /* Perform the low-level SLCAN initialization. */
804                 sl->rcount   = 0;
805                 sl->xleft    = 0;
806
807                 set_bit(SLF_INUSE, &sl->flags);
808
809                 err = register_netdevice(sl->dev);
810                 if (err)
811                         goto err_free_chan;
812         }
813
814         /* Done.  We have linked the TTY line to a channel. */
815         rtnl_unlock();
816
817 #if LINUX_VERSION_CODE >= KERNEL_VERSION(2,6,16)
818         tty->receive_room = 65536;      /* We don't flow control */
819 #endif
820
821         return sl->dev->base_addr;
822
823 err_free_chan:
824         sl->tty = NULL;
825         tty->disc_data = NULL;
826         clear_bit(SLF_INUSE, &sl->flags);
827
828 err_exit:
829         rtnl_unlock();
830
831         /* Count references from TTY module */
832         return err;
833 }
834
835 /*
836
837   FIXME: 1,2 are fixed 3 was never true anyway.
838
839    Let me to blame a bit.
840    1. TTY module calls this funstion on soft interrupt.
841    2. TTY module calls this function WITH MASKED INTERRUPTS!
842    3. TTY module does not notify us about line discipline
843       shutdown,
844
845    Seems, now it is clean. The solution is to consider netdevice and
846    line discipline sides as two independent threads.
847
848    By-product (not desired): slc? does not feel hangups and remains open.
849    It is supposed, that user level program (dip, diald, slattach...)
850    will catch SIGHUP and make the rest of work.
851
852    I see no way to make more with current tty code. --ANK
853  */
854
855 /*
856  * Close down a SLCAN channel.
857  * This means flushing out any pending queues, and then returning. This
858  * call is serialized against other ldisc functions.
859  */
860 static void slcan_close(struct tty_struct *tty)
861 {
862         struct slcan *sl = (struct slcan *) tty->disc_data;
863
864         /* First make sure we're connected. */
865         if (!sl || sl->magic != SLCAN_MAGIC || sl->tty != tty)
866                 return;
867
868         tty->disc_data = NULL;
869         sl->tty = NULL;
870         if (!sl->leased)
871                 sl->line = 0;
872
873         /* Count references from TTY module */
874 }
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         .ioctl          = slcan_ioctl,
923         .receive_buf    = slcan_receive_buf,
924 #if LINUX_VERSION_CODE < KERNEL_VERSION(2,6,16)
925         .receive_room   = slcan_receive_room,
926 #endif
927         .write_wakeup   = slcan_write_wakeup,
928 };
929
930 /************************************
931  * general slcan module init/exit
932  ************************************/
933
934 static int __init slcan_init(void)
935 {
936         int status;
937
938         if (maxdev < 4)
939                 maxdev = 4; /* Sanity */
940
941         printk(banner);
942         printk(KERN_INFO "slcan: %d dynamic interface channels.\n", maxdev);
943
944         slcan_devs = kmalloc(sizeof(struct net_device *)*maxdev, GFP_KERNEL);
945         if (!slcan_devs) {
946                 printk(KERN_ERR "slcan: can't allocate slcan device array!\n");
947                 return -ENOMEM;
948         }
949
950         /* Clear the pointer array, we allocate devices when we need them */
951         memset(slcan_devs, 0, sizeof(struct net_device *)*maxdev);
952
953         /* Fill in our line protocol discipline, and register it */
954         status = tty_register_ldisc(N_SLCAN, &slc_ldisc);
955         if (status != 0)  {
956                 printk(KERN_ERR "slcan: can't register line discipline\n");
957                 kfree(slcan_devs);
958         }
959         return status;
960 }
961
962 static void __exit slcan_exit(void)
963 {
964         int i;
965         struct net_device *dev;
966         struct slcan *sl;
967         unsigned long timeout = jiffies + HZ;
968         int busy = 0;
969
970         if (slcan_devs == NULL)
971                 return;
972
973         /* First of all: check for active disciplines and hangup them.
974          */
975         do {
976                 if (busy)
977                         msleep_interruptible(100);
978
979                 busy = 0;
980                 for (i = 0; i < maxdev; i++) {
981                         dev = slcan_devs[i];
982                         if (!dev)
983                                 continue;
984                         sl = netdev_priv(dev);
985                         spin_lock_bh(&sl->lock);
986                         if (sl->tty) {
987                                 busy++;
988                                 tty_hangup(sl->tty);
989                         }
990                         spin_unlock_bh(&sl->lock);
991                 }
992         } while (busy && time_before(jiffies, timeout));
993
994
995         for (i = 0; i < maxdev; i++) {
996                 dev = slcan_devs[i];
997                 if (!dev)
998                         continue;
999                 slcan_devs[i] = NULL;
1000
1001                 sl = netdev_priv(dev);
1002                 if (sl->tty) {
1003                         printk(KERN_ERR "%s: tty discipline still running\n",
1004                                dev->name);
1005                         /* Intentionally leak the control block. */
1006                         dev->destructor = NULL;
1007                 }
1008
1009                 unregister_netdev(dev);
1010         }
1011
1012         kfree(slcan_devs);
1013         slcan_devs = NULL;
1014
1015         i = tty_unregister_ldisc(N_SLCAN);
1016         if (i)
1017                 printk(KERN_ERR "slcan: can't unregister ldisc (err %d)\n", i);
1018 }
1019
1020 module_init(slcan_init);
1021 module_exit(slcan_exit);