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