Linux-2.6.12-rc2
[safe/jmp/linux-2.6] / net / wanrouter / af_wanpipe.c
1 /*****************************************************************************
2 * af_wanpipe.c  WANPIPE(tm) Secure Socket Layer.
3 *
4 * Author:       Nenad Corbic    <ncorbic@sangoma.com>
5 *
6 * Copyright:    (c) 2000 Sangoma Technologies Inc.
7 *
8 *               This program is free software; you can redistribute it and/or
9 *               modify it under the terms of the GNU General Public License
10 *               as published by the Free Software Foundation; either version
11 *               2 of the License, or (at your option) any later version.
12 * ============================================================================
13 * Due Credit:
14 *               Wanpipe socket layer is based on Packet and 
15 *               the X25 socket layers. The above sockets were 
16 *               used for the specific use of Sangoma Technoloiges 
17 *               API programs. 
18 *               Packet socket Authors: Ross Biro, Fred N. van Kempen and 
19 *                                      Alan Cox.
20 *               X25 socket Author: Jonathan Naylor.
21 * ============================================================================
22 * Mar 15, 2002  Arnaldo C. Melo  o Use wp_sk()->num, as it isnt anymore in sock
23 * Apr 25, 2000  Nenad Corbic     o Added the ability to send zero length packets.
24 * Mar 13, 2000  Nenad Corbic     o Added a tx buffer check via ioctl call.
25 * Mar 06, 2000  Nenad Corbic     o Fixed the corrupt sock lcn problem.
26 *                                  Server and client applicaton can run
27 *                                  simultaneously without conflicts.
28 * Feb 29, 2000  Nenad Corbic     o Added support for PVC protocols, such as
29 *                                  CHDLC, Frame Relay and HDLC API.
30 * Jan 17, 2000  Nenad Corbic     o Initial version, based on AF_PACKET socket.
31 *                                  X25API support only. 
32 *
33 ******************************************************************************/
34
35 #include <linux/config.h>
36 #include <linux/types.h>
37 #include <linux/sched.h>
38 #include <linux/mm.h>
39 #include <linux/fcntl.h>
40 #include <linux/socket.h>
41 #include <linux/in.h>
42 #include <linux/inet.h>
43 #include <linux/netdevice.h>
44 #include <linux/poll.h>
45 #include <linux/wireless.h>
46 #include <linux/kmod.h>
47 #include <net/ip.h>
48 #include <net/protocol.h>
49 #include <linux/skbuff.h>
50 #include <net/sock.h>
51 #include <linux/errno.h>
52 #include <linux/timer.h>
53 #include <asm/system.h>
54 #include <asm/uaccess.h>
55 #include <linux/module.h>
56 #include <linux/init.h>
57 #include <linux/wanpipe.h>
58 #include <linux/if_wanpipe.h>
59 #include <linux/pkt_sched.h>
60 #include <linux/tcp.h>
61 #include <linux/if_wanpipe_common.h>
62 #include <linux/sdla_x25.h>
63
64 #ifdef CONFIG_INET
65 #include <net/inet_common.h>
66 #endif
67
68 #define SLOW_BACKOFF 0.1*HZ
69 #define FAST_BACKOFF 0.01*HZ
70
71 //#define PRINT_DEBUG
72 #ifdef PRINT_DEBUG
73         #define DBG_PRINTK(format, a...) printk(format, ## a)
74 #else
75         #define DBG_PRINTK(format, a...)
76 #endif      
77
78
79 /* SECURE SOCKET IMPLEMENTATION 
80  * 
81  *   TRANSMIT:
82  *
83  *      When the user sends a packet via send() system call
84  *      the wanpipe_sendmsg() function is executed.  
85  *      
86  *      Each packet is enqueud into sk->sk_write_queue transmit
87  *      queue. When the packet is enqueued, a delayed transmit
88  *      timer is triggerd which acts as a Bottom Half hander. 
89  *
90  *      wanpipe_delay_transmit() function (BH), dequeues packets
91  *      from the sk->sk_write_queue transmit queue and sends it 
92  *      to the deriver via dev->hard_start_xmit(skb, dev) function.  
93  *      Note, this function is actual a function pointer of if_send()
94  *      routine in the wanpipe driver.
95  *
96  *      X25API GUARANTEED DELIVERY:
97  *
98  *         In order to provide 100% guaranteed packet delivery, 
99  *         an atomic 'packet_sent' counter is implemented.  Counter 
100  *         is incremented for each packet enqueued 
101  *         into sk->sk_write_queue.  Counter is decremented each
102  *         time wanpipe_delayed_transmit() function successfuly 
103  *         passes the packet to the driver. Before each send(), a poll
104  *         routine checks the sock resources The maximum value of
105  *         packet sent counter is 1, thus if one packet is queued, the
106  *         application will block until that packet is passed to the
107  *         driver.
108  *
109  *   RECEIVE:
110  *
111  *      Wanpipe device drivers call the socket bottom half
112  *      function, wanpipe_rcv() to queue the incoming packets
113  *      into an AF_WANPIPE socket queue.  Based on wanpipe_rcv()
114  *      return code, the driver knows whether the packet was
115  *      successfully queued.  If the socket queue is full, 
116  *      protocol flow control is used by the driver, if any, 
117  *      to slow down the traffic until the sock queue is free.
118  *
119  *      Every time a packet arrives into a socket queue the 
120  *      socket wakes up processes which are waiting to receive
121  *      data.
122  *
123  *      If the socket queue is full, the driver sets a block
124  *      bit which signals the socket to kick the wanpipe driver
125  *      bottom half hander when the socket queue is partialy
126  *      empty. wanpipe_recvmsg() function performs this action.
127  * 
128  *      In case of x25api, packets will never be dropped, since
129  *      flow control is available. 
130  *      
131  *      In case of streaming protocols like CHDLC, packets will 
132  *      be dropped but the statistics will be generated. 
133  */
134
135
136 /* The code below is used to test memory leaks. It prints out
137  * a message every time kmalloc and kfree system calls get executed.
138  * If the calls match there is no leak :)
139  */
140
141 /***********FOR DEBUGGING PURPOSES*********************************************
142 #define KMEM_SAFETYZONE 8
143
144 static void * dbg_kmalloc(unsigned int size, int prio, int line) {
145         void * v = kmalloc(size,prio);
146         printk(KERN_INFO "line %d  kmalloc(%d,%d) = %p\n",line,size,prio,v);
147         return v;
148 }
149 static void dbg_kfree(void * v, int line) {
150         printk(KERN_INFO "line %d  kfree(%p)\n",line,v);
151         kfree(v);
152 }
153
154 #define kmalloc(x,y) dbg_kmalloc(x,y,__LINE__)
155 #define kfree(x) dbg_kfree(x,__LINE__)
156 ******************************************************************************/
157
158
159 /* List of all wanpipe sockets. */
160 HLIST_HEAD(wanpipe_sklist);
161 static DEFINE_RWLOCK(wanpipe_sklist_lock);
162
163 atomic_t wanpipe_socks_nr;
164 static unsigned long wanpipe_tx_critical;
165
166 #if 0
167 /* Private wanpipe socket structures. */
168 struct wanpipe_opt
169 {
170         void   *mbox;           /* Mail box  */
171         void   *card;           /* Card bouded to */
172         struct net_device *dev; /* Bounded device */
173         unsigned short lcn;     /* Binded LCN */
174         unsigned char  svc;     /* 0=pvc, 1=svc */
175         unsigned char  timer;   /* flag for delayed transmit*/  
176         struct timer_list tx_timer;
177         unsigned poll_cnt;
178         unsigned char force;    /* Used to force sock release */
179         atomic_t packet_sent;   
180 };
181 #endif
182
183 static int sk_count;
184 extern struct proto_ops wanpipe_ops;
185 static unsigned long find_free_critical;
186
187 static void wanpipe_unlink_driver(struct sock *sk);
188 static void wanpipe_link_driver(struct net_device *dev, struct sock *sk);
189 static void wanpipe_wakeup_driver(struct sock *sk);
190 static int execute_command(struct sock *, unsigned char, unsigned int);
191 static int check_dev(struct net_device *dev, sdla_t *card);
192 struct net_device *wanpipe_find_free_dev(sdla_t *card);
193 static void wanpipe_unlink_card (struct sock *);
194 static int wanpipe_link_card (struct sock *);
195 static struct sock *wanpipe_make_new(struct sock *);
196 static struct sock *wanpipe_alloc_socket(void);
197 static inline int get_atomic_device(struct net_device *dev);
198 static int wanpipe_exec_cmd(struct sock *, int, unsigned int);
199 static int get_ioctl_cmd (struct sock *, void *);
200 static int set_ioctl_cmd (struct sock *, void *);
201 static void release_device(struct net_device *dev);
202 static void wanpipe_kill_sock_timer (unsigned long data);
203 static void wanpipe_kill_sock_irq (struct sock *);
204 static void wanpipe_kill_sock_accept (struct sock *);
205 static int wanpipe_do_bind(struct sock *sk, struct net_device *dev,
206                            int protocol);
207 struct sock * get_newsk_from_skb (struct sk_buff *);
208 static int wanpipe_debug (struct sock *, void *);
209 static void wanpipe_delayed_transmit (unsigned long data);
210 static void release_driver(struct sock *);
211 static void start_cleanup_timer (struct sock *);
212 static void check_write_queue(struct sock *);
213 static int check_driver_busy (struct sock *);
214
215 /*============================================================
216  * wanpipe_rcv
217  *
218  *      Wanpipe socket bottom half handler.  This function
219  *      is called by the WANPIPE device drivers to queue a
220  *      incoming packet into the socket receive queue. 
221  *      Once the packet is queued, all processes waiting to 
222  *      read are woken up.
223  *
224  *      During socket bind, this function is bounded into
225  *      WANPIPE driver private.
226  *===========================================================*/
227
228 static int wanpipe_rcv(struct sk_buff *skb, struct net_device *dev,
229                        struct sock *sk)
230 {
231         struct wan_sockaddr_ll *sll = (struct wan_sockaddr_ll*)skb->cb;
232         wanpipe_common_t *chan = dev->priv;
233         /*
234          *      When we registered the protocol we saved the socket in the data
235          *      field for just this event.
236          */
237
238         skb->dev = dev;
239
240         sll->sll_family = AF_WANPIPE;
241         sll->sll_hatype = dev->type;
242         sll->sll_protocol = skb->protocol;
243         sll->sll_pkttype = skb->pkt_type;
244         sll->sll_ifindex = dev->ifindex;
245         sll->sll_halen = 0;
246
247         if (dev->hard_header_parse)
248                 sll->sll_halen = dev->hard_header_parse(skb, sll->sll_addr);
249
250         /* 
251          * WAN_PACKET_DATA : Data which should be passed up the receive queue.
252          * WAN_PACKET_ASYC : Asynchronous data like place call, which should
253          *                   be passed up the listening sock.
254          * WAN_PACKET_ERR  : Asynchronous data like clear call or restart 
255          *                   which should go into an error queue.
256          */
257         switch (skb->pkt_type){
258
259                 case WAN_PACKET_DATA:
260                         if (sock_queue_rcv_skb(sk,skb)<0){
261                                 return -ENOMEM;
262                         }
263                         break;
264                 case WAN_PACKET_CMD:
265                         sk->sk_state = chan->state;
266                         /* Bug fix: update Mar6. 
267                          * Do not set the sock lcn number here, since
268                          * cmd is not guaranteed to be executed on the
269                          * board, thus Lcn could be wrong */
270                         sk->sk_data_ready(sk, skb->len);
271                         kfree_skb(skb);
272                         break;
273                 case WAN_PACKET_ERR:
274                         sk->sk_state = chan->state;
275                         if (sock_queue_err_skb(sk,skb)<0){
276                                 return -ENOMEM;
277                         }
278                         break;
279                 default:
280                         printk(KERN_INFO "wansock: BH Illegal Packet Type Dropping\n");
281                         kfree_skb(skb); 
282                         break;
283         }
284
285 //??????????????????????
286 //      if (sk->sk_state == WANSOCK_DISCONNECTED){
287 //              if (sk->sk_zapped) {
288 //                      //printk(KERN_INFO "wansock: Disconnected, killing early\n");
289 //                      wanpipe_unlink_driver(sk);
290 //                      sk->sk_bound_dev_if = 0;
291 //              }
292 //      }
293
294         return 0;
295 }
296
297 /*============================================================
298  * wanpipe_listen_rcv
299  *
300  *      Wanpipe LISTEN socket bottom half handler.  This function
301  *      is called by the WANPIPE device drivers to queue an
302  *      incoming call into the socket listening queue. 
303  *      Once the packet is queued, the waiting accept() process 
304  *      is woken up.
305  *
306  *      During socket bind, this function is bounded into
307  *      WANPIPE driver private. 
308  * 
309  *      IMPORTANT NOTE:
310  *          The accept call() is waiting for an skb packet
311  *          which contains a pointer to a device structure.
312  *
313  *          When we do a bind to a device structre, we 
314  *          bind a newly created socket into "chan->sk".  Thus, 
315  *          when accept receives the skb packet, it will know 
316  *          from which dev it came form, and in turn it will know
317  *          the address of the new sock.
318  *
319  *      NOTE: This function gets called from driver ISR.
320  *===========================================================*/
321
322 static int wanpipe_listen_rcv (struct sk_buff *skb,  struct sock *sk)
323 {
324         wanpipe_opt *wp = wp_sk(sk), *newwp;
325         struct wan_sockaddr_ll *sll = (struct wan_sockaddr_ll*)skb->cb;
326         struct sock *newsk;
327         struct net_device *dev; 
328         sdla_t *card;
329         mbox_cmd_t *mbox_ptr;
330         wanpipe_common_t *chan;
331
332         /* Find a free device, if none found, all svc's are busy 
333          */
334
335         card = (sdla_t*)wp->card;
336         if (!card){
337                 printk(KERN_INFO "wansock: LISTEN ERROR, No Card\n");
338                 return -ENODEV;
339         }
340         
341         dev = wanpipe_find_free_dev(card);
342         if (!dev){
343                 printk(KERN_INFO "wansock: LISTEN ERROR, No Free Device\n");
344                 return -ENODEV;
345         }
346
347         chan=dev->priv; 
348         chan->state = WANSOCK_CONNECTING;
349
350         /* Allocate a new sock, which accept will bind
351          * and pass up to the user 
352          */
353         if ((newsk = wanpipe_make_new(sk)) == NULL){
354                 release_device(dev);
355                 return -ENOMEM;
356         }
357
358
359         /* Initialize the new sock structure 
360          */
361         newsk->sk_bound_dev_if = dev->ifindex;
362         newwp = wp_sk(newsk);
363         newwp->card = wp->card;
364
365         /* Insert the sock into the main wanpipe
366          * sock list.
367          */
368         atomic_inc(&wanpipe_socks_nr);
369
370         /* Allocate and fill in the new Mail Box. Then
371          * bind the mail box to the sock. It will be 
372          * used by the ioctl call to read call information
373          * and to execute commands. 
374          */     
375         if ((mbox_ptr = kmalloc(sizeof(mbox_cmd_t), GFP_ATOMIC)) == NULL) {
376                 wanpipe_kill_sock_irq (newsk);
377                 release_device(dev);            
378                 return -ENOMEM;
379         }
380         memset(mbox_ptr, 0, sizeof(mbox_cmd_t));
381         memcpy(mbox_ptr,skb->data,skb->len);
382
383         /* Register the lcn on which incoming call came
384          * from. Thus, if we have to clear it, we know
385          * which lcn to clear
386          */ 
387
388         newwp->lcn = mbox_ptr->cmd.lcn;
389         newwp->mbox = (void *)mbox_ptr;
390
391         DBG_PRINTK(KERN_INFO "NEWSOCK : Device %s, bind to lcn %i\n",
392                         dev->name,mbox_ptr->cmd.lcn);
393
394         chan->lcn = mbox_ptr->cmd.lcn;
395         card->u.x.svc_to_dev_map[(chan->lcn%MAX_X25_LCN)] = dev;
396
397         sock_reset_flag(newsk, SOCK_ZAPPED);
398         newwp->num = htons(X25_PROT);
399
400         if (wanpipe_do_bind(newsk, dev, newwp->num)) {
401                 wanpipe_kill_sock_irq (newsk);
402                 release_device(dev);
403                 return -EINVAL;
404         }
405         newsk->sk_state = WANSOCK_CONNECTING;
406
407
408         /* Fill in the standard sock address info */
409
410         sll->sll_family = AF_WANPIPE;
411         sll->sll_hatype = dev->type;
412         sll->sll_protocol = skb->protocol;
413         sll->sll_pkttype = skb->pkt_type;
414         sll->sll_ifindex = dev->ifindex;
415         sll->sll_halen = 0;
416
417         skb->dev = dev;
418         sk->sk_ack_backlog++;
419
420         /* We must do this manually, since the sock_queue_rcv_skb()
421          * function sets the skb->dev to NULL.  However, we use
422          * the dev field in the accept function.*/ 
423         if (atomic_read(&sk->sk_rmem_alloc) + skb->truesize >= 
424             (unsigned)sk->sk_rcvbuf) {
425
426                 wanpipe_unlink_driver(newsk);
427                 wanpipe_kill_sock_irq (newsk);
428                 --sk->sk_ack_backlog;
429                 return -ENOMEM;
430         }       
431
432         skb_set_owner_r(skb, sk);
433         skb_queue_tail(&sk->sk_receive_queue, skb);
434         sk->sk_data_ready(sk, skb->len);
435         
436         return 0;
437 }
438
439
440
441 /*============================================================
442  * wanpipe_make_new
443  *
444  *      Create a new sock, and allocate a wanpipe private
445  *      structure to it. Also, copy the important data
446  *      from the original sock to the new sock.
447  *
448  *      This function is used by wanpipe_listen_rcv() listen
449  *      bottom half handler.  A copy of the listening sock
450  *      is created using this function.
451  *
452  *===========================================================*/
453
454 static struct sock *wanpipe_make_new(struct sock *osk)
455 {
456         struct sock *sk;
457
458         if (osk->sk_type != SOCK_RAW)
459                 return NULL;
460
461         if ((sk = wanpipe_alloc_socket()) == NULL)
462                 return NULL;
463
464         sk->sk_type     = osk->sk_type;
465         sk->sk_socket   = osk->sk_socket;
466         sk->sk_priority = osk->sk_priority;
467         sk->sk_protocol = osk->sk_protocol;
468         wp_sk(sk)->num  = wp_sk(osk)->num;
469         sk->sk_rcvbuf   = osk->sk_rcvbuf;
470         sk->sk_sndbuf   = osk->sk_sndbuf;
471         sk->sk_state    = WANSOCK_CONNECTING;
472         sk->sk_sleep    = osk->sk_sleep;
473
474         if (sock_flag(osk, SOCK_DBG))
475                 sock_set_flag(sk, SOCK_DBG);
476
477         return sk;
478 }
479
480 /* 
481  * FIXME: wanpipe_opt has to include a sock in its definition and stop using
482  * sk_protinfo, but this code is not even compilable now, so lets leave it for
483  * later.
484  */
485 static struct proto wanpipe_proto = {
486         .name     = "WANPIPE",
487         .owner    = THIS_MODULE,
488         .obj_size = sizeof(struct sock),
489 };
490
491 /*============================================================
492  * wanpipe_make_new
493  *
494  *      Allocate memory for the a new sock, and sock
495  *      private data.  
496  *      
497  *      Increment the module use count.
498  *              
499  *      This function is used by wanpipe_create() and 
500  *      wanpipe_make_new() functions. 
501  *
502  *===========================================================*/
503
504 static struct sock *wanpipe_alloc_socket(void)
505 {
506         struct sock *sk;
507         struct wanpipe_opt *wan_opt;
508
509         if ((sk = sk_alloc(PF_WANPIPE, GFP_ATOMIC, &wanpipe_proto, 1)) == NULL)
510                 return NULL;
511
512         if ((wan_opt = kmalloc(sizeof(struct wanpipe_opt), GFP_ATOMIC)) == NULL) {
513                 sk_free(sk);
514                 return NULL;
515         }
516         memset(wan_opt, 0x00, sizeof(struct wanpipe_opt));
517
518         wp_sk(sk) = wan_opt;
519
520         /* Use timer to send data to the driver. This will act
521          * as a BH handler for sendmsg functions */
522         init_timer(&wan_opt->tx_timer);
523         wan_opt->tx_timer.data     = (unsigned long)sk;
524         wan_opt->tx_timer.function = wanpipe_delayed_transmit;
525
526         sock_init_data(NULL, sk);
527         return sk;
528 }
529
530
531 /*============================================================
532  * wanpipe_sendmsg
533  *
534  *      This function implements a sendto() system call,
535  *      for AF_WANPIPE socket family. 
536  *      During socket bind() sk->sk_bound_dev_if is initialized
537  *      to a correct network device. This number is used
538  *      to find a network device to which the packet should
539  *      be passed to.
540  *
541  *      Each packet is queued into sk->sk_write_queue and 
542  *      delayed transmit bottom half handler is marked for 
543  *      execution.
544  *
545  *      A socket must be in WANSOCK_CONNECTED state before
546  *      a packet is queued into sk->sk_write_queue.
547  *===========================================================*/
548
549 static int wanpipe_sendmsg(struct kiocb *iocb, struct socket *sock,
550                            struct msghdr *msg, int len)
551 {
552         wanpipe_opt *wp;
553         struct sock *sk = sock->sk;
554         struct wan_sockaddr_ll *saddr=(struct wan_sockaddr_ll *)msg->msg_name;
555         struct sk_buff *skb;
556         struct net_device *dev;
557         unsigned short proto;
558         unsigned char *addr;
559         int ifindex, err, reserve = 0;
560
561         
562         if (!sock_flag(sk, SOCK_ZAPPED))
563                 return -ENETDOWN;
564
565         if (sk->sk_state != WANSOCK_CONNECTED)
566                 return -ENOTCONN;       
567
568         if (msg->msg_flags & ~(MSG_DONTWAIT|MSG_CMSG_COMPAT)) 
569                 return(-EINVAL);
570
571         /* it was <=, now one can send
572          * zero length packets */
573         if (len < sizeof(x25api_hdr_t))
574                 return -EINVAL;
575
576         wp = wp_sk(sk);
577
578         if (saddr == NULL) {
579                 ifindex = sk->sk_bound_dev_if;
580                 proto   = wp->num;
581                 addr    = NULL;
582
583         }else{
584                 if (msg->msg_namelen < sizeof(struct wan_sockaddr_ll)){ 
585                         return -EINVAL;
586                 }
587
588                 ifindex = sk->sk_bound_dev_if;
589                 proto   = saddr->sll_protocol;
590                 addr    = saddr->sll_addr;
591         }
592
593         dev = dev_get_by_index(ifindex);
594         if (dev == NULL){
595                 printk(KERN_INFO "wansock: Send failed, dev index: %i\n",ifindex);
596                 return -ENXIO;
597         }
598         dev_put(dev);
599         
600         if (sock->type == SOCK_RAW)
601                 reserve = dev->hard_header_len;
602
603         if (len > dev->mtu+reserve){
604                 return -EMSGSIZE;
605         }
606
607         skb = sock_alloc_send_skb(sk, len + LL_RESERVED_SPACE(dev),
608                                 msg->msg_flags & MSG_DONTWAIT, &err);
609
610         if (skb==NULL){
611                 goto out_unlock;
612         }
613                 
614         skb_reserve(skb, LL_RESERVED_SPACE(dev));
615         skb->nh.raw = skb->data;
616
617         /* Returns -EFAULT on error */
618         err = memcpy_fromiovec(skb_put(skb,len), msg->msg_iov, len);
619         if (err){
620                 goto out_free;
621         }
622
623         if (dev->hard_header) {
624                 int res;
625                 err = -EINVAL;
626                 res = dev->hard_header(skb, dev, ntohs(proto), addr, NULL, len);
627                 if (res<0){
628                         goto out_free;
629                 }
630         }
631
632         skb->protocol = proto;
633         skb->dev = dev;
634         skb->priority = sk->sk_priority;
635         skb->pkt_type = WAN_PACKET_DATA;
636
637         err = -ENETDOWN;
638         if (!(dev->flags & IFF_UP))
639                 goto out_free;
640
641         if (atomic_read(&sk->sk_wmem_alloc) + skb->truesize >
642             (unsigned int)sk->sk_sndbuf){
643                 kfree_skb(skb);
644                 return -ENOBUFS;
645         }
646
647         skb_queue_tail(&sk->sk_write_queue,skb);
648         atomic_inc(&wp->packet_sent);
649
650         if (!(test_and_set_bit(0, &wp->timer)))
651                 mod_timer(&wp->tx_timer, jiffies + 1);
652         
653         return(len);
654
655 out_free:
656         kfree_skb(skb);
657 out_unlock:
658         return err;
659 }
660
661 /*============================================================
662  * wanpipe_delayed_tarnsmit
663  *
664  *      Transmit bottom half handler. It dequeues packets
665  *      from sk->sk_write_queue and passes them to the 
666  *      driver.  If the driver is busy, the packet is 
667  *      re-enqueued.  
668  *
669  *      Packet Sent counter is decremented on successful
670  *      transmission. 
671  *===========================================================*/
672
673
674 static void wanpipe_delayed_transmit (unsigned long data)
675 {
676         struct sock *sk=(struct sock *)data;
677         struct sk_buff *skb;
678         wanpipe_opt *wp = wp_sk(sk);
679         struct net_device *dev = wp->dev;
680         sdla_t *card = (sdla_t*)wp->card;
681
682         if (!card || !dev){
683                 clear_bit(0, &wp->timer);
684                 DBG_PRINTK(KERN_INFO "wansock: Transmit delay, no dev or card\n");
685                 return;
686         }
687         
688         if (sk->sk_state != WANSOCK_CONNECTED || !sock_flag(sk, SOCK_ZAPPED)) {
689                 clear_bit(0, &wp->timer);
690                 DBG_PRINTK(KERN_INFO "wansock: Tx Timer, State not CONNECTED\n");
691                 return;
692         }
693         
694         /* If driver is executing command, we must offload
695          * the board by not sending data. Otherwise a 
696          * pending command will never get a free buffer
697          * to execute */        
698         if (atomic_read(&card->u.x.command_busy)){
699                 wp->tx_timer.expires = jiffies + SLOW_BACKOFF;
700                 add_timer(&wp->tx_timer);
701                 DBG_PRINTK(KERN_INFO "wansock: Tx Timer, command bys BACKOFF\n");
702                 return;
703         }
704
705         
706         if (test_and_set_bit(0,&wanpipe_tx_critical)){
707                 printk(KERN_INFO "WanSock: Tx timer critical %s\n",dev->name);
708                 wp->tx_timer.expires = jiffies + SLOW_BACKOFF;
709                 add_timer(&wp->tx_timer);
710                 return;
711         }       
712         
713         /* Check for a packet in the fifo and send */
714         if ((skb = skb_dequeue(&sk->sk_write_queue)) != NULL){
715
716                 if (dev->hard_start_xmit(skb, dev) != 0){                       
717
718                         /* Driver failed to transmit, re-enqueue
719                          * the packet and retry again later */
720                         skb_queue_head(&sk->sk_write_queue,skb);
721                         clear_bit(0,&wanpipe_tx_critical);
722                         return;
723                 }else{
724
725                         /* Packet Sent successful. Check for more packets
726                          * if more packets, re-trigger the transmit routine 
727                          * other wise exit
728                          */
729                         atomic_dec(&wp->packet_sent);
730
731                         if (skb_peek(&sk->sk_write_queue) == NULL) {
732                                 /* If there is nothing to send, kick
733                                  * the poll routine, which will trigger
734                                  * the application to send more data */
735                                 sk->sk_data_ready(sk, 0);
736                                 clear_bit(0, &wp->timer);
737                         }else{
738                                 /* Reschedule as fast as possible */
739                                 wp->tx_timer.expires = jiffies + 1;
740                                 add_timer(&wp->tx_timer);
741                         }
742                 }
743         }
744         clear_bit(0,&wanpipe_tx_critical);
745 }
746
747 /*============================================================
748  * execute_command 
749  *
750  *      Execute x25api commands.  The atomic variable
751  *      chan->command is used to indicate to the driver that
752  *      command is pending for execution.  The acutal command
753  *      structure is placed into a sock mbox structure 
754  *      (wp_sk(sk)->mbox).
755  *
756  *      The sock private structure, mbox is
757  *      used as shared memory between sock and the driver.
758  *      Driver uses the sock mbox to execute the command
759  *      and return the result.  
760  *
761  *      For all command except PLACE CALL, the function
762  *      waits for the result.  PLACE CALL can be ether
763  *      blocking or nonblocking. The user sets this option
764  *      via ioctl call.
765  *===========================================================*/
766
767
768 static int execute_command(struct sock *sk,  unsigned char cmd, unsigned int flags)
769 {
770         wanpipe_opt *wp = wp_sk(sk);
771         struct net_device *dev;
772         wanpipe_common_t *chan=NULL;
773         int err=0;
774         DECLARE_WAITQUEUE(wait, current);
775         
776         dev = dev_get_by_index(sk->sk_bound_dev_if);
777         if (dev == NULL){
778                 printk(KERN_INFO "wansock: Exec failed no dev %i\n",
779                         sk->sk_bound_dev_if);
780                 return -ENODEV;
781         }
782         dev_put(dev);
783
784         if ((chan=dev->priv) == NULL){
785                 printk(KERN_INFO "wansock: Exec cmd failed no priv area\n");
786                 return -ENODEV;
787         }
788
789         if (atomic_read(&chan->command)){
790                 printk(KERN_INFO "wansock: ERROR: Command already running %x, %s\n",
791                         atomic_read(&chan->command),dev->name);
792                 return -EINVAL;
793         }
794
795         if (!wp->mbox) {
796                 printk(KERN_INFO "wansock: In execute without MBOX\n");
797                 return -EINVAL;
798         }
799
800         ((mbox_cmd_t*)wp->mbox)->cmd.command = cmd;     
801         ((mbox_cmd_t*)wp->mbox)->cmd.lcn     = wp->lcn;
802         ((mbox_cmd_t*)wp->mbox)->cmd.result  = 0x7F;
803
804
805         if (flags & O_NONBLOCK){
806                 cmd |= 0x80;
807                 atomic_set(&chan->command, cmd);
808         }else{
809                 atomic_set(&chan->command, cmd);
810         }
811
812         add_wait_queue(sk->sk_sleep,&wait);
813         current->state = TASK_INTERRUPTIBLE;
814         for (;;){
815                 if (((mbox_cmd_t*)wp->mbox)->cmd.result != 0x7F) {
816                         err = 0;
817                         break;
818                 }
819                 if (signal_pending(current)) {
820                         err = -ERESTARTSYS;
821                         break;
822                 }
823                 schedule();
824         }
825         current->state = TASK_RUNNING;
826         remove_wait_queue(sk->sk_sleep,&wait);
827         
828         return err;
829 }
830
831 /*============================================================
832  * wanpipe_destroy_timer 
833  *
834  *      Used by wanpipe_release, to delay release of
835  *      the socket.
836  *===========================================================*/
837
838 static void wanpipe_destroy_timer(unsigned long data)
839 {
840         struct sock *sk=(struct sock *)data;
841         wanpipe_opt *wp = wp_sk(sk);
842
843         if ((!atomic_read(&sk->sk_wmem_alloc) &&
844              !atomic_read(&sk->sk_rmem_alloc)) ||
845             (++wp->force == 5)) {
846
847                 if (atomic_read(&sk->sk_wmem_alloc) ||
848                     atomic_read(&sk->sk_rmem_alloc))
849                         printk(KERN_INFO "wansock: Warning, Packet Discarded due to sock shutdown!\n");
850
851                 kfree(wp);
852                 wp_sk(sk) = NULL;
853                 
854                 if (atomic_read(&sk->sk_refcnt) != 1) {
855                         atomic_set(&sk->sk_refcnt, 1);
856                         DBG_PRINTK(KERN_INFO "wansock: Error, wrong reference count: %i ! :delay.\n",
857                                         atomic_read(&sk->sk_refcnt));
858                 }
859                 sock_put(sk);
860                 atomic_dec(&wanpipe_socks_nr);
861                 return;
862         }
863
864         sk->sk_timer.expires = jiffies + 5 * HZ;
865         add_timer(&sk->sk_timer);
866         printk(KERN_INFO "wansock: packet sk destroy delayed\n");
867 }
868
869 /*============================================================
870  * wanpipe_unlink_driver
871  *
872  *      When the socket is released, this function is 
873  *      used to remove links that bind the sock and the
874  *      driver together.  
875  *===========================================================*/
876 static void wanpipe_unlink_driver (struct sock *sk)
877 {
878         struct net_device *dev;
879         wanpipe_common_t *chan=NULL;
880
881         sock_reset_flag(sk, SOCK_ZAPPED);
882         sk->sk_state = WANSOCK_DISCONNECTED;
883         wp_sk(sk)->dev = NULL;
884
885         dev = dev_get_by_index(sk->sk_bound_dev_if);
886         if (!dev){
887                 printk(KERN_INFO "wansock: No dev on release\n");
888                 return;
889         }                       
890         dev_put(dev);
891
892         if ((chan = dev->priv) == NULL){
893                 printk(KERN_INFO "wansock: No Priv Area on release\n");
894                 return;
895         }
896
897         set_bit(0,&chan->common_critical);
898         chan->sk=NULL;
899         chan->func=NULL;
900         chan->mbox=NULL;
901         chan->tx_timer=NULL;
902         clear_bit(0,&chan->common_critical);
903         release_device(dev);
904         
905         return;
906 }
907
908 /*============================================================
909  * wanpipe_link_driver
910  *
911  *      Upon successful bind(), sock is linked to a driver
912  *      by binding in the wanpipe_rcv() bottom half handler
913  *      to the driver function pointer, as well as sock and
914  *      sock mailbox addresses.  This way driver can pass
915  *      data up the socket.
916  *===========================================================*/
917
918 static void wanpipe_link_driver(struct net_device *dev, struct sock *sk)
919 {
920         wanpipe_opt *wp = wp_sk(sk);
921         wanpipe_common_t *chan = dev->priv;
922         if (!chan)
923                 return;
924         set_bit(0,&chan->common_critical);
925         chan->sk=sk;
926         chan->func=wanpipe_rcv;
927         chan->mbox = wp->mbox;
928         chan->tx_timer = &wp->tx_timer;
929         wp->dev = dev;
930         sock_set_flag(sk, SOCK_ZAPPED);
931         clear_bit(0,&chan->common_critical);
932 }
933
934
935 /*============================================================
936  * release_device
937  *
938  *      During sock release, clear a critical bit, which 
939  *      marks the device a being taken.
940  *===========================================================*/
941
942
943 static void release_device(struct net_device *dev)
944 {
945         wanpipe_common_t *chan=dev->priv;
946         clear_bit(0,(void*)&chan->rw_bind);
947 }
948
949 /*============================================================
950  * wanpipe_release
951  *
952  *      Close a PACKET socket. This is fairly simple. We 
953  *      immediately go to 'closed' state and remove our 
954  *      protocol entry in the device list.
955  *===========================================================*/
956
957 static int wanpipe_release(struct socket *sock)
958 {
959         wanpipe_opt *wp;
960         struct sock *sk = sock->sk;
961         
962         if (!sk)
963                 return 0;
964
965         wp = wp_sk(sk);
966         check_write_queue(sk);
967
968         /* Kill the tx timer, if we don't kill it now, the timer
969          * will run after we kill the sock.  Timer code will 
970          * try to access the sock which has been killed and cause
971          * kernel panic */
972
973         del_timer(&wp->tx_timer);
974
975         /*
976          *      Unhook packet receive handler.
977          */
978
979         if (wp->num == htons(X25_PROT) &&
980             sk->sk_state != WANSOCK_DISCONNECTED && sock_flag(sk, SOCK_ZAPPED)) {
981                 struct net_device *dev = dev_get_by_index(sk->sk_bound_dev_if);
982                 wanpipe_common_t *chan;
983                 if (dev){
984                         chan=dev->priv;
985                         atomic_set(&chan->disconnect,1);
986                         DBG_PRINTK(KERN_INFO "wansock: Sending Clear Indication %i\n",
987                                         sk->sk_state);
988                         dev_put(dev);
989                 }       
990         }
991
992         set_bit(1,&wanpipe_tx_critical);
993         write_lock(&wanpipe_sklist_lock);
994         sk_del_node_init(sk);
995         write_unlock(&wanpipe_sklist_lock);
996         clear_bit(1,&wanpipe_tx_critical);
997
998
999         
1000         release_driver(sk);
1001
1002         
1003         /*
1004          *      Now the socket is dead. No more input will appear.
1005          */
1006
1007         sk->sk_state_change(sk);        /* It is useless. Just for sanity. */
1008
1009         sock->sk = NULL;
1010         sk->sk_socket = NULL;
1011         sock_set_flag(sk, SOCK_DEAD);
1012
1013         /* Purge queues */
1014         skb_queue_purge(&sk->sk_receive_queue);
1015         skb_queue_purge(&sk->sk_write_queue);
1016         skb_queue_purge(&sk->sk_error_queue);
1017
1018         if (atomic_read(&sk->sk_rmem_alloc) ||
1019             atomic_read(&sk->sk_wmem_alloc)) {
1020                 del_timer(&sk->sk_timer);
1021                 printk(KERN_INFO "wansock: Killing in Timer R %i , W %i\n",
1022                         atomic_read(&sk->sk_rmem_alloc),
1023                         atomic_read(&sk->sk_wmem_alloc));
1024                 sk->sk_timer.data       = (unsigned long)sk;
1025                 sk->sk_timer.expires    = jiffies + HZ;
1026                 sk->sk_timer.function   = wanpipe_destroy_timer;
1027                 add_timer(&sk->sk_timer);
1028                 return 0;
1029         }
1030
1031         kfree(wp);
1032         wp_sk(sk) = NULL;
1033
1034         if (atomic_read(&sk->sk_refcnt) != 1) {
1035                 DBG_PRINTK(KERN_INFO "wansock: Error, wrong reference count: %i !:release.\n",
1036                                         atomic_read(&sk->sk_refcnt));
1037                 atomic_set(&sk->sk_refcnt, 1);
1038         }
1039         sock_put(sk);
1040         atomic_dec(&wanpipe_socks_nr);
1041         return 0;
1042 }
1043
1044 /*============================================================
1045  * check_write_queue
1046  *
1047  *      During sock shutdown, if the sock state is 
1048  *      WANSOCK_CONNECTED and there is transmit data 
1049  *      pending. Wait until data is released 
1050  *      before proceeding.
1051  *===========================================================*/
1052
1053 static void check_write_queue(struct sock *sk)
1054 {
1055
1056         if (sk->sk_state != WANSOCK_CONNECTED)
1057                 return;
1058
1059         if (!atomic_read(&sk->sk_wmem_alloc))
1060                 return;
1061
1062         printk(KERN_INFO "wansock: MAJOR ERROR, Data lost on sock release !!!\n");
1063
1064 }
1065
1066 /*============================================================
1067  * release_driver
1068  *
1069  *      This function is called during sock shutdown, to 
1070  *      release any resources and links that bind the sock
1071  *      to the driver.  It also changes the state of the
1072  *      sock to WANSOCK_DISCONNECTED
1073  *===========================================================*/
1074
1075 static void release_driver(struct sock *sk)
1076 {
1077         wanpipe_opt *wp;
1078         struct sk_buff *skb=NULL;
1079         struct sock *deadsk=NULL;
1080
1081         if (sk->sk_state == WANSOCK_LISTEN ||
1082             sk->sk_state == WANSOCK_BIND_LISTEN) {
1083                 while ((skb = skb_dequeue(&sk->sk_receive_queue)) != NULL) {
1084                         if ((deadsk = get_newsk_from_skb(skb))){
1085                                 DBG_PRINTK (KERN_INFO "wansock: RELEASE: FOUND DEAD SOCK\n");
1086                                 sock_set_flag(deadsk, SOCK_DEAD);
1087                                 start_cleanup_timer(deadsk);
1088                         }
1089                         kfree_skb(skb);
1090                 }
1091                 if (sock_flag(sk, SOCK_ZAPPED))
1092                         wanpipe_unlink_card(sk);
1093         }else{
1094                 if (sock_flag(sk, SOCK_ZAPPED))
1095                         wanpipe_unlink_driver(sk);
1096         }
1097         sk->sk_state        = WANSOCK_DISCONNECTED;
1098         sk->sk_bound_dev_if = 0;
1099         sock_reset_flag(sk, SOCK_ZAPPED);
1100         wp = wp_sk(sk);
1101
1102         if (wp && wp->mbox) {
1103                 kfree(wp->mbox);
1104                 wp->mbox = NULL;
1105         }
1106 }
1107
1108 /*============================================================
1109  *  start_cleanup_timer
1110  *
1111  *      If new incoming call's are pending but the socket
1112  *      is being released, start the timer which will 
1113  *      envoke the kill routines for pending socks.
1114  *===========================================================*/
1115
1116
1117 static void start_cleanup_timer (struct sock *sk)
1118 {
1119         del_timer(&sk->sk_timer);
1120         sk->sk_timer.data       = (unsigned long)sk;
1121         sk->sk_timer.expires    = jiffies + HZ;
1122         sk->sk_timer.function   = wanpipe_kill_sock_timer;
1123         add_timer(&sk->sk_timer);
1124 }
1125
1126
1127 /*============================================================
1128  *  wanpipe_kill_sock
1129  *
1130  *      This is a function which performs actual killing
1131  *      of the sock.  It releases socket resources,
1132  *      and unlinks the sock from the driver. 
1133  *===========================================================*/
1134
1135 static void wanpipe_kill_sock_timer (unsigned long data)
1136 {
1137
1138         struct sock *sk = (struct sock *)data;
1139         struct sock **skp;
1140
1141         if (!sk)
1142                 return;
1143
1144         /* This function can be called from interrupt. We must use
1145          * appropriate locks */
1146         
1147         if (test_bit(1,&wanpipe_tx_critical)){
1148                 sk->sk_timer.expires = jiffies + 10;
1149                 add_timer(&sk->sk_timer);
1150                 return;
1151         }
1152         
1153         write_lock(&wanpipe_sklist_lock);
1154         sk_del_node_init(sk);
1155         write_unlock(&wanpipe_sklist_lock);
1156
1157
1158         if (wp_sk(sk)->num == htons(X25_PROT) &&
1159             sk->sk_state != WANSOCK_DISCONNECTED) {
1160                 struct net_device *dev = dev_get_by_index(sk->sk_bound_dev_if);
1161                 wanpipe_common_t *chan;
1162                 if (dev){
1163                         chan=dev->priv;
1164                         atomic_set(&chan->disconnect,1);
1165                         dev_put(dev);
1166                 }       
1167         }
1168
1169         release_driver(sk);
1170
1171         sk->sk_socket = NULL;
1172
1173         /* Purge queues */
1174         skb_queue_purge(&sk->sk_receive_queue);
1175         skb_queue_purge(&sk->sk_write_queue);
1176         skb_queue_purge(&sk->sk_error_queue);
1177         
1178         if (atomic_read(&sk->sk_rmem_alloc) ||
1179             atomic_read(&sk->sk_wmem_alloc)) {
1180                 del_timer(&sk->sk_timer);
1181                 printk(KERN_INFO "wansock: Killing SOCK in Timer\n");
1182                 sk->sk_timer.data       = (unsigned long)sk;
1183                 sk->sk_timer.expires    = jiffies + HZ;
1184                 sk->sk_timer.function   = wanpipe_destroy_timer;
1185                 add_timer(&sk->sk_timer);
1186                 return;
1187         }
1188
1189         if (wp_sk(sk)) {
1190                 kfree(wp_sk(sk));
1191                 wp_sk(sk) = NULL;
1192         }
1193
1194         if (atomic_read(&sk->sk_refcnt) != 1) {
1195                 atomic_set(&sk->sk_refcnt, 1);
1196                 DBG_PRINTK(KERN_INFO "wansock: Error, wrong reference count: %i ! :timer.\n",
1197                                         atomic_read(&sk->sk_refcnt));
1198         }
1199         sock_put(sk);
1200         atomic_dec(&wanpipe_socks_nr);
1201         return;
1202 }
1203
1204 static void wanpipe_kill_sock_accept (struct sock *sk)
1205 {
1206
1207         struct sock **skp;
1208
1209         if (!sk)
1210                 return;
1211
1212         /* This function can be called from interrupt. We must use
1213          * appropriate locks */
1214         
1215         write_lock(&wanpipe_sklist_lock);
1216         sk_del_node_init(sk);
1217         write_unlock(&wanpipe_sklist_lock);
1218
1219         sk->sk_socket = NULL;
1220
1221
1222         if (wp_sk(sk)) {
1223                 kfree(wp_sk(sk));
1224                 wp_sk(sk) = NULL;
1225         }
1226
1227         if (atomic_read(&sk->sk_refcnt) != 1) {
1228                 atomic_set(&sk->sk_refcnt, 1);
1229                 DBG_PRINTK(KERN_INFO "wansock: Error, wrong reference count: %i ! :timer.\n",
1230                                         atomic_read(&sk->sk_refcnt));
1231         }
1232         sock_put(sk);
1233         atomic_dec(&wanpipe_socks_nr);
1234         return;
1235 }
1236
1237
1238 static void wanpipe_kill_sock_irq (struct sock *sk)
1239 {
1240
1241         if (!sk)
1242                 return;
1243
1244         sk->sk_socket = NULL;
1245
1246         if (wp_sk(sk)) {
1247                 kfree(wp_sk(sk));
1248                 wp_sk(sk) = NULL;
1249         }
1250
1251         if (atomic_read(&sk->sk_refcnt) != 1) {
1252                 atomic_set(&sk->sk_refcnt, 1);
1253                 DBG_PRINTK(KERN_INFO "wansock: Error, wrong reference count: %i !:listen.\n",
1254                                         atomic_read(&sk->sk_refcnt));
1255         }
1256         sock_put(sk);
1257         atomic_dec(&wanpipe_socks_nr);
1258 }
1259
1260
1261 /*============================================================
1262  *  wanpipe_do_bind
1263  *
1264  *      Bottom half of the binding system call.
1265  *      Once the wanpipe_bind() function checks  the
1266  *      legality of the call, this function binds the
1267  *      sock to the driver.
1268  *===========================================================*/
1269
1270 static int wanpipe_do_bind(struct sock *sk, struct net_device *dev,
1271                            int protocol)
1272 {
1273         wanpipe_opt *wp = wp_sk(sk);
1274         wanpipe_common_t *chan=NULL;
1275         int err=0;
1276
1277         if (sock_flag(sk, SOCK_ZAPPED)) {
1278                 err = -EALREADY;
1279                 goto bind_unlock_exit;
1280         }
1281
1282         wp->num = protocol;
1283
1284         if (protocol == 0){
1285                 release_device(dev);
1286                 err = -EINVAL;
1287                 goto bind_unlock_exit;
1288         }
1289
1290         if (dev) {
1291                 if (dev->flags&IFF_UP) {
1292                         chan=dev->priv;
1293                         sk->sk_state = chan->state;
1294
1295                         if (wp->num == htons(X25_PROT) && 
1296                             sk->sk_state != WANSOCK_DISCONNECTED && 
1297                             sk->sk_state != WANSOCK_CONNECTING) {
1298                                 DBG_PRINTK(KERN_INFO 
1299                                         "wansock: Binding to Device not DISCONNECTED %i\n",
1300                                                 sk->sk_state);
1301                                 release_device(dev);
1302                                 err = -EAGAIN;
1303                                 goto bind_unlock_exit;
1304                         }
1305
1306                         wanpipe_link_driver(dev,sk);
1307                         sk->sk_bound_dev_if = dev->ifindex;
1308
1309                         /* X25 Specific option */
1310                         if (wp->num == htons(X25_PROT))
1311                                 wp_sk(sk)->svc = chan->svc;
1312
1313                 } else {
1314                         sk->sk_err = ENETDOWN;
1315                         sk->sk_error_report(sk);
1316                         release_device(dev);
1317                         err = -EINVAL;
1318                 }
1319         } else {
1320                 err = -ENODEV;
1321         }
1322 bind_unlock_exit:
1323         /* FIXME where is this lock */
1324
1325         return err;
1326 }
1327
1328 /*============================================================
1329  *  wanpipe_bind
1330  *
1331  *      BIND() System call, which is bound to the AF_WANPIPE
1332  *      operations structure.  It checks for correct wanpipe
1333  *      card name, and cross references interface names with
1334  *      the card names.  Thus, interface name must belong to
1335  *      the actual card.
1336  *===========================================================*/
1337
1338
1339 static int wanpipe_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
1340 {
1341         struct wan_sockaddr_ll *sll = (struct wan_sockaddr_ll*)uaddr;
1342         struct sock *sk=sock->sk;
1343         wanpipe_opt *wp = wp_sk(sk);
1344         struct net_device *dev = NULL;
1345         sdla_t *card=NULL;
1346         char name[15];
1347
1348         /*
1349          *      Check legality
1350          */
1351          
1352         if (addr_len < sizeof(struct wan_sockaddr_ll)){
1353                 printk(KERN_INFO "wansock: Address length error\n");
1354                 return -EINVAL;
1355         }
1356         if (sll->sll_family != AF_WANPIPE){
1357                 printk(KERN_INFO "wansock: Illegal family name specified.\n");
1358                 return -EINVAL;
1359         }
1360
1361         card = wanpipe_find_card (sll->sll_card);
1362         if (!card){
1363                 printk(KERN_INFO "wansock: Wanpipe card not found: %s\n",sll->sll_card);
1364                 return -ENODEV;
1365         }else{
1366                 wp_sk(sk)->card = (void *)card;
1367         }
1368
1369         if (!strcmp(sll->sll_device,"svc_listen")){
1370
1371                 /* Bind a sock to a card structure for listening 
1372                  */             
1373                 int err=0; 
1374
1375                 /* This is x25 specific area if protocol doesn't
1376                  * match, return error */
1377                 if (sll->sll_protocol != htons(X25_PROT))
1378                         return -EINVAL;
1379
1380                 err= wanpipe_link_card (sk);
1381                 if (err < 0)
1382                         return err;
1383
1384                 if (sll->sll_protocol)
1385                         wp->num = sll->sll_protocol;
1386                 sk->sk_state = WANSOCK_BIND_LISTEN;
1387                 return 0;
1388
1389         }else if (!strcmp(sll->sll_device,"svc_connect")){ 
1390
1391                 /* This is x25 specific area if protocol doesn't
1392                  * match, return error */
1393                 if (sll->sll_protocol != htons(X25_PROT))
1394                         return -EINVAL;
1395
1396                 /* Find a free device 
1397                  */
1398                 dev = wanpipe_find_free_dev(card);
1399                 if (dev == NULL){
1400                         DBG_PRINTK(KERN_INFO "wansock: No free network devices for card %s\n",
1401                                 card->devname);
1402                         return -EINVAL;
1403                 }
1404         }else{
1405                 /* Bind a socket to a interface name 
1406                  * This is used by PVC mostly
1407                  */
1408                 strlcpy(name,sll->sll_device,sizeof(name));
1409                 dev = dev_get_by_name(name);
1410                 if (dev == NULL){
1411                         printk(KERN_INFO "wansock: Failed to get Dev from name: %s,\n",
1412                                         name);
1413                         return -ENODEV;
1414                 }
1415
1416                 dev_put(dev);
1417
1418                 if (check_dev(dev, card)){
1419                         printk(KERN_INFO "wansock: Device %s, doesn't belong to card %s\n",
1420                                 dev->name, card->devname);
1421                         return -EINVAL;
1422                 }
1423                 if (get_atomic_device (dev))
1424                         return -EINVAL;
1425         }
1426
1427         return wanpipe_do_bind(sk, dev, sll->sll_protocol ? : wp->num);
1428 }
1429
1430 /*============================================================
1431  * get_atomic_device
1432  *      
1433  *      Sets a bit atomically which indicates that 
1434  *      the interface is taken. This avoids race conditions.
1435  *===========================================================*/
1436
1437
1438 static inline int get_atomic_device(struct net_device *dev)
1439 {
1440         wanpipe_common_t *chan = dev->priv;
1441         if (!test_and_set_bit(0,(void *)&chan->rw_bind)){
1442                 return 0;
1443         }
1444         return 1;
1445 }
1446
1447 /*============================================================
1448  * check_dev
1449  *      
1450  *      Check that device name belongs to a particular card.
1451  *===========================================================*/
1452
1453 static int check_dev(struct net_device *dev, sdla_t *card)
1454 {
1455         struct net_device* tmp_dev;
1456
1457         for (tmp_dev = card->wandev.dev; tmp_dev;
1458              tmp_dev = *((struct net_device **)tmp_dev->priv)) {
1459                 if (tmp_dev->ifindex == dev->ifindex){ 
1460                         return 0;       
1461                 }
1462         }
1463         return 1;
1464 }
1465
1466 /*============================================================
1467  *  wanpipe_find_free_dev
1468  *      
1469  *      Find a free network interface. If found set atomic
1470  *      bit indicating that the interface is taken.
1471  *      X25API Specific.
1472  *===========================================================*/
1473
1474 struct net_device *wanpipe_find_free_dev(sdla_t *card)
1475 {
1476         struct net_device* dev;
1477         volatile wanpipe_common_t *chan;
1478
1479         if (test_and_set_bit(0,&find_free_critical)){
1480                 printk(KERN_INFO "CRITICAL in Find Free\n");
1481         }       
1482
1483         for (dev = card->wandev.dev; dev;
1484              dev = *((struct net_device **)dev->priv)) {
1485                 chan = dev->priv;
1486                 if (!chan) 
1487                         continue;
1488                 if (chan->usedby == API && chan->svc){
1489                         if (!get_atomic_device (dev)){
1490                                 if (chan->state != WANSOCK_DISCONNECTED){
1491                                         release_device(dev);
1492                                 }else{
1493                                         clear_bit(0,&find_free_critical);
1494                                         return dev;
1495                                 }
1496                         }
1497                 }
1498         }
1499         clear_bit(0,&find_free_critical);
1500         return NULL;
1501 }
1502
1503 /*============================================================
1504  *  wanpipe_create
1505  *      
1506  *      SOCKET() System call.  It allocates a sock structure
1507  *      and adds the socket to the wanpipe_sk_list. 
1508  *      Crates AF_WANPIPE socket.
1509  *===========================================================*/
1510
1511 static int wanpipe_create(struct socket *sock, int protocol)
1512 {
1513         struct sock *sk;
1514         
1515         //FIXME: This checks for root user, SECURITY ?
1516         //if (!capable(CAP_NET_RAW))
1517         //      return -EPERM;
1518
1519         if (sock->type != SOCK_DGRAM && sock->type != SOCK_RAW)
1520                 return -ESOCKTNOSUPPORT;
1521
1522         sock->state = SS_UNCONNECTED;
1523
1524         if ((sk = wanpipe_alloc_socket()) == NULL)
1525                 return -ENOBUFS;
1526
1527         sk->sk_reuse = 1;
1528         sock->ops = &wanpipe_ops;
1529         sock_init_data(sock,sk);
1530
1531         sock_reset_flag(sk, SOCK_ZAPPED);
1532         sk->sk_family       = PF_WANPIPE;
1533         wp_sk(sk)->num      = protocol;
1534         sk->sk_state        = WANSOCK_DISCONNECTED;
1535         sk->sk_ack_backlog  = 0;
1536         sk->sk_bound_dev_if = 0;
1537
1538         atomic_inc(&wanpipe_socks_nr);
1539         
1540         /* We must disable interrupts because the ISR
1541          * can also change the list */
1542         set_bit(1,&wanpipe_tx_critical);
1543         write_lock(&wanpipe_sklist_lock);
1544         sk_add_node(sk, &wanpipe_sklist);
1545         write_unlock(&wanpipe_sklist_lock);
1546         clear_bit(1,&wanpipe_tx_critical);
1547
1548         return(0);
1549 }
1550
1551
1552 /*============================================================
1553  *  wanpipe_recvmsg
1554  *      
1555  *      Pull a packet from our receive queue and hand it 
1556  *      to the user. If necessary we block.
1557  *===========================================================*/
1558
1559 static int wanpipe_recvmsg(struct kiocb *iocb, struct socket *sock,
1560                            struct msghdr *msg, int len, int flags)
1561 {
1562         struct sock *sk = sock->sk;
1563         struct sk_buff *skb;
1564         int copied, err=-ENOBUFS;
1565
1566
1567         /*
1568          *      If the address length field is there to be filled in, we fill
1569          *      it in now.
1570          */
1571
1572         msg->msg_namelen = sizeof(struct wan_sockaddr_ll);
1573
1574         /*
1575          *      Call the generic datagram receiver. This handles all sorts
1576          *      of horrible races and re-entrancy so we can forget about it
1577          *      in the protocol layers.
1578          *
1579          *      Now it will return ENETDOWN, if device have just gone down,
1580          *      but then it will block.
1581          */
1582
1583         if (flags & MSG_OOB){   
1584                 skb = skb_dequeue(&sk->sk_error_queue);
1585         }else{
1586                 skb=skb_recv_datagram(sk,flags,1,&err);
1587         }
1588         /*
1589          *      An error occurred so return it. Because skb_recv_datagram() 
1590          *      handles the blocking we don't see and worry about blocking
1591          *      retries.
1592          */
1593
1594         if(skb==NULL)
1595                 goto out;
1596
1597         /*
1598          *      You lose any data beyond the buffer you gave. If it worries a
1599          *      user program they can ask the device for its MTU anyway.
1600          */
1601
1602         copied = skb->len;
1603         if (copied > len)
1604         {
1605                 copied=len;
1606                 msg->msg_flags|=MSG_TRUNC;
1607         }
1608
1609         wanpipe_wakeup_driver(sk);
1610
1611         /* We can't use skb_copy_datagram here */
1612         err = memcpy_toiovec(msg->msg_iov, skb->data, copied);
1613         if (err)
1614                 goto out_free;
1615         
1616         sock_recv_timestamp(msg, sk, skb);
1617         
1618         if (msg->msg_name)
1619                 memcpy(msg->msg_name, skb->cb, msg->msg_namelen);
1620
1621         /*
1622          *      Free or return the buffer as appropriate. Again this
1623          *      hides all the races and re-entrancy issues from us.
1624          */
1625         err = (flags&MSG_TRUNC) ? skb->len : copied;
1626
1627 out_free:
1628         skb_free_datagram(sk, skb);
1629 out:
1630         return err;
1631 }
1632
1633
1634 /*============================================================
1635  *  wanpipe_wakeup_driver
1636  *      
1637  *      If socket receive buffer is full and driver cannot
1638  *      pass data up the sock, it sets a packet_block flag.
1639  *      This function check that flag and if sock receive 
1640  *      queue has room it kicks the driver BH handler. 
1641  *
1642  *      This way, driver doesn't have to poll the sock 
1643  *      receive queue.
1644  *===========================================================*/
1645
1646 static void wanpipe_wakeup_driver(struct sock *sk)
1647 {
1648         struct net_device *dev = NULL;
1649         wanpipe_common_t *chan=NULL;
1650
1651         dev = dev_get_by_index(sk->sk_bound_dev_if);
1652         if (!dev)
1653                 return;
1654
1655         dev_put(dev);
1656
1657         if ((chan = dev->priv) == NULL)
1658                 return;
1659         
1660         if (atomic_read(&chan->receive_block)){  
1661                 if (atomic_read(&sk->sk_rmem_alloc) <
1662                     ((unsigned)sk->sk_rcvbuf * 0.9)) {
1663                         printk(KERN_INFO "wansock: Queuing task for wanpipe\n");
1664                         atomic_set(&chan->receive_block,0);
1665                         wanpipe_queue_tq(&chan->wanpipe_task);
1666                         wanpipe_mark_bh();
1667                 }
1668         }       
1669 }       
1670
1671 /*============================================================
1672  *  wanpipe_getname
1673  *      
1674  *      I don't know what to do with this yet. 
1675  *      User can use this function to get sock address
1676  *      information. Not very useful for Sangoma's purposes.
1677  *===========================================================*/
1678
1679
1680 static int wanpipe_getname(struct socket *sock, struct sockaddr *uaddr,
1681                           int *uaddr_len, int peer)
1682 {
1683         struct net_device *dev;
1684         struct sock *sk = sock->sk;
1685         struct wan_sockaddr_ll *sll = (struct wan_sockaddr_ll*)uaddr;
1686
1687         sll->sll_family = AF_WANPIPE;
1688         sll->sll_ifindex = sk->sk_bound_dev_if;
1689         sll->sll_protocol = wp_sk(sk)->num;
1690         dev = dev_get_by_index(sk->sk_bound_dev_if);
1691         if (dev) {
1692                 sll->sll_hatype = dev->type;
1693                 sll->sll_halen = dev->addr_len;
1694                 memcpy(sll->sll_addr, dev->dev_addr, dev->addr_len);
1695         } else {
1696                 sll->sll_hatype = 0;    /* Bad: we have no ARPHRD_UNSPEC */
1697                 sll->sll_halen = 0;
1698         }
1699         *uaddr_len = sizeof(*sll);
1700         
1701         dev_put(dev);
1702         
1703         return 0;
1704 }
1705
1706 /*============================================================
1707  *  wanpipe_notifier
1708  *      
1709  *      If driver turns off network interface, this function
1710  *      will be envoked. Currently I treate it as a 
1711  *      call disconnect. More thought should go into this
1712  *      function.
1713  *
1714  * FIXME: More thought should go into this function.
1715  *
1716  *===========================================================*/
1717
1718 static int wanpipe_notifier(struct notifier_block *this, unsigned long msg, void *data)
1719 {
1720         struct sock *sk;
1721         hlist_node *node;
1722         struct net_device *dev = (struct net_device *)data;
1723
1724         sk_for_each(sk, node, &wanpipe_sklist) {
1725                 struct wanpipe_opt *po = wp_sk(sk);
1726
1727                 if (!po)
1728                         continue;
1729                 if (dev == NULL)
1730                         continue;
1731                 
1732                 switch (msg) {
1733                 case NETDEV_DOWN:
1734                 case NETDEV_UNREGISTER:
1735                         if (dev->ifindex == sk->sk_bound_dev_if) {
1736                                 printk(KERN_INFO "wansock: Device down %s\n",dev->name);
1737                                 if (sock_flag(sk, SOCK_ZAPPED)) {
1738                                         wanpipe_unlink_driver(sk);
1739                                         sk->sk_err = ENETDOWN;
1740                                         sk->sk_error_report(sk);
1741                                 }
1742
1743                                 if (msg == NETDEV_UNREGISTER) {
1744                                         printk(KERN_INFO "wansock: Unregistering Device: %s\n",
1745                                                           dev->name);
1746                                         wanpipe_unlink_driver(sk);
1747                                         sk->sk_bound_dev_if = 0;
1748                                 }
1749                         }
1750                         break;
1751                 case NETDEV_UP:
1752                         if (dev->ifindex == sk->sk_bound_dev_if &&
1753                             po->num && !sock_flag(sk, SOCK_ZAPPED)) {
1754                                 printk(KERN_INFO "wansock: Registering Device: %s\n",
1755                                                 dev->name);
1756                                 wanpipe_link_driver(dev,sk);
1757                         }
1758                         break;
1759                 }
1760         }
1761         return NOTIFY_DONE;
1762 }
1763
1764 /*============================================================
1765  *  wanpipe_ioctl
1766  *      
1767  *      Execute a user commands, and set socket options.
1768  *
1769  * FIXME: More thought should go into this function.
1770  *
1771  *===========================================================*/
1772
1773 static int wanpipe_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
1774 {
1775         struct sock *sk = sock->sk;
1776         int err;
1777
1778         switch(cmd) 
1779         {
1780                 case SIOCGSTAMP:
1781                         return sock_get_timestamp(sk, (struct timeval __user *)arg);
1782
1783                 case SIOC_WANPIPE_CHECK_TX:
1784
1785                         return atomic_read(&sk->sk_wmem_alloc);
1786
1787                 case SIOC_WANPIPE_SOCK_STATE:
1788
1789                         if (sk->sk_state == WANSOCK_CONNECTED)
1790                                 return 0;
1791                         
1792                         return 1;
1793
1794
1795                 case SIOC_WANPIPE_GET_CALL_DATA:
1796
1797                         return get_ioctl_cmd (sk,(void*)arg);
1798
1799                 case SIOC_WANPIPE_SET_CALL_DATA:
1800
1801                         return set_ioctl_cmd (sk,(void*)arg);
1802
1803                 case SIOC_WANPIPE_ACCEPT_CALL:
1804                 case SIOC_WANPIPE_CLEAR_CALL:
1805                 case SIOC_WANPIPE_RESET_CALL:
1806
1807                         if ((err=set_ioctl_cmd(sk,(void*)arg)) < 0)
1808                                 return err;
1809
1810                         err=wanpipe_exec_cmd(sk,cmd,0);
1811                         get_ioctl_cmd(sk,(void*)arg);
1812                         return err;
1813
1814                 case SIOC_WANPIPE_DEBUG:
1815
1816                         return wanpipe_debug(sk,(void*)arg);
1817         
1818                 case SIOC_WANPIPE_SET_NONBLOCK:
1819
1820                         if (sk->sk_state != WANSOCK_DISCONNECTED)
1821                                 return -EINVAL;
1822
1823                         sock->file->f_flags |= O_NONBLOCK;
1824                         return 0;
1825         
1826 #ifdef CONFIG_INET
1827                 case SIOCADDRT:
1828                 case SIOCDELRT:
1829                 case SIOCDARP:
1830                 case SIOCGARP:
1831                 case SIOCSARP:
1832                 case SIOCDRARP:
1833                 case SIOCGRARP:
1834                 case SIOCSRARP:
1835                 case SIOCGIFADDR:
1836                 case SIOCSIFADDR:
1837                 case SIOCGIFBRDADDR:
1838                 case SIOCSIFBRDADDR:
1839                 case SIOCGIFNETMASK:
1840                 case SIOCSIFNETMASK:
1841                 case SIOCGIFDSTADDR:
1842                 case SIOCSIFDSTADDR:
1843                 case SIOCSIFFLAGS:
1844                         return inet_dgram_ops.ioctl(sock, cmd, arg);
1845 #endif
1846
1847                 default:
1848                         return dev_ioctl(cmd,(void __user *) arg);
1849         }
1850         /*NOTREACHED*/
1851 }
1852
1853 /*============================================================
1854  *  wanpipe_debug
1855  *      
1856  *      This function will pass up information about all
1857  *      active sockets.
1858  *
1859  * FIXME: More thought should go into this function.
1860  *
1861  *===========================================================*/
1862
1863 static int wanpipe_debug (struct sock *origsk, void *arg)
1864 {
1865         struct sock *sk;
1866         struct hlist_node *node;
1867         struct net_device *dev = NULL;
1868         wanpipe_common_t *chan=NULL;
1869         int cnt=0, err=0;
1870         wan_debug_t *dbg_data = (wan_debug_t *)arg;
1871
1872         sk_for_each(sk, node, &wanpipe_sklist) {
1873                 wanpipe_opt *wp = wp_sk(sk);
1874
1875                 if (sk == origsk){
1876                         continue;
1877                 }
1878
1879                 if ((err=put_user(1, &dbg_data->debug[cnt].free)))
1880                         return err;
1881                 if ((err = put_user(sk->sk_state,
1882                                     &dbg_data->debug[cnt].state_sk)))
1883                         return err;
1884                 if ((err = put_user(sk->sk_rcvbuf,
1885                                     &dbg_data->debug[cnt].rcvbuf)))
1886                         return err;
1887                 if ((err = put_user(atomic_read(&sk->sk_rmem_alloc),
1888                                     &dbg_data->debug[cnt].rmem)))
1889                         return err;
1890                 if ((err = put_user(atomic_read(&sk->sk_wmem_alloc),
1891                                     &dbg_data->debug[cnt].wmem)))
1892                         return err;
1893                 if ((err = put_user(sk->sk_sndbuf,
1894                                     &dbg_data->debug[cnt].sndbuf)))
1895                         return err;
1896                 if ((err=put_user(sk_count, &dbg_data->debug[cnt].sk_count)))
1897                         return err;
1898                 if ((err=put_user(wp->poll_cnt, &dbg_data->debug[cnt].poll_cnt)))
1899                         return err;
1900                 if ((err = put_user(sk->sk_bound_dev_if,
1901                                     &dbg_data->debug[cnt].bound)))
1902                         return err;
1903
1904                 if (sk->sk_bound_dev_if) {
1905                         dev = dev_get_by_index(sk->sk_bound_dev_if);
1906                         if (!dev)       
1907                                 continue;
1908
1909                         chan=dev->priv;
1910                         dev_put(dev);
1911         
1912                         if ((err=put_user(chan->state, &dbg_data->debug[cnt].d_state)))
1913                                 return err;
1914                         if ((err=put_user(chan->svc, &dbg_data->debug[cnt].svc)))
1915                                 return err;
1916
1917                         if ((err=put_user(atomic_read(&chan->command), 
1918                                                 &dbg_data->debug[cnt].command)))
1919                                 return err;
1920
1921
1922                         if (wp){
1923                                 sdla_t *card = (sdla_t*)wp->card;                       
1924         
1925                                 if (card){
1926                                         if ((err=put_user(atomic_read(&card->u.x.command_busy), 
1927                                                                 &dbg_data->debug[cnt].cmd_busy)))
1928                                                 return err;
1929                                 }
1930
1931                                 if ((err=put_user(wp->lcn, 
1932                                                   &dbg_data->debug[cnt].lcn)))
1933                                         return err;
1934                                 
1935                                 if (wp->mbox) {
1936                                         if ((err=put_user(1, &dbg_data->debug[cnt].mbox)))
1937                                                 return err;
1938                                 }
1939                         }
1940
1941                         if ((err=put_user(atomic_read(&chan->receive_block), 
1942                                                                 &dbg_data->debug[cnt].rblock)))
1943                                 return err;
1944
1945                         if (copy_to_user(dbg_data->debug[cnt].name, dev->name, strlen(dev->name)))
1946                                 return -EFAULT;
1947                 }
1948         
1949                 if (++cnt == MAX_NUM_DEBUG)
1950                         break;
1951         }
1952         return 0;
1953 }
1954
1955 /*============================================================
1956  *  get_ioctl_cmd
1957  *      
1958  *      Pass up the contents of socket MBOX to the user.
1959  *===========================================================*/
1960
1961 static int get_ioctl_cmd (struct sock *sk, void *arg)
1962 {
1963         x25api_t *usr_data = (x25api_t *)arg;
1964         mbox_cmd_t *mbox_ptr;
1965         int err;
1966
1967         if (usr_data == NULL)
1968                 return -EINVAL;
1969
1970         if (!wp_sk(sk)->mbox) {
1971                 return -EINVAL;
1972         }
1973
1974         mbox_ptr = (mbox_cmd_t *)wp_sk(sk)->mbox;
1975
1976         if ((err=put_user(mbox_ptr->cmd.qdm, &usr_data->hdr.qdm)))
1977                 return err;
1978         if ((err=put_user(mbox_ptr->cmd.cause, &usr_data->hdr.cause)))
1979                 return err;
1980         if ((err=put_user(mbox_ptr->cmd.diagn, &usr_data->hdr.diagn)))
1981                 return err;
1982         if ((err=put_user(mbox_ptr->cmd.length, &usr_data->hdr.length)))
1983                 return err;
1984         if ((err=put_user(mbox_ptr->cmd.result, &usr_data->hdr.result)))
1985                 return err;
1986         if ((err=put_user(mbox_ptr->cmd.lcn, &usr_data->hdr.lcn)))
1987                 return err;     
1988
1989         if (mbox_ptr->cmd.length > 0){
1990                 if (mbox_ptr->cmd.length > X25_MAX_DATA)
1991                         return -EINVAL;
1992
1993                 if (copy_to_user(usr_data->data, mbox_ptr->data, mbox_ptr->cmd.length)){
1994                         printk(KERN_INFO "wansock: Copy failed !!!\n");
1995                         return -EFAULT;
1996                 }
1997         }
1998         return 0;
1999
2000
2001 /*============================================================
2002  *  set_ioctl_cmd
2003  *      
2004  *      Before command can be execute, socket MBOX must
2005  *      be created, and initialized with user data.     
2006  *===========================================================*/
2007
2008 static int set_ioctl_cmd (struct sock *sk, void *arg)
2009 {
2010         x25api_t *usr_data = (x25api_t *)arg;
2011         mbox_cmd_t *mbox_ptr;
2012         int err;
2013
2014         if (!wp_sk(sk)->mbox) {
2015                 void *mbox_ptr;
2016                 struct net_device *dev = dev_get_by_index(sk->sk_bound_dev_if);
2017                 if (!dev)
2018                         return -ENODEV;
2019
2020                 dev_put(dev);
2021                 
2022                 if ((mbox_ptr = kmalloc(sizeof(mbox_cmd_t), GFP_ATOMIC)) == NULL)
2023                         return -ENOMEM;
2024
2025                 memset(mbox_ptr, 0, sizeof(mbox_cmd_t));
2026                 wp_sk(sk)->mbox = mbox_ptr;
2027
2028                 wanpipe_link_driver(dev,sk);
2029         }
2030
2031         mbox_ptr = (mbox_cmd_t*)wp_sk(sk)->mbox;
2032         memset(mbox_ptr, 0, sizeof(mbox_cmd_t));
2033
2034         if (usr_data == NULL){
2035                 return 0;
2036         }
2037         if ((err=get_user(mbox_ptr->cmd.qdm, &usr_data->hdr.qdm)))
2038                 return err;
2039         if ((err=get_user(mbox_ptr->cmd.cause, &usr_data->hdr.cause)))
2040                 return err;
2041         if ((err=get_user(mbox_ptr->cmd.diagn, &usr_data->hdr.diagn)))
2042                 return err;
2043         if ((err=get_user(mbox_ptr->cmd.length, &usr_data->hdr.length)))
2044                 return err;
2045         if ((err=get_user(mbox_ptr->cmd.result, &usr_data->hdr.result)))
2046                 return err;
2047
2048         if (mbox_ptr->cmd.length > 0){
2049                 if (mbox_ptr->cmd.length > X25_MAX_DATA)
2050                         return -EINVAL;
2051
2052                 if (copy_from_user(mbox_ptr->data, usr_data->data, mbox_ptr->cmd.length)){
2053                         printk(KERN_INFO "Copy failed\n");
2054                         return -EFAULT;
2055                 }
2056         }
2057         return 0;
2058 }
2059
2060
2061 /*======================================================================
2062  * wanpipe_poll
2063  *
2064  *      Datagram poll: Again totally generic. This also handles
2065  *      sequenced packet sockets providing the socket receive queue
2066  *      is only ever holding data ready to receive.
2067  *
2068  *      Note: when you _don't_ use this routine for this protocol,
2069  *      and you use a different write policy from sock_writeable()
2070  *      then please supply your own write_space callback.
2071  *=====================================================================*/
2072
2073 unsigned int wanpipe_poll(struct file * file, struct socket *sock, poll_table *wait)
2074 {
2075         struct sock *sk = sock->sk;
2076         unsigned int mask;
2077
2078         ++wp_sk(sk)->poll_cnt;
2079
2080         poll_wait(file, sk->sk_sleep, wait);
2081         mask = 0;
2082
2083         /* exceptional events? */
2084         if (sk->sk_err || !skb_queue_empty(&sk->sk_error_queue)) {
2085                 mask |= POLLPRI;
2086                 return mask;
2087         }
2088         if (sk->sk_shutdown & RCV_SHUTDOWN)
2089                 mask |= POLLHUP;
2090
2091         /* readable? */
2092         if (!skb_queue_empty(&sk->sk_receive_queue)) {
2093                 mask |= POLLIN | POLLRDNORM;
2094         }
2095
2096         /* connection hasn't started yet */
2097         if (sk->sk_state == WANSOCK_CONNECTING) {
2098                 return mask;
2099         }
2100
2101         if (sk->sk_state == WANSOCK_DISCONNECTED) {
2102                 mask = POLLPRI;
2103                 return mask;
2104         }
2105
2106         /* This check blocks the user process if there is   
2107          * a packet already queued in the socket write queue.
2108          * This option is only for X25API protocol, for other
2109          * protocol like chdlc enable streaming mode, 
2110          * where multiple packets can be pending in the socket 
2111          * transmit queue */
2112
2113         if (wp_sk(sk)->num == htons(X25_PROT)) {
2114                 if (atomic_read(&wp_sk(sk)->packet_sent))
2115                         return mask;
2116         }
2117
2118         /* writable? */
2119         if (sock_writeable(sk)){
2120                 mask |= POLLOUT | POLLWRNORM | POLLWRBAND;
2121         }else{
2122                 set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
2123         }
2124                 
2125         return mask;
2126 }
2127
2128 /*======================================================================
2129  * wanpipe_listen
2130  *
2131  *      X25API Specific function. Set a socket into LISTENING  MODE.
2132  *=====================================================================*/
2133
2134
2135 static int wanpipe_listen(struct socket *sock, int backlog)
2136 {
2137         struct sock *sk = sock->sk;
2138
2139         /* This is x25 specific area if protocol doesn't
2140          * match, return error */
2141         if (wp_sk(sk)->num != htons(X25_PROT))
2142                 return -EINVAL;
2143
2144         if (sk->sk_state == WANSOCK_BIND_LISTEN) {
2145
2146                 sk->sk_max_ack_backlog = backlog;
2147                 sk->sk_state           = WANSOCK_LISTEN;
2148                 return 0;
2149         }else{
2150                 printk(KERN_INFO "wansock: Listening sock was not binded\n");
2151         }
2152
2153         return -EINVAL;
2154 }
2155
2156 /*======================================================================
2157  * wanpipe_link_card
2158  *
2159  *      Connects the listening socket to the driver
2160  *=====================================================================*/
2161
2162 static int wanpipe_link_card (struct sock *sk)
2163 {
2164         sdla_t *card = (sdla_t*)wp_sk(sk)->card;
2165
2166         if (!card)
2167                 return -ENOMEM;
2168
2169         if ((card->sk != NULL) || (card->func != NULL)){
2170                 printk(KERN_INFO "wansock: Listening queue is already established\n");
2171                 return -EINVAL;
2172         }
2173
2174         card->sk=sk;
2175         card->func=wanpipe_listen_rcv;
2176         sock_set_flag(sk, SOCK_ZAPPED);
2177  
2178         return 0;
2179 }
2180
2181 /*======================================================================
2182  * wanpipe_listen
2183  *
2184  *      X25API Specific function. Disconnect listening socket from
2185  *      the driver.
2186  *=====================================================================*/
2187
2188 static void wanpipe_unlink_card (struct sock *sk)
2189 {
2190         sdla_t *card = (sdla_t*)wp_sk(sk)->card; 
2191
2192         if (card){
2193                 card->sk=NULL;
2194                 card->func=NULL;
2195         }
2196 }
2197
2198 /*======================================================================
2199  * wanpipe_exec_cmd
2200  *
2201  *      Ioctl function calls this function to execute user command.
2202  *      Connect() sytem call also calls this function to execute
2203  *      place call.  This function blocks until command is executed.
2204  *=====================================================================*/
2205
2206 static int wanpipe_exec_cmd(struct sock *sk, int cmd, unsigned int flags)
2207 {
2208         int err = -EINVAL;
2209         wanpipe_opt *wp = wp_sk(sk);
2210         mbox_cmd_t *mbox_ptr = (mbox_cmd_t*)wp->mbox;
2211
2212         if (!mbox_ptr){
2213                 printk(KERN_INFO "NO MBOX PTR !!!!!\n");
2214                 return -EINVAL;
2215         }
2216         
2217         /* This is x25 specific area if protocol doesn't
2218          * match, return error */
2219         if (wp->num != htons(X25_PROT))
2220                 return -EINVAL;
2221
2222
2223         switch (cmd){
2224
2225                 case SIOC_WANPIPE_ACCEPT_CALL:
2226
2227                         if (sk->sk_state != WANSOCK_CONNECTING) {
2228                                 err = -EHOSTDOWN;
2229                                 break;
2230                         }
2231                         
2232                         err = execute_command(sk,X25_ACCEPT_CALL,0);
2233                         if (err < 0)
2234                                 break;
2235
2236                         /* Update. Mar6 2000. 
2237                          * Do not set the sock lcn number here, since
2238                          * it is done in wanpipe_listen_rcv(). 
2239                          */ 
2240                         if (sk->sk_state == WANSOCK_CONNECTED) {
2241                                 wp->lcn = ((mbox_cmd_t*)wp->mbox)->cmd.lcn;     
2242                                 DBG_PRINTK(KERN_INFO "\nwansock: Accept OK %i\n",
2243                                         wp->lcn);
2244                                 err = 0;
2245
2246                         }else{
2247                                 DBG_PRINTK (KERN_INFO "\nwansock: Accept Failed %i\n",
2248                                         wp->lcn);
2249                                 wp->lcn = 0;
2250                                 err = -ECONNREFUSED;
2251                         }
2252                         break;
2253
2254                 case SIOC_WANPIPE_CLEAR_CALL:
2255
2256                         if (sk->sk_state == WANSOCK_DISCONNECTED) {
2257                                 err = -EINVAL;
2258                                 break;
2259                         }
2260
2261
2262                         /* Check if data buffers are pending for transmission,
2263                          * if so, check whether user wants to wait until data
2264                          * is transmitted, or clear a call and drop packets */
2265                           
2266                         if (atomic_read(&sk->sk_wmem_alloc) ||
2267                             check_driver_busy(sk)) {
2268                                 mbox_cmd_t *mbox = wp->mbox;
2269                                 if (mbox->cmd.qdm & 0x80){
2270                                         mbox->cmd.result = 0x35;
2271                                         err = -EAGAIN;  
2272                                         break;
2273                                 }
2274                         }
2275
2276                         sk->sk_state = WANSOCK_DISCONNECTING;
2277
2278                         err = execute_command(sk,X25_CLEAR_CALL,0);
2279                         if (err < 0)
2280                                 break;
2281
2282                         err = -ECONNREFUSED;
2283                         if (sk->sk_state == WANSOCK_DISCONNECTED) {
2284                                 DBG_PRINTK(KERN_INFO "\nwansock: CLEAR OK %i\n",
2285                                            wp->lcn);
2286                                 wp->lcn = 0;
2287                                 err = 0;
2288                         }
2289                         break;
2290
2291                 case SIOC_WANPIPE_RESET_CALL:
2292
2293                         if (sk->sk_state != WANSOCK_CONNECTED) {
2294                                 err = -EINVAL;
2295                                 break;
2296                         }
2297
2298
2299                         /* Check if data buffers are pending for transmission,
2300                          * if so, check whether user wants to wait until data
2301                          * is transmitted, or reset a call and drop packets */
2302                           
2303                         if (atomic_read(&sk->sk_wmem_alloc) ||
2304                             check_driver_busy(sk)) {
2305                                 mbox_cmd_t *mbox = wp->mbox;
2306                                 if (mbox->cmd.qdm & 0x80){
2307                                         mbox->cmd.result = 0x35;
2308                                         err = -EAGAIN;  
2309                                         break;
2310                                 }
2311                         }
2312
2313
2314                         err = execute_command(sk, X25_RESET,0);
2315                         if (err < 0)
2316                                 break;
2317
2318                         err = mbox_ptr->cmd.result;
2319                         break;
2320
2321
2322                 case X25_PLACE_CALL:
2323
2324                         err=execute_command(sk,X25_PLACE_CALL,flags);
2325                         if (err < 0)
2326                                 break;
2327
2328                         if (sk->sk_state == WANSOCK_CONNECTED) {
2329
2330                                 wp->lcn = ((mbox_cmd_t*)wp->mbox)->cmd.lcn;     
2331
2332                                 DBG_PRINTK(KERN_INFO "\nwansock: PLACE CALL OK %i\n",
2333                                         wp->lcn);
2334                                 err = 0;
2335
2336                         } else if (sk->sk_state == WANSOCK_CONNECTING &&
2337                                    (flags & O_NONBLOCK)) {
2338                                 wp->lcn = ((mbox_cmd_t*)wp->mbox)->cmd.lcn;
2339                                 DBG_PRINTK(KERN_INFO "\nwansock: Place Call OK: Waiting %i\n",
2340                                         wp->lcn);
2341
2342                                 err = 0;
2343
2344                         }else{
2345                                 DBG_PRINTK(KERN_INFO "\nwansock: Place call Failed\n");
2346                                 err = -ECONNREFUSED;
2347                         }
2348
2349                         break;
2350
2351                 default: 
2352                         return -EINVAL;
2353         }
2354
2355         return err;
2356 }
2357
2358 static int check_driver_busy (struct sock *sk)
2359 {
2360         struct net_device *dev = dev_get_by_index(sk->sk_bound_dev_if);
2361         wanpipe_common_t *chan;
2362
2363         if (!dev)
2364                 return 0;
2365
2366         dev_put(dev);
2367
2368         if ((chan=dev->priv) == NULL)
2369                 return 0;
2370
2371         return atomic_read(&chan->driver_busy);
2372 }
2373
2374
2375 /*======================================================================
2376  * wanpipe_accept
2377  *
2378  *      ACCEPT() System call.   X25API Specific function. 
2379  *      For each incoming call, create a new socket and 
2380  *      return it to the user.  
2381  *=====================================================================*/
2382
2383 static int wanpipe_accept(struct socket *sock, struct socket *newsock, int flags)
2384 {
2385         struct sock *sk;
2386         struct sock *newsk;
2387         struct sk_buff *skb;
2388         DECLARE_WAITQUEUE(wait, current);
2389         int err=0;
2390
2391         if (newsock->sk != NULL){
2392                 wanpipe_kill_sock_accept(newsock->sk);  
2393                 newsock->sk=NULL;
2394         }
2395         
2396         if ((sk = sock->sk) == NULL)
2397                 return -EINVAL;
2398
2399         if (sk->sk_type != SOCK_RAW)
2400                 return -EOPNOTSUPP;
2401
2402         if (sk->sk_state != WANSOCK_LISTEN)
2403                 return -EINVAL;
2404
2405         if (wp_sk(sk)->num != htons(X25_PROT))
2406                 return -EINVAL;
2407
2408         add_wait_queue(sk->sk_sleep,&wait);
2409         current->state = TASK_INTERRUPTIBLE;
2410         for (;;){
2411                 skb = skb_dequeue(&sk->sk_receive_queue);
2412                 if (skb){
2413                         err=0;
2414                         break;
2415                 }
2416                 if (signal_pending(current)) {
2417                         err = -ERESTARTSYS;
2418                         break;
2419                 }
2420                 schedule();
2421         }
2422         current->state = TASK_RUNNING;
2423         remove_wait_queue(sk->sk_sleep,&wait);
2424         
2425         if (err != 0)
2426                 return err;
2427         
2428         newsk = get_newsk_from_skb(skb);
2429         if (!newsk){
2430                 return -EINVAL;
2431         }
2432
2433         set_bit(1,&wanpipe_tx_critical);
2434         write_lock(&wanpipe_sklist_lock);
2435         sk_add_node(newsk, &wanpipe_sklist);
2436         write_unlock(&wanpipe_sklist_lock);
2437         clear_bit(1,&wanpipe_tx_critical);
2438
2439         newsk->sk_socket = newsock;
2440         newsk->sk_sleep = &newsock->wait;
2441
2442         /* Now attach up the new socket */
2443         sk->sk_ack_backlog--;
2444         newsock->sk = newsk;
2445         
2446         kfree_skb(skb);
2447
2448         DBG_PRINTK(KERN_INFO "\nwansock: ACCEPT Got LCN %i\n",
2449                    wp_sk(newsk)->lcn);
2450         return 0;
2451 }
2452
2453 /*======================================================================
2454  *  get_newsk_from_skb
2455  *
2456  *      Accept() uses this function to get the address of the new
2457  *      socket structure.
2458  *=====================================================================*/
2459
2460 struct sock * get_newsk_from_skb (struct sk_buff *skb)
2461 {
2462         struct net_device *dev = skb->dev;
2463         wanpipe_common_t *chan; 
2464
2465         if (!dev){
2466                 return NULL;
2467         }
2468                 
2469         if ((chan = dev->priv) == NULL){
2470                 return NULL;
2471         }
2472                 
2473         if (!chan->sk){
2474                 return NULL;
2475         }
2476         return (struct sock *)chan->sk;
2477 }
2478
2479 /*======================================================================
2480  *  wanpipe_connect
2481  *
2482  *      CONNECT() System Call. X25API specific function
2483  *      Check the state of the sock, and execute PLACE_CALL command.
2484  *      Connect can ether block or return without waiting for connection, 
2485  *      if specified by user.
2486  *=====================================================================*/
2487
2488 static int wanpipe_connect(struct socket *sock, struct sockaddr *uaddr, int addr_len, int flags)
2489 {
2490         struct sock *sk = sock->sk;
2491         struct wan_sockaddr_ll *addr = (struct wan_sockaddr_ll*)uaddr;
2492         struct net_device *dev;
2493         int err;
2494
2495         if (wp_sk(sk)->num != htons(X25_PROT))
2496                 return -EINVAL;
2497
2498         if (sk->sk_state == WANSOCK_CONNECTED)
2499                 return -EISCONN;        /* No reconnect on a seqpacket socket */
2500
2501         if (sk->sk_state != WAN_DISCONNECTED) {
2502                 printk(KERN_INFO "wansock: Trying to connect on channel NON DISCONNECT\n");
2503                 return -ECONNREFUSED;
2504         }
2505
2506         sk->sk_state = WANSOCK_DISCONNECTED;    
2507         sock->state  = SS_UNCONNECTED;
2508
2509         if (addr_len != sizeof(struct wan_sockaddr_ll))
2510                 return -EINVAL;
2511
2512         if (addr->sll_family != AF_WANPIPE)
2513                 return -EINVAL;
2514
2515         if ((dev = dev_get_by_index(sk->sk_bound_dev_if)) == NULL)
2516                 return -ENETUNREACH;
2517
2518         dev_put(dev);
2519         
2520         if (!sock_flag(sk, SOCK_ZAPPED)) /* Must bind first - autobinding does not work */
2521                 return -EINVAL;
2522
2523         sock->state   = SS_CONNECTING;
2524         sk->sk_state  = WANSOCK_CONNECTING;
2525
2526         if (!wp_sk(sk)->mbox) {
2527                 if (wp_sk (sk)->svc)
2528                         return -EINVAL;
2529                 else {
2530                         int err;
2531                         if ((err=set_ioctl_cmd(sk,NULL)) < 0)
2532                                 return err;
2533                 }
2534         }
2535
2536         if ((err=wanpipe_exec_cmd(sk, X25_PLACE_CALL,flags)) != 0){
2537                 sock->state = SS_UNCONNECTED;
2538                 sk->sk_state = WANSOCK_CONNECTED;
2539                 return err;
2540         }
2541
2542         if (sk->sk_state != WANSOCK_CONNECTED && (flags & O_NONBLOCK)) {
2543                 return 0;
2544         }
2545
2546         if (sk->sk_state != WANSOCK_CONNECTED) {
2547                 sock->state = SS_UNCONNECTED;
2548                 return -ECONNREFUSED; 
2549         }
2550
2551         sock->state = SS_CONNECTED;
2552         return 0;
2553 }
2554
2555 struct proto_ops wanpipe_ops = {
2556         .family =       PF_WANPIPE,
2557         .owner =        THIS_MODULE,
2558         .release =      wanpipe_release,
2559         .bind =         wanpipe_bind,
2560         .connect =      wanpipe_connect,
2561         .socketpair =   sock_no_socketpair,
2562         .accept =       wanpipe_accept,
2563         .getname =      wanpipe_getname, 
2564         .poll =         wanpipe_poll,
2565         .ioctl =        wanpipe_ioctl,
2566         .listen =       wanpipe_listen, 
2567         .shutdown =     sock_no_shutdown,
2568         .setsockopt =   sock_no_setsockopt,
2569         .getsockopt =   sock_no_getsockopt,
2570         .sendmsg =      wanpipe_sendmsg,
2571         .recvmsg =      wanpipe_recvmsg
2572 };
2573
2574 static struct net_proto_family wanpipe_family_ops = {
2575         .family = PF_WANPIPE,
2576         .create = wanpipe_create,
2577         .owner  = THIS_MODULE,
2578 };
2579
2580 struct notifier_block wanpipe_netdev_notifier = {
2581         .notifier_call = wanpipe_notifier,
2582 };
2583
2584
2585 #ifdef MODULE
2586 void cleanup_module(void)
2587 {
2588         printk(KERN_INFO "wansock: Cleaning up \n");
2589         unregister_netdevice_notifier(&wanpipe_netdev_notifier);
2590         sock_unregister(PF_WANPIPE);
2591         proto_unregister(&wanpipe_proto);
2592 }
2593
2594 int init_module(void)
2595 {
2596         int rc;
2597
2598         printk(KERN_INFO "wansock: Registering Socket \n");
2599
2600         rc = proto_register(&wanpipe_proto, 0);
2601         if (rc != 0)
2602                 goto out;
2603
2604         sock_register(&wanpipe_family_ops);
2605         register_netdevice_notifier(&wanpipe_netdev_notifier);
2606 out:
2607         return rc;
2608 }
2609 #endif
2610 MODULE_LICENSE("GPL");
2611 MODULE_ALIAS_NETPROTO(PF_WANPIPE);