]> rtime.felk.cvut.cz Git - linux-lin.git/blob - sllin/sllin.c
sllin: It is possible to send "LIN response" from linfr_cache when configured.
[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_LIN_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         canid_t frame_fl;       /* LIN frame flags. Passed from userspace as canid_t data type */
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_LIN_ID_CONF))
476                 return -1;
477
478         sce = &sl->linfr_cache[cf->can_id & SLLIN_ID_MASK];
479         printk(KERN_INFO "Setting frame cache with EFF CAN frame. "
480                 "LIN ID = %d\n", cf->can_id & SLLIN_ID_MASK);
481
482         sce->dlc = (cf->can_dlc > 8) ? 8 : cf->can_dlc;
483         sce->frame_fl = (cf->can_id & ~SLLIN_ID_MASK) & CAN_EFF_MASK;
484         memcpy(sce->data, cf->data, cf->can_dlc);
485
486         return 0;
487 }
488
489 int sllin_setup_msg(struct sllin *sl, int mode, int id,
490                 unsigned char *data, int len)
491 {
492         if (id > SLLIN_ID_MASK)
493                 return -1;
494
495         sl->rx_cnt = 0;
496         sl->tx_cnt = 0;
497         sl->rx_expect = 0;
498         sl->rx_lim = SLLIN_BUFF_LEN;
499
500         sl->tx_buff[SLLIN_BUFF_BREAK] = 0;
501         sl->tx_buff[SLLIN_BUFF_SYNC]  = 0x55;
502         sl->tx_buff[SLLIN_BUFF_ID]    = id | sllin_id_parity_table[id];
503         sl->tx_lim = SLLIN_BUFF_DATA;
504
505         if ((data != NULL) && len) {
506                 int i;
507                 unsigned csum  = 0;
508
509                 sl->tx_lim += len;
510                 memcpy(sl->tx_buff + SLLIN_BUFF_DATA, data, len);
511                 /* compute data parity there */
512                 for (i = SLLIN_BUFF_DATA; i < sl->tx_lim; i++) {
513                         csum += sl->tx_buff[i];
514                         if (csum > 255)
515                                 csum -= 255;
516                 }
517
518                 sl->tx_buff[sl->tx_lim++] = csum;
519         }
520         if (len != 0)
521                 sl->rx_lim = SLLIN_BUFF_DATA + len + 1;
522
523         return 0;
524 }
525
526
527 int sllin_send_tx_buff(struct sllin *sl)
528 {
529         struct tty_struct *tty = sl->tty;
530         int remains;
531         int res;
532
533 #ifdef BREAK_BY_BAUD
534         if (sl->lin_state != SLSTATE_BREAK_SENT)
535                 remains = sl->tx_lim - sl->tx_cnt;
536         else
537                 remains = 1;
538 #else
539         remains = sl->tx_lim - sl->tx_cnt;
540 #endif
541
542         res = tty->ops->write(tty, sl->tx_buff + sl->tx_cnt, remains);
543         if (res < 0)
544                 return -1;
545
546         remains -= res;
547         sl->tx_cnt += res;
548
549         if (remains > 0) {
550                 set_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
551                 res = tty->ops->write(tty, sl->tx_buff + sl->tx_cnt, remains);
552                 if (res < 0) {
553                         clear_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
554                         return -1;
555                 }
556                 
557                 remains -= res;
558                 sl->tx_cnt += res;
559         }
560
561         printk(KERN_INFO "sllin_send_tx_buff sent %d, remains %d\n",
562                         sl->tx_cnt, remains);
563
564         return 0;
565 }
566
567 #ifdef BREAK_BY_BAUD
568 int sllin_send_break(struct sllin *sl)
569 {
570         struct tty_struct *tty = sl->tty;
571         unsigned long break_baud;
572         int res;
573
574         break_baud = ((sl->lin_baud * 2) / 3);
575         sltty_change_speed(tty, break_baud);
576
577         tty->ops->flush_buffer(tty);
578         sl->rx_cnt = SLLIN_BUFF_BREAK;
579
580         sl->rx_expect = SLLIN_BUFF_BREAK + 1;
581         sl->lin_state = SLSTATE_BREAK_SENT;
582
583         res = sllin_send_tx_buff(sl);
584         if (res < 0) {
585                 sl->lin_state = SLSTATE_IDLE;
586                 return res;
587         }
588
589         return 0;
590 }
591 #else /* BREAK_BY_BAUD */
592
593 int sllin_send_break(struct sllin *sl)
594 {
595         struct tty_struct *tty = sl->tty;
596         unsigned long break_baud;
597         unsigned long flags;    
598         int retval;
599
600         sl->rx_cnt = SLLIN_BUFF_BREAK;
601         sl->rx_expect = SLLIN_BUFF_BREAK + 1;
602         sl->lin_state = SLSTATE_BREAK_SENT;
603
604         /* Do the break ourselves; Inspired by 
605            http://lxr.linux.no/#linux+v3.1.2/drivers/tty/tty_io.c#L2452 */
606         retval = tty->ops->break_ctl(tty, -1);
607         if (retval)
608                 return retval;
609
610         //udelay(712);
611         usleep_range(650, 750);
612
613         retval = tty->ops->break_ctl(tty, 0);
614         usleep_range(50, 100);
615         
616         tty->ops->flush_buffer(tty);
617
618         sl->tx_cnt = SLLIN_BUFF_SYNC;
619
620         printk(KERN_INFO "sllin: Break sent.\n");
621         set_bit(SLF_RXEVENT, &sl->flags);
622         wake_up(&sl->kwt_wq);
623
624         return 0;
625 }
626 #endif /* BREAK_BY_BAUD */
627
628
629 static enum hrtimer_restart sllin_rx_timeout_handler(struct hrtimer *hrtimer)
630 {
631         struct sllin *sl = container_of(hrtimer, struct sllin, rx_timer);
632
633         set_bit(SLF_TMOUTEVENT, &sl->flags);
634         wake_up(&sl->kwt_wq);
635
636         return HRTIMER_NORESTART;
637 }
638
639
640 /*****************************************
641  *  sllin_kwthread - kernel worker thread
642  *****************************************/
643
644 int sllin_kwthread(void *ptr)
645 {
646         struct sllin *sl = (struct sllin *)ptr;
647         struct tty_struct *tty = sl->tty;
648         struct sched_param schparam = { .sched_priority = 40 };
649         int res;
650         struct can_frame *cf;
651         char *lin_data;
652         int lin_dlc;
653         int tx_bytes = 0; /* Used for Network statistics */
654
655
656         printk(KERN_INFO "sllin: sllin_kwthread started.\n");
657         sched_setscheduler(current, SCHED_FIFO, &schparam);
658
659         clear_bit(SLF_ERROR, &sl->flags);
660         sltty_change_speed(tty, sl->lin_baud);
661
662         while (!kthread_should_stop()) {
663                 if ((sl->lin_state == SLSTATE_IDLE) && sl->lin_master &&
664                         sl->id_to_send) {
665                         if(sllin_send_break(sl) < 0) {
666                                 /* error processing */
667                         }
668                 }
669
670                 wait_event_killable(sl->kwt_wq, kthread_should_stop() ||
671                         test_bit(SLF_RXEVENT, &sl->flags) ||
672                         test_bit(SLF_TXEVENT, &sl->flags) ||
673                         test_bit(SLF_TMOUTEVENT, &sl->flags) ||
674                         ((sl->lin_state == SLSTATE_IDLE) && test_bit(SLF_MSGEVENT, &sl->flags)));
675
676                 if (test_and_clear_bit(SLF_RXEVENT, &sl->flags)) {
677                         printk(KERN_INFO "sllin_kthread RXEVENT \n");
678                 }
679
680                 if (test_and_clear_bit(SLF_TXEVENT, &sl->flags)) {
681                         printk(KERN_INFO "sllin_kthread TXEVENT \n");
682                 }
683
684                 if (test_and_clear_bit(SLF_TMOUTEVENT, &sl->flags)) {
685                         printk(KERN_INFO "sllin_kthread TMOUTEVENT \n");
686                         sl->rx_cnt = 0;
687                         sl->rx_expect = 0;
688                         sl->rx_lim = sl->lin_master ? 0 : SLLIN_BUFF_LEN;
689                         sl->tx_cnt = 0;
690                         sl->tx_lim = 0;
691                         sl->id_to_send = false;
692                         sl->data_to_send = false;
693                         
694                         sl->lin_state = SLSTATE_IDLE;
695                 }
696
697                 if ((sl->lin_state == SLSTATE_IDLE) && test_bit(SLF_MSGEVENT, &sl->flags)) {
698                         cf = (struct can_frame *)sl->rec_skb->data;
699
700                         /* EFF CAN frame -> "Configuration" frame */
701                         if (cf->can_id & CAN_EFF_FLAG) {
702                                 sllin_configure_frame_cache(sl, cf);
703                                 goto free_skb;
704                         } /* SFF RTR CAN frame -> LIN header */ 
705                         else if (cf->can_id & CAN_RTR_FLAG) {
706                                 printk(KERN_INFO "%s: RTR SFF CAN frame, ID = %x\n",
707                                         __FUNCTION__, cf->can_id & SLLIN_ID_MASK);
708
709                                 /* Is there Slave response in linfr_cache to be sent? */
710                                 if ((sl->linfr_cache[cf->can_id & SLLIN_ID_MASK].frame_fl & 
711                                         SLLIN_LOC_SLAVE_CACHE) 
712                                         && (sl->linfr_cache[cf->can_id & SLLIN_ID_MASK].dlc > 0)) {
713                                         
714                                         printk(KERN_INFO "Sending LIN response from linfr_cache\n");
715                                         lin_data = &sl->linfr_cache[cf->can_id & SLLIN_ID_MASK].data;
716                                         lin_dlc = sl->linfr_cache[cf->can_id & SLLIN_ID_MASK].dlc;
717                                 } else {
718                                         lin_data = NULL;
719                                         lin_dlc = 0;
720                                 }
721                         } else { /* SFF NON-RTR CAN frame -> LIN header + LIN response */
722                                 printk(KERN_INFO "%s: NON-RTR SFF CAN frame, ID = %x\n",
723                                         __FUNCTION__, (int)cf->can_id & SLLIN_ID_MASK);
724
725                                 lin_data = cf->data;
726                                 lin_dlc = tx_bytes = cf->can_dlc;
727                         }
728
729                         if (sllin_setup_msg(sl, 0, cf->can_id & SLLIN_ID_MASK,
730                                 lin_data, lin_dlc) != -1) {
731
732                                 sl->id_to_send = true;
733                                 sl->data_to_send = (lin_dlc > 0) ? true : false;
734                                 sl->dev->stats.tx_packets++;
735                                 sl->dev->stats.tx_bytes += tx_bytes;
736                         }
737
738                 free_skb:
739                         clear_bit(SLF_MSGEVENT, &sl->flags);
740                         kfree_skb(sl->rec_skb);
741                         netif_wake_queue(sl->dev);
742                 }
743
744                 switch (sl->lin_state) {
745                         case SLSTATE_BREAK_SENT:
746 #ifdef BREAK_BY_BAUD
747                                 if (sl->rx_cnt <= SLLIN_BUFF_BREAK)
748                                         continue;
749
750                                 res = sltty_change_speed(tty, sl->lin_baud);
751 #endif
752
753                                 sl->lin_state = SLSTATE_ID_SENT;
754                                 sllin_send_tx_buff(sl);
755                                 break;
756
757                         case SLSTATE_ID_SENT:
758                                 sl->id_to_send = false;
759                                 if (sl->data_to_send) {
760                                         sllin_send_tx_buff(sl);
761                                         sl->lin_state = SLSTATE_RESPONSE_SENT;
762                                         sl->rx_expect = sl->tx_lim;
763                                         goto slstate_response_sent;
764                                 } else {
765                                         sl->rx_expect = SLLIN_BUFF_DATA + 2;
766                                         sl->lin_state = SLSTATE_RESPONSE_WAIT;
767                                         /* If we don't receive anything, timer will "unblock" us */
768                                         hrtimer_start(&sl->rx_timer, 
769                                                 ktime_add(ktime_get(), sl->rx_timer_timeout),
770                                                 HRTIMER_MODE_ABS);
771                                         goto slstate_response_wait;
772                                 }
773                                 break;
774
775                         case SLSTATE_RESPONSE_WAIT:
776                         slstate_response_wait:
777                                 if (sl->rx_cnt < sl->rx_expect)
778                                         continue;
779                         
780                                 hrtimer_cancel(&sl->rx_timer);
781                                 printk(KERN_INFO "sllin: response received ID %d len %d\n",
782                                         sl->rx_buff[SLLIN_BUFF_ID], sl->rx_cnt - SLLIN_BUFF_DATA - 1);
783                                 // FIXME: check checksum in sl->rx_buff
784
785                                 // send CAN non-RTR frame with data
786                                 printk(KERN_INFO "sllin: sending NON-RTR CAN frame with LIN payload.");
787                                 sll_bump(sl); //send packet to the network layer
788                                 sl->id_to_send = false;
789                                 sl->lin_state = SLSTATE_IDLE;
790                                 break;
791
792                         case SLSTATE_RESPONSE_SENT:
793                         slstate_response_sent:
794                                 if (sl->rx_cnt < sl->tx_lim)
795                                         continue;
796                                 
797                                 sll_bump(sl); //send packet to the network layer
798                                 printk(KERN_INFO "sllin: response sent ID %d len %d\n",
799                                         sl->rx_buff[SLLIN_BUFF_ID], sl->rx_cnt - SLLIN_BUFF_DATA - 1);
800
801                                 sl->id_to_send = false;
802                                 sl->lin_state = SLSTATE_IDLE;
803                                 break;
804                 }
805
806
807
808
809                 /* sl->dev->stats.tx_packets++; send frames statistic */
810                 /* netif_wake_queue(sl->dev); allow next Tx packet arrival */
811         }
812
813         hrtimer_cancel(&sl->rx_timer);
814         printk(KERN_INFO "sllin: sllin_kwthread stopped.\n");
815
816         return 0;
817 }
818
819
820 /************************************
821  *  sllin_open helper routines.
822  ************************************/
823
824 /* Collect hanged up channels */
825 static void sll_sync(void)
826 {
827         int i;
828         struct net_device *dev;
829         struct sllin      *sl;
830
831         for (i = 0; i < maxdev; i++) {
832                 dev = sllin_devs[i];
833                 if (dev == NULL)
834                         break;
835
836                 sl = netdev_priv(dev);
837                 if (sl->tty)
838                         continue;
839                 if (dev->flags & IFF_UP)
840                         dev_close(dev);
841         }
842 }
843
844 /* Find a free SLLIN channel, and link in this `tty' line. */
845 static struct sllin *sll_alloc(dev_t line)
846 {
847         int i;
848         struct net_device *dev = NULL;
849         struct sllin       *sl;
850
851         if (sllin_devs == NULL)
852                 return NULL;    /* Master array missing ! */
853
854         for (i = 0; i < maxdev; i++) {
855                 dev = sllin_devs[i];
856                 if (dev == NULL)
857                         break;
858
859         }
860
861         /* Sorry, too many, all slots in use */
862         if (i >= maxdev)
863                 return NULL;
864
865         if (dev) {
866                 sl = netdev_priv(dev);
867                 if (test_bit(SLF_INUSE, &sl->flags)) {
868                         unregister_netdevice(dev);
869                         dev = NULL;
870                         sllin_devs[i] = NULL;
871                 }
872         }
873
874         if (!dev) {
875                 char name[IFNAMSIZ];
876                 sprintf(name, "sllin%d", i);
877
878                 dev = alloc_netdev(sizeof(*sl), name, sll_setup);
879                 if (!dev)
880                         return NULL;
881                 dev->base_addr  = i;
882         }
883
884         sl = netdev_priv(dev);
885         /* Initialize channel control data */
886         sl->magic = SLLIN_MAGIC;
887         sl->dev = dev;
888         spin_lock_init(&sl->lock);
889         sllin_devs[i] = dev;
890
891         return sl;
892 }
893
894 /*
895  * Open the high-level part of the SLLIN channel.
896  * This function is called by the TTY module when the
897  * SLLIN line discipline is called for.  Because we are
898  * sure the tty line exists, we only have to link it to
899  * a free SLLIN channel...
900  *
901  * Called in process context serialized from other ldisc calls.
902  */
903
904 static int sllin_open(struct tty_struct *tty)
905 {
906         struct sllin *sl;
907         int err;
908         pr_debug("sllin: %s() invoked\n", __FUNCTION__);
909
910         if (!capable(CAP_NET_ADMIN))
911                 return -EPERM;
912
913         if (tty->ops->write == NULL)
914                 return -EOPNOTSUPP;
915
916         /* RTnetlink lock is misused here to serialize concurrent
917            opens of sllin channels. There are better ways, but it is
918            the simplest one.
919          */
920         rtnl_lock();
921
922         /* Collect hanged up channels. */
923         sll_sync();
924
925         sl = tty->disc_data;
926
927         err = -EEXIST;
928         /* First make sure we're not already connected. */
929         if (sl && sl->magic == SLLIN_MAGIC)
930                 goto err_exit;
931
932         /* OK.  Find a free SLLIN channel to use. */
933         err = -ENFILE;
934         sl = sll_alloc(tty_devnum(tty));
935         if (sl == NULL)
936                 goto err_exit;
937
938         sl->tty = tty;
939         tty->disc_data = sl;
940         sl->line = tty_devnum(tty);
941
942         if (!test_bit(SLF_INUSE, &sl->flags)) {
943                 /* Perform the low-level SLLIN initialization. */
944                 sl->lin_master = true;
945
946                 sl->rx_cnt = 0;
947                 sl->rx_expect = 0;
948                 sl->rx_lim = sl->lin_master ? 0 : SLLIN_BUFF_LEN;
949                 sl->tx_cnt = 0;
950                 sl->tx_lim = 0;
951                 sl->id_to_send = false;
952                 sl->data_to_send = false;
953
954                 sl->lin_baud  = 19200;
955
956                 sl->lin_state = SLSTATE_IDLE;
957
958 #define SAMPLES_PER_CHAR        10
959 #define CHARS_TO_TIMEOUT        12
960                 hrtimer_init(&sl->rx_timer, CLOCK_MONOTONIC, HRTIMER_MODE_REL);
961                 sl->rx_timer.function = sllin_rx_timeout_handler;
962                 /* timeval_to_ktime(msg_head->ival1); */
963                 sl->rx_timer_timeout = ns_to_ktime(
964                         (1000000000 / sl->lin_baud) * 
965                         SAMPLES_PER_CHAR * CHARS_TO_TIMEOUT); 
966  
967                 set_bit(SLF_INUSE, &sl->flags);
968
969                 init_waitqueue_head(&sl->kwt_wq);
970                 sl->kwthread = kthread_run(sllin_kwthread, sl, "sllin");
971                 if (sl->kwthread == NULL)
972                         goto err_free_chan;
973
974                 err = register_netdevice(sl->dev);
975                 if (err)
976                         goto err_free_chan_and_thread;
977         }
978
979         /* Done.  We have linked the TTY line to a channel. */
980         rtnl_unlock();
981         tty->receive_room = SLLIN_BUFF_LEN * 40;        /* We don't flow control */
982
983         /* TTY layer expects 0 on success */
984         return 0;
985
986 err_free_chan_and_thread:
987         kthread_stop(sl->kwthread);
988         sl->kwthread = NULL;
989
990 err_free_chan:
991         sl->tty = NULL;
992         tty->disc_data = NULL;
993         clear_bit(SLF_INUSE, &sl->flags);
994
995 err_exit:
996         rtnl_unlock();
997
998         /* Count references from TTY module */
999         return err;
1000 }
1001
1002 /*
1003  * Close down a SLLIN channel.
1004  * This means flushing out any pending queues, and then returning. This
1005  * call is serialized against other ldisc functions.
1006  *
1007  * We also use this method for a hangup event.
1008  */
1009
1010 static void sllin_close(struct tty_struct *tty)
1011 {
1012         struct sllin *sl = (struct sllin *) tty->disc_data;
1013
1014         /* First make sure we're connected. */
1015         if (!sl || sl->magic != SLLIN_MAGIC || sl->tty != tty)
1016                 return;
1017
1018         kthread_stop(sl->kwthread);
1019         sl->kwthread = NULL;
1020
1021         tty->disc_data = NULL;
1022         sl->tty = NULL;
1023
1024         /* Flush network side */
1025         unregister_netdev(sl->dev);
1026         /* This will complete via sl_free_netdev */
1027 }
1028
1029 static int sllin_hangup(struct tty_struct *tty)
1030 {
1031         sllin_close(tty);
1032         return 0;
1033 }
1034
1035 /* Perform I/O control on an active SLLIN channel. */
1036 static int sllin_ioctl(struct tty_struct *tty, struct file *file,
1037                        unsigned int cmd, unsigned long arg)
1038 {
1039         struct sllin *sl = (struct sllin *) tty->disc_data;
1040         unsigned int tmp;
1041
1042         /* First make sure we're connected. */
1043         if (!sl || sl->magic != SLLIN_MAGIC)
1044                 return -EINVAL;
1045
1046         switch (cmd) {
1047         case SIOCGIFNAME:
1048                 tmp = strlen(sl->dev->name) + 1;
1049                 if (copy_to_user((void __user *)arg, sl->dev->name, tmp))
1050                         return -EFAULT;
1051                 return 0;
1052
1053         case SIOCSIFHWADDR:
1054                 return -EINVAL;
1055
1056         default:
1057                 return tty_mode_ioctl(tty, file, cmd, arg);
1058         }
1059 }
1060
1061 static struct tty_ldisc_ops sll_ldisc = {
1062         .owner          = THIS_MODULE,
1063         .magic          = TTY_LDISC_MAGIC,
1064         .name           = "sllin",
1065         .open           = sllin_open,
1066         .close          = sllin_close,
1067         .hangup         = sllin_hangup,
1068         .ioctl          = sllin_ioctl,
1069         .receive_buf    = sllin_receive_buf,
1070         .write_wakeup   = sllin_write_wakeup,
1071 };
1072
1073 static int __init sllin_init(void)
1074 {
1075         int status;
1076
1077         if (maxdev < 4)
1078                 maxdev = 4; /* Sanity */
1079
1080         printk(banner);
1081         printk(KERN_INFO "sllin: %d dynamic interface channels.\n", maxdev);
1082
1083         sllin_devs = kzalloc(sizeof(struct net_device *)*maxdev, GFP_KERNEL);
1084         if (!sllin_devs) {
1085                 printk(KERN_ERR "sllin: can't allocate sllin device array!\n");
1086                 return -ENOMEM;
1087         }
1088
1089         /* Fill in our line protocol discipline, and register it */
1090         status = tty_register_ldisc(N_SLLIN, &sll_ldisc);
1091         if (status)  {
1092                 printk(KERN_ERR "sllin: can't register line discipline\n");
1093                 kfree(sllin_devs);
1094         }
1095         return status;
1096 }
1097
1098 static void __exit sllin_exit(void)
1099 {
1100         int i;
1101         struct net_device *dev;
1102         struct sllin *sl;
1103         unsigned long timeout = jiffies + HZ;
1104         int busy = 0;
1105
1106         if (sllin_devs == NULL)
1107                 return;
1108
1109         /* First of all: check for active disciplines and hangup them.
1110          */
1111         do {
1112                 if (busy)
1113                         msleep_interruptible(100);
1114
1115                 busy = 0;
1116                 for (i = 0; i < maxdev; i++) {
1117                         dev = sllin_devs[i];
1118                         if (!dev)
1119                                 continue;
1120                         sl = netdev_priv(dev);
1121                         spin_lock_bh(&sl->lock);
1122                         if (sl->tty) {
1123                                 busy++;
1124                                 tty_hangup(sl->tty);
1125                         }
1126                         spin_unlock_bh(&sl->lock);
1127                 }
1128         } while (busy && time_before(jiffies, timeout));
1129
1130         /* FIXME: hangup is async so we should wait when doing this second
1131            phase */
1132
1133         for (i = 0; i < maxdev; i++) {
1134                 dev = sllin_devs[i];
1135                 if (!dev)
1136                         continue;
1137                 sllin_devs[i] = NULL;
1138
1139                 sl = netdev_priv(dev);
1140                 if (sl->tty) {
1141                         printk(KERN_ERR "%s: tty discipline still running\n",
1142                                dev->name);
1143                         /* Intentionally leak the control block. */
1144                         dev->destructor = NULL;
1145                 }
1146
1147                 unregister_netdev(dev);
1148         }
1149
1150         kfree(sllin_devs);
1151         sllin_devs = NULL;
1152
1153         i = tty_unregister_ldisc(N_SLLIN);
1154         if (i)
1155                 printk(KERN_ERR "sllin: can't unregister ldisc (err %d)\n", i);
1156 }
1157
1158 module_init(sllin_init);
1159 module_exit(sllin_exit);