1/*
2 * $Id: synclink_gt.c,v 1.1.1.1 2007/08/03 18:52:28 Exp $
3 *
4 * Device driver for Microgate SyncLink GT serial adapters.
5 *
6 * written by Paul Fulghum for Microgate Corporation
7 * paulkf@microgate.com
8 *
9 * Microgate and SyncLink are trademarks of Microgate Corporation
10 *
11 * This code is released under the GNU General Public License (GPL)
12 *
13 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESS OR IMPLIED
14 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
15 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
16 * DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
17 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
18 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
19 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
20 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
21 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
22 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
23 * OF THE POSSIBILITY OF SUCH DAMAGE.
24 */
25
26/*
27 * DEBUG OUTPUT DEFINITIONS
28 *
29 * uncomment lines below to enable specific types of debug output
30 *
31 * DBGINFO   information - most verbose output
32 * DBGERR    serious errors
33 * DBGBH     bottom half service routine debugging
34 * DBGISR    interrupt service routine debugging
35 * DBGDATA   output receive and transmit data
36 * DBGTBUF   output transmit DMA buffers and registers
37 * DBGRBUF   output receive DMA buffers and registers
38 */
39
40#define DBGINFO(fmt) if (debug_level >= DEBUG_LEVEL_INFO) printk fmt
41#define DBGERR(fmt) if (debug_level >= DEBUG_LEVEL_ERROR) printk fmt
42#define DBGBH(fmt) if (debug_level >= DEBUG_LEVEL_BH) printk fmt
43#define DBGISR(fmt) if (debug_level >= DEBUG_LEVEL_ISR) printk fmt
44#define DBGDATA(info, buf, size, label) if (debug_level >= DEBUG_LEVEL_DATA) trace_block((info), (buf), (size), (label))
45//#define DBGTBUF(info) dump_tbufs(info)
46//#define DBGRBUF(info) dump_rbufs(info)
47
48
49#include <linux/module.h>
50#include <linux/version.h>
51#include <linux/errno.h>
52#include <linux/signal.h>
53#include <linux/sched.h>
54#include <linux/timer.h>
55#include <linux/interrupt.h>
56#include <linux/pci.h>
57#include <linux/tty.h>
58#include <linux/tty_flip.h>
59#include <linux/serial.h>
60#include <linux/major.h>
61#include <linux/string.h>
62#include <linux/fcntl.h>
63#include <linux/ptrace.h>
64#include <linux/ioport.h>
65#include <linux/mm.h>
66#include <linux/slab.h>
67#include <linux/netdevice.h>
68#include <linux/vmalloc.h>
69#include <linux/init.h>
70#include <linux/delay.h>
71#include <linux/ioctl.h>
72#include <linux/termios.h>
73#include <linux/bitops.h>
74#include <linux/workqueue.h>
75#include <linux/hdlc.h>
76
77#include <asm/system.h>
78#include <asm/io.h>
79#include <asm/irq.h>
80#include <asm/dma.h>
81#include <asm/types.h>
82#include <asm/uaccess.h>
83
84#include "linux/synclink.h"
85
86#if defined(CONFIG_HDLC) || (defined(CONFIG_HDLC_MODULE) && \
87	defined(CONFIG_SYNCLINK_GT_MODULE))
88#define SYNCLINK_GENERIC_HDLC 1
89#else
90#define SYNCLINK_GENERIC_HDLC 0
91#endif
92
93/*
94 * module identification
95 */
96static char *driver_name     = "SyncLink GT";
97static char *driver_version  = "$Revision: 1.1.1.1 $";
98static char *tty_driver_name = "synclink_gt";
99static char *tty_dev_prefix  = "ttySLG";
100MODULE_LICENSE("GPL");
101#define MGSL_MAGIC 0x5401
102#define MAX_DEVICES 32
103
104static struct pci_device_id pci_table[] = {
105	{PCI_VENDOR_ID_MICROGATE, SYNCLINK_GT_DEVICE_ID, PCI_ANY_ID, PCI_ANY_ID,},
106	{PCI_VENDOR_ID_MICROGATE, SYNCLINK_GT2_DEVICE_ID, PCI_ANY_ID, PCI_ANY_ID,},
107	{PCI_VENDOR_ID_MICROGATE, SYNCLINK_GT4_DEVICE_ID, PCI_ANY_ID, PCI_ANY_ID,},
108	{PCI_VENDOR_ID_MICROGATE, SYNCLINK_AC_DEVICE_ID, PCI_ANY_ID, PCI_ANY_ID,},
109	{0,}, /* terminate list */
110};
111MODULE_DEVICE_TABLE(pci, pci_table);
112
113static int  init_one(struct pci_dev *dev,const struct pci_device_id *ent);
114static void remove_one(struct pci_dev *dev);
115static struct pci_driver pci_driver = {
116	.name		= "synclink_gt",
117	.id_table	= pci_table,
118	.probe		= init_one,
119	.remove		= __devexit_p(remove_one),
120};
121
122static int pci_registered;
123
124/*
125 * module configuration and status
126 */
127static struct slgt_info *slgt_device_list;
128static int slgt_device_count;
129
130static int ttymajor;
131static int debug_level;
132static int maxframe[MAX_DEVICES];
133static int dosyncppp[MAX_DEVICES];
134
135module_param(ttymajor, int, 0);
136module_param(debug_level, int, 0);
137module_param_array(maxframe, int, NULL, 0);
138module_param_array(dosyncppp, int, NULL, 0);
139
140MODULE_PARM_DESC(ttymajor, "TTY major device number override: 0=auto assigned");
141MODULE_PARM_DESC(debug_level, "Debug syslog output: 0=disabled, 1 to 5=increasing detail");
142MODULE_PARM_DESC(maxframe, "Maximum frame size used by device (4096 to 65535)");
143MODULE_PARM_DESC(dosyncppp, "Enable synchronous net device, 0=disable 1=enable");
144
145/*
146 * tty support and callbacks
147 */
148#define RELEVANT_IFLAG(iflag) (iflag & (IGNBRK|BRKINT|IGNPAR|PARMRK|INPCK))
149
150static struct tty_driver *serial_driver;
151
152static int  open(struct tty_struct *tty, struct file * filp);
153static void close(struct tty_struct *tty, struct file * filp);
154static void hangup(struct tty_struct *tty);
155static void set_termios(struct tty_struct *tty, struct ktermios *old_termios);
156
157static int  write(struct tty_struct *tty, const unsigned char *buf, int count);
158static void put_char(struct tty_struct *tty, unsigned char ch);
159static void send_xchar(struct tty_struct *tty, char ch);
160static void wait_until_sent(struct tty_struct *tty, int timeout);
161static int  write_room(struct tty_struct *tty);
162static void flush_chars(struct tty_struct *tty);
163static void flush_buffer(struct tty_struct *tty);
164static void tx_hold(struct tty_struct *tty);
165static void tx_release(struct tty_struct *tty);
166
167static int  ioctl(struct tty_struct *tty, struct file *file, unsigned int cmd, unsigned long arg);
168static int  read_proc(char *page, char **start, off_t off, int count,int *eof, void *data);
169static int  chars_in_buffer(struct tty_struct *tty);
170static void throttle(struct tty_struct * tty);
171static void unthrottle(struct tty_struct * tty);
172static void set_break(struct tty_struct *tty, int break_state);
173
174/*
175 * generic HDLC support and callbacks
176 */
177#if SYNCLINK_GENERIC_HDLC
178#define dev_to_port(D) (dev_to_hdlc(D)->priv)
179static void hdlcdev_tx_done(struct slgt_info *info);
180static void hdlcdev_rx(struct slgt_info *info, char *buf, int size);
181static int  hdlcdev_init(struct slgt_info *info);
182static void hdlcdev_exit(struct slgt_info *info);
183#endif
184
185
186/*
187 * device specific structures, macros and functions
188 */
189
190#define SLGT_MAX_PORTS 4
191#define SLGT_REG_SIZE  256
192
193/*
194 * conditional wait facility
195 */
196struct cond_wait {
197	struct cond_wait *next;
198	wait_queue_head_t q;
199	wait_queue_t wait;
200	unsigned int data;
201};
202static void init_cond_wait(struct cond_wait *w, unsigned int data);
203static void add_cond_wait(struct cond_wait **head, struct cond_wait *w);
204static void remove_cond_wait(struct cond_wait **head, struct cond_wait *w);
205static void flush_cond_wait(struct cond_wait **head);
206
207/*
208 * DMA buffer descriptor and access macros
209 */
210struct slgt_desc
211{
212	unsigned short count;
213	unsigned short status;
214	unsigned int pbuf;  /* physical address of data buffer */
215	unsigned int next;  /* physical address of next descriptor */
216
217	/* driver book keeping */
218	char *buf;          /* virtual  address of data buffer */
219    	unsigned int pdesc; /* physical address of this descriptor */
220	dma_addr_t buf_dma_addr;
221};
222
223#define set_desc_buffer(a,b) (a).pbuf = cpu_to_le32((unsigned int)(b))
224#define set_desc_next(a,b) (a).next   = cpu_to_le32((unsigned int)(b))
225#define set_desc_count(a,b)(a).count  = cpu_to_le16((unsigned short)(b))
226#define set_desc_eof(a,b)  (a).status = cpu_to_le16((b) ? (le16_to_cpu((a).status) | BIT0) : (le16_to_cpu((a).status) & ~BIT0))
227#define desc_count(a)      (le16_to_cpu((a).count))
228#define desc_status(a)     (le16_to_cpu((a).status))
229#define desc_complete(a)   (le16_to_cpu((a).status) & BIT15)
230#define desc_eof(a)        (le16_to_cpu((a).status) & BIT2)
231#define desc_crc_error(a)  (le16_to_cpu((a).status) & BIT1)
232#define desc_abort(a)      (le16_to_cpu((a).status) & BIT0)
233#define desc_residue(a)    ((le16_to_cpu((a).status) & 0x38) >> 3)
234
235struct _input_signal_events {
236	int ri_up;
237	int ri_down;
238	int dsr_up;
239	int dsr_down;
240	int dcd_up;
241	int dcd_down;
242	int cts_up;
243	int cts_down;
244};
245
246/*
247 * device instance data structure
248 */
249struct slgt_info {
250	void *if_ptr;		/* General purpose pointer (used by SPPP) */
251
252	struct slgt_info *next_device;	/* device list link */
253
254	int magic;
255	int flags;
256
257	char device_name[25];
258	struct pci_dev *pdev;
259
260	int port_count;  /* count of ports on adapter */
261	int adapter_num; /* adapter instance number */
262	int port_num;    /* port instance number */
263
264	/* array of pointers to port contexts on this adapter */
265	struct slgt_info *port_array[SLGT_MAX_PORTS];
266
267	int			count;		/* count of opens */
268	int			line;		/* tty line instance number */
269	unsigned short		close_delay;
270	unsigned short		closing_wait;	/* time to wait before closing */
271
272	struct mgsl_icount	icount;
273
274	struct tty_struct 	*tty;
275	int			timeout;
276	int			x_char;		/* xon/xoff character */
277	int			blocked_open;	/* # of blocked opens */
278	unsigned int		read_status_mask;
279	unsigned int 		ignore_status_mask;
280
281	wait_queue_head_t	open_wait;
282	wait_queue_head_t	close_wait;
283
284	wait_queue_head_t	status_event_wait_q;
285	wait_queue_head_t	event_wait_q;
286	struct timer_list	tx_timer;
287	struct timer_list	rx_timer;
288
289	unsigned int            gpio_present;
290	struct cond_wait        *gpio_wait_q;
291
292	spinlock_t lock;	/* spinlock for synchronizing with ISR */
293
294	struct work_struct task;
295	u32 pending_bh;
296	int bh_requested;
297	int bh_running;
298
299	int isr_overflow;
300	int irq_requested;	/* nonzero if IRQ requested */
301	int irq_occurred;	/* for diagnostics use */
302
303	/* device configuration */
304
305	unsigned int bus_type;
306	unsigned int irq_level;
307	unsigned long irq_flags;
308
309	unsigned char __iomem * reg_addr;  /* memory mapped registers address */
310	u32 phys_reg_addr;
311	int reg_addr_requested;
312
313	MGSL_PARAMS params;       /* communications parameters */
314	u32 idle_mode;
315	u32 max_frame_size;       /* as set by device config */
316
317	unsigned int raw_rx_size;
318	unsigned int if_mode;
319
320	/* device status */
321
322	int rx_enabled;
323	int rx_restart;
324
325	int tx_enabled;
326	int tx_active;
327
328	unsigned char signals;    /* serial signal states */
329	int init_error;  /* initialization error */
330
331	unsigned char *tx_buf;
332	int tx_count;
333
334	char flag_buf[MAX_ASYNC_BUFFER_SIZE];
335	char char_buf[MAX_ASYNC_BUFFER_SIZE];
336	BOOLEAN drop_rts_on_tx_done;
337	struct	_input_signal_events	input_signal_events;
338
339	int dcd_chkcount;	/* check counts to prevent */
340	int cts_chkcount;	/* too many IRQs if a signal */
341	int dsr_chkcount;	/* is floating */
342	int ri_chkcount;
343
344	char *bufs;		/* virtual address of DMA buffer lists */
345	dma_addr_t bufs_dma_addr; /* physical address of buffer descriptors */
346
347	unsigned int rbuf_count;
348	struct slgt_desc *rbufs;
349	unsigned int rbuf_current;
350	unsigned int rbuf_index;
351
352	unsigned int tbuf_count;
353	struct slgt_desc *tbufs;
354	unsigned int tbuf_current;
355	unsigned int tbuf_start;
356
357	unsigned char *tmp_rbuf;
358	unsigned int tmp_rbuf_count;
359
360	/* SPPP/Cisco HDLC device parts */
361
362	int netcount;
363	int dosyncppp;
364	spinlock_t netlock;
365#if SYNCLINK_GENERIC_HDLC
366	struct net_device *netdev;
367#endif
368
369};
370
371static MGSL_PARAMS default_params = {
372	.mode            = MGSL_MODE_HDLC,
373	.loopback        = 0,
374	.flags           = HDLC_FLAG_UNDERRUN_ABORT15,
375	.encoding        = HDLC_ENCODING_NRZI_SPACE,
376	.clock_speed     = 0,
377	.addr_filter     = 0xff,
378	.crc_type        = HDLC_CRC_16_CCITT,
379	.preamble_length = HDLC_PREAMBLE_LENGTH_8BITS,
380	.preamble        = HDLC_PREAMBLE_PATTERN_NONE,
381	.data_rate       = 9600,
382	.data_bits       = 8,
383	.stop_bits       = 1,
384	.parity          = ASYNC_PARITY_NONE
385};
386
387
388#define BH_RECEIVE  1
389#define BH_TRANSMIT 2
390#define BH_STATUS   4
391#define IO_PIN_SHUTDOWN_LIMIT 100
392
393#define DMABUFSIZE 256
394#define DESC_LIST_SIZE 4096
395
396#define MASK_PARITY  BIT1
397#define MASK_FRAMING BIT0
398#define MASK_BREAK   BIT14
399#define MASK_OVERRUN BIT4
400
401#define GSR   0x00 /* global status */
402#define JCR   0x04 /* JTAG control */
403#define IODR  0x08 /* GPIO direction */
404#define IOER  0x0c /* GPIO interrupt enable */
405#define IOVR  0x10 /* GPIO value */
406#define IOSR  0x14 /* GPIO interrupt status */
407#define TDR   0x80 /* tx data */
408#define RDR   0x80 /* rx data */
409#define TCR   0x82 /* tx control */
410#define TIR   0x84 /* tx idle */
411#define TPR   0x85 /* tx preamble */
412#define RCR   0x86 /* rx control */
413#define VCR   0x88 /* V.24 control */
414#define CCR   0x89 /* clock control */
415#define BDR   0x8a /* baud divisor */
416#define SCR   0x8c /* serial control */
417#define SSR   0x8e /* serial status */
418#define RDCSR 0x90 /* rx DMA control/status */
419#define TDCSR 0x94 /* tx DMA control/status */
420#define RDDAR 0x98 /* rx DMA descriptor address */
421#define TDDAR 0x9c /* tx DMA descriptor address */
422
423#define RXIDLE      BIT14
424#define RXBREAK     BIT14
425#define IRQ_TXDATA  BIT13
426#define IRQ_TXIDLE  BIT12
427#define IRQ_TXUNDER BIT11 /* HDLC */
428#define IRQ_RXDATA  BIT10
429#define IRQ_RXIDLE  BIT9  /* HDLC */
430#define IRQ_RXBREAK BIT9  /* async */
431#define IRQ_RXOVER  BIT8
432#define IRQ_DSR     BIT7
433#define IRQ_CTS     BIT6
434#define IRQ_DCD     BIT5
435#define IRQ_RI      BIT4
436#define IRQ_ALL     0x3ff0
437#define IRQ_MASTER  BIT0
438
439#define slgt_irq_on(info, mask) \
440	wr_reg16((info), SCR, (unsigned short)(rd_reg16((info), SCR) | (mask)))
441#define slgt_irq_off(info, mask) \
442	wr_reg16((info), SCR, (unsigned short)(rd_reg16((info), SCR) & ~(mask)))
443
444static __u8  rd_reg8(struct slgt_info *info, unsigned int addr);
445static void  wr_reg8(struct slgt_info *info, unsigned int addr, __u8 value);
446static __u16 rd_reg16(struct slgt_info *info, unsigned int addr);
447static void  wr_reg16(struct slgt_info *info, unsigned int addr, __u16 value);
448static __u32 rd_reg32(struct slgt_info *info, unsigned int addr);
449static void  wr_reg32(struct slgt_info *info, unsigned int addr, __u32 value);
450
451static void  msc_set_vcr(struct slgt_info *info);
452
453static int  startup(struct slgt_info *info);
454static int  block_til_ready(struct tty_struct *tty, struct file * filp,struct slgt_info *info);
455static void shutdown(struct slgt_info *info);
456static void program_hw(struct slgt_info *info);
457static void change_params(struct slgt_info *info);
458
459static int  register_test(struct slgt_info *info);
460static int  irq_test(struct slgt_info *info);
461static int  loopback_test(struct slgt_info *info);
462static int  adapter_test(struct slgt_info *info);
463
464static void reset_adapter(struct slgt_info *info);
465static void reset_port(struct slgt_info *info);
466static void async_mode(struct slgt_info *info);
467static void sync_mode(struct slgt_info *info);
468
469static void rx_stop(struct slgt_info *info);
470static void rx_start(struct slgt_info *info);
471static void reset_rbufs(struct slgt_info *info);
472static void free_rbufs(struct slgt_info *info, unsigned int first, unsigned int last);
473static void rdma_reset(struct slgt_info *info);
474static int  rx_get_frame(struct slgt_info *info);
475static int  rx_get_buf(struct slgt_info *info);
476
477static void tx_start(struct slgt_info *info);
478static void tx_stop(struct slgt_info *info);
479static void tx_set_idle(struct slgt_info *info);
480static unsigned int free_tbuf_count(struct slgt_info *info);
481static void reset_tbufs(struct slgt_info *info);
482static void tdma_reset(struct slgt_info *info);
483static void tx_load(struct slgt_info *info, const char *buf, unsigned int count);
484
485static void get_signals(struct slgt_info *info);
486static void set_signals(struct slgt_info *info);
487static void enable_loopback(struct slgt_info *info);
488static void set_rate(struct slgt_info *info, u32 data_rate);
489
490static int  bh_action(struct slgt_info *info);
491static void bh_handler(struct work_struct *work);
492static void bh_transmit(struct slgt_info *info);
493static void isr_serial(struct slgt_info *info);
494static void isr_rdma(struct slgt_info *info);
495static void isr_txeom(struct slgt_info *info, unsigned short status);
496static void isr_tdma(struct slgt_info *info);
497static irqreturn_t slgt_interrupt(int irq, void *dev_id);
498
499static int  alloc_dma_bufs(struct slgt_info *info);
500static void free_dma_bufs(struct slgt_info *info);
501static int  alloc_desc(struct slgt_info *info);
502static void free_desc(struct slgt_info *info);
503static int  alloc_bufs(struct slgt_info *info, struct slgt_desc *bufs, int count);
504static void free_bufs(struct slgt_info *info, struct slgt_desc *bufs, int count);
505
506static int  alloc_tmp_rbuf(struct slgt_info *info);
507static void free_tmp_rbuf(struct slgt_info *info);
508
509static void tx_timeout(unsigned long context);
510static void rx_timeout(unsigned long context);
511
512/*
513 * ioctl handlers
514 */
515static int  get_stats(struct slgt_info *info, struct mgsl_icount __user *user_icount);
516static int  get_params(struct slgt_info *info, MGSL_PARAMS __user *params);
517static int  set_params(struct slgt_info *info, MGSL_PARAMS __user *params);
518static int  get_txidle(struct slgt_info *info, int __user *idle_mode);
519static int  set_txidle(struct slgt_info *info, int idle_mode);
520static int  tx_enable(struct slgt_info *info, int enable);
521static int  tx_abort(struct slgt_info *info);
522static int  rx_enable(struct slgt_info *info, int enable);
523static int  modem_input_wait(struct slgt_info *info,int arg);
524static int  wait_mgsl_event(struct slgt_info *info, int __user *mask_ptr);
525static int  tiocmget(struct tty_struct *tty, struct file *file);
526static int  tiocmset(struct tty_struct *tty, struct file *file,
527		     unsigned int set, unsigned int clear);
528static void set_break(struct tty_struct *tty, int break_state);
529static int  get_interface(struct slgt_info *info, int __user *if_mode);
530static int  set_interface(struct slgt_info *info, int if_mode);
531static int  set_gpio(struct slgt_info *info, struct gpio_desc __user *gpio);
532static int  get_gpio(struct slgt_info *info, struct gpio_desc __user *gpio);
533static int  wait_gpio(struct slgt_info *info, struct gpio_desc __user *gpio);
534
535/*
536 * driver functions
537 */
538static void add_device(struct slgt_info *info);
539static void device_init(int adapter_num, struct pci_dev *pdev);
540static int  claim_resources(struct slgt_info *info);
541static void release_resources(struct slgt_info *info);
542
543/*
544 * DEBUG OUTPUT CODE
545 */
546#ifndef DBGINFO
547#define DBGINFO(fmt)
548#endif
549#ifndef DBGERR
550#define DBGERR(fmt)
551#endif
552#ifndef DBGBH
553#define DBGBH(fmt)
554#endif
555#ifndef DBGISR
556#define DBGISR(fmt)
557#endif
558
559#ifdef DBGDATA
560static void trace_block(struct slgt_info *info, const char *data, int count, const char *label)
561{
562	int i;
563	int linecount;
564	printk("%s %s data:\n",info->device_name, label);
565	while(count) {
566		linecount = (count > 16) ? 16 : count;
567		for(i=0; i < linecount; i++)
568			printk("%02X ",(unsigned char)data[i]);
569		for(;i<17;i++)
570			printk("   ");
571		for(i=0;i<linecount;i++) {
572			if (data[i]>=040 && data[i]<=0176)
573				printk("%c",data[i]);
574			else
575				printk(".");
576		}
577		printk("\n");
578		data  += linecount;
579		count -= linecount;
580	}
581}
582#else
583#define DBGDATA(info, buf, size, label)
584#endif
585
586#ifdef DBGTBUF
587static void dump_tbufs(struct slgt_info *info)
588{
589	int i;
590	printk("tbuf_current=%d\n", info->tbuf_current);
591	for (i=0 ; i < info->tbuf_count ; i++) {
592		printk("%d: count=%04X status=%04X\n",
593			i, le16_to_cpu(info->tbufs[i].count), le16_to_cpu(info->tbufs[i].status));
594	}
595}
596#else
597#define DBGTBUF(info)
598#endif
599
600#ifdef DBGRBUF
601static void dump_rbufs(struct slgt_info *info)
602{
603	int i;
604	printk("rbuf_current=%d\n", info->rbuf_current);
605	for (i=0 ; i < info->rbuf_count ; i++) {
606		printk("%d: count=%04X status=%04X\n",
607			i, le16_to_cpu(info->rbufs[i].count), le16_to_cpu(info->rbufs[i].status));
608	}
609}
610#else
611#define DBGRBUF(info)
612#endif
613
614static inline int sanity_check(struct slgt_info *info, char *devname, const char *name)
615{
616#ifdef SANITY_CHECK
617	if (!info) {
618		printk("null struct slgt_info for (%s) in %s\n", devname, name);
619		return 1;
620	}
621	if (info->magic != MGSL_MAGIC) {
622		printk("bad magic number struct slgt_info (%s) in %s\n", devname, name);
623		return 1;
624	}
625#else
626	if (!info)
627		return 1;
628#endif
629	return 0;
630}
631
632/**
633 * line discipline callback wrappers
634 *
635 * The wrappers maintain line discipline references
636 * while calling into the line discipline.
637 *
638 * ldisc_receive_buf  - pass receive data to line discipline
639 */
640static void ldisc_receive_buf(struct tty_struct *tty,
641			      const __u8 *data, char *flags, int count)
642{
643	struct tty_ldisc *ld;
644	if (!tty)
645		return;
646	ld = tty_ldisc_ref(tty);
647	if (ld) {
648		if (ld->receive_buf)
649			ld->receive_buf(tty, data, flags, count);
650		tty_ldisc_deref(ld);
651	}
652}
653
654/* tty callbacks */
655
656static int open(struct tty_struct *tty, struct file *filp)
657{
658	struct slgt_info *info;
659	int retval, line;
660	unsigned long flags;
661
662	line = tty->index;
663	if ((line < 0) || (line >= slgt_device_count)) {
664		DBGERR(("%s: open with invalid line #%d.\n", driver_name, line));
665		return -ENODEV;
666	}
667
668	info = slgt_device_list;
669	while(info && info->line != line)
670		info = info->next_device;
671	if (sanity_check(info, tty->name, "open"))
672		return -ENODEV;
673	if (info->init_error) {
674		DBGERR(("%s init error=%d\n", info->device_name, info->init_error));
675		return -ENODEV;
676	}
677
678	tty->driver_data = info;
679	info->tty = tty;
680
681	DBGINFO(("%s open, old ref count = %d\n", info->device_name, info->count));
682
683	/* If port is closing, signal caller to try again */
684	if (tty_hung_up_p(filp) || info->flags & ASYNC_CLOSING){
685		if (info->flags & ASYNC_CLOSING)
686			interruptible_sleep_on(&info->close_wait);
687		retval = ((info->flags & ASYNC_HUP_NOTIFY) ?
688			-EAGAIN : -ERESTARTSYS);
689		goto cleanup;
690	}
691
692	info->tty->low_latency = (info->flags & ASYNC_LOW_LATENCY) ? 1 : 0;
693
694	spin_lock_irqsave(&info->netlock, flags);
695	if (info->netcount) {
696		retval = -EBUSY;
697		spin_unlock_irqrestore(&info->netlock, flags);
698		goto cleanup;
699	}
700	info->count++;
701	spin_unlock_irqrestore(&info->netlock, flags);
702
703	if (info->count == 1) {
704		/* 1st open on this device, init hardware */
705		retval = startup(info);
706		if (retval < 0)
707			goto cleanup;
708	}
709
710	retval = block_til_ready(tty, filp, info);
711	if (retval) {
712		DBGINFO(("%s block_til_ready rc=%d\n", info->device_name, retval));
713		goto cleanup;
714	}
715
716	retval = 0;
717
718cleanup:
719	if (retval) {
720		if (tty->count == 1)
721			info->tty = NULL; /* tty layer will release tty struct */
722		if(info->count)
723			info->count--;
724	}
725
726	DBGINFO(("%s open rc=%d\n", info->device_name, retval));
727	return retval;
728}
729
730static void close(struct tty_struct *tty, struct file *filp)
731{
732	struct slgt_info *info = tty->driver_data;
733
734	if (sanity_check(info, tty->name, "close"))
735		return;
736	DBGINFO(("%s close entry, count=%d\n", info->device_name, info->count));
737
738	if (!info->count)
739		return;
740
741	if (tty_hung_up_p(filp))
742		goto cleanup;
743
744	if ((tty->count == 1) && (info->count != 1)) {
745		/*
746		 * tty->count is 1 and the tty structure will be freed.
747		 * info->count should be one in this case.
748		 * if it's not, correct it so that the port is shutdown.
749		 */
750		DBGERR(("%s close: bad refcount; tty->count=1, "
751		       "info->count=%d\n", info->device_name, info->count));
752		info->count = 1;
753	}
754
755	info->count--;
756
757	/* if at least one open remaining, leave hardware active */
758	if (info->count)
759		goto cleanup;
760
761	info->flags |= ASYNC_CLOSING;
762
763	/* set tty->closing to notify line discipline to
764	 * only process XON/XOFF characters. Only the N_TTY
765	 * discipline appears to use this (ppp does not).
766	 */
767	tty->closing = 1;
768
769	/* wait for transmit data to clear all layers */
770
771	if (info->closing_wait != ASYNC_CLOSING_WAIT_NONE) {
772		DBGINFO(("%s call tty_wait_until_sent\n", info->device_name));
773		tty_wait_until_sent(tty, info->closing_wait);
774	}
775
776 	if (info->flags & ASYNC_INITIALIZED)
777 		wait_until_sent(tty, info->timeout);
778	if (tty->driver->flush_buffer)
779		tty->driver->flush_buffer(tty);
780	tty_ldisc_flush(tty);
781
782	shutdown(info);
783
784	tty->closing = 0;
785	info->tty = NULL;
786
787	if (info->blocked_open) {
788		if (info->close_delay) {
789			msleep_interruptible(jiffies_to_msecs(info->close_delay));
790		}
791		wake_up_interruptible(&info->open_wait);
792	}
793
794	info->flags &= ~(ASYNC_NORMAL_ACTIVE|ASYNC_CLOSING);
795
796	wake_up_interruptible(&info->close_wait);
797
798cleanup:
799	DBGINFO(("%s close exit, count=%d\n", tty->driver->name, info->count));
800}
801
802static void hangup(struct tty_struct *tty)
803{
804	struct slgt_info *info = tty->driver_data;
805
806	if (sanity_check(info, tty->name, "hangup"))
807		return;
808	DBGINFO(("%s hangup\n", info->device_name));
809
810	flush_buffer(tty);
811	shutdown(info);
812
813	info->count = 0;
814	info->flags &= ~ASYNC_NORMAL_ACTIVE;
815	info->tty = NULL;
816
817	wake_up_interruptible(&info->open_wait);
818}
819
820static void set_termios(struct tty_struct *tty, struct ktermios *old_termios)
821{
822	struct slgt_info *info = tty->driver_data;
823	unsigned long flags;
824
825	DBGINFO(("%s set_termios\n", tty->driver->name));
826
827	/* just return if nothing has changed */
828	if ((tty->termios->c_cflag == old_termios->c_cflag)
829	    && (RELEVANT_IFLAG(tty->termios->c_iflag)
830		== RELEVANT_IFLAG(old_termios->c_iflag)))
831		return;
832
833	change_params(info);
834
835	/* Handle transition to B0 status */
836	if (old_termios->c_cflag & CBAUD &&
837	    !(tty->termios->c_cflag & CBAUD)) {
838		info->signals &= ~(SerialSignal_RTS + SerialSignal_DTR);
839		spin_lock_irqsave(&info->lock,flags);
840		set_signals(info);
841		spin_unlock_irqrestore(&info->lock,flags);
842	}
843
844	/* Handle transition away from B0 status */
845	if (!(old_termios->c_cflag & CBAUD) &&
846	    tty->termios->c_cflag & CBAUD) {
847		info->signals |= SerialSignal_DTR;
848 		if (!(tty->termios->c_cflag & CRTSCTS) ||
849 		    !test_bit(TTY_THROTTLED, &tty->flags)) {
850			info->signals |= SerialSignal_RTS;
851 		}
852		spin_lock_irqsave(&info->lock,flags);
853	 	set_signals(info);
854		spin_unlock_irqrestore(&info->lock,flags);
855	}
856
857	/* Handle turning off CRTSCTS */
858	if (old_termios->c_cflag & CRTSCTS &&
859	    !(tty->termios->c_cflag & CRTSCTS)) {
860		tty->hw_stopped = 0;
861		tx_release(tty);
862	}
863}
864
865static int write(struct tty_struct *tty,
866		 const unsigned char *buf, int count)
867{
868	int ret = 0;
869	struct slgt_info *info = tty->driver_data;
870	unsigned long flags;
871
872	if (sanity_check(info, tty->name, "write"))
873		goto cleanup;
874	DBGINFO(("%s write count=%d\n", info->device_name, count));
875
876	if (!info->tx_buf)
877		goto cleanup;
878
879	if (count > info->max_frame_size) {
880		ret = -EIO;
881		goto cleanup;
882	}
883
884	if (!count)
885		goto cleanup;
886
887	if (info->params.mode == MGSL_MODE_RAW ||
888	    info->params.mode == MGSL_MODE_MONOSYNC ||
889	    info->params.mode == MGSL_MODE_BISYNC) {
890		unsigned int bufs_needed = (count/DMABUFSIZE);
891		unsigned int bufs_free = free_tbuf_count(info);
892		if (count % DMABUFSIZE)
893			++bufs_needed;
894		if (bufs_needed > bufs_free)
895			goto cleanup;
896	} else {
897		if (info->tx_active)
898			goto cleanup;
899		if (info->tx_count) {
900			/* send accumulated data from send_char() calls */
901			/* as frame and wait before accepting more data. */
902			tx_load(info, info->tx_buf, info->tx_count);
903			goto start;
904		}
905	}
906
907	ret = info->tx_count = count;
908	tx_load(info, buf, count);
909	goto start;
910
911start:
912 	if (info->tx_count && !tty->stopped && !tty->hw_stopped) {
913		spin_lock_irqsave(&info->lock,flags);
914		if (!info->tx_active)
915		 	tx_start(info);
916		spin_unlock_irqrestore(&info->lock,flags);
917 	}
918
919cleanup:
920	DBGINFO(("%s write rc=%d\n", info->device_name, ret));
921	return ret;
922}
923
924static void put_char(struct tty_struct *tty, unsigned char ch)
925{
926	struct slgt_info *info = tty->driver_data;
927	unsigned long flags;
928
929	if (sanity_check(info, tty->name, "put_char"))
930		return;
931	DBGINFO(("%s put_char(%d)\n", info->device_name, ch));
932	if (!info->tx_buf)
933		return;
934	spin_lock_irqsave(&info->lock,flags);
935	if (!info->tx_active && (info->tx_count < info->max_frame_size))
936		info->tx_buf[info->tx_count++] = ch;
937	spin_unlock_irqrestore(&info->lock,flags);
938}
939
940static void send_xchar(struct tty_struct *tty, char ch)
941{
942	struct slgt_info *info = tty->driver_data;
943	unsigned long flags;
944
945	if (sanity_check(info, tty->name, "send_xchar"))
946		return;
947	DBGINFO(("%s send_xchar(%d)\n", info->device_name, ch));
948	info->x_char = ch;
949	if (ch) {
950		spin_lock_irqsave(&info->lock,flags);
951		if (!info->tx_enabled)
952		 	tx_start(info);
953		spin_unlock_irqrestore(&info->lock,flags);
954	}
955}
956
957static void wait_until_sent(struct tty_struct *tty, int timeout)
958{
959	struct slgt_info *info = tty->driver_data;
960	unsigned long orig_jiffies, char_time;
961
962	if (!info )
963		return;
964	if (sanity_check(info, tty->name, "wait_until_sent"))
965		return;
966	DBGINFO(("%s wait_until_sent entry\n", info->device_name));
967	if (!(info->flags & ASYNC_INITIALIZED))
968		goto exit;
969
970	orig_jiffies = jiffies;
971
972	/* Set check interval to 1/5 of estimated time to
973	 * send a character, and make it at least 1. The check
974	 * interval should also be less than the timeout.
975	 * Note: use tight timings here to satisfy the NIST-PCTS.
976	 */
977
978	if (info->params.data_rate) {
979	       	char_time = info->timeout/(32 * 5);
980		if (!char_time)
981			char_time++;
982	} else
983		char_time = 1;
984
985	if (timeout)
986		char_time = min_t(unsigned long, char_time, timeout);
987
988	while (info->tx_active) {
989		msleep_interruptible(jiffies_to_msecs(char_time));
990		if (signal_pending(current))
991			break;
992		if (timeout && time_after(jiffies, orig_jiffies + timeout))
993			break;
994	}
995
996exit:
997	DBGINFO(("%s wait_until_sent exit\n", info->device_name));
998}
999
1000static int write_room(struct tty_struct *tty)
1001{
1002	struct slgt_info *info = tty->driver_data;
1003	int ret;
1004
1005	if (sanity_check(info, tty->name, "write_room"))
1006		return 0;
1007	ret = (info->tx_active) ? 0 : HDLC_MAX_FRAME_SIZE;
1008	DBGINFO(("%s write_room=%d\n", info->device_name, ret));
1009	return ret;
1010}
1011
1012static void flush_chars(struct tty_struct *tty)
1013{
1014	struct slgt_info *info = tty->driver_data;
1015	unsigned long flags;
1016
1017	if (sanity_check(info, tty->name, "flush_chars"))
1018		return;
1019	DBGINFO(("%s flush_chars entry tx_count=%d\n", info->device_name, info->tx_count));
1020
1021	if (info->tx_count <= 0 || tty->stopped ||
1022	    tty->hw_stopped || !info->tx_buf)
1023		return;
1024
1025	DBGINFO(("%s flush_chars start transmit\n", info->device_name));
1026
1027	spin_lock_irqsave(&info->lock,flags);
1028	if (!info->tx_active && info->tx_count) {
1029		tx_load(info, info->tx_buf,info->tx_count);
1030	 	tx_start(info);
1031	}
1032	spin_unlock_irqrestore(&info->lock,flags);
1033}
1034
1035static void flush_buffer(struct tty_struct *tty)
1036{
1037	struct slgt_info *info = tty->driver_data;
1038	unsigned long flags;
1039
1040	if (sanity_check(info, tty->name, "flush_buffer"))
1041		return;
1042	DBGINFO(("%s flush_buffer\n", info->device_name));
1043
1044	spin_lock_irqsave(&info->lock,flags);
1045	if (!info->tx_active)
1046		info->tx_count = 0;
1047	spin_unlock_irqrestore(&info->lock,flags);
1048
1049	tty_wakeup(tty);
1050}
1051
1052/*
1053 * throttle (stop) transmitter
1054 */
1055static void tx_hold(struct tty_struct *tty)
1056{
1057	struct slgt_info *info = tty->driver_data;
1058	unsigned long flags;
1059
1060	if (sanity_check(info, tty->name, "tx_hold"))
1061		return;
1062	DBGINFO(("%s tx_hold\n", info->device_name));
1063	spin_lock_irqsave(&info->lock,flags);
1064	if (info->tx_enabled && info->params.mode == MGSL_MODE_ASYNC)
1065	 	tx_stop(info);
1066	spin_unlock_irqrestore(&info->lock,flags);
1067}
1068
1069/*
1070 * release (start) transmitter
1071 */
1072static void tx_release(struct tty_struct *tty)
1073{
1074	struct slgt_info *info = tty->driver_data;
1075	unsigned long flags;
1076
1077	if (sanity_check(info, tty->name, "tx_release"))
1078		return;
1079	DBGINFO(("%s tx_release\n", info->device_name));
1080	spin_lock_irqsave(&info->lock,flags);
1081	if (!info->tx_active && info->tx_count) {
1082		tx_load(info, info->tx_buf, info->tx_count);
1083	 	tx_start(info);
1084	}
1085	spin_unlock_irqrestore(&info->lock,flags);
1086}
1087
1088/*
1089 * Service an IOCTL request
1090 *
1091 * Arguments
1092 *
1093 * 	tty	pointer to tty instance data
1094 * 	file	pointer to associated file object for device
1095 * 	cmd	IOCTL command code
1096 * 	arg	command argument/context
1097 *
1098 * Return 0 if success, otherwise error code
1099 */
1100static int ioctl(struct tty_struct *tty, struct file *file,
1101		 unsigned int cmd, unsigned long arg)
1102{
1103	struct slgt_info *info = tty->driver_data;
1104	struct mgsl_icount cnow;	/* kernel counter temps */
1105	struct serial_icounter_struct __user *p_cuser;	/* user space */
1106	unsigned long flags;
1107	void __user *argp = (void __user *)arg;
1108
1109	if (sanity_check(info, tty->name, "ioctl"))
1110		return -ENODEV;
1111	DBGINFO(("%s ioctl() cmd=%08X\n", info->device_name, cmd));
1112
1113	if ((cmd != TIOCGSERIAL) && (cmd != TIOCSSERIAL) &&
1114	    (cmd != TIOCMIWAIT) && (cmd != TIOCGICOUNT)) {
1115		if (tty->flags & (1 << TTY_IO_ERROR))
1116		    return -EIO;
1117	}
1118
1119	switch (cmd) {
1120	case MGSL_IOCGPARAMS:
1121		return get_params(info, argp);
1122	case MGSL_IOCSPARAMS:
1123		return set_params(info, argp);
1124	case MGSL_IOCGTXIDLE:
1125		return get_txidle(info, argp);
1126	case MGSL_IOCSTXIDLE:
1127		return set_txidle(info, (int)arg);
1128	case MGSL_IOCTXENABLE:
1129		return tx_enable(info, (int)arg);
1130	case MGSL_IOCRXENABLE:
1131		return rx_enable(info, (int)arg);
1132	case MGSL_IOCTXABORT:
1133		return tx_abort(info);
1134	case MGSL_IOCGSTATS:
1135		return get_stats(info, argp);
1136	case MGSL_IOCWAITEVENT:
1137		return wait_mgsl_event(info, argp);
1138	case TIOCMIWAIT:
1139		return modem_input_wait(info,(int)arg);
1140	case MGSL_IOCGIF:
1141		return get_interface(info, argp);
1142	case MGSL_IOCSIF:
1143		return set_interface(info,(int)arg);
1144	case MGSL_IOCSGPIO:
1145		return set_gpio(info, argp);
1146	case MGSL_IOCGGPIO:
1147		return get_gpio(info, argp);
1148	case MGSL_IOCWAITGPIO:
1149		return wait_gpio(info, argp);
1150	case TIOCGICOUNT:
1151		spin_lock_irqsave(&info->lock,flags);
1152		cnow = info->icount;
1153		spin_unlock_irqrestore(&info->lock,flags);
1154		p_cuser = argp;
1155		if (put_user(cnow.cts, &p_cuser->cts) ||
1156		    put_user(cnow.dsr, &p_cuser->dsr) ||
1157		    put_user(cnow.rng, &p_cuser->rng) ||
1158		    put_user(cnow.dcd, &p_cuser->dcd) ||
1159		    put_user(cnow.rx, &p_cuser->rx) ||
1160		    put_user(cnow.tx, &p_cuser->tx) ||
1161		    put_user(cnow.frame, &p_cuser->frame) ||
1162		    put_user(cnow.overrun, &p_cuser->overrun) ||
1163		    put_user(cnow.parity, &p_cuser->parity) ||
1164		    put_user(cnow.brk, &p_cuser->brk) ||
1165		    put_user(cnow.buf_overrun, &p_cuser->buf_overrun))
1166			return -EFAULT;
1167		return 0;
1168	default:
1169		return -ENOIOCTLCMD;
1170	}
1171	return 0;
1172}
1173
1174/*
1175 * support for 32 bit ioctl calls on 64 bit systems
1176 */
1177#ifdef CONFIG_COMPAT
1178static long get_params32(struct slgt_info *info, struct MGSL_PARAMS32 __user *user_params)
1179{
1180	struct MGSL_PARAMS32 tmp_params;
1181
1182	DBGINFO(("%s get_params32\n", info->device_name));
1183	tmp_params.mode            = (compat_ulong_t)info->params.mode;
1184	tmp_params.loopback        = info->params.loopback;
1185	tmp_params.flags           = info->params.flags;
1186	tmp_params.encoding        = info->params.encoding;
1187	tmp_params.clock_speed     = (compat_ulong_t)info->params.clock_speed;
1188	tmp_params.addr_filter     = info->params.addr_filter;
1189	tmp_params.crc_type        = info->params.crc_type;
1190	tmp_params.preamble_length = info->params.preamble_length;
1191	tmp_params.preamble        = info->params.preamble;
1192	tmp_params.data_rate       = (compat_ulong_t)info->params.data_rate;
1193	tmp_params.data_bits       = info->params.data_bits;
1194	tmp_params.stop_bits       = info->params.stop_bits;
1195	tmp_params.parity          = info->params.parity;
1196	if (copy_to_user(user_params, &tmp_params, sizeof(struct MGSL_PARAMS32)))
1197		return -EFAULT;
1198	return 0;
1199}
1200
1201static long set_params32(struct slgt_info *info, struct MGSL_PARAMS32 __user *new_params)
1202{
1203	struct MGSL_PARAMS32 tmp_params;
1204
1205	DBGINFO(("%s set_params32\n", info->device_name));
1206	if (copy_from_user(&tmp_params, new_params, sizeof(struct MGSL_PARAMS32)))
1207		return -EFAULT;
1208
1209	spin_lock(&info->lock);
1210	info->params.mode            = tmp_params.mode;
1211	info->params.loopback        = tmp_params.loopback;
1212	info->params.flags           = tmp_params.flags;
1213	info->params.encoding        = tmp_params.encoding;
1214	info->params.clock_speed     = tmp_params.clock_speed;
1215	info->params.addr_filter     = tmp_params.addr_filter;
1216	info->params.crc_type        = tmp_params.crc_type;
1217	info->params.preamble_length = tmp_params.preamble_length;
1218	info->params.preamble        = tmp_params.preamble;
1219	info->params.data_rate       = tmp_params.data_rate;
1220	info->params.data_bits       = tmp_params.data_bits;
1221	info->params.stop_bits       = tmp_params.stop_bits;
1222	info->params.parity          = tmp_params.parity;
1223	spin_unlock(&info->lock);
1224
1225 	change_params(info);
1226
1227	return 0;
1228}
1229
1230static long slgt_compat_ioctl(struct tty_struct *tty, struct file *file,
1231			 unsigned int cmd, unsigned long arg)
1232{
1233	struct slgt_info *info = tty->driver_data;
1234	int rc = -ENOIOCTLCMD;
1235
1236	if (sanity_check(info, tty->name, "compat_ioctl"))
1237		return -ENODEV;
1238	DBGINFO(("%s compat_ioctl() cmd=%08X\n", info->device_name, cmd));
1239
1240	switch (cmd) {
1241
1242	case MGSL_IOCSPARAMS32:
1243		rc = set_params32(info, compat_ptr(arg));
1244		break;
1245
1246	case MGSL_IOCGPARAMS32:
1247		rc = get_params32(info, compat_ptr(arg));
1248		break;
1249
1250	case MGSL_IOCGPARAMS:
1251	case MGSL_IOCSPARAMS:
1252	case MGSL_IOCGTXIDLE:
1253	case MGSL_IOCGSTATS:
1254	case MGSL_IOCWAITEVENT:
1255	case MGSL_IOCGIF:
1256	case MGSL_IOCSGPIO:
1257	case MGSL_IOCGGPIO:
1258	case MGSL_IOCWAITGPIO:
1259	case TIOCGICOUNT:
1260		rc = ioctl(tty, file, cmd, (unsigned long)(compat_ptr(arg)));
1261		break;
1262
1263	case MGSL_IOCSTXIDLE:
1264	case MGSL_IOCTXENABLE:
1265	case MGSL_IOCRXENABLE:
1266	case MGSL_IOCTXABORT:
1267	case TIOCMIWAIT:
1268	case MGSL_IOCSIF:
1269		rc = ioctl(tty, file, cmd, arg);
1270		break;
1271	}
1272
1273	DBGINFO(("%s compat_ioctl() cmd=%08X rc=%d\n", info->device_name, cmd, rc));
1274	return rc;
1275}
1276#else
1277#define slgt_compat_ioctl NULL
1278#endif /* ifdef CONFIG_COMPAT */
1279
1280/*
1281 * proc fs support
1282 */
1283static inline int line_info(char *buf, struct slgt_info *info)
1284{
1285	char stat_buf[30];
1286	int ret;
1287	unsigned long flags;
1288
1289	ret = sprintf(buf, "%s: IO=%08X IRQ=%d MaxFrameSize=%u\n",
1290		      info->device_name, info->phys_reg_addr,
1291		      info->irq_level, info->max_frame_size);
1292
1293	/* output current serial signal states */
1294	spin_lock_irqsave(&info->lock,flags);
1295	get_signals(info);
1296	spin_unlock_irqrestore(&info->lock,flags);
1297
1298	stat_buf[0] = 0;
1299	stat_buf[1] = 0;
1300	if (info->signals & SerialSignal_RTS)
1301		strcat(stat_buf, "|RTS");
1302	if (info->signals & SerialSignal_CTS)
1303		strcat(stat_buf, "|CTS");
1304	if (info->signals & SerialSignal_DTR)
1305		strcat(stat_buf, "|DTR");
1306	if (info->signals & SerialSignal_DSR)
1307		strcat(stat_buf, "|DSR");
1308	if (info->signals & SerialSignal_DCD)
1309		strcat(stat_buf, "|CD");
1310	if (info->signals & SerialSignal_RI)
1311		strcat(stat_buf, "|RI");
1312
1313	if (info->params.mode != MGSL_MODE_ASYNC) {
1314		ret += sprintf(buf+ret, "\tHDLC txok:%d rxok:%d",
1315			       info->icount.txok, info->icount.rxok);
1316		if (info->icount.txunder)
1317			ret += sprintf(buf+ret, " txunder:%d", info->icount.txunder);
1318		if (info->icount.txabort)
1319			ret += sprintf(buf+ret, " txabort:%d", info->icount.txabort);
1320		if (info->icount.rxshort)
1321			ret += sprintf(buf+ret, " rxshort:%d", info->icount.rxshort);
1322		if (info->icount.rxlong)
1323			ret += sprintf(buf+ret, " rxlong:%d", info->icount.rxlong);
1324		if (info->icount.rxover)
1325			ret += sprintf(buf+ret, " rxover:%d", info->icount.rxover);
1326		if (info->icount.rxcrc)
1327			ret += sprintf(buf+ret, " rxcrc:%d", info->icount.rxcrc);
1328	} else {
1329		ret += sprintf(buf+ret, "\tASYNC tx:%d rx:%d",
1330			       info->icount.tx, info->icount.rx);
1331		if (info->icount.frame)
1332			ret += sprintf(buf+ret, " fe:%d", info->icount.frame);
1333		if (info->icount.parity)
1334			ret += sprintf(buf+ret, " pe:%d", info->icount.parity);
1335		if (info->icount.brk)
1336			ret += sprintf(buf+ret, " brk:%d", info->icount.brk);
1337		if (info->icount.overrun)
1338			ret += sprintf(buf+ret, " oe:%d", info->icount.overrun);
1339	}
1340
1341	/* Append serial signal status to end */
1342	ret += sprintf(buf+ret, " %s\n", stat_buf+1);
1343
1344	ret += sprintf(buf+ret, "\ttxactive=%d bh_req=%d bh_run=%d pending_bh=%x\n",
1345		       info->tx_active,info->bh_requested,info->bh_running,
1346		       info->pending_bh);
1347
1348	return ret;
1349}
1350
1351/* Called to print information about devices
1352 */
1353static int read_proc(char *page, char **start, off_t off, int count,
1354		     int *eof, void *data)
1355{
1356	int len = 0, l;
1357	off_t	begin = 0;
1358	struct slgt_info *info;
1359
1360	len += sprintf(page, "synclink_gt driver:%s\n", driver_version);
1361
1362	info = slgt_device_list;
1363	while( info ) {
1364		l = line_info(page + len, info);
1365		len += l;
1366		if (len+begin > off+count)
1367			goto done;
1368		if (len+begin < off) {
1369			begin += len;
1370			len = 0;
1371		}
1372		info = info->next_device;
1373	}
1374
1375	*eof = 1;
1376done:
1377	if (off >= len+begin)
1378		return 0;
1379	*start = page + (off-begin);
1380	return ((count < begin+len-off) ? count : begin+len-off);
1381}
1382
1383/*
1384 * return count of bytes in transmit buffer
1385 */
1386static int chars_in_buffer(struct tty_struct *tty)
1387{
1388	struct slgt_info *info = tty->driver_data;
1389	if (sanity_check(info, tty->name, "chars_in_buffer"))
1390		return 0;
1391	DBGINFO(("%s chars_in_buffer()=%d\n", info->device_name, info->tx_count));
1392	return info->tx_count;
1393}
1394
1395/*
1396 * signal remote device to throttle send data (our receive data)
1397 */
1398static void throttle(struct tty_struct * tty)
1399{
1400	struct slgt_info *info = tty->driver_data;
1401	unsigned long flags;
1402
1403	if (sanity_check(info, tty->name, "throttle"))
1404		return;
1405	DBGINFO(("%s throttle\n", info->device_name));
1406	if (I_IXOFF(tty))
1407		send_xchar(tty, STOP_CHAR(tty));
1408 	if (tty->termios->c_cflag & CRTSCTS) {
1409		spin_lock_irqsave(&info->lock,flags);
1410		info->signals &= ~SerialSignal_RTS;
1411	 	set_signals(info);
1412		spin_unlock_irqrestore(&info->lock,flags);
1413	}
1414}
1415
1416/*
1417 * signal remote device to stop throttling send data (our receive data)
1418 */
1419static void unthrottle(struct tty_struct * tty)
1420{
1421	struct slgt_info *info = tty->driver_data;
1422	unsigned long flags;
1423
1424	if (sanity_check(info, tty->name, "unthrottle"))
1425		return;
1426	DBGINFO(("%s unthrottle\n", info->device_name));
1427	if (I_IXOFF(tty)) {
1428		if (info->x_char)
1429			info->x_char = 0;
1430		else
1431			send_xchar(tty, START_CHAR(tty));
1432	}
1433 	if (tty->termios->c_cflag & CRTSCTS) {
1434		spin_lock_irqsave(&info->lock,flags);
1435		info->signals |= SerialSignal_RTS;
1436	 	set_signals(info);
1437		spin_unlock_irqrestore(&info->lock,flags);
1438	}
1439}
1440
1441/*
1442 * set or clear transmit break condition
1443 * break_state	-1=set break condition, 0=clear
1444 */
1445static void set_break(struct tty_struct *tty, int break_state)
1446{
1447	struct slgt_info *info = tty->driver_data;
1448	unsigned short value;
1449	unsigned long flags;
1450
1451	if (sanity_check(info, tty->name, "set_break"))
1452		return;
1453	DBGINFO(("%s set_break(%d)\n", info->device_name, break_state));
1454
1455	spin_lock_irqsave(&info->lock,flags);
1456	value = rd_reg16(info, TCR);
1457 	if (break_state == -1)
1458		value |= BIT6;
1459	else
1460		value &= ~BIT6;
1461	wr_reg16(info, TCR, value);
1462	spin_unlock_irqrestore(&info->lock,flags);
1463}
1464
1465#if SYNCLINK_GENERIC_HDLC
1466
1467/**
1468 * called by generic HDLC layer when protocol selected (PPP, frame relay, etc.)
1469 * set encoding and frame check sequence (FCS) options
1470 *
1471 * dev       pointer to network device structure
1472 * encoding  serial encoding setting
1473 * parity    FCS setting
1474 *
1475 * returns 0 if success, otherwise error code
1476 */
1477static int hdlcdev_attach(struct net_device *dev, unsigned short encoding,
1478			  unsigned short parity)
1479{
1480	struct slgt_info *info = dev_to_port(dev);
1481	unsigned char  new_encoding;
1482	unsigned short new_crctype;
1483
1484	/* return error if TTY interface open */
1485	if (info->count)
1486		return -EBUSY;
1487
1488	DBGINFO(("%s hdlcdev_attach\n", info->device_name));
1489
1490	switch (encoding)
1491	{
1492	case ENCODING_NRZ:        new_encoding = HDLC_ENCODING_NRZ; break;
1493	case ENCODING_NRZI:       new_encoding = HDLC_ENCODING_NRZI_SPACE; break;
1494	case ENCODING_FM_MARK:    new_encoding = HDLC_ENCODING_BIPHASE_MARK; break;
1495	case ENCODING_FM_SPACE:   new_encoding = HDLC_ENCODING_BIPHASE_SPACE; break;
1496	case ENCODING_MANCHESTER: new_encoding = HDLC_ENCODING_BIPHASE_LEVEL; break;
1497	default: return -EINVAL;
1498	}
1499
1500	switch (parity)
1501	{
1502	case PARITY_NONE:            new_crctype = HDLC_CRC_NONE; break;
1503	case PARITY_CRC16_PR1_CCITT: new_crctype = HDLC_CRC_16_CCITT; break;
1504	case PARITY_CRC32_PR1_CCITT: new_crctype = HDLC_CRC_32_CCITT; break;
1505	default: return -EINVAL;
1506	}
1507
1508	info->params.encoding = new_encoding;
1509	info->params.crc_type = new_crctype;
1510
1511	/* if network interface up, reprogram hardware */
1512	if (info->netcount)
1513		program_hw(info);
1514
1515	return 0;
1516}
1517
1518/**
1519 * called by generic HDLC layer to send frame
1520 *
1521 * skb  socket buffer containing HDLC frame
1522 * dev  pointer to network device structure
1523 *
1524 * returns 0 if success, otherwise error code
1525 */
1526static int hdlcdev_xmit(struct sk_buff *skb, struct net_device *dev)
1527{
1528	struct slgt_info *info = dev_to_port(dev);
1529	struct net_device_stats *stats = hdlc_stats(dev);
1530	unsigned long flags;
1531
1532	DBGINFO(("%s hdlc_xmit\n", dev->name));
1533
1534	/* stop sending until this frame completes */
1535	netif_stop_queue(dev);
1536
1537	/* copy data to device buffers */
1538	info->tx_count = skb->len;
1539	tx_load(info, skb->data, skb->len);
1540
1541	/* update network statistics */
1542	stats->tx_packets++;
1543	stats->tx_bytes += skb->len;
1544
1545	/* done with socket buffer, so free it */
1546	dev_kfree_skb(skb);
1547
1548	/* save start time for transmit timeout detection */
1549	dev->trans_start = jiffies;
1550
1551	/* start hardware transmitter if necessary */
1552	spin_lock_irqsave(&info->lock,flags);
1553	if (!info->tx_active)
1554	 	tx_start(info);
1555	spin_unlock_irqrestore(&info->lock,flags);
1556
1557	return 0;
1558}
1559
1560/**
1561 * called by network layer when interface enabled
1562 * claim resources and initialize hardware
1563 *
1564 * dev  pointer to network device structure
1565 *
1566 * returns 0 if success, otherwise error code
1567 */
1568static int hdlcdev_open(struct net_device *dev)
1569{
1570	struct slgt_info *info = dev_to_port(dev);
1571	int rc;
1572	unsigned long flags;
1573
1574	DBGINFO(("%s hdlcdev_open\n", dev->name));
1575
1576	/* generic HDLC layer open processing */
1577	if ((rc = hdlc_open(dev)))
1578		return rc;
1579
1580	/* arbitrate between network and tty opens */
1581	spin_lock_irqsave(&info->netlock, flags);
1582	if (info->count != 0 || info->netcount != 0) {
1583		DBGINFO(("%s hdlc_open busy\n", dev->name));
1584		spin_unlock_irqrestore(&info->netlock, flags);
1585		return -EBUSY;
1586	}
1587	info->netcount=1;
1588	spin_unlock_irqrestore(&info->netlock, flags);
1589
1590	/* claim resources and init adapter */
1591	if ((rc = startup(info)) != 0) {
1592		spin_lock_irqsave(&info->netlock, flags);
1593		info->netcount=0;
1594		spin_unlock_irqrestore(&info->netlock, flags);
1595		return rc;
1596	}
1597
1598	/* assert DTR and RTS, apply hardware settings */
1599	info->signals |= SerialSignal_RTS + SerialSignal_DTR;
1600	program_hw(info);
1601
1602	/* enable network layer transmit */
1603	dev->trans_start = jiffies;
1604	netif_start_queue(dev);
1605
1606	/* inform generic HDLC layer of current DCD status */
1607	spin_lock_irqsave(&info->lock, flags);
1608	get_signals(info);
1609	spin_unlock_irqrestore(&info->lock, flags);
1610	if (info->signals & SerialSignal_DCD)
1611		netif_carrier_on(dev);
1612	else
1613		netif_carrier_off(dev);
1614	return 0;
1615}
1616
1617/**
1618 * called by network layer when interface is disabled
1619 * shutdown hardware and release resources
1620 *
1621 * dev  pointer to network device structure
1622 *
1623 * returns 0 if success, otherwise error code
1624 */
1625static int hdlcdev_close(struct net_device *dev)
1626{
1627	struct slgt_info *info = dev_to_port(dev);
1628	unsigned long flags;
1629
1630	DBGINFO(("%s hdlcdev_close\n", dev->name));
1631
1632	netif_stop_queue(dev);
1633
1634	/* shutdown adapter and release resources */
1635	shutdown(info);
1636
1637	hdlc_close(dev);
1638
1639	spin_lock_irqsave(&info->netlock, flags);
1640	info->netcount=0;
1641	spin_unlock_irqrestore(&info->netlock, flags);
1642
1643	return 0;
1644}
1645
1646/**
1647 * called by network layer to process IOCTL call to network device
1648 *
1649 * dev  pointer to network device structure
1650 * ifr  pointer to network interface request structure
1651 * cmd  IOCTL command code
1652 *
1653 * returns 0 if success, otherwise error code
1654 */
1655static int hdlcdev_ioctl(struct net_device *dev, struct ifreq *ifr, int cmd)
1656{
1657	const size_t size = sizeof(sync_serial_settings);
1658	sync_serial_settings new_line;
1659	sync_serial_settings __user *line = ifr->ifr_settings.ifs_ifsu.sync;
1660	struct slgt_info *info = dev_to_port(dev);
1661	unsigned int flags;
1662
1663	DBGINFO(("%s hdlcdev_ioctl\n", dev->name));
1664
1665	/* return error if TTY interface open */
1666	if (info->count)
1667		return -EBUSY;
1668
1669	if (cmd != SIOCWANDEV)
1670		return hdlc_ioctl(dev, ifr, cmd);
1671
1672	switch(ifr->ifr_settings.type) {
1673	case IF_GET_IFACE: /* return current sync_serial_settings */
1674
1675		ifr->ifr_settings.type = IF_IFACE_SYNC_SERIAL;
1676		if (ifr->ifr_settings.size < size) {
1677			ifr->ifr_settings.size = size; /* data size wanted */
1678			return -ENOBUFS;
1679		}
1680
1681		flags = info->params.flags & (HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_RXC_DPLL |
1682					      HDLC_FLAG_RXC_BRG    | HDLC_FLAG_RXC_TXCPIN |
1683					      HDLC_FLAG_TXC_TXCPIN | HDLC_FLAG_TXC_DPLL |
1684					      HDLC_FLAG_TXC_BRG    | HDLC_FLAG_TXC_RXCPIN);
1685
1686		switch (flags){
1687		case (HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_TXC_TXCPIN): new_line.clock_type = CLOCK_EXT; break;
1688		case (HDLC_FLAG_RXC_BRG    | HDLC_FLAG_TXC_BRG):    new_line.clock_type = CLOCK_INT; break;
1689		case (HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_TXC_BRG):    new_line.clock_type = CLOCK_TXINT; break;
1690		case (HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_TXC_RXCPIN): new_line.clock_type = CLOCK_TXFROMRX; break;
1691		default: new_line.clock_type = CLOCK_DEFAULT;
1692		}
1693
1694		new_line.clock_rate = info->params.clock_speed;
1695		new_line.loopback   = info->params.loopback ? 1:0;
1696
1697		if (copy_to_user(line, &new_line, size))
1698			return -EFAULT;
1699		return 0;
1700
1701	case IF_IFACE_SYNC_SERIAL: /* set sync_serial_settings */
1702
1703		if(!capable(CAP_NET_ADMIN))
1704			return -EPERM;
1705		if (copy_from_user(&new_line, line, size))
1706			return -EFAULT;
1707
1708		switch (new_line.clock_type)
1709		{
1710		case CLOCK_EXT:      flags = HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_TXC_TXCPIN; break;
1711		case CLOCK_TXFROMRX: flags = HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_TXC_RXCPIN; break;
1712		case CLOCK_INT:      flags = HDLC_FLAG_RXC_BRG    | HDLC_FLAG_TXC_BRG;    break;
1713		case CLOCK_TXINT:    flags = HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_TXC_BRG;    break;
1714		case CLOCK_DEFAULT:  flags = info->params.flags &
1715					     (HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_RXC_DPLL |
1716					      HDLC_FLAG_RXC_BRG    | HDLC_FLAG_RXC_TXCPIN |
1717					      HDLC_FLAG_TXC_TXCPIN | HDLC_FLAG_TXC_DPLL |
1718					      HDLC_FLAG_TXC_BRG    | HDLC_FLAG_TXC_RXCPIN); break;
1719		default: return -EINVAL;
1720		}
1721
1722		if (new_line.loopback != 0 && new_line.loopback != 1)
1723			return -EINVAL;
1724
1725		info->params.flags &= ~(HDLC_FLAG_RXC_RXCPIN | HDLC_FLAG_RXC_DPLL |
1726					HDLC_FLAG_RXC_BRG    | HDLC_FLAG_RXC_TXCPIN |
1727					HDLC_FLAG_TXC_TXCPIN | HDLC_FLAG_TXC_DPLL |
1728					HDLC_FLAG_TXC_BRG    | HDLC_FLAG_TXC_RXCPIN);
1729		info->params.flags |= flags;
1730
1731		info->params.loopback = new_line.loopback;
1732
1733		if (flags & (HDLC_FLAG_RXC_BRG | HDLC_FLAG_TXC_BRG))
1734			info->params.clock_speed = new_line.clock_rate;
1735		else
1736			info->params.clock_speed = 0;
1737
1738		/* if network interface up, reprogram hardware */
1739		if (info->netcount)
1740			program_hw(info);
1741		return 0;
1742
1743	default:
1744		return hdlc_ioctl(dev, ifr, cmd);
1745	}
1746}
1747
1748/**
1749 * called by network layer when transmit timeout is detected
1750 *
1751 * dev  pointer to network device structure
1752 */
1753static void hdlcdev_tx_timeout(struct net_device *dev)
1754{
1755	struct slgt_info *info = dev_to_port(dev);
1756	struct net_device_stats *stats = hdlc_stats(dev);
1757	unsigned long flags;
1758
1759	DBGINFO(("%s hdlcdev_tx_timeout\n", dev->name));
1760
1761	stats->tx_errors++;
1762	stats->tx_aborted_errors++;
1763
1764	spin_lock_irqsave(&info->lock,flags);
1765	tx_stop(info);
1766	spin_unlock_irqrestore(&info->lock,flags);
1767
1768	netif_wake_queue(dev);
1769}
1770
1771/**
1772 * called by device driver when transmit completes
1773 * reenable network layer transmit if stopped
1774 *
1775 * info  pointer to device instance information
1776 */
1777static void hdlcdev_tx_done(struct slgt_info *info)
1778{
1779	if (netif_queue_stopped(info->netdev))
1780		netif_wake_queue(info->netdev);
1781}
1782
1783/**
1784 * called by device driver when frame received
1785 * pass frame to network layer
1786 *
1787 * info  pointer to device instance information
1788 * buf   pointer to buffer contianing frame data
1789 * size  count of data bytes in buf
1790 */
1791static void hdlcdev_rx(struct slgt_info *info, char *buf, int size)
1792{
1793	struct sk_buff *skb = dev_alloc_skb(size);
1794	struct net_device *dev = info->netdev;
1795	struct net_device_stats *stats = hdlc_stats(dev);
1796
1797	DBGINFO(("%s hdlcdev_rx\n", dev->name));
1798
1799	if (skb == NULL) {
1800		DBGERR(("%s: can't alloc skb, drop packet\n", dev->name));
1801		stats->rx_dropped++;
1802		return;
1803	}
1804
1805	memcpy(skb_put(skb, size),buf,size);
1806
1807	skb->protocol = hdlc_type_trans(skb, info->netdev);
1808
1809	stats->rx_packets++;
1810	stats->rx_bytes += size;
1811
1812	netif_rx(skb);
1813
1814	info->netdev->last_rx = jiffies;
1815}
1816
1817/**
1818 * called by device driver when adding device instance
1819 * do generic HDLC initialization
1820 *
1821 * info  pointer to device instance information
1822 *
1823 * returns 0 if success, otherwise error code
1824 */
1825static int hdlcdev_init(struct slgt_info *info)
1826{
1827	int rc;
1828	struct net_device *dev;
1829	hdlc_device *hdlc;
1830
1831	/* allocate and initialize network and HDLC layer objects */
1832
1833	if (!(dev = alloc_hdlcdev(info))) {
1834		printk(KERN_ERR "%s hdlc device alloc failure\n", info->device_name);
1835		return -ENOMEM;
1836	}
1837
1838	/* for network layer reporting purposes only */
1839	dev->mem_start = info->phys_reg_addr;
1840	dev->mem_end   = info->phys_reg_addr + SLGT_REG_SIZE - 1;
1841	dev->irq       = info->irq_level;
1842
1843	/* network layer callbacks and settings */
1844	dev->do_ioctl       = hdlcdev_ioctl;
1845	dev->open           = hdlcdev_open;
1846	dev->stop           = hdlcdev_close;
1847	dev->tx_timeout     = hdlcdev_tx_timeout;
1848	dev->watchdog_timeo = 10*HZ;
1849	dev->tx_queue_len   = 50;
1850
1851	/* generic HDLC layer callbacks and settings */
1852	hdlc         = dev_to_hdlc(dev);
1853	hdlc->attach = hdlcdev_attach;
1854	hdlc->xmit   = hdlcdev_xmit;
1855
1856	/* register objects with HDLC layer */
1857	if ((rc = register_hdlc_device(dev))) {
1858		printk(KERN_WARNING "%s:unable to register hdlc device\n",__FILE__);
1859		free_netdev(dev);
1860		return rc;
1861	}
1862
1863	info->netdev = dev;
1864	return 0;
1865}
1866
1867/**
1868 * called by device driver when removing device instance
1869 * do generic HDLC cleanup
1870 *
1871 * info  pointer to device instance information
1872 */
1873static void hdlcdev_exit(struct slgt_info *info)
1874{
1875	unregister_hdlc_device(info->netdev);
1876	free_netdev(info->netdev);
1877	info->netdev = NULL;
1878}
1879
1880#endif /* ifdef CONFIG_HDLC */
1881
1882/*
1883 * get async data from rx DMA buffers
1884 */
1885static void rx_async(struct slgt_info *info)
1886{
1887 	struct tty_struct *tty = info->tty;
1888 	struct mgsl_icount *icount = &info->icount;
1889	unsigned int start, end;
1890	unsigned char *p;
1891	unsigned char status;
1892	struct slgt_desc *bufs = info->rbufs;
1893	int i, count;
1894	int chars = 0;
1895	int stat;
1896	unsigned char ch;
1897
1898	start = end = info->rbuf_current;
1899
1900	while(desc_complete(bufs[end])) {
1901		count = desc_count(bufs[end]) - info->rbuf_index;
1902		p     = bufs[end].buf + info->rbuf_index;
1903
1904		DBGISR(("%s rx_async count=%d\n", info->device_name, count));
1905		DBGDATA(info, p, count, "rx");
1906
1907		for(i=0 ; i < count; i+=2, p+=2) {
1908			ch = *p;
1909			icount->rx++;
1910
1911			stat = 0;
1912
1913			if ((status = *(p+1) & (BIT1 + BIT0))) {
1914				if (status & BIT1)
1915					icount->parity++;
1916				else if (status & BIT0)
1917					icount->frame++;
1918				/* discard char if tty control flags say so */
1919				if (status & info->ignore_status_mask)
1920					continue;
1921				if (status & BIT1)
1922					stat = TTY_PARITY;
1923				else if (status & BIT0)
1924					stat = TTY_FRAME;
1925			}
1926			if (tty) {
1927				tty_insert_flip_char(tty, ch, stat);
1928				chars++;
1929			}
1930		}
1931
1932		if (i < count) {
1933			/* receive buffer not completed */
1934			info->rbuf_index += i;
1935			mod_timer(&info->rx_timer, jiffies + 1);
1936			break;
1937		}
1938
1939		info->rbuf_index = 0;
1940		free_rbufs(info, end, end);
1941
1942		if (++end == info->rbuf_count)
1943			end = 0;
1944
1945		/* if entire list searched then no frame available */
1946		if (end == start)
1947			break;
1948	}
1949
1950	if (tty && chars)
1951		tty_flip_buffer_push(tty);
1952}
1953
1954/*
1955 * return next bottom half action to perform
1956 */
1957static int bh_action(struct slgt_info *info)
1958{
1959	unsigned long flags;
1960	int rc;
1961
1962	spin_lock_irqsave(&info->lock,flags);
1963
1964	if (info->pending_bh & BH_RECEIVE) {
1965		info->pending_bh &= ~BH_RECEIVE;
1966		rc = BH_RECEIVE;
1967	} else if (info->pending_bh & BH_TRANSMIT) {
1968		info->pending_bh &= ~BH_TRANSMIT;
1969		rc = BH_TRANSMIT;
1970	} else if (info->pending_bh & BH_STATUS) {
1971		info->pending_bh &= ~BH_STATUS;
1972		rc = BH_STATUS;
1973	} else {
1974		/* Mark BH routine as complete */
1975		info->bh_running   = 0;
1976		info->bh_requested = 0;
1977		rc = 0;
1978	}
1979
1980	spin_unlock_irqrestore(&info->lock,flags);
1981
1982	return rc;
1983}
1984
1985/*
1986 * perform bottom half processing
1987 */
1988static void bh_handler(struct work_struct *work)
1989{
1990	struct slgt_info *info = container_of(work, struct slgt_info, task);
1991	int action;
1992
1993	if (!info)
1994		return;
1995	info->bh_running = 1;
1996
1997	while((action = bh_action(info))) {
1998		switch (action) {
1999		case BH_RECEIVE:
2000			DBGBH(("%s bh receive\n", info->device_name));
2001			switch(info->params.mode) {
2002			case MGSL_MODE_ASYNC:
2003				rx_async(info);
2004				break;
2005			case MGSL_MODE_HDLC:
2006				while(rx_get_frame(info));
2007				break;
2008			case MGSL_MODE_RAW:
2009			case MGSL_MODE_MONOSYNC:
2010			case MGSL_MODE_BISYNC:
2011				while(rx_get_buf(info));
2012				break;
2013			}
2014			/* restart receiver if rx DMA buffers exhausted */
2015			if (info->rx_restart)
2016				rx_start(info);
2017			break;
2018		case BH_TRANSMIT:
2019			bh_transmit(info);
2020			break;
2021		case BH_STATUS:
2022			DBGBH(("%s bh status\n", info->device_name));
2023			info->ri_chkcount = 0;
2024			info->dsr_chkcount = 0;
2025			info->dcd_chkcount = 0;
2026			info->cts_chkcount = 0;
2027			break;
2028		default:
2029			DBGBH(("%s unknown action\n", info->device_name));
2030			break;
2031		}
2032	}
2033	DBGBH(("%s bh_handler exit\n", info->device_name));
2034}
2035
2036static void bh_transmit(struct slgt_info *info)
2037{
2038	struct tty_struct *tty = info->tty;
2039
2040	DBGBH(("%s bh_transmit\n", info->device_name));
2041	if (tty)
2042		tty_wakeup(tty);
2043}
2044
2045static void dsr_change(struct slgt_info *info)
2046{
2047	get_signals(info);
2048	DBGISR(("dsr_change %s signals=%04X\n", info->device_name, info->signals));
2049	if ((info->dsr_chkcount)++ == IO_PIN_SHUTDOWN_LIMIT) {
2050		slgt_irq_off(info, IRQ_DSR);
2051		return;
2052	}
2053	info->icount.dsr++;
2054	if (info->signals & SerialSignal_DSR)
2055		info->input_signal_events.dsr_up++;
2056	else
2057		info->input_signal_events.dsr_down++;
2058	wake_up_interruptible(&info->status_event_wait_q);
2059	wake_up_interruptible(&info->event_wait_q);
2060	info->pending_bh |= BH_STATUS;
2061}
2062
2063static void cts_change(struct slgt_info *info)
2064{
2065	get_signals(info);
2066	DBGISR(("cts_change %s signals=%04X\n", info->device_name, info->signals));
2067	if ((info->cts_chkcount)++ == IO_PIN_SHUTDOWN_LIMIT) {
2068		slgt_irq_off(info, IRQ_CTS);
2069		return;
2070	}
2071	info->icount.cts++;
2072	if (info->signals & SerialSignal_CTS)
2073		info->input_signal_events.cts_up++;
2074	else
2075		info->input_signal_events.cts_down++;
2076	wake_up_interruptible(&info->status_event_wait_q);
2077	wake_up_interruptible(&info->event_wait_q);
2078	info->pending_bh |= BH_STATUS;
2079
2080	if (info->flags & ASYNC_CTS_FLOW) {
2081		if (info->tty) {
2082			if (info->tty->hw_stopped) {
2083				if (info->signals & SerialSignal_CTS) {
2084		 			info->tty->hw_stopped = 0;
2085					info->pending_bh |= BH_TRANSMIT;
2086					return;
2087				}
2088			} else {
2089				if (!(info->signals & SerialSignal_CTS))
2090		 			info->tty->hw_stopped = 1;
2091			}
2092		}
2093	}
2094}
2095
2096static void dcd_change(struct slgt_info *info)
2097{
2098	get_signals(info);
2099	DBGISR(("dcd_change %s signals=%04X\n", info->device_name, info->signals));
2100	if ((info->dcd_chkcount)++ == IO_PIN_SHUTDOWN_LIMIT) {
2101		slgt_irq_off(info, IRQ_DCD);
2102		return;
2103	}
2104	info->icount.dcd++;
2105	if (info->signals & SerialSignal_DCD) {
2106		info->input_signal_events.dcd_up++;
2107	} else {
2108		info->input_signal_events.dcd_down++;
2109	}
2110#if SYNCLINK_GENERIC_HDLC
2111	if (info->netcount) {
2112		if (info->signals & SerialSignal_DCD)
2113			netif_carrier_on(info->netdev);
2114		else
2115			netif_carrier_off(info->netdev);
2116	}
2117#endif
2118	wake_up_interruptible(&info->status_event_wait_q);
2119	wake_up_interruptible(&info->event_wait_q);
2120	info->pending_bh |= BH_STATUS;
2121
2122	if (info->flags & ASYNC_CHECK_CD) {
2123		if (info->signals & SerialSignal_DCD)
2124			wake_up_interruptible(&info->open_wait);
2125		else {
2126			if (info->tty)
2127				tty_hangup(info->tty);
2128		}
2129	}
2130}
2131
2132static void ri_change(struct slgt_info *info)
2133{
2134	get_signals(info);
2135	DBGISR(("ri_change %s signals=%04X\n", info->device_name, info->signals));
2136	if ((info->ri_chkcount)++ == IO_PIN_SHUTDOWN_LIMIT) {
2137		slgt_irq_off(info, IRQ_RI);
2138		return;
2139	}
2140	info->icount.dcd++;
2141	if (info->signals & SerialSignal_RI) {
2142		info->input_signal_events.ri_up++;
2143	} else {
2144		info->input_signal_events.ri_down++;
2145	}
2146	wake_up_interruptible(&info->status_event_wait_q);
2147	wake_up_interruptible(&info->event_wait_q);
2148	info->pending_bh |= BH_STATUS;
2149}
2150
2151static void isr_serial(struct slgt_info *info)
2152{
2153	unsigned short status = rd_reg16(info, SSR);
2154
2155	DBGISR(("%s isr_serial status=%04X\n", info->device_name, status));
2156
2157	wr_reg16(info, SSR, status); /* clear pending */
2158
2159	info->irq_occurred = 1;
2160
2161	if (info->params.mode == MGSL_MODE_ASYNC) {
2162		if (status & IRQ_TXIDLE) {
2163			if (info->tx_count)
2164				isr_txeom(info, status);
2165		}
2166		if ((status & IRQ_RXBREAK) && (status & RXBREAK)) {
2167			info->icount.brk++;
2168			/* process break detection if tty control allows */
2169			if (info->tty) {
2170				if (!(status & info->ignore_status_mask)) {
2171					if (info->read_status_mask & MASK_BREAK) {
2172						tty_insert_flip_char(info->tty, 0, TTY_BREAK);
2173						if (info->flags & ASYNC_SAK)
2174							do_SAK(info->tty);
2175					}
2176				}
2177			}
2178		}
2179	} else {
2180		if (status & (IRQ_TXIDLE + IRQ_TXUNDER))
2181			isr_txeom(info, status);
2182
2183		if (status & IRQ_RXIDLE) {
2184			if (status & RXIDLE)
2185				info->icount.rxidle++;
2186			else
2187				info->icount.exithunt++;
2188			wake_up_interruptible(&info->event_wait_q);
2189		}
2190
2191		if (status & IRQ_RXOVER)
2192			rx_start(info);
2193	}
2194
2195	if (status & IRQ_DSR)
2196		dsr_change(info);
2197	if (status & IRQ_CTS)
2198		cts_change(info);
2199	if (status & IRQ_DCD)
2200		dcd_change(info);
2201	if (status & IRQ_RI)
2202		ri_change(info);
2203}
2204
2205static void isr_rdma(struct slgt_info *info)
2206{
2207	unsigned int status = rd_reg32(info, RDCSR);
2208
2209	DBGISR(("%s isr_rdma status=%08x\n", info->device_name, status));
2210
2211	/* RDCSR (rx DMA control/status)
2212	 *
2213	 * 31..07  reserved
2214	 * 06      save status byte to DMA buffer
2215	 * 05      error
2216	 * 04      eol (end of list)
2217	 * 03      eob (end of buffer)
2218	 * 02      IRQ enable
2219	 * 01      reset
2220	 * 00      enable
2221	 */
2222	wr_reg32(info, RDCSR, status);	/* clear pending */
2223
2224	if (status & (BIT5 + BIT4)) {
2225		DBGISR(("%s isr_rdma rx_restart=1\n", info->device_name));
2226		info->rx_restart = 1;
2227	}
2228	info->pending_bh |= BH_RECEIVE;
2229}
2230
2231static void isr_tdma(struct slgt_info *info)
2232{
2233	unsigned int status = rd_reg32(info, TDCSR);
2234
2235	DBGISR(("%s isr_tdma status=%08x\n", info->device_name, status));
2236
2237	/* TDCSR (tx DMA control/status)
2238	 *
2239	 * 31..06  reserved
2240	 * 05      error
2241	 * 04      eol (end of list)
2242	 * 03      eob (end of buffer)
2243	 * 02      IRQ enable
2244	 * 01      reset
2245	 * 00      enable
2246	 */
2247	wr_reg32(info, TDCSR, status);	/* clear pending */
2248
2249	if (status & (BIT5 + BIT4 + BIT3)) {
2250		// another transmit buffer has completed
2251		// run bottom half to get more send data from user
2252		info->pending_bh |= BH_TRANSMIT;
2253	}
2254}
2255
2256static void isr_txeom(struct slgt_info *info, unsigned short status)
2257{
2258	DBGISR(("%s txeom status=%04x\n", info->device_name, status));
2259
2260	slgt_irq_off(info, IRQ_TXDATA + IRQ_TXIDLE + IRQ_TXUNDER);
2261	tdma_reset(info);
2262	reset_tbufs(info);
2263	if (status & IRQ_TXUNDER) {
2264		unsigned short val = rd_reg16(info, TCR);
2265		wr_reg16(info, TCR, (unsigned short)(val | BIT2)); /* set reset bit */
2266		wr_reg16(info, TCR, val); /* clear reset bit */
2267	}
2268
2269	if (info->tx_active) {
2270		if (info->params.mode != MGSL_MODE_ASYNC) {
2271			if (status & IRQ_TXUNDER)
2272				info->icount.txunder++;
2273			else if (status & IRQ_TXIDLE)
2274				info->icount.txok++;
2275		}
2276
2277		info->tx_active = 0;
2278		info->tx_count = 0;
2279
2280		del_timer(&info->tx_timer);
2281
2282		if (info->params.mode != MGSL_MODE_ASYNC && info->drop_rts_on_tx_done) {
2283			info->signals &= ~SerialSignal_RTS;
2284			info->drop_rts_on_tx_done = 0;
2285			set_signals(info);
2286		}
2287
2288#if SYNCLINK_GENERIC_HDLC
2289		if (info->netcount)
2290			hdlcdev_tx_done(info);
2291		else
2292#endif
2293		{
2294			if (info->tty && (info->tty->stopped || info->tty->hw_stopped)) {
2295				tx_stop(info);
2296				return;
2297			}
2298			info->pending_bh |= BH_TRANSMIT;
2299		}
2300	}
2301}
2302
2303static void isr_gpio(struct slgt_info *info, unsigned int changed, unsigned int state)
2304{
2305	struct cond_wait *w, *prev;
2306
2307	/* wake processes waiting for specific transitions */
2308	for (w = info->gpio_wait_q, prev = NULL ; w != NULL ; w = w->next) {
2309		if (w->data & changed) {
2310			w->data = state;
2311			wake_up_interruptible(&w->q);
2312			if (prev != NULL)
2313				prev->next = w->next;
2314			else
2315				info->gpio_wait_q = w->next;
2316		} else
2317			prev = w;
2318	}
2319}
2320
2321/* interrupt service routine
2322 *
2323 * 	irq	interrupt number
2324 * 	dev_id	device ID supplied during interrupt registration
2325 */
2326static irqreturn_t slgt_interrupt(int irq, void *dev_id)
2327{
2328	struct slgt_info *info;
2329	unsigned int gsr;
2330	unsigned int i;
2331
2332	DBGISR(("slgt_interrupt irq=%d entry\n", irq));
2333
2334	info = dev_id;
2335	if (!info)
2336		return IRQ_NONE;
2337
2338	spin_lock(&info->lock);
2339
2340	while((gsr = rd_reg32(info, GSR) & 0xffffff00)) {
2341		DBGISR(("%s gsr=%08x\n", info->device_name, gsr));
2342		info->irq_occurred = 1;
2343		for(i=0; i < info->port_count ; i++) {
2344			if (info->port_array[i] == NULL)
2345				continue;
2346			if (gsr & (BIT8 << i))
2347				isr_serial(info->port_array[i]);
2348			if (gsr & (BIT16 << (i*2)))
2349				isr_rdma(info->port_array[i]);
2350			if (gsr & (BIT17 << (i*2)))
2351				isr_tdma(info->port_array[i]);
2352		}
2353	}
2354
2355	if (info->gpio_present) {
2356		unsigned int state;
2357		unsigned int changed;
2358		while ((changed = rd_reg32(info, IOSR)) != 0) {
2359			DBGISR(("%s iosr=%08x\n", info->device_name, changed));
2360			/* read latched state of GPIO signals */
2361			state = rd_reg32(info, IOVR);
2362			/* clear pending GPIO interrupt bits */
2363			wr_reg32(info, IOSR, changed);
2364			for (i=0 ; i < info->port_count ; i++) {
2365				if (info->port_array[i] != NULL)
2366					isr_gpio(info->port_array[i], changed, state);
2367			}
2368		}
2369	}
2370
2371	for(i=0; i < info->port_count ; i++) {
2372		struct slgt_info *port = info->port_array[i];
2373
2374		if (port && (port->count || port->netcount) &&
2375		    port->pending_bh && !port->bh_running &&
2376		    !port->bh_requested) {
2377			DBGISR(("%s bh queued\n", port->device_name));
2378			schedule_work(&port->task);
2379			port->bh_requested = 1;
2380		}
2381	}
2382
2383	spin_unlock(&info->lock);
2384
2385	DBGISR(("slgt_interrupt irq=%d exit\n", irq));
2386	return IRQ_HANDLED;
2387}
2388
2389static int startup(struct slgt_info *info)
2390{
2391	DBGINFO(("%s startup\n", info->device_name));
2392
2393	if (info->flags & ASYNC_INITIALIZED)
2394		return 0;
2395
2396	if (!info->tx_buf) {
2397		info->tx_buf = kmalloc(info->max_frame_size, GFP_KERNEL);
2398		if (!info->tx_buf) {
2399			DBGERR(("%s can't allocate tx buffer\n", info->device_name));
2400			return -ENOMEM;
2401		}
2402	}
2403
2404	info->pending_bh = 0;
2405
2406	memset(&info->icount, 0, sizeof(info->icount));
2407
2408	/* program hardware for current parameters */
2409	change_params(info);
2410
2411	if (info->tty)
2412		clear_bit(TTY_IO_ERROR, &info->tty->flags);
2413
2414	info->flags |= ASYNC_INITIALIZED;
2415
2416	return 0;
2417}
2418
2419/*
2420 *  called by close() and hangup() to shutdown hardware
2421 */
2422static void shutdown(struct slgt_info *info)
2423{
2424	unsigned long flags;
2425
2426	if (!(info->flags & ASYNC_INITIALIZED))
2427		return;
2428
2429	DBGINFO(("%s shutdown\n", info->device_name));
2430
2431	/* clear status wait queue because status changes */
2432	/* can't happen after shutting down the hardware */
2433	wake_up_interruptible(&info->status_event_wait_q);
2434	wake_up_interruptible(&info->event_wait_q);
2435
2436	del_timer_sync(&info->tx_timer);
2437	del_timer_sync(&info->rx_timer);
2438
2439	kfree(info->tx_buf);
2440	info->tx_buf = NULL;
2441
2442	spin_lock_irqsave(&info->lock,flags);
2443
2444	tx_stop(info);
2445	rx_stop(info);
2446
2447	slgt_irq_off(info, IRQ_ALL | IRQ_MASTER);
2448
2449 	if (!info->tty || info->tty->termios->c_cflag & HUPCL) {
2450 		info->signals &= ~(SerialSignal_DTR + SerialSignal_RTS);
2451		set_signals(info);
2452	}
2453
2454	flush_cond_wait(&info->gpio_wait_q);
2455
2456	spin_unlock_irqrestore(&info->lock,flags);
2457
2458	if (info->tty)
2459		set_bit(TTY_IO_ERROR, &info->tty->flags);
2460
2461	info->flags &= ~ASYNC_INITIALIZED;
2462}
2463
2464static void program_hw(struct slgt_info *info)
2465{
2466	unsigned long flags;
2467
2468	spin_lock_irqsave(&info->lock,flags);
2469
2470	rx_stop(info);
2471	tx_stop(info);
2472
2473	if (info->params.mode != MGSL_MODE_ASYNC ||
2474	    info->netcount)
2475		sync_mode(info);
2476	else
2477		async_mode(info);
2478
2479	set_signals(info);
2480
2481	info->dcd_chkcount = 0;
2482	info->cts_chkcount = 0;
2483	info->ri_chkcount = 0;
2484	info->dsr_chkcount = 0;
2485
2486	slgt_irq_on(info, IRQ_DCD | IRQ_CTS | IRQ_DSR);
2487	get_signals(info);
2488
2489	if (info->netcount ||
2490	    (info->tty && info->tty->termios->c_cflag & CREAD))
2491		rx_start(info);
2492
2493	spin_unlock_irqrestore(&info->lock,flags);
2494}
2495
2496/*
2497 * reconfigure adapter based on new parameters
2498 */
2499static void change_params(struct slgt_info *info)
2500{
2501	unsigned cflag;
2502	int bits_per_char;
2503
2504	if (!info->tty || !info->tty->termios)
2505		return;
2506	DBGINFO(("%s change_params\n", info->device_name));
2507
2508	cflag = info->tty->termios->c_cflag;
2509
2510	/* if B0 rate (hangup) specified then negate DTR and RTS */
2511	/* otherwise assert DTR and RTS */
2512 	if (cflag & CBAUD)
2513		info->signals |= SerialSignal_RTS + SerialSignal_DTR;
2514	else
2515		info->signals &= ~(SerialSignal_RTS + SerialSignal_DTR);
2516
2517	/* byte size and parity */
2518
2519	switch (cflag & CSIZE) {
2520	case CS5: info->params.data_bits = 5; break;
2521	case CS6: info->params.data_bits = 6; break;
2522	case CS7: info->params.data_bits = 7; break;
2523	case CS8: info->params.data_bits = 8; break;
2524	default:  info->params.data_bits = 7; break;
2525	}
2526
2527	info->params.stop_bits = (cflag & CSTOPB) ? 2 : 1;
2528
2529	if (cflag & PARENB)
2530		info->params.parity = (cflag & PARODD) ? ASYNC_PARITY_ODD : ASYNC_PARITY_EVEN;
2531	else
2532		info->params.parity = ASYNC_PARITY_NONE;
2533
2534	/* calculate number of jiffies to transmit a full
2535	 * FIFO (32 bytes) at specified data rate
2536	 */
2537	bits_per_char = info->params.data_bits +
2538			info->params.stop_bits + 1;
2539
2540	info->params.data_rate = tty_get_baud_rate(info->tty);
2541
2542	if (info->params.data_rate) {
2543		info->timeout = (32*HZ*bits_per_char) /
2544				info->params.data_rate;
2545	}
2546	info->timeout += HZ/50;		/* Add .02 seconds of slop */
2547
2548	if (cflag & CRTSCTS)
2549		info->flags |= ASYNC_CTS_FLOW;
2550	else
2551		info->flags &= ~ASYNC_CTS_FLOW;
2552
2553	if (cflag & CLOCAL)
2554		info->flags &= ~ASYNC_CHECK_CD;
2555	else
2556		info->flags |= ASYNC_CHECK_CD;
2557
2558	/* process tty input control flags */
2559
2560	info->read_status_mask = IRQ_RXOVER;
2561	if (I_INPCK(info->tty))
2562		info->read_status_mask |= MASK_PARITY | MASK_FRAMING;
2563 	if (I_BRKINT(info->tty) || I_PARMRK(info->tty))
2564 		info->read_status_mask |= MASK_BREAK;
2565	if (I_IGNPAR(info->tty))
2566		info->ignore_status_mask |= MASK_PARITY | MASK_FRAMING;
2567	if (I_IGNBRK(info->tty)) {
2568		info->ignore_status_mask |= MASK_BREAK;
2569		/* If ignoring parity and break indicators, ignore
2570		 * overruns too.  (For real raw support).
2571		 */
2572		if (I_IGNPAR(info->tty))
2573			info->ignore_status_mask |= MASK_OVERRUN;
2574	}
2575
2576	program_hw(info);
2577}
2578
2579static int get_stats(struct slgt_info *info, struct mgsl_icount __user *user_icount)
2580{
2581	DBGINFO(("%s get_stats\n",  info->device_name));
2582	if (!user_icount) {
2583		memset(&info->icount, 0, sizeof(info->icount));
2584	} else {
2585		if (copy_to_user(user_icount, &info->icount, sizeof(struct mgsl_icount)))
2586			return -EFAULT;
2587	}
2588	return 0;
2589}
2590
2591static int get_params(struct slgt_info *info, MGSL_PARAMS __user *user_params)
2592{
2593	DBGINFO(("%s get_params\n", info->device_name));
2594	if (copy_to_user(user_params, &info->params, sizeof(MGSL_PARAMS)))
2595		return -EFAULT;
2596	return 0;
2597}
2598
2599static int set_params(struct slgt_info *info, MGSL_PARAMS __user *new_params)
2600{
2601 	unsigned long flags;
2602	MGSL_PARAMS tmp_params;
2603
2604	DBGINFO(("%s set_params\n", info->device_name));
2605	if (copy_from_user(&tmp_params, new_params, sizeof(MGSL_PARAMS)))
2606		return -EFAULT;
2607
2608	spin_lock_irqsave(&info->lock, flags);
2609	memcpy(&info->params, &tmp_params, sizeof(MGSL_PARAMS));
2610	spin_unlock_irqrestore(&info->lock, flags);
2611
2612 	change_params(info);
2613
2614	return 0;
2615}
2616
2617static int get_txidle(struct slgt_info *info, int __user *idle_mode)
2618{
2619	DBGINFO(("%s get_txidle=%d\n", info->device_name, info->idle_mode));
2620	if (put_user(info->idle_mode, idle_mode))
2621		return -EFAULT;
2622	return 0;
2623}
2624
2625static int set_txidle(struct slgt_info *info, int idle_mode)
2626{
2627 	unsigned long flags;
2628	DBGINFO(("%s set_txidle(%d)\n", info->device_name, idle_mode));
2629	spin_lock_irqsave(&info->lock,flags);
2630	info->idle_mode = idle_mode;
2631	if (info->params.mode != MGSL_MODE_ASYNC)
2632		tx_set_idle(info);
2633	spin_unlock_irqrestore(&info->lock,flags);
2634	return 0;
2635}
2636
2637static int tx_enable(struct slgt_info *info, int enable)
2638{
2639 	unsigned long flags;
2640	DBGINFO(("%s tx_enable(%d)\n", info->device_name, enable));
2641	spin_lock_irqsave(&info->lock,flags);
2642	if (enable) {
2643		if (!info->tx_enabled)
2644			tx_start(info);
2645	} else {
2646		if (info->tx_enabled)
2647			tx_stop(info);
2648	}
2649	spin_unlock_irqrestore(&info->lock,flags);
2650	return 0;
2651}
2652
2653/*
2654 * abort transmit HDLC frame
2655 */
2656static int tx_abort(struct slgt_info *info)
2657{
2658 	unsigned long flags;
2659	DBGINFO(("%s tx_abort\n", info->device_name));
2660	spin_lock_irqsave(&info->lock,flags);
2661	tdma_reset(info);
2662	spin_unlock_irqrestore(&info->lock,flags);
2663	return 0;
2664}
2665
2666static int rx_enable(struct slgt_info *info, int enable)
2667{
2668 	unsigned long flags;
2669	DBGINFO(("%s rx_enable(%d)\n", info->device_name, enable));
2670	spin_lock_irqsave(&info->lock,flags);
2671	if (enable) {
2672		if (!info->rx_enabled)
2673			rx_start(info);
2674		else if (enable == 2) {
2675			/* force hunt mode (write 1 to RCR[3]) */
2676			wr_reg16(info, RCR, rd_reg16(info, RCR) | BIT3);
2677		}
2678	} else {
2679		if (info->rx_enabled)
2680			rx_stop(info);
2681	}
2682	spin_unlock_irqrestore(&info->lock,flags);
2683	return 0;
2684}
2685
2686/*
2687 *  wait for specified event to occur
2688 */
2689static int wait_mgsl_event(struct slgt_info *info, int __user *mask_ptr)
2690{
2691 	unsigned long flags;
2692	int s;
2693	int rc=0;
2694	struct mgsl_icount cprev, cnow;
2695	int events;
2696	int mask;
2697	struct	_input_signal_events oldsigs, newsigs;
2698	DECLARE_WAITQUEUE(wait, current);
2699
2700	if (get_user(mask, mask_ptr))
2701		return -EFAULT;
2702
2703	DBGINFO(("%s wait_mgsl_event(%d)\n", info->device_name, mask));
2704
2705	spin_lock_irqsave(&info->lock,flags);
2706
2707	/* return immediately if state matches requested events */
2708	get_signals(info);
2709	s = info->signals;
2710
2711	events = mask &
2712		( ((s & SerialSignal_DSR) ? MgslEvent_DsrActive:MgslEvent_DsrInactive) +
2713 		  ((s & SerialSignal_DCD) ? MgslEvent_DcdActive:MgslEvent_DcdInactive) +
2714		  ((s & SerialSignal_CTS) ? MgslEvent_CtsActive:MgslEvent_CtsInactive) +
2715		  ((s & SerialSignal_RI)  ? MgslEvent_RiActive :MgslEvent_RiInactive) );
2716	if (events) {
2717		spin_unlock_irqrestore(&info->lock,flags);
2718		goto exit;
2719	}
2720
2721	/* save current irq counts */
2722	cprev = info->icount;
2723	oldsigs = info->input_signal_events;
2724
2725	/* enable hunt and idle irqs if needed */
2726	if (mask & (MgslEvent_ExitHuntMode+MgslEvent_IdleReceived)) {
2727		unsigned short val = rd_reg16(info, SCR);
2728		if (!(val & IRQ_RXIDLE))
2729			wr_reg16(info, SCR, (unsigned short)(val | IRQ_RXIDLE));
2730	}
2731
2732	set_current_state(TASK_INTERRUPTIBLE);
2733	add_wait_queue(&info->event_wait_q, &wait);
2734
2735	spin_unlock_irqrestore(&info->lock,flags);
2736
2737	for(;;) {
2738		schedule();
2739		if (signal_pending(current)) {
2740			rc = -ERESTARTSYS;
2741			break;
2742		}
2743
2744		/* get current irq counts */
2745		spin_lock_irqsave(&info->lock,flags);
2746		cnow = info->icount;
2747		newsigs = info->input_signal_events;
2748		set_current_state(TASK_INTERRUPTIBLE);
2749		spin_unlock_irqrestore(&info->lock,flags);
2750
2751		/* if no change, wait aborted for some reason */
2752		if (newsigs.dsr_up   == oldsigs.dsr_up   &&
2753		    newsigs.dsr_down == oldsigs.dsr_down &&
2754		    newsigs.dcd_up   == oldsigs.dcd_up   &&
2755		    newsigs.dcd_down == oldsigs.dcd_down &&
2756		    newsigs.cts_up   == oldsigs.cts_up   &&
2757		    newsigs.cts_down == oldsigs.cts_down &&
2758		    newsigs.ri_up    == oldsigs.ri_up    &&
2759		    newsigs.ri_down  == oldsigs.ri_down  &&
2760		    cnow.exithunt    == cprev.exithunt   &&
2761		    cnow.rxidle      == cprev.rxidle) {
2762			rc = -EIO;
2763			break;
2764		}
2765
2766		events = mask &
2767			( (newsigs.dsr_up   != oldsigs.dsr_up   ? MgslEvent_DsrActive:0)   +
2768			  (newsigs.dsr_down != oldsigs.dsr_down ? MgslEvent_DsrInactive:0) +
2769			  (newsigs.dcd_up   != oldsigs.dcd_up   ? MgslEvent_DcdActive:0)   +
2770			  (newsigs.dcd_down != oldsigs.dcd_down ? MgslEvent_DcdInactive:0) +
2771			  (newsigs.cts_up   != oldsigs.cts_up   ? MgslEvent_CtsActive:0)   +
2772			  (newsigs.cts_down != oldsigs.cts_down ? MgslEvent_CtsInactive:0) +
2773			  (newsigs.ri_up    != oldsigs.ri_up    ? MgslEvent_RiActive:0)    +
2774			  (newsigs.ri_down  != oldsigs.ri_down  ? MgslEvent_RiInactive:0)  +
2775			  (cnow.exithunt    != cprev.exithunt   ? MgslEvent_ExitHuntMode:0) +
2776			  (cnow.rxidle      != cprev.rxidle     ? MgslEvent_IdleReceived:0) );
2777		if (events)
2778			break;
2779
2780		cprev = cnow;
2781		oldsigs = newsigs;
2782	}
2783
2784	remove_wait_queue(&info->event_wait_q, &wait);
2785	set_current_state(TASK_RUNNING);
2786
2787
2788	if (mask & (MgslEvent_ExitHuntMode + MgslEvent_IdleReceived)) {
2789		spin_lock_irqsave(&info->lock,flags);
2790		if (!waitqueue_active(&info->event_wait_q)) {
2791			/* disable enable exit hunt mode/idle rcvd IRQs */
2792			wr_reg16(info, SCR,
2793				(unsigned short)(rd_reg16(info, SCR) & ~IRQ_RXIDLE));
2794		}
2795		spin_unlock_irqrestore(&info->lock,flags);
2796	}
2797exit:
2798	if (rc == 0)
2799		rc = put_user(events, mask_ptr);
2800	return rc;
2801}
2802
2803static int get_interface(struct slgt_info *info, int __user *if_mode)
2804{
2805	DBGINFO(("%s get_interface=%x\n", info->device_name, info->if_mode));
2806	if (put_user(info->if_mode, if_mode))
2807		return -EFAULT;
2808	return 0;
2809}
2810
2811static int set_interface(struct slgt_info *info, int if_mode)
2812{
2813 	unsigned long flags;
2814	unsigned short val;
2815
2816	DBGINFO(("%s set_interface=%x)\n", info->device_name, if_mode));
2817	spin_lock_irqsave(&info->lock,flags);
2818	info->if_mode = if_mode;
2819
2820	msc_set_vcr(info);
2821
2822	/* TCR (tx control) 07  1=RTS driver control */
2823	val = rd_reg16(info, TCR);
2824	if (info->if_mode & MGSL_INTERFACE_RTS_EN)
2825		val |= BIT7;
2826	else
2827		val &= ~BIT7;
2828	wr_reg16(info, TCR, val);
2829
2830	spin_unlock_irqrestore(&info->lock,flags);
2831	return 0;
2832}
2833
2834/*
2835 * set general purpose IO pin state and direction
2836 *
2837 * user_gpio fields:
2838 * state   each bit indicates a pin state
2839 * smask   set bit indicates pin state to set
2840 * dir     each bit indicates a pin direction (0=input, 1=output)
2841 * dmask   set bit indicates pin direction to set
2842 */
2843static int set_gpio(struct slgt_info *info, struct gpio_desc __user *user_gpio)
2844{
2845 	unsigned long flags;
2846	struct gpio_desc gpio;
2847	__u32 data;
2848
2849	if (!info->gpio_present)
2850		return -EINVAL;
2851	if (copy_from_user(&gpio, user_gpio, sizeof(gpio)))
2852		return -EFAULT;
2853	DBGINFO(("%s set_gpio state=%08x smask=%08x dir=%08x dmask=%08x\n",
2854		 info->device_name, gpio.state, gpio.smask,
2855		 gpio.dir, gpio.dmask));
2856
2857	spin_lock_irqsave(&info->lock,flags);
2858	if (gpio.dmask) {
2859		data = rd_reg32(info, IODR);
2860		data |= gpio.dmask & gpio.dir;
2861		data &= ~(gpio.dmask & ~gpio.dir);
2862		wr_reg32(info, IODR, data);
2863	}
2864	if (gpio.smask) {
2865		data = rd_reg32(info, IOVR);
2866		data |= gpio.smask & gpio.state;
2867		data &= ~(gpio.smask & ~gpio.state);
2868		wr_reg32(info, IOVR, data);
2869	}
2870	spin_unlock_irqrestore(&info->lock,flags);
2871
2872	return 0;
2873}
2874
2875/*
2876 * get general purpose IO pin state and direction
2877 */
2878static int get_gpio(struct slgt_info *info, struct gpio_desc __user *user_gpio)
2879{
2880	struct gpio_desc gpio;
2881	if (!info->gpio_present)
2882		return -EINVAL;
2883	gpio.state = rd_reg32(info, IOVR);
2884	gpio.smask = 0xffffffff;
2885	gpio.dir   = rd_reg32(info, IODR);
2886	gpio.dmask = 0xffffffff;
2887	if (copy_to_user(user_gpio, &gpio, sizeof(gpio)))
2888		return -EFAULT;
2889	DBGINFO(("%s get_gpio state=%08x dir=%08x\n",
2890		 info->device_name, gpio.state, gpio.dir));
2891	return 0;
2892}
2893
2894/*
2895 * conditional wait facility
2896 */
2897static void init_cond_wait(struct cond_wait *w, unsigned int data)
2898{
2899	init_waitqueue_head(&w->q);
2900	init_waitqueue_entry(&w->wait, current);
2901	w->data = data;
2902}
2903
2904static void add_cond_wait(struct cond_wait **head, struct cond_wait *w)
2905{
2906	set_current_state(TASK_INTERRUPTIBLE);
2907	add_wait_queue(&w->q, &w->wait);
2908	w->next = *head;
2909	*head = w;
2910}
2911
2912static void remove_cond_wait(struct cond_wait **head, struct cond_wait *cw)
2913{
2914	struct cond_wait *w, *prev;
2915	remove_wait_queue(&cw->q, &cw->wait);
2916	set_current_state(TASK_RUNNING);
2917	for (w = *head, prev = NULL ; w != NULL ; prev = w, w = w->next) {
2918		if (w == cw) {
2919			if (prev != NULL)
2920				prev->next = w->next;
2921			else
2922				*head = w->next;
2923			break;
2924		}
2925	}
2926}
2927
2928static void flush_cond_wait(struct cond_wait **head)
2929{
2930	while (*head != NULL) {
2931		wake_up_interruptible(&(*head)->q);
2932		*head = (*head)->next;
2933	}
2934}
2935
2936/*
2937 * wait for general purpose I/O pin(s) to enter specified state
2938 *
2939 * user_gpio fields:
2940 * state - bit indicates target pin state
2941 * smask - set bit indicates watched pin
2942 *
2943 * The wait ends when at least one watched pin enters the specified
2944 * state. When 0 (no error) is returned, user_gpio->state is set to the
2945 * state of all GPIO pins when the wait ends.
2946 *
2947 * Note: Each pin may be a dedicated input, dedicated output, or
2948 * configurable input/output. The number and configuration of pins
2949 * varies with the specific adapter model. Only input pins (dedicated
2950 * or configured) can be monitored with this function.
2951 */
2952static int wait_gpio(struct slgt_info *info, struct gpio_desc __user *user_gpio)
2953{
2954 	unsigned long flags;
2955	int rc = 0;
2956	struct gpio_desc gpio;
2957	struct cond_wait wait;
2958	u32 state;
2959
2960	if (!info->gpio_present)
2961		return -EINVAL;
2962	if (copy_from_user(&gpio, user_gpio, sizeof(gpio)))
2963		return -EFAULT;
2964	DBGINFO(("%s wait_gpio() state=%08x smask=%08x\n",
2965		 info->device_name, gpio.state, gpio.smask));
2966	/* ignore output pins identified by set IODR bit */
2967	if ((gpio.smask &= ~rd_reg32(info, IODR)) == 0)
2968		return -EINVAL;
2969	init_cond_wait(&wait, gpio.smask);
2970
2971	spin_lock_irqsave(&info->lock, flags);
2972	/* enable interrupts for watched pins */
2973	wr_reg32(info, IOER, rd_reg32(info, IOER) | gpio.smask);
2974	/* get current pin states */
2975	state = rd_reg32(info, IOVR);
2976
2977	if (gpio.smask & ~(state ^ gpio.state)) {
2978		/* already in target state */
2979		gpio.state = state;
2980	} else {
2981		/* wait for target state */
2982		add_cond_wait(&info->gpio_wait_q, &wait);
2983		spin_unlock_irqrestore(&info->lock, flags);
2984		schedule();
2985		if (signal_pending(current))
2986			rc = -ERESTARTSYS;
2987		else
2988			gpio.state = wait.data;
2989		spin_lock_irqsave(&info->lock, flags);
2990		remove_cond_wait(&info->gpio_wait_q, &wait);
2991	}
2992
2993	/* disable all GPIO interrupts if no waiting processes */
2994	if (info->gpio_wait_q == NULL)
2995		wr_reg32(info, IOER, 0);
2996	spin_unlock_irqrestore(&info->lock,flags);
2997
2998	if ((rc == 0) && copy_to_user(user_gpio, &gpio, sizeof(gpio)))
2999		rc = -EFAULT;
3000	return rc;
3001}
3002
3003static int modem_input_wait(struct slgt_info *info,int arg)
3004{
3005 	unsigned long flags;
3006	int rc;
3007	struct mgsl_icount cprev, cnow;
3008	DECLARE_WAITQUEUE(wait, current);
3009
3010	/* save current irq counts */
3011	spin_lock_irqsave(&info->lock,flags);
3012	cprev = info->icount;
3013	add_wait_queue(&info->status_event_wait_q, &wait);
3014	set_current_state(TASK_INTERRUPTIBLE);
3015	spin_unlock_irqrestore(&info->lock,flags);
3016
3017	for(;;) {
3018		schedule();
3019		if (signal_pending(current)) {
3020			rc = -ERESTARTSYS;
3021			break;
3022		}
3023
3024		/* get new irq counts */
3025		spin_lock_irqsave(&info->lock,flags);
3026		cnow = info->icount;
3027		set_current_state(TASK_INTERRUPTIBLE);
3028		spin_unlock_irqrestore(&info->lock,flags);
3029
3030		/* if no change, wait aborted for some reason */
3031		if (cnow.rng == cprev.rng && cnow.dsr == cprev.dsr &&
3032		    cnow.dcd == cprev.dcd && cnow.cts == cprev.cts) {
3033			rc = -EIO;
3034			break;
3035		}
3036
3037		/* check for change in caller specified modem input */
3038		if ((arg & TIOCM_RNG && cnow.rng != cprev.rng) ||
3039		    (arg & TIOCM_DSR && cnow.dsr != cprev.dsr) ||
3040		    (arg & TIOCM_CD  && cnow.dcd != cprev.dcd) ||
3041		    (arg & TIOCM_CTS && cnow.cts != cprev.cts)) {
3042			rc = 0;
3043			break;
3044		}
3045
3046		cprev = cnow;
3047	}
3048	remove_wait_queue(&info->status_event_wait_q, &wait);
3049	set_current_state(TASK_RUNNING);
3050	return rc;
3051}
3052
3053/*
3054 *  return state of serial control and status signals
3055 */
3056static int tiocmget(struct tty_struct *tty, struct file *file)
3057{
3058	struct slgt_info *info = tty->driver_data;
3059	unsigned int result;
3060 	unsigned long flags;
3061
3062	spin_lock_irqsave(&info->lock,flags);
3063 	get_signals(info);
3064	spin_unlock_irqrestore(&info->lock,flags);
3065
3066	result = ((info->signals & SerialSignal_RTS) ? TIOCM_RTS:0) +
3067		((info->signals & SerialSignal_DTR) ? TIOCM_DTR:0) +
3068		((info->signals & SerialSignal_DCD) ? TIOCM_CAR:0) +
3069		((info->signals & SerialSignal_RI)  ? TIOCM_RNG:0) +
3070		((info->signals & SerialSignal_DSR) ? TIOCM_DSR:0) +
3071		((info->signals & SerialSignal_CTS) ? TIOCM_CTS:0);
3072
3073	DBGINFO(("%s tiocmget value=%08X\n", info->device_name, result));
3074	return result;
3075}
3076
3077/*
3078 * set modem control signals (DTR/RTS)
3079 *
3080 * 	cmd	signal command: TIOCMBIS = set bit TIOCMBIC = clear bit
3081 *		TIOCMSET = set/clear signal values
3082 * 	value	bit mask for command
3083 */
3084static int tiocmset(struct tty_struct *tty, struct file *file,
3085		    unsigned int set, unsigned int clear)
3086{
3087	struct slgt_info *info = tty->driver_data;
3088 	unsigned long flags;
3089
3090	DBGINFO(("%s tiocmset(%x,%x)\n", info->device_name, set, clear));
3091
3092	if (set & TIOCM_RTS)
3093		info->signals |= SerialSignal_RTS;
3094	if (set & TIOCM_DTR)
3095		info->signals |= SerialSignal_DTR;
3096	if (clear & TIOCM_RTS)
3097		info->signals &= ~SerialSignal_RTS;
3098	if (clear & TIOCM_DTR)
3099		info->signals &= ~SerialSignal_DTR;
3100
3101	spin_lock_irqsave(&info->lock,flags);
3102 	set_signals(info);
3103	spin_unlock_irqrestore(&info->lock,flags);
3104	return 0;
3105}
3106
3107/*
3108 *  block current process until the device is ready to open
3109 */
3110static int block_til_ready(struct tty_struct *tty, struct file *filp,
3111			   struct slgt_info *info)
3112{
3113	DECLARE_WAITQUEUE(wait, current);
3114	int		retval;
3115	int		do_clocal = 0, extra_count = 0;
3116	unsigned long	flags;
3117
3118	DBGINFO(("%s block_til_ready\n", tty->driver->name));
3119
3120	if (filp->f_flags & O_NONBLOCK || tty->flags & (1 << TTY_IO_ERROR)){
3121		/* nonblock mode is set or port is not enabled */
3122		info->flags |= ASYNC_NORMAL_ACTIVE;
3123		return 0;
3124	}
3125
3126	if (tty->termios->c_cflag & CLOCAL)
3127		do_clocal = 1;
3128
3129	/* Wait for carrier detect and the line to become
3130	 * free (i.e., not in use by the callout).  While we are in
3131	 * this loop, info->count is dropped by one, so that
3132	 * close() knows when to free things.  We restore it upon
3133	 * exit, either normal or abnormal.
3134	 */
3135
3136	retval = 0;
3137	add_wait_queue(&info->open_wait, &wait);
3138
3139	spin_lock_irqsave(&info->lock, flags);
3140	if (!tty_hung_up_p(filp)) {
3141		extra_count = 1;
3142		info->count--;
3143	}
3144	spin_unlock_irqrestore(&info->lock, flags);
3145	info->blocked_open++;
3146
3147	while (1) {
3148		if ((tty->termios->c_cflag & CBAUD)) {
3149			spin_lock_irqsave(&info->lock,flags);
3150			info->signals |= SerialSignal_RTS + SerialSignal_DTR;
3151		 	set_signals(info);
3152			spin_unlock_irqrestore(&info->lock,flags);
3153		}
3154
3155		set_current_state(TASK_INTERRUPTIBLE);
3156
3157		if (tty_hung_up_p(filp) || !(info->flags & ASYNC_INITIALIZED)){
3158			retval = (info->flags & ASYNC_HUP_NOTIFY) ?
3159					-EAGAIN : -ERESTARTSYS;
3160			break;
3161		}
3162
3163		spin_lock_irqsave(&info->lock,flags);
3164	 	get_signals(info);
3165		spin_unlock_irqrestore(&info->lock,flags);
3166
3167 		if (!(info->flags & ASYNC_CLOSING) &&
3168 		    (do_clocal || (info->signals & SerialSignal_DCD)) ) {
3169 			break;
3170		}
3171
3172		if (signal_pending(current)) {
3173			retval = -ERESTARTSYS;
3174			break;
3175		}
3176
3177		DBGINFO(("%s block_til_ready wait\n", tty->driver->name));
3178		schedule();
3179	}
3180
3181	set_current_state(TASK_RUNNING);
3182	remove_wait_queue(&info->open_wait, &wait);
3183
3184	if (extra_count)
3185		info->count++;
3186	info->blocked_open--;
3187
3188	if (!retval)
3189		info->flags |= ASYNC_NORMAL_ACTIVE;
3190
3191	DBGINFO(("%s block_til_ready ready, rc=%d\n", tty->driver->name, retval));
3192	return retval;
3193}
3194
3195static int alloc_tmp_rbuf(struct slgt_info *info)
3196{
3197	info->tmp_rbuf = kmalloc(info->max_frame_size + 5, GFP_KERNEL);
3198	if (info->tmp_rbuf == NULL)
3199		return -ENOMEM;
3200	return 0;
3201}
3202
3203static void free_tmp_rbuf(struct slgt_info *info)
3204{
3205	kfree(info->tmp_rbuf);
3206	info->tmp_rbuf = NULL;
3207}
3208
3209/*
3210 * allocate DMA descriptor lists.
3211 */
3212static int alloc_desc(struct slgt_info *info)
3213{
3214	unsigned int i;
3215	unsigned int pbufs;
3216
3217	/* allocate memory to hold descriptor lists */
3218	info->bufs = pci_alloc_consistent(info->pdev, DESC_LIST_SIZE, &info->bufs_dma_addr);
3219	if (info->bufs == NULL)
3220		return -ENOMEM;
3221
3222	memset(info->bufs, 0, DESC_LIST_SIZE);
3223
3224	info->rbufs = (struct slgt_desc*)info->bufs;
3225	info->tbufs = ((struct slgt_desc*)info->bufs) + info->rbuf_count;
3226
3227	pbufs = (unsigned int)info->bufs_dma_addr;
3228
3229	/*
3230	 * Build circular lists of descriptors
3231	 */
3232
3233	for (i=0; i < info->rbuf_count; i++) {
3234		/* physical address of this descriptor */
3235		info->rbufs[i].pdesc = pbufs + (i * sizeof(struct slgt_desc));
3236
3237		/* physical address of next descriptor */
3238		if (i == info->rbuf_count - 1)
3239			info->rbufs[i].next = cpu_to_le32(pbufs);
3240		else
3241			info->rbufs[i].next = cpu_to_le32(pbufs + ((i+1) * sizeof(struct slgt_desc)));
3242		set_desc_count(info->rbufs[i], DMABUFSIZE);
3243	}
3244
3245	for (i=0; i < info->tbuf_count; i++) {
3246		/* physical address of this descriptor */
3247		info->tbufs[i].pdesc = pbufs + ((info->rbuf_count + i) * sizeof(struct slgt_desc));
3248
3249		/* physical address of next descriptor */
3250		if (i == info->tbuf_count - 1)
3251			info->tbufs[i].next = cpu_to_le32(pbufs + info->rbuf_count * sizeof(struct slgt_desc));
3252		else
3253			info->tbufs[i].next = cpu_to_le32(pbufs + ((info->rbuf_count + i + 1) * sizeof(struct slgt_desc)));
3254	}
3255
3256	return 0;
3257}
3258
3259static void free_desc(struct slgt_info *info)
3260{
3261	if (info->bufs != NULL) {
3262		pci_free_consistent(info->pdev, DESC_LIST_SIZE, info->bufs, info->bufs_dma_addr);
3263		info->bufs  = NULL;
3264		info->rbufs = NULL;
3265		info->tbufs = NULL;
3266	}
3267}
3268
3269static int alloc_bufs(struct slgt_info *info, struct slgt_desc *bufs, int count)
3270{
3271	int i;
3272	for (i=0; i < count; i++) {
3273		if ((bufs[i].buf = pci_alloc_consistent(info->pdev, DMABUFSIZE, &bufs[i].buf_dma_addr)) == NULL)
3274			return -ENOMEM;
3275		bufs[i].pbuf  = cpu_to_le32((unsigned int)bufs[i].buf_dma_addr);
3276	}
3277	return 0;
3278}
3279
3280static void free_bufs(struct slgt_info *info, struct slgt_desc *bufs, int count)
3281{
3282	int i;
3283	for (i=0; i < count; i++) {
3284		if (bufs[i].buf == NULL)
3285			continue;
3286		pci_free_consistent(info->pdev, DMABUFSIZE, bufs[i].buf, bufs[i].buf_dma_addr);
3287		bufs[i].buf = NULL;
3288	}
3289}
3290
3291static int alloc_dma_bufs(struct slgt_info *info)
3292{
3293	info->rbuf_count = 32;
3294	info->tbuf_count = 32;
3295
3296	if (alloc_desc(info) < 0 ||
3297	    alloc_bufs(info, info->rbufs, info->rbuf_count) < 0 ||
3298	    alloc_bufs(info, info->tbufs, info->tbuf_count) < 0 ||
3299	    alloc_tmp_rbuf(info) < 0) {
3300		DBGERR(("%s DMA buffer alloc fail\n", info->device_name));
3301		return -ENOMEM;
3302	}
3303	reset_rbufs(info);
3304	return 0;
3305}
3306
3307static void free_dma_bufs(struct slgt_info *info)
3308{
3309	if (info->bufs) {
3310		free_bufs(info, info->rbufs, info->rbuf_count);
3311		free_bufs(info, info->tbufs, info->tbuf_count);
3312		free_desc(info);
3313	}
3314	free_tmp_rbuf(info);
3315}
3316
3317static int claim_resources(struct slgt_info *info)
3318{
3319	if (request_mem_region(info->phys_reg_addr, SLGT_REG_SIZE, "synclink_gt") == NULL) {
3320		DBGERR(("%s reg addr conflict, addr=%08X\n",
3321			info->device_name, info->phys_reg_addr));
3322		info->init_error = DiagStatus_AddressConflict;
3323		goto errout;
3324	}
3325	else
3326		info->reg_addr_requested = 1;
3327
3328	info->reg_addr = ioremap(info->phys_reg_addr, SLGT_REG_SIZE);
3329	if (!info->reg_addr) {
3330		DBGERR(("%s cant map device registers, addr=%08X\n",
3331			info->device_name, info->phys_reg_addr));
3332		info->init_error = DiagStatus_CantAssignPciResources;
3333		goto errout;
3334	}
3335	return 0;
3336
3337errout:
3338	release_resources(info);
3339	return -ENODEV;
3340}
3341
3342static void release_resources(struct slgt_info *info)
3343{
3344	if (info->irq_requested) {
3345		free_irq(info->irq_level, info);
3346		info->irq_requested = 0;
3347	}
3348
3349	if (info->reg_addr_requested) {
3350		release_mem_region(info->phys_reg_addr, SLGT_REG_SIZE);
3351		info->reg_addr_requested = 0;
3352	}
3353
3354	if (info->reg_addr) {
3355		iounmap(info->reg_addr);
3356		info->reg_addr = NULL;
3357	}
3358}
3359
3360/* Add the specified device instance data structure to the
3361 * global linked list of devices and increment the device count.
3362 */
3363static void add_device(struct slgt_info *info)
3364{
3365	char *devstr;
3366
3367	info->next_device = NULL;
3368	info->line = slgt_device_count;
3369	sprintf(info->device_name, "%s%d", tty_dev_prefix, info->line);
3370
3371	if (info->line < MAX_DEVICES) {
3372		if (maxframe[info->line])
3373			info->max_frame_size = maxframe[info->line];
3374		info->dosyncppp = dosyncppp[info->line];
3375	}
3376
3377	slgt_device_count++;
3378
3379	if (!slgt_device_list)
3380		slgt_device_list = info;
3381	else {
3382		struct slgt_info *current_dev = slgt_device_list;
3383		while(current_dev->next_device)
3384			current_dev = current_dev->next_device;
3385		current_dev->next_device = info;
3386	}
3387
3388	if (info->max_frame_size < 4096)
3389		info->max_frame_size = 4096;
3390	else if (info->max_frame_size > 65535)
3391		info->max_frame_size = 65535;
3392
3393	switch(info->pdev->device) {
3394	case SYNCLINK_GT_DEVICE_ID:
3395		devstr = "GT";
3396		break;
3397	case SYNCLINK_GT2_DEVICE_ID:
3398		devstr = "GT2";
3399		break;
3400	case SYNCLINK_GT4_DEVICE_ID:
3401		devstr = "GT4";
3402		break;
3403	case SYNCLINK_AC_DEVICE_ID:
3404		devstr = "AC";
3405		info->params.mode = MGSL_MODE_ASYNC;
3406		break;
3407	default:
3408		devstr = "(unknown model)";
3409	}
3410	printk("SyncLink %s %s IO=%08x IRQ=%d MaxFrameSize=%u\n",
3411		devstr, info->device_name, info->phys_reg_addr,
3412		info->irq_level, info->max_frame_size);
3413
3414#if SYNCLINK_GENERIC_HDLC
3415	hdlcdev_init(info);
3416#endif
3417}
3418
3419/*
3420 *  allocate device instance structure, return NULL on failure
3421 */
3422static struct slgt_info *alloc_dev(int adapter_num, int port_num, struct pci_dev *pdev)
3423{
3424	struct slgt_info *info;
3425
3426	info = kmalloc(sizeof(struct slgt_info), GFP_KERNEL);
3427
3428	if (!info) {
3429		DBGERR(("%s device alloc failed adapter=%d port=%d\n",
3430			driver_name, adapter_num, port_num));
3431	} else {
3432		memset(info, 0, sizeof(struct slgt_info));
3433		info->magic = MGSL_MAGIC;
3434		INIT_WORK(&info->task, bh_handler);
3435		info->max_frame_size = 4096;
3436		info->raw_rx_size = DMABUFSIZE;
3437		info->close_delay = 5*HZ/10;
3438		info->closing_wait = 30*HZ;
3439		init_waitqueue_head(&info->open_wait);
3440		init_waitqueue_head(&info->close_wait);
3441		init_waitqueue_head(&info->status_event_wait_q);
3442		init_waitqueue_head(&info->event_wait_q);
3443		spin_lock_init(&info->netlock);
3444		memcpy(&info->params,&default_params,sizeof(MGSL_PARAMS));
3445		info->idle_mode = HDLC_TXIDLE_FLAGS;
3446		info->adapter_num = adapter_num;
3447		info->port_num = port_num;
3448
3449		setup_timer(&info->tx_timer, tx_timeout, (unsigned long)info);
3450		setup_timer(&info->rx_timer, rx_timeout, (unsigned long)info);
3451
3452		/* Copy configuration info to device instance data */
3453		info->pdev = pdev;
3454		info->irq_level = pdev->irq;
3455		info->phys_reg_addr = pci_resource_start(pdev,0);
3456
3457		info->bus_type = MGSL_BUS_TYPE_PCI;
3458		info->irq_flags = IRQF_SHARED;
3459
3460		info->init_error = -1; /* assume error, set to 0 on successful init */
3461	}
3462
3463	return info;
3464}
3465
3466static void device_init(int adapter_num, struct pci_dev *pdev)
3467{
3468	struct slgt_info *port_array[SLGT_MAX_PORTS];
3469	int i;
3470	int port_count = 1;
3471
3472	if (pdev->device == SYNCLINK_GT2_DEVICE_ID)
3473		port_count = 2;
3474	else if (pdev->device == SYNCLINK_GT4_DEVICE_ID)
3475		port_count = 4;
3476
3477	/* allocate device instances for all ports */
3478	for (i=0; i < port_count; ++i) {
3479		port_array[i] = alloc_dev(adapter_num, i, pdev);
3480		if (port_array[i] == NULL) {
3481			for (--i; i >= 0; --i)
3482				kfree(port_array[i]);
3483			return;
3484		}
3485	}
3486
3487	/* give copy of port_array to all ports and add to device list  */
3488	for (i=0; i < port_count; ++i) {
3489		memcpy(port_array[i]->port_array, port_array, sizeof(port_array));
3490		add_device(port_array[i]);
3491		port_array[i]->port_count = port_count;
3492		spin_lock_init(&port_array[i]->lock);
3493	}
3494
3495	/* Allocate and claim adapter resources */
3496	if (!claim_resources(port_array[0])) {
3497
3498		alloc_dma_bufs(port_array[0]);
3499
3500		/* copy resource information from first port to others */
3501		for (i = 1; i < port_count; ++i) {
3502			port_array[i]->lock      = port_array[0]->lock;
3503			port_array[i]->irq_level = port_array[0]->irq_level;
3504			port_array[i]->reg_addr  = port_array[0]->reg_addr;
3505			alloc_dma_bufs(port_array[i]);
3506		}
3507
3508		if (request_irq(port_array[0]->irq_level,
3509					slgt_interrupt,
3510					port_array[0]->irq_flags,
3511					port_array[0]->device_name,
3512					port_array[0]) < 0) {
3513			DBGERR(("%s request_irq failed IRQ=%d\n",
3514				port_array[0]->device_name,
3515				port_array[0]->irq_level));
3516		} else {
3517			port_array[0]->irq_requested = 1;
3518			adapter_test(port_array[0]);
3519			for (i=1 ; i < port_count ; i++) {
3520				port_array[i]->init_error = port_array[0]->init_error;
3521				port_array[i]->gpio_present = port_array[0]->gpio_present;
3522			}
3523		}
3524	}
3525
3526	for (i=0; i < port_count; ++i)
3527		tty_register_device(serial_driver, port_array[i]->line, &(port_array[i]->pdev->dev));
3528}
3529
3530static int __devinit init_one(struct pci_dev *dev,
3531			      const struct pci_device_id *ent)
3532{
3533	if (pci_enable_device(dev)) {
3534		printk("error enabling pci device %p\n", dev);
3535		return -EIO;
3536	}
3537	pci_set_master(dev);
3538	device_init(slgt_device_count, dev);
3539	return 0;
3540}
3541
3542static void __devexit remove_one(struct pci_dev *dev)
3543{
3544}
3545
3546static const struct tty_operations ops = {
3547	.open = open,
3548	.close = close,
3549	.write = write,
3550	.put_char = put_char,
3551	.flush_chars = flush_chars,
3552	.write_room = write_room,
3553	.chars_in_buffer = chars_in_buffer,
3554	.flush_buffer = flush_buffer,
3555	.ioctl = ioctl,
3556	.compat_ioctl = slgt_compat_ioctl,
3557	.throttle = throttle,
3558	.unthrottle = unthrottle,
3559	.send_xchar = send_xchar,
3560	.break_ctl = set_break,
3561	.wait_until_sent = wait_until_sent,
3562 	.read_proc = read_proc,
3563	.set_termios = set_termios,
3564	.stop = tx_hold,
3565	.start = tx_release,
3566	.hangup = hangup,
3567	.tiocmget = tiocmget,
3568	.tiocmset = tiocmset,
3569};
3570
3571static void slgt_cleanup(void)
3572{
3573	int rc;
3574	struct slgt_info *info;
3575	struct slgt_info *tmp;
3576
3577	printk("unload %s %s\n", driver_name, driver_version);
3578
3579	if (serial_driver) {
3580		for (info=slgt_device_list ; info != NULL ; info=info->next_device)
3581			tty_unregister_device(serial_driver, info->line);
3582		if ((rc = tty_unregister_driver(serial_driver)))
3583			DBGERR(("tty_unregister_driver error=%d\n", rc));
3584		put_tty_driver(serial_driver);
3585	}
3586
3587	/* reset devices */
3588	info = slgt_device_list;
3589	while(info) {
3590		reset_port(info);
3591		info = info->next_device;
3592	}
3593
3594	/* release devices */
3595	info = slgt_device_list;
3596	while(info) {
3597#if SYNCLINK_GENERIC_HDLC
3598		hdlcdev_exit(info);
3599#endif
3600		free_dma_bufs(info);
3601		free_tmp_rbuf(info);
3602		if (info->port_num == 0)
3603			release_resources(info);
3604		tmp = info;
3605		info = info->next_device;
3606		kfree(tmp);
3607	}
3608
3609	if (pci_registered)
3610		pci_unregister_driver(&pci_driver);
3611}
3612
3613/*
3614 *  Driver initialization entry point.
3615 */
3616static int __init slgt_init(void)
3617{
3618	int rc;
3619
3620 	printk("%s %s\n", driver_name, driver_version);
3621
3622	serial_driver = alloc_tty_driver(MAX_DEVICES);
3623	if (!serial_driver) {
3624		printk("%s can't allocate tty driver\n", driver_name);
3625		return -ENOMEM;
3626	}
3627
3628	/* Initialize the tty_driver structure */
3629
3630	serial_driver->owner = THIS_MODULE;
3631	serial_driver->driver_name = tty_driver_name;
3632	serial_driver->name = tty_dev_prefix;
3633	serial_driver->major = ttymajor;
3634	serial_driver->minor_start = 64;
3635	serial_driver->type = TTY_DRIVER_TYPE_SERIAL;
3636	serial_driver->subtype = SERIAL_TYPE_NORMAL;
3637	serial_driver->init_termios = tty_std_termios;
3638	serial_driver->init_termios.c_cflag =
3639		B9600 | CS8 | CREAD | HUPCL | CLOCAL;
3640	serial_driver->init_termios.c_ispeed = 9600;
3641	serial_driver->init_termios.c_ospeed = 9600;
3642	serial_driver->flags = TTY_DRIVER_REAL_RAW | TTY_DRIVER_DYNAMIC_DEV;
3643	tty_set_operations(serial_driver, &ops);
3644	if ((rc = tty_register_driver(serial_driver)) < 0) {
3645		DBGERR(("%s can't register serial driver\n", driver_name));
3646		put_tty_driver(serial_driver);
3647		serial_driver = NULL;
3648		goto error;
3649	}
3650
3651 	printk("%s %s, tty major#%d\n",
3652		driver_name, driver_version,
3653		serial_driver->major);
3654
3655	slgt_device_count = 0;
3656	if ((rc = pci_register_driver(&pci_driver)) < 0) {
3657		printk("%s pci_register_driver error=%d\n", driver_name, rc);
3658		goto error;
3659	}
3660	pci_registered = 1;
3661
3662	if (!slgt_device_list)
3663		printk("%s no devices found\n",driver_name);
3664
3665	return 0;
3666
3667error:
3668	slgt_cleanup();
3669	return rc;
3670}
3671
3672static void __exit slgt_exit(void)
3673{
3674	slgt_cleanup();
3675}
3676
3677module_init(slgt_init);
3678module_exit(slgt_exit);
3679
3680/*
3681 * register access routines
3682 */
3683
3684#define CALC_REGADDR() \
3685	unsigned long reg_addr = ((unsigned long)info->reg_addr) + addr; \
3686	if (addr >= 0x80) \
3687		reg_addr += (info->port_num) * 32;
3688
3689static __u8 rd_reg8(struct slgt_info *info, unsigned int addr)
3690{
3691	CALC_REGADDR();
3692	return readb((void __iomem *)reg_addr);
3693}
3694
3695static void wr_reg8(struct slgt_info *info, unsigned int addr, __u8 value)
3696{
3697	CALC_REGADDR();
3698	writeb(value, (void __iomem *)reg_addr);
3699}
3700
3701static __u16 rd_reg16(struct slgt_info *info, unsigned int addr)
3702{
3703	CALC_REGADDR();
3704	return readw((void __iomem *)reg_addr);
3705}
3706
3707static void wr_reg16(struct slgt_info *info, unsigned int addr, __u16 value)
3708{
3709	CALC_REGADDR();
3710	writew(value, (void __iomem *)reg_addr);
3711}
3712
3713static __u32 rd_reg32(struct slgt_info *info, unsigned int addr)
3714{
3715	CALC_REGADDR();
3716	return readl((void __iomem *)reg_addr);
3717}
3718
3719static void wr_reg32(struct slgt_info *info, unsigned int addr, __u32 value)
3720{
3721	CALC_REGADDR();
3722	writel(value, (void __iomem *)reg_addr);
3723}
3724
3725static void rdma_reset(struct slgt_info *info)
3726{
3727	unsigned int i;
3728
3729	/* set reset bit */
3730	wr_reg32(info, RDCSR, BIT1);
3731
3732	/* wait for enable bit cleared */
3733	for(i=0 ; i < 1000 ; i++)
3734		if (!(rd_reg32(info, RDCSR) & BIT0))
3735			break;
3736}
3737
3738static void tdma_reset(struct slgt_info *info)
3739{
3740	unsigned int i;
3741
3742	/* set reset bit */
3743	wr_reg32(info, TDCSR, BIT1);
3744
3745	/* wait for enable bit cleared */
3746	for(i=0 ; i < 1000 ; i++)
3747		if (!(rd_reg32(info, TDCSR) & BIT0))
3748			break;
3749}
3750
3751/*
3752 * enable internal loopback
3753 * TxCLK and RxCLK are generated from BRG
3754 * and TxD is looped back to RxD internally.
3755 */
3756static void enable_loopback(struct slgt_info *info)
3757{
3758	/* SCR (serial control) BIT2=looopback enable */
3759	wr_reg16(info, SCR, (unsigned short)(rd_reg16(info, SCR) | BIT2));
3760
3761	if (info->params.mode != MGSL_MODE_ASYNC) {
3762		/* CCR (clock control)
3763		 * 07..05  tx clock source (010 = BRG)
3764		 * 04..02  rx clock source (010 = BRG)
3765		 * 01      auxclk enable   (0 = disable)
3766		 * 00      BRG enable      (1 = enable)
3767		 *
3768		 * 0100 1001
3769		 */
3770		wr_reg8(info, CCR, 0x49);
3771
3772		/* set speed if available, otherwise use default */
3773		if (info->params.clock_speed)
3774			set_rate(info, info->params.clock_speed);
3775		else
3776			set_rate(info, 3686400);
3777	}
3778}
3779
3780/*
3781 *  set baud rate generator to specified rate
3782 */
3783static void set_rate(struct slgt_info *info, u32 rate)
3784{
3785	unsigned int div;
3786	static unsigned int osc = 14745600;
3787
3788	/* div = osc/rate - 1
3789	 *
3790	 * Round div up if osc/rate is not integer to
3791	 * force to next slowest rate.
3792	 */
3793
3794	if (rate) {
3795		div = osc/rate;
3796		if (!(osc % rate) && div)
3797			div--;
3798		wr_reg16(info, BDR, (unsigned short)div);
3799	}
3800}
3801
3802static void rx_stop(struct slgt_info *info)
3803{
3804	unsigned short val;
3805
3806	/* disable and reset receiver */
3807	val = rd_reg16(info, RCR) & ~BIT1;          /* clear enable bit */
3808	wr_reg16(info, RCR, (unsigned short)(val | BIT2)); /* set reset bit */
3809	wr_reg16(info, RCR, val);                  /* clear reset bit */
3810
3811	slgt_irq_off(info, IRQ_RXOVER + IRQ_RXDATA + IRQ_RXIDLE);
3812
3813	/* clear pending rx interrupts */
3814	wr_reg16(info, SSR, IRQ_RXIDLE + IRQ_RXOVER);
3815
3816	rdma_reset(info);
3817
3818	info->rx_enabled = 0;
3819	info->rx_restart = 0;
3820}
3821
3822static void rx_start(struct slgt_info *info)
3823{
3824	unsigned short val;
3825
3826	slgt_irq_off(info, IRQ_RXOVER + IRQ_RXDATA);
3827
3828	/* clear pending rx overrun IRQ */
3829	wr_reg16(info, SSR, IRQ_RXOVER);
3830
3831	/* reset and disable receiver */
3832	val = rd_reg16(info, RCR) & ~BIT1; /* clear enable bit */
3833	wr_reg16(info, RCR, (unsigned short)(val | BIT2)); /* set reset bit */
3834	wr_reg16(info, RCR, val);                  /* clear reset bit */
3835
3836	rdma_reset(info);
3837	reset_rbufs(info);
3838
3839	/* set 1st descriptor address */
3840	wr_reg32(info, RDDAR, info->rbufs[0].pdesc);
3841
3842	if (info->params.mode != MGSL_MODE_ASYNC) {
3843		/* enable rx DMA and DMA interrupt */
3844		wr_reg32(info, RDCSR, (BIT2 + BIT0));
3845	} else {
3846		/* enable saving of rx status, rx DMA and DMA interrupt */
3847		wr_reg32(info, RDCSR, (BIT6 + BIT2 + BIT0));
3848	}
3849
3850	slgt_irq_on(info, IRQ_RXOVER);
3851
3852	/* enable receiver */
3853	wr_reg16(info, RCR, (unsigned short)(rd_reg16(info, RCR) | BIT1));
3854
3855	info->rx_restart = 0;
3856	info->rx_enabled = 1;
3857}
3858
3859static void tx_start(struct slgt_info *info)
3860{
3861	if (!info->tx_enabled) {
3862		wr_reg16(info, TCR,
3863			 (unsigned short)((rd_reg16(info, TCR) | BIT1) & ~BIT2));
3864		info->tx_enabled = TRUE;
3865	}
3866
3867	if (info->tx_count) {
3868		info->drop_rts_on_tx_done = 0;
3869
3870		if (info->params.mode != MGSL_MODE_ASYNC) {
3871			if (info->params.flags & HDLC_FLAG_AUTO_RTS) {
3872				get_signals(info);
3873				if (!(info->signals & SerialSignal_RTS)) {
3874					info->signals |= SerialSignal_RTS;
3875					set_signals(info);
3876					info->drop_rts_on_tx_done = 1;
3877				}
3878			}
3879
3880			slgt_irq_off(info, IRQ_TXDATA);
3881			slgt_irq_on(info, IRQ_TXUNDER + IRQ_TXIDLE);
3882			/* clear tx idle and underrun status bits */
3883			wr_reg16(info, SSR, (unsigned short)(IRQ_TXIDLE + IRQ_TXUNDER));
3884
3885			if (!(rd_reg32(info, TDCSR) & BIT0)) {
3886				/* tx DMA stopped, restart tx DMA */
3887				tdma_reset(info);
3888				/* set 1st descriptor address */
3889				wr_reg32(info, TDDAR, info->tbufs[info->tbuf_start].pdesc);
3890				switch(info->params.mode) {
3891				case MGSL_MODE_RAW:
3892				case MGSL_MODE_MONOSYNC:
3893				case MGSL_MODE_BISYNC:
3894					wr_reg32(info, TDCSR, BIT2 + BIT0); /* IRQ + DMA enable */
3895					break;
3896				default:
3897					wr_reg32(info, TDCSR, BIT0); /* DMA enable */
3898				}
3899			}
3900
3901			if (info->params.mode == MGSL_MODE_HDLC)
3902				mod_timer(&info->tx_timer, jiffies +
3903						msecs_to_jiffies(5000));
3904		} else {
3905			tdma_reset(info);
3906			/* set 1st descriptor address */
3907			wr_reg32(info, TDDAR, info->tbufs[info->tbuf_start].pdesc);
3908
3909			slgt_irq_off(info, IRQ_TXDATA);
3910			slgt_irq_on(info, IRQ_TXIDLE);
3911			/* clear tx idle status bit */
3912			wr_reg16(info, SSR, IRQ_TXIDLE);
3913
3914			/* enable tx DMA */
3915			wr_reg32(info, TDCSR, BIT0);
3916		}
3917
3918		info->tx_active = 1;
3919	}
3920}
3921
3922static void tx_stop(struct slgt_info *info)
3923{
3924	unsigned short val;
3925
3926	del_timer(&info->tx_timer);
3927
3928	tdma_reset(info);
3929
3930	/* reset and disable transmitter */
3931	val = rd_reg16(info, TCR) & ~BIT1;          /* clear enable bit */
3932	wr_reg16(info, TCR, (unsigned short)(val | BIT2)); /* set reset bit */
3933
3934	slgt_irq_off(info, IRQ_TXDATA + IRQ_TXIDLE + IRQ_TXUNDER);
3935
3936	/* clear tx idle and underrun status bit */
3937	wr_reg16(info, SSR, (unsigned short)(IRQ_TXIDLE + IRQ_TXUNDER));
3938
3939	reset_tbufs(info);
3940
3941	info->tx_enabled = 0;
3942	info->tx_active  = 0;
3943}
3944
3945static void reset_port(struct slgt_info *info)
3946{
3947	if (!info->reg_addr)
3948		return;
3949
3950	tx_stop(info);
3951	rx_stop(info);
3952
3953	info->signals &= ~(SerialSignal_DTR + SerialSignal_RTS);
3954	set_signals(info);
3955
3956	slgt_irq_off(info, IRQ_ALL | IRQ_MASTER);
3957}
3958
3959static void reset_adapter(struct slgt_info *info)
3960{
3961	int i;
3962	for (i=0; i < info->port_count; ++i) {
3963		if (info->port_array[i])
3964			reset_port(info->port_array[i]);
3965	}
3966}
3967
3968static void async_mode(struct slgt_info *info)
3969{
3970  	unsigned short val;
3971
3972	slgt_irq_off(info, IRQ_ALL | IRQ_MASTER);
3973	tx_stop(info);
3974	rx_stop(info);
3975
3976	/* TCR (tx control)
3977	 *
3978	 * 15..13  mode, 010=async
3979	 * 12..10  encoding, 000=NRZ
3980	 * 09      parity enable
3981	 * 08      1=odd parity, 0=even parity
3982	 * 07      1=RTS driver control
3983	 * 06      1=break enable
3984	 * 05..04  character length
3985	 *         00=5 bits
3986	 *         01=6 bits
3987	 *         10=7 bits
3988	 *         11=8 bits
3989	 * 03      0=1 stop bit, 1=2 stop bits
3990	 * 02      reset
3991	 * 01      enable
3992	 * 00      auto-CTS enable
3993	 */
3994	val = 0x4000;
3995
3996	if (info->if_mode & MGSL_INTERFACE_RTS_EN)
3997		val |= BIT7;
3998
3999	if (info->params.parity != ASYNC_PARITY_NONE) {
4000		val |= BIT9;
4001		if (info->params.parity == ASYNC_PARITY_ODD)
4002			val |= BIT8;
4003	}
4004
4005	switch (info->params.data_bits)
4006	{
4007	case 6: val |= BIT4; break;
4008	case 7: val |= BIT5; break;
4009	case 8: val |= BIT5 + BIT4; break;
4010	}
4011
4012	if (info->params.stop_bits != 1)
4013		val |= BIT3;
4014
4015	if (info->params.flags & HDLC_FLAG_AUTO_CTS)
4016		val |= BIT0;
4017
4018	wr_reg16(info, TCR, val);
4019
4020	/* RCR (rx control)
4021	 *
4022	 * 15..13  mode, 010=async
4023	 * 12..10  encoding, 000=NRZ
4024	 * 09      parity enable
4025	 * 08      1=odd parity, 0=even parity
4026	 * 07..06  reserved, must be 0
4027	 * 05..04  character length
4028	 *         00=5 bits
4029	 *         01=6 bits
4030	 *         10=7 bits
4031	 *         11=8 bits
4032	 * 03      reserved, must be zero
4033	 * 02      reset
4034	 * 01      enable
4035	 * 00      auto-DCD enable
4036	 */
4037	val = 0x4000;
4038
4039	if (info->params.parity != ASYNC_PARITY_NONE) {
4040		val |= BIT9;
4041		if (info->params.parity == ASYNC_PARITY_ODD)
4042			val |= BIT8;
4043	}
4044
4045	switch (info->params.data_bits)
4046	{
4047	case 6: val |= BIT4; break;
4048	case 7: val |= BIT5; break;
4049	case 8: val |= BIT5 + BIT4; break;
4050	}
4051
4052	if (info->params.flags & HDLC_FLAG_AUTO_DCD)
4053		val |= BIT0;
4054
4055	wr_reg16(info, RCR, val);
4056
4057	/* CCR (clock control)
4058	 *
4059	 * 07..05  011 = tx clock source is BRG/16
4060	 * 04..02  010 = rx clock source is BRG
4061	 * 01      0 = auxclk disabled
4062	 * 00      1 = BRG enabled
4063	 *
4064	 * 0110 1001
4065	 */
4066	wr_reg8(info, CCR, 0x69);
4067
4068	msc_set_vcr(info);
4069
4070	/* SCR (serial control)
4071	 *
4072	 * 15  1=tx req on FIFO half empty
4073	 * 14  1=rx req on FIFO half full
4074	 * 13  tx data  IRQ enable
4075	 * 12  tx idle  IRQ enable
4076	 * 11  rx break on IRQ enable
4077	 * 10  rx data  IRQ enable
4078	 * 09  rx break off IRQ enable
4079	 * 08  overrun  IRQ enable
4080	 * 07  DSR      IRQ enable
4081	 * 06  CTS      IRQ enable
4082	 * 05  DCD      IRQ enable
4083	 * 04  RI       IRQ enable
4084	 * 03  reserved, must be zero
4085	 * 02  1=txd->rxd internal loopback enable
4086	 * 01  reserved, must be zero
4087	 * 00  1=master IRQ enable
4088	 */
4089	val = BIT15 + BIT14 + BIT0;
4090	wr_reg16(info, SCR, val);
4091
4092	slgt_irq_on(info, IRQ_RXBREAK | IRQ_RXOVER);
4093
4094	set_rate(info, info->params.data_rate * 16);
4095
4096	if (info->params.loopback)
4097		enable_loopback(info);
4098}
4099
4100static void sync_mode(struct slgt_info *info)
4101{
4102	unsigned short val;
4103
4104	slgt_irq_off(info, IRQ_ALL | IRQ_MASTER);
4105	tx_stop(info);
4106	rx_stop(info);
4107
4108	/* TCR (tx control)
4109	 *
4110	 * 15..13  mode, 000=HDLC 001=raw 010=async 011=monosync 100=bisync
4111	 * 12..10  encoding
4112	 * 09      CRC enable
4113	 * 08      CRC32
4114	 * 07      1=RTS driver control
4115	 * 06      preamble enable
4116	 * 05..04  preamble length
4117	 * 03      share open/close flag
4118	 * 02      reset
4119	 * 01      enable
4120	 * 00      auto-CTS enable
4121	 */
4122	val = 0;
4123
4124	switch(info->params.mode) {
4125	case MGSL_MODE_MONOSYNC: val |= BIT14 + BIT13; break;
4126	case MGSL_MODE_BISYNC:   val |= BIT15; break;
4127	case MGSL_MODE_RAW:      val |= BIT13; break;
4128	}
4129	if (info->if_mode & MGSL_INTERFACE_RTS_EN)
4130		val |= BIT7;
4131
4132	switch(info->params.encoding)
4133	{
4134	case HDLC_ENCODING_NRZB:          val |= BIT10; break;
4135	case HDLC_ENCODING_NRZI_MARK:     val |= BIT11; break;
4136	case HDLC_ENCODING_NRZI:          val |= BIT11 + BIT10; break;
4137	case HDLC_ENCODING_BIPHASE_MARK:  val |= BIT12; break;
4138	case HDLC_ENCODING_BIPHASE_SPACE: val |= BIT12 + BIT10; break;
4139	case HDLC_ENCODING_BIPHASE_LEVEL: val |= BIT12 + BIT11; break;
4140	case HDLC_ENCODING_DIFF_BIPHASE_LEVEL: val |= BIT12 + BIT11 + BIT10; break;
4141	}
4142
4143	switch (info->params.crc_type & HDLC_CRC_MASK)
4144	{
4145	case HDLC_CRC_16_CCITT: val |= BIT9; break;
4146	case HDLC_CRC_32_CCITT: val |= BIT9 + BIT8; break;
4147	}
4148
4149	if (info->params.preamble != HDLC_PREAMBLE_PATTERN_NONE)
4150		val |= BIT6;
4151
4152	switch (info->params.preamble_length)
4153	{
4154	case HDLC_PREAMBLE_LENGTH_16BITS: val |= BIT5; break;
4155	case HDLC_PREAMBLE_LENGTH_32BITS: val |= BIT4; break;
4156	case HDLC_PREAMBLE_LENGTH_64BITS: val |= BIT5 + BIT4; break;
4157	}
4158
4159	if (info->params.flags & HDLC_FLAG_AUTO_CTS)
4160		val |= BIT0;
4161
4162	wr_reg16(info, TCR, val);
4163
4164	/* TPR (transmit preamble) */
4165
4166	switch (info->params.preamble)
4167	{
4168	case HDLC_PREAMBLE_PATTERN_FLAGS: val = 0x7e; break;
4169	case HDLC_PREAMBLE_PATTERN_ONES:  val = 0xff; break;
4170	case HDLC_PREAMBLE_PATTERN_ZEROS: val = 0x00; break;
4171	case HDLC_PREAMBLE_PATTERN_10:    val = 0x55; break;
4172	case HDLC_PREAMBLE_PATTERN_01:    val = 0xaa; break;
4173	default:                          val = 0x7e; break;
4174	}
4175	wr_reg8(info, TPR, (unsigned char)val);
4176
4177	/* RCR (rx control)
4178	 *
4179	 * 15..13  mode, 000=HDLC 001=raw 010=async 011=monosync 100=bisync
4180	 * 12..10  encoding
4181	 * 09      CRC enable
4182	 * 08      CRC32
4183	 * 07..03  reserved, must be 0
4184	 * 02      reset
4185	 * 01      enable
4186	 * 00      auto-DCD enable
4187	 */
4188	val = 0;
4189
4190	switch(info->params.mode) {
4191	case MGSL_MODE_MONOSYNC: val |= BIT14 + BIT13; break;
4192	case MGSL_MODE_BISYNC:   val |= BIT15; break;
4193	case MGSL_MODE_RAW:      val |= BIT13; break;
4194	}
4195
4196	switch(info->params.encoding)
4197	{
4198	case HDLC_ENCODING_NRZB:          val |= BIT10; break;
4199	case HDLC_ENCODING_NRZI_MARK:     val |= BIT11; break;
4200	case HDLC_ENCODING_NRZI:          val |= BIT11 + BIT10; break;
4201	case HDLC_ENCODING_BIPHASE_MARK:  val |= BIT12; break;
4202	case HDLC_ENCODING_BIPHASE_SPACE: val |= BIT12 + BIT10; break;
4203	case HDLC_ENCODING_BIPHASE_LEVEL: val |= BIT12 + BIT11; break;
4204	case HDLC_ENCODING_DIFF_BIPHASE_LEVEL: val |= BIT12 + BIT11 + BIT10; break;
4205	}
4206
4207	switch (info->params.crc_type & HDLC_CRC_MASK)
4208	{
4209	case HDLC_CRC_16_CCITT: val |= BIT9; break;
4210	case HDLC_CRC_32_CCITT: val |= BIT9 + BIT8; break;
4211	}
4212
4213	if (info->params.flags & HDLC_FLAG_AUTO_DCD)
4214		val |= BIT0;
4215
4216	wr_reg16(info, RCR, val);
4217
4218	/* CCR (clock control)
4219	 *
4220	 * 07..05  tx clock source
4221	 * 04..02  rx clock source
4222	 * 01      auxclk enable
4223	 * 00      BRG enable
4224	 */
4225	val = 0;
4226
4227	if (info->params.flags & HDLC_FLAG_TXC_BRG)
4228	{
4229		// when RxC source is DPLL, BRG generates 16X DPLL
4230		// reference clock, so take TxC from BRG/16 to get
4231		// transmit clock at actual data rate
4232		if (info->params.flags & HDLC_FLAG_RXC_DPLL)
4233			val |= BIT6 + BIT5;	/* 011, txclk = BRG/16 */
4234		else
4235			val |= BIT6;	/* 010, txclk = BRG */
4236	}
4237	else if (info->params.flags & HDLC_FLAG_TXC_DPLL)
4238		val |= BIT7;	/* 100, txclk = DPLL Input */
4239	else if (info->params.flags & HDLC_FLAG_TXC_RXCPIN)
4240		val |= BIT5;	/* 001, txclk = RXC Input */
4241
4242	if (info->params.flags & HDLC_FLAG_RXC_BRG)
4243		val |= BIT3;	/* 010, rxclk = BRG */
4244	else if (info->params.flags & HDLC_FLAG_RXC_DPLL)
4245		val |= BIT4;	/* 100, rxclk = DPLL */
4246	else if (info->params.flags & HDLC_FLAG_RXC_TXCPIN)
4247		val |= BIT2;	/* 001, rxclk = TXC Input */
4248
4249	if (info->params.clock_speed)
4250		val |= BIT1 + BIT0;
4251
4252	wr_reg8(info, CCR, (unsigned char)val);
4253
4254	if (info->params.flags & (HDLC_FLAG_TXC_DPLL + HDLC_FLAG_RXC_DPLL))
4255	{
4256		// program DPLL mode
4257		switch(info->params.encoding)
4258		{
4259		case HDLC_ENCODING_BIPHASE_MARK:
4260		case HDLC_ENCODING_BIPHASE_SPACE:
4261			val = BIT7; break;
4262		case HDLC_ENCODING_BIPHASE_LEVEL:
4263		case HDLC_ENCODING_DIFF_BIPHASE_LEVEL:
4264			val = BIT7 + BIT6; break;
4265		default: val = BIT6;	// NRZ encodings
4266		}
4267		wr_reg16(info, RCR, (unsigned short)(rd_reg16(info, RCR) | val));
4268
4269		// DPLL requires a 16X reference clock from BRG
4270		set_rate(info, info->params.clock_speed * 16);
4271	}
4272	else
4273		set_rate(info, info->params.clock_speed);
4274
4275	tx_set_idle(info);
4276
4277	msc_set_vcr(info);
4278
4279	/* SCR (serial control)
4280	 *
4281	 * 15  1=tx req on FIFO half empty
4282	 * 14  1=rx req on FIFO half full
4283	 * 13  tx data  IRQ enable
4284	 * 12  tx idle  IRQ enable
4285	 * 11  underrun IRQ enable
4286	 * 10  rx data  IRQ enable
4287	 * 09  rx idle  IRQ enable
4288	 * 08  overrun  IRQ enable
4289	 * 07  DSR      IRQ enable
4290	 * 06  CTS      IRQ enable
4291	 * 05  DCD      IRQ enable
4292	 * 04  RI       IRQ enable
4293	 * 03  reserved, must be zero
4294	 * 02  1=txd->rxd internal loopback enable
4295	 * 01  reserved, must be zero
4296	 * 00  1=master IRQ enable
4297	 */
4298	wr_reg16(info, SCR, BIT15 + BIT14 + BIT0);
4299
4300	if (info->params.loopback)
4301		enable_loopback(info);
4302}
4303
4304/*
4305 *  set transmit idle mode
4306 */
4307static void tx_set_idle(struct slgt_info *info)
4308{
4309	unsigned char val;
4310	unsigned short tcr;
4311
4312	/* if preamble enabled (tcr[6] == 1) then tx idle size = 8 bits
4313	 * else tcr[5:4] = tx idle size: 00 = 8 bits, 01 = 16 bits
4314	 */
4315	tcr = rd_reg16(info, TCR);
4316	if (info->idle_mode & HDLC_TXIDLE_CUSTOM_16) {
4317		/* disable preamble, set idle size to 16 bits */
4318		tcr = (tcr & ~(BIT6 + BIT5)) | BIT4;
4319		/* MSB of 16 bit idle specified in tx preamble register (TPR) */
4320		wr_reg8(info, TPR, (unsigned char)((info->idle_mode >> 8) & 0xff));
4321	} else if (!(tcr & BIT6)) {
4322		/* preamble is disabled, set idle size to 8 bits */
4323		tcr &= ~(BIT5 + BIT4);
4324	}
4325	wr_reg16(info, TCR, tcr);
4326
4327	if (info->idle_mode & (HDLC_TXIDLE_CUSTOM_8 | HDLC_TXIDLE_CUSTOM_16)) {
4328		/* LSB of custom tx idle specified in tx idle register */
4329		val = (unsigned char)(info->idle_mode & 0xff);
4330	} else {
4331		/* standard 8 bit idle patterns */
4332		switch(info->idle_mode)
4333		{
4334		case HDLC_TXIDLE_FLAGS:          val = 0x7e; break;
4335		case HDLC_TXIDLE_ALT_ZEROS_ONES:
4336		case HDLC_TXIDLE_ALT_MARK_SPACE: val = 0xaa; break;
4337		case HDLC_TXIDLE_ZEROS:
4338		case HDLC_TXIDLE_SPACE:          val = 0x00; break;
4339		default:                         val = 0xff;
4340		}
4341	}
4342
4343	wr_reg8(info, TIR, val);
4344}
4345
4346/*
4347 * get state of V24 status (input) signals
4348 */
4349static void get_signals(struct slgt_info *info)
4350{
4351	unsigned short status = rd_reg16(info, SSR);
4352
4353	/* clear all serial signals except DTR and RTS */
4354	info->signals &= SerialSignal_DTR + SerialSignal_RTS;
4355
4356	if (status & BIT3)
4357		info->signals |= SerialSignal_DSR;
4358	if (status & BIT2)
4359		info->signals |= SerialSignal_CTS;
4360	if (status & BIT1)
4361		info->signals |= SerialSignal_DCD;
4362	if (status & BIT0)
4363		info->signals |= SerialSignal_RI;
4364}
4365
4366/*
4367 * set V.24 Control Register based on current configuration
4368 */
4369static void msc_set_vcr(struct slgt_info *info)
4370{
4371	unsigned char val = 0;
4372
4373	/* VCR (V.24 control)
4374	 *
4375	 * 07..04  serial IF select
4376	 * 03      DTR
4377	 * 02      RTS
4378	 * 01      LL
4379	 * 00      RL
4380	 */
4381
4382	switch(info->if_mode & MGSL_INTERFACE_MASK)
4383	{
4384	case MGSL_INTERFACE_RS232:
4385		val |= BIT5; /* 0010 */
4386		break;
4387	case MGSL_INTERFACE_V35:
4388		val |= BIT7 + BIT6 + BIT5; /* 1110 */
4389		break;
4390	case MGSL_INTERFACE_RS422:
4391		val |= BIT6; /* 0100 */
4392		break;
4393	}
4394
4395	if (info->signals & SerialSignal_DTR)
4396		val |= BIT3;
4397	if (info->signals & SerialSignal_RTS)
4398		val |= BIT2;
4399	if (info->if_mode & MGSL_INTERFACE_LL)
4400		val |= BIT1;
4401	if (info->if_mode & MGSL_INTERFACE_RL)
4402		val |= BIT0;
4403	wr_reg8(info, VCR, val);
4404}
4405
4406/*
4407 * set state of V24 control (output) signals
4408 */
4409static void set_signals(struct slgt_info *info)
4410{
4411	unsigned char val = rd_reg8(info, VCR);
4412	if (info->signals & SerialSignal_DTR)
4413		val |= BIT3;
4414	else
4415		val &= ~BIT3;
4416	if (info->signals & SerialSignal_RTS)
4417		val |= BIT2;
4418	else
4419		val &= ~BIT2;
4420	wr_reg8(info, VCR, val);
4421}
4422
4423/*
4424 * free range of receive DMA buffers (i to last)
4425 */
4426static void free_rbufs(struct slgt_info *info, unsigned int i, unsigned int last)
4427{
4428	int done = 0;
4429
4430	while(!done) {
4431		/* reset current buffer for reuse */
4432		info->rbufs[i].status = 0;
4433		switch(info->params.mode) {
4434		case MGSL_MODE_RAW:
4435		case MGSL_MODE_MONOSYNC:
4436		case MGSL_MODE_BISYNC:
4437			set_desc_count(info->rbufs[i], info->raw_rx_size);
4438			break;
4439		default:
4440			set_desc_count(info->rbufs[i], DMABUFSIZE);
4441		}
4442
4443		if (i == last)
4444			done = 1;
4445		if (++i == info->rbuf_count)
4446			i = 0;
4447	}
4448	info->rbuf_current = i;
4449}
4450
4451/*
4452 * mark all receive DMA buffers as free
4453 */
4454static void reset_rbufs(struct slgt_info *info)
4455{
4456	free_rbufs(info, 0, info->rbuf_count - 1);
4457}
4458
4459/*
4460 * pass receive HDLC frame to upper layer
4461 *
4462 * return 1 if frame available, otherwise 0
4463 */
4464static int rx_get_frame(struct slgt_info *info)
4465{
4466	unsigned int start, end;
4467	unsigned short status;
4468	unsigned int framesize = 0;
4469	int rc = 0;
4470	unsigned long flags;
4471	struct tty_struct *tty = info->tty;
4472	unsigned char addr_field = 0xff;
4473	unsigned int crc_size = 0;
4474
4475	switch (info->params.crc_type & HDLC_CRC_MASK) {
4476	case HDLC_CRC_16_CCITT: crc_size = 2; break;
4477	case HDLC_CRC_32_CCITT: crc_size = 4; break;
4478	}
4479
4480check_again:
4481
4482	framesize = 0;
4483	addr_field = 0xff;
4484	start = end = info->rbuf_current;
4485
4486	for (;;) {
4487		if (!desc_complete(info->rbufs[end]))
4488			goto cleanup;
4489
4490		if (framesize == 0 && info->params.addr_filter != 0xff)
4491			addr_field = info->rbufs[end].buf[0];
4492
4493		framesize += desc_count(info->rbufs[end]);
4494
4495		if (desc_eof(info->rbufs[end]))
4496			break;
4497
4498		if (++end == info->rbuf_count)
4499			end = 0;
4500
4501		if (end == info->rbuf_current) {
4502			if (info->rx_enabled){
4503				spin_lock_irqsave(&info->lock,flags);
4504				rx_start(info);
4505				spin_unlock_irqrestore(&info->lock,flags);
4506			}
4507			goto cleanup;
4508		}
4509	}
4510
4511	/* status
4512	 *
4513	 * 15      buffer complete
4514	 * 14..06  reserved
4515	 * 05..04  residue
4516	 * 02      eof (end of frame)
4517	 * 01      CRC error
4518	 * 00      abort
4519	 */
4520	status = desc_status(info->rbufs[end]);
4521
4522	/* ignore CRC bit if not using CRC (bit is undefined) */
4523	if ((info->params.crc_type & HDLC_CRC_MASK) == HDLC_CRC_NONE)
4524		status &= ~BIT1;
4525
4526	if (framesize == 0 ||
4527		 (addr_field != 0xff && addr_field != info->params.addr_filter)) {
4528		free_rbufs(info, start, end);
4529		goto check_again;
4530	}
4531
4532	if (framesize < (2 + crc_size) || status & BIT0) {
4533		info->icount.rxshort++;
4534		framesize = 0;
4535	} else if (status & BIT1) {
4536		info->icount.rxcrc++;
4537		if (!(info->params.crc_type & HDLC_CRC_RETURN_EX))
4538			framesize = 0;
4539	}
4540
4541#if SYNCLINK_GENERIC_HDLC
4542	if (framesize == 0) {
4543		struct net_device_stats *stats = hdlc_stats(info->netdev);
4544		stats->rx_errors++;
4545		stats->rx_frame_errors++;
4546	}
4547#endif
4548
4549	DBGBH(("%s rx frame status=%04X size=%d\n",
4550		info->device_name, status, framesize));
4551	DBGDATA(info, info->rbufs[start].buf, min_t(int, framesize, DMABUFSIZE), "rx");
4552
4553	if (framesize) {
4554		if (!(info->params.crc_type & HDLC_CRC_RETURN_EX)) {
4555			framesize -= crc_size;
4556			crc_size = 0;
4557		}
4558
4559		if (framesize > info->max_frame_size + crc_size)
4560			info->icount.rxlong++;
4561		else {
4562			/* copy dma buffer(s) to contiguous temp buffer */
4563			int copy_count = framesize;
4564			int i = start;
4565			unsigned char *p = info->tmp_rbuf;
4566			info->tmp_rbuf_count = framesize;
4567
4568			info->icount.rxok++;
4569
4570			while(copy_count) {
4571				int partial_count = min(copy_count, DMABUFSIZE);
4572				memcpy(p, info->rbufs[i].buf, partial_count);
4573				p += partial_count;
4574				copy_count -= partial_count;
4575				if (++i == info->rbuf_count)
4576					i = 0;
4577			}
4578
4579			if (info->params.crc_type & HDLC_CRC_RETURN_EX) {
4580				*p = (status & BIT1) ? RX_CRC_ERROR : RX_OK;
4581				framesize++;
4582			}
4583
4584#if SYNCLINK_GENERIC_HDLC
4585			if (info->netcount)
4586				hdlcdev_rx(info,info->tmp_rbuf, framesize);
4587			else
4588#endif
4589				ldisc_receive_buf(tty, info->tmp_rbuf, info->flag_buf, framesize);
4590		}
4591	}
4592	free_rbufs(info, start, end);
4593	rc = 1;
4594
4595cleanup:
4596	return rc;
4597}
4598
4599/*
4600 * pass receive buffer (RAW synchronous mode) to tty layer
4601 * return 1 if buffer available, otherwise 0
4602 */
4603static int rx_get_buf(struct slgt_info *info)
4604{
4605	unsigned int i = info->rbuf_current;
4606	unsigned int count;
4607
4608	if (!desc_complete(info->rbufs[i]))
4609		return 0;
4610	count = desc_count(info->rbufs[i]);
4611	switch(info->params.mode) {
4612	case MGSL_MODE_MONOSYNC:
4613	case MGSL_MODE_BISYNC:
4614		/* ignore residue in byte synchronous modes */
4615		if (desc_residue(info->rbufs[i]))
4616			count--;
4617		break;
4618	}
4619	DBGDATA(info, info->rbufs[i].buf, count, "rx");
4620	DBGINFO(("rx_get_buf size=%d\n", count));
4621	if (count)
4622		ldisc_receive_buf(info->tty, info->rbufs[i].buf,
4623				  info->flag_buf, count);
4624	free_rbufs(info, i, i);
4625	return 1;
4626}
4627
4628static void reset_tbufs(struct slgt_info *info)
4629{
4630	unsigned int i;
4631	info->tbuf_current = 0;
4632	for (i=0 ; i < info->tbuf_count ; i++) {
4633		info->tbufs[i].status = 0;
4634		info->tbufs[i].count  = 0;
4635	}
4636}
4637
4638/*
4639 * return number of free transmit DMA buffers
4640 */
4641static unsigned int free_tbuf_count(struct slgt_info *info)
4642{
4643	unsigned int count = 0;
4644	unsigned int i = info->tbuf_current;
4645
4646	do
4647	{
4648		if (desc_count(info->tbufs[i]))
4649			break; /* buffer in use */
4650		++count;
4651		if (++i == info->tbuf_count)
4652			i=0;
4653	} while (i != info->tbuf_current);
4654
4655	/* last buffer with zero count may be in use, assume it is */
4656	if (count)
4657		--count;
4658
4659	return count;
4660}
4661
4662/*
4663 * load transmit DMA buffer(s) with data
4664 */
4665static void tx_load(struct slgt_info *info, const char *buf, unsigned int size)
4666{
4667	unsigned short count;
4668	unsigned int i;
4669	struct slgt_desc *d;
4670
4671	if (size == 0)
4672		return;
4673
4674	DBGDATA(info, buf, size, "tx");
4675
4676	info->tbuf_start = i = info->tbuf_current;
4677
4678	while (size) {
4679		d = &info->tbufs[i];
4680		if (++i == info->tbuf_count)
4681			i = 0;
4682
4683		count = (unsigned short)((size > DMABUFSIZE) ? DMABUFSIZE : size);
4684		memcpy(d->buf, buf, count);
4685
4686		size -= count;
4687		buf  += count;
4688
4689		/*
4690		 * set EOF bit for last buffer of HDLC frame or
4691		 * for every buffer in raw mode
4692		 */
4693		if ((!size && info->params.mode == MGSL_MODE_HDLC) ||
4694		    info->params.mode == MGSL_MODE_RAW)
4695			set_desc_eof(*d, 1);
4696		else
4697			set_desc_eof(*d, 0);
4698
4699		set_desc_count(*d, count);
4700	}
4701
4702	info->tbuf_current = i;
4703}
4704
4705static int register_test(struct slgt_info *info)
4706{
4707	static unsigned short patterns[] =
4708		{0x0000, 0xffff, 0xaaaa, 0x5555, 0x6969, 0x9696};
4709	static unsigned int count = sizeof(patterns)/sizeof(patterns[0]);
4710	unsigned int i;
4711	int rc = 0;
4712
4713	for (i=0 ; i < count ; i++) {
4714		wr_reg16(info, TIR, patterns[i]);
4715		wr_reg16(info, BDR, patterns[(i+1)%count]);
4716		if ((rd_reg16(info, TIR) != patterns[i]) ||
4717		    (rd_reg16(info, BDR) != patterns[(i+1)%count])) {
4718			rc = -ENODEV;
4719			break;
4720		}
4721	}
4722	info->gpio_present = (rd_reg32(info, JCR) & BIT5) ? 1 : 0;
4723	info->init_error = rc ? 0 : DiagStatus_AddressFailure;
4724	return rc;
4725}
4726
4727static int irq_test(struct slgt_info *info)
4728{
4729	unsigned long timeout;
4730	unsigned long flags;
4731	struct tty_struct *oldtty = info->tty;
4732	u32 speed = info->params.data_rate;
4733
4734	info->params.data_rate = 921600;
4735	info->tty = NULL;
4736
4737	spin_lock_irqsave(&info->lock, flags);
4738	async_mode(info);
4739	slgt_irq_on(info, IRQ_TXIDLE);
4740
4741	/* enable transmitter */
4742	wr_reg16(info, TCR,
4743		(unsigned short)(rd_reg16(info, TCR) | BIT1));
4744
4745	/* write one byte and wait for tx idle */
4746	wr_reg16(info, TDR, 0);
4747
4748	/* assume failure */
4749	info->init_error = DiagStatus_IrqFailure;
4750	info->irq_occurred = FALSE;
4751
4752	spin_unlock_irqrestore(&info->lock, flags);
4753
4754	timeout=100;
4755	while(timeout-- && !info->irq_occurred)
4756		msleep_interruptible(10);
4757
4758	spin_lock_irqsave(&info->lock,flags);
4759	reset_port(info);
4760	spin_unlock_irqrestore(&info->lock,flags);
4761
4762	info->params.data_rate = speed;
4763	info->tty = oldtty;
4764
4765	info->init_error = info->irq_occurred ? 0 : DiagStatus_IrqFailure;
4766	return info->irq_occurred ? 0 : -ENODEV;
4767}
4768
4769static int loopback_test_rx(struct slgt_info *info)
4770{
4771	unsigned char *src, *dest;
4772	int count;
4773
4774	if (desc_complete(info->rbufs[0])) {
4775		count = desc_count(info->rbufs[0]);
4776		src   = info->rbufs[0].buf;
4777		dest  = info->tmp_rbuf;
4778
4779		for( ; count ; count-=2, src+=2) {
4780			/* src=data byte (src+1)=status byte */
4781			if (!(*(src+1) & (BIT9 + BIT8))) {
4782				*dest = *src;
4783				dest++;
4784				info->tmp_rbuf_count++;
4785			}
4786		}
4787		DBGDATA(info, info->tmp_rbuf, info->tmp_rbuf_count, "rx");
4788		return 1;
4789	}
4790	return 0;
4791}
4792
4793static int loopback_test(struct slgt_info *info)
4794{
4795#define TESTFRAMESIZE 20
4796
4797	unsigned long timeout;
4798	u16 count = TESTFRAMESIZE;
4799	unsigned char buf[TESTFRAMESIZE];
4800	int rc = -ENODEV;
4801	unsigned long flags;
4802
4803	struct tty_struct *oldtty = info->tty;
4804	MGSL_PARAMS params;
4805
4806	memcpy(&params, &info->params, sizeof(params));
4807
4808	info->params.mode = MGSL_MODE_ASYNC;
4809	info->params.data_rate = 921600;
4810	info->params.loopback = 1;
4811	info->tty = NULL;
4812
4813	/* build and send transmit frame */
4814	for (count = 0; count < TESTFRAMESIZE; ++count)
4815		buf[count] = (unsigned char)count;
4816
4817	info->tmp_rbuf_count = 0;
4818	memset(info->tmp_rbuf, 0, TESTFRAMESIZE);
4819
4820	/* program hardware for HDLC and enabled receiver */
4821	spin_lock_irqsave(&info->lock,flags);
4822	async_mode(info);
4823	rx_start(info);
4824	info->tx_count = count;
4825	tx_load(info, buf, count);
4826	tx_start(info);
4827	spin_unlock_irqrestore(&info->lock, flags);
4828
4829	/* wait for receive complete */
4830	for (timeout = 100; timeout; --timeout) {
4831		msleep_interruptible(10);
4832		if (loopback_test_rx(info)) {
4833			rc = 0;
4834			break;
4835		}
4836	}
4837
4838	/* verify received frame length and contents */
4839	if (!rc && (info->tmp_rbuf_count != count ||
4840		  memcmp(buf, info->tmp_rbuf, count))) {
4841		rc = -ENODEV;
4842	}
4843
4844	spin_lock_irqsave(&info->lock,flags);
4845	reset_adapter(info);
4846	spin_unlock_irqrestore(&info->lock,flags);
4847
4848	memcpy(&info->params, &params, sizeof(info->params));
4849	info->tty = oldtty;
4850
4851	info->init_error = rc ? DiagStatus_DmaFailure : 0;
4852	return rc;
4853}
4854
4855static int adapter_test(struct slgt_info *info)
4856{
4857	DBGINFO(("testing %s\n", info->device_name));
4858	if (register_test(info) < 0) {
4859		printk("register test failure %s addr=%08X\n",
4860			info->device_name, info->phys_reg_addr);
4861	} else if (irq_test(info) < 0) {
4862		printk("IRQ test failure %s IRQ=%d\n",
4863			info->device_name, info->irq_level);
4864	} else if (loopback_test(info) < 0) {
4865		printk("loopback test failure %s\n", info->device_name);
4866	}
4867	return info->init_error;
4868}
4869
4870/*
4871 * transmit timeout handler
4872 */
4873static void tx_timeout(unsigned long context)
4874{
4875	struct slgt_info *info = (struct slgt_info*)context;
4876	unsigned long flags;
4877
4878	DBGINFO(("%s tx_timeout\n", info->device_name));
4879	if(info->tx_active && info->params.mode == MGSL_MODE_HDLC) {
4880		info->icount.txtimeout++;
4881	}
4882	spin_lock_irqsave(&info->lock,flags);
4883	info->tx_active = 0;
4884	info->tx_count = 0;
4885	spin_unlock_irqrestore(&info->lock,flags);
4886
4887#if SYNCLINK_GENERIC_HDLC
4888	if (info->netcount)
4889		hdlcdev_tx_done(info);
4890	else
4891#endif
4892		bh_transmit(info);
4893}
4894
4895/*
4896 * receive buffer polling timer
4897 */
4898static void rx_timeout(unsigned long context)
4899{
4900	struct slgt_info *info = (struct slgt_info*)context;
4901	unsigned long flags;
4902
4903	DBGINFO(("%s rx_timeout\n", info->device_name));
4904	spin_lock_irqsave(&info->lock, flags);
4905	info->pending_bh |= BH_RECEIVE;
4906	spin_unlock_irqrestore(&info->lock, flags);
4907	bh_handler(&info->task);
4908}
4909