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