moxa.c revision 606d099cdd1080bbb50ea50dc52d98252f8f10a1
1/*****************************************************************************/
2/*
3 *           moxa.c  -- MOXA Intellio family multiport serial driver.
4 *
5 *      Copyright (C) 1999-2000  Moxa Technologies (support@moxa.com.tw).
6 *
7 *      This code is loosely based on the Linux serial driver, written by
8 *      Linus Torvalds, Theodore T'so and others.
9 *
10 *      This program is free software; you can redistribute it and/or modify
11 *      it under the terms of the GNU General Public License as published by
12 *      the Free Software Foundation; either version 2 of the License, or
13 *      (at your option) any later version.
14 *
15 *      This program is distributed in the hope that it will be useful,
16 *      but WITHOUT ANY WARRANTY; without even the implied warranty of
17 *      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 *      GNU General Public License for more details.
19 *
20 *      You should have received a copy of the GNU General Public License
21 *      along with this program; if not, write to the Free Software
22 *      Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
23 */
24
25/*
26 *    MOXA Intellio Series Driver
27 *      for             : LINUX
28 *      date            : 1999/1/7
29 *      version         : 5.1
30 */
31
32#include <linux/module.h>
33#include <linux/types.h>
34#include <linux/mm.h>
35#include <linux/ioport.h>
36#include <linux/errno.h>
37#include <linux/signal.h>
38#include <linux/sched.h>
39#include <linux/timer.h>
40#include <linux/interrupt.h>
41#include <linux/tty.h>
42#include <linux/tty_flip.h>
43#include <linux/major.h>
44#include <linux/string.h>
45#include <linux/fcntl.h>
46#include <linux/ptrace.h>
47#include <linux/serial.h>
48#include <linux/tty_driver.h>
49#include <linux/delay.h>
50#include <linux/pci.h>
51#include <linux/init.h>
52#include <linux/bitops.h>
53
54#include <asm/system.h>
55#include <asm/io.h>
56#include <asm/uaccess.h>
57
58#define		MOXA_VERSION		"5.1k"
59
60#define MOXAMAJOR       172
61#define MOXACUMAJOR     173
62
63#define put_to_user(arg1, arg2) put_user(arg1, (unsigned long *)arg2)
64#define get_from_user(arg1, arg2) get_user(arg1, (unsigned int *)arg2)
65
66#define MAX_BOARDS 		4	/* Don't change this value */
67#define MAX_PORTS_PER_BOARD	32	/* Don't change this value */
68#define MAX_PORTS 		128	/* Don't change this value */
69
70/*
71 *    Define the Moxa PCI vendor and device IDs.
72 */
73#define MOXA_BUS_TYPE_ISA		0
74#define MOXA_BUS_TYPE_PCI		1
75
76#ifndef	PCI_VENDOR_ID_MOXA
77#define	PCI_VENDOR_ID_MOXA	0x1393
78#endif
79#ifndef PCI_DEVICE_ID_CP204J
80#define PCI_DEVICE_ID_CP204J	0x2040
81#endif
82#ifndef PCI_DEVICE_ID_C218
83#define PCI_DEVICE_ID_C218	0x2180
84#endif
85#ifndef PCI_DEVICE_ID_C320
86#define PCI_DEVICE_ID_C320	0x3200
87#endif
88
89enum {
90	MOXA_BOARD_C218_PCI = 1,
91	MOXA_BOARD_C218_ISA,
92	MOXA_BOARD_C320_PCI,
93	MOXA_BOARD_C320_ISA,
94	MOXA_BOARD_CP204J,
95};
96
97static char *moxa_brdname[] =
98{
99	"C218 Turbo PCI series",
100	"C218 Turbo ISA series",
101	"C320 Turbo PCI series",
102	"C320 Turbo ISA series",
103	"CP-204J series",
104};
105
106#ifdef CONFIG_PCI
107static struct pci_device_id moxa_pcibrds[] = {
108	{ PCI_VENDOR_ID_MOXA, PCI_DEVICE_ID_C218, PCI_ANY_ID, PCI_ANY_ID,
109	  0, 0, MOXA_BOARD_C218_PCI },
110	{ PCI_VENDOR_ID_MOXA, PCI_DEVICE_ID_C320, PCI_ANY_ID, PCI_ANY_ID,
111	  0, 0, MOXA_BOARD_C320_PCI },
112	{ PCI_VENDOR_ID_MOXA, PCI_DEVICE_ID_CP204J, PCI_ANY_ID, PCI_ANY_ID,
113	  0, 0, MOXA_BOARD_CP204J },
114	{ 0 }
115};
116MODULE_DEVICE_TABLE(pci, moxa_pcibrds);
117#endif /* CONFIG_PCI */
118
119typedef struct _moxa_isa_board_conf {
120	int boardType;
121	int numPorts;
122	unsigned long baseAddr;
123} moxa_isa_board_conf;
124
125static moxa_isa_board_conf moxa_isa_boards[] =
126{
127/*       {MOXA_BOARD_C218_ISA,8,0xDC000}, */
128};
129
130typedef struct _moxa_pci_devinfo {
131	ushort busNum;
132	ushort devNum;
133	struct pci_dev *pdev;
134} moxa_pci_devinfo;
135
136typedef struct _moxa_board_conf {
137	int boardType;
138	int numPorts;
139	unsigned long baseAddr;
140	int busType;
141	moxa_pci_devinfo pciInfo;
142} moxa_board_conf;
143
144static moxa_board_conf moxa_boards[MAX_BOARDS];
145static void __iomem *moxaBaseAddr[MAX_BOARDS];
146static int loadstat[MAX_BOARDS];
147
148struct moxa_str {
149	int type;
150	int port;
151	int close_delay;
152	unsigned short closing_wait;
153	int count;
154	int blocked_open;
155	long event; /* long req'd for set_bit --RR */
156	int asyncflags;
157	unsigned long statusflags;
158	struct tty_struct *tty;
159	int cflag;
160	wait_queue_head_t open_wait;
161	wait_queue_head_t close_wait;
162	struct work_struct tqueue;
163};
164
165struct mxser_mstatus {
166	tcflag_t cflag;
167	int cts;
168	int dsr;
169	int ri;
170	int dcd;
171};
172
173static struct mxser_mstatus GMStatus[MAX_PORTS];
174
175/* statusflags */
176#define TXSTOPPED	0x1
177#define LOWWAIT 	0x2
178#define EMPTYWAIT	0x4
179#define THROTTLE	0x8
180
181/* event */
182#define MOXA_EVENT_HANGUP	1
183
184#define SERIAL_DO_RESTART
185
186
187#define SERIAL_TYPE_NORMAL	1
188
189#define WAKEUP_CHARS		256
190
191#define PORTNO(x)		((x)->index)
192
193static int verbose = 0;
194static int ttymajor = MOXAMAJOR;
195/* Variables for insmod */
196#ifdef MODULE
197static int baseaddr[] 	= 	{0, 0, 0, 0};
198static int type[]	=	{0, 0, 0, 0};
199static int numports[] 	=	{0, 0, 0, 0};
200#endif
201
202MODULE_AUTHOR("William Chen");
203MODULE_DESCRIPTION("MOXA Intellio Family Multiport Board Device Driver");
204MODULE_LICENSE("GPL");
205#ifdef MODULE
206module_param_array(type, int, NULL, 0);
207module_param_array(baseaddr, int, NULL, 0);
208module_param_array(numports, int, NULL, 0);
209#endif
210module_param(ttymajor, int, 0);
211module_param(verbose, bool, 0644);
212
213static struct tty_driver *moxaDriver;
214static struct moxa_str moxaChannels[MAX_PORTS];
215static unsigned char *moxaXmitBuff;
216static int moxaTimer_on;
217static struct timer_list moxaTimer;
218static int moxaEmptyTimer_on[MAX_PORTS];
219static struct timer_list moxaEmptyTimer[MAX_PORTS];
220static struct semaphore moxaBuffSem;
221
222/*
223 * static functions:
224 */
225static void do_moxa_softint(struct work_struct *);
226static int moxa_open(struct tty_struct *, struct file *);
227static void moxa_close(struct tty_struct *, struct file *);
228static int moxa_write(struct tty_struct *, const unsigned char *, int);
229static int moxa_write_room(struct tty_struct *);
230static void moxa_flush_buffer(struct tty_struct *);
231static int moxa_chars_in_buffer(struct tty_struct *);
232static void moxa_flush_chars(struct tty_struct *);
233static void moxa_put_char(struct tty_struct *, unsigned char);
234static int moxa_ioctl(struct tty_struct *, struct file *, unsigned int, unsigned long);
235static void moxa_throttle(struct tty_struct *);
236static void moxa_unthrottle(struct tty_struct *);
237static void moxa_set_termios(struct tty_struct *, struct ktermios *);
238static void moxa_stop(struct tty_struct *);
239static void moxa_start(struct tty_struct *);
240static void moxa_hangup(struct tty_struct *);
241static int moxa_tiocmget(struct tty_struct *tty, struct file *file);
242static int moxa_tiocmset(struct tty_struct *tty, struct file *file,
243			 unsigned int set, unsigned int clear);
244static void moxa_poll(unsigned long);
245static void set_tty_param(struct tty_struct *);
246static int block_till_ready(struct tty_struct *, struct file *,
247			    struct moxa_str *);
248static void setup_empty_event(struct tty_struct *);
249static void check_xmit_empty(unsigned long);
250static void shut_down(struct moxa_str *);
251static void receive_data(struct moxa_str *);
252/*
253 * moxa board interface functions:
254 */
255static void MoxaDriverInit(void);
256static int MoxaDriverIoctl(unsigned int, unsigned long, int);
257static int MoxaDriverPoll(void);
258static int MoxaPortsOfCard(int);
259static int MoxaPortIsValid(int);
260static void MoxaPortEnable(int);
261static void MoxaPortDisable(int);
262static long MoxaPortGetMaxBaud(int);
263static long MoxaPortSetBaud(int, long);
264static int MoxaPortSetTermio(int, struct ktermios *, speed_t);
265static int MoxaPortGetLineOut(int, int *, int *);
266static void MoxaPortLineCtrl(int, int, int);
267static void MoxaPortFlowCtrl(int, int, int, int, int, int);
268static int MoxaPortLineStatus(int);
269static int MoxaPortDCDChange(int);
270static int MoxaPortDCDON(int);
271static void MoxaPortFlushData(int, int);
272static int MoxaPortWriteData(int, unsigned char *, int);
273static int MoxaPortReadData(int, struct tty_struct *tty);
274static int MoxaPortTxQueue(int);
275static int MoxaPortRxQueue(int);
276static int MoxaPortTxFree(int);
277static void MoxaPortTxDisable(int);
278static void MoxaPortTxEnable(int);
279static int MoxaPortResetBrkCnt(int);
280static void MoxaPortSendBreak(int, int);
281static int moxa_get_serial_info(struct moxa_str *, struct serial_struct __user *);
282static int moxa_set_serial_info(struct moxa_str *, struct serial_struct __user *);
283static void MoxaSetFifo(int port, int enable);
284
285static const struct tty_operations moxa_ops = {
286	.open = moxa_open,
287	.close = moxa_close,
288	.write = moxa_write,
289	.write_room = moxa_write_room,
290	.flush_buffer = moxa_flush_buffer,
291	.chars_in_buffer = moxa_chars_in_buffer,
292	.flush_chars = moxa_flush_chars,
293	.put_char = moxa_put_char,
294	.ioctl = moxa_ioctl,
295	.throttle = moxa_throttle,
296	.unthrottle = moxa_unthrottle,
297	.set_termios = moxa_set_termios,
298	.stop = moxa_stop,
299	.start = moxa_start,
300	.hangup = moxa_hangup,
301	.tiocmget = moxa_tiocmget,
302	.tiocmset = moxa_tiocmset,
303};
304
305static DEFINE_SPINLOCK(moxa_lock);
306
307#ifdef CONFIG_PCI
308static int moxa_get_PCI_conf(struct pci_dev *p, int board_type, moxa_board_conf * board)
309{
310	board->baseAddr = pci_resource_start (p, 2);
311	board->boardType = board_type;
312	switch (board_type) {
313	case MOXA_BOARD_C218_ISA:
314	case MOXA_BOARD_C218_PCI:
315		board->numPorts = 8;
316		break;
317
318	case MOXA_BOARD_CP204J:
319		board->numPorts = 4;
320		break;
321	default:
322		board->numPorts = 0;
323		break;
324	}
325	board->busType = MOXA_BUS_TYPE_PCI;
326	board->pciInfo.busNum = p->bus->number;
327	board->pciInfo.devNum = p->devfn >> 3;
328	board->pciInfo.pdev = p;
329	/* don't lose the reference in the next pci_get_device iteration */
330	pci_dev_get(p);
331
332	return (0);
333}
334#endif /* CONFIG_PCI */
335
336static int __init moxa_init(void)
337{
338	int i, numBoards;
339	struct moxa_str *ch;
340
341	printk(KERN_INFO "MOXA Intellio family driver version %s\n", MOXA_VERSION);
342	moxaDriver = alloc_tty_driver(MAX_PORTS + 1);
343	if (!moxaDriver)
344		return -ENOMEM;
345
346	init_MUTEX(&moxaBuffSem);
347	moxaDriver->owner = THIS_MODULE;
348	moxaDriver->name = "ttyMX";
349	moxaDriver->major = ttymajor;
350	moxaDriver->minor_start = 0;
351	moxaDriver->type = TTY_DRIVER_TYPE_SERIAL;
352	moxaDriver->subtype = SERIAL_TYPE_NORMAL;
353	moxaDriver->init_termios = tty_std_termios;
354	moxaDriver->init_termios.c_iflag = 0;
355	moxaDriver->init_termios.c_oflag = 0;
356	moxaDriver->init_termios.c_cflag = B9600 | CS8 | CREAD | CLOCAL | HUPCL;
357	moxaDriver->init_termios.c_lflag = 0;
358	moxaDriver->init_termios.c_ispeed = 9600;
359	moxaDriver->init_termios.c_ospeed = 9600;
360	moxaDriver->flags = TTY_DRIVER_REAL_RAW;
361	tty_set_operations(moxaDriver, &moxa_ops);
362
363	moxaXmitBuff = NULL;
364
365	for (i = 0, ch = moxaChannels; i < MAX_PORTS; i++, ch++) {
366		ch->type = PORT_16550A;
367		ch->port = i;
368		INIT_WORK(&ch->tqueue, do_moxa_softint);
369		ch->tty = NULL;
370		ch->close_delay = 5 * HZ / 10;
371		ch->closing_wait = 30 * HZ;
372		ch->count = 0;
373		ch->blocked_open = 0;
374		ch->cflag = B9600 | CS8 | CREAD | CLOCAL | HUPCL;
375		init_waitqueue_head(&ch->open_wait);
376		init_waitqueue_head(&ch->close_wait);
377	}
378
379	for (i = 0; i < MAX_BOARDS; i++) {
380		moxa_boards[i].boardType = 0;
381		moxa_boards[i].numPorts = 0;
382		moxa_boards[i].baseAddr = 0;
383		moxa_boards[i].busType = 0;
384		moxa_boards[i].pciInfo.busNum = 0;
385		moxa_boards[i].pciInfo.devNum = 0;
386	}
387	MoxaDriverInit();
388	printk("Tty devices major number = %d\n", ttymajor);
389
390	if (tty_register_driver(moxaDriver)) {
391		printk(KERN_ERR "Couldn't install MOXA Smartio family driver !\n");
392		put_tty_driver(moxaDriver);
393		return -1;
394	}
395	for (i = 0; i < MAX_PORTS; i++) {
396		init_timer(&moxaEmptyTimer[i]);
397		moxaEmptyTimer[i].function = check_xmit_empty;
398		moxaEmptyTimer[i].data = (unsigned long) & moxaChannels[i];
399		moxaEmptyTimer_on[i] = 0;
400	}
401
402	init_timer(&moxaTimer);
403	moxaTimer.function = moxa_poll;
404	moxaTimer.expires = jiffies + (HZ / 50);
405	moxaTimer_on = 1;
406	add_timer(&moxaTimer);
407
408	/* Find the boards defined in source code */
409	numBoards = 0;
410	for (i = 0; i < MAX_BOARDS; i++) {
411		if ((moxa_isa_boards[i].boardType == MOXA_BOARD_C218_ISA) ||
412		 (moxa_isa_boards[i].boardType == MOXA_BOARD_C320_ISA)) {
413			moxa_boards[numBoards].boardType = moxa_isa_boards[i].boardType;
414			if (moxa_isa_boards[i].boardType == MOXA_BOARD_C218_ISA)
415				moxa_boards[numBoards].numPorts = 8;
416			else
417				moxa_boards[numBoards].numPorts = moxa_isa_boards[i].numPorts;
418			moxa_boards[numBoards].busType = MOXA_BUS_TYPE_ISA;
419			moxa_boards[numBoards].baseAddr = moxa_isa_boards[i].baseAddr;
420			if (verbose)
421				printk("Board %2d: %s board(baseAddr=%lx)\n",
422				       numBoards + 1,
423				       moxa_brdname[moxa_boards[numBoards].boardType - 1],
424				       moxa_boards[numBoards].baseAddr);
425			numBoards++;
426		}
427	}
428	/* Find the boards defined form module args. */
429#ifdef MODULE
430	for (i = 0; i < MAX_BOARDS; i++) {
431		if ((type[i] == MOXA_BOARD_C218_ISA) ||
432		    (type[i] == MOXA_BOARD_C320_ISA)) {
433			if (verbose)
434				printk("Board %2d: %s board(baseAddr=%lx)\n",
435				       numBoards + 1,
436				       moxa_brdname[type[i] - 1],
437				       (unsigned long) baseaddr[i]);
438			if (numBoards >= MAX_BOARDS) {
439				if (verbose)
440					printk("More than %d MOXA Intellio family boards found. Board is ignored.", MAX_BOARDS);
441				continue;
442			}
443			moxa_boards[numBoards].boardType = type[i];
444			if (moxa_isa_boards[i].boardType == MOXA_BOARD_C218_ISA)
445				moxa_boards[numBoards].numPorts = 8;
446			else
447				moxa_boards[numBoards].numPorts = numports[i];
448			moxa_boards[numBoards].busType = MOXA_BUS_TYPE_ISA;
449			moxa_boards[numBoards].baseAddr = baseaddr[i];
450			numBoards++;
451		}
452	}
453#endif
454	/* Find PCI boards here */
455#ifdef CONFIG_PCI
456	{
457		struct pci_dev *p = NULL;
458		int n = ARRAY_SIZE(moxa_pcibrds) - 1;
459		i = 0;
460		while (i < n) {
461			while ((p = pci_get_device(moxa_pcibrds[i].vendor, moxa_pcibrds[i].device, p))!=NULL)
462			{
463				if (pci_enable_device(p))
464					continue;
465				if (numBoards >= MAX_BOARDS) {
466					if (verbose)
467						printk("More than %d MOXA Intellio family boards found. Board is ignored.", MAX_BOARDS);
468				} else {
469					moxa_get_PCI_conf(p, moxa_pcibrds[i].driver_data,
470						&moxa_boards[numBoards]);
471					numBoards++;
472				}
473			}
474			i++;
475		}
476	}
477#endif
478	for (i = 0; i < numBoards; i++) {
479		moxaBaseAddr[i] = ioremap((unsigned long) moxa_boards[i].baseAddr, 0x4000);
480	}
481
482	return (0);
483}
484
485static void __exit moxa_exit(void)
486{
487	int i;
488
489	if (verbose)
490		printk("Unloading module moxa ...\n");
491
492	if (moxaTimer_on)
493		del_timer(&moxaTimer);
494
495	for (i = 0; i < MAX_PORTS; i++)
496		if (moxaEmptyTimer_on[i])
497			del_timer(&moxaEmptyTimer[i]);
498
499	if (tty_unregister_driver(moxaDriver))
500		printk("Couldn't unregister MOXA Intellio family serial driver\n");
501	put_tty_driver(moxaDriver);
502
503	for (i = 0; i < MAX_BOARDS; i++) {
504		if (moxaBaseAddr[i])
505			iounmap(moxaBaseAddr[i]);
506		if (moxa_boards[i].busType == MOXA_BUS_TYPE_PCI)
507			pci_dev_put(moxa_boards[i].pciInfo.pdev);
508	}
509
510	if (verbose)
511		printk("Done\n");
512}
513
514module_init(moxa_init);
515module_exit(moxa_exit);
516
517static void do_moxa_softint(struct work_struct *work)
518{
519	struct moxa_str *ch = container_of(work, struct moxa_str, tqueue);
520	struct tty_struct *tty;
521
522	if (ch && (tty = ch->tty)) {
523		if (test_and_clear_bit(MOXA_EVENT_HANGUP, &ch->event)) {
524			tty_hangup(tty);	/* FIXME: module removal race here - AKPM */
525			wake_up_interruptible(&ch->open_wait);
526			ch->asyncflags &= ~ASYNC_NORMAL_ACTIVE;
527		}
528	}
529}
530
531static int moxa_open(struct tty_struct *tty, struct file *filp)
532{
533	struct moxa_str *ch;
534	int port;
535	int retval;
536	unsigned long page;
537
538	port = PORTNO(tty);
539	if (port == MAX_PORTS) {
540		return (0);
541	}
542	if (!MoxaPortIsValid(port)) {
543		tty->driver_data = NULL;
544		return (-ENODEV);
545	}
546	down(&moxaBuffSem);
547	if (!moxaXmitBuff) {
548		page = get_zeroed_page(GFP_KERNEL);
549		if (!page) {
550			up(&moxaBuffSem);
551			return (-ENOMEM);
552		}
553		/* This test is guarded by the BuffSem so no longer needed
554		   delete me in 2.5 */
555		if (moxaXmitBuff)
556			free_page(page);
557		else
558			moxaXmitBuff = (unsigned char *) page;
559	}
560	up(&moxaBuffSem);
561
562	ch = &moxaChannels[port];
563	ch->count++;
564	tty->driver_data = ch;
565	ch->tty = tty;
566	if (!(ch->asyncflags & ASYNC_INITIALIZED)) {
567		ch->statusflags = 0;
568		set_tty_param(tty);
569		MoxaPortLineCtrl(ch->port, 1, 1);
570		MoxaPortEnable(ch->port);
571		ch->asyncflags |= ASYNC_INITIALIZED;
572	}
573	retval = block_till_ready(tty, filp, ch);
574
575	moxa_unthrottle(tty);
576
577	if (ch->type == PORT_16550A) {
578		MoxaSetFifo(ch->port, 1);
579	} else {
580		MoxaSetFifo(ch->port, 0);
581	}
582
583	return (retval);
584}
585
586static void moxa_close(struct tty_struct *tty, struct file *filp)
587{
588	struct moxa_str *ch;
589	int port;
590
591	port = PORTNO(tty);
592	if (port == MAX_PORTS) {
593		return;
594	}
595	if (!MoxaPortIsValid(port)) {
596#ifdef SERIAL_DEBUG_CLOSE
597		printk("Invalid portno in moxa_close\n");
598#endif
599		tty->driver_data = NULL;
600		return;
601	}
602	if (tty->driver_data == NULL) {
603		return;
604	}
605	if (tty_hung_up_p(filp)) {
606		return;
607	}
608	ch = (struct moxa_str *) tty->driver_data;
609
610	if ((tty->count == 1) && (ch->count != 1)) {
611		printk("moxa_close: bad serial port count; tty->count is 1, "
612		       "ch->count is %d\n", ch->count);
613		ch->count = 1;
614	}
615	if (--ch->count < 0) {
616		printk("moxa_close: bad serial port count, device=%s\n",
617		       tty->name);
618		ch->count = 0;
619	}
620	if (ch->count) {
621		return;
622	}
623	ch->asyncflags |= ASYNC_CLOSING;
624
625	ch->cflag = tty->termios->c_cflag;
626	if (ch->asyncflags & ASYNC_INITIALIZED) {
627		setup_empty_event(tty);
628		tty_wait_until_sent(tty, 30 * HZ);	/* 30 seconds timeout */
629		moxaEmptyTimer_on[ch->port] = 0;
630		del_timer(&moxaEmptyTimer[ch->port]);
631	}
632	shut_down(ch);
633	MoxaPortFlushData(port, 2);
634
635	if (tty->driver->flush_buffer)
636		tty->driver->flush_buffer(tty);
637	tty_ldisc_flush(tty);
638
639	tty->closing = 0;
640	ch->event = 0;
641	ch->tty = NULL;
642	if (ch->blocked_open) {
643		if (ch->close_delay) {
644			msleep_interruptible(jiffies_to_msecs(ch->close_delay));
645		}
646		wake_up_interruptible(&ch->open_wait);
647	}
648	ch->asyncflags &= ~(ASYNC_NORMAL_ACTIVE | ASYNC_CLOSING);
649	wake_up_interruptible(&ch->close_wait);
650}
651
652static int moxa_write(struct tty_struct *tty,
653		      const unsigned char *buf, int count)
654{
655	struct moxa_str *ch;
656	int len, port;
657	unsigned long flags;
658
659	ch = (struct moxa_str *) tty->driver_data;
660	if (ch == NULL)
661		return (0);
662	port = ch->port;
663
664	spin_lock_irqsave(&moxa_lock, flags);
665	len = MoxaPortWriteData(port, (unsigned char *) buf, count);
666	spin_unlock_irqrestore(&moxa_lock, flags);
667
668	/*********************************************
669	if ( !(ch->statusflags & LOWWAIT) &&
670	     ((len != count) || (MoxaPortTxFree(port) <= 100)) )
671	************************************************/
672	ch->statusflags |= LOWWAIT;
673	return (len);
674}
675
676static int moxa_write_room(struct tty_struct *tty)
677{
678	struct moxa_str *ch;
679
680	if (tty->stopped)
681		return (0);
682	ch = (struct moxa_str *) tty->driver_data;
683	if (ch == NULL)
684		return (0);
685	return (MoxaPortTxFree(ch->port));
686}
687
688static void moxa_flush_buffer(struct tty_struct *tty)
689{
690	struct moxa_str *ch = (struct moxa_str *) tty->driver_data;
691
692	if (ch == NULL)
693		return;
694	MoxaPortFlushData(ch->port, 1);
695	tty_wakeup(tty);
696}
697
698static int moxa_chars_in_buffer(struct tty_struct *tty)
699{
700	int chars;
701	struct moxa_str *ch = (struct moxa_str *) tty->driver_data;
702
703	/*
704	 * Sigh...I have to check if driver_data is NULL here, because
705	 * if an open() fails, the TTY subsystem eventually calls
706	 * tty_wait_until_sent(), which calls the driver's chars_in_buffer()
707	 * routine.  And since the open() failed, we return 0 here.  TDJ
708	 */
709	if (ch == NULL)
710		return (0);
711	chars = MoxaPortTxQueue(ch->port);
712	if (chars) {
713		/*
714		 * Make it possible to wakeup anything waiting for output
715		 * in tty_ioctl.c, etc.
716		 */
717		if (!(ch->statusflags & EMPTYWAIT))
718			setup_empty_event(tty);
719	}
720	return (chars);
721}
722
723static void moxa_flush_chars(struct tty_struct *tty)
724{
725	/*
726	 * Don't think I need this, because this is called to empty the TX
727	 * buffer for the 16450, 16550, etc.
728	 */
729}
730
731static void moxa_put_char(struct tty_struct *tty, unsigned char c)
732{
733	struct moxa_str *ch;
734	int port;
735	unsigned long flags;
736
737	ch = (struct moxa_str *) tty->driver_data;
738	if (ch == NULL)
739		return;
740	port = ch->port;
741	spin_lock_irqsave(&moxa_lock, flags);
742	moxaXmitBuff[0] = c;
743	MoxaPortWriteData(port, moxaXmitBuff, 1);
744	spin_unlock_irqrestore(&moxa_lock, flags);
745	/************************************************
746	if ( !(ch->statusflags & LOWWAIT) && (MoxaPortTxFree(port) <= 100) )
747	*************************************************/
748	ch->statusflags |= LOWWAIT;
749}
750
751static int moxa_tiocmget(struct tty_struct *tty, struct file *file)
752{
753	struct moxa_str *ch = (struct moxa_str *) tty->driver_data;
754	int port;
755	int flag = 0, dtr, rts;
756
757	port = PORTNO(tty);
758	if ((port != MAX_PORTS) && (!ch))
759		return (-EINVAL);
760
761	MoxaPortGetLineOut(ch->port, &dtr, &rts);
762	if (dtr)
763		flag |= TIOCM_DTR;
764	if (rts)
765		flag |= TIOCM_RTS;
766	dtr = MoxaPortLineStatus(ch->port);
767	if (dtr & 1)
768		flag |= TIOCM_CTS;
769	if (dtr & 2)
770		flag |= TIOCM_DSR;
771	if (dtr & 4)
772		flag |= TIOCM_CD;
773	return flag;
774}
775
776static int moxa_tiocmset(struct tty_struct *tty, struct file *file,
777			 unsigned int set, unsigned int clear)
778{
779	struct moxa_str *ch = (struct moxa_str *) tty->driver_data;
780	int port;
781	int dtr, rts;
782
783	port = PORTNO(tty);
784	if ((port != MAX_PORTS) && (!ch))
785		return (-EINVAL);
786
787	MoxaPortGetLineOut(ch->port, &dtr, &rts);
788	if (set & TIOCM_RTS)
789		rts = 1;
790	if (set & TIOCM_DTR)
791		dtr = 1;
792	if (clear & TIOCM_RTS)
793		rts = 0;
794	if (clear & TIOCM_DTR)
795		dtr = 0;
796	MoxaPortLineCtrl(ch->port, dtr, rts);
797	return 0;
798}
799
800static int moxa_ioctl(struct tty_struct *tty, struct file *file,
801		      unsigned int cmd, unsigned long arg)
802{
803	struct moxa_str *ch = (struct moxa_str *) tty->driver_data;
804	register int port;
805	void __user *argp = (void __user *)arg;
806	int retval;
807
808	port = PORTNO(tty);
809	if ((port != MAX_PORTS) && (!ch))
810		return (-EINVAL);
811
812	switch (cmd) {
813	case TCSBRK:		/* SVID version: non-zero arg --> no break */
814		retval = tty_check_change(tty);
815		if (retval)
816			return (retval);
817		setup_empty_event(tty);
818		tty_wait_until_sent(tty, 0);
819		if (!arg)
820			MoxaPortSendBreak(ch->port, 0);
821		return (0);
822	case TCSBRKP:		/* support for POSIX tcsendbreak() */
823		retval = tty_check_change(tty);
824		if (retval)
825			return (retval);
826		setup_empty_event(tty);
827		tty_wait_until_sent(tty, 0);
828		MoxaPortSendBreak(ch->port, arg);
829		return (0);
830	case TIOCGSOFTCAR:
831		return put_user(C_CLOCAL(tty) ? 1 : 0, (unsigned long __user *) argp);
832	case TIOCSSOFTCAR:
833		if(get_user(retval, (unsigned long __user *) argp))
834			return -EFAULT;
835		arg = retval;
836		tty->termios->c_cflag = ((tty->termios->c_cflag & ~CLOCAL) |
837					 (arg ? CLOCAL : 0));
838		if (C_CLOCAL(tty))
839			ch->asyncflags &= ~ASYNC_CHECK_CD;
840		else
841			ch->asyncflags |= ASYNC_CHECK_CD;
842		return (0);
843	case TIOCGSERIAL:
844		return moxa_get_serial_info(ch, argp);
845
846	case TIOCSSERIAL:
847		return moxa_set_serial_info(ch, argp);
848	default:
849		retval = MoxaDriverIoctl(cmd, arg, port);
850	}
851	return (retval);
852}
853
854static void moxa_throttle(struct tty_struct *tty)
855{
856	struct moxa_str *ch = (struct moxa_str *) tty->driver_data;
857
858	ch->statusflags |= THROTTLE;
859}
860
861static void moxa_unthrottle(struct tty_struct *tty)
862{
863	struct moxa_str *ch = (struct moxa_str *) tty->driver_data;
864
865	ch->statusflags &= ~THROTTLE;
866}
867
868static void moxa_set_termios(struct tty_struct *tty,
869			     struct ktermios *old_termios)
870{
871	struct moxa_str *ch = (struct moxa_str *) tty->driver_data;
872
873	if (ch == NULL)
874		return;
875	set_tty_param(tty);
876	if (!(old_termios->c_cflag & CLOCAL) &&
877	    (tty->termios->c_cflag & CLOCAL))
878		wake_up_interruptible(&ch->open_wait);
879}
880
881static void moxa_stop(struct tty_struct *tty)
882{
883	struct moxa_str *ch = (struct moxa_str *) tty->driver_data;
884
885	if (ch == NULL)
886		return;
887	MoxaPortTxDisable(ch->port);
888	ch->statusflags |= TXSTOPPED;
889}
890
891
892static void moxa_start(struct tty_struct *tty)
893{
894	struct moxa_str *ch = (struct moxa_str *) tty->driver_data;
895
896	if (ch == NULL)
897		return;
898
899	if (!(ch->statusflags & TXSTOPPED))
900		return;
901
902	MoxaPortTxEnable(ch->port);
903	ch->statusflags &= ~TXSTOPPED;
904}
905
906static void moxa_hangup(struct tty_struct *tty)
907{
908	struct moxa_str *ch = (struct moxa_str *) tty->driver_data;
909
910	moxa_flush_buffer(tty);
911	shut_down(ch);
912	ch->event = 0;
913	ch->count = 0;
914	ch->asyncflags &= ~ASYNC_NORMAL_ACTIVE;
915	ch->tty = NULL;
916	wake_up_interruptible(&ch->open_wait);
917}
918
919static void moxa_poll(unsigned long ignored)
920{
921	register int card;
922	struct moxa_str *ch;
923	struct tty_struct *tp;
924	int i, ports;
925
926	moxaTimer_on = 0;
927	del_timer(&moxaTimer);
928
929	if (MoxaDriverPoll() < 0) {
930		moxaTimer.function = moxa_poll;
931		moxaTimer.expires = jiffies + (HZ / 50);
932		moxaTimer_on = 1;
933		add_timer(&moxaTimer);
934		return;
935	}
936	for (card = 0; card < MAX_BOARDS; card++) {
937		if ((ports = MoxaPortsOfCard(card)) <= 0)
938			continue;
939		ch = &moxaChannels[card * MAX_PORTS_PER_BOARD];
940		for (i = 0; i < ports; i++, ch++) {
941			if ((ch->asyncflags & ASYNC_INITIALIZED) == 0)
942				continue;
943			if (!(ch->statusflags & THROTTLE) &&
944			    (MoxaPortRxQueue(ch->port) > 0))
945				receive_data(ch);
946			if ((tp = ch->tty) == 0)
947				continue;
948			if (ch->statusflags & LOWWAIT) {
949				if (MoxaPortTxQueue(ch->port) <= WAKEUP_CHARS) {
950					if (!tp->stopped) {
951						ch->statusflags &= ~LOWWAIT;
952						tty_wakeup(tp);
953					}
954				}
955			}
956			if (!I_IGNBRK(tp) && (MoxaPortResetBrkCnt(ch->port) > 0)) {
957				tty_insert_flip_char(tp, 0, TTY_BREAK);
958				tty_schedule_flip(tp);
959			}
960			if (MoxaPortDCDChange(ch->port)) {
961				if (ch->asyncflags & ASYNC_CHECK_CD) {
962					if (MoxaPortDCDON(ch->port))
963						wake_up_interruptible(&ch->open_wait);
964					else {
965						set_bit(MOXA_EVENT_HANGUP, &ch->event);
966						schedule_work(&ch->tqueue);
967					}
968				}
969			}
970		}
971	}
972
973	moxaTimer.function = moxa_poll;
974	moxaTimer.expires = jiffies + (HZ / 50);
975	moxaTimer_on = 1;
976	add_timer(&moxaTimer);
977}
978
979/******************************************************************************/
980
981static void set_tty_param(struct tty_struct *tty)
982{
983	register struct ktermios *ts;
984	struct moxa_str *ch;
985	int rts, cts, txflow, rxflow, xany;
986
987	ch = (struct moxa_str *) tty->driver_data;
988	ts = tty->termios;
989	if (ts->c_cflag & CLOCAL)
990		ch->asyncflags &= ~ASYNC_CHECK_CD;
991	else
992		ch->asyncflags |= ASYNC_CHECK_CD;
993	rts = cts = txflow = rxflow = xany = 0;
994	if (ts->c_cflag & CRTSCTS)
995		rts = cts = 1;
996	if (ts->c_iflag & IXON)
997		txflow = 1;
998	if (ts->c_iflag & IXOFF)
999		rxflow = 1;
1000	if (ts->c_iflag & IXANY)
1001		xany = 1;
1002	MoxaPortFlowCtrl(ch->port, rts, cts, txflow, rxflow, xany);
1003	MoxaPortSetTermio(ch->port, ts, tty_get_baud_rate(tty));
1004}
1005
1006static int block_till_ready(struct tty_struct *tty, struct file *filp,
1007			    struct moxa_str *ch)
1008{
1009	DECLARE_WAITQUEUE(wait,current);
1010	unsigned long flags;
1011	int retval;
1012	int do_clocal = C_CLOCAL(tty);
1013
1014	/*
1015	 * If the device is in the middle of being closed, then block
1016	 * until it's done, and then try again.
1017	 */
1018	if (tty_hung_up_p(filp) || (ch->asyncflags & ASYNC_CLOSING)) {
1019		if (ch->asyncflags & ASYNC_CLOSING)
1020			interruptible_sleep_on(&ch->close_wait);
1021#ifdef SERIAL_DO_RESTART
1022		if (ch->asyncflags & ASYNC_HUP_NOTIFY)
1023			return (-EAGAIN);
1024		else
1025			return (-ERESTARTSYS);
1026#else
1027		return (-EAGAIN);
1028#endif
1029	}
1030	/*
1031	 * If non-blocking mode is set, then make the check up front
1032	 * and then exit.
1033	 */
1034	if (filp->f_flags & O_NONBLOCK) {
1035		ch->asyncflags |= ASYNC_NORMAL_ACTIVE;
1036		return (0);
1037	}
1038	/*
1039	 * Block waiting for the carrier detect and the line to become free
1040	 */
1041	retval = 0;
1042	add_wait_queue(&ch->open_wait, &wait);
1043#ifdef SERIAL_DEBUG_OPEN
1044	printk("block_til_ready before block: ttys%d, count = %d\n",
1045	       ch->line, ch->count);
1046#endif
1047	spin_lock_irqsave(&moxa_lock, flags);
1048	if (!tty_hung_up_p(filp))
1049		ch->count--;
1050	ch->blocked_open++;
1051	spin_unlock_irqrestore(&moxa_lock, flags);
1052
1053	while (1) {
1054		set_current_state(TASK_INTERRUPTIBLE);
1055		if (tty_hung_up_p(filp) ||
1056		    !(ch->asyncflags & ASYNC_INITIALIZED)) {
1057#ifdef SERIAL_DO_RESTART
1058			if (ch->asyncflags & ASYNC_HUP_NOTIFY)
1059				retval = -EAGAIN;
1060			else
1061				retval = -ERESTARTSYS;
1062#else
1063			retval = -EAGAIN;
1064#endif
1065			break;
1066		}
1067		if (!(ch->asyncflags & ASYNC_CLOSING) && (do_clocal ||
1068						MoxaPortDCDON(ch->port)))
1069			break;
1070
1071		if (signal_pending(current)) {
1072			retval = -ERESTARTSYS;
1073			break;
1074		}
1075		schedule();
1076	}
1077	set_current_state(TASK_RUNNING);
1078	remove_wait_queue(&ch->open_wait, &wait);
1079
1080	spin_lock_irqsave(&moxa_lock, flags);
1081	if (!tty_hung_up_p(filp))
1082		ch->count++;
1083	ch->blocked_open--;
1084	spin_unlock_irqrestore(&moxa_lock, flags);
1085#ifdef SERIAL_DEBUG_OPEN
1086	printk("block_til_ready after blocking: ttys%d, count = %d\n",
1087	       ch->line, ch->count);
1088#endif
1089	if (retval)
1090		return (retval);
1091	/* FIXME: review to see if we need to use set_bit on these */
1092	ch->asyncflags |= ASYNC_NORMAL_ACTIVE;
1093	return 0;
1094}
1095
1096static void setup_empty_event(struct tty_struct *tty)
1097{
1098	struct moxa_str *ch = tty->driver_data;
1099	unsigned long flags;
1100
1101	spin_lock_irqsave(&moxa_lock, flags);
1102	ch->statusflags |= EMPTYWAIT;
1103	moxaEmptyTimer_on[ch->port] = 0;
1104	del_timer(&moxaEmptyTimer[ch->port]);
1105	moxaEmptyTimer[ch->port].expires = jiffies + HZ;
1106	moxaEmptyTimer_on[ch->port] = 1;
1107	add_timer(&moxaEmptyTimer[ch->port]);
1108	spin_unlock_irqrestore(&moxa_lock, flags);
1109}
1110
1111static void check_xmit_empty(unsigned long data)
1112{
1113	struct moxa_str *ch;
1114
1115	ch = (struct moxa_str *) data;
1116	moxaEmptyTimer_on[ch->port] = 0;
1117	del_timer(&moxaEmptyTimer[ch->port]);
1118	if (ch->tty && (ch->statusflags & EMPTYWAIT)) {
1119		if (MoxaPortTxQueue(ch->port) == 0) {
1120			ch->statusflags &= ~EMPTYWAIT;
1121			tty_wakeup(ch->tty);
1122			return;
1123		}
1124		moxaEmptyTimer[ch->port].expires = jiffies + HZ;
1125		moxaEmptyTimer_on[ch->port] = 1;
1126		add_timer(&moxaEmptyTimer[ch->port]);
1127	} else
1128		ch->statusflags &= ~EMPTYWAIT;
1129}
1130
1131static void shut_down(struct moxa_str *ch)
1132{
1133	struct tty_struct *tp;
1134
1135	if (!(ch->asyncflags & ASYNC_INITIALIZED))
1136		return;
1137
1138	tp = ch->tty;
1139
1140	MoxaPortDisable(ch->port);
1141
1142	/*
1143	 * If we're a modem control device and HUPCL is on, drop RTS & DTR.
1144	 */
1145	if (tp->termios->c_cflag & HUPCL)
1146		MoxaPortLineCtrl(ch->port, 0, 0);
1147
1148	ch->asyncflags &= ~ASYNC_INITIALIZED;
1149}
1150
1151static void receive_data(struct moxa_str *ch)
1152{
1153	struct tty_struct *tp;
1154	struct ktermios *ts;
1155	unsigned long flags;
1156
1157	ts = NULL;
1158	tp = ch->tty;
1159	if (tp)
1160		ts = tp->termios;
1161	/**************************************************
1162	if ( !tp || !ts || !(ts->c_cflag & CREAD) ) {
1163	*****************************************************/
1164	if (!tp || !ts) {
1165		MoxaPortFlushData(ch->port, 0);
1166		return;
1167	}
1168	spin_lock_irqsave(&moxa_lock, flags);
1169	MoxaPortReadData(ch->port, tp);
1170	spin_unlock_irqrestore(&moxa_lock, flags);
1171	tty_schedule_flip(tp);
1172}
1173
1174#define Magic_code	0x404
1175
1176/*
1177 *    System Configuration
1178 */
1179/*
1180 *    for C218 BIOS initialization
1181 */
1182#define C218_ConfBase	0x800
1183#define C218_status	(C218_ConfBase + 0)	/* BIOS running status    */
1184#define C218_diag	(C218_ConfBase + 2)	/* diagnostic status      */
1185#define C218_key	(C218_ConfBase + 4)	/* WORD (0x218 for C218) */
1186#define C218DLoad_len	(C218_ConfBase + 6)	/* WORD           */
1187#define C218check_sum	(C218_ConfBase + 8)	/* BYTE           */
1188#define C218chksum_ok	(C218_ConfBase + 0x0a)	/* BYTE (1:ok)            */
1189#define C218_TestRx	(C218_ConfBase + 0x10)	/* 8 bytes for 8 ports    */
1190#define C218_TestTx	(C218_ConfBase + 0x18)	/* 8 bytes for 8 ports    */
1191#define C218_RXerr	(C218_ConfBase + 0x20)	/* 8 bytes for 8 ports    */
1192#define C218_ErrFlag	(C218_ConfBase + 0x28)	/* 8 bytes for 8 ports    */
1193
1194#define C218_LoadBuf	0x0F00
1195#define C218_KeyCode	0x218
1196#define CP204J_KeyCode	0x204
1197
1198/*
1199 *    for C320 BIOS initialization
1200 */
1201#define C320_ConfBase	0x800
1202#define C320_LoadBuf	0x0f00
1203#define STS_init	0x05	/* for C320_status        */
1204
1205#define C320_status	C320_ConfBase + 0	/* BIOS running status    */
1206#define C320_diag	C320_ConfBase + 2	/* diagnostic status      */
1207#define C320_key	C320_ConfBase + 4	/* WORD (0320H for C320) */
1208#define C320DLoad_len	C320_ConfBase + 6	/* WORD           */
1209#define C320check_sum	C320_ConfBase + 8	/* WORD           */
1210#define C320chksum_ok	C320_ConfBase + 0x0a	/* WORD (1:ok)            */
1211#define C320bapi_len	C320_ConfBase + 0x0c	/* WORD           */
1212#define C320UART_no	C320_ConfBase + 0x0e	/* WORD           */
1213
1214#define C320_KeyCode	0x320
1215
1216#define FixPage_addr	0x0000	/* starting addr of static page  */
1217#define DynPage_addr	0x2000	/* starting addr of dynamic page */
1218#define C218_start	0x3000	/* starting addr of C218 BIOS prg */
1219#define Control_reg	0x1ff0	/* select page and reset control */
1220#define HW_reset	0x80
1221
1222/*
1223 *    Function Codes
1224 */
1225#define FC_CardReset	0x80
1226#define FC_ChannelReset 1	/* C320 firmware not supported */
1227#define FC_EnableCH	2
1228#define FC_DisableCH	3
1229#define FC_SetParam	4
1230#define FC_SetMode	5
1231#define FC_SetRate	6
1232#define FC_LineControl	7
1233#define FC_LineStatus	8
1234#define FC_XmitControl	9
1235#define FC_FlushQueue	10
1236#define FC_SendBreak	11
1237#define FC_StopBreak	12
1238#define FC_LoopbackON	13
1239#define FC_LoopbackOFF	14
1240#define FC_ClrIrqTable	15
1241#define FC_SendXon	16
1242#define FC_SetTermIrq	17	/* C320 firmware not supported */
1243#define FC_SetCntIrq	18	/* C320 firmware not supported */
1244#define FC_SetBreakIrq	19
1245#define FC_SetLineIrq	20
1246#define FC_SetFlowCtl	21
1247#define FC_GenIrq	22
1248#define FC_InCD180	23
1249#define FC_OutCD180	24
1250#define FC_InUARTreg	23
1251#define FC_OutUARTreg	24
1252#define FC_SetXonXoff	25
1253#define FC_OutCD180CCR	26
1254#define FC_ExtIQueue	27
1255#define FC_ExtOQueue	28
1256#define FC_ClrLineIrq	29
1257#define FC_HWFlowCtl	30
1258#define FC_GetClockRate 35
1259#define FC_SetBaud	36
1260#define FC_SetDataMode  41
1261#define FC_GetCCSR      43
1262#define FC_GetDataError 45
1263#define FC_RxControl	50
1264#define FC_ImmSend	51
1265#define FC_SetXonState	52
1266#define FC_SetXoffState	53
1267#define FC_SetRxFIFOTrig 54
1268#define FC_SetTxFIFOCnt 55
1269#define FC_UnixRate	56
1270#define FC_UnixResetTimer 57
1271
1272#define	RxFIFOTrig1	0
1273#define	RxFIFOTrig4	1
1274#define	RxFIFOTrig8	2
1275#define	RxFIFOTrig14	3
1276
1277/*
1278 *    Dual-Ported RAM
1279 */
1280#define DRAM_global	0
1281#define INT_data	(DRAM_global + 0)
1282#define Config_base	(DRAM_global + 0x108)
1283
1284#define IRQindex	(INT_data + 0)
1285#define IRQpending	(INT_data + 4)
1286#define IRQtable	(INT_data + 8)
1287
1288/*
1289 *    Interrupt Status
1290 */
1291#define IntrRx		0x01	/* receiver data O.K.             */
1292#define IntrTx		0x02	/* transmit buffer empty  */
1293#define IntrFunc	0x04	/* function complete              */
1294#define IntrBreak	0x08	/* received break         */
1295#define IntrLine	0x10	/* line status change
1296				   for transmitter                */
1297#define IntrIntr	0x20	/* received INTR code             */
1298#define IntrQuit	0x40	/* received QUIT code             */
1299#define IntrEOF 	0x80	/* received EOF code              */
1300
1301#define IntrRxTrigger 	0x100	/* rx data count reach tigger value */
1302#define IntrTxTrigger 	0x200	/* tx data count below trigger value */
1303
1304#define Magic_no	(Config_base + 0)
1305#define Card_model_no	(Config_base + 2)
1306#define Total_ports	(Config_base + 4)
1307#define Module_cnt	(Config_base + 8)
1308#define Module_no	(Config_base + 10)
1309#define Timer_10ms	(Config_base + 14)
1310#define Disable_IRQ	(Config_base + 20)
1311#define TMS320_PORT1	(Config_base + 22)
1312#define TMS320_PORT2	(Config_base + 24)
1313#define TMS320_CLOCK	(Config_base + 26)
1314
1315/*
1316 *    DATA BUFFER in DRAM
1317 */
1318#define Extern_table	0x400	/* Base address of the external table
1319				   (24 words *    64) total 3K bytes
1320				   (24 words * 128) total 6K bytes */
1321#define Extern_size	0x60	/* 96 bytes                       */
1322#define RXrptr		0x00	/* read pointer for RX buffer     */
1323#define RXwptr		0x02	/* write pointer for RX buffer    */
1324#define TXrptr		0x04	/* read pointer for TX buffer     */
1325#define TXwptr		0x06	/* write pointer for TX buffer    */
1326#define HostStat	0x08	/* IRQ flag and general flag      */
1327#define FlagStat	0x0A
1328#define FlowControl	0x0C	/* B7 B6 B5 B4 B3 B2 B1 B0              */
1329					/*  x  x  x  x  |  |  |  |            */
1330					/*              |  |  |  + CTS flow   */
1331					/*              |  |  +--- RTS flow   */
1332					/*              |  +------ TX Xon/Xoff */
1333					/*              +--------- RX Xon/Xoff */
1334#define Break_cnt	0x0E	/* received break count   */
1335#define CD180TXirq	0x10	/* if non-0: enable TX irq        */
1336#define RX_mask 	0x12
1337#define TX_mask 	0x14
1338#define Ofs_rxb 	0x16
1339#define Ofs_txb 	0x18
1340#define Page_rxb	0x1A
1341#define Page_txb	0x1C
1342#define EndPage_rxb	0x1E
1343#define EndPage_txb	0x20
1344#define Data_error	0x22
1345#define RxTrigger	0x28
1346#define TxTrigger	0x2a
1347
1348#define rRXwptr 	0x34
1349#define Low_water	0x36
1350
1351#define FuncCode	0x40
1352#define FuncArg 	0x42
1353#define FuncArg1	0x44
1354
1355#define C218rx_size	0x2000	/* 8K bytes */
1356#define C218tx_size	0x8000	/* 32K bytes */
1357
1358#define C218rx_mask	(C218rx_size - 1)
1359#define C218tx_mask	(C218tx_size - 1)
1360
1361#define C320p8rx_size	0x2000
1362#define C320p8tx_size	0x8000
1363#define C320p8rx_mask	(C320p8rx_size - 1)
1364#define C320p8tx_mask	(C320p8tx_size - 1)
1365
1366#define C320p16rx_size	0x2000
1367#define C320p16tx_size	0x4000
1368#define C320p16rx_mask	(C320p16rx_size - 1)
1369#define C320p16tx_mask	(C320p16tx_size - 1)
1370
1371#define C320p24rx_size	0x2000
1372#define C320p24tx_size	0x2000
1373#define C320p24rx_mask	(C320p24rx_size - 1)
1374#define C320p24tx_mask	(C320p24tx_size - 1)
1375
1376#define C320p32rx_size	0x1000
1377#define C320p32tx_size	0x1000
1378#define C320p32rx_mask	(C320p32rx_size - 1)
1379#define C320p32tx_mask	(C320p32tx_size - 1)
1380
1381#define Page_size	0x2000
1382#define Page_mask	(Page_size - 1)
1383#define C218rx_spage	3
1384#define C218tx_spage	4
1385#define C218rx_pageno	1
1386#define C218tx_pageno	4
1387#define C218buf_pageno	5
1388
1389#define C320p8rx_spage	3
1390#define C320p8tx_spage	4
1391#define C320p8rx_pgno	1
1392#define C320p8tx_pgno	4
1393#define C320p8buf_pgno	5
1394
1395#define C320p16rx_spage 3
1396#define C320p16tx_spage 4
1397#define C320p16rx_pgno	1
1398#define C320p16tx_pgno	2
1399#define C320p16buf_pgno 3
1400
1401#define C320p24rx_spage 3
1402#define C320p24tx_spage 4
1403#define C320p24rx_pgno	1
1404#define C320p24tx_pgno	1
1405#define C320p24buf_pgno 2
1406
1407#define C320p32rx_spage 3
1408#define C320p32tx_ofs	C320p32rx_size
1409#define C320p32tx_spage 3
1410#define C320p32buf_pgno 1
1411
1412/*
1413 *    Host Status
1414 */
1415#define WakeupRx	0x01
1416#define WakeupTx	0x02
1417#define WakeupBreak	0x08
1418#define WakeupLine	0x10
1419#define WakeupIntr	0x20
1420#define WakeupQuit	0x40
1421#define WakeupEOF	0x80	/* used in VTIME control */
1422#define WakeupRxTrigger	0x100
1423#define WakeupTxTrigger	0x200
1424/*
1425 *    Flag status
1426 */
1427#define Rx_over		0x01
1428#define Xoff_state	0x02
1429#define Tx_flowOff	0x04
1430#define Tx_enable	0x08
1431#define CTS_state	0x10
1432#define DSR_state	0x20
1433#define DCD_state	0x80
1434/*
1435 *    FlowControl
1436 */
1437#define CTS_FlowCtl	1
1438#define RTS_FlowCtl	2
1439#define Tx_FlowCtl	4
1440#define Rx_FlowCtl	8
1441#define IXM_IXANY	0x10
1442
1443#define LowWater	128
1444
1445#define DTR_ON		1
1446#define RTS_ON		2
1447#define CTS_ON		1
1448#define DSR_ON		2
1449#define DCD_ON		8
1450
1451/* mode definition */
1452#define	MX_CS8		0x03
1453#define	MX_CS7		0x02
1454#define	MX_CS6		0x01
1455#define	MX_CS5		0x00
1456
1457#define	MX_STOP1	0x00
1458#define	MX_STOP15	0x04
1459#define	MX_STOP2	0x08
1460
1461#define	MX_PARNONE	0x00
1462#define	MX_PAREVEN	0x40
1463#define	MX_PARODD	0xC0
1464
1465/*
1466 *    Query
1467 */
1468#define QueryPort	MAX_PORTS
1469
1470
1471
1472struct mon_str {
1473	int tick;
1474	int rxcnt[MAX_PORTS];
1475	int txcnt[MAX_PORTS];
1476};
1477typedef struct mon_str mon_st;
1478
1479#define 	DCD_changed	0x01
1480#define 	DCD_oldstate	0x80
1481
1482static unsigned char moxaBuff[10240];
1483static void __iomem *moxaIntNdx[MAX_BOARDS];
1484static void __iomem *moxaIntPend[MAX_BOARDS];
1485static void __iomem *moxaIntTable[MAX_BOARDS];
1486static char moxaChkPort[MAX_PORTS];
1487static char moxaLineCtrl[MAX_PORTS];
1488static void __iomem *moxaTableAddr[MAX_PORTS];
1489static long moxaCurBaud[MAX_PORTS];
1490static char moxaDCDState[MAX_PORTS];
1491static char moxaLowChkFlag[MAX_PORTS];
1492static int moxaLowWaterChk;
1493static int moxaCard;
1494static mon_st moxaLog;
1495static int moxaFuncTout;
1496static ushort moxaBreakCnt[MAX_PORTS];
1497
1498static void moxadelay(int);
1499static void moxafunc(void __iomem *, int, ushort);
1500static void wait_finish(void __iomem *);
1501static void low_water_check(void __iomem *);
1502static int moxaloadbios(int, unsigned char __user *, int);
1503static int moxafindcard(int);
1504static int moxaload320b(int, unsigned char __user *, int);
1505static int moxaloadcode(int, unsigned char __user *, int);
1506static int moxaloadc218(int, void __iomem *, int);
1507static int moxaloadc320(int, void __iomem *, int, int *);
1508
1509/*****************************************************************************
1510 *	Driver level functions: 					     *
1511 *	1. MoxaDriverInit(void);					     *
1512 *	2. MoxaDriverIoctl(unsigned int cmd, unsigned long arg, int port);   *
1513 *	3. MoxaDriverPoll(void);					     *
1514 *****************************************************************************/
1515void MoxaDriverInit(void)
1516{
1517	int i;
1518
1519	moxaFuncTout = HZ / 2;	/* 500 mini-seconds */
1520	moxaCard = 0;
1521	moxaLog.tick = 0;
1522	moxaLowWaterChk = 0;
1523	for (i = 0; i < MAX_PORTS; i++) {
1524		moxaChkPort[i] = 0;
1525		moxaLowChkFlag[i] = 0;
1526		moxaLineCtrl[i] = 0;
1527		moxaLog.rxcnt[i] = 0;
1528		moxaLog.txcnt[i] = 0;
1529	}
1530}
1531
1532#define	MOXA		0x400
1533#define MOXA_GET_IQUEUE 	(MOXA + 1)	/* get input buffered count */
1534#define MOXA_GET_OQUEUE 	(MOXA + 2)	/* get output buffered count */
1535#define MOXA_INIT_DRIVER	(MOXA + 6)	/* moxaCard=0 */
1536#define MOXA_LOAD_BIOS		(MOXA + 9)	/* download BIOS */
1537#define MOXA_FIND_BOARD		(MOXA + 10)	/* Check if MOXA card exist? */
1538#define MOXA_LOAD_C320B		(MOXA + 11)	/* download 320B firmware */
1539#define MOXA_LOAD_CODE		(MOXA + 12)	/* download firmware */
1540#define MOXA_GETDATACOUNT       (MOXA + 23)
1541#define MOXA_GET_IOQUEUE	(MOXA + 27)
1542#define MOXA_FLUSH_QUEUE	(MOXA + 28)
1543#define MOXA_GET_CONF		(MOXA + 35)	/* configuration */
1544#define MOXA_GET_MAJOR          (MOXA + 63)
1545#define MOXA_GET_CUMAJOR        (MOXA + 64)
1546#define MOXA_GETMSTATUS         (MOXA + 65)
1547
1548
1549struct moxaq_str {
1550	int inq;
1551	int outq;
1552};
1553
1554struct dl_str {
1555	char __user *buf;
1556	int len;
1557	int cardno;
1558};
1559
1560static struct moxaq_str temp_queue[MAX_PORTS];
1561static struct dl_str dltmp;
1562
1563void MoxaPortFlushData(int port, int mode)
1564{
1565	void __iomem *ofsAddr;
1566	if ((mode < 0) || (mode > 2))
1567		return;
1568	ofsAddr = moxaTableAddr[port];
1569	moxafunc(ofsAddr, FC_FlushQueue, mode);
1570	if (mode != 1) {
1571		moxaLowChkFlag[port] = 0;
1572		low_water_check(ofsAddr);
1573	}
1574}
1575
1576int MoxaDriverIoctl(unsigned int cmd, unsigned long arg, int port)
1577{
1578	int i;
1579	int status;
1580	int MoxaPortTxQueue(int), MoxaPortRxQueue(int);
1581	void __user *argp = (void __user *)arg;
1582
1583	if (port == QueryPort) {
1584		if ((cmd != MOXA_GET_CONF) && (cmd != MOXA_INIT_DRIVER) &&
1585		    (cmd != MOXA_LOAD_BIOS) && (cmd != MOXA_FIND_BOARD) && (cmd != MOXA_LOAD_C320B) &&
1586		 (cmd != MOXA_LOAD_CODE) && (cmd != MOXA_GETDATACOUNT) &&
1587		  (cmd != MOXA_GET_IOQUEUE) && (cmd != MOXA_GET_MAJOR) &&
1588		    (cmd != MOXA_GET_CUMAJOR) && (cmd != MOXA_GETMSTATUS))
1589			return (-EINVAL);
1590	}
1591	switch (cmd) {
1592	case MOXA_GET_CONF:
1593		if(copy_to_user(argp, &moxa_boards, MAX_BOARDS * sizeof(moxa_board_conf)))
1594			return -EFAULT;
1595		return (0);
1596	case MOXA_INIT_DRIVER:
1597		if ((int) arg == 0x404)
1598			MoxaDriverInit();
1599		return (0);
1600	case MOXA_GETDATACOUNT:
1601		moxaLog.tick = jiffies;
1602		if(copy_to_user(argp, &moxaLog, sizeof(mon_st)))
1603			return -EFAULT;
1604		return (0);
1605	case MOXA_FLUSH_QUEUE:
1606		MoxaPortFlushData(port, arg);
1607		return (0);
1608	case MOXA_GET_IOQUEUE:
1609		for (i = 0; i < MAX_PORTS; i++) {
1610			if (moxaChkPort[i]) {
1611				temp_queue[i].inq = MoxaPortRxQueue(i);
1612				temp_queue[i].outq = MoxaPortTxQueue(i);
1613			}
1614		}
1615		if(copy_to_user(argp, temp_queue, sizeof(struct moxaq_str) * MAX_PORTS))
1616			return -EFAULT;
1617		return (0);
1618	case MOXA_GET_OQUEUE:
1619		i = MoxaPortTxQueue(port);
1620		return put_user(i, (unsigned long __user *)argp);
1621	case MOXA_GET_IQUEUE:
1622		i = MoxaPortRxQueue(port);
1623		return put_user(i, (unsigned long __user *)argp);
1624	case MOXA_GET_MAJOR:
1625		if(copy_to_user(argp, &ttymajor, sizeof(int)))
1626			return -EFAULT;
1627		return 0;
1628	case MOXA_GET_CUMAJOR:
1629		i = 0;
1630		if(copy_to_user(argp, &i, sizeof(int)))
1631			return -EFAULT;
1632		return 0;
1633	case MOXA_GETMSTATUS:
1634		for (i = 0; i < MAX_PORTS; i++) {
1635			GMStatus[i].ri = 0;
1636			GMStatus[i].dcd = 0;
1637			GMStatus[i].dsr = 0;
1638			GMStatus[i].cts = 0;
1639			if (!moxaChkPort[i]) {
1640				continue;
1641			} else {
1642				status = MoxaPortLineStatus(moxaChannels[i].port);
1643				if (status & 1)
1644					GMStatus[i].cts = 1;
1645				if (status & 2)
1646					GMStatus[i].dsr = 1;
1647				if (status & 4)
1648					GMStatus[i].dcd = 1;
1649			}
1650
1651			if (!moxaChannels[i].tty || !moxaChannels[i].tty->termios)
1652				GMStatus[i].cflag = moxaChannels[i].cflag;
1653			else
1654				GMStatus[i].cflag = moxaChannels[i].tty->termios->c_cflag;
1655		}
1656		if(copy_to_user(argp, GMStatus, sizeof(struct mxser_mstatus) * MAX_PORTS))
1657			return -EFAULT;
1658		return 0;
1659	default:
1660		return (-ENOIOCTLCMD);
1661	case MOXA_LOAD_BIOS:
1662	case MOXA_FIND_BOARD:
1663	case MOXA_LOAD_C320B:
1664	case MOXA_LOAD_CODE:
1665		if (!capable(CAP_SYS_RAWIO))
1666			return -EPERM;
1667		break;
1668	}
1669
1670	if(copy_from_user(&dltmp, argp, sizeof(struct dl_str)))
1671		return -EFAULT;
1672	if(dltmp.cardno < 0 || dltmp.cardno >= MAX_BOARDS)
1673		return -EINVAL;
1674
1675	switch(cmd)
1676	{
1677	case MOXA_LOAD_BIOS:
1678		i = moxaloadbios(dltmp.cardno, dltmp.buf, dltmp.len);
1679		return (i);
1680	case MOXA_FIND_BOARD:
1681		return moxafindcard(dltmp.cardno);
1682	case MOXA_LOAD_C320B:
1683		moxaload320b(dltmp.cardno, dltmp.buf, dltmp.len);
1684	default: /* to keep gcc happy */
1685		return (0);
1686	case MOXA_LOAD_CODE:
1687		i = moxaloadcode(dltmp.cardno, dltmp.buf, dltmp.len);
1688		if (i == -1)
1689			return (-EFAULT);
1690		return (i);
1691
1692	}
1693}
1694
1695int MoxaDriverPoll(void)
1696{
1697	register ushort temp;
1698	register int card;
1699	void __iomem *ofsAddr;
1700	void __iomem *ip;
1701	int port, p, ports;
1702
1703	if (moxaCard == 0)
1704		return (-1);
1705	for (card = 0; card < MAX_BOARDS; card++) {
1706	        if (loadstat[card] == 0)
1707			continue;
1708		if ((ports = moxa_boards[card].numPorts) == 0)
1709			continue;
1710		if (readb(moxaIntPend[card]) == 0xff) {
1711			ip = moxaIntTable[card] + readb(moxaIntNdx[card]);
1712			p = card * MAX_PORTS_PER_BOARD;
1713			ports <<= 1;
1714			for (port = 0; port < ports; port += 2, p++) {
1715				if ((temp = readw(ip + port)) != 0) {
1716					writew(0, ip + port);
1717					ofsAddr = moxaTableAddr[p];
1718					if (temp & IntrTx)
1719						writew(readw(ofsAddr + HostStat) & ~WakeupTx, ofsAddr + HostStat);
1720					if (temp & IntrBreak) {
1721						moxaBreakCnt[p]++;
1722					}
1723					if (temp & IntrLine) {
1724						if (readb(ofsAddr + FlagStat) & DCD_state) {
1725							if ((moxaDCDState[p] & DCD_oldstate) == 0)
1726								moxaDCDState[p] = (DCD_oldstate |
1727										   DCD_changed);
1728						} else {
1729							if (moxaDCDState[p] & DCD_oldstate)
1730								moxaDCDState[p] = DCD_changed;
1731						}
1732					}
1733				}
1734			}
1735			writeb(0, moxaIntPend[card]);
1736		}
1737		if (moxaLowWaterChk) {
1738			p = card * MAX_PORTS_PER_BOARD;
1739			for (port = 0; port < ports; port++, p++) {
1740				if (moxaLowChkFlag[p]) {
1741					moxaLowChkFlag[p] = 0;
1742					ofsAddr = moxaTableAddr[p];
1743					low_water_check(ofsAddr);
1744				}
1745			}
1746		}
1747	}
1748	moxaLowWaterChk = 0;
1749	return (0);
1750}
1751
1752/*****************************************************************************
1753 *	Card level function:						     *
1754 *	1. MoxaPortsOfCard(int cardno); 				     *
1755 *****************************************************************************/
1756int MoxaPortsOfCard(int cardno)
1757{
1758
1759	if (moxa_boards[cardno].boardType == 0)
1760		return (0);
1761	return (moxa_boards[cardno].numPorts);
1762}
1763
1764/*****************************************************************************
1765 *	Port level functions:						     *
1766 *	1.  MoxaPortIsValid(int port);					     *
1767 *	2.  MoxaPortEnable(int port);					     *
1768 *	3.  MoxaPortDisable(int port);					     *
1769 *	4.  MoxaPortGetMaxBaud(int port);				     *
1770 *	5.  MoxaPortGetCurBaud(int port);				     *
1771 *	6.  MoxaPortSetBaud(int port, long baud);			     *
1772 *	7.  MoxaPortSetMode(int port, int databit, int stopbit, int parity); *
1773 *	8.  MoxaPortSetTermio(int port, unsigned char *termio); 	     *
1774 *	9.  MoxaPortGetLineOut(int port, int *dtrState, int *rtsState);      *
1775 *	10. MoxaPortLineCtrl(int port, int dtrState, int rtsState);	     *
1776 *	11. MoxaPortFlowCtrl(int port, int rts, int cts, int rx, int tx,int xany);    *
1777 *	12. MoxaPortLineStatus(int port);				     *
1778 *	13. MoxaPortDCDChange(int port);				     *
1779 *	14. MoxaPortDCDON(int port);					     *
1780 *	15. MoxaPortFlushData(int port, int mode);	                     *
1781 *	16. MoxaPortWriteData(int port, unsigned char * buffer, int length); *
1782 *	17. MoxaPortReadData(int port, struct tty_struct *tty); 	     *
1783 *	18. MoxaPortTxBufSize(int port);				     *
1784 *	19. MoxaPortRxBufSize(int port);				     *
1785 *	20. MoxaPortTxQueue(int port);					     *
1786 *	21. MoxaPortTxFree(int port);					     *
1787 *	22. MoxaPortRxQueue(int port);					     *
1788 *	23. MoxaPortRxFree(int port);					     *
1789 *	24. MoxaPortTxDisable(int port);				     *
1790 *	25. MoxaPortTxEnable(int port); 				     *
1791 *	26. MoxaPortGetBrkCnt(int port);				     *
1792 *	27. MoxaPortResetBrkCnt(int port);				     *
1793 *	28. MoxaPortSetXonXoff(int port, int xonValue, int xoffValue);	     *
1794 *	29. MoxaPortIsTxHold(int port); 				     *
1795 *	30. MoxaPortSendBreak(int port, int ticks);			     *
1796 *****************************************************************************/
1797/*
1798 *    Moxa Port Number Description:
1799 *
1800 *      MOXA serial driver supports up to 4 MOXA-C218/C320 boards. And,
1801 *      the port number using in MOXA driver functions will be 0 to 31 for
1802 *      first MOXA board, 32 to 63 for second, 64 to 95 for third and 96
1803 *      to 127 for fourth. For example, if you setup three MOXA boards,
1804 *      first board is C218, second board is C320-16 and third board is
1805 *      C320-32. The port number of first board (C218 - 8 ports) is from
1806 *      0 to 7. The port number of second board (C320 - 16 ports) is form
1807 *      32 to 47. The port number of third board (C320 - 32 ports) is from
1808 *      64 to 95. And those port numbers form 8 to 31, 48 to 63 and 96 to
1809 *      127 will be invalid.
1810 *
1811 *
1812 *      Moxa Functions Description:
1813 *
1814 *      Function 1:     Driver initialization routine, this routine must be
1815 *                      called when initialized driver.
1816 *      Syntax:
1817 *      void MoxaDriverInit();
1818 *
1819 *
1820 *      Function 2:     Moxa driver private IOCTL command processing.
1821 *      Syntax:
1822 *      int  MoxaDriverIoctl(unsigned int cmd, unsigned long arg, int port);
1823 *
1824 *           unsigned int cmd   : IOCTL command
1825 *           unsigned long arg  : IOCTL argument
1826 *           int port           : port number (0 - 127)
1827 *
1828 *           return:    0  (OK)
1829 *                      -EINVAL
1830 *                      -ENOIOCTLCMD
1831 *
1832 *
1833 *      Function 3:     Moxa driver polling process routine.
1834 *      Syntax:
1835 *      int  MoxaDriverPoll(void);
1836 *
1837 *           return:    0       ; polling O.K.
1838 *                      -1      : no any Moxa card.
1839 *
1840 *
1841 *      Function 4:     Get the ports of this card.
1842 *      Syntax:
1843 *      int  MoxaPortsOfCard(int cardno);
1844 *
1845 *           int cardno         : card number (0 - 3)
1846 *
1847 *           return:    0       : this card is invalid
1848 *                      8/16/24/32
1849 *
1850 *
1851 *      Function 5:     Check this port is valid or invalid
1852 *      Syntax:
1853 *      int  MoxaPortIsValid(int port);
1854 *           int port           : port number (0 - 127, ref port description)
1855 *
1856 *           return:    0       : this port is invalid
1857 *                      1       : this port is valid
1858 *
1859 *
1860 *      Function 6:     Enable this port to start Tx/Rx data.
1861 *      Syntax:
1862 *      void MoxaPortEnable(int port);
1863 *           int port           : port number (0 - 127)
1864 *
1865 *
1866 *      Function 7:     Disable this port
1867 *      Syntax:
1868 *      void MoxaPortDisable(int port);
1869 *           int port           : port number (0 - 127)
1870 *
1871 *
1872 *      Function 8:     Get the maximun available baud rate of this port.
1873 *      Syntax:
1874 *      long MoxaPortGetMaxBaud(int port);
1875 *           int port           : port number (0 - 127)
1876 *
1877 *           return:    0       : this port is invalid
1878 *                      38400/57600/115200 bps
1879 *
1880 *
1881 *      Function 9:     Get the current baud rate of this port.
1882 *      Syntax:
1883 *      long MoxaPortGetCurBaud(int port);
1884 *           int port           : port number (0 - 127)
1885 *
1886 *           return:    0       : this port is invalid
1887 *                      50 - 115200 bps
1888 *
1889 *
1890 *      Function 10:    Setting baud rate of this port.
1891 *      Syntax:
1892 *      long MoxaPortSetBaud(int port, long baud);
1893 *           int port           : port number (0 - 127)
1894 *           long baud          : baud rate (50 - 115200)
1895 *
1896 *           return:    0       : this port is invalid or baud < 50
1897 *                      50 - 115200 : the real baud rate set to the port, if
1898 *                                    the argument baud is large than maximun
1899 *                                    available baud rate, the real setting
1900 *                                    baud rate will be the maximun baud rate.
1901 *
1902 *
1903 *      Function 11:    Setting the data-bits/stop-bits/parity of this port
1904 *      Syntax:
1905 *      int  MoxaPortSetMode(int port, int databits, int stopbits, int parity);
1906 *           int port           : port number (0 - 127)
1907 *           int databits       : data bits (8/7/6/5)
1908 *           int stopbits       : stop bits (2/1/0, 0 show 1.5 stop bits)
1909 int parity     : parity (0:None,1:Odd,2:Even,3:Mark,4:Space)
1910 *
1911 *           return:    -1      : invalid parameter
1912 *                      0       : setting O.K.
1913 *
1914 *
1915 *      Function 12:    Configure the port.
1916 *      Syntax:
1917 *      int  MoxaPortSetTermio(int port, struct ktermios *termio, speed_t baud);
1918 *           int port           : port number (0 - 127)
1919 *           struct ktermios * termio : termio structure pointer
1920 *	     speed_t baud	: baud rate
1921 *
1922 *           return:    -1      : this port is invalid or termio == NULL
1923 *                      0       : setting O.K.
1924 *
1925 *
1926 *      Function 13:    Get the DTR/RTS state of this port.
1927 *      Syntax:
1928 *      int  MoxaPortGetLineOut(int port, int *dtrState, int *rtsState);
1929 *           int port           : port number (0 - 127)
1930 *           int * dtrState     : pointer to INT to receive the current DTR
1931 *                                state. (if NULL, this function will not
1932 *                                write to this address)
1933 *           int * rtsState     : pointer to INT to receive the current RTS
1934 *                                state. (if NULL, this function will not
1935 *                                write to this address)
1936 *
1937 *           return:    -1      : this port is invalid
1938 *                      0       : O.K.
1939 *
1940 *
1941 *      Function 14:    Setting the DTR/RTS output state of this port.
1942 *      Syntax:
1943 *      void MoxaPortLineCtrl(int port, int dtrState, int rtsState);
1944 *           int port           : port number (0 - 127)
1945 *           int dtrState       : DTR output state (0: off, 1: on)
1946 *           int rtsState       : RTS output state (0: off, 1: on)
1947 *
1948 *
1949 *      Function 15:    Setting the flow control of this port.
1950 *      Syntax:
1951 *      void MoxaPortFlowCtrl(int port, int rtsFlow, int ctsFlow, int rxFlow,
1952 *                            int txFlow,int xany);
1953 *           int port           : port number (0 - 127)
1954 *           int rtsFlow        : H/W RTS flow control (0: no, 1: yes)
1955 *           int ctsFlow        : H/W CTS flow control (0: no, 1: yes)
1956 *           int rxFlow         : S/W Rx XON/XOFF flow control (0: no, 1: yes)
1957 *           int txFlow         : S/W Tx XON/XOFF flow control (0: no, 1: yes)
1958 *           int xany           : S/W XANY flow control (0: no, 1: yes)
1959 *
1960 *
1961 *      Function 16:    Get ths line status of this port
1962 *      Syntax:
1963 *      int  MoxaPortLineStatus(int port);
1964 *           int port           : port number (0 - 127)
1965 *
1966 *           return:    Bit 0 - CTS state (0: off, 1: on)
1967 *                      Bit 1 - DSR state (0: off, 1: on)
1968 *                      Bit 2 - DCD state (0: off, 1: on)
1969 *
1970 *
1971 *      Function 17:    Check the DCD state has changed since the last read
1972 *                      of this function.
1973 *      Syntax:
1974 *      int  MoxaPortDCDChange(int port);
1975 *           int port           : port number (0 - 127)
1976 *
1977 *           return:    0       : no changed
1978 *                      1       : DCD has changed
1979 *
1980 *
1981 *      Function 18:    Check ths current DCD state is ON or not.
1982 *      Syntax:
1983 *      int  MoxaPortDCDON(int port);
1984 *           int port           : port number (0 - 127)
1985 *
1986 *           return:    0       : DCD off
1987 *                      1       : DCD on
1988 *
1989 *
1990 *      Function 19:    Flush the Rx/Tx buffer data of this port.
1991 *      Syntax:
1992 *      void MoxaPortFlushData(int port, int mode);
1993 *           int port           : port number (0 - 127)
1994 *           int mode
1995 *                      0       : flush the Rx buffer
1996 *                      1       : flush the Tx buffer
1997 *                      2       : flush the Rx and Tx buffer
1998 *
1999 *
2000 *      Function 20:    Write data.
2001 *      Syntax:
2002 *      int  MoxaPortWriteData(int port, unsigned char * buffer, int length);
2003 *           int port           : port number (0 - 127)
2004 *           unsigned char * buffer     : pointer to write data buffer.
2005 *           int length         : write data length
2006 *
2007 *           return:    0 - length      : real write data length
2008 *
2009 *
2010 *      Function 21:    Read data.
2011 *      Syntax:
2012 *      int  MoxaPortReadData(int port, struct tty_struct *tty);
2013 *           int port           : port number (0 - 127)
2014 *	     struct tty_struct *tty : tty for data
2015 *
2016 *           return:    0 - length      : real read data length
2017 *
2018 *
2019 *      Function 22:    Get the Tx buffer size of this port
2020 *      Syntax:
2021 *      int  MoxaPortTxBufSize(int port);
2022 *           int port           : port number (0 - 127)
2023 *
2024 *           return:    ..      : Tx buffer size
2025 *
2026 *
2027 *      Function 23:    Get the Rx buffer size of this port
2028 *      Syntax:
2029 *      int  MoxaPortRxBufSize(int port);
2030 *           int port           : port number (0 - 127)
2031 *
2032 *           return:    ..      : Rx buffer size
2033 *
2034 *
2035 *      Function 24:    Get the Tx buffer current queued data bytes
2036 *      Syntax:
2037 *      int  MoxaPortTxQueue(int port);
2038 *           int port           : port number (0 - 127)
2039 *
2040 *           return:    ..      : Tx buffer current queued data bytes
2041 *
2042 *
2043 *      Function 25:    Get the Tx buffer current free space
2044 *      Syntax:
2045 *      int  MoxaPortTxFree(int port);
2046 *           int port           : port number (0 - 127)
2047 *
2048 *           return:    ..      : Tx buffer current free space
2049 *
2050 *
2051 *      Function 26:    Get the Rx buffer current queued data bytes
2052 *      Syntax:
2053 *      int  MoxaPortRxQueue(int port);
2054 *           int port           : port number (0 - 127)
2055 *
2056 *           return:    ..      : Rx buffer current queued data bytes
2057 *
2058 *
2059 *      Function 27:    Get the Rx buffer current free space
2060 *      Syntax:
2061 *      int  MoxaPortRxFree(int port);
2062 *           int port           : port number (0 - 127)
2063 *
2064 *           return:    ..      : Rx buffer current free space
2065 *
2066 *
2067 *      Function 28:    Disable port data transmission.
2068 *      Syntax:
2069 *      void MoxaPortTxDisable(int port);
2070 *           int port           : port number (0 - 127)
2071 *
2072 *
2073 *      Function 29:    Enable port data transmission.
2074 *      Syntax:
2075 *      void MoxaPortTxEnable(int port);
2076 *           int port           : port number (0 - 127)
2077 *
2078 *
2079 *      Function 30:    Get the received BREAK signal count.
2080 *      Syntax:
2081 *      int  MoxaPortGetBrkCnt(int port);
2082 *           int port           : port number (0 - 127)
2083 *
2084 *           return:    0 - ..  : BREAK signal count
2085 *
2086 *
2087 *      Function 31:    Get the received BREAK signal count and reset it.
2088 *      Syntax:
2089 *      int  MoxaPortResetBrkCnt(int port);
2090 *           int port           : port number (0 - 127)
2091 *
2092 *           return:    0 - ..  : BREAK signal count
2093 *
2094 *
2095 *      Function 32:    Set the S/W flow control new XON/XOFF value, default
2096 *                      XON is 0x11 & XOFF is 0x13.
2097 *      Syntax:
2098 *      void MoxaPortSetXonXoff(int port, int xonValue, int xoffValue);
2099 *           int port           : port number (0 - 127)
2100 *           int xonValue       : new XON value (0 - 255)
2101 *           int xoffValue      : new XOFF value (0 - 255)
2102 *
2103 *
2104 *      Function 33:    Check this port's transmission is hold by remote site
2105 *                      because the flow control.
2106 *      Syntax:
2107 *      int  MoxaPortIsTxHold(int port);
2108 *           int port           : port number (0 - 127)
2109 *
2110 *           return:    0       : normal
2111 *                      1       : hold by remote site
2112 *
2113 *
2114 *      Function 34:    Send out a BREAK signal.
2115 *      Syntax:
2116 *      void MoxaPortSendBreak(int port, int ms100);
2117 *           int port           : port number (0 - 127)
2118 *           int ms100          : break signal time interval.
2119 *                                unit: 100 mini-second. if ms100 == 0, it will
2120 *                                send out a about 250 ms BREAK signal.
2121 *
2122 */
2123int MoxaPortIsValid(int port)
2124{
2125
2126	if (moxaCard == 0)
2127		return (0);
2128	if (moxaChkPort[port] == 0)
2129		return (0);
2130	return (1);
2131}
2132
2133void MoxaPortEnable(int port)
2134{
2135	void __iomem *ofsAddr;
2136	int MoxaPortLineStatus(int);
2137	short lowwater = 512;
2138
2139	ofsAddr = moxaTableAddr[port];
2140	writew(lowwater, ofsAddr + Low_water);
2141	moxaBreakCnt[port] = 0;
2142	if ((moxa_boards[port / MAX_PORTS_PER_BOARD].boardType == MOXA_BOARD_C320_ISA) ||
2143	    (moxa_boards[port / MAX_PORTS_PER_BOARD].boardType == MOXA_BOARD_C320_PCI)) {
2144		moxafunc(ofsAddr, FC_SetBreakIrq, 0);
2145	} else {
2146		writew(readw(ofsAddr + HostStat) | WakeupBreak, ofsAddr + HostStat);
2147	}
2148
2149	moxafunc(ofsAddr, FC_SetLineIrq, Magic_code);
2150	moxafunc(ofsAddr, FC_FlushQueue, 2);
2151
2152	moxafunc(ofsAddr, FC_EnableCH, Magic_code);
2153	MoxaPortLineStatus(port);
2154}
2155
2156void MoxaPortDisable(int port)
2157{
2158	void __iomem *ofsAddr = moxaTableAddr[port];
2159
2160	moxafunc(ofsAddr, FC_SetFlowCtl, 0);	/* disable flow control */
2161	moxafunc(ofsAddr, FC_ClrLineIrq, Magic_code);
2162	writew(0, ofsAddr + HostStat);
2163	moxafunc(ofsAddr, FC_DisableCH, Magic_code);
2164}
2165
2166long MoxaPortGetMaxBaud(int port)
2167{
2168	if ((moxa_boards[port / MAX_PORTS_PER_BOARD].boardType == MOXA_BOARD_C320_ISA) ||
2169	    (moxa_boards[port / MAX_PORTS_PER_BOARD].boardType == MOXA_BOARD_C320_PCI))
2170		return (460800L);
2171	else
2172		return (921600L);
2173}
2174
2175
2176long MoxaPortSetBaud(int port, long baud)
2177{
2178	void __iomem *ofsAddr;
2179	long max, clock;
2180	unsigned int val;
2181
2182	if ((baud < 50L) || ((max = MoxaPortGetMaxBaud(port)) == 0))
2183		return (0);
2184	ofsAddr = moxaTableAddr[port];
2185	if (baud > max)
2186		baud = max;
2187	if (max == 38400L)
2188		clock = 614400L;	/* for 9.8304 Mhz : max. 38400 bps */
2189	else if (max == 57600L)
2190		clock = 691200L;	/* for 11.0592 Mhz : max. 57600 bps */
2191	else
2192		clock = 921600L;	/* for 14.7456 Mhz : max. 115200 bps */
2193	val = clock / baud;
2194	moxafunc(ofsAddr, FC_SetBaud, val);
2195	baud = clock / val;
2196	moxaCurBaud[port] = baud;
2197	return (baud);
2198}
2199
2200int MoxaPortSetTermio(int port, struct ktermios *termio, speed_t baud)
2201{
2202	void __iomem *ofsAddr;
2203	tcflag_t cflag;
2204	tcflag_t mode = 0;
2205
2206	if (moxaChkPort[port] == 0 || termio == 0)
2207		return (-1);
2208	ofsAddr = moxaTableAddr[port];
2209	cflag = termio->c_cflag;	/* termio->c_cflag */
2210
2211	mode = termio->c_cflag & CSIZE;
2212	if (mode == CS5)
2213		mode = MX_CS5;
2214	else if (mode == CS6)
2215		mode = MX_CS6;
2216	else if (mode == CS7)
2217		mode = MX_CS7;
2218	else if (mode == CS8)
2219		mode = MX_CS8;
2220
2221	if (termio->c_cflag & CSTOPB) {
2222		if (mode == MX_CS5)
2223			mode |= MX_STOP15;
2224		else
2225			mode |= MX_STOP2;
2226	} else
2227		mode |= MX_STOP1;
2228
2229	if (termio->c_cflag & PARENB) {
2230		if (termio->c_cflag & PARODD)
2231			mode |= MX_PARODD;
2232		else
2233			mode |= MX_PAREVEN;
2234	} else
2235		mode |= MX_PARNONE;
2236
2237	moxafunc(ofsAddr, FC_SetDataMode, (ushort) mode);
2238
2239	if ((moxa_boards[port / MAX_PORTS_PER_BOARD].boardType == MOXA_BOARD_C320_ISA) ||
2240	    (moxa_boards[port / MAX_PORTS_PER_BOARD].boardType == MOXA_BOARD_C320_PCI)) {
2241		if (baud >= 921600L)
2242			return (-1);
2243	}
2244	MoxaPortSetBaud(port, baud);
2245
2246	if (termio->c_iflag & (IXON | IXOFF | IXANY)) {
2247		writeb(termio->c_cc[VSTART], ofsAddr + FuncArg);
2248		writeb(termio->c_cc[VSTOP], ofsAddr + FuncArg1);
2249		writeb(FC_SetXonXoff, ofsAddr + FuncCode);
2250		wait_finish(ofsAddr);
2251
2252	}
2253	return (0);
2254}
2255
2256int MoxaPortGetLineOut(int port, int *dtrState, int *rtsState)
2257{
2258
2259	if (!MoxaPortIsValid(port))
2260		return (-1);
2261	if (dtrState) {
2262		if (moxaLineCtrl[port] & DTR_ON)
2263			*dtrState = 1;
2264		else
2265			*dtrState = 0;
2266	}
2267	if (rtsState) {
2268		if (moxaLineCtrl[port] & RTS_ON)
2269			*rtsState = 1;
2270		else
2271			*rtsState = 0;
2272	}
2273	return (0);
2274}
2275
2276void MoxaPortLineCtrl(int port, int dtr, int rts)
2277{
2278	void __iomem *ofsAddr;
2279	int mode;
2280
2281	ofsAddr = moxaTableAddr[port];
2282	mode = 0;
2283	if (dtr)
2284		mode |= DTR_ON;
2285	if (rts)
2286		mode |= RTS_ON;
2287	moxaLineCtrl[port] = mode;
2288	moxafunc(ofsAddr, FC_LineControl, mode);
2289}
2290
2291void MoxaPortFlowCtrl(int port, int rts, int cts, int txflow, int rxflow, int txany)
2292{
2293	void __iomem *ofsAddr;
2294	int mode;
2295
2296	ofsAddr = moxaTableAddr[port];
2297	mode = 0;
2298	if (rts)
2299		mode |= RTS_FlowCtl;
2300	if (cts)
2301		mode |= CTS_FlowCtl;
2302	if (txflow)
2303		mode |= Tx_FlowCtl;
2304	if (rxflow)
2305		mode |= Rx_FlowCtl;
2306	if (txany)
2307		mode |= IXM_IXANY;
2308	moxafunc(ofsAddr, FC_SetFlowCtl, mode);
2309}
2310
2311int MoxaPortLineStatus(int port)
2312{
2313	void __iomem *ofsAddr;
2314	int val;
2315
2316	ofsAddr = moxaTableAddr[port];
2317	if ((moxa_boards[port / MAX_PORTS_PER_BOARD].boardType == MOXA_BOARD_C320_ISA) ||
2318	    (moxa_boards[port / MAX_PORTS_PER_BOARD].boardType == MOXA_BOARD_C320_PCI)) {
2319		moxafunc(ofsAddr, FC_LineStatus, 0);
2320		val = readw(ofsAddr + FuncArg);
2321	} else {
2322		val = readw(ofsAddr + FlagStat) >> 4;
2323	}
2324	val &= 0x0B;
2325	if (val & 8) {
2326		val |= 4;
2327		if ((moxaDCDState[port] & DCD_oldstate) == 0)
2328			moxaDCDState[port] = (DCD_oldstate | DCD_changed);
2329	} else {
2330		if (moxaDCDState[port] & DCD_oldstate)
2331			moxaDCDState[port] = DCD_changed;
2332	}
2333	val &= 7;
2334	return (val);
2335}
2336
2337int MoxaPortDCDChange(int port)
2338{
2339	int n;
2340
2341	if (moxaChkPort[port] == 0)
2342		return (0);
2343	n = moxaDCDState[port];
2344	moxaDCDState[port] &= ~DCD_changed;
2345	n &= DCD_changed;
2346	return (n);
2347}
2348
2349int MoxaPortDCDON(int port)
2350{
2351	int n;
2352
2353	if (moxaChkPort[port] == 0)
2354		return (0);
2355	if (moxaDCDState[port] & DCD_oldstate)
2356		n = 1;
2357	else
2358		n = 0;
2359	return (n);
2360}
2361
2362
2363/*
2364   int MoxaDumpMem(int port, unsigned char * buffer, int len)
2365   {
2366   int          i;
2367   unsigned long                baseAddr,ofsAddr,ofs;
2368
2369   baseAddr = moxaBaseAddr[port / MAX_PORTS_PER_BOARD];
2370   ofs = baseAddr + DynPage_addr + pageofs;
2371   if (len > 0x2000L)
2372   len = 0x2000L;
2373   for (i = 0; i < len; i++)
2374   buffer[i] = readb(ofs+i);
2375   }
2376 */
2377
2378
2379int MoxaPortWriteData(int port, unsigned char * buffer, int len)
2380{
2381	int c, total, i;
2382	ushort tail;
2383	int cnt;
2384	ushort head, tx_mask, spage, epage;
2385	ushort pageno, pageofs, bufhead;
2386	void __iomem *baseAddr, *ofsAddr, *ofs;
2387
2388	ofsAddr = moxaTableAddr[port];
2389	baseAddr = moxaBaseAddr[port / MAX_PORTS_PER_BOARD];
2390	tx_mask = readw(ofsAddr + TX_mask);
2391	spage = readw(ofsAddr + Page_txb);
2392	epage = readw(ofsAddr + EndPage_txb);
2393	tail = readw(ofsAddr + TXwptr);
2394	head = readw(ofsAddr + TXrptr);
2395	c = (head > tail) ? (head - tail - 1)
2396	    : (head - tail + tx_mask);
2397	if (c > len)
2398		c = len;
2399	moxaLog.txcnt[port] += c;
2400	total = c;
2401	if (spage == epage) {
2402		bufhead = readw(ofsAddr + Ofs_txb);
2403		writew(spage, baseAddr + Control_reg);
2404		while (c > 0) {
2405			if (head > tail)
2406				len = head - tail - 1;
2407			else
2408				len = tx_mask + 1 - tail;
2409			len = (c > len) ? len : c;
2410			ofs = baseAddr + DynPage_addr + bufhead + tail;
2411			for (i = 0; i < len; i++)
2412				writeb(*buffer++, ofs + i);
2413			tail = (tail + len) & tx_mask;
2414			c -= len;
2415		}
2416		writew(tail, ofsAddr + TXwptr);
2417	} else {
2418		len = c;
2419		pageno = spage + (tail >> 13);
2420		pageofs = tail & Page_mask;
2421		do {
2422			cnt = Page_size - pageofs;
2423			if (cnt > c)
2424				cnt = c;
2425			c -= cnt;
2426			writeb(pageno, baseAddr + Control_reg);
2427			ofs = baseAddr + DynPage_addr + pageofs;
2428			for (i = 0; i < cnt; i++)
2429				writeb(*buffer++, ofs + i);
2430			if (c == 0) {
2431				writew((tail + len) & tx_mask, ofsAddr + TXwptr);
2432				break;
2433			}
2434			if (++pageno == epage)
2435				pageno = spage;
2436			pageofs = 0;
2437		} while (1);
2438	}
2439	writeb(1, ofsAddr + CD180TXirq);	/* start to send */
2440	return (total);
2441}
2442
2443int MoxaPortReadData(int port, struct tty_struct *tty)
2444{
2445	register ushort head, pageofs;
2446	int i, count, cnt, len, total, remain;
2447	ushort tail, rx_mask, spage, epage;
2448	ushort pageno, bufhead;
2449	void __iomem *baseAddr, *ofsAddr, *ofs;
2450
2451	ofsAddr = moxaTableAddr[port];
2452	baseAddr = moxaBaseAddr[port / MAX_PORTS_PER_BOARD];
2453	head = readw(ofsAddr + RXrptr);
2454	tail = readw(ofsAddr + RXwptr);
2455	rx_mask = readw(ofsAddr + RX_mask);
2456	spage = readw(ofsAddr + Page_rxb);
2457	epage = readw(ofsAddr + EndPage_rxb);
2458	count = (tail >= head) ? (tail - head)
2459	    : (tail - head + rx_mask + 1);
2460	if (count == 0)
2461		return 0;
2462
2463	total = count;
2464	remain = count - total;
2465	moxaLog.rxcnt[port] += total;
2466	count = total;
2467	if (spage == epage) {
2468		bufhead = readw(ofsAddr + Ofs_rxb);
2469		writew(spage, baseAddr + Control_reg);
2470		while (count > 0) {
2471			if (tail >= head)
2472				len = tail - head;
2473			else
2474				len = rx_mask + 1 - head;
2475			len = (count > len) ? len : count;
2476			ofs = baseAddr + DynPage_addr + bufhead + head;
2477			for (i = 0; i < len; i++)
2478				tty_insert_flip_char(tty, readb(ofs + i), TTY_NORMAL);
2479			head = (head + len) & rx_mask;
2480			count -= len;
2481		}
2482		writew(head, ofsAddr + RXrptr);
2483	} else {
2484		len = count;
2485		pageno = spage + (head >> 13);
2486		pageofs = head & Page_mask;
2487		do {
2488			cnt = Page_size - pageofs;
2489			if (cnt > count)
2490				cnt = count;
2491			count -= cnt;
2492			writew(pageno, baseAddr + Control_reg);
2493			ofs = baseAddr + DynPage_addr + pageofs;
2494			for (i = 0; i < cnt; i++)
2495				tty_insert_flip_char(tty, readb(ofs + i), TTY_NORMAL);
2496			if (count == 0) {
2497				writew((head + len) & rx_mask, ofsAddr + RXrptr);
2498				break;
2499			}
2500			if (++pageno == epage)
2501				pageno = spage;
2502			pageofs = 0;
2503		} while (1);
2504	}
2505	if ((readb(ofsAddr + FlagStat) & Xoff_state) && (remain < LowWater)) {
2506		moxaLowWaterChk = 1;
2507		moxaLowChkFlag[port] = 1;
2508	}
2509	return (total);
2510}
2511
2512
2513int MoxaPortTxQueue(int port)
2514{
2515	void __iomem *ofsAddr;
2516	ushort rptr, wptr, mask;
2517	int len;
2518
2519	ofsAddr = moxaTableAddr[port];
2520	rptr = readw(ofsAddr + TXrptr);
2521	wptr = readw(ofsAddr + TXwptr);
2522	mask = readw(ofsAddr + TX_mask);
2523	len = (wptr - rptr) & mask;
2524	return (len);
2525}
2526
2527int MoxaPortTxFree(int port)
2528{
2529	void __iomem *ofsAddr;
2530	ushort rptr, wptr, mask;
2531	int len;
2532
2533	ofsAddr = moxaTableAddr[port];
2534	rptr = readw(ofsAddr + TXrptr);
2535	wptr = readw(ofsAddr + TXwptr);
2536	mask = readw(ofsAddr + TX_mask);
2537	len = mask - ((wptr - rptr) & mask);
2538	return (len);
2539}
2540
2541int MoxaPortRxQueue(int port)
2542{
2543	void __iomem *ofsAddr;
2544	ushort rptr, wptr, mask;
2545	int len;
2546
2547	ofsAddr = moxaTableAddr[port];
2548	rptr = readw(ofsAddr + RXrptr);
2549	wptr = readw(ofsAddr + RXwptr);
2550	mask = readw(ofsAddr + RX_mask);
2551	len = (wptr - rptr) & mask;
2552	return (len);
2553}
2554
2555
2556void MoxaPortTxDisable(int port)
2557{
2558	void __iomem *ofsAddr;
2559
2560	ofsAddr = moxaTableAddr[port];
2561	moxafunc(ofsAddr, FC_SetXoffState, Magic_code);
2562}
2563
2564void MoxaPortTxEnable(int port)
2565{
2566	void __iomem *ofsAddr;
2567
2568	ofsAddr = moxaTableAddr[port];
2569	moxafunc(ofsAddr, FC_SetXonState, Magic_code);
2570}
2571
2572
2573int MoxaPortResetBrkCnt(int port)
2574{
2575	ushort cnt;
2576	cnt = moxaBreakCnt[port];
2577	moxaBreakCnt[port] = 0;
2578	return (cnt);
2579}
2580
2581
2582void MoxaPortSendBreak(int port, int ms100)
2583{
2584	void __iomem *ofsAddr;
2585
2586	ofsAddr = moxaTableAddr[port];
2587	if (ms100) {
2588		moxafunc(ofsAddr, FC_SendBreak, Magic_code);
2589		moxadelay(ms100 * (HZ / 10));
2590	} else {
2591		moxafunc(ofsAddr, FC_SendBreak, Magic_code);
2592		moxadelay(HZ / 4);	/* 250 ms */
2593	}
2594	moxafunc(ofsAddr, FC_StopBreak, Magic_code);
2595}
2596
2597static int moxa_get_serial_info(struct moxa_str *info,
2598				struct serial_struct __user *retinfo)
2599{
2600	struct serial_struct tmp;
2601
2602	memset(&tmp, 0, sizeof(tmp));
2603	tmp.type = info->type;
2604	tmp.line = info->port;
2605	tmp.port = 0;
2606	tmp.irq = 0;
2607	tmp.flags = info->asyncflags;
2608	tmp.baud_base = 921600;
2609	tmp.close_delay = info->close_delay;
2610	tmp.closing_wait = info->closing_wait;
2611	tmp.custom_divisor = 0;
2612	tmp.hub6 = 0;
2613	if(copy_to_user(retinfo, &tmp, sizeof(*retinfo)))
2614		return -EFAULT;
2615	return (0);
2616}
2617
2618
2619static int moxa_set_serial_info(struct moxa_str *info,
2620				struct serial_struct __user *new_info)
2621{
2622	struct serial_struct new_serial;
2623
2624	if(copy_from_user(&new_serial, new_info, sizeof(new_serial)))
2625		return -EFAULT;
2626
2627	if ((new_serial.irq != 0) ||
2628	    (new_serial.port != 0) ||
2629//           (new_serial.type != info->type) ||
2630	    (new_serial.custom_divisor != 0) ||
2631	    (new_serial.baud_base != 921600))
2632		return (-EPERM);
2633
2634	if (!capable(CAP_SYS_ADMIN)) {
2635		if (((new_serial.flags & ~ASYNC_USR_MASK) !=
2636		     (info->asyncflags & ~ASYNC_USR_MASK)))
2637			return (-EPERM);
2638	} else {
2639		info->close_delay = new_serial.close_delay * HZ / 100;
2640		info->closing_wait = new_serial.closing_wait * HZ / 100;
2641	}
2642
2643	new_serial.flags = (new_serial.flags & ~ASYNC_FLAGS);
2644	new_serial.flags |= (info->asyncflags & ASYNC_FLAGS);
2645
2646	if (new_serial.type == PORT_16550A) {
2647		MoxaSetFifo(info->port, 1);
2648	} else {
2649		MoxaSetFifo(info->port, 0);
2650	}
2651
2652	info->type = new_serial.type;
2653	return (0);
2654}
2655
2656
2657
2658/*****************************************************************************
2659 *	Static local functions: 					     *
2660 *****************************************************************************/
2661/*
2662 * moxadelay - delays a specified number ticks
2663 */
2664static void moxadelay(int tick)
2665{
2666	unsigned long st, et;
2667
2668	st = jiffies;
2669	et = st + tick;
2670	while (time_before(jiffies, et));
2671}
2672
2673static void moxafunc(void __iomem *ofsAddr, int cmd, ushort arg)
2674{
2675
2676	writew(arg, ofsAddr + FuncArg);
2677	writew(cmd, ofsAddr + FuncCode);
2678	wait_finish(ofsAddr);
2679}
2680
2681static void wait_finish(void __iomem *ofsAddr)
2682{
2683	unsigned long i, j;
2684
2685	i = jiffies;
2686	while (readw(ofsAddr + FuncCode) != 0) {
2687		j = jiffies;
2688		if ((j - i) > moxaFuncTout) {
2689			return;
2690		}
2691	}
2692}
2693
2694static void low_water_check(void __iomem *ofsAddr)
2695{
2696	int len;
2697	ushort rptr, wptr, mask;
2698
2699	if (readb(ofsAddr + FlagStat) & Xoff_state) {
2700		rptr = readw(ofsAddr + RXrptr);
2701		wptr = readw(ofsAddr + RXwptr);
2702		mask = readw(ofsAddr + RX_mask);
2703		len = (wptr - rptr) & mask;
2704		if (len <= Low_water)
2705			moxafunc(ofsAddr, FC_SendXon, 0);
2706	}
2707}
2708
2709static int moxaloadbios(int cardno, unsigned char __user *tmp, int len)
2710{
2711	void __iomem *baseAddr;
2712	int i;
2713
2714	if(copy_from_user(moxaBuff, tmp, len))
2715		return -EFAULT;
2716	baseAddr = moxaBaseAddr[cardno];
2717	writeb(HW_reset, baseAddr + Control_reg);	/* reset */
2718	moxadelay(1);		/* delay 10 ms */
2719	for (i = 0; i < 4096; i++)
2720		writeb(0, baseAddr + i);	/* clear fix page */
2721	for (i = 0; i < len; i++)
2722		writeb(moxaBuff[i], baseAddr + i);	/* download BIOS */
2723	writeb(0, baseAddr + Control_reg);	/* restart */
2724	return (0);
2725}
2726
2727static int moxafindcard(int cardno)
2728{
2729	void __iomem *baseAddr;
2730	ushort tmp;
2731
2732	baseAddr = moxaBaseAddr[cardno];
2733	switch (moxa_boards[cardno].boardType) {
2734	case MOXA_BOARD_C218_ISA:
2735	case MOXA_BOARD_C218_PCI:
2736		if ((tmp = readw(baseAddr + C218_key)) != C218_KeyCode) {
2737			return (-1);
2738		}
2739		break;
2740	case MOXA_BOARD_CP204J:
2741		if ((tmp = readw(baseAddr + C218_key)) != CP204J_KeyCode) {
2742			return (-1);
2743		}
2744		break;
2745	default:
2746		if ((tmp = readw(baseAddr + C320_key)) != C320_KeyCode) {
2747			return (-1);
2748		}
2749		if ((tmp = readw(baseAddr + C320_status)) != STS_init) {
2750			return (-2);
2751		}
2752	}
2753	return (0);
2754}
2755
2756static int moxaload320b(int cardno, unsigned char __user *tmp, int len)
2757{
2758	void __iomem *baseAddr;
2759	int i;
2760
2761	if(len > sizeof(moxaBuff))
2762		return -EINVAL;
2763	if(copy_from_user(moxaBuff, tmp, len))
2764		return -EFAULT;
2765	baseAddr = moxaBaseAddr[cardno];
2766	writew(len - 7168 - 2, baseAddr + C320bapi_len);
2767	writeb(1, baseAddr + Control_reg);	/* Select Page 1 */
2768	for (i = 0; i < 7168; i++)
2769		writeb(moxaBuff[i], baseAddr + DynPage_addr + i);
2770	writeb(2, baseAddr + Control_reg);	/* Select Page 2 */
2771	for (i = 0; i < (len - 7168); i++)
2772		writeb(moxaBuff[i + 7168], baseAddr + DynPage_addr + i);
2773	return (0);
2774}
2775
2776static int moxaloadcode(int cardno, unsigned char __user *tmp, int len)
2777{
2778	void __iomem *baseAddr, *ofsAddr;
2779	int retval, port, i;
2780
2781	if(copy_from_user(moxaBuff, tmp, len))
2782		return -EFAULT;
2783	baseAddr = moxaBaseAddr[cardno];
2784	switch (moxa_boards[cardno].boardType) {
2785	case MOXA_BOARD_C218_ISA:
2786	case MOXA_BOARD_C218_PCI:
2787	case MOXA_BOARD_CP204J:
2788		retval = moxaloadc218(cardno, baseAddr, len);
2789		if (retval)
2790			return (retval);
2791		port = cardno * MAX_PORTS_PER_BOARD;
2792		for (i = 0; i < moxa_boards[cardno].numPorts; i++, port++) {
2793			moxaChkPort[port] = 1;
2794			moxaCurBaud[port] = 9600L;
2795			moxaDCDState[port] = 0;
2796			moxaTableAddr[port] = baseAddr + Extern_table + Extern_size * i;
2797			ofsAddr = moxaTableAddr[port];
2798			writew(C218rx_mask, ofsAddr + RX_mask);
2799			writew(C218tx_mask, ofsAddr + TX_mask);
2800			writew(C218rx_spage + i * C218buf_pageno, ofsAddr + Page_rxb);
2801			writew(readw(ofsAddr + Page_rxb) + C218rx_pageno, ofsAddr + EndPage_rxb);
2802
2803			writew(C218tx_spage + i * C218buf_pageno, ofsAddr + Page_txb);
2804			writew(readw(ofsAddr + Page_txb) + C218tx_pageno, ofsAddr + EndPage_txb);
2805
2806		}
2807		break;
2808	default:
2809		retval = moxaloadc320(cardno, baseAddr, len,
2810				      &moxa_boards[cardno].numPorts);
2811		if (retval)
2812			return (retval);
2813		port = cardno * MAX_PORTS_PER_BOARD;
2814		for (i = 0; i < moxa_boards[cardno].numPorts; i++, port++) {
2815			moxaChkPort[port] = 1;
2816			moxaCurBaud[port] = 9600L;
2817			moxaDCDState[port] = 0;
2818			moxaTableAddr[port] = baseAddr + Extern_table + Extern_size * i;
2819			ofsAddr = moxaTableAddr[port];
2820			if (moxa_boards[cardno].numPorts == 8) {
2821				writew(C320p8rx_mask, ofsAddr + RX_mask);
2822				writew(C320p8tx_mask, ofsAddr + TX_mask);
2823				writew(C320p8rx_spage + i * C320p8buf_pgno, ofsAddr + Page_rxb);
2824				writew(readw(ofsAddr + Page_rxb) + C320p8rx_pgno, ofsAddr + EndPage_rxb);
2825				writew(C320p8tx_spage + i * C320p8buf_pgno, ofsAddr + Page_txb);
2826				writew(readw(ofsAddr + Page_txb) + C320p8tx_pgno, ofsAddr + EndPage_txb);
2827
2828			} else if (moxa_boards[cardno].numPorts == 16) {
2829				writew(C320p16rx_mask, ofsAddr + RX_mask);
2830				writew(C320p16tx_mask, ofsAddr + TX_mask);
2831				writew(C320p16rx_spage + i * C320p16buf_pgno, ofsAddr + Page_rxb);
2832				writew(readw(ofsAddr + Page_rxb) + C320p16rx_pgno, ofsAddr + EndPage_rxb);
2833				writew(C320p16tx_spage + i * C320p16buf_pgno, ofsAddr + Page_txb);
2834				writew(readw(ofsAddr + Page_txb) + C320p16tx_pgno, ofsAddr + EndPage_txb);
2835
2836			} else if (moxa_boards[cardno].numPorts == 24) {
2837				writew(C320p24rx_mask, ofsAddr + RX_mask);
2838				writew(C320p24tx_mask, ofsAddr + TX_mask);
2839				writew(C320p24rx_spage + i * C320p24buf_pgno, ofsAddr + Page_rxb);
2840				writew(readw(ofsAddr + Page_rxb) + C320p24rx_pgno, ofsAddr + EndPage_rxb);
2841				writew(C320p24tx_spage + i * C320p24buf_pgno, ofsAddr + Page_txb);
2842				writew(readw(ofsAddr + Page_txb), ofsAddr + EndPage_txb);
2843			} else if (moxa_boards[cardno].numPorts == 32) {
2844				writew(C320p32rx_mask, ofsAddr + RX_mask);
2845				writew(C320p32tx_mask, ofsAddr + TX_mask);
2846				writew(C320p32tx_ofs, ofsAddr + Ofs_txb);
2847				writew(C320p32rx_spage + i * C320p32buf_pgno, ofsAddr + Page_rxb);
2848				writew(readb(ofsAddr + Page_rxb), ofsAddr + EndPage_rxb);
2849				writew(C320p32tx_spage + i * C320p32buf_pgno, ofsAddr + Page_txb);
2850				writew(readw(ofsAddr + Page_txb), ofsAddr + EndPage_txb);
2851			}
2852		}
2853		break;
2854	}
2855	loadstat[cardno] = 1;
2856	return (0);
2857}
2858
2859static int moxaloadc218(int cardno, void __iomem *baseAddr, int len)
2860{
2861	char retry;
2862	int i, j, len1, len2;
2863	ushort usum, *ptr, keycode;
2864
2865	if (moxa_boards[cardno].boardType == MOXA_BOARD_CP204J)
2866		keycode = CP204J_KeyCode;
2867	else
2868		keycode = C218_KeyCode;
2869	usum = 0;
2870	len1 = len >> 1;
2871	ptr = (ushort *) moxaBuff;
2872	for (i = 0; i < len1; i++)
2873		usum += le16_to_cpu(*(ptr + i));
2874	retry = 0;
2875	do {
2876		len1 = len >> 1;
2877		j = 0;
2878		while (len1) {
2879			len2 = (len1 > 2048) ? 2048 : len1;
2880			len1 -= len2;
2881			for (i = 0; i < len2 << 1; i++)
2882				writeb(moxaBuff[i + j], baseAddr + C218_LoadBuf + i);
2883			j += i;
2884
2885			writew(len2, baseAddr + C218DLoad_len);
2886			writew(0, baseAddr + C218_key);
2887			for (i = 0; i < 100; i++) {
2888				if (readw(baseAddr + C218_key) == keycode)
2889					break;
2890				moxadelay(1);	/* delay 10 ms */
2891			}
2892			if (readw(baseAddr + C218_key) != keycode) {
2893				return (-1);
2894			}
2895		}
2896		writew(0, baseAddr + C218DLoad_len);
2897		writew(usum, baseAddr + C218check_sum);
2898		writew(0, baseAddr + C218_key);
2899		for (i = 0; i < 100; i++) {
2900			if (readw(baseAddr + C218_key) == keycode)
2901				break;
2902			moxadelay(1);	/* delay 10 ms */
2903		}
2904		retry++;
2905	} while ((readb(baseAddr + C218chksum_ok) != 1) && (retry < 3));
2906	if (readb(baseAddr + C218chksum_ok) != 1) {
2907		return (-1);
2908	}
2909	writew(0, baseAddr + C218_key);
2910	for (i = 0; i < 100; i++) {
2911		if (readw(baseAddr + Magic_no) == Magic_code)
2912			break;
2913		moxadelay(1);	/* delay 10 ms */
2914	}
2915	if (readw(baseAddr + Magic_no) != Magic_code) {
2916		return (-1);
2917	}
2918	writew(1, baseAddr + Disable_IRQ);
2919	writew(0, baseAddr + Magic_no);
2920	for (i = 0; i < 100; i++) {
2921		if (readw(baseAddr + Magic_no) == Magic_code)
2922			break;
2923		moxadelay(1);	/* delay 10 ms */
2924	}
2925	if (readw(baseAddr + Magic_no) != Magic_code) {
2926		return (-1);
2927	}
2928	moxaCard = 1;
2929	moxaIntNdx[cardno] = baseAddr + IRQindex;
2930	moxaIntPend[cardno] = baseAddr + IRQpending;
2931	moxaIntTable[cardno] = baseAddr + IRQtable;
2932	return (0);
2933}
2934
2935static int moxaloadc320(int cardno, void __iomem *baseAddr, int len, int *numPorts)
2936{
2937	ushort usum;
2938	int i, j, wlen, len2, retry;
2939	ushort *uptr;
2940
2941	usum = 0;
2942	wlen = len >> 1;
2943	uptr = (ushort *) moxaBuff;
2944	for (i = 0; i < wlen; i++)
2945		usum += le16_to_cpu(uptr[i]);
2946	retry = 0;
2947	j = 0;
2948	do {
2949		while (wlen) {
2950			if (wlen > 2048)
2951				len2 = 2048;
2952			else
2953				len2 = wlen;
2954			wlen -= len2;
2955			len2 <<= 1;
2956			for (i = 0; i < len2; i++)
2957				writeb(moxaBuff[j + i], baseAddr + C320_LoadBuf + i);
2958			len2 >>= 1;
2959			j += i;
2960			writew(len2, baseAddr + C320DLoad_len);
2961			writew(0, baseAddr + C320_key);
2962			for (i = 0; i < 10; i++) {
2963				if (readw(baseAddr + C320_key) == C320_KeyCode)
2964					break;
2965				moxadelay(1);
2966			}
2967			if (readw(baseAddr + C320_key) != C320_KeyCode)
2968				return (-1);
2969		}
2970		writew(0, baseAddr + C320DLoad_len);
2971		writew(usum, baseAddr + C320check_sum);
2972		writew(0, baseAddr + C320_key);
2973		for (i = 0; i < 10; i++) {
2974			if (readw(baseAddr + C320_key) == C320_KeyCode)
2975				break;
2976			moxadelay(1);
2977		}
2978		retry++;
2979	} while ((readb(baseAddr + C320chksum_ok) != 1) && (retry < 3));
2980	if (readb(baseAddr + C320chksum_ok) != 1)
2981		return (-1);
2982	writew(0, baseAddr + C320_key);
2983	for (i = 0; i < 600; i++) {
2984		if (readw(baseAddr + Magic_no) == Magic_code)
2985			break;
2986		moxadelay(1);
2987	}
2988	if (readw(baseAddr + Magic_no) != Magic_code)
2989		return (-100);
2990
2991	if (moxa_boards[cardno].busType == MOXA_BUS_TYPE_PCI) {		/* ASIC board */
2992		writew(0x3800, baseAddr + TMS320_PORT1);
2993		writew(0x3900, baseAddr + TMS320_PORT2);
2994		writew(28499, baseAddr + TMS320_CLOCK);
2995	} else {
2996		writew(0x3200, baseAddr + TMS320_PORT1);
2997		writew(0x3400, baseAddr + TMS320_PORT2);
2998		writew(19999, baseAddr + TMS320_CLOCK);
2999	}
3000	writew(1, baseAddr + Disable_IRQ);
3001	writew(0, baseAddr + Magic_no);
3002	for (i = 0; i < 500; i++) {
3003		if (readw(baseAddr + Magic_no) == Magic_code)
3004			break;
3005		moxadelay(1);
3006	}
3007	if (readw(baseAddr + Magic_no) != Magic_code)
3008		return (-102);
3009
3010	j = readw(baseAddr + Module_cnt);
3011	if (j <= 0)
3012		return (-101);
3013	*numPorts = j * 8;
3014	writew(j, baseAddr + Module_no);
3015	writew(0, baseAddr + Magic_no);
3016	for (i = 0; i < 600; i++) {
3017		if (readw(baseAddr + Magic_no) == Magic_code)
3018			break;
3019		moxadelay(1);
3020	}
3021	if (readw(baseAddr + Magic_no) != Magic_code)
3022		return (-102);
3023	moxaCard = 1;
3024	moxaIntNdx[cardno] = baseAddr + IRQindex;
3025	moxaIntPend[cardno] = baseAddr + IRQpending;
3026	moxaIntTable[cardno] = baseAddr + IRQtable;
3027	return (0);
3028}
3029
3030#if 0
3031long MoxaPortGetCurBaud(int port)
3032{
3033
3034	if (moxaChkPort[port] == 0)
3035		return (0);
3036	return (moxaCurBaud[port]);
3037}
3038#endif  /*  0  */
3039
3040static void MoxaSetFifo(int port, int enable)
3041{
3042	void __iomem *ofsAddr = moxaTableAddr[port];
3043
3044	if (!enable) {
3045		moxafunc(ofsAddr, FC_SetRxFIFOTrig, 0);
3046		moxafunc(ofsAddr, FC_SetTxFIFOCnt, 1);
3047	} else {
3048		moxafunc(ofsAddr, FC_SetRxFIFOTrig, 3);
3049		moxafunc(ofsAddr, FC_SetTxFIFOCnt, 16);
3050	}
3051}
3052
3053#if 0
3054int MoxaPortSetMode(int port, int databits, int stopbits, int parity)
3055{
3056	void __iomem *ofsAddr;
3057	int val;
3058
3059	val = 0;
3060	switch (databits) {
3061	case 5:
3062		val |= 0;
3063		break;
3064	case 6:
3065		val |= 1;
3066		break;
3067	case 7:
3068		val |= 2;
3069		break;
3070	case 8:
3071		val |= 3;
3072		break;
3073	default:
3074		return (-1);
3075	}
3076	switch (stopbits) {
3077	case 0:
3078		val |= 0;
3079		break;		/* stop bits 1.5 */
3080	case 1:
3081		val |= 0;
3082		break;
3083	case 2:
3084		val |= 4;
3085		break;
3086	default:
3087		return (-1);
3088	}
3089	switch (parity) {
3090	case 0:
3091		val |= 0x00;
3092		break;		/* None  */
3093	case 1:
3094		val |= 0x08;
3095		break;		/* Odd   */
3096	case 2:
3097		val |= 0x18;
3098		break;		/* Even  */
3099	case 3:
3100		val |= 0x28;
3101		break;		/* Mark  */
3102	case 4:
3103		val |= 0x38;
3104		break;		/* Space */
3105	default:
3106		return (-1);
3107	}
3108	ofsAddr = moxaTableAddr[port];
3109	moxafunc(ofsAddr, FC_SetMode, val);
3110	return (0);
3111}
3112
3113int MoxaPortTxBufSize(int port)
3114{
3115	void __iomem *ofsAddr;
3116	int size;
3117
3118	ofsAddr = moxaTableAddr[port];
3119	size = readw(ofsAddr + TX_mask);
3120	return (size);
3121}
3122
3123int MoxaPortRxBufSize(int port)
3124{
3125	void __iomem *ofsAddr;
3126	int size;
3127
3128	ofsAddr = moxaTableAddr[port];
3129	size = readw(ofsAddr + RX_mask);
3130	return (size);
3131}
3132
3133int MoxaPortRxFree(int port)
3134{
3135	void __iomem *ofsAddr;
3136	ushort rptr, wptr, mask;
3137	int len;
3138
3139	ofsAddr = moxaTableAddr[port];
3140	rptr = readw(ofsAddr + RXrptr);
3141	wptr = readw(ofsAddr + RXwptr);
3142	mask = readw(ofsAddr + RX_mask);
3143	len = mask - ((wptr - rptr) & mask);
3144	return (len);
3145}
3146int MoxaPortGetBrkCnt(int port)
3147{
3148	return (moxaBreakCnt[port]);
3149}
3150
3151void MoxaPortSetXonXoff(int port, int xonValue, int xoffValue)
3152{
3153	void __iomem *ofsAddr;
3154
3155	ofsAddr = moxaTableAddr[port];
3156	writew(xonValue, ofsAddr + FuncArg);
3157	writew(xoffValue, ofsAddr + FuncArg1);
3158	writew(FC_SetXonXoff, ofsAddr + FuncCode);
3159	wait_finish(ofsAddr);
3160}
3161
3162int MoxaPortIsTxHold(int port)
3163{
3164	void __iomem *ofsAddr;
3165	int val;
3166
3167	ofsAddr = moxaTableAddr[port];
3168	if ((moxa_boards[port / MAX_PORTS_PER_BOARD].boardType == MOXA_BOARD_C320_ISA) ||
3169	    (moxa_boards[port / MAX_PORTS_PER_BOARD].boardType == MOXA_BOARD_C320_PCI)) {
3170		moxafunc(ofsAddr, FC_GetCCSR, 0);
3171		val = readw(ofsAddr + FuncArg);
3172		if (val & 0x04)
3173			return (1);
3174	} else {
3175		if (readw(ofsAddr + FlagStat) & Tx_flowOff)
3176			return (1);
3177	}
3178	return (0);
3179}
3180#endif
3181