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