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