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