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