]> rtime.felk.cvut.cz Git - linux-lin.git/blob - sllin/sllin.c
Update response checksum calculation for kernel code too.
[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_send;     /* 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                         printk(KERN_INFO "sllin_write_wakeup sent %d, remains %d, waiting\n",
307                                 sl->tx_cnt, sl->tx_lim - sl->tx_cnt);
308                         return;
309                 }
310         }
311
312         clear_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
313         set_bit(SLF_TXEVENT, &sl->flags);
314         wake_up(&sl->kwt_wq);
315
316         printk(KERN_INFO "sllin_write_wakeup sent %d, wakeup\n", sl->tx_cnt);
317 }
318
319 /* Send a can_frame to a TTY queue. */
320 static netdev_tx_t sll_xmit(struct sk_buff *skb, struct net_device *dev)
321 {
322         struct sllin *sl = netdev_priv(dev);
323
324         if (skb->len != sizeof(struct can_frame))
325                 goto out;
326
327         spin_lock(&sl->lock);
328         if (!netif_running(dev))  {
329                 spin_unlock(&sl->lock);
330                 printk(KERN_WARNING "%s: xmit: iface is down\n", dev->name);
331                 goto out;
332         }
333         if (sl->tty == NULL) {
334                 spin_unlock(&sl->lock);
335                 goto out;
336         }
337
338         netif_stop_queue(sl->dev);
339         sll_encaps(sl, (struct can_frame *) skb->data); /* encaps & send */
340         spin_unlock(&sl->lock);
341
342 out:
343         kfree_skb(skb);
344         return NETDEV_TX_OK;
345 }
346
347
348 /******************************************
349  *   Routines looking at netdevice side.
350  ******************************************/
351
352 /* Netdevice UP -> DOWN routine */
353 static int sll_close(struct net_device *dev)
354 {
355         struct sllin *sl = netdev_priv(dev);
356
357         spin_lock_bh(&sl->lock);
358         if (sl->tty) {
359                 /* TTY discipline is running. */
360                 clear_bit(TTY_DO_WRITE_WAKEUP, &sl->tty->flags);
361         }
362         netif_stop_queue(dev);
363         sl->rx_expect = 0;
364         sl->tx_lim    = 0;
365         spin_unlock_bh(&sl->lock);
366
367         return 0;
368 }
369
370 /* Netdevice DOWN -> UP routine */
371 static int sll_open(struct net_device *dev)
372 {
373         struct sllin *sl = netdev_priv(dev);
374
375         pr_debug("sllin: %s() invoked\n", __FUNCTION__);
376
377         if (sl->tty == NULL)
378                 return -ENODEV;
379
380         sl->flags &= (1 << SLF_INUSE);
381         netif_start_queue(dev);
382         return 0;
383 }
384
385 /* Hook the destructor so we can free sllin devs at the right point in time */
386 static void sll_free_netdev(struct net_device *dev)
387 {
388         int i = dev->base_addr;
389         free_netdev(dev);
390         sllin_devs[i] = NULL;
391 }
392
393 static const struct net_device_ops sll_netdev_ops = {
394         .ndo_open               = sll_open,
395         .ndo_stop               = sll_close,
396         .ndo_start_xmit         = sll_xmit,
397 };
398
399 static void sll_setup(struct net_device *dev)
400 {
401         dev->netdev_ops         = &sll_netdev_ops;
402         dev->destructor         = sll_free_netdev;
403
404         dev->hard_header_len    = 0;
405         dev->addr_len           = 0;
406         dev->tx_queue_len       = 10;
407
408         dev->mtu                = sizeof(struct can_frame);
409         dev->type               = ARPHRD_CAN;
410
411         /* New-style flags. */
412         dev->flags              = IFF_NOARP;
413         dev->features           = NETIF_F_NO_CSUM;
414 }
415
416 /******************************************
417   Routines looking at TTY side.
418  ******************************************/
419
420 /*
421  * Handle the 'receiver data ready' interrupt.
422  * This function is called by the 'tty_io' module in the kernel when
423  * a block of SLLIN data has been received, which can now be decapsulated
424  * and sent on to some IP layer for further processing. This will not
425  * be re-entered while running but other ldisc functions may be called
426  * in parallel
427  */
428
429 static void sllin_receive_buf(struct tty_struct *tty,
430                               const unsigned char *cp, char *fp, int count)
431 {
432         struct sllin *sl = (struct sllin *) tty->disc_data;
433
434         printk(KERN_INFO "sllin_receive_buf invoked\n");
435
436         if (!sl || sl->magic != SLLIN_MAGIC || !netif_running(sl->dev))
437                 return;
438
439         /* Read the characters out of the buffer */
440         while (count--) {
441                 if (fp && *fp++) {
442                         if (!test_and_set_bit(SLF_ERROR, &sl->flags))
443                                 sl->dev->stats.rx_errors++;
444                         cp++;
445                         continue;
446                 }
447
448                 if (sl->rx_cnt < SLLIN_BUFF_LEN)  {
449                         sl->rx_buff[sl->rx_cnt++] = *cp++;
450                 }
451         }
452
453         if(sl->rx_cnt >= sl->rx_expect) {
454                 set_bit(SLF_RXEVENT, &sl->flags);
455                 wake_up(&sl->kwt_wq);
456                 printk(KERN_INFO "sllin_receive_buf count %d, wakeup\n", sl->rx_cnt);
457         } else {
458                 printk(KERN_INFO "sllin_receive_buf count %d, waiting\n", sl->rx_cnt);
459         }
460 }
461
462 /*****************************************
463  *  sllin message helper routines
464  *****************************************/
465
466 int sllin_setup_msg(struct sllin *sl, int mode, int id,
467                 unsigned char *data, int len)
468 {
469         if (id > 0x3f)
470                 return -1;
471
472         sl->rx_cnt = 0;
473         sl->tx_cnt = 0;
474         sl->rx_expect = 0;
475
476         sl->tx_buff[SLLIN_BUFF_BREAK] = 0;
477         sl->tx_buff[SLLIN_BUFF_SYNC]  = 0x55;
478         sl->tx_buff[SLLIN_BUFF_ID]    = id | sllin_id_parity_table[id];
479         sl->tx_lim = SLLIN_BUFF_DATA;
480
481         if ((data != NULL) && len) {
482                 int i;
483                 unsigned csum  = 0;
484
485                 sl->tx_lim += len;
486                 memcpy(sl->tx_buff + SLLIN_BUFF_DATA, data, len);
487                 /* compute data parity there */
488                 for (i = SLLIN_BUFF_DATA; i < sl->tx_lim; i++) {
489                         csum += sl->tx_buff[i];
490                         if (csum > 255)
491                                 csum -= 255;
492                 }
493
494                 sl->tx_buff[sl->tx_lim++] = csum;
495         }
496         if (len != 0)
497                 sl->rx_lim += len + 1;
498
499         return 0;
500 }
501
502
503 int sllin_send_tx_buff(struct sllin *sl)
504 {
505         struct tty_struct *tty = sl->tty;
506         int remains;
507         int res;
508
509         if (sl->lin_state != SLSTATE_BREAK_SENT)
510                 remains = sl->tx_lim - sl->tx_cnt;
511         else
512                 remains = 1;
513
514
515         res = tty->ops->write(tty, sl->tx_buff + sl->tx_cnt, remains);
516         if (res < 0)
517                 return -1;
518
519         remains -= res;
520         sl->tx_cnt += res;
521
522         if (remains > 0) {
523                 set_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
524                 res = tty->ops->write(tty, sl->tx_buff + sl->tx_cnt, remains);
525                 if (res < 0) {
526                         clear_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
527                         return -1;
528                 }
529                 
530                 remains -= res;
531                 sl->tx_cnt += res;
532         }
533
534         printk(KERN_INFO "sllin_send_tx_buff sent %d, remains %d\n",
535                         sl->tx_cnt, remains);
536
537         return 0;
538 }
539
540 int sllin_send_break(struct sllin *sl)
541 {
542         struct tty_struct *tty = sl->tty;
543         unsigned long break_baud = sl->lin_baud;
544         int res;
545
546         //break_baud = (break_baud * 8) / 14;
547         break_baud /= 2;
548
549         sltty_change_speed(tty, break_baud);
550
551         sl->rx_expect = SLLIN_BUFF_BREAK + 1;
552
553         sl->lin_state = SLSTATE_BREAK_SENT;
554
555         res = sllin_send_tx_buff(sl);
556         if (res < 0) {
557                 sl->lin_state = SLSTATE_IDLE;
558                 return res;
559         }
560
561         return 0;
562 }
563
564 /*****************************************
565  *  sllin_kwthread - kernel worker thread
566  *****************************************/
567
568 int sllin_kwthread(void *ptr)
569 {
570         struct sllin *sl = (struct sllin *)ptr;
571         struct tty_struct *tty = sl->tty;
572         int res;
573
574         printk(KERN_INFO "sllin: sllin_kwthread started.\n");
575
576         clear_bit(SLF_ERROR, &sl->flags);
577
578         sltty_change_speed(tty, sl->lin_baud);
579
580         sllin_setup_msg(sl, 0, 0x33, NULL, 0);
581         sl->id_to_send = 1;
582
583         while (!kthread_should_stop()) {
584
585                 if ((sl->lin_state == SLSTATE_IDLE) && sl->lin_master &&
586                         sl->id_to_send) {
587                         if(sllin_send_break(sl)<0) {
588                                 /* error processing */
589                         }
590
591                 }
592
593                 wait_event_killable(sl->kwt_wq, kthread_should_stop() ||
594                         test_bit(SLF_RXEVENT, &sl->flags) ||
595                         test_bit(SLF_TXEVENT, &sl->flags));
596
597                 if (test_and_clear_bit(SLF_RXEVENT, &sl->flags)) {
598                         printk(KERN_INFO "sllin_kthread RXEVENT \n");
599                 }
600
601                 if (test_and_clear_bit(SLF_TXEVENT, &sl->flags)) {
602                         printk(KERN_INFO "sllin_kthread TXEVENT \n");
603                 }
604
605                 switch (sl->lin_state) {
606                         case SLSTATE_BREAK_SENT:
607                                 if (sl->rx_cnt <= SLLIN_BUFF_BREAK)
608                                         continue;
609
610                                 res = sltty_change_speed(tty, sl->lin_baud);
611
612                                 sllin_send_tx_buff(sl);
613
614                                 sl->lin_state = SLSTATE_ID_SENT;
615
616                                 break;
617                         case SLSTATE_ID_SENT:
618                                 sl->id_to_send = 0;
619                                 sl->lin_state = SLSTATE_IDLE;
620                                 break;
621                 }
622
623
624
625                 /* sll_bump(sl); send packet to the network layer */
626
627                 /* sl->dev->stats.tx_packets++; send frames statistic */
628                 /* netif_wake_queue(sl->dev); allow next Tx packet arrival */
629         }
630
631
632         printk(KERN_INFO "sllin: sllin_kwthread stopped.\n");
633
634         return 0;
635 }
636
637
638 /************************************
639  *  sllin_open helper routines.
640  ************************************/
641
642 /* Collect hanged up channels */
643 static void sll_sync(void)
644 {
645         int i;
646         struct net_device *dev;
647         struct sllin      *sl;
648
649         for (i = 0; i < maxdev; i++) {
650                 dev = sllin_devs[i];
651                 if (dev == NULL)
652                         break;
653
654                 sl = netdev_priv(dev);
655                 if (sl->tty || sl->leased)
656                         continue;
657                 if (dev->flags & IFF_UP)
658                         dev_close(dev);
659         }
660 }
661
662 /* Find a free SLLIN channel, and link in this `tty' line. */
663 static struct sllin *sll_alloc(dev_t line)
664 {
665         int i;
666         struct net_device *dev = NULL;
667         struct sllin       *sl;
668
669         if (sllin_devs == NULL)
670                 return NULL;    /* Master array missing ! */
671
672         for (i = 0; i < maxdev; i++) {
673                 dev = sllin_devs[i];
674                 if (dev == NULL)
675                         break;
676
677         }
678
679         /* Sorry, too many, all slots in use */
680         if (i >= maxdev)
681                 return NULL;
682
683         if (dev) {
684                 sl = netdev_priv(dev);
685                 if (test_bit(SLF_INUSE, &sl->flags)) {
686                         unregister_netdevice(dev);
687                         dev = NULL;
688                         sllin_devs[i] = NULL;
689                 }
690         }
691
692         if (!dev) {
693                 char name[IFNAMSIZ];
694                 sprintf(name, "sllin%d", i);
695
696                 dev = alloc_netdev(sizeof(*sl), name, sll_setup);
697                 if (!dev)
698                         return NULL;
699                 dev->base_addr  = i;
700         }
701
702         sl = netdev_priv(dev);
703
704         /* Initialize channel control data */
705         sl->magic = SLLIN_MAGIC;
706         sl->dev = dev;
707         spin_lock_init(&sl->lock);
708         sllin_devs[i] = dev;
709
710         return sl;
711 }
712
713 /*
714  * Open the high-level part of the SLLIN channel.
715  * This function is called by the TTY module when the
716  * SLLIN line discipline is called for.  Because we are
717  * sure the tty line exists, we only have to link it to
718  * a free SLLIN channel...
719  *
720  * Called in process context serialized from other ldisc calls.
721  */
722
723 static int sllin_open(struct tty_struct *tty)
724 {
725         struct sllin *sl;
726         int err;
727         pr_debug("sllin: %s() invoked\n", __FUNCTION__);
728
729         if (!capable(CAP_NET_ADMIN))
730                 return -EPERM;
731
732         if (tty->ops->write == NULL)
733                 return -EOPNOTSUPP;
734
735         /* RTnetlink lock is misused here to serialize concurrent
736            opens of sllin channels. There are better ways, but it is
737            the simplest one.
738          */
739         rtnl_lock();
740
741         /* Collect hanged up channels. */
742         sll_sync();
743
744         sl = tty->disc_data;
745
746         err = -EEXIST;
747         /* First make sure we're not already connected. */
748         if (sl && sl->magic == SLLIN_MAGIC)
749                 goto err_exit;
750
751         /* OK.  Find a free SLLIN channel to use. */
752         err = -ENFILE;
753         sl = sll_alloc(tty_devnum(tty));
754         if (sl == NULL)
755                 goto err_exit;
756
757         sl->tty = tty;
758         tty->disc_data = sl;
759         sl->line = tty_devnum(tty);
760
761         if (!test_bit(SLF_INUSE, &sl->flags)) {
762                 /* Perform the low-level SLLIN initialization. */
763                 sl->rx_cnt    = 0;
764                 sl->rx_expect = 0;
765                 sl->tx_cnt    = 0;
766                 sl->tx_lim    = 0;
767
768                 sl->lin_baud  = 2400;
769
770                 sl->lin_master = 1;
771                 sl->lin_state = SLSTATE_IDLE;
772
773                 set_bit(SLF_INUSE, &sl->flags);
774
775                 init_waitqueue_head(&sl->kwt_wq);
776                 sl->kwthread = kthread_run(sllin_kwthread, sl, "sllin");
777                 if (sl->kwthread == NULL)
778                         goto err_free_chan;
779
780                 err = register_netdevice(sl->dev);
781                 if (err)
782                         goto err_free_chan_and_thread;
783         }
784
785         /* Done.  We have linked the TTY line to a channel. */
786         rtnl_unlock();
787         tty->receive_room = SLLIN_BUFF_LEN * 40;        /* We don't flow control */
788
789         /* TTY layer expects 0 on success */
790         return 0;
791
792 err_free_chan_and_thread:
793         kthread_stop(sl->kwthread);
794         sl->kwthread = NULL;
795
796 err_free_chan:
797         sl->tty = NULL;
798         tty->disc_data = NULL;
799         clear_bit(SLF_INUSE, &sl->flags);
800
801 err_exit:
802         rtnl_unlock();
803
804         /* Count references from TTY module */
805         return err;
806 }
807
808 /*
809  * Close down a SLLIN channel.
810  * This means flushing out any pending queues, and then returning. This
811  * call is serialized against other ldisc functions.
812  *
813  * We also use this method for a hangup event.
814  */
815
816 static void sllin_close(struct tty_struct *tty)
817 {
818         struct sllin *sl = (struct sllin *) tty->disc_data;
819
820         /* First make sure we're connected. */
821         if (!sl || sl->magic != SLLIN_MAGIC || sl->tty != tty)
822                 return;
823
824         kthread_stop(sl->kwthread);
825         sl->kwthread = NULL;
826
827         tty->disc_data = NULL;
828         sl->tty = NULL;
829         if (!sl->leased)
830                 sl->line = 0;
831
832         /* Flush network side */
833         unregister_netdev(sl->dev);
834         /* This will complete via sl_free_netdev */
835 }
836
837 static int sllin_hangup(struct tty_struct *tty)
838 {
839         sllin_close(tty);
840         return 0;
841 }
842
843 /* Perform I/O control on an active SLLIN channel. */
844 static int sllin_ioctl(struct tty_struct *tty, struct file *file,
845                        unsigned int cmd, unsigned long arg)
846 {
847         struct sllin *sl = (struct sllin *) tty->disc_data;
848         unsigned int tmp;
849
850         /* First make sure we're connected. */
851         if (!sl || sl->magic != SLLIN_MAGIC)
852                 return -EINVAL;
853
854         switch (cmd) {
855         case SIOCGIFNAME:
856                 tmp = strlen(sl->dev->name) + 1;
857                 if (copy_to_user((void __user *)arg, sl->dev->name, tmp))
858                         return -EFAULT;
859                 return 0;
860
861         case SIOCSIFHWADDR:
862                 return -EINVAL;
863
864         default:
865                 return tty_mode_ioctl(tty, file, cmd, arg);
866         }
867 }
868
869 static struct tty_ldisc_ops sll_ldisc = {
870         .owner          = THIS_MODULE,
871         .magic          = TTY_LDISC_MAGIC,
872         .name           = "sllin",
873         .open           = sllin_open,
874         .close          = sllin_close,
875         .hangup         = sllin_hangup,
876         .ioctl          = sllin_ioctl,
877         .receive_buf    = sllin_receive_buf,
878         .write_wakeup   = sllin_write_wakeup,
879 };
880
881 static int __init sllin_init(void)
882 {
883         int status;
884
885         if (maxdev < 4)
886                 maxdev = 4; /* Sanity */
887
888         printk(banner);
889         printk(KERN_INFO "sllin: %d dynamic interface channels.\n", maxdev);
890
891         sllin_devs = kzalloc(sizeof(struct net_device *)*maxdev, GFP_KERNEL);
892         if (!sllin_devs) {
893                 printk(KERN_ERR "sllin: can't allocate sllin device array!\n");
894                 return -ENOMEM;
895         }
896
897         /* Fill in our line protocol discipline, and register it */
898         status = tty_register_ldisc(N_SLLIN, &sll_ldisc);
899         if (status)  {
900                 printk(KERN_ERR "sllin: can't register line discipline\n");
901                 kfree(sllin_devs);
902         }
903         return status;
904 }
905
906 static void __exit sllin_exit(void)
907 {
908         int i;
909         struct net_device *dev;
910         struct sllin *sl;
911         unsigned long timeout = jiffies + HZ;
912         int busy = 0;
913
914         if (sllin_devs == NULL)
915                 return;
916
917         /* First of all: check for active disciplines and hangup them.
918          */
919         do {
920                 if (busy)
921                         msleep_interruptible(100);
922
923                 busy = 0;
924                 for (i = 0; i < maxdev; i++) {
925                         dev = sllin_devs[i];
926                         if (!dev)
927                                 continue;
928                         sl = netdev_priv(dev);
929                         spin_lock_bh(&sl->lock);
930                         if (sl->tty) {
931                                 busy++;
932                                 tty_hangup(sl->tty);
933                         }
934                         spin_unlock_bh(&sl->lock);
935                 }
936         } while (busy && time_before(jiffies, timeout));
937
938         /* FIXME: hangup is async so we should wait when doing this second
939            phase */
940
941         for (i = 0; i < maxdev; i++) {
942                 dev = sllin_devs[i];
943                 if (!dev)
944                         continue;
945                 sllin_devs[i] = NULL;
946
947                 sl = netdev_priv(dev);
948                 if (sl->tty) {
949                         printk(KERN_ERR "%s: tty discipline still running\n",
950                                dev->name);
951                         /* Intentionally leak the control block. */
952                         dev->destructor = NULL;
953                 }
954
955                 unregister_netdev(dev);
956         }
957
958         kfree(sllin_devs);
959         sllin_devs = NULL;
960
961         i = tty_unregister_ldisc(N_SLLIN);
962         if (i)
963                 printk(KERN_ERR "sllin: can't unregister ldisc (err %d)\n", i);
964 }
965
966 module_init(sllin_init);
967 module_exit(sllin_exit);