]> rtime.felk.cvut.cz Git - linux-lin.git/blob - sllin/sllin.c
Basic functions to synchronize Tx with LIN state automata implemented.
[linux-lin.git] / sllin / sllin.c
1 /*
2  * sllin.c - serial line LIN 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  * sllin.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/module.h>
43 #include <linux/moduleparam.h>
44
45 #include <asm/system.h>
46 #include <linux/uaccess.h>
47 #include <linux/bitops.h>
48 #include <linux/string.h>
49 #include <linux/tty.h>
50 #include <linux/errno.h>
51 #include <linux/netdevice.h>
52 #include <linux/skbuff.h>
53 #include <linux/rtnetlink.h>
54 #include <linux/if_arp.h>
55 #include <linux/if_ether.h>
56 #include <linux/sched.h>
57 #include <linux/delay.h>
58 #include <linux/init.h>
59 #include <linux/can.h>
60 #include <linux/kthread.h>
61
62 /* Should be in include/linux/tty.h */
63 #define N_SLLIN         25
64
65 static __initdata const char banner[] =
66         KERN_INFO "sllin: serial line LIN interface driver\n";
67
68 MODULE_ALIAS_LDISC(N_SLLIN);
69 MODULE_DESCRIPTION("serial line LIN interface");
70 MODULE_LICENSE("GPL");
71 MODULE_AUTHOR("Oliver Hartkopp <socketcan@hartkopp.net>");
72
73 #define SLLIN_MAGIC 0x53CA
74
75 static int maxdev = 10;         /* MAX number of SLLIN channels;
76                                    This can be overridden with
77                                    insmod sllin.ko maxdev=nnn   */
78 module_param(maxdev, int, 0);
79 MODULE_PARM_DESC(maxdev, "Maximum number of sllin interfaces");
80
81 /* maximum buffer len to store whole LIN message*/
82 #define SLLIN_DATA_MAX   8
83 #define SLLIN_BUFF_LEN  (1 /*break*/ + 1 /*sync*/ + 1 /*ID*/ + \
84                          SLLIN_DATA_MAX + 1 /*checksum*/)
85 #define SLLIN_BUFF_BREAK 0
86 #define SLLIN_BUFF_SYNC  1
87 #define SLLIN_BUFF_ID    2
88 #define SLLIN_BUFF_DATA  3
89
90 enum slstate {
91         SLSTATE_IDLE = 0,
92         SLSTATE_BREAK_SENT,
93         SLSTATE_ID_SENT,
94         SLSTATE_RESPONSE_WAIT,
95         SLSTATE_RESPONSE_SENT,
96 };
97
98 struct sllin {
99         int                     magic;
100
101         /* Various fields. */
102         struct tty_struct       *tty;           /* ptr to TTY structure      */
103         struct net_device       *dev;           /* easy for intr handling    */
104         spinlock_t              lock;
105
106         /* LIN message buffer and actual processed data counts */
107         unsigned char           rx_buff[SLLIN_BUFF_LEN]; /* LIN Rx buffer */
108         unsigned char           tx_buff[SLLIN_BUFF_LEN]; /* LIN Tx buffer */
109         int                     rx_expect;      /* expected number of Rx chars */
110         int                     rx_lim;         /* maximum Rx chars for ID  */
111         int                     rx_cnt;         /* message buffer Rx fill level  */
112         int                     tx_lim;         /* actual limit of bytes to Tx */
113         int                     tx_cnt;         /* number of already Tx bytes */
114         char                    lin_master;     /* node is a master node */
115         int                     lin_baud;       /* LIN baudrate */
116         int                     lin_state;      /* state */
117         int                     id_to_sent;     /* there is ID to be sent */
118
119         unsigned long           flags;          /* Flag values/ mode etc     */
120 #define SLF_INUSE               0               /* Channel in use            */
121 #define SLF_ERROR               1               /* Parity, etc. error        */
122 #define SLF_RXEVENT             2               /* Rx wake event             */
123 #define SLF_TXEVENT             3               /* Tx wake event             */
124 #define SLF_MSGEVENT            4               /* CAN message to sent       */
125
126         unsigned char           leased;
127         dev_t                   line;
128         struct task_struct      *kwthread;
129         wait_queue_head_t       kwt_wq;
130 };
131
132 static struct net_device **sllin_devs;
133
134 const unsigned char sllin_id_parity_table[] = {
135         0x80,0xc0,0x40,0x00,0xc0,0x80,0x00,0x40,
136         0x00,0x40,0xc0,0x80,0x40,0x00,0x80,0xc0,
137         0x40,0x00,0x80,0xc0,0x00,0x40,0xc0,0x80,
138         0xc0,0x80,0x00,0x40,0x80,0xc0,0x40,0x00,
139         0x00,0x40,0xc0,0x80,0x40,0x00,0x80,0xc0,
140         0x80,0xc0,0x40,0x00,0xc0,0x80,0x00,0x40,
141         0xc0,0x80,0x00,0x40,0x80,0xc0,0x40,0x00,
142         0x40,0x00,0x80,0xc0,0x00,0x40,0xc0,0x80
143 };
144
145 static int sltty_change_speed(struct tty_struct *tty, unsigned speed)
146 {
147         struct ktermios old_termios;
148         int cflag;
149
150         mutex_lock(&tty->termios_mutex);
151         old_termios = *(tty->termios);
152         cflag = tty->termios->c_cflag;
153         tty_encode_baud_rate(tty, speed, speed);
154         if (tty->ops->set_termios)
155                 tty->ops->set_termios(tty, &old_termios);
156         //priv->io.speed = speed;
157         mutex_unlock(&tty->termios_mutex);
158
159         return 0;
160 }
161
162
163 /* Send one completely decapsulated can_frame to the network layer */
164 static void sll_bump(struct sllin *sl)
165 {
166 //      struct sk_buff *skb;
167 //      struct can_frame cf;
168 //      int i, dlc_pos, tmp;
169 //      unsigned long ultmp;
170 //      char cmd = sl->rbuff[0];
171 //
172 //      if ((cmd != 't') && (cmd != 'T') && (cmd != 'r') && (cmd != 'R'))
173 //              return;
174 //
175 //      if (cmd & 0x20) /* tiny chars 'r' 't' => standard frame format */
176 //              dlc_pos = 4; /* dlc position tiiid */
177 //      else
178 //              dlc_pos = 9; /* dlc position Tiiiiiiiid */
179 //
180 //      if (!((sl->rbuff[dlc_pos] >= '0') && (sl->rbuff[dlc_pos] < '9')))
181 //              return;
182 //
183 //      cf.can_dlc = sl->rbuff[dlc_pos] - '0'; /* get can_dlc from ASCII val */
184 //
185 //      sl->rbuff[dlc_pos] = 0; /* terminate can_id string */
186 //
187 //      if (strict_strtoul(sl->rbuff+1, 16, &ultmp))
188 //              return;
189 //
190 //      cf.can_id = ultmp;
191 //
192 //      if (!(cmd & 0x20)) /* NO tiny chars => extended frame format */
193 //              cf.can_id |= CAN_EFF_FLAG;
194 //
195 //      if ((cmd | 0x20) == 'r') /* RTR frame */
196 //              cf.can_id |= CAN_RTR_FLAG;
197 //
198 //      *(u64 *) (&cf.data) = 0; /* clear payload */
199 //
200 //      for (i = 0, dlc_pos++; i < cf.can_dlc; i++) {
201 //
202 //              tmp = asc2nibble(sl->rbuff[dlc_pos++]);
203 //              if (tmp > 0x0F)
204 //                      return;
205 //              cf.data[i] = (tmp << 4);
206 //              tmp = asc2nibble(sl->rbuff[dlc_pos++]);
207 //              if (tmp > 0x0F)
208 //                      return;
209 //              cf.data[i] |= tmp;
210 //      }
211 //
212 //
213 //      skb = dev_alloc_skb(sizeof(struct can_frame));
214 //      if (!skb)
215 //              return;
216 //
217 //      skb->dev = sl->dev;
218 //      skb->protocol = htons(ETH_P_CAN);
219 //      skb->pkt_type = PACKET_BROADCAST;
220 //      skb->ip_summed = CHECKSUM_UNNECESSARY;
221 //      memcpy(skb_put(skb, sizeof(struct can_frame)),
222 //             &cf, sizeof(struct can_frame));
223 //      netif_rx(skb);
224 //
225 //      sl->dev->stats.rx_packets++;
226 //      sl->dev->stats.rx_bytes += cf.can_dlc;
227 }
228
229
230  /************************************************************************
231   *                     STANDARD SLLIN ENCAPSULATION                     *
232   ************************************************************************/
233
234 /* Convert particular CAN frame into LIN frame and send it to TTY queue. */
235 static void sll_encaps(struct sllin *sl, struct can_frame *cf)
236 {
237         int actual, idx, i;
238         char lframe[16] = {0x00, 0x55}; /* Fake break, Sync byte */
239         struct tty_struct *tty = sl->tty;
240
241         pr_debug("sllin: %s() invoked\n", __FUNCTION__);
242
243         /* We do care only about SFF frames */
244         if (cf->can_id & CAN_EFF_FLAG)
245                 return;
246
247         /* Send only header */
248         if (cf->can_id & CAN_RTR_FLAG) {
249                 pr_debug("sllin: %s() RTR CAN frame\n", __FUNCTION__);
250                 lframe[2] = (u8)cf->can_id; /* Get one byte LIN ID */
251
252                 sltty_change_speed(tty, sl->lin_baud / 2);
253                 tty->ops->write(tty, &lframe[0], 1);
254                 sltty_change_speed(tty, sl->lin_baud);
255                 tty->ops->write(tty, &lframe[1], 1);
256                 tty->ops->write(tty, &lframe[2], 1);
257         } else {
258                 pr_debug("sllin: %s() non-RTR CAN frame\n", __FUNCTION__);
259                 /*      idx = strlen(sl->xbuff);
260
261                         for (i = 0; i < cf->can_dlc; i++)
262                         sprintf(&sl->xbuff[idx + 2*i], "%02X", cf->data[i]);
263
264                  * Order of next two lines is *very* important.
265                  * When we are sending a little amount of data,
266                  * the transfer may be completed inside the ops->write()
267                  * routine, because it's running with interrupts enabled.
268                  * In this case we *never* got WRITE_WAKEUP event,
269                  * if we did not request it before write operation.
270                  *       14 Oct 1994  Dmitry Gorodchanin.
271
272                  set_bit(TTY_DO_WRITE_WAKEUP, &sl->tty->flags);
273                  actual = sl->tty->ops->write(sl->tty, sl->xbuff, strlen(sl->xbuff));
274                  sl->xleft = strlen(sl->xbuff) - actual;
275                  sl->xhead = sl->xbuff + actual;
276                  sl->dev->stats.tx_bytes += cf->can_dlc;
277                  */
278         }
279
280 }
281
282 /*
283  * Called by the driver when there's room for more data.  If we have
284  * more packets to send, we send them here.
285  */
286 static void sllin_write_wakeup(struct tty_struct *tty)
287 {
288         int actual;
289         int remains;
290         struct sllin *sl = (struct sllin *) tty->disc_data;
291
292         /* First make sure we're connected. */
293         if (!sl || sl->magic != SLLIN_MAGIC || !netif_running(sl->dev))
294                 return;
295
296         if (sl->lin_state != SLSTATE_BREAK_SENT)
297                 remains = sl->tx_lim - sl->tx_cnt;
298         else
299                 remains = SLLIN_BUFF_BREAK + 1 - sl->tx_cnt;
300
301         if (remains > 0) {
302                 actual = tty->ops->write(tty, sl->tx_buff + sl->tx_cnt, sl->tx_cnt - sl->tx_lim);
303                 sl->tx_cnt += actual;
304
305                 if(sl->tx_cnt < sl->tx_lim)
306                         return;
307         }
308
309         clear_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
310         set_bit(SLF_TXEVENT, &sl->flags);
311         wake_up(&sl->kwt_wq);
312
313 }
314
315 /* Send a can_frame to a TTY queue. */
316 static netdev_tx_t sll_xmit(struct sk_buff *skb, struct net_device *dev)
317 {
318         struct sllin *sl = netdev_priv(dev);
319
320         if (skb->len != sizeof(struct can_frame))
321                 goto out;
322
323         spin_lock(&sl->lock);
324         if (!netif_running(dev))  {
325                 spin_unlock(&sl->lock);
326                 printk(KERN_WARNING "%s: xmit: iface is down\n", dev->name);
327                 goto out;
328         }
329         if (sl->tty == NULL) {
330                 spin_unlock(&sl->lock);
331                 goto out;
332         }
333
334         netif_stop_queue(sl->dev);
335         sll_encaps(sl, (struct can_frame *) skb->data); /* encaps & send */
336         spin_unlock(&sl->lock);
337
338 out:
339         kfree_skb(skb);
340         return NETDEV_TX_OK;
341 }
342
343
344 /******************************************
345  *   Routines looking at netdevice side.
346  ******************************************/
347
348 /* Netdevice UP -> DOWN routine */
349 static int sll_close(struct net_device *dev)
350 {
351         struct sllin *sl = netdev_priv(dev);
352
353         spin_lock_bh(&sl->lock);
354         if (sl->tty) {
355                 /* TTY discipline is running. */
356                 clear_bit(TTY_DO_WRITE_WAKEUP, &sl->tty->flags);
357         }
358         netif_stop_queue(dev);
359         sl->rx_expect = 0;
360         sl->tx_lim    = 0;
361         spin_unlock_bh(&sl->lock);
362
363         return 0;
364 }
365
366 /* Netdevice DOWN -> UP routine */
367 static int sll_open(struct net_device *dev)
368 {
369         struct sllin *sl = netdev_priv(dev);
370
371         pr_debug("sllin: %s() invoked\n", __FUNCTION__);
372
373         if (sl->tty == NULL)
374                 return -ENODEV;
375
376         sl->flags &= (1 << SLF_INUSE);
377         netif_start_queue(dev);
378         return 0;
379 }
380
381 /* Hook the destructor so we can free sllin devs at the right point in time */
382 static void sll_free_netdev(struct net_device *dev)
383 {
384         int i = dev->base_addr;
385         free_netdev(dev);
386         sllin_devs[i] = NULL;
387 }
388
389 static const struct net_device_ops sll_netdev_ops = {
390         .ndo_open               = sll_open,
391         .ndo_stop               = sll_close,
392         .ndo_start_xmit         = sll_xmit,
393 };
394
395 static void sll_setup(struct net_device *dev)
396 {
397         dev->netdev_ops         = &sll_netdev_ops;
398         dev->destructor         = sll_free_netdev;
399
400         dev->hard_header_len    = 0;
401         dev->addr_len           = 0;
402         dev->tx_queue_len       = 10;
403
404         dev->mtu                = sizeof(struct can_frame);
405         dev->type               = ARPHRD_CAN;
406
407         /* New-style flags. */
408         dev->flags              = IFF_NOARP;
409         dev->features           = NETIF_F_NO_CSUM;
410 }
411
412 /******************************************
413   Routines looking at TTY side.
414  ******************************************/
415
416 /*
417  * Handle the 'receiver data ready' interrupt.
418  * This function is called by the 'tty_io' module in the kernel when
419  * a block of SLLIN data has been received, which can now be decapsulated
420  * and sent on to some IP layer for further processing. This will not
421  * be re-entered while running but other ldisc functions may be called
422  * in parallel
423  */
424
425 static void sllin_receive_buf(struct tty_struct *tty,
426                               const unsigned char *cp, char *fp, int count)
427 {
428         struct sllin *sl = (struct sllin *) tty->disc_data;
429
430         if (!sl || sl->magic != SLLIN_MAGIC || !netif_running(sl->dev))
431                 return;
432
433         /* Read the characters out of the buffer */
434         while (count--) {
435                 if (fp && *fp++) {
436                         if (!test_and_set_bit(SLF_ERROR, &sl->flags))
437                                 sl->dev->stats.rx_errors++;
438                         cp++;
439                         continue;
440                 }
441
442                 if (sl->rx_cnt < SLLIN_BUFF_LEN)  {
443                         sl->rx_buff[sl->rx_cnt++] = *cp++;
444                 }
445         }
446
447         if(sl->rx_cnt >= sl->rx_expect) {
448                 set_bit(SLF_RXEVENT, &sl->flags);
449                 wake_up(&sl->kwt_wq);
450         }
451 }
452
453 /*****************************************
454  *  sllin message helper routines
455  *****************************************/
456
457 int sllin_setup_msg(struct sllin *sl, int mode, int id,
458                 unsigned char *data, int len)
459 {
460         if (id > 0x3f)
461                 return -1;
462
463         sl->rx_cnt = 0;
464         sl->tx_cnt = 0;
465         sl->rx_expect = 0;
466
467         sl->tx_buff[SLLIN_BUFF_BREAK] = 0;
468         sl->tx_buff[SLLIN_BUFF_SYNC]  = 0x55;
469         sl->tx_buff[SLLIN_BUFF_ID]    = id | sllin_id_parity_table[id];
470         sl->tx_lim = SLLIN_BUFF_DATA;
471
472         if ((data != NULL) && len) {
473                 sl->tx_lim += len;
474                 memcpy(sl->tx_buff + SLLIN_BUFF_DATA, data, len);
475         }
476         sl->rx_lim += len;
477
478         return 0;
479 }
480
481
482 int sllin_send_tx_buff(struct sllin *sl)
483 {
484         struct tty_struct *tty = sl->tty;
485         int remains;
486         int res;
487
488         if (sl->lin_state != SLSTATE_BREAK_SENT)
489                 remains = sl->tx_lim - sl->tx_cnt;
490         else
491                 remains = 1;
492
493
494         res = tty->ops->write(tty, sl->tx_buff + sl->tx_cnt, remains);
495         if (res < 0)
496                 return -1;
497
498         remains -= res;
499         sl->tx_cnt += res;
500
501         if (remains > 0) {
502                 set_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
503                 res = tty->ops->write(tty, sl->tx_buff + sl->tx_cnt, remains);
504                 if (res < 0) {
505                         clear_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
506                         return -1;
507                 }
508         }
509         sl->tx_cnt += res;
510
511         return 0;
512 }
513
514 int sllin_send_break(struct sllin *sl)
515 {
516         struct tty_struct *tty = sl->tty;
517         unsigned long break_baud = sl->lin_baud;
518         int res;
519
520         break_baud = (break_baud * 8) / 14;
521
522         sltty_change_speed(tty, break_baud);
523
524         sl->rx_expect = SLLIN_BUFF_BREAK + 1;
525
526         sl->lin_state = SLSTATE_BREAK_SENT;
527
528         res = sllin_send_tx_buff(sl);
529         if (res < 0) {
530                 sl->lin_state = SLSTATE_IDLE;
531                 return res;
532         }
533
534         return 0;
535 }
536
537 /*****************************************
538  *  sllin_kwthread - kernel worker thread
539  *****************************************/
540
541 int sllin_kwthread(void *ptr)
542 {
543         struct sllin *sl = (struct sllin *)ptr;
544         struct tty_struct *tty = sl->tty;
545         int res;
546
547         printk(KERN_INFO "sllin: sllin_kwthread started.\n");
548
549         clear_bit(SLF_ERROR, &sl->flags);
550
551         sltty_change_speed(tty, sl->lin_baud);
552
553         sllin_setup_msg(sl, 0, 0x33, NULL, 0);
554
555         while (!kthread_should_stop()) {
556
557                 if ((sl->lin_state == SLSTATE_IDLE) && sl->lin_master &&
558                         sl->id_to_sent) {
559                         if(sllin_send_break(sl)<0) {
560                                 /* error processing */
561                         }
562
563                 }
564
565                 wait_event_killable(sl->kwt_wq, kthread_should_stop() ||
566                         test_bit(SLF_RXEVENT, &sl->flags) ||
567                         test_bit(SLF_TXEVENT, &sl->flags));
568
569                 if (test_and_clear_bit(SLF_RXEVENT, &sl->flags)) {
570
571                 }
572
573                 if (test_and_clear_bit(SLF_TXEVENT, &sl->flags)) {
574
575                 }
576
577                 switch (sl->lin_state) {
578                         case SLSTATE_BREAK_SENT:
579                                 if (sl->rx_cnt <= SLLIN_BUFF_BREAK)
580                                         continue;
581
582                                 res = sltty_change_speed(tty, sl->lin_baud);
583
584                                 sllin_send_tx_buff(sl);
585
586                                 sl->lin_state = SLSTATE_ID_SENT;
587
588                                 break;
589                 }
590
591
592
593                 /* sll_bump(sl); send packet to the network layer */
594
595                 /* sl->dev->stats.tx_packets++; send frames statistic */
596                 /* netif_wake_queue(sl->dev); allow next Tx packet arrival */
597         }
598
599
600         printk(KERN_INFO "sllin: sllin_kwthread stopped.\n");
601
602         return 0;
603 }
604
605
606 /************************************
607  *  sllin_open helper routines.
608  ************************************/
609
610 /* Collect hanged up channels */
611 static void sll_sync(void)
612 {
613         int i;
614         struct net_device *dev;
615         struct sllin      *sl;
616
617         for (i = 0; i < maxdev; i++) {
618                 dev = sllin_devs[i];
619                 if (dev == NULL)
620                         break;
621
622                 sl = netdev_priv(dev);
623                 if (sl->tty || sl->leased)
624                         continue;
625                 if (dev->flags & IFF_UP)
626                         dev_close(dev);
627         }
628 }
629
630 /* Find a free SLLIN channel, and link in this `tty' line. */
631 static struct sllin *sll_alloc(dev_t line)
632 {
633         int i;
634         struct net_device *dev = NULL;
635         struct sllin       *sl;
636
637         if (sllin_devs == NULL)
638                 return NULL;    /* Master array missing ! */
639
640         for (i = 0; i < maxdev; i++) {
641                 dev = sllin_devs[i];
642                 if (dev == NULL)
643                         break;
644
645         }
646
647         /* Sorry, too many, all slots in use */
648         if (i >= maxdev)
649                 return NULL;
650
651         if (dev) {
652                 sl = netdev_priv(dev);
653                 if (test_bit(SLF_INUSE, &sl->flags)) {
654                         unregister_netdevice(dev);
655                         dev = NULL;
656                         sllin_devs[i] = NULL;
657                 }
658         }
659
660         if (!dev) {
661                 char name[IFNAMSIZ];
662                 sprintf(name, "sllin%d", i);
663
664                 dev = alloc_netdev(sizeof(*sl), name, sll_setup);
665                 if (!dev)
666                         return NULL;
667                 dev->base_addr  = i;
668         }
669
670         sl = netdev_priv(dev);
671
672         /* Initialize channel control data */
673         sl->magic = SLLIN_MAGIC;
674         sl->dev = dev;
675         spin_lock_init(&sl->lock);
676         sllin_devs[i] = dev;
677
678         return sl;
679 }
680
681 /*
682  * Open the high-level part of the SLLIN channel.
683  * This function is called by the TTY module when the
684  * SLLIN line discipline is called for.  Because we are
685  * sure the tty line exists, we only have to link it to
686  * a free SLLIN channel...
687  *
688  * Called in process context serialized from other ldisc calls.
689  */
690
691 static int sllin_open(struct tty_struct *tty)
692 {
693         struct sllin *sl;
694         int err;
695         pr_debug("sllin: %s() invoked\n", __FUNCTION__);
696
697         if (!capable(CAP_NET_ADMIN))
698                 return -EPERM;
699
700         if (tty->ops->write == NULL)
701                 return -EOPNOTSUPP;
702
703         /* RTnetlink lock is misused here to serialize concurrent
704            opens of sllin channels. There are better ways, but it is
705            the simplest one.
706          */
707         rtnl_lock();
708
709         /* Collect hanged up channels. */
710         sll_sync();
711
712         sl = tty->disc_data;
713
714         err = -EEXIST;
715         /* First make sure we're not already connected. */
716         if (sl && sl->magic == SLLIN_MAGIC)
717                 goto err_exit;
718
719         /* OK.  Find a free SLLIN channel to use. */
720         err = -ENFILE;
721         sl = sll_alloc(tty_devnum(tty));
722         if (sl == NULL)
723                 goto err_exit;
724
725         sl->tty = tty;
726         tty->disc_data = sl;
727         sl->line = tty_devnum(tty);
728
729         if (!test_bit(SLF_INUSE, &sl->flags)) {
730                 /* Perform the low-level SLLIN initialization. */
731                 sl->rx_cnt    = 0;
732                 sl->rx_expect = 0;
733                 sl->tx_cnt    = 0;
734                 sl->tx_lim    = 0;
735
736                 sl->lin_baud  = 2400;
737
738                 sl->lin_master = 1;
739                 sl->lin_state = SLSTATE_IDLE;
740
741                 set_bit(SLF_INUSE, &sl->flags);
742
743                 init_waitqueue_head(&sl->kwt_wq);
744                 sl->kwthread = kthread_run(sllin_kwthread, sl, "sllin");
745                 if (sl->kwthread == NULL)
746                         goto err_free_chan;
747
748                 err = register_netdevice(sl->dev);
749                 if (err)
750                         goto err_free_chan_and_thread;
751         }
752
753         /* Done.  We have linked the TTY line to a channel. */
754         rtnl_unlock();
755         tty->receive_room = SLLIN_BUFF_LEN * 40;        /* We don't flow control */
756
757         /* TTY layer expects 0 on success */
758         return 0;
759
760 err_free_chan_and_thread:
761         kthread_stop(sl->kwthread);
762         sl->kwthread = NULL;
763
764 err_free_chan:
765         sl->tty = NULL;
766         tty->disc_data = NULL;
767         clear_bit(SLF_INUSE, &sl->flags);
768
769 err_exit:
770         rtnl_unlock();
771
772         /* Count references from TTY module */
773         return err;
774 }
775
776 /*
777  * Close down a SLLIN channel.
778  * This means flushing out any pending queues, and then returning. This
779  * call is serialized against other ldisc functions.
780  *
781  * We also use this method for a hangup event.
782  */
783
784 static void sllin_close(struct tty_struct *tty)
785 {
786         struct sllin *sl = (struct sllin *) tty->disc_data;
787
788         /* First make sure we're connected. */
789         if (!sl || sl->magic != SLLIN_MAGIC || sl->tty != tty)
790                 return;
791
792         kthread_stop(sl->kwthread);
793         sl->kwthread = NULL;
794
795         tty->disc_data = NULL;
796         sl->tty = NULL;
797         if (!sl->leased)
798                 sl->line = 0;
799
800         /* Flush network side */
801         unregister_netdev(sl->dev);
802         /* This will complete via sl_free_netdev */
803 }
804
805 static int sllin_hangup(struct tty_struct *tty)
806 {
807         sllin_close(tty);
808         return 0;
809 }
810
811 /* Perform I/O control on an active SLLIN channel. */
812 static int sllin_ioctl(struct tty_struct *tty, struct file *file,
813                        unsigned int cmd, unsigned long arg)
814 {
815         struct sllin *sl = (struct sllin *) tty->disc_data;
816         unsigned int tmp;
817
818         /* First make sure we're connected. */
819         if (!sl || sl->magic != SLLIN_MAGIC)
820                 return -EINVAL;
821
822         switch (cmd) {
823         case SIOCGIFNAME:
824                 tmp = strlen(sl->dev->name) + 1;
825                 if (copy_to_user((void __user *)arg, sl->dev->name, tmp))
826                         return -EFAULT;
827                 return 0;
828
829         case SIOCSIFHWADDR:
830                 return -EINVAL;
831
832         default:
833                 return tty_mode_ioctl(tty, file, cmd, arg);
834         }
835 }
836
837 static struct tty_ldisc_ops sll_ldisc = {
838         .owner          = THIS_MODULE,
839         .magic          = TTY_LDISC_MAGIC,
840         .name           = "sllin",
841         .open           = sllin_open,
842         .close          = sllin_close,
843         .hangup         = sllin_hangup,
844         .ioctl          = sllin_ioctl,
845         .receive_buf    = sllin_receive_buf,
846         .write_wakeup   = sllin_write_wakeup,
847 };
848
849 static int __init sllin_init(void)
850 {
851         int status;
852
853         if (maxdev < 4)
854                 maxdev = 4; /* Sanity */
855
856         printk(banner);
857         printk(KERN_INFO "sllin: %d dynamic interface channels.\n", maxdev);
858
859         sllin_devs = kzalloc(sizeof(struct net_device *)*maxdev, GFP_KERNEL);
860         if (!sllin_devs) {
861                 printk(KERN_ERR "sllin: can't allocate sllin device array!\n");
862                 return -ENOMEM;
863         }
864
865         /* Fill in our line protocol discipline, and register it */
866         status = tty_register_ldisc(N_SLLIN, &sll_ldisc);
867         if (status)  {
868                 printk(KERN_ERR "sllin: can't register line discipline\n");
869                 kfree(sllin_devs);
870         }
871         return status;
872 }
873
874 static void __exit sllin_exit(void)
875 {
876         int i;
877         struct net_device *dev;
878         struct sllin *sl;
879         unsigned long timeout = jiffies + HZ;
880         int busy = 0;
881
882         if (sllin_devs == NULL)
883                 return;
884
885         /* First of all: check for active disciplines and hangup them.
886          */
887         do {
888                 if (busy)
889                         msleep_interruptible(100);
890
891                 busy = 0;
892                 for (i = 0; i < maxdev; i++) {
893                         dev = sllin_devs[i];
894                         if (!dev)
895                                 continue;
896                         sl = netdev_priv(dev);
897                         spin_lock_bh(&sl->lock);
898                         if (sl->tty) {
899                                 busy++;
900                                 tty_hangup(sl->tty);
901                         }
902                         spin_unlock_bh(&sl->lock);
903                 }
904         } while (busy && time_before(jiffies, timeout));
905
906         /* FIXME: hangup is async so we should wait when doing this second
907            phase */
908
909         for (i = 0; i < maxdev; i++) {
910                 dev = sllin_devs[i];
911                 if (!dev)
912                         continue;
913                 sllin_devs[i] = NULL;
914
915                 sl = netdev_priv(dev);
916                 if (sl->tty) {
917                         printk(KERN_ERR "%s: tty discipline still running\n",
918                                dev->name);
919                         /* Intentionally leak the control block. */
920                         dev->destructor = NULL;
921                 }
922
923                 unregister_netdev(dev);
924         }
925
926         kfree(sllin_devs);
927         sllin_devs = NULL;
928
929         i = tty_unregister_ldisc(N_SLLIN);
930         if (i)
931                 printk(KERN_ERR "sllin: can't unregister ldisc (err %d)\n", i);
932 }
933
934 module_init(sllin_init);
935 module_exit(sllin_exit);