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