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