]> rtime.felk.cvut.cz Git - linux-lin.git/blob - sllin/sllin.c
Merge branch 'master' of ssh://rtime.felk.cvut.cz/lisovros/pcan_lin
[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
75 static int maxdev = 10;         /* MAX number of SLLIN channels;
76                                    This can be overridden with
77                                    insmod sllin.ko maxdev=nnn   */
78 module_param(maxdev, int, 0);
79 MODULE_PARM_DESC(maxdev, "Maximum number of sllin interfaces");
80
81 /* maximum buffer len to store whole LIN message*/
82 #define SLLIN_DATA_MAX   8
83 #define SLLIN_BUFF_LEN  (1 /*break*/ + 1 /*sync*/ + 1 /*ID*/ + \
84                          SLLIN_DATA_MAX + 1 /*checksum*/)
85 #define SLLIN_BUFF_BREAK 0
86 #define SLLIN_BUFF_SYNC  1
87 #define SLLIN_BUFF_ID    2
88 #define SLLIN_BUFF_DATA  3
89
90 enum slstate {
91         SLSTATE_IDLE = 0,
92         SLSTATE_BREAK_SENT,
93         SLSTATE_ID_SENT,
94         SLSTATE_RESPONSE_WAIT,
95         SLSTATE_RESPONSE_SENT,
96 };
97
98 struct sllin {
99         int                     magic;
100
101         /* Various fields. */
102         struct tty_struct       *tty;           /* ptr to TTY structure      */
103         struct net_device       *dev;           /* easy for intr handling    */
104         spinlock_t              lock;
105
106         /* LIN message buffer and actual processed data counts */
107         unsigned char           rx_buff[SLLIN_BUFF_LEN]; /* LIN Rx buffer */
108         unsigned char           tx_buff[SLLIN_BUFF_LEN]; /* LIN Tx buffer */
109         int                     rx_expect;      /* expected number of Rx chars */
110         int                     rx_lim;         /* maximum Rx chars for ID  */
111         int                     rx_cnt;         /* message buffer Rx fill level  */
112         int                     tx_lim;         /* actual limit of bytes to Tx */
113         int                     tx_cnt;         /* number of already Tx bytes */
114         char                    lin_master;     /* node is a master node */
115         int                     lin_baud;       /* LIN baudrate */
116         int                     lin_state;      /* state */
117         int                     id_to_send;     /* there is ID to be sent */
118
119         unsigned long           flags;          /* Flag values/ mode etc     */
120 #define SLF_INUSE               0               /* Channel in use            */
121 #define SLF_ERROR               1               /* Parity, etc. error        */
122 #define SLF_RXEVENT             2               /* Rx wake event             */
123 #define SLF_TXEVENT             3               /* Tx wake event             */
124 #define SLF_MSGEVENT            4               /* CAN message to sent       */
125
126         dev_t                   line;
127         struct task_struct      *kwthread;
128         wait_queue_head_t       kwt_wq;
129 };
130
131 static struct net_device **sllin_devs;
132
133 const unsigned char sllin_id_parity_table[] = {
134         0x80,0xc0,0x40,0x00,0xc0,0x80,0x00,0x40,
135         0x00,0x40,0xc0,0x80,0x40,0x00,0x80,0xc0,
136         0x40,0x00,0x80,0xc0,0x00,0x40,0xc0,0x80,
137         0xc0,0x80,0x00,0x40,0x80,0xc0,0x40,0x00,
138         0x00,0x40,0xc0,0x80,0x40,0x00,0x80,0xc0,
139         0x80,0xc0,0x40,0x00,0xc0,0x80,0x00,0x40,
140         0xc0,0x80,0x00,0x40,0x80,0xc0,0x40,0x00,
141         0x40,0x00,0x80,0xc0,0x00,0x40,0xc0,0x80
142 };
143
144 static int sltty_change_speed(struct tty_struct *tty, unsigned speed)
145 {
146         struct ktermios old_termios;
147         int cflag;
148
149         mutex_lock(&tty->termios_mutex);
150
151         old_termios = *(tty->termios);
152         cflag = tty->termios->c_cflag;
153         cflag &= ~(CBAUD | CIBAUD);
154         cflag |= BOTHER;
155         tty->termios->c_cflag = cflag;
156
157         tty_encode_baud_rate(tty, speed, speed);
158
159         if (tty->ops->set_termios)
160                 tty->ops->set_termios(tty, &old_termios);
161         //priv->io.speed = speed;
162         mutex_unlock(&tty->termios_mutex);
163
164         return 0;
165 }
166
167
168 /* Send one completely decapsulated can_frame to the network layer */
169 static void sll_bump(struct sllin *sl)
170 {
171 //      struct sk_buff *skb;
172 //      struct can_frame cf;
173 //      int i, dlc_pos, tmp;
174 //      unsigned long ultmp;
175 //      char cmd = sl->rbuff[0];
176 //
177 //      if ((cmd != 't') && (cmd != 'T') && (cmd != 'r') && (cmd != 'R'))
178 //              return;
179 //
180 //      if (cmd & 0x20) /* tiny chars 'r' 't' => standard frame format */
181 //              dlc_pos = 4; /* dlc position tiiid */
182 //      else
183 //              dlc_pos = 9; /* dlc position Tiiiiiiiid */
184 //
185 //      if (!((sl->rbuff[dlc_pos] >= '0') && (sl->rbuff[dlc_pos] < '9')))
186 //              return;
187 //
188 //      cf.can_dlc = sl->rbuff[dlc_pos] - '0'; /* get can_dlc from ASCII val */
189 //
190 //      sl->rbuff[dlc_pos] = 0; /* terminate can_id string */
191 //
192 //      if (strict_strtoul(sl->rbuff+1, 16, &ultmp))
193 //              return;
194 //
195 //      cf.can_id = ultmp;
196 //
197 //      if (!(cmd & 0x20)) /* NO tiny chars => extended frame format */
198 //              cf.can_id |= CAN_EFF_FLAG;
199 //
200 //      if ((cmd | 0x20) == 'r') /* RTR frame */
201 //              cf.can_id |= CAN_RTR_FLAG;
202 //
203 //      *(u64 *) (&cf.data) = 0; /* clear payload */
204 //
205 //      for (i = 0, dlc_pos++; i < cf.can_dlc; i++) {
206 //
207 //              tmp = asc2nibble(sl->rbuff[dlc_pos++]);
208 //              if (tmp > 0x0F)
209 //                      return;
210 //              cf.data[i] = (tmp << 4);
211 //              tmp = asc2nibble(sl->rbuff[dlc_pos++]);
212 //              if (tmp > 0x0F)
213 //                      return;
214 //              cf.data[i] |= tmp;
215 //      }
216 //
217 //
218 //      skb = dev_alloc_skb(sizeof(struct can_frame));
219 //      if (!skb)
220 //              return;
221 //
222 //      skb->dev = sl->dev;
223 //      skb->protocol = htons(ETH_P_CAN);
224 //      skb->pkt_type = PACKET_BROADCAST;
225 //      skb->ip_summed = CHECKSUM_UNNECESSARY;
226 //      memcpy(skb_put(skb, sizeof(struct can_frame)),
227 //             &cf, sizeof(struct can_frame));
228 //      netif_rx(skb);
229 //
230 //      sl->dev->stats.rx_packets++;
231 //      sl->dev->stats.rx_bytes += cf.can_dlc;
232 }
233
234
235  /************************************************************************
236   *                     STANDARD SLLIN ENCAPSULATION                     *
237   ************************************************************************/
238
239 /* Convert particular CAN frame into LIN frame and send it to TTY queue. */
240 static void sll_encaps(struct sllin *sl, struct can_frame *cf)
241 {
242         int actual, idx, i;
243         char lframe[16] = {0x00, 0x55}; /* Fake break, Sync byte */
244         struct tty_struct *tty = sl->tty;
245
246         pr_debug("sllin: %s() invoked\n", __FUNCTION__);
247
248         /* We do care only about SFF frames */
249         if (cf->can_id & CAN_EFF_FLAG)
250                 return;
251
252         /* Send only header */
253         if (cf->can_id & CAN_RTR_FLAG) {
254                 pr_debug("sllin: %s() RTR CAN frame\n", __FUNCTION__);
255                 lframe[2] = (u8)cf->can_id; /* Get one byte LIN ID */
256
257                 sltty_change_speed(tty, sl->lin_baud * 2 / 3);
258                 tty->ops->write(tty, &lframe[0], 1);
259                 sltty_change_speed(tty, sl->lin_baud);
260                 tty->ops->write(tty, &lframe[1], 1);
261                 tty->ops->write(tty, &lframe[2], 1);
262         } else {
263                 pr_debug("sllin: %s() non-RTR CAN frame\n", __FUNCTION__);
264                 /*      idx = strlen(sl->xbuff);
265
266                         for (i = 0; i < cf->can_dlc; i++)
267                         sprintf(&sl->xbuff[idx + 2*i], "%02X", cf->data[i]);
268
269                  * Order of next two lines is *very* important.
270                  * When we are sending a little amount of data,
271                  * the transfer may be completed inside the ops->write()
272                  * routine, because it's running with interrupts enabled.
273                  * In this case we *never* got WRITE_WAKEUP event,
274                  * if we did not request it before write operation.
275                  *       14 Oct 1994  Dmitry Gorodchanin.
276
277                  set_bit(TTY_DO_WRITE_WAKEUP, &sl->tty->flags);
278                  actual = sl->tty->ops->write(sl->tty, sl->xbuff, strlen(sl->xbuff));
279                  sl->xleft = strlen(sl->xbuff) - actual;
280                  sl->xhead = sl->xbuff + actual;
281                  sl->dev->stats.tx_bytes += cf->can_dlc;
282                  */
283         }
284
285 }
286
287 /*
288  * Called by the driver when there's room for more data.  If we have
289  * more packets to send, we send them here.
290  */
291 static void sllin_write_wakeup(struct tty_struct *tty)
292 {
293         int actual;
294         int remains;
295         struct sllin *sl = (struct sllin *) tty->disc_data;
296
297         /* First make sure we're connected. */
298         if (!sl || sl->magic != SLLIN_MAGIC || !netif_running(sl->dev))
299                 return;
300
301         if (sl->lin_state != SLSTATE_BREAK_SENT)
302                 remains = sl->tx_lim - sl->tx_cnt;
303         else
304                 remains = SLLIN_BUFF_BREAK + 1 - sl->tx_cnt;
305
306         if (remains > 0) {
307                 actual = tty->ops->write(tty, sl->tx_buff + sl->tx_cnt, sl->tx_cnt - sl->tx_lim);
308                 sl->tx_cnt += actual;
309
310                 if (sl->tx_cnt < sl->tx_lim) {
311                         printk(KERN_INFO "sllin_write_wakeup sent %d, remains %d, waiting\n",
312                                 sl->tx_cnt, sl->tx_lim - sl->tx_cnt);
313                         return;
314                 }
315         }
316
317         clear_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
318         set_bit(SLF_TXEVENT, &sl->flags);
319         wake_up(&sl->kwt_wq);
320
321         printk(KERN_INFO "sllin_write_wakeup sent %d, wakeup\n", sl->tx_cnt);
322 }
323
324 /* Send a can_frame to a TTY queue. */
325 static netdev_tx_t sll_xmit(struct sk_buff *skb, struct net_device *dev)
326 {
327         struct sllin *sl = netdev_priv(dev);
328
329         if (skb->len != sizeof(struct can_frame))
330                 goto out;
331
332         spin_lock(&sl->lock);
333         if (!netif_running(dev))  {
334                 spin_unlock(&sl->lock);
335                 printk(KERN_WARNING "%s: xmit: iface is down\n", dev->name);
336                 goto out;
337         }
338         if (sl->tty == NULL) {
339                 spin_unlock(&sl->lock);
340                 goto out;
341         }
342
343         netif_stop_queue(sl->dev);
344         sll_encaps(sl, (struct can_frame *) skb->data); /* encaps & send */
345         spin_unlock(&sl->lock);
346
347 out:
348         kfree_skb(skb);
349         return NETDEV_TX_OK;
350 }
351
352
353 /******************************************
354  *   Routines looking at netdevice side.
355  ******************************************/
356
357 /* Netdevice UP -> DOWN routine */
358 static int sll_close(struct net_device *dev)
359 {
360         struct sllin *sl = netdev_priv(dev);
361
362         spin_lock_bh(&sl->lock);
363         if (sl->tty) {
364                 /* TTY discipline is running. */
365                 clear_bit(TTY_DO_WRITE_WAKEUP, &sl->tty->flags);
366         }
367         netif_stop_queue(dev);
368         sl->rx_expect = 0;
369         sl->tx_lim    = 0;
370         spin_unlock_bh(&sl->lock);
371
372         return 0;
373 }
374
375 /* Netdevice DOWN -> UP routine */
376 static int sll_open(struct net_device *dev)
377 {
378         struct sllin *sl = netdev_priv(dev);
379
380         pr_debug("sllin: %s() invoked\n", __FUNCTION__);
381
382         if (sl->tty == NULL)
383                 return -ENODEV;
384
385         sl->flags &= (1 << SLF_INUSE);
386         netif_start_queue(dev);
387         return 0;
388 }
389
390 /* Hook the destructor so we can free sllin devs at the right point in time */
391 static void sll_free_netdev(struct net_device *dev)
392 {
393         int i = dev->base_addr;
394         free_netdev(dev);
395         sllin_devs[i] = NULL;
396 }
397
398 static const struct net_device_ops sll_netdev_ops = {
399         .ndo_open               = sll_open,
400         .ndo_stop               = sll_close,
401         .ndo_start_xmit         = sll_xmit,
402 };
403
404 static void sll_setup(struct net_device *dev)
405 {
406         dev->netdev_ops         = &sll_netdev_ops;
407         dev->destructor         = sll_free_netdev;
408
409         dev->hard_header_len    = 0;
410         dev->addr_len           = 0;
411         dev->tx_queue_len       = 10;
412
413         dev->mtu                = sizeof(struct can_frame);
414         dev->type               = ARPHRD_CAN;
415
416         /* New-style flags. */
417         dev->flags              = IFF_NOARP;
418         dev->features           = NETIF_F_NO_CSUM;
419 }
420
421 /******************************************
422   Routines looking at TTY side.
423  ******************************************/
424
425 /*
426  * Handle the 'receiver data ready' interrupt.
427  * This function is called by the 'tty_io' module in the kernel when
428  * a block of SLLIN data has been received, which can now be decapsulated
429  * and sent on to some IP layer for further processing. This will not
430  * be re-entered while running but other ldisc functions may be called
431  * in parallel
432  */
433
434 static void sllin_receive_buf(struct tty_struct *tty,
435                               const unsigned char *cp, char *fp, int count)
436 {
437         struct sllin *sl = (struct sllin *) tty->disc_data;
438
439         printk(KERN_INFO "sllin_receive_buf invoked\n");
440
441         if (!sl || sl->magic != SLLIN_MAGIC || !netif_running(sl->dev))
442                 return;
443
444         /* Read the characters out of the buffer */
445         while (count--) {
446                 if (fp && *fp++) {
447                         if (!test_and_set_bit(SLF_ERROR, &sl->flags))
448                                 sl->dev->stats.rx_errors++;
449                         printk(KERN_INFO "sllin_receive_buf char 0x%02x ignored due marker 0x%02x, flags 0x%lx\n",
450                                 *cp, *(fp-1), sl->flags);
451                         cp++;
452                         continue;
453                 }
454
455                 if (sl->rx_cnt < SLLIN_BUFF_LEN)  {
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
473 int sllin_setup_msg(struct sllin *sl, int mode, int id,
474                 unsigned char *data, int len)
475 {
476         if (id > 0x3f)
477                 return -1;
478
479         sl->rx_cnt = 0;
480         sl->tx_cnt = 0;
481         sl->rx_expect = 0;
482
483         sl->tx_buff[SLLIN_BUFF_BREAK] = 0;
484         sl->tx_buff[SLLIN_BUFF_SYNC]  = 0x55;
485         sl->tx_buff[SLLIN_BUFF_ID]    = id | sllin_id_parity_table[id];
486         sl->tx_lim = SLLIN_BUFF_DATA;
487
488         if ((data != NULL) && len) {
489                 int i;
490                 unsigned csum  = 0;
491
492                 sl->tx_lim += len;
493                 memcpy(sl->tx_buff + SLLIN_BUFF_DATA, data, len);
494                 /* compute data parity there */
495                 for (i = SLLIN_BUFF_DATA; i < sl->tx_lim; i++) {
496                         csum += sl->tx_buff[i];
497                         if (csum > 255)
498                                 csum -= 255;
499                 }
500
501                 sl->tx_buff[sl->tx_lim++] = csum;
502         }
503         if (len != 0)
504                 sl->rx_lim += len + 1;
505
506         return 0;
507 }
508
509
510 int sllin_send_tx_buff(struct sllin *sl)
511 {
512         struct tty_struct *tty = sl->tty;
513         int remains;
514         int res;
515
516         if (sl->lin_state != SLSTATE_BREAK_SENT)
517                 remains = sl->tx_lim - sl->tx_cnt;
518         else
519                 remains = 1;
520
521
522         res = tty->ops->write(tty, sl->tx_buff + sl->tx_cnt, remains);
523         if (res < 0)
524                 return -1;
525
526         remains -= res;
527         sl->tx_cnt += res;
528
529         if (remains > 0) {
530                 set_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
531                 res = tty->ops->write(tty, sl->tx_buff + sl->tx_cnt, remains);
532                 if (res < 0) {
533                         clear_bit(TTY_DO_WRITE_WAKEUP, &tty->flags);
534                         return -1;
535                 }
536                 
537                 remains -= res;
538                 sl->tx_cnt += res;
539         }
540
541         printk(KERN_INFO "sllin_send_tx_buff sent %d, remains %d\n",
542                         sl->tx_cnt, remains);
543
544         return 0;
545 }
546
547 int sllin_send_break(struct sllin *sl)
548 {
549         struct tty_struct *tty = sl->tty;
550         unsigned long break_baud = sl->lin_baud;
551         int res;
552
553         //break_baud = (break_baud * 8) / 14;
554         break_baud /= 2;
555
556         sltty_change_speed(tty, break_baud);
557
558         sl->rx_expect = SLLIN_BUFF_BREAK + 1;
559
560         sl->lin_state = SLSTATE_BREAK_SENT;
561
562         res = sllin_send_tx_buff(sl);
563         if (res < 0) {
564                 sl->lin_state = SLSTATE_IDLE;
565                 return res;
566         }
567
568         return 0;
569 }
570
571 /*****************************************
572  *  sllin_kwthread - kernel worker thread
573  *****************************************/
574
575 int sllin_kwthread(void *ptr)
576 {
577         struct sllin *sl = (struct sllin *)ptr;
578         struct tty_struct *tty = sl->tty;
579         int res;
580
581         printk(KERN_INFO "sllin: sllin_kwthread started.\n");
582
583         clear_bit(SLF_ERROR, &sl->flags);
584
585         sltty_change_speed(tty, sl->lin_baud);
586
587         sllin_setup_msg(sl, 0, 0x33, NULL, 0);
588         sl->id_to_send = 1;
589
590         while (!kthread_should_stop()) {
591
592                 if ((sl->lin_state == SLSTATE_IDLE) && sl->lin_master &&
593                         sl->id_to_send) {
594                         if(sllin_send_break(sl)<0) {
595                                 /* error processing */
596                         }
597
598                 }
599
600                 wait_event_killable(sl->kwt_wq, kthread_should_stop() ||
601                         test_bit(SLF_RXEVENT, &sl->flags) ||
602                         test_bit(SLF_TXEVENT, &sl->flags));
603
604                 if (test_and_clear_bit(SLF_RXEVENT, &sl->flags)) {
605                         printk(KERN_INFO "sllin_kthread RXEVENT \n");
606                 }
607
608                 if (test_and_clear_bit(SLF_TXEVENT, &sl->flags)) {
609                         printk(KERN_INFO "sllin_kthread TXEVENT \n");
610                 }
611
612                 switch (sl->lin_state) {
613                         case SLSTATE_BREAK_SENT:
614                                 if (sl->rx_cnt <= SLLIN_BUFF_BREAK)
615                                         continue;
616
617                                 res = sltty_change_speed(tty, sl->lin_baud);
618
619                                 sllin_send_tx_buff(sl);
620
621                                 sl->lin_state = SLSTATE_ID_SENT;
622
623                                 break;
624                         case SLSTATE_ID_SENT:
625                                 sl->id_to_send = 0;
626                                 sl->lin_state = SLSTATE_IDLE;
627                                 break;
628                 }
629
630
631
632                 /* sll_bump(sl); send packet to the network layer */
633
634                 /* sl->dev->stats.tx_packets++; send frames statistic */
635                 /* netif_wake_queue(sl->dev); allow next Tx packet arrival */
636         }
637
638
639         printk(KERN_INFO "sllin: sllin_kwthread stopped.\n");
640
641         return 0;
642 }
643
644
645 /************************************
646  *  sllin_open helper routines.
647  ************************************/
648
649 /* Collect hanged up channels */
650 static void sll_sync(void)
651 {
652         int i;
653         struct net_device *dev;
654         struct sllin      *sl;
655
656         for (i = 0; i < maxdev; i++) {
657                 dev = sllin_devs[i];
658                 if (dev == NULL)
659                         break;
660
661                 sl = netdev_priv(dev);
662                 if (sl->tty)
663                         continue;
664                 if (dev->flags & IFF_UP)
665                         dev_close(dev);
666         }
667 }
668
669 /* Find a free SLLIN channel, and link in this `tty' line. */
670 static struct sllin *sll_alloc(dev_t line)
671 {
672         int i;
673         struct net_device *dev = NULL;
674         struct sllin       *sl;
675
676         if (sllin_devs == NULL)
677                 return NULL;    /* Master array missing ! */
678
679         for (i = 0; i < maxdev; i++) {
680                 dev = sllin_devs[i];
681                 if (dev == NULL)
682                         break;
683
684         }
685
686         /* Sorry, too many, all slots in use */
687         if (i >= maxdev)
688                 return NULL;
689
690         if (dev) {
691                 sl = netdev_priv(dev);
692                 if (test_bit(SLF_INUSE, &sl->flags)) {
693                         unregister_netdevice(dev);
694                         dev = NULL;
695                         sllin_devs[i] = NULL;
696                 }
697         }
698
699         if (!dev) {
700                 char name[IFNAMSIZ];
701                 sprintf(name, "sllin%d", i);
702
703                 dev = alloc_netdev(sizeof(*sl), name, sll_setup);
704                 if (!dev)
705                         return NULL;
706                 dev->base_addr  = i;
707         }
708
709         sl = netdev_priv(dev);
710
711         /* Initialize channel control data */
712         sl->magic = SLLIN_MAGIC;
713         sl->dev = dev;
714         spin_lock_init(&sl->lock);
715         sllin_devs[i] = dev;
716
717         return sl;
718 }
719
720 /*
721  * Open the high-level part of the SLLIN channel.
722  * This function is called by the TTY module when the
723  * SLLIN line discipline is called for.  Because we are
724  * sure the tty line exists, we only have to link it to
725  * a free SLLIN channel...
726  *
727  * Called in process context serialized from other ldisc calls.
728  */
729
730 static int sllin_open(struct tty_struct *tty)
731 {
732         struct sllin *sl;
733         int err;
734         pr_debug("sllin: %s() invoked\n", __FUNCTION__);
735
736         if (!capable(CAP_NET_ADMIN))
737                 return -EPERM;
738
739         if (tty->ops->write == NULL)
740                 return -EOPNOTSUPP;
741
742         /* RTnetlink lock is misused here to serialize concurrent
743            opens of sllin channels. There are better ways, but it is
744            the simplest one.
745          */
746         rtnl_lock();
747
748         /* Collect hanged up channels. */
749         sll_sync();
750
751         sl = tty->disc_data;
752
753         err = -EEXIST;
754         /* First make sure we're not already connected. */
755         if (sl && sl->magic == SLLIN_MAGIC)
756                 goto err_exit;
757
758         /* OK.  Find a free SLLIN channel to use. */
759         err = -ENFILE;
760         sl = sll_alloc(tty_devnum(tty));
761         if (sl == NULL)
762                 goto err_exit;
763
764         sl->tty = tty;
765         tty->disc_data = sl;
766         sl->line = tty_devnum(tty);
767
768         if (!test_bit(SLF_INUSE, &sl->flags)) {
769                 /* Perform the low-level SLLIN initialization. */
770                 sl->rx_cnt    = 0;
771                 sl->rx_expect = 0;
772                 sl->tx_cnt    = 0;
773                 sl->tx_lim    = 0;
774
775                 sl->lin_baud  = 2400;
776
777                 sl->lin_master = 1;
778                 sl->lin_state = SLSTATE_IDLE;
779
780                 set_bit(SLF_INUSE, &sl->flags);
781
782                 init_waitqueue_head(&sl->kwt_wq);
783                 sl->kwthread = kthread_run(sllin_kwthread, sl, "sllin");
784                 if (sl->kwthread == NULL)
785                         goto err_free_chan;
786
787                 err = register_netdevice(sl->dev);
788                 if (err)
789                         goto err_free_chan_and_thread;
790         }
791
792         /* Done.  We have linked the TTY line to a channel. */
793         rtnl_unlock();
794         tty->receive_room = SLLIN_BUFF_LEN * 40;        /* We don't flow control */
795
796         /* TTY layer expects 0 on success */
797         return 0;
798
799 err_free_chan_and_thread:
800         kthread_stop(sl->kwthread);
801         sl->kwthread = NULL;
802
803 err_free_chan:
804         sl->tty = NULL;
805         tty->disc_data = NULL;
806         clear_bit(SLF_INUSE, &sl->flags);
807
808 err_exit:
809         rtnl_unlock();
810
811         /* Count references from TTY module */
812         return err;
813 }
814
815 /*
816  * Close down a SLLIN channel.
817  * This means flushing out any pending queues, and then returning. This
818  * call is serialized against other ldisc functions.
819  *
820  * We also use this method for a hangup event.
821  */
822
823 static void sllin_close(struct tty_struct *tty)
824 {
825         struct sllin *sl = (struct sllin *) tty->disc_data;
826
827         /* First make sure we're connected. */
828         if (!sl || sl->magic != SLLIN_MAGIC || sl->tty != tty)
829                 return;
830
831         kthread_stop(sl->kwthread);
832         sl->kwthread = NULL;
833
834         tty->disc_data = NULL;
835         sl->tty = NULL;
836
837         /* Flush network side */
838         unregister_netdev(sl->dev);
839         /* This will complete via sl_free_netdev */
840 }
841
842 static int sllin_hangup(struct tty_struct *tty)
843 {
844         sllin_close(tty);
845         return 0;
846 }
847
848 /* Perform I/O control on an active SLLIN channel. */
849 static int sllin_ioctl(struct tty_struct *tty, struct file *file,
850                        unsigned int cmd, unsigned long arg)
851 {
852         struct sllin *sl = (struct sllin *) tty->disc_data;
853         unsigned int tmp;
854
855         /* First make sure we're connected. */
856         if (!sl || sl->magic != SLLIN_MAGIC)
857                 return -EINVAL;
858
859         switch (cmd) {
860         case SIOCGIFNAME:
861                 tmp = strlen(sl->dev->name) + 1;
862                 if (copy_to_user((void __user *)arg, sl->dev->name, tmp))
863                         return -EFAULT;
864                 return 0;
865
866         case SIOCSIFHWADDR:
867                 return -EINVAL;
868
869         default:
870                 return tty_mode_ioctl(tty, file, cmd, arg);
871         }
872 }
873
874 static struct tty_ldisc_ops sll_ldisc = {
875         .owner          = THIS_MODULE,
876         .magic          = TTY_LDISC_MAGIC,
877         .name           = "sllin",
878         .open           = sllin_open,
879         .close          = sllin_close,
880         .hangup         = sllin_hangup,
881         .ioctl          = sllin_ioctl,
882         .receive_buf    = sllin_receive_buf,
883         .write_wakeup   = sllin_write_wakeup,
884 };
885
886 static int __init sllin_init(void)
887 {
888         int status;
889
890         if (maxdev < 4)
891                 maxdev = 4; /* Sanity */
892
893         printk(banner);
894         printk(KERN_INFO "sllin: %d dynamic interface channels.\n", maxdev);
895
896         sllin_devs = kzalloc(sizeof(struct net_device *)*maxdev, GFP_KERNEL);
897         if (!sllin_devs) {
898                 printk(KERN_ERR "sllin: can't allocate sllin device array!\n");
899                 return -ENOMEM;
900         }
901
902         /* Fill in our line protocol discipline, and register it */
903         status = tty_register_ldisc(N_SLLIN, &sll_ldisc);
904         if (status)  {
905                 printk(KERN_ERR "sllin: can't register line discipline\n");
906                 kfree(sllin_devs);
907         }
908         return status;
909 }
910
911 static void __exit sllin_exit(void)
912 {
913         int i;
914         struct net_device *dev;
915         struct sllin *sl;
916         unsigned long timeout = jiffies + HZ;
917         int busy = 0;
918
919         if (sllin_devs == NULL)
920                 return;
921
922         /* First of all: check for active disciplines and hangup them.
923          */
924         do {
925                 if (busy)
926                         msleep_interruptible(100);
927
928                 busy = 0;
929                 for (i = 0; i < maxdev; i++) {
930                         dev = sllin_devs[i];
931                         if (!dev)
932                                 continue;
933                         sl = netdev_priv(dev);
934                         spin_lock_bh(&sl->lock);
935                         if (sl->tty) {
936                                 busy++;
937                                 tty_hangup(sl->tty);
938                         }
939                         spin_unlock_bh(&sl->lock);
940                 }
941         } while (busy && time_before(jiffies, timeout));
942
943         /* FIXME: hangup is async so we should wait when doing this second
944            phase */
945
946         for (i = 0; i < maxdev; i++) {
947                 dev = sllin_devs[i];
948                 if (!dev)
949                         continue;
950                 sllin_devs[i] = NULL;
951
952                 sl = netdev_priv(dev);
953                 if (sl->tty) {
954                         printk(KERN_ERR "%s: tty discipline still running\n",
955                                dev->name);
956                         /* Intentionally leak the control block. */
957                         dev->destructor = NULL;
958                 }
959
960                 unregister_netdev(dev);
961         }
962
963         kfree(sllin_devs);
964         sllin_devs = NULL;
965
966         i = tty_unregister_ldisc(N_SLLIN);
967         if (i)
968                 printk(KERN_ERR "sllin: can't unregister ldisc (err %d)\n", i);
969 }
970
971 module_init(sllin_init);
972 module_exit(sllin_exit);