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