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