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