ftp://ftp.kernel.org/pub/linux/kernel/v2.6/linux-2.6.6.tar.bz2
[linux-2.6.git] / drivers / char / synclink.c
1 /*
2  * linux/drivers/char/synclink.c
3  *
4  * $Id: synclink.c,v 4.21 2004/03/08 15:29:22 paulkf Exp $
5  *
6  * Device driver for Microgate SyncLink ISA and PCI
7  * high speed multiprotocol serial adapters.
8  *
9  * written by Paul Fulghum for Microgate Corporation
10  * paulkf@microgate.com
11  *
12  * Microgate and SyncLink are trademarks of Microgate Corporation
13  *
14  * Derived from serial.c written by Theodore Ts'o and Linus Torvalds
15  *
16  * Original release 01/11/99
17  *
18  * This code is released under the GNU General Public License (GPL)
19  *
20  * This driver is primarily intended for use in synchronous
21  * HDLC mode. Asynchronous mode is also provided.
22  *
23  * When operating in synchronous mode, each call to mgsl_write()
24  * contains exactly one complete HDLC frame. Calling mgsl_put_char
25  * will start assembling an HDLC frame that will not be sent until
26  * mgsl_flush_chars or mgsl_write is called.
27  * 
28  * Synchronous receive data is reported as complete frames. To accomplish
29  * this, the TTY flip buffer is bypassed (too small to hold largest
30  * frame and may fragment frames) and the line discipline
31  * receive entry point is called directly.
32  *
33  * This driver has been tested with a slightly modified ppp.c driver
34  * for synchronous PPP.
35  *
36  * 2000/02/16
37  * Added interface for syncppp.c driver (an alternate synchronous PPP
38  * implementation that also supports Cisco HDLC). Each device instance
39  * registers as a tty device AND a network device (if dosyncppp option
40  * is set for the device). The functionality is determined by which
41  * device interface is opened.
42  *
43  * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
44  * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
45  * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
46  * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
47  * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
48  * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
49  * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
50  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
51  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
52  * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
53  * OF THE POSSIBILITY OF SUCH DAMAGE.
54  */
55
56 #define VERSION(ver,rel,seq) (((ver)<<16) | ((rel)<<8) | (seq))
57 #if defined(__i386__)
58 #  define BREAKPOINT() asm("   int $3");
59 #else
60 #  define BREAKPOINT() { }
61 #endif
62
63 #define MAX_ISA_DEVICES 10
64 #define MAX_PCI_DEVICES 10
65 #define MAX_TOTAL_DEVICES 20
66
67 #include <linux/config.h>       
68 #include <linux/module.h>
69 #include <linux/errno.h>
70 #include <linux/signal.h>
71 #include <linux/sched.h>
72 #include <linux/timer.h>
73 #include <linux/interrupt.h>
74 #include <linux/pci.h>
75 #include <linux/tty.h>
76 #include <linux/tty_flip.h>
77 #include <linux/serial.h>
78 #include <linux/major.h>
79 #include <linux/string.h>
80 #include <linux/fcntl.h>
81 #include <linux/ptrace.h>
82 #include <linux/ioport.h>
83 #include <linux/mm.h>
84 #include <linux/slab.h>
85
86 #include <linux/netdevice.h>
87
88 #include <linux/vmalloc.h>
89 #include <linux/init.h>
90 #include <asm/serial.h>
91
92 #include <linux/delay.h>
93 #include <linux/ioctl.h>
94
95 #include <asm/system.h>
96 #include <asm/io.h>
97 #include <asm/irq.h>
98 #include <asm/dma.h>
99 #include <asm/bitops.h>
100 #include <asm/types.h>
101 #include <linux/termios.h>
102 #include <linux/workqueue.h>
103
104 #ifdef CONFIG_SYNCLINK_SYNCPPP_MODULE
105 #define CONFIG_SYNCLINK_SYNCPPP 1
106 #endif
107
108 #ifdef CONFIG_SYNCLINK_SYNCPPP
109 #include <net/syncppp.h>
110 #endif
111
112 #define GET_USER(error,value,addr) error = get_user(value,addr)
113 #define COPY_FROM_USER(error,dest,src,size) error = copy_from_user(dest,src,size) ? -EFAULT : 0
114 #define PUT_USER(error,value,addr) error = put_user(value,addr)
115 #define COPY_TO_USER(error,dest,src,size) error = copy_to_user(dest,src,size) ? -EFAULT : 0
116
117 #include <asm/uaccess.h>
118
119 #include "linux/synclink.h"
120
121 #define RCLRVALUE 0xffff
122
123 MGSL_PARAMS default_params = {
124         MGSL_MODE_HDLC,                 /* unsigned long mode */
125         0,                              /* unsigned char loopback; */
126         HDLC_FLAG_UNDERRUN_ABORT15,     /* unsigned short flags; */
127         HDLC_ENCODING_NRZI_SPACE,       /* unsigned char encoding; */
128         0,                              /* unsigned long clock_speed; */
129         0xff,                           /* unsigned char addr_filter; */
130         HDLC_CRC_16_CCITT,              /* unsigned short crc_type; */
131         HDLC_PREAMBLE_LENGTH_8BITS,     /* unsigned char preamble_length; */
132         HDLC_PREAMBLE_PATTERN_NONE,     /* unsigned char preamble; */
133         9600,                           /* unsigned long data_rate; */
134         8,                              /* unsigned char data_bits; */
135         1,                              /* unsigned char stop_bits; */
136         ASYNC_PARITY_NONE               /* unsigned char parity; */
137 };
138
139 #define SHARED_MEM_ADDRESS_SIZE 0x40000
140 #define BUFFERLISTSIZE (PAGE_SIZE)
141 #define DMABUFFERSIZE (PAGE_SIZE)
142 #define MAXRXFRAMES 7
143
144 typedef struct _DMABUFFERENTRY
145 {
146         u32 phys_addr;  /* 32-bit flat physical address of data buffer */
147         u16 count;      /* buffer size/data count */
148         u16 status;     /* Control/status field */
149         u16 rcc;        /* character count field */
150         u16 reserved;   /* padding required by 16C32 */
151         u32 link;       /* 32-bit flat link to next buffer entry */
152         char *virt_addr;        /* virtual address of data buffer */
153         u32 phys_entry; /* physical address of this buffer entry */
154 } DMABUFFERENTRY, *DMAPBUFFERENTRY;
155
156 /* The queue of BH actions to be performed */
157
158 #define BH_RECEIVE  1
159 #define BH_TRANSMIT 2
160 #define BH_STATUS   4
161
162 #define IO_PIN_SHUTDOWN_LIMIT 100
163
164 #define RELEVANT_IFLAG(iflag) (iflag & (IGNBRK|BRKINT|IGNPAR|PARMRK|INPCK))
165
166 struct  _input_signal_events {
167         int     ri_up;  
168         int     ri_down;
169         int     dsr_up;
170         int     dsr_down;
171         int     dcd_up;
172         int     dcd_down;
173         int     cts_up;
174         int     cts_down;
175 };
176
177 /* transmit holding buffer definitions*/
178 #define MAX_TX_HOLDING_BUFFERS 5
179 struct tx_holding_buffer {
180         int     buffer_size;
181         unsigned char * buffer;
182 };
183
184
185 /*
186  * Device instance data structure
187  */
188  
189 struct mgsl_struct {
190         void *if_ptr;   /* General purpose pointer (used by SPPP) */
191         int                     magic;
192         int                     flags;
193         int                     count;          /* count of opens */
194         int                     line;
195         int                     hw_version;
196         unsigned short          close_delay;
197         unsigned short          closing_wait;   /* time to wait before closing */
198         
199         struct mgsl_icount      icount;
200         
201         struct tty_struct       *tty;
202         int                     timeout;
203         int                     x_char;         /* xon/xoff character */
204         int                     blocked_open;   /* # of blocked opens */
205         u16                     read_status_mask;
206         u16                     ignore_status_mask;     
207         unsigned char           *xmit_buf;
208         int                     xmit_head;
209         int                     xmit_tail;
210         int                     xmit_cnt;
211         
212         wait_queue_head_t       open_wait;
213         wait_queue_head_t       close_wait;
214         
215         wait_queue_head_t       status_event_wait_q;
216         wait_queue_head_t       event_wait_q;
217         struct timer_list       tx_timer;       /* HDLC transmit timeout timer */
218         struct mgsl_struct      *next_device;   /* device list link */
219         
220         spinlock_t irq_spinlock;                /* spinlock for synchronizing with ISR */
221         struct work_struct task;                /* task structure for scheduling bh */
222
223         u32 EventMask;                  /* event trigger mask */
224         u32 RecordedEvents;             /* pending events */
225
226         u32 max_frame_size;             /* as set by device config */
227
228         u32 pending_bh;
229
230         int bh_running;         /* Protection from multiple */
231         int isr_overflow;
232         int bh_requested;
233         
234         int dcd_chkcount;               /* check counts to prevent */
235         int cts_chkcount;               /* too many IRQs if a signal */
236         int dsr_chkcount;               /* is floating */
237         int ri_chkcount;
238
239         char *buffer_list;              /* virtual address of Rx & Tx buffer lists */
240         unsigned long buffer_list_phys;
241
242         unsigned int rx_buffer_count;   /* count of total allocated Rx buffers */
243         DMABUFFERENTRY *rx_buffer_list; /* list of receive buffer entries */
244         unsigned int current_rx_buffer;
245
246         int num_tx_dma_buffers;         /* number of tx dma frames required */
247         int tx_dma_buffers_used;
248         unsigned int tx_buffer_count;   /* count of total allocated Tx buffers */
249         DMABUFFERENTRY *tx_buffer_list; /* list of transmit buffer entries */
250         int start_tx_dma_buffer;        /* tx dma buffer to start tx dma operation */
251         int current_tx_buffer;          /* next tx dma buffer to be loaded */
252         
253         unsigned char *intermediate_rxbuffer;
254
255         int num_tx_holding_buffers;     /* number of tx holding buffer allocated */
256         int get_tx_holding_index;       /* next tx holding buffer for adapter to load */
257         int put_tx_holding_index;       /* next tx holding buffer to store user request */
258         int tx_holding_count;           /* number of tx holding buffers waiting */
259         struct tx_holding_buffer tx_holding_buffers[MAX_TX_HOLDING_BUFFERS];
260
261         int rx_enabled;
262         int rx_overflow;
263         int rx_rcc_underrun;
264
265         int tx_enabled;
266         int tx_active;
267         u32 idle_mode;
268
269         u16 cmr_value;
270         u16 tcsr_value;
271
272         char device_name[25];           /* device instance name */
273
274         unsigned int bus_type;  /* expansion bus type (ISA,EISA,PCI) */
275         unsigned char bus;              /* expansion bus number (zero based) */
276         unsigned char function;         /* PCI device number */
277
278         unsigned int io_base;           /* base I/O address of adapter */
279         unsigned int io_addr_size;      /* size of the I/O address range */
280         int io_addr_requested;          /* nonzero if I/O address requested */
281         
282         unsigned int irq_level;         /* interrupt level */
283         unsigned long irq_flags;
284         int irq_requested;              /* nonzero if IRQ requested */
285         
286         unsigned int dma_level;         /* DMA channel */
287         int dma_requested;              /* nonzero if dma channel requested */
288
289         u16 mbre_bit;
290         u16 loopback_bits;
291         u16 usc_idle_mode;
292
293         MGSL_PARAMS params;             /* communications parameters */
294
295         unsigned char serial_signals;   /* current serial signal states */
296
297         int irq_occurred;               /* for diagnostics use */
298         unsigned int init_error;        /* Initialization startup error                 (DIAGS) */
299         int     fDiagnosticsmode;       /* Driver in Diagnostic mode?                   (DIAGS) */
300
301         u32 last_mem_alloc;
302         unsigned char* memory_base;     /* shared memory address (PCI only) */
303         u32 phys_memory_base;
304         int shared_mem_requested;
305
306         unsigned char* lcr_base;        /* local config registers (PCI only) */
307         u32 phys_lcr_base;
308         u32 lcr_offset;
309         int lcr_mem_requested;
310
311         u32 misc_ctrl_value;
312         char flag_buf[MAX_ASYNC_BUFFER_SIZE];
313         char char_buf[MAX_ASYNC_BUFFER_SIZE];   
314         BOOLEAN drop_rts_on_tx_done;
315
316         BOOLEAN loopmode_insert_requested;
317         BOOLEAN loopmode_send_done_requested;
318         
319         struct  _input_signal_events    input_signal_events;
320
321         /* SPPP/Cisco HDLC device parts */
322         int netcount;
323         int dosyncppp;
324         spinlock_t netlock;
325 #ifdef CONFIG_SYNCLINK_SYNCPPP
326         struct ppp_device pppdev;
327         char netname[10];
328         struct net_device *netdev;
329         struct net_device_stats netstats;
330 #endif
331 };
332
333 #define MGSL_MAGIC 0x5401
334
335 /*
336  * The size of the serial xmit buffer is 1 page, or 4096 bytes
337  */
338 #ifndef SERIAL_XMIT_SIZE
339 #define SERIAL_XMIT_SIZE 4096
340 #endif
341
342 /*
343  * These macros define the offsets used in calculating the
344  * I/O address of the specified USC registers.
345  */
346
347
348 #define DCPIN 2         /* Bit 1 of I/O address */
349 #define SDPIN 4         /* Bit 2 of I/O address */
350
351 #define DCAR 0          /* DMA command/address register */
352 #define CCAR SDPIN              /* channel command/address register */
353 #define DATAREG DCPIN + SDPIN   /* serial data register */
354 #define MSBONLY 0x41
355 #define LSBONLY 0x40
356
357 /*
358  * These macros define the register address (ordinal number)
359  * used for writing address/value pairs to the USC.
360  */
361
362 #define CMR     0x02    /* Channel mode Register */
363 #define CCSR    0x04    /* Channel Command/status Register */
364 #define CCR     0x06    /* Channel Control Register */
365 #define PSR     0x08    /* Port status Register */
366 #define PCR     0x0a    /* Port Control Register */
367 #define TMDR    0x0c    /* Test mode Data Register */
368 #define TMCR    0x0e    /* Test mode Control Register */
369 #define CMCR    0x10    /* Clock mode Control Register */
370 #define HCR     0x12    /* Hardware Configuration Register */
371 #define IVR     0x14    /* Interrupt Vector Register */
372 #define IOCR    0x16    /* Input/Output Control Register */
373 #define ICR     0x18    /* Interrupt Control Register */
374 #define DCCR    0x1a    /* Daisy Chain Control Register */
375 #define MISR    0x1c    /* Misc Interrupt status Register */
376 #define SICR    0x1e    /* status Interrupt Control Register */
377 #define RDR     0x20    /* Receive Data Register */
378 #define RMR     0x22    /* Receive mode Register */
379 #define RCSR    0x24    /* Receive Command/status Register */
380 #define RICR    0x26    /* Receive Interrupt Control Register */
381 #define RSR     0x28    /* Receive Sync Register */
382 #define RCLR    0x2a    /* Receive count Limit Register */
383 #define RCCR    0x2c    /* Receive Character count Register */
384 #define TC0R    0x2e    /* Time Constant 0 Register */
385 #define TDR     0x30    /* Transmit Data Register */
386 #define TMR     0x32    /* Transmit mode Register */
387 #define TCSR    0x34    /* Transmit Command/status Register */
388 #define TICR    0x36    /* Transmit Interrupt Control Register */
389 #define TSR     0x38    /* Transmit Sync Register */
390 #define TCLR    0x3a    /* Transmit count Limit Register */
391 #define TCCR    0x3c    /* Transmit Character count Register */
392 #define TC1R    0x3e    /* Time Constant 1 Register */
393
394
395 /*
396  * MACRO DEFINITIONS FOR DMA REGISTERS
397  */
398
399 #define DCR     0x06    /* DMA Control Register (shared) */
400 #define DACR    0x08    /* DMA Array count Register (shared) */
401 #define BDCR    0x12    /* Burst/Dwell Control Register (shared) */
402 #define DIVR    0x14    /* DMA Interrupt Vector Register (shared) */    
403 #define DICR    0x18    /* DMA Interrupt Control Register (shared) */
404 #define CDIR    0x1a    /* Clear DMA Interrupt Register (shared) */
405 #define SDIR    0x1c    /* Set DMA Interrupt Register (shared) */
406
407 #define TDMR    0x02    /* Transmit DMA mode Register */
408 #define TDIAR   0x1e    /* Transmit DMA Interrupt Arm Register */
409 #define TBCR    0x2a    /* Transmit Byte count Register */
410 #define TARL    0x2c    /* Transmit Address Register (low) */
411 #define TARU    0x2e    /* Transmit Address Register (high) */
412 #define NTBCR   0x3a    /* Next Transmit Byte count Register */
413 #define NTARL   0x3c    /* Next Transmit Address Register (low) */
414 #define NTARU   0x3e    /* Next Transmit Address Register (high) */
415
416 #define RDMR    0x82    /* Receive DMA mode Register (non-shared) */
417 #define RDIAR   0x9e    /* Receive DMA Interrupt Arm Register */
418 #define RBCR    0xaa    /* Receive Byte count Register */
419 #define RARL    0xac    /* Receive Address Register (low) */
420 #define RARU    0xae    /* Receive Address Register (high) */
421 #define NRBCR   0xba    /* Next Receive Byte count Register */
422 #define NRARL   0xbc    /* Next Receive Address Register (low) */
423 #define NRARU   0xbe    /* Next Receive Address Register (high) */
424
425
426 /*
427  * MACRO DEFINITIONS FOR MODEM STATUS BITS
428  */
429
430 #define MODEMSTATUS_DTR 0x80
431 #define MODEMSTATUS_DSR 0x40
432 #define MODEMSTATUS_RTS 0x20
433 #define MODEMSTATUS_CTS 0x10
434 #define MODEMSTATUS_RI  0x04
435 #define MODEMSTATUS_DCD 0x01
436
437
438 /*
439  * Channel Command/Address Register (CCAR) Command Codes
440  */
441
442 #define RTCmd_Null                      0x0000
443 #define RTCmd_ResetHighestIus           0x1000
444 #define RTCmd_TriggerChannelLoadDma     0x2000
445 #define RTCmd_TriggerRxDma              0x2800
446 #define RTCmd_TriggerTxDma              0x3000
447 #define RTCmd_TriggerRxAndTxDma         0x3800
448 #define RTCmd_PurgeRxFifo               0x4800
449 #define RTCmd_PurgeTxFifo               0x5000
450 #define RTCmd_PurgeRxAndTxFifo          0x5800
451 #define RTCmd_LoadRcc                   0x6800
452 #define RTCmd_LoadTcc                   0x7000
453 #define RTCmd_LoadRccAndTcc             0x7800
454 #define RTCmd_LoadTC0                   0x8800
455 #define RTCmd_LoadTC1                   0x9000
456 #define RTCmd_LoadTC0AndTC1             0x9800
457 #define RTCmd_SerialDataLSBFirst        0xa000
458 #define RTCmd_SerialDataMSBFirst        0xa800
459 #define RTCmd_SelectBigEndian           0xb000
460 #define RTCmd_SelectLittleEndian        0xb800
461
462
463 /*
464  * DMA Command/Address Register (DCAR) Command Codes
465  */
466
467 #define DmaCmd_Null                     0x0000
468 #define DmaCmd_ResetTxChannel           0x1000
469 #define DmaCmd_ResetRxChannel           0x1200
470 #define DmaCmd_StartTxChannel           0x2000
471 #define DmaCmd_StartRxChannel           0x2200
472 #define DmaCmd_ContinueTxChannel        0x3000
473 #define DmaCmd_ContinueRxChannel        0x3200
474 #define DmaCmd_PauseTxChannel           0x4000
475 #define DmaCmd_PauseRxChannel           0x4200
476 #define DmaCmd_AbortTxChannel           0x5000
477 #define DmaCmd_AbortRxChannel           0x5200
478 #define DmaCmd_InitTxChannel            0x7000
479 #define DmaCmd_InitRxChannel            0x7200
480 #define DmaCmd_ResetHighestDmaIus       0x8000
481 #define DmaCmd_ResetAllChannels         0x9000
482 #define DmaCmd_StartAllChannels         0xa000
483 #define DmaCmd_ContinueAllChannels      0xb000
484 #define DmaCmd_PauseAllChannels         0xc000
485 #define DmaCmd_AbortAllChannels         0xd000
486 #define DmaCmd_InitAllChannels          0xf000
487
488 #define TCmd_Null                       0x0000
489 #define TCmd_ClearTxCRC                 0x2000
490 #define TCmd_SelectTicrTtsaData         0x4000
491 #define TCmd_SelectTicrTxFifostatus     0x5000
492 #define TCmd_SelectTicrIntLevel         0x6000
493 #define TCmd_SelectTicrdma_level                0x7000
494 #define TCmd_SendFrame                  0x8000
495 #define TCmd_SendAbort                  0x9000
496 #define TCmd_EnableDleInsertion         0xc000
497 #define TCmd_DisableDleInsertion        0xd000
498 #define TCmd_ClearEofEom                0xe000
499 #define TCmd_SetEofEom                  0xf000
500
501 #define RCmd_Null                       0x0000
502 #define RCmd_ClearRxCRC                 0x2000
503 #define RCmd_EnterHuntmode              0x3000
504 #define RCmd_SelectRicrRtsaData         0x4000
505 #define RCmd_SelectRicrRxFifostatus     0x5000
506 #define RCmd_SelectRicrIntLevel         0x6000
507 #define RCmd_SelectRicrdma_level                0x7000
508
509 /*
510  * Bits for enabling and disabling IRQs in Interrupt Control Register (ICR)
511  */
512  
513 #define RECEIVE_STATUS          BIT5
514 #define RECEIVE_DATA            BIT4
515 #define TRANSMIT_STATUS         BIT3
516 #define TRANSMIT_DATA           BIT2
517 #define IO_PIN                  BIT1
518 #define MISC                    BIT0
519
520
521 /*
522  * Receive status Bits in Receive Command/status Register RCSR
523  */
524
525 #define RXSTATUS_SHORT_FRAME            BIT8
526 #define RXSTATUS_CODE_VIOLATION         BIT8
527 #define RXSTATUS_EXITED_HUNT            BIT7
528 #define RXSTATUS_IDLE_RECEIVED          BIT6
529 #define RXSTATUS_BREAK_RECEIVED         BIT5
530 #define RXSTATUS_ABORT_RECEIVED         BIT5
531 #define RXSTATUS_RXBOUND                BIT4
532 #define RXSTATUS_CRC_ERROR              BIT3
533 #define RXSTATUS_FRAMING_ERROR          BIT3
534 #define RXSTATUS_ABORT                  BIT2
535 #define RXSTATUS_PARITY_ERROR           BIT2
536 #define RXSTATUS_OVERRUN                BIT1
537 #define RXSTATUS_DATA_AVAILABLE         BIT0
538 #define RXSTATUS_ALL                    0x01f6
539 #define usc_UnlatchRxstatusBits(a,b) usc_OutReg( (a), RCSR, (u16)((b) & RXSTATUS_ALL) )
540
541 /*
542  * Values for setting transmit idle mode in 
543  * Transmit Control/status Register (TCSR)
544  */
545 #define IDLEMODE_FLAGS                  0x0000
546 #define IDLEMODE_ALT_ONE_ZERO           0x0100
547 #define IDLEMODE_ZERO                   0x0200
548 #define IDLEMODE_ONE                    0x0300
549 #define IDLEMODE_ALT_MARK_SPACE         0x0500
550 #define IDLEMODE_SPACE                  0x0600
551 #define IDLEMODE_MARK                   0x0700
552 #define IDLEMODE_MASK                   0x0700
553
554 /*
555  * IUSC revision identifiers
556  */
557 #define IUSC_SL1660                     0x4d44
558 #define IUSC_PRE_SL1660                 0x4553
559
560 /*
561  * Transmit status Bits in Transmit Command/status Register (TCSR)
562  */
563
564 #define TCSR_PRESERVE                   0x0F00
565
566 #define TCSR_UNDERWAIT                  BIT11
567 #define TXSTATUS_PREAMBLE_SENT          BIT7
568 #define TXSTATUS_IDLE_SENT              BIT6
569 #define TXSTATUS_ABORT_SENT             BIT5
570 #define TXSTATUS_EOF_SENT               BIT4
571 #define TXSTATUS_EOM_SENT               BIT4
572 #define TXSTATUS_CRC_SENT               BIT3
573 #define TXSTATUS_ALL_SENT               BIT2
574 #define TXSTATUS_UNDERRUN               BIT1
575 #define TXSTATUS_FIFO_EMPTY             BIT0
576 #define TXSTATUS_ALL                    0x00fa
577 #define usc_UnlatchTxstatusBits(a,b) usc_OutReg( (a), TCSR, (u16)((a)->tcsr_value + ((b) & 0x00FF)) )
578                                 
579
580 #define MISCSTATUS_RXC_LATCHED          BIT15
581 #define MISCSTATUS_RXC                  BIT14
582 #define MISCSTATUS_TXC_LATCHED          BIT13
583 #define MISCSTATUS_TXC                  BIT12
584 #define MISCSTATUS_RI_LATCHED           BIT11
585 #define MISCSTATUS_RI                   BIT10
586 #define MISCSTATUS_DSR_LATCHED          BIT9
587 #define MISCSTATUS_DSR                  BIT8
588 #define MISCSTATUS_DCD_LATCHED          BIT7
589 #define MISCSTATUS_DCD                  BIT6
590 #define MISCSTATUS_CTS_LATCHED          BIT5
591 #define MISCSTATUS_CTS                  BIT4
592 #define MISCSTATUS_RCC_UNDERRUN         BIT3
593 #define MISCSTATUS_DPLL_NO_SYNC         BIT2
594 #define MISCSTATUS_BRG1_ZERO            BIT1
595 #define MISCSTATUS_BRG0_ZERO            BIT0
596
597 #define usc_UnlatchIostatusBits(a,b) usc_OutReg((a),MISR,(u16)((b) & 0xaaa0))
598 #define usc_UnlatchMiscstatusBits(a,b) usc_OutReg((a),MISR,(u16)((b) & 0x000f))
599
600 #define SICR_RXC_ACTIVE                 BIT15
601 #define SICR_RXC_INACTIVE               BIT14
602 #define SICR_RXC                        (BIT15+BIT14)
603 #define SICR_TXC_ACTIVE                 BIT13
604 #define SICR_TXC_INACTIVE               BIT12
605 #define SICR_TXC                        (BIT13+BIT12)
606 #define SICR_RI_ACTIVE                  BIT11
607 #define SICR_RI_INACTIVE                BIT10
608 #define SICR_RI                         (BIT11+BIT10)
609 #define SICR_DSR_ACTIVE                 BIT9
610 #define SICR_DSR_INACTIVE               BIT8
611 #define SICR_DSR                        (BIT9+BIT8)
612 #define SICR_DCD_ACTIVE                 BIT7
613 #define SICR_DCD_INACTIVE               BIT6
614 #define SICR_DCD                        (BIT7+BIT6)
615 #define SICR_CTS_ACTIVE                 BIT5
616 #define SICR_CTS_INACTIVE               BIT4
617 #define SICR_CTS                        (BIT5+BIT4)
618 #define SICR_RCC_UNDERFLOW              BIT3
619 #define SICR_DPLL_NO_SYNC               BIT2
620 #define SICR_BRG1_ZERO                  BIT1
621 #define SICR_BRG0_ZERO                  BIT0
622
623 void usc_DisableMasterIrqBit( struct mgsl_struct *info );
624 void usc_EnableMasterIrqBit( struct mgsl_struct *info );
625 void usc_EnableInterrupts( struct mgsl_struct *info, u16 IrqMask );
626 void usc_DisableInterrupts( struct mgsl_struct *info, u16 IrqMask );
627 void usc_ClearIrqPendingBits( struct mgsl_struct *info, u16 IrqMask );
628
629 #define usc_EnableInterrupts( a, b ) \
630         usc_OutReg( (a), ICR, (u16)((usc_InReg((a),ICR) & 0xff00) + 0xc0 + (b)) )
631
632 #define usc_DisableInterrupts( a, b ) \
633         usc_OutReg( (a), ICR, (u16)((usc_InReg((a),ICR) & 0xff00) + 0x80 + (b)) )
634
635 #define usc_EnableMasterIrqBit(a) \
636         usc_OutReg( (a), ICR, (u16)((usc_InReg((a),ICR) & 0x0f00) + 0xb000) )
637
638 #define usc_DisableMasterIrqBit(a) \
639         usc_OutReg( (a), ICR, (u16)(usc_InReg((a),ICR) & 0x7f00) )
640
641 #define usc_ClearIrqPendingBits( a, b ) usc_OutReg( (a), DCCR, 0x40 + (b) )
642
643 /*
644  * Transmit status Bits in Transmit Control status Register (TCSR)
645  * and Transmit Interrupt Control Register (TICR) (except BIT2, BIT0)
646  */
647
648 #define TXSTATUS_PREAMBLE_SENT  BIT7
649 #define TXSTATUS_IDLE_SENT      BIT6
650 #define TXSTATUS_ABORT_SENT     BIT5
651 #define TXSTATUS_EOF            BIT4
652 #define TXSTATUS_CRC_SENT       BIT3
653 #define TXSTATUS_ALL_SENT       BIT2
654 #define TXSTATUS_UNDERRUN       BIT1
655 #define TXSTATUS_FIFO_EMPTY     BIT0
656
657 #define DICR_MASTER             BIT15
658 #define DICR_TRANSMIT           BIT0
659 #define DICR_RECEIVE            BIT1
660
661 #define usc_EnableDmaInterrupts(a,b) \
662         usc_OutDmaReg( (a), DICR, (u16)(usc_InDmaReg((a),DICR) | (b)) )
663
664 #define usc_DisableDmaInterrupts(a,b) \
665         usc_OutDmaReg( (a), DICR, (u16)(usc_InDmaReg((a),DICR) & ~(b)) )
666
667 #define usc_EnableStatusIrqs(a,b) \
668         usc_OutReg( (a), SICR, (u16)(usc_InReg((a),SICR) | (b)) )
669
670 #define usc_DisablestatusIrqs(a,b) \
671         usc_OutReg( (a), SICR, (u16)(usc_InReg((a),SICR) & ~(b)) )
672
673 /* Transmit status Bits in Transmit Control status Register (TCSR) */
674 /* and Transmit Interrupt Control Register (TICR) (except BIT2, BIT0) */
675
676
677 #define DISABLE_UNCONDITIONAL    0
678 #define DISABLE_END_OF_FRAME     1
679 #define ENABLE_UNCONDITIONAL     2
680 #define ENABLE_AUTO_CTS          3
681 #define ENABLE_AUTO_DCD          3
682 #define usc_EnableTransmitter(a,b) \
683         usc_OutReg( (a), TMR, (u16)((usc_InReg((a),TMR) & 0xfffc) | (b)) )
684 #define usc_EnableReceiver(a,b) \
685         usc_OutReg( (a), RMR, (u16)((usc_InReg((a),RMR) & 0xfffc) | (b)) )
686
687 u16  usc_InDmaReg( struct mgsl_struct *info, u16 Port );
688 void usc_OutDmaReg( struct mgsl_struct *info, u16 Port, u16 Value );
689 void usc_DmaCmd( struct mgsl_struct *info, u16 Cmd );
690
691 u16  usc_InReg( struct mgsl_struct *info, u16 Port );
692 void usc_OutReg( struct mgsl_struct *info, u16 Port, u16 Value );
693 void usc_RTCmd( struct mgsl_struct *info, u16 Cmd );
694 void usc_RCmd( struct mgsl_struct *info, u16 Cmd );
695 void usc_TCmd( struct mgsl_struct *info, u16 Cmd );
696
697 #define usc_TCmd(a,b) usc_OutReg((a), TCSR, (u16)((a)->tcsr_value + (b)))
698 #define usc_RCmd(a,b) usc_OutReg((a), RCSR, (b))
699
700 #define usc_SetTransmitSyncChars(a,s0,s1) usc_OutReg((a), TSR, (u16)(((u16)s0<<8)|(u16)s1))
701
702 void usc_process_rxoverrun_sync( struct mgsl_struct *info );
703 void usc_start_receiver( struct mgsl_struct *info );
704 void usc_stop_receiver( struct mgsl_struct *info );
705
706 void usc_start_transmitter( struct mgsl_struct *info );
707 void usc_stop_transmitter( struct mgsl_struct *info );
708 void usc_set_txidle( struct mgsl_struct *info );
709 void usc_load_txfifo( struct mgsl_struct *info );
710
711 void usc_enable_aux_clock( struct mgsl_struct *info, u32 DataRate );
712 void usc_enable_loopback( struct mgsl_struct *info, int enable );
713
714 void usc_get_serial_signals( struct mgsl_struct *info );
715 void usc_set_serial_signals( struct mgsl_struct *info );
716
717 void usc_reset( struct mgsl_struct *info );
718
719 void usc_set_sync_mode( struct mgsl_struct *info );
720 void usc_set_sdlc_mode( struct mgsl_struct *info );
721 void usc_set_async_mode( struct mgsl_struct *info );
722 void usc_enable_async_clock( struct mgsl_struct *info, u32 DataRate );
723
724 void usc_loopback_frame( struct mgsl_struct *info );
725
726 void mgsl_tx_timeout(unsigned long context);
727
728
729 void usc_loopmode_cancel_transmit( struct mgsl_struct * info );
730 void usc_loopmode_insert_request( struct mgsl_struct * info );
731 int usc_loopmode_active( struct mgsl_struct * info);
732 void usc_loopmode_send_done( struct mgsl_struct * info );
733 int usc_loopmode_send_active( struct mgsl_struct * info );
734
735 int mgsl_ioctl_common(struct mgsl_struct *info, unsigned int cmd, unsigned long arg);
736
737 #ifdef CONFIG_SYNCLINK_SYNCPPP
738 /* SPPP/HDLC stuff */
739 static void mgsl_sppp_init(struct mgsl_struct *info);
740 static void mgsl_sppp_delete(struct mgsl_struct *info);
741 int mgsl_sppp_open(struct net_device *d);
742 int mgsl_sppp_close(struct net_device *d);
743 void mgsl_sppp_tx_timeout(struct net_device *d);
744 int mgsl_sppp_tx(struct sk_buff *skb, struct net_device *d);
745 void mgsl_sppp_rx_done(struct mgsl_struct *info, char *buf, int size);
746 void mgsl_sppp_tx_done(struct mgsl_struct *info);
747 int mgsl_sppp_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd);
748 struct net_device_stats *mgsl_net_stats(struct net_device *dev);
749 #endif
750
751 /*
752  * Defines a BUS descriptor value for the PCI adapter
753  * local bus address ranges.
754  */
755
756 #define BUS_DESCRIPTOR( WrHold, WrDly, RdDly, Nwdd, Nwad, Nxda, Nrdd, Nrad ) \
757 (0x00400020 + \
758 ((WrHold) << 30) + \
759 ((WrDly)  << 28) + \
760 ((RdDly)  << 26) + \
761 ((Nwdd)   << 20) + \
762 ((Nwad)   << 15) + \
763 ((Nxda)   << 13) + \
764 ((Nrdd)   << 11) + \
765 ((Nrad)   <<  6) )
766
767 void mgsl_trace_block(struct mgsl_struct *info,const char* data, int count, int xmit);
768
769 /*
770  * Adapter diagnostic routines
771  */
772 BOOLEAN mgsl_register_test( struct mgsl_struct *info );
773 BOOLEAN mgsl_irq_test( struct mgsl_struct *info );
774 BOOLEAN mgsl_dma_test( struct mgsl_struct *info );
775 BOOLEAN mgsl_memory_test( struct mgsl_struct *info );
776 int mgsl_adapter_test( struct mgsl_struct *info );
777
778 /*
779  * device and resource management routines
780  */
781 int mgsl_claim_resources(struct mgsl_struct *info);
782 void mgsl_release_resources(struct mgsl_struct *info);
783 void mgsl_add_device(struct mgsl_struct *info);
784 struct mgsl_struct* mgsl_allocate_device(void);
785 int mgsl_enum_isa_devices(void);
786
787 /*
788  * DMA buffer manupulation functions.
789  */
790 void mgsl_free_rx_frame_buffers( struct mgsl_struct *info, unsigned int StartIndex, unsigned int EndIndex );
791 int  mgsl_get_rx_frame( struct mgsl_struct *info );
792 int  mgsl_get_raw_rx_frame( struct mgsl_struct *info );
793 void mgsl_reset_rx_dma_buffers( struct mgsl_struct *info );
794 void mgsl_reset_tx_dma_buffers( struct mgsl_struct *info );
795 int num_free_tx_dma_buffers(struct mgsl_struct *info);
796 void mgsl_load_tx_dma_buffer( struct mgsl_struct *info, const char *Buffer, unsigned int BufferSize);
797 void mgsl_load_pci_memory(char* TargetPtr, const char* SourcePtr, unsigned short count);
798
799 /*
800  * DMA and Shared Memory buffer allocation and formatting
801  */
802 int  mgsl_allocate_dma_buffers(struct mgsl_struct *info);
803 void mgsl_free_dma_buffers(struct mgsl_struct *info);
804 int  mgsl_alloc_frame_memory(struct mgsl_struct *info, DMABUFFERENTRY *BufferList,int Buffercount);
805 void mgsl_free_frame_memory(struct mgsl_struct *info, DMABUFFERENTRY *BufferList,int Buffercount);
806 int  mgsl_alloc_buffer_list_memory(struct mgsl_struct *info);
807 void mgsl_free_buffer_list_memory(struct mgsl_struct *info);
808 int mgsl_alloc_intermediate_rxbuffer_memory(struct mgsl_struct *info);
809 void mgsl_free_intermediate_rxbuffer_memory(struct mgsl_struct *info);
810 int mgsl_alloc_intermediate_txbuffer_memory(struct mgsl_struct *info);
811 void mgsl_free_intermediate_txbuffer_memory(struct mgsl_struct *info);
812 int load_next_tx_holding_buffer(struct mgsl_struct *info);
813 int save_tx_buffer_request(struct mgsl_struct *info,const char *Buffer, unsigned int BufferSize);
814
815 /*
816  * Bottom half interrupt handlers
817  */
818 void mgsl_bh_handler(void* Context);
819 void mgsl_bh_receive(struct mgsl_struct *info);
820 void mgsl_bh_transmit(struct mgsl_struct *info);
821 void mgsl_bh_status(struct mgsl_struct *info);
822
823 /*
824  * Interrupt handler routines and dispatch table.
825  */
826 void mgsl_isr_null( struct mgsl_struct *info );
827 void mgsl_isr_transmit_data( struct mgsl_struct *info );
828 void mgsl_isr_receive_data( struct mgsl_struct *info );
829 void mgsl_isr_receive_status( struct mgsl_struct *info );
830 void mgsl_isr_transmit_status( struct mgsl_struct *info );
831 void mgsl_isr_io_pin( struct mgsl_struct *info );
832 void mgsl_isr_misc( struct mgsl_struct *info );
833 void mgsl_isr_receive_dma( struct mgsl_struct *info );
834 void mgsl_isr_transmit_dma( struct mgsl_struct *info );
835
836 typedef void (*isr_dispatch_func)(struct mgsl_struct *);
837
838 isr_dispatch_func UscIsrTable[7] =
839 {
840         mgsl_isr_null,
841         mgsl_isr_misc,
842         mgsl_isr_io_pin,
843         mgsl_isr_transmit_data,
844         mgsl_isr_transmit_status,
845         mgsl_isr_receive_data,
846         mgsl_isr_receive_status
847 };
848
849 /*
850  * ioctl call handlers
851  */
852 static int tiocmget(struct tty_struct *tty, struct file *file);
853 static int tiocmset(struct tty_struct *tty, struct file *file,
854                     unsigned int set, unsigned int clear);
855 static int mgsl_get_stats(struct mgsl_struct * info, struct mgsl_icount
856         *user_icount);
857 static int mgsl_get_params(struct mgsl_struct * info, MGSL_PARAMS *user_params);
858 static int mgsl_set_params(struct mgsl_struct * info, MGSL_PARAMS *new_params);
859 static int mgsl_get_txidle(struct mgsl_struct * info, int*idle_mode);
860 static int mgsl_set_txidle(struct mgsl_struct * info, int idle_mode);
861 static int mgsl_txenable(struct mgsl_struct * info, int enable);
862 static int mgsl_txabort(struct mgsl_struct * info);
863 static int mgsl_rxenable(struct mgsl_struct * info, int enable);
864 static int mgsl_wait_event(struct mgsl_struct * info, int * mask);
865 static int mgsl_loopmode_send_done( struct mgsl_struct * info );
866
867 #define jiffies_from_ms(a) ((((a) * HZ)/1000)+1)
868
869 /*
870  * Global linked list of SyncLink devices
871  */
872 struct mgsl_struct *mgsl_device_list;
873 static int mgsl_device_count;
874
875 /*
876  * Set this param to non-zero to load eax with the
877  * .text section address and breakpoint on module load.
878  * This is useful for use with gdb and add-symbol-file command.
879  */
880 static int break_on_load;
881
882 /*
883  * Driver major number, defaults to zero to get auto
884  * assigned major number. May be forced as module parameter.
885  */
886 static int ttymajor;
887
888 /*
889  * Array of user specified options for ISA adapters.
890  */
891 static int io[MAX_ISA_DEVICES];
892 static int irq[MAX_ISA_DEVICES];
893 static int dma[MAX_ISA_DEVICES];
894 static int debug_level;
895 static int maxframe[MAX_TOTAL_DEVICES];
896 static int dosyncppp[MAX_TOTAL_DEVICES];
897 static int txdmabufs[MAX_TOTAL_DEVICES];
898 static int txholdbufs[MAX_TOTAL_DEVICES];
899         
900 MODULE_PARM(break_on_load,"i");
901 MODULE_PARM(ttymajor,"i");
902 MODULE_PARM(io,"1-" __MODULE_STRING(MAX_ISA_DEVICES) "i");
903 MODULE_PARM(irq,"1-" __MODULE_STRING(MAX_ISA_DEVICES) "i");
904 MODULE_PARM(dma,"1-" __MODULE_STRING(MAX_ISA_DEVICES) "i");
905 MODULE_PARM(debug_level,"i");
906 MODULE_PARM(maxframe,"1-" __MODULE_STRING(MAX_TOTAL_DEVICES) "i");
907 MODULE_PARM(dosyncppp,"1-" __MODULE_STRING(MAX_TOTAL_DEVICES) "i");
908 MODULE_PARM(txdmabufs,"1-" __MODULE_STRING(MAX_TOTAL_DEVICES) "i");
909 MODULE_PARM(txholdbufs,"1-" __MODULE_STRING(MAX_TOTAL_DEVICES) "i");
910
911 static char *driver_name = "SyncLink serial driver";
912 static char *driver_version = "$Revision: 4.21 $";
913
914 static int synclink_init_one (struct pci_dev *dev,
915                                      const struct pci_device_id *ent);
916 static void synclink_remove_one (struct pci_dev *dev);
917
918 static struct pci_device_id synclink_pci_tbl[] = {
919         { PCI_VENDOR_ID_MICROGATE, PCI_DEVICE_ID_MICROGATE_USC, PCI_ANY_ID, PCI_ANY_ID, },
920         { PCI_VENDOR_ID_MICROGATE, 0x0210, PCI_ANY_ID, PCI_ANY_ID, },
921         { 0, }, /* terminate list */
922 };
923 MODULE_DEVICE_TABLE(pci, synclink_pci_tbl);
924
925 MODULE_LICENSE("GPL");
926
927 static struct pci_driver synclink_pci_driver = {
928         .name           = "synclink",
929         .id_table       = synclink_pci_tbl,
930         .probe          = synclink_init_one,
931         .remove         = __devexit_p(synclink_remove_one),
932 };
933
934 static struct tty_driver *serial_driver;
935
936 /* number of characters left in xmit buffer before we ask for more */
937 #define WAKEUP_CHARS 256
938
939
940 static void mgsl_change_params(struct mgsl_struct *info);
941 static void mgsl_wait_until_sent(struct tty_struct *tty, int timeout);
942
943 #ifndef MIN
944 #define MIN(a,b)        ((a) < (b) ? (a) : (b))
945 #endif
946
947 /*
948  * 1st function defined in .text section. Calling this function in
949  * init_module() followed by a breakpoint allows a remote debugger
950  * (gdb) to get the .text address for the add-symbol-file command.
951  * This allows remote debugging of dynamically loadable modules.
952  */
953 void* mgsl_get_text_ptr(void);
954 void* mgsl_get_text_ptr() {return mgsl_get_text_ptr;}
955
956 /*
957  * tmp_buf is used as a temporary buffer by mgsl_write.  We need to
958  * lock it in case the COPY_FROM_USER blocks while swapping in a page,
959  * and some other program tries to do a serial write at the same time.
960  * Since the lock will only come under contention when the system is
961  * swapping and available memory is low, it makes sense to share one
962  * buffer across all the serial ioports, since it significantly saves
963  * memory if large numbers of serial ports are open.
964  */
965 static unsigned char *tmp_buf;
966 static DECLARE_MUTEX(tmp_buf_sem);
967
968 static inline int mgsl_paranoia_check(struct mgsl_struct *info,
969                                         char *name, const char *routine)
970 {
971 #ifdef MGSL_PARANOIA_CHECK
972         static const char *badmagic =
973                 "Warning: bad magic number for mgsl struct (%s) in %s\n";
974         static const char *badinfo =
975                 "Warning: null mgsl_struct for (%s) in %s\n";
976
977         if (!info) {
978                 printk(badinfo, name, routine);
979                 return 1;
980         }
981         if (info->magic != MGSL_MAGIC) {
982                 printk(badmagic, name, routine);
983                 return 1;
984         }
985 #else
986         if (!info)
987                 return 1;
988 #endif
989         return 0;
990 }
991
992 /* mgsl_stop()          throttle (stop) transmitter
993  *      
994  * Arguments:           tty     pointer to tty info structure
995  * Return Value:        None
996  */
997 static void mgsl_stop(struct tty_struct *tty)
998 {
999         struct mgsl_struct *info = (struct mgsl_struct *)tty->driver_data;
1000         unsigned long flags;
1001         
1002         if (mgsl_paranoia_check(info, tty->name, "mgsl_stop"))
1003                 return;
1004         
1005         if ( debug_level >= DEBUG_LEVEL_INFO )
1006                 printk("mgsl_stop(%s)\n",info->device_name);    
1007                 
1008         spin_lock_irqsave(&info->irq_spinlock,flags);
1009         if (info->tx_enabled)
1010                 usc_stop_transmitter(info);
1011         spin_unlock_irqrestore(&info->irq_spinlock,flags);
1012         
1013 }       /* end of mgsl_stop() */
1014
1015 /* mgsl_start()         release (start) transmitter
1016  *      
1017  * Arguments:           tty     pointer to tty info structure
1018  * Return Value:        None
1019  */
1020 static void mgsl_start(struct tty_struct *tty)
1021 {
1022         struct mgsl_struct *info = (struct mgsl_struct *)tty->driver_data;
1023         unsigned long flags;
1024         
1025         if (mgsl_paranoia_check(info, tty->name, "mgsl_start"))
1026                 return;
1027         
1028         if ( debug_level >= DEBUG_LEVEL_INFO )
1029                 printk("mgsl_start(%s)\n",info->device_name);   
1030                 
1031         spin_lock_irqsave(&info->irq_spinlock,flags);
1032         if (!info->tx_enabled)
1033                 usc_start_transmitter(info);
1034         spin_unlock_irqrestore(&info->irq_spinlock,flags);
1035         
1036 }       /* end of mgsl_start() */
1037
1038 /*
1039  * Bottom half work queue access functions
1040  */
1041
1042 /* mgsl_bh_action()     Return next bottom half action to perform.
1043  * Return Value:        BH action code or 0 if nothing to do.
1044  */
1045 int mgsl_bh_action(struct mgsl_struct *info)
1046 {
1047         unsigned long flags;
1048         int rc = 0;
1049         
1050         spin_lock_irqsave(&info->irq_spinlock,flags);
1051
1052         if (info->pending_bh & BH_RECEIVE) {
1053                 info->pending_bh &= ~BH_RECEIVE;
1054                 rc = BH_RECEIVE;
1055         } else if (info->pending_bh & BH_TRANSMIT) {
1056                 info->pending_bh &= ~BH_TRANSMIT;
1057                 rc = BH_TRANSMIT;
1058         } else if (info->pending_bh & BH_STATUS) {
1059                 info->pending_bh &= ~BH_STATUS;
1060                 rc = BH_STATUS;
1061         }
1062
1063         if (!rc) {
1064                 /* Mark BH routine as complete */
1065                 info->bh_running   = 0;
1066                 info->bh_requested = 0;
1067         }
1068         
1069         spin_unlock_irqrestore(&info->irq_spinlock,flags);
1070         
1071         return rc;
1072 }
1073
1074 /*
1075  *      Perform bottom half processing of work items queued by ISR.
1076  */
1077 void mgsl_bh_handler(void* Context)
1078 {
1079         struct mgsl_struct *info = (struct mgsl_struct*)Context;
1080         int action;
1081
1082         if (!info)
1083                 return;
1084                 
1085         if ( debug_level >= DEBUG_LEVEL_BH )
1086                 printk( "%s(%d):mgsl_bh_handler(%s) entry\n",
1087                         __FILE__,__LINE__,info->device_name);
1088         
1089         info->bh_running = 1;
1090
1091         while((action = mgsl_bh_action(info)) != 0) {
1092         
1093                 /* Process work item */
1094                 if ( debug_level >= DEBUG_LEVEL_BH )
1095                         printk( "%s(%d):mgsl_bh_handler() work item action=%d\n",
1096                                 __FILE__,__LINE__,action);
1097
1098                 switch (action) {
1099                 
1100                 case BH_RECEIVE:
1101                         mgsl_bh_receive(info);
1102                         break;
1103                 case BH_TRANSMIT:
1104                         mgsl_bh_transmit(info);
1105                         break;
1106                 case BH_STATUS:
1107                         mgsl_bh_status(info);
1108                         break;
1109                 default:
1110                         /* unknown work item ID */
1111                         printk("Unknown work item ID=%08X!\n", action);
1112                         break;
1113                 }
1114         }
1115
1116         if ( debug_level >= DEBUG_LEVEL_BH )
1117                 printk( "%s(%d):mgsl_bh_handler(%s) exit\n",
1118                         __FILE__,__LINE__,info->device_name);
1119 }
1120
1121 void mgsl_bh_receive(struct mgsl_struct *info)
1122 {
1123         int (*get_rx_frame)(struct mgsl_struct *info) =
1124                 (info->params.mode == MGSL_MODE_HDLC ? mgsl_get_rx_frame : mgsl_get_raw_rx_frame);
1125
1126         if ( debug_level >= DEBUG_LEVEL_BH )
1127                 printk( "%s(%d):mgsl_bh_receive(%s)\n",
1128                         __FILE__,__LINE__,info->device_name);
1129         
1130         do
1131         {
1132                 if (info->rx_rcc_underrun) {
1133                         unsigned long flags;
1134                         spin_lock_irqsave(&info->irq_spinlock,flags);
1135                         usc_start_receiver(info);
1136                         spin_unlock_irqrestore(&info->irq_spinlock,flags);
1137                         return;
1138                 }
1139         } while(get_rx_frame(info));
1140 }
1141
1142 void mgsl_bh_transmit(struct mgsl_struct *info)
1143 {
1144         struct tty_struct *tty = info->tty;
1145         unsigned long flags;
1146         
1147         if ( debug_level >= DEBUG_LEVEL_BH )
1148                 printk( "%s(%d):mgsl_bh_transmit() entry on %s\n",
1149                         __FILE__,__LINE__,info->device_name);
1150
1151         if (tty) {
1152                 if ((tty->flags & (1 << TTY_DO_WRITE_WAKEUP)) &&
1153                     tty->ldisc.write_wakeup) {
1154                         if ( debug_level >= DEBUG_LEVEL_BH )
1155                                 printk( "%s(%d):calling ldisc.write_wakeup on %s\n",
1156                                         __FILE__,__LINE__,info->device_name);
1157                         (tty->ldisc.write_wakeup)(tty);
1158                 }
1159                 wake_up_interruptible(&tty->write_wait);
1160         }
1161
1162         /* if transmitter idle and loopmode_send_done_requested
1163          * then start echoing RxD to TxD
1164          */
1165         spin_lock_irqsave(&info->irq_spinlock,flags);
1166         if ( !info->tx_active && info->loopmode_send_done_requested )
1167                 usc_loopmode_send_done( info );
1168         spin_unlock_irqrestore(&info->irq_spinlock,flags);
1169 }
1170
1171 void mgsl_bh_status(struct mgsl_struct *info)
1172 {
1173         if ( debug_level >= DEBUG_LEVEL_BH )
1174                 printk( "%s(%d):mgsl_bh_status() entry on %s\n",
1175                         __FILE__,__LINE__,info->device_name);
1176
1177         info->ri_chkcount = 0;
1178         info->dsr_chkcount = 0;
1179         info->dcd_chkcount = 0;
1180         info->cts_chkcount = 0;
1181 }
1182
1183 /* mgsl_isr_receive_status()
1184  * 
1185  *      Service a receive status interrupt. The type of status
1186  *      interrupt is indicated by the state of the RCSR.
1187  *      This is only used for HDLC mode.
1188  *
1189  * Arguments:           info    pointer to device instance data
1190  * Return Value:        None
1191  */
1192 void mgsl_isr_receive_status( struct mgsl_struct *info )
1193 {
1194         u16 status = usc_InReg( info, RCSR );
1195
1196         if ( debug_level >= DEBUG_LEVEL_ISR )   
1197                 printk("%s(%d):mgsl_isr_receive_status status=%04X\n",
1198                         __FILE__,__LINE__,status);
1199                         
1200         if ( (status & RXSTATUS_ABORT_RECEIVED) && 
1201                 info->loopmode_insert_requested &&
1202                 usc_loopmode_active(info) )
1203         {
1204                 ++info->icount.rxabort;
1205                 info->loopmode_insert_requested = FALSE;
1206  
1207                 /* clear CMR:13 to start echoing RxD to TxD */
1208                 info->cmr_value &= ~BIT13;
1209                 usc_OutReg(info, CMR, info->cmr_value);
1210  
1211                 /* disable received abort irq (no longer required) */
1212                 usc_OutReg(info, RICR,
1213                         (usc_InReg(info, RICR) & ~RXSTATUS_ABORT_RECEIVED));
1214         }
1215
1216         if (status & (RXSTATUS_EXITED_HUNT + RXSTATUS_IDLE_RECEIVED)) {
1217                 if (status & RXSTATUS_EXITED_HUNT)
1218                         info->icount.exithunt++;
1219                 if (status & RXSTATUS_IDLE_RECEIVED)
1220                         info->icount.rxidle++;
1221                 wake_up_interruptible(&info->event_wait_q);
1222         }
1223
1224         if (status & RXSTATUS_OVERRUN){
1225                 info->icount.rxover++;
1226                 usc_process_rxoverrun_sync( info );
1227         }
1228
1229         usc_ClearIrqPendingBits( info, RECEIVE_STATUS );
1230         usc_UnlatchRxstatusBits( info, status );
1231
1232 }       /* end of mgsl_isr_receive_status() */
1233
1234 /* mgsl_isr_transmit_status()
1235  * 
1236  *      Service a transmit status interrupt
1237  *      HDLC mode :end of transmit frame
1238  *      Async mode:all data is sent
1239  *      transmit status is indicated by bits in the TCSR.
1240  * 
1241  * Arguments:           info           pointer to device instance data
1242  * Return Value:        None
1243  */
1244 void mgsl_isr_transmit_status( struct mgsl_struct *info )
1245 {
1246         u16 status = usc_InReg( info, TCSR );
1247
1248         if ( debug_level >= DEBUG_LEVEL_ISR )   
1249                 printk("%s(%d):mgsl_isr_transmit_status status=%04X\n",
1250                         __FILE__,__LINE__,status);
1251         
1252         usc_ClearIrqPendingBits( info, TRANSMIT_STATUS );
1253         usc_UnlatchTxstatusBits( info, status );
1254         
1255         if ( status & (TXSTATUS_UNDERRUN | TXSTATUS_ABORT_SENT) )
1256         {
1257                 /* finished sending HDLC abort. This may leave  */
1258                 /* the TxFifo with data from the aborted frame  */
1259                 /* so purge the TxFifo. Also shutdown the DMA   */
1260                 /* channel in case there is data remaining in   */
1261                 /* the DMA buffer                               */
1262                 usc_DmaCmd( info, DmaCmd_ResetTxChannel );
1263                 usc_RTCmd( info, RTCmd_PurgeTxFifo );
1264         }
1265  
1266         if ( status & TXSTATUS_EOF_SENT )
1267                 info->icount.txok++;
1268         else if ( status & TXSTATUS_UNDERRUN )
1269                 info->icount.txunder++;
1270         else if ( status & TXSTATUS_ABORT_SENT )
1271                 info->icount.txabort++;
1272         else
1273                 info->icount.txunder++;
1274                         
1275         info->tx_active = 0;
1276         info->xmit_cnt = info->xmit_head = info->xmit_tail = 0;
1277         del_timer(&info->tx_timer);     
1278         
1279         if ( info->drop_rts_on_tx_done ) {
1280                 usc_get_serial_signals( info );
1281                 if ( info->serial_signals & SerialSignal_RTS ) {
1282                         info->serial_signals &= ~SerialSignal_RTS;
1283                         usc_set_serial_signals( info );
1284                 }
1285                 info->drop_rts_on_tx_done = 0;
1286         }
1287
1288 #ifdef CONFIG_SYNCLINK_SYNCPPP  
1289         if (info->netcount)
1290                 mgsl_sppp_tx_done(info);
1291         else 
1292 #endif
1293         {
1294                 if (info->tty->stopped || info->tty->hw_stopped) {
1295                         usc_stop_transmitter(info);
1296                         return;
1297                 }
1298                 info->pending_bh |= BH_TRANSMIT;
1299         }
1300
1301 }       /* end of mgsl_isr_transmit_status() */
1302
1303 /* mgsl_isr_io_pin()
1304  * 
1305  *      Service an Input/Output pin interrupt. The type of
1306  *      interrupt is indicated by bits in the MISR
1307  *      
1308  * Arguments:           info           pointer to device instance data
1309  * Return Value:        None
1310  */
1311 void mgsl_isr_io_pin( struct mgsl_struct *info )
1312 {
1313         struct  mgsl_icount *icount;
1314         u16 status = usc_InReg( info, MISR );
1315
1316         if ( debug_level >= DEBUG_LEVEL_ISR )   
1317                 printk("%s(%d):mgsl_isr_io_pin status=%04X\n",
1318                         __FILE__,__LINE__,status);
1319                         
1320         usc_ClearIrqPendingBits( info, IO_PIN );
1321         usc_UnlatchIostatusBits( info, status );
1322
1323         if (status & (MISCSTATUS_CTS_LATCHED | MISCSTATUS_DCD_LATCHED |
1324                       MISCSTATUS_DSR_LATCHED | MISCSTATUS_RI_LATCHED) ) {
1325                 icount = &info->icount;
1326                 /* update input line counters */
1327                 if (status & MISCSTATUS_RI_LATCHED) {
1328                         if ((info->ri_chkcount)++ >= IO_PIN_SHUTDOWN_LIMIT)
1329                                 usc_DisablestatusIrqs(info,SICR_RI);
1330                         icount->rng++;
1331                         if ( status & MISCSTATUS_RI )
1332                                 info->input_signal_events.ri_up++;      
1333                         else
1334                                 info->input_signal_events.ri_down++;    
1335                 }
1336                 if (status & MISCSTATUS_DSR_LATCHED) {
1337                         if ((info->dsr_chkcount)++ >= IO_PIN_SHUTDOWN_LIMIT)
1338                                 usc_DisablestatusIrqs(info,SICR_DSR);
1339                         icount->dsr++;
1340                         if ( status & MISCSTATUS_DSR )
1341                                 info->input_signal_events.dsr_up++;
1342                         else
1343                                 info->input_signal_events.dsr_down++;
1344                 }
1345                 if (status & MISCSTATUS_DCD_LATCHED) {
1346                         if ((info->dcd_chkcount)++ >= IO_PIN_SHUTDOWN_LIMIT)
1347                                 usc_DisablestatusIrqs(info,SICR_DCD);
1348                         icount->dcd++;
1349                         if (status & MISCSTATUS_DCD) {
1350                                 info->input_signal_events.dcd_up++;
1351 #ifdef CONFIG_SYNCLINK_SYNCPPP  
1352                                 if (info->netcount)
1353                                         sppp_reopen(info->netdev);
1354 #endif
1355                         } else
1356                                 info->input_signal_events.dcd_down++;
1357                 }
1358                 if (status & MISCSTATUS_CTS_LATCHED)
1359                 {
1360                         if ((info->cts_chkcount)++ >= IO_PIN_SHUTDOWN_LIMIT)
1361                                 usc_DisablestatusIrqs(info,SICR_CTS);
1362                         icount->cts++;
1363                         if ( status & MISCSTATUS_CTS )
1364                                 info->input_signal_events.cts_up++;
1365                         else
1366                                 info->input_signal_events.cts_down++;
1367                 }
1368                 wake_up_interruptible(&info->status_event_wait_q);
1369                 wake_up_interruptible(&info->event_wait_q);
1370
1371                 if ( (info->flags & ASYNC_CHECK_CD) && 
1372                      (status & MISCSTATUS_DCD_LATCHED) ) {
1373                         if ( debug_level >= DEBUG_LEVEL_ISR )
1374                                 printk("%s CD now %s...", info->device_name,
1375                                        (status & MISCSTATUS_DCD) ? "on" : "off");
1376                         if (status & MISCSTATUS_DCD)
1377                                 wake_up_interruptible(&info->open_wait);
1378                         else {
1379                                 if ( debug_level >= DEBUG_LEVEL_ISR )
1380                                         printk("doing serial hangup...");
1381                                 if (info->tty)
1382                                         tty_hangup(info->tty);
1383                         }
1384                 }
1385         
1386                 if ( (info->flags & ASYNC_CTS_FLOW) && 
1387                      (status & MISCSTATUS_CTS_LATCHED) ) {
1388                         if (info->tty->hw_stopped) {
1389                                 if (status & MISCSTATUS_CTS) {
1390                                         if ( debug_level >= DEBUG_LEVEL_ISR )
1391                                                 printk("CTS tx start...");
1392                                         if (info->tty)
1393                                                 info->tty->hw_stopped = 0;
1394                                         usc_start_transmitter(info);
1395                                         info->pending_bh |= BH_TRANSMIT;
1396                                         return;
1397                                 }
1398                         } else {
1399                                 if (!(status & MISCSTATUS_CTS)) {
1400                                         if ( debug_level >= DEBUG_LEVEL_ISR )
1401                                                 printk("CTS tx stop...");
1402                                         if (info->tty)
1403                                                 info->tty->hw_stopped = 1;
1404                                         usc_stop_transmitter(info);
1405                                 }
1406                         }
1407                 }
1408         }
1409
1410         info->pending_bh |= BH_STATUS;
1411         
1412         /* for diagnostics set IRQ flag */
1413         if ( status & MISCSTATUS_TXC_LATCHED ){
1414                 usc_OutReg( info, SICR,
1415                         (unsigned short)(usc_InReg(info,SICR) & ~(SICR_TXC_ACTIVE+SICR_TXC_INACTIVE)) );
1416                 usc_UnlatchIostatusBits( info, MISCSTATUS_TXC_LATCHED );
1417                 info->irq_occurred = 1;
1418         }
1419
1420 }       /* end of mgsl_isr_io_pin() */
1421
1422 /* mgsl_isr_transmit_data()
1423  * 
1424  *      Service a transmit data interrupt (async mode only).
1425  * 
1426  * Arguments:           info    pointer to device instance data
1427  * Return Value:        None
1428  */
1429 void mgsl_isr_transmit_data( struct mgsl_struct *info )
1430 {
1431         if ( debug_level >= DEBUG_LEVEL_ISR )   
1432                 printk("%s(%d):mgsl_isr_transmit_data xmit_cnt=%d\n",
1433                         __FILE__,__LINE__,info->xmit_cnt);
1434                         
1435         usc_ClearIrqPendingBits( info, TRANSMIT_DATA );
1436         
1437         if (info->tty->stopped || info->tty->hw_stopped) {
1438                 usc_stop_transmitter(info);
1439                 return;
1440         }
1441         
1442         if ( info->xmit_cnt )
1443                 usc_load_txfifo( info );
1444         else
1445                 info->tx_active = 0;
1446                 
1447         if (info->xmit_cnt < WAKEUP_CHARS)
1448                 info->pending_bh |= BH_TRANSMIT;
1449
1450 }       /* end of mgsl_isr_transmit_data() */
1451
1452 /* mgsl_isr_receive_data()
1453  * 
1454  *      Service a receive data interrupt. This occurs
1455  *      when operating in asynchronous interrupt transfer mode.
1456  *      The receive data FIFO is flushed to the receive data buffers. 
1457  * 
1458  * Arguments:           info            pointer to device instance data
1459  * Return Value:        None
1460  */
1461 void mgsl_isr_receive_data( struct mgsl_struct *info )
1462 {
1463         int Fifocount;
1464         u16 status;
1465         unsigned char DataByte;
1466         struct tty_struct *tty = info->tty;
1467         struct  mgsl_icount *icount = &info->icount;
1468         
1469         if ( debug_level >= DEBUG_LEVEL_ISR )   
1470                 printk("%s(%d):mgsl_isr_receive_data\n",
1471                         __FILE__,__LINE__);
1472
1473         usc_ClearIrqPendingBits( info, RECEIVE_DATA );
1474         
1475         /* select FIFO status for RICR readback */
1476         usc_RCmd( info, RCmd_SelectRicrRxFifostatus );
1477
1478         /* clear the Wordstatus bit so that status readback */
1479         /* only reflects the status of this byte */
1480         usc_OutReg( info, RICR+LSBONLY, (u16)(usc_InReg(info, RICR+LSBONLY) & ~BIT3 ));
1481
1482         /* flush the receive FIFO */
1483
1484         while( (Fifocount = (usc_InReg(info,RICR) >> 8)) ) {
1485                 /* read one byte from RxFIFO */
1486                 outw( (inw(info->io_base + CCAR) & 0x0780) | (RDR+LSBONLY),
1487                       info->io_base + CCAR );
1488                 DataByte = inb( info->io_base + CCAR );
1489
1490                 /* get the status of the received byte */
1491                 status = usc_InReg(info, RCSR);
1492                 if ( status & (RXSTATUS_FRAMING_ERROR + RXSTATUS_PARITY_ERROR +
1493                                 RXSTATUS_OVERRUN + RXSTATUS_BREAK_RECEIVED) )
1494                         usc_UnlatchRxstatusBits(info,RXSTATUS_ALL);
1495                 
1496                 if (tty->flip.count >= TTY_FLIPBUF_SIZE)
1497                         continue;
1498                         
1499                 *tty->flip.char_buf_ptr = DataByte;
1500                 icount->rx++;
1501                 
1502                 *tty->flip.flag_buf_ptr = 0;
1503                 if ( status & (RXSTATUS_FRAMING_ERROR + RXSTATUS_PARITY_ERROR +
1504                                 RXSTATUS_OVERRUN + RXSTATUS_BREAK_RECEIVED) ) {
1505                         printk("rxerr=%04X\n",status);                                  
1506                         /* update error statistics */
1507                         if ( status & RXSTATUS_BREAK_RECEIVED ) {
1508                                 status &= ~(RXSTATUS_FRAMING_ERROR + RXSTATUS_PARITY_ERROR);
1509                                 icount->brk++;
1510                         } else if (status & RXSTATUS_PARITY_ERROR) 
1511                                 icount->parity++;
1512                         else if (status & RXSTATUS_FRAMING_ERROR)
1513                                 icount->frame++;
1514                         else if (status & RXSTATUS_OVERRUN) {
1515                                 /* must issue purge fifo cmd before */
1516                                 /* 16C32 accepts more receive chars */
1517                                 usc_RTCmd(info,RTCmd_PurgeRxFifo);
1518                                 icount->overrun++;
1519                         }
1520
1521                         /* discard char if tty control flags say so */                                  
1522                         if (status & info->ignore_status_mask)
1523                                 continue;
1524                                 
1525                         status &= info->read_status_mask;
1526                 
1527                         if (status & RXSTATUS_BREAK_RECEIVED) {
1528                                 *tty->flip.flag_buf_ptr = TTY_BREAK;
1529                                 if (info->flags & ASYNC_SAK)
1530                                         do_SAK(tty);
1531                         } else if (status & RXSTATUS_PARITY_ERROR)
1532                                 *tty->flip.flag_buf_ptr = TTY_PARITY;
1533                         else if (status & RXSTATUS_FRAMING_ERROR)
1534                                 *tty->flip.flag_buf_ptr = TTY_FRAME;
1535                         if (status & RXSTATUS_OVERRUN) {
1536                                 /* Overrun is special, since it's
1537                                  * reported immediately, and doesn't
1538                                  * affect the current character
1539                                  */
1540                                 if (tty->flip.count < TTY_FLIPBUF_SIZE) {
1541                                         tty->flip.count++;
1542                                         tty->flip.flag_buf_ptr++;
1543                                         tty->flip.char_buf_ptr++;
1544                                         *tty->flip.flag_buf_ptr = TTY_OVERRUN;
1545                                 }
1546                         }
1547                 }       /* end of if (error) */
1548                 
1549                 tty->flip.flag_buf_ptr++;
1550                 tty->flip.char_buf_ptr++;
1551                 tty->flip.count++;
1552         }
1553
1554         if ( debug_level >= DEBUG_LEVEL_ISR ) {
1555                 printk("%s(%d):mgsl_isr_receive_data flip count=%d\n",
1556                         __FILE__,__LINE__,tty->flip.count);
1557                 printk("%s(%d):rx=%d brk=%d parity=%d frame=%d overrun=%d\n",
1558                         __FILE__,__LINE__,icount->rx,icount->brk,
1559                         icount->parity,icount->frame,icount->overrun);
1560         }
1561                         
1562         if ( tty->flip.count )
1563                 tty_flip_buffer_push(tty);
1564 }
1565
1566 /* mgsl_isr_misc()
1567  * 
1568  *      Service a miscellaneos interrupt source.
1569  *      
1570  * Arguments:           info            pointer to device extension (instance data)
1571  * Return Value:        None
1572  */
1573 void mgsl_isr_misc( struct mgsl_struct *info )
1574 {
1575         u16 status = usc_InReg( info, MISR );
1576
1577         if ( debug_level >= DEBUG_LEVEL_ISR )   
1578                 printk("%s(%d):mgsl_isr_misc status=%04X\n",
1579                         __FILE__,__LINE__,status);
1580                         
1581         if ((status & MISCSTATUS_RCC_UNDERRUN) &&
1582             (info->params.mode == MGSL_MODE_HDLC)) {
1583
1584                 /* turn off receiver and rx DMA */
1585                 usc_EnableReceiver(info,DISABLE_UNCONDITIONAL);
1586                 usc_DmaCmd(info, DmaCmd_ResetRxChannel);
1587                 usc_UnlatchRxstatusBits(info, RXSTATUS_ALL);
1588                 usc_ClearIrqPendingBits(info, RECEIVE_DATA + RECEIVE_STATUS);
1589                 usc_DisableInterrupts(info, RECEIVE_DATA + RECEIVE_STATUS);
1590
1591                 /* schedule BH handler to restart receiver */
1592                 info->pending_bh |= BH_RECEIVE;
1593                 info->rx_rcc_underrun = 1;
1594         }
1595
1596         usc_ClearIrqPendingBits( info, MISC );
1597         usc_UnlatchMiscstatusBits( info, status );
1598
1599 }       /* end of mgsl_isr_misc() */
1600
1601 /* mgsl_isr_null()
1602  *
1603  *      Services undefined interrupt vectors from the
1604  *      USC. (hence this function SHOULD never be called)
1605  * 
1606  * Arguments:           info            pointer to device extension (instance data)
1607  * Return Value:        None
1608  */
1609 void mgsl_isr_null( struct mgsl_struct *info )
1610 {
1611
1612 }       /* end of mgsl_isr_null() */
1613
1614 /* mgsl_isr_receive_dma()
1615  * 
1616  *      Service a receive DMA channel interrupt.
1617  *      For this driver there are two sources of receive DMA interrupts
1618  *      as identified in the Receive DMA mode Register (RDMR):
1619  * 
1620  *      BIT3    EOA/EOL         End of List, all receive buffers in receive
1621  *                              buffer list have been filled (no more free buffers
1622  *                              available). The DMA controller has shut down.
1623  * 
1624  *      BIT2    EOB             End of Buffer. This interrupt occurs when a receive
1625  *                              DMA buffer is terminated in response to completion
1626  *                              of a good frame or a frame with errors. The status
1627  *                              of the frame is stored in the buffer entry in the
1628  *                              list of receive buffer entries.
1629  * 
1630  * Arguments:           info            pointer to device instance data
1631  * Return Value:        None
1632  */
1633 void mgsl_isr_receive_dma( struct mgsl_struct *info )
1634 {
1635         u16 status;
1636         
1637         /* clear interrupt pending and IUS bit for Rx DMA IRQ */
1638         usc_OutDmaReg( info, CDIR, BIT9+BIT1 );
1639
1640         /* Read the receive DMA status to identify interrupt type. */
1641         /* This also clears the status bits. */
1642         status = usc_InDmaReg( info, RDMR );
1643
1644         if ( debug_level >= DEBUG_LEVEL_ISR )   
1645                 printk("%s(%d):mgsl_isr_receive_dma(%s) status=%04X\n",
1646                         __FILE__,__LINE__,info->device_name,status);
1647                         
1648         info->pending_bh |= BH_RECEIVE;
1649         
1650         if ( status & BIT3 ) {
1651                 info->rx_overflow = 1;
1652                 info->icount.buf_overrun++;
1653         }
1654
1655 }       /* end of mgsl_isr_receive_dma() */
1656
1657 /* mgsl_isr_transmit_dma()
1658  *
1659  *      This function services a transmit DMA channel interrupt.
1660  *
1661  *      For this driver there is one source of transmit DMA interrupts
1662  *      as identified in the Transmit DMA Mode Register (TDMR):
1663  *
1664  *      BIT2  EOB       End of Buffer. This interrupt occurs when a
1665  *                      transmit DMA buffer has been emptied.
1666  *
1667  *      The driver maintains enough transmit DMA buffers to hold at least
1668  *      one max frame size transmit frame. When operating in a buffered
1669  *      transmit mode, there may be enough transmit DMA buffers to hold at
1670  *      least two or more max frame size frames. On an EOB condition,
1671  *      determine if there are any queued transmit buffers and copy into
1672  *      transmit DMA buffers if we have room.
1673  *
1674  * Arguments:           info            pointer to device instance data
1675  * Return Value:        None
1676  */
1677 void mgsl_isr_transmit_dma( struct mgsl_struct *info )
1678 {
1679         u16 status;
1680
1681         /* clear interrupt pending and IUS bit for Tx DMA IRQ */
1682         usc_OutDmaReg(info, CDIR, BIT8+BIT0 );
1683
1684         /* Read the transmit DMA status to identify interrupt type. */
1685         /* This also clears the status bits. */
1686
1687         status = usc_InDmaReg( info, TDMR );
1688
1689         if ( debug_level >= DEBUG_LEVEL_ISR )
1690                 printk("%s(%d):mgsl_isr_transmit_dma(%s) status=%04X\n",
1691                         __FILE__,__LINE__,info->device_name,status);
1692
1693         if ( status & BIT2 ) {
1694                 --info->tx_dma_buffers_used;
1695
1696                 /* if there are transmit frames queued,
1697                  *  try to load the next one
1698                  */
1699                 if ( load_next_tx_holding_buffer(info) ) {
1700                         /* if call returns non-zero value, we have
1701                          * at least one free tx holding buffer
1702                          */
1703                         info->pending_bh |= BH_TRANSMIT;
1704                 }
1705         }
1706
1707 }       /* end of mgsl_isr_transmit_dma() */
1708
1709 /* mgsl_interrupt()
1710  * 
1711  *      Interrupt service routine entry point.
1712  *      
1713  * Arguments:
1714  * 
1715  *      irq             interrupt number that caused interrupt
1716  *      dev_id          device ID supplied during interrupt registration
1717  *      regs            interrupted processor context
1718  *      
1719  * Return Value: None
1720  */
1721 static irqreturn_t mgsl_interrupt(int irq, void *dev_id, struct pt_regs * regs)
1722 {
1723         struct mgsl_struct * info;
1724         u16 UscVector;
1725         u16 DmaVector;
1726
1727         if ( debug_level >= DEBUG_LEVEL_ISR )   
1728                 printk("%s(%d):mgsl_interrupt(%d)entry.\n",
1729                         __FILE__,__LINE__,irq);
1730
1731         info = (struct mgsl_struct *)dev_id;    
1732         if (!info)
1733                 return IRQ_NONE;
1734                 
1735         spin_lock(&info->irq_spinlock);
1736
1737         for(;;) {
1738                 /* Read the interrupt vectors from hardware. */
1739                 UscVector = usc_InReg(info, IVR) >> 9;
1740                 DmaVector = usc_InDmaReg(info, DIVR);
1741                 
1742                 if ( debug_level >= DEBUG_LEVEL_ISR )   
1743                         printk("%s(%d):%s UscVector=%08X DmaVector=%08X\n",
1744                                 __FILE__,__LINE__,info->device_name,UscVector,DmaVector);
1745                         
1746                 if ( !UscVector && !DmaVector )
1747                         break;
1748                         
1749                 /* Dispatch interrupt vector */
1750                 if ( UscVector )
1751                         (*UscIsrTable[UscVector])(info);
1752                 else if ( (DmaVector&(BIT10|BIT9)) == BIT10)
1753                         mgsl_isr_transmit_dma(info);
1754                 else
1755                         mgsl_isr_receive_dma(info);
1756
1757                 if ( info->isr_overflow ) {
1758                         printk(KERN_ERR"%s(%d):%s isr overflow irq=%d\n",
1759                                 __FILE__,__LINE__,info->device_name, irq);
1760                         usc_DisableMasterIrqBit(info);
1761                         usc_DisableDmaInterrupts(info,DICR_MASTER);
1762                         break;
1763                 }
1764         }
1765         
1766         /* Request bottom half processing if there's something 
1767          * for it to do and the bh is not already running
1768          */
1769
1770         if ( info->pending_bh && !info->bh_running && !info->bh_requested ) {
1771                 if ( debug_level >= DEBUG_LEVEL_ISR )   
1772                         printk("%s(%d):%s queueing bh task.\n",
1773                                 __FILE__,__LINE__,info->device_name);
1774                 schedule_work(&info->task);
1775                 info->bh_requested = 1;
1776         }
1777
1778         spin_unlock(&info->irq_spinlock);
1779         
1780         if ( debug_level >= DEBUG_LEVEL_ISR )   
1781                 printk("%s(%d):mgsl_interrupt(%d)exit.\n",
1782                         __FILE__,__LINE__,irq);
1783         return IRQ_HANDLED;
1784 }       /* end of mgsl_interrupt() */
1785
1786 /* startup()
1787  * 
1788  *      Initialize and start device.
1789  *      
1790  * Arguments:           info    pointer to device instance data
1791  * Return Value:        0 if success, otherwise error code
1792  */
1793 static int startup(struct mgsl_struct * info)
1794 {
1795         int retval = 0;
1796         
1797         if ( debug_level >= DEBUG_LEVEL_INFO )
1798                 printk("%s(%d):mgsl_startup(%s)\n",__FILE__,__LINE__,info->device_name);
1799                 
1800         if (info->flags & ASYNC_INITIALIZED)
1801                 return 0;
1802         
1803         if (!info->xmit_buf) {
1804                 /* allocate a page of memory for a transmit buffer */
1805                 info->xmit_buf = (unsigned char *)get_zeroed_page(GFP_KERNEL);
1806                 if (!info->xmit_buf) {
1807                         printk(KERN_ERR"%s(%d):%s can't allocate transmit buffer\n",
1808                                 __FILE__,__LINE__,info->device_name);
1809                         return -ENOMEM;
1810                 }
1811         }
1812
1813         info->pending_bh = 0;
1814         
1815         init_timer(&info->tx_timer);
1816         info->tx_timer.data = (unsigned long)info;
1817         info->tx_timer.function = mgsl_tx_timeout;
1818         
1819         /* Allocate and claim adapter resources */
1820         retval = mgsl_claim_resources(info);
1821         
1822         /* perform existence check and diagnostics */
1823         if ( !retval )
1824                 retval = mgsl_adapter_test(info);
1825                 
1826         if ( retval ) {
1827                 if (capable(CAP_SYS_ADMIN) && info->tty)
1828                         set_bit(TTY_IO_ERROR, &info->tty->flags);
1829                 mgsl_release_resources(info);
1830                 return retval;
1831         }
1832
1833         /* program hardware for current parameters */
1834         mgsl_change_params(info);
1835         
1836         if (info->tty)
1837                 clear_bit(TTY_IO_ERROR, &info->tty->flags);
1838
1839         info->flags |= ASYNC_INITIALIZED;
1840         
1841         return 0;
1842         
1843 }       /* end of startup() */
1844
1845 /* shutdown()
1846  *
1847  * Called by mgsl_close() and mgsl_hangup() to shutdown hardware
1848  *
1849  * Arguments:           info    pointer to device instance data
1850  * Return Value:        None
1851  */
1852 static void shutdown(struct mgsl_struct * info)
1853 {
1854         unsigned long flags;
1855         
1856         if (!(info->flags & ASYNC_INITIALIZED))
1857                 return;
1858
1859         if (debug_level >= DEBUG_LEVEL_INFO)
1860                 printk("%s(%d):mgsl_shutdown(%s)\n",
1861                          __FILE__,__LINE__, info->device_name );
1862
1863         /* clear status wait queue because status changes */
1864         /* can't happen after shutting down the hardware */
1865         wake_up_interruptible(&info->status_event_wait_q);
1866         wake_up_interruptible(&info->event_wait_q);
1867
1868         del_timer(&info->tx_timer);     
1869
1870         if (info->xmit_buf) {
1871                 free_page((unsigned long) info->xmit_buf);
1872                 info->xmit_buf = 0;
1873         }
1874
1875         spin_lock_irqsave(&info->irq_spinlock,flags);
1876         usc_DisableMasterIrqBit(info);
1877         usc_stop_receiver(info);
1878         usc_stop_transmitter(info);
1879         usc_DisableInterrupts(info,RECEIVE_DATA + RECEIVE_STATUS +
1880                 TRANSMIT_DATA + TRANSMIT_STATUS + IO_PIN + MISC );
1881         usc_DisableDmaInterrupts(info,DICR_MASTER + DICR_TRANSMIT + DICR_RECEIVE);
1882         
1883         /* Disable DMAEN (Port 7, Bit 14) */
1884         /* This disconnects the DMA request signal from the ISA bus */
1885         /* on the ISA adapter. This has no effect for the PCI adapter */
1886         usc_OutReg(info, PCR, (u16)((usc_InReg(info, PCR) | BIT15) | BIT14));
1887         
1888         /* Disable INTEN (Port 6, Bit12) */
1889         /* This disconnects the IRQ request signal to the ISA bus */
1890         /* on the ISA adapter. This has no effect for the PCI adapter */
1891         usc_OutReg(info, PCR, (u16)((usc_InReg(info, PCR) | BIT13) | BIT12));
1892         
1893         if (!info->tty || info->tty->termios->c_cflag & HUPCL) {
1894                 info->serial_signals &= ~(SerialSignal_DTR + SerialSignal_RTS);
1895                 usc_set_serial_signals(info);
1896         }
1897         
1898         spin_unlock_irqrestore(&info->irq_spinlock,flags);
1899
1900         mgsl_release_resources(info);   
1901         
1902         if (info->tty)
1903                 set_bit(TTY_IO_ERROR, &info->tty->flags);
1904
1905         info->flags &= ~ASYNC_INITIALIZED;
1906         
1907 }       /* end of shutdown() */
1908
1909 static void mgsl_program_hw(struct mgsl_struct *info)
1910 {
1911         unsigned long flags;
1912
1913         spin_lock_irqsave(&info->irq_spinlock,flags);
1914         
1915         usc_stop_receiver(info);
1916         usc_stop_transmitter(info);
1917         info->xmit_cnt = info->xmit_head = info->xmit_tail = 0;
1918         
1919         if (info->params.mode == MGSL_MODE_HDLC ||
1920             info->params.mode == MGSL_MODE_RAW ||
1921             info->netcount)
1922                 usc_set_sync_mode(info);
1923         else
1924                 usc_set_async_mode(info);
1925                 
1926         usc_set_serial_signals(info);
1927         
1928         info->dcd_chkcount = 0;
1929         info->cts_chkcount = 0;
1930         info->ri_chkcount = 0;
1931         info->dsr_chkcount = 0;
1932
1933         usc_EnableStatusIrqs(info,SICR_CTS+SICR_DSR+SICR_DCD+SICR_RI);          
1934         usc_EnableInterrupts(info, IO_PIN);
1935         usc_get_serial_signals(info);
1936                 
1937         if (info->netcount || info->tty->termios->c_cflag & CREAD)
1938                 usc_start_receiver(info);
1939                 
1940         spin_unlock_irqrestore(&info->irq_spinlock,flags);
1941 }
1942
1943 /* Reconfigure adapter based on new parameters
1944  */
1945 static void mgsl_change_params(struct mgsl_struct *info)
1946 {
1947         unsigned cflag;
1948         int bits_per_char;
1949
1950         if (!info->tty || !info->tty->termios)
1951                 return;
1952                 
1953         if (debug_level >= DEBUG_LEVEL_INFO)
1954                 printk("%s(%d):mgsl_change_params(%s)\n",
1955                          __FILE__,__LINE__, info->device_name );
1956                          
1957         cflag = info->tty->termios->c_cflag;
1958
1959         /* if B0 rate (hangup) specified then negate DTR and RTS */
1960         /* otherwise assert DTR and RTS */
1961         if (cflag & CBAUD)
1962                 info->serial_signals |= SerialSignal_RTS + SerialSignal_DTR;
1963         else
1964                 info->serial_signals &= ~(SerialSignal_RTS + SerialSignal_DTR);
1965         
1966         /* byte size and parity */
1967         
1968         switch (cflag & CSIZE) {
1969               case CS5: info->params.data_bits = 5; break;
1970               case CS6: info->params.data_bits = 6; break;
1971               case CS7: info->params.data_bits = 7; break;
1972               case CS8: info->params.data_bits = 8; break;
1973               /* Never happens, but GCC is too dumb to figure it out */
1974               default:  info->params.data_bits = 7; break;
1975               }
1976               
1977         if (cflag & CSTOPB)
1978                 info->params.stop_bits = 2;
1979         else
1980                 info->params.stop_bits = 1;
1981
1982         info->params.parity = ASYNC_PARITY_NONE;
1983         if (cflag & PARENB) {
1984                 if (cflag & PARODD)
1985                         info->params.parity = ASYNC_PARITY_ODD;
1986                 else
1987                         info->params.parity = ASYNC_PARITY_EVEN;
1988 #ifdef CMSPAR
1989                 if (cflag & CMSPAR)
1990                         info->params.parity = ASYNC_PARITY_SPACE;
1991 #endif
1992         }
1993
1994         /* calculate number of jiffies to transmit a full
1995          * FIFO (32 bytes) at specified data rate
1996          */
1997         bits_per_char = info->params.data_bits + 
1998                         info->params.stop_bits + 1;
1999
2000         /* if port data rate is set to 460800 or less then
2001          * allow tty settings to override, otherwise keep the
2002          * current data rate.
2003          */
2004         if (info->params.data_rate <= 460800)
2005                 info->params.data_rate = tty_get_baud_rate(info->tty);
2006         
2007         if ( info->params.data_rate ) {
2008                 info->timeout = (32*HZ*bits_per_char) / 
2009                                 info->params.data_rate;
2010         }
2011         info->timeout += HZ/50;         /* Add .02 seconds of slop */
2012
2013         if (cflag & CRTSCTS)
2014                 info->flags |= ASYNC_CTS_FLOW;
2015         else
2016                 info->flags &= ~ASYNC_CTS_FLOW;
2017                 
2018         if (cflag & CLOCAL)
2019                 info->flags &= ~ASYNC_CHECK_CD;
2020         else
2021                 info->flags |= ASYNC_CHECK_CD;
2022
2023         /* process tty input control flags */
2024         
2025         info->read_status_mask = RXSTATUS_OVERRUN;
2026         if (I_INPCK(info->tty))
2027                 info->read_status_mask |= RXSTATUS_PARITY_ERROR | RXSTATUS_FRAMING_ERROR;
2028         if (I_BRKINT(info->tty) || I_PARMRK(info->tty))
2029                 info->read_status_mask |= RXSTATUS_BREAK_RECEIVED;
2030         
2031         if (I_IGNPAR(info->tty))
2032                 info->ignore_status_mask |= RXSTATUS_PARITY_ERROR | RXSTATUS_FRAMING_ERROR;
2033         if (I_IGNBRK(info->tty)) {
2034                 info->ignore_status_mask |= RXSTATUS_BREAK_RECEIVED;
2035                 /* If ignoring parity and break indicators, ignore 
2036                  * overruns too.  (For real raw support).
2037                  */
2038                 if (I_IGNPAR(info->tty))
2039                         info->ignore_status_mask |= RXSTATUS_OVERRUN;
2040         }
2041
2042         mgsl_program_hw(info);
2043
2044 }       /* end of mgsl_change_params() */
2045
2046 /* mgsl_put_char()
2047  * 
2048  *      Add a character to the transmit buffer.
2049  *      
2050  * Arguments:           tty     pointer to tty information structure
2051  *                      ch      character to add to transmit buffer
2052  *              
2053  * Return Value:        None
2054  */
2055 static void mgsl_put_char(struct tty_struct *tty, unsigned char ch)
2056 {
2057         struct mgsl_struct *info = (struct mgsl_struct *)tty->driver_data;
2058         unsigned long flags;
2059
2060         if ( debug_level >= DEBUG_LEVEL_INFO ) {
2061                 printk( "%s(%d):mgsl_put_char(%d) on %s\n",
2062                         __FILE__,__LINE__,ch,info->device_name);
2063         }               
2064         
2065         if (mgsl_paranoia_check(info, tty->name, "mgsl_put_char"))
2066                 return;
2067
2068         if (!tty || !info->xmit_buf)
2069                 return;
2070
2071         spin_lock_irqsave(&info->irq_spinlock,flags);
2072         
2073         if ( (info->params.mode == MGSL_MODE_ASYNC ) || !info->tx_active ) {
2074         
2075                 if (info->xmit_cnt < SERIAL_XMIT_SIZE - 1) {
2076                         info->xmit_buf[info->xmit_head++] = ch;
2077                         info->xmit_head &= SERIAL_XMIT_SIZE-1;
2078                         info->xmit_cnt++;
2079                 }
2080         }
2081         
2082         spin_unlock_irqrestore(&info->irq_spinlock,flags);
2083         
2084 }       /* end of mgsl_put_char() */
2085
2086 /* mgsl_flush_chars()
2087  * 
2088  *      Enable transmitter so remaining characters in the
2089  *      transmit buffer are sent.
2090  *      
2091  * Arguments:           tty     pointer to tty information structure
2092  * Return Value:        None
2093  */
2094 static void mgsl_flush_chars(struct tty_struct *tty)
2095 {
2096         struct mgsl_struct *info = (struct mgsl_struct *)tty->driver_data;
2097         unsigned long flags;
2098                                 
2099         if ( debug_level >= DEBUG_LEVEL_INFO )
2100                 printk( "%s(%d):mgsl_flush_chars() entry on %s xmit_cnt=%d\n",
2101                         __FILE__,__LINE__,info->device_name,info->xmit_cnt);
2102         
2103         if (mgsl_paranoia_check(info, tty->name, "mgsl_flush_chars"))
2104                 return;
2105
2106         if (info->xmit_cnt <= 0 || tty->stopped || tty->hw_stopped ||
2107             !info->xmit_buf)
2108                 return;
2109
2110         if ( debug_level >= DEBUG_LEVEL_INFO )
2111                 printk( "%s(%d):mgsl_flush_chars() entry on %s starting transmitter\n",
2112                         __FILE__,__LINE__,info->device_name );
2113
2114         spin_lock_irqsave(&info->irq_spinlock,flags);
2115         
2116         if (!info->tx_active) {
2117                 if ( (info->params.mode == MGSL_MODE_HDLC ||
2118                         info->params.mode == MGSL_MODE_RAW) && info->xmit_cnt ) {
2119                         /* operating in synchronous (frame oriented) mode */
2120                         /* copy data from circular xmit_buf to */
2121                         /* transmit DMA buffer. */
2122                         mgsl_load_tx_dma_buffer(info,
2123                                  info->xmit_buf,info->xmit_cnt);
2124                 }
2125                 usc_start_transmitter(info);
2126         }
2127         
2128         spin_unlock_irqrestore(&info->irq_spinlock,flags);
2129         
2130 }       /* end of mgsl_flush_chars() */
2131
2132 /* mgsl_write()
2133  * 
2134  *      Send a block of data
2135  *      
2136  * Arguments:
2137  * 
2138  *      tty             pointer to tty information structure
2139  *      from_user       flag: 1 = from user process
2140  *      buf             pointer to buffer containing send data
2141  *      count           size of send data in bytes
2142  *      
2143  * Return Value:        number of characters written
2144  */
2145 static int mgsl_write(struct tty_struct * tty, int from_user,
2146                     const unsigned char *buf, int count)
2147 {
2148         int     c, ret = 0, err;
2149         struct mgsl_struct *info = (struct mgsl_struct *)tty->driver_data;
2150         unsigned long flags;
2151         
2152         if ( debug_level >= DEBUG_LEVEL_INFO )
2153                 printk( "%s(%d):mgsl_write(%s) count=%d\n",
2154                         __FILE__,__LINE__,info->device_name,count);
2155         
2156         if (mgsl_paranoia_check(info, tty->name, "mgsl_write"))
2157                 goto cleanup;
2158
2159         if (!tty || !info->xmit_buf || !tmp_buf)
2160                 goto cleanup;
2161
2162         if ( info->params.mode == MGSL_MODE_HDLC ||
2163                         info->params.mode == MGSL_MODE_RAW ) {
2164                 /* operating in synchronous (frame oriented) mode */
2165                 /* operating in synchronous (frame oriented) mode */
2166                 if (info->tx_active) {
2167
2168                         if ( info->params.mode == MGSL_MODE_HDLC ) {
2169                                 ret = 0;
2170                                 goto cleanup;
2171                         }
2172                         /* transmitter is actively sending data -
2173                          * if we have multiple transmit dma and
2174                          * holding buffers, attempt to queue this
2175                          * frame for transmission at a later time.
2176                          */
2177                         if (info->tx_holding_count >= info->num_tx_holding_buffers ) {
2178                                 /* no tx holding buffers available */
2179                                 ret = 0;
2180                                 goto cleanup;
2181                         }
2182
2183                         /* queue transmit frame request */
2184                         ret = count;
2185                         if (from_user) {
2186                                 down(&tmp_buf_sem);
2187                                 COPY_FROM_USER(err,tmp_buf, buf, count);
2188                                 if (err) {
2189                                         if ( debug_level >= DEBUG_LEVEL_INFO )
2190                                                 printk( "%s(%d):mgsl_write(%s) sync user buf copy failed\n",
2191                                                         __FILE__,__LINE__,info->device_name);
2192                                         ret = -EFAULT;
2193                                 } else
2194                                         save_tx_buffer_request(info,tmp_buf,count);
2195                                 up(&tmp_buf_sem);
2196                         }
2197                         else
2198                                 save_tx_buffer_request(info,buf,count);
2199
2200                         /* if we have sufficient tx dma buffers,
2201                          * load the next buffered tx request
2202                          */
2203                         spin_lock_irqsave(&info->irq_spinlock,flags);
2204                         load_next_tx_holding_buffer(info);
2205                         spin_unlock_irqrestore(&info->irq_spinlock,flags);
2206                         goto cleanup;
2207                 }
2208         
2209                 /* if operating in HDLC LoopMode and the adapter  */
2210                 /* has yet to be inserted into the loop, we can't */
2211                 /* transmit                                       */
2212
2213                 if ( (info->params.flags & HDLC_FLAG_HDLC_LOOPMODE) &&
2214                         !usc_loopmode_active(info) )
2215                 {
2216                         ret = 0;
2217                         goto cleanup;
2218                 }
2219
2220                 if ( info->xmit_cnt ) {
2221                         /* Send accumulated from send_char() calls */
2222                         /* as frame and wait before accepting more data. */
2223                         ret = 0;
2224                         
2225                         /* copy data from circular xmit_buf to */
2226                         /* transmit DMA buffer. */
2227                         mgsl_load_tx_dma_buffer(info,
2228                                 info->xmit_buf,info->xmit_cnt);
2229                         if ( debug_level >= DEBUG_LEVEL_INFO )
2230                                 printk( "%s(%d):mgsl_write(%s) sync xmit_cnt flushing\n",
2231                                         __FILE__,__LINE__,info->device_name);
2232                 } else {
2233                         if ( debug_level >= DEBUG_LEVEL_INFO )
2234                                 printk( "%s(%d):mgsl_write(%s) sync transmit accepted\n",
2235                                         __FILE__,__LINE__,info->device_name);
2236                         ret = count;
2237                         info->xmit_cnt = count;
2238                         if (from_user) {
2239                                 down(&tmp_buf_sem);
2240                                 COPY_FROM_USER(err,tmp_buf, buf, count);
2241                                 if (err) {
2242                                         if ( debug_level >= DEBUG_LEVEL_INFO )
2243                                                 printk( "%s(%d):mgsl_write(%s) sync user buf copy failed\n",
2244                                                         __FILE__,__LINE__,info->device_name);
2245                                         ret = -EFAULT;
2246                                 } else
2247                                         mgsl_load_tx_dma_buffer(info,tmp_buf,count);
2248                                 up(&tmp_buf_sem);
2249                         }
2250                         else
2251                                 mgsl_load_tx_dma_buffer(info,buf,count);
2252                 }
2253         } else {
2254                 if (from_user) {
2255                         down(&tmp_buf_sem);
2256                         while (1) {
2257                                 c = MIN(count,
2258                                         MIN(SERIAL_XMIT_SIZE - info->xmit_cnt - 1,
2259                                             SERIAL_XMIT_SIZE - info->xmit_head));
2260                                 if (c <= 0)
2261                                         break;
2262
2263                                 COPY_FROM_USER(err,tmp_buf, buf, c);
2264                                 c -= err;
2265                                 if (!c) {
2266                                         if (!ret)
2267                                                 ret = -EFAULT;
2268                                         break;
2269                                 }
2270                                 spin_lock_irqsave(&info->irq_spinlock,flags);
2271                                 c = MIN(c, MIN(SERIAL_XMIT_SIZE - info->xmit_cnt - 1,
2272                                                SERIAL_XMIT_SIZE - info->xmit_head));
2273                                 memcpy(info->xmit_buf + info->xmit_head, tmp_buf, c);
2274                                 info->xmit_head = ((info->xmit_head + c) &
2275                                                    (SERIAL_XMIT_SIZE-1));
2276                                 info->xmit_cnt += c;
2277                                 spin_unlock_irqrestore(&info->irq_spinlock,flags);
2278                                 buf += c;
2279                                 count -= c;
2280                                 ret += c;
2281                         }
2282                         up(&tmp_buf_sem);
2283                 } else {
2284                         while (1) {
2285                                 spin_lock_irqsave(&info->irq_spinlock,flags);
2286                                 c = MIN(count,
2287                                         MIN(SERIAL_XMIT_SIZE - info->xmit_cnt - 1,
2288                                             SERIAL_XMIT_SIZE - info->xmit_head));
2289                                 if (c <= 0) {
2290                                         spin_unlock_irqrestore(&info->irq_spinlock,flags);
2291                                         break;
2292                                 }
2293                                 memcpy(info->xmit_buf + info->xmit_head, buf, c);
2294                                 info->xmit_head = ((info->xmit_head + c) &
2295                                                    (SERIAL_XMIT_SIZE-1));
2296                                 info->xmit_cnt += c;
2297                                 spin_unlock_irqrestore(&info->irq_spinlock,flags);
2298                                 buf += c;
2299                                 count -= c;
2300                                 ret += c;
2301                         }
2302                 }
2303         }       
2304         
2305         if (info->xmit_cnt && !tty->stopped && !tty->hw_stopped) {
2306                 spin_lock_irqsave(&info->irq_spinlock,flags);
2307                 if (!info->tx_active)
2308                         usc_start_transmitter(info);
2309                 spin_unlock_irqrestore(&info->irq_spinlock,flags);
2310         }
2311 cleanup:        
2312         if ( debug_level >= DEBUG_LEVEL_INFO )
2313                 printk( "%s(%d):mgsl_write(%s) returning=%d\n",
2314                         __FILE__,__LINE__,info->device_name,ret);
2315                         
2316         return ret;
2317         
2318 }       /* end of mgsl_write() */
2319
2320 /* mgsl_write_room()
2321  *
2322  *      Return the count of free bytes in transmit buffer
2323  *      
2324  * Arguments:           tty     pointer to tty info structure
2325  * Return Value:        None
2326  */
2327 static int mgsl_write_room(struct tty_struct *tty)
2328 {
2329         struct mgsl_struct *info = (struct mgsl_struct *)tty->driver_data;
2330         int     ret;
2331                                 
2332         if (mgsl_paranoia_check(info, tty->name, "mgsl_write_room"))
2333                 return 0;
2334         ret = SERIAL_XMIT_SIZE - info->xmit_cnt - 1;
2335         if (ret < 0)
2336                 ret = 0;
2337                 
2338         if (debug_level >= DEBUG_LEVEL_INFO)
2339                 printk("%s(%d):mgsl_write_room(%s)=%d\n",
2340                          __FILE__,__LINE__, info->device_name,ret );
2341                          
2342         if ( info->params.mode == MGSL_MODE_HDLC ||
2343                 info->params.mode == MGSL_MODE_RAW ) {
2344                 /* operating in synchronous (frame oriented) mode */
2345                 if ( info->tx_active )
2346                         return 0;
2347                 else
2348                         return HDLC_MAX_FRAME_SIZE;
2349         }
2350         
2351         return ret;
2352         
2353 }       /* end of mgsl_write_room() */
2354
2355 /* mgsl_chars_in_buffer()
2356  *
2357  *      Return the count of bytes in transmit buffer
2358  *      
2359  * Arguments:           tty     pointer to tty info structure
2360  * Return Value:        None
2361  */
2362 static int mgsl_chars_in_buffer(struct tty_struct *tty)
2363 {
2364         struct mgsl_struct *info = (struct mgsl_struct *)tty->driver_data;
2365                          
2366         if (debug_level >= DEBUG_LEVEL_INFO)
2367                 printk("%s(%d):mgsl_chars_in_buffer(%s)\n",
2368                          __FILE__,__LINE__, info->device_name );
2369                          
2370         if (mgsl_paranoia_check(info, tty->name, "mgsl_chars_in_buffer"))
2371                 return 0;
2372                 
2373         if (debug_level >= DEBUG_LEVEL_INFO)
2374                 printk("%s(%d):mgsl_chars_in_buffer(%s)=%d\n",
2375                          __FILE__,__LINE__, info->device_name,info->xmit_cnt );
2376                          
2377         if ( info->params.mode == MGSL_MODE_HDLC ||
2378                 info->params.mode == MGSL_MODE_RAW ) {
2379                 /* operating in synchronous (frame oriented) mode */
2380                 if ( info->tx_active )
2381                         return info->max_frame_size;
2382                 else
2383                         return 0;
2384         }
2385                          
2386         return info->xmit_cnt;
2387 }       /* end of mgsl_chars_in_buffer() */
2388
2389 /* mgsl_flush_buffer()
2390  *
2391  *      Discard all data in the send buffer
2392  *      
2393  * Arguments:           tty     pointer to tty info structure
2394  * Return Value:        None
2395  */
2396 static void mgsl_flush_buffer(struct tty_struct *tty)
2397 {
2398         struct mgsl_struct *info = (struct mgsl_struct *)tty->driver_data;
2399         unsigned long flags;
2400         
2401         if (debug_level >= DEBUG_LEVEL_INFO)
2402                 printk("%s(%d):mgsl_flush_buffer(%s) entry\n",
2403                          __FILE__,__LINE__, info->device_name );
2404         
2405         if (mgsl_paranoia_check(info, tty->name, "mgsl_flush_buffer"))
2406                 return;
2407                 
2408         spin_lock_irqsave(&info->irq_spinlock,flags); 
2409         info->xmit_cnt = info->xmit_head = info->xmit_tail = 0;
2410         del_timer(&info->tx_timer);     
2411         spin_unlock_irqrestore(&info->irq_spinlock,flags);
2412         
2413         wake_up_interruptible(&tty->write_wait);
2414         if ((tty->flags & (1 << TTY_DO_WRITE_WAKEUP)) &&
2415             tty->ldisc.write_wakeup)
2416                 (tty->ldisc.write_wakeup)(tty);
2417                 
2418 }       /* end of mgsl_flush_buffer() */
2419
2420 /* mgsl_send_xchar()
2421  *
2422  *      Send a high-priority XON/XOFF character
2423  *      
2424  * Arguments:           tty     pointer to tty info structure
2425  *                      ch      character to send
2426  * Return Value:        None
2427  */
2428 static void mgsl_send_xchar(struct tty_struct *tty, char ch)
2429 {
2430         struct mgsl_struct *info = (struct mgsl_struct *)tty->driver_data;
2431         unsigned long flags;
2432
2433         if (debug_level >= DEBUG_LEVEL_INFO)
2434                 printk("%s(%d):mgsl_send_xchar(%s,%d)\n",
2435                          __FILE__,__LINE__, info->device_name, ch );
2436                          
2437         if (mgsl_paranoia_check(info, tty->name, "mgsl_send_xchar"))
2438                 return;
2439
2440         info->x_char = ch;
2441         if (ch) {
2442                 /* Make sure transmit interrupts are on */
2443                 spin_lock_irqsave(&info->irq_spinlock,flags);
2444                 if (!info->tx_enabled)
2445                         usc_start_transmitter(info);
2446                 spin_unlock_irqrestore(&info->irq_spinlock,flags);
2447         }
2448 }       /* end of mgsl_send_xchar() */
2449
2450 /* mgsl_throttle()
2451  * 
2452  *      Signal remote device to throttle send data (our receive data)
2453  *      
2454  * Arguments:           tty     pointer to tty info structure
2455  * Return Value:        None
2456  */
2457 static void mgsl_throttle(struct tty_struct * tty)
2458 {
2459         struct mgsl_struct *info = (struct mgsl_struct *)tty->driver_data;
2460         unsigned long flags;
2461         
2462         if (debug_level >= DEBUG_LEVEL_INFO)
2463                 printk("%s(%d):mgsl_throttle(%s) entry\n",
2464                          __FILE__,__LINE__, info->device_name );
2465
2466         if (mgsl_paranoia_check(info, tty->name, "mgsl_throttle"))
2467                 return;
2468         
2469         if (I_IXOFF(tty))
2470                 mgsl_send_xchar(tty, STOP_CHAR(tty));
2471  
2472         if (tty->termios->c_cflag & CRTSCTS) {
2473                 spin_lock_irqsave(&info->irq_spinlock,flags);
2474                 info->serial_signals &= ~SerialSignal_RTS;
2475                 usc_set_serial_signals(info);
2476                 spin_unlock_irqrestore(&info->irq_spinlock,flags);
2477         }
2478 }       /* end of mgsl_throttle() */
2479
2480 /* mgsl_unthrottle()
2481  * 
2482  *      Signal remote device to stop throttling send data (our receive data)
2483  *      
2484  * Arguments:           tty     pointer to tty info structure
2485  * Return Value:        None
2486  */
2487 static void mgsl_unthrottle(struct tty_struct * tty)
2488 {
2489         struct mgsl_struct *info = (struct mgsl_struct *)tty->driver_data;
2490         unsigned long flags;
2491         
2492         if (debug_level >= DEBUG_LEVEL_INFO)
2493                 printk("%s(%d):mgsl_unthrottle(%s) entry\n",
2494                          __FILE__,__LINE__, info->device_name );
2495
2496         if (mgsl_paranoia_check(info, tty->name, "mgsl_unthrottle"))
2497                 return;
2498         
2499         if (I_IXOFF(tty)) {
2500                 if (info->x_char)
2501                         info->x_char = 0;
2502                 else
2503                         mgsl_send_xchar(tty, START_CHAR(tty));
2504         }
2505         
2506         if (tty->termios->c_cflag & CRTSCTS) {
2507                 spin_lock_irqsave(&info->irq_spinlock,flags);
2508                 info->serial_signals |= SerialSignal_RTS;
2509                 usc_set_serial_signals(info);
2510                 spin_unlock_irqrestore(&info->irq_spinlock,flags);
2511         }
2512         
2513 }       /* end of mgsl_unthrottle() */
2514
2515 /* mgsl_get_stats()
2516  * 
2517  *      get the current serial parameters information
2518  *
2519  * Arguments:   info            pointer to device instance data
2520  *              user_icount     pointer to buffer to hold returned stats
2521  *      
2522  * Return Value:        0 if success, otherwise error code
2523  */
2524 static int mgsl_get_stats(struct mgsl_struct * info, struct mgsl_icount *user_icount)
2525 {
2526         int err;
2527         
2528         if (debug_level >= DEBUG_LEVEL_INFO)
2529                 printk("%s(%d):mgsl_get_params(%s)\n",
2530                          __FILE__,__LINE__, info->device_name);
2531                         
2532         COPY_TO_USER(err,user_icount, &info->icount, sizeof(struct mgsl_icount));
2533         if (err) {
2534                 if ( debug_level >= DEBUG_LEVEL_INFO )
2535                         printk( "%s(%d):mgsl_get_stats(%s) user buffer copy failed\n",
2536                                 __FILE__,__LINE__,info->device_name);
2537                 return -EFAULT;
2538         }
2539         
2540         return 0;
2541         
2542 }       /* end of mgsl_get_stats() */
2543
2544 /* mgsl_get_params()
2545  * 
2546  *      get the current serial parameters information
2547  *
2548  * Arguments:   info            pointer to device instance data
2549  *              user_params     pointer to buffer to hold returned params
2550  *      
2551  * Return Value:        0 if success, otherwise error code
2552  */
2553 static int mgsl_get_params(struct mgsl_struct * info, MGSL_PARAMS *user_params)
2554 {
2555         int err;
2556         if (debug_level >= DEBUG_LEVEL_INFO)
2557                 printk("%s(%d):mgsl_get_params(%s)\n",
2558                          __FILE__,__LINE__, info->device_name);
2559                         
2560         COPY_TO_USER(err,user_params, &info->params, sizeof(MGSL_PARAMS));
2561         if (err) {
2562                 if ( debug_level >= DEBUG_LEVEL_INFO )
2563                         printk( "%s(%d):mgsl_get_params(%s) user buffer copy failed\n",
2564                                 __FILE__,__LINE__,info->device_name);
2565                 return -EFAULT;
2566         }
2567         
2568         return 0;
2569         
2570 }       /* end of mgsl_get_params() */
2571
2572 /* mgsl_set_params()
2573  * 
2574  *      set the serial parameters
2575  *      
2576  * Arguments:
2577  * 
2578  *      info            pointer to device instance data
2579  *      new_params      user buffer containing new serial params
2580  *
2581  * Return Value:        0 if success, otherwise error code
2582  */
2583 static int mgsl_set_params(struct mgsl_struct * info, MGSL_PARAMS *new_params)
2584 {
2585         unsigned long flags;
2586         MGSL_PARAMS tmp_params;
2587         int err;
2588  
2589         if (debug_level >= DEBUG_LEVEL_INFO)
2590                 printk("%s(%d):mgsl_set_params %s\n", __FILE__,__LINE__,
2591                         info->device_name );
2592         COPY_FROM_USER(err,&tmp_params, new_params, sizeof(MGSL_PARAMS));
2593         if (err) {
2594                 if ( debug_level >= DEBUG_LEVEL_INFO )
2595                         printk( "%s(%d):mgsl_set_params(%s) user buffer copy failed\n",
2596                                 __FILE__,__LINE__,info->device_name);
2597                 return -EFAULT;
2598         }
2599         
2600         spin_lock_irqsave(&info->irq_spinlock,flags);
2601         memcpy(&info->params,&tmp_params,sizeof(MGSL_PARAMS));
2602         spin_unlock_irqrestore(&info->irq_spinlock,flags);
2603         
2604         mgsl_change_params(info);
2605         
2606         return 0;
2607         
2608 }       /* end of mgsl_set_params() */
2609
2610 /* mgsl_get_txidle()
2611  * 
2612  *      get the current transmit idle mode
2613  *
2614  * Arguments:   info            pointer to device instance data
2615  *              idle_mode       pointer to buffer to hold returned idle mode
2616  *      
2617  * Return Value:        0 if success, otherwise error code
2618  */
2619 static int mgsl_get_txidle(struct mgsl_struct * info, int*idle_mode)
2620 {
2621         int err;
2622         
2623         if (debug_level >= DEBUG_LEVEL_INFO)
2624                 printk("%s(%d):mgsl_get_txidle(%s)=%d\n",
2625                          __FILE__,__LINE__, info->device_name, info->idle_mode);
2626                         
2627         COPY_TO_USER(err,idle_mode, &info->idle_mode, sizeof(int));
2628         if (err) {
2629                 if ( debug_level >= DEBUG_LEVEL_INFO )
2630                         printk( "%s(%d):mgsl_get_txidle(%s) user buffer copy failed\n",
2631                                 __FILE__,__LINE__,info->device_name);
2632                 return -EFAULT;
2633         }
2634         
2635         return 0;
2636         
2637 }       /* end of mgsl_get_txidle() */
2638
2639 /* mgsl_set_txidle()    service ioctl to set transmit idle mode
2640  *      
2641  * Arguments:           info            pointer to device instance data
2642  *                      idle_mode       new idle mode
2643  *
2644  * Return Value:        0 if success, otherwise error code
2645  */
2646 static int mgsl_set_txidle(struct mgsl_struct * info, int idle_mode)
2647 {
2648         unsigned long flags;
2649  
2650         if (debug_level >= DEBUG_LEVEL_INFO)
2651                 printk("%s(%d):mgsl_set_txidle(%s,%d)\n", __FILE__,__LINE__,
2652                         info->device_name, idle_mode );
2653                         
2654         spin_lock_irqsave(&info->irq_spinlock,flags);
2655         info->idle_mode = idle_mode;
2656         usc_set_txidle( info );
2657         spin_unlock_irqrestore(&info->irq_spinlock,flags);
2658         return 0;
2659         
2660 }       /* end of mgsl_set_txidle() */
2661
2662 /* mgsl_txenable()
2663  * 
2664  *      enable or disable the transmitter
2665  *      
2666  * Arguments:
2667  * 
2668  *      info            pointer to device instance data
2669  *      enable          1 = enable, 0 = disable
2670  *
2671  * Return Value:        0 if success, otherwise error code
2672  */
2673 static int mgsl_txenable(struct mgsl_struct * info, int enable)
2674 {
2675         unsigned long flags;
2676  
2677         if (debug_level >= DEBUG_LEVEL_INFO)
2678                 printk("%s(%d):mgsl_txenable(%s,%d)\n", __FILE__,__LINE__,
2679                         info->device_name, enable);
2680                         
2681         spin_lock_irqsave(&info->irq_spinlock,flags);
2682         if ( enable ) {
2683                 if ( !info->tx_enabled ) {
2684
2685                         usc_start_transmitter(info);
2686                         /*--------------------------------------------------
2687                          * if HDLC/SDLC Loop mode, attempt to insert the
2688                          * station in the 'loop' by setting CMR:13. Upon
2689                          * receipt of the next GoAhead (RxAbort) sequence,
2690                          * the OnLoop indicator (CCSR:7) should go active
2691                          * to indicate that we are on the loop
2692                          *--------------------------------------------------*/
2693                         if ( info->params.flags & HDLC_FLAG_HDLC_LOOPMODE )
2694                                 usc_loopmode_insert_request( info );
2695                 }
2696         } else {
2697                 if ( info->tx_enabled )
2698                         usc_stop_transmitter(info);
2699         }
2700         spin_unlock_irqrestore(&info->irq_spinlock,flags);
2701         return 0;
2702         
2703 }       /* end of mgsl_txenable() */
2704
2705 /* mgsl_txabort()       abort send HDLC frame
2706  *      
2707  * Arguments:           info            pointer to device instance data
2708  * Return Value:        0 if success, otherwise error code
2709  */
2710 static int mgsl_txabort(struct mgsl_struct * info)
2711 {
2712         unsigned long flags;
2713  
2714         if (debug_level >= DEBUG_LEVEL_INFO)
2715                 printk("%s(%d):mgsl_txabort(%s)\n", __FILE__,__LINE__,
2716                         info->device_name);
2717                         
2718         spin_lock_irqsave(&info->irq_spinlock,flags);
2719         if ( info->tx_active && info->params.mode == MGSL_MODE_HDLC )
2720         {
2721                 if ( info->params.flags & HDLC_FLAG_HDLC_LOOPMODE )
2722                         usc_loopmode_cancel_transmit( info );
2723                 else
2724                         usc_TCmd(info,TCmd_SendAbort);
2725         }
2726         spin_unlock_irqrestore(&info->irq_spinlock,flags);
2727         return 0;
2728         
2729 }       /* end of mgsl_txabort() */
2730
2731 /* mgsl_rxenable()      enable or disable the receiver
2732  *      
2733  * Arguments:           info            pointer to device instance data
2734  *                      enable          1 = enable, 0 = disable
2735  * Return Value:        0 if success, otherwise error code
2736  */
2737 static int mgsl_rxenable(struct mgsl_struct * info, int enable)
2738 {
2739         unsigned long flags;
2740  
2741         if (debug_level >= DEBUG_LEVEL_INFO)
2742                 printk("%s(%d):mgsl_rxenable(%s,%d)\n", __FILE__,__LINE__,
2743                         info->device_name, enable);
2744                         
2745         spin_lock_irqsave(&info->irq_spinlock,flags);
2746         if ( enable ) {
2747                 if ( !info->rx_enabled )
2748                         usc_start_receiver(info);
2749         } else {
2750                 if ( info->rx_enabled )
2751                         usc_stop_receiver(info);
2752         }
2753         spin_unlock_irqrestore(&info->irq_spinlock,flags);
2754         return 0;
2755         
2756 }       /* end of mgsl_rxenable() */
2757
2758 /* mgsl_wait_event()    wait for specified event to occur
2759  *      
2760  * Arguments:           info    pointer to device instance data
2761  *                      mask    pointer to bitmask of events to wait for
2762  * Return Value:        0       if successful and bit mask updated with
2763  *                              of events triggerred,
2764  *                      otherwise error code
2765  */
2766 static int mgsl_wait_event(struct mgsl_struct * info, int * mask_ptr)
2767 {
2768         unsigned long flags;
2769         int s;
2770         int rc=0;
2771         struct mgsl_icount cprev, cnow;
2772         int events;
2773         int mask;
2774         struct  _input_signal_events oldsigs, newsigs;
2775         DECLARE_WAITQUEUE(wait, current);
2776
2777         COPY_FROM_USER(rc,&mask, mask_ptr, sizeof(int));
2778         if (rc) {
2779                 return  -EFAULT;
2780         }
2781                  
2782         if (debug_level >= DEBUG_LEVEL_INFO)
2783                 printk("%s(%d):mgsl_wait_event(%s,%d)\n", __FILE__,__LINE__,
2784                         info->device_name, mask);
2785
2786         spin_lock_irqsave(&info->irq_spinlock,flags);
2787
2788         /* return immediately if state matches requested events */
2789         usc_get_serial_signals(info);
2790         s = info->serial_signals;
2791         events = mask &
2792                 ( ((s & SerialSignal_DSR) ? MgslEvent_DsrActive:MgslEvent_DsrInactive) +
2793                   ((s & SerialSignal_DCD) ? MgslEvent_DcdActive:MgslEvent_DcdInactive) +
2794                   ((s & SerialSignal_CTS) ? MgslEvent_CtsActive:MgslEvent_CtsInactive) +
2795                   ((s & SerialSignal_RI)  ? MgslEvent_RiActive :MgslEvent_RiInactive) );
2796         if (events) {
2797                 spin_unlock_irqrestore(&info->irq_spinlock,flags);
2798                 goto exit;
2799         }
2800
2801         /* save current irq counts */
2802         cprev = info->icount;
2803         oldsigs = info->input_signal_events;
2804         
2805         /* enable hunt and idle irqs if needed */
2806         if (mask & (MgslEvent_ExitHuntMode + MgslEvent_IdleReceived)) {
2807                 u16 oldreg = usc_InReg(info,RICR);
2808                 u16 newreg = oldreg +
2809                          (mask & MgslEvent_ExitHuntMode ? RXSTATUS_EXITED_HUNT:0) +
2810                          (mask & MgslEvent_IdleReceived ? RXSTATUS_IDLE_RECEIVED:0);
2811                 if (oldreg != newreg)
2812                         usc_OutReg(info, RICR, newreg);
2813         }
2814         
2815         set_current_state(TASK_INTERRUPTIBLE);
2816         add_wait_queue(&info->event_wait_q, &wait);
2817         
2818         spin_unlock_irqrestore(&info->irq_spinlock,flags);
2819         
2820
2821         for(;;) {
2822                 schedule();
2823                 if (signal_pending(current)) {
2824                         rc = -ERESTARTSYS;
2825                         break;
2826                 }
2827                         
2828                 /* get current irq counts */
2829                 spin_lock_irqsave(&info->irq_spinlock,flags);
2830                 cnow = info->icount;
2831                 newsigs = info->input_signal_events;
2832                 set_current_state(TASK_INTERRUPTIBLE);
2833                 spin_unlock_irqrestore(&info->irq_spinlock,flags);
2834
2835                 /* if no change, wait aborted for some reason */
2836                 if (newsigs.dsr_up   == oldsigs.dsr_up   &&
2837                     newsigs.dsr_down == oldsigs.dsr_down &&
2838                     newsigs.dcd_up   == oldsigs.dcd_up   &&
2839                     newsigs.dcd_down == oldsigs.dcd_down &&
2840                     newsigs.cts_up   == oldsigs.cts_up   &&
2841                     newsigs.cts_down == oldsigs.cts_down &&
2842                     newsigs.ri_up    == oldsigs.ri_up    &&
2843                     newsigs.ri_down  == oldsigs.ri_down  &&
2844                     cnow.exithunt    == cprev.exithunt   &&
2845                     cnow.rxidle      == cprev.rxidle) {
2846                         rc = -EIO;
2847                         break;
2848                 }
2849
2850                 events = mask &
2851                         ( (newsigs.dsr_up   != oldsigs.dsr_up   ? MgslEvent_DsrActive:0)   +
2852                         (newsigs.dsr_down != oldsigs.dsr_down ? MgslEvent_DsrInactive:0) +
2853                         (newsigs.dcd_up   != oldsigs.dcd_up   ? MgslEvent_DcdActive:0)   +
2854                         (newsigs.dcd_down != oldsigs.dcd_down ? MgslEvent_DcdInactive:0) +
2855                         (newsigs.cts_up   != oldsigs.cts_up   ? MgslEvent_CtsActive:0)   +
2856                         (newsigs.cts_down != oldsigs.cts_down ? MgslEvent_CtsInactive:0) +
2857                         (newsigs.ri_up    != oldsigs.ri_up    ? MgslEvent_RiActive:0)    +
2858                         (newsigs.ri_down  != oldsigs.ri_down  ? MgslEvent_RiInactive:0)  +
2859                         (cnow.exithunt    != cprev.exithunt   ? MgslEvent_ExitHuntMode:0) +
2860                           (cnow.rxidle      != cprev.rxidle     ? MgslEvent_IdleReceived:0) );
2861                 if (events)
2862                         break;
2863                 
2864                 cprev = cnow;
2865                 oldsigs = newsigs;
2866         }
2867         
2868         remove_wait_queue(&info->event_wait_q, &wait);
2869         set_current_state(TASK_RUNNING);
2870
2871         if (mask & (MgslEvent_ExitHuntMode + MgslEvent_IdleReceived)) {
2872                 spin_lock_irqsave(&info->irq_spinlock,flags);
2873                 if (!waitqueue_active(&info->event_wait_q)) {
2874                         /* disable enable exit hunt mode/idle rcvd IRQs */
2875                         usc_OutReg(info, RICR, usc_InReg(info,RICR) &
2876                                 ~(RXSTATUS_EXITED_HUNT + RXSTATUS_IDLE_RECEIVED));
2877                 }
2878                 spin_unlock_irqrestore(&info->irq_spinlock,flags);
2879         }
2880 exit:
2881         if ( rc == 0 )
2882                 PUT_USER(rc, events, mask_ptr);
2883                 
2884         return rc;
2885         
2886 }       /* end of mgsl_wait_event() */
2887
2888 static int modem_input_wait(struct mgsl_struct *info,int arg)
2889 {
2890         unsigned long flags;
2891         int rc;
2892         struct mgsl_icount cprev, cnow;
2893         DECLARE_WAITQUEUE(wait, current);
2894
2895         /* save current irq counts */
2896         spin_lock_irqsave(&info->irq_spinlock,flags);
2897         cprev = info->icount;
2898         add_wait_queue(&info->status_event_wait_q, &wait);
2899         set_current_state(TASK_INTERRUPTIBLE);
2900         spin_unlock_irqrestore(&info->irq_spinlock,flags);
2901
2902         for(;;) {
2903                 schedule();
2904                 if (signal_pending(current)) {
2905                         rc = -ERESTARTSYS;
2906                         break;
2907                 }
2908
2909                 /* get new irq counts */
2910                 spin_lock_irqsave(&info->irq_spinlock,flags);
2911                 cnow = info->icount;
2912                 set_current_state(TASK_INTERRUPTIBLE);
2913                 spin_unlock_irqrestore(&info->irq_spinlock,flags);
2914
2915                 /* if no change, wait aborted for some reason */
2916                 if (cnow.rng == cprev.rng && cnow.dsr == cprev.dsr &&
2917                     cnow.dcd == cprev.dcd && cnow.cts == cprev.cts) {
2918                         rc = -EIO;
2919                         break;
2920                 }
2921
2922                 /* check for change in caller specified modem input */
2923                 if ((arg & TIOCM_RNG && cnow.rng != cprev.rng) ||
2924                     (arg & TIOCM_DSR && cnow.dsr != cprev.dsr) ||
2925                     (arg & TIOCM_CD  && cnow.dcd != cprev.dcd) ||
2926                     (arg & TIOCM_CTS && cnow.cts != cprev.cts)) {
2927                         rc = 0;
2928                         break;
2929                 }
2930
2931                 cprev = cnow;
2932         }
2933         remove_wait_queue(&info->status_event_wait_q, &wait);
2934         set_current_state(TASK_RUNNING);
2935         return rc;
2936 }
2937
2938 /* return the state of the serial control and status signals
2939  */
2940 static int tiocmget(struct tty_struct *tty, struct file *file)
2941 {
2942         struct mgsl_struct *info = (struct mgsl_struct *)tty->driver_data;
2943         unsigned int result;
2944         unsigned long flags;
2945
2946         spin_lock_irqsave(&info->irq_spinlock,flags);
2947         usc_get_serial_signals(info);
2948         spin_unlock_irqrestore(&info->irq_spinlock,flags);
2949
2950         result = ((info->serial_signals & SerialSignal_RTS) ? TIOCM_RTS:0) +
2951                 ((info->serial_signals & SerialSignal_DTR) ? TIOCM_DTR:0) +
2952                 ((info->serial_signals & SerialSignal_DCD) ? TIOCM_CAR:0) +
2953                 ((info->serial_signals & SerialSignal_RI)  ? TIOCM_RNG:0) +
2954                 ((info->serial_signals & SerialSignal_DSR) ? TIOCM_DSR:0) +
2955                 ((info->serial_signals & SerialSignal_CTS) ? TIOCM_CTS:0);
2956
2957         if (debug_level >= DEBUG_LEVEL_INFO)
2958                 printk("%s(%d):%s tiocmget() value=%08X\n",
2959                          __FILE__,__LINE__, info->device_name, result );
2960         return result;
2961 }
2962
2963 /* set modem control signals (DTR/RTS)
2964  */
2965 static int tiocmset(struct tty_struct *tty, struct file *file,
2966                     unsigned int set, unsigned int clear)
2967 {
2968         struct mgsl_struct *info = (struct mgsl_struct *)tty->driver_data;
2969         unsigned long flags;
2970
2971         if (debug_level >= DEBUG_LEVEL_INFO)
2972                 printk("%s(%d):%s tiocmset(%x,%x)\n",
2973                         __FILE__,__LINE__,info->device_name, set, clear);
2974
2975         if (set & TIOCM_RTS)
2976                 info->serial_signals |= SerialSignal_RTS;
2977         if (set & TIOCM_DTR)
2978                 info->serial_signals |= SerialSignal_DTR;
2979         if (clear & TIOCM_RTS)
2980                 info->serial_signals &= ~SerialSignal_RTS;
2981         if (clear & TIOCM_DTR)
2982                 info->serial_signals &= ~SerialSignal_DTR;
2983
2984         spin_lock_irqsave(&info->irq_spinlock,flags);
2985         usc_set_serial_signals(info);
2986         spin_unlock_irqrestore(&info->irq_spinlock,flags);
2987
2988         return 0;
2989 }
2990
2991 /* mgsl_break()         Set or clear transmit break condition
2992  *
2993  * Arguments:           tty             pointer to tty instance data
2994  *                      break_state     -1=set break condition, 0=clear
2995  * Return Value:        None
2996  */
2997 static void mgsl_break(struct tty_struct *tty, int break_state)
2998 {
2999         struct mgsl_struct * info = (struct mgsl_struct *)tty->driver_data;
3000         unsigned long flags;
3001         
3002         if (debug_level >= DEBUG_LEVEL_INFO)
3003                 printk("%s(%d):mgsl_break(%s,%d)\n",
3004                          __FILE__,__LINE__, info->device_name, break_state);
3005                          
3006         if (mgsl_paranoia_check(info, tty->name, "mgsl_break"))
3007                 return;
3008
3009         spin_lock_irqsave(&info->irq_spinlock,flags);
3010         if (break_state == -1)
3011                 usc_OutReg(info,IOCR,(u16)(usc_InReg(info,IOCR) | BIT7));
3012         else 
3013                 usc_OutReg(info,IOCR,(u16)(usc_InReg(info,IOCR) & ~BIT7));
3014         spin_unlock_irqrestore(&info->irq_spinlock,flags);
3015         
3016 }       /* end of mgsl_break() */
3017
3018 /* mgsl_ioctl() Service an IOCTL request
3019  *      
3020  * Arguments:
3021  * 
3022  *      tty     pointer to tty instance data
3023  *      file    pointer to associated file object for device
3024  *      cmd     IOCTL command code
3025  *      arg     command argument/context
3026  *      
3027  * Return Value:        0 if success, otherwise error code
3028  */
3029 static int mgsl_ioctl(struct tty_struct *tty, struct file * file,
3030                     unsigned int cmd, unsigned long arg)
3031 {
3032         struct mgsl_struct * info = (struct mgsl_struct *)tty->driver_data;
3033         
3034         if (debug_level >= DEBUG_LEVEL_INFO)
3035                 printk("%s(%d):mgsl_ioctl %s cmd=%08X\n", __FILE__,__LINE__,
3036                         info->device_name, cmd );
3037         
3038         if (mgsl_paranoia_check(info, tty->name, "mgsl_ioctl"))
3039                 return -ENODEV;
3040
3041         if ((cmd != TIOCGSERIAL) && (cmd != TIOCSSERIAL) &&
3042             (cmd != TIOCMIWAIT) && (cmd != TIOCGICOUNT)) {
3043                 if (tty->flags & (1 << TTY_IO_ERROR))
3044                     return -EIO;
3045         }
3046
3047         return mgsl_ioctl_common(info, cmd, arg);
3048 }
3049
3050 int mgsl_ioctl_common(struct mgsl_struct *info, unsigned int cmd, unsigned long arg)
3051 {
3052         int error;
3053         struct mgsl_icount cnow;        /* kernel counter temps */
3054         struct serial_icounter_struct *p_cuser; /* user space */
3055         unsigned long flags;
3056         
3057         switch (cmd) {
3058                 case MGSL_IOCGPARAMS:
3059                         return mgsl_get_params(info,(MGSL_PARAMS *)arg);
3060                 case MGSL_IOCSPARAMS:
3061                         return mgsl_set_params(info,(MGSL_PARAMS *)arg);
3062                 case MGSL_IOCGTXIDLE:
3063                         return mgsl_get_txidle(info,(int*)arg);
3064                 case MGSL_IOCSTXIDLE:
3065                         return mgsl_set_txidle(info,(int)arg);
3066                 case MGSL_IOCTXENABLE:
3067                         return mgsl_txenable(info,(int)arg);
3068                 case MGSL_IOCRXENABLE:
3069                         return mgsl_rxenable(info,(int)arg);
3070                 case MGSL_IOCTXABORT:
3071                         return mgsl_txabort(info);
3072                 case MGSL_IOCGSTATS:
3073                         return mgsl_get_stats(info,(struct mgsl_icount*)arg);
3074                 case MGSL_IOCWAITEVENT:
3075                         return mgsl_wait_event(info,(int*)arg);
3076                 case MGSL_IOCLOOPTXDONE:
3077                         return mgsl_loopmode_send_done(info);
3078                 /* Wait for modem input (DCD,RI,DSR,CTS) change
3079                  * as specified by mask in arg (TIOCM_RNG/DSR/CD/CTS)
3080                  */
3081                 case TIOCMIWAIT:
3082                         return modem_input_wait(info,(int)arg);
3083
3084                 /* 
3085                  * Get counter of input serial line interrupts (DCD,RI,DSR,CTS)
3086                  * Return: write counters to the user passed counter struct
3087                  * NB: both 1->0 and 0->1 transitions are counted except for
3088                  *     RI where only 0->1 is counted.
3089                  */
3090                 case TIOCGICOUNT:
3091                         spin_lock_irqsave(&info->irq_spinlock,flags);
3092                         cnow = info->icount;
3093                         spin_unlock_irqrestore(&info->irq_spinlock,flags);
3094                         p_cuser = (struct serial_icounter_struct *) arg;
3095                         PUT_USER(error,cnow.cts, &p_cuser->cts);
3096                         if (error) return error;
3097                         PUT_USER(error,cnow.dsr, &p_cuser->dsr);
3098                         if (error) return error;
3099                         PUT_USER(error,cnow.rng, &p_cuser->rng);
3100                         if (error) return error;
3101                         PUT_USER(error,cnow.dcd, &p_cuser->dcd);
3102                         if (error) return error;
3103                         PUT_USER(error,cnow.rx, &p_cuser->rx);
3104                         if (error) return error;
3105                         PUT_USER(error,cnow.tx, &p_cuser->tx);
3106                         if (error) return error;
3107                         PUT_USER(error,cnow.frame, &p_cuser->frame);
3108                         if (error) return error;
3109                         PUT_USER(error,cnow.overrun, &p_cuser->overrun);
3110                         if (error) return error;
3111                         PUT_USER(error,cnow.parity, &p_cuser->parity);
3112                         if (error) return error;
3113                         PUT_USER(error,cnow.brk, &p_cuser->brk);
3114                         if (error) return error;
3115                         PUT_USER(error,cnow.buf_overrun, &p_cuser->buf_overrun);
3116                         if (error) return error;
3117                         return 0;
3118                 default:
3119                         return -ENOIOCTLCMD;
3120         }
3121         return 0;
3122 }
3123
3124 /* mgsl_set_termios()
3125  * 
3126  *      Set new termios settings
3127  *      
3128  * Arguments:
3129  * 
3130  *      tty             pointer to tty structure
3131  *      termios         pointer to buffer to hold returned old termios
3132  *      
3133  * Return Value:                None
3134  */
3135 static void mgsl_set_termios(struct tty_struct *tty, struct termios *old_termios)
3136 {
3137         struct mgsl_struct *info = (struct mgsl_struct *)tty->driver_data;
3138         unsigned long flags;
3139         
3140         if (debug_level >= DEBUG_LEVEL_INFO)
3141                 printk("%s(%d):mgsl_set_termios %s\n", __FILE__,__LINE__,
3142                         tty->driver->name );
3143         
3144         /* just return if nothing has changed */
3145         if ((tty->termios->c_cflag == old_termios->c_cflag)
3146             && (RELEVANT_IFLAG(tty->termios->c_iflag) 
3147                 == RELEVANT_IFLAG(old_termios->c_iflag)))
3148           return;
3149
3150         mgsl_change_params(info);
3151
3152         /* Handle transition to B0 status */
3153         if (old_termios->c_cflag & CBAUD &&
3154             !(tty->termios->c_cflag & CBAUD)) {
3155                 info->serial_signals &= ~(SerialSignal_RTS + SerialSignal_DTR);
3156                 spin_lock_irqsave(&info->irq_spinlock,flags);
3157                 usc_set_serial_signals(info);
3158                 spin_unlock_irqrestore(&info->irq_spinlock,flags);
3159         }
3160         
3161         /* Handle transition away from B0 status */
3162         if (!(old_termios->c_cflag & CBAUD) &&
3163             tty->termios->c_cflag & CBAUD) {
3164                 info->serial_signals |= SerialSignal_DTR;
3165                 if (!(tty->termios->c_cflag & CRTSCTS) || 
3166                     !test_bit(TTY_THROTTLED, &tty->flags)) {
3167                         info->serial_signals |= SerialSignal_RTS;
3168                 }
3169                 spin_lock_irqsave(&info->irq_spinlock,flags);
3170                 usc_set_serial_signals(info);
3171                 spin_unlock_irqrestore(&info->irq_spinlock,flags);
3172         }
3173         
3174         /* Handle turning off CRTSCTS */
3175         if (old_termios->c_cflag & CRTSCTS &&
3176             !(tty->termios->c_cflag & CRTSCTS)) {
3177                 tty->hw_stopped = 0;
3178                 mgsl_start(tty);
3179         }
3180
3181 }       /* end of mgsl_set_termios() */
3182
3183 /* mgsl_close()
3184  * 
3185  *      Called when port is closed. Wait for remaining data to be
3186  *      sent. Disable port and free resources.
3187  *      
3188  * Arguments:
3189  * 
3190  *      tty     pointer to open tty structure
3191  *      filp    pointer to open file object
3192  *      
3193  * Return Value:        None
3194  */
3195 static void mgsl_close(struct tty_struct *tty, struct file * filp)
3196 {
3197         struct mgsl_struct * info = (struct mgsl_struct *)tty->driver_data;
3198
3199         if (mgsl_paranoia_check(info, tty->name, "mgsl_close"))
3200                 return;
3201         
3202         if (debug_level >= DEBUG_LEVEL_INFO)
3203                 printk("%s(%d):mgsl_close(%s) entry, count=%d\n",
3204                          __FILE__,__LINE__, info->device_name, info->count);
3205                          
3206         if (!info->count)
3207                 return;
3208
3209         if (tty_hung_up_p(filp))
3210                 goto cleanup;
3211                         
3212         if ((tty->count == 1) && (info->count != 1)) {
3213                 /*
3214                  * tty->count is 1 and the tty structure will be freed.
3215                  * info->count should be one in this case.
3216                  * if it's not, correct it so that the port is shutdown.
3217                  */
3218                 printk("mgsl_close: bad refcount; tty->count is 1, "
3219                        "info->count is %d\n", info->count);
3220                 info->count = 1;
3221         }
3222         
3223         info->count--;
3224         
3225         /* if at least one open remaining, leave hardware active */
3226         if (info->count)
3227                 goto cleanup;
3228         
3229         info->flags |= ASYNC_CLOSING;
3230         
3231         /* set tty->closing to notify line discipline to 
3232          * only process XON/XOFF characters. Only the N_TTY
3233          * discipline appears to use this (ppp does not).
3234          */
3235         tty->closing = 1;
3236         
3237         /* wait for transmit data to clear all layers */
3238         
3239         if (info->closing_wait != ASYNC_CLOSING_WAIT_NONE) {
3240                 if (debug_level >= DEBUG_LEVEL_INFO)
3241                         printk("%s(%d):mgsl_close(%s) calling tty_wait_until_sent\n",
3242                                  __FILE__,__LINE__, info->device_name );
3243                 tty_wait_until_sent(tty, info->closing_wait);
3244         }
3245                 
3246         if (info->flags & ASYNC_INITIALIZED)
3247                 mgsl_wait_until_sent(tty, info->timeout);
3248
3249         if (tty->driver->flush_buffer)
3250                 tty->driver->flush_buffer(tty);
3251                 
3252         if (tty->ldisc.flush_buffer)
3253                 tty->ldisc.flush_buffer(tty);
3254                 
3255         shutdown(info);
3256         
3257         tty->closing = 0;
3258         info->tty = 0;
3259         
3260         if (info->blocked_open) {
3261                 if (info->close_delay) {
3262                         set_current_state(TASK_INTERRUPTIBLE);
3263                         schedule_timeout(info->close_delay);
3264                 }
3265                 wake_up_interruptible(&info->open_wait);
3266         }
3267         
3268         info->flags &= ~(ASYNC_NORMAL_ACTIVE|ASYNC_CLOSING);
3269                          
3270         wake_up_interruptible(&info->close_wait);
3271         
3272 cleanup:                        
3273         if (debug_level >= DEBUG_LEVEL_INFO)
3274                 printk("%s(%d):mgsl_close(%s) exit, count=%d\n", __FILE__,__LINE__,
3275                         tty->driver->name, info->count);
3276                         
3277 }       /* end of mgsl_close() */
3278
3279 /* mgsl_wait_until_sent()
3280  *
3281  *      Wait until the transmitter is empty.
3282  *
3283  * Arguments:
3284  *
3285  *      tty             pointer to tty info structure
3286  *      timeout         time to wait for send completion
3287  *
3288  * Return Value:        None
3289  */
3290 static void mgsl_wait_until_sent(struct tty_struct *tty, int timeout)
3291 {
3292         struct mgsl_struct * info = (struct mgsl_struct *)tty->driver_data;
3293         unsigned long orig_jiffies, char_time;
3294
3295         if (!info )
3296                 return;
3297
3298         if (debug_level >= DEBUG_LEVEL_INFO)
3299                 printk("%s(%d):mgsl_wait_until_sent(%s) entry\n",
3300                          __FILE__,__LINE__, info->device_name );
3301       
3302         if (mgsl_paranoia_check(info, tty->name, "mgsl_wait_until_sent"))
3303                 return;
3304
3305         if (!(info->flags & ASYNC_INITIALIZED))
3306                 goto exit;
3307          
3308         orig_jiffies = jiffies;
3309       
3310         /* Set check interval to 1/5 of estimated time to
3311          * send a character, and make it at least 1. The check
3312          * interval should also be less than the timeout.
3313          * Note: use tight timings here to satisfy the NIST-PCTS.
3314          */ 
3315        
3316         if ( info->params.data_rate ) {
3317                 char_time = info->timeout/(32 * 5);
3318                 if (!char_time)
3319                         char_time++;
3320         } else
3321                 char_time = 1;
3322                 
3323         if (timeout)
3324                 char_time = MIN(char_time, timeout);
3325                 
3326         if ( info->params.mode == MGSL_MODE_HDLC ||
3327                 info->params.mode == MGSL_MODE_RAW ) {
3328                 while (info->tx_active) {
3329                         set_current_state(TASK_INTERRUPTIBLE);
3330                         schedule_timeout(char_time);
3331                         if (signal_pending(current))
3332                                 break;
3333                         if (timeout && time_after(jiffies, orig_jiffies + timeout))
3334                                 break;
3335                 }
3336         } else {
3337                 while (!(usc_InReg(info,TCSR) & TXSTATUS_ALL_SENT) &&
3338                         info->tx_enabled) {
3339                         set_current_state(TASK_INTERRUPTIBLE);
3340                         schedule_timeout(char_time);
3341                         if (signal_pending(current))
3342                                 break;
3343                         if (timeout && time_after(jiffies, orig_jiffies + timeout))
3344                                 break;
3345                 }
3346         }
3347       
3348 exit:
3349         if (debug_level >= DEBUG_LEVEL_INFO)
3350                 printk("%s(%d):mgsl_wait_until_sent(%s) exit\n",
3351                          __FILE__,__LINE__, info->device_name );
3352                          
3353 }       /* end of mgsl_wait_until_sent() */
3354
3355 /* mgsl_hangup()
3356  *
3357  *      Called by tty_hangup() when a hangup is signaled.
3358  *      This is the same as to closing all open files for the port.
3359  *
3360  * Arguments:           tty     pointer to associated tty object
3361  * Return Value:        None
3362  */
3363 static void mgsl_hangup(struct tty_struct *tty)
3364 {
3365         struct mgsl_struct * info = (struct mgsl_struct *)tty->driver_data;
3366         
3367         if (debug_level >= DEBUG_LEVEL_INFO)
3368                 printk("%s(%d):mgsl_hangup(%s)\n",
3369                          __FILE__,__LINE__, info->device_name );
3370                          
3371         if (mgsl_paranoia_check(info, tty->name, "mgsl_hangup"))
3372                 return;
3373
3374         mgsl_flush_buffer(tty);
3375         shutdown(info);
3376         
3377         info->count = 0;        
3378         info->flags &= ~ASYNC_NORMAL_ACTIVE;
3379         info->tty = 0;
3380
3381         wake_up_interruptible(&info->open_wait);
3382         
3383 }       /* end of mgsl_hangup() */
3384
3385 /* block_til_ready()
3386  * 
3387  *      Block the current process until the specified port
3388  *      is ready to be opened.
3389  *      
3390  * Arguments:
3391  * 
3392  *      tty             pointer to tty info structure
3393  *      filp            pointer to open file object
3394  *      info            pointer to device instance data
3395  *      
3396  * Return Value:        0 if success, otherwise error code
3397  */
3398 static int block_til_ready(struct tty_struct *tty, struct file * filp,
3399                            struct mgsl_struct *info)
3400 {
3401         DECLARE_WAITQUEUE(wait, current);
3402         int             retval;
3403         int             do_clocal = 0, extra_count = 0;
3404         unsigned long   flags;
3405         
3406         if (debug_level >= DEBUG_LEVEL_INFO)
3407                 printk("%s(%d):block_til_ready on %s\n",
3408                          __FILE__,__LINE__, tty->driver->name );
3409
3410         if (filp->f_flags & O_NONBLOCK || tty->flags & (1 << TTY_IO_ERROR)){
3411                 /* nonblock mode is set or port is not enabled */
3412                 info->flags |= ASYNC_NORMAL_ACTIVE;
3413                 return 0;
3414         }
3415
3416         if (tty->termios->c_cflag & CLOCAL)
3417                 do_clocal = 1;
3418
3419         /* Wait for carrier detect and the line to become
3420          * free (i.e., not in use by the callout).  While we are in
3421          * this loop, info->count is dropped by one, so that
3422          * mgsl_close() knows when to free things.  We restore it upon
3423          * exit, either normal or abnormal.
3424          */
3425          
3426         retval = 0;
3427         add_wait_queue(&info->open_wait, &wait);
3428         
3429         if (debug_level >= DEBUG_LEVEL_INFO)
3430                 printk("%s(%d):block_til_ready before block on %s count=%d\n",
3431                          __FILE__,__LINE__, tty->driver->name, info->count );
3432
3433         spin_lock_irqsave(&info->irq_spinlock, flags);
3434         if (!tty_hung_up_p(filp)) {
3435                 extra_count = 1;
3436                 info->count--;
3437         }
3438         spin_unlock_irqrestore(&info->irq_spinlock, flags);
3439         info->blocked_open++;
3440         
3441         while (1) {
3442                 if (tty->termios->c_cflag & CBAUD) {
3443                         spin_lock_irqsave(&info->irq_spinlock,flags);
3444                         info->serial_signals |= SerialSignal_RTS + SerialSignal_DTR;
3445                         usc_set_serial_signals(info);
3446                         spin_unlock_irqrestore(&info->irq_spinlock,flags);
3447                 }
3448                 
3449                 set_current_state(TASK_INTERRUPTIBLE);
3450                 
3451                 if (tty_hung_up_p(filp) || !(info->flags & ASYNC_INITIALIZED)){
3452                         retval = (info->flags & ASYNC_HUP_NOTIFY) ?
3453                                         -EAGAIN : -ERESTARTSYS;
3454                         break;
3455                 }
3456                 
3457                 spin_lock_irqsave(&info->irq_spinlock,flags);
3458                 usc_get_serial_signals(info);
3459                 spin_unlock_irqrestore(&info->irq_spinlock,flags);
3460                 
3461                 if (!(info->flags & ASYNC_CLOSING) &&
3462                     (do_clocal || (info->serial_signals & SerialSignal_DCD)) ) {
3463                         break;
3464                 }
3465                         
3466                 if (signal_pending(current)) {
3467                         retval = -ERESTARTSYS;
3468                         break;
3469                 }
3470                 
3471                 if (debug_level >= DEBUG_LEVEL_INFO)
3472                         printk("%s(%d):block_til_ready blocking on %s count=%d\n",
3473                                  __FILE__,__LINE__, tty->driver->name, info->count );
3474                                  
3475                 schedule();
3476         }
3477         
3478         set_current_state(TASK_RUNNING);
3479         remove_wait_queue(&info->open_wait, &wait);
3480         
3481         if (extra_count)
3482                 info->count++;
3483         info->blocked_open--;
3484         
3485         if (debug_level >= DEBUG_LEVEL_INFO)
3486                 printk("%s(%d):block_til_ready after blocking on %s count=%d\n",
3487                          __FILE__,__LINE__, tty->driver->name, info->count );
3488                          
3489         if (!retval)
3490                 info->flags |= ASYNC_NORMAL_ACTIVE;
3491                 
3492         return retval;
3493         
3494 }       /* end of block_til_ready() */
3495
3496 /* mgsl_open()
3497  *
3498  *      Called when a port is opened.  Init and enable port.
3499  *      Perform serial-specific initialization for the tty structure.
3500  *
3501  * Arguments:           tty     pointer to tty info structure
3502  *                      filp    associated file pointer
3503  *
3504  * Return Value:        0 if success, otherwise error code
3505  */
3506 static int mgsl_open(struct tty_struct *tty, struct file * filp)
3507 {
3508         struct mgsl_struct      *info;
3509         int                     retval, line;
3510         unsigned long           page;
3511         unsigned long flags;
3512
3513         /* verify range of specified line number */     
3514         line = tty->index;
3515         if ((line < 0) || (line >= mgsl_device_count)) {
3516                 printk("%s(%d):mgsl_open with invalid line #%d.\n",
3517                         __FILE__,__LINE__,line);
3518                 return -ENODEV;
3519         }
3520
3521         /* find the info structure for the specified line */
3522         info = mgsl_device_list;
3523         while(info && info->line != line)
3524                 info = info->next_device;
3525         if (mgsl_paranoia_check(info, tty->name, "mgsl_open"))
3526                 return -ENODEV;
3527         
3528         tty->driver_data = info;
3529         info->tty = tty;
3530                 
3531         if (debug_level >= DEBUG_LEVEL_INFO)
3532                 printk("%s(%d):mgsl_open(%s), old ref count = %d\n",
3533                          __FILE__,__LINE__,tty->driver->name, info->count);
3534
3535         /* If port is closing, signal caller to try again */
3536         if (tty_hung_up_p(filp) || info->flags & ASYNC_CLOSING){
3537                 if (info->flags & ASYNC_CLOSING)
3538                         interruptible_sleep_on(&info->close_wait);
3539                 retval = ((info->flags & ASYNC_HUP_NOTIFY) ?
3540                         -EAGAIN : -ERESTARTSYS);
3541                 goto cleanup;
3542         }
3543         
3544         if (!tmp_buf) {
3545                 page = get_zeroed_page(GFP_KERNEL);
3546                 if (!page) {
3547                         retval = -ENOMEM;
3548                         goto cleanup;
3549                 }
3550                 if (tmp_buf)
3551                         free_page(page);
3552                 else
3553                         tmp_buf = (unsigned char *) page;
3554         }
3555         
3556         info->tty->low_latency = (info->flags & ASYNC_LOW_LATENCY) ? 1 : 0;
3557
3558         spin_lock_irqsave(&info->netlock, flags);
3559         if (info->netcount) {
3560                 retval = -EBUSY;
3561                 spin_unlock_irqrestore(&info->netlock, flags);
3562                 goto cleanup;
3563         }
3564         info->count++;
3565         spin_unlock_irqrestore(&info->netlock, flags);
3566
3567         if (info->count == 1) {
3568                 /* 1st open on this device, init hardware */
3569                 retval = startup(info);
3570                 if (retval < 0)
3571                         goto cleanup;
3572         }
3573
3574         retval = block_til_ready(tty, filp, info);
3575         if (retval) {
3576                 if (debug_level >= DEBUG_LEVEL_INFO)
3577                         printk("%s(%d):block_til_ready(%s) returned %d\n",
3578                                  __FILE__,__LINE__, info->device_name, retval);
3579                 goto cleanup;
3580         }
3581
3582         if (debug_level >= DEBUG_LEVEL_INFO)
3583                 printk("%s(%d):mgsl_open(%s) success\n",
3584                          __FILE__,__LINE__, info->device_name);
3585         retval = 0;
3586         
3587 cleanup:                        
3588         if (retval) {
3589                 if (tty->count == 1)
3590                         info->tty = 0; /* tty layer will release tty struct */
3591                 if(info->count)
3592                         info->count--;
3593         }
3594         
3595         return retval;
3596         
3597 }       /* end of mgsl_open() */
3598
3599 /*
3600  * /proc fs routines....
3601  */
3602
3603 static inline int line_info(char *buf, struct mgsl_struct *info)
3604 {
3605         char    stat_buf[30];
3606         int     ret;
3607         unsigned long flags;
3608
3609         if (info->bus_type == MGSL_BUS_TYPE_PCI) {
3610                 ret = sprintf(buf, "%s:PCI io:%04X irq:%d mem:%08X lcr:%08X",
3611                         info->device_name, info->io_base, info->irq_level,
3612                         info->phys_memory_base, info->phys_lcr_base);
3613         } else {
3614                 ret = sprintf(buf, "%s:(E)ISA io:%04X irq:%d dma:%d",
3615                         info->device_name, info->io_base, 
3616                         info->irq_level, info->dma_level);
3617         }
3618
3619         /* output current serial signal states */
3620         spin_lock_irqsave(&info->irq_spinlock,flags);
3621         usc_get_serial_signals(info);
3622         spin_unlock_irqrestore(&info->irq_spinlock,flags);
3623         
3624         stat_buf[0] = 0;
3625         stat_buf[1] = 0;
3626         if (info->serial_signals & SerialSignal_RTS)
3627                 strcat(stat_buf, "|RTS");
3628         if (info->serial_signals & SerialSignal_CTS)
3629                 strcat(stat_buf, "|CTS");
3630         if (info->serial_signals & SerialSignal_DTR)
3631                 strcat(stat_buf, "|DTR");
3632         if (info->serial_signals & SerialSignal_DSR)
3633                 strcat(stat_buf, "|DSR");
3634         if (info->serial_signals & SerialSignal_DCD)
3635                 strcat(stat_buf, "|CD");
3636         if (info->serial_signals & SerialSignal_RI)
3637                 strcat(stat_buf, "|RI");
3638
3639         if (info->params.mode == MGSL_MODE_HDLC ||
3640             info->params.mode == MGSL_MODE_RAW ) {
3641                 ret += sprintf(buf+ret, " HDLC txok:%d rxok:%d",
3642                               info->icount.txok, info->icount.rxok);
3643                 if (info->icount.txunder)
3644                         ret += sprintf(buf+ret, " txunder:%d", info->icount.txunder);
3645                 if (info->icount.txabort)
3646                         ret += sprintf(buf+ret, " txabort:%d", info->icount.txabort);
3647                 if (info->icount.rxshort)
3648                         ret += sprintf(buf+ret, " rxshort:%d", info->icount.rxshort);   
3649                 if (info->icount.rxlong)
3650                         ret += sprintf(buf+ret, " rxlong:%d", info->icount.rxlong);
3651                 if (info->icount.rxover)
3652                         ret += sprintf(buf+ret, " rxover:%d", info->icount.rxover);
3653                 if (info->icount.rxcrc)
3654                         ret += sprintf(buf+ret, " rxcrc:%d", info->icount.rxcrc);
3655         } else {
3656                 ret += sprintf(buf+ret, " ASYNC tx:%d rx:%d",
3657                               info->icount.tx, info->icount.rx);
3658                 if (info->icount.frame)
3659                         ret += sprintf(buf+ret, " fe:%d", info->icount.frame);
3660                 if (info->icount.parity)
3661                         ret += sprintf(buf+ret, " pe:%d", info->icount.parity);
3662                 if (info->icount.brk)
3663                         ret += sprintf(buf+ret, " brk:%d", info->icount.brk);   
3664                 if (info->icount.overrun)
3665                         ret += sprintf(buf+ret, " oe:%d", info->icount.overrun);
3666         }
3667         
3668         /* Append serial signal status to end */
3669         ret += sprintf(buf+ret, " %s\n", stat_buf+1);
3670         
3671         ret += sprintf(buf+ret, "txactive=%d bh_req=%d bh_run=%d pending_bh=%x\n",
3672          info->tx_active,info->bh_requested,info->bh_running,
3673          info->pending_bh);
3674          
3675         spin_lock_irqsave(&info->irq_spinlock,flags);
3676         {       
3677         u16 Tcsr = usc_InReg( info, TCSR );
3678         u16 Tdmr = usc_InDmaReg( info, TDMR );
3679         u16 Ticr = usc_InReg( info, TICR );
3680         u16 Rscr = usc_InReg( info, RCSR );
3681         u16 Rdmr = usc_InDmaReg( info, RDMR );
3682         u16 Ricr = usc_InReg( info, RICR );
3683         u16 Icr = usc_InReg( info, ICR );
3684         u16 Dccr = usc_InReg( info, DCCR );
3685         u16 Tmr = usc_InReg( info, TMR );
3686         u16 Tccr = usc_InReg( info, TCCR );
3687         u16 Ccar = inw( info->io_base + CCAR );
3688         ret += sprintf(buf+ret, "tcsr=%04X tdmr=%04X ticr=%04X rcsr=%04X rdmr=%04X\n"
3689                         "ricr=%04X icr =%04X dccr=%04X tmr=%04X tccr=%04X ccar=%04X\n",
3690                         Tcsr,Tdmr,Ticr,Rscr,Rdmr,Ricr,Icr,Dccr,Tmr,Tccr,Ccar );
3691         }
3692         spin_unlock_irqrestore(&info->irq_spinlock,flags);
3693         
3694         return ret;
3695         
3696 }       /* end of line_info() */
3697
3698 /* mgsl_read_proc()
3699  * 
3700  * Called to print information about devices
3701  * 
3702  * Arguments:
3703  *      page    page of memory to hold returned info
3704  *      start   
3705  *      off
3706  *      count
3707  *      eof
3708  *      data
3709  *      
3710  * Return Value:
3711  */
3712 int mgsl_read_proc(char *page, char **start, off_t off, int count,
3713                  int *eof, void *data)
3714 {
3715         int len = 0, l;
3716         off_t   begin = 0;
3717         struct mgsl_struct *info;
3718         
3719         len += sprintf(page, "synclink driver:%s\n", driver_version);
3720         
3721         info = mgsl_device_list;
3722         while( info ) {
3723                 l = line_info(page + len, info);
3724                 len += l;
3725                 if (len+begin > off+count)
3726                         goto done;
3727                 if (len+begin < off) {
3728                         begin += len;
3729                         len = 0;
3730                 }
3731                 info = info->next_device;
3732         }
3733
3734         *eof = 1;
3735 done:
3736         if (off >= len+begin)
3737                 return 0;
3738         *start = page + (off-begin);
3739         return ((count < begin+len-off) ? count : begin+len-off);
3740         
3741 }       /* end of mgsl_read_proc() */
3742
3743 /* mgsl_allocate_dma_buffers()
3744  * 
3745  *      Allocate and format DMA buffers (ISA adapter)
3746  *      or format shared memory buffers (PCI adapter).
3747  * 
3748  * Arguments:           info    pointer to device instance data
3749  * Return Value:        0 if success, otherwise error
3750  */
3751 int mgsl_allocate_dma_buffers(struct mgsl_struct *info)
3752 {
3753         unsigned short BuffersPerFrame;
3754
3755         info->last_mem_alloc = 0;
3756
3757         /* Calculate the number of DMA buffers necessary to hold the */
3758         /* largest allowable frame size. Note: If the max frame size is */
3759         /* not an even multiple of the DMA buffer size then we need to */
3760         /* round the buffer count per frame up one. */
3761
3762         BuffersPerFrame = (unsigned short)(info->max_frame_size/DMABUFFERSIZE);
3763         if ( info->max_frame_size % DMABUFFERSIZE )
3764                 BuffersPerFrame++;
3765
3766         if ( info->bus_type == MGSL_BUS_TYPE_PCI ) {
3767                 /*
3768                  * The PCI adapter has 256KBytes of shared memory to use.
3769                  * This is 64 PAGE_SIZE buffers.
3770                  *
3771                  * The first page is used for padding at this time so the
3772                  * buffer list does not begin at offset 0 of the PCI
3773                  * adapter's shared memory.
3774                  *
3775                  * The 2nd page is used for the buffer list. A 4K buffer
3776                  * list can hold 128 DMA_BUFFER structures at 32 bytes
3777                  * each.
3778                  *
3779                  * This leaves 62 4K pages.
3780                  *
3781                  * The next N pages are used for transmit frame(s). We
3782                  * reserve enough 4K page blocks to hold the required
3783                  * number of transmit dma buffers (num_tx_dma_buffers),
3784                  * each of MaxFrameSize size.
3785                  *
3786                  * Of the remaining pages (62-N), determine how many can
3787                  * be used to receive full MaxFrameSize inbound frames
3788                  */
3789                 info->tx_buffer_count = info->num_tx_dma_buffers * BuffersPerFrame;
3790                 info->rx_buffer_count = 62 - info->tx_buffer_count;
3791         } else {
3792                 /* Calculate the number of PAGE_SIZE buffers needed for */
3793                 /* receive and transmit DMA buffers. */
3794
3795
3796                 /* Calculate the number of DMA buffers necessary to */
3797                 /* hold 7 max size receive frames and one max size transmit frame. */
3798                 /* The receive buffer count is bumped by one so we avoid an */
3799                 /* End of List condition if all receive buffers are used when */
3800                 /* using linked list DMA buffers. */
3801
3802                 info->tx_buffer_count = info->num_tx_dma_buffers * BuffersPerFrame;
3803                 info->rx_buffer_count = (BuffersPerFrame * MAXRXFRAMES) + 6;
3804                 
3805                 /* 
3806                  * limit total TxBuffers & RxBuffers to 62 4K total 
3807                  * (ala PCI Allocation) 
3808                  */
3809                 
3810                 if ( (info->tx_buffer_count + info->rx_buffer_count) > 62 )
3811                         info->rx_buffer_count = 62 - info->tx_buffer_count;
3812
3813         }
3814
3815         if ( debug_level >= DEBUG_LEVEL_INFO )
3816                 printk("%s(%d):Allocating %d TX and %d RX DMA buffers.\n",
3817                         __FILE__,__LINE__, info->tx_buffer_count,info->rx_buffer_count);
3818         
3819         if ( mgsl_alloc_buffer_list_memory( info ) < 0 ||
3820                   mgsl_alloc_frame_memory(info, info->rx_buffer_list, info->rx_buffer_count) < 0 || 
3821                   mgsl_alloc_frame_memory(info, info->tx_buffer_list, info->tx_buffer_count) < 0 || 
3822                   mgsl_alloc_intermediate_rxbuffer_memory(info) < 0  ||
3823                   mgsl_alloc_intermediate_txbuffer_memory(info) < 0 ) {
3824                 printk("%s(%d):Can't allocate DMA buffer memory\n",__FILE__,__LINE__);
3825                 return -ENOMEM;
3826         }
3827         
3828         mgsl_reset_rx_dma_buffers( info );
3829         mgsl_reset_tx_dma_buffers( info );
3830
3831         return 0;
3832
3833 }       /* end of mgsl_allocate_dma_buffers() */
3834
3835 /*
3836  * mgsl_alloc_buffer_list_memory()
3837  * 
3838  * Allocate a common DMA buffer for use as the
3839  * receive and transmit buffer lists.
3840  * 
3841  * A buffer list is a set of buffer entries where each entry contains
3842  * a pointer to an actual buffer and a pointer to the next buffer entry
3843  * (plus some other info about the buffer).
3844  * 
3845  * The buffer entries for a list are built to form a circular list so
3846  * that when the entire list has been traversed you start back at the
3847  * beginning.
3848  * 
3849  * This function allocates memory for just the buffer entries.
3850  * The links (pointer to next entry) are filled in with the physical
3851  * address of the next entry so the adapter can navigate the list
3852  * using bus master DMA. The pointers to the actual buffers are filled
3853  * out later when the actual buffers are allocated.
3854  * 
3855  * Arguments:           info    pointer to device instance data
3856  * Return Value:        0 if success, otherwise error
3857  */
3858 int mgsl_alloc_buffer_list_memory( struct mgsl_struct *info )
3859 {
3860         unsigned int i;
3861
3862         if ( info->bus_type == MGSL_BUS_TYPE_PCI ) {
3863                 /* PCI adapter uses shared memory. */
3864                 info->buffer_list = info->memory_base + info->last_mem_alloc;
3865                 info->buffer_list_phys = info->last_mem_alloc;
3866                 info->last_mem_alloc += BUFFERLISTSIZE;
3867         } else {
3868                 /* ISA adapter uses system memory. */
3869                 /* The buffer lists are allocated as a common buffer that both */
3870                 /* the processor and adapter can access. This allows the driver to */
3871                 /* inspect portions of the buffer while other portions are being */
3872                 /* updated by the adapter using Bus Master DMA. */
3873
3874                 info->buffer_list = kmalloc(BUFFERLISTSIZE, GFP_KERNEL | GFP_DMA);
3875                 if ( info->buffer_list == NULL )
3876                         return -ENOMEM;
3877                         
3878                 info->buffer_list_phys = isa_virt_to_bus(info->buffer_list);
3879         }
3880
3881         /* We got the memory for the buffer entry lists. */
3882         /* Initialize the memory block to all zeros. */
3883         memset( info->buffer_list, 0, BUFFERLISTSIZE );
3884
3885         /* Save virtual address pointers to the receive and */
3886         /* transmit buffer lists. (Receive 1st). These pointers will */
3887         /* be used by the processor to access the lists. */
3888         info->rx_buffer_list = (DMABUFFERENTRY *)info->buffer_list;
3889         info->tx_buffer_list = (DMABUFFERENTRY *)info->buffer_list;
3890         info->tx_buffer_list += info->rx_buffer_count;
3891
3892         /*
3893          * Build the links for the buffer entry lists such that
3894          * two circular lists are built. (Transmit and Receive).
3895          *
3896          * Note: the links are physical addresses
3897          * which are read by the adapter to determine the next
3898          * buffer entry to use.
3899          */
3900
3901         for ( i = 0; i < info->rx_buffer_count; i++ ) {
3902                 /* calculate and store physical address of this buffer entry */
3903                 info->rx_buffer_list[i].phys_entry =
3904                         info->buffer_list_phys + (i * sizeof(DMABUFFERENTRY));
3905
3906                 /* calculate and store physical address of */
3907                 /* next entry in cirular list of entries */
3908
3909                 info->rx_buffer_list[i].link = info->buffer_list_phys;
3910
3911                 if ( i < info->rx_buffer_count - 1 )
3912                         info->rx_buffer_list[i].link += (i + 1) * sizeof(DMABUFFERENTRY);
3913         }
3914
3915         for ( i = 0; i < info->tx_buffer_count; i++ ) {
3916                 /* calculate and store physical address of this buffer entry */
3917                 info->tx_buffer_list[i].phys_entry = info->buffer_list_phys +
3918                         ((info->rx_buffer_count + i) * sizeof(DMABUFFERENTRY));
3919
3920                 /* calculate and store physical address of */
3921                 /* next entry in cirular list of entries */
3922
3923                 info->tx_buffer_list[i].link = info->buffer_list_phys +
3924                         info->rx_buffer_count * sizeof(DMABUFFERENTRY);
3925
3926                 if ( i < info->tx_buffer_count - 1 )
3927                         info->tx_buffer_list[i].link += (i + 1) * sizeof(DMABUFFERENTRY);
3928         }
3929
3930         return 0;
3931
3932 }       /* end of mgsl_alloc_buffer_list_memory() */
3933
3934 /* Free DMA buffers allocated for use as the
3935  * receive and transmit buffer lists.
3936  * Warning:
3937  * 
3938  *      The data transfer buffers associated with the buffer list
3939  *      MUST be freed before freeing the buffer list itself because
3940  *      the buffer list contains the information necessary to free
3941  *      the individual buffers!
3942  */
3943 void mgsl_free_buffer_list_memory( struct mgsl_struct *info )
3944 {
3945         if ( info->buffer_list && info->bus_type != MGSL_BUS_TYPE_PCI )
3946                 kfree(info->buffer_list);
3947                 
3948         info->buffer_list = NULL;
3949         info->rx_buffer_list = NULL;
3950         info->tx_buffer_list = NULL;
3951
3952 }       /* end of mgsl_free_buffer_list_memory() */
3953
3954 /*
3955  * mgsl_alloc_frame_memory()
3956  * 
3957  *      Allocate the frame DMA buffers used by the specified buffer list.
3958  *      Each DMA buffer will be one memory page in size. This is necessary
3959  *      because memory can fragment enough that it may be impossible
3960  *      contiguous pages.
3961  * 
3962  * Arguments:
3963  * 
3964  *      info            pointer to device instance data
3965  *      BufferList      pointer to list of buffer entries
3966  *      Buffercount     count of buffer entries in buffer list
3967  * 
3968  * Return Value:        0 if success, otherwise -ENOMEM
3969  */
3970 int mgsl_alloc_frame_memory(struct mgsl_struct *info,DMABUFFERENTRY *BufferList,int Buffercount)
3971 {
3972         int i;
3973         unsigned long phys_addr;
3974
3975         /* Allocate page sized buffers for the receive buffer list */
3976
3977         for ( i = 0; i < Buffercount; i++ ) {
3978                 if ( info->bus_type == MGSL_BUS_TYPE_PCI ) {
3979                         /* PCI adapter uses shared memory buffers. */
3980                         BufferList[i].virt_addr = info->memory_base + info->last_mem_alloc;
3981                         phys_addr = info->last_mem_alloc;
3982                         info->last_mem_alloc += DMABUFFERSIZE;
3983                 } else {
3984                         /* ISA adapter uses system memory. */
3985                         BufferList[i].virt_addr = 
3986                                 kmalloc(DMABUFFERSIZE, GFP_KERNEL | GFP_DMA);
3987                         if ( BufferList[i].virt_addr == NULL )
3988                                 return -ENOMEM;
3989                         phys_addr = isa_virt_to_bus(BufferList[i].virt_addr);
3990                 }
3991                 BufferList[i].phys_addr = phys_addr;
3992         }
3993
3994         return 0;
3995
3996 }       /* end of mgsl_alloc_frame_memory() */
3997
3998 /*
3999  * mgsl_free_frame_memory()
4000  * 
4001  *      Free the buffers associated with
4002  *      each buffer entry of a buffer list.
4003  * 
4004  * Arguments:
4005  * 
4006  *      info            pointer to device instance data
4007  *      BufferList      pointer to list of buffer entries
4008  *      Buffercount     count of buffer entries in buffer list
4009  * 
4010  * Return Value:        None
4011  */
4012 void mgsl_free_frame_memory(struct mgsl_struct *info, DMABUFFERENTRY *BufferList, int Buffercount)
4013 {
4014         int i;
4015
4016         if ( BufferList ) {
4017                 for ( i = 0 ; i < Buffercount ; i++ ) {
4018                         if ( BufferList[i].virt_addr ) {
4019                                 if ( info->bus_type != MGSL_BUS_TYPE_PCI )
4020                                         kfree(BufferList[i].virt_addr);
4021                                 BufferList[i].virt_addr = NULL;
4022                         }
4023                 }
4024         }
4025
4026 }       /* end of mgsl_free_frame_memory() */
4027
4028 /* mgsl_free_dma_buffers()
4029  * 
4030  *      Free DMA buffers
4031  *      
4032  * Arguments:           info    pointer to device instance data
4033  * Return Value:        None
4034  */
4035 void mgsl_free_dma_buffers( struct mgsl_struct *info )
4036 {
4037         mgsl_free_frame_memory( info, info->rx_buffer_list, info->rx_buffer_count );
4038         mgsl_free_frame_memory( info, info->tx_buffer_list, info->tx_buffer_count );
4039         mgsl_free_buffer_list_memory( info );
4040
4041 }       /* end of mgsl_free_dma_buffers() */
4042
4043
4044 /*
4045  * mgsl_alloc_intermediate_rxbuffer_memory()
4046  * 
4047  *      Allocate a buffer large enough to hold max_frame_size. This buffer
4048  *      is used to pass an assembled frame to the line discipline.
4049  * 
4050  * Arguments:
4051  * 
4052  *      info            pointer to device instance data
4053  * 
4054  * Return Value:        0 if success, otherwise -ENOMEM
4055  */
4056 int mgsl_alloc_intermediate_rxbuffer_memory(struct mgsl_struct *info)
4057 {
4058         info->intermediate_rxbuffer = kmalloc(info->max_frame_size, GFP_KERNEL | GFP_DMA);
4059         if ( info->intermediate_rxbuffer == NULL )
4060                 return -ENOMEM;
4061
4062         return 0;
4063
4064 }       /* end of mgsl_alloc_intermediate_rxbuffer_memory() */
4065
4066 /*
4067  * mgsl_free_intermediate_rxbuffer_memory()
4068  * 
4069  * 
4070  * Arguments:
4071  * 
4072  *      info            pointer to device instance data
4073  * 
4074  * Return Value:        None
4075  */
4076 void mgsl_free_intermediate_rxbuffer_memory(struct mgsl_struct *info)
4077 {
4078         if ( info->intermediate_rxbuffer )
4079                 kfree(info->intermediate_rxbuffer);
4080
4081         info->intermediate_rxbuffer = NULL;
4082
4083 }       /* end of mgsl_free_intermediate_rxbuffer_memory() */
4084
4085 /*
4086  * mgsl_alloc_intermediate_txbuffer_memory()
4087  *
4088  *      Allocate intermdiate transmit buffer(s) large enough to hold max_frame_size.
4089  *      This buffer is used to load transmit frames into the adapter's dma transfer
4090  *      buffers when there is sufficient space.
4091  *
4092  * Arguments:
4093  *
4094  *      info            pointer to device instance data
4095  *
4096  * Return Value:        0 if success, otherwise -ENOMEM
4097  */
4098 int mgsl_alloc_intermediate_txbuffer_memory(struct mgsl_struct *info)
4099 {
4100         int i;
4101
4102         if ( debug_level >= DEBUG_LEVEL_INFO )
4103                 printk("%s %s(%d)  allocating %d tx holding buffers\n",
4104                                 info->device_name, __FILE__,__LINE__,info->num_tx_holding_buffers);
4105
4106         memset(info->tx_holding_buffers,0,sizeof(info->tx_holding_buffers));
4107
4108         for ( i=0; i<info->num_tx_holding_buffers; ++i) {
4109                 info->tx_holding_buffers[i].buffer =
4110                         kmalloc(info->max_frame_size, GFP_KERNEL);
4111                 if ( info->tx_holding_buffers[i].buffer == NULL )
4112                         return -ENOMEM;
4113         }
4114
4115         return 0;
4116
4117 }       /* end of mgsl_alloc_intermediate_txbuffer_memory() */
4118
4119 /*
4120  * mgsl_free_intermediate_txbuffer_memory()
4121  *
4122  *
4123  * Arguments:
4124  *
4125  *      info            pointer to device instance data
4126  *
4127  * Return Value:        None
4128  */
4129 void mgsl_free_intermediate_txbuffer_memory(struct mgsl_struct *info)
4130 {
4131         int i;
4132
4133         for ( i=0; i<info->num_tx_holding_buffers; ++i ) {
4134                 if ( info->tx_holding_buffers[i].buffer ) {
4135                                 kfree(info->tx_holding_buffers[i].buffer);
4136                                 info->tx_holding_buffers[i].buffer=NULL;
4137                 }
4138         }
4139
4140         info->get_tx_holding_index = 0;
4141         info->put_tx_holding_index = 0;
4142         info->tx_holding_count = 0;
4143
4144 }       /* end of mgsl_free_intermediate_txbuffer_memory() */
4145
4146
4147 /*
4148  * load_next_tx_holding_buffer()
4149  *
4150  * attempts to load the next buffered tx request into the
4151  * tx dma buffers
4152  *
4153  * Arguments:
4154  *
4155  *      info            pointer to device instance data
4156  *
4157  * Return Value:        1 if next buffered tx request loaded
4158  *                      into adapter's tx dma buffer,
4159  *                      0 otherwise
4160  */
4161 int load_next_tx_holding_buffer(struct mgsl_struct *info)
4162 {
4163         int ret = 0;
4164
4165         if ( info->tx_holding_count ) {
4166                 /* determine if we have enough tx dma buffers
4167                  * to accommodate the next tx frame
4168                  */
4169                 struct tx_holding_buffer *ptx =
4170                         &info->tx_holding_buffers[info->get_tx_holding_index];
4171                 int num_free = num_free_tx_dma_buffers(info);
4172                 int num_needed = ptx->buffer_size / DMABUFFERSIZE;
4173                 if ( ptx->buffer_size % DMABUFFERSIZE )
4174                         ++num_needed;
4175
4176                 if (num_needed <= num_free) {
4177                         info->xmit_cnt = ptx->buffer_size;
4178                         mgsl_load_tx_dma_buffer(info,ptx->buffer,ptx->buffer_size);
4179
4180                         --info->tx_holding_count;
4181                         if ( ++info->get_tx_holding_index >= info->num_tx_holding_buffers)
4182                                 info->get_tx_holding_index=0;
4183
4184                         /* restart transmit timer */
4185                         mod_timer(&info->tx_timer, jiffies + jiffies_from_ms(5000));
4186
4187                         ret = 1;
4188                 }
4189         }
4190
4191         return ret;
4192 }
4193
4194 /*
4195  * save_tx_buffer_request()
4196  *
4197  * attempt to store transmit frame request for later transmission
4198  *
4199  * Arguments:
4200  *
4201  *      info            pointer to device instance data
4202  *      Buffer          pointer to buffer containing frame to load
4203  *      BufferSize      size in bytes of frame in Buffer
4204  *
4205  * Return Value:        1 if able to store, 0 otherwise
4206  */
4207 int save_tx_buffer_request(struct mgsl_struct *info,const char *Buffer, unsigned int BufferSize)
4208 {
4209         struct tx_holding_buffer *ptx;
4210
4211         if ( info->tx_holding_count >= info->num_tx_holding_buffers ) {
4212                 return 0;               /* all buffers in use */
4213         }
4214
4215         ptx = &info->tx_holding_buffers[info->put_tx_holding_index];
4216         ptx->buffer_size = BufferSize;
4217         memcpy( ptx->buffer, Buffer, BufferSize);
4218
4219         ++info->tx_holding_count;
4220         if ( ++info->put_tx_holding_index >= info->num_tx_holding_buffers)
4221                 info->put_tx_holding_index=0;
4222
4223         return 1;
4224 }
4225
4226 int mgsl_claim_resources(struct mgsl_struct *info)
4227 {
4228         if (request_region(info->io_base,info->io_addr_size,"synclink") == NULL) {
4229                 printk( "%s(%d):I/O address conflict on device %s Addr=%08X\n",
4230                         __FILE__,__LINE__,info->device_name, info->io_base);
4231                 return -ENODEV;
4232         }
4233         info->io_addr_requested = 1;
4234         
4235         if ( request_irq(info->irq_level,mgsl_interrupt,info->irq_flags,
4236                 info->device_name, info ) < 0 ) {
4237                 printk( "%s(%d):Cant request interrupt on device %s IRQ=%d\n",
4238                         __FILE__,__LINE__,info->device_name, info->irq_level );
4239                 goto errout;
4240         }
4241         info->irq_requested = 1;
4242         
4243         if ( info->bus_type == MGSL_BUS_TYPE_PCI ) {
4244                 if (request_mem_region(info->phys_memory_base,0x40000,"synclink") == NULL) {
4245                         printk( "%s(%d):mem addr conflict device %s Addr=%08X\n",
4246                                 __FILE__,__LINE__,info->device_name, info->phys_memory_base);
4247                         goto errout;
4248                 }
4249                 info->shared_mem_requested = 1;
4250                 if (request_mem_region(info->phys_lcr_base + info->lcr_offset,128,"synclink") == NULL) {
4251                         printk( "%s(%d):lcr mem addr conflict device %s Addr=%08X\n",
4252                                 __FILE__,__LINE__,info->device_name, info->phys_lcr_base + info->lcr_offset);
4253                         goto errout;
4254                 }
4255                 info->lcr_mem_requested = 1;
4256
4257                 info->memory_base = ioremap(info->phys_memory_base,0x40000);
4258                 if (!info->memory_base) {
4259                         printk( "%s(%d):Cant map shared memory on device %s MemAddr=%08X\n",
4260                                 __FILE__,__LINE__,info->device_name, info->phys_memory_base );
4261                         goto errout;
4262                 }
4263                 
4264                 if ( !mgsl_memory_test(info) ) {
4265                         printk( "%s(%d):Failed shared memory test %s MemAddr=%08X\n",
4266                                 __FILE__,__LINE__,info->device_name, info->phys_memory_base );
4267                         goto errout;
4268                 }
4269                 
4270                 info->lcr_base = ioremap(info->phys_lcr_base,PAGE_SIZE) + info->lcr_offset;
4271                 if (!info->lcr_base) {
4272                         printk( "%s(%d):Cant map LCR memory on device %s MemAddr=%08X\n",
4273                                 __FILE__,__LINE__,info->device_name, info->phys_lcr_base );
4274                         goto errout;
4275                 }
4276                 
4277         } else {
4278                 /* claim DMA channel */
4279                 
4280                 if (request_dma(info->dma_level,info->device_name) < 0){
4281                         printk( "%s(%d):Cant request DMA channel on device %s DMA=%d\n",
4282                                 __FILE__,__LINE__,info->device_name, info->dma_level );
4283                         mgsl_release_resources( info );
4284                         return -ENODEV;
4285                 }
4286                 info->dma_requested = 1;
4287
4288                 /* ISA adapter uses bus master DMA */           
4289                 set_dma_mode(info->dma_level,DMA_MODE_CASCADE);
4290                 enable_dma(info->dma_level);
4291         }
4292         
4293         if ( mgsl_allocate_dma_buffers(info) < 0 ) {
4294                 printk( "%s(%d):Cant allocate DMA buffers on device %s DMA=%d\n",
4295                         __FILE__,__LINE__,info->device_name, info->dma_level );
4296                 goto errout;
4297         }       
4298         
4299         return 0;
4300 errout:
4301         mgsl_release_resources(info);
4302         return -ENODEV;
4303
4304 }       /* end of mgsl_claim_resources() */
4305
4306 void mgsl_release_resources(struct mgsl_struct *info)
4307 {
4308         if ( debug_level >= DEBUG_LEVEL_INFO )
4309                 printk( "%s(%d):mgsl_release_resources(%s) entry\n",
4310                         __FILE__,__LINE__,info->device_name );
4311                         
4312         if ( info->irq_requested ) {
4313                 free_irq(info->irq_level, info);
4314                 info->irq_requested = 0;
4315         }
4316         if ( info->dma_requested ) {
4317                 disable_dma(info->dma_level);
4318                 free_dma(info->dma_level);
4319                 info->dma_requested = 0;
4320         }
4321         mgsl_free_dma_buffers(info);
4322         mgsl_free_intermediate_rxbuffer_memory(info);
4323         mgsl_free_intermediate_txbuffer_memory(info);
4324         
4325         if ( info->io_addr_requested ) {
4326                 release_region(info->io_base,info->io_addr_size);
4327                 info->io_addr_requested = 0;
4328         }
4329         if ( info->shared_mem_requested ) {
4330                 release_mem_region(info->phys_memory_base,0x40000);
4331                 info->shared_mem_requested = 0;
4332         }
4333         if ( info->lcr_mem_requested ) {
4334                 release_mem_region(info->phys_lcr_base + info->lcr_offset,128);
4335                 info->lcr_mem_requested = 0;
4336         }
4337         if (info->memory_base){
4338                 iounmap(info->memory_base);
4339                 info->memory_base = 0;
4340         }
4341         if (info->lcr_base){
4342                 iounmap(info->lcr_base - info->lcr_offset);
4343                 info->lcr_base = 0;
4344         }
4345         
4346         if ( debug_level >= DEBUG_LEVEL_INFO )
4347                 printk( "%s(%d):mgsl_release_resources(%s) exit\n",
4348                         __FILE__,__LINE__,info->device_name );
4349                         
4350 }       /* end of mgsl_release_resources() */
4351
4352 /* mgsl_add_device()
4353  * 
4354  *      Add the specified device instance data structure to the
4355  *      global linked list of devices and increment the device count.
4356  *      
4357  * Arguments:           info    pointer to device instance data
4358  * Return Value:        None
4359  */
4360 void mgsl_add_device( struct mgsl_struct *info )
4361 {
4362         info->next_device = NULL;
4363         info->line = mgsl_device_count;
4364         sprintf(info->device_name,"ttySL%d",info->line);
4365         
4366         if (info->line < MAX_TOTAL_DEVICES) {
4367                 if (maxframe[info->line])
4368                         info->max_frame_size = maxframe[info->line];
4369                 info->dosyncppp = dosyncppp[info->line];
4370
4371                 if (txdmabufs[info->line]) {
4372                         info->num_tx_dma_buffers = txdmabufs[info->line];
4373                         if (info->num_tx_dma_buffers < 1)
4374                                 info->num_tx_dma_buffers = 1;
4375                 }
4376
4377                 if (txholdbufs[info->line]) {
4378                         info->num_tx_holding_buffers = txholdbufs[info->line];
4379                         if (info->num_tx_holding_buffers < 1)
4380                                 info->num_tx_holding_buffers = 1;
4381                         else if (info->num_tx_holding_buffers > MAX_TX_HOLDING_BUFFERS)
4382                                 info->num_tx_holding_buffers = MAX_TX_HOLDING_BUFFERS;
4383                 }
4384         }
4385
4386         mgsl_device_count++;
4387         
4388         if ( !mgsl_device_list )
4389                 mgsl_device_list = info;
4390         else {  
4391                 struct mgsl_struct *current_dev = mgsl_device_list;
4392                 while( current_dev->next_device )
4393                         current_dev = current_dev->next_device;
4394                 current_dev->next_device = info;
4395         }
4396         
4397         if ( info->max_frame_size < 4096 )
4398                 info->max_frame_size = 4096;
4399         else if ( info->max_frame_size > 65535 )
4400                 info->max_frame_size = 65535;
4401         
4402         if ( info->bus_type == MGSL_BUS_TYPE_PCI ) {
4403                 printk( "SyncLink PCI v%d %s: IO=%04X IRQ=%d Mem=%08X,%08X MaxFrameSize=%u\n",
4404                         info->hw_version + 1, info->device_name, info->io_base, info->irq_level,
4405                         info->phys_memory_base, info->phys_lcr_base,
4406                         info->max_frame_size );
4407         } else {
4408                 printk( "SyncLink ISA %s: IO=%04X IRQ=%d DMA=%d MaxFrameSize=%u\n",
4409                         info->device_name, info->io_base, info->irq_level, info->dma_level,
4410                         info->max_frame_size );
4411         }
4412
4413 #ifdef CONFIG_SYNCLINK_SYNCPPP
4414 #ifdef MODULE
4415         if (info->dosyncppp)
4416 #endif
4417                 mgsl_sppp_init(info);
4418 #endif
4419 }       /* end of mgsl_add_device() */
4420
4421 /* mgsl_allocate_device()
4422  * 
4423  *      Allocate and initialize a device instance structure
4424  *      
4425  * Arguments:           none
4426  * Return Value:        pointer to mgsl_struct if success, otherwise NULL
4427  */
4428 struct mgsl_struct* mgsl_allocate_device()
4429 {
4430         struct mgsl_struct *info;
4431         
4432         info = (struct mgsl_struct *)kmalloc(sizeof(struct mgsl_struct),
4433                  GFP_KERNEL);
4434                  
4435         if (!info) {
4436                 printk("Error can't allocate device instance data\n");
4437         } else {
4438                 memset(info, 0, sizeof(struct mgsl_struct));
4439                 info->magic = MGSL_MAGIC;
4440                 INIT_WORK(&info->task, mgsl_bh_handler, info);
4441                 info->max_frame_size = 4096;
4442                 info->close_delay = 5*HZ/10;
4443                 info->closing_wait = 30*HZ;
4444                 init_waitqueue_head(&info->open_wait);
4445                 init_waitqueue_head(&info->close_wait);
4446                 init_waitqueue_head(&info->status_event_wait_q);
4447                 init_waitqueue_head(&info->event_wait_q);
4448                 spin_lock_init(&info->irq_spinlock);
4449                 spin_lock_init(&info->netlock);
4450                 memcpy(&info->params,&default_params,sizeof(MGSL_PARAMS));
4451                 info->idle_mode = HDLC_TXIDLE_FLAGS;            
4452                 info->num_tx_dma_buffers = 1;
4453                 info->num_tx_holding_buffers = 0;
4454         }
4455         
4456         return info;
4457
4458 }       /* end of mgsl_allocate_device()*/
4459
4460 static struct tty_operations mgsl_ops = {
4461         .open = mgsl_open,
4462         .close = mgsl_close,
4463         .write = mgsl_write,
4464         .put_char = mgsl_put_char,
4465         .flush_chars = mgsl_flush_chars,
4466         .write_room = mgsl_write_room,
4467         .chars_in_buffer = mgsl_chars_in_buffer,
4468         .flush_buffer = mgsl_flush_buffer,
4469         .ioctl = mgsl_ioctl,
4470         .throttle = mgsl_throttle,
4471         .unthrottle = mgsl_unthrottle,
4472         .send_xchar = mgsl_send_xchar,
4473         .break_ctl = mgsl_break,
4474         .wait_until_sent = mgsl_wait_until_sent,
4475         .read_proc = mgsl_read_proc,
4476         .set_termios = mgsl_set_termios,
4477         .stop = mgsl_stop,
4478         .start = mgsl_start,
4479         .hangup = mgsl_hangup,
4480         .tiocmget = tiocmget,
4481         .tiocmset = tiocmset,
4482 };
4483
4484 /*
4485  * perform tty device initialization
4486  */
4487 int mgsl_init_tty(void);
4488 int mgsl_init_tty()
4489 {
4490         serial_driver = alloc_tty_driver(mgsl_device_count);
4491         if (!serial_driver)
4492                 return -ENOMEM;
4493         
4494         serial_driver->owner = THIS_MODULE;
4495         serial_driver->driver_name = "synclink";
4496         serial_driver->name = "ttySL";
4497         serial_driver->major = ttymajor;
4498         serial_driver->minor_start = 64;
4499         serial_driver->type = TTY_DRIVER_TYPE_SERIAL;
4500         serial_driver->subtype = SERIAL_TYPE_NORMAL;
4501         serial_driver->init_termios = tty_std_termios;
4502         serial_driver->init_termios.c_cflag =
4503                 B9600 | CS8 | CREAD | HUPCL | CLOCAL;
4504         serial_driver->flags = TTY_DRIVER_REAL_RAW;
4505         tty_set_operations(serial_driver, &mgsl_ops);
4506         if (tty_register_driver(serial_driver) < 0)
4507                 printk("%s(%d):Couldn't register serial driver\n",
4508                         __FILE__,__LINE__);
4509                         
4510         printk("%s %s, tty major#%d\n",
4511                 driver_name, driver_version,
4512                 serial_driver->major);
4513         return 0;
4514 }
4515
4516 /* enumerate user specified ISA adapters
4517  */
4518 int mgsl_enum_isa_devices()
4519 {
4520         struct mgsl_struct *info;
4521         int i;
4522                 
4523         /* Check for user specified ISA devices */
4524         
4525         for (i=0 ;(i < MAX_ISA_DEVICES) && io[i] && irq[i]; i++){
4526                 if ( debug_level >= DEBUG_LEVEL_INFO )
4527                         printk("ISA device specified io=%04X,irq=%d,dma=%d\n",
4528                                 io[i], irq[i], dma[i] );
4529                 
4530                 info = mgsl_allocate_device();
4531                 if ( !info ) {
4532                         /* error allocating device instance data */
4533                         if ( debug_level >= DEBUG_LEVEL_ERROR )
4534                                 printk( "can't allocate device instance data.\n");
4535                         continue;
4536                 }
4537                 
4538                 /* Copy user configuration info to device instance data */
4539                 info->io_base = (unsigned int)io[i];
4540                 info->irq_level = (unsigned int)irq[i];
4541                 info->irq_level = irq_canonicalize(info->irq_level);
4542                 info->dma_level = (unsigned int)dma[i];
4543                 info->bus_type = MGSL_BUS_TYPE_ISA;
4544                 info->io_addr_size = 16;
4545                 info->irq_flags = 0;
4546                 
4547                 mgsl_add_device( info );
4548         }
4549         
4550         return 0;
4551 }
4552
4553 /* mgsl_init()
4554  * 
4555  *      Driver initialization entry point.
4556  *      
4557  * Arguments:   None
4558  * Return Value:        0 if success, otherwise error code
4559  */
4560 int __init mgsl_init(void)
4561 {
4562         int rc;
4563
4564         printk("%s %s\n", driver_name, driver_version);
4565         
4566         mgsl_enum_isa_devices();
4567         pci_register_driver(&synclink_pci_driver);
4568
4569         if ( !mgsl_device_list ) {
4570                 printk("%s(%d):No SyncLink devices found.\n",__FILE__,__LINE__);
4571                 return -ENODEV;
4572         }
4573         if ((rc = mgsl_init_tty()))
4574                 return rc;
4575         
4576         return 0;
4577 }
4578
4579 static int __init synclink_init(void)
4580 {
4581 /* Uncomment this to kernel debug module.
4582  * mgsl_get_text_ptr() leaves the .text address in eax
4583  * which can be used with add-symbol-file with gdb.
4584  */
4585         if (break_on_load) {
4586                 mgsl_get_text_ptr();
4587                 BREAKPOINT();
4588         }
4589         
4590         return mgsl_init();
4591 }
4592
4593 static void __exit synclink_exit(void) 
4594 {
4595         int rc;
4596         struct mgsl_struct *info;
4597         struct mgsl_struct *tmp;
4598
4599         printk("Unloading %s: %s\n", driver_name, driver_version);
4600
4601         if ((rc = tty_unregister_driver(serial_driver)))
4602                 printk("%s(%d) failed to unregister tty driver err=%d\n",
4603                        __FILE__,__LINE__,rc);
4604
4605         put_tty_driver(serial_driver);
4606         info = mgsl_device_list;
4607         while(info) {
4608 #ifdef CONFIG_SYNCLINK_SYNCPPP
4609                 if (info->dosyncppp)
4610                         mgsl_sppp_delete(info);
4611 #endif
4612                 mgsl_release_resources(info);
4613                 tmp = info;
4614                 info = info->next_device;
4615                 kfree(tmp);
4616         }
4617         
4618         if (tmp_buf) {
4619                 free_page((unsigned long) tmp_buf);
4620                 tmp_buf = NULL;
4621         }
4622         
4623         pci_unregister_driver(&synclink_pci_driver);
4624 }
4625
4626 module_init(synclink_init);
4627 module_exit(synclink_exit);
4628
4629 /*
4630  * usc_RTCmd()
4631  *
4632  * Issue a USC Receive/Transmit command to the
4633  * Channel Command/Address Register (CCAR).
4634  *
4635  * Notes:
4636  *
4637  *    The command is encoded in the most significant 5 bits <15..11>
4638  *    of the CCAR value. Bits <10..7> of the CCAR must be preserved
4639  *    and Bits <6..0> must be written as zeros.
4640  *
4641  * Arguments:
4642  *
4643  *    info   pointer to device information structure
4644  *    Cmd    command mask (use symbolic macros)
4645  *
4646  * Return Value:
4647  *
4648  *    None
4649  */
4650 void usc_RTCmd( struct mgsl_struct *info, u16 Cmd )
4651 {
4652         /* output command to CCAR in bits <15..11> */
4653         /* preserve bits <10..7>, bits <6..0> must be zero */
4654
4655         outw( Cmd + info->loopback_bits, info->io_base + CCAR );
4656
4657         /* Read to flush write to CCAR */
4658         if ( info->bus_type == MGSL_BUS_TYPE_PCI )
4659                 inw( info->io_base + CCAR );
4660
4661 }       /* end of usc_RTCmd() */
4662
4663 /*
4664  * usc_DmaCmd()
4665  *
4666  *    Issue a DMA command to the DMA Command/Address Register (DCAR).
4667  *
4668  * Arguments:
4669  *
4670  *    info   pointer to device information structure
4671  *    Cmd    DMA command mask (usc_DmaCmd_XX Macros)
4672  *
4673  * Return Value:
4674  *
4675  *       None
4676  */
4677 void usc_DmaCmd( struct mgsl_struct *info, u16 Cmd )
4678 {
4679         /* write command mask to DCAR */
4680         outw( Cmd + info->mbre_bit, info->io_base );
4681
4682         /* Read to flush write to DCAR */
4683         if ( info->bus_type == MGSL_BUS_TYPE_PCI )
4684                 inw( info->io_base );
4685
4686 }       /* end of usc_DmaCmd() */
4687
4688 /*
4689  * usc_OutDmaReg()
4690  *
4691  *    Write a 16-bit value to a USC DMA register
4692  *
4693  * Arguments:
4694  *
4695  *    info      pointer to device info structure
4696  *    RegAddr   register address (number) for write
4697  *    RegValue  16-bit value to write to register
4698  *
4699  * Return Value:
4700  *
4701  *    None
4702  *
4703  */
4704 void usc_OutDmaReg( struct mgsl_struct *info, u16 RegAddr, u16 RegValue )
4705 {
4706         /* Note: The DCAR is located at the adapter base address */
4707         /* Note: must preserve state of BIT8 in DCAR */
4708
4709         outw( RegAddr + info->mbre_bit, info->io_base );
4710         outw( RegValue, info->io_base );
4711
4712         /* Read to flush write to DCAR */
4713         if ( info->bus_type == MGSL_BUS_TYPE_PCI )
4714                 inw( info->io_base );
4715
4716 }       /* end of usc_OutDmaReg() */
4717  
4718 /*
4719  * usc_InDmaReg()
4720  *
4721  *    Read a 16-bit value from a DMA register
4722  *
4723  * Arguments:
4724  *
4725  *    info     pointer to device info structure
4726  *    RegAddr  register address (number) to read from
4727  *
4728  * Return Value:
4729  *
4730  *    The 16-bit value read from register
4731  *
4732  */
4733 u16 usc_InDmaReg( struct mgsl_struct *info, u16 RegAddr )
4734 {
4735         /* Note: The DCAR is located at the adapter base address */
4736         /* Note: must preserve state of BIT8 in DCAR */
4737
4738         outw( RegAddr + info->mbre_bit, info->io_base );
4739         return inw( info->io_base );
4740
4741 }       /* end of usc_InDmaReg() */
4742
4743 /*
4744  *
4745  * usc_OutReg()
4746  *
4747  *    Write a 16-bit value to a USC serial channel register 
4748  *
4749  * Arguments:
4750  *
4751  *    info      pointer to device info structure
4752  *    RegAddr   register address (number) to write to
4753  *    RegValue  16-bit value to write to register
4754  *
4755  * Return Value:
4756  *
4757  *    None
4758  *
4759  */
4760 void usc_OutReg( struct mgsl_struct *info, u16 RegAddr, u16 RegValue )
4761 {
4762         outw( RegAddr + info->loopback_bits, info->io_base + CCAR );
4763         outw( RegValue, info->io_base + CCAR );
4764
4765         /* Read to flush write to CCAR */
4766         if ( info->bus_type == MGSL_BUS_TYPE_PCI )
4767                 inw( info->io_base + CCAR );
4768
4769 }       /* end of usc_OutReg() */
4770
4771 /*
4772  * usc_InReg()
4773  *
4774  *    Reads a 16-bit value from a USC serial channel register
4775  *
4776  * Arguments:
4777  *
4778  *    info       pointer to device extension
4779  *    RegAddr    register address (number) to read from
4780  *
4781  * Return Value:
4782  *
4783  *    16-bit value read from register
4784  */
4785 u16 usc_InReg( struct mgsl_struct *info, u16 RegAddr )
4786 {
4787         outw( RegAddr + info->loopback_bits, info->io_base + CCAR );
4788         return inw( info->io_base + CCAR );
4789
4790 }       /* end of usc_InReg() */
4791
4792 /* usc_set_sdlc_mode()
4793  *
4794  *    Set up the adapter for SDLC DMA communications.
4795  *
4796  * Arguments:           info    pointer to device instance data
4797  * Return Value:        NONE
4798  */
4799 void usc_set_sdlc_mode( struct mgsl_struct *info )
4800 {
4801         u16 RegValue;
4802         int PreSL1660;
4803         
4804         /*
4805          * determine if the IUSC on the adapter is pre-SL1660. If
4806          * not, take advantage of the UnderWait feature of more
4807          * modern chips. If an underrun occurs and this bit is set,
4808          * the transmitter will idle the programmed idle pattern
4809          * until the driver has time to service the underrun. Otherwise,
4810          * the dma controller may get the cycles previously requested
4811          * and begin transmitting queued tx data.
4812          */
4813         usc_OutReg(info,TMCR,0x1f);
4814         RegValue=usc_InReg(info,TMDR);
4815         if ( RegValue == IUSC_PRE_SL1660 )
4816                 PreSL1660 = 1;
4817         else
4818                 PreSL1660 = 0;
4819         
4820
4821         if ( info->params.flags & HDLC_FLAG_HDLC_LOOPMODE )
4822         {
4823            /*
4824            ** Channel Mode Register (CMR)
4825            **
4826            ** <15..14>    10    Tx Sub Modes, Send Flag on Underrun
4827            ** <13>        0     0 = Transmit Disabled (initially)
4828            ** <12>        0     1 = Consecutive Idles share common 0
4829            ** <11..8>     1110  Transmitter Mode = HDLC/SDLC Loop
4830            ** <7..4>      0000  Rx Sub Modes, addr/ctrl field handling
4831            ** <3..0>      0110  Receiver Mode = HDLC/SDLC
4832            **
4833            ** 1000 1110 0000 0110 = 0x8e06
4834            */
4835            RegValue = 0x8e06;
4836  
4837            /*--------------------------------------------------
4838             * ignore user options for UnderRun Actions and
4839             * preambles
4840             *--------------------------------------------------*/
4841         }
4842         else
4843         {       
4844                 /* Channel mode Register (CMR)
4845                  *
4846                  * <15..14>  00    Tx Sub modes, Underrun Action
4847                  * <13>      0     1 = Send Preamble before opening flag
4848                  * <12>      0     1 = Consecutive Idles share common 0
4849                  * <11..8>   0110  Transmitter mode = HDLC/SDLC
4850                  * <7..4>    0000  Rx Sub modes, addr/ctrl field handling
4851                  * <3..0>    0110  Receiver mode = HDLC/SDLC
4852                  *
4853                  * 0000 0110 0000 0110 = 0x0606
4854                  */
4855                 if (info->params.mode == MGSL_MODE_RAW) {
4856                         RegValue = 0x0001;              /* Set Receive mode = external sync */
4857
4858                         usc_OutReg( info, IOCR,         /* Set IOCR DCD is RxSync Detect Input */
4859                                 (unsigned short)((usc_InReg(info, IOCR) & ~(BIT13|BIT12)) | BIT12));
4860
4861                         /*
4862                          * TxSubMode:
4863                          *      CMR <15>                0       Don't send CRC on Tx Underrun
4864                          *      CMR <14>                x       undefined
4865                          *      CMR <13>                0       Send preamble before openning sync
4866                          *      CMR <12>                0       Send 8-bit syncs, 1=send Syncs per TxLength
4867                          *
4868                          * TxMode:
4869                          *      CMR <11-8)      0100    MonoSync
4870                          *
4871                          *      0x00 0100 xxxx xxxx  04xx
4872                          */
4873                         RegValue |= 0x0400;
4874                 }
4875                 else {
4876
4877                 RegValue = 0x0606;
4878
4879                 if ( info->params.flags & HDLC_FLAG_UNDERRUN_ABORT15 )
4880                         RegValue |= BIT14;
4881                 else if ( info->params.flags & HDLC_FLAG_UNDERRUN_FLAG )
4882                         RegValue |= BIT15;
4883                 else if ( info->params.flags & HDLC_FLAG_UNDERRUN_CRC )
4884                         RegValue |= BIT15 + BIT14;
4885                 }
4886
4887                 if ( info->params.preamble != HDLC_PREAMBLE_PATTERN_NONE )
4888                         RegValue |= BIT13;
4889         }
4890
4891         if ( info->params.mode == MGSL_MODE_HDLC &&
4892                 (info->params.flags & HDLC_FLAG_SHARE_ZERO) )
4893                 RegValue |= BIT12;
4894
4895         if ( info->params.addr_filter != 0xff )
4896         {
4897                 /* set up receive address filtering */
4898                 usc_OutReg( info, RSR, info->params.addr_filter );
4899                 RegValue |= BIT4;
4900         }
4901
4902         usc_OutReg( info, CMR, RegValue );
4903         info->cmr_value = RegValue;
4904
4905         /* Receiver mode Register (RMR)
4906          *
4907          * <15..13>  000    encoding
4908          * <12..11>  00     FCS = 16bit CRC CCITT (x15 + x12 + x5 + 1)
4909          * <10>      1      1 = Set CRC to all 1s (use for SDLC/HDLC)
4910          * <9>       0      1 = Include Receive chars in CRC
4911          * <8>       1      1 = Use Abort/PE bit as abort indicator
4912          * <7..6>    00     Even parity
4913          * <5>       0      parity disabled
4914          * <4..2>    000    Receive Char Length = 8 bits
4915          * <1..0>    00     Disable Receiver
4916          *
4917          * 0000 0101 0000 0000 = 0x0500
4918          */
4919
4920         RegValue = 0x0500;
4921
4922         switch ( info->params.encoding ) {
4923         case HDLC_ENCODING_NRZB:               RegValue |= BIT13; break;
4924         case HDLC_ENCODING_NRZI_MARK:          RegValue |= BIT14; break;
4925         case HDLC_ENCODING_NRZI_SPACE:         RegValue |= BIT14 + BIT13; break;
4926         case HDLC_ENCODING_BIPHASE_MARK:       RegValue |= BIT15; break;
4927         case HDLC_ENCODING_BIPHASE_SPACE:      RegValue |= BIT15 + BIT13; break;
4928         case HDLC_ENCODING_BIPHASE_LEVEL:      RegValue |= BIT15 + BIT14; break;
4929         case HDLC_ENCODING_DIFF_BIPHASE_LEVEL: RegValue |= BIT15 + BIT14 + BIT13; break;
4930         }
4931
4932         if ( (info->params.crc_type & HDLC_CRC_MASK) == HDLC_CRC_16_CCITT )
4933                 RegValue |= BIT9;
4934         else if ( (info->params.crc_type & HDLC_CRC_MASK) == HDLC_CRC_32_CCITT )
4935                 RegValue |= ( BIT12 | BIT10 | BIT9 );
4936
4937         usc_OutReg( info, RMR, RegValue );
4938
4939         /* Set the Receive count Limit Register (RCLR) to 0xffff. */
4940         /* When an opening flag of an SDLC frame is recognized the */
4941         /* Receive Character count (RCC) is loaded with the value in */
4942         /* RCLR. The RCC is decremented for each received byte.  The */
4943         /* value of RCC is stored after the closing flag of the frame */
4944         /* allowing the frame size to be computed. */
4945
4946         usc_OutReg( info, RCLR, RCLRVALUE );
4947
4948         usc_RCmd( info, RCmd_SelectRicrdma_level );
4949
4950         /* Receive Interrupt Control Register (RICR)
4951          *
4952          * <15..8>      ?       RxFIFO DMA Request Level
4953          * <7>          0       Exited Hunt IA (Interrupt Arm)
4954          * <6>          0       Idle Received IA
4955          * <5>          0       Break/Abort IA
4956          * <4>          0       Rx Bound IA
4957          * <3>          1       Queued status reflects oldest 2 bytes in FIFO
4958          * <2>          0       Abort/PE IA
4959          * <1>          1       Rx Overrun IA
4960          * <0>          0       Select TC0 value for readback
4961          *
4962          *      0000 0000 0000 1000 = 0x000a
4963          */
4964
4965         /* Carry over the Exit Hunt and Idle Received bits */
4966         /* in case they have been armed by usc_ArmEvents.   */
4967
4968         RegValue = usc_InReg( info, RICR ) & 0xc0;
4969
4970         if ( info->bus_type == MGSL_BUS_TYPE_PCI )
4971                 usc_OutReg( info, RICR, (u16)(0x030a | RegValue) );
4972         else
4973                 usc_OutReg( info, RICR, (u16)(0x140a | RegValue) );
4974
4975         /* Unlatch all Rx status bits and clear Rx status IRQ Pending */
4976
4977         usc_UnlatchRxstatusBits( info, RXSTATUS_ALL );
4978         usc_ClearIrqPendingBits( info, RECEIVE_STATUS );
4979
4980         /* Transmit mode Register (TMR)
4981          *      
4982          * <15..13>     000     encoding
4983          * <12..11>     00      FCS = 16bit CRC CCITT (x15 + x12 + x5 + 1)
4984          * <10>         1       1 = Start CRC as all 1s (use for SDLC/HDLC)
4985          * <9>          0       1 = Tx CRC Enabled
4986          * <8>          0       1 = Append CRC to end of transmit frame
4987          * <7..6>       00      Transmit parity Even
4988          * <5>          0       Transmit parity Disabled
4989          * <4..2>       000     Tx Char Length = 8 bits
4990          * <1..0>       00      Disable Transmitter
4991          *
4992          *      0000 0100 0000 0000 = 0x0400
4993          */
4994
4995         RegValue = 0x0400;
4996
4997         switch ( info->params.encoding ) {
4998         case HDLC_ENCODING_NRZB:               RegValue |= BIT13; break;
4999         case HDLC_ENCODING_NRZI_MARK:          RegValue |= BIT14; break;
5000         case HDLC_ENCODING_NRZI_SPACE:         RegValue |= BIT14 + BIT13; break;
5001         case HDLC_ENCODING_BIPHASE_MARK:       RegValue |= BIT15; break;
5002         case HDLC_ENCODING_BIPHASE_SPACE:      RegValue |= BIT15 + BIT13; break;
5003         case HDLC_ENCODING_BIPHASE_LEVEL:      RegValue |= BIT15 + BIT14; break;
5004         case HDLC_ENCODING_DIFF_BIPHASE_LEVEL: RegValue |= BIT15 + BIT14 + BIT13; break;
5005         }
5006
5007         if ( (info->params.crc_type & HDLC_CRC_MASK) == HDLC_CRC_16_CCITT )
5008                 RegValue |= BIT9 + BIT8;
5009         else if ( (info->params.crc_type & HDLC_CRC_MASK) == HDLC_CRC_32_CCITT )
5010                 RegValue |= ( BIT12 | BIT10 | BIT9 | BIT8);
5011
5012         usc_OutReg( info, TMR, RegValue );
5013
5014         usc_set_txidle( info );
5015
5016
5017         usc_TCmd( info, TCmd_SelectTicrdma_level );
5018
5019         /* Transmit Interrupt Control Register (TICR)
5020          *
5021          * <15..8>      ?       Transmit FIFO DMA Level
5022          * <7>          0       Present IA (Interrupt Arm)
5023          * <6>          0       Idle Sent IA
5024          * <5>          1       Abort Sent IA
5025          * <4>          1       EOF/EOM Sent IA
5026          * <3>          0       CRC Sent IA
5027          * <2>          1       1 = Wait for SW Trigger to Start Frame
5028          * <1>          1       Tx Underrun IA
5029          * <0>          0       TC0 constant on read back
5030          *
5031          *      0000 0000 0011 0110 = 0x0036
5032          */
5033
5034         if ( info->bus_type == MGSL_BUS_TYPE_PCI )
5035                 usc_OutReg( info, TICR, 0x0736 );
5036         else                                                            
5037                 usc_OutReg( info, TICR, 0x1436 );
5038
5039         usc_UnlatchTxstatusBits( info, TXSTATUS_ALL );
5040         usc_ClearIrqPendingBits( info, TRANSMIT_STATUS );
5041
5042         /*
5043         ** Transmit Command/Status Register (TCSR)
5044         **
5045         ** <15..12>     0000    TCmd
5046         ** <11>         0/1     UnderWait
5047         ** <10..08>     000     TxIdle
5048         ** <7>          x       PreSent
5049         ** <6>          x       IdleSent
5050         ** <5>          x       AbortSent
5051         ** <4>          x       EOF/EOM Sent
5052         ** <3>          x       CRC Sent
5053         ** <2>          x       All Sent
5054         ** <1>          x       TxUnder
5055         ** <0>          x       TxEmpty
5056         ** 
5057         ** 0000 0000 0000 0000 = 0x0000
5058         */
5059         info->tcsr_value = 0;
5060
5061         if ( !PreSL1660 )
5062                 info->tcsr_value |= TCSR_UNDERWAIT;
5063                 
5064         usc_OutReg( info, TCSR, info->tcsr_value );
5065
5066         /* Clock mode Control Register (CMCR)
5067          *
5068          * <15..14>     00      counter 1 Source = Disabled
5069          * <13..12>     00      counter 0 Source = Disabled
5070          * <11..10>     11      BRG1 Input is TxC Pin
5071          * <9..8>       11      BRG0 Input is TxC Pin
5072          * <7..6>       01      DPLL Input is BRG1 Output
5073          * <5..3>       XXX     TxCLK comes from Port 0
5074          * <2..0>       XXX     RxCLK comes from Port 1
5075          *
5076          *      0000 1111 0111 0111 = 0x0f77
5077          */
5078
5079         RegValue = 0x0f40;
5080
5081         if ( info->params.flags & HDLC_FLAG_RXC_DPLL )
5082                 RegValue |= 0x0003;     /* RxCLK from DPLL */
5083         else if ( info->params.flags & HDLC_FLAG_RXC_BRG )
5084                 RegValue |= 0x0004;     /* RxCLK from BRG0 */
5085         else if ( info->params.flags & HDLC_FLAG_RXC_TXCPIN)
5086                 RegValue |= 0x0006;     /* RxCLK from TXC Input */
5087         else
5088                 RegValue |= 0x0007;     /* RxCLK from Port1 */
5089
5090         if ( info->params.flags & HDLC_FLAG_TXC_DPLL )
5091                 RegValue |= 0x0018;     /* TxCLK from DPLL */
5092         else if ( info->params.flags & HDLC_FLAG_TXC_BRG )
5093                 RegValue |= 0x0020;     /* TxCLK from BRG0 */
5094         else if ( info->params.flags & HDLC_FLAG_TXC_RXCPIN)
5095                 RegValue |= 0x0038;     /* RxCLK from TXC Input */
5096         else
5097                 RegValue |= 0x0030;     /* TxCLK from Port0 */
5098
5099         usc_OutReg( info, CMCR, RegValue );
5100
5101
5102         /* Hardware Configuration Register (HCR)
5103          *
5104          * <15..14>     00      CTR0 Divisor:00=32,01=16,10=8,11=4
5105          * <13>         0       CTR1DSel:0=CTR0Div determines CTR0Div
5106          * <12>         0       CVOK:0=report code violation in biphase
5107          * <11..10>     00      DPLL Divisor:00=32,01=16,10=8,11=4
5108          * <9..8>       XX      DPLL mode:00=disable,01=NRZ,10=Biphase,11=Biphase Level
5109          * <7..6>       00      reserved
5110          * <5>          0       BRG1 mode:0=continuous,1=single cycle
5111          * <4>          X       BRG1 Enable
5112          * <3..2>       00      reserved
5113          * <1>          0       BRG0 mode:0=continuous,1=single cycle
5114          * <0>          0       BRG0 Enable
5115          */
5116
5117         RegValue = 0x0000;
5118
5119         if ( info->params.flags & (HDLC_FLAG_RXC_DPLL + HDLC_FLAG_TXC_DPLL) ) {
5120                 u32 XtalSpeed;
5121                 u32 DpllDivisor;
5122                 u16 Tc;
5123
5124                 /*  DPLL is enabled. Use BRG1 to provide continuous reference clock  */
5125                 /*  for DPLL. DPLL mode in HCR is dependent on the encoding used. */
5126
5127                 if ( info->bus_type == MGSL_BUS_TYPE_PCI )
5128                         XtalSpeed = 11059200;
5129                 else
5130                         XtalSpeed = 14745600;
5131
5132                 if ( info->params.flags & HDLC_FLAG_DPLL_DIV16 ) {
5133                         DpllDivisor = 16;
5134                         RegValue |= BIT10;
5135                 }
5136                 else if ( info->params.flags & HDLC_FLAG_DPLL_DIV8 ) {
5137                         DpllDivisor = 8;
5138                         RegValue |= BIT11;
5139                 }
5140                 else
5141                         DpllDivisor = 32;
5142
5143                 /*  Tc = (Xtal/Speed) - 1 */
5144                 /*  If twice the remainder of (Xtal/Speed) is greater than Speed */
5145                 /*  then rounding up gives a more precise time constant. Instead */
5146                 /*  of rounding up and then subtracting 1 we just don't subtract */
5147                 /*  the one in this case. */
5148
5149                 /*--------------------------------------------------
5150                  * ejz: for DPLL mode, application should use the
5151                  * same clock speed as the partner system, even 
5152                  * though clocking is derived from the input RxData.
5153                  * In case the user uses a 0 for the clock speed,
5154                  * default to 0xffffffff and don't try to divide by
5155                  * zero
5156                  *--------------------------------------------------*/
5157                 if ( info->params.clock_speed )
5158                 {
5159                         Tc = (u16)((XtalSpeed/DpllDivisor)/info->params.clock_speed);
5160                         if ( !((((XtalSpeed/DpllDivisor) % info->params.clock_speed) * 2)
5161                                / info->params.clock_speed) )
5162                                 Tc--;
5163                 }
5164                 else
5165                         Tc = -1;
5166                                   
5167
5168                 /* Write 16-bit Time Constant for BRG1 */
5169                 usc_OutReg( info, TC1R, Tc );
5170
5171                 RegValue |= BIT4;               /* enable BRG1 */
5172
5173                 switch ( info->params.encoding ) {
5174                 case HDLC_ENCODING_NRZ:
5175                 case HDLC_ENCODING_NRZB:
5176                 case HDLC_ENCODING_NRZI_MARK:
5177                 case HDLC_ENCODING_NRZI_SPACE: RegValue |= BIT8; break;
5178                 case HDLC_ENCODING_BIPHASE_MARK:
5179                 case HDLC_ENCODING_BIPHASE_SPACE: RegValue |= BIT9; break;
5180                 case HDLC_ENCODING_BIPHASE_LEVEL:
5181                 case HDLC_ENCODING_DIFF_BIPHASE_LEVEL: RegValue |= BIT9 + BIT8; break;
5182                 }
5183         }
5184
5185         usc_OutReg( info, HCR, RegValue );
5186
5187
5188         /* Channel Control/status Register (CCSR)
5189          *
5190          * <15>         X       RCC FIFO Overflow status (RO)
5191          * <14>         X       RCC FIFO Not Empty status (RO)
5192          * <13>         0       1 = Clear RCC FIFO (WO)
5193          * <12>         X       DPLL Sync (RW)
5194          * <11>         X       DPLL 2 Missed Clocks status (RO)
5195          * <10>         X       DPLL 1 Missed Clock status (RO)
5196          * <9..8>       00      DPLL Resync on rising and falling edges (RW)
5197          * <7>          X       SDLC Loop On status (RO)
5198          * <6>          X       SDLC Loop Send status (RO)
5199          * <5>          1       Bypass counters for TxClk and RxClk (RW)
5200          * <4..2>       000     Last Char of SDLC frame has 8 bits (RW)
5201          * <1..0>       00      reserved
5202          *
5203          *      0000 0000 0010 0000 = 0x0020
5204          */
5205
5206         usc_OutReg( info, CCSR, 0x1020 );
5207
5208
5209         if ( info->params.flags & HDLC_FLAG_AUTO_CTS ) {
5210                 usc_OutReg( info, SICR,
5211                             (u16)(usc_InReg(info,SICR) | SICR_CTS_INACTIVE) );
5212         }
5213         
5214
5215         /* enable Master Interrupt Enable bit (MIE) */
5216         usc_EnableMasterIrqBit( info );
5217
5218         usc_ClearIrqPendingBits( info, RECEIVE_STATUS + RECEIVE_DATA +
5219                                 TRANSMIT_STATUS + TRANSMIT_DATA + MISC);
5220
5221         /* arm RCC underflow interrupt */
5222         usc_OutReg(info, SICR, (u16)(usc_InReg(info,SICR) | BIT3));
5223         usc_EnableInterrupts(info, MISC);
5224
5225         info->mbre_bit = 0;
5226         outw( 0, info->io_base );                       /* clear Master Bus Enable (DCAR) */
5227         usc_DmaCmd( info, DmaCmd_ResetAllChannels );    /* disable both DMA channels */
5228         info->mbre_bit = BIT8;
5229         outw( BIT8, info->io_base );                    /* set Master Bus Enable (DCAR) */
5230
5231         if (info->bus_type == MGSL_BUS_TYPE_ISA) {
5232                 /* Enable DMAEN (Port 7, Bit 14) */
5233                 /* This connects the DMA request signal to the ISA bus */
5234                 usc_OutReg(info, PCR, (u16)((usc_InReg(info, PCR) | BIT15) & ~BIT14));
5235         }
5236
5237         /* DMA Control Register (DCR)
5238          *
5239          * <15..14>     10      Priority mode = Alternating Tx/Rx
5240          *              01      Rx has priority
5241          *              00      Tx has priority
5242          *
5243          * <13>         1       Enable Priority Preempt per DCR<15..14>
5244          *                      (WARNING DCR<11..10> must be 00 when this is 1)
5245          *              0       Choose activate channel per DCR<11..10>
5246          *
5247          * <12>         0       Little Endian for Array/List
5248          * <11..10>     00      Both Channels can use each bus grant
5249          * <9..6>       0000    reserved
5250          * <5>          0       7 CLK - Minimum Bus Re-request Interval
5251          * <4>          0       1 = drive D/C and S/D pins
5252          * <3>          1       1 = Add one wait state to all DMA cycles.
5253          * <2>          0       1 = Strobe /UAS on every transfer.
5254          * <1..0>       11      Addr incrementing only affects LS24 bits
5255          *
5256          *      0110 0000 0000 1011 = 0x600b
5257          */
5258
5259         if ( info->bus_type == MGSL_BUS_TYPE_PCI ) {
5260                 /* PCI adapter does not need DMA wait state */
5261                 usc_OutDmaReg( info, DCR, 0xa00b );
5262         }
5263         else
5264                 usc_OutDmaReg( info, DCR, 0x800b );
5265
5266
5267         /* Receive DMA mode Register (RDMR)
5268          *
5269          * <15..14>     11      DMA mode = Linked List Buffer mode
5270          * <13>         1       RSBinA/L = store Rx status Block in Arrary/List entry
5271          * <12>         1       Clear count of List Entry after fetching
5272          * <11..10>     00      Address mode = Increment
5273          * <9>          1       Terminate Buffer on RxBound
5274          * <8>          0       Bus Width = 16bits
5275          * <7..0>       ?       status Bits (write as 0s)
5276          *
5277          * 1111 0010 0000 0000 = 0xf200
5278          */
5279
5280         usc_OutDmaReg( info, RDMR, 0xf200 );
5281
5282
5283         /* Transmit DMA mode Register (TDMR)
5284          *
5285          * <15..14>     11      DMA mode = Linked List Buffer mode
5286          * <13>         1       TCBinA/L = fetch Tx Control Block from List entry
5287          * <12>         1       Clear count of List Entry after fetching
5288          * <11..10>     00      Address mode = Increment
5289          * <9>          1       Terminate Buffer on end of frame
5290          * <8>          0       Bus Width = 16bits
5291          * <7..0>       ?       status Bits (Read Only so write as 0)
5292          *
5293          *      1111 0010 0000 0000 = 0xf200
5294          */
5295
5296         usc_OutDmaReg( info, TDMR, 0xf200 );
5297
5298
5299         /* DMA Interrupt Control Register (DICR)
5300          *
5301          * <15>         1       DMA Interrupt Enable
5302          * <14>         0       1 = Disable IEO from USC
5303          * <13>         0       1 = Don't provide vector during IntAck
5304          * <12>         1       1 = Include status in Vector
5305          * <10..2>      0       reserved, Must be 0s
5306          * <1>          0       1 = Rx DMA Interrupt Enabled
5307          * <0>          0       1 = Tx DMA Interrupt Enabled
5308          *
5309          *      1001 0000 0000 0000 = 0x9000
5310          */
5311
5312         usc_OutDmaReg( info, DICR, 0x9000 );
5313
5314         usc_InDmaReg( info, RDMR );             /* clear pending receive DMA IRQ bits */
5315         usc_InDmaReg( info, TDMR );             /* clear pending transmit DMA IRQ bits */
5316         usc_OutDmaReg( info, CDIR, 0x0303 );    /* clear IUS and Pending for Tx and Rx */
5317
5318         /* Channel Control Register (CCR)
5319          *
5320          * <15..14>     10      Use 32-bit Tx Control Blocks (TCBs)
5321          * <13>         0       Trigger Tx on SW Command Disabled
5322          * <12>         0       Flag Preamble Disabled
5323          * <11..10>     00      Preamble Length
5324          * <9..8>       00      Preamble Pattern
5325          * <7..6>       10      Use 32-bit Rx status Blocks (RSBs)
5326          * <5>          0       Trigger Rx on SW Command Disabled
5327          * <4..0>       0       reserved
5328          *
5329          *      1000 0000 1000 0000 = 0x8080
5330          */
5331
5332         RegValue = 0x8080;
5333
5334         switch ( info->params.preamble_length ) {
5335         case HDLC_PREAMBLE_LENGTH_16BITS: RegValue |= BIT10; break;
5336         case HDLC_PREAMBLE_LENGTH_32BITS: RegValue |= BIT11; break;
5337         case HDLC_PREAMBLE_LENGTH_64BITS: RegValue |= BIT11 + BIT10; break;
5338         }
5339
5340         switch ( info->params.preamble ) {
5341         case HDLC_PREAMBLE_PATTERN_FLAGS: RegValue |= BIT8 + BIT12; break;
5342         case HDLC_PREAMBLE_PATTERN_ONES:  RegValue |= BIT8; break;
5343         case HDLC_PREAMBLE_PATTERN_10:    RegValue |= BIT9; break;
5344         case HDLC_PREAMBLE_PATTERN_01:    RegValue |= BIT9 + BIT8; break;
5345         }
5346
5347         usc_OutReg( info, CCR, RegValue );
5348
5349
5350         /*
5351          * Burst/Dwell Control Register
5352          *
5353          * <15..8>      0x20    Maximum number of transfers per bus grant
5354          * <7..0>       0x00    Maximum number of clock cycles per bus grant
5355          */
5356
5357         if ( info->bus_type == MGSL_BUS_TYPE_PCI ) {
5358                 /* don't limit bus occupancy on PCI adapter */
5359                 usc_OutDmaReg( info, BDCR, 0x0000 );
5360         }
5361         else
5362                 usc_OutDmaReg( info, BDCR, 0x2000 );
5363
5364         usc_stop_transmitter(info);
5365         usc_stop_receiver(info);
5366         
5367 }       /* end of usc_set_sdlc_mode() */
5368
5369 /* usc_enable_loopback()
5370  *
5371  * Set the 16C32 for internal loopback mode.
5372  * The TxCLK and RxCLK signals are generated from the BRG0 and
5373  * the TxD is looped back to the RxD internally.
5374  *
5375  * Arguments:           info    pointer to device instance data
5376  *                      enable  1 = enable loopback, 0 = disable
5377  * Return Value:        None
5378  */
5379 void usc_enable_loopback(struct mgsl_struct *info, int enable)
5380 {
5381         if (enable) {
5382                 /* blank external TXD output */
5383                 usc_OutReg(info,IOCR,usc_InReg(info,IOCR) | (BIT7+BIT6));
5384         
5385                 /* Clock mode Control Register (CMCR)
5386                  *
5387                  * <15..14>     00      counter 1 Disabled
5388                  * <13..12>     00      counter 0 Disabled
5389                  * <11..10>     11      BRG1 Input is TxC Pin
5390                  * <9..8>       11      BRG0 Input is TxC Pin
5391                  * <7..6>       01      DPLL Input is BRG1 Output
5392                  * <5..3>       100     TxCLK comes from BRG0
5393                  * <2..0>       100     RxCLK comes from BRG0
5394                  *
5395                  * 0000 1111 0110 0100 = 0x0f64
5396                  */
5397
5398                 usc_OutReg( info, CMCR, 0x0f64 );
5399
5400                 /* Write 16-bit Time Constant for BRG0 */
5401                 /* use clock speed if available, otherwise use 8 for diagnostics */
5402                 if (info->params.clock_speed) {
5403                         if (info->bus_type == MGSL_BUS_TYPE_PCI)
5404                                 usc_OutReg(info, TC0R, (u16)((11059200/info->params.clock_speed)-1));
5405                         else
5406                                 usc_OutReg(info, TC0R, (u16)((14745600/info->params.clock_speed)-1));
5407                 } else
5408                         usc_OutReg(info, TC0R, (u16)8);
5409
5410                 /* Hardware Configuration Register (HCR) Clear Bit 1, BRG0
5411                    mode = Continuous Set Bit 0 to enable BRG0.  */
5412                 usc_OutReg( info, HCR, (u16)((usc_InReg( info, HCR ) & ~BIT1) | BIT0) );
5413
5414                 /* Input/Output Control Reg, <2..0> = 100, Drive RxC pin with BRG0 */
5415                 usc_OutReg(info, IOCR, (u16)((usc_InReg(info, IOCR) & 0xfff8) | 0x0004));
5416
5417                 /* set Internal Data loopback mode */
5418                 info->loopback_bits = 0x300;
5419                 outw( 0x0300, info->io_base + CCAR );
5420         } else {
5421                 /* enable external TXD output */
5422                 usc_OutReg(info,IOCR,usc_InReg(info,IOCR) & ~(BIT7+BIT6));
5423         
5424                 /* clear Internal Data loopback mode */
5425                 info->loopback_bits = 0;
5426                 outw( 0,info->io_base + CCAR );
5427         }
5428         
5429 }       /* end of usc_enable_loopback() */
5430
5431 /* usc_enable_aux_clock()
5432  *
5433  * Enabled the AUX clock output at the specified frequency.
5434  *
5435  * Arguments:
5436  *
5437  *      info            pointer to device extension
5438  *      data_rate       data rate of clock in bits per second
5439  *                      A data rate of 0 disables the AUX clock.
5440  *
5441  * Return Value:        None
5442  */
5443 void usc_enable_aux_clock( struct mgsl_struct *info, u32 data_rate )
5444 {
5445         u32 XtalSpeed;
5446         u16 Tc;
5447
5448         if ( data_rate ) {
5449                 if ( info->bus_type == MGSL_BUS_TYPE_PCI )
5450                         XtalSpeed = 11059200;
5451                 else
5452                         XtalSpeed = 14745600;
5453
5454
5455                 /* Tc = (Xtal/Speed) - 1 */
5456                 /* If twice the remainder of (Xtal/Speed) is greater than Speed */
5457                 /* then rounding up gives a more precise time constant. Instead */
5458                 /* of rounding up and then subtracting 1 we just don't subtract */
5459                 /* the one in this case. */
5460
5461
5462                 Tc = (u16)(XtalSpeed/data_rate);
5463                 if ( !(((XtalSpeed % data_rate) * 2) / data_rate) )
5464                         Tc--;
5465
5466                 /* Write 16-bit Time Constant for BRG0 */
5467                 usc_OutReg( info, TC0R, Tc );
5468
5469                 /*
5470                  * Hardware Configuration Register (HCR)
5471                  * Clear Bit 1, BRG0 mode = Continuous
5472                  * Set Bit 0 to enable BRG0.
5473                  */
5474
5475                 usc_OutReg( info, HCR, (u16)((usc_InReg( info, HCR ) & ~BIT1) | BIT0) );
5476
5477                 /* Input/Output Control Reg, <2..0> = 100, Drive RxC pin with BRG0 */
5478                 usc_OutReg( info, IOCR, (u16)((usc_InReg(info, IOCR) & 0xfff8) | 0x0004) );
5479         } else {
5480                 /* data rate == 0 so turn off BRG0 */
5481                 usc_OutReg( info, HCR, (u16)(usc_InReg( info, HCR ) & ~BIT0) );
5482         }
5483
5484 }       /* end of usc_enable_aux_clock() */
5485
5486 /*
5487  *
5488  * usc_process_rxoverrun_sync()
5489  *
5490  *              This function processes a receive overrun by resetting the
5491  *              receive DMA buffers and issuing a Purge Rx FIFO command
5492  *              to allow the receiver to continue receiving.
5493  *
5494  * Arguments:
5495  *
5496  *      info            pointer to device extension
5497  *
5498  * Return Value: None
5499  */
5500 void usc_process_rxoverrun_sync( struct mgsl_struct *info )
5501 {
5502         int start_index;
5503         int end_index;
5504         int frame_start_index;
5505         int start_of_frame_found = FALSE;
5506         int end_of_frame_found = FALSE;
5507         int reprogram_dma = FALSE;
5508
5509         DMABUFFERENTRY *buffer_list = info->rx_buffer_list;
5510         u32 phys_addr;
5511
5512         usc_DmaCmd( info, DmaCmd_PauseRxChannel );
5513         usc_RCmd( info, RCmd_EnterHuntmode );
5514         usc_RTCmd( info, RTCmd_PurgeRxFifo );
5515
5516         /* CurrentRxBuffer points to the 1st buffer of the next */
5517         /* possibly available receive frame. */
5518         
5519         frame_start_index = start_index = end_index = info->current_rx_buffer;
5520
5521         /* Search for an unfinished string of buffers. This means */
5522         /* that a receive frame started (at least one buffer with */
5523         /* count set to zero) but there is no terminiting buffer */
5524         /* (status set to non-zero). */
5525
5526         while( !buffer_list[end_index].count )
5527         {
5528                 /* Count field has been reset to zero by 16C32. */
5529                 /* This buffer is currently in use. */
5530
5531                 if ( !start_of_frame_found )
5532                 {
5533                         start_of_frame_found = TRUE;
5534                         frame_start_index = end_index;
5535                         end_of_frame_found = FALSE;
5536                 }
5537
5538                 if ( buffer_list[end_index].status )
5539                 {
5540                         /* Status field has been set by 16C32. */
5541                         /* This is the last buffer of a received frame. */
5542
5543                         /* We want to leave the buffers for this frame intact. */
5544                         /* Move on to next possible frame. */
5545
5546                         start_of_frame_found = FALSE;
5547                         end_of_frame_found = TRUE;
5548                 }
5549
5550                 /* advance to next buffer entry in linked list */
5551                 end_index++;
5552                 if ( end_index == info->rx_buffer_count )
5553                         end_index = 0;
5554
5555                 if ( start_index == end_index )
5556                 {
5557                         /* The entire list has been searched with all Counts == 0 and */
5558                         /* all Status == 0. The receive buffers are */
5559                         /* completely screwed, reset all receive buffers! */
5560                         mgsl_reset_rx_dma_buffers( info );
5561                         frame_start_index = 0;
5562                         start_of_frame_found = FALSE;
5563                         reprogram_dma = TRUE;
5564                         break;
5565                 }
5566         }
5567
5568         if ( start_of_frame_found && !end_of_frame_found )
5569         {
5570                 /* There is an unfinished string of receive DMA buffers */
5571                 /* as a result of the receiver overrun. */
5572
5573                 /* Reset the buffers for the unfinished frame */
5574                 /* and reprogram the receive DMA controller to start */
5575                 /* at the 1st buffer of unfinished frame. */
5576
5577                 start_index = frame_start_index;
5578
5579                 do
5580                 {
5581                         *((unsigned long *)&(info->rx_buffer_list[start_index++].count)) = DMABUFFERSIZE;
5582
5583                         /* Adjust index for wrap around. */
5584                         if ( start_index == info->rx_buffer_count )
5585                                 start_index = 0;
5586
5587                 } while( start_index != end_index );
5588
5589                 reprogram_dma = TRUE;
5590         }
5591
5592         if ( reprogram_dma )
5593         {
5594                 usc_UnlatchRxstatusBits(info,RXSTATUS_ALL);
5595                 usc_ClearIrqPendingBits(info, RECEIVE_DATA|RECEIVE_STATUS);
5596                 usc_UnlatchRxstatusBits(info, RECEIVE_DATA|RECEIVE_STATUS);
5597                 
5598                 usc_EnableReceiver(info,DISABLE_UNCONDITIONAL);
5599                 
5600                 /* This empties the receive FIFO and loads the RCC with RCLR */
5601                 usc_OutReg( info, CCSR, (u16)(usc_InReg(info,CCSR) | BIT13) );
5602
5603                 /* program 16C32 with physical address of 1st DMA buffer entry */
5604                 phys_addr = info->rx_buffer_list[frame_start_index].phys_entry;
5605                 usc_OutDmaReg( info, NRARL, (u16)phys_addr );
5606                 usc_OutDmaReg( info, NRARU, (u16)(phys_addr >> 16) );
5607
5608                 usc_UnlatchRxstatusBits( info, RXSTATUS_ALL );
5609                 usc_ClearIrqPendingBits( info, RECEIVE_DATA + RECEIVE_STATUS );
5610                 usc_EnableInterrupts( info, RECEIVE_STATUS );
5611
5612                 /* 1. Arm End of Buffer (EOB) Receive DMA Interrupt (BIT2 of RDIAR) */
5613                 /* 2. Enable Receive DMA Interrupts (BIT1 of DICR) */
5614
5615                 usc_OutDmaReg( info, RDIAR, BIT3 + BIT2 );
5616                 usc_OutDmaReg( info, DICR, (u16)(usc_InDmaReg(info,DICR) | BIT1) );
5617                 usc_DmaCmd( info, DmaCmd_InitRxChannel );
5618                 if ( info->params.flags & HDLC_FLAG_AUTO_DCD )
5619                         usc_EnableReceiver(info,ENABLE_AUTO_DCD);
5620                 else
5621                         usc_EnableReceiver(info,ENABLE_UNCONDITIONAL);
5622         }
5623         else
5624         {
5625                 /* This empties the receive FIFO and loads the RCC with RCLR */
5626                 usc_OutReg( info, CCSR, (u16)(usc_InReg(info,CCSR) | BIT13) );
5627                 usc_RTCmd( info, RTCmd_PurgeRxFifo );
5628         }
5629
5630 }       /* end of usc_process_rxoverrun_sync() */
5631
5632 /* usc_stop_receiver()
5633  *
5634  *      Disable USC receiver
5635  *
5636  * Arguments:           info    pointer to device instance data
5637  * Return Value:        None
5638  */
5639 void usc_stop_receiver( struct mgsl_struct *info )
5640 {
5641         if (debug_level >= DEBUG_LEVEL_ISR)
5642                 printk("%s(%d):usc_stop_receiver(%s)\n",
5643                          __FILE__,__LINE__, info->device_name );
5644                          
5645         /* Disable receive DMA channel. */
5646         /* This also disables receive DMA channel interrupts */
5647         usc_DmaCmd( info, DmaCmd_ResetRxChannel );
5648
5649         usc_UnlatchRxstatusBits( info, RXSTATUS_ALL );
5650         usc_ClearIrqPendingBits( info, RECEIVE_DATA + RECEIVE_STATUS );
5651         usc_DisableInterrupts( info, RECEIVE_DATA + RECEIVE_STATUS );
5652
5653         usc_EnableReceiver(info,DISABLE_UNCONDITIONAL);
5654
5655         /* This empties the receive FIFO and loads the RCC with RCLR */
5656         usc_OutReg( info, CCSR, (u16)(usc_InReg(info,CCSR) | BIT13) );
5657         usc_RTCmd( info, RTCmd_PurgeRxFifo );
5658
5659         info->rx_enabled = 0;
5660         info->rx_overflow = 0;
5661         info->rx_rcc_underrun = 0;
5662         
5663 }       /* end of stop_receiver() */
5664
5665 /* usc_start_receiver()
5666  *
5667  *      Enable the USC receiver 
5668  *
5669  * Arguments:           info    pointer to device instance data
5670  * Return Value:        None
5671  */
5672 void usc_start_receiver( struct mgsl_struct *info )
5673 {
5674         u32 phys_addr;
5675         
5676         if (debug_level >= DEBUG_LEVEL_ISR)
5677                 printk("%s(%d):usc_start_receiver(%s)\n",
5678                          __FILE__,__LINE__, info->device_name );
5679
5680         mgsl_reset_rx_dma_buffers( info );
5681         usc_stop_receiver( info );
5682
5683         usc_OutReg( info, CCSR, (u16)(usc_InReg(info,CCSR) | BIT13) );
5684         usc_RTCmd( info, RTCmd_PurgeRxFifo );
5685
5686         if ( info->params.mode == MGSL_MODE_HDLC ||
5687                 info->params.mode == MGSL_MODE_RAW ) {
5688                 /* DMA mode Transfers */
5689                 /* Program the DMA controller. */
5690                 /* Enable the DMA controller end of buffer interrupt. */
5691
5692                 /* program 16C32 with physical address of 1st DMA buffer entry */
5693                 phys_addr = info->rx_buffer_list[0].phys_entry;
5694                 usc_OutDmaReg( info, NRARL, (u16)phys_addr );
5695                 usc_OutDmaReg( info, NRARU, (u16)(phys_addr >> 16) );
5696
5697                 usc_UnlatchRxstatusBits( info, RXSTATUS_ALL );
5698                 usc_ClearIrqPendingBits( info, RECEIVE_DATA + RECEIVE_STATUS );
5699                 usc_EnableInterrupts( info, RECEIVE_STATUS );
5700
5701                 /* 1. Arm End of Buffer (EOB) Receive DMA Interrupt (BIT2 of RDIAR) */
5702                 /* 2. Enable Receive DMA Interrupts (BIT1 of DICR) */
5703
5704                 usc_OutDmaReg( info, RDIAR, BIT3 + BIT2 );
5705                 usc_OutDmaReg( info, DICR, (u16)(usc_InDmaReg(info,DICR) | BIT1) );
5706                 usc_DmaCmd( info, DmaCmd_InitRxChannel );
5707                 if ( info->params.flags & HDLC_FLAG_AUTO_DCD )
5708                         usc_EnableReceiver(info,ENABLE_AUTO_DCD);
5709                 else
5710                         usc_EnableReceiver(info,ENABLE_UNCONDITIONAL);
5711         } else {
5712                 usc_UnlatchRxstatusBits(info, RXSTATUS_ALL);
5713                 usc_ClearIrqPendingBits(info, RECEIVE_DATA + RECEIVE_STATUS);
5714                 usc_EnableInterrupts(info, RECEIVE_DATA);
5715
5716                 usc_RTCmd( info, RTCmd_PurgeRxFifo );
5717                 usc_RCmd( info, RCmd_EnterHuntmode );
5718
5719                 usc_EnableReceiver(info,ENABLE_UNCONDITIONAL);
5720         }
5721
5722         usc_OutReg( info, CCSR, 0x1020 );
5723
5724         info->rx_enabled = 1;
5725
5726 }       /* end of usc_start_receiver() */
5727
5728 /* usc_start_transmitter()
5729  *
5730  *      Enable the USC transmitter and send a transmit frame if
5731  *      one is loaded in the DMA buffers.
5732  *
5733  * Arguments:           info    pointer to device instance data
5734  * Return Value:        None
5735  */
5736 void usc_start_transmitter( struct mgsl_struct *info )
5737 {
5738         u32 phys_addr;
5739         unsigned int FrameSize;
5740
5741         if (debug_level >= DEBUG_LEVEL_ISR)
5742                 printk("%s(%d):usc_start_transmitter(%s)\n",
5743                          __FILE__,__LINE__, info->device_name );
5744                          
5745         if ( info->xmit_cnt ) {
5746
5747                 /* If auto RTS enabled and RTS is inactive, then assert */
5748                 /* RTS and set a flag indicating that the driver should */
5749                 /* negate RTS when the transmission completes. */
5750
5751                 info->drop_rts_on_tx_done = 0;
5752
5753                 if ( info->params.flags & HDLC_FLAG_AUTO_RTS ) {
5754                         usc_get_serial_signals( info );
5755                         if ( !(info->serial_signals & SerialSignal_RTS) ) {
5756                                 info->serial_signals |= SerialSignal_RTS;
5757                                 usc_set_serial_signals( info );
5758                                 info->drop_rts_on_tx_done = 1;
5759                         }
5760                 }
5761
5762
5763                 if ( info->params.mode == MGSL_MODE_ASYNC ) {
5764                         if ( !info->tx_active ) {
5765                                 usc_UnlatchTxstatusBits(info, TXSTATUS_ALL);
5766                                 usc_ClearIrqPendingBits(info, TRANSMIT_STATUS + TRANSMIT_DATA);
5767                                 usc_EnableInterrupts(info, TRANSMIT_DATA);
5768                                 usc_load_txfifo(info);
5769                         }
5770                 } else {
5771                         /* Disable transmit DMA controller while programming. */
5772                         usc_DmaCmd( info, DmaCmd_ResetTxChannel );
5773                         
5774                         /* Transmit DMA buffer is loaded, so program USC */
5775                         /* to send the frame contained in the buffers.   */
5776
5777                         FrameSize = info->tx_buffer_list[info->start_tx_dma_buffer].rcc;
5778
5779                         /* if operating in Raw sync mode, reset the rcc component
5780                          * of the tx dma buffer entry, otherwise, the serial controller
5781                          * will send a closing sync char after this count.
5782                          */
5783                         if ( info->params.mode == MGSL_MODE_RAW )
5784                                 info->tx_buffer_list[info->start_tx_dma_buffer].rcc = 0;
5785
5786                         /* Program the Transmit Character Length Register (TCLR) */
5787                         /* and clear FIFO (TCC is loaded with TCLR on FIFO clear) */
5788                         usc_OutReg( info, TCLR, (u16)FrameSize );
5789
5790                         usc_RTCmd( info, RTCmd_PurgeTxFifo );
5791
5792                         /* Program the address of the 1st DMA Buffer Entry in linked list */
5793                         phys_addr = info->tx_buffer_list[info->start_tx_dma_buffer].phys_entry;
5794                         usc_OutDmaReg( info, NTARL, (u16)phys_addr );
5795                         usc_OutDmaReg( info, NTARU, (u16)(phys_addr >> 16) );
5796
5797                         usc_UnlatchTxstatusBits( info, TXSTATUS_ALL );
5798                         usc_ClearIrqPendingBits( info, TRANSMIT_STATUS );
5799                         usc_EnableInterrupts( info, TRANSMIT_STATUS );
5800
5801                         if ( info->params.mode == MGSL_MODE_RAW &&
5802                                         info->num_tx_dma_buffers > 1 ) {
5803                            /* When running external sync mode, attempt to 'stream' transmit  */
5804                            /* by filling tx dma buffers as they become available. To do this */
5805                            /* we need to enable Tx DMA EOB Status interrupts :               */
5806                            /*                                                                */
5807                            /* 1. Arm End of Buffer (EOB) Transmit DMA Interrupt (BIT2 of TDIAR) */
5808                            /* 2. Enable Transmit DMA Interrupts (BIT0 of DICR) */
5809
5810                            usc_OutDmaReg( info, TDIAR, BIT2|BIT3 );
5811                            usc_OutDmaReg( info, DICR, (u16)(usc_InDmaReg(info,DICR) | BIT0) );
5812                         }
5813
5814                         /* Initialize Transmit DMA Channel */
5815                         usc_DmaCmd( info, DmaCmd_InitTxChannel );
5816                         
5817                         usc_TCmd( info, TCmd_SendFrame );
5818                         
5819                         info->tx_timer.expires = jiffies + jiffies_from_ms(5000);
5820                         add_timer(&info->tx_timer);     
5821                 }
5822                 info->tx_active = 1;
5823         }
5824
5825         if ( !info->tx_enabled ) {
5826                 info->tx_enabled = 1;
5827                 if ( info->params.flags & HDLC_FLAG_AUTO_CTS )
5828                         usc_EnableTransmitter(info,ENABLE_AUTO_CTS);
5829                 else
5830                         usc_EnableTransmitter(info,ENABLE_UNCONDITIONAL);
5831         }
5832
5833 }       /* end of usc_start_transmitter() */
5834
5835 /* usc_stop_transmitter()
5836  *
5837  *      Stops the transmitter and DMA
5838  *
5839  * Arguments:           info    pointer to device isntance data
5840  * Return Value:        None
5841  */
5842 void usc_stop_transmitter( struct mgsl_struct *info )
5843 {
5844         if (debug_level >= DEBUG_LEVEL_ISR)
5845                 printk("%s(%d):usc_stop_transmitter(%s)\n",
5846                          __FILE__,__LINE__, info->device_name );
5847                          
5848         del_timer(&info->tx_timer);     
5849                          
5850         usc_UnlatchTxstatusBits( info, TXSTATUS_ALL );
5851         usc_ClearIrqPendingBits( info, TRANSMIT_STATUS + TRANSMIT_DATA );
5852         usc_DisableInterrupts( info, TRANSMIT_STATUS + TRANSMIT_DATA );
5853
5854         usc_EnableTransmitter(info,DISABLE_UNCONDITIONAL);
5855         usc_DmaCmd( info, DmaCmd_ResetTxChannel );
5856         usc_RTCmd( info, RTCmd_PurgeTxFifo );
5857
5858         info->tx_enabled = 0;
5859         info->tx_active  = 0;
5860
5861 }       /* end of usc_stop_transmitter() */
5862
5863 /* usc_load_txfifo()
5864  *
5865  *      Fill the transmit FIFO until the FIFO is full or
5866  *      there is no more data to load.
5867  *
5868  * Arguments:           info    pointer to device extension (instance data)
5869  * Return Value:        None
5870  */
5871 void usc_load_txfifo( struct mgsl_struct *info )
5872 {
5873         int Fifocount;
5874         u8 TwoBytes[2];
5875         
5876         if ( !info->xmit_cnt && !info->x_char )
5877                 return; 
5878                 
5879         /* Select transmit FIFO status readback in TICR */
5880         usc_TCmd( info, TCmd_SelectTicrTxFifostatus );
5881
5882         /* load the Transmit FIFO until FIFOs full or all data sent */
5883
5884         while( (Fifocount = usc_InReg(info, TICR) >> 8) && info->xmit_cnt ) {
5885                 /* there is more space in the transmit FIFO and */
5886                 /* there is more data in transmit buffer */
5887
5888                 if ( (info->xmit_cnt > 1) && (Fifocount > 1) && !info->x_char ) {
5889                         /* write a 16-bit word from transmit buffer to 16C32 */
5890                                 
5891                         TwoBytes[0] = info->xmit_buf[info->xmit_tail++];
5892                         info->xmit_tail = info->xmit_tail & (SERIAL_XMIT_SIZE-1);
5893                         TwoBytes[1] = info->xmit_buf[info->xmit_tail++];
5894                         info->xmit_tail = info->xmit_tail & (SERIAL_XMIT_SIZE-1);
5895                         
5896                         outw( *((u16 *)TwoBytes), info->io_base + DATAREG);
5897                                 
5898                         info->xmit_cnt -= 2;
5899                         info->icount.tx += 2;
5900                 } else {
5901                         /* only 1 byte left to transmit or 1 FIFO slot left */
5902                         
5903                         outw( (inw( info->io_base + CCAR) & 0x0780) | (TDR+LSBONLY),
5904                                 info->io_base + CCAR );
5905                         
5906                         if (info->x_char) {
5907                                 /* transmit pending high priority char */
5908                                 outw( info->x_char,info->io_base + CCAR );
5909                                 info->x_char = 0;
5910                         } else {
5911                                 outw( info->xmit_buf[info->xmit_tail++],info->io_base + CCAR );
5912                                 info->xmit_tail = info->xmit_tail & (SERIAL_XMIT_SIZE-1);
5913                                 info->xmit_cnt--;
5914                         }
5915                         info->icount.tx++;
5916                 }
5917         }
5918
5919 }       /* end of usc_load_txfifo() */
5920
5921 /* usc_reset()
5922  *
5923  *      Reset the adapter to a known state and prepare it for further use.
5924  *
5925  * Arguments:           info    pointer to device instance data
5926  * Return Value:        None
5927  */
5928 void usc_reset( struct mgsl_struct *info )
5929 {
5930         if ( info->bus_type == MGSL_BUS_TYPE_PCI ) {
5931                 int i;
5932                 u32 readval;
5933
5934                 /* Set BIT30 of Misc Control Register */
5935                 /* (Local Control Register 0x50) to force reset of USC. */
5936
5937                 volatile u32 *MiscCtrl = (u32 *)(info->lcr_base + 0x50);
5938                 u32 *LCR0BRDR = (u32 *)(info->lcr_base + 0x28);
5939
5940                 info->misc_ctrl_value |= BIT30;
5941                 *MiscCtrl = info->misc_ctrl_value;
5942
5943                 /*
5944                  * Force at least 170ns delay before clearing 
5945                  * reset bit. Each read from LCR takes at least 
5946                  * 30ns so 10 times for 300ns to be safe.
5947                  */
5948                 for(i=0;i<10;i++)
5949                         readval = *MiscCtrl;
5950
5951                 info->misc_ctrl_value &= ~BIT30;
5952                 *MiscCtrl = info->misc_ctrl_value;
5953
5954                 *LCR0BRDR = BUS_DESCRIPTOR(
5955                         1,              // Write Strobe Hold (0-3)
5956                         2,              // Write Strobe Delay (0-3)
5957                         2,              // Read Strobe Delay  (0-3)
5958                         0,              // NWDD (Write data-data) (0-3)
5959                         4,              // NWAD (Write Addr-data) (0-31)
5960                         0,              // NXDA (Read/Write Data-Addr) (0-3)
5961                         0,              // NRDD (Read Data-Data) (0-3)
5962                         5               // NRAD (Read Addr-Data) (0-31)
5963                         );
5964         } else {
5965                 /* do HW reset */
5966                 outb( 0,info->io_base + 8 );
5967         }
5968
5969         info->mbre_bit = 0;
5970         info->loopback_bits = 0;
5971         info->usc_idle_mode = 0;
5972
5973         /*
5974          * Program the Bus Configuration Register (BCR)
5975          *
5976          * <15>         0       Don't use separate address
5977          * <14..6>      0       reserved
5978          * <5..4>       00      IAckmode = Default, don't care
5979          * <3>          1       Bus Request Totem Pole output
5980          * <2>          1       Use 16 Bit data bus
5981          * <1>          0       IRQ Totem Pole output
5982          * <0>          0       Don't Shift Right Addr
5983          *
5984          * 0000 0000 0000 1100 = 0x000c
5985          *
5986          * By writing to io_base + SDPIN the Wait/Ack pin is
5987          * programmed to work as a Wait pin.
5988          */
5989         
5990         outw( 0x000c,info->io_base + SDPIN );
5991
5992
5993         outw( 0,info->io_base );
5994         outw( 0,info->io_base + CCAR );
5995
5996         /* select little endian byte ordering */
5997         usc_RTCmd( info, RTCmd_SelectLittleEndian );
5998
5999
6000         /* Port Control Register (PCR)
6001          *
6002          * <15..14>     11      Port 7 is Output (~DMAEN, Bit 14 : 0 = Enabled)
6003          * <13..12>     11      Port 6 is Output (~INTEN, Bit 12 : 0 = Enabled)
6004          * <11..10>     00      Port 5 is Input (No Connect, Don't Care)
6005          * <9..8>       00      Port 4 is Input (No Connect, Don't Care)
6006          * <7..6>       11      Port 3 is Output (~RTS, Bit 6 : 0 = Enabled )
6007          * <5..4>       11      Port 2 is Output (~DTR, Bit 4 : 0 = Enabled )
6008          * <3..2>       01      Port 1 is Input (Dedicated RxC)
6009          * <1..0>       01      Port 0 is Input (Dedicated TxC)
6010          *
6011          *      1111 0000 1111 0101 = 0xf0f5
6012          */
6013
6014         usc_OutReg( info, PCR, 0xf0f5 );
6015
6016
6017         /*
6018          * Input/Output Control Register
6019          *
6020          * <15..14>     00      CTS is active low input
6021          * <13..12>     00      DCD is active low input
6022          * <11..10>     00      TxREQ pin is input (DSR)
6023          * <9..8>       00      RxREQ pin is input (RI)
6024          * <7..6>       00      TxD is output (Transmit Data)
6025          * <5..3>       000     TxC Pin in Input (14.7456MHz Clock)
6026          * <2..0>       100     RxC is Output (drive with BRG0)
6027          *
6028          *      0000 0000 0000 0100 = 0x0004
6029          */
6030
6031         usc_OutReg( info, IOCR, 0x0004 );
6032
6033 }       /* end of usc_reset() */
6034
6035 /* usc_set_async_mode()
6036  *
6037  *      Program adapter for asynchronous communications.
6038  *
6039  * Arguments:           info            pointer to device instance data
6040  * Return Value:        None
6041  */
6042 void usc_set_async_mode( struct mgsl_struct *info )
6043 {
6044         u16 RegValue;
6045
6046         /* disable interrupts while programming USC */
6047         usc_DisableMasterIrqBit( info );
6048
6049         outw( 0, info->io_base );                       /* clear Master Bus Enable (DCAR) */
6050         usc_DmaCmd( info, DmaCmd_ResetAllChannels );    /* disable both DMA channels */
6051
6052         usc_loopback_frame( info );
6053
6054         /* Channel mode Register (CMR)
6055          *
6056          * <15..14>     00      Tx Sub modes, 00 = 1 Stop Bit
6057          * <13..12>     00                    00 = 16X Clock
6058          * <11..8>      0000    Transmitter mode = Asynchronous
6059          * <7..6>       00      reserved?
6060          * <5..4>       00      Rx Sub modes, 00 = 16X Clock
6061          * <3..0>       0000    Receiver mode = Asynchronous
6062          *
6063          * 0000 0000 0000 0000 = 0x0
6064          */
6065
6066         RegValue = 0;
6067         if ( info->params.stop_bits != 1 )
6068                 RegValue |= BIT14;
6069         usc_OutReg( info, CMR, RegValue );
6070
6071         
6072         /* Receiver mode Register (RMR)
6073          *
6074          * <15..13>     000     encoding = None
6075          * <12..08>     00000   reserved (Sync Only)
6076          * <7..6>       00      Even parity
6077          * <5>          0       parity disabled
6078          * <4..2>       000     Receive Char Length = 8 bits
6079          * <1..0>       00      Disable Receiver
6080          *
6081          * 0000 0000 0000 0000 = 0x0
6082          */
6083
6084         RegValue = 0;
6085
6086         if ( info->params.data_bits != 8 )
6087                 RegValue |= BIT4+BIT3+BIT2;
6088
6089         if ( info->params.parity != ASYNC_PARITY_NONE ) {
6090                 RegValue |= BIT5;
6091                 if ( info->params.parity != ASYNC_PARITY_ODD )
6092                         RegValue |= BIT6;
6093         }
6094
6095         usc_OutReg( info, RMR, RegValue );
6096
6097
6098         /* Set IRQ trigger level */
6099
6100         usc_RCmd( info, RCmd_SelectRicrIntLevel );
6101
6102         
6103         /* Receive Interrupt Control Register (RICR)
6104          *
6105          * <15..8>      ?               RxFIFO IRQ Request Level
6106          *
6107          * Note: For async mode the receive FIFO level must be set
6108          * to 0 to aviod the situation where the FIFO contains fewer bytes
6109          * than the trigger level and no more data is expected.
6110          *
6111          * <7>          0               Exited Hunt IA (Interrupt Arm)
6112          * <6>          0               Idle Received IA
6113          * <5>          0               Break/Abort IA
6114          * <4>          0               Rx Bound IA
6115          * <3>          0               Queued status reflects oldest byte in FIFO
6116          * <2>          0               Abort/PE IA
6117          * <1>          0               Rx Overrun IA
6118          * <0>          0               Select TC0 value for readback
6119          *
6120          * 0000 0000 0100 0000 = 0x0000 + (FIFOLEVEL in MSB)
6121          */
6122         
6123         usc_OutReg( info, RICR, 0x0000 );
6124
6125         usc_UnlatchRxstatusBits( info, RXSTATUS_ALL );
6126         usc_ClearIrqPendingBits( info, RECEIVE_STATUS );
6127
6128         
6129         /* Transmit mode Register (TMR)
6130          *
6131          * <15..13>     000     encoding = None
6132          * <12..08>     00000   reserved (Sync Only)
6133          * <7..6>       00      Transmit parity Even
6134          * <5>          0       Transmit parity Disabled
6135          * <4..2>       000     Tx Char Length = 8 bits
6136          * <1..0>       00      Disable Transmitter
6137          *
6138          * 0000 0000 0000 0000 = 0x0
6139          */
6140
6141         RegValue = 0;
6142
6143         if ( info->params.data_bits != 8 )
6144                 RegValue |= BIT4+BIT3+BIT2;
6145
6146         if ( info->params.parity != ASYNC_PARITY_NONE ) {
6147                 RegValue |= BIT5;
6148                 if ( info->params.parity != ASYNC_PARITY_ODD )
6149                         RegValue |= BIT6;
6150         }
6151
6152         usc_OutReg( info, TMR, RegValue );
6153
6154         usc_set_txidle( info );
6155
6156
6157         /* Set IRQ trigger level */
6158
6159         usc_TCmd( info, TCmd_SelectTicrIntLevel );
6160
6161         
6162         /* Transmit Interrupt Control Register (TICR)
6163          *
6164          * <15..8>      ?       Transmit FIFO IRQ Level
6165          * <7>          0       Present IA (Interrupt Arm)
6166          * <6>          1       Idle Sent IA
6167          * <5>          0       Abort Sent IA
6168          * <4>          0       EOF/EOM Sent IA
6169          * <3>          0       CRC Sent IA
6170          * <2>          0       1 = Wait for SW Trigger to Start Frame
6171          * <1>          0       Tx Underrun IA
6172          * <0>          0       TC0 constant on read back
6173          *
6174          *      0000 0000 0100 0000 = 0x0040
6175          */
6176
6177         usc_OutReg( info, TICR, 0x1f40 );
6178
6179         usc_UnlatchTxstatusBits( info, TXSTATUS_ALL );
6180         usc_ClearIrqPendingBits( info, TRANSMIT_STATUS );
6181
6182         usc_enable_async_clock( info, info->params.data_rate );
6183
6184         
6185         /* Channel Control/status Register (CCSR)
6186          *
6187          * <15>         X       RCC FIFO Overflow status (RO)
6188          * <14>         X       RCC FIFO Not Empty status (RO)
6189          * <13>         0       1 = Clear RCC FIFO (WO)
6190          * <12>         X       DPLL in Sync status (RO)
6191          * <11>         X       DPLL 2 Missed Clocks status (RO)
6192          * <10>         X       DPLL 1 Missed Clock status (RO)
6193          * <9..8>       00      DPLL Resync on rising and falling edges (RW)
6194          * <7>          X       SDLC Loop On status (RO)
6195          * <6>          X       SDLC Loop Send status (RO)
6196          * <5>          1       Bypass counters for TxClk and RxClk (RW)
6197          * <4..2>       000     Last Char of SDLC frame has 8 bits (RW)
6198          * <1..0>       00      reserved
6199          *
6200          *      0000 0000 0010 0000 = 0x0020
6201          */
6202         
6203         usc_OutReg( info, CCSR, 0x0020 );
6204
6205         usc_DisableInterrupts( info, TRANSMIT_STATUS + TRANSMIT_DATA +
6206                               RECEIVE_DATA + RECEIVE_STATUS );
6207
6208         usc_ClearIrqPendingBits( info, TRANSMIT_STATUS + TRANSMIT_DATA +
6209                                 RECEIVE_DATA + RECEIVE_STATUS );
6210
6211         usc_EnableMasterIrqBit( info );
6212
6213         if (info->bus_type == MGSL_BUS_TYPE_ISA) {
6214                 /* Enable INTEN (Port 6, Bit12) */
6215                 /* This connects the IRQ request signal to the ISA bus */
6216                 usc_OutReg(info, PCR, (u16)((usc_InReg(info, PCR) | BIT13) & ~BIT12));
6217         }
6218
6219 }       /* end of usc_set_async_mode() */
6220
6221 /* usc_loopback_frame()
6222  *
6223  *      Loop back a small (2 byte) dummy SDLC frame.
6224  *      Interrupts and DMA are NOT used. The purpose of this is to
6225  *      clear any 'stale' status info left over from running in async mode.
6226  *
6227  *      The 16C32 shows the strange behaviour of marking the 1st
6228  *      received SDLC frame with a CRC error even when there is no
6229  *      CRC error. To get around this a small dummy from of 2 bytes
6230  *      is looped back when switching from async to sync mode.
6231  *
6232  * Arguments:           info            pointer to device instance data
6233  * Return Value:        None
6234  */
6235 void usc_loopback_frame( struct mgsl_struct *info )
6236 {
6237         int i;
6238         unsigned long oldmode = info->params.mode;
6239
6240         info->params.mode = MGSL_MODE_HDLC;
6241         
6242         usc_DisableMasterIrqBit( info );
6243
6244         usc_set_sdlc_mode( info );
6245         usc_enable_loopback( info, 1 );
6246
6247         /* Write 16-bit Time Constant for BRG0 */
6248         usc_OutReg( info, TC0R, 0 );
6249         
6250         /* Channel Control Register (CCR)
6251          *
6252          * <15..14>     00      Don't use 32-bit Tx Control Blocks (TCBs)
6253          * <13>         0       Trigger Tx on SW Command Disabled
6254          * <12>         0       Flag Preamble Disabled
6255          * <11..10>     00      Preamble Length = 8-Bits
6256          * <9..8>       01      Preamble Pattern = flags
6257          * <7..6>       10      Don't use 32-bit Rx status Blocks (RSBs)
6258          * <5>          0       Trigger Rx on SW Command Disabled
6259          * <4..0>       0       reserved
6260          *
6261          *      0000 0001 0000 0000 = 0x0100
6262          */
6263
6264         usc_OutReg( info, CCR, 0x0100 );
6265
6266         /* SETUP RECEIVER */
6267         usc_RTCmd( info, RTCmd_PurgeRxFifo );
6268         usc_EnableReceiver(info,ENABLE_UNCONDITIONAL);
6269
6270         /* SETUP TRANSMITTER */
6271         /* Program the Transmit Character Length Register (TCLR) */
6272         /* and clear FIFO (TCC is loaded with TCLR on FIFO clear) */
6273         usc_OutReg( info, TCLR, 2 );
6274         usc_RTCmd( info, RTCmd_PurgeTxFifo );
6275
6276         /* unlatch Tx status bits, and start transmit channel. */
6277         usc_UnlatchTxstatusBits(info,TXSTATUS_ALL);
6278         outw(0,info->io_base + DATAREG);
6279
6280         /* ENABLE TRANSMITTER */
6281         usc_TCmd( info, TCmd_SendFrame );
6282         usc_EnableTransmitter(info,ENABLE_UNCONDITIONAL);
6283                                                         
6284         /* WAIT FOR RECEIVE COMPLETE */
6285         for (i=0 ; i<1000 ; i++)
6286                 if (usc_InReg( info, RCSR ) & (BIT8 + BIT4 + BIT3 + BIT1))
6287                         break;
6288
6289         /* clear Internal Data loopback mode */
6290         usc_enable_loopback(info, 0);
6291
6292         usc_EnableMasterIrqBit(info);
6293
6294         info->params.mode = oldmode;
6295
6296 }       /* end of usc_loopback_frame() */
6297
6298 /* usc_set_sync_mode()  Programs the USC for SDLC communications.
6299  *
6300  * Arguments:           info    pointer to adapter info structure
6301  * Return Value:        None
6302  */
6303 void usc_set_sync_mode( struct mgsl_struct *info )
6304 {
6305         usc_loopback_frame( info );
6306         usc_set_sdlc_mode( info );
6307
6308         if (info->bus_type == MGSL_BUS_TYPE_ISA) {
6309                 /* Enable INTEN (Port 6, Bit12) */
6310                 /* This connects the IRQ request signal to the ISA bus */
6311                 usc_OutReg(info, PCR, (u16)((usc_InReg(info, PCR) | BIT13) & ~BIT12));
6312         }
6313
6314         usc_enable_aux_clock(info, info->params.clock_speed);
6315
6316         if (info->params.loopback)
6317                 usc_enable_loopback(info,1);
6318
6319 }       /* end of mgsl_set_sync_mode() */
6320
6321 /* usc_set_txidle()     Set the HDLC idle mode for the transmitter.
6322  *
6323  * Arguments:           info    pointer to device instance data
6324  * Return Value:        None
6325  */
6326 void usc_set_txidle( struct mgsl_struct *info )
6327 {
6328         u16 usc_idle_mode = IDLEMODE_FLAGS;
6329
6330         /* Map API idle mode to USC register bits */
6331
6332         switch( info->idle_mode ){
6333         case HDLC_TXIDLE_FLAGS:                 usc_idle_mode = IDLEMODE_FLAGS; break;
6334         case HDLC_TXIDLE_ALT_ZEROS_ONES:        usc_idle_mode = IDLEMODE_ALT_ONE_ZERO; break;
6335         case HDLC_TXIDLE_ZEROS:                 usc_idle_mode = IDLEMODE_ZERO; break;
6336         case HDLC_TXIDLE_ONES:                  usc_idle_mode = IDLEMODE_ONE; break;
6337         case HDLC_TXIDLE_ALT_MARK_SPACE:        usc_idle_mode = IDLEMODE_ALT_MARK_SPACE; break;
6338         case HDLC_TXIDLE_SPACE:                 usc_idle_mode = IDLEMODE_SPACE; break;
6339         case HDLC_TXIDLE_MARK:                  usc_idle_mode = IDLEMODE_MARK; break;
6340         }
6341
6342         info->usc_idle_mode = usc_idle_mode;
6343         //usc_OutReg(info, TCSR, usc_idle_mode);
6344         info->tcsr_value &= ~IDLEMODE_MASK;     /* clear idle mode bits */
6345         info->tcsr_value += usc_idle_mode;
6346         usc_OutReg(info, TCSR, info->tcsr_value);
6347
6348         /*
6349          * if SyncLink WAN adapter is running in external sync mode, the
6350          * transmitter has been set to Monosync in order to try to mimic
6351          * a true raw outbound bit stream. Monosync still sends an open/close
6352          * sync char at the start/end of a frame. Try to match those sync
6353          * patterns to the idle mode set here
6354          */
6355         if ( info->params.mode == MGSL_MODE_RAW ) {
6356                 unsigned char syncpat = 0;
6357                 switch( info->idle_mode ) {
6358                 case HDLC_TXIDLE_FLAGS:
6359                         syncpat = 0x7e;
6360                         break;
6361                 case HDLC_TXIDLE_ALT_ZEROS_ONES:
6362                         syncpat = 0x55;
6363                         break;
6364                 case HDLC_TXIDLE_ZEROS:
6365                 case HDLC_TXIDLE_SPACE:
6366                         syncpat = 0x00;
6367                         break;
6368                 case HDLC_TXIDLE_ONES:
6369                 case HDLC_TXIDLE_MARK:
6370                         syncpat = 0xff;
6371                         break;
6372                 case HDLC_TXIDLE_ALT_MARK_SPACE:
6373                         syncpat = 0xaa;
6374                         break;
6375                 }
6376
6377                 usc_SetTransmitSyncChars(info,syncpat,syncpat);
6378         }
6379
6380 }       /* end of usc_set_txidle() */
6381
6382 /* usc_get_serial_signals()
6383  *
6384  *      Query the adapter for the state of the V24 status (input) signals.
6385  *
6386  * Arguments:           info    pointer to device instance data
6387  * Return Value:        None
6388  */
6389 void usc_get_serial_signals( struct mgsl_struct *info )
6390 {
6391         u16 status;
6392
6393         /* clear all serial signals except DTR and RTS */
6394         info->serial_signals &= SerialSignal_DTR + SerialSignal_RTS;
6395
6396         /* Read the Misc Interrupt status Register (MISR) to get */
6397         /* the V24 status signals. */
6398
6399         status = usc_InReg( info, MISR );
6400
6401         /* set serial signal bits to reflect MISR */
6402
6403         if ( status & MISCSTATUS_CTS )
6404                 info->serial_signals |= SerialSignal_CTS;
6405
6406         if ( status & MISCSTATUS_DCD )
6407                 info->serial_signals |= SerialSignal_DCD;
6408
6409         if ( status & MISCSTATUS_RI )
6410                 info->serial_signals |= SerialSignal_RI;
6411
6412         if ( status & MISCSTATUS_DSR )
6413                 info->serial_signals |= SerialSignal_DSR;
6414
6415 }       /* end of usc_get_serial_signals() */
6416
6417 /* usc_set_serial_signals()
6418  *
6419  *      Set the state of DTR and RTS based on contents of
6420  *      serial_signals member of device extension.
6421  *      
6422  * Arguments:           info    pointer to device instance data
6423  * Return Value:        None
6424  */
6425 void usc_set_serial_signals( struct mgsl_struct *info )
6426 {
6427         u16 Control;
6428         unsigned char V24Out = info->serial_signals;
6429
6430         /* get the current value of the Port Control Register (PCR) */
6431
6432         Control = usc_InReg( info, PCR );
6433
6434         if ( V24Out & SerialSignal_RTS )
6435                 Control &= ~(BIT6);
6436         else
6437                 Control |= BIT6;
6438
6439         if ( V24Out & SerialSignal_DTR )
6440                 Control &= ~(BIT4);
6441         else
6442                 Control |= BIT4;
6443
6444         usc_OutReg( info, PCR, Control );
6445
6446 }       /* end of usc_set_serial_signals() */
6447
6448 /* usc_enable_async_clock()
6449  *
6450  *      Enable the async clock at the specified frequency.
6451  *
6452  * Arguments:           info            pointer to device instance data
6453  *                      data_rate       data rate of clock in bps
6454  *                                      0 disables the AUX clock.
6455  * Return Value:        None
6456  */
6457 void usc_enable_async_clock( struct mgsl_struct *info, u32 data_rate )
6458 {
6459         if ( data_rate )        {
6460                 /*
6461                  * Clock mode Control Register (CMCR)
6462                  * 
6463                  * <15..14>     00      counter 1 Disabled
6464                  * <13..12>     00      counter 0 Disabled
6465                  * <11..10>     11      BRG1 Input is TxC Pin
6466                  * <9..8>       11      BRG0 Input is TxC Pin
6467                  * <7..6>       01      DPLL Input is BRG1 Output
6468                  * <5..3>       100     TxCLK comes from BRG0
6469                  * <2..0>       100     RxCLK comes from BRG0
6470                  *
6471                  * 0000 1111 0110 0100 = 0x0f64
6472                  */
6473                 
6474                 usc_OutReg( info, CMCR, 0x0f64 );
6475
6476
6477                 /*
6478                  * Write 16-bit Time Constant for BRG0
6479                  * Time Constant = (ClkSpeed / data_rate) - 1
6480                  * ClkSpeed = 921600 (ISA), 691200 (PCI)
6481                  */
6482
6483                 if ( info->bus_type == MGSL_BUS_TYPE_PCI )
6484                         usc_OutReg( info, TC0R, (u16)((691200/data_rate) - 1) );
6485                 else
6486                         usc_OutReg( info, TC0R, (u16)((921600/data_rate) - 1) );
6487
6488                 
6489                 /*
6490                  * Hardware Configuration Register (HCR)
6491                  * Clear Bit 1, BRG0 mode = Continuous
6492                  * Set Bit 0 to enable BRG0.
6493                  */
6494
6495                 usc_OutReg( info, HCR,
6496                             (u16)((usc_InReg( info, HCR ) & ~BIT1) | BIT0) );
6497
6498
6499                 /* Input/Output Control Reg, <2..0> = 100, Drive RxC pin with BRG0 */
6500
6501                 usc_OutReg( info, IOCR,
6502                             (u16)((usc_InReg(info, IOCR) & 0xfff8) | 0x0004) );
6503         } else {
6504                 /* data rate == 0 so turn off BRG0 */
6505                 usc_OutReg( info, HCR, (u16)(usc_InReg( info, HCR ) & ~BIT0) );
6506         }
6507
6508 }       /* end of usc_enable_async_clock() */
6509
6510 /*
6511  * Buffer Structures:
6512  *
6513  * Normal memory access uses virtual addresses that can make discontiguous
6514  * physical memory pages appear to be contiguous in the virtual address
6515  * space (the processors memory mapping handles the conversions).
6516  *
6517  * DMA transfers require physically contiguous memory. This is because
6518  * the DMA system controller and DMA bus masters deal with memory using
6519  * only physical addresses.
6520  *
6521  * This causes a problem under Windows NT when large DMA buffers are
6522  * needed. Fragmentation of the nonpaged pool prevents allocations of
6523  * physically contiguous buffers larger than the PAGE_SIZE.
6524  *
6525  * However the 16C32 supports Bus Master Scatter/Gather DMA which
6526  * allows DMA transfers to physically discontiguous buffers. Information
6527  * about each data transfer buffer is contained in a memory structure
6528  * called a 'buffer entry'. A list of buffer entries is maintained
6529  * to track and control the use of the data transfer buffers.
6530  *
6531  * To support this strategy we will allocate sufficient PAGE_SIZE
6532  * contiguous memory buffers to allow for the total required buffer
6533  * space.
6534  *
6535  * The 16C32 accesses the list of buffer entries using Bus Master
6536  * DMA. Control information is read from the buffer entries by the
6537  * 16C32 to control data transfers. status information is written to
6538  * the buffer entries by the 16C32 to indicate the status of completed
6539  * transfers.
6540  *
6541  * The CPU writes control information to the buffer entries to control
6542  * the 16C32 and reads status information from the buffer entries to
6543  * determine information about received and transmitted frames.
6544  *
6545  * Because the CPU and 16C32 (adapter) both need simultaneous access
6546  * to the buffer entries, the buffer entry memory is allocated with
6547  * HalAllocateCommonBuffer(). This restricts the size of the buffer
6548  * entry list to PAGE_SIZE.
6549  *
6550  * The actual data buffers on the other hand will only be accessed
6551  * by the CPU or the adapter but not by both simultaneously. This allows
6552  * Scatter/Gather packet based DMA procedures for using physically
6553  * discontiguous pages.
6554  */
6555
6556 /*
6557  * mgsl_reset_tx_dma_buffers()
6558  *
6559  *      Set the count for all transmit buffers to 0 to indicate the
6560  *      buffer is available for use and set the current buffer to the
6561  *      first buffer. This effectively makes all buffers free and
6562  *      discards any data in buffers.
6563  *
6564  * Arguments:           info    pointer to device instance data
6565  * Return Value:        None
6566  */
6567 void mgsl_reset_tx_dma_buffers( struct mgsl_struct *info )
6568 {
6569         unsigned int i;
6570
6571         for ( i = 0; i < info->tx_buffer_count; i++ ) {
6572                 *((unsigned long *)&(info->tx_buffer_list[i].count)) = 0;
6573         }
6574
6575         info->current_tx_buffer = 0;
6576         info->start_tx_dma_buffer = 0;
6577         info->tx_dma_buffers_used = 0;
6578
6579         info->get_tx_holding_index = 0;
6580         info->put_tx_holding_index = 0;
6581         info->tx_holding_count = 0;
6582
6583 }       /* end of mgsl_reset_tx_dma_buffers() */
6584
6585 /*
6586  * num_free_tx_dma_buffers()
6587  *
6588  *      returns the number of free tx dma buffers available
6589  *
6590  * Arguments:           info    pointer to device instance data
6591  * Return Value:        number of free tx dma buffers
6592  */
6593 int num_free_tx_dma_buffers(struct mgsl_struct *info)
6594 {
6595         return info->tx_buffer_count - info->tx_dma_buffers_used;
6596 }
6597
6598 /*
6599  * mgsl_reset_rx_dma_buffers()
6600  * 
6601  *      Set the count for all receive buffers to DMABUFFERSIZE
6602  *      and set the current buffer to the first buffer. This effectively
6603  *      makes all buffers free and discards any data in buffers.
6604  * 
6605  * Arguments:           info    pointer to device instance data
6606  * Return Value:        None
6607  */
6608 void mgsl_reset_rx_dma_buffers( struct mgsl_struct *info )
6609 {
6610         unsigned int i;
6611
6612         for ( i = 0; i < info->rx_buffer_count; i++ ) {
6613                 *((unsigned long *)&(info->rx_buffer_list[i].count)) = DMABUFFERSIZE;
6614 //              info->rx_buffer_list[i].count = DMABUFFERSIZE;
6615 //              info->rx_buffer_list[i].status = 0;
6616         }
6617
6618         info->current_rx_buffer = 0;
6619
6620 }       /* end of mgsl_reset_rx_dma_buffers() */
6621
6622 /*
6623  * mgsl_free_rx_frame_buffers()
6624  * 
6625  *      Free the receive buffers used by a received SDLC
6626  *      frame such that the buffers can be reused.
6627  * 
6628  * Arguments:
6629  * 
6630  *      info                    pointer to device instance data
6631  *      StartIndex              index of 1st receive buffer of frame
6632  *      EndIndex                index of last receive buffer of frame
6633  * 
6634  * Return Value:        None
6635  */
6636 void mgsl_free_rx_frame_buffers( struct mgsl_struct *info, unsigned int StartIndex, unsigned int EndIndex )
6637 {
6638         int Done = 0;
6639         DMABUFFERENTRY *pBufEntry;
6640         unsigned int Index;
6641
6642         /* Starting with 1st buffer entry of the frame clear the status */
6643         /* field and set the count field to DMA Buffer Size. */
6644
6645         Index = StartIndex;
6646
6647         while( !Done ) {
6648                 pBufEntry = &(info->rx_buffer_list[Index]);
6649
6650                 if ( Index == EndIndex ) {
6651                         /* This is the last buffer of the frame! */
6652                         Done = 1;
6653                 }
6654
6655                 /* reset current buffer for reuse */
6656 //              pBufEntry->status = 0;
6657 //              pBufEntry->count = DMABUFFERSIZE;
6658                 *((unsigned long *)&(pBufEntry->count)) = DMABUFFERSIZE;
6659
6660                 /* advance to next buffer entry in linked list */
6661                 Index++;
6662                 if ( Index == info->rx_buffer_count )
6663                         Index = 0;
6664         }
6665
6666         /* set current buffer to next buffer after last buffer of frame */
6667         info->current_rx_buffer = Index;
6668
6669 }       /* end of free_rx_frame_buffers() */
6670
6671 /* mgsl_get_rx_frame()
6672  * 
6673  *      This function attempts to return a received SDLC frame from the
6674  *      receive DMA buffers. Only frames received without errors are returned.
6675  *
6676  * Arguments:           info    pointer to device extension
6677  * Return Value:        1 if frame returned, otherwise 0
6678  */
6679 int mgsl_get_rx_frame(struct mgsl_struct *info)
6680 {
6681         unsigned int StartIndex, EndIndex;      /* index of 1st and last buffers of Rx frame */
6682         unsigned short status;
6683         DMABUFFERENTRY *pBufEntry;
6684         unsigned int framesize = 0;
6685         int ReturnCode = 0;
6686         unsigned long flags;
6687         struct tty_struct *tty = info->tty;
6688         int return_frame = 0;
6689         
6690         /*
6691          * current_rx_buffer points to the 1st buffer of the next available
6692          * receive frame. To find the last buffer of the frame look for
6693          * a non-zero status field in the buffer entries. (The status
6694          * field is set by the 16C32 after completing a receive frame.
6695          */
6696
6697         StartIndex = EndIndex = info->current_rx_buffer;
6698
6699         while( !info->rx_buffer_list[EndIndex].status ) {
6700                 /*
6701                  * If the count field of the buffer entry is non-zero then
6702                  * this buffer has not been used. (The 16C32 clears the count
6703                  * field when it starts using the buffer.) If an unused buffer
6704                  * is encountered then there are no frames available.
6705                  */
6706
6707                 if ( info->rx_buffer_list[EndIndex].count )
6708                         goto Cleanup;
6709
6710                 /* advance to next buffer entry in linked list */
6711                 EndIndex++;
6712                 if ( EndIndex == info->rx_buffer_count )
6713                         EndIndex = 0;
6714
6715                 /* if entire list searched then no frame available */
6716                 if ( EndIndex == StartIndex ) {
6717                         /* If this occurs then something bad happened,
6718                          * all buffers have been 'used' but none mark
6719                          * the end of a frame. Reset buffers and receiver.
6720                          */
6721
6722                         if ( info->rx_enabled ){
6723                                 spin_lock_irqsave(&info->irq_spinlock,flags);
6724                                 usc_start_receiver(info);
6725                                 spin_unlock_irqrestore(&info->irq_spinlock,flags);
6726                         }
6727                         goto Cleanup;
6728                 }
6729         }
6730
6731
6732         /* check status of receive frame */
6733         
6734         status = info->rx_buffer_list[EndIndex].status;
6735
6736         if ( status & (RXSTATUS_SHORT_FRAME + RXSTATUS_OVERRUN +
6737                         RXSTATUS_CRC_ERROR + RXSTATUS_ABORT) ) {
6738                 if ( status & RXSTATUS_SHORT_FRAME )
6739                         info->icount.rxshort++;
6740                 else if ( status & RXSTATUS_ABORT )
6741                         info->icount.rxabort++;
6742                 else if ( status & RXSTATUS_OVERRUN )
6743                         info->icount.rxover++;
6744                 else {
6745                         info->icount.rxcrc++;
6746                         if ( info->params.crc_type & HDLC_CRC_RETURN_EX )
6747                                 return_frame = 1;
6748                 }
6749                 framesize = 0;
6750 #ifdef CONFIG_SYNCLINK_SYNCPPP
6751                 info->netstats.rx_errors++;
6752                 info->netstats.rx_frame_errors++;
6753 #endif
6754         } else
6755                 return_frame = 1;
6756
6757         if ( return_frame ) {
6758                 /* receive frame has no errors, get frame size.
6759                  * The frame size is the starting value of the RCC (which was
6760                  * set to 0xffff) minus the ending value of the RCC (decremented
6761                  * once for each receive character) minus 2 for the 16-bit CRC.
6762                  */
6763
6764                 framesize = RCLRVALUE - info->rx_buffer_list[EndIndex].rcc;
6765
6766                 /* adjust frame size for CRC if any */
6767                 if ( info->params.crc_type == HDLC_CRC_16_CCITT )
6768                         framesize -= 2;
6769                 else if ( info->params.crc_type == HDLC_CRC_32_CCITT )
6770                         framesize -= 4;         
6771         }
6772
6773         if ( debug_level >= DEBUG_LEVEL_BH )
6774                 printk("%s(%d):mgsl_get_rx_frame(%s) status=%04X size=%d\n",
6775                         __FILE__,__LINE__,info->device_name,status,framesize);
6776                         
6777         if ( debug_level >= DEBUG_LEVEL_DATA )
6778                 mgsl_trace_block(info,info->rx_buffer_list[StartIndex].virt_addr,
6779                         MIN(framesize,DMABUFFERSIZE),0);        
6780                 
6781         if (framesize) {
6782                 if ( ( (info->params.crc_type & HDLC_CRC_RETURN_EX) &&
6783                                 ((framesize+1) > info->max_frame_size) ) ||
6784                         (framesize > info->max_frame_size) )
6785                         info->icount.rxlong++;
6786                 else {
6787                         /* copy dma buffer(s) to contiguous intermediate buffer */
6788                         int copy_count = framesize;
6789                         int index = StartIndex;
6790                         unsigned char *ptmp = info->intermediate_rxbuffer;
6791
6792                         if ( !(status & RXSTATUS_CRC_ERROR))
6793                         info->icount.rxok++;
6794                         
6795                         while(copy_count) {
6796                                 int partial_count;
6797                                 if ( copy_count > DMABUFFERSIZE )
6798                                         partial_count = DMABUFFERSIZE;
6799                                 else
6800                                         partial_count = copy_count;
6801                         
6802                                 pBufEntry = &(info->rx_buffer_list[index]);
6803                                 memcpy( ptmp, pBufEntry->virt_addr, partial_count );
6804                                 ptmp += partial_count;
6805                                 copy_count -= partial_count;
6806                                 
6807                                 if ( ++index == info->rx_buffer_count )
6808                                         index = 0;
6809                         }
6810
6811                         if ( info->params.crc_type & HDLC_CRC_RETURN_EX ) {
6812                                 ++framesize;
6813                                 *ptmp = (status & RXSTATUS_CRC_ERROR ?
6814                                                 RX_CRC_ERROR :
6815                                                 RX_OK);
6816
6817                                 if ( debug_level >= DEBUG_LEVEL_DATA )
6818                                         printk("%s(%d):mgsl_get_rx_frame(%s) rx frame status=%d\n",
6819                                                 __FILE__,__LINE__,info->device_name,
6820                                                 *ptmp);
6821                         }
6822
6823 #ifdef CONFIG_SYNCLINK_SYNCPPP
6824                         if (info->netcount) {
6825                                 /* pass frame to syncppp device */
6826                                 mgsl_sppp_rx_done(info,info->intermediate_rxbuffer,framesize);
6827                         } 
6828                         else
6829 #endif
6830                         {
6831                                 /* Call the line discipline receive callback directly. */
6832                                 if ( tty && tty->ldisc.receive_buf )
6833                                 tty->ldisc.receive_buf(tty, info->intermediate_rxbuffer, info->flag_buf, framesize);
6834                         }
6835                 }
6836         }
6837         /* Free the buffers used by this frame. */
6838         mgsl_free_rx_frame_buffers( info, StartIndex, EndIndex );
6839
6840         ReturnCode = 1;
6841
6842 Cleanup:
6843
6844         if ( info->rx_enabled && info->rx_overflow ) {
6845                 /* The receiver needs to restarted because of 
6846                  * a receive overflow (buffer or FIFO). If the 
6847                  * receive buffers are now empty, then restart receiver.
6848                  */
6849
6850                 if ( !info->rx_buffer_list[EndIndex].status &&
6851                         info->rx_buffer_list[EndIndex].count ) {
6852                         spin_lock_irqsave(&info->irq_spinlock,flags);
6853                         usc_start_receiver(info);
6854                         spin_unlock_irqrestore(&info->irq_spinlock,flags);
6855                 }
6856         }
6857
6858         return ReturnCode;
6859
6860 }       /* end of mgsl_get_rx_frame() */
6861
6862 /* mgsl_get_raw_rx_frame()
6863  *
6864  *      This function attempts to return a received frame from the
6865  *      receive DMA buffers when running in external loop mode. In this mode,
6866  *      we will return at most one DMABUFFERSIZE frame to the application.
6867  *      The USC receiver is triggering off of DCD going active to start a new
6868  *      frame, and DCD going inactive to terminate the frame (similar to
6869  *      processing a closing flag character).
6870  *
6871  *      In this routine, we will return DMABUFFERSIZE "chunks" at a time.
6872  *      If DCD goes inactive, the last Rx DMA Buffer will have a non-zero
6873  *      status field and the RCC field will indicate the length of the
6874  *      entire received frame. We take this RCC field and get the modulus
6875  *      of RCC and DMABUFFERSIZE to determine if number of bytes in the
6876  *      last Rx DMA buffer and return that last portion of the frame.
6877  *
6878  * Arguments:           info    pointer to device extension
6879  * Return Value:        1 if frame returned, otherwise 0
6880  */
6881 int mgsl_get_raw_rx_frame(struct mgsl_struct *info)
6882 {
6883         unsigned int CurrentIndex, NextIndex;
6884         unsigned short status;
6885         DMABUFFERENTRY *pBufEntry;
6886         unsigned int framesize = 0;
6887         int ReturnCode = 0;
6888         unsigned long flags;
6889         struct tty_struct *tty = info->tty;
6890
6891         /*
6892          * current_rx_buffer points to the 1st buffer of the next available
6893          * receive frame. The status field is set by the 16C32 after
6894          * completing a receive frame. If the status field of this buffer
6895          * is zero, either the USC is still filling this buffer or this
6896          * is one of a series of buffers making up a received frame.
6897          *
6898          * If the count field of this buffer is zero, the USC is either
6899          * using this buffer or has used this buffer. Look at the count
6900          * field of the next buffer. If that next buffer's count is
6901          * non-zero, the USC is still actively using the current buffer.
6902          * Otherwise, if the next buffer's count field is zero, the
6903          * current buffer is complete and the USC is using the next
6904          * buffer.
6905          */
6906         CurrentIndex = NextIndex = info->current_rx_buffer;
6907         ++NextIndex;
6908         if ( NextIndex == info->rx_buffer_count )
6909                 NextIndex = 0;
6910
6911         if ( info->rx_buffer_list[CurrentIndex].status != 0 ||
6912                 (info->rx_buffer_list[CurrentIndex].count == 0 &&
6913                         info->rx_buffer_list[NextIndex].count == 0)) {
6914                 /*
6915                  * Either the status field of this dma buffer is non-zero
6916                  * (indicating the last buffer of a receive frame) or the next
6917                  * buffer is marked as in use -- implying this buffer is complete
6918                  * and an intermediate buffer for this received frame.
6919                  */
6920
6921                 status = info->rx_buffer_list[CurrentIndex].status;
6922
6923                 if ( status & (RXSTATUS_SHORT_FRAME + RXSTATUS_OVERRUN +
6924                                 RXSTATUS_CRC_ERROR + RXSTATUS_ABORT) ) {
6925                         if ( status & RXSTATUS_SHORT_FRAME )
6926                                 info->icount.rxshort++;
6927                         else if ( status & RXSTATUS_ABORT )
6928                                 info->icount.rxabort++;
6929                         else if ( status & RXSTATUS_OVERRUN )
6930                                 info->icount.rxover++;
6931                         else
6932                                 info->icount.rxcrc++;
6933                         framesize = 0;
6934                 } else {
6935                         /*
6936                          * A receive frame is available, get frame size and status.
6937                          *
6938                          * The frame size is the starting value of the RCC (which was
6939                          * set to 0xffff) minus the ending value of the RCC (decremented
6940                          * once for each receive character) minus 2 or 4 for the 16-bit
6941                          * or 32-bit CRC.
6942                          *
6943                          * If the status field is zero, this is an intermediate buffer.
6944                          * It's size is 4K.
6945                          *
6946                          * If the DMA Buffer Entry's Status field is non-zero, the
6947                          * receive operation completed normally (ie: DCD dropped). The
6948                          * RCC field is valid and holds the received frame size.
6949                          * It is possible that the RCC field will be zero on a DMA buffer
6950                          * entry with a non-zero status. This can occur if the total
6951                          * frame size (number of bytes between the time DCD goes active
6952                          * to the time DCD goes inactive) exceeds 65535 bytes. In this
6953                          * case the 16C32 has underrun on the RCC count and appears to
6954                          * stop updating this counter to let us know the actual received
6955                          * frame size. If this happens (non-zero status and zero RCC),
6956                          * simply return the entire RxDMA Buffer
6957                          */
6958                         if ( status ) {
6959                                 /*
6960                                  * In the event that the final RxDMA Buffer is
6961                                  * terminated with a non-zero status and the RCC
6962                                  * field is zero, we interpret this as the RCC
6963                                  * having underflowed (received frame > 65535 bytes).
6964                                  *
6965                                  * Signal the event to the user by passing back
6966                                  * a status of RxStatus_CrcError returning the full
6967                                  * buffer and let the app figure out what data is
6968                                  * actually valid
6969                                  */
6970                                 if ( info->rx_buffer_list[CurrentIndex].rcc )
6971                                         framesize = RCLRVALUE - info->rx_buffer_list[CurrentIndex].rcc;
6972                                 else
6973                                         framesize = DMABUFFERSIZE;
6974                         }
6975                         else
6976                                 framesize = DMABUFFERSIZE;
6977                 }
6978
6979                 if ( framesize > DMABUFFERSIZE ) {
6980                         /*
6981                          * if running in raw sync mode, ISR handler for
6982                          * End Of Buffer events terminates all buffers at 4K.
6983                          * If this frame size is said to be >4K, get the
6984                          * actual number of bytes of the frame in this buffer.
6985                          */
6986                         framesize = framesize % DMABUFFERSIZE;
6987                 }
6988
6989
6990                 if ( debug_level >= DEBUG_LEVEL_BH )
6991                         printk("%s(%d):mgsl_get_raw_rx_frame(%s) status=%04X size=%d\n",
6992                                 __FILE__,__LINE__,info->device_name,status,framesize);
6993
6994                 if ( debug_level >= DEBUG_LEVEL_DATA )
6995                         mgsl_trace_block(info,info->rx_buffer_list[CurrentIndex].virt_addr,
6996                                 MIN(framesize,DMABUFFERSIZE),0);
6997
6998                 if (framesize) {
6999                         /* copy dma buffer(s) to contiguous intermediate buffer */
7000                         /* NOTE: we never copy more than DMABUFFERSIZE bytes    */
7001
7002                         pBufEntry = &(info->rx_buffer_list[CurrentIndex]);
7003                         memcpy( info->intermediate_rxbuffer, pBufEntry->virt_addr, framesize);
7004                         info->icount.rxok++;
7005
7006                         /* Call the line discipline receive callback directly. */
7007                         if ( tty && tty->ldisc.receive_buf )
7008                                 tty->ldisc.receive_buf(tty, info->intermediate_rxbuffer, info->flag_buf, framesize);
7009                 }
7010
7011                 /* Free the buffers used by this frame. */
7012                 mgsl_free_rx_frame_buffers( info, CurrentIndex, CurrentIndex );
7013
7014                 ReturnCode = 1;
7015         }
7016
7017
7018         if ( info->rx_enabled && info->rx_overflow ) {
7019                 /* The receiver needs to restarted because of
7020                  * a receive overflow (buffer or FIFO). If the
7021                  * receive buffers are now empty, then restart receiver.
7022                  */
7023
7024                 if ( !info->rx_buffer_list[CurrentIndex].status &&
7025                         info->rx_buffer_list[CurrentIndex].count ) {
7026                         spin_lock_irqsave(&info->irq_spinlock,flags);
7027                         usc_start_receiver(info);
7028                         spin_unlock_irqrestore(&info->irq_spinlock,flags);
7029                 }
7030         }
7031
7032         return ReturnCode;
7033
7034 }       /* end of mgsl_get_raw_rx_frame() */
7035
7036 /* mgsl_load_tx_dma_buffer()
7037  * 
7038  *      Load the transmit DMA buffer with the specified data.
7039  * 
7040  * Arguments:
7041  * 
7042  *      info            pointer to device extension
7043  *      Buffer          pointer to buffer containing frame to load
7044  *      BufferSize      size in bytes of frame in Buffer
7045  * 
7046  * Return Value:        None
7047  */
7048 void mgsl_load_tx_dma_buffer(struct mgsl_struct *info, const char *Buffer,
7049          unsigned int BufferSize)
7050 {
7051         unsigned short Copycount;
7052         unsigned int i = 0;
7053         DMABUFFERENTRY *pBufEntry;
7054         
7055         if ( debug_level >= DEBUG_LEVEL_DATA )
7056                 mgsl_trace_block(info,Buffer, MIN(BufferSize,DMABUFFERSIZE), 1);        
7057
7058         if (info->params.flags & HDLC_FLAG_HDLC_LOOPMODE) {
7059                 /* set CMR:13 to start transmit when
7060                  * next GoAhead (abort) is received
7061                  */
7062                 info->cmr_value |= BIT13;                         
7063         }
7064                 
7065         /* begin loading the frame in the next available tx dma
7066          * buffer, remember it's starting location for setting
7067          * up tx dma operation
7068          */
7069         i = info->current_tx_buffer;
7070         info->start_tx_dma_buffer = i;
7071
7072         /* Setup the status and RCC (Frame Size) fields of the 1st */
7073         /* buffer entry in the transmit DMA buffer list. */
7074
7075         info->tx_buffer_list[i].status = info->cmr_value & 0xf000;
7076         info->tx_buffer_list[i].rcc    = BufferSize;
7077         info->tx_buffer_list[i].count  = BufferSize;
7078
7079         /* Copy frame data from 1st source buffer to the DMA buffers. */
7080         /* The frame data may span multiple DMA buffers. */
7081
7082         while( BufferSize ){
7083                 /* Get a pointer to next DMA buffer entry. */
7084                 pBufEntry = &info->tx_buffer_list[i++];
7085                         
7086                 if ( i == info->tx_buffer_count )
7087                         i=0;
7088
7089                 /* Calculate the number of bytes that can be copied from */
7090                 /* the source buffer to this DMA buffer. */
7091                 if ( BufferSize > DMABUFFERSIZE )
7092                         Copycount = DMABUFFERSIZE;
7093                 else
7094                         Copycount = BufferSize;
7095
7096                 /* Actually copy data from source buffer to DMA buffer. */
7097                 /* Also set the data count for this individual DMA buffer. */
7098                 if ( info->bus_type == MGSL_BUS_TYPE_PCI )
7099                         mgsl_load_pci_memory(pBufEntry->virt_addr, Buffer,Copycount);
7100                 else
7101                         memcpy(pBufEntry->virt_addr, Buffer, Copycount);
7102
7103                 pBufEntry->count = Copycount;
7104
7105                 /* Advance source pointer and reduce remaining data count. */
7106                 Buffer += Copycount;
7107                 BufferSize -= Copycount;
7108
7109                 ++info->tx_dma_buffers_used;
7110         }
7111
7112         /* remember next available tx dma buffer */
7113         info->current_tx_buffer = i;
7114
7115 }       /* end of mgsl_load_tx_dma_buffer() */
7116
7117 /*
7118  * mgsl_register_test()
7119  * 
7120  *      Performs a register test of the 16C32.
7121  *      
7122  * Arguments:           info    pointer to device instance data
7123  * Return Value:                TRUE if test passed, otherwise FALSE
7124  */
7125 BOOLEAN mgsl_register_test( struct mgsl_struct *info )
7126 {
7127         static unsigned short BitPatterns[] =
7128                 { 0x0000, 0xffff, 0xaaaa, 0x5555, 0x1234, 0x6969, 0x9696, 0x0f0f };
7129         static unsigned int Patterncount = sizeof(BitPatterns)/sizeof(unsigned short);
7130         unsigned int i;
7131         BOOLEAN rc = TRUE;
7132         unsigned long flags;
7133
7134         spin_lock_irqsave(&info->irq_spinlock,flags);
7135         usc_reset(info);
7136
7137         /* Verify the reset state of some registers. */
7138
7139         if ( (usc_InReg( info, SICR ) != 0) ||
7140                   (usc_InReg( info, IVR  ) != 0) ||
7141                   (usc_InDmaReg( info, DIVR ) != 0) ){
7142                 rc = FALSE;
7143         }
7144
7145         if ( rc == TRUE ){
7146                 /* Write bit patterns to various registers but do it out of */
7147                 /* sync, then read back and verify values. */
7148
7149                 for ( i = 0 ; i < Patterncount ; i++ ) {
7150                         usc_OutReg( info, TC0R, BitPatterns[i] );
7151                         usc_OutReg( info, TC1R, BitPatterns[(i+1)%Patterncount] );
7152                         usc_OutReg( info, TCLR, BitPatterns[(i+2)%Patterncount] );
7153                         usc_OutReg( info, RCLR, BitPatterns[(i+3)%Patterncount] );
7154                         usc_OutReg( info, RSR,  BitPatterns[(i+4)%Patterncount] );
7155                         usc_OutDmaReg( info, TBCR, BitPatterns[(i+5)%Patterncount] );
7156
7157                         if ( (usc_InReg( info, TC0R ) != BitPatterns[i]) ||
7158                                   (usc_InReg( info, TC1R ) != BitPatterns[(i+1)%Patterncount]) ||
7159                                   (usc_InReg( info, TCLR ) != BitPatterns[(i+2)%Patterncount]) ||
7160                                   (usc_InReg( info, RCLR ) != BitPatterns[(i+3)%Patterncount]) ||
7161                                   (usc_InReg( info, RSR )  != BitPatterns[(i+4)%Patterncount]) ||
7162                                   (usc_InDmaReg( info, TBCR ) != BitPatterns[(i+5)%Patterncount]) ){
7163                                 rc = FALSE;
7164                                 break;
7165                         }
7166                 }
7167         }
7168
7169         usc_reset(info);
7170         spin_unlock_irqrestore(&info->irq_spinlock,flags);
7171
7172         return rc;
7173
7174 }       /* end of mgsl_register_test() */
7175
7176 /* mgsl_irq_test()      Perform interrupt test of the 16C32.
7177  * 
7178  * Arguments:           info    pointer to device instance data
7179  * Return Value:        TRUE if test passed, otherwise FALSE
7180  */
7181 BOOLEAN mgsl_irq_test( struct mgsl_struct *info )
7182 {
7183         unsigned long EndTime;
7184         unsigned long flags;
7185
7186         spin_lock_irqsave(&info->irq_spinlock,flags);
7187         usc_reset(info);
7188
7189         /*
7190          * Setup 16C32 to interrupt on TxC pin (14MHz clock) transition. 
7191          * The ISR sets irq_occurred to 1. 
7192          */
7193
7194         info->irq_occurred = FALSE;
7195
7196         /* Enable INTEN gate for ISA adapter (Port 6, Bit12) */
7197         /* Enable INTEN (Port 6, Bit12) */
7198         /* This connects the IRQ request signal to the ISA bus */
7199         /* on the ISA adapter. This has no effect for the PCI adapter */
7200         usc_OutReg( info, PCR, (unsigned short)((usc_InReg(info, PCR) | BIT13) & ~BIT12) );
7201
7202         usc_EnableMasterIrqBit(info);
7203         usc_EnableInterrupts(info, IO_PIN);
7204         usc_ClearIrqPendingBits(info, IO_PIN);
7205         
7206         usc_UnlatchIostatusBits(info, MISCSTATUS_TXC_LATCHED);
7207         usc_EnableStatusIrqs(info, SICR_TXC_ACTIVE + SICR_TXC_INACTIVE);
7208
7209         spin_unlock_irqrestore(&info->irq_spinlock,flags);
7210
7211         EndTime=100;
7212         while( EndTime-- && !info->irq_occurred ) {
7213                 set_current_state(TASK_INTERRUPTIBLE);
7214                 schedule_timeout(jiffies_from_ms(10));
7215         }
7216         
7217         spin_lock_irqsave(&info->irq_spinlock,flags);
7218         usc_reset(info);
7219         spin_unlock_irqrestore(&info->irq_spinlock,flags);
7220         
7221         if ( !info->irq_occurred ) 
7222                 return FALSE;
7223         else
7224                 return TRUE;
7225
7226 }       /* end of mgsl_irq_test() */
7227
7228 /* mgsl_dma_test()
7229  * 
7230  *      Perform a DMA test of the 16C32. A small frame is
7231  *      transmitted via DMA from a transmit buffer to a receive buffer
7232  *      using single buffer DMA mode.
7233  *      
7234  * Arguments:           info    pointer to device instance data
7235  * Return Value:        TRUE if test passed, otherwise FALSE
7236  */
7237 BOOLEAN mgsl_dma_test( struct mgsl_struct *info )
7238 {
7239         unsigned short FifoLevel;
7240         unsigned long phys_addr;
7241         unsigned int FrameSize;
7242         unsigned int i;
7243         char *TmpPtr;
7244         BOOLEAN rc = TRUE;
7245         unsigned short status=0;
7246         unsigned long EndTime;
7247         unsigned long flags;
7248         MGSL_PARAMS tmp_params;
7249
7250         /* save current port options */
7251         memcpy(&tmp_params,&info->params,sizeof(MGSL_PARAMS));
7252         /* load default port options */
7253         memcpy(&info->params,&default_params,sizeof(MGSL_PARAMS));
7254         
7255 #define TESTFRAMESIZE 40
7256
7257         spin_lock_irqsave(&info->irq_spinlock,flags);
7258         
7259         /* setup 16C32 for SDLC DMA transfer mode */
7260
7261         usc_reset(info);
7262         usc_set_sdlc_mode(info);
7263         usc_enable_loopback(info,1);
7264         
7265         /* Reprogram the RDMR so that the 16C32 does NOT clear the count
7266          * field of the buffer entry after fetching buffer address. This
7267          * way we can detect a DMA failure for a DMA read (which should be
7268          * non-destructive to system memory) before we try and write to
7269          * memory (where a failure could corrupt system memory).
7270          */
7271
7272         /* Receive DMA mode Register (RDMR)
7273          * 
7274          * <15..14>     11      DMA mode = Linked List Buffer mode
7275          * <13>         1       RSBinA/L = store Rx status Block in List entry
7276          * <12>         0       1 = Clear count of List Entry after fetching
7277          * <11..10>     00      Address mode = Increment
7278          * <9>          1       Terminate Buffer on RxBound
7279          * <8>          0       Bus Width = 16bits
7280          * <7..0>               ?       status Bits (write as 0s)
7281          * 
7282          * 1110 0010 0000 0000 = 0xe200
7283          */
7284
7285         usc_OutDmaReg( info, RDMR, 0xe200 );
7286         
7287         spin_unlock_irqrestore(&info->irq_spinlock,flags);
7288
7289
7290         /* SETUP TRANSMIT AND RECEIVE DMA BUFFERS */
7291
7292         FrameSize = TESTFRAMESIZE;
7293
7294         /* setup 1st transmit buffer entry: */
7295         /* with frame size and transmit control word */
7296
7297         info->tx_buffer_list[0].count  = FrameSize;
7298         info->tx_buffer_list[0].rcc    = FrameSize;
7299         info->tx_buffer_list[0].status = 0x4000;
7300
7301         /* build a transmit frame in 1st transmit DMA buffer */
7302
7303         TmpPtr = info->tx_buffer_list[0].virt_addr;
7304         for (i = 0; i < FrameSize; i++ )
7305                 *TmpPtr++ = i;
7306
7307         /* setup 1st receive buffer entry: */
7308         /* clear status, set max receive buffer size */
7309
7310         info->rx_buffer_list[0].status = 0;
7311         info->rx_buffer_list[0].count = FrameSize + 4;
7312
7313         /* zero out the 1st receive buffer */
7314
7315         memset( info->rx_buffer_list[0].virt_addr, 0, FrameSize + 4 );
7316
7317         /* Set count field of next buffer entries to prevent */
7318         /* 16C32 from using buffers after the 1st one. */
7319
7320         info->tx_buffer_list[1].count = 0;
7321         info->rx_buffer_list[1].count = 0;
7322         
7323
7324         /***************************/
7325         /* Program 16C32 receiver. */
7326         /***************************/
7327         
7328         spin_lock_irqsave(&info->irq_spinlock,flags);
7329
7330         /* setup DMA transfers */
7331         usc_RTCmd( info, RTCmd_PurgeRxFifo );
7332
7333         /* program 16C32 receiver with physical address of 1st DMA buffer entry */
7334         phys_addr = info->rx_buffer_list[0].phys_entry;
7335         usc_OutDmaReg( info, NRARL, (unsigned short)phys_addr );
7336         usc_OutDmaReg( info, NRARU, (unsigned short)(phys_addr >> 16) );
7337
7338         /* Clear the Rx DMA status bits (read RDMR) and start channel */
7339         usc_InDmaReg( info, RDMR );
7340         usc_DmaCmd( info, DmaCmd_InitRxChannel );
7341
7342         /* Enable Receiver (RMR <1..0> = 10) */
7343         usc_OutReg( info, RMR, (unsigned short)((usc_InReg(info, RMR) & 0xfffc) | 0x0002) );
7344         
7345         spin_unlock_irqrestore(&info->irq_spinlock,flags);
7346
7347
7348         /*************************************************************/
7349         /* WAIT FOR RECEIVER TO DMA ALL PARAMETERS FROM BUFFER ENTRY */
7350         /*************************************************************/
7351
7352         /* Wait 100ms for interrupt. */
7353         EndTime = jiffies + jiffies_from_ms(100);
7354
7355         for(;;) {
7356                 if (time_after(jiffies, EndTime)) {
7357                         rc = FALSE;
7358                         break;
7359                 }
7360
7361                 spin_lock_irqsave(&info->irq_spinlock,flags);
7362                 status = usc_InDmaReg( info, RDMR );
7363                 spin_unlock_irqrestore(&info->irq_spinlock,flags);
7364
7365                 if ( !(status & BIT4) && (status & BIT5) ) {
7366                         /* INITG (BIT 4) is inactive (no entry read in progress) AND */
7367                         /* BUSY  (BIT 5) is active (channel still active). */
7368                         /* This means the buffer entry read has completed. */
7369                         break;
7370                 }
7371         }
7372
7373
7374         /******************************/
7375         /* Program 16C32 transmitter. */
7376         /******************************/
7377         
7378         spin_lock_irqsave(&info->irq_spinlock,flags);
7379
7380         /* Program the Transmit Character Length Register (TCLR) */
7381         /* and clear FIFO (TCC is loaded with TCLR on FIFO clear) */
7382
7383         usc_OutReg( info, TCLR, (unsigned short)info->tx_buffer_list[0].count );
7384         usc_RTCmd( info, RTCmd_PurgeTxFifo );
7385
7386         /* Program the address of the 1st DMA Buffer Entry in linked list */
7387
7388         phys_addr = info->tx_buffer_list[0].phys_entry;
7389         usc_OutDmaReg( info, NTARL, (unsigned short)phys_addr );
7390         usc_OutDmaReg( info, NTARU, (unsigned short)(phys_addr >> 16) );
7391
7392         /* unlatch Tx status bits, and start transmit channel. */
7393
7394         usc_OutReg( info, TCSR, (unsigned short)(( usc_InReg(info, TCSR) & 0x0f00) | 0xfa) );
7395         usc_DmaCmd( info, DmaCmd_InitTxChannel );
7396
7397         /* wait for DMA controller to fill transmit FIFO */
7398
7399         usc_TCmd( info, TCmd_SelectTicrTxFifostatus );
7400         
7401         spin_unlock_irqrestore(&info->irq_spinlock,flags);
7402
7403
7404         /**********************************/
7405         /* WAIT FOR TRANSMIT FIFO TO FILL */
7406         /**********************************/
7407         
7408         /* Wait 100ms */
7409         EndTime = jiffies + jiffies_from_ms(100);
7410
7411         for(;;) {
7412                 if (time_after(jiffies, EndTime)) {
7413                         rc = FALSE;
7414                         break;
7415                 }
7416
7417                 spin_lock_irqsave(&info->irq_spinlock,flags);
7418                 FifoLevel = usc_InReg(info, TICR) >> 8;
7419                 spin_unlock_irqrestore(&info->irq_spinlock,flags);
7420                         
7421                 if ( FifoLevel < 16 )
7422                         break;
7423                 else
7424                         if ( FrameSize < 32 ) {
7425                                 /* This frame is smaller than the entire transmit FIFO */
7426                                 /* so wait for the entire frame to be loaded. */
7427                                 if ( FifoLevel <= (32 - FrameSize) )
7428                                         break;
7429                         }
7430         }
7431
7432
7433         if ( rc == TRUE )
7434         {
7435                 /* Enable 16C32 transmitter. */
7436
7437                 spin_lock_irqsave(&info->irq_spinlock,flags);
7438                 
7439                 /* Transmit mode Register (TMR), <1..0> = 10, Enable Transmitter */
7440                 usc_TCmd( info, TCmd_SendFrame );
7441                 usc_OutReg( info, TMR, (unsigned short)((usc_InReg(info, TMR) & 0xfffc) | 0x0002) );
7442                 
7443                 spin_unlock_irqrestore(&info->irq_spinlock,flags);
7444
7445                                                 
7446                 /******************************/
7447                 /* WAIT FOR TRANSMIT COMPLETE */
7448                 /******************************/
7449
7450                 /* Wait 100ms */
7451                 EndTime = jiffies + jiffies_from_ms(100);
7452
7453                 /* While timer not expired wait for transmit complete */
7454
7455                 spin_lock_irqsave(&info->irq_spinlock,flags);
7456                 status = usc_InReg( info, TCSR );
7457                 spin_unlock_irqrestore(&info->irq_spinlock,flags);
7458
7459                 while ( !(status & (BIT6+BIT5+BIT4+BIT2+BIT1)) ) {
7460                         if (time_after(jiffies, EndTime)) {
7461                                 rc = FALSE;
7462                                 break;
7463                         }
7464
7465                         spin_lock_irqsave(&info->irq_spinlock,flags);
7466                         status = usc_InReg( info, TCSR );
7467                         spin_unlock_irqrestore(&info->irq_spinlock,flags);
7468                 }
7469         }
7470
7471
7472         if ( rc == TRUE ){
7473                 /* CHECK FOR TRANSMIT ERRORS */
7474                 if ( status & (BIT5 + BIT1) ) 
7475                         rc = FALSE;
7476         }
7477
7478         if ( rc == TRUE ) {
7479                 /* WAIT FOR RECEIVE COMPLETE */
7480
7481                 /* Wait 100ms */
7482                 EndTime = jiffies + jiffies_from_ms(100);
7483
7484                 /* Wait for 16C32 to write receive status to buffer entry. */
7485                 status=info->rx_buffer_list[0].status;
7486                 while ( status == 0 ) {
7487                         if (time_after(jiffies, EndTime)) {
7488                                 rc = FALSE;
7489                                 break;
7490                         }
7491                         status=info->rx_buffer_list[0].status;
7492                 }
7493         }
7494
7495
7496         if ( rc == TRUE ) {
7497                 /* CHECK FOR RECEIVE ERRORS */
7498                 status = info->rx_buffer_list[0].status;
7499
7500                 if ( status & (BIT8 + BIT3 + BIT1) ) {
7501                         /* receive error has occurred */
7502                         rc = FALSE;
7503                 } else {
7504                         if ( memcmp( info->tx_buffer_list[0].virt_addr ,
7505                                 info->rx_buffer_list[0].virt_addr, FrameSize ) ){
7506                                 rc = FALSE;
7507                         }
7508                 }
7509         }
7510
7511         spin_lock_irqsave(&info->irq_spinlock,flags);
7512         usc_reset( info );
7513         spin_unlock_irqrestore(&info->irq_spinlock,flags);
7514
7515         /* restore current port options */
7516         memcpy(&info->params,&tmp_params,sizeof(MGSL_PARAMS));
7517         
7518         return rc;
7519
7520 }       /* end of mgsl_dma_test() */
7521
7522 /* mgsl_adapter_test()
7523  * 
7524  *      Perform the register, IRQ, and DMA tests for the 16C32.
7525  *      
7526  * Arguments:           info    pointer to device instance data
7527  * Return Value:        0 if success, otherwise -ENODEV
7528  */
7529 int mgsl_adapter_test( struct mgsl_struct *info )
7530 {
7531         if ( debug_level >= DEBUG_LEVEL_INFO )
7532                 printk( "%s(%d):Testing device %s\n",
7533                         __FILE__,__LINE__,info->device_name );
7534                         
7535         if ( !mgsl_register_test( info ) ) {
7536                 info->init_error = DiagStatus_AddressFailure;
7537                 printk( "%s(%d):Register test failure for device %s Addr=%04X\n",
7538                         __FILE__,__LINE__,info->device_name, (unsigned short)(info->io_base) );
7539                 return -ENODEV;
7540         }
7541
7542         if ( !mgsl_irq_test( info ) ) {
7543                 info->init_error = DiagStatus_IrqFailure;
7544                 printk( "%s(%d):Interrupt test failure for device %s IRQ=%d\n",
7545                         __FILE__,__LINE__,info->device_name, (unsigned short)(info->irq_level) );
7546                 return -ENODEV;
7547         }
7548
7549         if ( !mgsl_dma_test( info ) ) {
7550                 info->init_error = DiagStatus_DmaFailure;
7551                 printk( "%s(%d):DMA test failure for device %s DMA=%d\n",
7552                         __FILE__,__LINE__,info->device_name, (unsigned short)(info->dma_level) );
7553                 return -ENODEV;
7554         }
7555
7556         if ( debug_level >= DEBUG_LEVEL_INFO )
7557                 printk( "%s(%d):device %s passed diagnostics\n",
7558                         __FILE__,__LINE__,info->device_name );
7559                         
7560         return 0;
7561
7562 }       /* end of mgsl_adapter_test() */
7563
7564 /* mgsl_memory_test()
7565  * 
7566  *      Test the shared memory on a PCI adapter.
7567  * 
7568  * Arguments:           info    pointer to device instance data
7569  * Return Value:        TRUE if test passed, otherwise FALSE
7570  */
7571 BOOLEAN mgsl_memory_test( struct mgsl_struct *info )
7572 {
7573         static unsigned long BitPatterns[] = { 0x0, 0x55555555, 0xaaaaaaaa,
7574                                                                                         0x66666666, 0x99999999, 0xffffffff, 0x12345678 };
7575         unsigned long Patterncount = sizeof(BitPatterns)/sizeof(unsigned long);
7576         unsigned long i;
7577         unsigned long TestLimit = SHARED_MEM_ADDRESS_SIZE/sizeof(unsigned long);
7578         unsigned long * TestAddr;
7579
7580         if ( info->bus_type != MGSL_BUS_TYPE_PCI )
7581                 return TRUE;
7582
7583         TestAddr = (unsigned long *)info->memory_base;
7584
7585         /* Test data lines with test pattern at one location. */
7586
7587         for ( i = 0 ; i < Patterncount ; i++ ) {
7588                 *TestAddr = BitPatterns[i];
7589                 if ( *TestAddr != BitPatterns[i] )
7590                         return FALSE;
7591         }
7592
7593         /* Test address lines with incrementing pattern over */
7594         /* entire address range. */
7595
7596         for ( i = 0 ; i < TestLimit ; i++ ) {
7597                 *TestAddr = i * 4;
7598                 TestAddr++;
7599         }
7600
7601         TestAddr = (unsigned long *)info->memory_base;
7602
7603         for ( i = 0 ; i < TestLimit ; i++ ) {
7604                 if ( *TestAddr != i * 4 )
7605                         return FALSE;
7606                 TestAddr++;
7607         }
7608
7609         memset( info->memory_base, 0, SHARED_MEM_ADDRESS_SIZE );
7610
7611         return TRUE;
7612
7613 }       /* End Of mgsl_memory_test() */
7614
7615
7616 /* mgsl_load_pci_memory()
7617  * 
7618  *      Load a large block of data into the PCI shared memory.
7619  *      Use this instead of memcpy() or memmove() to move data
7620  *      into the PCI shared memory.
7621  * 
7622  * Notes:
7623  * 
7624  *      This function prevents the PCI9050 interface chip from hogging
7625  *      the adapter local bus, which can starve the 16C32 by preventing
7626  *      16C32 bus master cycles.
7627  * 
7628  *      The PCI9050 documentation says that the 9050 will always release
7629  *      control of the local bus after completing the current read
7630  *      or write operation.
7631  * 
7632  *      It appears that as long as the PCI9050 write FIFO is full, the
7633  *      PCI9050 treats all of the writes as a single burst transaction
7634  *      and will not release the bus. This causes DMA latency problems
7635  *      at high speeds when copying large data blocks to the shared
7636  *      memory.
7637  * 
7638  *      This function in effect, breaks the a large shared memory write
7639  *      into multiple transations by interleaving a shared memory read
7640  *      which will flush the write FIFO and 'complete' the write
7641  *      transation. This allows any pending DMA request to gain control
7642  *      of the local bus in a timely fasion.
7643  * 
7644  * Arguments:
7645  * 
7646  *      TargetPtr       pointer to target address in PCI shared memory
7647  *      SourcePtr       pointer to source buffer for data
7648  *      count           count in bytes of data to copy
7649  *
7650  * Return Value:        None
7651  */
7652 void mgsl_load_pci_memory( char* TargetPtr, const char* SourcePtr, 
7653         unsigned short count )
7654 {
7655         /* 16 32-bit writes @ 60ns each = 960ns max latency on local bus */
7656 #define PCI_LOAD_INTERVAL 64
7657
7658         unsigned short Intervalcount = count / PCI_LOAD_INTERVAL;
7659         unsigned short Index;
7660         unsigned long Dummy;
7661
7662         for ( Index = 0 ; Index < Intervalcount ; Index++ )
7663         {
7664                 memcpy(TargetPtr, SourcePtr, PCI_LOAD_INTERVAL);
7665                 Dummy = *((volatile unsigned long *)TargetPtr);
7666                 TargetPtr += PCI_LOAD_INTERVAL;
7667                 SourcePtr += PCI_LOAD_INTERVAL;
7668         }
7669
7670         memcpy( TargetPtr, SourcePtr, count % PCI_LOAD_INTERVAL );
7671
7672 }       /* End Of mgsl_load_pci_memory() */
7673
7674 void mgsl_trace_block(struct mgsl_struct *info,const char* data, int count, int xmit)
7675 {
7676         int i;
7677         int linecount;
7678         if (xmit)
7679                 printk("%s tx data:\n",info->device_name);
7680         else
7681                 printk("%s rx data:\n",info->device_name);
7682                 
7683         while(count) {
7684                 if (count > 16)
7685                         linecount = 16;
7686                 else
7687                         linecount = count;
7688                         
7689                 for(i=0;i<linecount;i++)
7690                         printk("%02X ",(unsigned char)data[i]);
7691                 for(;i<17;i++)
7692                         printk("   ");
7693                 for(i=0;i<linecount;i++) {
7694                         if (data[i]>=040 && data[i]<=0176)
7695                                 printk("%c",data[i]);
7696                         else
7697                                 printk(".");
7698                 }
7699                 printk("\n");
7700                 
7701                 data  += linecount;
7702                 count -= linecount;
7703         }
7704 }       /* end of mgsl_trace_block() */
7705
7706 /* mgsl_tx_timeout()
7707  * 
7708  *      called when HDLC frame times out
7709  *      update stats and do tx completion processing
7710  *      
7711  * Arguments:   context         pointer to device instance data
7712  * Return Value:        None
7713  */
7714 void mgsl_tx_timeout(unsigned long context)
7715 {
7716         struct mgsl_struct *info = (struct mgsl_struct*)context;
7717         unsigned long flags;
7718         
7719         if ( debug_level >= DEBUG_LEVEL_INFO )
7720                 printk( "%s(%d):mgsl_tx_timeout(%s)\n",
7721                         __FILE__,__LINE__,info->device_name);
7722         if(info->tx_active &&
7723            (info->params.mode == MGSL_MODE_HDLC ||
7724             info->params.mode == MGSL_MODE_RAW) ) {
7725                 info->icount.txtimeout++;
7726         }
7727         spin_lock_irqsave(&info->irq_spinlock,flags);
7728         info->tx_active = 0;
7729         info->xmit_cnt = info->xmit_head = info->xmit_tail = 0;
7730
7731         if ( info->params.flags & HDLC_FLAG_HDLC_LOOPMODE )
7732                 usc_loopmode_cancel_transmit( info );
7733
7734         spin_unlock_irqrestore(&info->irq_spinlock,flags);
7735         
7736 #ifdef CONFIG_SYNCLINK_SYNCPPP
7737         if (info->netcount)
7738                 mgsl_sppp_tx_done(info);
7739         else
7740 #endif
7741                 mgsl_bh_transmit(info);
7742         
7743 }       /* end of mgsl_tx_timeout() */
7744
7745 /* signal that there are no more frames to send, so that
7746  * line is 'released' by echoing RxD to TxD when current
7747  * transmission is complete (or immediately if no tx in progress).
7748  */
7749 static int mgsl_loopmode_send_done( struct mgsl_struct * info )
7750 {
7751         unsigned long flags;
7752         
7753         spin_lock_irqsave(&info->irq_spinlock,flags);
7754         if (info->params.flags & HDLC_FLAG_HDLC_LOOPMODE) {
7755                 if (info->tx_active)
7756                         info->loopmode_send_done_requested = TRUE;
7757                 else
7758                         usc_loopmode_send_done(info);
7759         }
7760         spin_unlock_irqrestore(&info->irq_spinlock,flags);
7761
7762         return 0;
7763 }
7764
7765 /* release the line by echoing RxD to TxD
7766  * upon completion of a transmit frame
7767  */
7768 void usc_loopmode_send_done( struct mgsl_struct * info )
7769 {
7770         info->loopmode_send_done_requested = FALSE;
7771         /* clear CMR:13 to 0 to start echoing RxData to TxData */
7772         info->cmr_value &= ~BIT13;                        
7773         usc_OutReg(info, CMR, info->cmr_value);
7774 }
7775
7776 /* abort a transmit in progress while in HDLC LoopMode
7777  */
7778 void usc_loopmode_cancel_transmit( struct mgsl_struct * info )
7779 {
7780         /* reset tx dma channel and purge TxFifo */
7781         usc_RTCmd( info, RTCmd_PurgeTxFifo );
7782         usc_DmaCmd( info, DmaCmd_ResetTxChannel );
7783         usc_loopmode_send_done( info );
7784 }
7785
7786 /* for HDLC/SDLC LoopMode, setting CMR:13 after the transmitter is enabled
7787  * is an Insert Into Loop action. Upon receipt of a GoAhead sequence (RxAbort)
7788  * we must clear CMR:13 to begin repeating TxData to RxData
7789  */
7790 void usc_loopmode_insert_request( struct mgsl_struct * info )
7791 {
7792         info->loopmode_insert_requested = TRUE;
7793  
7794         /* enable RxAbort irq. On next RxAbort, clear CMR:13 to
7795          * begin repeating TxData on RxData (complete insertion)
7796          */
7797         usc_OutReg( info, RICR, 
7798                 (usc_InReg( info, RICR ) | RXSTATUS_ABORT_RECEIVED ) );
7799                 
7800         /* set CMR:13 to insert into loop on next GoAhead (RxAbort) */
7801         info->cmr_value |= BIT13;
7802         usc_OutReg(info, CMR, info->cmr_value);
7803 }
7804
7805 /* return 1 if station is inserted into the loop, otherwise 0
7806  */
7807 int usc_loopmode_active( struct mgsl_struct * info)
7808 {
7809         return usc_InReg( info, CCSR ) & BIT7 ? 1 : 0 ;
7810 }
7811
7812 /* return 1 if USC is in loop send mode, otherwise 0
7813  */
7814 int usc_loopmode_send_active( struct mgsl_struct * info )
7815 {
7816         return usc_InReg( info, CCSR ) & BIT6 ? 1 : 0 ;
7817 }                         
7818
7819 #ifdef CONFIG_SYNCLINK_SYNCPPP
7820 /* syncppp net device routines
7821  */
7822 static void mgsl_setup(struct net_device *dev)
7823 {
7824         dev->open = mgsl_sppp_open;
7825         dev->stop = mgsl_sppp_close;
7826         dev->hard_start_xmit = mgsl_sppp_tx;
7827         dev->do_ioctl = mgsl_sppp_ioctl;
7828         dev->get_stats = mgsl_net_stats;
7829         dev->tx_timeout = mgsl_sppp_tx_timeout;
7830         dev->watchdog_timeo = 10*HZ;
7831 }
7832
7833 static void mgsl_sppp_init(struct mgsl_struct *info)
7834 {
7835         struct net_device *d;
7836
7837         sprintf(info->netname,"mgsl%d",info->line);
7838
7839         d = alloc_netdev(0, info->netname, mgsl_setup);
7840         if (!d) {
7841                 printk(KERN_WARNING "%s: alloc_netdev failed.\n",
7842                                                 info->netname);
7843                 return;
7844         }
7845
7846         info->if_ptr = &info->pppdev;
7847         info->netdev = info->pppdev.dev = d;
7848
7849         d->base_addr = info->io_base;
7850         d->irq = info->irq_level;
7851         d->dma = info->dma_level;
7852         d->priv = info;
7853
7854         sppp_attach(&info->pppdev);
7855         mgsl_setup(d);
7856
7857         if (register_netdev(d)) {
7858                 printk(KERN_WARNING "%s: register_netdev failed.\n", d->name);
7859                 sppp_detach(info->netdev);
7860                 info->netdev = NULL;
7861                 free_netdev(d);
7862                 return;
7863         }
7864
7865         if (debug_level >= DEBUG_LEVEL_INFO)
7866                 printk("mgsl_sppp_init()\n");   
7867 }
7868
7869 void mgsl_sppp_delete(struct mgsl_struct *info)
7870 {
7871         if (debug_level >= DEBUG_LEVEL_INFO)
7872                 printk("mgsl_sppp_delete(%s)\n",info->netname); 
7873         unregister_netdev(info->netdev);
7874         sppp_detach(info->netdev);
7875         free_netdev(info->netdev);
7876         info->netdev = NULL;
7877         info->pppdev.dev = NULL;
7878 }
7879
7880 int mgsl_sppp_open(struct net_device *d)
7881 {
7882         struct mgsl_struct *info = d->priv;
7883         int err;
7884         unsigned long flags;
7885
7886         if (debug_level >= DEBUG_LEVEL_INFO)
7887                 printk("mgsl_sppp_open(%s)\n",info->netname);   
7888
7889         spin_lock_irqsave(&info->netlock, flags);
7890         if (info->count != 0 || info->netcount != 0) {
7891                 printk(KERN_WARNING "%s: sppp_open returning busy\n", info->netname);
7892                 spin_unlock_irqrestore(&info->netlock, flags);
7893                 return -EBUSY;
7894         }
7895         info->netcount=1;
7896         spin_unlock_irqrestore(&info->netlock, flags);
7897
7898         /* claim resources and init adapter */
7899         if ((err = startup(info)) != 0)
7900                 goto open_fail;
7901
7902         /* allow syncppp module to do open processing */
7903         if ((err = sppp_open(d)) != 0) {
7904                 shutdown(info);
7905                 goto open_fail;
7906         }
7907
7908         info->serial_signals |= SerialSignal_RTS + SerialSignal_DTR;
7909         mgsl_program_hw(info);
7910
7911         d->trans_start = jiffies;
7912         netif_start_queue(d);
7913         return 0;
7914
7915 open_fail:
7916         spin_lock_irqsave(&info->netlock, flags);
7917         info->netcount=0;
7918         spin_unlock_irqrestore(&info->netlock, flags);
7919         return err;
7920 }
7921
7922 void mgsl_sppp_tx_timeout(struct net_device *dev)
7923 {
7924         struct mgsl_struct *info = dev->priv;
7925         unsigned long flags;
7926
7927         if (debug_level >= DEBUG_LEVEL_INFO)
7928                 printk("mgsl_sppp_tx_timeout(%s)\n",info->netname);     
7929
7930         info->netstats.tx_errors++;
7931         info->netstats.tx_aborted_errors++;
7932
7933         spin_lock_irqsave(&info->irq_spinlock,flags);
7934         usc_stop_transmitter(info);
7935         spin_unlock_irqrestore(&info->irq_spinlock,flags);
7936
7937         netif_wake_queue(dev);
7938 }
7939
7940 int mgsl_sppp_tx(struct sk_buff *skb, struct net_device *dev)
7941 {
7942         struct mgsl_struct *info = dev->priv;
7943         unsigned long flags;
7944
7945         if (debug_level >= DEBUG_LEVEL_INFO)
7946                 printk("mgsl_sppp_tx(%s)\n",info->netname);     
7947
7948         netif_stop_queue(dev);
7949
7950         info->xmit_cnt = skb->len;
7951         mgsl_load_tx_dma_buffer(info, skb->data, skb->len);
7952         info->netstats.tx_packets++;
7953         info->netstats.tx_bytes += skb->len;
7954         dev_kfree_skb(skb);
7955
7956         dev->trans_start = jiffies;
7957
7958         spin_lock_irqsave(&info->irq_spinlock,flags);
7959         if (!info->tx_active)
7960                 usc_start_transmitter(info);
7961         spin_unlock_irqrestore(&info->irq_spinlock,flags);
7962
7963         return 0;
7964 }
7965
7966 int mgsl_sppp_close(struct net_device *d)
7967 {
7968         struct mgsl_struct *info = d->priv;
7969         unsigned long flags;
7970
7971         if (debug_level >= DEBUG_LEVEL_INFO)
7972                 printk("mgsl_sppp_close(%s)\n",info->netname);  
7973
7974         /* shutdown adapter and release resources */
7975         shutdown(info);
7976
7977         /* allow syncppp to do close processing */
7978         sppp_close(d);
7979         netif_stop_queue(d);
7980
7981         spin_lock_irqsave(&info->netlock, flags);
7982         info->netcount=0;
7983         spin_unlock_irqrestore(&info->netlock, flags);
7984         return 0;
7985 }
7986
7987 void mgsl_sppp_rx_done(struct mgsl_struct *info, char *buf, int size)
7988 {
7989         struct sk_buff *skb = dev_alloc_skb(size);
7990         if (debug_level >= DEBUG_LEVEL_INFO)
7991                 printk("mgsl_sppp_rx_done(%s)\n",info->netname);        
7992         if (skb == NULL) {
7993                 printk(KERN_NOTICE "%s: can't alloc skb, dropping packet\n",
7994                         info->netname);
7995                 info->netstats.rx_dropped++;
7996                 return;
7997         }
7998
7999         memcpy(skb_put(skb, size),buf,size);
8000
8001         skb->protocol = htons(ETH_P_WAN_PPP);
8002         skb->dev = info->netdev;
8003         skb->mac.raw = skb->data;
8004         info->netstats.rx_packets++;
8005         info->netstats.rx_bytes += size;
8006         netif_rx(skb);
8007         info->netdev->trans_start = jiffies;
8008 }
8009
8010 void mgsl_sppp_tx_done(struct mgsl_struct *info)
8011 {
8012         if (netif_queue_stopped(info->netdev))
8013             netif_wake_queue(info->netdev);
8014 }
8015
8016 struct net_device_stats *mgsl_net_stats(struct net_device *dev)
8017 {
8018         struct mgsl_struct *info = dev->priv;
8019         if (debug_level >= DEBUG_LEVEL_INFO)
8020                 printk("mgsl_net_stats(%s)\n",info->netname);   
8021         return &info->netstats;
8022 }
8023
8024 int mgsl_sppp_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
8025 {
8026         struct mgsl_struct *info = dev->priv;
8027         if (debug_level >= DEBUG_LEVEL_INFO)
8028                 printk("%s(%d):mgsl_ioctl %s cmd=%08X\n", __FILE__,__LINE__,
8029                         info->netname, cmd );
8030         return sppp_do_ioctl(dev, ifr, cmd);
8031 }
8032
8033 #endif /* ifdef CONFIG_SYNCLINK_SYNCPPP */
8034
8035 static int __devinit synclink_init_one (struct pci_dev *dev,
8036                                         const struct pci_device_id *ent)
8037 {
8038         struct mgsl_struct *info;
8039
8040         if (pci_enable_device(dev)) {
8041                 printk("error enabling pci device %p\n", dev);
8042                 return -EIO;
8043         }
8044
8045         if (!(info = mgsl_allocate_device())) {
8046                 printk("can't allocate device instance data.\n");
8047                 return -EIO;
8048         }
8049
8050         /* Copy user configuration info to device instance data */
8051                 
8052         info->io_base = pci_resource_start(dev, 2);
8053         info->irq_level = dev->irq;
8054         info->phys_memory_base = pci_resource_start(dev, 3);
8055                                 
8056         /* Because veremap only works on page boundaries we must map
8057          * a larger area than is actually implemented for the LCR
8058          * memory range. We map a full page starting at the page boundary.
8059          */
8060         info->phys_lcr_base = pci_resource_start(dev, 0);
8061         info->lcr_offset    = info->phys_lcr_base & (PAGE_SIZE-1);
8062         info->phys_lcr_base &= ~(PAGE_SIZE-1);
8063                                 
8064         info->bus_type = MGSL_BUS_TYPE_PCI;
8065         info->io_addr_size = 8;
8066         info->irq_flags = SA_SHIRQ;
8067
8068         if (dev->device == 0x0210) {
8069                 /* Version 1 PCI9030 based universal PCI adapter */
8070                 info->misc_ctrl_value = 0x007c4080;
8071                 info->hw_version = 1;
8072         } else {
8073                 /* Version 0 PCI9050 based 5V PCI adapter
8074                  * A PCI9050 bug prevents reading LCR registers if 
8075                  * LCR base address bit 7 is set. Maintain shadow
8076                  * value so we can write to LCR misc control reg.
8077                  */
8078                 info->misc_ctrl_value = 0x087e4546;
8079                 info->hw_version = 0;
8080         }
8081                                 
8082         mgsl_add_device(info);
8083
8084         return 0;
8085 }
8086
8087 static void __devexit synclink_remove_one (struct pci_dev *dev)
8088 {
8089 }
8090