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