/spare/repo/libata-dev branch 'v2.6.13'
[linux-2.6] / drivers / net / wan / sdla_x25.c
1 /*****************************************************************************
2 * sdla_x25.c    WANPIPE(tm) Multiprotocol WAN Link Driver.  X.25 module.
3 *
4 * Author:       Nenad Corbic    <ncorbic@sangoma.com>
5 *
6 * Copyright:    (c) 1995-2001 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 * Apr 03, 2001  Nenad Corbic     o Fixed the rx_skb=NULL bug in x25 in rx_intr().
14 * Dec 26, 2000  Nenad Corbic     o Added a new polling routine, that uses
15 *                                  a kernel timer (more efficient).
16 * Dec 25, 2000  Nenad Corbic     o Updated for 2.4.X kernel
17 * Jul 26, 2000  Nenad Corbic     o Increased the local packet buffering
18 *                                  for API to 4096+header_size. 
19 * Jul 17, 2000  Nenad Corbic     o Fixed the x25 startup bug. Enable 
20 *                                  communications only after all interfaces
21 *                                  come up.  HIGH SVC/PVC is used to calculate
22 *                                  the number of channels.
23 *                                  Enable protocol only after all interfaces
24 *                                  are enabled.
25 * Jul 10, 2000  Nenad Corbic     o Fixed the M_BIT bug. 
26 * Apr 25, 2000  Nenad Corbic     o Pass Modem messages to the API.
27 *                                  Disable idle timeout in X25 API.
28 * Apr 14, 2000  Nenad Corbic     o Fixed: Large LCN number support.
29 *                                  Maximum LCN number is 4095.
30 *                                  Maximum number of X25 channels is 255.
31 * Apr 06, 2000  Nenad Corbic     o Added SMP Support.
32 * Mar 29, 2000  Nenad Corbic     o Added support for S514 PCI Card
33 * Mar 23, 2000  Nenad Corbic     o Improved task queue, BH handling.
34 * Mar 14, 2000  Nenad Corbic     o Updated Protocol Violation handling
35 *                                  routines.  Bug Fix.
36 * Mar 10, 2000  Nenad Corbic     o Bug Fix: corrupted mbox recovery.
37 * Mar 09, 2000  Nenad Corbic     o Fixed the auto HDLC bug.
38 * Mar 08, 2000  Nenad Corbic     o Fixed LAPB HDLC startup problems.
39 *                                  Application must bring the link up 
40 *                                  before tx/rx, and bring the 
41 *                                  link down on close().
42 * Mar 06, 2000  Nenad Corbic     o Added an option for logging call setup 
43 *                                  information. 
44 * Feb 29, 2000  Nenad Corbic     o Added support for LAPB HDLC API
45 * Feb 25, 2000  Nenad Corbic     o Fixed the modem failure handling.
46 *                                  No Modem OOB message will be passed 
47 *                                  to the user.
48 * Feb 21, 2000  Nenad Corbic     o Added Xpipemon Debug Support
49 * Dec 30, 1999  Nenad Corbic     o Socket based X25API 
50 * Sep 17, 1998  Jaspreet Singh   o Updates for 2.2.X  kernel
51 * Mar 15, 1998  Alan Cox         o 2.1.x porting
52 * Dec 19, 1997  Jaspreet Singh   o Added multi-channel IPX support
53 * Nov 27, 1997  Jaspreet Singh   o Added protection against enabling of irqs
54 *                                  when they are disabled.
55 * Nov 17, 1997  Farhan Thawar    o Added IPX support
56 *                                o Changed if_send() to now buffer packets when
57 *                                  the board is busy
58 *                                o Removed queueing of packets via the polling
59 *                                  routing
60 *                                o Changed if_send() critical flags to properly
61 *                                  handle race conditions
62 * Nov 06, 1997  Farhan Thawar    o Added support for SVC timeouts
63 *                                o Changed PVC encapsulation to ETH_P_IP
64 * Jul 21, 1997  Jaspreet Singh   o Fixed freeing up of buffers using kfree()
65 *                                  when packets are received.
66 * Mar 11, 1997  Farhan Thawar   Version 3.1.1
67 *                                o added support for V35
68 *                                o changed if_send() to return 0 if
69 *                                  wandev.critical() is true
70 *                                o free socket buffer in if_send() if
71 *                                  returning 0
72 *                                o added support for single '@' address to
73 *                                  accept all incoming calls
74 *                                o fixed bug in set_chan_state() to disconnect
75 * Jan 15, 1997  Gene Kozin      Version 3.1.0
76 *                                o implemented exec() entry point
77 * Jan 07, 1997  Gene Kozin      Initial version.
78 *****************************************************************************/
79
80 /*======================================================
81  *      Includes 
82  *=====================================================*/
83
84 #include <linux/module.h>
85 #include <linux/kernel.h>       /* printk(), and other useful stuff */
86 #include <linux/stddef.h>       /* offsetof(), etc. */
87 #include <linux/errno.h>        /* return codes */
88 #include <linux/string.h>       /* inline memset(), etc. */
89 #include <linux/ctype.h>
90 #include <linux/slab.h> /* kmalloc(), kfree() */
91 #include <linux/wanrouter.h>    /* WAN router definitions */
92 #include <linux/wanpipe.h>      /* WANPIPE common user API definitions */
93 #include <linux/workqueue.h>
94 #include <linux/jiffies.h>      /* time_after() macro */
95 #include <asm/byteorder.h>      /* htons(), etc. */
96 #include <asm/atomic.h>
97 #include <linux/delay.h>        /* Experimental delay */
98
99 #include <asm/uaccess.h>
100
101 #include <linux/if.h>
102 #include <linux/if_arp.h>
103 #include <linux/sdla_x25.h>     /* X.25 firmware API definitions */
104 #include <linux/if_wanpipe_common.h>
105 #include <linux/if_wanpipe.h>
106
107
108 /*======================================================
109  *      Defines & Macros 
110  *=====================================================*/
111
112
113 #define CMD_OK          0               /* normal firmware return code */
114 #define CMD_TIMEOUT     0xFF            /* firmware command timed out */
115 #define MAX_CMD_RETRY   10              /* max number of firmware retries */
116
117 #define X25_CHAN_MTU    4096            /* unfragmented logical channel MTU */
118 #define X25_HRDHDR_SZ   7               /* max encapsulation header size */
119 #define X25_CONCT_TMOUT (90*HZ)         /* link connection timeout */
120 #define X25_RECON_TMOUT (10*HZ)         /* link connection timeout */
121 #define CONNECT_TIMEOUT (90*HZ)         /* link connection timeout */
122 #define HOLD_DOWN_TIME  (30*HZ)         /* link hold down time */
123 #define MAX_BH_BUFF     10
124 #define M_BIT           0x01    
125
126 //#define PRINT_DEBUG 1
127 #ifdef PRINT_DEBUG
128 #define DBG_PRINTK(format, a...) printk(format, ## a)
129 #else
130 #define DBG_PRINTK(format, a...)
131 #endif  
132
133 #define TMR_INT_ENABLED_POLL_ACTIVE      0x01
134 #define TMR_INT_ENABLED_POLL_CONNECT_ON  0x02
135 #define TMR_INT_ENABLED_POLL_CONNECT_OFF 0x04
136 #define TMR_INT_ENABLED_POLL_DISCONNECT  0x08
137 #define TMR_INT_ENABLED_CMD_EXEC         0x10
138 #define TMR_INT_ENABLED_UPDATE           0x20
139 #define TMR_INT_ENABLED_UDP_PKT          0x40
140
141 #define MAX_X25_ADDR_SIZE       16
142 #define MAX_X25_DATA_SIZE       129
143 #define MAX_X25_FACL_SIZE       110
144
145 #define TRY_CMD_AGAIN   2
146 #define DELAY_RESULT    1
147 #define RETURN_RESULT   0
148
149 #define DCD(x) (x & 0x03 ? "HIGH" : "LOW")
150 #define CTS(x) (x & 0x05 ? "HIGH" : "LOW")
151
152
153 /* Driver will not write log messages about 
154  * modem status if defined.*/
155 #define MODEM_NOT_LOG 1
156
157 /*==================================================== 
158  *      For IPXWAN 
159  *===================================================*/
160
161 #define CVHexToAscii(b) (((unsigned char)(b) > (unsigned char)9) ? ((unsigned char)'A' + ((unsigned char)(b) - (unsigned char)10)) : ((unsigned char)'0' + (unsigned char)(b)))
162
163
164 /*====================================================
165  *           MEMORY DEBUGGING FUNCTION
166  *====================================================
167
168 #define KMEM_SAFETYZONE 8
169
170 static void * dbg_kmalloc(unsigned int size, int prio, int line) {
171         int i = 0;
172         void * v = kmalloc(size+sizeof(unsigned int)+2*KMEM_SAFETYZONE*8,prio);
173         char * c1 = v;  
174         c1 += sizeof(unsigned int);
175         *((unsigned int *)v) = size;
176
177         for (i = 0; i < KMEM_SAFETYZONE; i++) {
178                 c1[0] = 'D'; c1[1] = 'E'; c1[2] = 'A'; c1[3] = 'D';
179                 c1[4] = 'B'; c1[5] = 'E'; c1[6] = 'E'; c1[7] = 'F';
180                 c1 += 8;
181         }
182         c1 += size;
183         for (i = 0; i < KMEM_SAFETYZONE; i++) {
184                 c1[0] = 'M'; c1[1] = 'U'; c1[2] = 'N'; c1[3] = 'G';
185                 c1[4] = 'W'; c1[5] = 'A'; c1[6] = 'L'; c1[7] = 'L';
186                 c1 += 8;
187         }
188         v = ((char *)v) + sizeof(unsigned int) + KMEM_SAFETYZONE*8;
189         printk(KERN_INFO "line %d  kmalloc(%d,%d) = %p\n",line,size,prio,v);
190         return v;
191 }
192 static void dbg_kfree(void * v, int line) {
193         unsigned int * sp = (unsigned int *)(((char *)v) - (sizeof(unsigned int) + KMEM_SAFETYZONE*8));
194         unsigned int size = *sp;
195         char * c1 = ((char *)v) - KMEM_SAFETYZONE*8;
196         int i = 0;
197         for (i = 0; i < KMEM_SAFETYZONE; i++) {
198                 if (   c1[0] != 'D' || c1[1] != 'E' || c1[2] != 'A' || c1[3] != 'D'
199                     || c1[4] != 'B' || c1[5] != 'E' || c1[6] != 'E' || c1[7] != 'F') {
200                         printk(KERN_INFO "kmalloced block at %p has been corrupted (underrun)!\n",v);
201                         printk(KERN_INFO " %4x: %2x %2x %2x %2x %2x %2x %2x %2x\n", i*8,
202                                         c1[0],c1[1],c1[2],c1[3],c1[4],c1[5],c1[6],c1[7] );
203                 }
204                 c1 += 8;
205         }
206         c1 += size;
207         for (i = 0; i < KMEM_SAFETYZONE; i++) {
208                 if (   c1[0] != 'M' || c1[1] != 'U' || c1[2] != 'N' || c1[3] != 'G'
209                     || c1[4] != 'W' || c1[5] != 'A' || c1[6] != 'L' || c1[7] != 'L'
210                    ) {
211                         printk(KERN_INFO "kmalloced block at %p has been corrupted (overrun):\n",v);
212                         printk(KERN_INFO " %4x: %2x %2x %2x %2x %2x %2x %2x %2x\n", i*8,
213                                         c1[0],c1[1],c1[2],c1[3],c1[4],c1[5],c1[6],c1[7] );
214                 }
215                 c1 += 8;
216         }
217         printk(KERN_INFO "line %d  kfree(%p)\n",line,v);
218         v = ((char *)v) - (sizeof(unsigned int) + KMEM_SAFETYZONE*8);
219         kfree(v);
220 }
221
222 #define kmalloc(x,y) dbg_kmalloc(x,y,__LINE__)
223 #define kfree(x) dbg_kfree(x,__LINE__)
224
225 ==============================================================*/
226
227
228
229 /*===============================================
230  *      Data Structures 
231  *===============================================*/
232
233
234 /*========================================================
235  * Name:        x25_channel
236  *
237  * Purpose:     To hold private informaton for each  
238  *              logical channel.
239  *              
240  * Rationale:   Per-channel debugging is possible if each 
241  *              channel has its own private area.
242  *      
243  * Assumptions:
244  *
245  * Description: This is an extention of the struct net_device
246  *              we create for each network interface to keep 
247  *              the rest of X.25 channel-specific data. 
248  *
249  * Construct:   Typedef
250  */
251 typedef struct x25_channel
252 {
253         wanpipe_common_t common;        /* common area for x25api and socket */
254         char name[WAN_IFNAME_SZ+1];     /* interface name, ASCIIZ */
255         char addr[WAN_ADDRESS_SZ+1];    /* media address, ASCIIZ */
256         unsigned tx_pkt_size;
257         unsigned short protocol;        /* ethertype, 0 - multiplexed */
258         char drop_sequence;             /* mark sequence for dropping */
259         unsigned long state_tick;       /* time of the last state change */
260         unsigned idle_timeout;          /* sec, before disconnecting */
261         unsigned long i_timeout_sofar;  /* # of sec's we've been idle */
262         unsigned hold_timeout;          /* sec, before re-connecting */
263         unsigned long tick_counter;     /* counter for transmit time out */
264         char devtint;                   /* Weather we should dev_tint() */
265         struct sk_buff* rx_skb;         /* receive socket buffer */
266         struct sk_buff* tx_skb;         /* transmit socket buffer */
267
268         bh_data_t *bh_head;               /* Circular buffer for x25api_bh */
269         unsigned long  tq_working;
270         volatile int  bh_write;
271         volatile int  bh_read;
272         atomic_t  bh_buff_used;
273
274         sdla_t* card;                   /* -> owner */
275         struct net_device *dev;         /* -> bound devce */
276
277         int ch_idx;
278         unsigned char enable_IPX;
279         unsigned long network_number;
280         struct net_device_stats ifstats;        /* interface statistics */
281         unsigned short transmit_length;
282         unsigned short tx_offset;
283         char transmit_buffer[X25_CHAN_MTU+sizeof(x25api_hdr_t)];
284
285         if_send_stat_t   if_send_stat;
286         rx_intr_stat_t   rx_intr_stat;
287         pipe_mgmt_stat_t pipe_mgmt_stat;    
288
289         unsigned long router_start_time; /* Router start time in seconds */
290         unsigned long router_up_time;
291         
292 } x25_channel_t;
293
294 /* FIXME Take this out */
295
296 #ifdef NEX_OLD_CALL_INFO
297 typedef struct x25_call_info
298 {
299         char dest[17];                  PACKED;/* ASCIIZ destination address */
300         char src[17];                   PACKED;/* ASCIIZ source address */
301         char nuser;                     PACKED;/* number of user data bytes */
302         unsigned char user[127];        PACKED;/* user data */
303         char nfacil;                    PACKED;/* number of facilities */
304         struct
305         {
306                 unsigned char code;     PACKED;
307                 unsigned char parm;     PACKED;
308         } facil[64];                            /* facilities */
309 } x25_call_info_t;
310 #else
311 typedef struct x25_call_info
312 {
313         char dest[MAX_X25_ADDR_SIZE]            PACKED;/* ASCIIZ destination address */
314         char src[MAX_X25_ADDR_SIZE]             PACKED;/* ASCIIZ source address */
315         unsigned char nuser                     PACKED;
316         unsigned char user[MAX_X25_DATA_SIZE]   PACKED;/* user data */
317         unsigned char nfacil                    PACKED;
318         unsigned char facil[MAX_X25_FACL_SIZE]  PACKED;
319         unsigned short lcn                      PACKED;
320 } x25_call_info_t;
321 #endif
322
323
324   
325 /*===============================================
326  *      Private Function Prototypes
327  *==============================================*/
328
329
330 /*================================================= 
331  * WAN link driver entry points. These are 
332  * called by the WAN router module.
333  */
334 static int update(struct wan_device* wandev);
335 static int new_if(struct wan_device* wandev, struct net_device* dev,
336                   wanif_conf_t* conf);
337 static int del_if(struct wan_device* wandev, struct net_device* dev);
338 static void disable_comm (sdla_t* card);
339 static void disable_comm_shutdown(sdla_t *card);
340
341
342
343 /*================================================= 
344  *      WANPIPE-specific entry points 
345  */
346 static int wpx_exec (struct sdla* card, void* u_cmd, void* u_data);
347 static void x25api_bh(struct net_device *dev);
348 static int x25api_bh_cleanup(struct net_device *dev);
349 static int bh_enqueue(struct net_device *dev, struct sk_buff *skb);
350
351
352 /*=================================================  
353  *      Network device interface 
354  */
355 static int if_init(struct net_device* dev);
356 static int if_open(struct net_device* dev);
357 static int if_close(struct net_device* dev);
358 static int if_header(struct sk_buff* skb, struct net_device* dev,
359         unsigned short type, void* daddr, void* saddr, unsigned len);
360 static int if_rebuild_hdr (struct sk_buff* skb);
361 static int if_send(struct sk_buff* skb, struct net_device* dev);
362 static struct net_device_stats *if_stats(struct net_device* dev);
363
364 static void if_tx_timeout(struct net_device *dev);
365
366 /*=================================================  
367  *      Interrupt handlers 
368  */
369 static void wpx_isr     (sdla_t *);
370 static void rx_intr     (sdla_t *);
371 static void tx_intr     (sdla_t *);
372 static void status_intr (sdla_t *);
373 static void event_intr  (sdla_t *);
374 static void spur_intr   (sdla_t *);
375 static void timer_intr  (sdla_t *);
376
377 static int tx_intr_send(sdla_t *card, struct net_device *dev);
378 static struct net_device *move_dev_to_next(sdla_t *card,
379                                            struct net_device *dev);
380
381 /*=================================================  
382  *      Background polling routines 
383  */
384 static void wpx_poll (sdla_t* card);
385 static void poll_disconnected (sdla_t* card);
386 static void poll_connecting (sdla_t* card);
387 static void poll_active (sdla_t* card);
388 static void trigger_x25_poll(sdla_t *card);
389 static void x25_timer_routine(unsigned long data);
390
391
392
393 /*=================================================  
394  *      X.25 firmware interface functions 
395  */
396 static int x25_get_version (sdla_t* card, char* str);
397 static int x25_configure (sdla_t* card, TX25Config* conf);
398 static int hdlc_configure (sdla_t* card, TX25Config* conf);
399 static int set_hdlc_level (sdla_t* card);
400 static int x25_get_err_stats (sdla_t* card);
401 static int x25_get_stats (sdla_t* card);
402 static int x25_set_intr_mode (sdla_t* card, int mode);
403 static int x25_close_hdlc (sdla_t* card);
404 static int x25_open_hdlc (sdla_t* card);
405 static int x25_setup_hdlc (sdla_t* card);
406 static int x25_set_dtr (sdla_t* card, int dtr);
407 static int x25_get_chan_conf (sdla_t* card, x25_channel_t* chan);
408 static int x25_place_call (sdla_t* card, x25_channel_t* chan);
409 static int x25_accept_call (sdla_t* card, int lcn, int qdm);
410 static int x25_clear_call (sdla_t* card, int lcn, int cause, int diagn);
411 static int x25_send (sdla_t* card, int lcn, int qdm, int len, void* buf);
412 static int x25_fetch_events (sdla_t* card);
413 static int x25_error (sdla_t* card, int err, int cmd, int lcn);
414
415 /*=================================================  
416  *      X.25 asynchronous event handlers 
417  */
418 static int incoming_call (sdla_t* card, int cmd, int lcn, TX25Mbox* mb);
419 static int call_accepted (sdla_t* card, int cmd, int lcn, TX25Mbox* mb);
420 static int call_cleared (sdla_t* card, int cmd, int lcn, TX25Mbox* mb);
421 static int timeout_event (sdla_t* card, int cmd, int lcn, TX25Mbox* mb);
422 static int restart_event (sdla_t* card, int cmd, int lcn, TX25Mbox* mb);
423
424
425 /*=================================================  
426  *      Miscellaneous functions 
427  */
428 static int connect (sdla_t* card);
429 static int disconnect (sdla_t* card);
430 static struct net_device* get_dev_by_lcn(struct wan_device* wandev,
431                                          unsigned lcn);
432 static int chan_connect(struct net_device* dev);
433 static int chan_disc(struct net_device* dev);
434 static void set_chan_state(struct net_device* dev, int state);
435 static int chan_send(struct net_device *dev, void* buff, unsigned data_len,
436                      unsigned char tx_intr);
437 static unsigned char bps_to_speed_code (unsigned long bps);
438 static unsigned int dec_to_uint (unsigned char* str, int len);
439 static unsigned int hex_to_uint (unsigned char*, int);
440 static void parse_call_info (unsigned char*, x25_call_info_t*);
441 static struct net_device *find_channel(sdla_t *card, unsigned lcn);
442 static void bind_lcn_to_dev(sdla_t *card, struct net_device *dev, unsigned lcn);
443 static void setup_for_delayed_transmit(struct net_device *dev,
444                                        void *buf, unsigned len);
445
446
447 /*=================================================  
448  *      X25 API Functions 
449  */
450 static int wanpipe_pull_data_in_skb(sdla_t *card, struct net_device *dev,
451                                     struct sk_buff **);
452 static void timer_intr_exec(sdla_t *, unsigned char);
453 static int execute_delayed_cmd(sdla_t *card, struct net_device *dev,
454                                mbox_cmd_t *usr_cmd, char bad_cmd);
455 static int api_incoming_call (sdla_t*, TX25Mbox *, int);
456 static int alloc_and_init_skb_buf (sdla_t *,struct sk_buff **, int);
457 static void send_delayed_cmd_result(sdla_t *card, struct net_device *dev,
458                                     TX25Mbox* mbox);
459 static int clear_confirm_event (sdla_t *, TX25Mbox*);
460 static void send_oob_msg (sdla_t *card, struct net_device *dev, TX25Mbox *mbox);
461 static int timer_intr_cmd_exec(sdla_t *card);
462 static void api_oob_event (sdla_t *card,TX25Mbox *mbox);
463 static int check_bad_command(sdla_t *card, struct net_device *dev);
464 static int channel_disconnect(sdla_t* card, struct net_device *dev);
465 static void hdlc_link_down (sdla_t*);
466
467 /*=================================================
468  *     XPIPEMON Functions
469  */
470 static int process_udp_mgmt_pkt(sdla_t *);
471 static int udp_pkt_type( struct sk_buff *, sdla_t*);
472 static int reply_udp( unsigned char *, unsigned int); 
473 static void init_x25_channel_struct( x25_channel_t *);
474 static void init_global_statistics( sdla_t *);
475 static int store_udp_mgmt_pkt(int udp_type, char udp_pkt_src, sdla_t *card,
476                               struct net_device *dev,
477                               struct sk_buff *skb, int lcn);
478 static unsigned short calc_checksum (char *, int);
479
480
481
482 /*================================================= 
483  *      IPX functions 
484  */
485 static void switch_net_numbers(unsigned char *, unsigned long, unsigned char);
486 static int handle_IPXWAN(unsigned char *, char *, unsigned char , 
487                          unsigned long , unsigned short );
488
489 extern void disable_irq(unsigned int);
490 extern void enable_irq(unsigned int);
491
492 static void S508_S514_lock(sdla_t *, unsigned long *);
493 static void S508_S514_unlock(sdla_t *, unsigned long *);
494
495
496 /*=================================================  
497  *      Global Variables 
498  *=================================================*/
499
500
501
502 /*================================================= 
503  *      Public Functions 
504  *=================================================*/
505
506
507
508
509 /*===================================================================
510  * wpx_init:    X.25 Protocol Initialization routine.
511  *
512  * Purpose:     To initialize the protocol/firmware.
513  * 
514  * Rationale:   This function is called by setup() function, in
515  *              sdlamain.c, to dynamically setup the x25 protocol.
516  *              This is the first protocol specific function, which
517  *              executes once on startup.
518  *                
519  * Description: This procedure initializes the x25 firmware and
520  *              sets up the mailbox, transmit and receive buffer
521  *              pointers. It also initializes all debugging structures
522  *              and sets up the X25 environment.
523  *
524  *              Sets up hardware options defined by user in [wanpipe#] 
525  *              section of wanpipe#.conf configuration file. 
526  *
527  *              At this point adapter is completely initialized 
528  *              and X.25 firmware is running.
529  *              o read firmware version (to make sure it's alive)
530  *              o configure adapter
531  *              o initialize protocol-specific fields of the 
532  *                adapter data space.
533  *
534  * Called by:   setup() function in sdlamain.c
535  *
536  * Assumptions: None
537  *
538  * Warnings:    None
539  *
540  * Return:      0       o.k.
541  *              < 0     failure.
542  */
543
544 int wpx_init (sdla_t* card, wandev_conf_t* conf)
545 {
546         union{
547                 char str[80];
548                 TX25Config cfg;
549         } u;
550
551         /* Verify configuration ID */
552         if (conf->config_id != WANCONFIG_X25){
553                 printk(KERN_INFO "%s: invalid configuration ID %u!\n",
554                         card->devname, conf->config_id)
555                 ;
556                 return -EINVAL;
557         }
558
559         /* Initialize protocol-specific fields */
560         card->mbox  = (void*)(card->hw.dpmbase + X25_MBOX_OFFS);
561         card->rxmb  = (void*)(card->hw.dpmbase + X25_RXMBOX_OFFS);
562         card->flags = (void*)(card->hw.dpmbase + X25_STATUS_OFFS);
563
564         /* Initialize for S514 Card */
565         if(card->hw.type == SDLA_S514) {
566                 card->mbox += X25_MB_VECTOR;
567                 card->flags += X25_MB_VECTOR;
568                 card->rxmb += X25_MB_VECTOR;
569         }
570
571
572         /* Read firmware version.  Note that when adapter initializes, it
573          * clears the mailbox, so it may appear that the first command was
574          * executed successfully when in fact it was merely erased. To work
575          * around this, we execute the first command twice.
576          */
577         if (x25_get_version(card, NULL) || x25_get_version(card, u.str))
578                 return -EIO;
579
580
581         /* X25 firmware can run ether in X25 or LAPB HDLC mode.
582          * Check the user defined option and configure accordingly */
583         if (conf->u.x25.LAPB_hdlc_only == WANOPT_YES){
584                 if (set_hdlc_level(card) != CMD_OK){
585                         return -EIO;    
586                 }else{
587                         printk(KERN_INFO "%s: running LAP_B HDLC firmware v%s\n",
588                                 card->devname, u.str);
589                 }
590                 card->u.x.LAPB_hdlc = 1;
591         }else{
592                 printk(KERN_INFO "%s: running X.25 firmware v%s\n",
593                                 card->devname, u.str);
594                 card->u.x.LAPB_hdlc = 0;
595         }
596
597         /* Configure adapter. Here we set resonable defaults, then parse
598          * device configuration structure and set configuration options.
599          * Most configuration options are verified and corrected (if
600          * necessary) since we can't rely on the adapter to do so.
601          */
602         memset(&u.cfg, 0, sizeof(u.cfg));
603         u.cfg.t1                = 3;
604         u.cfg.n2                = 10;
605         u.cfg.autoHdlc          = 1;            /* automatic HDLC connection */
606         u.cfg.hdlcWindow        = 7;
607         u.cfg.pktWindow         = 2;
608         u.cfg.station           = 1;            /* DTE */
609         u.cfg.options           = 0x0090;       /* disable D-bit pragmatics */
610         u.cfg.ccittCompat       = 1988;
611         u.cfg.t10t20            = 30;
612         u.cfg.t11t21            = 30;
613         u.cfg.t12t22            = 30;
614         u.cfg.t13t23            = 30;
615         u.cfg.t16t26            = 30;
616         u.cfg.t28               = 30;
617         u.cfg.r10r20            = 5;
618         u.cfg.r12r22            = 5;
619         u.cfg.r13r23            = 5;
620         u.cfg.responseOpt       = 1;            /* RR's after every packet */
621
622         if (card->u.x.LAPB_hdlc){
623                 u.cfg.hdlcMTU = 1027;
624         }
625
626         if (conf->u.x25.x25_conf_opt){
627                 u.cfg.options = conf->u.x25.x25_conf_opt;
628         }
629
630         if (conf->clocking != WANOPT_EXTERNAL)
631                 u.cfg.baudRate = bps_to_speed_code(conf->bps);
632
633         if (conf->station != WANOPT_DTE){
634                 u.cfg.station = 0;              /* DCE mode */
635         }
636
637         if (conf->interface != WANOPT_RS232 ){
638                 u.cfg.hdlcOptions |= 0x80;      /* V35 mode */
639         } 
640
641         /* adjust MTU */
642         if (!conf->mtu || (conf->mtu >= 1024))
643                 card->wandev.mtu = 1024;
644         else if (conf->mtu >= 512)
645                 card->wandev.mtu = 512;
646         else if (conf->mtu >= 256)
647                 card->wandev.mtu = 256;
648         else if (conf->mtu >= 128)
649                 card->wandev.mtu = 128;
650         else 
651                 card->wandev.mtu = 64;
652
653         u.cfg.defPktSize = u.cfg.pktMTU = card->wandev.mtu;
654
655         if (conf->u.x25.hi_pvc){
656                 card->u.x.hi_pvc = min_t(unsigned int, conf->u.x25.hi_pvc, MAX_LCN_NUM);
657                 card->u.x.lo_pvc = min_t(unsigned int, conf->u.x25.lo_pvc, card->u.x.hi_pvc);
658         }
659
660         if (conf->u.x25.hi_svc){
661                 card->u.x.hi_svc = min_t(unsigned int, conf->u.x25.hi_svc, MAX_LCN_NUM);
662                 card->u.x.lo_svc = min_t(unsigned int, conf->u.x25.lo_svc, card->u.x.hi_svc);
663         }
664
665         /* Figure out the total number of channels to configure */
666         card->u.x.num_of_ch = 0;
667         if (card->u.x.hi_svc != 0){
668                 card->u.x.num_of_ch = (card->u.x.hi_svc - card->u.x.lo_svc) + 1;
669         }
670         if (card->u.x.hi_pvc != 0){
671                 card->u.x.num_of_ch += (card->u.x.hi_pvc - card->u.x.lo_pvc) + 1;
672         }
673
674         if (card->u.x.num_of_ch == 0){
675                 printk(KERN_INFO "%s: ERROR, Minimum number of PVC/SVC channels is 1 !\n"
676                                  "%s: Please set the Lowest/Highest PVC/SVC values !\n",
677                                  card->devname,card->devname);
678                 return -ECHRNG;
679         }
680         
681         u.cfg.loPVC = card->u.x.lo_pvc;
682         u.cfg.hiPVC = card->u.x.hi_pvc;
683         u.cfg.loTwoWaySVC = card->u.x.lo_svc;
684         u.cfg.hiTwoWaySVC = card->u.x.hi_svc;
685
686         if (conf->u.x25.hdlc_window)
687                 u.cfg.hdlcWindow = min_t(unsigned int, conf->u.x25.hdlc_window, 7);
688         if (conf->u.x25.pkt_window)
689                 u.cfg.pktWindow = min_t(unsigned int, conf->u.x25.pkt_window, 7);
690
691         if (conf->u.x25.t1)
692                 u.cfg.t1 = min_t(unsigned int, conf->u.x25.t1, 30);
693         if (conf->u.x25.t2)
694                 u.cfg.t2 = min_t(unsigned int, conf->u.x25.t2, 29);
695         if (conf->u.x25.t4)
696                 u.cfg.t4 = min_t(unsigned int, conf->u.x25.t4, 240);
697         if (conf->u.x25.n2)
698                 u.cfg.n2 = min_t(unsigned int, conf->u.x25.n2, 30);
699
700         if (conf->u.x25.t10_t20)
701                 u.cfg.t10t20 = min_t(unsigned int, conf->u.x25.t10_t20,255);
702         if (conf->u.x25.t11_t21)
703                 u.cfg.t11t21 = min_t(unsigned int, conf->u.x25.t11_t21,255);
704         if (conf->u.x25.t12_t22)
705                 u.cfg.t12t22 = min_t(unsigned int, conf->u.x25.t12_t22,255);
706         if (conf->u.x25.t13_t23)        
707                 u.cfg.t13t23 = min_t(unsigned int, conf->u.x25.t13_t23,255);
708         if (conf->u.x25.t16_t26)
709                 u.cfg.t16t26 = min_t(unsigned int, conf->u.x25.t16_t26, 255);
710         if (conf->u.x25.t28)
711                 u.cfg.t28 = min_t(unsigned int, conf->u.x25.t28, 255);
712
713         if (conf->u.x25.r10_r20)
714                 u.cfg.r10r20 = min_t(unsigned int, conf->u.x25.r10_r20,250);
715         if (conf->u.x25.r12_r22)
716                 u.cfg.r12r22 = min_t(unsigned int, conf->u.x25.r12_r22,250);
717         if (conf->u.x25.r13_r23)
718                 u.cfg.r13r23 = min_t(unsigned int, conf->u.x25.r13_r23,250);
719
720
721         if (conf->u.x25.ccitt_compat)
722                 u.cfg.ccittCompat = conf->u.x25.ccitt_compat;
723
724         /* initialize adapter */
725         if (card->u.x.LAPB_hdlc){
726                 if (hdlc_configure(card, &u.cfg) != CMD_OK)
727                         return -EIO;
728         }else{
729                 if (x25_configure(card, &u.cfg) != CMD_OK)
730                         return -EIO;
731         }
732
733         if ((x25_close_hdlc(card) != CMD_OK) ||         /* close HDLC link */
734             (x25_set_dtr(card, 0) != CMD_OK))           /* drop DTR */
735                 return -EIO;
736
737         /* Initialize protocol-specific fields of adapter data space */
738         card->wandev.bps        = conf->bps;
739         card->wandev.interface  = conf->interface;
740         card->wandev.clocking   = conf->clocking;
741         card->wandev.station    = conf->station;
742         card->isr               = &wpx_isr;
743         card->poll              = NULL; //&wpx_poll;
744         card->disable_comm      = &disable_comm;
745         card->exec              = &wpx_exec;
746         card->wandev.update     = &update;
747         card->wandev.new_if     = &new_if;
748         card->wandev.del_if     = &del_if;
749
750         /* WARNING: This function cannot exit with an error
751          *          after the change of state */
752         card->wandev.state      = WAN_DISCONNECTED;
753         
754         card->wandev.enable_tx_int = 0;
755         card->irq_dis_if_send_count = 0;
756         card->irq_dis_poll_count = 0;
757         card->u.x.tx_dev = NULL;
758         card->u.x.no_dev = 0;
759
760
761         /* Configure for S514 PCI Card */
762         if (card->hw.type == SDLA_S514) {
763                 card->u.x.hdlc_buf_status = 
764                         (volatile unsigned char *)
765                                 (card->hw.dpmbase + X25_MB_VECTOR+ X25_MISC_HDLC_BITS);
766         }else{
767                 card->u.x.hdlc_buf_status = 
768                         (volatile unsigned char *)(card->hw.dpmbase + X25_MISC_HDLC_BITS); 
769         }
770
771         card->u.x.poll_device=NULL;
772         card->wandev.udp_port = conf->udp_port;
773
774         /* Enable or disable call setup logging */
775         if (conf->u.x25.logging == WANOPT_YES){
776                 printk(KERN_INFO "%s: Enabling Call Logging.\n",
777                         card->devname);
778                 card->u.x.logging = 1;
779         }else{  
780                 card->u.x.logging = 0;
781         }
782
783         /* Enable or disable modem status reporting */
784         if (conf->u.x25.oob_on_modem == WANOPT_YES){
785                 printk(KERN_INFO "%s: Enabling OOB on Modem change.\n",
786                         card->devname);
787                 card->u.x.oob_on_modem = 1;
788         }else{
789                 card->u.x.oob_on_modem = 0;
790         }
791         
792         init_global_statistics(card);   
793
794         INIT_WORK(&card->u.x.x25_poll_work, (void *)wpx_poll, card);
795
796         init_timer(&card->u.x.x25_timer);
797         card->u.x.x25_timer.data = (unsigned long)card;
798         card->u.x.x25_timer.function = x25_timer_routine;
799         
800         return 0;
801 }
802
803 /*=========================================================
804  *      WAN Device Driver Entry Points 
805  *========================================================*/
806
807 /*============================================================
808  * Name:        update(),  Update device status & statistics.
809  *
810  * Purpose:     To provide debugging and statitical
811  *              information to the /proc file system.
812  *              /proc/net/wanrouter/wanpipe#
813  *                      
814  * Rationale:   The /proc file system is used to collect
815  *              information about the kernel and drivers.
816  *              Using the /proc file system the user
817  *              can see exactly what the sangoma drivers are
818  *              doing. And in what state they are in. 
819  *                
820  * Description: Collect all driver statistical information
821  *              and pass it to the top laywer. 
822  *              
823  *              Since we have to execute a debugging command, 
824  *              to obtain firmware statitics, we trigger a 
825  *              UPDATE function within the timer interrtup.
826  *              We wait until the timer update is complete.
827  *              Once complete return the appropriate return
828  *              code to indicate that the update was successful.
829  *              
830  * Called by:   device_stat() in wanmain.c
831  *
832  * Assumptions: 
833  *
834  * Warnings:    This function will degrade the performance
835  *              of the router, since it uses the mailbox. 
836  *
837  * Return:      0       OK
838  *              <0      Failed (or busy).
839  */
840
841 static int update(struct wan_device* wandev)
842 {
843         volatile sdla_t* card;
844         TX25Status* status;
845         unsigned long timeout;
846
847         /* sanity checks */
848         if ((wandev == NULL) || (wandev->private == NULL))
849                 return -EFAULT;
850
851         if (wandev->state == WAN_UNCONFIGURED)
852                 return -ENODEV;
853
854         if (test_bit(SEND_CRIT, (void*)&wandev->critical))
855                 return -EAGAIN;
856
857         if (!wandev->dev)
858                 return -ENODEV;
859         
860         card = wandev->private;
861         status = card->flags;
862
863         card->u.x.timer_int_enabled |= TMR_INT_ENABLED_UPDATE;
864         status->imask |= INTR_ON_TIMER;
865         timeout = jiffies;      
866
867         for (;;){
868                 if (!(card->u.x.timer_int_enabled & TMR_INT_ENABLED_UPDATE)){   
869                         break;
870                 }
871                 if (time_after(jiffies, timeout + 1*HZ)){
872                         card->u.x.timer_int_enabled &= ~TMR_INT_ENABLED_UPDATE;
873                         return -EAGAIN;
874                 }
875         }
876         return 0;
877 }
878
879
880 /*===================================================================
881  * Name:        new_if
882  *
883  * Purpose:     To allocate and initialize resources for a 
884  *              new logical channel.  
885  * 
886  * Rationale:   A new channel can be added dynamically via
887  *              ioctl call.
888  *                
889  * Description: Allocate a private channel structure, x25_channel_t.
890  *              Parse the user interface options from wanpipe#.conf 
891  *              configuration file. 
892  *              Bind the private are into the network device private
893  *              area pointer (dev->priv).
894  *              Prepare the network device structure for registration.
895  *
896  * Called by:   ROUTER_IFNEW Ioctl call, from wanrouter_ioctl() 
897  *              (wanmain.c)
898  *
899  * Assumptions: None
900  *
901  * Warnings:    None
902  *
903  * Return:      0       Ok
904  *              <0      Failed (channel will not be created)
905  */
906 static int new_if(struct wan_device* wandev, struct net_device* dev,
907                   wanif_conf_t* conf)
908 {
909         sdla_t* card = wandev->private;
910         x25_channel_t* chan;
911         int err = 0;
912
913         if ((conf->name[0] == '\0') || (strlen(conf->name) > WAN_IFNAME_SZ)){
914                 printk(KERN_INFO "%s: invalid interface name!\n",
915                         card->devname);
916                 return -EINVAL;
917         }
918
919         if(card->wandev.new_if_cnt++ > 0 && card->u.x.LAPB_hdlc) {
920                 printk(KERN_INFO "%s: Error: Running LAPB HDLC Mode !\n",
921                                                 card->devname);
922                 printk(KERN_INFO 
923                         "%s: Maximum number of network interfaces must be one !\n",
924                                                 card->devname);
925                 return -EEXIST;
926         }
927
928         /* allocate and initialize private data */
929         chan = kmalloc(sizeof(x25_channel_t), GFP_ATOMIC);
930         if (chan == NULL){
931                 return -ENOMEM;
932         }
933         
934         memset(chan, 0, sizeof(x25_channel_t));
935
936         /* Bug Fix: Seg Err on PVC startup
937          * It must be here since bind_lcn_to_dev expects 
938          * it bellow */
939         dev->priv = chan;
940         
941         strcpy(chan->name, conf->name);
942         chan->card = card;
943         chan->dev = dev;
944         chan->common.sk = NULL;
945         chan->common.func = NULL;
946         chan->common.rw_bind = 0;
947         chan->tx_skb = chan->rx_skb = NULL;
948
949         /* verify media address */
950         if (conf->addr[0] == '@'){              /* SVC */
951                 chan->common.svc = 1;
952                 strncpy(chan->addr, &conf->addr[1], WAN_ADDRESS_SZ);
953
954                 /* Set channel timeouts (default if not specified) */
955                 chan->idle_timeout = (conf->idle_timeout) ? 
956                                         conf->idle_timeout : 90;
957                 chan->hold_timeout = (conf->hold_timeout) ? 
958                                         conf->hold_timeout : 10;
959
960         }else if (is_digit(conf->addr[0])){     /* PVC */
961                 int lcn = dec_to_uint(conf->addr, 0);
962
963                 if ((lcn >= card->u.x.lo_pvc) && (lcn <= card->u.x.hi_pvc)){
964                         bind_lcn_to_dev (card, dev, lcn);
965                 }else{
966                         printk(KERN_ERR
967                                 "%s: PVC %u is out of range on interface %s!\n",
968                                 wandev->name, lcn, chan->name);
969                         err = -EINVAL;
970                 }
971         }else{
972                 printk(KERN_ERR
973                         "%s: invalid media address on interface %s!\n",
974                         wandev->name, chan->name);
975                 err = -EINVAL;
976         }
977
978         if(strcmp(conf->usedby, "WANPIPE") == 0){
979                 printk(KERN_INFO "%s: Running in WANPIPE mode %s\n",
980                         wandev->name, chan->name);
981                 chan->common.usedby = WANPIPE;
982                 chan->protocol = htons(ETH_P_IP);
983
984         }else if(strcmp(conf->usedby, "API") == 0){
985                 chan->common.usedby = API;
986                 printk(KERN_INFO "%s: Running in API mode %s\n",
987                         wandev->name, chan->name);
988                 chan->protocol = htons(X25_PROT);
989         }
990
991
992         if (err){
993                 kfree(chan);
994                 dev->priv = NULL;
995                 return err;
996         }
997         
998         chan->enable_IPX = conf->enable_IPX;
999         
1000         if (chan->enable_IPX)
1001                 chan->protocol = htons(ETH_P_IPX);
1002         
1003         if (conf->network_number)
1004                 chan->network_number = conf->network_number;
1005         else
1006                 chan->network_number = 0xDEADBEEF;
1007
1008         /* prepare network device data space for registration */
1009         strcpy(dev->name,chan->name);
1010
1011         dev->init = &if_init;
1012
1013         init_x25_channel_struct(chan);
1014
1015         return 0;
1016 }
1017
1018 /*===================================================================
1019  * Name:        del_if(),  Remove a logical channel.     
1020  *
1021  * Purpose:     To dynamically remove a logical channel.
1022  * 
1023  * Rationale:   Each logical channel should be dynamically
1024  *              removable. This functin is called by an 
1025  *              IOCTL_IFDEL ioctl call or shutdown(). 
1026  *                
1027  * Description: Do nothing.
1028  *
1029  * Called by:   IOCTL_IFDEL : wanrouter_ioctl() from wanmain.c
1030  *              shutdown() from sdlamain.c
1031  *
1032  * Assumptions: 
1033  *
1034  * Warnings:
1035  *
1036  * Return:      0 Ok. Void function.
1037  */
1038
1039 //FIXME Del IF Should be taken out now.
1040
1041 static int del_if(struct wan_device* wandev, struct net_device* dev)
1042 {
1043         return 0;
1044 }
1045
1046
1047 /*============================================================
1048  * Name:        wpx_exec
1049  *
1050  * Description: Execute adapter interface command.
1051  *              This option is currently dissabled.
1052  *===========================================================*/
1053
1054 static int wpx_exec (struct sdla* card, void* u_cmd, void* u_data)
1055 {
1056         return 0;
1057 }
1058
1059 /*============================================================
1060  * Name:        disable_comm    
1061  *
1062  * Description: Disable communications during shutdown.
1063  *              Dont check return code because there is 
1064  *              nothing we can do about it.  
1065  *
1066  * Warning:     Dev and private areas are gone at this point.
1067  *===========================================================*/
1068
1069 static void disable_comm(sdla_t* card)
1070 {
1071         disable_comm_shutdown(card);
1072         del_timer(&card->u.x.x25_timer);
1073         return;
1074 }
1075
1076
1077 /*============================================================
1078  *      Network Device Interface 
1079  *===========================================================*/
1080
1081 /*===================================================================
1082  * Name:        if_init(),   Netowrk Interface Initialization    
1083  *
1084  * Purpose:     To initialize a network interface device structure.
1085  * 
1086  * Rationale:   During network interface startup, the if_init
1087  *              is called by the kernel to initialize the
1088  *              netowrk device structure.  Thus a driver
1089  *              can customze a network device. 
1090  *                
1091  * Description: Initialize the netowrk device call back
1092  *              routines.  This is where we tell the kernel
1093  *              which function to use when it wants to send
1094  *              via our interface. 
1095  *              Furthermore, we initialize the device flags, 
1096  *              MTU and physical address of the board.
1097  *
1098  * Called by:   Kernel (/usr/src/linux/net/core/dev.c)
1099  *              (dev->init())
1100  *
1101  * Assumptions: None
1102  *      
1103  * Warnings:    None
1104  *
1105  * Return:      0       Ok : Void function.
1106  */
1107 static int if_init(struct net_device* dev)
1108 {
1109         x25_channel_t* chan = dev->priv;
1110         sdla_t* card = chan->card;
1111         struct wan_device* wandev = &card->wandev;
1112
1113         /* Initialize device driver entry points */
1114         dev->open               = &if_open;
1115         dev->stop               = &if_close;
1116         dev->hard_header        = &if_header;
1117         dev->rebuild_header     = &if_rebuild_hdr;
1118         dev->hard_start_xmit    = &if_send;
1119         dev->get_stats          = &if_stats;
1120         dev->tx_timeout         = &if_tx_timeout;
1121         dev->watchdog_timeo     = TX_TIMEOUT;
1122
1123         /* Initialize media-specific parameters */
1124         dev->type               = ARPHRD_PPP;           /* ARP h/w type */
1125         dev->flags              |= IFF_POINTOPOINT;
1126         dev->flags              |= IFF_NOARP;
1127
1128         if (chan->common.usedby == API){
1129                 dev->mtu        = X25_CHAN_MTU+sizeof(x25api_hdr_t);
1130         }else{
1131                 dev->mtu        = card->wandev.mtu;     
1132         }
1133         
1134         dev->hard_header_len    = X25_HRDHDR_SZ; /* media header length */
1135         dev->addr_len           = 2;            /* hardware address length */
1136         
1137         if (!chan->common.svc){
1138                 *(unsigned short*)dev->dev_addr = htons(chan->common.lcn);
1139         }
1140         
1141         /* Initialize hardware parameters (just for reference) */
1142         dev->irq        = wandev->irq;
1143         dev->dma        = wandev->dma;
1144         dev->base_addr  = wandev->ioport;
1145         dev->mem_start  = (unsigned long)wandev->maddr;
1146         dev->mem_end    = wandev->maddr + wandev->msize - 1;
1147
1148         /* Set transmit buffer queue length */
1149         dev->tx_queue_len = 100;
1150         SET_MODULE_OWNER(dev);
1151
1152         /* FIXME Why are we doing this */
1153         set_chan_state(dev, WAN_DISCONNECTED);
1154         return 0;
1155 }
1156
1157
1158 /*===================================================================
1159  * Name:        if_open(),   Open/Bring up the Netowrk Interface 
1160  *
1161  * Purpose:     To bring up a network interface.
1162  * 
1163  * Rationale:   
1164  *                
1165  * Description: Open network interface.
1166  *              o prevent module from unloading by incrementing use count
1167  *              o if link is disconnected then initiate connection
1168  *
1169  * Called by:   Kernel (/usr/src/linux/net/core/dev.c)
1170  *              (dev->open())
1171  *
1172  * Assumptions: None
1173  *      
1174  * Warnings:    None
1175  *
1176  * Return:      0       Ok
1177  *              <0      Failure: Interface will not come up.
1178  */
1179
1180 static int if_open(struct net_device* dev)
1181 {
1182         x25_channel_t* chan = dev->priv;
1183         sdla_t* card = chan->card;
1184         struct timeval tv;
1185         unsigned long smp_flags;
1186         
1187         if (netif_running(dev))
1188                 return -EBUSY;
1189
1190         chan->tq_working = 0;
1191
1192         /* Initialize the workqueue */
1193         INIT_WORK(&chan->common.wanpipe_work, (void *)x25api_bh, dev);
1194
1195         /* Allocate and initialize BH circular buffer */
1196         /* Add 1 to MAX_BH_BUFF so we don't have test with (MAX_BH_BUFF-1) */
1197         chan->bh_head = kmalloc((sizeof(bh_data_t)*(MAX_BH_BUFF+1)),GFP_ATOMIC);
1198
1199         if (chan->bh_head == NULL){
1200                 printk(KERN_INFO "%s: ERROR, failed to allocate memory ! BH_BUFFERS !\n",
1201                                 card->devname);
1202
1203                 return -ENOBUFS;
1204         }
1205         memset(chan->bh_head,0,(sizeof(bh_data_t)*(MAX_BH_BUFF+1)));
1206         atomic_set(&chan->bh_buff_used, 0);
1207
1208         /* Increment the number of interfaces */
1209         ++card->u.x.no_dev;
1210         
1211         wanpipe_open(card);
1212
1213         /* LAPB protocol only uses one interface, thus
1214          * start the protocol after it comes up. */
1215         if (card->u.x.LAPB_hdlc){
1216                 if (card->open_cnt == 1){
1217                         TX25Status* status = card->flags;
1218                         S508_S514_lock(card, &smp_flags);
1219                         x25_set_intr_mode(card, INTR_ON_TIMER); 
1220                         status->imask &= ~INTR_ON_TIMER;
1221                         S508_S514_unlock(card, &smp_flags);
1222                 }
1223         }else{
1224                 /* X25 can have multiple interfaces thus, start the 
1225                  * protocol once all interfaces are up */
1226
1227                 //FIXME: There is a bug here. If interface is
1228                 //brought down and up, it will try to enable comm.
1229                 if (card->open_cnt == card->u.x.num_of_ch){
1230
1231                         S508_S514_lock(card, &smp_flags);
1232                         connect(card);
1233                         S508_S514_unlock(card, &smp_flags);
1234
1235                         mod_timer(&card->u.x.x25_timer, jiffies + HZ);
1236                 }
1237         }
1238         /* Device is not up until the we are in connected state */
1239         do_gettimeofday( &tv );
1240         chan->router_start_time = tv.tv_sec;
1241
1242         netif_start_queue(dev);
1243
1244         return 0;
1245 }
1246
1247 /*===================================================================
1248  * Name:        if_close(),   Close/Bring down the Netowrk Interface 
1249  *
1250  * Purpose:     To bring down a network interface.
1251  * 
1252  * Rationale:   
1253  *                
1254  * Description: Close network interface.
1255  *              o decrement use module use count
1256  *
1257  * Called by:   Kernel (/usr/src/linux/net/core/dev.c)
1258  *              (dev->close())
1259  *              ifconfig <name> down: will trigger the kernel
1260  *              which will call this function.
1261  *
1262  * Assumptions: None
1263  *      
1264  * Warnings:    None
1265  *
1266  * Return:      0       Ok
1267  *              <0      Failure: Interface will not exit properly.
1268  */
1269 static int if_close(struct net_device* dev)
1270 {
1271         x25_channel_t* chan = dev->priv;
1272         sdla_t* card = chan->card;
1273         unsigned long smp_flags;
1274         
1275         netif_stop_queue(dev);
1276
1277         if ((chan->common.state == WAN_CONNECTED) || 
1278             (chan->common.state == WAN_CONNECTING)){
1279                 S508_S514_lock(card, &smp_flags);
1280                 chan_disc(dev);
1281                 S508_S514_unlock(card, &smp_flags);
1282         }
1283
1284         wanpipe_close(card);
1285
1286         S508_S514_lock(card, &smp_flags);
1287         if (chan->bh_head){
1288                 int i;
1289                 struct sk_buff *skb;
1290         
1291                 for (i=0; i<(MAX_BH_BUFF+1); i++){
1292                         skb = ((bh_data_t *)&chan->bh_head[i])->skb;
1293                         if (skb != NULL){
1294                                 dev_kfree_skb_any(skb);
1295                         }
1296                 }
1297                 kfree(chan->bh_head);
1298                 chan->bh_head=NULL;
1299         }
1300         S508_S514_unlock(card, &smp_flags);
1301
1302         /* If this is the last close, disconnect physical link */
1303         if (!card->open_cnt){
1304                 S508_S514_lock(card, &smp_flags);
1305                 disconnect(card);
1306                 x25_set_intr_mode(card, 0);
1307                 S508_S514_unlock(card, &smp_flags);
1308         }
1309         
1310         /* Decrement the number of interfaces */
1311         --card->u.x.no_dev;
1312         return 0;
1313 }
1314
1315 /*======================================================================
1316  *      Build media header.
1317  *      o encapsulate packet according to encapsulation type.
1318  *
1319  *      The trick here is to put packet type (Ethertype) into 'protocol' 
1320  *      field of the socket buffer, so that we don't forget it.  
1321  *      If encapsulation fails, set skb->protocol to 0 and discard 
1322  *      packet later.
1323  *
1324  *      Return:         media header length.
1325  *======================================================================*/
1326
1327 static int if_header(struct sk_buff* skb, struct net_device* dev,
1328                      unsigned short type, void* daddr, void* saddr,
1329                      unsigned len)
1330 {
1331         x25_channel_t* chan = dev->priv;
1332         int hdr_len = dev->hard_header_len;
1333         
1334         skb->protocol = htons(type);
1335         if (!chan->protocol){
1336                 hdr_len = wanrouter_encapsulate(skb, dev, type);
1337                 if (hdr_len < 0){
1338                         hdr_len = 0;
1339                         skb->protocol = htons(0);
1340                 }
1341         }
1342         return hdr_len;
1343 }
1344
1345 /*===============================================================
1346  *      Re-build media header.
1347  *
1348  *      Return:         1       physical address resolved.
1349  *                      0       physical address not resolved
1350  *==============================================================*/
1351
1352 static int if_rebuild_hdr (struct sk_buff* skb)
1353 {
1354         struct net_device *dev = skb->dev; 
1355         x25_channel_t* chan = dev->priv;
1356         sdla_t* card = chan->card;
1357
1358         printk(KERN_INFO "%s: rebuild_header() called for interface %s!\n",
1359                 card->devname, dev->name);
1360         return 1;
1361 }
1362
1363
1364 /*============================================================================
1365  * Handle transmit timeout event from netif watchdog
1366  */
1367 static void if_tx_timeout(struct net_device *dev)
1368 {
1369         x25_channel_t* chan = dev->priv;
1370         sdla_t *card = chan->card;
1371
1372         /* If our device stays busy for at least 5 seconds then we will
1373          * kick start the device by making dev->tbusy = 0.  We expect
1374          * that our device never stays busy more than 5 seconds. So this                 
1375          * is only used as a last resort.
1376          */
1377
1378         ++chan->if_send_stat.if_send_tbusy_timeout;
1379         printk (KERN_INFO "%s: Transmit timed out on %s\n", 
1380                         card->devname, dev->name);
1381         netif_wake_queue (dev);
1382 }
1383
1384
1385 /*=========================================================================
1386  *      Send a packet on a network interface.
1387  *      o set tbusy flag (marks start of the transmission).
1388  *      o check link state. If link is not up, then drop the packet.
1389  *      o check channel status. If it's down then initiate a call.
1390  *      o pass a packet to corresponding WAN device.
1391  *      o free socket buffer
1392  *
1393  *      Return: 0       complete (socket buffer must be freed)
1394  *              non-0   packet may be re-transmitted (tbusy must be set)
1395  *
1396  *      Notes:
1397  *      1. This routine is called either by the protocol stack or by the "net
1398  *      bottom half" (with interrupts enabled).
1399  *      2. Setting tbusy flag will inhibit further transmit requests from the
1400  *      protocol stack and can be used for flow control with protocol layer.
1401  *
1402  *========================================================================*/
1403
1404 static int if_send(struct sk_buff* skb, struct net_device* dev)
1405 {
1406         x25_channel_t* chan = dev->priv;
1407         sdla_t* card = chan->card;
1408         TX25Status* status = card->flags;
1409         int udp_type;
1410         unsigned long smp_flags=0;
1411
1412         ++chan->if_send_stat.if_send_entry;
1413
1414         netif_stop_queue(dev);
1415
1416         /* No need to check frame length, since socket code
1417          * will perform the check for us */
1418
1419         chan->tick_counter = jiffies;
1420         
1421         /* Critical region starts here */
1422         S508_S514_lock(card, &smp_flags);
1423         
1424         if (test_and_set_bit(SEND_CRIT, (void*)&card->wandev.critical)){
1425                 printk(KERN_INFO "Hit critical in if_send()! %lx\n",card->wandev.critical);
1426                 goto if_send_crit_exit;
1427         }
1428         
1429         udp_type = udp_pkt_type(skb, card);
1430
1431         if(udp_type != UDP_INVALID_TYPE) {
1432
1433                 if(store_udp_mgmt_pkt(udp_type, UDP_PKT_FRM_STACK, card, dev, skb,
1434                         chan->common.lcn)) {
1435
1436                         status->imask |= INTR_ON_TIMER;
1437                         if (udp_type == UDP_XPIPE_TYPE){
1438                                 chan->if_send_stat.if_send_PIPE_request++;
1439                         }
1440                 }
1441                 netif_start_queue(dev);
1442                 clear_bit(SEND_CRIT,(void*)&card->wandev.critical);
1443                 S508_S514_unlock(card, &smp_flags);
1444                 return 0;
1445         }
1446
1447         if (chan->transmit_length){
1448                 //FIXME: This check doesn't make sense any more
1449                 if (chan->common.state != WAN_CONNECTED){
1450                         chan->transmit_length=0;
1451                         atomic_set(&chan->common.driver_busy,0);
1452                 }else{
1453                         netif_stop_queue(dev);
1454                         ++card->u.x.tx_interrupts_pending;
1455                         status->imask |= INTR_ON_TX_FRAME;
1456                         clear_bit(SEND_CRIT,(void*)&card->wandev.critical);
1457                         S508_S514_unlock(card, &smp_flags);
1458                         return 1;
1459                 }
1460         }
1461
1462         if (card->wandev.state != WAN_CONNECTED){
1463                 ++chan->ifstats.tx_dropped;
1464                 ++card->wandev.stats.tx_dropped;
1465                 ++chan->if_send_stat.if_send_wan_disconnected;  
1466                 
1467         }else if ( chan->protocol && (chan->protocol != skb->protocol)){
1468                 printk(KERN_INFO
1469                         "%s: unsupported Ethertype 0x%04X on interface %s!\n",
1470                         chan->name, htons(skb->protocol), dev->name);
1471                 
1472                 printk(KERN_INFO "PROTO %Xn", htons(chan->protocol));
1473                 ++chan->ifstats.tx_errors;
1474                 ++chan->ifstats.tx_dropped;
1475                 ++card->wandev.stats.tx_dropped;
1476                 ++chan->if_send_stat.if_send_protocol_error;
1477                 
1478         }else switch (chan->common.state){
1479
1480                 case WAN_DISCONNECTED:
1481                         /* Try to establish connection. If succeded, then start
1482                          * transmission, else drop a packet.
1483                          */
1484                         if (chan->common.usedby == API){
1485                                 ++chan->ifstats.tx_dropped;
1486                                 ++card->wandev.stats.tx_dropped;
1487                                 break;
1488                         }else{
1489                                 if (chan_connect(dev) != 0){
1490                                         ++chan->ifstats.tx_dropped;
1491                                         ++card->wandev.stats.tx_dropped;
1492                                         break;
1493                                 }
1494                         }
1495                         /* fall through */
1496
1497                 case WAN_CONNECTED:
1498                         if( skb->protocol == htons(ETH_P_IPX)) {
1499                                 if(chan->enable_IPX) {
1500                                         switch_net_numbers( skb->data, 
1501                                                 chan->network_number, 0);
1502                                 } else {
1503                                         ++card->wandev.stats.tx_dropped;
1504                                         ++chan->ifstats.tx_dropped;
1505                                         ++chan->if_send_stat.if_send_protocol_error;
1506                                         goto if_send_crit_exit;
1507                                 }
1508                         }
1509                         /* We never drop here, if cannot send than, copy
1510                          * a packet into a transmit buffer 
1511                          */
1512                         chan_send(dev, skb->data, skb->len, 0);
1513                         break;
1514
1515                 default:
1516                         ++chan->ifstats.tx_dropped;     
1517                         ++card->wandev.stats.tx_dropped;
1518                         break;
1519         }
1520
1521
1522 if_send_crit_exit:
1523         
1524         dev_kfree_skb_any(skb);
1525
1526         netif_start_queue(dev);
1527         clear_bit(SEND_CRIT,(void*)&card->wandev.critical);
1528         S508_S514_unlock(card, &smp_flags);
1529         return 0;
1530 }
1531
1532 /*============================================================================
1533  * Setup so that a frame can be transmitted on the occurrence of a transmit
1534  * interrupt.
1535  *===========================================================================*/
1536
1537 static void setup_for_delayed_transmit(struct net_device* dev, void* buf,
1538                                        unsigned len)
1539 {
1540         x25_channel_t* chan = dev->priv;
1541         sdla_t* card = chan->card;
1542         TX25Status* status = card->flags;
1543
1544         ++chan->if_send_stat.if_send_adptr_bfrs_full;
1545
1546         if(chan->transmit_length) {
1547                 printk(KERN_INFO "%s: Error, transmit length set in delayed transmit!\n",
1548                                 card->devname);
1549                 return;
1550         }
1551
1552         if (chan->common.usedby == API){
1553                 if (len > X25_CHAN_MTU+sizeof(x25api_hdr_t)) {
1554                         ++chan->ifstats.tx_dropped;     
1555                         ++card->wandev.stats.tx_dropped;
1556                         printk(KERN_INFO "%s: Length is too big for delayed transmit\n",
1557                                 card->devname);
1558                         return;
1559                 }
1560         }else{
1561                 if (len > X25_MAX_DATA) {
1562                         ++chan->ifstats.tx_dropped;     
1563                         ++card->wandev.stats.tx_dropped;
1564                         printk(KERN_INFO "%s: Length is too big for delayed transmit\n",
1565                                 card->devname);
1566                         return;
1567                 }
1568         }
1569
1570         chan->transmit_length = len;
1571         atomic_set(&chan->common.driver_busy,1);
1572         memcpy(chan->transmit_buffer, buf, len);
1573
1574         ++chan->if_send_stat.if_send_tx_int_enabled;
1575
1576         /* Enable Transmit Interrupt */
1577         ++card->u.x.tx_interrupts_pending;
1578         status->imask |= INTR_ON_TX_FRAME;
1579 }
1580
1581
1582 /*===============================================================
1583  * net_device_stats
1584  *
1585  *      Get ethernet-style interface statistics.
1586  *      Return a pointer to struct enet_statistics.
1587  *
1588  *==============================================================*/
1589 static struct net_device_stats *if_stats(struct net_device* dev)
1590 {
1591         x25_channel_t *chan = dev->priv;
1592
1593         if(chan == NULL)
1594                 return NULL;
1595
1596         return &chan->ifstats;
1597 }
1598
1599
1600 /*
1601  *      Interrupt Handlers 
1602  */
1603
1604 /*
1605  * X.25 Interrupt Service Routine.
1606  */
1607
1608 static void wpx_isr (sdla_t* card)
1609 {
1610         TX25Status* status = card->flags;
1611
1612         card->in_isr = 1;
1613         ++card->statistics.isr_entry;
1614
1615         if (test_bit(PERI_CRIT,(void*)&card->wandev.critical)){
1616                 card->in_isr=0;
1617                 status->iflags = 0;
1618                 return;
1619         }
1620         
1621         if (test_bit(SEND_CRIT, (void*)&card->wandev.critical)){
1622
1623                 printk(KERN_INFO "%s: wpx_isr: wandev.critical set to 0x%02lx, int type = 0x%02x\n", 
1624                         card->devname, card->wandev.critical, status->iflags);
1625                 card->in_isr = 0;
1626                 status->iflags = 0;
1627                 return;
1628         }
1629
1630         /* For all interrupts set the critical flag to CRITICAL_RX_INTR.
1631          * If the if_send routine is called with this flag set it will set
1632          * the enable transmit flag to 1. (for a delayed interrupt)
1633          */
1634         switch (status->iflags){
1635
1636                 case RX_INTR_PENDING:           /* receive interrupt */
1637                         rx_intr(card);
1638                         break;
1639
1640                 case TX_INTR_PENDING:           /* transmit interrupt */
1641                         tx_intr(card);
1642                         break;
1643
1644                 case MODEM_INTR_PENDING:        /* modem status interrupt */
1645                         status_intr(card);
1646                         break;
1647
1648                 case X25_ASY_TRANS_INTR_PENDING:        /* network event interrupt */
1649                         event_intr(card);
1650                         break;
1651
1652                 case TIMER_INTR_PENDING:
1653                         timer_intr(card);
1654                         break;
1655
1656                 default:                /* unwanted interrupt */
1657                         spur_intr(card);
1658         }
1659
1660         card->in_isr = 0;
1661         status->iflags = 0;     /* clear interrupt condition */
1662 }
1663
1664 /*
1665  *      Receive interrupt handler.
1666  *      This routine handles fragmented IP packets using M-bit according to the
1667  *      RFC1356.
1668  *      o map ligical channel number to network interface.
1669  *      o allocate socket buffer or append received packet to the existing one.
1670  *      o if M-bit is reset (i.e. it's the last packet in a sequence) then 
1671  *      decapsulate packet and pass socket buffer to the protocol stack.
1672  *
1673  *      Notes:
1674  *      1. When allocating a socket buffer, if M-bit is set then more data is
1675  *      coming and we have to allocate buffer for the maximum IP packet size
1676  *      expected on this channel.
1677  *      2. If something goes wrong and X.25 packet has to be dropped (e.g. no
1678  *      socket buffers available) the whole packet sequence must be discarded.
1679  */
1680
1681 static void rx_intr (sdla_t* card)
1682 {
1683         TX25Mbox* rxmb = card->rxmb;
1684         unsigned lcn = rxmb->cmd.lcn;
1685         struct net_device* dev = find_channel(card,lcn);
1686         x25_channel_t* chan;
1687         struct sk_buff* skb=NULL;
1688
1689         if (dev == NULL){
1690                 /* Invalid channel, discard packet */
1691                 printk(KERN_INFO "%s: receiving on orphaned LCN %d!\n",
1692                         card->devname, lcn);
1693                 return;
1694         }
1695
1696         chan = dev->priv;
1697         chan->i_timeout_sofar = jiffies;
1698
1699
1700         /* Copy the data from the board, into an
1701          * skb buffer 
1702          */
1703         if (wanpipe_pull_data_in_skb(card,dev,&skb)){
1704                 ++chan->ifstats.rx_dropped;
1705                 ++card->wandev.stats.rx_dropped;
1706                 ++chan->rx_intr_stat.rx_intr_no_socket;
1707                 ++chan->rx_intr_stat.rx_intr_bfr_not_passed_to_stack;
1708                 return;
1709         }
1710
1711         dev->last_rx = jiffies;         /* timestamp */
1712
1713
1714         /* ------------ API ----------------*/
1715
1716         if (chan->common.usedby == API){
1717
1718                 if (bh_enqueue(dev, skb)){
1719                         ++chan->ifstats.rx_dropped;
1720                         ++card->wandev.stats.rx_dropped;
1721                         ++chan->rx_intr_stat.rx_intr_bfr_not_passed_to_stack;
1722                         dev_kfree_skb_any(skb);
1723                         return;
1724                 }               
1725
1726                 ++chan->ifstats.rx_packets;
1727                 chan->ifstats.rx_bytes += skb->len;
1728                 
1729
1730                 chan->rx_skb = NULL;
1731                 if (!test_and_set_bit(0, &chan->tq_working)){
1732                         wanpipe_queue_work(&chan->common.wanpipe_work);
1733                 }
1734                 return;
1735         }
1736
1737
1738         /* ------------- WANPIPE -------------------*/
1739         
1740         /* set rx_skb to NULL so we won't access it later when kernel already owns it */
1741         chan->rx_skb=NULL;
1742         
1743         /* Decapsulate packet, if necessary */
1744         if (!skb->protocol && !wanrouter_type_trans(skb, dev)){
1745                 /* can't decapsulate packet */
1746                 dev_kfree_skb_any(skb);
1747                 ++chan->ifstats.rx_errors;
1748                 ++chan->ifstats.rx_dropped;
1749                 ++card->wandev.stats.rx_dropped;
1750                 ++chan->rx_intr_stat.rx_intr_bfr_not_passed_to_stack;
1751
1752         }else{
1753                 if( handle_IPXWAN(skb->data, chan->name, 
1754                                   chan->enable_IPX, chan->network_number, 
1755                                   skb->protocol)){
1756
1757                         if( chan->enable_IPX ){
1758                                 if(chan_send(dev, skb->data, skb->len,0)){
1759                                         chan->tx_skb = skb;
1760                                 }else{
1761                                         dev_kfree_skb_any(skb);
1762                                         ++chan->rx_intr_stat.rx_intr_bfr_not_passed_to_stack;
1763                                 }
1764                         }else{
1765                                 /* increment IPX packet dropped statistic */
1766                                 ++chan->ifstats.rx_dropped;
1767                                 ++chan->rx_intr_stat.rx_intr_bfr_not_passed_to_stack;
1768                         }
1769                 }else{
1770                         skb->mac.raw = skb->data;
1771                         chan->ifstats.rx_bytes += skb->len;
1772                         ++chan->ifstats.rx_packets;
1773                         ++chan->rx_intr_stat.rx_intr_bfr_passed_to_stack;
1774                         netif_rx(skb);
1775                 }
1776         }
1777         
1778         return;
1779 }
1780
1781
1782 static int wanpipe_pull_data_in_skb(sdla_t *card, struct net_device *dev,
1783                                     struct sk_buff **skb)
1784 {
1785         void *bufptr;
1786         TX25Mbox* rxmb = card->rxmb;
1787         unsigned len = rxmb->cmd.length;        /* packet length */
1788         unsigned qdm = rxmb->cmd.qdm;           /* Q,D and M bits */
1789         x25_channel_t *chan = dev->priv;
1790         struct sk_buff *new_skb = *skb;
1791
1792         if (chan->common.usedby == WANPIPE){
1793                 if (chan->drop_sequence){
1794                         if (!(qdm & 0x01)){ 
1795                                 chan->drop_sequence = 0;
1796                         }
1797                         return 1;
1798                 }
1799                 new_skb = chan->rx_skb;
1800         }else{
1801                 /* Add on the API header to the received
1802                  * data 
1803                  */
1804                 len += sizeof(x25api_hdr_t);
1805         }
1806
1807         if (new_skb == NULL){
1808                 int bufsize;
1809
1810                 if (chan->common.usedby == WANPIPE){
1811                         bufsize = (qdm & 0x01) ? dev->mtu : len;
1812                 }else{
1813                         bufsize = len;
1814                 }
1815
1816                 /* Allocate new socket buffer */
1817                 new_skb = dev_alloc_skb(bufsize + dev->hard_header_len);
1818                 if (new_skb == NULL){
1819                         printk(KERN_INFO "%s: no socket buffers available!\n",
1820                                 card->devname);
1821                         chan->drop_sequence = 1;        /* set flag */
1822                         ++chan->ifstats.rx_dropped;
1823                         return 1;
1824                 }
1825         }
1826
1827         if (skb_tailroom(new_skb) < len){
1828                 /* No room for the packet. Call off the whole thing! */
1829                 dev_kfree_skb_any(new_skb);
1830                 if (chan->common.usedby == WANPIPE){
1831                         chan->rx_skb = NULL;
1832                         if (qdm & 0x01){ 
1833                                 chan->drop_sequence = 1;
1834                         }
1835                 }
1836
1837                 printk(KERN_INFO "%s: unexpectedly long packet sequence "
1838                         "on interface %s!\n", card->devname, dev->name);
1839                 ++chan->ifstats.rx_length_errors;
1840                 return 1;
1841         }
1842
1843         bufptr = skb_put(new_skb,len);
1844
1845
1846         if (chan->common.usedby == API){
1847                 /* Fill in the x25api header 
1848                  */
1849                 x25api_t * api_data = (x25api_t*)bufptr;
1850                 api_data->hdr.qdm = rxmb->cmd.qdm;
1851                 api_data->hdr.cause = rxmb->cmd.cause;
1852                 api_data->hdr.diagn = rxmb->cmd.diagn;
1853                 api_data->hdr.length = rxmb->cmd.length;
1854                 memcpy(api_data->data, rxmb->data, rxmb->cmd.length);
1855         }else{
1856                 memcpy(bufptr, rxmb->data, len);
1857         }
1858
1859         new_skb->dev = dev;
1860
1861         if (chan->common.usedby == API){
1862                 new_skb->mac.raw = new_skb->data;
1863                 new_skb->protocol = htons(X25_PROT);
1864                 new_skb->pkt_type = WAN_PACKET_DATA;
1865         }else{
1866                 new_skb->protocol = chan->protocol;
1867                 chan->rx_skb = new_skb;
1868         }
1869
1870         /* If qdm bit is set, more data is coming 
1871          * thus, exit and wait for more data before
1872          * sending the packet up. (Used by router only) 
1873          */
1874         if ((qdm & 0x01) && (chan->common.usedby == WANPIPE)) 
1875                 return 1;       
1876
1877         *skb = new_skb; 
1878
1879         return 0;
1880 }
1881
1882 /*===============================================================
1883  * tx_intr
1884  *  
1885  *      Transmit interrupt handler.
1886  *      For each dev, check that there is something to send.
1887  *      If data available, transmit.    
1888  *
1889  *===============================================================*/
1890
1891 static void tx_intr (sdla_t* card)
1892 {
1893         struct net_device *dev;
1894         TX25Status* status = card->flags;
1895         unsigned char more_to_tx=0;
1896         x25_channel_t *chan=NULL;
1897         int i=0;        
1898
1899         if (card->u.x.tx_dev == NULL){
1900                 card->u.x.tx_dev = card->wandev.dev;
1901         }
1902
1903         dev = card->u.x.tx_dev;
1904
1905         for (;;){
1906
1907                 chan = dev->priv;
1908                 if (chan->transmit_length){
1909                         /* Device was set to transmit, check if the TX
1910                          * buffers are available 
1911                          */             
1912                         if (chan->common.state != WAN_CONNECTED){
1913                                 chan->transmit_length = 0;
1914                                 atomic_set(&chan->common.driver_busy,0);
1915                                 chan->tx_offset=0;
1916                                 if (netif_queue_stopped(dev)){
1917                                         if (chan->common.usedby == API){
1918                                                 netif_start_queue(dev);
1919                                                 wakeup_sk_bh(dev);
1920                                         }else{
1921                                                 netif_wake_queue(dev);
1922                                         }
1923                                 }
1924                                 dev = move_dev_to_next(card,dev);
1925                                 break;
1926                         }                               
1927
1928                         if ((status->cflags[chan->ch_idx] & 0x40 || card->u.x.LAPB_hdlc) && 
1929                              (*card->u.x.hdlc_buf_status & 0x40) ){
1930                                 /* Tx buffer available, we can send */
1931                                 
1932                                 if (tx_intr_send(card, dev)){
1933                                         more_to_tx=1;
1934                                 }
1935
1936                                 /* If more than one interface present, move the
1937                                  * device pointer to the next interface, so on the 
1938                                  * next TX interrupt we will try sending from it. 
1939                                  */
1940                                 dev = move_dev_to_next(card,dev);
1941                                 break;
1942                         }else{
1943                                 /* Tx buffers not available, but device set
1944                                  * the TX interrupt.  Set more_to_tx and try  
1945                                  * to transmit for other devices.
1946                                  */
1947                                 more_to_tx=1;
1948                                 dev = move_dev_to_next(card,dev);
1949                         }
1950
1951                 }else{
1952                         /* This device was not set to transmit,
1953                          * go to next 
1954                          */
1955                         dev = move_dev_to_next(card,dev);
1956                 }       
1957
1958                 if (++i == card->u.x.no_dev){
1959                         if (!more_to_tx){
1960                                 DBG_PRINTK(KERN_INFO "%s: Nothing to Send in TX INTR\n",
1961                                         card->devname);
1962                         }
1963                         break;
1964                 }
1965
1966         } //End of FOR
1967
1968         card->u.x.tx_dev = dev;
1969         
1970         if (!more_to_tx){
1971                 /* if any other interfaces have transmit interrupts pending, */
1972                 /* do not disable the global transmit interrupt */
1973                 if (!(--card->u.x.tx_interrupts_pending)){
1974                         status->imask &= ~INTR_ON_TX_FRAME;
1975                 }
1976         }
1977         return;
1978 }
1979
1980 /*===============================================================
1981  * move_dev_to_next
1982  *  
1983  *
1984  *===============================================================*/
1985
1986
1987 struct net_device *move_dev_to_next(sdla_t *card, struct net_device *dev)
1988 {
1989         if (card->u.x.no_dev != 1){
1990                 if (!*((struct net_device **)dev->priv))
1991                         return card->wandev.dev;
1992                 else
1993                         return *((struct net_device **)dev->priv);
1994         }
1995         return dev;
1996 }
1997
1998 /*===============================================================
1999  *  tx_intr_send
2000  *  
2001  *
2002  *===============================================================*/
2003
2004 static int tx_intr_send(sdla_t *card, struct net_device *dev)
2005 {
2006         x25_channel_t* chan = dev->priv; 
2007
2008         if (chan_send (dev,chan->transmit_buffer,chan->transmit_length,1)){
2009                  
2010                 /* Packet was split up due to its size, do not disable
2011                  * tx_intr 
2012                  */
2013                 return 1;
2014         }
2015
2016         chan->transmit_length=0;
2017         atomic_set(&chan->common.driver_busy,0);
2018         chan->tx_offset=0;
2019
2020         /* If we are in API mode, wakeup the 
2021          * sock BH handler, not the NET_BH */
2022         if (netif_queue_stopped(dev)){
2023                 if (chan->common.usedby == API){
2024                         netif_start_queue(dev);
2025                         wakeup_sk_bh(dev);
2026                 }else{
2027                         netif_wake_queue(dev);
2028                 }
2029         }
2030         return 0;
2031 }
2032
2033
2034 /*===============================================================
2035  * timer_intr
2036  *  
2037  *      Timer interrupt handler.
2038  *      Check who called the timer interrupt and perform
2039  *      action accordingly.
2040  *
2041  *===============================================================*/
2042
2043 static void timer_intr (sdla_t *card)
2044 {
2045         TX25Status* status = card->flags;
2046
2047         if (card->u.x.timer_int_enabled & TMR_INT_ENABLED_CMD_EXEC){
2048
2049                 if (timer_intr_cmd_exec(card) == 0){
2050                         card->u.x.timer_int_enabled &=
2051                                 ~TMR_INT_ENABLED_CMD_EXEC;
2052                 }
2053
2054         }else  if(card->u.x.timer_int_enabled & TMR_INT_ENABLED_UDP_PKT) {
2055
2056                 if ((*card->u.x.hdlc_buf_status & 0x40) && 
2057                     card->u.x.udp_type == UDP_XPIPE_TYPE){
2058
2059                         if(process_udp_mgmt_pkt(card)) {
2060                                 card->u.x.timer_int_enabled &= 
2061                                         ~TMR_INT_ENABLED_UDP_PKT;
2062                         }
2063                 }
2064
2065         }else if (card->u.x.timer_int_enabled & TMR_INT_ENABLED_POLL_ACTIVE) {
2066
2067                 struct net_device *dev = card->u.x.poll_device;
2068                 x25_channel_t *chan = NULL;
2069
2070                 if (!dev){
2071                         card->u.x.timer_int_enabled &= ~TMR_INT_ENABLED_POLL_ACTIVE;
2072                         return;
2073                 }
2074                 chan = dev->priv;
2075
2076                 printk(KERN_INFO 
2077                         "%s: Closing down Idle link %s on LCN %d\n",
2078                                         card->devname,chan->name,chan->common.lcn); 
2079                 chan->i_timeout_sofar = jiffies;
2080                 chan_disc(dev); 
2081                 card->u.x.timer_int_enabled &= ~TMR_INT_ENABLED_POLL_ACTIVE;
2082                 card->u.x.poll_device=NULL;
2083
2084         }else if (card->u.x.timer_int_enabled & TMR_INT_ENABLED_POLL_CONNECT_ON) {
2085
2086                 wanpipe_set_state(card, WAN_CONNECTED);
2087                 if (card->u.x.LAPB_hdlc){
2088                         struct net_device *dev = card->wandev.dev;
2089                         set_chan_state(dev,WAN_CONNECTED);
2090                         send_delayed_cmd_result(card,dev,card->mbox);   
2091                 }
2092
2093                 /* 0x8F enable all interrupts */
2094                 x25_set_intr_mode(card, INTR_ON_RX_FRAME|       
2095                                         INTR_ON_TX_FRAME|
2096                                         INTR_ON_MODEM_STATUS_CHANGE|
2097                                         //INTR_ON_COMMAND_COMPLETE|
2098                                         X25_ASY_TRANS_INTR_PENDING |
2099                                         INTR_ON_TIMER |
2100                                         DIRECT_RX_INTR_USAGE
2101                                 ); 
2102
2103                 status->imask &= ~INTR_ON_TX_FRAME;     /* mask Tx interrupts */
2104                 card->u.x.timer_int_enabled &= ~TMR_INT_ENABLED_POLL_CONNECT_ON;
2105
2106         }else if (card->u.x.timer_int_enabled & TMR_INT_ENABLED_POLL_CONNECT_OFF) {
2107
2108                 //printk(KERN_INFO "Poll connect, Turning OFF\n");
2109                 disconnect(card);
2110                 card->u.x.timer_int_enabled &= ~TMR_INT_ENABLED_POLL_CONNECT_OFF;
2111
2112         }else if (card->u.x.timer_int_enabled & TMR_INT_ENABLED_POLL_DISCONNECT) {
2113
2114                 //printk(KERN_INFO "POll disconnect, trying to connect\n");
2115                 connect(card);
2116                 card->u.x.timer_int_enabled &= ~TMR_INT_ENABLED_POLL_DISCONNECT;
2117
2118         }else if (card->u.x.timer_int_enabled & TMR_INT_ENABLED_UPDATE){
2119
2120                 if (*card->u.x.hdlc_buf_status & 0x40){
2121                         x25_get_err_stats(card);
2122                         x25_get_stats(card);
2123                         card->u.x.timer_int_enabled &= ~TMR_INT_ENABLED_UPDATE;
2124                 }
2125         }
2126
2127         if(!card->u.x.timer_int_enabled){
2128                 //printk(KERN_INFO "Turning Timer Off \n");
2129                 status->imask &= ~INTR_ON_TIMER;        
2130         }
2131 }
2132
2133 /*====================================================================
2134  *      Modem status interrupt handler.
2135  *===================================================================*/
2136 static void status_intr (sdla_t* card)
2137 {
2138
2139         /* Added to avoid Modem status message flooding */
2140         static TX25ModemStatus last_stat;
2141
2142         TX25Mbox* mbox = card->mbox;
2143         TX25ModemStatus *modem_status;
2144         struct net_device *dev;
2145         x25_channel_t *chan;
2146         int err;
2147
2148         memset(&mbox->cmd, 0, sizeof(TX25Cmd));
2149         mbox->cmd.command = X25_READ_MODEM_STATUS;
2150         err = sdla_exec(mbox) ? mbox->cmd.result : CMD_TIMEOUT;
2151         if (err){ 
2152                 x25_error(card, err, X25_READ_MODEM_STATUS, 0);
2153         }else{
2154         
2155                 modem_status = (TX25ModemStatus*)mbox->data;    
2156         
2157                 /* Check if the last status was the same
2158                  * if it was, do NOT print message again */
2159         
2160                 if (last_stat.status != modem_status->status){
2161
2162                         printk(KERN_INFO "%s: Modem Status Change: DCD=%s, CTS=%s\n",
2163                                 card->devname,DCD(modem_status->status),CTS(modem_status->status));
2164
2165                         last_stat.status = modem_status->status;
2166                 
2167                         if (card->u.x.oob_on_modem){
2168
2169                                 mbox->cmd.pktType = mbox->cmd.command;
2170                                 mbox->cmd.result = 0x08;
2171
2172                                 /* Send a OOB to all connected sockets */
2173                                 for (dev = card->wandev.dev; dev;
2174                                      dev = *((struct net_device**)dev->priv)) {
2175                                         chan=dev->priv;
2176                                         if (chan->common.usedby == API){
2177                                                 send_oob_msg(card,dev,mbox);                            
2178                                         }
2179                                 }
2180
2181                                 /* The modem OOB message will probably kill the
2182                                  * the link. If we don't clear the flag here,
2183                                  * a deadlock could occur */ 
2184                                 if (atomic_read(&card->u.x.command_busy)){
2185                                         atomic_set(&card->u.x.command_busy,0);
2186                                 }
2187                         }
2188                 }
2189         }
2190
2191         memset(&mbox->cmd, 0, sizeof(TX25Cmd));
2192         mbox->cmd.command = X25_HDLC_LINK_STATUS;
2193         err = sdla_exec(mbox) ? mbox->cmd.result : CMD_TIMEOUT;
2194         if (err){ 
2195                 x25_error(card, err, X25_HDLC_LINK_STATUS, 0);
2196         }
2197
2198 }
2199
2200 /*====================================================================
2201  *      Network event interrupt handler.
2202  *===================================================================*/
2203 static void event_intr (sdla_t* card)
2204 {
2205         x25_fetch_events(card);
2206 }
2207
2208 /*====================================================================
2209  *      Spurious interrupt handler.
2210  *      o print a warning
2211  *      o        
2212  *====================================================================*/
2213
2214 static void spur_intr (sdla_t* card)
2215 {
2216         printk(KERN_INFO "%s: spurious interrupt!\n", card->devname);
2217 }
2218
2219
2220 /*
2221  *      Background Polling Routines  
2222  */
2223
2224 /*====================================================================
2225  *      Main polling routine.
2226  *      This routine is repeatedly called by the WANPIPE 'thread' to allow for
2227  *      time-dependent housekeeping work.
2228  *
2229  *      Notes:
2230  *      1. This routine may be called on interrupt context with all interrupts
2231  *      enabled. Beware!
2232  *====================================================================*/
2233
2234 static void wpx_poll (sdla_t *card)
2235 {
2236         if (!card->wandev.dev){
2237                 goto wpx_poll_exit;
2238         }
2239
2240         if (card->open_cnt != card->u.x.num_of_ch){
2241                 goto wpx_poll_exit;
2242         }
2243         
2244         if (test_bit(PERI_CRIT,&card->wandev.critical)){
2245                 goto wpx_poll_exit;
2246         }
2247
2248         if (test_bit(SEND_CRIT,&card->wandev.critical)){
2249                 goto wpx_poll_exit;
2250         }
2251
2252         switch(card->wandev.state){
2253                 case WAN_CONNECTED:
2254                         poll_active(card);
2255                         break;
2256
2257                 case WAN_CONNECTING:
2258                         poll_connecting(card);
2259                         break;
2260
2261                 case WAN_DISCONNECTED:
2262                         poll_disconnected(card);
2263                         break;
2264         }
2265
2266 wpx_poll_exit:
2267         clear_bit(POLL_CRIT,&card->wandev.critical);
2268         return;
2269 }
2270
2271 static void trigger_x25_poll(sdla_t *card)
2272 {
2273         schedule_work(&card->u.x.x25_poll_work);
2274 }
2275
2276 /*====================================================================
2277  *      Handle physical link establishment phase.
2278  *      o if connection timed out, disconnect the link.
2279  *===================================================================*/
2280
2281 static void poll_connecting (sdla_t* card)
2282 {
2283         volatile TX25Status* status = card->flags;
2284
2285         if (status->gflags & X25_HDLC_ABM){
2286
2287                 timer_intr_exec (card, TMR_INT_ENABLED_POLL_CONNECT_ON);
2288
2289         }else if ((jiffies - card->state_tick) > CONNECT_TIMEOUT){
2290
2291                 timer_intr_exec (card, TMR_INT_ENABLED_POLL_CONNECT_OFF);
2292
2293         }
2294 }
2295
2296 /*====================================================================
2297  *      Handle physical link disconnected phase.
2298  *      o if hold-down timeout has expired and there are open interfaces, 
2299  *      connect link.
2300  *===================================================================*/
2301
2302 static void poll_disconnected (sdla_t* card)
2303 {
2304         struct net_device *dev; 
2305         x25_channel_t *chan;
2306         TX25Status* status = card->flags;
2307
2308         if (!card->u.x.LAPB_hdlc && card->open_cnt && 
2309             ((jiffies - card->state_tick) > HOLD_DOWN_TIME)){
2310                 timer_intr_exec(card, TMR_INT_ENABLED_POLL_DISCONNECT);
2311         }
2312
2313
2314         if ((dev=card->wandev.dev) == NULL)
2315                 return;
2316
2317         if ((chan=dev->priv) == NULL)
2318                 return;
2319
2320         if (chan->common.usedby == API && 
2321             atomic_read(&chan->common.command) && 
2322             card->u.x.LAPB_hdlc){
2323
2324                 if (!(card->u.x.timer_int_enabled & TMR_INT_ENABLED_CMD_EXEC)) 
2325                         card->u.x.timer_int_enabled |= TMR_INT_ENABLED_CMD_EXEC;
2326
2327                 if (!(status->imask & INTR_ON_TIMER))
2328                         status->imask |= INTR_ON_TIMER;
2329         }       
2330
2331 }
2332
2333 /*====================================================================
2334  *      Handle active link phase.
2335  *      o fetch X.25 asynchronous events.
2336  *      o kick off transmission on all interfaces.
2337  *===================================================================*/
2338
2339 static void poll_active (sdla_t* card)
2340 {
2341         struct net_device* dev;
2342         TX25Status* status = card->flags;
2343
2344         for (dev = card->wandev.dev; dev;
2345              dev = *((struct net_device **)dev->priv)){
2346                 x25_channel_t* chan = dev->priv;
2347
2348                 /* If SVC has been idle long enough, close virtual circuit */
2349                 if ( chan->common.svc && 
2350                      chan->common.state == WAN_CONNECTED &&
2351                      chan->common.usedby == WANPIPE ){
2352                 
2353                         if( (jiffies - chan->i_timeout_sofar) / HZ > chan->idle_timeout ){
2354                                 /* Close svc */
2355                                 card->u.x.poll_device=dev;
2356                                 timer_intr_exec (card, TMR_INT_ENABLED_POLL_ACTIVE);
2357                         }
2358                 }
2359
2360 #ifdef PRINT_DEBUG
2361                 chan->ifstats.tx_compressed = atomic_read(&chan->common.command);
2362                 chan->ifstats.tx_errors = chan->common.state;
2363                 chan->ifstats.rx_fifo_errors = atomic_read(&card->u.x.command_busy);
2364                 ++chan->ifstats.tx_bytes;
2365
2366                 chan->ifstats.rx_fifo_errors=atomic_read(&chan->common.disconnect);
2367                 chan->ifstats.multicast=atomic_read(&chan->bh_buff_used);
2368                 chan->ifstats.rx_length_errors=*card->u.x.hdlc_buf_status;
2369 #endif  
2370
2371                 if (chan->common.usedby == API && 
2372                     atomic_read(&chan->common.command) && 
2373                     !card->u.x.LAPB_hdlc){
2374
2375                         if (!(card->u.x.timer_int_enabled & TMR_INT_ENABLED_CMD_EXEC)) 
2376                                 card->u.x.timer_int_enabled |= TMR_INT_ENABLED_CMD_EXEC;
2377
2378                         if (!(status->imask & INTR_ON_TIMER))
2379                                 status->imask |= INTR_ON_TIMER;
2380                 }       
2381
2382                 if ((chan->common.usedby == API) && 
2383                      atomic_read(&chan->common.disconnect)){
2384
2385                         if (chan->common.state == WAN_DISCONNECTED){
2386                                 atomic_set(&chan->common.disconnect,0);
2387                                 return;
2388                         }
2389
2390                         atomic_set(&chan->common.command,X25_CLEAR_CALL);
2391                         if (!(card->u.x.timer_int_enabled & TMR_INT_ENABLED_CMD_EXEC)) 
2392                                 card->u.x.timer_int_enabled |= TMR_INT_ENABLED_CMD_EXEC;
2393
2394                         if (!(status->imask & INTR_ON_TIMER))
2395                                 status->imask |= INTR_ON_TIMER;
2396                 }
2397         }
2398 }
2399
2400 static void timer_intr_exec(sdla_t *card, unsigned char TYPE)
2401 {
2402         TX25Status* status = card->flags;
2403         card->u.x.timer_int_enabled |= TYPE;
2404         if (!(status->imask & INTR_ON_TIMER))
2405                 status->imask |= INTR_ON_TIMER;
2406 }
2407
2408
2409 /*==================================================================== 
2410  * SDLA Firmware-Specific Functions 
2411  *
2412  *  Almost all X.25 commands can unexpetedly fail due to so called 'X.25
2413  *  asynchronous events' such as restart, interrupt, incoming call request,
2414  *  call clear request, etc.  They can't be ignored and have to be delt with
2415  *  immediately.  To tackle with this problem we execute each interface 
2416  *  command in a loop until good return code is received or maximum number 
2417  *  of retries is reached.  Each interface command returns non-zero return 
2418  *  code, an asynchronous event/error handler x25_error() is called.
2419  *====================================================================*/
2420
2421 /*====================================================================
2422  *      Read X.25 firmware version.
2423  *              Put code version as ASCII string in str. 
2424  *===================================================================*/
2425
2426 static int x25_get_version (sdla_t* card, char* str)
2427 {
2428         TX25Mbox* mbox = card->mbox;
2429         int retry = MAX_CMD_RETRY;
2430         int err;
2431
2432         do
2433         {
2434                 memset(&mbox->cmd, 0, sizeof(TX25Cmd));
2435                 mbox->cmd.command = X25_READ_CODE_VERSION;
2436                 err = sdla_exec(mbox) ? mbox->cmd.result : CMD_TIMEOUT;
2437         } while (err && retry-- &&
2438                  x25_error(card, err, X25_READ_CODE_VERSION, 0));
2439
2440         if (!err && str)
2441         {
2442                 int len = mbox->cmd.length;
2443
2444                 memcpy(str, mbox->data, len);
2445                 str[len] = '\0';
2446         }
2447         return err;
2448 }
2449
2450 /*====================================================================
2451  *      Configure adapter.
2452  *===================================================================*/
2453
2454 static int x25_configure (sdla_t* card, TX25Config* conf)
2455 {
2456         TX25Mbox* mbox = card->mbox;
2457         int retry = MAX_CMD_RETRY;
2458         int err;
2459
2460         do{
2461                 memset(&mbox->cmd, 0, sizeof(TX25Cmd));
2462                 memcpy(mbox->data, (void*)conf, sizeof(TX25Config));
2463                 mbox->cmd.length  = sizeof(TX25Config);
2464                 mbox->cmd.command = X25_SET_CONFIGURATION;
2465                 err = sdla_exec(mbox) ? mbox->cmd.result : CMD_TIMEOUT;
2466         } while (err && retry-- && x25_error(card, err, X25_SET_CONFIGURATION, 0));
2467         return err;
2468 }
2469
2470 /*====================================================================
2471  *      Configure adapter for HDLC only.
2472  *===================================================================*/
2473
2474 static int hdlc_configure (sdla_t* card, TX25Config* conf)
2475 {
2476         TX25Mbox* mbox = card->mbox;
2477         int retry = MAX_CMD_RETRY;
2478         int err;
2479
2480         do{
2481                 memset(&mbox->cmd, 0, sizeof(TX25Cmd));
2482                 memcpy(mbox->data, (void*)conf, sizeof(TX25Config));
2483                 mbox->cmd.length  = sizeof(TX25Config);
2484                 mbox->cmd.command = X25_HDLC_SET_CONFIG;
2485                 err = sdla_exec(mbox) ? mbox->cmd.result : CMD_TIMEOUT;
2486         } while (err && retry-- && x25_error(card, err, X25_SET_CONFIGURATION, 0));
2487
2488         return err;
2489 }
2490
2491 static int set_hdlc_level (sdla_t* card)
2492 {
2493
2494         TX25Mbox* mbox = card->mbox;
2495         int retry = MAX_CMD_RETRY;
2496         int err;
2497
2498         do{
2499                 memset(&mbox->cmd, 0, sizeof(TX25Cmd));
2500                 mbox->cmd.command = SET_PROTOCOL_LEVEL;
2501                 mbox->cmd.length = 1;
2502                 mbox->data[0] = HDLC_LEVEL; //| DO_HDLC_LEVEL_ERROR_CHECKING;   
2503                 err = sdla_exec(mbox) ? mbox->cmd.result : CMD_TIMEOUT;
2504         } while (err && retry-- && x25_error(card, err, SET_PROTOCOL_LEVEL, 0));
2505
2506         return err;
2507 }
2508
2509
2510
2511 /*====================================================================
2512  * Get communications error statistics.
2513  *====================================================================*/
2514
2515 static int x25_get_err_stats (sdla_t* card)
2516 {
2517         TX25Mbox* mbox = card->mbox;
2518         int retry = MAX_CMD_RETRY;
2519         int err;
2520
2521         do
2522         {
2523                 memset(&mbox->cmd, 0, sizeof(TX25Cmd));
2524                 mbox->cmd.command = X25_HDLC_READ_COMM_ERR;
2525                 err = sdla_exec(mbox) ? mbox->cmd.result : CMD_TIMEOUT;
2526         } while (err && retry-- && x25_error(card, err, X25_HDLC_READ_COMM_ERR, 0));
2527         
2528         if (!err)
2529         {
2530                 THdlcCommErr* stats = (void*)mbox->data;
2531
2532                 card->wandev.stats.rx_over_errors    = stats->rxOverrun;
2533                 card->wandev.stats.rx_crc_errors     = stats->rxBadCrc;
2534                 card->wandev.stats.rx_missed_errors  = stats->rxAborted;
2535                 card->wandev.stats.tx_aborted_errors = stats->txAborted;
2536         }
2537         return err;
2538 }
2539
2540 /*====================================================================
2541  *      Get protocol statistics.
2542  *===================================================================*/
2543
2544 static int x25_get_stats (sdla_t* card)
2545 {
2546         TX25Mbox* mbox = card->mbox;
2547         int retry = MAX_CMD_RETRY;
2548         int err;
2549
2550         do
2551         {
2552                 memset(&mbox->cmd, 0, sizeof(TX25Cmd));
2553                 mbox->cmd.command = X25_READ_STATISTICS;
2554                 err = sdla_exec(mbox) ? mbox->cmd.result : CMD_TIMEOUT;
2555         } while (err && retry-- && x25_error(card, err, X25_READ_STATISTICS, 0)) ;
2556         
2557         if (!err)
2558         {
2559                 TX25Stats* stats = (void*)mbox->data;
2560
2561                 card->wandev.stats.rx_packets = stats->rxData;
2562                 card->wandev.stats.tx_packets = stats->txData;
2563         }
2564         return err;
2565 }
2566
2567 /*====================================================================
2568  *      Close HDLC link.
2569  *===================================================================*/
2570
2571 static int x25_close_hdlc (sdla_t* card)
2572 {
2573         TX25Mbox* mbox = card->mbox;
2574         int retry = MAX_CMD_RETRY;
2575         int err;
2576
2577         do
2578         {
2579                 memset(&mbox->cmd, 0, sizeof(TX25Cmd));
2580                 mbox->cmd.command = X25_HDLC_LINK_CLOSE;
2581                 err = sdla_exec(mbox) ? mbox->cmd.result : CMD_TIMEOUT;
2582         } while (err && retry-- && x25_error(card, err, X25_HDLC_LINK_CLOSE, 0));
2583         
2584         return err;
2585 }
2586
2587
2588 /*====================================================================
2589  *      Open HDLC link.
2590  *===================================================================*/
2591
2592 static int x25_open_hdlc (sdla_t* card)
2593 {
2594         TX25Mbox* mbox = card->mbox;
2595         int retry = MAX_CMD_RETRY;
2596         int err;
2597
2598         do
2599         {
2600                 memset(&mbox->cmd, 0, sizeof(TX25Cmd));
2601                 mbox->cmd.command = X25_HDLC_LINK_OPEN;
2602                 err = sdla_exec(mbox) ? mbox->cmd.result : CMD_TIMEOUT;
2603         } while (err && retry-- && x25_error(card, err, X25_HDLC_LINK_OPEN, 0));
2604
2605         return err;
2606 }
2607
2608 /*=====================================================================
2609  * Setup HDLC link.
2610  *====================================================================*/
2611 static int x25_setup_hdlc (sdla_t* card)
2612 {
2613         TX25Mbox* mbox = card->mbox;
2614         int retry = MAX_CMD_RETRY;
2615         int err;
2616
2617         do
2618         {
2619                 memset(&mbox->cmd, 0, sizeof(TX25Cmd));
2620                 mbox->cmd.command = X25_HDLC_LINK_SETUP;
2621                 err = sdla_exec(mbox) ? mbox->cmd.result : CMD_TIMEOUT;
2622         } while (err && retry-- && x25_error(card, err, X25_HDLC_LINK_SETUP, 0));
2623         
2624         return err;
2625 }
2626
2627 /*====================================================================
2628  * Set (raise/drop) DTR.
2629  *===================================================================*/
2630
2631 static int x25_set_dtr (sdla_t* card, int dtr)
2632 {
2633         TX25Mbox* mbox = card->mbox;
2634         int retry = MAX_CMD_RETRY;
2635         int err;
2636
2637         do
2638         {
2639                 memset(&mbox->cmd, 0, sizeof(TX25Cmd));
2640                 mbox->data[0] = 0;
2641                 mbox->data[2] = 0;
2642                 mbox->data[1] = dtr ? 0x02 : 0x01;
2643                 mbox->cmd.length  = 3;
2644                 mbox->cmd.command = X25_SET_GLOBAL_VARS;
2645                 err = sdla_exec(mbox) ? mbox->cmd.result : CMD_TIMEOUT;
2646         } while (err && retry-- && x25_error(card, err, X25_SET_GLOBAL_VARS, 0));
2647         
2648         return err;
2649 }
2650
2651 /*====================================================================
2652  *      Set interrupt mode.
2653  *===================================================================*/
2654
2655 static int x25_set_intr_mode (sdla_t* card, int mode)
2656 {
2657         TX25Mbox* mbox = card->mbox;
2658         int retry = MAX_CMD_RETRY;
2659         int err;
2660
2661         do
2662         {
2663                 memset(&mbox->cmd, 0, sizeof(TX25Cmd));
2664                 mbox->data[0] = mode;
2665                 if (card->hw.fwid == SFID_X25_508){
2666                         mbox->data[1] = card->hw.irq;
2667                         mbox->data[2] = 2;
2668                         mbox->cmd.length = 3;
2669                 }else {
2670                         mbox->cmd.length  = 1;
2671                 }
2672                 mbox->cmd.command = X25_SET_INTERRUPT_MODE;
2673                 err = sdla_exec(mbox) ? mbox->cmd.result : CMD_TIMEOUT;
2674         } while (err && retry-- && x25_error(card, err, X25_SET_INTERRUPT_MODE, 0));
2675         
2676         return err;
2677 }
2678
2679 /*====================================================================
2680  *      Read X.25 channel configuration.
2681  *===================================================================*/
2682
2683 static int x25_get_chan_conf (sdla_t* card, x25_channel_t* chan)
2684 {
2685         TX25Mbox* mbox = card->mbox;
2686         int retry = MAX_CMD_RETRY;
2687         int lcn = chan->common.lcn;
2688         int err;
2689
2690         do{
2691                 memset(&mbox->cmd, 0, sizeof(TX25Cmd));
2692                 mbox->cmd.lcn     = lcn;
2693                 mbox->cmd.command = X25_READ_CHANNEL_CONFIG;
2694                 err = sdla_exec(mbox) ? mbox->cmd.result : CMD_TIMEOUT;
2695         } while (err && retry-- && x25_error(card, err, X25_READ_CHANNEL_CONFIG, lcn));
2696
2697         if (!err)
2698         {
2699                 TX25Status* status = card->flags;
2700
2701                 /* calculate an offset into the array of status bytes */
2702                 if (card->u.x.hi_svc <= X25_MAX_CHAN){ 
2703
2704                         chan->ch_idx = lcn - 1;
2705
2706                 }else{
2707                         int offset;
2708
2709                         /* FIX: Apr 14 2000 : Nenad Corbic
2710                          * The data field was being compared to 0x1F using
2711                          * '&&' instead of '&'. 
2712                          * This caused X25API to fail for LCNs greater than 255.
2713                          */
2714                         switch (mbox->data[0] & 0x1F)
2715                         {
2716                                 case 0x01: 
2717                                         offset = status->pvc_map; break;
2718                                 case 0x03: 
2719                                         offset = status->icc_map; break;
2720                                 case 0x07: 
2721                                         offset = status->twc_map; break;
2722                                 case 0x0B: 
2723                                         offset = status->ogc_map; break;
2724                                 default: 
2725                                         offset = 0;
2726                         }
2727                         chan->ch_idx = lcn - 1 - offset;
2728                 }
2729
2730                 /* get actual transmit packet size on this channel */
2731                 switch(mbox->data[1] & 0x38)
2732                 {
2733                         case 0x00: 
2734                                 chan->tx_pkt_size = 16; 
2735                                 break;
2736                         case 0x08: 
2737                                 chan->tx_pkt_size = 32; 
2738                                 break;
2739                         case 0x10: 
2740                                 chan->tx_pkt_size = 64; 
2741                                 break;
2742                         case 0x18: 
2743                                 chan->tx_pkt_size = 128; 
2744                                 break;
2745                         case 0x20: 
2746                                 chan->tx_pkt_size = 256; 
2747                                 break;
2748                         case 0x28: 
2749                                 chan->tx_pkt_size = 512; 
2750                                 break;
2751                         case 0x30: 
2752                                 chan->tx_pkt_size = 1024; 
2753                                 break;
2754                 }
2755                 if (card->u.x.logging)
2756                         printk(KERN_INFO "%s: X.25 packet size on LCN %d is %d.\n",
2757                                 card->devname, lcn, chan->tx_pkt_size);
2758         }
2759         return err;
2760 }
2761
2762 /*====================================================================
2763  *      Place X.25 call.
2764  *====================================================================*/
2765
2766 static int x25_place_call (sdla_t* card, x25_channel_t* chan)
2767 {
2768         TX25Mbox* mbox = card->mbox;
2769         int retry = MAX_CMD_RETRY;
2770         int err;
2771         char str[64];
2772
2773
2774         if (chan->protocol == htons(ETH_P_IP)){
2775                 sprintf(str, "-d%s -uCC", chan->addr);
2776         
2777         }else if (chan->protocol == htons(ETH_P_IPX)){
2778                 sprintf(str, "-d%s -u800000008137", chan->addr);
2779         
2780         }
2781         
2782         do
2783         {
2784                 memset(&mbox->cmd, 0, sizeof(TX25Cmd));
2785                 strcpy(mbox->data, str);
2786                 mbox->cmd.length  = strlen(str);
2787                 mbox->cmd.command = X25_PLACE_CALL;
2788                 err = sdla_exec(mbox) ? mbox->cmd.result : CMD_TIMEOUT;
2789         } while (err && retry-- && x25_error(card, err, X25_PLACE_CALL, 0));
2790
2791         if (!err){
2792                 bind_lcn_to_dev (card, chan->dev, mbox->cmd.lcn);
2793         }
2794         return err;
2795 }
2796
2797 /*====================================================================
2798  *      Accept X.25 call.
2799  *====================================================================*/
2800
2801 static int x25_accept_call (sdla_t* card, int lcn, int qdm)
2802 {
2803         TX25Mbox* mbox = card->mbox;
2804         int retry = MAX_CMD_RETRY;
2805         int err;
2806
2807         do
2808         {
2809                 memset(&mbox->cmd, 0, sizeof(TX25Cmd));
2810                 mbox->cmd.lcn     = lcn;
2811                 mbox->cmd.qdm     = qdm;
2812                 mbox->cmd.command = X25_ACCEPT_CALL;
2813                 err = sdla_exec(mbox) ? mbox->cmd.result : CMD_TIMEOUT;
2814         } while (err && retry-- && x25_error(card, err, X25_ACCEPT_CALL, lcn));
2815         
2816         return err;
2817 }
2818
2819 /*====================================================================
2820  *      Clear X.25 call.
2821  *====================================================================*/
2822
2823 static int x25_clear_call (sdla_t* card, int lcn, int cause, int diagn)
2824 {
2825         TX25Mbox* mbox = card->mbox;
2826         int retry = MAX_CMD_RETRY;
2827         int err;
2828
2829         do
2830         {
2831                 memset(&mbox->cmd, 0, sizeof(TX25Cmd));
2832                 mbox->cmd.lcn     = lcn;
2833                 mbox->cmd.cause   = cause;
2834                 mbox->cmd.diagn   = diagn;
2835                 mbox->cmd.command = X25_CLEAR_CALL;
2836                 err = sdla_exec(mbox) ? mbox->cmd.result : CMD_TIMEOUT;
2837         } while (err && retry-- && x25_error(card, err, X25_CLEAR_CALL, lcn));
2838         
2839         return err;
2840 }
2841
2842 /*====================================================================
2843  *      Send X.25 data packet.
2844  *====================================================================*/
2845
2846 static int x25_send (sdla_t* card, int lcn, int qdm, int len, void* buf)
2847 {
2848         TX25Mbox* mbox = card->mbox;
2849         int retry = MAX_CMD_RETRY;
2850         int err;
2851         unsigned char cmd;
2852                 
2853         if (card->u.x.LAPB_hdlc)
2854                 cmd = X25_HDLC_WRITE;
2855         else
2856                 cmd = X25_WRITE;
2857
2858         do
2859         {
2860                 memset(&mbox->cmd, 0, sizeof(TX25Cmd));
2861                 memcpy(mbox->data, buf, len);
2862                 mbox->cmd.length  = len;
2863                 mbox->cmd.lcn     = lcn;
2864
2865                 if (card->u.x.LAPB_hdlc){
2866                         mbox->cmd.pf = qdm;
2867                 }else{                  
2868                         mbox->cmd.qdm = qdm;
2869                 }
2870
2871                 mbox->cmd.command = cmd;
2872                 err = sdla_exec(mbox) ? mbox->cmd.result : CMD_TIMEOUT;
2873         } while (err && retry-- && x25_error(card, err, cmd , lcn));
2874
2875
2876         /* If buffers are busy the return code for LAPB HDLC is
2877          * 1. The above functions are looking for return code
2878          * of X25RES_NOT_READY if busy. */
2879
2880         if (card->u.x.LAPB_hdlc && err == 1){
2881                 err = X25RES_NOT_READY;
2882         }
2883
2884         return err;
2885 }
2886
2887 /*====================================================================
2888  *      Fetch X.25 asynchronous events.
2889  *===================================================================*/
2890
2891 static int x25_fetch_events (sdla_t* card)
2892 {
2893         TX25Status* status = card->flags;
2894         TX25Mbox* mbox = card->mbox;
2895         int err = 0;
2896
2897         if (status->gflags & 0x20)
2898         {
2899                 memset(&mbox->cmd, 0, sizeof(TX25Cmd));
2900                 mbox->cmd.command = X25_IS_DATA_AVAILABLE;
2901                 err = sdla_exec(mbox) ? mbox->cmd.result : CMD_TIMEOUT;
2902                 if (err) x25_error(card, err, X25_IS_DATA_AVAILABLE, 0);
2903         }
2904         return err;
2905 }
2906
2907 /*====================================================================
2908  *      X.25 asynchronous event/error handler.
2909  *              This routine is called each time interface command returns 
2910  *              non-zero return code to handle X.25 asynchronous events and 
2911  *              common errors. Return non-zero to repeat command or zero to 
2912  *              cancel it.
2913  *
2914  *      Notes:
2915  *      1. This function may be called recursively, as handling some of the
2916  *      asynchronous events (e.g. call request) requires execution of the
2917  *      interface command(s) that, in turn, may also return asynchronous
2918  *      events.  To avoid re-entrancy problems we copy mailbox to dynamically
2919  *      allocated memory before processing events.
2920  *====================================================================*/
2921
2922 static int x25_error (sdla_t* card, int err, int cmd, int lcn)
2923 {
2924         int retry = 1;
2925         unsigned dlen = ((TX25Mbox*)card->mbox)->cmd.length;
2926         TX25Mbox* mb;
2927
2928         mb = kmalloc(sizeof(TX25Mbox) + dlen, GFP_ATOMIC);
2929         if (mb == NULL)
2930         {
2931                 printk(KERN_ERR "%s: x25_error() out of memory!\n",
2932                         card->devname);
2933                 return 0;
2934         }
2935         memcpy(mb, card->mbox, sizeof(TX25Mbox) + dlen);
2936         switch (err){
2937
2938         case X25RES_ASYNC_PACKET:       /* X.25 asynchronous packet was received */
2939
2940                 mb->data[dlen] = '\0';
2941
2942                 switch (mb->cmd.pktType & 0x7F){
2943
2944                 case ASE_CALL_RQST:             /* incoming call */
2945                         retry = incoming_call(card, cmd, lcn, mb);
2946                         break;
2947
2948                 case ASE_CALL_ACCEPTED:         /* connected */
2949                         retry = call_accepted(card, cmd, lcn, mb);
2950                         break;
2951
2952                 case ASE_CLEAR_RQST:            /* call clear request */
2953                         retry = call_cleared(card, cmd, lcn, mb);
2954                         break;
2955
2956                 case ASE_RESET_RQST:            /* reset request */
2957                         printk(KERN_INFO "%s: X.25 reset request on LCN %d! "
2958                                 "Cause:0x%02X Diagn:0x%02X\n",
2959                                 card->devname, mb->cmd.lcn, mb->cmd.cause,
2960                                 mb->cmd.diagn);
2961                         api_oob_event (card,mb);
2962                         break;
2963
2964                 case ASE_RESTART_RQST:          /* restart request */
2965                         retry = restart_event(card, cmd, lcn, mb);
2966                         break;
2967
2968                 case ASE_CLEAR_CONFRM:
2969                         if (clear_confirm_event (card,mb))
2970                                 break;
2971
2972                         /* I use the goto statement here so if 
2973                          * somebody inserts code between the
2974                          * case and default, we will not have
2975                          * ghost problems */
2976
2977                         goto dflt_1;
2978
2979                 default:
2980 dflt_1:
2981                         printk(KERN_INFO "%s: X.25 event 0x%02X on LCN %d! "
2982                                 "Cause:0x%02X Diagn:0x%02X\n",
2983                                 card->devname, mb->cmd.pktType,
2984                                 mb->cmd.lcn, mb->cmd.cause, mb->cmd.diagn);
2985                 }
2986                 break;
2987
2988         case X25RES_PROTO_VIOLATION:    /* X.25 protocol violation indication */
2989
2990                 /* Bug Fix: Mar 14 2000
2991                  * The Protocol violation error conditions were  
2992                  * not handled previously */
2993
2994                 switch (mb->cmd.pktType & 0x7F){
2995
2996                 case PVE_CLEAR_RQST:    /* Clear request */             
2997                         retry = call_cleared(card, cmd, lcn, mb);
2998                         break;  
2999
3000                 case PVE_RESET_RQST:    /* Reset request */
3001                         printk(KERN_INFO "%s: X.25 reset request on LCN %d! "
3002                                 "Cause:0x%02X Diagn:0x%02X\n",
3003                                 card->devname, mb->cmd.lcn, mb->cmd.cause,
3004                                 mb->cmd.diagn);
3005                         api_oob_event (card,mb);
3006                         break;
3007
3008                 case PVE_RESTART_RQST:  /* Restart request */
3009                         retry = restart_event(card, cmd, lcn, mb);
3010                         break;
3011
3012                 default :
3013                         printk(KERN_INFO
3014                                 "%s: X.25 protocol violation on LCN %d! "
3015                                 "Packet:0x%02X Cause:0x%02X Diagn:0x%02X\n",
3016                                 card->devname, mb->cmd.lcn,
3017                                 mb->cmd.pktType & 0x7F, mb->cmd.cause, mb->cmd.diagn);
3018                         api_oob_event(card,mb);
3019                 }
3020                 break;
3021
3022         case 0x42:      /* X.25 timeout */
3023                 retry = timeout_event(card, cmd, lcn, mb);
3024                 break;
3025
3026         case 0x43:      /* X.25 retry limit exceeded */
3027                 printk(KERN_INFO
3028                         "%s: exceeded X.25 retry limit on LCN %d! "
3029                         "Packet:0x%02X Diagn:0x%02X\n", card->devname,
3030                         mb->cmd.lcn, mb->cmd.pktType, mb->cmd.diagn)
3031                 ;
3032                 break;
3033
3034         case 0x08:      /* modem failure */
3035 #ifndef MODEM_NOT_LOG
3036                 printk(KERN_INFO "%s: modem failure!\n", card->devname);
3037 #endif /* MODEM_NOT_LOG */
3038                 api_oob_event(card,mb);
3039                 break;
3040
3041         case 0x09:      /* N2 retry limit */
3042                 printk(KERN_INFO "%s: exceeded HDLC retry limit!\n",
3043                         card->devname);
3044                 api_oob_event(card,mb);
3045                 break;
3046
3047         case 0x06:      /* unnumbered frame was received while in ABM */
3048                 printk(KERN_INFO "%s: received Unnumbered frame 0x%02X!\n",
3049                         card->devname, mb->data[0]);
3050                 api_oob_event(card,mb);
3051                 break;
3052
3053         case CMD_TIMEOUT:
3054                 printk(KERN_ERR "%s: command 0x%02X timed out!\n",
3055                         card->devname, cmd)
3056                 ;
3057                 retry = 0;      /* abort command */
3058                 break;
3059
3060         case X25RES_NOT_READY:
3061                 retry = 1;
3062                 break;
3063
3064         case 0x01:
3065                 if (card->u.x.LAPB_hdlc)
3066                         break;
3067
3068                 if (mb->cmd.command == 0x16)
3069                         break;
3070                 /* I use the goto statement here so if 
3071                  * somebody inserts code between the
3072                  * case and default, we will not have
3073                  * ghost problems */
3074                 goto dflt_2;
3075
3076         default:
3077 dflt_2:
3078                 printk(KERN_INFO "%s: command 0x%02X returned 0x%02X! Lcn %i\n",
3079                         card->devname, cmd, err, mb->cmd.lcn)
3080                 ;
3081                 retry = 0;      /* abort command */
3082         }
3083         kfree(mb);
3084         return retry;
3085 }
3086
3087 /*==================================================================== 
3088  *      X.25 Asynchronous Event Handlers
3089  *      These functions are called by the x25_error() and should return 0, if
3090  *      the command resulting in the asynchronous event must be aborted.
3091  *====================================================================*/
3092
3093
3094
3095 /*====================================================================
3096  *Handle X.25 incoming call request.
3097  *      RFC 1356 establishes the following rules:
3098  *      1. The first octet in the Call User Data (CUD) field of the call
3099  *         request packet contains NLPID identifying protocol encapsulation
3100  *      2. Calls MUST NOT be accepted unless router supports requested
3101  *         protocol encapsulation.
3102  *      3. A diagnostic code 249 defined by ISO/IEC 8208 may be used 
3103  *         when clearing a call because protocol encapsulation is not 
3104  *         supported.
3105  *      4. If an incoming call is received while a call request is 
3106  *         pending (i.e. call collision has occurred), the incoming call 
3107  *         shall be rejected and call request shall be retried.
3108  *====================================================================*/
3109
3110 static int incoming_call (sdla_t* card, int cmd, int lcn, TX25Mbox* mb)
3111 {
3112         struct wan_device* wandev = &card->wandev;
3113         int new_lcn = mb->cmd.lcn;
3114         struct net_device* dev = get_dev_by_lcn(wandev, new_lcn);
3115         x25_channel_t* chan = NULL;
3116         int accept = 0;         /* set to '1' if o.k. to accept call */
3117         unsigned int user_data;
3118         x25_call_info_t* info;
3119         
3120         /* Make sure there is no call collision */
3121         if (dev != NULL)
3122         {
3123                 printk(KERN_INFO
3124                         "%s: X.25 incoming call collision on LCN %d!\n",
3125                         card->devname, new_lcn);
3126
3127                 x25_clear_call(card, new_lcn, 0, 0);
3128                 return 1;
3129         }
3130
3131         /* Make sure D bit is not set in call request */
3132 //FIXME: THIS IS NOT TURE !!!! TAKE IT OUT
3133 //      if (mb->cmd.qdm & 0x02)
3134 //      {
3135 //              printk(KERN_INFO
3136 //                      "%s: X.25 incoming call on LCN %d with D-bit set!\n",
3137 //                      card->devname, new_lcn);
3138 //
3139 //              x25_clear_call(card, new_lcn, 0, 0);
3140 //              return 1;
3141 //      }
3142
3143         /* Parse call request data */
3144         info = kmalloc(sizeof(x25_call_info_t), GFP_ATOMIC);
3145         if (info == NULL)
3146         {
3147                 printk(KERN_ERR
3148                         "%s: not enough memory to parse X.25 incoming call "
3149                         "on LCN %d!\n", card->devname, new_lcn);
3150                 x25_clear_call(card, new_lcn, 0, 0);
3151                 return 1;
3152         }
3153  
3154         parse_call_info(mb->data, info);
3155
3156         if (card->u.x.logging)
3157                 printk(KERN_INFO "\n%s: X.25 incoming call on LCN %d!\n",
3158                         card->devname, new_lcn);
3159
3160         /* Conver the first two ASCII characters into an
3161          * interger. Used to check the incoming protocol 
3162          */
3163         user_data = hex_to_uint(info->user,2);
3164
3165         /* Find available channel */
3166         for (dev = wandev->dev; dev; dev = *((struct net_device **)dev->priv)) {
3167                 chan = dev->priv;
3168
3169                 if (chan->common.usedby == API)
3170                         continue;
3171
3172                 if (!chan->common.svc || (chan->common.state != WAN_DISCONNECTED))
3173                         continue;
3174
3175                 if (user_data == NLPID_IP && chan->protocol != htons(ETH_P_IP)){
3176                         printk(KERN_INFO "IP packet but configured for IPX : %x, %x\n",
3177                                        htons(chan->protocol), info->user[0]);
3178                         continue;
3179                 }
3180         
3181                 if (user_data == NLPID_SNAP && chan->protocol != htons(ETH_P_IPX)){
3182                         printk(KERN_INFO "IPX packet but configured for IP: %x\n",
3183                                        htons(chan->protocol));
3184                         continue;
3185                 }
3186                 if (strcmp(info->src, chan->addr) == 0)
3187                         break;
3188
3189                 /* If just an '@' is specified, accept all incoming calls */
3190                 if (strcmp(chan->addr, "") == 0)
3191                         break;
3192         }
3193
3194         if (dev == NULL){
3195
3196                 /* If the call is not for any WANPIPE interfaces
3197                  * check to see if there is an API listening queue
3198                  * waiting for data. If there is send the packet
3199                  * up the stack.
3200                  */
3201                 if (card->sk != NULL && card->func != NULL){
3202                         if (api_incoming_call(card,mb,new_lcn)){
3203                                 x25_clear_call(card, new_lcn, 0, 0);
3204                         }
3205                         accept = 0;
3206                 }else{
3207                         printk(KERN_INFO "%s: no channels available!\n",
3208                                 card->devname);
3209                         
3210                         x25_clear_call(card, new_lcn, 0, 0);
3211                 }
3212
3213         }else if (info->nuser == 0){
3214
3215                 printk(KERN_INFO
3216                         "%s: no user data in incoming call on LCN %d!\n",
3217                         card->devname, new_lcn)
3218                 ;
3219                 x25_clear_call(card, new_lcn, 0, 0);
3220
3221         }else switch (info->user[0]){
3222
3223                 case 0:         /* multiplexed */
3224                         chan->protocol = htons(0);
3225                         accept = 1;
3226                         break;
3227
3228                 case NLPID_IP:  /* IP datagrams */
3229                         accept = 1;
3230                         break;
3231
3232                 case NLPID_SNAP: /* IPX datagrams */
3233                         accept = 1;
3234                         break;
3235
3236                 default:
3237                         printk(KERN_INFO
3238                                 "%s: unsupported NLPID 0x%02X in incoming call "
3239                                 "on LCN %d!\n", card->devname, info->user[0], new_lcn);
3240                         x25_clear_call(card, new_lcn, 0, 249);
3241         }
3242         
3243         if (accept && (x25_accept_call(card, new_lcn, 0) == CMD_OK)){
3244
3245                 bind_lcn_to_dev (card, chan->dev, new_lcn);
3246                 
3247                 if (x25_get_chan_conf(card, chan) == CMD_OK)
3248                         set_chan_state(dev, WAN_CONNECTED);
3249                 else 
3250                         x25_clear_call(card, new_lcn, 0, 0);
3251         }
3252         kfree(info);
3253         return 1;
3254 }
3255
3256 /*====================================================================
3257  *      Handle accepted call.
3258  *====================================================================*/
3259
3260 static int call_accepted (sdla_t* card, int cmd, int lcn, TX25Mbox* mb)
3261 {
3262         unsigned new_lcn = mb->cmd.lcn;
3263         struct net_device* dev = find_channel(card, new_lcn);
3264         x25_channel_t* chan;
3265
3266         if (dev == NULL){
3267                 printk(KERN_INFO
3268                         "%s: clearing orphaned connection on LCN %d!\n",
3269                         card->devname, new_lcn);
3270                 x25_clear_call(card, new_lcn, 0, 0);
3271                 return 1;
3272         }
3273
3274         if (card->u.x.logging)  
3275                 printk(KERN_INFO "%s: X.25 call accepted on Dev %s and LCN %d!\n",
3276                         card->devname, dev->name, new_lcn);
3277
3278         /* Get channel configuration and notify router */
3279         chan = dev->priv;
3280         if (x25_get_chan_conf(card, chan) != CMD_OK)
3281         {
3282                 x25_clear_call(card, new_lcn, 0, 0);
3283                 return 1;
3284         }
3285
3286         set_chan_state(dev, WAN_CONNECTED);
3287
3288         if (chan->common.usedby == API){
3289                 send_delayed_cmd_result(card,dev,mb);
3290                 bind_lcn_to_dev (card, dev, new_lcn);
3291         }
3292
3293         return 1;
3294 }
3295
3296 /*====================================================================
3297  *      Handle cleared call.
3298  *====================================================================*/
3299
3300 static int call_cleared (sdla_t* card, int cmd, int lcn, TX25Mbox* mb)
3301 {
3302         unsigned new_lcn = mb->cmd.lcn;
3303         struct net_device* dev = find_channel(card, new_lcn);
3304         x25_channel_t *chan;
3305         unsigned char old_state;
3306
3307         if (card->u.x.logging){
3308                 printk(KERN_INFO "%s: X.25 clear request on LCN %d! Cause:0x%02X "
3309                 "Diagn:0x%02X\n",
3310                 card->devname, new_lcn, mb->cmd.cause, mb->cmd.diagn);
3311         }
3312
3313         if (dev == NULL){ 
3314                 printk(KERN_INFO "%s: X.25 clear request : No device for clear\n",
3315                                 card->devname);
3316                 return 1;
3317         }
3318
3319         chan=dev->priv;
3320
3321         old_state = chan->common.state;
3322
3323         set_chan_state(dev, WAN_DISCONNECTED);
3324
3325         if (chan->common.usedby == API){
3326
3327                 switch (old_state){
3328                 
3329                 case WAN_CONNECTING:
3330                         send_delayed_cmd_result(card,dev,mb);
3331                         break;
3332                 case WAN_CONNECTED:
3333                         send_oob_msg(card,dev,mb);                              
3334                         break;
3335                 }
3336         }
3337         
3338         return ((cmd == X25_WRITE) && (lcn == new_lcn)) ? 0 : 1;
3339 }
3340
3341 /*====================================================================
3342  *      Handle X.25 restart event.
3343  *====================================================================*/
3344
3345 static int restart_event (sdla_t* card, int cmd, int lcn, TX25Mbox* mb)
3346 {
3347         struct wan_device* wandev = &card->wandev;
3348         struct net_device* dev;
3349         x25_channel_t *chan;
3350         unsigned char old_state;
3351
3352         printk(KERN_INFO
3353                 "%s: X.25 restart request! Cause:0x%02X Diagn:0x%02X\n",
3354                 card->devname, mb->cmd.cause, mb->cmd.diagn);
3355
3356         /* down all logical channels */
3357         for (dev = wandev->dev; dev; dev = *((struct net_device **)dev->priv)) {
3358                 chan=dev->priv;
3359                 old_state = chan->common.state;
3360
3361                 set_chan_state(dev, WAN_DISCONNECTED);
3362
3363                 if (chan->common.usedby == API){
3364                         switch (old_state){
3365                 
3366                         case WAN_CONNECTING:
3367                                 send_delayed_cmd_result(card,dev,mb);
3368                                 break;
3369                         case WAN_CONNECTED:
3370                                 send_oob_msg(card,dev,mb);                              
3371                                 break;
3372                         }
3373                 }
3374         }
3375         return (cmd == X25_WRITE) ? 0 : 1;
3376 }
3377
3378 /*====================================================================
3379  * Handle timeout event.
3380  *====================================================================*/
3381
3382 static int timeout_event (sdla_t* card, int cmd, int lcn, TX25Mbox* mb)
3383 {
3384         unsigned new_lcn = mb->cmd.lcn;
3385
3386         if (mb->cmd.pktType == 0x05)    /* call request time out */
3387         {
3388                 struct net_device* dev = find_channel(card,new_lcn);
3389
3390                 printk(KERN_INFO "%s: X.25 call timed timeout on LCN %d!\n",
3391                         card->devname, new_lcn);
3392
3393                 if (dev){
3394                         x25_channel_t *chan = dev->priv;
3395                         set_chan_state(dev, WAN_DISCONNECTED);
3396
3397                         if (chan->common.usedby == API){
3398                                 send_delayed_cmd_result(card,dev,card->mbox);
3399                         }
3400                 }
3401         }else{ 
3402                 printk(KERN_INFO "%s: X.25 packet 0x%02X timeout on LCN %d!\n",
3403                 card->devname, mb->cmd.pktType, new_lcn);
3404         }
3405         return 1;
3406 }
3407
3408 /* 
3409  *      Miscellaneous 
3410  */
3411
3412 /*====================================================================
3413  *      Establish physical connection.
3414  *      o open HDLC and raise DTR
3415  *
3416  *      Return:         0       connection established
3417  *                      1       connection is in progress
3418  *                      <0      error
3419  *===================================================================*/
3420
3421 static int connect (sdla_t* card)
3422 {
3423         TX25Status* status = card->flags;
3424
3425         if (x25_open_hdlc(card) || x25_setup_hdlc(card))
3426                 return -EIO;
3427
3428         wanpipe_set_state(card, WAN_CONNECTING);
3429
3430         x25_set_intr_mode(card, INTR_ON_TIMER); 
3431         status->imask &= ~INTR_ON_TIMER;
3432
3433         return 1;
3434 }
3435
3436 /*
3437  *      Tear down physical connection.
3438  *      o close HDLC link
3439  *      o drop DTR
3440  *
3441  *      Return:         0
3442  *                      <0      error
3443  */
3444
3445 static int disconnect (sdla_t* card)
3446 {
3447         wanpipe_set_state(card, WAN_DISCONNECTED);
3448         x25_set_intr_mode(card, INTR_ON_TIMER); /* disable all interrupt except timer */
3449         x25_close_hdlc(card);                   /* close HDLC link */
3450         x25_set_dtr(card, 0);                   /* drop DTR */
3451         return 0;
3452 }
3453
3454 /*
3455  * Find network device by its channel number.
3456  */
3457
3458 static struct net_device* get_dev_by_lcn(struct wan_device* wandev,
3459                                          unsigned lcn)
3460 {
3461         struct net_device* dev;
3462
3463         for (dev = wandev->dev; dev; dev = *((struct net_device **)dev->priv))
3464                 if (((x25_channel_t*)dev->priv)->common.lcn == lcn) 
3465                         break;
3466         return dev;
3467 }
3468
3469 /*
3470  *      Initiate connection on the logical channel.
3471  *      o for PVC we just get channel configuration
3472  *      o for SVCs place an X.25 call
3473  *
3474  *      Return:         0       connected
3475  *                      >0      connection in progress
3476  *                      <0      failure
3477  */
3478
3479 static int chan_connect(struct net_device* dev)
3480 {
3481         x25_channel_t* chan = dev->priv;
3482         sdla_t* card = chan->card;
3483
3484         if (chan->common.svc && chan->common.usedby == WANPIPE){
3485                 if (!chan->addr[0]){
3486                         printk(KERN_INFO "%s: No Destination Address\n",
3487                                         card->devname);
3488                         return -EINVAL; /* no destination address */
3489                 }
3490                 printk(KERN_INFO "%s: placing X.25 call to %s ...\n",
3491                         card->devname, chan->addr);
3492
3493                 if (x25_place_call(card, chan) != CMD_OK)
3494                         return -EIO;
3495
3496                 set_chan_state(dev, WAN_CONNECTING);
3497                 return 1;
3498         }else{
3499                 if (x25_get_chan_conf(card, chan) != CMD_OK)
3500                         return -EIO;
3501
3502                 set_chan_state(dev, WAN_CONNECTED);
3503         }
3504         return 0;
3505 }
3506
3507 /*
3508  *      Disconnect logical channel.
3509  *      o if SVC then clear X.25 call
3510  */
3511
3512 static int chan_disc(struct net_device* dev)
3513 {
3514         x25_channel_t* chan = dev->priv;
3515
3516         if (chan->common.svc){ 
3517                 x25_clear_call(chan->card, chan->common.lcn, 0, 0);
3518
3519                 /* For API we disconnect on clear
3520                  * confirmation. 
3521                  */
3522                 if (chan->common.usedby == API)
3523                         return 0;
3524         }
3525
3526         set_chan_state(dev, WAN_DISCONNECTED);
3527         
3528         return 0;
3529 }
3530
3531 /*
3532  *      Set logical channel state.
3533  */
3534
3535 static void set_chan_state(struct net_device* dev, int state)
3536 {
3537         x25_channel_t* chan = dev->priv;
3538         sdla_t* card = chan->card;
3539         unsigned long flags;
3540
3541         save_flags(flags);
3542         cli();
3543         if (chan->common.state != state)
3544         {
3545                 switch (state)
3546                 {
3547                         case WAN_CONNECTED:
3548                                 if (card->u.x.logging){
3549                                         printk (KERN_INFO 
3550                                                 "%s: interface %s connected, lcn %i !\n", 
3551                                                 card->devname, dev->name,chan->common.lcn);
3552                                 }
3553                                 *(unsigned short*)dev->dev_addr = htons(chan->common.lcn);
3554                                 chan->i_timeout_sofar = jiffies;
3555
3556                                 /* LAPB is PVC Based */
3557                                 if (card->u.x.LAPB_hdlc)
3558                                         chan->common.svc=0;
3559                                 break;
3560
3561                         case WAN_CONNECTING:
3562                                 if (card->u.x.logging){
3563                                         printk (KERN_INFO 
3564                                                 "%s: interface %s connecting, lcn %i ...\n", 
3565                                                 card->devname, dev->name, chan->common.lcn);
3566                                 }
3567                                 break;
3568
3569                         case WAN_DISCONNECTED:
3570                                 if (card->u.x.logging){
3571                                         printk (KERN_INFO 
3572                                                 "%s: interface %s disconnected, lcn %i !\n", 
3573                                                 card->devname, dev->name,chan->common.lcn);
3574                                 }
3575                                 atomic_set(&chan->common.disconnect,0);
3576                                 
3577                                 if (chan->common.svc) {
3578                                         *(unsigned short*)dev->dev_addr = 0;
3579                                         card->u.x.svc_to_dev_map[(chan->common.lcn%X25_MAX_CHAN)]=NULL;
3580                                         chan->common.lcn = 0;
3581                                 }
3582
3583                                 if (chan->transmit_length){
3584                                         chan->transmit_length=0;
3585                                         atomic_set(&chan->common.driver_busy,0);
3586                                         chan->tx_offset=0;
3587                                         if (netif_queue_stopped(dev)){
3588                                                 netif_wake_queue(dev);
3589                                         }
3590                                 }
3591                                 atomic_set(&chan->common.command,0);
3592                                 break;
3593
3594                         case WAN_DISCONNECTING:
3595                                 if (card->u.x.logging){
3596                                         printk (KERN_INFO 
3597                                         "\n%s: interface %s disconnecting, lcn %i ...\n", 
3598                                         card->devname, dev->name,chan->common.lcn);
3599                                 }
3600                                 atomic_set(&chan->common.disconnect,0);
3601                                 break;
3602                 }
3603                 chan->common.state = state;
3604         }
3605         chan->state_tick = jiffies;
3606         restore_flags(flags);
3607 }
3608
3609 /*
3610  *      Send packet on a logical channel.
3611  *              When this function is called, tx_skb field of the channel data 
3612  *              space points to the transmit socket buffer.  When transmission 
3613  *              is complete, release socket buffer and reset 'tbusy' flag.
3614  *
3615  *      Return:         0       - transmission complete
3616  *                      1       - busy
3617  *
3618  *      Notes:
3619  *      1. If packet length is greater than MTU for this channel, we'll fragment
3620  *      the packet into 'complete sequence' using M-bit.
3621  *      2. When transmission is complete, an event notification should be issued
3622  *      to the router.
3623  */
3624
3625 static int chan_send(struct net_device* dev, void* buff, unsigned data_len,
3626                      unsigned char tx_intr)
3627 {
3628         x25_channel_t* chan = dev->priv;
3629         sdla_t* card = chan->card;
3630         TX25Status* status = card->flags;
3631         unsigned len=0, qdm=0, res=0, orig_len = 0;
3632         void *data;
3633
3634         /* Check to see if channel is ready */
3635         if ((!(status->cflags[chan->ch_idx] & 0x40) && !card->u.x.LAPB_hdlc)  || 
3636              !(*card->u.x.hdlc_buf_status & 0x40)){ 
3637             
3638                 if (!tx_intr){
3639                         setup_for_delayed_transmit (dev, buff, data_len);
3640                         return 0;
3641                 }else{
3642                         /* By returning 0 to tx_intr the packet will be dropped */
3643                         ++card->wandev.stats.tx_dropped;
3644                         ++chan->ifstats.tx_dropped;
3645                         printk(KERN_INFO "%s: ERROR, Tx intr could not send, dropping %s:\n", 
3646                                 card->devname,dev->name);
3647                         ++chan->if_send_stat.if_send_bfr_not_passed_to_adptr;
3648                         return 0;
3649                 }
3650         }
3651
3652         if (chan->common.usedby == API){
3653                 /* Remove the API Header */
3654                 x25api_hdr_t *api_data = (x25api_hdr_t *)buff;
3655
3656                 /* Set the qdm bits from the packet header 
3657                  * User has the option to set the qdm bits
3658                  */
3659                 qdm = api_data->qdm;
3660
3661                 orig_len = len = data_len - sizeof(x25api_hdr_t);
3662                 data = (unsigned char*)buff + sizeof(x25api_hdr_t);
3663         }else{
3664                 data = buff;
3665                 orig_len = len = data_len;
3666         }       
3667
3668         if (tx_intr){
3669                 /* We are in tx_intr, minus the tx_offset from 
3670                  * the total length. The tx_offset part of the
3671                  * data has already been sent. Also, move the 
3672                  * data pointer to proper offset location.
3673                  */
3674                 len -= chan->tx_offset;
3675                 data = (unsigned char*)data + chan->tx_offset;
3676         }
3677                 
3678         /* Check if the packet length is greater than MTU
3679          * If YES: Cut the len to MTU and set the M bit 
3680          */
3681         if (len > chan->tx_pkt_size && !card->u.x.LAPB_hdlc){
3682                 len = chan->tx_pkt_size;
3683                 qdm |= M_BIT;           
3684         } 
3685
3686
3687         /* Pass only first three bits of the qdm byte to the send
3688          * routine. In case user sets any other bit which might
3689          * cause errors. 
3690          */
3691
3692         switch(x25_send(card, chan->common.lcn, (qdm&0x07), len, data)){
3693                 case 0x00:      /* success */
3694                         chan->i_timeout_sofar = jiffies;
3695
3696                         dev->trans_start=jiffies;
3697                         
3698                         if ((qdm & M_BIT) && !card->u.x.LAPB_hdlc){
3699                                 if (!tx_intr){
3700                                         /* The M bit was set, which means that part of the
3701                                          * packet has been sent. Copy the packet into a buffer
3702                                          * and set the offset to len, so on next tx_inter 
3703                                          * the packet will be sent using the below offset.
3704                                          */
3705                                         chan->tx_offset += len;
3706
3707                                         ++chan->ifstats.tx_packets;
3708                                         chan->ifstats.tx_bytes += len;
3709                                         
3710                                         if (chan->tx_offset < orig_len){
3711                                                 setup_for_delayed_transmit (dev, buff, data_len);
3712                                         }
3713                                         res=0;
3714                                 }else{
3715                                         /* We are already in tx_inter, thus data is already
3716                                          * in the buffer. Update the offset and wait for
3717                                          * next tx_intr. We add on to the offset, since data can
3718                                          * be X number of times larger than max data size.
3719                                          */
3720                                         ++chan->ifstats.tx_packets;
3721                                         chan->ifstats.tx_bytes += len;
3722                                         
3723                                         ++chan->if_send_stat.if_send_bfr_passed_to_adptr;
3724                                         chan->tx_offset += len;
3725
3726                                         /* The user can set the qdm bit as well.
3727                                          * If the entire packet was sent and qdm is still
3728                                          * set, than it's the user who has set the M bit. In that,
3729                                          * case indicate that the packet was send by returning 
3730                                          * 0 and wait for a new packet. Otherwise, wait for next
3731                                          * tx interrupt to send the rest of the packet */
3732
3733                                         if (chan->tx_offset < orig_len){
3734                                                 res=1;
3735                                         }else{  
3736                                                 res=0;
3737                                         }
3738                                 }
3739                         }else{
3740                                 ++chan->ifstats.tx_packets;
3741                                 chan->ifstats.tx_bytes += len;
3742                                 ++chan->if_send_stat.if_send_bfr_passed_to_adptr;
3743                                 res=0;
3744                         }
3745                         break;
3746
3747                 case 0x33:      /* Tx busy */
3748                         if (tx_intr){
3749                                 printk(KERN_INFO "%s: Tx_intr: Big Error dropping packet %s\n",
3750                                                 card->devname,dev->name);
3751                                 ++chan->ifstats.tx_dropped;
3752                                 ++card->wandev.stats.tx_dropped;
3753                                 ++chan->if_send_stat.if_send_bfr_not_passed_to_adptr;
3754                                 res=0;
3755                         }else{
3756                                 DBG_PRINTK(KERN_INFO 
3757                                         "%s: Send: Big Error should have tx: storring %s\n",
3758                                                 card->devname,dev->name);
3759                                 setup_for_delayed_transmit (dev, buff, data_len);       
3760                                 res=1;
3761                         }
3762                         break;
3763
3764                 default:        /* failure */
3765                         ++chan->ifstats.tx_errors;
3766                         if (tx_intr){
3767                                 printk(KERN_INFO "%s: Tx_intr: Failure to send, dropping %s\n",
3768                                         card->devname,dev->name);
3769                                 ++chan->ifstats.tx_dropped;
3770                                 ++card->wandev.stats.tx_dropped;
3771                                 ++chan->if_send_stat.if_send_bfr_not_passed_to_adptr;
3772                                 res=0;
3773                         }else{
3774                                 DBG_PRINTK(KERN_INFO "%s: Send: Failure to send !!!, storing %s\n",
3775                                         card->devname,dev->name);                       
3776                                 setup_for_delayed_transmit (dev, buff, data_len);
3777                                 res=1;
3778                         }
3779                         break;  
3780         }
3781         return res;
3782 }
3783
3784
3785 /*
3786  *      Parse X.25 call request data and fill x25_call_info_t structure.
3787  */
3788
3789 static void parse_call_info (unsigned char* str, x25_call_info_t* info)
3790 {
3791         memset(info, 0, sizeof(x25_call_info_t));
3792         for (; *str; ++str)
3793         {
3794                 int i;
3795                 unsigned char ch;
3796
3797                 if (*str == '-') switch (str[1]) {
3798
3799                         /* Take minus 2 off the maximum size so that 
3800                          * last byte is 0. This way we can use string
3801                          * manipulaton functions on call information.
3802                          */
3803
3804                         case 'd':       /* destination address */
3805                                 for (i = 0; i < (MAX_X25_ADDR_SIZE-2); ++i){
3806                                         ch = str[2+i];
3807                                         if (isspace(ch)) break;
3808                                         info->dest[i] = ch;
3809                                 }
3810                                 break;
3811
3812                         case 's':       /* source address */
3813                                 for (i = 0; i < (MAX_X25_ADDR_SIZE-2); ++i){
3814                                         ch = str[2+i];
3815                                         if (isspace(ch)) break;
3816                                         info->src[i] = ch;
3817                                 }
3818                                 break;
3819
3820                         case 'u':       /* user data */
3821                                 for (i = 0; i < (MAX_X25_DATA_SIZE-2); ++i){
3822                                         ch = str[2+i];
3823                                         if (isspace(ch)) break;
3824                                         info->user[i] = ch; 
3825                                 }
3826                                 info->nuser = i;
3827                                 break;
3828
3829                         case 'f':       /* facilities */
3830                                 for (i = 0; i < (MAX_X25_FACL_SIZE-2); ++i){
3831                                         ch = str[2+i];
3832                                         if (isspace(ch)) break;
3833                                         info->facil[i] = ch;
3834                                 }
3835                                 info->nfacil = i;
3836                                 break;
3837                 }
3838         }
3839 }
3840
3841 /*
3842  *      Convert line speed in bps to a number used by S502 code.
3843  */
3844
3845 static unsigned char bps_to_speed_code (unsigned long bps)
3846 {
3847         unsigned char   number;
3848
3849         if (bps <= 1200)        number = 0x01;
3850         else if (bps <= 2400)   number = 0x02;
3851         else if (bps <= 4800)   number = 0x03;
3852         else if (bps <= 9600)   number = 0x04;
3853         else if (bps <= 19200)  number = 0x05;
3854         else if (bps <= 38400)  number = 0x06;
3855         else if (bps <= 45000)  number = 0x07;
3856         else if (bps <= 56000)  number = 0x08;
3857         else if (bps <= 64000)  number = 0x09;
3858         else if (bps <= 74000)  number = 0x0A;
3859         else if (bps <= 112000) number = 0x0B;
3860         else if (bps <= 128000) number = 0x0C;
3861         else number = 0x0D;
3862
3863         return number;
3864 }
3865
3866 /*
3867  *      Convert decimal string to unsigned integer.
3868  *      If len != 0 then only 'len' characters of the string are converted.
3869  */
3870
3871 static unsigned int dec_to_uint (unsigned char* str, int len)
3872 {
3873         unsigned val;
3874
3875         if (!len) 
3876                 len = strlen(str);
3877
3878         for (val = 0; len && is_digit(*str); ++str, --len)
3879                 val = (val * 10) + (*str - (unsigned)'0');
3880         
3881         return val;
3882 }
3883
3884 /*
3885  *      Convert hex string to unsigned integer.
3886  *      If len != 0 then only 'len' characters of the string are conferted.
3887  */
3888
3889 static unsigned int hex_to_uint (unsigned char* str, int len)
3890 {
3891         unsigned val, ch;
3892
3893         if (!len) 
3894                 len = strlen(str);
3895
3896         for (val = 0; len; ++str, --len)
3897         {
3898                 ch = *str;
3899                 if (is_digit(ch))
3900                         val = (val << 4) + (ch - (unsigned)'0');
3901                 else if (is_hex_digit(ch))
3902                         val = (val << 4) + ((ch & 0xDF) - (unsigned)'A' + 10);
3903                 else break;
3904         }
3905         return val;
3906 }
3907
3908
3909 static int handle_IPXWAN(unsigned char *sendpacket, char *devname, unsigned char enable_IPX, unsigned long network_number, unsigned short proto)
3910 {
3911         int i;
3912
3913         if( proto == ETH_P_IPX) {
3914                 /* It's an IPX packet */
3915                 if(!enable_IPX) {
3916                         /* Return 1 so we don't pass it up the stack. */
3917                         return 1;
3918                 }
3919         } else {
3920                 /* It's not IPX so pass it up the stack.*/ 
3921                 return 0;
3922         }
3923
3924         if( sendpacket[16] == 0x90 &&
3925             sendpacket[17] == 0x04)
3926         {
3927                 /* It's IPXWAN  */
3928
3929                 if( sendpacket[2] == 0x02 &&
3930                     sendpacket[34] == 0x00)
3931                 {
3932                         /* It's a timer request packet */
3933                         printk(KERN_INFO "%s: Received IPXWAN Timer Request packet\n",devname);
3934
3935                         /* Go through the routing options and answer no to every
3936                          * option except Unnumbered RIP/SAP
3937                          */
3938                         for(i = 41; sendpacket[i] == 0x00; i += 5)
3939                         {
3940                                 /* 0x02 is the option for Unnumbered RIP/SAP */
3941                                 if( sendpacket[i + 4] != 0x02)
3942                                 {
3943                                         sendpacket[i + 1] = 0;
3944                                 }
3945                         }
3946
3947                         /* Skip over the extended Node ID option */
3948                         if( sendpacket[i] == 0x04 )
3949                         {
3950                                 i += 8;
3951                         }
3952
3953                         /* We also want to turn off all header compression opt.                          */ 
3954                         for(; sendpacket[i] == 0x80 ;)
3955                         {
3956                                 sendpacket[i + 1] = 0;
3957                                 i += (sendpacket[i + 2] << 8) + (sendpacket[i + 3]) + 4;
3958                         }
3959
3960                         /* Set the packet type to timer response */
3961                         sendpacket[34] = 0x01;
3962
3963                         printk(KERN_INFO "%s: Sending IPXWAN Timer Response\n",devname);
3964                 }
3965                 else if( sendpacket[34] == 0x02 )
3966                 {
3967                         /* This is an information request packet */
3968                         printk(KERN_INFO "%s: Received IPXWAN Information Request packet\n",devname);
3969
3970                         /* Set the packet type to information response */
3971                         sendpacket[34] = 0x03;
3972
3973                         /* Set the router name */
3974                         sendpacket[51] = 'X';
3975                         sendpacket[52] = 'T';
3976                         sendpacket[53] = 'P';
3977                         sendpacket[54] = 'I';
3978                         sendpacket[55] = 'P';
3979                         sendpacket[56] = 'E';
3980                         sendpacket[57] = '-';
3981                         sendpacket[58] = CVHexToAscii(network_number >> 28);
3982                         sendpacket[59] = CVHexToAscii((network_number & 0x0F000000)>> 24);
3983                         sendpacket[60] = CVHexToAscii((network_number & 0x00F00000)>> 20);
3984                         sendpacket[61] = CVHexToAscii((network_number & 0x000F0000)>> 16);
3985                         sendpacket[62] = CVHexToAscii((network_number & 0x0000F000)>> 12);
3986                         sendpacket[63] = CVHexToAscii((network_number & 0x00000F00)>> 8);
3987                         sendpacket[64] = CVHexToAscii((network_number & 0x000000F0)>> 4);
3988                         sendpacket[65] = CVHexToAscii(network_number & 0x0000000F);
3989                         for(i = 66; i < 99; i+= 1)
3990                         {
3991                                 sendpacket[i] = 0;
3992                         }
3993
3994                         printk(KERN_INFO "%s: Sending IPXWAN Information Response packet\n",devname);
3995                 }
3996                 else
3997                 {
3998                         printk(KERN_INFO "%s: Unknown IPXWAN packet!\n",devname);
3999                         return 0;
4000                 }
4001
4002                 /* Set the WNodeID to our network address */
4003                 sendpacket[35] = (unsigned char)(network_number >> 24);
4004                 sendpacket[36] = (unsigned char)((network_number & 0x00FF0000) >> 16);
4005                 sendpacket[37] = (unsigned char)((network_number & 0x0000FF00) >> 8);
4006                 sendpacket[38] = (unsigned char)(network_number & 0x000000FF);
4007
4008                 return 1;
4009         } else {
4010                 /*If we get here it's an IPX-data packet, so it'll get passed up the stack.
4011                  */
4012                 /* switch the network numbers */
4013                 switch_net_numbers(sendpacket, network_number, 1);      
4014                 return 0;
4015         }
4016 }
4017
4018 /*
4019  *      If incoming is 0 (outgoing)- if the net numbers is ours make it 0
4020  *      if incoming is 1 - if the net number is 0 make it ours 
4021  */
4022
4023 static void switch_net_numbers(unsigned char *sendpacket, unsigned long network_number, unsigned char incoming)
4024 {
4025         unsigned long pnetwork_number;
4026
4027         pnetwork_number = (unsigned long)((sendpacket[6] << 24) + 
4028                           (sendpacket[7] << 16) + (sendpacket[8] << 8) + 
4029                           sendpacket[9]);
4030         
4031
4032         if (!incoming) {
4033                 /*If the destination network number is ours, make it 0 */
4034                 if( pnetwork_number == network_number) {
4035                         sendpacket[6] = sendpacket[7] = sendpacket[8] = 
4036                                          sendpacket[9] = 0x00;
4037                 }
4038         } else {
4039                 /* If the incoming network is 0, make it ours */
4040                 if( pnetwork_number == 0) {
4041                         sendpacket[6] = (unsigned char)(network_number >> 24);
4042                         sendpacket[7] = (unsigned char)((network_number & 
4043                                          0x00FF0000) >> 16);
4044                         sendpacket[8] = (unsigned char)((network_number & 
4045                                          0x0000FF00) >> 8);
4046                         sendpacket[9] = (unsigned char)(network_number & 
4047                                          0x000000FF);
4048                 }
4049         }
4050
4051
4052         pnetwork_number = (unsigned long)((sendpacket[18] << 24) + 
4053                           (sendpacket[19] << 16) + (sendpacket[20] << 8) + 
4054                           sendpacket[21]);
4055         
4056         
4057         if( !incoming ) {
4058                 /* If the source network is ours, make it 0 */
4059                 if( pnetwork_number == network_number) {
4060                         sendpacket[18] = sendpacket[19] = sendpacket[20] = 
4061                                  sendpacket[21] = 0x00;
4062                 }
4063         } else {
4064                 /* If the source network is 0, make it ours */
4065                 if( pnetwork_number == 0 ) {
4066                         sendpacket[18] = (unsigned char)(network_number >> 24);
4067                         sendpacket[19] = (unsigned char)((network_number & 
4068                                          0x00FF0000) >> 16);
4069                         sendpacket[20] = (unsigned char)((network_number & 
4070                                          0x0000FF00) >> 8);
4071                         sendpacket[21] = (unsigned char)(network_number & 
4072                                          0x000000FF);
4073                 }
4074         }
4075 } /* switch_net_numbers */
4076
4077
4078
4079
4080 /********************* X25API SPECIFIC FUNCTIONS ****************/
4081
4082
4083 /*===============================================================
4084  *  find_channel
4085  *
4086  *      Manages the lcn to device map. It increases performance
4087  *      because it eliminates the need to search through the link  
4088  *      list for a device which is bounded to a specific lcn.
4089  *
4090  *===============================================================*/
4091
4092
4093 struct net_device *find_channel(sdla_t *card, unsigned lcn)
4094 {
4095         if (card->u.x.LAPB_hdlc){
4096
4097                 return card->wandev.dev;
4098
4099         }else{
4100                 /* We don't know whether the incoming lcn
4101                  * is a PVC or an SVC channel. But we do know that
4102                  * the lcn cannot be for both the PVC and the SVC
4103                  * channel.
4104
4105                  * If the lcn number is greater or equal to 255, 
4106                  * take the modulo 255 of that number. We only have
4107                  * 255 locations, thus higher numbers must be mapped
4108                  * to a number between 0 and 245. 
4109
4110                  * We must separate pvc's and svc's since two don't
4111                  * have to be contiguous.  Meaning pvc's can start
4112                  * from 1 to 10 and svc's can start from 256 to 266.
4113                  * But 256%255 is 1, i.e. CONFLICT.
4114                  */
4115
4116
4117                 /* Highest LCN number must be less or equal to 4096 */
4118                 if ((lcn <= MAX_LCN_NUM) && (lcn > 0)){
4119
4120                         if (lcn < X25_MAX_CHAN){
4121                                 if (card->u.x.svc_to_dev_map[lcn])
4122                                         return card->u.x.svc_to_dev_map[lcn];
4123
4124                                 if (card->u.x.pvc_to_dev_map[lcn])
4125                                         return card->u.x.pvc_to_dev_map[lcn];
4126                         
4127                         }else{
4128                                 int new_lcn = lcn%X25_MAX_CHAN;
4129                                 if (card->u.x.svc_to_dev_map[new_lcn])
4130                                         return card->u.x.svc_to_dev_map[new_lcn];
4131
4132                                 if (card->u.x.pvc_to_dev_map[new_lcn])
4133                                         return card->u.x.pvc_to_dev_map[new_lcn];
4134                         }
4135                 }
4136                 return NULL;
4137         }
4138 }
4139
4140 void bind_lcn_to_dev(sdla_t *card, struct net_device *dev, unsigned lcn)
4141 {
4142         x25_channel_t *chan = dev->priv;
4143
4144         /* Modulo the lcn number by X25_MAX_CHAN (255)
4145          * because the lcn number can be greater than 255 
4146          *
4147          * We need to split svc and pvc since they don't have
4148          * to be contigous. 
4149          */
4150
4151         if (chan->common.svc){
4152                 card->u.x.svc_to_dev_map[(lcn % X25_MAX_CHAN)] = dev;
4153         }else{
4154                 card->u.x.pvc_to_dev_map[(lcn % X25_MAX_CHAN)] = dev;
4155         }
4156         chan->common.lcn = lcn;
4157 }
4158
4159
4160
4161 /*===============================================================
4162  * x25api_bh 
4163  *
4164  *
4165  *==============================================================*/
4166
4167 static void x25api_bh(struct net_device* dev)
4168 {
4169         x25_channel_t* chan = dev->priv;
4170         sdla_t* card = chan->card;
4171         struct sk_buff *skb;
4172
4173         if (atomic_read(&chan->bh_buff_used) == 0){
4174                 printk(KERN_INFO "%s: BH Buffer Empty in BH\n",
4175                                 card->devname);
4176                 clear_bit(0, &chan->tq_working);
4177                 return;
4178         }
4179
4180         while (atomic_read(&chan->bh_buff_used)){
4181
4182                 /* If the sock is in the process of unlinking the
4183                  * driver from the socket, we must get out. 
4184                  * This never happends but is a sanity check. */
4185                 if (test_bit(0,&chan->common.common_critical)){
4186                         clear_bit(0, &chan->tq_working);
4187                         return;
4188                 }
4189                 
4190                 /* If LAPB HDLC, do not drop packets if socket is
4191                  * not connected.  Let the buffer fill up and
4192                  * turn off rx interrupt */
4193                 if (card->u.x.LAPB_hdlc){
4194                         if (chan->common.sk == NULL || chan->common.func == NULL){
4195                                 clear_bit(0, &chan->tq_working);                        
4196                                 return;
4197                         }
4198                 }
4199
4200                 skb  = ((bh_data_t *)&chan->bh_head[chan->bh_read])->skb;
4201
4202                 if (skb == NULL){
4203                         printk(KERN_INFO "%s: BH Skb empty for read %i\n",
4204                                         card->devname,chan->bh_read);
4205                 }else{
4206                         
4207                         if (chan->common.sk == NULL || chan->common.func == NULL){
4208                                 printk(KERN_INFO "%s: BH: Socket disconnected, dropping\n",
4209                                                 card->devname);
4210                                 dev_kfree_skb_any(skb);
4211                                 x25api_bh_cleanup(dev);
4212                                 ++chan->ifstats.rx_dropped;
4213                                 ++chan->rx_intr_stat.rx_intr_bfr_not_passed_to_stack;
4214                                 continue;
4215                         }
4216
4217
4218                         if (chan->common.func(skb,dev,chan->common.sk) != 0){
4219                                 /* Sock full cannot send, queue us for another
4220                                  * try 
4221                                  */
4222                                 printk(KERN_INFO "%s: BH: !!! Packet failed to send !!!!! \n",
4223                                                 card->devname);
4224                                 atomic_set(&chan->common.receive_block,1);
4225                                 return;
4226                         }else{
4227                                 x25api_bh_cleanup(dev);
4228                                 ++chan->rx_intr_stat.rx_intr_bfr_passed_to_stack;
4229                         }
4230                 }
4231         }       
4232         clear_bit(0, &chan->tq_working);
4233
4234         return;
4235 }
4236
4237 /*===============================================================
4238  * x25api_bh_cleanup 
4239  *
4240  *
4241  *==============================================================*/
4242
4243 static int x25api_bh_cleanup(struct net_device *dev)
4244 {
4245         x25_channel_t* chan = dev->priv;
4246         sdla_t *card = chan->card;
4247         TX25Status* status = card->flags;
4248
4249
4250         ((bh_data_t *)&chan->bh_head[chan->bh_read])->skb = NULL;
4251
4252         if (chan->bh_read == MAX_BH_BUFF){
4253                 chan->bh_read=0;
4254         }else{
4255                 ++chan->bh_read;        
4256         }
4257
4258         /* If the Receive interrupt was off, it means
4259          * that we filled up our circular buffer. Check    
4260          * that we have space in the buffer. If so 
4261          * turn the RX interrupt back on. 
4262          */
4263         if (!(status->imask & INTR_ON_RX_FRAME)){
4264                 if (atomic_read(&chan->bh_buff_used) < (MAX_BH_BUFF+1)){
4265                         printk(KERN_INFO "%s: BH: Turning on the interrupt\n",
4266                                         card->devname);
4267                         status->imask |= INTR_ON_RX_FRAME;
4268                 }
4269         }       
4270
4271         atomic_dec(&chan->bh_buff_used);
4272         return 0;
4273 }
4274
4275
4276 /*===============================================================
4277  * bh_enqueue 
4278  *
4279  *
4280  *==============================================================*/
4281
4282 static int bh_enqueue(struct net_device *dev, struct sk_buff *skb)
4283 {
4284         x25_channel_t* chan = dev->priv;
4285         sdla_t *card = chan->card;
4286         TX25Status* status = card->flags;
4287
4288         if (atomic_read(&chan->bh_buff_used) == (MAX_BH_BUFF+1)){
4289                 printk(KERN_INFO "%s: Bottom half buffer FULL\n",
4290                                 card->devname);
4291                 return 1; 
4292         }
4293
4294         ((bh_data_t *)&chan->bh_head[chan->bh_write])->skb = skb;
4295
4296         if (chan->bh_write == MAX_BH_BUFF){
4297                 chan->bh_write=0;
4298         }else{
4299                 ++chan->bh_write;
4300         }
4301
4302         atomic_inc(&chan->bh_buff_used);
4303
4304         if (atomic_read(&chan->bh_buff_used) == (MAX_BH_BUFF+1)){
4305                 printk(KERN_INFO "%s: Buffer is now full, Turning off RX Intr\n",
4306                                 card->devname);
4307                 status->imask &= ~INTR_ON_RX_FRAME;
4308         }
4309
4310         return 0;
4311 }
4312
4313
4314 /*===============================================================
4315  * timer_intr_cmd_exec
4316  *  
4317  *      Called by timer interrupt to execute a command
4318  *===============================================================*/
4319
4320 static int timer_intr_cmd_exec (sdla_t* card)
4321 {
4322         struct net_device *dev;
4323         unsigned char more_to_exec=0;
4324         volatile x25_channel_t *chan=NULL;
4325         int i=0,bad_cmd=0,err=0;        
4326
4327         if (card->u.x.cmd_dev == NULL){
4328                 card->u.x.cmd_dev = card->wandev.dev;
4329         }
4330
4331         dev = card->u.x.cmd_dev;
4332
4333         for (;;){
4334
4335                 chan = dev->priv;
4336                 
4337                 if (atomic_read(&chan->common.command)){ 
4338
4339                         bad_cmd = check_bad_command(card,dev);
4340
4341                         if ((!chan->common.mbox || atomic_read(&chan->common.disconnect)) && 
4342                              !bad_cmd){
4343
4344                                 /* Socket has died or exited, We must bring the
4345                                  * channel down before anybody else tries to 
4346                                  * use it */
4347                                 err = channel_disconnect(card,dev);
4348                         }else{
4349                                 err = execute_delayed_cmd(card, dev,
4350                                                          (mbox_cmd_t*)chan->common.mbox,
4351                                                           bad_cmd);
4352                         }
4353
4354                         switch (err){
4355
4356                         case RETURN_RESULT:
4357
4358                                 /* Return the result to the socket without
4359                                  * delay. NO_WAIT Command */    
4360                                 atomic_set(&chan->common.command,0);
4361                                 if (atomic_read(&card->u.x.command_busy))
4362                                         atomic_set(&card->u.x.command_busy,0);
4363
4364                                 send_delayed_cmd_result(card,dev,card->mbox);
4365
4366                                 more_to_exec=0;
4367                                 break;
4368                         case DELAY_RESULT:
4369                 
4370                                 /* Wait for the remote to respond, before
4371                                  * sending the result up to the socket.
4372                                  * WAIT command */
4373                                 if (atomic_read(&card->u.x.command_busy))
4374                                         atomic_set(&card->u.x.command_busy,0);
4375                                 
4376                                 atomic_set(&chan->common.command,0);
4377                                 more_to_exec=0;
4378                                 break;
4379                         default:
4380
4381                                 /* If command could not be executed for
4382                                  * some reason (i.e return code 0x33 busy)
4383                                  * set the more_to_exec bit which will
4384                                  * indicate that this command must be exectued
4385                                  * again during next timer interrupt 
4386                                  */
4387                                 more_to_exec=1;
4388                                 if (atomic_read(&card->u.x.command_busy) == 0)
4389                                         atomic_set(&card->u.x.command_busy,1);
4390                                 break;
4391                         }
4392
4393                         bad_cmd=0;
4394
4395                         /* If flags is set, there are no hdlc buffers,
4396                          * thus, wait for the next pass and try the
4397                          * same command again. Otherwise, start searching 
4398                          * from next device on the next pass. 
4399                          */
4400                         if (!more_to_exec){
4401                                 dev = move_dev_to_next(card,dev);
4402                         }
4403                         break;
4404                 }else{
4405                         /* This device has nothing to execute,
4406                          * go to next. 
4407                          */
4408                         if (atomic_read(&card->u.x.command_busy))
4409                                         atomic_set(&card->u.x.command_busy,0);
4410                         dev = move_dev_to_next(card,dev);
4411                 }       
4412
4413                 if (++i == card->u.x.no_dev){
4414                         if (!more_to_exec){
4415                                 DBG_PRINTK(KERN_INFO "%s: Nothing to execute in Timer\n",
4416                                         card->devname);
4417                                 if (atomic_read(&card->u.x.command_busy)){
4418                                         atomic_set(&card->u.x.command_busy,0);
4419                                 }
4420                         }
4421                         break;
4422                 }
4423
4424         } //End of FOR
4425
4426         card->u.x.cmd_dev = dev;
4427         
4428         if (more_to_exec){
4429                 /* If more commands are pending, do not turn off timer 
4430                  * interrupt */
4431                 return 1;
4432         }else{
4433                 /* No more commands, turn off timer interrupt */
4434                 return 0;
4435         }       
4436 }
4437
4438 /*===============================================================
4439  * execute_delayed_cmd 
4440  *
4441  *      Execute an API command which was passed down from the
4442  *      sock.  Sock is very limited in which commands it can
4443  *      execute.  Wait and No Wait commands are supported.  
4444  *      Place Call, Clear Call and Reset wait commands, where
4445  *      Accept Call is a no_wait command.
4446  *
4447  *===============================================================*/
4448
4449 static int execute_delayed_cmd(sdla_t* card, struct net_device *dev,
4450                                mbox_cmd_t *usr_cmd, char bad_cmd)
4451 {
4452         TX25Mbox* mbox = card->mbox;
4453         int err;
4454         x25_channel_t *chan = dev->priv;
4455         int delay=RETURN_RESULT;
4456
4457         if (!(*card->u.x.hdlc_buf_status & 0x40) && !bad_cmd){
4458                 return TRY_CMD_AGAIN;
4459         }
4460
4461         /* This way a command is guaranteed to be executed for
4462          * a specific lcn, the network interface is bound to. */
4463         usr_cmd->cmd.lcn = chan->common.lcn;
4464         
4465
4466         /* If channel is pvc, instead of place call
4467          * run x25_channel configuration. If running LAPB HDLC
4468          * enable communications. 
4469          */
4470         if ((!chan->common.svc) && (usr_cmd->cmd.command == X25_PLACE_CALL)){
4471
4472                 if (card->u.x.LAPB_hdlc){
4473                         DBG_PRINTK(KERN_INFO "LAPB: Connecting\n");
4474                         connect(card);
4475                         set_chan_state(dev,WAN_CONNECTING);
4476                         return DELAY_RESULT;
4477                 }else{
4478                         DBG_PRINTK(KERN_INFO "%s: PVC is CONNECTING\n",card->devname);
4479                         if (x25_get_chan_conf(card, chan) == CMD_OK){
4480                                 set_chan_state(dev, WAN_CONNECTED);
4481                         }else{ 
4482                                 set_chan_state(dev, WAN_DISCONNECTED);
4483                         }
4484                         return RETURN_RESULT;
4485                 }
4486         }
4487
4488         /* Copy the socket mbox command onto the board */
4489
4490         memcpy(&mbox->cmd, &usr_cmd->cmd, sizeof(TX25Cmd));
4491         if (usr_cmd->cmd.length){
4492                 memcpy(mbox->data, usr_cmd->data, usr_cmd->cmd.length);
4493         }
4494
4495         /* Check if command is bad. We need to copy the cmd into
4496          * the buffer regardless since we return the, mbox to
4497          * the user */
4498         if (bad_cmd){
4499                 mbox->cmd.result=0x01;
4500                 return RETURN_RESULT;
4501         }
4502
4503         err = sdla_exec(mbox) ? mbox->cmd.result : CMD_TIMEOUT;
4504
4505         if (err != CMD_OK && err != X25RES_NOT_READY)
4506                 x25_error(card, err, usr_cmd->cmd.command, usr_cmd->cmd.lcn);
4507
4508         if (mbox->cmd.result == X25RES_NOT_READY){
4509                 return TRY_CMD_AGAIN;
4510         }
4511
4512         switch (mbox->cmd.command){
4513
4514         case X25_PLACE_CALL:
4515                 
4516                 switch (mbox->cmd.result){
4517
4518                 case CMD_OK:
4519
4520                         /* Check if Place call is a wait command or a 
4521                          * no wait command */
4522                         if (atomic_read(&chan->common.command) & 0x80)
4523                                 delay=RETURN_RESULT;
4524                         else
4525                                 delay=DELAY_RESULT;
4526                 
4527
4528                         DBG_PRINTK(KERN_INFO "\n%s: PLACE CALL Binding dev %s to lcn %i\n",
4529                                         card->devname,dev->name, mbox->cmd.lcn);
4530                 
4531                         bind_lcn_to_dev (card, dev, mbox->cmd.lcn);
4532                         set_chan_state(dev, WAN_CONNECTING);
4533                         break;
4534
4535
4536                 default:
4537                         delay=RETURN_RESULT;
4538                         set_chan_state(dev, WAN_DISCONNECTED);
4539                         break;
4540                 }
4541                 break;
4542
4543         case X25_ACCEPT_CALL: 
4544                 
4545                 switch (mbox->cmd.result){
4546
4547                 case CMD_OK:
4548
4549                         DBG_PRINTK(KERN_INFO "\n%s: ACCEPT Binding dev %s to lcn %i\n",
4550                                 card->devname,dev->name,mbox->cmd.lcn);
4551
4552                         bind_lcn_to_dev (card, dev, mbox->cmd.lcn);
4553
4554                         if (x25_get_chan_conf(card, chan) == CMD_OK){
4555
4556                                 set_chan_state(dev, WAN_CONNECTED);
4557                                 delay=RETURN_RESULT;
4558
4559                         }else{ 
4560                                 if (x25_clear_call(card, usr_cmd->cmd.lcn, 0, 0) == CMD_OK){
4561                                         /* if clear is successful, wait for clear confirm 
4562                                          */ 
4563                                         delay=DELAY_RESULT;
4564                                 }else{
4565                                         /* Do not change the state here. If we fail 
4566                                          * the accept the return code is send up 
4567                                          *the stack, which will ether retry
4568                                          * or clear the call 
4569                                          */
4570                                         DBG_PRINTK(KERN_INFO 
4571                                                 "%s: ACCEPT: STATE MAY BE CURRUPTED 2 !!!!!\n",
4572                                                 card->devname);
4573                                         delay=RETURN_RESULT;
4574                                 }
4575                         }
4576                         break;
4577
4578
4579                 case X25RES_ASYNC_PACKET:
4580                         delay=TRY_CMD_AGAIN;
4581                         break;
4582
4583                 default: 
4584                         DBG_PRINTK(KERN_INFO "%s: ACCEPT FAILED\n",card->devname);
4585                         if (x25_clear_call(card, usr_cmd->cmd.lcn, 0, 0) == CMD_OK){
4586                                 delay=DELAY_RESULT;
4587                         }else{
4588                                 /* Do not change the state here. If we fail the accept. The
4589                                  * return code is send up the stack, which will ether retry
4590                                  * or clear the call */
4591                                 DBG_PRINTK(KERN_INFO 
4592                                         "%s: ACCEPT: STATE MAY BE CORRUPTED 1 !!!!!\n",
4593                                                 card->devname);
4594                                 delay=RETURN_RESULT;
4595                         }
4596                 }
4597                 break;
4598
4599         case X25_CLEAR_CALL:
4600
4601                 switch (mbox->cmd.result){
4602
4603                 case CMD_OK:
4604                         DBG_PRINTK(KERN_INFO 
4605                                         "CALL CLEAR OK: Dev %s Mbox Lcn %i  Chan Lcn %i\n",
4606                                         dev->name,mbox->cmd.lcn,chan->common.lcn);
4607                         set_chan_state(dev, WAN_DISCONNECTING);
4608                         delay = DELAY_RESULT;
4609                         break;
4610
4611                 case X25RES_CHANNEL_IN_USE:
4612                 case X25RES_ASYNC_PACKET:
4613                         delay = TRY_CMD_AGAIN;
4614                         break;
4615                         
4616                 case X25RES_LINK_NOT_IN_ABM:
4617                 case X25RES_INVAL_LCN:
4618                 case X25RES_INVAL_STATE:
4619                         set_chan_state(dev, WAN_DISCONNECTED);
4620                         delay = RETURN_RESULT;
4621                         break;
4622                 
4623                 default:
4624                         /* If command did not execute because of user
4625                          * fault, do not change the state. This will
4626                          * signal the socket that clear command failed.
4627                          * User can retry or close the socket.
4628                          * When socket gets killed, it will set the 
4629                          * chan->disconnect which will signal
4630                          * driver to clear the call */
4631                         printk(KERN_INFO "%s: Clear Command Failed, Rc %x\n",
4632                                 card->devname,mbox->cmd.command); 
4633                         delay = RETURN_RESULT;
4634                 }
4635                 break;
4636         }       
4637
4638         return delay;
4639 }
4640
4641 /*===============================================================
4642  * api_incoming_call 
4643  *
4644  *      Pass an incoming call request up the listening
4645  *      sock.  If the API sock is not listening reject the
4646  *      call.
4647  *
4648  *===============================================================*/
4649
4650 static int api_incoming_call (sdla_t* card, TX25Mbox *mbox, int lcn)
4651 {
4652         struct sk_buff *skb;
4653         int len = sizeof(TX25Cmd)+mbox->cmd.length;
4654
4655         if (alloc_and_init_skb_buf(card, &skb, len)){
4656                 printk(KERN_INFO "%s: API incoming call, no memory\n",card->devname);
4657                 return 1;
4658         }
4659
4660         memcpy(skb_put(skb,len),&mbox->cmd,len);
4661
4662         skb->mac.raw = skb->data;
4663         skb->protocol = htons(X25_PROT);
4664         skb->pkt_type = WAN_PACKET_ASYNC;
4665
4666         if (card->func(skb,card->sk) < 0){
4667                 printk(KERN_INFO "%s: MAJOR ERROR: Failed to send up place call \n",card->devname);
4668                 dev_kfree_skb_any(skb);
4669                 return 1;
4670         }
4671
4672         return 0;
4673 }
4674
4675 /*===============================================================
4676  * send_delayed_cmd_result
4677  *
4678  *      Wait commands like PLEACE CALL or CLEAR CALL must wait
4679  *      until the result arrives. This function passes
4680  *      the result to a waiting sock. 
4681  *
4682  *===============================================================*/
4683 static void send_delayed_cmd_result(sdla_t *card, struct net_device *dev,
4684                                     TX25Mbox* mbox)
4685 {
4686         x25_channel_t *chan = dev->priv;
4687         mbox_cmd_t *usr_cmd = (mbox_cmd_t *)chan->common.mbox;
4688         struct sk_buff *skb;
4689         int len=sizeof(unsigned char);
4690
4691         atomic_set(&chan->common.command,0);
4692
4693         /* If the sock is in the process of unlinking the
4694          * driver from the socket, we must get out. 
4695          * This never happends but is a sanity check. */
4696         if (test_bit(0,&chan->common.common_critical)){
4697                 return;
4698         }
4699
4700         if (!usr_cmd || !chan->common.sk || !chan->common.func){
4701                 DBG_PRINTK(KERN_INFO "Delay result: Sock not bounded sk: %u, func: %u, mbox: %u\n",
4702                         (unsigned int)chan->common.sk,
4703                         (unsigned int)chan->common.func,
4704                         (unsigned int)usr_cmd); 
4705                 return;
4706         }
4707
4708         memcpy(&usr_cmd->cmd, &mbox->cmd, sizeof(TX25Cmd)); 
4709         if (mbox->cmd.length > 0){
4710                 memcpy(usr_cmd->data, mbox->data, mbox->cmd.length);
4711         }
4712
4713         if (alloc_and_init_skb_buf(card,&skb,len)){
4714                 printk(KERN_INFO "Delay result: No sock buffers\n");
4715                 return;
4716         }
4717
4718         memcpy(skb_put(skb,len),&mbox->cmd.command,len);
4719         
4720         skb->mac.raw = skb->data;
4721         skb->pkt_type = WAN_PACKET_CMD;
4722                         
4723         chan->common.func(skb,dev,chan->common.sk);
4724 }
4725
4726 /*===============================================================
4727  * clear_confirm_event
4728  *
4729  *      Pass the clear confirmation event up the sock. The
4730  *      API will disconnect only after the clear confirmation
4731  *      has been received. 
4732  *
4733  *      Depending on the state, clear confirmation could 
4734  *      be an OOB event, or a result of an API command.
4735  *===============================================================*/
4736
4737 static int clear_confirm_event (sdla_t *card, TX25Mbox* mb)
4738 {
4739         struct net_device *dev;
4740         x25_channel_t *chan;
4741         unsigned char old_state;        
4742
4743         dev = find_channel(card,mb->cmd.lcn);
4744         if (!dev){
4745                 DBG_PRINTK(KERN_INFO "%s: *** GOT CLEAR BUT NO DEV %i\n",
4746                                 card->devname,mb->cmd.lcn);
4747                 return 0;
4748         }
4749
4750         chan=dev->priv;
4751         DBG_PRINTK(KERN_INFO "%s: GOT CLEAR CONFIRM %s:  Mbox lcn %i  Chan lcn %i\n",
4752                         card->devname, dev->name, mb->cmd.lcn, chan->common.lcn);
4753
4754         /* If not API fall through to default. 
4755          * If API, send the result to a waiting
4756          * socket.
4757          */
4758         
4759         old_state = chan->common.state;
4760         set_chan_state(dev, WAN_DISCONNECTED);
4761
4762         if (chan->common.usedby == API){
4763                 switch (old_state) {
4764
4765                 case WAN_DISCONNECTING:
4766                 case WAN_CONNECTING:
4767                         send_delayed_cmd_result(card,dev,mb);
4768                         break;
4769                 case WAN_CONNECTED:
4770                         send_oob_msg(card,dev,mb);
4771                         break;
4772                 }
4773                 return 1;
4774         }
4775
4776         return 0;
4777 }
4778
4779 /*===============================================================
4780  * send_oob_msg
4781  *
4782  *    Construct an NEM Message and pass it up the connected
4783  *    sock. If the sock is not bounded discard the NEM.
4784  *
4785  *===============================================================*/
4786
4787 static void send_oob_msg(sdla_t *card, struct net_device *dev, TX25Mbox *mbox)
4788 {
4789         x25_channel_t *chan = dev->priv;
4790         mbox_cmd_t *usr_cmd = (mbox_cmd_t *)chan->common.mbox;
4791         struct sk_buff *skb;
4792         int len=sizeof(x25api_hdr_t)+mbox->cmd.length;
4793         x25api_t *api_hdr;
4794
4795         /* If the sock is in the process of unlinking the
4796          * driver from the socket, we must get out. 
4797          * This never happends but is a sanity check. */
4798         if (test_bit(0,&chan->common.common_critical)){
4799                 return;
4800         }
4801
4802         if (!usr_cmd || !chan->common.sk || !chan->common.func){
4803                 DBG_PRINTK(KERN_INFO "OOB MSG: Sock not bounded\n"); 
4804                 return;
4805         }
4806
4807         memcpy(&usr_cmd->cmd, &mbox->cmd, sizeof(TX25Cmd)); 
4808         if (mbox->cmd.length > 0){
4809                 memcpy(usr_cmd->data, mbox->data, mbox->cmd.length);
4810         }
4811
4812         if (alloc_and_init_skb_buf(card,&skb,len)){
4813                 printk(KERN_INFO "%s: OOB MSG: No sock buffers\n",card->devname);
4814                 return;
4815         }
4816
4817         api_hdr = (x25api_t*)skb_put(skb,len); 
4818         api_hdr->hdr.pktType = mbox->cmd.pktType & 0x7F;
4819         api_hdr->hdr.qdm     = mbox->cmd.qdm;
4820         api_hdr->hdr.cause   = mbox->cmd.cause;
4821         api_hdr->hdr.diagn   = mbox->cmd.diagn;
4822         api_hdr->hdr.length  = mbox->cmd.length;
4823         api_hdr->hdr.result  = mbox->cmd.result;
4824         api_hdr->hdr.lcn     = mbox->cmd.lcn;
4825
4826         if (mbox->cmd.length > 0){
4827                 memcpy(api_hdr->data,mbox->data,mbox->cmd.length);
4828         }
4829         
4830         skb->mac.raw = skb->data;
4831         skb->pkt_type = WAN_PACKET_ERR;
4832                         
4833         if (chan->common.func(skb,dev,chan->common.sk) < 0){
4834                 if (bh_enqueue(dev,skb)){
4835                         printk(KERN_INFO "%s: Dropping OOB MSG\n",card->devname);
4836                         dev_kfree_skb_any(skb);
4837                 }
4838         }
4839
4840         DBG_PRINTK(KERN_INFO "%s: OOB MSG OK, %s, lcn %i\n",
4841                         card->devname, dev->name, mbox->cmd.lcn);
4842 }       
4843
4844 /*===============================================================
4845  *  alloc_and_init_skb_buf 
4846  *
4847  *      Allocate and initialize an skb buffer. 
4848  *
4849  *===============================================================*/
4850
4851 static int alloc_and_init_skb_buf (sdla_t *card, struct sk_buff **skb, int len)
4852 {
4853         struct sk_buff *new_skb = *skb;
4854
4855         new_skb = dev_alloc_skb(len + X25_HRDHDR_SZ);
4856         if (new_skb == NULL){
4857                 printk(KERN_INFO "%s: no socket buffers available!\n",
4858                         card->devname);
4859                 return 1;
4860         }
4861
4862         if (skb_tailroom(new_skb) < len){
4863                 /* No room for the packet. Call off the whole thing! */
4864                 dev_kfree_skb_any(new_skb);
4865                 printk(KERN_INFO "%s: Listen: unexpectedly long packet sequence\n"
4866                         ,card->devname);
4867                 *skb = NULL;
4868                 return 1;
4869         }
4870
4871         *skb = new_skb;
4872         return 0;
4873
4874 }
4875
4876 /*===============================================================
4877  *  api_oob_event 
4878  *
4879  *      Send an OOB event up to the sock 
4880  *
4881  *===============================================================*/
4882
4883 static void api_oob_event (sdla_t *card,TX25Mbox *mbox)
4884 {
4885         struct net_device *dev = find_channel(card, mbox->cmd.lcn);
4886         x25_channel_t *chan;
4887
4888         if (!dev)
4889                 return;
4890
4891         chan=dev->priv;
4892
4893         if (chan->common.usedby == API)
4894                 send_oob_msg(card,dev,mbox);
4895         
4896 }
4897
4898
4899
4900
4901 static int channel_disconnect(sdla_t* card, struct net_device *dev)
4902 {
4903
4904         int err;
4905         x25_channel_t *chan = dev->priv;
4906
4907         DBG_PRINTK(KERN_INFO "%s: TIMER: %s, Device down disconnecting\n",
4908                                 card->devname,dev->name);
4909
4910         if (chan->common.svc){
4911                 err = x25_clear_call(card,chan->common.lcn,0,0);
4912         }else{
4913                 /* If channel is PVC or LAPB HDLC, there is no call
4914                  * to be cleared, thus drop down to the default
4915                  * area 
4916                  */
4917                 err = 1;
4918         }
4919
4920         switch (err){
4921         
4922                 case X25RES_CHANNEL_IN_USE:     
4923                 case X25RES_NOT_READY:
4924                         err = TRY_CMD_AGAIN;
4925                         break;
4926                 case CMD_OK:
4927                         DBG_PRINTK(KERN_INFO "CALL CLEAR OK: Dev %s Chan Lcn %i\n",
4928                                                 dev->name,chan->common.lcn);
4929
4930                         set_chan_state(dev,WAN_DISCONNECTING);
4931                         atomic_set(&chan->common.command,0);
4932                         err = DELAY_RESULT;
4933                         break;
4934                 default:
4935                         /* If LAPB HDLC protocol, bring the whole link down
4936                          * once the application terminates 
4937                          */
4938
4939                         set_chan_state(dev,WAN_DISCONNECTED);
4940
4941                         if (card->u.x.LAPB_hdlc){
4942                                 DBG_PRINTK(KERN_INFO "LAPB: Disconnecting Link\n");
4943                                 hdlc_link_down (card);
4944                         }
4945                         atomic_set(&chan->common.command,0);
4946                         err = RETURN_RESULT;
4947                         break;
4948         }
4949
4950         return err;
4951 }
4952
4953 static void hdlc_link_down (sdla_t *card)
4954 {
4955         TX25Mbox* mbox = card->mbox;
4956         int retry = 5;
4957         int err=0;
4958
4959         do {
4960                 memset(mbox,0,sizeof(TX25Mbox));
4961                 mbox->cmd.command = X25_HDLC_LINK_DISC;
4962                 mbox->cmd.length = 1;
4963                 mbox->data[0]=0;
4964                 err = sdla_exec(mbox) ? mbox->cmd.result : CMD_TIMEOUT;
4965
4966         } while (err && retry-- && x25_error(card, err, X25_HDLC_LINK_DISC, 0));
4967
4968         if (err)
4969                 printk(KERN_INFO "%s: Hdlc Link Down Failed %x\n",card->devname,err);
4970
4971         disconnect (card);
4972         
4973 }
4974
4975 static int check_bad_command(sdla_t* card, struct net_device *dev)
4976 {
4977         x25_channel_t *chan = dev->priv;
4978         int bad_cmd = 0;
4979
4980         switch (atomic_read(&chan->common.command)&0x7F){
4981
4982                 case X25_PLACE_CALL:
4983                         if (chan->common.state != WAN_DISCONNECTED)
4984                                 bad_cmd=1;
4985                         break;
4986                 case X25_CLEAR_CALL:
4987                         if (chan->common.state == WAN_DISCONNECTED)
4988                                 bad_cmd=1;
4989                         break;
4990                 case X25_ACCEPT_CALL:
4991                         if (chan->common.state != WAN_CONNECTING)
4992                                 bad_cmd=1;
4993                         break;
4994                 case X25_RESET:
4995                         if (chan->common.state != WAN_CONNECTED)
4996                                 bad_cmd=1;
4997                         break;
4998                 default:
4999                         bad_cmd=1;
5000                         break;
5001         }
5002
5003         if (bad_cmd){
5004                 printk(KERN_INFO "%s: Invalid State, BAD Command %x, dev %s, lcn %i, st %i\n", 
5005                         card->devname,atomic_read(&chan->common.command),dev->name, 
5006                         chan->common.lcn, chan->common.state);
5007         }
5008
5009         return bad_cmd;
5010 }
5011
5012
5013
5014 /*************************** XPIPEMON FUNCTIONS **************************/
5015
5016 /*==============================================================================
5017  * Process UDP call of type XPIPE
5018  */
5019
5020 static int process_udp_mgmt_pkt(sdla_t *card)
5021 {
5022         int            c_retry = MAX_CMD_RETRY;
5023         unsigned int   len;
5024         struct sk_buff *new_skb;
5025         TX25Mbox       *mbox = card->mbox;
5026         int            err;
5027         int            udp_mgmt_req_valid = 1;
5028         struct net_device *dev;
5029         x25_channel_t  *chan;
5030         unsigned short lcn;
5031         struct timeval tv;
5032         
5033
5034         x25_udp_pkt_t *x25_udp_pkt;
5035         x25_udp_pkt = (x25_udp_pkt_t *)card->u.x.udp_pkt_data;
5036
5037         dev = card->u.x.udp_dev;
5038         chan = dev->priv;
5039         lcn = chan->common.lcn;
5040
5041         switch(x25_udp_pkt->cblock.command) {
5042             
5043                 /* XPIPE_ENABLE_TRACE */
5044                 case XPIPE_ENABLE_TRACING:
5045
5046                 /* XPIPE_GET_TRACE_INFO */
5047                 case XPIPE_GET_TRACE_INFO:
5048  
5049                 /* SET FT1 MODE */
5050                 case XPIPE_SET_FT1_MODE:
5051            
5052                         if(card->u.x.udp_pkt_src == UDP_PKT_FRM_NETWORK) {
5053                                 ++chan->pipe_mgmt_stat.UDP_PIPE_mgmt_direction_err;
5054                                 udp_mgmt_req_valid = 0;
5055                                 break;
5056                         }
5057
5058                 /* XPIPE_FT1_READ_STATUS */
5059                 case XPIPE_FT1_READ_STATUS:
5060
5061                 /* FT1 MONITOR STATUS */
5062                 case XPIPE_FT1_STATUS_CTRL:
5063                         if(card->hw.fwid !=  SFID_X25_508) {
5064                                 ++chan->pipe_mgmt_stat.UDP_PIPE_mgmt_adptr_type_err;
5065                                 udp_mgmt_req_valid = 0;
5066                                 break;
5067                         }
5068                 default:
5069                         break;
5070         }
5071
5072         if(!udp_mgmt_req_valid) {
5073                 /* set length to 0 */
5074                 x25_udp_pkt->cblock.length = 0;
5075                 /* set return code */
5076                 x25_udp_pkt->cblock.result = (card->hw.fwid != SFID_X25_508) ? 0x1F : 0xCD;
5077                 
5078         } else {   
5079         
5080                 switch (x25_udp_pkt->cblock.command) {
5081     
5082         
5083                 case XPIPE_FLUSH_DRIVER_STATS:
5084                         init_x25_channel_struct(chan);
5085                         init_global_statistics(card);
5086                         mbox->cmd.length = 0;
5087                         break;
5088
5089
5090                 case XPIPE_DRIVER_STAT_IFSEND:
5091                         memcpy(x25_udp_pkt->data, &chan->if_send_stat, sizeof(if_send_stat_t));
5092                         mbox->cmd.length = sizeof(if_send_stat_t);
5093                         x25_udp_pkt->cblock.length =  mbox->cmd.length; 
5094                         break;
5095         
5096                 case XPIPE_DRIVER_STAT_INTR:
5097                         memcpy(&x25_udp_pkt->data[0], &card->statistics, sizeof(global_stats_t));
5098                         memcpy(&x25_udp_pkt->data[sizeof(global_stats_t)],
5099                                 &chan->rx_intr_stat, sizeof(rx_intr_stat_t));
5100                         
5101                         mbox->cmd.length = sizeof(global_stats_t) +
5102                                         sizeof(rx_intr_stat_t);
5103                         x25_udp_pkt->cblock.length =  mbox->cmd.length;
5104                         break;
5105
5106                 case XPIPE_DRIVER_STAT_GEN:
5107                         memcpy(x25_udp_pkt->data,
5108                                 &chan->pipe_mgmt_stat.UDP_PIPE_mgmt_kmalloc_err,
5109                                 sizeof(pipe_mgmt_stat_t));
5110
5111                         memcpy(&x25_udp_pkt->data[sizeof(pipe_mgmt_stat_t)],
5112                                &card->statistics, sizeof(global_stats_t));
5113
5114                         x25_udp_pkt->cblock.result = 0;
5115                         x25_udp_pkt->cblock.length = sizeof(global_stats_t)+
5116                                                      sizeof(rx_intr_stat_t);
5117                         mbox->cmd.length = x25_udp_pkt->cblock.length;
5118                         break;
5119
5120                 case XPIPE_ROUTER_UP_TIME:
5121                         do_gettimeofday(&tv);
5122                         chan->router_up_time = tv.tv_sec - chan->router_start_time;
5123                         *(unsigned long *)&x25_udp_pkt->data = chan->router_up_time;    
5124                         x25_udp_pkt->cblock.length = mbox->cmd.length = 4;
5125                         x25_udp_pkt->cblock.result = 0;
5126                         break;
5127         
5128                 default :
5129
5130                         do {
5131                                 memcpy(&mbox->cmd, &x25_udp_pkt->cblock.command, sizeof(TX25Cmd));
5132                                 if(mbox->cmd.length){ 
5133                                         memcpy(&mbox->data, 
5134                                                (char *)x25_udp_pkt->data, 
5135                                                mbox->cmd.length);
5136                                 }       
5137                 
5138                                 err = sdla_exec(mbox) ? mbox->cmd.result : CMD_TIMEOUT;
5139                         } while (err && c_retry-- && x25_error(card, err, mbox->cmd.command, 0));
5140
5141
5142                         if ( err == CMD_OK || 
5143                             (err == 1 && 
5144                              (mbox->cmd.command == 0x06 || 
5145                               mbox->cmd.command == 0x16)  ) ){
5146
5147                                 ++chan->pipe_mgmt_stat.UDP_PIPE_mgmt_adptr_cmnd_OK;
5148                         } else {
5149                                 ++chan->pipe_mgmt_stat.UDP_PIPE_mgmt_adptr_cmnd_timeout;
5150                         }
5151
5152                           /* copy the result back to our buffer */
5153                         memcpy(&x25_udp_pkt->cblock.command, &mbox->cmd, sizeof(TX25Cmd));
5154
5155                         if(mbox->cmd.length) {
5156                                memcpy(&x25_udp_pkt->data, &mbox->data, mbox->cmd.length);
5157                         }
5158                         break;
5159
5160                 } //switch
5161
5162         }
5163     
5164         /* Fill UDP TTL */
5165
5166         x25_udp_pkt->ip_pkt.ttl = card->wandev.ttl;
5167         len = reply_udp(card->u.x.udp_pkt_data, mbox->cmd.length);
5168
5169
5170         if(card->u.x.udp_pkt_src == UDP_PKT_FRM_NETWORK) {
5171                 
5172                 err = x25_send(card, lcn, 0, len, card->u.x.udp_pkt_data);
5173                 if (!err) 
5174                         ++chan->pipe_mgmt_stat.UDP_PIPE_mgmt_adptr_send_passed;
5175                 else
5176                         ++chan->pipe_mgmt_stat.UDP_PIPE_mgmt_adptr_send_failed;
5177         
5178         } else {
5179
5180                 /* Allocate socket buffer */
5181                 if((new_skb = dev_alloc_skb(len)) != NULL) {
5182                         void *buf;
5183
5184                         /* copy data into new_skb */
5185                         buf = skb_put(new_skb, len);
5186                         memcpy(buf, card->u.x.udp_pkt_data, len);
5187         
5188                         /* Decapsulate packet and pass it up the protocol 
5189                            stack */
5190                         new_skb->dev = dev;
5191         
5192                         if (chan->common.usedby == API)
5193                                 new_skb->protocol = htons(X25_PROT);
5194                         else 
5195                                 new_skb->protocol = htons(ETH_P_IP);
5196         
5197                         new_skb->mac.raw = new_skb->data;
5198
5199                         netif_rx(new_skb);
5200                         ++chan->pipe_mgmt_stat.UDP_PIPE_mgmt_passed_to_stack;
5201                 
5202                 } else {
5203                         ++chan->pipe_mgmt_stat.UDP_PIPE_mgmt_no_socket;
5204                         printk(KERN_INFO 
5205                         "%s: UDP mgmt cmnd, no socket buffers available!\n", 
5206                         card->devname);
5207                 }
5208         }
5209
5210         card->u.x.udp_pkt_lgth = 0;
5211
5212         return 1;
5213 }
5214
5215
5216 /*==============================================================================
5217  * Determine what type of UDP call it is. DRVSTATS or XPIPE8ND ?
5218  */
5219 static int udp_pkt_type( struct sk_buff *skb, sdla_t* card )
5220 {
5221         x25_udp_pkt_t *x25_udp_pkt = (x25_udp_pkt_t *)skb->data;
5222
5223         if((x25_udp_pkt->ip_pkt.protocol == UDPMGMT_UDP_PROTOCOL) &&
5224                 (x25_udp_pkt->ip_pkt.ver_inet_hdr_length == 0x45) &&
5225                 (x25_udp_pkt->udp_pkt.udp_dst_port == ntohs(card->wandev.udp_port)) &&
5226                 (x25_udp_pkt->wp_mgmt.request_reply == UDPMGMT_REQUEST)) {
5227
5228                         if(!strncmp(x25_udp_pkt->wp_mgmt.signature,
5229                                 UDPMGMT_XPIPE_SIGNATURE, 8)){
5230                                 return UDP_XPIPE_TYPE;
5231                         }else{
5232                                 printk(KERN_INFO "%s: UDP Packet, Failed Signature !\n",
5233                                         card->devname);
5234                         }
5235         }
5236
5237         return UDP_INVALID_TYPE;
5238 }
5239
5240
5241 /*============================================================================
5242  * Reply to UDP Management system.
5243  * Return nothing.
5244  */
5245 static int reply_udp( unsigned char *data, unsigned int mbox_len ) 
5246 {
5247         unsigned short len, udp_length, temp, ip_length;
5248         unsigned long ip_temp;
5249         int even_bound = 0;
5250
5251   
5252         x25_udp_pkt_t *x25_udp_pkt = (x25_udp_pkt_t *)data; 
5253
5254         /* Set length of packet */
5255         len = sizeof(ip_pkt_t)+ 
5256               sizeof(udp_pkt_t)+
5257               sizeof(wp_mgmt_t)+
5258               sizeof(cblock_t)+
5259               mbox_len;
5260  
5261
5262         /* fill in UDP reply */
5263         x25_udp_pkt->wp_mgmt.request_reply = UDPMGMT_REPLY;
5264   
5265         /* fill in UDP length */
5266         udp_length = sizeof(udp_pkt_t)+ 
5267                      sizeof(wp_mgmt_t)+
5268                      sizeof(cblock_t)+
5269                      mbox_len; 
5270
5271
5272         /* put it on an even boundary */
5273         if ( udp_length & 0x0001 ) {
5274                 udp_length += 1;
5275                 len += 1;
5276                 even_bound = 1;
5277         }
5278
5279         temp = (udp_length<<8)|(udp_length>>8);
5280         x25_udp_pkt->udp_pkt.udp_length = temp;
5281          
5282         /* swap UDP ports */
5283         temp = x25_udp_pkt->udp_pkt.udp_src_port;
5284         x25_udp_pkt->udp_pkt.udp_src_port = 
5285                         x25_udp_pkt->udp_pkt.udp_dst_port; 
5286         x25_udp_pkt->udp_pkt.udp_dst_port = temp;
5287
5288
5289
5290         /* add UDP pseudo header */
5291         temp = 0x1100;
5292         *((unsigned short *)
5293                 (x25_udp_pkt->data+mbox_len+even_bound)) = temp;        
5294         temp = (udp_length<<8)|(udp_length>>8);
5295         *((unsigned short *)
5296                 (x25_udp_pkt->data+mbox_len+even_bound+2)) = temp;
5297                  
5298         /* calculate UDP checksum */
5299         x25_udp_pkt->udp_pkt.udp_checksum = 0;
5300
5301         x25_udp_pkt->udp_pkt.udp_checksum = 
5302                 calc_checksum(&data[UDP_OFFSET], udp_length+UDP_OFFSET);
5303
5304         /* fill in IP length */
5305         ip_length = len;
5306         temp = (ip_length<<8)|(ip_length>>8);
5307         x25_udp_pkt->ip_pkt.total_length = temp;
5308   
5309         /* swap IP addresses */
5310         ip_temp = x25_udp_pkt->ip_pkt.ip_src_address;
5311         x25_udp_pkt->ip_pkt.ip_src_address = 
5312                                 x25_udp_pkt->ip_pkt.ip_dst_address;
5313         x25_udp_pkt->ip_pkt.ip_dst_address = ip_temp;
5314
5315                  
5316         /* fill in IP checksum */
5317         x25_udp_pkt->ip_pkt.hdr_checksum = 0;
5318         x25_udp_pkt->ip_pkt.hdr_checksum = calc_checksum(data, sizeof(ip_pkt_t));
5319
5320         return len;
5321 } /* reply_udp */
5322
5323 unsigned short calc_checksum (char *data, int len)
5324 {
5325         unsigned short temp; 
5326         unsigned long sum=0;
5327         int i;
5328
5329         for( i = 0; i <len; i+=2 ) {
5330                 memcpy(&temp,&data[i],2);
5331                 sum += (unsigned long)temp;
5332         }
5333
5334         while (sum >> 16 ) {
5335                 sum = (sum & 0xffffUL) + (sum >> 16);
5336         }
5337
5338         temp = (unsigned short)sum;
5339         temp = ~temp;
5340
5341         if( temp == 0 ) 
5342                 temp = 0xffff;
5343
5344         return temp;    
5345 }
5346
5347 /*=============================================================================
5348  * Store a UDP management packet for later processing.
5349  */
5350
5351 static int store_udp_mgmt_pkt(int udp_type, char udp_pkt_src, sdla_t* card,
5352                               struct net_device *dev, struct sk_buff *skb,
5353                               int lcn)
5354 {
5355         int udp_pkt_stored = 0;
5356
5357         if(!card->u.x.udp_pkt_lgth && (skb->len <= MAX_LGTH_UDP_MGNT_PKT)){
5358                 card->u.x.udp_pkt_lgth = skb->len;
5359                 card->u.x.udp_type = udp_type;
5360                 card->u.x.udp_pkt_src = udp_pkt_src;
5361                 card->u.x.udp_lcn = lcn;
5362                 card->u.x.udp_dev = dev;
5363                 memcpy(card->u.x.udp_pkt_data, skb->data, skb->len);
5364                 card->u.x.timer_int_enabled |= TMR_INT_ENABLED_UDP_PKT;
5365                 udp_pkt_stored = 1;
5366
5367         }else{
5368                 printk(KERN_INFO "%s: ERROR: UDP packet not stored for LCN %d\n", 
5369                                                         card->devname,lcn);
5370         }
5371
5372         if(udp_pkt_src == UDP_PKT_FRM_STACK){
5373                 dev_kfree_skb_any(skb);
5374         }else{
5375                 dev_kfree_skb_any(skb);
5376         }
5377
5378         return(udp_pkt_stored);
5379 }
5380
5381
5382
5383 /*=============================================================================
5384  * Initial the ppp_private_area structure.
5385  */
5386 static void init_x25_channel_struct( x25_channel_t *chan )
5387 {
5388         memset(&chan->if_send_stat.if_send_entry,0,sizeof(if_send_stat_t));
5389         memset(&chan->rx_intr_stat.rx_intr_no_socket,0,sizeof(rx_intr_stat_t));
5390         memset(&chan->pipe_mgmt_stat.UDP_PIPE_mgmt_kmalloc_err,0,sizeof(pipe_mgmt_stat_t));
5391 }
5392
5393 /*============================================================================
5394  * Initialize Global Statistics
5395  */
5396 static void init_global_statistics( sdla_t *card )
5397 {
5398         memset(&card->statistics.isr_entry,0,sizeof(global_stats_t));
5399 }
5400
5401
5402 /*===============================================================
5403  * SMP Support
5404  * ==============================================================*/
5405
5406 static void S508_S514_lock(sdla_t *card, unsigned long *smp_flags)
5407 {
5408         spin_lock_irqsave(&card->wandev.lock, *smp_flags);
5409 }
5410 static void S508_S514_unlock(sdla_t *card, unsigned long *smp_flags)
5411 {
5412         spin_unlock_irqrestore(&card->wandev.lock, *smp_flags);
5413 }
5414
5415 /*===============================================================
5416  * x25_timer_routine
5417  *
5418  *      A more efficient polling routine.  Each half a second
5419  *      queue a polling task. We want to do the polling in a 
5420  *      task not timer, because timer runs in interrupt time.
5421  *
5422  *      FIXME Polling should be rethinked.
5423  *==============================================================*/
5424
5425 static void x25_timer_routine(unsigned long data)
5426 {
5427         sdla_t *card = (sdla_t*)data;
5428
5429         if (!card->wandev.dev){
5430                 printk(KERN_INFO "%s: Stopping the X25 Poll Timer: No Dev.\n",
5431                                 card->devname);
5432                 return;
5433         }
5434
5435         if (card->open_cnt != card->u.x.num_of_ch){
5436                 printk(KERN_INFO "%s: Stopping the X25 Poll Timer: Interface down.\n",
5437                                 card->devname);
5438                 return;
5439         }
5440
5441         if (test_bit(PERI_CRIT,&card->wandev.critical)){
5442                 printk(KERN_INFO "%s: Stopping the X25 Poll Timer: Shutting down.\n",
5443                                 card->devname);
5444                 return;
5445         }
5446         
5447         if (!test_and_set_bit(POLL_CRIT,&card->wandev.critical)){
5448                 trigger_x25_poll(card);
5449         }
5450         
5451         card->u.x.x25_timer.expires=jiffies+(HZ>>1);
5452         add_timer(&card->u.x.x25_timer);
5453         return;
5454 }
5455
5456 void disable_comm_shutdown(sdla_t *card)
5457 {
5458         TX25Mbox* mbox = card->mbox;
5459         int err;
5460
5461         /* Turn of interrutps */
5462         mbox->data[0] = 0;
5463         if (card->hw.fwid == SFID_X25_508){
5464                 mbox->data[1] = card->hw.irq;
5465                 mbox->data[2] = 2;
5466                 mbox->cmd.length = 3;
5467         }else {
5468                 mbox->cmd.length  = 1;
5469         }
5470         mbox->cmd.command = X25_SET_INTERRUPT_MODE;
5471         err = sdla_exec(mbox) ? mbox->cmd.result : CMD_TIMEOUT;
5472         if (err)
5473                 printk(KERN_INFO "INTERRUPT OFF FAIED %x\n",err);
5474
5475         /* Bring down HDLC */
5476         mbox->cmd.command = X25_HDLC_LINK_CLOSE;
5477         mbox->cmd.length  = 0;
5478         err = sdla_exec(mbox) ? mbox->cmd.result : CMD_TIMEOUT;
5479         if (err)
5480                 printk(KERN_INFO "LINK CLOSED FAILED %x\n",err);
5481
5482
5483         /* Brind down DTR */
5484         mbox->data[0] = 0;
5485         mbox->data[2] = 0;
5486         mbox->data[1] = 0x01;
5487         mbox->cmd.length  = 3;
5488         mbox->cmd.command = X25_SET_GLOBAL_VARS;
5489         err = sdla_exec(mbox) ? mbox->cmd.result : CMD_TIMEOUT;
5490         if (err)
5491                 printk(KERN_INFO "DTR DOWN FAILED %x\n",err);
5492
5493 }
5494
5495 MODULE_LICENSE("GPL");
5496
5497 /****** End *****************************************************************/