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