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