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