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