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