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