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