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