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