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