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