]> rtime.felk.cvut.cz Git - linux-lin.git/blob - sllin/sllin.c
sllin: Improved sending of a "LIN response" sent by master following LIN header.
[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
62 /* Should be in include/linux/tty.h */
63 #define N_SLLIN         25
64
65 static __initdata const char banner[] =
66         KERN_INFO "sllin: serial line LIN interface driver\n";
67
68 MODULE_ALIAS_LDISC(N_SLLIN);
69 MODULE_DESCRIPTION("serial line LIN interface");
70 MODULE_LICENSE("GPL");
71 MODULE_AUTHOR("Oliver Hartkopp <socketcan@hartkopp.net>");
72
73 #define SLLIN_MAGIC 0x53CA
74 // #define BREAK_BY_BAUD
75
76 static int maxdev = 10;         /* MAX number of SLLIN channels;
77                                    This can be overridden with
78                                    insmod sllin.ko maxdev=nnn   */
79 module_param(maxdev, int, 0);
80 MODULE_PARM_DESC(maxdev, "Maximum number of sllin interfaces");
81
82 /* maximum buffer len to store whole LIN message*/
83 #define SLLIN_DATA_MAX   8
84 #define SLLIN_BUFF_LEN  (1 /*break*/ + 1 /*sync*/ + 1 /*ID*/ + \
85                          SLLIN_DATA_MAX + 1 /*checksum*/)
86 #define SLLIN_BUFF_BREAK 0
87 #define SLLIN_BUFF_SYNC  1
88 #define SLLIN_BUFF_ID    2
89 #define SLLIN_BUFF_DATA  3
90
91 enum slstate {
92         SLSTATE_IDLE = 0,
93         SLSTATE_BREAK_SENT,
94         SLSTATE_ID_SENT,
95         SLSTATE_RESPONSE_WAIT,
96         SLSTATE_RESPONSE_SENT,
97 };
98
99 struct sllin {
100         int                     magic;
101
102         /* Various fields. */
103         struct tty_struct       *tty;           /* ptr to TTY structure      */
104         struct net_device       *dev;           /* easy for intr handling    */
105         spinlock_t              lock;
106
107         /* LIN message buffer and actual processed data counts */
108         unsigned char           rx_buff[SLLIN_BUFF_LEN]; /* LIN Rx buffer */
109         unsigned char           tx_buff[SLLIN_BUFF_LEN]; /* LIN Tx buffer */
110         int                     rx_expect;      /* expected number of Rx chars */
111         int                     rx_lim;         /* maximum Rx chars for current frame */
112         int                     rx_cnt;         /* message buffer Rx fill level  */
113         int                     tx_lim;         /* actual limit of bytes to Tx */
114         int                     tx_cnt;         /* number of already Tx bytes */
115         char                    lin_master;     /* node is a master node */
116         int                     lin_baud;       /* LIN baudrate */
117         int                     lin_state;      /* state */
118         char                    id_to_send;     /* there is ID to be sent */
119         char                    data_to_send;   /* there are data to be sent */
120
121         unsigned long           flags;          /* Flag values/ mode etc     */
122 #define SLF_INUSE               0               /* Channel in use            */
123 #define SLF_ERROR               1               /* Parity, etc. error        */
124 #define SLF_RXEVENT             2               /* Rx wake event             */
125 #define SLF_TXEVENT             3               /* Tx wake event             */
126 #define SLF_MSGEVENT            4               /* CAN message to sent       */
127
128         dev_t                   line;
129         struct task_struct      *kwthread;
130         wait_queue_head_t       kwt_wq;
131
132         struct sk_buff          *rec_skb;       /* Socket buffer with received CAN frame */
133 };
134
135 static struct net_device **sllin_devs;
136
137 const unsigned char sllin_id_parity_table[] = {
138         0x80,0xc0,0x40,0x00,0xc0,0x80,0x00,0x40,
139         0x00,0x40,0xc0,0x80,0x40,0x00,0x80,0xc0,
140         0x40,0x00,0x80,0xc0,0x00,0x40,0xc0,0x80,
141         0xc0,0x80,0x00,0x40,0x80,0xc0,0x40,0x00,
142         0x00,0x40,0xc0,0x80,0x40,0x00,0x80,0xc0,
143         0x80,0xc0,0x40,0x00,0xc0,0x80,0x00,0x40,
144         0xc0,0x80,0x00,0x40,0x80,0xc0,0x40,0x00,
145         0x40,0x00,0x80,0xc0,0x00,0x40,0xc0,0x80
146 };
147
148 static int sltty_change_speed(struct tty_struct *tty, unsigned speed)
149 {
150         struct ktermios old_termios;
151         int cflag;
152
153         mutex_lock(&tty->termios_mutex);
154
155         old_termios = *(tty->termios);
156         cflag = tty->termios->c_cflag;
157         cflag &= ~(CBAUD | CIBAUD);
158         cflag |= BOTHER;
159         tty->termios->c_cflag = cflag;
160
161         tty_encode_baud_rate(tty, speed, speed);
162
163         if (tty->ops->set_termios)
164                 tty->ops->set_termios(tty, &old_termios);
165
166         mutex_unlock(&tty->termios_mutex);
167
168         return 0;
169 }
170
171
172 /* Send one completely decapsulated can_frame to the network layer */
173 static void sll_bump(struct sllin *sl)
174 {
175 //      struct sk_buff *skb;
176 //      struct can_frame cf;
177 //      int i, dlc_pos, tmp;
178 //      unsigned long ultmp;
179 //      char cmd = sl->rbuff[0];
180 //
181 //      if ((cmd != 't') && (cmd != 'T') && (cmd != 'r') && (cmd != 'R'))
182 //              return;
183 //
184 //      if (cmd & 0x20) /* tiny chars 'r' 't' => standard frame format */
185 //              dlc_pos = 4; /* dlc position tiiid */
186 //      else
187 //              dlc_pos = 9; /* dlc position Tiiiiiiiid */
188 //
189 //      if (!((sl->rbuff[dlc_pos] >= '0') && (sl->rbuff[dlc_pos] < '9')))
190 //              return;
191 //
192 //      cf.can_dlc = sl->rbuff[dlc_pos] - '0'; /* get can_dlc from ASCII val */
193 //
194 //      sl->rbuff[dlc_pos] = 0; /* terminate can_id string */
195 //
196 //      if (strict_strtoul(sl->rbuff+1, 16, &ultmp))
197 //              return;
198 //
199 //      cf.can_id = ultmp;
200 //
201 //      if (!(cmd & 0x20)) /* NO tiny chars => extended frame format */
202 //              cf.can_id |= CAN_EFF_FLAG;
203 //
204 //      if ((cmd | 0x20) == 'r') /* RTR frame */
205 //              cf.can_id |= CAN_RTR_FLAG;
206 //
207 //      *(u64 *) (&cf.data) = 0; /* clear payload */
208 //
209 //      for (i = 0, dlc_pos++; i < cf.can_dlc; i++) {
210 //
211 //              tmp = asc2nibble(sl->rbuff[dlc_pos++]);
212 //              if (tmp > 0x0F)
213 //                      return;
214 //              cf.data[i] = (tmp << 4);
215 //              tmp = asc2nibble(sl->rbuff[dlc_pos++]);
216 //              if (tmp > 0x0F)
217 //                      return;
218 //              cf.data[i] |= tmp;
219 //      }
220 //
221 //
222 //      skb = dev_alloc_skb(sizeof(struct can_frame));
223 //      if (!skb)
224 //              return;
225 //
226 //      skb->dev = sl->dev;
227 //      skb->protocol = htons(ETH_P_CAN);
228 //      skb->pkt_type = PACKET_BROADCAST;
229 //      skb->ip_summed = CHECKSUM_UNNECESSARY;
230 //      memcpy(skb_put(skb, sizeof(struct can_frame)),
231 //             &cf, sizeof(struct can_frame));
232 //      netif_rx(skb);
233 //
234 //      sl->dev->stats.rx_packets++;
235 //      sl->dev->stats.rx_bytes += cf.can_dlc;
236 }
237
238
239  /************************************************************************
240   *                     STANDARD SLLIN ENCAPSULATION                     *
241   ************************************************************************/
242
243 /* Convert particular CAN frame into LIN frame and send it to TTY queue. */
244 static void sll_encaps(struct sllin *sl, struct can_frame *cf)
245 {
246 //      int actual, idx, i;
247 //      char lframe[16] = {0x00, 0x55}; /* Fake break, Sync byte */
248 //      struct tty_struct *tty = sl->tty;
249 //
250 //      pr_debug("sllin: %s() invoked\n", __FUNCTION__);
251 //
252 //      /* We do care only about SFF frames */
253 //      if (cf->can_id & CAN_EFF_FLAG)
254 //              return;
255 //
256 //      /* Send only header */
257 //      if (cf->can_id & CAN_RTR_FLAG) {
258 //              pr_debug("sllin: %s() RTR CAN frame\n", __FUNCTION__);
259 //              lframe[2] = (u8)cf->can_id; /* Get one byte LIN ID */
260 //
261 //              sltty_change_speed(tty, sl->lin_baud * 2 / 3);
262 //              tty->ops->write(tty, &lframe[0], 1);
263 //              sltty_change_speed(tty, sl->lin_baud);
264 //              tty->ops->write(tty, &lframe[1], 1);
265 //              tty->ops->write(tty, &lframe[2], 1);
266 //      } else {
267 //              pr_debug("sllin: %s() non-RTR CAN frame\n", __FUNCTION__);
268 //              /*      idx = strlen(sl->xbuff);
269 //
270 //                      for (i = 0; i < cf->can_dlc; i++)
271 //                      sprintf(&sl->xbuff[idx + 2*i], "%02X", cf->data[i]);
272 //
273 //               * Order of next two lines is *very* important.
274 //               * When we are sending a little amount of data,
275 //               * the transfer may be completed inside the ops->write()
276 //               * routine, because it's running with interrupts enabled.
277 //               * In this case we *never* got WRITE_WAKEUP event,
278 //               * if we did not request it before write operation.
279 //               *       14 Oct 1994  Dmitry Gorodchanin.
280 //
281 //               set_bit(TTY_DO_WRITE_WAKEUP, &sl->tty->flags);
282 //               actual = sl->tty->ops->write(sl->tty, sl->xbuff, strlen(sl->xbuff));
283 //               sl->xleft = strlen(sl->xbuff) - actual;
284 //               sl->xhead = sl->xbuff + actual;
285 //               sl->dev->stats.tx_bytes += cf->can_dlc;
286 //               */
287 //      }
288 //
289 }
290
291 /*
292  * Called by the driver when there's room for more data.  If we have
293  * more packets to send, we send them here.
294  */
295 static void sllin_write_wakeup(struct tty_struct *tty)
296 {
297         int actual;
298         int remains;
299         struct sllin *sl = (struct sllin *) tty->disc_data;
300
301         /* First make sure we're connected. */
302         if (!sl || sl->magic != SLLIN_MAGIC || !netif_running(sl->dev))
303                 return;
304
305         if (sl->lin_state != SLSTATE_BREAK_SENT)
306                 remains = sl->tx_lim - sl->tx_cnt;
307         else
308                 remains = SLLIN_BUFF_BREAK + 1 - sl->tx_cnt;
309
310         if (remains > 0) {
311                 actual = tty->ops->write(tty, sl->tx_buff + sl->tx_cnt, sl->tx_cnt - sl->tx_lim);
312                 sl->tx_cnt += actual;
313
314                 if (sl->tx_cnt < sl->tx_lim) {
315                         printk(KERN_INFO "sllin_write_wakeup sent %d, remains %d, waiting\n",
316                                 sl->tx_cnt, sl->tx_lim - sl->tx_cnt);
317                         return;
318                 }
319         }
320
321         clear_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
322         set_bit(SLF_TXEVENT, &sl->flags);
323         wake_up(&sl->kwt_wq);
324
325         printk(KERN_INFO "sllin_write_wakeup sent %d, wakeup\n", sl->tx_cnt);
326 }
327
328 /* Send a can_frame to a TTY queue. */
329 static netdev_tx_t sll_xmit(struct sk_buff *skb, struct net_device *dev)
330 {
331         struct sllin *sl = netdev_priv(dev);
332
333         if (skb->len != sizeof(struct can_frame))
334                 goto err_out;
335
336         spin_lock(&sl->lock);
337         if (!netif_running(dev))  {
338                 spin_unlock(&sl->lock);
339                 printk(KERN_WARNING "%s: xmit: iface is down\n", dev->name);
340                 goto err_out;
341         }
342         if (sl->tty == NULL) {
343                 spin_unlock(&sl->lock);
344                 goto err_out;
345         }
346
347         netif_stop_queue(sl->dev);
348
349         sl->rec_skb = skb;
350         set_bit(SLF_MSGEVENT, &sl->flags);
351         wake_up(&sl->kwt_wq);
352         spin_unlock(&sl->lock);
353         return NETDEV_TX_OK;
354
355 err_out:
356         kfree_skb(skb);
357         return NETDEV_TX_OK;
358 }
359
360
361 /******************************************
362  *   Routines looking at netdevice side.
363  ******************************************/
364
365 /* Netdevice UP -> DOWN routine */
366 static int sll_close(struct net_device *dev)
367 {
368         struct sllin *sl = netdev_priv(dev);
369
370         spin_lock_bh(&sl->lock);
371         if (sl->tty) {
372                 /* TTY discipline is running. */
373                 clear_bit(TTY_DO_WRITE_WAKEUP, &sl->tty->flags);
374         }
375         netif_stop_queue(dev);
376         sl->rx_expect = 0;
377         sl->tx_lim    = 0;
378         spin_unlock_bh(&sl->lock);
379
380         return 0;
381 }
382
383 /* Netdevice DOWN -> UP routine */
384 static int sll_open(struct net_device *dev)
385 {
386         struct sllin *sl = netdev_priv(dev);
387
388         pr_debug("sllin: %s() invoked\n", __FUNCTION__);
389
390         if (sl->tty == NULL)
391                 return -ENODEV;
392
393         sl->flags &= (1 << SLF_INUSE);
394         netif_start_queue(dev);
395         return 0;
396 }
397
398 /* Hook the destructor so we can free sllin devs at the right point in time */
399 static void sll_free_netdev(struct net_device *dev)
400 {
401         int i = dev->base_addr;
402         free_netdev(dev);
403         sllin_devs[i] = NULL;
404 }
405
406 static const struct net_device_ops sll_netdev_ops = {
407         .ndo_open               = sll_open,
408         .ndo_stop               = sll_close,
409         .ndo_start_xmit         = sll_xmit,
410 };
411
412 static void sll_setup(struct net_device *dev)
413 {
414         dev->netdev_ops         = &sll_netdev_ops;
415         dev->destructor         = sll_free_netdev;
416
417         dev->hard_header_len    = 0;
418         dev->addr_len           = 0;
419         dev->tx_queue_len       = 10;
420
421         dev->mtu                = sizeof(struct can_frame);
422         dev->type               = ARPHRD_CAN;
423
424         /* New-style flags. */
425         dev->flags              = IFF_NOARP;
426         dev->features           = NETIF_F_NO_CSUM;
427 }
428
429 /******************************************
430   Routines looking at TTY side.
431  ******************************************/
432
433 /*
434  * Handle the 'receiver data ready' interrupt.
435  * This function is called by the 'tty_io' module in the kernel when
436  * a block of SLLIN data has been received, which can now be decapsulated
437  * and sent on to some IP layer for further processing. This will not
438  * be re-entered while running but other ldisc functions may be called
439  * in parallel
440  */
441
442 static void sllin_receive_buf(struct tty_struct *tty,
443                               const unsigned char *cp, char *fp, int count)
444 {
445         struct sllin *sl = (struct sllin *) tty->disc_data;
446
447         printk(KERN_INFO "sllin_receive_buf invoked\n");
448
449         if (!sl || sl->magic != SLLIN_MAGIC || !netif_running(sl->dev))
450                 return;
451
452         /* Read the characters out of the buffer */
453         while (count--) {
454                 if (fp && *fp++) {
455                         if (!test_and_set_bit(SLF_ERROR, &sl->flags))
456                                 sl->dev->stats.rx_errors++;
457                         printk(KERN_INFO "sllin_receive_buf char 0x%02x ignored "
458                                 "due marker 0x%02x, flags 0x%lx\n",
459                                 *cp, *(fp-1), sl->flags);
460                         cp++;
461                         continue;
462                 }
463
464                 if (sl->rx_cnt < SLLIN_BUFF_LEN) {
465 #ifndef BREAK_BY_BAUD
466                         /* We didn't receive Break character */
467                         if ((sl->rx_cnt == SLLIN_BUFF_BREAK) && (*cp == 0x55)) {
468                                 sl->rx_buff[sl->rx_cnt++] = 0x00;
469                         }
470 #endif
471                         printk(KERN_INFO "LIN_RX[%d]: 0x%02x\n", sl->rx_cnt, *cp);
472                         sl->rx_buff[sl->rx_cnt++] = *cp++;
473                 }
474         }
475
476         if (sl->rx_cnt >= sl->rx_expect) {
477                 set_bit(SLF_RXEVENT, &sl->flags);
478                 wake_up(&sl->kwt_wq);
479                 printk(KERN_INFO "sllin_receive_buf count %d, wakeup\n", sl->rx_cnt);
480         } else {
481                 printk(KERN_INFO "sllin_receive_buf count %d, waiting\n", sl->rx_cnt);
482         }
483 }
484
485 /*****************************************
486  *  sllin message helper routines
487  *****************************************/
488
489 int sllin_setup_msg(struct sllin *sl, int mode, int id,
490                 unsigned char *data, int len)
491 {
492         if (id > 0x3f)
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  *  sllin_kwthread - kernel worker thread
630  *****************************************/
631
632 int sllin_kwthread(void *ptr)
633 {
634         struct sllin *sl = (struct sllin *)ptr;
635         struct tty_struct *tty = sl->tty;
636         struct sched_param schparam = { .sched_priority = 40 };
637         int res;
638         struct can_frame *cf;
639
640         printk(KERN_INFO "sllin: sllin_kwthread started.\n");
641         sched_setscheduler(current, SCHED_FIFO, &schparam);
642
643         clear_bit(SLF_ERROR, &sl->flags);
644         sltty_change_speed(tty, sl->lin_baud);
645
646         while (!kthread_should_stop()) {
647                 if ((sl->lin_state == SLSTATE_IDLE) && sl->lin_master &&
648                         sl->id_to_send) {
649                         if(sllin_send_break(sl) < 0) {
650                                 /* error processing */
651                         }
652                 }
653
654                 wait_event_killable(sl->kwt_wq, kthread_should_stop() ||
655                         test_bit(SLF_RXEVENT, &sl->flags) ||
656                         test_bit(SLF_TXEVENT, &sl->flags) ||
657                         ((sl->lin_state == SLSTATE_IDLE) && test_bit(SLF_MSGEVENT, &sl->flags)));
658
659                 if (test_and_clear_bit(SLF_RXEVENT, &sl->flags)) {
660                         printk(KERN_INFO "sllin_kthread RXEVENT \n");
661                 }
662
663                 if (test_and_clear_bit(SLF_TXEVENT, &sl->flags)) {
664                         printk(KERN_INFO "sllin_kthread TXEVENT \n");
665                 }
666
667                 if ((sl->lin_state == SLSTATE_IDLE) && test_bit(SLF_MSGEVENT, &sl->flags)) {
668                         cf = (struct can_frame *)sl->rec_skb->data;
669
670                         /* We do care only about SFF frames */
671                         if (cf->can_id & CAN_EFF_FLAG)
672                                 goto release_skb;
673
674                         if (cf->can_id & CAN_RTR_FLAG) {
675                                 printk(KERN_INFO "%s: RTR CAN frame, ID = %x\n",
676                                         __FUNCTION__, cf->can_id & CAN_SFF_MASK);
677                                 if (sllin_setup_msg(sl, 0, 
678                                         cf->can_id & CAN_SFF_MASK, NULL, 0) != -1) {
679                                         sl->id_to_send = true;
680                                         sl->data_to_send = false;
681                                 }
682                         } else {
683                                 printk(KERN_INFO "%s: NON-RTR CAN frame, ID = %x\n",
684                                         __FUNCTION__, (int)cf->can_id & CAN_SFF_MASK);
685
686                                 if (sllin_setup_msg(sl, 0, cf->can_id & CAN_SFF_MASK, 
687                                         cf->data, cf->can_dlc) != -1) {
688                                         sl->id_to_send = true;
689                                         sl->data_to_send = true;
690                                 }
691                         }
692
693                 release_skb:
694                         clear_bit(SLF_MSGEVENT, &sl->flags);
695                         kfree_skb(sl->rec_skb);
696                         netif_wake_queue(sl->dev);
697                 }
698
699                 switch (sl->lin_state) {
700                         case SLSTATE_BREAK_SENT:
701 #ifdef BREAK_BY_BAUD
702                                 if (sl->rx_cnt <= SLLIN_BUFF_BREAK)
703                                         continue;
704
705                                 res = sltty_change_speed(tty, sl->lin_baud);
706 #endif
707
708                                 sl->lin_state = SLSTATE_ID_SENT;
709                                 sllin_send_tx_buff(sl);
710                                 break;
711
712                         case SLSTATE_ID_SENT:
713                                 sl->id_to_send = false;
714                                 if (sl->data_to_send) {
715                                         sllin_send_tx_buff(sl);
716                                         sl->lin_state = SLSTATE_RESPONSE_SENT;
717                                         sl->rx_expect = sl->tx_lim;
718                                         goto slstate_response_sent;
719                                 } else {
720                                         sl->rx_expect = SLLIN_BUFF_DATA + 2;
721                                         sl->lin_state = SLSTATE_RESPONSE_WAIT;
722                                         goto slstate_response_wait;
723                                 }
724                                 break;
725
726                         case SLSTATE_RESPONSE_WAIT:
727                         slstate_response_wait:
728                                 if (sl->rx_cnt < sl->rx_expect)
729                                         continue;
730                         
731                                 printk(KERN_INFO "sllin: response received ID %d len %d\n",
732                                         sl->rx_buff[SLLIN_BUFF_ID], sl->rx_cnt - SLLIN_BUFF_DATA - 1);
733                                 // check checksum in sl->rx_buff
734                                 // send CAN non-RTR frame with data
735                                 sl->id_to_send = false;
736                                 sl->lin_state = SLSTATE_IDLE;
737                                 break;
738
739                         case SLSTATE_RESPONSE_SENT:
740                         slstate_response_sent:
741                                 if (sl->rx_cnt < sl->tx_lim)
742                                         continue;
743                                 
744                                 printk(KERN_INFO "sllin: response sent ID %d len %d\n",
745                                         sl->rx_buff[SLLIN_BUFF_ID], sl->rx_cnt - SLLIN_BUFF_DATA - 1);
746
747                                 sl->id_to_send = false;
748                                 sl->lin_state = SLSTATE_IDLE;
749                                 break;
750                 }
751
752
753
754                 /* sll_bump(sl); send packet to the network layer */
755
756                 /* sl->dev->stats.tx_packets++; send frames statistic */
757                 /* netif_wake_queue(sl->dev); allow next Tx packet arrival */
758         }
759
760
761         printk(KERN_INFO "sllin: sllin_kwthread stopped.\n");
762
763         return 0;
764 }
765
766
767 /************************************
768  *  sllin_open helper routines.
769  ************************************/
770
771 /* Collect hanged up channels */
772 static void sll_sync(void)
773 {
774         int i;
775         struct net_device *dev;
776         struct sllin      *sl;
777
778         for (i = 0; i < maxdev; i++) {
779                 dev = sllin_devs[i];
780                 if (dev == NULL)
781                         break;
782
783                 sl = netdev_priv(dev);
784                 if (sl->tty)
785                         continue;
786                 if (dev->flags & IFF_UP)
787                         dev_close(dev);
788         }
789 }
790
791 /* Find a free SLLIN channel, and link in this `tty' line. */
792 static struct sllin *sll_alloc(dev_t line)
793 {
794         int i;
795         struct net_device *dev = NULL;
796         struct sllin       *sl;
797
798         if (sllin_devs == NULL)
799                 return NULL;    /* Master array missing ! */
800
801         for (i = 0; i < maxdev; i++) {
802                 dev = sllin_devs[i];
803                 if (dev == NULL)
804                         break;
805
806         }
807
808         /* Sorry, too many, all slots in use */
809         if (i >= maxdev)
810                 return NULL;
811
812         if (dev) {
813                 sl = netdev_priv(dev);
814                 if (test_bit(SLF_INUSE, &sl->flags)) {
815                         unregister_netdevice(dev);
816                         dev = NULL;
817                         sllin_devs[i] = NULL;
818                 }
819         }
820
821         if (!dev) {
822                 char name[IFNAMSIZ];
823                 sprintf(name, "sllin%d", i);
824
825                 dev = alloc_netdev(sizeof(*sl), name, sll_setup);
826                 if (!dev)
827                         return NULL;
828                 dev->base_addr  = i;
829         }
830
831         sl = netdev_priv(dev);
832
833         /* Initialize channel control data */
834         sl->magic = SLLIN_MAGIC;
835         sl->dev = dev;
836         spin_lock_init(&sl->lock);
837         sllin_devs[i] = dev;
838
839         return sl;
840 }
841
842 /*
843  * Open the high-level part of the SLLIN channel.
844  * This function is called by the TTY module when the
845  * SLLIN line discipline is called for.  Because we are
846  * sure the tty line exists, we only have to link it to
847  * a free SLLIN channel...
848  *
849  * Called in process context serialized from other ldisc calls.
850  */
851
852 static int sllin_open(struct tty_struct *tty)
853 {
854         struct sllin *sl;
855         int err;
856         pr_debug("sllin: %s() invoked\n", __FUNCTION__);
857
858         if (!capable(CAP_NET_ADMIN))
859                 return -EPERM;
860
861         if (tty->ops->write == NULL)
862                 return -EOPNOTSUPP;
863
864         /* RTnetlink lock is misused here to serialize concurrent
865            opens of sllin channels. There are better ways, but it is
866            the simplest one.
867          */
868         rtnl_lock();
869
870         /* Collect hanged up channels. */
871         sll_sync();
872
873         sl = tty->disc_data;
874
875         err = -EEXIST;
876         /* First make sure we're not already connected. */
877         if (sl && sl->magic == SLLIN_MAGIC)
878                 goto err_exit;
879
880         /* OK.  Find a free SLLIN channel to use. */
881         err = -ENFILE;
882         sl = sll_alloc(tty_devnum(tty));
883         if (sl == NULL)
884                 goto err_exit;
885
886         sl->tty = tty;
887         tty->disc_data = sl;
888         sl->line = tty_devnum(tty);
889
890         if (!test_bit(SLF_INUSE, &sl->flags)) {
891                 /* Perform the low-level SLLIN initialization. */
892                 sl->lin_master = true;
893
894                 sl->rx_cnt = 0;
895                 sl->rx_expect = 0;
896                 sl->rx_lim = sl->lin_master ? 0 : SLLIN_BUFF_LEN;
897                 sl->tx_cnt = 0;
898                 sl->tx_lim = 0;
899                 sl->id_to_send = false;
900                 sl->data_to_send = false;
901
902                 sl->lin_baud  = 19200;
903
904                 sl->lin_state = SLSTATE_IDLE;
905
906                 set_bit(SLF_INUSE, &sl->flags);
907
908                 init_waitqueue_head(&sl->kwt_wq);
909                 sl->kwthread = kthread_run(sllin_kwthread, sl, "sllin");
910                 if (sl->kwthread == NULL)
911                         goto err_free_chan;
912
913                 err = register_netdevice(sl->dev);
914                 if (err)
915                         goto err_free_chan_and_thread;
916         }
917
918         /* Done.  We have linked the TTY line to a channel. */
919         rtnl_unlock();
920         tty->receive_room = SLLIN_BUFF_LEN * 40;        /* We don't flow control */
921
922         /* TTY layer expects 0 on success */
923         return 0;
924
925 err_free_chan_and_thread:
926         kthread_stop(sl->kwthread);
927         sl->kwthread = NULL;
928
929 err_free_chan:
930         sl->tty = NULL;
931         tty->disc_data = NULL;
932         clear_bit(SLF_INUSE, &sl->flags);
933
934 err_exit:
935         rtnl_unlock();
936
937         /* Count references from TTY module */
938         return err;
939 }
940
941 /*
942  * Close down a SLLIN channel.
943  * This means flushing out any pending queues, and then returning. This
944  * call is serialized against other ldisc functions.
945  *
946  * We also use this method for a hangup event.
947  */
948
949 static void sllin_close(struct tty_struct *tty)
950 {
951         struct sllin *sl = (struct sllin *) tty->disc_data;
952
953         /* First make sure we're connected. */
954         if (!sl || sl->magic != SLLIN_MAGIC || sl->tty != tty)
955                 return;
956
957         kthread_stop(sl->kwthread);
958         sl->kwthread = NULL;
959
960         tty->disc_data = NULL;
961         sl->tty = NULL;
962
963         /* Flush network side */
964         unregister_netdev(sl->dev);
965         /* This will complete via sl_free_netdev */
966 }
967
968 static int sllin_hangup(struct tty_struct *tty)
969 {
970         sllin_close(tty);
971         return 0;
972 }
973
974 /* Perform I/O control on an active SLLIN channel. */
975 static int sllin_ioctl(struct tty_struct *tty, struct file *file,
976                        unsigned int cmd, unsigned long arg)
977 {
978         struct sllin *sl = (struct sllin *) tty->disc_data;
979         unsigned int tmp;
980
981         /* First make sure we're connected. */
982         if (!sl || sl->magic != SLLIN_MAGIC)
983                 return -EINVAL;
984
985         switch (cmd) {
986         case SIOCGIFNAME:
987                 tmp = strlen(sl->dev->name) + 1;
988                 if (copy_to_user((void __user *)arg, sl->dev->name, tmp))
989                         return -EFAULT;
990                 return 0;
991
992         case SIOCSIFHWADDR:
993                 return -EINVAL;
994
995         default:
996                 return tty_mode_ioctl(tty, file, cmd, arg);
997         }
998 }
999
1000 static struct tty_ldisc_ops sll_ldisc = {
1001         .owner          = THIS_MODULE,
1002         .magic          = TTY_LDISC_MAGIC,
1003         .name           = "sllin",
1004         .open           = sllin_open,
1005         .close          = sllin_close,
1006         .hangup         = sllin_hangup,
1007         .ioctl          = sllin_ioctl,
1008         .receive_buf    = sllin_receive_buf,
1009         .write_wakeup   = sllin_write_wakeup,
1010 };
1011
1012 static int __init sllin_init(void)
1013 {
1014         int status;
1015
1016         if (maxdev < 4)
1017                 maxdev = 4; /* Sanity */
1018
1019         printk(banner);
1020         printk(KERN_INFO "sllin: %d dynamic interface channels.\n", maxdev);
1021
1022         sllin_devs = kzalloc(sizeof(struct net_device *)*maxdev, GFP_KERNEL);
1023         if (!sllin_devs) {
1024                 printk(KERN_ERR "sllin: can't allocate sllin device array!\n");
1025                 return -ENOMEM;
1026         }
1027
1028         /* Fill in our line protocol discipline, and register it */
1029         status = tty_register_ldisc(N_SLLIN, &sll_ldisc);
1030         if (status)  {
1031                 printk(KERN_ERR "sllin: can't register line discipline\n");
1032                 kfree(sllin_devs);
1033         }
1034         return status;
1035 }
1036
1037 static void __exit sllin_exit(void)
1038 {
1039         int i;
1040         struct net_device *dev;
1041         struct sllin *sl;
1042         unsigned long timeout = jiffies + HZ;
1043         int busy = 0;
1044
1045         if (sllin_devs == NULL)
1046                 return;
1047
1048         /* First of all: check for active disciplines and hangup them.
1049          */
1050         do {
1051                 if (busy)
1052                         msleep_interruptible(100);
1053
1054                 busy = 0;
1055                 for (i = 0; i < maxdev; i++) {
1056                         dev = sllin_devs[i];
1057                         if (!dev)
1058                                 continue;
1059                         sl = netdev_priv(dev);
1060                         spin_lock_bh(&sl->lock);
1061                         if (sl->tty) {
1062                                 busy++;
1063                                 tty_hangup(sl->tty);
1064                         }
1065                         spin_unlock_bh(&sl->lock);
1066                 }
1067         } while (busy && time_before(jiffies, timeout));
1068
1069         /* FIXME: hangup is async so we should wait when doing this second
1070            phase */
1071
1072         for (i = 0; i < maxdev; i++) {
1073                 dev = sllin_devs[i];
1074                 if (!dev)
1075                         continue;
1076                 sllin_devs[i] = NULL;
1077
1078                 sl = netdev_priv(dev);
1079                 if (sl->tty) {
1080                         printk(KERN_ERR "%s: tty discipline still running\n",
1081                                dev->name);
1082                         /* Intentionally leak the control block. */
1083                         dev->destructor = NULL;
1084                 }
1085
1086                 unregister_netdev(dev);
1087         }
1088
1089         kfree(sllin_devs);
1090         sllin_devs = NULL;
1091
1092         i = tty_unregister_ldisc(N_SLLIN);
1093         if (i)
1094                 printk(KERN_ERR "sllin: can't unregister ldisc (err %d)\n", i);
1095 }
1096
1097 module_init(sllin_init);
1098 module_exit(sllin_exit);