sio.c revision 52831
1/*-
2 * Copyright (c) 1991 The Regents of the University of California.
3 * All rights reserved.
4 *
5 * Redistribution and use in source and binary forms, with or without
6 * modification, are permitted provided that the following conditions
7 * are met:
8 * 1. Redistributions of source code must retain the above copyright
9 *    notice, this list of conditions and the following disclaimer.
10 * 2. Redistributions in binary form must reproduce the above copyright
11 *    notice, this list of conditions and the following disclaimer in the
12 *    documentation and/or other materials provided with the distribution.
13 * 3. All advertising materials mentioning features or use of this software
14 *    must display the following acknowledgement:
15 *	This product includes software developed by the University of
16 *	California, Berkeley and its contributors.
17 * 4. Neither the name of the University nor the names of its contributors
18 *    may be used to endorse or promote products derived from this software
19 *    without specific prior written permission.
20 *
21 * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24 * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25 * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26 * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27 * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29 * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30 * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31 * SUCH DAMAGE.
32 *
33 * $FreeBSD: head/sys/pc98/cbus/sio.c 52831 1999-11-03 09:02:23Z nyan $
34 *	from: @(#)com.c	7.5 (Berkeley) 5/16/91
35 *	from: i386/isa sio.c,v 1.234
36 */
37
38#include "opt_comconsole.h"
39#include "opt_compat.h"
40#include "opt_ddb.h"
41#include "opt_sio.h"
42#include "sio.h"
43
44/*
45 * Serial driver, based on 386BSD-0.1 com driver.
46 * Mostly rewritten to use pseudo-DMA.
47 * Works for National Semiconductor NS8250-NS16550AF UARTs.
48 * COM driver, based on HP dca driver.
49 *
50 * Changes for PC-Card integration:
51 *	- Added PC-Card driver table and handlers
52 */
53/*===============================================================
54 * 386BSD(98),FreeBSD-1.1x(98) com driver.
55 * -----
56 * modified for PC9801 by M.Ishii
57 *			Kyoto University Microcomputer Club (KMC)
58 * Chou "TEFUTEFU" Hirotomi
59 *			Kyoto Univ.  the faculty of medicine
60 *===============================================================
61 * FreeBSD-2.0.1(98) sio driver.
62 * -----
63 * modified for pc98 Internal i8251 and MICRO CORE MC16550II
64 *			T.Koike(hfc01340@niftyserve.or.jp)
65 * implement kernel device configuration
66 *			aizu@orient.center.nitech.ac.jp
67 *
68 * Notes.
69 * -----
70 *  PC98 localization based on 386BSD(98) com driver. Using its PC98 local
71 *  functions.
72 *  This driver is under debugging,has bugs.
73 *
74 * 1) config
75 *  options COM_MULTIPORT  #if using MC16550II
76 *  device sio0 at nec? port 0x30  tty irq 4             #internal
77 *  device sio1 at nec? port 0xd2  tty irq 5 flags 0x101 #mc1
78 *  device sio2 at nec? port 0x8d2 tty flags 0x101       #mc2
79 *                         # ~~~~~iobase        ~~multi port flag
80 *                         #                   ~  master device is sio1
81 * 2) device
82 *  cd /dev; MAKEDEV ttyd0 ttyd1 ..
83 * 3) /etc/rc.serial
84 *  57600bps is too fast for sio0(internal8251)
85 *  my ex.
86 *    #set default speed 9600
87 *    modem()
88 *       :
89 *      stty </dev/ttyid$i crtscts 9600
90 *       :                 #       ~~~~ default speed(can change after init.)
91 *    modem 0 1 2
92 * 4) COMCONSOLE
93 *  not changed.
94 * 5) PC9861K,PIO9032B,B98_01
95 *  not tested.
96 */
97/*
98 * modified for AIWA B98-01
99 * by T.Hatanou <hatanou@yasuda.comm.waseda.ac.jp>  last update: 15 Sep.1995
100 *
101 * How to configure...
102 *   # options COM_MULTIPORT         # support for MICROCORE MC16550II
103 *      ... comment-out this line, which will conflict with B98_01.
104 *   options "B98_01"                # support for AIWA B98-01
105 *   device  sio1 at nec? port 0x00d1 tty irq ?
106 *   device  sio2 at nec? port 0x00d5 tty irq ?
107 *      ... you can leave these lines `irq ?', irq will be autodetected.
108 */
109/*
110 * Modified by Y.Takahashi of Kogakuin University.
111 */
112
113#ifdef PC98
114#define COM_IF_INTERNAL		0x00
115#define COM_IF_PC9861K_1	0x01
116#define COM_IF_PC9861K_2	0x02
117#define COM_IF_IND_SS_1		0x03
118#define COM_IF_IND_SS_2		0x04
119#define COM_IF_PIO9032B_1	0x05
120#define COM_IF_PIO9032B_2	0x06
121#define COM_IF_B98_01_1		0x07
122#define COM_IF_B98_01_2		0x08
123#define COM_IF_END1		COM_IF_B98_01_2
124#define COM_IF_RSA98		0x10	/* same as COM_IF_NS16550 */
125#define COM_IF_NS16550		0x11
126#define COM_IF_SECOND_CCU	0x12	/* same as COM_IF_NS16550 */
127#define COM_IF_MC16550II	0x13
128#define COM_IF_MCRS98		0x14	/* same as COM_IF_MC16550II */
129#define COM_IF_RSB3000		0x15
130#define COM_IF_RSB384		0x16
131#define COM_IF_MODEM_CARD	0x17	/* same as COM_IF_NS16550 */
132#define COM_IF_RSA98III		0x18
133#define COM_IF_ESP98		0x19
134#define COM_IF_END2		COM_IF_ESP98
135#endif /* PC98 */
136
137#include <sys/param.h>
138#include <sys/systm.h>
139#include <sys/reboot.h>
140#include <sys/malloc.h>
141#include <sys/tty.h>
142#include <sys/proc.h>
143#include <sys/module.h>
144#include <sys/conf.h>
145#include <sys/dkstat.h>
146#include <sys/fcntl.h>
147#include <sys/interrupt.h>
148#include <sys/kernel.h>
149#include <sys/syslog.h>
150#include <sys/sysctl.h>
151#include <sys/bus.h>
152#include <machine/bus.h>
153#include <sys/rman.h>
154#include <sys/timepps.h>
155
156#ifdef PC98
157#include <pc98/pc98/pc98.h>
158#include <pc98/pc98/pc98_machdep.h>
159#include <i386/isa/ic/i8251.h>
160#else
161#include <isa/isareg.h>
162#endif
163#include <isa/isavar.h>
164#include <machine/lock.h>
165
166#include <machine/clock.h>
167#include <machine/ipl.h>
168#ifndef SMP
169#include <machine/lock.h>
170#endif
171#include <machine/resource.h>
172
173#include <isa/sioreg.h>
174
175#ifdef COM_ESP
176#include <i386/isa/ic/esp.h>
177#endif
178#include <i386/isa/ic/ns16550.h>
179#ifdef PC98
180#include <i386/isa/ic/rsa.h>
181#endif
182
183#include "card.h"
184#if NCARD > 0
185/* XXX should die XXX */
186#include <sys/select.h>
187#include <sys/module.h>
188#include <pccard/cardinfo.h>
189#include <pccard/slot.h>
190#endif
191
192#ifndef __i386__
193#define disable_intr()
194#define enable_intr()
195#endif
196
197#ifdef SMP
198#define disable_intr()	COM_DISABLE_INTR()
199#define enable_intr()	COM_ENABLE_INTR()
200#endif /* SMP */
201
202#ifndef EXTRA_SIO
203#define EXTRA_SIO 4		/* XXX shouldn't need NSIO */
204#endif
205
206#define NSIOTOT (NSIO + EXTRA_SIO)
207
208#define	LOTS_OF_EVENTS	64	/* helps separate urgent events from input */
209
210#define	CALLOUT_MASK		0x80
211#define	CONTROL_MASK		0x60
212#define	CONTROL_INIT_STATE	0x20
213#define	CONTROL_LOCK_STATE	0x40
214#define	DEV_TO_UNIT(dev)	(MINOR_TO_UNIT(minor(dev)))
215#define	MINOR_MAGIC_MASK	(CALLOUT_MASK | CONTROL_MASK)
216#define	MINOR_TO_UNIT(mynor)	((mynor) & ~MINOR_MAGIC_MASK)
217
218#ifdef COM_MULTIPORT
219/* checks in flags for multiport and which is multiport "master chip"
220 * for a given card
221 */
222#define	COM_ISMULTIPORT(flags)	((flags) & 0x01)
223#define	COM_MPMASTER(flags)	(((flags) >> 8) & 0x0ff)
224#define	COM_NOTAST4(flags)	((flags) & 0x04)
225#endif /* COM_MULTIPORT */
226
227#define	COM_CONSOLE(flags)	((flags) & 0x10)
228#define	COM_FORCECONSOLE(flags)	((flags) & 0x20)
229#define	COM_LLCONSOLE(flags)	((flags) & 0x40)
230#define	COM_DEBUGGER(flags)	((flags) & 0x80)
231#define	COM_LOSESOUTINTS(flags)	((flags) & 0x08)
232#define	COM_NOFIFO(flags)		((flags) & 0x02)
233#define COM_ST16650A(flags)	((flags) & 0x20000)
234#define COM_C_NOPROBE		(0x40000)
235#define COM_NOPROBE(flags)	((flags) & COM_C_NOPROBE)
236#define COM_C_IIR_TXRDYBUG	(0x80000)
237#define COM_IIR_TXRDYBUG(flags)	((flags) & COM_C_IIR_TXRDYBUG)
238#define	COM_FIFOSIZE(flags)	(((flags) & 0xff000000) >> 24)
239
240#ifdef PC98
241#define	com_emr		com_msr	/* Extension mode register for RSB-2000/3000 */
242#else
243#define	com_scr		7	/* scratch register for 16450-16550 (R/W) */
244#endif
245
246/*
247 * com state bits.
248 * (CS_BUSY | CS_TTGO) and (CS_BUSY | CS_TTGO | CS_ODEVREADY) must be higher
249 * than the other bits so that they can be tested as a group without masking
250 * off the low bits.
251 *
252 * The following com and tty flags correspond closely:
253 *	CS_BUSY		= TS_BUSY (maintained by comstart(), siopoll() and
254 *				   comstop())
255 *	CS_TTGO		= ~TS_TTSTOP (maintained by comparam() and comstart())
256 *	CS_CTS_OFLOW	= CCTS_OFLOW (maintained by comparam())
257 *	CS_RTS_IFLOW	= CRTS_IFLOW (maintained by comparam())
258 * TS_FLUSH is not used.
259 * XXX I think TIOCSETA doesn't clear TS_TTSTOP when it clears IXON.
260 * XXX CS_*FLOW should be CF_*FLOW in com->flags (control flags not state).
261 */
262#define	CS_BUSY		0x80	/* output in progress */
263#define	CS_TTGO		0x40	/* output not stopped by XOFF */
264#define	CS_ODEVREADY	0x20	/* external device h/w ready (CTS) */
265#define	CS_CHECKMSR	1	/* check of MSR scheduled */
266#define	CS_CTS_OFLOW	2	/* use CTS output flow control */
267#define	CS_DTR_OFF	0x10	/* DTR held off */
268#define	CS_ODONE	4	/* output completed */
269#define	CS_RTS_IFLOW	8	/* use RTS input flow control */
270#define	CSE_BUSYCHECK	1	/* siobusycheck() scheduled */
271
272static	char const * const	error_desc[] = {
273#define	CE_OVERRUN			0
274	"silo overflow",
275#define	CE_INTERRUPT_BUF_OVERFLOW	1
276	"interrupt-level buffer overflow",
277#define	CE_TTY_BUF_OVERFLOW		2
278	"tty-level buffer overflow",
279};
280
281#define	CE_NTYPES			3
282#define	CE_RECORD(com, errnum)		(++(com)->delta_error_counts[errnum])
283
284/* types.  XXX - should be elsewhere */
285typedef u_int	Port_t;		/* hardware port */
286typedef u_char	bool_t;		/* boolean */
287
288/* queue of linear buffers */
289struct lbq {
290	u_char	*l_head;	/* next char to process */
291	u_char	*l_tail;	/* one past the last char to process */
292	struct lbq *l_next;	/* next in queue */
293	bool_t	l_queued;	/* nonzero if queued */
294};
295
296/* com device structure */
297struct com_s {
298	u_int	flags;		/* Copy isa device flags */
299	u_char	state;		/* miscellaneous flag bits */
300	bool_t  active_out;	/* nonzero if the callout device is open */
301	u_char	cfcr_image;	/* copy of value written to CFCR */
302#ifdef COM_ESP
303	bool_t	esp;		/* is this unit a hayes esp board? */
304#endif
305	u_char	extra_state;	/* more flag bits, separate for order trick */
306	u_char	fifo_image;	/* copy of value written to FIFO */
307	bool_t	hasfifo;	/* nonzero for 16550 UARTs */
308	bool_t	st16650a;	/* Is a Startech 16650A or RTS/CTS compat */
309	bool_t	loses_outints;	/* nonzero if device loses output interrupts */
310	u_char	mcr_image;	/* copy of value written to MCR */
311#ifdef COM_MULTIPORT
312	bool_t	multiport;	/* is this unit part of a multiport device? */
313#endif /* COM_MULTIPORT */
314	bool_t	no_irq;		/* nonzero if irq is not attached */
315	bool_t  gone;		/* hardware disappeared */
316	bool_t	poll;		/* nonzero if polling is required */
317	bool_t	poll_output;	/* nonzero if polling for output is required */
318	int	unit;		/* unit	number */
319	int	dtr_wait;	/* time to hold DTR down on close (* 1/hz) */
320	u_int	tx_fifo_size;
321	u_int	wopeners;	/* # processes waiting for DCD in open() */
322
323	/*
324	 * The high level of the driver never reads status registers directly
325	 * because there would be too many side effects to handle conveniently.
326	 * Instead, it reads copies of the registers stored here by the
327	 * interrupt handler.
328	 */
329	u_char	last_modem_status;	/* last MSR read by intr handler */
330	u_char	prev_modem_status;	/* last MSR handled by high level */
331
332	u_char	hotchar;	/* ldisc-specific char to be handled ASAP */
333	u_char	*ibuf;		/* start of input buffer */
334	u_char	*ibufend;	/* end of input buffer */
335	u_char	*ibufold;	/* old input buffer, to be freed */
336	u_char	*ihighwater;	/* threshold in input buffer */
337	u_char	*iptr;		/* next free spot in input buffer */
338	int	ibufsize;	/* size of ibuf (not include error bytes) */
339	int	ierroff;	/* offset of error bytes in ibuf */
340
341	struct lbq	obufq;	/* head of queue of output buffers */
342	struct lbq	obufs[2];	/* output buffers */
343
344#ifdef PC98
345	Port_t	cmd_port;
346	Port_t	sts_port;
347	Port_t	in_modem_port;
348	Port_t	intr_ctrl_port;
349	int	intr_enable;
350	int	pc98_prev_modem_status;
351	int	pc98_modem_delta;
352	int	modem_car_chg_timer;
353	int	pc98_prev_siocmd;
354	int	pc98_prev_siomod;
355	int	modem_checking;
356	int	pc98_if_type;
357#endif /* PC98 */
358	Port_t	data_port;	/* i/o ports */
359#ifdef COM_ESP
360	Port_t	esp_port;
361#endif
362	Port_t	int_id_port;
363	Port_t	iobase;
364#ifdef PC98
365	Port_t	rsabase;	/* iobase address of a I/O-DATA RSA board */
366#endif
367	Port_t	modem_ctl_port;
368	Port_t	line_status_port;
369	Port_t	modem_status_port;
370	Port_t	intr_ctl_port;	/* Ports of IIR register */
371
372	struct tty	*tp;	/* cross reference */
373
374	/* Initial state. */
375	struct termios	it_in;	/* should be in struct tty */
376	struct termios	it_out;
377
378	/* Lock state. */
379	struct termios	lt_in;	/* should be in struct tty */
380	struct termios	lt_out;
381
382	bool_t	do_timestamp;
383	bool_t	do_dcd_timestamp;
384	struct timeval	timestamp;
385	struct timeval	dcd_timestamp;
386	struct	pps_state pps;
387
388	u_long	bytes_in;	/* statistics */
389	u_long	bytes_out;
390	u_int	delta_error_counts[CE_NTYPES];
391	u_long	error_counts[CE_NTYPES];
392
393	struct resource *irqres;
394	struct resource *ioportres;
395
396	/*
397	 * Data area for output buffers.  Someday we should build the output
398	 * buffer queue without copying data.
399	 */
400#ifdef PC98
401	int	obufsize;
402 	u_char	*obuf1;
403 	u_char	*obuf2;
404#else
405	u_char	obuf1[256];
406	u_char	obuf2[256];
407#endif
408};
409
410#ifdef COM_ESP
411static	int	espattach	__P((struct com_s *com, Port_t esp_port));
412#endif
413static	int	sioattach	__P((device_t dev));
414static	int	sio_isa_attach	__P((device_t dev));
415
416static	timeout_t siobusycheck;
417static	timeout_t siodtrwakeup;
418static	void	comhardclose	__P((struct com_s *com));
419static	void	sioinput	__P((struct com_s *com));
420static	void	siointr1	__P((struct com_s *com));
421static	void	siointr		__P((void *arg));
422static	int	commctl		__P((struct com_s *com, int bits, int how));
423static	int	comparam	__P((struct tty *tp, struct termios *t));
424static	swihand_t siopoll;
425static	int	sioprobe	__P((device_t dev));
426static	int	sio_isa_probe	__P((device_t dev));
427static	void	siosettimeout	__P((void));
428static	int	siosetwater	__P((struct com_s *com, speed_t speed));
429static	void	comstart	__P((struct tty *tp));
430static	void	comstop		__P((struct tty *tp, int rw));
431static	timeout_t comwakeup;
432static	void	disc_optim	__P((struct tty	*tp, struct termios *t,
433				     struct com_s *com));
434
435#if NCARD > 0
436static	int	sio_pccard_attach __P((device_t dev));
437static	void	sio_pccard_detach __P((device_t dev));
438static	int	sio_pccard_probe __P((device_t dev));
439#endif /* NCARD > 0 */
440
441static char driver_name[] = "sio";
442
443/* table and macro for fast conversion from a unit number to its com struct */
444static	devclass_t	sio_devclass;
445#define	com_addr(unit)	((struct com_s *) \
446			 devclass_get_softc(sio_devclass, unit))
447
448static device_method_t sio_isa_methods[] = {
449	/* Device interface */
450	DEVMETHOD(device_probe,		sio_isa_probe),
451	DEVMETHOD(device_attach,	sio_isa_attach),
452
453	{ 0, 0 }
454};
455
456static driver_t sio_isa_driver = {
457	driver_name,
458	sio_isa_methods,
459	sizeof(struct com_s),
460};
461
462#if NCARD > 0
463static device_method_t sio_pccard_methods[] = {
464	/* Device interface */
465	DEVMETHOD(device_probe,		sio_pccard_probe),
466	DEVMETHOD(device_attach,	sio_pccard_attach),
467	DEVMETHOD(device_detach,	sio_pccard_detach),
468
469	{ 0, 0 }
470};
471
472static driver_t sio_pccard_driver = {
473	driver_name,
474	sio_pccard_methods,
475	sizeof(struct com_s),
476};
477#endif (NCARD > 0)
478
479static	d_open_t	sioopen;
480static	d_close_t	sioclose;
481static	d_read_t	sioread;
482static	d_write_t	siowrite;
483static	d_ioctl_t	sioioctl;
484
485#define	CDEV_MAJOR	28
486static struct cdevsw sio_cdevsw = {
487	/* open */	sioopen,
488	/* close */	sioclose,
489	/* read */	sioread,
490	/* write */	siowrite,
491	/* ioctl */	sioioctl,
492	/* poll */	ttypoll,
493	/* mmap */	nommap,
494	/* strategy */	nostrategy,
495	/* name */	driver_name,
496	/* maj */	CDEV_MAJOR,
497	/* dump */	nodump,
498	/* psize */	nopsize,
499	/* flags */	D_TTY,
500	/* bmaj */	-1
501};
502
503int	comconsole = -1;
504static	volatile speed_t	comdefaultrate = CONSPEED;
505#ifdef __alpha__
506static	volatile speed_t	gdbdefaultrate = CONSPEED;
507#endif
508static	u_int	com_events;	/* input chars + weighted output completions */
509static	Port_t	siocniobase;
510static	int	siocnunit;
511static	Port_t	siogdbiobase;
512static	int	siogdbunit = -1;
513static	bool_t	sio_registered;
514static	int	sio_timeout;
515static	int	sio_timeouts_until_log;
516static	struct	callout_handle sio_timeout_handle
517    = CALLOUT_HANDLE_INITIALIZER(&sio_timeout_handle);
518
519#ifdef PC98
520struct	siodev	{
521	short	if_type;
522	short	irq;
523	Port_t	cmd, sts, ctrl, mod;
524};
525static	int	sysclock;
526
527#define	COM_INT_DISABLE		{int previpri; previpri=spltty();
528#define	COM_INT_ENABLE		splx(previpri);}
529#define IEN_TxFLAG		IEN_Tx
530
531#define COM_CARRIER_DETECT_EMULATE	0
532#define	PC98_CHECK_MODEM_INTERVAL	(hz/10)
533#define DCD_OFF_TOLERANCE		2
534#define DCD_ON_RECOGNITION		2
535#define	IS_8251(if_type)		(!(if_type & 0x10))
536#define COM1_EXT_CLOCK			0x40000
537
538static	void	commint		__P((dev_t dev));
539static	void	com_tiocm_set	__P((struct com_s *com, int msr));
540static	void	com_tiocm_bis	__P((struct com_s *com, int msr));
541static	void	com_tiocm_bic	__P((struct com_s *com, int msr));
542static	int	com_tiocm_get	__P((struct com_s *com));
543static	int	com_tiocm_get_delta	__P((struct com_s *com));
544static	void	pc98_msrint_start	__P((dev_t dev));
545static	void	com_cflag_and_speed_set	__P((struct com_s *com, int cflag, int speed));
546static	int	pc98_ttspeedtab		__P((struct com_s *com, int speed));
547static	int	pc98_get_modem_status	__P((struct com_s *com));
548static	timeout_t	pc98_check_msr;
549static	void	pc98_set_baud_rate	__P((struct com_s *com, int count));
550static	void	pc98_i8251_reset	__P((struct com_s *com, int mode, int command));
551static	void	pc98_disable_i8251_interrupt	__P((struct com_s *com, int mod));
552static	void	pc98_enable_i8251_interrupt	__P((struct com_s *com, int mod));
553static	int	pc98_check_i8251_interrupt	__P((struct com_s *com));
554static	int	pc98_i8251_get_cmd	__P((struct com_s *com));
555static	int	pc98_i8251_get_mod	__P((struct com_s *com));
556static	void	pc98_i8251_set_cmd	__P((struct com_s *com, int x));
557static	void	pc98_i8251_or_cmd	__P((struct com_s *com, int x));
558static	void	pc98_i8251_clear_cmd	__P((struct com_s *com, int x));
559static	void	pc98_i8251_clear_or_cmd	__P((struct com_s *com, int clr, int x));
560static	int	pc98_check_if_type	__P((device_t dev, struct siodev *iod));
561static	void	pc98_check_sysclock	__P((void));
562static	int	pc98_set_ioport		__P((struct com_s *com, int id_flags));
563
564#define com_int_Tx_disable(com) \
565		pc98_disable_i8251_interrupt(com,IEN_Tx|IEN_TxEMP)
566#define com_int_Tx_enable(com) \
567		pc98_enable_i8251_interrupt(com,IEN_TxFLAG)
568#define com_int_Rx_disable(com) \
569		pc98_disable_i8251_interrupt(com,IEN_Rx)
570#define com_int_Rx_enable(com) \
571		pc98_enable_i8251_interrupt(com,IEN_Rx)
572#define com_int_TxRx_disable(com) \
573		pc98_disable_i8251_interrupt(com,IEN_Tx|IEN_TxEMP|IEN_Rx)
574#define com_int_TxRx_enable(com) \
575		pc98_enable_i8251_interrupt(com,IEN_TxFLAG|IEN_Rx)
576#define com_send_break_on(com) \
577		pc98_i8251_or_cmd(com,CMD8251_SBRK)
578#define com_send_break_off(com) \
579		pc98_i8251_clear_cmd(com,CMD8251_SBRK)
580
581static struct speedtab pc98speedtab[] = {	/* internal RS232C interface */
582	{ 0,		0, },
583	{ 50,		50, },
584	{ 75,		75, },
585	{ 150,		150, },
586	{ 200,		200, },
587	{ 300,		300, },
588	{ 600,		600, },
589	{ 1200,		1200, },
590	{ 2400,		2400, },
591	{ 4800,		4800, },
592	{ 9600,		9600, },
593	{ 19200,	19200, },
594	{ 38400,	38400, },
595	{ 51200,	51200, },
596	{ 76800,	76800, },
597	{ 20800,	20800, },
598	{ 31200,	31200, },
599	{ 41600,	41600, },
600	{ 62400,	62400, },
601	{ -1,		-1 }
602};
603static struct speedtab pc98fast_speedtab[] = {
604	{ 9600,		0x80 | COMBRD(9600), },
605	{ 19200,	0x80 | COMBRD(19200), },
606	{ 38400,	0x80 | COMBRD(38400), },
607	{ 57600,	0x80 | COMBRD(57600), },
608	{ 115200,	0x80 | COMBRD(115200), },
609	{ -1,		-1 }
610};
611static struct speedtab comspeedtab_pio9032b[] = {
612	{ 300,		6, },
613	{ 600,		5, },
614	{ 1200,		4, },
615	{ 2400,		3, },
616	{ 4800,		2, },
617	{ 9600,		1, },
618	{ 19200,	0, },
619	{ 38400,	7, },
620	{ -1,		-1 }
621};
622static struct speedtab comspeedtab_b98_01[] = {
623	{ 75,		11, },
624	{ 150,		10, },
625	{ 300,		9, },
626	{ 600,		8, },
627	{ 1200,		7, },
628	{ 2400,		6, },
629	{ 4800,		5, },
630	{ 9600,		4, },
631	{ 19200,	3, },
632	{ 38400,	2, },
633	{ 76800,	1, },
634	{ 153600,	0, },
635	{ -1,		-1 }
636};
637static struct speedtab comspeedtab_mc16550[] = {
638	{ 300,		1536, },
639	{ 600,		768, },
640	{ 1200,		384, },
641	{ 2400,		192, },
642	{ 4800,		96, },
643	{ 9600,		48, },
644	{ 19200,	24, },
645	{ 38400,	12, },
646	{ 57600,	8, },
647	{ 115200,	4, },
648	{ 153600,	3, },
649	{ 230400,	2, },
650	{ 460800,	1, },
651	{ -1,		-1 }
652};
653static struct speedtab comspeedtab_rsb384[] = {
654	{ 300,		3840, },
655	{ 600,		1920, },
656	{ 1200,		960, },
657	{ 2400,		480, },
658	{ 4800,		240, },
659	{ 9600,		120, },
660	{ 19200,	60, },
661	{ 38400,	30, },
662	{ 57600,	20, },
663	{ 115200,	10, },
664	{ 128000,	9, },
665	{ 144000,	8, },
666	{ 192000,	6, },
667	{ 230400,	5, },
668	{ 288000,	4, },
669	{ 384000,	3, },
670	{ 576000,	2, },
671	{ 1152000,	1, },
672	{ -1,		-1 }
673};
674static  struct speedtab comspeedtab_rsa[] = {
675        { 0,		0 },
676	{ 50,		COMBRD_RSA(50) },
677	{ 75,		COMBRD_RSA(75) },
678	{ 110,		COMBRD_RSA(110) },
679	{ 134,		COMBRD_RSA(134) },
680	{ 150,		COMBRD_RSA(150) },
681	{ 200,		COMBRD_RSA(200) },
682	{ 300,		COMBRD_RSA(300) },
683	{ 600,		COMBRD_RSA(600) },
684	{ 1200,		COMBRD_RSA(1200) },
685	{ 1800,		COMBRD_RSA(1800) },
686	{ 2400,		COMBRD_RSA(2400) },
687	{ 4800,		COMBRD_RSA(4800) },
688	{ 9600,		COMBRD_RSA(9600) },
689	{ 19200,	COMBRD_RSA(19200) },
690	{ 38400,	COMBRD_RSA(38400) },
691	{ 57600,	COMBRD_RSA(57600) },
692	{ 115200,	COMBRD_RSA(115200) },
693	{ 230400,	COMBRD_RSA(230400) },
694	{ 460800,	COMBRD_RSA(460800) },
695	{ 921600,	COMBRD_RSA(921600) },
696	{ -1,           -1 }
697};
698#endif /* PC98 */
699
700static	struct speedtab comspeedtab[] = {
701	{ 0,		0 },
702	{ 50,		COMBRD(50) },
703	{ 75,		COMBRD(75) },
704	{ 110,		COMBRD(110) },
705	{ 134,		COMBRD(134) },
706	{ 150,		COMBRD(150) },
707	{ 200,		COMBRD(200) },
708	{ 300,		COMBRD(300) },
709	{ 600,		COMBRD(600) },
710	{ 1200,		COMBRD(1200) },
711	{ 1800,		COMBRD(1800) },
712	{ 2400,		COMBRD(2400) },
713	{ 4800,		COMBRD(4800) },
714	{ 9600,		COMBRD(9600) },
715	{ 19200,	COMBRD(19200) },
716	{ 38400,	COMBRD(38400) },
717	{ 57600,	COMBRD(57600) },
718	{ 115200,	COMBRD(115200) },
719	{ -1,		-1 }
720};
721
722#ifdef PC98
723struct {
724	char	*name;
725	short	port_table[7];
726	short	irr_mask;
727	struct speedtab	*speedtab;
728	short	check_irq;
729} if_8251_type[] = {
730	/* COM_IF_INTERNAL */
731	{ " (internal)", {0x30, 0x32, 0x32, 0x33, 0x35, -1, -1},
732	     -1, pc98speedtab, 1 },
733	/* COM_IF_PC9861K_1 */
734	{ " (PC9861K)", {0xb1, 0xb3, 0xb3, 0xb0, 0xb0, -1, -1},
735	     3, NULL, 1 },
736	/* COM_IF_PC9861K_2 */
737	{ " (PC9861K)", {0xb9, 0xbb, 0xbb, 0xb2, 0xb2, -1, -1},
738	      3, NULL, 1 },
739	/* COM_IF_IND_SS_1 */
740	{ " (IND-SS)", {0xb1, 0xb3, 0xb3, 0xb0, 0xb0, 0xb3, -1},
741	     3, comspeedtab_mc16550, 1 },
742	/* COM_IF_IND_SS_2 */
743	{ " (IND-SS)", {0xb9, 0xbb, 0xbb, 0xb2, 0xb2, 0xbb, -1},
744	     3, comspeedtab_mc16550, 1 },
745	/* COM_IF_PIO9032B_1 */
746	{ " (PIO9032B)", {0xb1, 0xb3, 0xb3, 0xb0, 0xb0, 0xb8, -1},
747	      7, comspeedtab_pio9032b, 1 },
748	/* COM_IF_PIO9032B_2 */
749	{ " (PIO9032B)", {0xb9, 0xbb, 0xbb, 0xb2, 0xb2, 0xba, -1},
750	      7, comspeedtab_pio9032b, 1 },
751	/* COM_IF_B98_01_1 */
752	{ " (B98-01)", {0xb1, 0xb3, 0xb3, 0xb0, 0xb0, 0xd1, 0xd3},
753	      7, comspeedtab_b98_01, 0 },
754	/* COM_IF_B98_01_2 */
755	{ " (B98-01)", {0xb9, 0xbb, 0xbb, 0xb2, 0xb2, 0xd5, 0xd7},
756	     7, comspeedtab_b98_01, 0 },
757};
758#define	PC98SIO_data_port(type)		(if_8251_type[type].port_table[0])
759#define	PC98SIO_cmd_port(type)		(if_8251_type[type].port_table[1])
760#define	PC98SIO_sts_port(type)		(if_8251_type[type].port_table[2])
761#define	PC98SIO_in_modem_port(type)	(if_8251_type[type].port_table[3])
762#define	PC98SIO_intr_ctrl_port(type)	(if_8251_type[type].port_table[4])
763#define	PC98SIO_baud_rate_port(type)	(if_8251_type[type].port_table[5])
764#define	PC98SIO_func_port(type)		(if_8251_type[type].port_table[6])
765
766struct {
767	char	*name;
768	short	irr_read;
769	short	irr_write;
770	short	port_shift;
771	short	io_size;
772	struct speedtab	*speedtab;
773} if_16550a_type[] = {
774	/* COM_IF_RSA98 */
775        { " (RSA-98)", -1, -1, 0, IO_COMSIZE, comspeedtab },
776	/* COM_IF_NS16550 */
777	{ "", -1, -1, 0, IO_COMSIZE, comspeedtab },
778	/* COM_IF_SECOND_CCU */
779	{ "", -1, -1, 0, IO_COMSIZE, comspeedtab },
780	/* COM_IF_MC16550II */
781	{ " (MC16550II)", -1, 0x1000, 8, 1, comspeedtab_mc16550 },
782	/* COM_IF_MCRS98 */
783	{ " (MC-RS98)", -1, 0x1000, 8, 1, comspeedtab_mc16550 },
784	/* COM_IF_RSB3000 */
785	{ " (RSB-3000)", 0xbf, -1, 1, 1, comspeedtab_rsb384 },
786	/* COM_IF_RSB384 */
787	{ " (RSB-384)", 0xbf, -1, 1, 1, comspeedtab_rsb384 },
788	/* COM_IF_MODEM_CARD */
789	{ "", -1, -1, 0, IO_COMSIZE, comspeedtab },
790	/* COM_IF_RSA98III */
791	{ " (RSA-98III)", -1, -1, 0, 16, comspeedtab_rsa },
792	/* COM_IF_ESP98 */
793	{ " (ESP98)", -1, -1, 1, 1, comspeedtab_mc16550 },
794};
795#endif /* PC98 */
796
797#ifdef COM_ESP
798#ifdef PC98
799
800/* XXX configure this properly. */
801static  Port_t  likely_com_ports[] = { 0, 0xb0, 0xb1, 0 };
802static  Port_t  likely_esp_ports[] = { 0xc0d0, 0 };
803
804#define	ESP98_CMD1	(ESP_CMD1 * 0x100)
805#define	ESP98_CMD2	(ESP_CMD2 * 0x100)
806#define	ESP98_STATUS1	(ESP_STATUS1 * 0x100)
807#define	ESP98_STATUS2	(ESP_STATUS2 * 0x100)
808
809#else /* PC98 */
810
811/* XXX configure this properly. */
812static	Port_t	likely_com_ports[] = { 0x3f8, 0x2f8, 0x3e8, 0x2e8, };
813static	Port_t	likely_esp_ports[] = { 0x140, 0x180, 0x280, 0 };
814
815#endif /* PC98 */
816#endif
817
818/*
819 * handle sysctl read/write requests for console speed
820 *
821 * In addition to setting comdefaultrate for I/O through /dev/console,
822 * also set the initial and lock values for the /dev/ttyXX device
823 * if there is one associated with the console.  Finally, if the /dev/tty
824 * device has already been open, change the speed on the open running port
825 * itself.
826 */
827
828static int
829sysctl_machdep_comdefaultrate SYSCTL_HANDLER_ARGS
830{
831	int error, s;
832	speed_t newspeed;
833	struct com_s *com;
834	struct tty *tp;
835
836	newspeed = comdefaultrate;
837
838	error = sysctl_handle_opaque(oidp, &newspeed, sizeof newspeed, req);
839	if (error || !req->newptr)
840		return (error);
841
842	comdefaultrate = newspeed;
843
844	if (comconsole < 0)		/* serial console not selected? */
845		return (0);
846
847	com = com_addr(comconsole);
848	if (!com)
849		return (ENXIO);
850
851	/*
852	 * set the initial and lock rates for /dev/ttydXX and /dev/cuaXX
853	 * (note, the lock rates really are boolean -- if non-zero, disallow
854	 *  speed changes)
855	 */
856	com->it_in.c_ispeed  = com->it_in.c_ospeed =
857	com->lt_in.c_ispeed  = com->lt_in.c_ospeed =
858	com->it_out.c_ispeed = com->it_out.c_ospeed =
859	com->lt_out.c_ispeed = com->lt_out.c_ospeed = comdefaultrate;
860
861	/*
862	 * if we're open, change the running rate too
863	 */
864	tp = com->tp;
865	if (tp && (tp->t_state & TS_ISOPEN)) {
866		tp->t_termios.c_ispeed =
867		tp->t_termios.c_ospeed = comdefaultrate;
868		s = spltty();
869		error = comparam(tp, &tp->t_termios);
870		splx(s);
871	}
872	return error;
873}
874
875SYSCTL_PROC(_machdep, OID_AUTO, conspeed, CTLTYPE_INT | CTLFLAG_RW,
876	    0, 0, sysctl_machdep_comdefaultrate, "I", "");
877
878#if NCARD > 0
879static int
880sio_pccard_probe(dev)
881	device_t	dev;
882{
883	return (sioprobe(dev));
884}
885
886static int
887sio_pccard_attach(dev)
888	device_t	dev;
889{
890	return (sioattach(dev));
891}
892
893/*
894 *	sio_detach - unload the driver and clear the table.
895 *	XXX TODO:
896 *	This is usually called when the card is ejected, but
897 *	can be caused by a modunload of a controller driver.
898 *	The idea is to reset the driver's view of the device
899 *	and ensure that any driver entry points such as
900 *	read and write do not hang.
901 */
902static void
903sio_pccard_detach(dev)
904	device_t	dev;
905{
906	struct com_s	*com;
907
908	com = (struct com_s *) device_get_softc(dev);
909	if (!com) {
910		device_printf(dev, "NULL com in siounload\n");
911		return;
912	}
913	if (!com->iobase) {
914		device_printf(dev, "already unloaded!\n");
915		return;
916	}
917	if (com->tp && (com->tp->t_state & TS_ISOPEN)) {
918		com->gone = 1;
919		device_printf(dev, "unload\n");
920		com->tp->t_gen++;
921		ttyclose(com->tp);
922		ttwakeup(com->tp);
923		ttwwakeup(com->tp);
924	} else {
925		if (com->ibuf != NULL)
926			free(com->ibuf, M_DEVBUF);
927		free(com, M_DEVBUF);
928		device_printf(dev, "unload,gone\n");
929	}
930}
931#endif /* NCARD > 0 */
932
933#define SET_FLAG(dev, bit) device_set_flags(dev, device_get_flags(dev) | (bit))
934#define CLR_FLAG(dev, bit) device_set_flags(dev, device_get_flags(dev) & ~(bit))
935
936static struct isa_pnp_id sio_ids[] = {
937	{0x0005d041, "Standard PC COM port"},	/* PNP0500 */
938	{0x0105d041, "16550A-compatible COM port"},	/* PNP0501 */
939	{0x0205d041, "Multiport serial device (non-intelligent 16550)"}, /* PNP0502 */
940	{0x1005d041, "Generic IRDA-compatible device"},	/* PNP0510 */
941	{0x1105d041, "Generic IRDA-compatible device"},	/* PNP0511 */
942	{0x01017256, NULL},				/* USR0101 */
943	{0x30207256, NULL},				/* USR2030 */
944	{0x31307256, NULL},				/* USR3031 */
945	{0x8020b04e, NULL},				/* SUP2080 */
946	{0x8024b04e, NULL},				/* SUP2480 */
947	{0}
948};
949
950static int
951sio_isa_probe(dev)
952	device_t	dev;
953{
954	/* Check isapnp ids */
955	if (ISA_PNP_PROBE(device_get_parent(dev), dev, sio_ids) == ENXIO)
956		return (ENXIO);
957	return (sioprobe(dev));
958}
959
960static int
961sioprobe(dev)
962	device_t	dev;
963{
964	static bool_t	already_init;
965	bool_t		failures[10];
966	int		fn;
967	device_t	idev;
968	Port_t		iobase;
969	intrmask_t	irqmap[4];
970	intrmask_t	irqs;
971	u_char		mcr_image;
972	int		result;
973	device_t	xdev;
974	u_int		flags = device_get_flags(dev);
975	int		rid;
976	struct resource *port;
977#ifdef PC98
978	int		irqout=0;
979	int		tmp;
980	int		port_shift = 0;
981	struct siodev	iod;
982	Port_t		rsabase = NULL;
983#endif
984
985	rid = 0;
986#ifdef PC98
987	port = bus_alloc_resource(dev, SYS_RES_IOPORT, &rid,
988				  0, ~0, 1, RF_ACTIVE);		/* XXX */
989#else
990	port = bus_alloc_resource(dev, SYS_RES_IOPORT, &rid,
991				  0, ~0, IO_COMSIZE, RF_ACTIVE);
992#endif
993	if (!port)
994		return ENXIO;
995
996	if (!already_init) {
997		/*
998		 * Turn off MCR_IENABLE for all likely serial ports.  An unused
999		 * port with its MCR_IENABLE gate open will inhibit interrupts
1000		 * from any used port that shares the interrupt vector.
1001		 * XXX the gate enable is elsewhere for some multiports.
1002		 */
1003		device_t *devs;
1004		int count, i;
1005
1006		devclass_get_devices(sio_devclass, &devs, &count);
1007#ifdef PC98
1008		for (i = 0; i < count; i++) {
1009			xdev = devs[i];
1010			if (device_is_enabled(xdev)) {
1011			    tmp = (flags >> 24) & 0xff;
1012			    if (IS_8251(tmp))
1013				outb((isa_get_port(xdev) & 0xff00) | PC98SIO_cmd_port(tmp & 0x0f), 0xf2);
1014			    else
1015				if (tmp == COM_IF_RSA98III) {
1016				    rsabase = isa_get_port(xdev) & 0xfff0;
1017				    outb(isa_get_port(xdev) + 8 + (com_mcr << if_16550a_type[tmp & 0x0f].port_shift), 0);
1018				} else
1019				    outb(isa_get_port(xdev) + (com_mcr << if_16550a_type[tmp & 0x0f].port_shift), 0);
1020			}
1021		}
1022#else
1023		for (i = 0; i < count; i++) {
1024			xdev = devs[i];
1025			if (device_is_enabled(xdev))
1026				outb(isa_get_port(xdev) + com_mcr, 0);
1027		}
1028#endif
1029		free(devs, M_TEMP);
1030		already_init = TRUE;
1031	}
1032
1033	if (COM_LLCONSOLE(flags)) {
1034		printf("sio%d: reserved for low-level i/o\n",
1035		       device_get_unit(dev));
1036		return (ENXIO);
1037	}
1038
1039#ifdef PC98
1040	DELAY(10);
1041
1042	/*
1043	 * If the port is i8251 UART (internal, B98_01)
1044	 */
1045	if (pc98_check_if_type(dev, &iod) == -1)
1046		return ENXIO;
1047	if (iod.irq > 0)
1048		isa_set_irq(dev, iod.irq);
1049	if (IS_8251(iod.if_type)) {
1050		outb(iod.cmd, 0);
1051		DELAY(10);
1052		outb(iod.cmd, 0);
1053		DELAY(10);
1054		outb(iod.cmd, 0);
1055		DELAY(10);
1056		outb(iod.cmd, CMD8251_RESET);
1057		DELAY(1000);		/* for a while...*/
1058		outb(iod.cmd, 0xf2);	/* MODE (dummy) */
1059		DELAY(10);
1060		outb(iod.cmd, 0x01);	/* CMD (dummy) */
1061		DELAY(1000);		/* for a while...*/
1062		if (( inb(iod.sts) & STS8251_TxEMP ) == 0 ) {
1063		    result = ENXIO;
1064		}
1065		if (if_8251_type[iod.if_type & 0x0f].check_irq) {
1066		    COM_INT_DISABLE
1067		    tmp = ( inb( iod.ctrl ) & ~(IEN_Rx|IEN_TxEMP|IEN_Tx));
1068		    outb( iod.ctrl, tmp|IEN_TxEMP );
1069		    DELAY(10);
1070		    result = isa_irq_pending() ? 0 : ENXIO;
1071		    outb( iod.ctrl, tmp );
1072		    COM_INT_ENABLE
1073		} else {
1074		    /*
1075		     * B98_01 doesn't activate TxEMP interrupt line
1076		     * when being reset, so we can't check irq pending.
1077		     */
1078		    result = 0;
1079		}
1080		if (epson_machine_id==0x20) {	/* XXX */
1081		    result = 0;
1082		}
1083		bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
1084		return result;
1085	}
1086#endif /* PC98 */
1087	/*
1088	 * If the device is on a multiport card and has an AST/4
1089	 * compatible interrupt control register, initialize this
1090	 * register and prepare to leave MCR_IENABLE clear in the mcr.
1091	 * Otherwise, prepare to set MCR_IENABLE in the mcr.
1092	 * Point idev to the device struct giving the correct id_irq.
1093	 * This is the struct for the master device if there is one.
1094	 */
1095	idev = dev;
1096	mcr_image = MCR_IENABLE;
1097#ifdef PC98
1098        if (iod.if_type == COM_IF_RSA98III) {
1099		mcr_image = 0;
1100		rsabase = isa_get_port(idev) & 0xfff0;
1101		if (rsabase != isa_get_port(idev))
1102			return(0);
1103		outb(rsabase + rsa_msr,   0x04);
1104		outb(rsabase + rsa_frr,   0x00);
1105		if ((inb(rsabase + rsa_srr) & 0x36) != 0x36)
1106			return (0);
1107		outb(rsabase + rsa_ier,   0x00);
1108		outb(rsabase + rsa_frr,   0x00);
1109		outb(rsabase + rsa_tivsr, 0x00);
1110		outb(rsabase + rsa_tcr,   0x00);
1111	}
1112#endif /* PC98 */
1113#ifdef COM_MULTIPORT
1114	if (COM_ISMULTIPORT(flags)) {
1115		idev = devclass_get_device(sio_devclass, COM_MPMASTER(flags));
1116		if (idev == NULL) {
1117			printf("sio%d: master device %d not configured\n",
1118			       device_get_unit(dev), COM_MPMASTER(flags));
1119			idev = dev;
1120		}
1121#ifndef PC98
1122		if (!COM_NOTAST4(flags)) {
1123			outb(isa_get_port(idev) + com_scr,
1124			     isa_get_irq(idev) >= 0 ? 0x80 : 0);
1125			mcr_image = 0;
1126		}
1127#endif /* !PC98 */
1128	}
1129#endif /* COM_MULTIPORT */
1130	if (isa_get_irq(idev) < 0)
1131		mcr_image = 0;
1132
1133#ifdef PC98
1134	tmp = if_16550a_type[iod.if_type & 0x0f].irr_write;
1135	if (tmp != -1) {
1136	    /* MC16550II */
1137	    switch (isa_get_irq(idev)) {
1138	    case 3: irqout = 4; break;
1139	    case 5: irqout = 5; break;
1140	    case 6: irqout = 6; break;
1141	    case 12: irqout = 7; break;
1142	    default:
1143		printf("sio%d: irq configuration error\n",
1144		       device_get_unit(dev));
1145		return (0);
1146	    }
1147	    outb((isa_get_port(dev) & 0x00ff) | tmp, irqout);
1148	}
1149	port_shift = if_16550a_type[iod.if_type & 0x0f].port_shift;
1150#endif
1151	bzero(failures, sizeof failures);
1152	iobase = rman_get_start(port);
1153#ifdef PC98
1154        if (iod.if_type == COM_IF_RSA98III)
1155		iobase += 8;
1156#endif
1157
1158	/*
1159	 * We don't want to get actual interrupts, just masked ones.
1160	 * Interrupts from this line should already be masked in the ICU,
1161	 * but mask them in the processor as well in case there are some
1162	 * (misconfigured) shared interrupts.
1163	 */
1164	disable_intr();
1165/* EXTRA DELAY? */
1166
1167	/*
1168	 * Initialize the speed and the word size and wait long enough to
1169	 * drain the maximum of 16 bytes of junk in device output queues.
1170	 * The speed is undefined after a master reset and must be set
1171	 * before relying on anything related to output.  There may be
1172	 * junk after a (very fast) soft reboot and (apparently) after
1173	 * master reset.
1174	 * XXX what about the UART bug avoided by waiting in comparam()?
1175	 * We don't want to to wait long enough to drain at 2 bps.
1176	 */
1177	if (iobase == siocniobase)
1178		DELAY((16 + 1) * 1000000 / (comdefaultrate / 10));
1179	else {
1180#ifdef PC98
1181		tmp = ttspeedtab(SIO_TEST_SPEED,
1182				 if_16550a_type[iod.if_type & 0x0f].speedtab);
1183		outb(iobase + (com_cfcr << port_shift), CFCR_DLAB|CFCR_8BITS);
1184		outb(iobase + (com_dlbl << port_shift), tmp & 0xff);
1185		outb(iobase + (com_dlbh << port_shift), (tmp >> 8) & 0xff);
1186		outb(iobase + (com_cfcr << port_shift), CFCR_8BITS);
1187#else
1188		outb(iobase + com_cfcr, CFCR_DLAB | CFCR_8BITS);
1189		outb(iobase + com_dlbl, COMBRD(SIO_TEST_SPEED) & 0xff);
1190		outb(iobase + com_dlbh, (u_int) COMBRD(SIO_TEST_SPEED) >> 8);
1191		outb(iobase + com_cfcr, CFCR_8BITS);
1192#endif
1193		DELAY((16 + 1) * 1000000 / (SIO_TEST_SPEED / 10));
1194	}
1195
1196	/*
1197	 * Enable the interrupt gate and disable device interupts.  This
1198	 * should leave the device driving the interrupt line low and
1199	 * guarantee an edge trigger if an interrupt can be generated.
1200	 */
1201/* EXTRA DELAY? */
1202#ifdef PC98
1203	outb(iobase + (com_mcr << port_shift), mcr_image);
1204	outb(iobase + (com_ier << port_shift), 0);
1205#else
1206	outb(iobase + com_mcr, mcr_image);
1207	outb(iobase + com_ier, 0);
1208#endif
1209	DELAY(1000);		/* XXX */
1210	irqmap[0] = isa_irq_pending();
1211
1212	/*
1213	 * Attempt to set loopback mode so that we can send a null byte
1214	 * without annoying any external device.
1215	 */
1216/* EXTRA DELAY? */
1217#ifdef PC98
1218	outb(iobase + (com_mcr << port_shift), mcr_image | MCR_LOOPBACK);
1219#else
1220	outb(iobase + com_mcr, mcr_image | MCR_LOOPBACK);
1221#endif
1222
1223	/*
1224	 * Attempt to generate an output interrupt.  On 8250's, setting
1225	 * IER_ETXRDY generates an interrupt independent of the current
1226	 * setting and independent of whether the THR is empty.  On 16450's,
1227	 * setting IER_ETXRDY generates an interrupt independent of the
1228	 * current setting.  On 16550A's, setting IER_ETXRDY only
1229	 * generates an interrupt when IER_ETXRDY is not already set.
1230	 */
1231#ifdef PC98
1232	outb(iobase + (com_ier << port_shift), IER_ETXRDY);
1233        if (iod.if_type == COM_IF_RSA98III)
1234		outb(rsabase + rsa_ier,   0x04);
1235#else
1236	outb(iobase + com_ier, IER_ETXRDY);
1237#endif /* PC98 */
1238
1239	/*
1240	 * On some 16x50 incompatibles, setting IER_ETXRDY doesn't generate
1241	 * an interrupt.  They'd better generate one for actually doing
1242	 * output.  Loopback may be broken on the same incompatibles but
1243	 * it's unlikely to do more than allow the null byte out.
1244	 */
1245#ifdef PC98
1246 	outb(iobase + (com_data << port_shift), 0);
1247#else
1248	outb(iobase + com_data, 0);
1249#endif
1250	DELAY((1 + 2) * 1000000 / (SIO_TEST_SPEED / 10));
1251
1252	/*
1253	 * Turn off loopback mode so that the interrupt gate works again
1254	 * (MCR_IENABLE was hidden).  This should leave the device driving
1255	 * an interrupt line high.  It doesn't matter if the interrupt
1256	 * line oscillates while we are not looking at it, since interrupts
1257	 * are disabled.
1258	 */
1259/* EXTRA DELAY? */
1260#ifdef PC98
1261	outb(iobase + (com_mcr << port_shift), mcr_image);
1262#else
1263	outb(iobase + com_mcr, mcr_image);
1264#endif /* PC98 */
1265
1266	/*
1267	 * Some pcmcia cards have the "TXRDY bug", so we check everyone
1268	 * for IIR_TXRDY implementation ( Palido 321s, DC-1S... )
1269	 * XXX Bruce, is this OK? XXX
1270	 */
1271#if 0
1272	/* Reading IIR register twice */
1273	for ( fn = 0; fn < 2; fn ++ ) {
1274		DELAY(10000);
1275#ifdef PC98
1276		failures[6] = inb(iobase + (com_iir << port_shift));
1277#else
1278		failures[6] = inb(iobase + com_iir);
1279#endif
1280	}
1281	/* Check IIR_TXRDY clear ? */
1282	result = 0;
1283	if ( failures[6] & IIR_TXRDY ) {
1284		/* Nop, Double check with clearing IER */
1285#ifdef PC98
1286		outb(iobase + (com_ier << port_shift), 0);
1287		if (inb(iobase + (com_iir << port_shift)) & IIR_NOPEND) {
1288#else
1289		outb(iobase + com_ier, 0);
1290		if ( inb(iobase + com_iir) & IIR_NOPEND ) {
1291#endif
1292			/* Ok. we're familia this gang */
1293			SET_FLAG(dev, COM_C_IIR_TXRDYBUG); /* Set IIR_TXRDYBUG */
1294		} else {
1295			/* Unknown, Just omit this chip.. XXX */
1296			result = ENXIO;
1297		}
1298	} else {
1299		/* OK. this is well-known guys */
1300		CLR_FLAG(dev, COM_C_IIR_TXRDYBUG); /*Clear IIR_TXRDYBUG*/
1301	}
1302#endif
1303	/*
1304	 * Check that
1305	 *	o the CFCR, IER and MCR in UART hold the values written to them
1306	 *	  (the values happen to be all distinct - this is good for
1307	 *	  avoiding false positive tests from bus echoes).
1308	 *	o an output interrupt is generated and its vector is correct.
1309	 *	o the interrupt goes away when the IIR in the UART is read.
1310	 */
1311/* EXTRA DELAY? */
1312#ifdef PC98
1313	failures[0] = inb(iobase + (com_cfcr << port_shift)) - CFCR_8BITS;
1314	failures[1] = inb(iobase + (com_ier << port_shift)) - IER_ETXRDY;
1315	failures[2] = inb(iobase + (com_mcr << port_shift)) - mcr_image;
1316#else
1317	failures[0] = inb(iobase + com_cfcr) - CFCR_8BITS;
1318	failures[1] = inb(iobase + com_ier) - IER_ETXRDY;
1319	failures[2] = inb(iobase + com_mcr) - mcr_image;
1320#endif
1321	DELAY(10000);		/* Some internal modems need this time */
1322	irqmap[1] = isa_irq_pending();
1323#ifdef PC98
1324	failures[4] = (inb(iobase + (com_iir << port_shift)) & IIR_IMASK)
1325	    - IIR_TXRDY;
1326        if (iod.if_type == COM_IF_RSA98III)
1327		inb(rsabase + rsa_srr);
1328#else
1329	failures[4] = (inb(iobase + com_iir) & IIR_IMASK) - IIR_TXRDY;
1330#endif
1331	DELAY(1000);		/* XXX */
1332	irqmap[2] = isa_irq_pending();
1333#ifdef PC98
1334	failures[6] = (inb(iobase + (com_iir << port_shift)) & IIR_IMASK)
1335	    - IIR_NOPEND;
1336        if (iod.if_type == COM_IF_RSA98III)
1337		inb(rsabase + rsa_srr);
1338#else
1339	failures[6] = (inb(iobase + com_iir) & IIR_IMASK) - IIR_NOPEND;
1340#endif
1341
1342	/*
1343	 * Turn off all device interrupts and check that they go off properly.
1344	 * Leave MCR_IENABLE alone.  For ports without a master port, it gates
1345	 * the OUT2 output of the UART to
1346	 * the ICU input.  Closing the gate would give a floating ICU input
1347	 * (unless there is another device driving it) and spurious interrupts.
1348	 * (On the system that this was first tested on, the input floats high
1349	 * and gives a (masked) interrupt as soon as the gate is closed.)
1350	 */
1351#ifdef PC98
1352	outb(iobase + (com_ier << port_shift), 0);
1353	outb(iobase + (com_cfcr << port_shift), CFCR_8BITS);
1354	failures[7] = inb(iobase + (com_ier << port_shift));
1355        if (iod.if_type == COM_IF_RSA98III)
1356		outb(rsabase + rsa_ier,   0x00);
1357#else
1358	outb(iobase + com_ier, 0);
1359	outb(iobase + com_cfcr, CFCR_8BITS);	/* dummy to avoid bus echo */
1360	failures[7] = inb(iobase + com_ier);
1361#endif
1362	DELAY(1000);		/* XXX */
1363	irqmap[3] = isa_irq_pending();
1364#ifdef PC98
1365	failures[9] = (inb(iobase + (com_iir << port_shift)) & IIR_IMASK)
1366	    - IIR_NOPEND;
1367        if (iod.if_type == COM_IF_RSA98III) {
1368		inb(rsabase + rsa_srr);
1369		outb(rsabase + rsa_frr, 0x00);
1370	}
1371#else
1372	failures[9] = (inb(iobase + com_iir) & IIR_IMASK) - IIR_NOPEND;
1373#endif
1374
1375	enable_intr();
1376
1377	irqs = irqmap[1] & ~irqmap[0];
1378	if (isa_get_irq(idev) >= 0 && ((1 << isa_get_irq(idev)) & irqs) == 0)
1379		printf(
1380		"sio%d: configured irq %d not in bitmap of probed irqs %#x\n",
1381		    device_get_unit(dev), isa_get_irq(idev), irqs);
1382	if (bootverbose)
1383		printf("sio%d: irq maps: %#x %#x %#x %#x\n",
1384		    device_get_unit(dev),
1385		    irqmap[0], irqmap[1], irqmap[2], irqmap[3]);
1386
1387	result = 0;
1388	for (fn = 0; fn < sizeof failures; ++fn)
1389		if (failures[fn]) {
1390#ifdef PC98
1391			outb(iobase + (com_mcr << port_shift), 0);
1392#else
1393			outb(iobase + com_mcr, 0);
1394#endif
1395			result = ENXIO;
1396			if (bootverbose) {
1397				printf("sio%d: probe failed test(s):",
1398				    device_get_unit(dev));
1399				for (fn = 0; fn < sizeof failures; ++fn)
1400					if (failures[fn])
1401						printf(" %d", fn);
1402				printf("\n");
1403			}
1404			break;
1405		}
1406	bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
1407	return (iobase == siocniobase ? 0 : result);
1408}
1409
1410#ifdef COM_ESP
1411static int
1412espattach(com, esp_port)
1413	struct com_s		*com;
1414	Port_t			esp_port;
1415{
1416	u_char	dips;
1417	u_char	val;
1418
1419	/*
1420	 * Check the ESP-specific I/O port to see if we're an ESP
1421	 * card.  If not, return failure immediately.
1422	 */
1423	if ((inb(esp_port) & 0xf3) == 0) {
1424		printf(" port 0x%x is not an ESP board?\n", esp_port);
1425		return (0);
1426	}
1427
1428	/*
1429	 * We've got something that claims to be a Hayes ESP card.
1430	 * Let's hope so.
1431	 */
1432
1433	/* Get the dip-switch configuration */
1434#ifdef PC98
1435	outb(esp_port + ESP98_CMD1, ESP_GETDIPS);
1436	dips = inb(esp_port + ESP98_STATUS1);
1437#else
1438	outb(esp_port + ESP_CMD1, ESP_GETDIPS);
1439	dips = inb(esp_port + ESP_STATUS1);
1440#endif
1441
1442	/*
1443	 * Bits 0,1 of dips say which COM port we are.
1444	 */
1445#ifdef PC98
1446	if ((com->iobase & 0xff) == likely_com_ports[dips & 0x03])
1447#else
1448	if (com->iobase == likely_com_ports[dips & 0x03])
1449#endif
1450		printf(" : ESP");
1451	else {
1452		printf(" esp_port has com %d\n", dips & 0x03);
1453		return (0);
1454	}
1455
1456	/*
1457	 * Check for ESP version 2.0 or later:  bits 4,5,6 = 010.
1458	 */
1459#ifdef PC98
1460	outb(esp_port + ESP98_CMD1, ESP_GETTEST);
1461	val = inb(esp_port + ESP98_STATUS1);	/* clear reg 1 */
1462	val = inb(esp_port + ESP98_STATUS2);
1463#else
1464	outb(esp_port + ESP_CMD1, ESP_GETTEST);
1465	val = inb(esp_port + ESP_STATUS1);	/* clear reg 1 */
1466	val = inb(esp_port + ESP_STATUS2);
1467#endif
1468	if ((val & 0x70) < 0x20) {
1469		printf("-old (%o)", val & 0x70);
1470		return (0);
1471	}
1472
1473	/*
1474	 * Check for ability to emulate 16550:  bit 7 == 1
1475	 */
1476	if ((dips & 0x80) == 0) {
1477		printf(" slave");
1478		return (0);
1479	}
1480
1481	/*
1482	 * Okay, we seem to be a Hayes ESP card.  Whee.
1483	 */
1484	com->esp = TRUE;
1485	com->esp_port = esp_port;
1486	return (1);
1487}
1488#endif /* COM_ESP */
1489
1490static int
1491sio_isa_attach(dev)
1492	device_t	dev;
1493{
1494	return (sioattach(dev));
1495}
1496
1497static int
1498sioattach(dev)
1499	device_t	dev;
1500{
1501	struct com_s	*com;
1502#ifdef COM_ESP
1503	Port_t		*espp;
1504#endif
1505	Port_t		iobase;
1506	int		unit;
1507	void		*ih;
1508	u_int		flags = device_get_flags(dev);
1509	int		rid;
1510	struct resource *port;
1511#ifdef PC98
1512	int		port_shift = 0;
1513	u_char		*obuf;
1514	u_long		obufsize;
1515#endif
1516
1517	rid = 0;
1518#ifdef PC98
1519	port = bus_alloc_resource(dev, SYS_RES_IOPORT, &rid,
1520				  0, ~0, 1, RF_ACTIVE);		/* XXX */
1521#else
1522	port = bus_alloc_resource(dev, SYS_RES_IOPORT, &rid,
1523				  0, ~0, IO_COMSIZE, RF_ACTIVE);
1524#endif
1525	if (!port)
1526		return ENXIO;
1527
1528	iobase = rman_get_start(port);
1529#ifdef PC98
1530	if (((flags >> 24) & 0xff) == COM_IF_RSA98III)
1531		iobase += 8;
1532#endif
1533	unit = device_get_unit(dev);
1534	com = device_get_softc(dev);
1535#ifdef PC98
1536	obufsize = 256;
1537	if (((flags >> 24) & 0xff) == COM_IF_RSA98III)
1538		obufsize = 2048;
1539	if ((obuf = malloc(obufsize * 2, M_DEVBUF, M_NOWAIT)) == NULL)
1540		return (0);
1541	bzero(obuf, obufsize * 2);
1542#endif
1543
1544	/*
1545	 * sioprobe() has initialized the device registers as follows:
1546	 *	o cfcr = CFCR_8BITS.
1547	 *	  It is most important that CFCR_DLAB is off, so that the
1548	 *	  data port is not hidden when we enable interrupts.
1549	 *	o ier = 0.
1550	 *	  Interrupts are only enabled when the line is open.
1551	 *	o mcr = MCR_IENABLE, or 0 if the port has AST/4 compatible
1552	 *	  interrupt control register or the config specifies no irq.
1553	 *	  Keeping MCR_DTR and MCR_RTS off might stop the external
1554	 *	  device from sending before we are ready.
1555	 */
1556	bzero(com, sizeof *com);
1557#ifdef PC98
1558	com->obufsize = obufsize;
1559	com->obuf1 = obuf;
1560	com->obuf2 = obuf + obufsize;
1561#endif
1562	com->unit = unit;
1563	com->ioportres = port;
1564	com->cfcr_image = CFCR_8BITS;
1565	com->dtr_wait = 3 * hz;
1566	com->loses_outints = COM_LOSESOUTINTS(flags) != 0;
1567	com->no_irq = isa_get_irq(dev) < 0;
1568	com->tx_fifo_size = 1;
1569	com->obufs[0].l_head = com->obuf1;
1570	com->obufs[1].l_head = com->obuf2;
1571
1572	com->iobase = iobase;
1573#ifdef PC98
1574	if (pc98_set_ioport(com, device_get_flags(dev)) == -1) {
1575	    com->pc98_if_type = (device_get_flags(dev) >> 24) & 0xff;
1576	    port_shift = if_16550a_type[com->pc98_if_type & 0x0f].port_shift;
1577	    com->data_port = iobase + (com_data << port_shift);
1578	    com->int_id_port = iobase + (com_iir << port_shift);
1579	    com->modem_ctl_port = iobase + (com_mcr << port_shift);
1580	    com->mcr_image = inb(com->modem_ctl_port);
1581	    com->line_status_port = iobase + (com_lsr << port_shift);
1582	    com->modem_status_port = iobase + (com_msr << port_shift);
1583	    com->intr_ctl_port = iobase + (com_ier << port_shift);
1584	}
1585#else /* not PC98 */
1586	com->data_port = iobase + com_data;
1587	com->int_id_port = iobase + com_iir;
1588	com->modem_ctl_port = iobase + com_mcr;
1589	com->mcr_image = inb(com->modem_ctl_port);
1590	com->line_status_port = iobase + com_lsr;
1591	com->modem_status_port = iobase + com_msr;
1592	com->intr_ctl_port = iobase + com_ier;
1593#endif
1594
1595	/*
1596	 * We don't use all the flags from <sys/ttydefaults.h> since they
1597	 * are only relevant for logins.  It's important to have echo off
1598	 * initially so that the line doesn't start blathering before the
1599	 * echo flag can be turned off.
1600	 */
1601	com->it_in.c_iflag = 0;
1602	com->it_in.c_oflag = 0;
1603	com->it_in.c_cflag = TTYDEF_CFLAG;
1604	com->it_in.c_lflag = 0;
1605	if (unit == comconsole) {
1606#ifdef PC98
1607		if (IS_8251(com->pc98_if_type))
1608			DELAY(100000);
1609#endif
1610		com->it_in.c_iflag = TTYDEF_IFLAG;
1611		com->it_in.c_oflag = TTYDEF_OFLAG;
1612		com->it_in.c_cflag = TTYDEF_CFLAG | CLOCAL;
1613		com->it_in.c_lflag = TTYDEF_LFLAG;
1614		com->lt_out.c_cflag = com->lt_in.c_cflag = CLOCAL;
1615		com->lt_out.c_ispeed = com->lt_out.c_ospeed =
1616		com->lt_in.c_ispeed = com->lt_in.c_ospeed =
1617		com->it_in.c_ispeed = com->it_in.c_ospeed = comdefaultrate;
1618	} else
1619		com->it_in.c_ispeed = com->it_in.c_ospeed = TTYDEF_SPEED;
1620	if (siosetwater(com, com->it_in.c_ispeed) != 0) {
1621		enable_intr();
1622		free(com, M_DEVBUF);
1623		return (0);
1624	}
1625	enable_intr();
1626	termioschars(&com->it_in);
1627	com->it_out = com->it_in;
1628
1629	/* attempt to determine UART type */
1630	printf("sio%d: type", unit);
1631
1632
1633#ifndef PC98
1634#ifdef COM_MULTIPORT
1635	if (!COM_ISMULTIPORT(flags) && !COM_IIR_TXRDYBUG(flags))
1636#else
1637	if (!COM_IIR_TXRDYBUG(flags))
1638#endif
1639	{
1640		u_char	scr;
1641		u_char	scr1;
1642		u_char	scr2;
1643
1644		scr = inb(iobase + com_scr);
1645		outb(iobase + com_scr, 0xa5);
1646		scr1 = inb(iobase + com_scr);
1647		outb(iobase + com_scr, 0x5a);
1648		scr2 = inb(iobase + com_scr);
1649		outb(iobase + com_scr, scr);
1650		if (scr1 != 0xa5 || scr2 != 0x5a) {
1651			printf(" 8250");
1652			goto determined_type;
1653		}
1654	}
1655#endif /* !PC98 */
1656#ifdef PC98
1657	if (IS_8251(com->pc98_if_type)) {
1658	    com_int_TxRx_disable( com );
1659	    com_cflag_and_speed_set( com, com->it_in.c_cflag, comdefaultrate );
1660	    com_tiocm_bic( com, TIOCM_DTR|TIOCM_RTS|TIOCM_LE );
1661	    com_send_break_off( com );
1662	    printf(" 8251%s", if_8251_type[com->pc98_if_type & 0x0f].name);
1663	} else {
1664	outb(iobase + (com_fifo << port_shift), FIFO_ENABLE | FIFO_RX_HIGH);
1665#else
1666	outb(iobase + com_fifo, FIFO_ENABLE | FIFO_RX_HIGH);
1667#endif /* PC98 */
1668	DELAY(100);
1669	com->st16650a = 0;
1670	switch (inb(com->int_id_port) & IIR_FIFO_MASK) {
1671	case FIFO_RX_LOW:
1672		printf(" 16450");
1673		break;
1674	case FIFO_RX_MEDL:
1675		printf(" 16450?");
1676		break;
1677	case FIFO_RX_MEDH:
1678		printf(" 16550?");
1679		break;
1680	case FIFO_RX_HIGH:
1681		if (COM_NOFIFO(flags)) {
1682			printf(" 16550A fifo disabled");
1683		} else {
1684			com->hasfifo = TRUE;
1685#ifdef PC98
1686			com->tx_fifo_size = 0;	/* XXX flag conflicts. */
1687			printf(" 16550A");
1688#else
1689			if (COM_ST16650A(flags)) {
1690				com->st16650a = 1;
1691				com->tx_fifo_size = 32;
1692				printf(" ST16650A");
1693			} else {
1694				com->tx_fifo_size = COM_FIFOSIZE(flags);
1695				printf(" 16550A");
1696			}
1697#endif
1698		}
1699#ifdef PC98
1700		if (com->pc98_if_type == COM_IF_RSA98III) {
1701			com->tx_fifo_size = 2048;
1702			com->rsabase = isa_get_port(dev);
1703			outb(com->rsabase + rsa_ier, 0x00);
1704			outb(com->rsabase + rsa_frr, 0x00);
1705		}
1706#endif
1707
1708#ifdef COM_ESP
1709#ifdef PC98
1710		if (com->pc98_if_type == COM_IF_ESP98)
1711#endif
1712		for (espp = likely_esp_ports; *espp != 0; espp++)
1713			if (espattach(com, *espp)) {
1714				com->tx_fifo_size = 1024;
1715				break;
1716			}
1717#endif
1718		if (!com->st16650a) {
1719			if (!com->tx_fifo_size)
1720				com->tx_fifo_size = 16;
1721			else
1722				printf(" lookalike with %d bytes FIFO",
1723				    com->tx_fifo_size);
1724		}
1725
1726		break;
1727	}
1728
1729#ifdef PC98
1730	if (com->pc98_if_type == COM_IF_RSB3000) {
1731	    /* Set RSB-2000/3000 Extended Buffer mode. */
1732	    u_char lcr;
1733	    lcr = inb(iobase + (com_cfcr << port_shift));
1734	    outb(iobase + (com_cfcr << port_shift), lcr | CFCR_DLAB);
1735	    outb(iobase + (com_emr << port_shift), EMR_EXBUFF | EMR_EFMODE);
1736	    outb(iobase + (com_cfcr << port_shift), lcr);
1737	}
1738#endif
1739
1740#ifdef COM_ESP
1741	if (com->esp) {
1742		/*
1743		 * Set 16550 compatibility mode.
1744		 * We don't use the ESP_MODE_SCALE bit to increase the
1745		 * fifo trigger levels because we can't handle large
1746		 * bursts of input.
1747		 * XXX flow control should be set in comparam(), not here.
1748		 */
1749#ifdef PC98
1750		outb(com->esp_port + ESP98_CMD1, ESP_SETMODE);
1751		outb(com->esp_port + ESP98_CMD2, ESP_MODE_RTS | ESP_MODE_FIFO);
1752#else
1753		outb(com->esp_port + ESP_CMD1, ESP_SETMODE);
1754		outb(com->esp_port + ESP_CMD2, ESP_MODE_RTS | ESP_MODE_FIFO);
1755#endif
1756
1757		/* Set RTS/CTS flow control. */
1758#ifdef PC98
1759		outb(com->esp_port + ESP98_CMD1, ESP_SETFLOWTYPE);
1760		outb(com->esp_port + ESP98_CMD2, ESP_FLOW_RTS);
1761		outb(com->esp_port + ESP98_CMD2, ESP_FLOW_CTS);
1762#else
1763		outb(com->esp_port + ESP_CMD1, ESP_SETFLOWTYPE);
1764		outb(com->esp_port + ESP_CMD2, ESP_FLOW_RTS);
1765		outb(com->esp_port + ESP_CMD2, ESP_FLOW_CTS);
1766#endif
1767
1768		/* Set flow-control levels. */
1769#ifdef PC98
1770		outb(com->esp_port + ESP98_CMD1, ESP_SETRXFLOW);
1771		outb(com->esp_port + ESP98_CMD2, HIBYTE(768));
1772		outb(com->esp_port + ESP98_CMD2, LOBYTE(768));
1773		outb(com->esp_port + ESP98_CMD2, HIBYTE(512));
1774		outb(com->esp_port + ESP98_CMD2, LOBYTE(512));
1775#else
1776		outb(com->esp_port + ESP_CMD1, ESP_SETRXFLOW);
1777		outb(com->esp_port + ESP_CMD2, HIBYTE(768));
1778		outb(com->esp_port + ESP_CMD2, LOBYTE(768));
1779		outb(com->esp_port + ESP_CMD2, HIBYTE(512));
1780		outb(com->esp_port + ESP_CMD2, LOBYTE(512));
1781#endif
1782
1783#ifdef PC98
1784                /* Set UART clock prescaler. */
1785                outb(com->esp_port + ESP98_CMD1, ESP_SETCLOCK);
1786                outb(com->esp_port + ESP98_CMD2, 2);	/* 4 times */
1787#endif
1788	}
1789#endif /* COM_ESP */
1790#ifdef PC98
1791	printf("%s", if_16550a_type[com->pc98_if_type & 0x0f].name);
1792	outb(iobase + (com_fifo << port_shift), 0);
1793#else
1794	outb(iobase + com_fifo, 0);
1795determined_type: ;
1796#endif
1797
1798#ifdef COM_MULTIPORT
1799	if (COM_ISMULTIPORT(flags)) {
1800		com->multiport = TRUE;
1801		printf(" (multiport");
1802		if (unit == COM_MPMASTER(flags))
1803			printf(" master");
1804		printf(")");
1805		com->no_irq =
1806			isa_get_irq(devclass_get_device
1807				    (sio_devclass, COM_MPMASTER(flags))) < 0;
1808	 }
1809#endif /* COM_MULTIPORT */
1810#ifdef PC98
1811	}
1812#endif
1813	if (unit == comconsole)
1814		printf(", console");
1815	if ( COM_IIR_TXRDYBUG(flags) )
1816		printf(" with a bogus IIR_TXRDY register");
1817	printf("\n");
1818
1819	if (!sio_registered) {
1820		register_swi(SWI_TTY, siopoll);
1821		sio_registered = TRUE;
1822	}
1823	make_dev(&sio_cdevsw, unit,
1824	    UID_ROOT, GID_WHEEL, 0600, "ttyd%r", unit);
1825	make_dev(&sio_cdevsw, unit | CONTROL_INIT_STATE,
1826	    UID_ROOT, GID_WHEEL, 0600, "ttyid%r", unit);
1827	make_dev(&sio_cdevsw, unit | CONTROL_LOCK_STATE,
1828	    UID_ROOT, GID_WHEEL, 0600, "ttyld%r", unit);
1829	make_dev(&sio_cdevsw, unit | CALLOUT_MASK,
1830	    UID_UUCP, GID_DIALER, 0660, "cuaa%r", unit);
1831	make_dev(&sio_cdevsw, unit | CALLOUT_MASK | CONTROL_INIT_STATE,
1832	    UID_UUCP, GID_DIALER, 0660, "cuaia%r", unit);
1833	make_dev(&sio_cdevsw, unit | CALLOUT_MASK | CONTROL_LOCK_STATE,
1834	    UID_UUCP, GID_DIALER, 0660, "cuala%r", unit);
1835	com->flags = flags;
1836	com->pps.ppscap = PPS_CAPTUREASSERT | PPS_CAPTURECLEAR;
1837	pps_init(&com->pps);
1838
1839	rid = 0;
1840	com->irqres = bus_alloc_resource(dev, SYS_RES_IRQ, &rid, 0ul, ~0ul, 1,
1841	    RF_SHAREABLE | RF_ACTIVE);
1842	BUS_SETUP_INTR(device_get_parent(dev), dev, com->irqres,
1843		       INTR_TYPE_TTY | INTR_TYPE_FAST,
1844		       siointr, com, &ih);
1845
1846	return (0);
1847}
1848
1849static int
1850sioopen(dev, flag, mode, p)
1851	dev_t		dev;
1852	int		flag;
1853	int		mode;
1854	struct proc	*p;
1855{
1856	struct com_s	*com;
1857	int		error;
1858	Port_t		iobase;
1859	int		mynor;
1860	int		s;
1861	struct tty	*tp;
1862	int		unit;
1863#ifdef PC98
1864	int		port_shift = 0;
1865#endif
1866
1867	mynor = minor(dev);
1868	unit = MINOR_TO_UNIT(mynor);
1869	if ((u_int) unit >= NSIOTOT || (com = com_addr(unit)) == NULL)
1870		return (ENXIO);
1871	if (com->gone)
1872		return (ENXIO);
1873	if (mynor & CONTROL_MASK)
1874		return (0);
1875	tp = dev->si_tty = com->tp = ttymalloc(com->tp);
1876	s = spltty();
1877
1878#ifdef PC98
1879	if (!IS_8251(com->pc98_if_type))
1880	    port_shift = if_16550a_type[com->pc98_if_type & 0x0f].port_shift;
1881#endif
1882	/*
1883	 * We jump to this label after all non-interrupted sleeps to pick
1884	 * up any changes of the device state.
1885	 */
1886open_top:
1887	while (com->state & CS_DTR_OFF) {
1888		error = tsleep(&com->dtr_wait, TTIPRI | PCATCH, "siodtr", 0);
1889		if (com_addr(unit) == NULL)
1890			return (ENXIO);
1891		if (error != 0 || com->gone)
1892			goto out;
1893	}
1894	if (tp->t_state & TS_ISOPEN) {
1895		/*
1896		 * The device is open, so everything has been initialized.
1897		 * Handle conflicts.
1898		 */
1899		if (mynor & CALLOUT_MASK) {
1900			if (!com->active_out) {
1901				error = EBUSY;
1902				goto out;
1903			}
1904		} else {
1905			if (com->active_out) {
1906				if (flag & O_NONBLOCK) {
1907					error = EBUSY;
1908					goto out;
1909				}
1910				error =	tsleep(&com->active_out,
1911					       TTIPRI | PCATCH, "siobi", 0);
1912				if (com_addr(unit) == NULL)
1913					return (ENXIO);
1914				if (error != 0 || com->gone)
1915					goto out;
1916				goto open_top;
1917			}
1918		}
1919		if (tp->t_state & TS_XCLUDE &&
1920		    suser(p)) {
1921			error = EBUSY;
1922			goto out;
1923		}
1924	} else {
1925		/*
1926		 * The device isn't open, so there are no conflicts.
1927		 * Initialize it.  Initialization is done twice in many
1928		 * cases: to preempt sleeping callin opens if we are
1929		 * callout, and to complete a callin open after DCD rises.
1930		 */
1931		tp->t_oproc = comstart;
1932		tp->t_param = comparam;
1933		tp->t_stop = comstop;
1934		tp->t_dev = dev;
1935		tp->t_termios = mynor & CALLOUT_MASK
1936				? com->it_out : com->it_in;
1937#ifdef PC98
1938		if (!IS_8251(com->pc98_if_type))
1939#endif
1940		(void)commctl(com, TIOCM_DTR | TIOCM_RTS, DMSET);
1941		com->poll = com->no_irq;
1942		com->poll_output = com->loses_outints;
1943		++com->wopeners;
1944		error = comparam(tp, &tp->t_termios);
1945		--com->wopeners;
1946		if (error != 0)
1947			goto out;
1948#ifdef PC98
1949		if (IS_8251(com->pc98_if_type)) {
1950			com_tiocm_bis(com, TIOCM_DTR|TIOCM_RTS);
1951			pc98_msrint_start(dev);
1952		}
1953#endif
1954		/*
1955		 * XXX we should goto open_top if comparam() slept.
1956		 */
1957		iobase = com->iobase;
1958		if (com->hasfifo) {
1959			/*
1960			 * (Re)enable and drain fifos.
1961			 *
1962			 * Certain SMC chips cause problems if the fifos
1963			 * are enabled while input is ready.  Turn off the
1964			 * fifo if necessary to clear the input.  We test
1965			 * the input ready bit after enabling the fifos
1966			 * since we've already enabled them in comparam()
1967			 * and to handle races between enabling and fresh
1968			 * input.
1969			 */
1970			while (TRUE) {
1971#ifdef PC98
1972 				outb(iobase + (com_fifo << port_shift),
1973 				     FIFO_RCV_RST | FIFO_XMT_RST
1974 				     | com->fifo_image);
1975				if (com->pc98_if_type == COM_IF_RSA98III)
1976				  outb(com->rsabase + rsa_frr , 0x00);
1977#else
1978				outb(iobase + com_fifo,
1979				     FIFO_RCV_RST | FIFO_XMT_RST
1980				     | com->fifo_image);
1981#endif
1982				/*
1983				 * XXX the delays are for superstitious
1984				 * historical reasons.  It must be less than
1985				 * the character time at the maximum
1986				 * supported speed (87 usec at 115200 bps
1987				 * 8N1).  Otherwise we might loop endlessly
1988				 * if data is streaming in.  We used to use
1989				 * delays of 100.  That usually worked
1990				 * because DELAY(100) used to usually delay
1991				 * for about 85 usec instead of 100.
1992				 */
1993				DELAY(50);
1994#ifndef PC98
1995				if (!(inb(com->line_status_port) & LSR_RXRDY))
1996#else
1997				if (com->pc98_if_type == COM_IF_RSA98III
1998				    ? !(inb(com->rsabase + rsa_srr) & 0x08)
1999				    : !(inb(com->line_status_port) & LSR_RXRDY))
2000#endif
2001					break;
2002#ifdef PC98
2003 				outb(iobase + (com_fifo << port_shift), 0);
2004#else
2005				outb(iobase + com_fifo, 0);
2006#endif
2007				DELAY(50);
2008				(void) inb(com->data_port);
2009			}
2010		}
2011
2012		disable_intr();
2013#ifdef PC98
2014		if (IS_8251(com->pc98_if_type)) {
2015		    com_tiocm_bis(com, TIOCM_LE);
2016		    com->pc98_prev_modem_status = pc98_get_modem_status(com);
2017		    com_int_Rx_enable(com);
2018		} else {
2019#endif
2020		(void) inb(com->line_status_port);
2021		(void) inb(com->data_port);
2022		com->prev_modem_status = com->last_modem_status
2023		    = inb(com->modem_status_port);
2024		if (COM_IIR_TXRDYBUG(com->flags)) {
2025			outb(com->intr_ctl_port, IER_ERXRDY | IER_ERLS
2026						| IER_EMSC);
2027		} else {
2028			outb(com->intr_ctl_port, IER_ERXRDY | IER_ETXRDY
2029						| IER_ERLS | IER_EMSC);
2030		}
2031#ifdef PC98
2032		if (com->pc98_if_type == COM_IF_RSA98III) {
2033			outb(com->rsabase + rsa_ier, 0x1d);
2034			outb(com->intr_ctl_port, IER_ERLS | IER_EMSC);
2035		}
2036#endif
2037#ifdef PC98
2038		}
2039#endif
2040		enable_intr();
2041		/*
2042		 * Handle initial DCD.  Callout devices get a fake initial
2043		 * DCD (trapdoor DCD).  If we are callout, then any sleeping
2044		 * callin opens get woken up and resume sleeping on "siobi"
2045		 * instead of "siodcd".
2046		 */
2047		/*
2048		 * XXX `mynor & CALLOUT_MASK' should be
2049		 * `tp->t_cflag & (SOFT_CARRIER | TRAPDOOR_CARRIER) where
2050		 * TRAPDOOR_CARRIER is the default initial state for callout
2051		 * devices and SOFT_CARRIER is like CLOCAL except it hides
2052		 * the true carrier.
2053		 */
2054#ifdef PC98
2055		if ((IS_8251(com->pc98_if_type) &&
2056			(pc98_get_modem_status(com) & TIOCM_CAR)) ||
2057		    (!IS_8251(com->pc98_if_type) &&
2058			(com->prev_modem_status & MSR_DCD)) ||
2059		    mynor & CALLOUT_MASK)
2060#else
2061		if (com->prev_modem_status & MSR_DCD || mynor & CALLOUT_MASK)
2062#endif
2063			(*linesw[tp->t_line].l_modem)(tp, 1);
2064	}
2065	/*
2066	 * Wait for DCD if necessary.
2067	 */
2068	if (!(tp->t_state & TS_CARR_ON) && !(mynor & CALLOUT_MASK)
2069	    && !(tp->t_cflag & CLOCAL) && !(flag & O_NONBLOCK)) {
2070		++com->wopeners;
2071		error = tsleep(TSA_CARR_ON(tp), TTIPRI | PCATCH, "siodcd", 0);
2072		if (com_addr(unit) == NULL)
2073			return (ENXIO);
2074		--com->wopeners;
2075		if (error != 0 || com->gone)
2076			goto out;
2077		goto open_top;
2078	}
2079	error =	(*linesw[tp->t_line].l_open)(dev, tp);
2080	disc_optim(tp, &tp->t_termios, com);
2081	if (tp->t_state & TS_ISOPEN && mynor & CALLOUT_MASK)
2082		com->active_out = TRUE;
2083	siosettimeout();
2084out:
2085	splx(s);
2086	if (!(tp->t_state & TS_ISOPEN) && com->wopeners == 0)
2087		comhardclose(com);
2088	return (error);
2089}
2090
2091static int
2092sioclose(dev, flag, mode, p)
2093	dev_t		dev;
2094	int		flag;
2095	int		mode;
2096	struct proc	*p;
2097{
2098	struct com_s	*com;
2099	int		mynor;
2100	int		s;
2101	struct tty	*tp;
2102
2103	mynor = minor(dev);
2104	if (mynor & CONTROL_MASK)
2105		return (0);
2106	com = com_addr(MINOR_TO_UNIT(mynor));
2107	tp = com->tp;
2108	s = spltty();
2109	(*linesw[tp->t_line].l_close)(tp, flag);
2110#ifdef PC98
2111	com->modem_checking = 0;
2112#endif
2113	disc_optim(tp, &tp->t_termios, com);
2114	comstop(tp, FREAD | FWRITE);
2115	comhardclose(com);
2116	ttyclose(tp);
2117	siosettimeout();
2118	splx(s);
2119	if (com->gone) {
2120		printf("sio%d: gone\n", com->unit);
2121		s = spltty();
2122		if (com->ibuf != NULL)
2123			free(com->ibuf, M_DEVBUF);
2124		bzero(tp, sizeof *tp);
2125		free(com, M_DEVBUF);
2126		splx(s);
2127	}
2128	return (0);
2129}
2130
2131static void
2132comhardclose(com)
2133	struct com_s	*com;
2134{
2135	Port_t		iobase;
2136	int		s;
2137	struct tty	*tp;
2138	int		unit;
2139#ifdef PC98
2140	int		port_shift = 0;
2141#endif
2142
2143	unit = com->unit;
2144	iobase = com->iobase;
2145	s = spltty();
2146	com->poll = FALSE;
2147	com->poll_output = FALSE;
2148	com->do_timestamp = FALSE;
2149	com->do_dcd_timestamp = FALSE;
2150	com->pps.ppsparam.mode = 0;
2151#ifdef PC98
2152	if (IS_8251(com->pc98_if_type))
2153	    com_send_break_off(com);
2154	else {
2155	    port_shift = if_16550a_type[com->pc98_if_type & 0x0f].port_shift;
2156	    outb(iobase + (com_cfcr << port_shift),
2157		 com->cfcr_image &= ~CFCR_SBREAK);
2158	}
2159#else
2160	outb(iobase + com_cfcr, com->cfcr_image &= ~CFCR_SBREAK);
2161#endif
2162	{
2163#ifdef PC98
2164		int tmp;
2165		if (IS_8251(com->pc98_if_type))
2166			com_int_TxRx_disable(com);
2167		else
2168			outb(iobase + (com_ier << port_shift), 0);
2169		if (com->pc98_if_type == COM_IF_RSA98III) {
2170			outb(com->rsabase + rsa_ier, 0x00);
2171		}
2172#else
2173		outb(iobase + com_ier, 0);
2174#endif
2175		tp = com->tp;
2176#ifdef PC98
2177		if (IS_8251(com->pc98_if_type))
2178			tmp = pc98_get_modem_status(com) & TIOCM_CAR;
2179		else
2180			tmp = com->prev_modem_status & MSR_DCD;
2181#endif
2182		if (tp->t_cflag & HUPCL
2183		    /*
2184		     * XXX we will miss any carrier drop between here and the
2185		     * next open.  Perhaps we should watch DCD even when the
2186		     * port is closed; it is not sufficient to check it at
2187		     * the next open because it might go up and down while
2188		     * we're not watching.
2189		     */
2190		    || (!com->active_out
2191#ifdef PC98
2192		       && !(tmp)
2193#else
2194		        && !(com->prev_modem_status & MSR_DCD)
2195#endif
2196		        && !(com->it_in.c_cflag & CLOCAL))
2197		    || !(tp->t_state & TS_ISOPEN)) {
2198#ifdef PC98
2199			if (IS_8251(com->pc98_if_type))
2200			    com_tiocm_bic(com, TIOCM_DTR|TIOCM_RTS|TIOCM_LE);
2201			else
2202#endif
2203			(void)commctl(com, TIOCM_DTR, DMBIC);
2204			if (com->dtr_wait != 0 && !(com->state & CS_DTR_OFF)) {
2205				timeout(siodtrwakeup, com, com->dtr_wait);
2206				com->state |= CS_DTR_OFF;
2207			}
2208		}
2209#ifdef PC98
2210		else {
2211			if (IS_8251(com->pc98_if_type))
2212				com_tiocm_bic(com, TIOCM_LE );
2213		}
2214#endif
2215	}
2216	if (com->hasfifo) {
2217		/*
2218		 * Disable fifos so that they are off after controlled
2219		 * reboots.  Some BIOSes fail to detect 16550s when the
2220		 * fifos are enabled.
2221		 */
2222#ifdef PC98
2223		outb(iobase + (com_fifo << port_shift), 0);
2224#else
2225		outb(iobase + com_fifo, 0);
2226#endif
2227	}
2228	com->active_out = FALSE;
2229	wakeup(&com->active_out);
2230	wakeup(TSA_CARR_ON(tp));	/* restart any wopeners */
2231	splx(s);
2232}
2233
2234static int
2235sioread(dev, uio, flag)
2236	dev_t		dev;
2237	struct uio	*uio;
2238	int		flag;
2239{
2240	int		mynor;
2241	struct com_s	*com;
2242
2243	mynor = minor(dev);
2244	if (mynor & CONTROL_MASK)
2245		return (ENODEV);
2246	com = com_addr(MINOR_TO_UNIT(mynor));
2247	if (com->gone)
2248		return (ENODEV);
2249	return ((*linesw[com->tp->t_line].l_read)(com->tp, uio, flag));
2250}
2251
2252static int
2253siowrite(dev, uio, flag)
2254	dev_t		dev;
2255	struct uio	*uio;
2256	int		flag;
2257{
2258	int		mynor;
2259	struct com_s	*com;
2260	int		unit;
2261
2262	mynor = minor(dev);
2263	if (mynor & CONTROL_MASK)
2264		return (ENODEV);
2265
2266	unit = MINOR_TO_UNIT(mynor);
2267	com = com_addr(unit);
2268	if (com->gone)
2269		return (ENODEV);
2270	/*
2271	 * (XXX) We disallow virtual consoles if the physical console is
2272	 * a serial port.  This is in case there is a display attached that
2273	 * is not the console.  In that situation we don't need/want the X
2274	 * server taking over the console.
2275	 */
2276	if (constty != NULL && unit == comconsole)
2277		constty = NULL;
2278	return ((*linesw[com->tp->t_line].l_write)(com->tp, uio, flag));
2279}
2280
2281static void
2282siobusycheck(chan)
2283	void	*chan;
2284{
2285	struct com_s	*com;
2286	int		s;
2287
2288	com = (struct com_s *)chan;
2289
2290	/*
2291	 * Clear TS_BUSY if low-level output is complete.
2292	 * spl locking is sufficient because siointr1() does not set CS_BUSY.
2293	 * If siointr1() clears CS_BUSY after we look at it, then we'll get
2294	 * called again.  Reading the line status port outside of siointr1()
2295	 * is safe because CS_BUSY is clear so there are no output interrupts
2296	 * to lose.
2297	 */
2298	s = spltty();
2299	if (com->state & CS_BUSY)
2300		com->extra_state &= ~CSE_BUSYCHECK;	/* False alarm. */
2301#ifdef	PC98
2302	else if ((IS_8251(com->pc98_if_type) &&
2303		 (inb(com->sts_port) & (STS8251_TxRDY | STS8251_TxEMP))
2304		 == (STS8251_TxRDY | STS8251_TxEMP)) ||
2305		 (inb(com->line_status_port) & (LSR_TSRE | LSR_TXRDY))
2306		 == (LSR_TSRE | LSR_TXRDY)) {
2307#else
2308	else if ((inb(com->line_status_port) & (LSR_TSRE | LSR_TXRDY))
2309	    == (LSR_TSRE | LSR_TXRDY)) {
2310#endif
2311		com->tp->t_state &= ~TS_BUSY;
2312		ttwwakeup(com->tp);
2313		com->extra_state &= ~CSE_BUSYCHECK;
2314	} else
2315		timeout(siobusycheck, com, hz / 100);
2316	splx(s);
2317}
2318
2319static void
2320siodtrwakeup(chan)
2321	void	*chan;
2322{
2323	struct com_s	*com;
2324
2325	com = (struct com_s *)chan;
2326	com->state &= ~CS_DTR_OFF;
2327	wakeup(&com->dtr_wait);
2328}
2329
2330static void
2331sioinput(com)
2332	struct com_s	*com;
2333{
2334	u_char		*buf;
2335	int		incc;
2336	u_char		line_status;
2337	int		recv_data;
2338	struct tty	*tp;
2339#ifdef PC98
2340	u_char		tmp;
2341#endif
2342
2343	buf = com->ibuf;
2344	tp = com->tp;
2345	if (!(tp->t_state & TS_ISOPEN) || !(tp->t_cflag & CREAD)) {
2346		com_events -= (com->iptr - com->ibuf);
2347		com->iptr = com->ibuf;
2348		return;
2349	}
2350	if (tp->t_state & TS_CAN_BYPASS_L_RINT) {
2351		/*
2352		 * Avoid the grotesquely inefficient lineswitch routine
2353		 * (ttyinput) in "raw" mode.  It usually takes about 450
2354		 * instructions (that's without canonical processing or echo!).
2355		 * slinput is reasonably fast (usually 40 instructions plus
2356		 * call overhead).
2357		 */
2358		do {
2359			enable_intr();
2360			incc = com->iptr - buf;
2361			if (tp->t_rawq.c_cc + incc > tp->t_ihiwat
2362			    && (com->state & CS_RTS_IFLOW
2363				|| tp->t_iflag & IXOFF)
2364			    && !(tp->t_state & TS_TBLOCK))
2365				ttyblock(tp);
2366			com->delta_error_counts[CE_TTY_BUF_OVERFLOW]
2367				+= b_to_q((char *)buf, incc, &tp->t_rawq);
2368			buf += incc;
2369			tk_nin += incc;
2370			tk_rawcc += incc;
2371			tp->t_rawcc += incc;
2372			ttwakeup(tp);
2373			if (tp->t_state & TS_TTSTOP
2374			    && (tp->t_iflag & IXANY
2375				|| tp->t_cc[VSTART] == tp->t_cc[VSTOP])) {
2376				tp->t_state &= ~TS_TTSTOP;
2377				tp->t_lflag &= ~FLUSHO;
2378				comstart(tp);
2379			}
2380			disable_intr();
2381		} while (buf < com->iptr);
2382	} else {
2383		do {
2384			enable_intr();
2385			line_status = buf[com->ierroff];
2386			recv_data = *buf++;
2387			if (line_status
2388			    & (LSR_BI | LSR_FE | LSR_OE | LSR_PE)) {
2389				if (line_status & LSR_BI)
2390					recv_data |= TTY_BI;
2391				if (line_status & LSR_FE)
2392					recv_data |= TTY_FE;
2393				if (line_status & LSR_OE)
2394					recv_data |= TTY_OE;
2395				if (line_status & LSR_PE)
2396					recv_data |= TTY_PE;
2397			}
2398			(*linesw[tp->t_line].l_rint)(recv_data, tp);
2399			disable_intr();
2400		} while (buf < com->iptr);
2401	}
2402	com_events -= (com->iptr - com->ibuf);
2403	com->iptr = com->ibuf;
2404
2405	/*
2406	 * There is now room for another low-level buffer full of input,
2407	 * so enable RTS if it is now disabled and there is room in the
2408	 * high-level buffer.
2409	 */
2410#ifdef PC98
2411	if (IS_8251(com->pc98_if_type))
2412		tmp = com_tiocm_get(com) & TIOCM_RTS;
2413	else
2414		tmp = com->mcr_image & MCR_RTS;
2415	if ((com->state & CS_RTS_IFLOW) && !(tmp) &&
2416	    !(tp->t_state & TS_TBLOCK))
2417		if (IS_8251(com->pc98_if_type))
2418			com_tiocm_bis(com, TIOCM_RTS);
2419		else
2420			outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
2421#else
2422	if ((com->state & CS_RTS_IFLOW) && !(com->mcr_image & MCR_RTS) &&
2423	    !(tp->t_state & TS_TBLOCK))
2424		outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
2425#endif
2426}
2427
2428void
2429siointr(arg)
2430	void		*arg;
2431{
2432#ifndef COM_MULTIPORT
2433	COM_LOCK();
2434	siointr1((struct com_s *) arg);
2435	COM_UNLOCK();
2436#else /* COM_MULTIPORT */
2437	bool_t		possibly_more_intrs;
2438	int		unit;
2439	struct com_s	*com;
2440#ifdef PC98
2441	u_char		rsa_buf_status;
2442#endif
2443
2444	/*
2445	 * Loop until there is no activity on any port.  This is necessary
2446	 * to get an interrupt edge more than to avoid another interrupt.
2447	 * If the IRQ signal is just an OR of the IRQ signals from several
2448	 * devices, then the edge from one may be lost because another is
2449	 * on.
2450	 */
2451	COM_LOCK();
2452	do {
2453		possibly_more_intrs = FALSE;
2454		for (unit = 0; unit < NSIOTOT; ++unit) {
2455			com = com_addr(unit);
2456			/*
2457			 * XXX COM_LOCK();
2458			 * would it work here, or be counter-productive?
2459			 */
2460#ifdef PC98
2461			if (com != NULL
2462			    && !com->gone
2463			    && IS_8251(com->pc98_if_type)){
2464				siointr1(com);
2465			} else
2466#endif /* PC98 */
2467#ifdef PC98
2468			if (com != NULL
2469			    && !com->gone
2470			    && com->pc98_if_type == COM_IF_RSA98III) {
2471			  rsa_buf_status = inb(com->rsabase + rsa_srr) & 0xc9;
2472			  if ((rsa_buf_status & 0xc8)
2473			      || !(rsa_buf_status & 0x01)) {
2474			    siointr1(com);
2475			    if(rsa_buf_status
2476			       != (inb(com->rsabase + rsa_srr) & 0xc9))
2477			      possibly_more_intrs = TRUE;
2478			  }
2479			} else
2480#endif
2481			if (com != NULL
2482			    && !com->gone
2483			    && (inb(com->int_id_port) & IIR_IMASK)
2484			       != IIR_NOPEND) {
2485				siointr1(com);
2486				possibly_more_intrs = TRUE;
2487			}
2488			/* XXX COM_UNLOCK(); */
2489		}
2490	} while (possibly_more_intrs);
2491	COM_UNLOCK();
2492#endif /* COM_MULTIPORT */
2493}
2494
2495static void
2496siointr1(com)
2497	struct com_s	*com;
2498{
2499	u_char	line_status;
2500	u_char	modem_status;
2501	u_char	*ioptr;
2502	u_char	recv_data;
2503	u_char	int_ctl;
2504	u_char	int_ctl_new;
2505	struct	timecounter *tc;
2506	u_int	count;
2507
2508#ifdef PC98
2509	u_char	tmp=0;
2510	u_char	rsa_buf_status = 0;
2511	int	rsa_tx_fifo_size=0;
2512	recv_data=0;
2513#endif /* PC98 */
2514
2515	int_ctl = inb(com->intr_ctl_port);
2516	int_ctl_new = int_ctl;
2517
2518	while (!com->gone) {
2519#ifdef PC98
2520status_read:;
2521		if (IS_8251(com->pc98_if_type)) {
2522			tmp = inb(com->sts_port);
2523more_intr:
2524			line_status = 0;
2525			if (tmp & STS8251_TxRDY) line_status |= LSR_TXRDY;
2526			if (tmp & STS8251_RxRDY) line_status |= LSR_RXRDY;
2527			if (tmp & STS8251_TxEMP) line_status |= LSR_TSRE;
2528			if (tmp & STS8251_PE)    line_status |= LSR_PE;
2529			if (tmp & STS8251_OE)    line_status |= LSR_OE;
2530			if (tmp & STS8251_FE)    line_status |= LSR_FE;
2531			if (tmp & STS8251_BD_SD) line_status |= LSR_BI;
2532		} else {
2533#endif /* PC98 */
2534		if (com->pps.ppsparam.mode & PPS_CAPTUREBOTH) {
2535			modem_status = inb(com->modem_status_port);
2536		        if ((modem_status ^ com->last_modem_status) & MSR_DCD) {
2537				tc = timecounter;
2538				count = tc->tc_get_timecount(tc);
2539				pps_event(&com->pps, tc, count,
2540				    (modem_status & MSR_DCD) ?
2541				    PPS_CAPTUREASSERT : PPS_CAPTURECLEAR);
2542			}
2543		}
2544		line_status = inb(com->line_status_port);
2545#ifdef PC98
2546		}
2547		if (com->pc98_if_type == COM_IF_RSA98III)
2548			rsa_buf_status = inb(com->rsabase + rsa_srr);
2549#endif /* PC98 */
2550
2551		/* input event? (check first to help avoid overruns) */
2552#ifndef PC98
2553		while (line_status & LSR_RCV_MASK) {
2554#else
2555		while ((line_status & LSR_RCV_MASK)
2556		       || (com->pc98_if_type == COM_IF_RSA98III
2557			   && (rsa_buf_status & 0x08))) {
2558#endif /* PC98 */
2559			/* break/unnattached error bits or real input? */
2560#ifdef PC98
2561			if (IS_8251(com->pc98_if_type)) {
2562				recv_data = inb(com->data_port);
2563				if (tmp & 0x78) {
2564					pc98_i8251_or_cmd(com,CMD8251_ER);
2565					recv_data = 0;
2566				}
2567			} else {
2568#endif /* PC98 */
2569#ifdef PC98
2570			if (com->pc98_if_type == COM_IF_RSA98III) {
2571			  if (!(rsa_buf_status & 0x08))
2572			    recv_data = 0;
2573			  else {
2574			    recv_data = inb(com->data_port);
2575			  }
2576			} else
2577#endif
2578			if (!(line_status & LSR_RXRDY))
2579				recv_data = 0;
2580			else
2581				recv_data = inb(com->data_port);
2582#ifdef PC98
2583			}
2584#endif
2585			if (line_status & (LSR_BI | LSR_FE | LSR_PE)) {
2586				/*
2587				 * Don't store BI if IGNBRK or FE/PE if IGNPAR.
2588				 * Otherwise, push the work to a higher level
2589				 * (to handle PARMRK) if we're bypassing.
2590				 * Otherwise, convert BI/FE and PE+INPCK to 0.
2591				 *
2592				 * This makes bypassing work right in the
2593				 * usual "raw" case (IGNBRK set, and IGNPAR
2594				 * and INPCK clear).
2595				 *
2596				 * Note: BI together with FE/PE means just BI.
2597				 */
2598				if (line_status & LSR_BI) {
2599#if defined(DDB) && defined(BREAK_TO_DEBUGGER)
2600					if (com->unit == comconsole) {
2601						breakpoint();
2602						goto cont;
2603					}
2604#endif
2605					if (com->tp == NULL
2606					    || com->tp->t_iflag & IGNBRK)
2607						goto cont;
2608				} else {
2609					if (com->tp == NULL
2610					    || com->tp->t_iflag & IGNPAR)
2611						goto cont;
2612				}
2613				if (com->tp->t_state & TS_CAN_BYPASS_L_RINT
2614				    && (line_status & (LSR_BI | LSR_FE)
2615					|| com->tp->t_iflag & INPCK))
2616					recv_data = 0;
2617			}
2618			++com->bytes_in;
2619			if (com->hotchar != 0 && recv_data == com->hotchar)
2620				setsofttty();
2621			ioptr = com->iptr;
2622			if (ioptr >= com->ibufend)
2623				CE_RECORD(com, CE_INTERRUPT_BUF_OVERFLOW);
2624			else {
2625				if (com->do_timestamp)
2626					microtime(&com->timestamp);
2627				++com_events;
2628				schedsofttty();
2629#if 0 /* for testing input latency vs efficiency */
2630if (com->iptr - com->ibuf == 8)
2631	setsofttty();
2632#endif
2633				ioptr[0] = recv_data;
2634				ioptr[com->ierroff] = line_status;
2635				com->iptr = ++ioptr;
2636				if (ioptr == com->ihighwater
2637				    && com->state & CS_RTS_IFLOW)
2638#ifdef PC98
2639					if (IS_8251(com->pc98_if_type))
2640						com_tiocm_bic(com, TIOCM_RTS);
2641					else
2642#endif
2643					outb(com->modem_ctl_port,
2644					     com->mcr_image &= ~MCR_RTS);
2645				if (line_status & LSR_OE)
2646					CE_RECORD(com, CE_OVERRUN);
2647			}
2648cont:
2649			/*
2650			 * "& 0x7F" is to avoid the gcc-1.40 generating a slow
2651			 * jump from the top of the loop to here
2652			 */
2653#ifdef PC98
2654			if (IS_8251(com->pc98_if_type))
2655				goto status_read;
2656			else
2657#endif
2658			line_status = inb(com->line_status_port) & 0x7F;
2659#ifdef PC98
2660			if (com->pc98_if_type == COM_IF_RSA98III)
2661				rsa_buf_status = inb(com->rsabase + rsa_srr);
2662#endif /* PC98 */
2663		}
2664
2665		/* modem status change? (always check before doing output) */
2666#ifdef PC98
2667		if (!IS_8251(com->pc98_if_type)) {
2668#endif
2669		modem_status = inb(com->modem_status_port);
2670		if (modem_status != com->last_modem_status) {
2671			if (com->do_dcd_timestamp
2672			    && !(com->last_modem_status & MSR_DCD)
2673			    && modem_status & MSR_DCD)
2674				microtime(&com->dcd_timestamp);
2675
2676			/*
2677			 * Schedule high level to handle DCD changes.  Note
2678			 * that we don't use the delta bits anywhere.  Some
2679			 * UARTs mess them up, and it's easy to remember the
2680			 * previous bits and calculate the delta.
2681			 */
2682			com->last_modem_status = modem_status;
2683			if (!(com->state & CS_CHECKMSR)) {
2684				com_events += LOTS_OF_EVENTS;
2685				com->state |= CS_CHECKMSR;
2686				setsofttty();
2687			}
2688
2689			/* handle CTS change immediately for crisp flow ctl */
2690			if (com->state & CS_CTS_OFLOW) {
2691				if (modem_status & MSR_CTS)
2692					com->state |= CS_ODEVREADY;
2693				else
2694					com->state &= ~CS_ODEVREADY;
2695			}
2696		}
2697#ifdef PC98
2698		}
2699#endif
2700
2701		/* output queued and everything ready? */
2702#ifndef PC98
2703		if (line_status & LSR_TXRDY
2704		    && com->state >= (CS_BUSY | CS_TTGO | CS_ODEVREADY)) {
2705#else
2706		if (((com->pc98_if_type == COM_IF_RSA98III)
2707		     ? (rsa_buf_status & 0x02)
2708		     : (line_status & LSR_TXRDY))
2709		    && com->state >= (CS_BUSY | CS_TTGO | CS_ODEVREADY)) {
2710#endif
2711			ioptr = com->obufq.l_head;
2712			if (com->tx_fifo_size > 1) {
2713				u_int	ocount;
2714
2715				ocount = com->obufq.l_tail - ioptr;
2716#ifdef PC98
2717				if (com->pc98_if_type == COM_IF_RSA98III) {
2718				  rsa_buf_status = inb(com->rsabase + rsa_srr);
2719				  rsa_tx_fifo_size = 1024;
2720				  if (!(rsa_buf_status & 0x01))
2721				    rsa_tx_fifo_size = 2048;
2722				  if (ocount > rsa_tx_fifo_size)
2723				    ocount = rsa_tx_fifo_size;
2724				} else
2725#endif
2726				if (ocount > com->tx_fifo_size)
2727					ocount = com->tx_fifo_size;
2728				com->bytes_out += ocount;
2729				do
2730					outb(com->data_port, *ioptr++);
2731				while (--ocount != 0);
2732			} else {
2733				outb(com->data_port, *ioptr++);
2734				++com->bytes_out;
2735			}
2736#ifdef PC98
2737			if (IS_8251(com->pc98_if_type))
2738			    if (!(pc98_check_i8251_interrupt(com) & IEN_TxFLAG))
2739					com_int_Tx_enable(com);
2740#endif
2741			com->obufq.l_head = ioptr;
2742			if (COM_IIR_TXRDYBUG(com->flags)) {
2743				int_ctl_new = int_ctl | IER_ETXRDY;
2744			}
2745			if (ioptr >= com->obufq.l_tail) {
2746				struct lbq	*qp;
2747
2748				qp = com->obufq.l_next;
2749				qp->l_queued = FALSE;
2750				qp = qp->l_next;
2751				if (qp != NULL) {
2752					com->obufq.l_head = qp->l_head;
2753					com->obufq.l_tail = qp->l_tail;
2754					com->obufq.l_next = qp;
2755				} else {
2756					/* output just completed */
2757					if ( COM_IIR_TXRDYBUG(com->flags) ) {
2758						int_ctl_new = int_ctl & ~IER_ETXRDY;
2759					}
2760					com->state &= ~CS_BUSY;
2761#if defined(PC98)
2762					if (IS_8251(com->pc98_if_type))
2763					    if ( pc98_check_i8251_interrupt(com) & IEN_TxFLAG )
2764						com_int_Tx_disable(com);
2765#endif
2766				}
2767				if (!(com->state & CS_ODONE)) {
2768					com_events += LOTS_OF_EVENTS;
2769					com->state |= CS_ODONE;
2770					setsofttty();	/* handle at high level ASAP */
2771				}
2772			}
2773			if ( COM_IIR_TXRDYBUG(com->flags) && (int_ctl != int_ctl_new)) {
2774#ifdef PC98
2775				if (com->pc98_if_type == COM_IF_RSA98III) {
2776				  int_ctl_new &= ~(IER_ETXRDY | IER_ERXRDY);
2777				  outb(com->intr_ctl_port, int_ctl_new);
2778				  outb(com->rsabase + rsa_ier, 0x1d);
2779				} else
2780#endif
2781				outb(com->intr_ctl_port, int_ctl_new);
2782			}
2783		}
2784#ifdef PC98
2785		else if (line_status & LSR_TXRDY) {
2786		    if (IS_8251(com->pc98_if_type))
2787			if ( pc98_check_i8251_interrupt(com) & IEN_TxFLAG )
2788			    com_int_Tx_disable(com);
2789		}
2790		if (IS_8251(com->pc98_if_type))
2791		    if ((tmp = inb(com->sts_port)) & STS8251_RxRDY)
2792			goto more_intr;
2793#endif
2794
2795		/* finished? */
2796#ifndef COM_MULTIPORT
2797#ifdef PC98
2798		if (IS_8251(com->pc98_if_type))
2799			return;
2800#endif
2801		if ((inb(com->int_id_port) & IIR_IMASK) == IIR_NOPEND)
2802#endif /* COM_MULTIPORT */
2803			return;
2804	}
2805}
2806
2807static int
2808sioioctl(dev, cmd, data, flag, p)
2809	dev_t		dev;
2810	u_long		cmd;
2811	caddr_t		data;
2812	int		flag;
2813	struct proc	*p;
2814{
2815	struct com_s	*com;
2816	int		error;
2817	Port_t		iobase;
2818	int		mynor;
2819	int		s;
2820	struct tty	*tp;
2821#if defined(COMPAT_43) || defined(COMPAT_SUNOS)
2822	u_long		oldcmd;
2823	struct termios	term;
2824#endif
2825
2826	mynor = minor(dev);
2827	com = com_addr(MINOR_TO_UNIT(mynor));
2828	if (com->gone)
2829		return (ENODEV);
2830	iobase = com->iobase;
2831	if (mynor & CONTROL_MASK) {
2832		struct termios	*ct;
2833
2834		switch (mynor & CONTROL_MASK) {
2835		case CONTROL_INIT_STATE:
2836			ct = mynor & CALLOUT_MASK ? &com->it_out : &com->it_in;
2837			break;
2838		case CONTROL_LOCK_STATE:
2839			ct = mynor & CALLOUT_MASK ? &com->lt_out : &com->lt_in;
2840			break;
2841		default:
2842			return (ENODEV);	/* /dev/nodev */
2843		}
2844		switch (cmd) {
2845		case TIOCSETA:
2846			error = suser(p);
2847			if (error != 0)
2848				return (error);
2849			*ct = *(struct termios *)data;
2850			return (0);
2851		case TIOCGETA:
2852			*(struct termios *)data = *ct;
2853			return (0);
2854		case TIOCGETD:
2855			*(int *)data = TTYDISC;
2856			return (0);
2857		case TIOCGWINSZ:
2858			bzero(data, sizeof(struct winsize));
2859			return (0);
2860		default:
2861			return (ENOTTY);
2862		}
2863	}
2864	tp = com->tp;
2865#if defined(COMPAT_43) || defined(COMPAT_SUNOS)
2866	term = tp->t_termios;
2867	oldcmd = cmd;
2868	error = ttsetcompat(tp, &cmd, data, &term);
2869	if (error != 0)
2870		return (error);
2871	if (cmd != oldcmd)
2872		data = (caddr_t)&term;
2873#endif
2874	if (cmd == TIOCSETA || cmd == TIOCSETAW || cmd == TIOCSETAF) {
2875		int	cc;
2876		struct termios *dt = (struct termios *)data;
2877		struct termios *lt = mynor & CALLOUT_MASK
2878				     ? &com->lt_out : &com->lt_in;
2879
2880		dt->c_iflag = (tp->t_iflag & lt->c_iflag)
2881			      | (dt->c_iflag & ~lt->c_iflag);
2882		dt->c_oflag = (tp->t_oflag & lt->c_oflag)
2883			      | (dt->c_oflag & ~lt->c_oflag);
2884		dt->c_cflag = (tp->t_cflag & lt->c_cflag)
2885			      | (dt->c_cflag & ~lt->c_cflag);
2886		dt->c_lflag = (tp->t_lflag & lt->c_lflag)
2887			      | (dt->c_lflag & ~lt->c_lflag);
2888		for (cc = 0; cc < NCCS; ++cc)
2889			if (lt->c_cc[cc] != 0)
2890				dt->c_cc[cc] = tp->t_cc[cc];
2891		if (lt->c_ispeed != 0)
2892			dt->c_ispeed = tp->t_ispeed;
2893		if (lt->c_ospeed != 0)
2894			dt->c_ospeed = tp->t_ospeed;
2895	}
2896	error = (*linesw[tp->t_line].l_ioctl)(tp, cmd, data, flag, p);
2897	if (error != ENOIOCTL)
2898		return (error);
2899	s = spltty();
2900	error = ttioctl(tp, cmd, data, flag);
2901	disc_optim(tp, &tp->t_termios, com);
2902	if (error != ENOIOCTL) {
2903		splx(s);
2904		return (error);
2905	}
2906#ifdef PC98
2907	if (IS_8251(com->pc98_if_type)) {
2908	    switch (cmd) {
2909	    case TIOCSBRK:
2910		com_send_break_on( com );
2911		break;
2912	    case TIOCCBRK:
2913		com_send_break_off( com );
2914		break;
2915	    case TIOCSDTR:
2916		com_tiocm_bis(com, TIOCM_DTR | TIOCM_RTS );
2917		break;
2918	    case TIOCCDTR:
2919		com_tiocm_bic(com, TIOCM_DTR);
2920		break;
2921	/*
2922	 * XXX should disallow changing MCR_RTS if CS_RTS_IFLOW is set.  The
2923	 * changes get undone on the next call to comparam().
2924	 */
2925	    case TIOCMSET:
2926		com_tiocm_set( com, *(int *)data );
2927		break;
2928	    case TIOCMBIS:
2929		com_tiocm_bis( com, *(int *)data );
2930		break;
2931	    case TIOCMBIC:
2932		com_tiocm_bic( com, *(int *)data );
2933		break;
2934	    case TIOCMGET:
2935		*(int *)data = com_tiocm_get(com);
2936		break;
2937	    case TIOCMSDTRWAIT:
2938		/* must be root since the wait applies to following logins */
2939		error = suser(p);
2940		if (error != 0) {
2941			splx(s);
2942			return (error);
2943		}
2944		com->dtr_wait = *(int *)data * hz / 100;
2945		break;
2946	    case TIOCMGDTRWAIT:
2947		*(int *)data = com->dtr_wait * 100 / hz;
2948		break;
2949	    case TIOCTIMESTAMP:
2950		com->do_timestamp = TRUE;
2951		*(struct timeval *)data = com->timestamp;
2952		break;
2953	    case TIOCDCDTIMESTAMP:
2954		com->do_dcd_timestamp = TRUE;
2955		*(struct timeval *)data = com->dcd_timestamp;
2956		break;
2957	    default:
2958		splx(s);
2959		return (ENOTTY);
2960	    }
2961	} else {
2962	    int port_shift;
2963	    port_shift = if_16550a_type[com->pc98_if_type & 0x0f].port_shift;
2964#endif
2965	switch (cmd) {
2966	case TIOCSBRK:
2967#ifdef PC98
2968		outb(iobase + (com_cfcr << port_shift),
2969		     com->cfcr_image |= CFCR_SBREAK);
2970#else
2971		outb(iobase + com_cfcr, com->cfcr_image |= CFCR_SBREAK);
2972#endif
2973		break;
2974	case TIOCCBRK:
2975#ifdef PC98
2976		outb(iobase + (com_cfcr << port_shift),
2977		     com->cfcr_image &= ~CFCR_SBREAK);
2978#else
2979		outb(iobase + com_cfcr, com->cfcr_image &= ~CFCR_SBREAK);
2980#endif
2981		break;
2982	case TIOCSDTR:
2983		(void)commctl(com, TIOCM_DTR, DMBIS);
2984		break;
2985	case TIOCCDTR:
2986		(void)commctl(com, TIOCM_DTR, DMBIC);
2987		break;
2988	/*
2989	 * XXX should disallow changing MCR_RTS if CS_RTS_IFLOW is set.  The
2990	 * changes get undone on the next call to comparam().
2991	 */
2992	case TIOCMSET:
2993		(void)commctl(com, *(int *)data, DMSET);
2994		break;
2995	case TIOCMBIS:
2996		(void)commctl(com, *(int *)data, DMBIS);
2997		break;
2998	case TIOCMBIC:
2999		(void)commctl(com, *(int *)data, DMBIC);
3000		break;
3001	case TIOCMGET:
3002		*(int *)data = commctl(com, 0, DMGET);
3003		break;
3004	case TIOCMSDTRWAIT:
3005		/* must be root since the wait applies to following logins */
3006		error = suser(p);
3007		if (error != 0) {
3008			splx(s);
3009			return (error);
3010		}
3011		com->dtr_wait = *(int *)data * hz / 100;
3012		break;
3013	case TIOCMGDTRWAIT:
3014		*(int *)data = com->dtr_wait * 100 / hz;
3015		break;
3016	case TIOCTIMESTAMP:
3017		com->do_timestamp = TRUE;
3018		*(struct timeval *)data = com->timestamp;
3019		break;
3020	case TIOCDCDTIMESTAMP:
3021		com->do_dcd_timestamp = TRUE;
3022		*(struct timeval *)data = com->dcd_timestamp;
3023		break;
3024	default:
3025		splx(s);
3026		error = pps_ioctl(cmd, data, &com->pps);
3027		if (error == ENODEV)
3028			error = ENOTTY;
3029		return (error);
3030	}
3031#ifdef PC98
3032	}
3033#endif
3034	splx(s);
3035	return (0);
3036}
3037
3038static void
3039siopoll()
3040{
3041	int		unit;
3042
3043	if (com_events == 0)
3044		return;
3045repeat:
3046	for (unit = 0; unit < NSIOTOT; ++unit) {
3047		struct com_s	*com;
3048		int		incc;
3049		struct tty	*tp;
3050
3051		com = com_addr(unit);
3052		if (com == NULL)
3053			continue;
3054		tp = com->tp;
3055		if (tp == NULL || com->gone) {
3056			/*
3057			 * Discard any events related to never-opened or
3058			 * going-away devices.
3059			 */
3060			disable_intr();
3061			incc = com->iptr - com->ibuf;
3062			com->iptr = com->ibuf;
3063			if (com->state & CS_CHECKMSR) {
3064				incc += LOTS_OF_EVENTS;
3065				com->state &= ~CS_CHECKMSR;
3066			}
3067			com_events -= incc;
3068			enable_intr();
3069			continue;
3070		}
3071		if (com->iptr != com->ibuf) {
3072			disable_intr();
3073			sioinput(com);
3074			enable_intr();
3075		}
3076		if (com->state & CS_CHECKMSR) {
3077			u_char	delta_modem_status;
3078
3079#ifdef PC98
3080			if (!IS_8251(com->pc98_if_type)) {
3081#endif
3082			disable_intr();
3083			delta_modem_status = com->last_modem_status
3084					     ^ com->prev_modem_status;
3085			com->prev_modem_status = com->last_modem_status;
3086			com_events -= LOTS_OF_EVENTS;
3087			com->state &= ~CS_CHECKMSR;
3088			enable_intr();
3089			if (delta_modem_status & MSR_DCD)
3090				(*linesw[tp->t_line].l_modem)
3091					(tp, com->prev_modem_status & MSR_DCD);
3092#ifdef PC98
3093			}
3094#endif
3095		}
3096		if (com->state & CS_ODONE) {
3097			disable_intr();
3098			com_events -= LOTS_OF_EVENTS;
3099			com->state &= ~CS_ODONE;
3100			enable_intr();
3101			if (!(com->state & CS_BUSY)
3102			    && !(com->extra_state & CSE_BUSYCHECK)) {
3103				timeout(siobusycheck, com, hz / 100);
3104				com->extra_state |= CSE_BUSYCHECK;
3105			}
3106			(*linesw[tp->t_line].l_start)(tp);
3107		}
3108		if (com_events == 0)
3109			break;
3110	}
3111	if (com_events >= LOTS_OF_EVENTS)
3112		goto repeat;
3113}
3114
3115static int
3116comparam(tp, t)
3117	struct tty	*tp;
3118	struct termios	*t;
3119{
3120	u_int		cfcr;
3121	int		cflag;
3122	struct com_s	*com;
3123	int		divisor;
3124	u_char		dlbh;
3125	u_char		dlbl;
3126	Port_t		iobase;
3127	int		s;
3128	int		unit;
3129#ifdef PC98
3130	int		port_shift = 0;
3131	u_char		param = 0;
3132#endif
3133
3134#ifdef PC98
3135	cfcr = 0;
3136	unit = DEV_TO_UNIT(tp->t_dev);
3137	com = com_addr(unit);
3138	iobase = com->iobase;
3139	if (IS_8251(com->pc98_if_type)) {
3140	    divisor = pc98_ttspeedtab(com, t->c_ospeed);
3141	} else {
3142	    port_shift = if_16550a_type[com->pc98_if_type & 0x0f].port_shift;
3143
3144	    /* do historical conversions */
3145	    if (t->c_ispeed == 0)
3146		t->c_ispeed = t->c_ospeed;
3147
3148	    /* check requested parameters */
3149	    divisor = ttspeedtab(t->c_ospeed,
3150			if_16550a_type[com->pc98_if_type & 0x0f].speedtab);
3151	}
3152#else
3153	/* do historical conversions */
3154	if (t->c_ispeed == 0)
3155		t->c_ispeed = t->c_ospeed;
3156
3157	/* check requested parameters */
3158	divisor = ttspeedtab(t->c_ospeed, comspeedtab);
3159#endif
3160	if (divisor < 0 || (divisor > 0 && t->c_ispeed != t->c_ospeed))
3161		return (EINVAL);
3162
3163	/* parameters are OK, convert them to the com struct and the device */
3164#ifndef PC98
3165	unit = DEV_TO_UNIT(tp->t_dev);
3166	com = com_addr(unit);
3167	iobase = com->iobase;
3168#endif
3169	s = spltty();
3170#ifdef PC98
3171	if (IS_8251(com->pc98_if_type)) {
3172		if (divisor == 0)
3173			com_tiocm_bic( com, TIOCM_DTR|TIOCM_RTS|TIOCM_LE );
3174		else
3175			com_tiocm_bis( com, TIOCM_DTR|TIOCM_RTS|TIOCM_LE );
3176	} else {
3177#endif
3178	if (divisor == 0)
3179		(void)commctl(com, TIOCM_DTR, DMBIC);	/* hang up line */
3180	else
3181		(void)commctl(com, TIOCM_DTR, DMBIS);
3182#ifdef PC98
3183	}
3184#endif
3185	cflag = t->c_cflag;
3186#ifdef PC98
3187	if (!IS_8251(com->pc98_if_type)) {
3188#endif
3189	switch (cflag & CSIZE) {
3190	case CS5:
3191		cfcr = CFCR_5BITS;
3192		break;
3193	case CS6:
3194		cfcr = CFCR_6BITS;
3195		break;
3196	case CS7:
3197		cfcr = CFCR_7BITS;
3198		break;
3199	default:
3200		cfcr = CFCR_8BITS;
3201		break;
3202	}
3203	if (cflag & PARENB) {
3204		cfcr |= CFCR_PENAB;
3205		if (!(cflag & PARODD))
3206			cfcr |= CFCR_PEVEN;
3207	}
3208	if (cflag & CSTOPB)
3209		cfcr |= CFCR_STOPB;
3210
3211	if (com->hasfifo && divisor != 0) {
3212		/*
3213		 * Use a fifo trigger level low enough so that the input
3214		 * latency from the fifo is less than about 16 msec and
3215		 * the total latency is less than about 30 msec.  These
3216		 * latencies are reasonable for humans.  Serial comms
3217		 * protocols shouldn't expect anything better since modem
3218		 * latencies are larger.
3219		 */
3220		com->fifo_image = t->c_ospeed <= 4800
3221				  ? FIFO_ENABLE : FIFO_ENABLE | FIFO_RX_HIGH;
3222#ifdef COM_ESP
3223		/*
3224		 * The Hayes ESP card needs the fifo DMA mode bit set
3225		 * in compatibility mode.  If not, it will interrupt
3226		 * for each character received.
3227		 */
3228		if (com->esp)
3229			com->fifo_image |= FIFO_DMA_MODE;
3230#endif
3231#ifdef PC98
3232		outb(iobase + (com_fifo << port_shift), com->fifo_image);
3233#else
3234		outb(iobase + com_fifo, com->fifo_image);
3235#endif
3236	}
3237#ifdef PC98
3238	}
3239#endif
3240
3241	/*
3242	 * This returns with interrupts disabled so that we can complete
3243	 * the speed change atomically.  Keeping interrupts disabled is
3244	 * especially important while com_data is hidden.
3245	 */
3246	(void) siosetwater(com, t->c_ispeed);
3247
3248#ifdef PC98
3249	if (IS_8251(com->pc98_if_type))
3250	    com_cflag_and_speed_set(com, cflag, t->c_ospeed);
3251	else {
3252#endif
3253	if (divisor != 0) {
3254#ifdef PC98
3255		outb(iobase + (com_cfcr << port_shift), cfcr | CFCR_DLAB);
3256#else
3257		outb(iobase + com_cfcr, cfcr | CFCR_DLAB);
3258#endif
3259		/*
3260		 * Only set the divisor registers if they would change,
3261		 * since on some 16550 incompatibles (UMC8669F), setting
3262		 * them while input is arriving them loses sync until
3263		 * data stops arriving.
3264		 */
3265		dlbl = divisor & 0xFF;
3266#ifdef PC98
3267		if (inb(iobase + (com_dlbl << port_shift)) != dlbl)
3268			outb(iobase + (com_dlbl << port_shift), dlbl);
3269		dlbh = (u_int) divisor >> 8;
3270		if (inb(iobase + (com_dlbh << port_shift)) != dlbh)
3271			outb(iobase + (com_dlbh << port_shift), dlbh);
3272#else
3273		if (inb(iobase + com_dlbl) != dlbl)
3274			outb(iobase + com_dlbl, dlbl);
3275		dlbh = (u_int) divisor >> 8;
3276		if (inb(iobase + com_dlbh) != dlbh)
3277			outb(iobase + com_dlbh, dlbh);
3278#endif
3279	}
3280
3281
3282#ifdef PC98
3283	}
3284	outb(iobase + (com_cfcr << port_shift), com->cfcr_image = cfcr);
3285#else
3286	outb(iobase + com_cfcr, com->cfcr_image = cfcr);
3287#endif
3288
3289	if (!(tp->t_state & TS_TTSTOP))
3290		com->state |= CS_TTGO;
3291
3292	if (cflag & CRTS_IFLOW) {
3293		if (com->st16650a) {
3294			outb(iobase + com_cfcr, 0xbf);
3295			outb(iobase + com_fifo, inb(iobase + com_fifo) | 0x40);
3296		}
3297		com->state |= CS_RTS_IFLOW;
3298		/*
3299		 * If CS_RTS_IFLOW just changed from off to on, the change
3300		 * needs to be propagated to MCR_RTS.  This isn't urgent,
3301		 * so do it later by calling comstart() instead of repeating
3302		 * a lot of code from comstart() here.
3303		 */
3304	} else if (com->state & CS_RTS_IFLOW) {
3305		com->state &= ~CS_RTS_IFLOW;
3306		/*
3307		 * CS_RTS_IFLOW just changed from on to off.  Force MCR_RTS
3308		 * on here, since comstart() won't do it later.
3309		 */
3310#ifdef PC98
3311		if (IS_8251(com->pc98_if_type))
3312			com_tiocm_bis(com, TIOCM_RTS);
3313		else
3314#endif
3315		outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
3316		if (com->st16650a) {
3317			outb(iobase + com_cfcr, 0xbf);
3318			outb(iobase + com_fifo, inb(iobase + com_fifo) & ~0x40);
3319		}
3320	}
3321
3322
3323	/*
3324	 * Set up state to handle output flow control.
3325	 * XXX - worth handling MDMBUF (DCD) flow control at the lowest level?
3326	 * Now has 10+ msec latency, while CTS flow has 50- usec latency.
3327	 */
3328	com->state |= CS_ODEVREADY;
3329	com->state &= ~CS_CTS_OFLOW;
3330#ifdef PC98
3331	if (com->pc98_if_type == COM_IF_RSA98III) {
3332		param = inb(com->rsabase + rsa_msr);
3333		outb(com->rsabase + rsa_msr, param & 0x14);
3334	}
3335#endif
3336	if (cflag & CCTS_OFLOW) {
3337		com->state |= CS_CTS_OFLOW;
3338#ifdef PC98
3339		if (IS_8251(com->pc98_if_type)) {
3340			if (!(pc98_get_modem_status(com) & TIOCM_CTS))
3341				com->state &= ~CS_ODEVREADY;
3342		} else {
3343#endif
3344#ifdef PC98
3345		if (com->pc98_if_type == COM_IF_RSA98III) {
3346			/* Set automatic flow control mode */
3347			outb(com->rsabase + rsa_msr, param | 0x08);
3348		} else
3349#endif
3350		if (!(com->last_modem_status & MSR_CTS))
3351			com->state &= ~CS_ODEVREADY;
3352		if (com->st16650a) {
3353			outb(iobase + com_cfcr, 0xbf);
3354			outb(iobase + com_fifo, inb(iobase + com_fifo) | 0x80);
3355		}
3356#ifdef PC98
3357		}
3358#endif
3359	} else {
3360		if (com->st16650a) {
3361			outb(iobase + com_cfcr, 0xbf);
3362			outb(iobase + com_fifo, inb(iobase + com_fifo) & ~0x80);
3363		}
3364	}
3365
3366
3367#ifdef PC98
3368	outb(iobase + (com_cfcr << port_shift), com->cfcr_image);
3369#else
3370	outb(iobase + com_cfcr, com->cfcr_image);
3371#endif
3372
3373
3374	/* XXX shouldn't call functions while intrs are disabled. */
3375	disc_optim(tp, t, com);
3376	/*
3377	 * Recover from fiddling with CS_TTGO.  We used to call siointr1()
3378	 * unconditionally, but that defeated the careful discarding of
3379	 * stale input in sioopen().
3380	 */
3381	if (com->state >= (CS_BUSY | CS_TTGO))
3382		siointr1(com);
3383
3384	enable_intr();
3385	splx(s);
3386	comstart(tp);
3387	if (com->ibufold != NULL) {
3388		free(com->ibufold, M_DEVBUF);
3389		com->ibufold = NULL;
3390	}
3391	return (0);
3392}
3393
3394static int
3395siosetwater(com, speed)
3396	struct com_s	*com;
3397	speed_t		speed;
3398{
3399	int		cp4ticks;
3400	u_char		*ibuf;
3401	int		ibufsize;
3402	struct tty	*tp;
3403
3404	/*
3405	 * Make the buffer size large enough to handle a softtty interrupt
3406	 * latency of about 2 ticks without loss of throughput or data
3407	 * (about 3 ticks if input flow control is not used or not honoured,
3408	 * but a bit less for CS5-CS7 modes).
3409	 */
3410	cp4ticks = speed / 10 / hz * 4;
3411	for (ibufsize = 128; ibufsize < cp4ticks;)
3412		ibufsize <<= 1;
3413#ifdef PC98
3414	if (com->pc98_if_type == COM_IF_RSA98III)
3415		ibufsize = 2048;
3416#endif
3417	if (ibufsize == com->ibufsize) {
3418		disable_intr();
3419		return (0);
3420	}
3421
3422	/*
3423	 * Allocate input buffer.  The extra factor of 2 in the size is
3424	 * to allow for an error byte for each input byte.
3425	 */
3426	ibuf = malloc(2 * ibufsize, M_DEVBUF, M_NOWAIT);
3427	if (ibuf == NULL) {
3428		disable_intr();
3429		return (ENOMEM);
3430	}
3431
3432	/* Initialize non-critical variables. */
3433	com->ibufold = com->ibuf;
3434	com->ibufsize = ibufsize;
3435	tp = com->tp;
3436	if (tp != NULL) {
3437		tp->t_ififosize = 2 * ibufsize;
3438		tp->t_ispeedwat = (speed_t)-1;
3439		tp->t_ospeedwat = (speed_t)-1;
3440	}
3441
3442	/*
3443	 * Read current input buffer, if any.  Continue with interrupts
3444	 * disabled.
3445	 */
3446	disable_intr();
3447	if (com->iptr != com->ibuf)
3448		sioinput(com);
3449
3450	/*-
3451	 * Initialize critical variables, including input buffer watermarks.
3452	 * The external device is asked to stop sending when the buffer
3453	 * exactly reaches high water, or when the high level requests it.
3454	 * The high level is notified immediately (rather than at a later
3455	 * clock tick) when this watermark is reached.
3456	 * The buffer size is chosen so the watermark should almost never
3457	 * be reached.
3458	 * The low watermark is invisibly 0 since the buffer is always
3459	 * emptied all at once.
3460	 */
3461	com->iptr = com->ibuf = ibuf;
3462	com->ibufend = ibuf + ibufsize;
3463	com->ierroff = ibufsize;
3464	com->ihighwater = ibuf + 3 * ibufsize / 4;
3465	return (0);
3466}
3467
3468static void
3469comstart(tp)
3470	struct tty	*tp;
3471{
3472	struct com_s	*com;
3473	int		s;
3474	int		unit;
3475#ifdef PC98
3476	int		tmp;
3477#endif
3478
3479	unit = DEV_TO_UNIT(tp->t_dev);
3480	com = com_addr(unit);
3481	s = spltty();
3482	disable_intr();
3483	if (tp->t_state & TS_TTSTOP)
3484		com->state &= ~CS_TTGO;
3485	else
3486		com->state |= CS_TTGO;
3487	if (tp->t_state & TS_TBLOCK) {
3488#ifdef PC98
3489		if (IS_8251(com->pc98_if_type))
3490			tmp = com_tiocm_get(com) & TIOCM_RTS;
3491		else
3492			tmp = com->mcr_image & MCR_RTS;
3493		if (tmp && (com->state & CS_RTS_IFLOW))
3494#else
3495		if (com->mcr_image & MCR_RTS && com->state & CS_RTS_IFLOW)
3496#endif
3497#ifdef PC98
3498			if (IS_8251(com->pc98_if_type))
3499				com_tiocm_bic(com, TIOCM_RTS);
3500			else
3501#endif
3502			outb(com->modem_ctl_port, com->mcr_image &= ~MCR_RTS);
3503	} else {
3504#ifdef PC98
3505		if (IS_8251(com->pc98_if_type))
3506			tmp = com_tiocm_get(com) & TIOCM_RTS;
3507		else
3508			tmp = com->mcr_image & MCR_RTS;
3509		if (!(tmp) && com->iptr < com->ihighwater
3510			&& com->state & CS_RTS_IFLOW)
3511#else
3512		if (!(com->mcr_image & MCR_RTS) && com->iptr < com->ihighwater
3513		    && com->state & CS_RTS_IFLOW)
3514#endif
3515#ifdef PC98
3516			if (IS_8251(com->pc98_if_type))
3517				com_tiocm_bis(com, TIOCM_RTS);
3518			else
3519#endif
3520			outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
3521	}
3522	enable_intr();
3523	if (tp->t_state & (TS_TIMEOUT | TS_TTSTOP)) {
3524		ttwwakeup(tp);
3525#ifdef PC98
3526/*		if(IS_8251(com->pc98_if_type))
3527			com_int_Tx_enable(com); */
3528#endif
3529		splx(s);
3530		return;
3531	}
3532	if (tp->t_outq.c_cc != 0) {
3533		struct lbq	*qp;
3534		struct lbq	*next;
3535
3536		if (!com->obufs[0].l_queued) {
3537			com->obufs[0].l_tail
3538			    = com->obuf1 + q_to_b(&tp->t_outq, com->obuf1,
3539#ifndef PC98
3540						  sizeof com->obuf1);
3541#else
3542						  com->obufsize);
3543#endif
3544			com->obufs[0].l_next = NULL;
3545			com->obufs[0].l_queued = TRUE;
3546			disable_intr();
3547			if (com->state & CS_BUSY) {
3548				qp = com->obufq.l_next;
3549				while ((next = qp->l_next) != NULL)
3550					qp = next;
3551				qp->l_next = &com->obufs[0];
3552			} else {
3553				com->obufq.l_head = com->obufs[0].l_head;
3554				com->obufq.l_tail = com->obufs[0].l_tail;
3555				com->obufq.l_next = &com->obufs[0];
3556				com->state |= CS_BUSY;
3557			}
3558			enable_intr();
3559		}
3560		if (tp->t_outq.c_cc != 0 && !com->obufs[1].l_queued) {
3561			com->obufs[1].l_tail
3562			    = com->obuf2 + q_to_b(&tp->t_outq, com->obuf2,
3563#ifndef PC98
3564						  sizeof com->obuf2);
3565#else
3566						  com->obufsize);
3567#endif
3568			com->obufs[1].l_next = NULL;
3569			com->obufs[1].l_queued = TRUE;
3570			disable_intr();
3571			if (com->state & CS_BUSY) {
3572				qp = com->obufq.l_next;
3573				while ((next = qp->l_next) != NULL)
3574					qp = next;
3575				qp->l_next = &com->obufs[1];
3576			} else {
3577				com->obufq.l_head = com->obufs[1].l_head;
3578				com->obufq.l_tail = com->obufs[1].l_tail;
3579				com->obufq.l_next = &com->obufs[1];
3580				com->state |= CS_BUSY;
3581			}
3582			enable_intr();
3583		}
3584		tp->t_state |= TS_BUSY;
3585	}
3586	disable_intr();
3587	if (com->state >= (CS_BUSY | CS_TTGO))
3588		siointr1(com);	/* fake interrupt to start output */
3589	enable_intr();
3590#ifdef PC98
3591/*		if(IS_8251(com->pc98_if_type))
3592			com_int_Tx_enable(com); */
3593#endif
3594	ttwwakeup(tp);
3595	splx(s);
3596}
3597
3598static void
3599comstop(tp, rw)
3600	struct tty	*tp;
3601	int		rw;
3602{
3603	struct com_s	*com;
3604#ifdef PC98
3605	int		port_shift = 0;
3606	int		rsa98_tmp  = 0;
3607#endif
3608
3609	com = com_addr(DEV_TO_UNIT(tp->t_dev));
3610	if (com->gone)
3611		return;
3612#ifdef PC98
3613	if (!IS_8251(com->pc98_if_type))
3614	    port_shift = if_16550a_type[com->pc98_if_type & 0x0f].port_shift;
3615#endif
3616	disable_intr();
3617	if (rw & FWRITE) {
3618		if (com->hasfifo)
3619#ifdef COM_ESP
3620		    /* XXX avoid h/w bug. */
3621		    if (!com->esp)
3622#endif
3623#ifdef PC98
3624			outb(com->iobase + (com_fifo << port_shift),
3625			     FIFO_XMT_RST | com->fifo_image);
3626			if (com->pc98_if_type == COM_IF_RSA98III)
3627			    for(rsa98_tmp = 0; rsa98_tmp < 2048; rsa98_tmp++)
3628				outb(com->iobase + (com_fifo << port_shift),
3629				     FIFO_XMT_RST | com->fifo_image);
3630#else
3631			outb(com->iobase + com_fifo,
3632			     FIFO_XMT_RST | com->fifo_image);
3633#endif
3634		com->obufs[0].l_queued = FALSE;
3635		com->obufs[1].l_queued = FALSE;
3636		if (com->state & CS_ODONE)
3637			com_events -= LOTS_OF_EVENTS;
3638		com->state &= ~(CS_ODONE | CS_BUSY);
3639		com->tp->t_state &= ~TS_BUSY;
3640	}
3641	if (rw & FREAD) {
3642		if (com->hasfifo)
3643#ifdef COM_ESP
3644		    /* XXX avoid h/w bug. */
3645		    if (!com->esp)
3646#endif
3647#ifdef PC98
3648			if (com->pc98_if_type == COM_IF_RSA98III) {
3649			    for(rsa98_tmp = 0; rsa98_tmp < 2048; rsa98_tmp++)
3650				inb(com->data_port);
3651			}
3652			outb(com->iobase + (com_fifo << port_shift),
3653			     FIFO_RCV_RST | com->fifo_image);
3654#else
3655			outb(com->iobase + com_fifo,
3656			     FIFO_RCV_RST | com->fifo_image);
3657#endif
3658		com_events -= (com->iptr - com->ibuf);
3659		com->iptr = com->ibuf;
3660	}
3661	enable_intr();
3662	comstart(tp);
3663}
3664
3665static int
3666commctl(com, bits, how)
3667	struct com_s	*com;
3668	int		bits;
3669	int		how;
3670{
3671	int	mcr;
3672	int	msr;
3673
3674	if (how == DMGET) {
3675		bits = TIOCM_LE;	/* XXX - always enabled while open */
3676		mcr = com->mcr_image;
3677		if (mcr & MCR_DTR)
3678			bits |= TIOCM_DTR;
3679		if (mcr & MCR_RTS)
3680			bits |= TIOCM_RTS;
3681		msr = com->prev_modem_status;
3682		if (msr & MSR_CTS)
3683			bits |= TIOCM_CTS;
3684		if (msr & MSR_DCD)
3685			bits |= TIOCM_CD;
3686		if (msr & MSR_DSR)
3687			bits |= TIOCM_DSR;
3688		/*
3689		 * XXX - MSR_RI is naturally volatile, and we make MSR_TERI
3690		 * more volatile by reading the modem status a lot.  Perhaps
3691		 * we should latch both bits until the status is read here.
3692		 */
3693		if (msr & (MSR_RI | MSR_TERI))
3694			bits |= TIOCM_RI;
3695		return (bits);
3696	}
3697	mcr = 0;
3698	if (bits & TIOCM_DTR)
3699		mcr |= MCR_DTR;
3700	if (bits & TIOCM_RTS)
3701		mcr |= MCR_RTS;
3702	if (com->gone)
3703		return(0);
3704	disable_intr();
3705	switch (how) {
3706	case DMSET:
3707		outb(com->modem_ctl_port,
3708		     com->mcr_image = mcr | (com->mcr_image & MCR_IENABLE));
3709		break;
3710	case DMBIS:
3711		outb(com->modem_ctl_port, com->mcr_image |= mcr);
3712		break;
3713	case DMBIC:
3714		outb(com->modem_ctl_port, com->mcr_image &= ~mcr);
3715		break;
3716	}
3717	enable_intr();
3718	return (0);
3719}
3720
3721static void
3722siosettimeout()
3723{
3724	struct com_s	*com;
3725	bool_t		someopen;
3726	int		unit;
3727
3728	/*
3729	 * Set our timeout period to 1 second if no polled devices are open.
3730	 * Otherwise set it to max(1/200, 1/hz).
3731	 * Enable timeouts iff some device is open.
3732	 */
3733	untimeout(comwakeup, (void *)NULL, sio_timeout_handle);
3734	sio_timeout = hz;
3735	someopen = FALSE;
3736	for (unit = 0; unit < NSIOTOT; ++unit) {
3737		com = com_addr(unit);
3738		if (com != NULL && com->tp != NULL
3739		    && com->tp->t_state & TS_ISOPEN && !com->gone) {
3740			someopen = TRUE;
3741			if (com->poll || com->poll_output) {
3742				sio_timeout = hz > 200 ? hz / 200 : 1;
3743				break;
3744			}
3745		}
3746	}
3747	if (someopen) {
3748		sio_timeouts_until_log = hz / sio_timeout;
3749		sio_timeout_handle = timeout(comwakeup, (void *)NULL,
3750					     sio_timeout);
3751	} else {
3752		/* Flush error messages, if any. */
3753		sio_timeouts_until_log = 1;
3754		comwakeup((void *)NULL);
3755		untimeout(comwakeup, (void *)NULL, sio_timeout_handle);
3756	}
3757}
3758
3759static void
3760comwakeup(chan)
3761	void	*chan;
3762{
3763	struct com_s	*com;
3764	int		unit;
3765
3766	sio_timeout_handle = timeout(comwakeup, (void *)NULL, sio_timeout);
3767
3768	/*
3769	 * Recover from lost output interrupts.
3770	 * Poll any lines that don't use interrupts.
3771	 */
3772	for (unit = 0; unit < NSIOTOT; ++unit) {
3773		com = com_addr(unit);
3774		if (com != NULL && !com->gone
3775		    && (com->state >= (CS_BUSY | CS_TTGO) || com->poll)) {
3776			disable_intr();
3777			siointr1(com);
3778			enable_intr();
3779		}
3780	}
3781
3782	/*
3783	 * Check for and log errors, but not too often.
3784	 */
3785	if (--sio_timeouts_until_log > 0)
3786		return;
3787	sio_timeouts_until_log = hz / sio_timeout;
3788	for (unit = 0; unit < NSIOTOT; ++unit) {
3789		int	errnum;
3790
3791		com = com_addr(unit);
3792		if (com == NULL)
3793			continue;
3794		if (com->gone)
3795			continue;
3796		for (errnum = 0; errnum < CE_NTYPES; ++errnum) {
3797			u_int	delta;
3798			u_long	total;
3799
3800			disable_intr();
3801			delta = com->delta_error_counts[errnum];
3802			com->delta_error_counts[errnum] = 0;
3803			enable_intr();
3804			if (delta == 0)
3805				continue;
3806			total = com->error_counts[errnum] += delta;
3807			log(LOG_ERR, "sio%d: %u more %s%s (total %lu)\n",
3808			    unit, delta, error_desc[errnum],
3809			    delta == 1 ? "" : "s", total);
3810		}
3811	}
3812}
3813
3814#ifdef PC98
3815/* commint is called when modem control line changes */
3816static void
3817commint(dev_t dev)
3818{
3819	register struct tty *tp;
3820	int	stat,delta;
3821	struct com_s *com;
3822	int	mynor,unit;
3823
3824	mynor = minor(dev);
3825	unit = MINOR_TO_UNIT(mynor);
3826	com = com_addr(unit);
3827	tp = com->tp;
3828
3829	stat = com_tiocm_get(com);
3830	delta = com_tiocm_get_delta(com);
3831
3832	if (com->state & CS_CTS_OFLOW) {
3833		if (stat & TIOCM_CTS)
3834			com->state |= CS_ODEVREADY;
3835		else
3836			com->state &= ~CS_ODEVREADY;
3837	}
3838	if ((delta & TIOCM_CAR) && (mynor & CALLOUT_MASK) == 0) {
3839	    if (stat & TIOCM_CAR )
3840		(void)(*linesw[tp->t_line].l_modem)(tp, 1);
3841	    else if ((*linesw[tp->t_line].l_modem)(tp, 0) == 0) {
3842		/* negate DTR, RTS */
3843		com_tiocm_bic(com, (tp->t_cflag & HUPCL) ?
3844				TIOCM_DTR|TIOCM_RTS|TIOCM_LE : TIOCM_LE );
3845		/* disable IENABLE */
3846		com_int_TxRx_disable( com );
3847	    }
3848	}
3849}
3850#endif
3851
3852static void
3853disc_optim(tp, t, com)
3854	struct tty	*tp;
3855	struct termios	*t;
3856	struct com_s	*com;
3857{
3858	if (!(t->c_iflag & (ICRNL | IGNCR | IMAXBEL | INLCR | ISTRIP | IXON))
3859	    && (!(t->c_iflag & BRKINT) || (t->c_iflag & IGNBRK))
3860	    && (!(t->c_iflag & PARMRK)
3861		|| (t->c_iflag & (IGNPAR | IGNBRK)) == (IGNPAR | IGNBRK))
3862	    && !(t->c_lflag & (ECHO | ICANON | IEXTEN | ISIG | PENDIN))
3863	    && linesw[tp->t_line].l_rint == ttyinput)
3864		tp->t_state |= TS_CAN_BYPASS_L_RINT;
3865	else
3866		tp->t_state &= ~TS_CAN_BYPASS_L_RINT;
3867	com->hotchar = linesw[tp->t_line].l_hotchar;
3868}
3869
3870/*
3871 * Following are all routines needed for SIO to act as console
3872 */
3873#include <sys/cons.h>
3874
3875struct siocnstate {
3876	u_char	dlbl;
3877	u_char	dlbh;
3878	u_char	ier;
3879	u_char	cfcr;
3880	u_char	mcr;
3881};
3882
3883static speed_t siocngetspeed __P((Port_t, struct speedtab *));
3884static void siocnclose	__P((struct siocnstate *sp, Port_t iobase));
3885static void siocnopen	__P((struct siocnstate *sp, Port_t iobase, int speed));
3886static void siocntxwait	__P((Port_t iobase));
3887
3888static cn_probe_t siocnprobe;
3889static cn_init_t siocninit;
3890static cn_checkc_t siocncheckc;
3891static cn_getc_t siocngetc;
3892static cn_putc_t siocnputc;
3893
3894#ifdef __i386__
3895CONS_DRIVER(sio, siocnprobe, siocninit, NULL, siocngetc, siocncheckc, siocnputc);
3896
3897#endif
3898
3899/* To get the GDB related variables */
3900#if DDB > 0
3901#include <ddb/ddb.h>
3902#endif
3903
3904static void
3905siocntxwait(iobase)
3906	Port_t	iobase;
3907{
3908	int	timo;
3909
3910	/*
3911	 * Wait for any pending transmission to finish.  Required to avoid
3912	 * the UART lockup bug when the speed is changed, and for normal
3913	 * transmits.
3914	 */
3915	timo = 100000;
3916	while ((inb(iobase + com_lsr) & (LSR_TSRE | LSR_TXRDY))
3917	       != (LSR_TSRE | LSR_TXRDY) && --timo != 0)
3918		;
3919}
3920
3921/*
3922 * Read the serial port specified and try to figure out what speed
3923 * it's currently running at.  We're assuming the serial port has
3924 * been initialized and is basicly idle.  This routine is only intended
3925 * to be run at system startup.
3926 *
3927 * If the value read from the serial port doesn't make sense, return 0.
3928 */
3929
3930static speed_t
3931siocngetspeed(iobase, table)
3932	Port_t iobase;
3933	struct speedtab *table;
3934{
3935	int	code;
3936	u_char	dlbh;
3937	u_char	dlbl;
3938	u_char  cfcr;
3939
3940	cfcr = inb(iobase + com_cfcr);
3941	outb(iobase + com_cfcr, CFCR_DLAB | cfcr);
3942
3943	dlbl = inb(iobase + com_dlbl);
3944	dlbh = inb(iobase + com_dlbh);
3945
3946	outb(iobase + com_cfcr, cfcr);
3947
3948	code = dlbh << 8 | dlbl;
3949
3950	for ( ; table->sp_speed != -1; table++)
3951		if (table->sp_code == code)
3952			return (table->sp_speed);
3953
3954	return 0;	/* didn't match anything sane */
3955}
3956
3957static void
3958siocnopen(sp, iobase, speed)
3959	struct siocnstate	*sp;
3960	Port_t			iobase;
3961	int			speed;
3962{
3963	int	divisor;
3964	u_char	dlbh;
3965	u_char	dlbl;
3966
3967	/*
3968	 * Save all the device control registers except the fifo register
3969	 * and set our default ones (cs8 -parenb speed=comdefaultrate).
3970	 * We can't save the fifo register since it is read-only.
3971	 */
3972	sp->ier = inb(iobase + com_ier);
3973	outb(iobase + com_ier, 0);	/* spltty() doesn't stop siointr() */
3974	siocntxwait(iobase);
3975	sp->cfcr = inb(iobase + com_cfcr);
3976	outb(iobase + com_cfcr, CFCR_DLAB | CFCR_8BITS);
3977	sp->dlbl = inb(iobase + com_dlbl);
3978	sp->dlbh = inb(iobase + com_dlbh);
3979	/*
3980	 * Only set the divisor registers if they would change, since on
3981	 * some 16550 incompatibles (Startech), setting them clears the
3982	 * data input register.  This also reduces the effects of the
3983	 * UMC8669F bug.
3984	 */
3985	divisor = ttspeedtab(speed, comspeedtab);
3986	dlbl = divisor & 0xFF;
3987	if (sp->dlbl != dlbl)
3988		outb(iobase + com_dlbl, dlbl);
3989	dlbh = (u_int) divisor >> 8;
3990	if (sp->dlbh != dlbh)
3991		outb(iobase + com_dlbh, dlbh);
3992	outb(iobase + com_cfcr, CFCR_8BITS);
3993	sp->mcr = inb(iobase + com_mcr);
3994	/*
3995	 * We don't want interrupts, but must be careful not to "disable"
3996	 * them by clearing the MCR_IENABLE bit, since that might cause
3997	 * an interrupt by floating the IRQ line.
3998	 */
3999	outb(iobase + com_mcr, (sp->mcr & MCR_IENABLE) | MCR_DTR | MCR_RTS);
4000}
4001
4002static void
4003siocnclose(sp, iobase)
4004	struct siocnstate	*sp;
4005	Port_t			iobase;
4006{
4007	/*
4008	 * Restore the device control registers.
4009	 */
4010	siocntxwait(iobase);
4011	outb(iobase + com_cfcr, CFCR_DLAB | CFCR_8BITS);
4012	if (sp->dlbl != inb(iobase + com_dlbl))
4013		outb(iobase + com_dlbl, sp->dlbl);
4014	if (sp->dlbh != inb(iobase + com_dlbh))
4015		outb(iobase + com_dlbh, sp->dlbh);
4016	outb(iobase + com_cfcr, sp->cfcr);
4017	/*
4018	 * XXX damp oscillations of MCR_DTR and MCR_RTS by not restoring them.
4019	 */
4020	outb(iobase + com_mcr, sp->mcr | MCR_DTR | MCR_RTS);
4021	outb(iobase + com_ier, sp->ier);
4022}
4023
4024static void
4025siocnprobe(cp)
4026	struct consdev	*cp;
4027{
4028	speed_t			boot_speed;
4029	u_char			cfcr;
4030	int			s, unit;
4031	struct siocnstate	sp;
4032
4033	/*
4034	 * Find our first enabled console, if any.  If it is a high-level
4035	 * console device, then initialize it and return successfully.
4036	 * If it is a low-level console device, then initialize it and
4037	 * return unsuccessfully.  It must be initialized in both cases
4038	 * for early use by console drivers and debuggers.  Initializing
4039	 * the hardware is not necessary in all cases, since the i/o
4040	 * routines initialize it on the fly, but it is necessary if
4041	 * input might arrive while the hardware is switched back to an
4042	 * uninitialized state.  We can't handle multiple console devices
4043	 * yet because our low-level routines don't take a device arg.
4044	 * We trust the user to set the console flags properly so that we
4045	 * don't need to probe.
4046	 */
4047	cp->cn_pri = CN_DEAD;
4048
4049	for (unit = 0; unit < 16; unit++) { /* XXX need to know how many */
4050		int flags;
4051		int disabled;
4052		if (resource_int_value("sio", unit, "disabled", &disabled) == 0) {
4053			if (disabled)
4054				continue;
4055		}
4056		if (resource_int_value("sio", unit, "flags", &flags))
4057			continue;
4058		if (COM_CONSOLE(flags) || COM_DEBUGGER(flags)) {
4059			int port;
4060			Port_t iobase;
4061
4062			if (resource_int_value("sio", unit, "port", &port))
4063				continue;
4064			iobase = port;
4065			s = spltty();
4066			if (boothowto & RB_SERIAL) {
4067				boot_speed = siocngetspeed(iobase, comspeedtab);
4068				if (boot_speed)
4069					comdefaultrate = boot_speed;
4070			}
4071
4072			/*
4073			 * Initialize the divisor latch.  We can't rely on
4074			 * siocnopen() to do this the first time, since it
4075			 * avoids writing to the latch if the latch appears
4076			 * to have the correct value.  Also, if we didn't
4077			 * just read the speed from the hardware, then we
4078			 * need to set the speed in hardware so that
4079			 * switching it later is null.
4080			 */
4081			cfcr = inb(iobase + com_cfcr);
4082			outb(iobase + com_cfcr, CFCR_DLAB | cfcr);
4083			outb(iobase + com_dlbl,
4084			     COMBRD(comdefaultrate) & 0xff);
4085			outb(iobase + com_dlbh,
4086			     (u_int) COMBRD(comdefaultrate) >> 8);
4087			outb(iobase + com_cfcr, cfcr);
4088
4089			siocnopen(&sp, iobase, comdefaultrate);
4090
4091			splx(s);
4092			if (COM_CONSOLE(flags) && !COM_LLCONSOLE(flags)) {
4093				cp->cn_dev = makedev(CDEV_MAJOR, unit);
4094				cp->cn_pri = COM_FORCECONSOLE(flags)
4095					     || boothowto & RB_SERIAL
4096					     ? CN_REMOTE : CN_NORMAL;
4097				siocniobase = iobase;
4098				siocnunit = unit;
4099			}
4100			if (COM_DEBUGGER(flags)) {
4101				printf("sio%d: gdb debugging port\n", unit);
4102				siogdbiobase = iobase;
4103				siogdbunit = unit;
4104#if DDB > 0
4105				gdbdev = makedev(CDEV_MAJOR, unit);
4106				gdb_getc = siocngetc;
4107				gdb_putc = siocnputc;
4108#endif
4109			}
4110		}
4111	}
4112#ifdef	__i386__
4113#if DDB > 0
4114	/*
4115	 * XXX Ugly Compatability.
4116	 * If no gdb port has been specified, set it to be the console
4117	 * as some configuration files don't specify the gdb port.
4118	 */
4119	if (gdbdev == NODEV && (boothowto & RB_GDB)) {
4120		printf("Warning: no GDB port specified. Defaulting to sio%d.\n",
4121			siocnunit);
4122		printf("Set flag 0x80 on desired GDB port in your\n");
4123		printf("configuration file (currently sio only).\n");
4124		siogdbiobase = siocniobase;
4125		siogdbunit = siocnunit;
4126		gdbdev = makedev(CDEV_MAJOR, siocnunit);
4127		gdb_getc = siocngetc;
4128		gdb_putc = siocnputc;
4129	}
4130#endif
4131#endif
4132}
4133
4134#ifdef __alpha__
4135
4136CONS_DRIVER(sio, NULL, NULL, NULL, siocngetc, siocncheckc, siocnputc);
4137
4138int
4139siocnattach(port, speed)
4140	int port;
4141	int speed;
4142{
4143	int			s;
4144	u_char			cfcr;
4145	struct siocnstate	sp;
4146
4147	siocniobase = port;
4148	comdefaultrate = speed;
4149	sio_consdev.cn_pri = CN_NORMAL;
4150	sio_consdev.cn_dev = makedev(CDEV_MAJOR, 0);
4151
4152	s = spltty();
4153
4154	/*
4155	 * Initialize the divisor latch.  We can't rely on
4156	 * siocnopen() to do this the first time, since it
4157	 * avoids writing to the latch if the latch appears
4158	 * to have the correct value.  Also, if we didn't
4159	 * just read the speed from the hardware, then we
4160	 * need to set the speed in hardware so that
4161	 * switching it later is null.
4162	 */
4163	cfcr = inb(siocniobase + com_cfcr);
4164	outb(siocniobase + com_cfcr, CFCR_DLAB | cfcr);
4165	outb(siocniobase + com_dlbl,
4166	     COMBRD(comdefaultrate) & 0xff);
4167	outb(siocniobase + com_dlbh,
4168	     (u_int) COMBRD(comdefaultrate) >> 8);
4169	outb(siocniobase + com_cfcr, cfcr);
4170
4171	siocnopen(&sp, siocniobase, comdefaultrate);
4172	splx(s);
4173
4174	cn_tab = &sio_consdev;
4175	return 0;
4176}
4177
4178int
4179siogdbattach(port, speed)
4180	int port;
4181	int speed;
4182{
4183	int			s;
4184	u_char			cfcr;
4185	struct siocnstate	sp;
4186
4187	siogdbiobase = port;
4188	gdbdefaultrate = speed;
4189
4190	s = spltty();
4191
4192	/*
4193	 * Initialize the divisor latch.  We can't rely on
4194	 * siocnopen() to do this the first time, since it
4195	 * avoids writing to the latch if the latch appears
4196	 * to have the correct value.  Also, if we didn't
4197	 * just read the speed from the hardware, then we
4198	 * need to set the speed in hardware so that
4199	 * switching it later is null.
4200	 */
4201	cfcr = inb(siogdbiobase + com_cfcr);
4202	outb(siogdbiobase + com_cfcr, CFCR_DLAB | cfcr);
4203	outb(siogdbiobase + com_dlbl,
4204	     COMBRD(gdbdefaultrate) & 0xff);
4205	outb(siogdbiobase + com_dlbh,
4206	     (u_int) COMBRD(gdbdefaultrate) >> 8);
4207	outb(siogdbiobase + com_cfcr, cfcr);
4208
4209	siocnopen(&sp, siogdbiobase, gdbdefaultrate);
4210	splx(s);
4211
4212	return 0;
4213}
4214
4215#endif
4216
4217static void
4218siocninit(cp)
4219	struct consdev	*cp;
4220{
4221	comconsole = DEV_TO_UNIT(cp->cn_dev);
4222}
4223
4224static int
4225siocncheckc(dev)
4226	dev_t	dev;
4227{
4228	int	c;
4229	Port_t	iobase;
4230	int	s;
4231	struct siocnstate	sp;
4232
4233	if (minor(dev) == siogdbunit)
4234		iobase = siogdbiobase;
4235	else
4236		iobase = siocniobase;
4237	s = spltty();
4238	siocnopen(&sp, iobase, comdefaultrate);
4239	if (inb(iobase + com_lsr) & LSR_RXRDY)
4240		c = inb(iobase + com_data);
4241	else
4242		c = -1;
4243	siocnclose(&sp, iobase);
4244	splx(s);
4245	return (c);
4246}
4247
4248
4249int
4250siocngetc(dev)
4251	dev_t	dev;
4252{
4253	int	c;
4254	Port_t	iobase;
4255	int	s;
4256	struct siocnstate	sp;
4257
4258	if (minor(dev) == siogdbunit)
4259		iobase = siogdbiobase;
4260	else
4261		iobase = siocniobase;
4262	s = spltty();
4263	siocnopen(&sp, iobase, comdefaultrate);
4264	while (!(inb(iobase + com_lsr) & LSR_RXRDY))
4265		;
4266	c = inb(iobase + com_data);
4267	siocnclose(&sp, iobase);
4268	splx(s);
4269	return (c);
4270}
4271
4272void
4273siocnputc(dev, c)
4274	dev_t	dev;
4275	int	c;
4276{
4277	int	s;
4278	struct siocnstate	sp;
4279	Port_t	iobase;
4280
4281	if (minor(dev) == siogdbunit)
4282		iobase = siogdbiobase;
4283	else
4284		iobase = siocniobase;
4285	s = spltty();
4286	siocnopen(&sp, iobase, comdefaultrate);
4287	siocntxwait(iobase);
4288	outb(iobase + com_data, c);
4289	siocnclose(&sp, iobase);
4290	splx(s);
4291}
4292
4293#ifdef __alpha__
4294int
4295siogdbgetc()
4296{
4297	int	c;
4298	Port_t	iobase;
4299	int	s;
4300	struct siocnstate	sp;
4301
4302	iobase = siogdbiobase;
4303	s = spltty();
4304	siocnopen(&sp, iobase, gdbdefaultrate);
4305	while (!(inb(iobase + com_lsr) & LSR_RXRDY))
4306		;
4307	c = inb(iobase + com_data);
4308	siocnclose(&sp, iobase);
4309	splx(s);
4310	return (c);
4311}
4312
4313void
4314siogdbputc(c)
4315	int	c;
4316{
4317	int	s;
4318	struct siocnstate	sp;
4319
4320	s = spltty();
4321	siocnopen(&sp, siogdbiobase, gdbdefaultrate);
4322	siocntxwait(siogdbiobase);
4323	outb(siogdbiobase + com_data, c);
4324	siocnclose(&sp, siogdbiobase);
4325	splx(s);
4326}
4327#endif
4328
4329DRIVER_MODULE(sio, isa, sio_isa_driver, sio_devclass, 0, 0);
4330#if NCARD > 0
4331DRIVER_MODULE(sio, pccard, sio_pccard_driver, sio_devclass, 0, 0);
4332#endif
4333
4334#ifdef PC98
4335/*
4336 *  pc98 local function
4337 */
4338
4339static void
4340com_tiocm_set(struct com_s *com, int msr)
4341{
4342	int	s;
4343	int	tmp = 0;
4344	int	mask = CMD8251_TxEN|CMD8251_RxEN|CMD8251_DTR|CMD8251_RTS;
4345
4346	s=spltty();
4347	com->pc98_prev_modem_status = ( msr & (TIOCM_LE|TIOCM_DTR|TIOCM_RTS) )
4348	   | ( com->pc98_prev_modem_status & ~(TIOCM_LE|TIOCM_DTR|TIOCM_RTS) );
4349	tmp |= (CMD8251_TxEN|CMD8251_RxEN);
4350	if ( msr & TIOCM_DTR ) tmp |= CMD8251_DTR;
4351	if ( msr & TIOCM_RTS ) tmp |= CMD8251_RTS;
4352	pc98_i8251_clear_or_cmd( com, mask, tmp );
4353	splx(s);
4354}
4355
4356static void
4357com_tiocm_bis(struct com_s *com, int msr)
4358{
4359	int	s;
4360	int	tmp = 0;
4361
4362	s=spltty();
4363	com->pc98_prev_modem_status |= ( msr & (TIOCM_LE|TIOCM_DTR|TIOCM_RTS) );
4364	tmp |= CMD8251_TxEN|CMD8251_RxEN;
4365	if ( msr & TIOCM_DTR ) tmp |= CMD8251_DTR;
4366	if ( msr & TIOCM_RTS ) tmp |= CMD8251_RTS;
4367
4368	pc98_i8251_or_cmd( com, tmp );
4369	splx(s);
4370}
4371
4372static void
4373com_tiocm_bic(struct com_s *com, int msr)
4374{
4375	int	s;
4376	int	tmp = msr;
4377
4378	s=spltty();
4379	com->pc98_prev_modem_status &= ~( msr & (TIOCM_LE|TIOCM_DTR|TIOCM_RTS) );
4380	if ( msr & TIOCM_DTR ) tmp |= CMD8251_DTR;
4381	if ( msr & TIOCM_RTS ) tmp |= CMD8251_RTS;
4382
4383	pc98_i8251_clear_cmd( com, tmp );
4384	splx(s);
4385}
4386
4387static int
4388com_tiocm_get(struct com_s *com)
4389{
4390	return( com->pc98_prev_modem_status );
4391}
4392
4393static int
4394com_tiocm_get_delta(struct com_s *com)
4395{
4396	int	tmp;
4397
4398	tmp = com->pc98_modem_delta;
4399	com->pc98_modem_delta = 0;
4400	return( tmp );
4401}
4402
4403/* convert to TIOCM_?? ( ioctl.h ) */
4404static int
4405pc98_get_modem_status(struct com_s *com)
4406{
4407	int	stat, stat2;
4408	register int	msr;
4409
4410	stat  = inb(com->sts_port);
4411	stat2 = inb(com->in_modem_port);
4412	msr = com->pc98_prev_modem_status
4413			& ~(TIOCM_CAR|TIOCM_RI|TIOCM_DSR|TIOCM_CTS);
4414	if ( !(stat2 & CICSCD_CD) ) msr |= TIOCM_CAR;
4415	if ( !(stat2 & CICSCD_CI) ) msr |= TIOCM_RI;
4416	if (   stat & STS8251_DSR ) msr |= TIOCM_DSR;
4417	if ( !(stat2 & CICSCD_CS) ) msr |= TIOCM_CTS;
4418#if COM_CARRIER_DETECT_EMULATE
4419	if ( msr & (TIOCM_DSR|TIOCM_CTS) ) {
4420		msr |= TIOCM_CAR;
4421	}
4422#endif
4423	return(msr);
4424}
4425
4426static void
4427pc98_check_msr(void* chan)
4428{
4429	int	msr, delta;
4430	int	s;
4431	register struct tty *tp;
4432	struct	com_s *com;
4433	int	mynor;
4434	int	unit;
4435	dev_t	dev;
4436
4437	dev=(dev_t)chan;
4438	mynor = minor(dev);
4439	unit = MINOR_TO_UNIT(mynor);
4440	com = com_addr(unit);
4441	tp = com->tp;
4442
4443	s = spltty();
4444	msr = pc98_get_modem_status(com);
4445	/* make change flag */
4446	delta = msr ^ com->pc98_prev_modem_status;
4447	if ( delta & TIOCM_CAR ) {
4448	    if ( com->modem_car_chg_timer ) {
4449		if ( -- com->modem_car_chg_timer )
4450		    msr ^= TIOCM_CAR;
4451	    } else {
4452		if ((com->modem_car_chg_timer = (msr & TIOCM_CAR) ?
4453		     DCD_ON_RECOGNITION : DCD_OFF_TOLERANCE) != 0)
4454		    msr ^= TIOCM_CAR;
4455	    }
4456	} else
4457	    com->modem_car_chg_timer = 0;
4458	delta = ( msr ^ com->pc98_prev_modem_status ) &
4459			(TIOCM_CAR|TIOCM_RI|TIOCM_DSR|TIOCM_CTS);
4460	com->pc98_prev_modem_status = msr;
4461	delta = ( com->pc98_modem_delta |= delta );
4462	splx(s);
4463	if ( com->modem_checking || (tp->t_state & (TS_ISOPEN)) ) {
4464		if ( delta ) {
4465			commint(dev);
4466		}
4467		timeout(pc98_check_msr, (caddr_t)dev,
4468					PC98_CHECK_MODEM_INTERVAL);
4469	} else {
4470		com->modem_checking = 0;
4471	}
4472}
4473
4474static void
4475pc98_msrint_start(dev_t dev)
4476{
4477	struct	com_s *com;
4478	int	mynor;
4479	int	unit;
4480	int	s = spltty();
4481
4482	mynor = minor(dev);
4483	unit = MINOR_TO_UNIT(mynor);
4484	com = com_addr(unit);
4485	/* modem control line check routine envoke interval is 1/10 sec */
4486	if ( com->modem_checking == 0 ) {
4487		com->pc98_prev_modem_status = pc98_get_modem_status(com);
4488		com->pc98_modem_delta = 0;
4489		timeout(pc98_check_msr, (caddr_t)dev,
4490					PC98_CHECK_MODEM_INTERVAL);
4491		com->modem_checking = 1;
4492	}
4493	splx(s);
4494}
4495
4496static void
4497pc98_disable_i8251_interrupt(struct com_s *com, int mod)
4498{
4499	/* disable interrupt */
4500	register int	tmp;
4501
4502	mod |= ~(IEN_Tx|IEN_TxEMP|IEN_Rx);
4503	COM_INT_DISABLE
4504	tmp = inb( com->intr_ctrl_port ) & ~(IEN_Tx|IEN_TxEMP|IEN_Rx);
4505	outb( com->intr_ctrl_port, (com->intr_enable&=~mod) | tmp );
4506	COM_INT_ENABLE
4507}
4508
4509static void
4510pc98_enable_i8251_interrupt(struct com_s *com, int mod)
4511{
4512	register int	tmp;
4513
4514	COM_INT_DISABLE
4515	tmp = inb( com->intr_ctrl_port ) & ~(IEN_Tx|IEN_TxEMP|IEN_Rx);
4516	outb( com->intr_ctrl_port, (com->intr_enable|=mod) | tmp );
4517	COM_INT_ENABLE
4518}
4519
4520static int
4521pc98_check_i8251_interrupt(struct com_s *com)
4522{
4523	return ( com->intr_enable & 0x07 );
4524}
4525
4526static void
4527pc98_i8251_clear_cmd(struct com_s *com, int x)
4528{
4529	int	tmp;
4530
4531	COM_INT_DISABLE
4532	tmp = com->pc98_prev_siocmd & ~(x);
4533	outb(com->cmd_port, tmp);
4534	com->pc98_prev_siocmd = tmp & ~(CMD8251_ER|CMD8251_RESET|CMD8251_EH);
4535	COM_INT_ENABLE
4536}
4537
4538static void
4539pc98_i8251_or_cmd(struct com_s *com, int x)
4540{
4541	int	tmp;
4542
4543	COM_INT_DISABLE
4544	tmp = com->pc98_prev_siocmd | (x);
4545	outb(com->cmd_port, tmp);
4546	com->pc98_prev_siocmd = tmp & ~(CMD8251_ER|CMD8251_RESET|CMD8251_EH);
4547	COM_INT_ENABLE
4548}
4549
4550static void
4551pc98_i8251_set_cmd(struct com_s *com, int x)
4552{
4553	int	tmp;
4554
4555	COM_INT_DISABLE
4556	tmp = (x);
4557	outb(com->cmd_port, tmp);
4558	com->pc98_prev_siocmd = tmp & ~(CMD8251_ER|CMD8251_RESET|CMD8251_EH);
4559	COM_INT_ENABLE
4560}
4561
4562static void
4563pc98_i8251_clear_or_cmd(struct com_s *com, int clr, int x)
4564{
4565	int	tmp;
4566	COM_INT_DISABLE
4567	tmp = com->pc98_prev_siocmd & ~(clr);
4568	tmp |= (x);
4569	outb(com->cmd_port, tmp);
4570	com->pc98_prev_siocmd = tmp & ~(CMD8251_ER|CMD8251_RESET|CMD8251_EH);
4571	COM_INT_ENABLE
4572}
4573
4574static int
4575pc98_i8251_get_cmd(struct com_s *com)
4576{
4577	return com->pc98_prev_siocmd;
4578}
4579
4580static int
4581pc98_i8251_get_mod(struct com_s *com)
4582{
4583	return com->pc98_prev_siomod;
4584}
4585
4586static void
4587pc98_i8251_reset(struct com_s *com, int mode, int command)
4588{
4589	outb(com->cmd_port, 0);	/* dummy */
4590	DELAY(2);
4591	outb(com->cmd_port, 0);	/* dummy */
4592	DELAY(2);
4593	outb(com->cmd_port, 0);	/* dummy */
4594	DELAY(2);
4595	outb(com->cmd_port, CMD8251_RESET);	/* internal reset */
4596	DELAY(2);
4597	outb(com->cmd_port, mode );	/* mode register */
4598	com->pc98_prev_siomod = mode;
4599	DELAY(2);
4600	pc98_i8251_set_cmd( com, (command|CMD8251_ER) );
4601}
4602
4603static void
4604pc98_check_sysclock(void)
4605{
4606	/* get system clock from port */
4607	if ( pc98_machine_type & M_8M ) {
4608	/* 8 MHz system & H98 */
4609		sysclock = 8;
4610	} else {
4611	/* 5 MHz system */
4612		sysclock = 5;
4613	}
4614}
4615
4616static void
4617com_cflag_and_speed_set( struct com_s *com, int cflag, int speed)
4618{
4619	int	cfcr=0, count;
4620	int	previnterrupt;
4621
4622	count = pc98_ttspeedtab( com, speed );
4623	if ( count < 0 ) return;
4624
4625	previnterrupt = pc98_check_i8251_interrupt(com);
4626	pc98_disable_i8251_interrupt( com, IEN_Tx|IEN_TxEMP|IEN_Rx );
4627
4628	switch ( cflag&CSIZE ) {
4629	  case CS5:
4630		cfcr = MOD8251_5BITS; break;
4631	  case CS6:
4632		cfcr = MOD8251_6BITS; break;
4633	  case CS7:
4634		cfcr = MOD8251_7BITS; break;
4635	  case CS8:
4636		cfcr = MOD8251_8BITS; break;
4637	}
4638	if ( cflag&PARENB ) {
4639	    if ( cflag&PARODD )
4640		cfcr |= MOD8251_PODD;
4641	    else
4642		cfcr |= MOD8251_PEVEN;
4643	} else
4644		cfcr |= MOD8251_PDISAB;
4645
4646	if ( cflag&CSTOPB )
4647		cfcr |= MOD8251_STOP2;
4648	else
4649		cfcr |= MOD8251_STOP1;
4650
4651	if ( count & 0x10000 )
4652		cfcr |= MOD8251_CLKX1;
4653	else
4654		cfcr |= MOD8251_CLKX16;
4655
4656	if (epson_machine_id != 0x20) {	/* XXX */
4657		int	tmp;
4658		while (!((tmp = inb(com->sts_port)) & STS8251_TxEMP))
4659			;
4660	}
4661	/* set baud rate from ospeed */
4662	pc98_set_baud_rate( com, count );
4663
4664	if ( cfcr != pc98_i8251_get_mod(com) )
4665		pc98_i8251_reset(com, cfcr, pc98_i8251_get_cmd(com) );
4666
4667	pc98_enable_i8251_interrupt( com, previnterrupt );
4668}
4669
4670static int
4671pc98_ttspeedtab(struct com_s *com, int speed)
4672{
4673	int	if_type, effect_sp, count = -1, mod;
4674
4675	if_type = com->pc98_if_type & 0x0f;
4676
4677	switch (com->pc98_if_type) {
4678	case COM_IF_INTERNAL:
4679	    if (PC98SIO_baud_rate_port(if_type) != -1) {
4680		count = ttspeedtab(speed, if_8251_type[if_type].speedtab);
4681		if (count > 0) {
4682		    count |= COM1_EXT_CLOCK;
4683		    break;
4684		}
4685	    }
4686
4687	    /* for *1CLK asynchronous! mode, TEFUTEFU */
4688	    mod = (sysclock == 5) ? 2457600 : 1996800;
4689	    effect_sp = ttspeedtab( speed, pc98speedtab );
4690	    if ( effect_sp < 0 )	/* XXX */
4691		effect_sp = ttspeedtab( (speed - 1), pc98speedtab );
4692	    if ( effect_sp <= 0 )
4693		return effect_sp;
4694	    if ( effect_sp == speed )
4695		mod /= 16;
4696	    if ( mod % effect_sp )
4697		return(-1);
4698	    count = mod / effect_sp;
4699	    if ( count > 65535 )
4700		return(-1);
4701	    if ( effect_sp != speed )
4702		count |= 0x10000;
4703	    break;
4704	case COM_IF_PC9861K_1:
4705	case COM_IF_PC9861K_2:
4706	    count = 1;
4707	    break;
4708	case COM_IF_IND_SS_1:
4709	case COM_IF_IND_SS_2:
4710	case COM_IF_PIO9032B_1:
4711	case COM_IF_PIO9032B_2:
4712	    if ( speed == 0 ) return 0;
4713	    count = ttspeedtab( speed, if_8251_type[if_type].speedtab );
4714	    break;
4715	case COM_IF_B98_01_1:
4716	case COM_IF_B98_01_2:
4717	    if ( speed == 0 ) return 0;
4718	    count = ttspeedtab( speed, if_8251_type[if_type].speedtab );
4719#ifdef B98_01_OLD
4720	    if (count == 0 || count == 1) {
4721		count += 4;
4722		count |= 0x20000;  /* x1 mode for 76800 and 153600 */
4723	    }
4724#endif
4725	    break;
4726	}
4727
4728	return count;
4729}
4730
4731static void
4732pc98_set_baud_rate( struct com_s *com, int count )
4733{
4734	int	if_type, io, s;
4735
4736	if_type = com->pc98_if_type & 0x0f;
4737	io = com->iobase & 0xff00;
4738
4739	switch (com->pc98_if_type) {
4740	case COM_IF_INTERNAL:
4741	    if (PC98SIO_baud_rate_port(if_type) != -1) {
4742		if (count & COM1_EXT_CLOCK) {
4743		    outb((Port_t)PC98SIO_baud_rate_port(if_type), count & 0xff);
4744		    break;
4745		} else {
4746		    outb((Port_t)PC98SIO_baud_rate_port(if_type), 0x09);
4747		}
4748	    }
4749
4750	    if ( count < 0 ) {
4751		printf( "[ Illegal count : %d ]", count );
4752		return;
4753	    } else if ( count == 0 )
4754		return;
4755	    /* set i8253 */
4756	    s = splclock();
4757	    if (count != 3)
4758		outb( 0x77, 0xb6 );
4759	    else
4760		outb( 0x77, 0xb4 );
4761	    outb( 0x5f, 0);
4762	    outb( 0x75, count & 0xff );
4763	    outb( 0x5f, 0);
4764	    outb( 0x75, (count >> 8) & 0xff );
4765	    splx(s);
4766	    break;
4767	case COM_IF_IND_SS_1:
4768	case COM_IF_IND_SS_2:
4769	    outb(io | PC98SIO_intr_ctrl_port(if_type), 0);
4770	    outb(io | PC98SIO_baud_rate_port(if_type), 0);
4771	    outb(io | PC98SIO_baud_rate_port(if_type), 0xc0);
4772	    outb(io | PC98SIO_baud_rate_port(if_type), (count >> 8) | 0x80);
4773	    outb(io | PC98SIO_baud_rate_port(if_type), count & 0xff);
4774	    break;
4775	case COM_IF_PIO9032B_1:
4776	case COM_IF_PIO9032B_2:
4777	    outb(io | PC98SIO_baud_rate_port(if_type), count);
4778	    break;
4779	case COM_IF_B98_01_1:
4780	case COM_IF_B98_01_2:
4781	    outb(io | PC98SIO_baud_rate_port(if_type), count & 0x0f);
4782#ifdef B98_01_OLD
4783	    /*
4784	     * Some old B98_01 board should be controlled
4785	     * in different way, but this hasn't been tested yet.
4786	     */
4787	    outb(io | PC98SIO_func_port(if_type),
4788		 (count & 0x20000) ? 0xf0 : 0xf2);
4789#endif
4790	    break;
4791	}
4792}
4793static int
4794pc98_check_if_type(device_t dev, struct siodev *iod)
4795{
4796	int	irr, io, if_type, tmp;
4797	static  short	irq_tab[2][8] = {
4798		{  3,  5,  6,  9, 10, 12, 13, -1},
4799		{  3, 10, 12, 13,  5,  6,  9, -1}
4800	};
4801
4802	iod->if_type = if_type = (device_get_flags(dev) >> 24) & 0xff;
4803	if ((if_type < 0 || if_type > COM_IF_END1) &&
4804	    (if_type < 0x10 || if_type > COM_IF_END2))
4805	    return(-1);
4806	if_type &= 0x0f;
4807	iod->irq = 0;
4808	io = isa_get_port(dev) & 0xff00;
4809
4810	if (IS_8251(iod->if_type)) {
4811	    if (PC98SIO_func_port(if_type) != -1) {
4812		outb(io | PC98SIO_func_port(if_type), 0xf2);
4813		tmp = ttspeedtab(9600, if_8251_type[if_type].speedtab);
4814		if (tmp != -1 && PC98SIO_baud_rate_port(if_type) != -1)
4815		    outb(io | PC98SIO_baud_rate_port(if_type), tmp);
4816	    }
4817
4818	    iod->cmd  = io | PC98SIO_cmd_port(if_type);
4819	    iod->sts  = io | PC98SIO_sts_port(if_type);
4820	    iod->mod  = io | PC98SIO_in_modem_port(if_type);
4821	    iod->ctrl = io | PC98SIO_intr_ctrl_port(if_type);
4822
4823	    if (iod->if_type == COM_IF_INTERNAL) {
4824		iod->irq = 4;
4825
4826		/* XXX check new internal port. */
4827		outb(0x13a, 0);
4828		DELAY(10);
4829		for (tmp = 0; tmp < 100; tmp++) {
4830		    if ((inb(0x13a) & 0x80) == 0) {
4831			PC98SIO_baud_rate_port(if_type) = 0x13a;
4832			if_8251_type[if_type].name = " (internal fast)";
4833			if_8251_type[if_type].speedtab = pc98fast_speedtab;
4834			break;
4835		    }
4836		    DELAY(1);
4837		}
4838	    } else {
4839		tmp = inb( iod->mod ) & if_8251_type[if_type].irr_mask;
4840		if ((isa_get_port(dev) & 0xff) == IO_COM2)
4841		    iod->irq = irq_tab[0][tmp];
4842		else
4843		    iod->irq = irq_tab[1][tmp];
4844	    }
4845	} else {
4846	    irr = if_16550a_type[if_type].irr_read;
4847#ifdef COM_MULTIPORT
4848	    if (!COM_ISMULTIPORT(device_get_flags(dev)) ||
4849		    device_get_unit(dev) == COM_MPMASTER(device_get_flags(dev)))
4850#endif
4851	    if (irr != -1) {
4852		tmp = inb(io | irr);
4853		if (isa_get_port(dev) & 0x01)	/* XXX depend on RSB-384 */
4854		    iod->irq = irq_tab[1][tmp >> 3];
4855		else
4856		    iod->irq = irq_tab[0][tmp & 0x07];
4857	    }
4858	}
4859	if ( iod->irq == -1 ) return -1;
4860
4861	return 0;
4862}
4863static int
4864pc98_set_ioport( struct com_s *com, int id_flags )
4865{
4866	int	io, if_type;
4867
4868	if_type = (id_flags >> 24) & 0xff;
4869	if (IS_8251(if_type)) {
4870	    pc98_check_sysclock();
4871	    io = com->iobase & 0xff00;
4872	    com->pc98_if_type	= if_type;
4873	    if_type &= 0x0f;
4874	    com->data_port	= io | PC98SIO_data_port(if_type);
4875	    com->cmd_port	= io | PC98SIO_cmd_port(if_type);
4876	    com->sts_port	= io | PC98SIO_sts_port(if_type);
4877	    com->in_modem_port	= io | PC98SIO_in_modem_port(if_type);
4878	    com->intr_ctrl_port	= io | PC98SIO_intr_ctrl_port(if_type);
4879	    return 0;
4880	}
4881
4882	return -1;
4883}
4884#endif /* PC98 defined */
4885