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