sio.c revision 119525
125184Sjkh/*-
225184Sjkh * Copyright (c) 1991 The Regents of the University of California.
350472Speter * All rights reserved.
425184Sjkh *
525184Sjkh * Redistribution and use in source and binary forms, with or without
651231Ssheldonh * modification, are permitted provided that the following conditions
751231Ssheldonh * are met:
825184Sjkh * 1. Redistributions of source code must retain the above copyright
925184Sjkh *    notice, this list of conditions and the following disclaimer.
1025184Sjkh * 2. Redistributions in binary form must reproduce the above copyright
1125184Sjkh *    notice, this list of conditions and the following disclaimer in the
1251231Ssheldonh *    documentation and/or other materials provided with the distribution.
1325184Sjkh * 3. All advertising materials mentioning features or use of this software
1451231Ssheldonh *    must display the following acknowledgement:
1525184Sjkh *	This product includes software developed by the University of
1651231Ssheldonh *	California, Berkeley and its contributors.
1751231Ssheldonh * 4. Neither the name of the University nor the names of its contributors
1851231Ssheldonh *    may be used to endorse or promote products derived from this software
1951231Ssheldonh *    without specific prior written permission.
2051231Ssheldonh *
2151231Ssheldonh * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
2225184Sjkh * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
2351231Ssheldonh * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
2451231Ssheldonh * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
2551231Ssheldonh * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
2651231Ssheldonh * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
2751231Ssheldonh * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
2851231Ssheldonh * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
2951231Ssheldonh * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
3051231Ssheldonh * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
3151231Ssheldonh * SUCH DAMAGE.
3251231Ssheldonh *
3340006Sphk * $FreeBSD: head/sys/pc98/cbus/sio.c 119525 2003-08-28 11:20:54Z nyan $
3451231Ssheldonh *	from: @(#)com.c	7.5 (Berkeley) 5/16/91
3542621Shm *	from: i386/isa sio.c,v 1.234
3651231Ssheldonh */
3751231Ssheldonh
3851231Ssheldonh#include "opt_comconsole.h"
3951231Ssheldonh#include "opt_compat.h"
4051231Ssheldonh#include "opt_ddb.h"
4151231Ssheldonh#include "opt_sio.h"
4251231Ssheldonh
4351231Ssheldonh/*
4451231Ssheldonh * Serial driver, based on 386BSD-0.1 com driver.
4551231Ssheldonh * Mostly rewritten to use pseudo-DMA.
4642627Sjoerg * Works for National Semiconductor NS8250-NS16550AF UARTs.
4751231Ssheldonh * COM driver, based on HP dca driver.
4851231Ssheldonh *
4951231Ssheldonh * Changes for PC-Card integration:
5051231Ssheldonh *	- Added PC-Card driver table and handlers
5151231Ssheldonh */
5251231Ssheldonh/*===============================================================
5351231Ssheldonh * 386BSD(98),FreeBSD-1.1x(98) com driver.
5451231Ssheldonh * -----
5551231Ssheldonh * modified for PC9801 by M.Ishii
5651231Ssheldonh *			Kyoto University Microcomputer Club (KMC)
5751231Ssheldonh * Chou "TEFUTEFU" Hirotomi
5851231Ssheldonh *			Kyoto Univ.  the faculty of medicine
5951231Ssheldonh *===============================================================
6051231Ssheldonh * FreeBSD-2.0.1(98) sio driver.
6149122Sbrian * -----
6251231Ssheldonh * modified for pc98 Internal i8251 and MICRO CORE MC16550II
6351231Ssheldonh *			T.Koike(hfc01340@niftyserve.or.jp)
6451231Ssheldonh * implement kernel device configuration
6551231Ssheldonh *			aizu@orient.center.nitech.ac.jp
6651231Ssheldonh *
6751231Ssheldonh * Notes.
6851231Ssheldonh * -----
6949122Sbrian *  PC98 localization based on 386BSD(98) com driver. Using its PC98 local
7054458Sobrien *  functions.
7151231Ssheldonh *  This driver is under debugging,has bugs.
7251231Ssheldonh *
7351231Ssheldonh * 1) config
7454458Sobrien *  options COM_MULTIPORT  #if using MC16550II
7551231Ssheldonh *  device sio0 at nec? port 0x30  tty irq 4             #internal
7649122Sbrian *  device sio1 at nec? port 0xd2  tty irq 5 flags 0x101 #mc1
7751231Ssheldonh *  device sio2 at nec? port 0x8d2 tty flags 0x101       #mc2
7851231Ssheldonh *                         # ~~~~~iobase        ~~multi port flag
7951231Ssheldonh *                         #                   ~  master device is sio1
8029300Sdanny * 2) device
8151231Ssheldonh *  cd /dev; MAKEDEV ttyd0 ttyd1 ..
8251231Ssheldonh * 3) /etc/rc.serial
8351231Ssheldonh *  57600bps is too fast for sio0(internal8251)
8451231Ssheldonh *  my ex.
8554458Sobrien *    #set default speed 9600
8654458Sobrien *    modem()
8754458Sobrien *       :
8851231Ssheldonh *      stty </dev/ttyid$i crtscts 9600
8951231Ssheldonh *       :                 #       ~~~~ default speed(can change after init.)
9051231Ssheldonh *    modem 0 1 2
9154458Sobrien * 4) COMCONSOLE
9251231Ssheldonh *  not changed.
9351231Ssheldonh * 5) PC9861K,PIO9032B,B98_01
9454458Sobrien *  not tested.
9551231Ssheldonh */
9654458Sobrien/*
9754458Sobrien * modified for AIWA B98-01
9854458Sobrien * by T.Hatanou <hatanou@yasuda.comm.waseda.ac.jp>  last update: 15 Sep.1995
9954458Sobrien *
10054458Sobrien * How to configure...
10151231Ssheldonh *   # options COM_MULTIPORT         # support for MICROCORE MC16550II
10251231Ssheldonh *      ... comment-out this line, which will conflict with B98_01.
10351231Ssheldonh *   options "B98_01"                # support for AIWA B98-01
10451231Ssheldonh *   device  sio1 at nec? port 0x00d1 tty irq ?
10551231Ssheldonh *   device  sio2 at nec? port 0x00d5 tty irq ?
10651231Ssheldonh *      ... you can leave these lines `irq ?', irq will be autodetected.
10751231Ssheldonh */
10854458Sobrien/*
10951231Ssheldonh * Modified by Y.Takahashi of Kogakuin University.
11051231Ssheldonh */
11151231Ssheldonh/*
11251231Ssheldonh * modified for 8251(FIFO) by Seigo TANIMURA <tanimura@FreeBSD.org>
11351231Ssheldonh */
11451231Ssheldonh
11551231Ssheldonh#include <sys/param.h>
11651231Ssheldonh#include <sys/systm.h>
11751231Ssheldonh#include <sys/bus.h>
11851231Ssheldonh#include <sys/conf.h>
11951231Ssheldonh#include <sys/fcntl.h>
12054458Sobrien#include <sys/interrupt.h>
12151231Ssheldonh#include <sys/kernel.h>
12254458Sobrien#include <sys/limits.h>
12351231Ssheldonh#include <sys/lock.h>
12454458Sobrien#include <sys/malloc.h>
12554458Sobrien#include <sys/module.h>
12654458Sobrien#include <sys/mutex.h>
12751231Ssheldonh#include <sys/proc.h>
12854458Sobrien#include <sys/reboot.h>
12951231Ssheldonh#include <sys/sysctl.h>
13051231Ssheldonh#include <sys/syslog.h>
13157012Shm#include <sys/tty.h>
13257012Shm#include <machine/bus.h>
13357012Shm#include <sys/rman.h>
13457012Shm#include <sys/timepps.h>
13557012Shm#include <sys/uio.h>
13657012Shm#include <sys/cons.h>
13757012Shm#if DDB > 0
13857012Shm#include <ddb/ddb.h>
13957012Shm#endif
14057012Shm
14151231Ssheldonh#include <isa/isavar.h>
14251231Ssheldonh
14351231Ssheldonh#include <machine/resource.h>
14451231Ssheldonh
14551231Ssheldonh#include <dev/sio/sioreg.h>
14651231Ssheldonh#include <dev/sio/siovar.h>
14751231Ssheldonh
14851231Ssheldonh#ifdef PC98
14951231Ssheldonh#include <pc98/pc98/pc98.h>
15051231Ssheldonh#include <pc98/pc98/pc98_machdep.h>
15151231Ssheldonh#endif
15251231Ssheldonh
15351231Ssheldonh#ifdef COM_ESP
15451231Ssheldonh#include <dev/ic/esp.h>
15551231Ssheldonh#endif
15651231Ssheldonh#include <dev/ic/ns16550.h>
15751231Ssheldonh#ifdef PC98
15851231Ssheldonh#include <dev/ic/i8251.h>
15951231Ssheldonh#include <dev/ic/rsa.h>
16051231Ssheldonh#endif
16151231Ssheldonh
16251231Ssheldonh#define	LOTS_OF_EVENTS	64	/* helps separate urgent events from input */
16351231Ssheldonh
16451231Ssheldonh#define	CALLOUT_MASK		0x80
16551231Ssheldonh#define	CONTROL_MASK		0x60
16651231Ssheldonh#define	CONTROL_INIT_STATE	0x20
16751231Ssheldonh#define	CONTROL_LOCK_STATE	0x40
16851231Ssheldonh#define	DEV_TO_UNIT(dev)	(MINOR_TO_UNIT(minor(dev)))
16951231Ssheldonh#define	MINOR_TO_UNIT(mynor)	((((mynor) & ~0xffffU) >> (8 + 3)) \
17051231Ssheldonh				 | ((mynor) & 0x1f))
17151231Ssheldonh#define	UNIT_TO_MINOR(unit)	((((unit) & ~0x1fU) << (8 + 3)) \
17251231Ssheldonh				 | ((unit) & 0x1f))
17329300Sdanny
17451231Ssheldonh#ifdef COM_MULTIPORT
17529300Sdanny/* checks in flags for multiport and which is multiport "master chip"
17629300Sdanny * for a given card
17751231Ssheldonh */
17851231Ssheldonh#define	COM_ISMULTIPORT(flags)	((flags) & 0x01)
17951231Ssheldonh#define	COM_MPMASTER(flags)	(((flags) >> 8) & 0x0ff)
18051231Ssheldonh#define	COM_NOTAST4(flags)	((flags) & 0x04)
18151231Ssheldonh#else
18251231Ssheldonh#define	COM_ISMULTIPORT(flags)	(0)
18351231Ssheldonh#endif /* COM_MULTIPORT */
18451231Ssheldonh
18551231Ssheldonh#define	COM_CONSOLE(flags)	((flags) & 0x10)
18651231Ssheldonh#define	COM_FORCECONSOLE(flags)	((flags) & 0x20)
18744992Sbrian#define	COM_LLCONSOLE(flags)	((flags) & 0x40)
18851231Ssheldonh#define	COM_DEBUGGER(flags)	((flags) & 0x80)
18951231Ssheldonh#define	COM_LOSESOUTINTS(flags)	((flags) & 0x08)
19051231Ssheldonh#define	COM_NOFIFO(flags)		((flags) & 0x02)
19151231Ssheldonh#define	COM_PPSCTS(flags)	((flags) & 0x10000)
19251231Ssheldonh#define COM_ST16650A(flags)	((flags) & 0x20000)
19351231Ssheldonh#define COM_C_NOPROBE		(0x40000)
19444992Sbrian#define COM_NOPROBE(flags)	((flags) & COM_C_NOPROBE)
19551231Ssheldonh#define COM_C_IIR_TXRDYBUG	(0x80000)
19651231Ssheldonh#define COM_IIR_TXRDYBUG(flags)	((flags) & COM_C_IIR_TXRDYBUG)
19751231Ssheldonh#define COM_NOSCR(flags)	((flags) & 0x100000)
19851426Sgreen#define	COM_FIFOSIZE(flags)	(((flags) & 0xff000000) >> 24)
19951426Sgreen
20051231Ssheldonh#define	sio_getreg(com, off) \
20151231Ssheldonh	(bus_space_read_1((com)->bst, (com)->bsh, (off)))
20251231Ssheldonh#define	sio_setreg(com, off, value) \
20351231Ssheldonh	(bus_space_write_1((com)->bst, (com)->bsh, (off), (value)))
20451231Ssheldonh
20551231Ssheldonh/*
20651231Ssheldonh * com state bits.
20751231Ssheldonh * (CS_BUSY | CS_TTGO) and (CS_BUSY | CS_TTGO | CS_ODEVREADY) must be higher
20851231Ssheldonh * than the other bits so that they can be tested as a group without masking
20951231Ssheldonh * off the low bits.
21051231Ssheldonh *
21151231Ssheldonh * The following com and tty flags correspond closely:
21251231Ssheldonh *	CS_BUSY		= TS_BUSY (maintained by comstart(), siopoll() and
21351231Ssheldonh *				   comstop())
21451231Ssheldonh *	CS_TTGO		= ~TS_TTSTOP (maintained by comparam() and comstart())
21551231Ssheldonh *	CS_CTS_OFLOW	= CCTS_OFLOW (maintained by comparam())
21651231Ssheldonh *	CS_RTS_IFLOW	= CRTS_IFLOW (maintained by comparam())
21751231Ssheldonh * TS_FLUSH is not used.
21851231Ssheldonh * XXX I think TIOCSETA doesn't clear TS_TTSTOP when it clears IXON.
21951231Ssheldonh * XXX CS_*FLOW should be CF_*FLOW in com->flags (control flags not state).
22051231Ssheldonh */
22151231Ssheldonh#define	CS_BUSY		0x80	/* output in progress */
22251231Ssheldonh#define	CS_TTGO		0x40	/* output not stopped by XOFF */
22351231Ssheldonh#define	CS_ODEVREADY	0x20	/* external device h/w ready (CTS) */
22451231Ssheldonh#define	CS_CHECKMSR	1	/* check of MSR scheduled */
22551231Ssheldonh#define	CS_CTS_OFLOW	2	/* use CTS output flow control */
22660103Sache#define	CS_DTR_OFF	0x10	/* DTR held off */
22760103Sache#define	CS_ODONE	4	/* output completed */
22860103Sache#define	CS_RTS_IFLOW	8	/* use RTS input flow control */
22960103Sache#define	CSE_BUSYCHECK	1	/* siobusycheck() scheduled */
23060103Sache
23160103Sachestatic	char const * const	error_desc[] = {
23260103Sache#define	CE_OVERRUN			0
23360103Sache	"silo overflow",
23460103Sache#define	CE_INTERRUPT_BUF_OVERFLOW	1
23560103Sache	"interrupt-level buffer overflow",
23651231Ssheldonh#define	CE_TTY_BUF_OVERFLOW		2
23751231Ssheldonh	"tty-level buffer overflow",
23851231Ssheldonh};
23951231Ssheldonh
24051231Ssheldonh#define	CE_NTYPES			3
24151231Ssheldonh#define	CE_RECORD(com, errnum)		(++(com)->delta_error_counts[errnum])
24251231Ssheldonh
24351231Ssheldonh/* types.  XXX - should be elsewhere */
24451231Ssheldonhtypedef u_int	Port_t;		/* hardware port */
24529300Sdannytypedef u_char	bool_t;		/* boolean */
24625184Sjkh
24751231Ssheldonh/* queue of linear buffers */
24851231Ssheldonhstruct lbq {
24951231Ssheldonh	u_char	*l_head;	/* next char to process */
25051231Ssheldonh	u_char	*l_tail;	/* one past the last char to process */
25151231Ssheldonh	struct lbq *l_next;	/* next in queue */
25251231Ssheldonh	bool_t	l_queued;	/* nonzero if queued */
25351231Ssheldonh};
25451231Ssheldonh
25551231Ssheldonh/* com device structure */
25651231Ssheldonhstruct com_s {
25740006Sphk	u_int	flags;		/* Copy isa device flags */
25851231Ssheldonh	u_char	state;		/* miscellaneous flag bits */
25951231Ssheldonh	bool_t  active_out;	/* nonzero if the callout device is open */
26051231Ssheldonh	u_char	cfcr_image;	/* copy of value written to CFCR */
26151231Ssheldonh#ifdef COM_ESP
26251231Ssheldonh	bool_t	esp;		/* is this unit a hayes esp board? */
26351231Ssheldonh#endif
26451231Ssheldonh	u_char	extra_state;	/* more flag bits, separate for order trick */
26551231Ssheldonh	u_char	fifo_image;	/* copy of value written to FIFO */
26629300Sdanny	bool_t	hasfifo;	/* nonzero for 16550 UARTs */
26751231Ssheldonh	bool_t	st16650a;	/* Is a Startech 16650A or RTS/CTS compat */
26851231Ssheldonh	bool_t	loses_outints;	/* nonzero if device loses output interrupts */
26951231Ssheldonh	u_char	mcr_image;	/* copy of value written to MCR */
27051231Ssheldonh#ifdef COM_MULTIPORT
27151231Ssheldonh	bool_t	multiport;	/* is this unit part of a multiport device? */
27251231Ssheldonh#endif /* COM_MULTIPORT */
27351231Ssheldonh	bool_t	no_irq;		/* nonzero if irq is not attached */
27451231Ssheldonh	bool_t  gone;		/* hardware disappeared */
27551231Ssheldonh	bool_t	poll;		/* nonzero if polling is required */
27625184Sjkh	bool_t	poll_output;	/* nonzero if polling for output is required */
27751231Ssheldonh	int	unit;		/* unit	number */
27851231Ssheldonh	int	dtr_wait;	/* time to hold DTR down on close (* 1/hz) */
27951231Ssheldonh	u_int	tx_fifo_size;
28051231Ssheldonh	u_int	wopeners;	/* # processes waiting for DCD in open() */
28151231Ssheldonh
28251231Ssheldonh	/*
28345096Simp	 * The high level of the driver never reads status registers directly
28451231Ssheldonh	 * because there would be too many side effects to handle conveniently.
28551231Ssheldonh	 * Instead, it reads copies of the registers stored here by the
28651231Ssheldonh	 * interrupt handler.
28751231Ssheldonh	 */
28851231Ssheldonh	u_char	last_modem_status;	/* last MSR read by intr handler */
28951231Ssheldonh	u_char	prev_modem_status;	/* last MSR handled by high level */
29039267Sjkoshy
29151231Ssheldonh	u_char	hotchar;	/* ldisc-specific char to be handled ASAP */
29251231Ssheldonh	u_char	*ibuf;		/* start of input buffer */
29351231Ssheldonh	u_char	*ibufend;	/* end of input buffer */
29451231Ssheldonh	u_char	*ibufold;	/* old input buffer, to be freed */
29551231Ssheldonh	u_char	*ihighwater;	/* threshold in input buffer */
29651231Ssheldonh	u_char	*iptr;		/* next free spot in input buffer */
29733439Sguido	int	ibufsize;	/* size of ibuf (not include error bytes) */
29851231Ssheldonh	int	ierroff;	/* offset of error bytes in ibuf */
29951231Ssheldonh
30051231Ssheldonh	struct lbq	obufq;	/* head of queue of output buffers */
30151231Ssheldonh	struct lbq	obufs[2];	/* output buffers */
30251231Ssheldonh
30351231Ssheldonh	bus_space_tag_t		bst;
30433439Sguido	bus_space_handle_t	bsh;
30551231Ssheldonh
30651231Ssheldonh#ifdef PC98
30751231Ssheldonh	Port_t	cmd_port;
30851231Ssheldonh	Port_t	sts_port;
30951231Ssheldonh	Port_t	in_modem_port;
31051231Ssheldonh	Port_t	intr_ctrl_port;
31147752Sphk	Port_t	rsabase;	/* Iobase address of an I/O-DATA RSA board. */
31251231Ssheldonh	int	intr_enable;
31351231Ssheldonh	int	pc98_prev_modem_status;
31451231Ssheldonh	int	pc98_modem_delta;
31551231Ssheldonh	int	modem_car_chg_timer;
31651231Ssheldonh	int	pc98_prev_siocmd;
31751231Ssheldonh	int	pc98_prev_siomod;
31851209Sdes	int	modem_checking;
31951231Ssheldonh	int	pc98_if_type;
32051231Ssheldonh
32151231Ssheldonh	bool_t	pc98_8251fifo;
32251231Ssheldonh	bool_t	pc98_8251fifo_enable;
32351231Ssheldonh#endif /* PC98 */
32451231Ssheldonh	Port_t	data_port;	/* i/o ports */
32551209Sdes#ifdef COM_ESP
32651231Ssheldonh	Port_t	esp_port;
32751231Ssheldonh#endif
32851231Ssheldonh	Port_t	int_id_port;
32951231Ssheldonh	Port_t	modem_ctl_port;
33051231Ssheldonh	Port_t	line_status_port;
33151231Ssheldonh	Port_t	modem_status_port;
33236174Sjkh	Port_t	intr_ctl_port;	/* Ports of IIR register */
33351231Ssheldonh
33451231Ssheldonh	struct tty	*tp;	/* cross reference */
33551231Ssheldonh
33651231Ssheldonh	/* Initial state. */
33751231Ssheldonh	struct termios	it_in;	/* should be in struct tty */
33851231Ssheldonh	struct termios	it_out;
33936174Sjkh
34051231Ssheldonh	/* Lock state. */
34151231Ssheldonh	struct termios	lt_in;	/* should be in struct tty */
34251231Ssheldonh	struct termios	lt_out;
34351231Ssheldonh
34451231Ssheldonh	bool_t	do_timestamp;
34551231Ssheldonh	bool_t	do_dcd_timestamp;
34651231Ssheldonh	struct timeval	timestamp;
34751231Ssheldonh	struct timeval	dcd_timestamp;
34851231Ssheldonh	struct	pps_state pps;
34951231Ssheldonh	int	pps_bit;
35051231Ssheldonh#ifdef ALT_BREAK_TO_DEBUGGER
35151231Ssheldonh	int	alt_brk_state;
35251231Ssheldonh#endif
35351231Ssheldonh
35451231Ssheldonh	u_long	bytes_in;	/* statistics */
35551231Ssheldonh	u_long	bytes_out;
35651231Ssheldonh	u_int	delta_error_counts[CE_NTYPES];
35751231Ssheldonh	u_long	error_counts[CE_NTYPES];
35851231Ssheldonh
35951231Ssheldonh	u_long	rclk;
36051231Ssheldonh
36151231Ssheldonh	struct resource *irqres;
36251231Ssheldonh	struct resource *ioportres;
36351231Ssheldonh	int	ioportrid;
36451231Ssheldonh	void	*cookie;
36551231Ssheldonh	dev_t	devs[6];
36651231Ssheldonh
36751231Ssheldonh	/*
36851231Ssheldonh	 * Data area for output buffers.  Someday we should build the output
36951231Ssheldonh	 * buffer queue without copying data.
37051231Ssheldonh	 */
37151231Ssheldonh#ifdef PC98
37251231Ssheldonh	int	obufsize;
37351231Ssheldonh 	u_char	*obuf1;
37451231Ssheldonh 	u_char	*obuf2;
37551231Ssheldonh#else
37651231Ssheldonh	u_char	obuf1[256];
37751231Ssheldonh	u_char	obuf2[256];
37851231Ssheldonh#endif
37951231Ssheldonh};
38051231Ssheldonh
38151231Ssheldonh#ifdef COM_ESP
38251231Ssheldonhstatic	int	espattach(struct com_s *com, Port_t esp_port);
38351231Ssheldonh#endif
38451231Ssheldonh
38525184Sjkhstatic	timeout_t siobusycheck;
38625184Sjkhstatic	u_int	siodivisor(u_long rclk, speed_t speed);
38725184Sjkhstatic	timeout_t siodtrwakeup;
38851231Ssheldonhstatic	void	comhardclose(struct com_s *com);
38951231Ssheldonhstatic	void	sioinput(struct com_s *com);
39051231Ssheldonhstatic	void	siointr1(struct com_s *com);
39151231Ssheldonhstatic	void	siointr(void *arg);
39251231Ssheldonhstatic	int	commctl(struct com_s *com, int bits, int how);
39351231Ssheldonhstatic	int	comparam(struct tty *tp, struct termios *t);
39425184Sjkhstatic	void	siopoll(void *);
39551231Ssheldonhstatic	void	siosettimeout(void);
39651231Ssheldonhstatic	int	siosetwater(struct com_s *com, speed_t speed);
39751231Ssheldonhstatic	void	comstart(struct tty *tp);
39851231Ssheldonhstatic	void	comstop(struct tty *tp, int rw);
39951231Ssheldonhstatic	timeout_t comwakeup;
40051231Ssheldonhstatic	void	disc_optim(struct tty *tp, struct termios *t,
40125184Sjkh		    struct com_s *com);
40251231Ssheldonh
40351231Ssheldonhchar		sio_driver_name[] = "sio";
40454739Srobertostatic struct	mtx sio_lock;
40551231Ssheldonhstatic int	sio_inited;
40651231Ssheldonh
40725184Sjkh/* table and macro for fast conversion from a unit number to its com struct */
40851231Ssheldonhdevclass_t	sio_devclass;
40951231Ssheldonh#define	com_addr(unit)	((struct com_s *) \
41051231Ssheldonh			 devclass_get_softc(sio_devclass, unit)) /* XXX */
41151231Ssheldonh
41251231Ssheldonhstatic	d_open_t	sioopen;
41325184Sjkhstatic	d_close_t	sioclose;
41451231Ssheldonhstatic	d_read_t	sioread;
41551231Ssheldonhstatic	d_write_t	siowrite;
41651231Ssheldonhstatic	d_ioctl_t	sioioctl;
41751231Ssheldonh
41851231Ssheldonh#define	CDEV_MAJOR	28
41925184Sjkhstatic struct cdevsw sio_cdevsw = {
42051231Ssheldonh	.d_open =	sioopen,
42151231Ssheldonh	.d_close =	sioclose,
42251231Ssheldonh	.d_read =	sioread,
42351231Ssheldonh	.d_write =	siowrite,
42451231Ssheldonh	.d_ioctl =	sioioctl,
42551231Ssheldonh	.d_poll =	ttypoll,
42625184Sjkh	.d_name =	sio_driver_name,
42751231Ssheldonh	.d_maj =	CDEV_MAJOR,
42851231Ssheldonh	.d_flags =	D_TTY,
42951231Ssheldonh	.d_kqfilter =	ttykqfilter,
43051231Ssheldonh};
43151231Ssheldonh
43251231Ssheldonhint	comconsole = -1;
43325184Sjkhstatic	volatile speed_t	comdefaultrate = CONSPEED;
43451231Ssheldonhstatic	u_long			comdefaultrclk = DEFAULT_RCLK;
43551231SsheldonhSYSCTL_ULONG(_machdep, OID_AUTO, conrclk, CTLFLAG_RW, &comdefaultrclk, 0, "");
43651231Ssheldonhstatic	speed_t			gdbdefaultrate = GDBSPEED;
43751231SsheldonhSYSCTL_UINT(_machdep, OID_AUTO, gdbspeed, CTLFLAG_RW,
43851231Ssheldonh	    &gdbdefaultrate, GDBSPEED, "");
43951231Ssheldonhstatic	u_int	com_events;	/* input chars + weighted output completions */
44051231Ssheldonhstatic	Port_t	siocniobase;
44151231Ssheldonhstatic	int	siocnunit = -1;
44235149Smarkmstatic	Port_t	siogdbiobase;
44351231Ssheldonhstatic	int	siogdbunit = -1;
44451231Ssheldonhstatic	void	*sio_slow_ih;
44551231Ssheldonhstatic	void	*sio_fast_ih;
44651231Ssheldonhstatic	int	sio_timeout;
44751231Ssheldonhstatic	int	sio_timeouts_until_log;
44851231Ssheldonhstatic	struct	callout_handle sio_timeout_handle
44951231Ssheldonh    = CALLOUT_HANDLE_INITIALIZER(&sio_timeout_handle);
45051231Ssheldonhstatic	int	sio_numunits;
45151231Ssheldonh
45251231Ssheldonh#ifdef PC98
45351231Ssheldonhstruct	siodev	{
45451231Ssheldonh	short	if_type;
45540006Sphk	short	irq;
45651231Ssheldonh	Port_t	cmd, sts, ctrl, mod;
45751231Ssheldonh};
45851231Ssheldonhstatic	int	sysclock;
45951231Ssheldonh
46051231Ssheldonh#define	COM_INT_DISABLE		{int previpri; previpri=spltty();
46151231Ssheldonh#define	COM_INT_ENABLE		splx(previpri);}
46251231Ssheldonh#define IEN_TxFLAG		IEN_Tx
46351231Ssheldonh
46451231Ssheldonh#define COM_CARRIER_DETECT_EMULATE	0
46551231Ssheldonh#define	PC98_CHECK_MODEM_INTERVAL	(hz/10)
46651231Ssheldonh#define DCD_OFF_TOLERANCE		2
46751231Ssheldonh#define DCD_ON_RECOGNITION		2
46851231Ssheldonh#define IS_8251(if_type)		(!(if_type & 0x10))
46951231Ssheldonh#define COM1_EXT_CLOCK			0x40000
47051231Ssheldonh
47151231Ssheldonhstatic	void	commint(dev_t dev);
47251231Ssheldonhstatic	void	com_tiocm_set(struct com_s *com, int msr);
47351231Ssheldonhstatic	void	com_tiocm_bis(struct com_s *com, int msr);
47451231Ssheldonhstatic	void	com_tiocm_bic(struct com_s *com, int msr);
47551231Ssheldonhstatic	int	com_tiocm_get(struct com_s *com);
47651231Ssheldonhstatic	int	com_tiocm_get_delta(struct com_s *com);
47751231Ssheldonhstatic	void	pc98_msrint_start(dev_t dev);
47851231Ssheldonhstatic	void	com_cflag_and_speed_set(struct com_s *com, int cflag, int speed);
47925184Sjkhstatic	int	pc98_ttspeedtab(struct com_s *com, int speed, u_int *divisor);
48025184Sjkhstatic	int	pc98_get_modem_status(struct com_s *com);
48125184Sjkhstatic	timeout_t	pc98_check_msr;
48251231Ssheldonhstatic	void	pc98_set_baud_rate(struct com_s *com, u_int count);
48325184Sjkhstatic	void	pc98_i8251_reset(struct com_s *com, int mode, int command);
48451231Ssheldonhstatic	void	pc98_disable_i8251_interrupt(struct com_s *com, int mod);
48551231Ssheldonhstatic	void	pc98_enable_i8251_interrupt(struct com_s *com, int mod);
48651231Ssheldonhstatic	int	pc98_check_i8251_interrupt(struct com_s *com);
48751231Ssheldonhstatic	int	pc98_i8251_get_cmd(struct com_s *com);
48851231Ssheldonhstatic	int	pc98_i8251_get_mod(struct com_s *com);
48951231Ssheldonhstatic	void	pc98_i8251_set_cmd(struct com_s *com, int x);
49051231Ssheldonhstatic	void	pc98_i8251_or_cmd(struct com_s *com, int x);
49151231Ssheldonhstatic	void	pc98_i8251_clear_cmd(struct com_s *com, int x);
49251231Ssheldonhstatic	void	pc98_i8251_clear_or_cmd(struct com_s *com, int clr, int x);
49351231Ssheldonhstatic	int	pc98_check_if_type(device_t dev, struct siodev *iod);
49451231Ssheldonhstatic	int	pc98_check_8251vfast(void);
49551231Ssheldonhstatic	int	pc98_check_8251fifo(void);
49651231Ssheldonhstatic	void	pc98_check_sysclock(void);
49751231Ssheldonhstatic	void	pc98_set_ioport(struct com_s *com);
49851231Ssheldonh
49951231Ssheldonh#define com_int_Tx_disable(com) \
50051231Ssheldonh		pc98_disable_i8251_interrupt(com,IEN_Tx|IEN_TxEMP)
50151231Ssheldonh#define com_int_Tx_enable(com) \
50251231Ssheldonh		pc98_enable_i8251_interrupt(com,IEN_TxFLAG)
50351231Ssheldonh#define com_int_Rx_disable(com) \
50451231Ssheldonh		pc98_disable_i8251_interrupt(com,IEN_Rx)
50551231Ssheldonh#define com_int_Rx_enable(com) \
50658710Sdillon		pc98_enable_i8251_interrupt(com,IEN_Rx)
50758710Sdillon#define com_int_TxRx_disable(com) \
50858710Sdillon		pc98_disable_i8251_interrupt(com,IEN_Tx|IEN_TxEMP|IEN_Rx)
50958710Sdillon#define com_int_TxRx_enable(com) \
51058710Sdillon		pc98_enable_i8251_interrupt(com,IEN_TxFLAG|IEN_Rx)
51151231Ssheldonh#define com_send_break_on(com) \
51251231Ssheldonh		pc98_i8251_or_cmd(com,CMD8251_SBRK)
51351231Ssheldonh#define com_send_break_off(com) \
51451231Ssheldonh		pc98_i8251_clear_cmd(com,CMD8251_SBRK)
51551231Ssheldonh
51651231Ssheldonhstatic struct speedtab pc98speedtab[] = {	/* internal RS232C interface */
51751231Ssheldonh	{ 0,		0, },
51851231Ssheldonh	{ 50,		50, },
51951231Ssheldonh	{ 75,		75, },
52051231Ssheldonh	{ 150,		150, },
52151231Ssheldonh	{ 200,		200, },
52251231Ssheldonh	{ 300,		300, },
52351231Ssheldonh	{ 600,		600, },
52453158Sache	{ 1200,		1200, },
52553158Sache	{ 2400,		2400, },
52653158Sache	{ 4800,		4800, },
52753158Sache	{ 9600,		9600, },
52853158Sache	{ 19200,	19200, },
52953158Sache	{ 38400,	38400, },
53053158Sache	{ 51200,	51200, },
53153158Sache	{ 76800,	76800, },
53253158Sache	{ 20800,	20800, },
53353158Sache	{ 31200,	31200, },
53453158Sache	{ 41600,	41600, },
53553158Sache	{ 62400,	62400, },
53653158Sache	{ -1,		-1 }
53753158Sache};
53853158Sachestatic struct speedtab pc98fast_speedtab[] = {
53953158Sache	{ 9600,		0x80 | (DEFAULT_RCLK / (16 * (9600))), },
54053158Sache	{ 19200,	0x80 | (DEFAULT_RCLK / (16 * (19200))), },
54151231Ssheldonh	{ 38400,	0x80 | (DEFAULT_RCLK / (16 * (38400))), },
54251231Ssheldonh	{ 57600,	0x80 | (DEFAULT_RCLK / (16 * (57600))), },
54351231Ssheldonh	{ 115200,	0x80 | (DEFAULT_RCLK / (16 * (115200))), },
54451231Ssheldonh	{ -1,		-1 }
54551231Ssheldonh};
54651231Ssheldonhstatic struct speedtab comspeedtab_pio9032b[] = {
54747755Sbde	{ 300,		6, },
54841371Sjkoshy	{ 600,		5, },
54951231Ssheldonh	{ 1200,		4, },
55051231Ssheldonh	{ 2400,		3, },
55151231Ssheldonh	{ 4800,		2, },
55251231Ssheldonh	{ 9600,		1, },
55325184Sjkh	{ 19200,	0, },
55456038Sgreen	{ 38400,	7, },
55556038Sgreen	{ -1,		-1 }
55656038Sgreen};
55756038Sgreenstatic struct speedtab comspeedtab_b98_01[] = {
55856038Sgreen	{ 75,		11, },
55956038Sgreen	{ 150,		10, },
56056038Sgreen	{ 300,		9, },
56151231Ssheldonh	{ 600,		8, },
56251231Ssheldonh	{ 1200,		7, },
56351231Ssheldonh	{ 2400,		6, },
56451231Ssheldonh	{ 4800,		5, },
56551231Ssheldonh	{ 9600,		4, },
56651231Ssheldonh	{ 19200,	3, },
56751231Ssheldonh	{ 38400,	2, },
56851231Ssheldonh	{ 76800,	1, },
56951231Ssheldonh	{ 153600,	0, },
57051231Ssheldonh	{ -1,		-1 }
57125184Sjkh};
57251231Ssheldonhstatic struct speedtab comspeedtab_ind[] = {
57351231Ssheldonh	{ 300,		1536, },
57451231Ssheldonh	{ 600,		768, },
57551231Ssheldonh	{ 1200,		384, },
57651231Ssheldonh	{ 2400,		192, },
57751231Ssheldonh	{ 4800,		96, },
57851231Ssheldonh	{ 9600,		48, },
57925184Sjkh	{ 19200,	24, },
58051231Ssheldonh	{ 38400,	12, },
58151231Ssheldonh	{ 57600,	8, },
58251231Ssheldonh	{ 115200,	4, },
58351231Ssheldonh	{ 153600,	3, },
58451231Ssheldonh	{ 230400,	2, },
58551231Ssheldonh	{ 460800,	1, },
58651231Ssheldonh	{ -1,		-1 }
58751231Ssheldonh};
58851231Ssheldonh
58951231Ssheldonhstruct {
59051231Ssheldonh	char	*name;
59151231Ssheldonh	short	port_table[7];
59251231Ssheldonh	short	irr_mask;
59351231Ssheldonh	struct speedtab	*speedtab;
59451231Ssheldonh	short	check_irq;
59551231Ssheldonh} if_8251_type[] = {
59651231Ssheldonh	/* COM_IF_INTERNAL */
59751231Ssheldonh	{ " (internal)", {0x30, 0x32, 0x32, 0x33, 0x35, -1, -1},
59851231Ssheldonh	     -1, pc98speedtab, 1 },
59938316Sphk	/* COM_IF_PC9861K_1 */
60051231Ssheldonh	{ " (PC9861K)", {0xb1, 0xb3, 0xb3, 0xb0, 0xb0, -1, -1},
60151231Ssheldonh	     3, NULL, 1 },
60251231Ssheldonh	/* COM_IF_PC9861K_2 */
60351231Ssheldonh	{ " (PC9861K)", {0xb9, 0xbb, 0xbb, 0xb2, 0xb2, -1, -1},
60451231Ssheldonh	      3, NULL, 1 },
60551231Ssheldonh	/* COM_IF_IND_SS_1 */
60651231Ssheldonh	{ " (IND-SS)", {0xb1, 0xb3, 0xb3, 0xb0, 0xb0, 0xb3, -1},
60751231Ssheldonh	     3, comspeedtab_ind, 1 },
60851231Ssheldonh	/* COM_IF_IND_SS_2 */
60951231Ssheldonh	{ " (IND-SS)", {0xb9, 0xbb, 0xbb, 0xb2, 0xb2, 0xbb, -1},
61051231Ssheldonh	     3, comspeedtab_ind, 1 },
61153611Sbrian	/* COM_IF_PIO9032B_1 */
61253611Sbrian	{ " (PIO9032B)", {0xb1, 0xb3, 0xb3, 0xb0, 0xb0, 0xb8, -1},
61353613Sbrian	      7, comspeedtab_pio9032b, 1 },
61453611Sbrian	/* COM_IF_PIO9032B_2 */
61553611Sbrian	{ " (PIO9032B)", {0xb9, 0xbb, 0xbb, 0xb2, 0xb2, 0xba, -1},
61653611Sbrian	      7, comspeedtab_pio9032b, 1 },
61753611Sbrian	/* COM_IF_B98_01_1 */
61853611Sbrian	{ " (B98-01)", {0xb1, 0xb3, 0xb3, 0xb0, 0xb0, 0xd1, 0xd3},
61953611Sbrian	      7, comspeedtab_b98_01, 0 },
62053611Sbrian	/* COM_IF_B98_01_2 */
62157459Smarkm	{ " (B98-01)", {0xb9, 0xbb, 0xbb, 0xb2, 0xb2, 0xd5, 0xd7},
62257459Smarkm	     7, comspeedtab_b98_01, 0 },
62357567Sjkh};
62460578Skris#define	PC98SIO_data_port(type)		(if_8251_type[type].port_table[0])
62557567Sjkh#define	PC98SIO_cmd_port(type)		(if_8251_type[type].port_table[1])
62657567Sjkh#define	PC98SIO_sts_port(type)		(if_8251_type[type].port_table[2])
62757459Smarkm#define	PC98SIO_in_modem_port(type)	(if_8251_type[type].port_table[3])
62860578Skris#define	PC98SIO_intr_ctrl_port(type)	(if_8251_type[type].port_table[4])
62960578Skris#define	PC98SIO_baud_rate_port(type)	(if_8251_type[type].port_table[5])
63060578Skris#define	PC98SIO_func_port(type)		(if_8251_type[type].port_table[6])
63160578Skris
63260578Skris#define	I8251F_data		0x130
63357459Smarkm#define	I8251F_lsr		0x132
63457459Smarkm#define	I8251F_msr		0x134
63551231Ssheldonh#define	I8251F_iir		0x136
63651231Ssheldonh#define	I8251F_fcr		0x138
63725184Sjkh#define	I8251F_div		0x13a
63853314Sache
63953314Sache
64053314Sachestatic bus_addr_t port_table_0[] =
64153314Sache	{0x000, 0x001, 0x002, 0x003, 0x004, 0x005, 0x006, 0x007};
64253314Sachestatic bus_addr_t port_table_1[] =
64353314Sache	{0x000, 0x002, 0x004, 0x006, 0x008, 0x00a, 0x00c, 0x00e};
64453314Sachestatic bus_addr_t port_table_8[] =
64553314Sache	{0x000, 0x100, 0x200, 0x300, 0x400, 0x500, 0x600, 0x700};
64653314Sachestatic bus_addr_t port_table_rsa[] = {
64753314Sache	0x008, 0x009, 0x00a, 0x00b, 0x00c, 0x00d, 0x00e, 0x00f,
64853314Sache	0x000, 0x001, 0x002, 0x003, 0x004, 0x005, 0x006, 0x007
64953314Sache};
65053314Sache
65153314Sachestruct {
65253314Sache	char		*name;
65353314Sache	short		irr_read;
654	short		irr_write;
655	bus_addr_t	*iat;
656	bus_size_t	iatsz;
657	u_long		rclk;
658} if_16550a_type[] = {
659	/* COM_IF_RSA98 */
660	{" (RSA-98)", -1, -1, port_table_0, IO_COMSIZE, DEFAULT_RCLK},
661	/* COM_IF_NS16550 */
662	{"", -1, -1, port_table_0, IO_COMSIZE, DEFAULT_RCLK},
663	/* COM_IF_SECOND_CCU */
664	{"", -1, -1, port_table_0, IO_COMSIZE, DEFAULT_RCLK},
665	/* COM_IF_MC16550II */
666	{" (MC16550II)", -1, 0x1000, port_table_8, IO_COMSIZE,
667	 DEFAULT_RCLK * 4},
668	/* COM_IF_MCRS98 */
669	{" (MC-RS98)", -1, 0x1000, port_table_8, IO_COMSIZE, DEFAULT_RCLK * 4},
670	/* COM_IF_RSB3000 */
671	{" (RSB-3000)", 0xbf, -1, port_table_1, IO_COMSIZE, DEFAULT_RCLK * 10},
672	/* COM_IF_RSB384 */
673	{" (RSB-384)", 0xbf, -1, port_table_1, IO_COMSIZE, DEFAULT_RCLK * 10},
674	/* COM_IF_MODEM_CARD */
675	{"", -1, -1, port_table_0, IO_COMSIZE, DEFAULT_RCLK},
676	/* COM_IF_RSA98III */
677	{" (RSA-98III)", -1, -1, port_table_rsa, 16, DEFAULT_RCLK * 8},
678	/* COM_IF_ESP98 */
679	{" (ESP98)", -1, -1, port_table_1, IO_COMSIZE, DEFAULT_RCLK * 4},
680};
681#endif /* PC98 */
682
683#ifdef COM_ESP
684#ifdef PC98
685
686/* XXX configure this properly. */
687/* XXX quite broken for new-bus. */
688static  Port_t  likely_com_ports[] = { 0, 0xb0, 0xb1, 0 };
689static  Port_t  likely_esp_ports[] = { 0xc0d0, 0 };
690
691#define	ESP98_CMD1	(ESP_CMD1 * 0x100)
692#define	ESP98_CMD2	(ESP_CMD2 * 0x100)
693#define	ESP98_STATUS1	(ESP_STATUS1 * 0x100)
694#define	ESP98_STATUS2	(ESP_STATUS2 * 0x100)
695
696#else /* PC98 */
697
698/* XXX configure this properly. */
699static	Port_t	likely_com_ports[] = { 0x3f8, 0x2f8, 0x3e8, 0x2e8, };
700static	Port_t	likely_esp_ports[] = { 0x140, 0x180, 0x280, 0 };
701
702#endif /* PC98 */
703#endif
704
705/*
706 * handle sysctl read/write requests for console speed
707 *
708 * In addition to setting comdefaultrate for I/O through /dev/console,
709 * also set the initial and lock values for the /dev/ttyXX device
710 * if there is one associated with the console.  Finally, if the /dev/tty
711 * device has already been open, change the speed on the open running port
712 * itself.
713 */
714
715static int
716sysctl_machdep_comdefaultrate(SYSCTL_HANDLER_ARGS)
717{
718	int error, s;
719	speed_t newspeed;
720	struct com_s *com;
721	struct tty *tp;
722
723	newspeed = comdefaultrate;
724
725	error = sysctl_handle_opaque(oidp, &newspeed, sizeof newspeed, req);
726	if (error || !req->newptr)
727		return (error);
728
729	comdefaultrate = newspeed;
730
731	if (comconsole < 0)		/* serial console not selected? */
732		return (0);
733
734	com = com_addr(comconsole);
735	if (com == NULL)
736		return (ENXIO);
737
738	/*
739	 * set the initial and lock rates for /dev/ttydXX and /dev/cuaXX
740	 * (note, the lock rates really are boolean -- if non-zero, disallow
741	 *  speed changes)
742	 */
743	com->it_in.c_ispeed  = com->it_in.c_ospeed =
744	com->lt_in.c_ispeed  = com->lt_in.c_ospeed =
745	com->it_out.c_ispeed = com->it_out.c_ospeed =
746	com->lt_out.c_ispeed = com->lt_out.c_ospeed = comdefaultrate;
747
748	/*
749	 * if we're open, change the running rate too
750	 */
751	tp = com->tp;
752	if (tp && (tp->t_state & TS_ISOPEN)) {
753		tp->t_termios.c_ispeed =
754		tp->t_termios.c_ospeed = comdefaultrate;
755		s = spltty();
756		error = comparam(tp, &tp->t_termios);
757		splx(s);
758	}
759	return error;
760}
761
762SYSCTL_PROC(_machdep, OID_AUTO, conspeed, CTLTYPE_INT | CTLFLAG_RW,
763	    0, 0, sysctl_machdep_comdefaultrate, "I", "");
764
765/*
766 *	Unload the driver and clear the table.
767 *	XXX this is mostly wrong.
768 *	XXX TODO:
769 *	This is usually called when the card is ejected, but
770 *	can be caused by a kldunload of a controller driver.
771 *	The idea is to reset the driver's view of the device
772 *	and ensure that any driver entry points such as
773 *	read and write do not hang.
774 */
775int
776siodetach(dev)
777	device_t	dev;
778{
779	struct com_s	*com;
780	int i;
781
782	com = (struct com_s *) device_get_softc(dev);
783	if (com == NULL) {
784		device_printf(dev, "NULL com in siounload\n");
785		return (0);
786	}
787	com->gone = 1;
788	for (i = 0 ; i < 6; i++)
789		destroy_dev(com->devs[i]);
790	if (com->irqres) {
791		bus_teardown_intr(dev, com->irqres, com->cookie);
792		bus_release_resource(dev, SYS_RES_IRQ, 0, com->irqres);
793	}
794	if (com->ioportres)
795		bus_release_resource(dev, SYS_RES_IOPORT, com->ioportrid,
796				     com->ioportres);
797	if (com->tp && (com->tp->t_state & TS_ISOPEN)) {
798		device_printf(dev, "still open, forcing close\n");
799		(*linesw[com->tp->t_line].l_close)(com->tp, 0);
800		com->tp->t_gen++;
801		ttyclose(com->tp);
802		ttwakeup(com->tp);
803		ttwwakeup(com->tp);
804	} else {
805		if (com->ibuf != NULL)
806			free(com->ibuf, M_DEVBUF);
807#ifdef PC98
808		if (com->obuf1 != NULL)
809			free(com->obuf1, M_DEVBUF);
810#endif
811		device_set_softc(dev, NULL);
812		free(com, M_DEVBUF);
813	}
814	return (0);
815}
816
817int
818sioprobe(dev, xrid, rclk, noprobe)
819	device_t	dev;
820	int		xrid;
821	u_long		rclk;
822	int		noprobe;
823{
824#if 0
825	static bool_t	already_init;
826	device_t	xdev;
827#endif
828	struct com_s	*com;
829	u_int		divisor;
830	bool_t		failures[10];
831	int		fn;
832	device_t	idev;
833	Port_t		iobase;
834	intrmask_t	irqmap[4];
835	intrmask_t	irqs;
836	u_char		mcr_image;
837	int		result;
838	u_long		xirq;
839	u_int		flags = device_get_flags(dev);
840	int		rid;
841	struct resource *port;
842#ifdef PC98
843	int		tmp;
844	struct siodev	iod;
845#endif
846
847#ifdef PC98
848	iod.if_type = GET_IFTYPE(flags);
849	if ((iod.if_type < 0 || iod.if_type > COM_IF_END1) &&
850	    (iod.if_type < 0x10 || iod.if_type > COM_IF_END2))
851			return ENXIO;
852#endif
853
854	rid = xrid;
855#ifdef PC98
856	if (IS_8251(iod.if_type)) {
857		port = bus_alloc_resource(dev, SYS_RES_IOPORT, &rid,
858					  0, ~0, 1, RF_ACTIVE);
859	} else if (iod.if_type == COM_IF_MODEM_CARD ||
860		   iod.if_type == COM_IF_RSA98III ||
861		   isa_get_vendorid(dev)) {
862		port = bus_alloc_resource(dev, SYS_RES_IOPORT, &rid, 0, ~0,
863		  if_16550a_type[iod.if_type & 0x0f].iatsz, RF_ACTIVE);
864	} else {
865		port = isa_alloc_resourcev(dev, SYS_RES_IOPORT, &rid,
866		   if_16550a_type[iod.if_type & 0x0f].iat,
867		   if_16550a_type[iod.if_type & 0x0f].iatsz, RF_ACTIVE);
868	}
869#else
870	port = bus_alloc_resource(dev, SYS_RES_IOPORT, &rid,
871				  0, ~0, IO_COMSIZE, RF_ACTIVE);
872#endif
873	if (!port)
874		return (ENXIO);
875#ifdef PC98
876	if (!IS_8251(iod.if_type)) {
877		if (isa_load_resourcev(port,
878		       if_16550a_type[iod.if_type & 0x0f].iat,
879		       if_16550a_type[iod.if_type & 0x0f].iatsz) != 0) {
880			bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
881			return ENXIO;
882		}
883	}
884#endif
885
886	com = malloc(sizeof(*com), M_DEVBUF, M_NOWAIT | M_ZERO);
887	if (com == NULL)
888		return (ENOMEM);
889	device_set_softc(dev, com);
890	com->bst = rman_get_bustag(port);
891	com->bsh = rman_get_bushandle(port);
892#ifdef PC98
893	if (!IS_8251(iod.if_type) && rclk == 0)
894		rclk = if_16550a_type[iod.if_type & 0x0f].rclk;
895#else
896	if (rclk == 0)
897		rclk = DEFAULT_RCLK;
898#endif
899	com->rclk = rclk;
900
901	while (sio_inited != 2)
902		if (atomic_cmpset_int(&sio_inited, 0, 1)) {
903			mtx_init(&sio_lock, sio_driver_name, NULL,
904			    (comconsole != -1) ?
905			    MTX_SPIN | MTX_QUIET : MTX_SPIN);
906			atomic_store_rel_int(&sio_inited, 2);
907		}
908
909#if 0
910	/*
911	 * XXX this is broken - when we are first called, there are no
912	 * previously configured IO ports.  We could hard code
913	 * 0x3f8, 0x2f8, 0x3e8, 0x2e8 etc but that's probably worse.
914	 * This code has been doing nothing since the conversion since
915	 * "count" is zero the first time around.
916	 */
917	if (!already_init) {
918		/*
919		 * Turn off MCR_IENABLE for all likely serial ports.  An unused
920		 * port with its MCR_IENABLE gate open will inhibit interrupts
921		 * from any used port that shares the interrupt vector.
922		 * XXX the gate enable is elsewhere for some multiports.
923		 */
924		device_t *devs;
925		int count, i, xioport;
926#ifdef PC98
927		int xiftype;
928#endif
929
930		devclass_get_devices(sio_devclass, &devs, &count);
931#ifdef PC98
932		for (i = 0; i < count; i++) {
933			xdev = devs[i];
934			xioport = bus_get_resource_start(xdev, SYS_RES_IOPORT, 0);
935			xiftype = GET_IFTYPE(device_get_flags(xdev));
936			if (device_is_enabled(xdev) && xioport > 0) {
937			    if (IS_8251(xiftype))
938				outb((xioport & 0xff00) | PC98SIO_cmd_port(xiftype & 0x0f), 0xf2);
939			    else
940				outb(xioport + if_16550a_type[xiftype & 0x0f].iat[com_mcr], 0);
941			}
942		}
943#else
944		for (i = 0; i < count; i++) {
945			xdev = devs[i];
946			if (device_is_enabled(xdev) &&
947			    bus_get_resource(xdev, SYS_RES_IOPORT, 0, &xioport,
948					     NULL) == 0)
949				outb(xioport + com_mcr, 0);
950		}
951#endif
952		free(devs, M_TEMP);
953		already_init = TRUE;
954	}
955#endif
956
957	if (COM_LLCONSOLE(flags)) {
958		printf("sio%d: reserved for low-level i/o\n",
959		       device_get_unit(dev));
960		bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
961		device_set_softc(dev, NULL);
962		free(com, M_DEVBUF);
963		return (ENXIO);
964	}
965
966#ifdef PC98
967	DELAY(10);
968
969	/*
970	 * If the port is i8251 UART (internal, B98_01)
971	 */
972	if (pc98_check_if_type(dev, &iod) == -1) {
973		bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
974		device_set_softc(dev, NULL);
975		free(com, M_DEVBUF);
976		return (ENXIO);
977	}
978	if (iod.irq > 0)
979		bus_set_resource(dev, SYS_RES_IRQ, 0, iod.irq, 1);
980	if (IS_8251(iod.if_type)) {
981		outb(iod.cmd, 0);
982		DELAY(10);
983		outb(iod.cmd, 0);
984		DELAY(10);
985		outb(iod.cmd, 0);
986		DELAY(10);
987		outb(iod.cmd, CMD8251_RESET);
988		DELAY(1000);		/* for a while...*/
989		outb(iod.cmd, 0xf2);	/* MODE (dummy) */
990		DELAY(10);
991		outb(iod.cmd, 0x01);	/* CMD (dummy) */
992		DELAY(1000);		/* for a while...*/
993		if (( inb(iod.sts) & STS8251_TxEMP ) == 0 ) {
994		    result = (ENXIO);
995		}
996		if (if_8251_type[iod.if_type & 0x0f].check_irq) {
997		    COM_INT_DISABLE
998		    tmp = ( inb( iod.ctrl ) & ~(IEN_Rx|IEN_TxEMP|IEN_Tx));
999		    outb( iod.ctrl, tmp|IEN_TxEMP );
1000		    DELAY(10);
1001		    result = isa_irq_pending() ? 0 : ENXIO;
1002		    outb( iod.ctrl, tmp );
1003		    COM_INT_ENABLE
1004		} else {
1005		    /*
1006		     * B98_01 doesn't activate TxEMP interrupt line
1007		     * when being reset, so we can't check irq pending.
1008		     */
1009		    result = 0;
1010		}
1011		if (epson_machine_id==0x20) {	/* XXX */
1012		    result = 0;
1013		}
1014		bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
1015		if (result) {
1016			device_set_softc(dev, NULL);
1017			free(com, M_DEVBUF);
1018		}
1019		return result;
1020	}
1021#endif /* PC98 */
1022	/*
1023	 * If the device is on a multiport card and has an AST/4
1024	 * compatible interrupt control register, initialize this
1025	 * register and prepare to leave MCR_IENABLE clear in the mcr.
1026	 * Otherwise, prepare to set MCR_IENABLE in the mcr.
1027	 * Point idev to the device struct giving the correct id_irq.
1028	 * This is the struct for the master device if there is one.
1029	 */
1030	idev = dev;
1031	mcr_image = MCR_IENABLE;
1032#ifdef COM_MULTIPORT
1033	if (COM_ISMULTIPORT(flags)) {
1034#ifndef PC98
1035		Port_t xiobase;
1036		u_long io;
1037#endif
1038
1039		idev = devclass_get_device(sio_devclass, COM_MPMASTER(flags));
1040		if (idev == NULL) {
1041			printf("sio%d: master device %d not configured\n",
1042			       device_get_unit(dev), COM_MPMASTER(flags));
1043			idev = dev;
1044		}
1045#ifndef PC98
1046		if (!COM_NOTAST4(flags)) {
1047			if (bus_get_resource(idev, SYS_RES_IOPORT, 0, &io,
1048					     NULL) == 0) {
1049				xiobase = io;
1050				if (bus_get_resource(idev, SYS_RES_IRQ, 0,
1051				    NULL, NULL) == 0)
1052					outb(xiobase + com_scr, 0x80);
1053				else
1054					outb(xiobase + com_scr, 0);
1055			}
1056			mcr_image = 0;
1057		}
1058#endif
1059	}
1060#endif /* COM_MULTIPORT */
1061	if (bus_get_resource(idev, SYS_RES_IRQ, 0, NULL, NULL) != 0)
1062		mcr_image = 0;
1063
1064	bzero(failures, sizeof failures);
1065	iobase = rman_get_start(port);
1066
1067#ifdef PC98
1068        if (iod.if_type == COM_IF_RSA98III) {
1069		mcr_image = 0;
1070
1071		outb(iobase + rsa_msr,   0x04);
1072		outb(iobase + rsa_frr,   0x00);
1073		if ((inb(iobase + rsa_srr) & 0x36) != 0x36) {
1074			bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
1075			device_set_softc(dev, NULL);
1076			free(com, M_DEVBUF);
1077			return (ENXIO);
1078		}
1079		outb(iobase + rsa_ier,   0x00);
1080		outb(iobase + rsa_frr,   0x00);
1081		outb(iobase + rsa_tivsr, 0x00);
1082		outb(iobase + rsa_tcr,   0x00);
1083	}
1084
1085	tmp = if_16550a_type[iod.if_type & 0x0f].irr_write;
1086	if (tmp != -1) {
1087	    /* MC16550II */
1088	    int	irqout;
1089	    switch (isa_get_irq(idev)) {
1090	    case 3: irqout = 4; break;
1091	    case 5: irqout = 5; break;
1092	    case 6: irqout = 6; break;
1093	    case 12: irqout = 7; break;
1094	    default:
1095		printf("sio%d: irq configuration error\n",
1096		       device_get_unit(dev));
1097		bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
1098		device_set_softc(dev, NULL);
1099		free(com, M_DEVBUF);
1100		return (ENXIO);
1101	    }
1102	    outb((iobase & 0x00ff) | tmp, irqout);
1103	}
1104#endif
1105
1106	/*
1107	 * We don't want to get actual interrupts, just masked ones.
1108	 * Interrupts from this line should already be masked in the ICU,
1109	 * but mask them in the processor as well in case there are some
1110	 * (misconfigured) shared interrupts.
1111	 */
1112	mtx_lock_spin(&sio_lock);
1113/* EXTRA DELAY? */
1114
1115	/*
1116	 * Initialize the speed and the word size and wait long enough to
1117	 * drain the maximum of 16 bytes of junk in device output queues.
1118	 * The speed is undefined after a master reset and must be set
1119	 * before relying on anything related to output.  There may be
1120	 * junk after a (very fast) soft reboot and (apparently) after
1121	 * master reset.
1122	 * XXX what about the UART bug avoided by waiting in comparam()?
1123	 * We don't want to to wait long enough to drain at 2 bps.
1124	 */
1125	if (iobase == siocniobase)
1126		DELAY((16 + 1) * 1000000 / (comdefaultrate / 10));
1127	else {
1128		sio_setreg(com, com_cfcr, CFCR_DLAB | CFCR_8BITS);
1129		divisor = siodivisor(rclk, SIO_TEST_SPEED);
1130		sio_setreg(com, com_dlbl, divisor & 0xff);
1131		sio_setreg(com, com_dlbh, divisor >> 8);
1132		sio_setreg(com, com_cfcr, CFCR_8BITS);
1133		DELAY((16 + 1) * 1000000 / (SIO_TEST_SPEED / 10));
1134	}
1135
1136	/*
1137	 * Enable the interrupt gate and disable device interupts.  This
1138	 * should leave the device driving the interrupt line low and
1139	 * guarantee an edge trigger if an interrupt can be generated.
1140	 */
1141/* EXTRA DELAY? */
1142	sio_setreg(com, com_mcr, mcr_image);
1143	sio_setreg(com, com_ier, 0);
1144	DELAY(1000);		/* XXX */
1145	irqmap[0] = isa_irq_pending();
1146
1147	/*
1148	 * Attempt to set loopback mode so that we can send a null byte
1149	 * without annoying any external device.
1150	 */
1151/* EXTRA DELAY? */
1152	sio_setreg(com, com_mcr, mcr_image | MCR_LOOPBACK);
1153
1154	/*
1155	 * Attempt to generate an output interrupt.  On 8250's, setting
1156	 * IER_ETXRDY generates an interrupt independent of the current
1157	 * setting and independent of whether the THR is empty.  On 16450's,
1158	 * setting IER_ETXRDY generates an interrupt independent of the
1159	 * current setting.  On 16550A's, setting IER_ETXRDY only
1160	 * generates an interrupt when IER_ETXRDY is not already set.
1161	 */
1162	sio_setreg(com, com_ier, IER_ETXRDY);
1163#ifdef PC98
1164        if (iod.if_type == COM_IF_RSA98III)
1165		outb(iobase + rsa_ier, 0x04);
1166#endif
1167
1168	/*
1169	 * On some 16x50 incompatibles, setting IER_ETXRDY doesn't generate
1170	 * an interrupt.  They'd better generate one for actually doing
1171	 * output.  Loopback may be broken on the same incompatibles but
1172	 * it's unlikely to do more than allow the null byte out.
1173	 */
1174	sio_setreg(com, com_data, 0);
1175	DELAY((1 + 2) * 1000000 / (SIO_TEST_SPEED / 10));
1176
1177	/*
1178	 * Turn off loopback mode so that the interrupt gate works again
1179	 * (MCR_IENABLE was hidden).  This should leave the device driving
1180	 * an interrupt line high.  It doesn't matter if the interrupt
1181	 * line oscillates while we are not looking at it, since interrupts
1182	 * are disabled.
1183	 */
1184/* EXTRA DELAY? */
1185	sio_setreg(com, com_mcr, mcr_image);
1186
1187	/*
1188	 * It seems my Xircom CBEM56G Cardbus modem wants to be reset
1189	 * to 8 bits *again*, or else probe test 0 will fail.
1190	 * gwk@sgi.com, 4/19/2001
1191	 */
1192	sio_setreg(com, com_cfcr, CFCR_8BITS);
1193
1194	/*
1195	 * Some pcmcia cards have the "TXRDY bug", so we check everyone
1196	 * for IIR_TXRDY implementation ( Palido 321s, DC-1S... )
1197	 */
1198	if (noprobe) {
1199		/* Reading IIR register twice */
1200		for (fn = 0; fn < 2; fn ++) {
1201			DELAY(10000);
1202			failures[6] = sio_getreg(com, com_iir);
1203		}
1204		/* Check IIR_TXRDY clear ? */
1205		result = 0;
1206		if (failures[6] & IIR_TXRDY) {
1207			/* No, Double check with clearing IER */
1208			sio_setreg(com, com_ier, 0);
1209			if (sio_getreg(com, com_iir) & IIR_NOPEND) {
1210				/* Ok. We discovered TXRDY bug! */
1211				SET_FLAG(dev, COM_C_IIR_TXRDYBUG);
1212			} else {
1213				/* Unknown, Just omit this chip.. XXX */
1214				result = ENXIO;
1215				sio_setreg(com, com_mcr, 0);
1216			}
1217		} else {
1218			/* OK. this is well-known guys */
1219			CLR_FLAG(dev, COM_C_IIR_TXRDYBUG);
1220		}
1221		sio_setreg(com, com_ier, 0);
1222		sio_setreg(com, com_cfcr, CFCR_8BITS);
1223		mtx_unlock_spin(&sio_lock);
1224		bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
1225		if (iobase == siocniobase)
1226			result = 0;
1227		if (result != 0) {
1228			device_set_softc(dev, NULL);
1229			free(com, M_DEVBUF);
1230		}
1231		return (result);
1232	}
1233
1234	/*
1235	 * Check that
1236	 *	o the CFCR, IER and MCR in UART hold the values written to them
1237	 *	  (the values happen to be all distinct - this is good for
1238	 *	  avoiding false positive tests from bus echoes).
1239	 *	o an output interrupt is generated and its vector is correct.
1240	 *	o the interrupt goes away when the IIR in the UART is read.
1241	 */
1242/* EXTRA DELAY? */
1243	failures[0] = sio_getreg(com, com_cfcr) - CFCR_8BITS;
1244	failures[1] = sio_getreg(com, com_ier) - IER_ETXRDY;
1245	failures[2] = sio_getreg(com, com_mcr) - mcr_image;
1246	DELAY(10000);		/* Some internal modems need this time */
1247	irqmap[1] = isa_irq_pending();
1248	failures[4] = (sio_getreg(com, com_iir) & IIR_IMASK) - IIR_TXRDY;
1249#ifdef PC98
1250        if (iod.if_type == COM_IF_RSA98III)
1251		inb(iobase + rsa_srr);
1252#endif
1253	DELAY(1000);		/* XXX */
1254	irqmap[2] = isa_irq_pending();
1255	failures[6] = (sio_getreg(com, com_iir) & IIR_IMASK) - IIR_NOPEND;
1256#ifdef PC98
1257        if (iod.if_type == COM_IF_RSA98III)
1258		inb(iobase + rsa_srr);
1259#endif
1260
1261	/*
1262	 * Turn off all device interrupts and check that they go off properly.
1263	 * Leave MCR_IENABLE alone.  For ports without a master port, it gates
1264	 * the OUT2 output of the UART to
1265	 * the ICU input.  Closing the gate would give a floating ICU input
1266	 * (unless there is another device driving it) and spurious interrupts.
1267	 * (On the system that this was first tested on, the input floats high
1268	 * and gives a (masked) interrupt as soon as the gate is closed.)
1269	 */
1270	sio_setreg(com, com_ier, 0);
1271	sio_setreg(com, com_cfcr, CFCR_8BITS);	/* dummy to avoid bus echo */
1272	failures[7] = sio_getreg(com, com_ier);
1273#ifdef PC98
1274        if (iod.if_type == COM_IF_RSA98III)
1275		outb(iobase + rsa_ier, 0x00);
1276#endif
1277	DELAY(1000);		/* XXX */
1278	irqmap[3] = isa_irq_pending();
1279	failures[9] = (sio_getreg(com, com_iir) & IIR_IMASK) - IIR_NOPEND;
1280#ifdef PC98
1281        if (iod.if_type == COM_IF_RSA98III) {
1282		inb(iobase + rsa_srr);
1283		outb(iobase + rsa_frr, 0x00);
1284	}
1285#endif
1286
1287	mtx_unlock_spin(&sio_lock);
1288
1289	irqs = irqmap[1] & ~irqmap[0];
1290	if (bus_get_resource(idev, SYS_RES_IRQ, 0, &xirq, NULL) == 0 &&
1291	    ((1 << xirq) & irqs) == 0) {
1292		printf(
1293		"sio%d: configured irq %ld not in bitmap of probed irqs %#x\n",
1294		    device_get_unit(dev), xirq, irqs);
1295		printf(
1296		"sio%d: port may not be enabled\n",
1297		    device_get_unit(dev));
1298	}
1299	if (bootverbose)
1300		printf("sio%d: irq maps: %#x %#x %#x %#x\n",
1301		    device_get_unit(dev),
1302		    irqmap[0], irqmap[1], irqmap[2], irqmap[3]);
1303
1304	result = 0;
1305	for (fn = 0; fn < sizeof failures; ++fn)
1306		if (failures[fn]) {
1307			sio_setreg(com, com_mcr, 0);
1308			result = ENXIO;
1309			if (bootverbose) {
1310				printf("sio%d: probe failed test(s):",
1311				    device_get_unit(dev));
1312				for (fn = 0; fn < sizeof failures; ++fn)
1313					if (failures[fn])
1314						printf(" %d", fn);
1315				printf("\n");
1316			}
1317			break;
1318		}
1319	bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
1320	if (iobase == siocniobase)
1321		result = 0;
1322	if (result != 0) {
1323		device_set_softc(dev, NULL);
1324		free(com, M_DEVBUF);
1325	}
1326	return (result);
1327}
1328
1329#ifdef COM_ESP
1330static int
1331espattach(com, esp_port)
1332	struct com_s		*com;
1333	Port_t			esp_port;
1334{
1335	u_char	dips;
1336	u_char	val;
1337
1338	/*
1339	 * Check the ESP-specific I/O port to see if we're an ESP
1340	 * card.  If not, return failure immediately.
1341	 */
1342	if ((inb(esp_port) & 0xf3) == 0) {
1343		printf(" port 0x%x is not an ESP board?\n", esp_port);
1344		return (0);
1345	}
1346
1347	/*
1348	 * We've got something that claims to be a Hayes ESP card.
1349	 * Let's hope so.
1350	 */
1351
1352	/* Get the dip-switch configuration */
1353#ifdef PC98
1354	outb(esp_port + ESP98_CMD1, ESP_GETDIPS);
1355	dips = inb(esp_port + ESP98_STATUS1);
1356#else
1357	outb(esp_port + ESP_CMD1, ESP_GETDIPS);
1358	dips = inb(esp_port + ESP_STATUS1);
1359#endif
1360
1361	/*
1362	 * Bits 0,1 of dips say which COM port we are.
1363	 */
1364#ifdef PC98
1365	if ((rman_get_start(com->ioportres) & 0xff) ==
1366	    likely_com_ports[dips & 0x03])
1367#else
1368	if (rman_get_start(com->ioportres) == likely_com_ports[dips & 0x03])
1369#endif
1370		printf(" : ESP");
1371	else {
1372		printf(" esp_port has com %d\n", dips & 0x03);
1373		return (0);
1374	}
1375
1376	/*
1377	 * Check for ESP version 2.0 or later:  bits 4,5,6 = 010.
1378	 */
1379#ifdef PC98
1380	outb(esp_port + ESP98_CMD1, ESP_GETTEST);
1381	val = inb(esp_port + ESP98_STATUS1);	/* clear reg 1 */
1382	val = inb(esp_port + ESP98_STATUS2);
1383#else
1384	outb(esp_port + ESP_CMD1, ESP_GETTEST);
1385	val = inb(esp_port + ESP_STATUS1);	/* clear reg 1 */
1386	val = inb(esp_port + ESP_STATUS2);
1387#endif
1388	if ((val & 0x70) < 0x20) {
1389		printf("-old (%o)", val & 0x70);
1390		return (0);
1391	}
1392
1393	/*
1394	 * Check for ability to emulate 16550:  bit 7 == 1
1395	 */
1396	if ((dips & 0x80) == 0) {
1397		printf(" slave");
1398		return (0);
1399	}
1400
1401	/*
1402	 * Okay, we seem to be a Hayes ESP card.  Whee.
1403	 */
1404	com->esp = TRUE;
1405	com->esp_port = esp_port;
1406	return (1);
1407}
1408#endif /* COM_ESP */
1409
1410int
1411sioattach(dev, xrid, rclk)
1412	device_t	dev;
1413	int		xrid;
1414	u_long		rclk;
1415{
1416	struct com_s	*com;
1417#ifdef COM_ESP
1418	Port_t		*espp;
1419#endif
1420	Port_t		iobase;
1421	int		minorbase;
1422	int		unit;
1423	u_int		flags;
1424	int		rid;
1425	struct resource *port;
1426	int		ret;
1427#ifdef PC98
1428	u_char		*obuf;
1429	u_long		obufsize;
1430	int		if_type = GET_IFTYPE(device_get_flags(dev));
1431#endif
1432
1433	rid = xrid;
1434#ifdef PC98
1435	if (IS_8251(if_type)) {
1436		port = bus_alloc_resource(dev, SYS_RES_IOPORT, &rid,
1437					  0, ~0, 1, RF_ACTIVE);
1438	} else if (if_type == COM_IF_MODEM_CARD ||
1439		   if_type == COM_IF_RSA98III ||
1440		   isa_get_vendorid(dev)) {
1441		port = bus_alloc_resource(dev, SYS_RES_IOPORT, &rid, 0, ~0,
1442			  if_16550a_type[if_type & 0x0f].iatsz, RF_ACTIVE);
1443	} else {
1444		port = isa_alloc_resourcev(dev, SYS_RES_IOPORT, &rid,
1445			   if_16550a_type[if_type & 0x0f].iat,
1446			   if_16550a_type[if_type & 0x0f].iatsz, RF_ACTIVE);
1447	}
1448#else
1449	port = bus_alloc_resource(dev, SYS_RES_IOPORT, &rid,
1450				  0, ~0, IO_COMSIZE, RF_ACTIVE);
1451#endif
1452	if (!port)
1453		return (ENXIO);
1454#ifdef PC98
1455	if (!IS_8251(if_type)) {
1456		if (isa_load_resourcev(port,
1457			       if_16550a_type[if_type & 0x0f].iat,
1458			       if_16550a_type[if_type & 0x0f].iatsz) != 0) {
1459			bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
1460			return ENXIO;
1461		}
1462	}
1463#endif
1464
1465	iobase = rman_get_start(port);
1466	unit = device_get_unit(dev);
1467	com = device_get_softc(dev);
1468	flags = device_get_flags(dev);
1469
1470	if (unit >= sio_numunits)
1471		sio_numunits = unit + 1;
1472
1473#ifdef PC98
1474	obufsize = 256;
1475	if (if_type == COM_IF_RSA98III)
1476		obufsize = 2048;
1477	if ((obuf = malloc(obufsize * 2, M_DEVBUF, M_NOWAIT)) == NULL) {
1478		bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
1479		return ENXIO;
1480	}
1481	bzero(obuf, obufsize * 2);
1482#endif
1483
1484	/*
1485	 * sioprobe() has initialized the device registers as follows:
1486	 *	o cfcr = CFCR_8BITS.
1487	 *	  It is most important that CFCR_DLAB is off, so that the
1488	 *	  data port is not hidden when we enable interrupts.
1489	 *	o ier = 0.
1490	 *	  Interrupts are only enabled when the line is open.
1491	 *	o mcr = MCR_IENABLE, or 0 if the port has AST/4 compatible
1492	 *	  interrupt control register or the config specifies no irq.
1493	 *	  Keeping MCR_DTR and MCR_RTS off might stop the external
1494	 *	  device from sending before we are ready.
1495	 */
1496	bzero(com, sizeof *com);
1497	com->unit = unit;
1498	com->ioportres = port;
1499	com->ioportrid = rid;
1500	com->bst = rman_get_bustag(port);
1501	com->bsh = rman_get_bushandle(port);
1502	com->cfcr_image = CFCR_8BITS;
1503	com->dtr_wait = 3 * hz;
1504	com->loses_outints = COM_LOSESOUTINTS(flags) != 0;
1505	com->no_irq = bus_get_resource(dev, SYS_RES_IRQ, 0, NULL, NULL) != 0;
1506	com->tx_fifo_size = 1;
1507#ifdef PC98
1508	com->obufsize = obufsize;
1509	com->obuf1 = obuf;
1510	com->obuf2 = obuf + obufsize;
1511#endif
1512	com->obufs[0].l_head = com->obuf1;
1513	com->obufs[1].l_head = com->obuf2;
1514
1515#ifdef PC98
1516	com->pc98_if_type = if_type;
1517
1518	if (IS_8251(if_type)) {
1519	    pc98_set_ioport(com);
1520
1521	    if (if_type == COM_IF_INTERNAL && pc98_check_8251fifo()) {
1522		com->pc98_8251fifo = 1;
1523		com->pc98_8251fifo_enable = 0;
1524	    }
1525	} else {
1526	    bus_addr_t	*iat = if_16550a_type[if_type & 0x0f].iat;
1527
1528	    com->data_port = iobase + iat[com_data];
1529	    com->int_id_port = iobase + iat[com_iir];
1530	    com->modem_ctl_port = iobase + iat[com_mcr];
1531	    com->mcr_image = inb(com->modem_ctl_port);
1532	    com->line_status_port = iobase + iat[com_lsr];
1533	    com->modem_status_port = iobase + iat[com_msr];
1534	    com->intr_ctl_port = iobase + iat[com_ier];
1535	}
1536#else /* not PC98 */
1537	com->data_port = iobase + com_data;
1538	com->int_id_port = iobase + com_iir;
1539	com->modem_ctl_port = iobase + com_mcr;
1540	com->mcr_image = inb(com->modem_ctl_port);
1541	com->line_status_port = iobase + com_lsr;
1542	com->modem_status_port = iobase + com_msr;
1543	com->intr_ctl_port = iobase + com_ier;
1544#endif
1545
1546#ifdef PC98
1547	if (!IS_8251(if_type) && rclk == 0)
1548		rclk = if_16550a_type[if_type & 0x0f].rclk;
1549#else
1550	if (rclk == 0)
1551		rclk = DEFAULT_RCLK;
1552#endif
1553	com->rclk = rclk;
1554
1555	/*
1556	 * We don't use all the flags from <sys/ttydefaults.h> since they
1557	 * are only relevant for logins.  It's important to have echo off
1558	 * initially so that the line doesn't start blathering before the
1559	 * echo flag can be turned off.
1560	 */
1561	com->it_in.c_iflag = 0;
1562	com->it_in.c_oflag = 0;
1563	com->it_in.c_cflag = TTYDEF_CFLAG;
1564	com->it_in.c_lflag = 0;
1565	if (unit == comconsole) {
1566#ifdef PC98
1567		if (IS_8251(com->pc98_if_type))
1568			DELAY(100000);
1569#endif
1570		com->it_in.c_iflag = TTYDEF_IFLAG;
1571		com->it_in.c_oflag = TTYDEF_OFLAG;
1572		com->it_in.c_cflag = TTYDEF_CFLAG | CLOCAL;
1573		com->it_in.c_lflag = TTYDEF_LFLAG;
1574		com->lt_out.c_cflag = com->lt_in.c_cflag = CLOCAL;
1575		com->lt_out.c_ispeed = com->lt_out.c_ospeed =
1576		com->lt_in.c_ispeed = com->lt_in.c_ospeed =
1577		com->it_in.c_ispeed = com->it_in.c_ospeed = comdefaultrate;
1578	} else
1579		com->it_in.c_ispeed = com->it_in.c_ospeed = TTYDEF_SPEED;
1580	if (siosetwater(com, com->it_in.c_ispeed) != 0) {
1581		mtx_unlock_spin(&sio_lock);
1582		/*
1583		 * Leave i/o resources allocated if this is a `cn'-level
1584		 * console, so that other devices can't snarf them.
1585		 */
1586		if (iobase != siocniobase)
1587			bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
1588		return (ENOMEM);
1589	}
1590	mtx_unlock_spin(&sio_lock);
1591	termioschars(&com->it_in);
1592	com->it_out = com->it_in;
1593
1594	/* attempt to determine UART type */
1595	printf("sio%d: type", unit);
1596
1597
1598#ifndef PC98
1599	if (!COM_ISMULTIPORT(flags) &&
1600	    !COM_IIR_TXRDYBUG(flags) && !COM_NOSCR(flags)) {
1601		u_char	scr;
1602		u_char	scr1;
1603		u_char	scr2;
1604
1605		scr = sio_getreg(com, com_scr);
1606		sio_setreg(com, com_scr, 0xa5);
1607		scr1 = sio_getreg(com, com_scr);
1608		sio_setreg(com, com_scr, 0x5a);
1609		scr2 = sio_getreg(com, com_scr);
1610		sio_setreg(com, com_scr, scr);
1611		if (scr1 != 0xa5 || scr2 != 0x5a) {
1612			printf(" 8250 or not responding");
1613			goto determined_type;
1614		}
1615	}
1616#endif /* !PC98 */
1617#ifdef PC98
1618	if (IS_8251(com->pc98_if_type)) {
1619	    if (com->pc98_8251fifo && !COM_NOFIFO(flags))
1620		com->tx_fifo_size = 16;
1621	    com_int_TxRx_disable( com );
1622	    com_cflag_and_speed_set( com, com->it_in.c_cflag, comdefaultrate );
1623	    com_tiocm_bic( com, TIOCM_DTR|TIOCM_RTS|TIOCM_LE );
1624	    com_send_break_off( com );
1625
1626	    if (com->pc98_if_type == COM_IF_INTERNAL) {
1627		printf(" (internal%s%s)",
1628		       com->pc98_8251fifo ? " fifo" : "",
1629		       PC98SIO_baud_rate_port(com->pc98_if_type) != -1 ?
1630		       " v-fast" : "");
1631	    } else {
1632		printf(" 8251%s", if_8251_type[com->pc98_if_type & 0x0f].name);
1633	    }
1634	} else {
1635#endif /* PC98 */
1636	sio_setreg(com, com_fifo, FIFO_ENABLE | FIFO_RX_HIGH);
1637	DELAY(100);
1638	com->st16650a = 0;
1639	switch (inb(com->int_id_port) & IIR_FIFO_MASK) {
1640	case FIFO_RX_LOW:
1641		printf(" 16450");
1642		break;
1643	case FIFO_RX_MEDL:
1644		printf(" 16450?");
1645		break;
1646	case FIFO_RX_MEDH:
1647		printf(" 16550?");
1648		break;
1649	case FIFO_RX_HIGH:
1650		if (COM_NOFIFO(flags)) {
1651			printf(" 16550A fifo disabled");
1652		} else {
1653			com->hasfifo = TRUE;
1654#ifdef PC98
1655			com->tx_fifo_size = 0;	/* XXX flag conflicts. */
1656			printf(" 16550A");
1657#else
1658			if (COM_ST16650A(flags)) {
1659				com->st16650a = 1;
1660				com->tx_fifo_size = 32;
1661				printf(" ST16650A");
1662			} else {
1663				com->tx_fifo_size = COM_FIFOSIZE(flags);
1664				printf(" 16550A");
1665			}
1666#endif
1667		}
1668#ifdef PC98
1669		if (com->pc98_if_type == COM_IF_RSA98III) {
1670			com->tx_fifo_size = 2048;
1671			com->rsabase = iobase;
1672			outb(com->rsabase + rsa_ier, 0x00);
1673			outb(com->rsabase + rsa_frr, 0x00);
1674		}
1675#endif
1676
1677#ifdef COM_ESP
1678#ifdef PC98
1679		if (com->pc98_if_type == COM_IF_ESP98)
1680#endif
1681		for (espp = likely_esp_ports; *espp != 0; espp++)
1682			if (espattach(com, *espp)) {
1683				com->tx_fifo_size = 1024;
1684				break;
1685			}
1686#endif
1687		if (!com->st16650a) {
1688			if (!com->tx_fifo_size)
1689				com->tx_fifo_size = 16;
1690			else
1691				printf(" lookalike with %d bytes FIFO",
1692				    com->tx_fifo_size);
1693		}
1694
1695		break;
1696	}
1697
1698#ifdef PC98
1699	if (com->pc98_if_type == COM_IF_RSB3000) {
1700	    /* Set RSB-2000/3000 Extended Buffer mode. */
1701	    u_char lcr;
1702	    lcr = sio_getreg(com, com_cfcr);
1703	    sio_setreg(com, com_cfcr, lcr | CFCR_DLAB);
1704	    sio_setreg(com, com_emr, EMR_EXBUFF | EMR_EFMODE);
1705	    sio_setreg(com, com_cfcr, lcr);
1706	}
1707#endif
1708
1709#ifdef COM_ESP
1710	if (com->esp) {
1711		/*
1712		 * Set 16550 compatibility mode.
1713		 * We don't use the ESP_MODE_SCALE bit to increase the
1714		 * fifo trigger levels because we can't handle large
1715		 * bursts of input.
1716		 * XXX flow control should be set in comparam(), not here.
1717		 */
1718#ifdef PC98
1719		outb(com->esp_port + ESP98_CMD1, ESP_SETMODE);
1720		outb(com->esp_port + ESP98_CMD2, ESP_MODE_RTS | ESP_MODE_FIFO);
1721#else
1722		outb(com->esp_port + ESP_CMD1, ESP_SETMODE);
1723		outb(com->esp_port + ESP_CMD2, ESP_MODE_RTS | ESP_MODE_FIFO);
1724#endif
1725
1726		/* Set RTS/CTS flow control. */
1727#ifdef PC98
1728		outb(com->esp_port + ESP98_CMD1, ESP_SETFLOWTYPE);
1729		outb(com->esp_port + ESP98_CMD2, ESP_FLOW_RTS);
1730		outb(com->esp_port + ESP98_CMD2, ESP_FLOW_CTS);
1731#else
1732		outb(com->esp_port + ESP_CMD1, ESP_SETFLOWTYPE);
1733		outb(com->esp_port + ESP_CMD2, ESP_FLOW_RTS);
1734		outb(com->esp_port + ESP_CMD2, ESP_FLOW_CTS);
1735#endif
1736
1737		/* Set flow-control levels. */
1738#ifdef PC98
1739		outb(com->esp_port + ESP98_CMD1, ESP_SETRXFLOW);
1740		outb(com->esp_port + ESP98_CMD2, HIBYTE(768));
1741		outb(com->esp_port + ESP98_CMD2, LOBYTE(768));
1742		outb(com->esp_port + ESP98_CMD2, HIBYTE(512));
1743		outb(com->esp_port + ESP98_CMD2, LOBYTE(512));
1744#else
1745		outb(com->esp_port + ESP_CMD1, ESP_SETRXFLOW);
1746		outb(com->esp_port + ESP_CMD2, HIBYTE(768));
1747		outb(com->esp_port + ESP_CMD2, LOBYTE(768));
1748		outb(com->esp_port + ESP_CMD2, HIBYTE(512));
1749		outb(com->esp_port + ESP_CMD2, LOBYTE(512));
1750#endif
1751
1752#ifdef PC98
1753                /* Set UART clock prescaler. */
1754                outb(com->esp_port + ESP98_CMD1, ESP_SETCLOCK);
1755                outb(com->esp_port + ESP98_CMD2, 2);	/* 4 times */
1756#endif
1757	}
1758#endif /* COM_ESP */
1759	sio_setreg(com, com_fifo, 0);
1760#ifdef PC98
1761	printf("%s", if_16550a_type[com->pc98_if_type & 0x0f].name);
1762#else
1763determined_type: ;
1764#endif
1765
1766#ifdef COM_MULTIPORT
1767	if (COM_ISMULTIPORT(flags)) {
1768		device_t masterdev;
1769
1770		com->multiport = TRUE;
1771		printf(" (multiport");
1772		if (unit == COM_MPMASTER(flags))
1773			printf(" master");
1774		printf(")");
1775		masterdev = devclass_get_device(sio_devclass,
1776		    COM_MPMASTER(flags));
1777		com->no_irq = (masterdev == NULL || bus_get_resource(masterdev,
1778		    SYS_RES_IRQ, 0, NULL, NULL) != 0);
1779	 }
1780#endif /* COM_MULTIPORT */
1781#ifdef PC98
1782	}
1783#endif
1784	if (unit == comconsole)
1785		printf(", console");
1786	if (COM_IIR_TXRDYBUG(flags))
1787		printf(" with a bogus IIR_TXRDY register");
1788	printf("\n");
1789
1790	if (sio_fast_ih == NULL) {
1791		swi_add(&tty_ithd, "tty:sio", siopoll, NULL, SWI_TTY, 0,
1792		    &sio_fast_ih);
1793		swi_add(&clk_ithd, "tty:sio", siopoll, NULL, SWI_TTY, 0,
1794		    &sio_slow_ih);
1795	}
1796	minorbase = UNIT_TO_MINOR(unit);
1797	com->devs[0] = make_dev(&sio_cdevsw, minorbase,
1798	    UID_ROOT, GID_WHEEL, 0600, "ttyd%r", unit);
1799	com->devs[1] = make_dev(&sio_cdevsw, minorbase | CONTROL_INIT_STATE,
1800	    UID_ROOT, GID_WHEEL, 0600, "ttyid%r", unit);
1801	com->devs[2] = make_dev(&sio_cdevsw, minorbase | CONTROL_LOCK_STATE,
1802	    UID_ROOT, GID_WHEEL, 0600, "ttyld%r", unit);
1803	com->devs[3] = make_dev(&sio_cdevsw, minorbase | CALLOUT_MASK,
1804	    UID_UUCP, GID_DIALER, 0660, "cuaa%r", unit);
1805	com->devs[4] = make_dev(&sio_cdevsw,
1806	    minorbase | CALLOUT_MASK | CONTROL_INIT_STATE,
1807	    UID_UUCP, GID_DIALER, 0660, "cuaia%r", unit);
1808	com->devs[5] = make_dev(&sio_cdevsw,
1809	    minorbase | CALLOUT_MASK | CONTROL_LOCK_STATE,
1810	    UID_UUCP, GID_DIALER, 0660, "cuala%r", unit);
1811	for (rid = 0; rid < 6; rid++)
1812		com->devs[rid]->si_drv1 = com;
1813	com->flags = flags;
1814	com->pps.ppscap = PPS_CAPTUREASSERT | PPS_CAPTURECLEAR;
1815
1816	if (COM_PPSCTS(flags))
1817		com->pps_bit = MSR_CTS;
1818	else
1819		com->pps_bit = MSR_DCD;
1820	pps_init(&com->pps);
1821
1822	rid = 0;
1823	com->irqres = bus_alloc_resource(dev, SYS_RES_IRQ, &rid, 0ul, ~0ul, 1,
1824	    RF_ACTIVE);
1825	if (com->irqres) {
1826		ret = BUS_SETUP_INTR(device_get_parent(dev), dev, com->irqres,
1827				     INTR_TYPE_TTY | INTR_FAST,
1828				     siointr, com, &com->cookie);
1829		if (ret) {
1830			ret = BUS_SETUP_INTR(device_get_parent(dev), dev,
1831					     com->irqres, INTR_TYPE_TTY,
1832					     siointr, com, &com->cookie);
1833			if (ret == 0)
1834				device_printf(dev, "unable to activate interrupt in fast mode - using normal mode\n");
1835		}
1836		if (ret)
1837			device_printf(dev, "could not activate interrupt\n");
1838#if defined(DDB) && (defined(BREAK_TO_DEBUGGER) || \
1839    defined(ALT_BREAK_TO_DEBUGGER))
1840		/*
1841		 * Enable interrupts for early break-to-debugger support
1842		 * on the console.
1843		 */
1844		if (ret == 0 && unit == comconsole)
1845			outb(siocniobase + com_ier, IER_ERXRDY | IER_ERLS |
1846			    IER_EMSC);
1847#endif
1848	}
1849
1850	return (0);
1851}
1852
1853static int
1854sioopen(dev, flag, mode, td)
1855	dev_t		dev;
1856	int		flag;
1857	int		mode;
1858	struct thread	*td;
1859{
1860	struct com_s	*com;
1861	int		error;
1862	int		mynor;
1863	int		s;
1864	struct tty	*tp;
1865	int		unit;
1866
1867	mynor = minor(dev);
1868	unit = MINOR_TO_UNIT(mynor);
1869	com = com_addr(unit);
1870	if (com == NULL)
1871		return (ENXIO);
1872	if (com->gone)
1873		return (ENXIO);
1874	if (mynor & CONTROL_MASK)
1875		return (0);
1876	tp = dev->si_tty = com->tp = ttymalloc(com->tp);
1877	s = spltty();
1878	/*
1879	 * We jump to this label after all non-interrupted sleeps to pick
1880	 * up any changes of the device state.
1881	 */
1882open_top:
1883	while (com->state & CS_DTR_OFF) {
1884		error = tsleep(&com->dtr_wait, TTIPRI | PCATCH, "siodtr", 0);
1885		if (com_addr(unit) == NULL)
1886			return (ENXIO);
1887		if (error != 0 || com->gone)
1888			goto out;
1889	}
1890	if (tp->t_state & TS_ISOPEN) {
1891		/*
1892		 * The device is open, so everything has been initialized.
1893		 * Handle conflicts.
1894		 */
1895		if (mynor & CALLOUT_MASK) {
1896			if (!com->active_out) {
1897				error = EBUSY;
1898				goto out;
1899			}
1900		} else {
1901			if (com->active_out) {
1902				if (flag & O_NONBLOCK) {
1903					error = EBUSY;
1904					goto out;
1905				}
1906				error =	tsleep(&com->active_out,
1907					       TTIPRI | PCATCH, "siobi", 0);
1908				if (com_addr(unit) == NULL)
1909					return (ENXIO);
1910				if (error != 0 || com->gone)
1911					goto out;
1912				goto open_top;
1913			}
1914		}
1915		if (tp->t_state & TS_XCLUDE &&
1916		    suser(td)) {
1917			error = EBUSY;
1918			goto out;
1919		}
1920	} else {
1921		/*
1922		 * The device isn't open, so there are no conflicts.
1923		 * Initialize it.  Initialization is done twice in many
1924		 * cases: to preempt sleeping callin opens if we are
1925		 * callout, and to complete a callin open after DCD rises.
1926		 */
1927		tp->t_oproc = comstart;
1928		tp->t_param = comparam;
1929		tp->t_stop = comstop;
1930		tp->t_dev = dev;
1931		tp->t_termios = mynor & CALLOUT_MASK
1932				? com->it_out : com->it_in;
1933#ifdef PC98
1934		if (!IS_8251(com->pc98_if_type))
1935#endif
1936		(void)commctl(com, TIOCM_DTR | TIOCM_RTS, DMSET);
1937		com->poll = com->no_irq;
1938		com->poll_output = com->loses_outints;
1939		++com->wopeners;
1940		error = comparam(tp, &tp->t_termios);
1941		--com->wopeners;
1942		if (error != 0)
1943			goto out;
1944#ifdef PC98
1945		if (IS_8251(com->pc98_if_type)) {
1946			com_tiocm_bis(com, TIOCM_DTR|TIOCM_RTS);
1947			pc98_msrint_start(dev);
1948			if (com->pc98_8251fifo) {
1949			    com->pc98_8251fifo_enable = 1;
1950			    outb(I8251F_fcr, CTRL8251F_ENABLE |
1951				 CTRL8251F_XMT_RST | CTRL8251F_RCV_RST);
1952			}
1953		}
1954#endif
1955		/*
1956		 * XXX we should goto open_top if comparam() slept.
1957		 */
1958		if (com->hasfifo) {
1959			int i;
1960			/*
1961			 * (Re)enable and drain fifos.
1962			 *
1963			 * Certain SMC chips cause problems if the fifos
1964			 * are enabled while input is ready.  Turn off the
1965			 * fifo if necessary to clear the input.  We test
1966			 * the input ready bit after enabling the fifos
1967			 * since we've already enabled them in comparam()
1968			 * and to handle races between enabling and fresh
1969			 * input.
1970			 */
1971			for (i = 0; i < 500; i++) {
1972				sio_setreg(com, com_fifo,
1973					   FIFO_RCV_RST | FIFO_XMT_RST
1974					   | com->fifo_image);
1975#ifdef PC98
1976				if (com->pc98_if_type == COM_IF_RSA98III)
1977					outb(com->rsabase + rsa_frr , 0x00);
1978#endif
1979				/*
1980				 * XXX the delays are for superstitious
1981				 * historical reasons.  It must be less than
1982				 * the character time at the maximum
1983				 * supported speed (87 usec at 115200 bps
1984				 * 8N1).  Otherwise we might loop endlessly
1985				 * if data is streaming in.  We used to use
1986				 * delays of 100.  That usually worked
1987				 * because DELAY(100) used to usually delay
1988				 * for about 85 usec instead of 100.
1989				 */
1990				DELAY(50);
1991#ifdef PC98
1992				if (com->pc98_if_type == COM_IF_RSA98III ?
1993				    !(inb(com->rsabase + rsa_srr) & 0x08) :
1994				    !(inb(com->line_status_port) & LSR_RXRDY))
1995					break;
1996#else
1997				if (!(inb(com->line_status_port) & LSR_RXRDY))
1998					break;
1999#endif
2000				sio_setreg(com, com_fifo, 0);
2001				DELAY(50);
2002				(void) inb(com->data_port);
2003			}
2004			if (i == 500) {
2005				error = EIO;
2006				goto out;
2007			}
2008		}
2009
2010		mtx_lock_spin(&sio_lock);
2011#ifdef PC98
2012		if (IS_8251(com->pc98_if_type)) {
2013		    com_tiocm_bis(com, TIOCM_LE);
2014		    com->pc98_prev_modem_status = pc98_get_modem_status(com);
2015		    com_int_Rx_enable(com);
2016		} else {
2017#endif
2018		(void) inb(com->line_status_port);
2019		(void) inb(com->data_port);
2020		com->prev_modem_status = com->last_modem_status
2021		    = inb(com->modem_status_port);
2022		if (COM_IIR_TXRDYBUG(com->flags)) {
2023			outb(com->intr_ctl_port, IER_ERXRDY | IER_ERLS
2024						| IER_EMSC);
2025		} else {
2026			outb(com->intr_ctl_port, IER_ERXRDY | IER_ETXRDY
2027						| IER_ERLS | IER_EMSC);
2028		}
2029#ifdef PC98
2030		if (com->pc98_if_type == COM_IF_RSA98III) {
2031			outb(com->rsabase + rsa_ier, 0x1d);
2032			outb(com->intr_ctl_port, IER_ERLS | IER_EMSC);
2033		}
2034#endif
2035#ifdef PC98
2036		}
2037#endif
2038		mtx_unlock_spin(&sio_lock);
2039		/*
2040		 * Handle initial DCD.  Callout devices get a fake initial
2041		 * DCD (trapdoor DCD).  If we are callout, then any sleeping
2042		 * callin opens get woken up and resume sleeping on "siobi"
2043		 * instead of "siodcd".
2044		 */
2045		/*
2046		 * XXX `mynor & CALLOUT_MASK' should be
2047		 * `tp->t_cflag & (SOFT_CARRIER | TRAPDOOR_CARRIER) where
2048		 * TRAPDOOR_CARRIER is the default initial state for callout
2049		 * devices and SOFT_CARRIER is like CLOCAL except it hides
2050		 * the true carrier.
2051		 */
2052#ifdef PC98
2053		if ((IS_8251(com->pc98_if_type) &&
2054			(pc98_get_modem_status(com) & TIOCM_CAR)) ||
2055		    (!IS_8251(com->pc98_if_type) &&
2056			(com->prev_modem_status & MSR_DCD)) ||
2057		    mynor & CALLOUT_MASK)
2058			(*linesw[tp->t_line].l_modem)(tp, 1);
2059#else
2060		if (com->prev_modem_status & MSR_DCD || mynor & CALLOUT_MASK)
2061			(*linesw[tp->t_line].l_modem)(tp, 1);
2062#endif
2063	}
2064	/*
2065	 * Wait for DCD if necessary.
2066	 */
2067	if (!(tp->t_state & TS_CARR_ON) && !(mynor & CALLOUT_MASK)
2068	    && !(tp->t_cflag & CLOCAL) && !(flag & O_NONBLOCK)) {
2069		++com->wopeners;
2070		error = tsleep(TSA_CARR_ON(tp), TTIPRI | PCATCH, "siodcd", 0);
2071		if (com_addr(unit) == NULL)
2072			return (ENXIO);
2073		--com->wopeners;
2074		if (error != 0 || com->gone)
2075			goto out;
2076		goto open_top;
2077	}
2078	error =	(*linesw[tp->t_line].l_open)(dev, tp);
2079	disc_optim(tp, &tp->t_termios, com);
2080	if (tp->t_state & TS_ISOPEN && mynor & CALLOUT_MASK)
2081		com->active_out = TRUE;
2082	siosettimeout();
2083out:
2084	splx(s);
2085	if (!(tp->t_state & TS_ISOPEN) && com->wopeners == 0)
2086		comhardclose(com);
2087	return (error);
2088}
2089
2090static int
2091sioclose(dev, flag, mode, td)
2092	dev_t		dev;
2093	int		flag;
2094	int		mode;
2095	struct thread	*td;
2096{
2097	struct com_s	*com;
2098	int		mynor;
2099	int		s;
2100	struct tty	*tp;
2101
2102	mynor = minor(dev);
2103	if (mynor & CONTROL_MASK)
2104		return (0);
2105	com = com_addr(MINOR_TO_UNIT(mynor));
2106	if (com == NULL)
2107		return (ENODEV);
2108	tp = com->tp;
2109	s = spltty();
2110	(*linesw[tp->t_line].l_close)(tp, flag);
2111#ifdef PC98
2112	com->modem_checking = 0;
2113#endif
2114	disc_optim(tp, &tp->t_termios, com);
2115	comstop(tp, FREAD | FWRITE);
2116	comhardclose(com);
2117	ttyclose(tp);
2118	siosettimeout();
2119	splx(s);
2120	if (com->gone) {
2121		printf("sio%d: gone\n", com->unit);
2122		s = spltty();
2123		if (com->ibuf != NULL)
2124			free(com->ibuf, M_DEVBUF);
2125		bzero(tp, sizeof *tp);
2126		splx(s);
2127	}
2128	return (0);
2129}
2130
2131static void
2132comhardclose(com)
2133	struct com_s	*com;
2134{
2135	int		s;
2136	struct tty	*tp;
2137
2138	s = spltty();
2139	com->poll = FALSE;
2140	com->poll_output = FALSE;
2141	com->do_timestamp = FALSE;
2142	com->do_dcd_timestamp = FALSE;
2143	com->pps.ppsparam.mode = 0;
2144#ifdef PC98
2145	if (IS_8251(com->pc98_if_type))
2146		com_send_break_off(com);
2147	else
2148#endif
2149	sio_setreg(com, com_cfcr, com->cfcr_image &= ~CFCR_SBREAK);
2150	tp = com->tp;
2151
2152#if defined(DDB) && (defined(BREAK_TO_DEBUGGER) || \
2153    defined(ALT_BREAK_TO_DEBUGGER))
2154	/*
2155	 * Leave interrupts enabled and don't clear DTR if this is the
2156	 * console. This allows us to detect break-to-debugger events
2157	 * while the console device is closed.
2158	 */
2159	if (com->unit != comconsole)
2160#endif
2161	{
2162#ifdef PC98
2163		int	tmp;
2164		if (IS_8251(com->pc98_if_type))
2165			com_int_TxRx_disable(com);
2166		else
2167			sio_setreg(com, com_ier, 0);
2168		if (com->pc98_if_type == COM_IF_RSA98III)
2169			outb(com->rsabase + rsa_ier, 0x00);
2170		if (IS_8251(com->pc98_if_type))
2171			tmp = pc98_get_modem_status(com) & TIOCM_CAR;
2172		else
2173			tmp = com->prev_modem_status & MSR_DCD;
2174#else
2175		sio_setreg(com, com_ier, 0);
2176#endif
2177		if (tp->t_cflag & HUPCL
2178		    /*
2179		     * XXX we will miss any carrier drop between here and the
2180		     * next open.  Perhaps we should watch DCD even when the
2181		     * port is closed; it is not sufficient to check it at
2182		     * the next open because it might go up and down while
2183		     * we're not watching.
2184		     */
2185		    || (!com->active_out
2186#ifdef PC98
2187			&& !(tmp)
2188#else
2189		        && !(com->prev_modem_status & MSR_DCD)
2190#endif
2191		        && !(com->it_in.c_cflag & CLOCAL))
2192		    || !(tp->t_state & TS_ISOPEN)) {
2193#ifdef PC98
2194			if (IS_8251(com->pc98_if_type))
2195			    com_tiocm_bic(com, TIOCM_DTR|TIOCM_RTS|TIOCM_LE);
2196			else
2197#endif
2198			(void)commctl(com, TIOCM_DTR, DMBIC);
2199			if (com->dtr_wait != 0 && !(com->state & CS_DTR_OFF)) {
2200				timeout(siodtrwakeup, com, com->dtr_wait);
2201				com->state |= CS_DTR_OFF;
2202			}
2203		}
2204#ifdef PC98
2205		else {
2206			if (IS_8251(com->pc98_if_type))
2207				com_tiocm_bic(com, TIOCM_LE);
2208		}
2209#endif
2210	}
2211#ifdef PC98
2212	if (com->pc98_8251fifo)	{
2213	    if (com->pc98_8251fifo_enable)
2214		outb(I8251F_fcr, CTRL8251F_XMT_RST | CTRL8251F_RCV_RST);
2215	    com->pc98_8251fifo_enable = 0;
2216	}
2217#endif
2218	if (com->hasfifo) {
2219		/*
2220		 * Disable fifos so that they are off after controlled
2221		 * reboots.  Some BIOSes fail to detect 16550s when the
2222		 * fifos are enabled.
2223		 */
2224		sio_setreg(com, com_fifo, 0);
2225	}
2226	com->active_out = FALSE;
2227	wakeup(&com->active_out);
2228	wakeup(TSA_CARR_ON(tp));	/* restart any wopeners */
2229	splx(s);
2230}
2231
2232static int
2233sioread(dev, uio, flag)
2234	dev_t		dev;
2235	struct uio	*uio;
2236	int		flag;
2237{
2238	int		mynor;
2239	struct com_s	*com;
2240
2241	mynor = minor(dev);
2242	if (mynor & CONTROL_MASK)
2243		return (ENODEV);
2244	com = com_addr(MINOR_TO_UNIT(mynor));
2245	if (com == NULL || com->gone)
2246		return (ENODEV);
2247	return ((*linesw[com->tp->t_line].l_read)(com->tp, uio, flag));
2248}
2249
2250static int
2251siowrite(dev, uio, flag)
2252	dev_t		dev;
2253	struct uio	*uio;
2254	int		flag;
2255{
2256	int		mynor;
2257	struct com_s	*com;
2258	int		unit;
2259
2260	mynor = minor(dev);
2261	if (mynor & CONTROL_MASK)
2262		return (ENODEV);
2263
2264	unit = MINOR_TO_UNIT(mynor);
2265	com = com_addr(unit);
2266	if (com == NULL || com->gone)
2267		return (ENODEV);
2268	/*
2269	 * (XXX) We disallow virtual consoles if the physical console is
2270	 * a serial port.  This is in case there is a display attached that
2271	 * is not the console.  In that situation we don't need/want the X
2272	 * server taking over the console.
2273	 */
2274	if (constty != NULL && unit == comconsole)
2275		constty = NULL;
2276	return ((*linesw[com->tp->t_line].l_write)(com->tp, uio, flag));
2277}
2278
2279static void
2280siobusycheck(chan)
2281	void	*chan;
2282{
2283	struct com_s	*com;
2284	int		s;
2285
2286	com = (struct com_s *)chan;
2287
2288	/*
2289	 * Clear TS_BUSY if low-level output is complete.
2290	 * spl locking is sufficient because siointr1() does not set CS_BUSY.
2291	 * If siointr1() clears CS_BUSY after we look at it, then we'll get
2292	 * called again.  Reading the line status port outside of siointr1()
2293	 * is safe because CS_BUSY is clear so there are no output interrupts
2294	 * to lose.
2295	 */
2296	s = spltty();
2297	if (com->state & CS_BUSY)
2298		com->extra_state &= ~CSE_BUSYCHECK;	/* False alarm. */
2299#ifdef	PC98
2300	else if ((IS_8251(com->pc98_if_type) &&
2301		  ((com->pc98_8251fifo_enable &&
2302		    (inb(I8251F_lsr) & (STS8251F_TxRDY | STS8251F_TxEMP))
2303		    == (STS8251F_TxRDY | STS8251F_TxEMP)) ||
2304		   (!com->pc98_8251fifo_enable &&
2305		    (inb(com->sts_port) & (STS8251_TxRDY | STS8251_TxEMP))
2306		    == (STS8251_TxRDY | STS8251_TxEMP)))) ||
2307		 ((inb(com->line_status_port) & (LSR_TSRE | LSR_TXRDY))
2308		  == (LSR_TSRE | LSR_TXRDY))) {
2309#else
2310	else if ((inb(com->line_status_port) & (LSR_TSRE | LSR_TXRDY))
2311	    == (LSR_TSRE | LSR_TXRDY)) {
2312#endif
2313		com->tp->t_state &= ~TS_BUSY;
2314		ttwwakeup(com->tp);
2315		com->extra_state &= ~CSE_BUSYCHECK;
2316	} else
2317		timeout(siobusycheck, com, hz / 100);
2318	splx(s);
2319}
2320
2321static u_int
2322siodivisor(rclk, speed)
2323	u_long	rclk;
2324	speed_t	speed;
2325{
2326	long	actual_speed;
2327	u_int	divisor;
2328	int	error;
2329
2330	if (speed == 0 || speed > (ULONG_MAX - 1) / 8)
2331		return (0);
2332	divisor = (rclk / (8UL * speed) + 1) / 2;
2333	if (divisor == 0 || divisor >= 65536)
2334		return (0);
2335	actual_speed = rclk / (16UL * divisor);
2336
2337	/* 10 times error in percent: */
2338	error = ((actual_speed - (long)speed) * 2000 / (long)speed + 1) / 2;
2339
2340	/* 3.0% maximum error tolerance: */
2341	if (error < -30 || error > 30)
2342		return (0);
2343
2344	return (divisor);
2345}
2346
2347static void
2348siodtrwakeup(chan)
2349	void	*chan;
2350{
2351	struct com_s	*com;
2352
2353	com = (struct com_s *)chan;
2354	com->state &= ~CS_DTR_OFF;
2355	wakeup(&com->dtr_wait);
2356}
2357
2358/*
2359 * Call this function with the sio_lock mutex held.  It will return with the
2360 * lock still held.
2361 */
2362static void
2363sioinput(com)
2364	struct com_s	*com;
2365{
2366	u_char		*buf;
2367	int		incc;
2368	u_char		line_status;
2369	int		recv_data;
2370	struct tty	*tp;
2371
2372	buf = com->ibuf;
2373	tp = com->tp;
2374	if (!(tp->t_state & TS_ISOPEN) || !(tp->t_cflag & CREAD)) {
2375		com_events -= (com->iptr - com->ibuf);
2376		com->iptr = com->ibuf;
2377		return;
2378	}
2379	if (tp->t_state & TS_CAN_BYPASS_L_RINT) {
2380		/*
2381		 * Avoid the grotesquely inefficient lineswitch routine
2382		 * (ttyinput) in "raw" mode.  It usually takes about 450
2383		 * instructions (that's without canonical processing or echo!).
2384		 * slinput is reasonably fast (usually 40 instructions plus
2385		 * call overhead).
2386		 */
2387		do {
2388			/*
2389			 * This may look odd, but it is using save-and-enable
2390			 * semantics instead of the save-and-disable semantics
2391			 * that are used everywhere else.
2392			 */
2393			mtx_unlock_spin(&sio_lock);
2394			incc = com->iptr - buf;
2395			if (tp->t_rawq.c_cc + incc > tp->t_ihiwat
2396			    && (com->state & CS_RTS_IFLOW
2397				|| tp->t_iflag & IXOFF)
2398			    && !(tp->t_state & TS_TBLOCK))
2399				ttyblock(tp);
2400			com->delta_error_counts[CE_TTY_BUF_OVERFLOW]
2401				+= b_to_q((char *)buf, incc, &tp->t_rawq);
2402			buf += incc;
2403			tk_nin += incc;
2404			tk_rawcc += incc;
2405			tp->t_rawcc += incc;
2406			ttwakeup(tp);
2407			if (tp->t_state & TS_TTSTOP
2408			    && (tp->t_iflag & IXANY
2409				|| tp->t_cc[VSTART] == tp->t_cc[VSTOP])) {
2410				tp->t_state &= ~TS_TTSTOP;
2411				tp->t_lflag &= ~FLUSHO;
2412				comstart(tp);
2413			}
2414			mtx_lock_spin(&sio_lock);
2415		} while (buf < com->iptr);
2416	} else {
2417		do {
2418			/*
2419			 * This may look odd, but it is using save-and-enable
2420			 * semantics instead of the save-and-disable semantics
2421			 * that are used everywhere else.
2422			 */
2423			mtx_unlock_spin(&sio_lock);
2424			line_status = buf[com->ierroff];
2425			recv_data = *buf++;
2426			if (line_status
2427			    & (LSR_BI | LSR_FE | LSR_OE | LSR_PE)) {
2428				if (line_status & LSR_BI)
2429					recv_data |= TTY_BI;
2430				if (line_status & LSR_FE)
2431					recv_data |= TTY_FE;
2432				if (line_status & LSR_OE)
2433					recv_data |= TTY_OE;
2434				if (line_status & LSR_PE)
2435					recv_data |= TTY_PE;
2436			}
2437			(*linesw[tp->t_line].l_rint)(recv_data, tp);
2438			mtx_lock_spin(&sio_lock);
2439		} while (buf < com->iptr);
2440	}
2441	com_events -= (com->iptr - com->ibuf);
2442	com->iptr = com->ibuf;
2443
2444	/*
2445	 * There is now room for another low-level buffer full of input,
2446	 * so enable RTS if it is now disabled and there is room in the
2447	 * high-level buffer.
2448	 */
2449#ifdef PC98
2450	if (IS_8251(com->pc98_if_type)) {
2451		if ((com->state & CS_RTS_IFLOW) &&
2452		    !(com_tiocm_get(com) & TIOCM_RTS) &&
2453		    !(tp->t_state & TS_TBLOCK))
2454			com_tiocm_bis(com, TIOCM_RTS);
2455	} else {
2456		if ((com->state & CS_RTS_IFLOW) &&
2457		    !(com->mcr_image & MCR_RTS) &&
2458		    !(tp->t_state & TS_TBLOCK))
2459			outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
2460	}
2461#else
2462	if ((com->state & CS_RTS_IFLOW) && !(com->mcr_image & MCR_RTS) &&
2463	    !(tp->t_state & TS_TBLOCK))
2464		outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
2465#endif
2466}
2467
2468static void
2469siointr(arg)
2470	void		*arg;
2471{
2472	struct com_s	*com;
2473#if defined(PC98) && defined(COM_MULTIPORT)
2474	u_char		rsa_buf_status;
2475#endif
2476
2477#ifndef COM_MULTIPORT
2478	com = (struct com_s *)arg;
2479
2480	mtx_lock_spin(&sio_lock);
2481	siointr1(com);
2482	mtx_unlock_spin(&sio_lock);
2483#else /* COM_MULTIPORT */
2484	bool_t		possibly_more_intrs;
2485	int		unit;
2486
2487	/*
2488	 * Loop until there is no activity on any port.  This is necessary
2489	 * to get an interrupt edge more than to avoid another interrupt.
2490	 * If the IRQ signal is just an OR of the IRQ signals from several
2491	 * devices, then the edge from one may be lost because another is
2492	 * on.
2493	 */
2494	mtx_lock_spin(&sio_lock);
2495	do {
2496		possibly_more_intrs = FALSE;
2497		for (unit = 0; unit < sio_numunits; ++unit) {
2498			com = com_addr(unit);
2499			/*
2500			 * XXX COM_LOCK();
2501			 * would it work here, or be counter-productive?
2502			 */
2503#ifdef PC98
2504			if (com != NULL
2505			    && !com->gone
2506			    && IS_8251(com->pc98_if_type)) {
2507				siointr1(com);
2508			} else if (com != NULL
2509			    && !com->gone
2510			    && com->pc98_if_type == COM_IF_RSA98III) {
2511				rsa_buf_status =
2512				    inb(com->rsabase + rsa_srr) & 0xc9;
2513				if ((rsa_buf_status & 0xc8)
2514				    || !(rsa_buf_status & 0x01)) {
2515				    siointr1(com);
2516				    if (rsa_buf_status !=
2517					(inb(com->rsabase + rsa_srr) & 0xc9))
2518					possibly_more_intrs = TRUE;
2519				}
2520			} else
2521#endif
2522			if (com != NULL
2523			    && !com->gone
2524			    && (inb(com->int_id_port) & IIR_IMASK)
2525			       != IIR_NOPEND) {
2526				siointr1(com);
2527				possibly_more_intrs = TRUE;
2528			}
2529			/* XXX COM_UNLOCK(); */
2530		}
2531	} while (possibly_more_intrs);
2532	mtx_unlock_spin(&sio_lock);
2533#endif /* COM_MULTIPORT */
2534}
2535
2536static struct timespec siots[8192];
2537static int siotso;
2538static int volatile siotsunit = -1;
2539
2540static int
2541sysctl_siots(SYSCTL_HANDLER_ARGS)
2542{
2543	char buf[128];
2544	long long delta;
2545	size_t len;
2546	int error, i;
2547
2548	for (i = 1; i < siotso; i++) {
2549		delta = (long long)(siots[i].tv_sec - siots[i - 1].tv_sec) *
2550		    1000000000 +
2551		    (siots[i].tv_nsec - siots[i - 1].tv_nsec);
2552		len = sprintf(buf, "%lld\n", delta);
2553		if (delta >= 110000)
2554			len += sprintf(buf + len - 1, ": *** %ld.%09ld\n",
2555			    (long)siots[i].tv_sec, siots[i].tv_nsec);
2556		if (i == siotso - 1)
2557			buf[len - 1] = '\0';
2558		error = SYSCTL_OUT(req, buf, len);
2559		if (error != 0)
2560			return (error);
2561		uio_yield();
2562	}
2563	return (0);
2564}
2565
2566SYSCTL_PROC(_machdep, OID_AUTO, siots, CTLTYPE_STRING | CTLFLAG_RD,
2567    0, 0, sysctl_siots, "A", "sio timestamps");
2568
2569static void
2570siointr1(com)
2571	struct com_s	*com;
2572{
2573	u_char	line_status;
2574	u_char	modem_status;
2575	u_char	*ioptr;
2576	u_char	recv_data;
2577	u_char	int_ctl;
2578	u_char	int_ctl_new;
2579
2580#ifdef PC98
2581	u_char	tmp = 0;
2582	u_char	rsa_buf_status = 0;
2583	int	rsa_tx_fifo_size = 0;
2584#endif /* PC98 */
2585
2586	int_ctl = inb(com->intr_ctl_port);
2587	int_ctl_new = int_ctl;
2588
2589	while (!com->gone) {
2590#ifdef PC98
2591status_read:;
2592		if (IS_8251(com->pc98_if_type)) {
2593			if (com->pc98_8251fifo_enable)
2594				tmp = inb(I8251F_lsr);
2595			else
2596				tmp = inb(com->sts_port);
2597more_intr:
2598			line_status = 0;
2599			if (com->pc98_8251fifo_enable) {
2600			    if (tmp & STS8251F_TxRDY) line_status |= LSR_TXRDY;
2601			    if (tmp & STS8251F_RxRDY) line_status |= LSR_RXRDY;
2602			    if (tmp & STS8251F_TxEMP) line_status |= LSR_TSRE;
2603			    if (tmp & STS8251F_PE)    line_status |= LSR_PE;
2604			    if (tmp & STS8251F_OE)    line_status |= LSR_OE;
2605			    if (tmp & STS8251F_BD_SD) line_status |= LSR_BI;
2606			} else {
2607			    if (tmp & STS8251_TxRDY)  line_status |= LSR_TXRDY;
2608			    if (tmp & STS8251_RxRDY)  line_status |= LSR_RXRDY;
2609			    if (tmp & STS8251_TxEMP)  line_status |= LSR_TSRE;
2610			    if (tmp & STS8251_PE)     line_status |= LSR_PE;
2611			    if (tmp & STS8251_OE)     line_status |= LSR_OE;
2612			    if (tmp & STS8251_FE)     line_status |= LSR_FE;
2613			    if (tmp & STS8251_BD_SD)  line_status |= LSR_BI;
2614			}
2615		} else {
2616#endif /* PC98 */
2617		if (com->pps.ppsparam.mode & PPS_CAPTUREBOTH) {
2618			modem_status = inb(com->modem_status_port);
2619		        if ((modem_status ^ com->last_modem_status) &
2620			    com->pps_bit) {
2621				pps_capture(&com->pps);
2622				pps_event(&com->pps,
2623				    (modem_status & com->pps_bit) ?
2624				    PPS_CAPTUREASSERT : PPS_CAPTURECLEAR);
2625			}
2626		}
2627		line_status = inb(com->line_status_port);
2628#ifdef PC98
2629		}
2630		if (com->pc98_if_type == COM_IF_RSA98III)
2631			rsa_buf_status = inb(com->rsabase + rsa_srr);
2632#endif /* PC98 */
2633
2634		/* input event? (check first to help avoid overruns) */
2635#ifndef PC98
2636		while (line_status & LSR_RCV_MASK) {
2637#else
2638		while ((line_status & LSR_RCV_MASK)
2639		       || (com->pc98_if_type == COM_IF_RSA98III
2640			   && (rsa_buf_status & 0x08))) {
2641#endif /* PC98 */
2642			/* break/unnattached error bits or real input? */
2643#ifdef PC98
2644			if (IS_8251(com->pc98_if_type)) {
2645				if (com->pc98_8251fifo_enable) {
2646				    recv_data = inb(I8251F_data);
2647				    if (tmp & (STS8251F_PE | STS8251F_OE |
2648					       STS8251F_BD_SD)) {
2649					pc98_i8251_or_cmd(com, CMD8251_ER);
2650					recv_data = 0;
2651				    }
2652				} else {
2653				    recv_data = inb(com->data_port);
2654				    if (tmp & (STS8251_PE | STS8251_OE |
2655					       STS8251_FE | STS8251_BD_SD)) {
2656					pc98_i8251_or_cmd(com, CMD8251_ER);
2657					recv_data = 0;
2658				    }
2659				}
2660			} else if (com->pc98_if_type == COM_IF_RSA98III) {
2661				if (!(rsa_buf_status & 0x08))
2662					recv_data = 0;
2663				else
2664					recv_data = inb(com->data_port);
2665			} else
2666#endif
2667			if (!(line_status & LSR_RXRDY))
2668				recv_data = 0;
2669			else
2670				recv_data = inb(com->data_port);
2671#ifdef DDB
2672#ifdef ALT_BREAK_TO_DEBUGGER
2673			if (com->unit == comconsole &&
2674			    db_alt_break(recv_data, &com->alt_brk_state) != 0)
2675				breakpoint();
2676#endif /* ALT_BREAK_TO_DEBUGGER */
2677#endif /* DDB */
2678			if (line_status & (LSR_BI | LSR_FE | LSR_PE)) {
2679				/*
2680				 * Don't store BI if IGNBRK or FE/PE if IGNPAR.
2681				 * Otherwise, push the work to a higher level
2682				 * (to handle PARMRK) if we're bypassing.
2683				 * Otherwise, convert BI/FE and PE+INPCK to 0.
2684				 *
2685				 * This makes bypassing work right in the
2686				 * usual "raw" case (IGNBRK set, and IGNPAR
2687				 * and INPCK clear).
2688				 *
2689				 * Note: BI together with FE/PE means just BI.
2690				 */
2691				if (line_status & LSR_BI) {
2692#if defined(DDB) && defined(BREAK_TO_DEBUGGER)
2693					if (com->unit == comconsole) {
2694						breakpoint();
2695						goto cont;
2696					}
2697#endif
2698					if (com->tp == NULL
2699					    || com->tp->t_iflag & IGNBRK)
2700						goto cont;
2701				} else {
2702					if (com->tp == NULL
2703					    || com->tp->t_iflag & IGNPAR)
2704						goto cont;
2705				}
2706				if (com->tp->t_state & TS_CAN_BYPASS_L_RINT
2707				    && (line_status & (LSR_BI | LSR_FE)
2708					|| com->tp->t_iflag & INPCK))
2709					recv_data = 0;
2710			}
2711			++com->bytes_in;
2712			if (com->hotchar != 0 && recv_data == com->hotchar)
2713				swi_sched(sio_fast_ih, 0);
2714			ioptr = com->iptr;
2715			if (ioptr >= com->ibufend)
2716				CE_RECORD(com, CE_INTERRUPT_BUF_OVERFLOW);
2717			else {
2718				if (com->do_timestamp)
2719					microtime(&com->timestamp);
2720				++com_events;
2721				swi_sched(sio_slow_ih, SWI_DELAY);
2722#if 0 /* for testing input latency vs efficiency */
2723if (com->iptr - com->ibuf == 8)
2724	swi_sched(sio_fast_ih, 0);
2725#endif
2726				ioptr[0] = recv_data;
2727				ioptr[com->ierroff] = line_status;
2728				com->iptr = ++ioptr;
2729				if (ioptr == com->ihighwater
2730				    && com->state & CS_RTS_IFLOW)
2731#ifdef PC98
2732					IS_8251(com->pc98_if_type) ?
2733						com_tiocm_bic(com, TIOCM_RTS) :
2734#endif
2735					outb(com->modem_ctl_port,
2736					     com->mcr_image &= ~MCR_RTS);
2737				if (line_status & LSR_OE)
2738					CE_RECORD(com, CE_OVERRUN);
2739			}
2740cont:
2741			/*
2742			 * "& 0x7F" is to avoid the gcc-1.40 generating a slow
2743			 * jump from the top of the loop to here
2744			 */
2745#ifdef PC98
2746			if (IS_8251(com->pc98_if_type))
2747				goto status_read;
2748			else
2749#endif
2750			line_status = inb(com->line_status_port) & 0x7F;
2751#ifdef PC98
2752			if (com->pc98_if_type == COM_IF_RSA98III)
2753				rsa_buf_status = inb(com->rsabase + rsa_srr);
2754#endif /* PC98 */
2755		}
2756
2757		/* modem status change? (always check before doing output) */
2758#ifdef PC98
2759		if (!IS_8251(com->pc98_if_type)) {
2760#endif
2761		modem_status = inb(com->modem_status_port);
2762		if (modem_status != com->last_modem_status) {
2763			if (com->do_dcd_timestamp
2764			    && !(com->last_modem_status & MSR_DCD)
2765			    && modem_status & MSR_DCD)
2766				microtime(&com->dcd_timestamp);
2767
2768			/*
2769			 * Schedule high level to handle DCD changes.  Note
2770			 * that we don't use the delta bits anywhere.  Some
2771			 * UARTs mess them up, and it's easy to remember the
2772			 * previous bits and calculate the delta.
2773			 */
2774			com->last_modem_status = modem_status;
2775			if (!(com->state & CS_CHECKMSR)) {
2776				com_events += LOTS_OF_EVENTS;
2777				com->state |= CS_CHECKMSR;
2778				swi_sched(sio_fast_ih, 0);
2779			}
2780
2781			/* handle CTS change immediately for crisp flow ctl */
2782			if (com->state & CS_CTS_OFLOW) {
2783				if (modem_status & MSR_CTS)
2784					com->state |= CS_ODEVREADY;
2785				else
2786					com->state &= ~CS_ODEVREADY;
2787			}
2788		}
2789#ifdef PC98
2790		}
2791#endif
2792
2793		/* output queued and everything ready? */
2794#ifndef PC98
2795		if (line_status & LSR_TXRDY
2796		    && com->state >= (CS_BUSY | CS_TTGO | CS_ODEVREADY)) {
2797#else
2798		if (((com->pc98_if_type == COM_IF_RSA98III)
2799		     ? (rsa_buf_status & 0x02)
2800		     : (line_status & LSR_TXRDY))
2801		    && com->state >= (CS_BUSY | CS_TTGO | CS_ODEVREADY)) {
2802#endif
2803#ifdef PC98
2804			Port_t	tmp_data_port;
2805
2806			if (IS_8251(com->pc98_if_type) &&
2807			    com->pc98_8251fifo_enable)
2808				tmp_data_port = I8251F_data;
2809			else
2810				tmp_data_port = com->data_port;
2811#endif
2812
2813			ioptr = com->obufq.l_head;
2814			if (com->tx_fifo_size > 1 && com->unit != siotsunit) {
2815				u_int	ocount;
2816
2817				ocount = com->obufq.l_tail - ioptr;
2818#ifdef PC98
2819				if (com->pc98_if_type == COM_IF_RSA98III) {
2820				  rsa_buf_status = inb(com->rsabase + rsa_srr);
2821				  rsa_tx_fifo_size = 1024;
2822				  if (!(rsa_buf_status & 0x01))
2823				      rsa_tx_fifo_size = 2048;
2824				  if (ocount > rsa_tx_fifo_size)
2825				      ocount = rsa_tx_fifo_size;
2826				} else
2827#endif
2828				if (ocount > com->tx_fifo_size)
2829					ocount = com->tx_fifo_size;
2830				com->bytes_out += ocount;
2831				do
2832#ifdef PC98
2833					outb(tmp_data_port, *ioptr++);
2834#else
2835					outb(com->data_port, *ioptr++);
2836#endif
2837				while (--ocount != 0);
2838			} else {
2839#ifdef PC98
2840				outb(tmp_data_port, *ioptr++);
2841#else
2842				outb(com->data_port, *ioptr++);
2843#endif
2844				++com->bytes_out;
2845				if (com->unit == siotsunit) {
2846					nanouptime(&siots[siotso]);
2847					siotso = (siotso + 1) %
2848					    (sizeof siots / sizeof siots[0]);
2849				}
2850			}
2851#ifdef PC98
2852			if (IS_8251(com->pc98_if_type))
2853			    if (!(pc98_check_i8251_interrupt(com) & IEN_TxFLAG))
2854				com_int_Tx_enable(com);
2855#endif
2856			com->obufq.l_head = ioptr;
2857			if (COM_IIR_TXRDYBUG(com->flags)) {
2858				int_ctl_new = int_ctl | IER_ETXRDY;
2859			}
2860			if (ioptr >= com->obufq.l_tail) {
2861				struct lbq	*qp;
2862
2863				qp = com->obufq.l_next;
2864				qp->l_queued = FALSE;
2865				qp = qp->l_next;
2866				if (qp != NULL) {
2867					com->obufq.l_head = qp->l_head;
2868					com->obufq.l_tail = qp->l_tail;
2869					com->obufq.l_next = qp;
2870				} else {
2871					/* output just completed */
2872					if (COM_IIR_TXRDYBUG(com->flags)) {
2873						int_ctl_new = int_ctl & ~IER_ETXRDY;
2874					}
2875					com->state &= ~CS_BUSY;
2876#if defined(PC98)
2877					if (IS_8251(com->pc98_if_type) &&
2878					    pc98_check_i8251_interrupt(com) & IEN_TxFLAG)
2879						com_int_Tx_disable(com);
2880#endif
2881				}
2882				if (!(com->state & CS_ODONE)) {
2883					com_events += LOTS_OF_EVENTS;
2884					com->state |= CS_ODONE;
2885					/* handle at high level ASAP */
2886					swi_sched(sio_fast_ih, 0);
2887				}
2888			}
2889			if (COM_IIR_TXRDYBUG(com->flags) && (int_ctl != int_ctl_new)) {
2890#ifdef PC98
2891				if (com->pc98_if_type == COM_IF_RSA98III) {
2892				    int_ctl_new &= ~(IER_ETXRDY | IER_ERXRDY);
2893				    outb(com->intr_ctl_port, int_ctl_new);
2894				    outb(com->rsabase + rsa_ier, 0x1d);
2895				} else
2896#endif
2897				outb(com->intr_ctl_port, int_ctl_new);
2898			}
2899		}
2900#ifdef PC98
2901		else if (line_status & LSR_TXRDY) {
2902		    if (IS_8251(com->pc98_if_type))
2903			if (pc98_check_i8251_interrupt(com) & IEN_TxFLAG)
2904			    com_int_Tx_disable(com);
2905		}
2906		if (IS_8251(com->pc98_if_type)) {
2907		    if (com->pc98_8251fifo_enable) {
2908			if ((tmp = inb(I8251F_lsr)) & STS8251F_RxRDY)
2909			    goto more_intr;
2910		    } else {
2911			if ((tmp = inb(com->sts_port)) & STS8251_RxRDY)
2912			    goto more_intr;
2913		    }
2914		}
2915#endif
2916
2917		/* finished? */
2918#ifndef COM_MULTIPORT
2919#ifdef PC98
2920		if (IS_8251(com->pc98_if_type))
2921			return;
2922#endif
2923		if ((inb(com->int_id_port) & IIR_IMASK) == IIR_NOPEND)
2924#endif /* COM_MULTIPORT */
2925			return;
2926	}
2927}
2928
2929static int
2930sioioctl(dev, cmd, data, flag, td)
2931	dev_t		dev;
2932	u_long		cmd;
2933	caddr_t		data;
2934	int		flag;
2935	struct thread	*td;
2936{
2937	struct com_s	*com;
2938	int		error;
2939	int		mynor;
2940	int		s;
2941	struct tty	*tp;
2942#if defined(COMPAT_43) || defined(COMPAT_SUNOS)
2943	u_long		oldcmd;
2944	struct termios	term;
2945#endif
2946
2947	mynor = minor(dev);
2948	com = com_addr(MINOR_TO_UNIT(mynor));
2949	if (com == NULL || com->gone)
2950		return (ENODEV);
2951	if (mynor & CONTROL_MASK) {
2952		struct termios	*ct;
2953
2954		switch (mynor & CONTROL_MASK) {
2955		case CONTROL_INIT_STATE:
2956			ct = mynor & CALLOUT_MASK ? &com->it_out : &com->it_in;
2957			break;
2958		case CONTROL_LOCK_STATE:
2959			ct = mynor & CALLOUT_MASK ? &com->lt_out : &com->lt_in;
2960			break;
2961		default:
2962			return (ENODEV);	/* /dev/nodev */
2963		}
2964		switch (cmd) {
2965		case TIOCSETA:
2966			error = suser(td);
2967			if (error != 0)
2968				return (error);
2969			*ct = *(struct termios *)data;
2970			return (0);
2971		case TIOCGETA:
2972			*(struct termios *)data = *ct;
2973			return (0);
2974		case TIOCGETD:
2975			*(int *)data = TTYDISC;
2976			return (0);
2977		case TIOCGWINSZ:
2978			bzero(data, sizeof(struct winsize));
2979			return (0);
2980		default:
2981			return (ENOTTY);
2982		}
2983	}
2984	tp = com->tp;
2985#if defined(COMPAT_43) || defined(COMPAT_SUNOS)
2986	term = tp->t_termios;
2987	oldcmd = cmd;
2988	error = ttsetcompat(tp, &cmd, data, &term);
2989	if (error != 0)
2990		return (error);
2991	if (cmd != oldcmd)
2992		data = (caddr_t)&term;
2993#endif
2994	if (cmd == TIOCSETA || cmd == TIOCSETAW || cmd == TIOCSETAF) {
2995		int	cc;
2996		struct termios *dt = (struct termios *)data;
2997		struct termios *lt = mynor & CALLOUT_MASK
2998				     ? &com->lt_out : &com->lt_in;
2999
3000		dt->c_iflag = (tp->t_iflag & lt->c_iflag)
3001			      | (dt->c_iflag & ~lt->c_iflag);
3002		dt->c_oflag = (tp->t_oflag & lt->c_oflag)
3003			      | (dt->c_oflag & ~lt->c_oflag);
3004		dt->c_cflag = (tp->t_cflag & lt->c_cflag)
3005			      | (dt->c_cflag & ~lt->c_cflag);
3006		dt->c_lflag = (tp->t_lflag & lt->c_lflag)
3007			      | (dt->c_lflag & ~lt->c_lflag);
3008		for (cc = 0; cc < NCCS; ++cc)
3009			if (lt->c_cc[cc] != 0)
3010				dt->c_cc[cc] = tp->t_cc[cc];
3011		if (lt->c_ispeed != 0)
3012			dt->c_ispeed = tp->t_ispeed;
3013		if (lt->c_ospeed != 0)
3014			dt->c_ospeed = tp->t_ospeed;
3015	}
3016	error = (*linesw[tp->t_line].l_ioctl)(tp, cmd, data, flag, td);
3017	if (error != ENOIOCTL)
3018		return (error);
3019	s = spltty();
3020	error = ttioctl(tp, cmd, data, flag);
3021	disc_optim(tp, &tp->t_termios, com);
3022	if (error != ENOIOCTL) {
3023		splx(s);
3024		return (error);
3025	}
3026#ifdef PC98
3027	if (IS_8251(com->pc98_if_type)) {
3028	    switch (cmd) {
3029	    case TIOCSBRK:
3030		com_send_break_on(com);
3031		break;
3032	    case TIOCCBRK:
3033		com_send_break_off(com);
3034		break;
3035	    case TIOCSDTR:
3036		com_tiocm_bis(com, TIOCM_DTR | TIOCM_RTS);
3037		break;
3038	    case TIOCCDTR:
3039		com_tiocm_bic(com, TIOCM_DTR);
3040		break;
3041	/*
3042	 * XXX should disallow changing MCR_RTS if CS_RTS_IFLOW is set.  The
3043	 * changes get undone on the next call to comparam().
3044	 */
3045	    case TIOCMSET:
3046		com_tiocm_set(com, *(int *)data);
3047		break;
3048	    case TIOCMBIS:
3049		com_tiocm_bis(com, *(int *)data);
3050		break;
3051	    case TIOCMBIC:
3052		com_tiocm_bic(com, *(int *)data);
3053		break;
3054	    case TIOCMGET:
3055		*(int *)data = com_tiocm_get(com);
3056		break;
3057	    case TIOCMSDTRWAIT:
3058		/* must be root since the wait applies to following logins */
3059		error = suser(td);
3060		if (error != 0) {
3061			splx(s);
3062			return (error);
3063		}
3064		com->dtr_wait = *(int *)data * hz / 100;
3065		break;
3066	    case TIOCMGDTRWAIT:
3067		*(int *)data = com->dtr_wait * 100 / hz;
3068		break;
3069	    case TIOCTIMESTAMP:
3070		com->do_timestamp = TRUE;
3071		*(struct timeval *)data = com->timestamp;
3072		break;
3073	    case TIOCDCDTIMESTAMP:
3074		com->do_dcd_timestamp = TRUE;
3075		*(struct timeval *)data = com->dcd_timestamp;
3076		break;
3077	    default:
3078		splx(s);
3079		error = pps_ioctl(cmd, data, &com->pps);
3080		if (error == ENODEV)
3081			error = ENOTTY;
3082		return (error);
3083	    }
3084	} else {
3085#endif
3086	switch (cmd) {
3087	case TIOCSBRK:
3088		sio_setreg(com, com_cfcr, com->cfcr_image |= CFCR_SBREAK);
3089		break;
3090	case TIOCCBRK:
3091		sio_setreg(com, com_cfcr, com->cfcr_image &= ~CFCR_SBREAK);
3092		break;
3093	case TIOCSDTR:
3094		(void)commctl(com, TIOCM_DTR, DMBIS);
3095		break;
3096	case TIOCCDTR:
3097		(void)commctl(com, TIOCM_DTR, DMBIC);
3098		break;
3099	/*
3100	 * XXX should disallow changing MCR_RTS if CS_RTS_IFLOW is set.  The
3101	 * changes get undone on the next call to comparam().
3102	 */
3103	case TIOCMSET:
3104		(void)commctl(com, *(int *)data, DMSET);
3105		break;
3106	case TIOCMBIS:
3107		(void)commctl(com, *(int *)data, DMBIS);
3108		break;
3109	case TIOCMBIC:
3110		(void)commctl(com, *(int *)data, DMBIC);
3111		break;
3112	case TIOCMGET:
3113		*(int *)data = commctl(com, 0, DMGET);
3114		break;
3115	case TIOCMSDTRWAIT:
3116		/* must be root since the wait applies to following logins */
3117		error = suser(td);
3118		if (error != 0) {
3119			splx(s);
3120			return (error);
3121		}
3122		com->dtr_wait = *(int *)data * hz / 100;
3123		break;
3124	case TIOCMGDTRWAIT:
3125		*(int *)data = com->dtr_wait * 100 / hz;
3126		break;
3127	case TIOCTIMESTAMP:
3128		com->do_timestamp = TRUE;
3129		*(struct timeval *)data = com->timestamp;
3130		break;
3131	case TIOCDCDTIMESTAMP:
3132		com->do_dcd_timestamp = TRUE;
3133		*(struct timeval *)data = com->dcd_timestamp;
3134		break;
3135	default:
3136		splx(s);
3137		error = pps_ioctl(cmd, data, &com->pps);
3138		if (error == ENODEV)
3139			error = ENOTTY;
3140		return (error);
3141	}
3142#ifdef PC98
3143	}
3144#endif
3145	splx(s);
3146	return (0);
3147}
3148
3149/* software interrupt handler for SWI_TTY */
3150static void
3151siopoll(void *dummy)
3152{
3153	int		unit;
3154
3155	if (com_events == 0)
3156		return;
3157repeat:
3158	for (unit = 0; unit < sio_numunits; ++unit) {
3159		struct com_s	*com;
3160		int		incc;
3161		struct tty	*tp;
3162
3163		com = com_addr(unit);
3164		if (com == NULL)
3165			continue;
3166		tp = com->tp;
3167		if (tp == NULL || com->gone) {
3168			/*
3169			 * Discard any events related to never-opened or
3170			 * going-away devices.
3171			 */
3172			mtx_lock_spin(&sio_lock);
3173			incc = com->iptr - com->ibuf;
3174			com->iptr = com->ibuf;
3175			if (com->state & CS_CHECKMSR) {
3176				incc += LOTS_OF_EVENTS;
3177				com->state &= ~CS_CHECKMSR;
3178			}
3179			com_events -= incc;
3180			mtx_unlock_spin(&sio_lock);
3181			continue;
3182		}
3183		if (com->iptr != com->ibuf) {
3184			mtx_lock_spin(&sio_lock);
3185			sioinput(com);
3186			mtx_unlock_spin(&sio_lock);
3187		}
3188		if (com->state & CS_CHECKMSR) {
3189			u_char	delta_modem_status;
3190
3191#ifdef PC98
3192			if (!IS_8251(com->pc98_if_type)) {
3193#endif
3194			mtx_lock_spin(&sio_lock);
3195			delta_modem_status = com->last_modem_status
3196					     ^ com->prev_modem_status;
3197			com->prev_modem_status = com->last_modem_status;
3198			com_events -= LOTS_OF_EVENTS;
3199			com->state &= ~CS_CHECKMSR;
3200			mtx_unlock_spin(&sio_lock);
3201			if (delta_modem_status & MSR_DCD)
3202				(*linesw[tp->t_line].l_modem)
3203					(tp, com->prev_modem_status & MSR_DCD);
3204#ifdef PC98
3205			}
3206#endif
3207		}
3208		if (com->state & CS_ODONE) {
3209			mtx_lock_spin(&sio_lock);
3210			com_events -= LOTS_OF_EVENTS;
3211			com->state &= ~CS_ODONE;
3212			mtx_unlock_spin(&sio_lock);
3213			if (!(com->state & CS_BUSY)
3214			    && !(com->extra_state & CSE_BUSYCHECK)) {
3215				timeout(siobusycheck, com, hz / 100);
3216				com->extra_state |= CSE_BUSYCHECK;
3217			}
3218			(*linesw[tp->t_line].l_start)(tp);
3219		}
3220		if (com_events == 0)
3221			break;
3222	}
3223	if (com_events >= LOTS_OF_EVENTS)
3224		goto repeat;
3225}
3226
3227static int
3228comparam(tp, t)
3229	struct tty	*tp;
3230	struct termios	*t;
3231{
3232	u_int		cfcr;
3233	int		cflag;
3234	struct com_s	*com;
3235	u_int		divisor;
3236	u_char		dlbh;
3237	u_char		dlbl;
3238	int		s;
3239	int		unit;
3240#ifdef PC98
3241	u_char		param = 0;
3242#endif
3243
3244	unit = DEV_TO_UNIT(tp->t_dev);
3245	com = com_addr(unit);
3246	if (com == NULL)
3247		return (ENODEV);
3248
3249#ifdef PC98
3250	cfcr = 0;
3251
3252	if (IS_8251(com->pc98_if_type)) {
3253		if (pc98_ttspeedtab(com, t->c_ospeed, &divisor) != 0)
3254			return (EINVAL);
3255	} else {
3256#endif
3257	/* do historical conversions */
3258	if (t->c_ispeed == 0)
3259		t->c_ispeed = t->c_ospeed;
3260
3261	/* check requested parameters */
3262	if (t->c_ospeed == 0)
3263		divisor = 0;
3264	else {
3265		if (t->c_ispeed != t->c_ospeed)
3266			return (EINVAL);
3267		divisor = siodivisor(com->rclk, t->c_ispeed);
3268		if (divisor == 0)
3269			return (EINVAL);
3270	}
3271#ifdef PC98
3272	}
3273#endif
3274
3275	/* parameters are OK, convert them to the com struct and the device */
3276	s = spltty();
3277#ifdef PC98
3278	if (IS_8251(com->pc98_if_type)) {
3279		if (divisor == 0)
3280			com_tiocm_bic(com, TIOCM_DTR|TIOCM_RTS|TIOCM_LE);
3281		else
3282			com_tiocm_bis(com, TIOCM_DTR|TIOCM_RTS|TIOCM_LE);
3283	} else
3284#endif
3285	if (divisor == 0)
3286		(void)commctl(com, TIOCM_DTR, DMBIC);	/* hang up line */
3287	else
3288		(void)commctl(com, TIOCM_DTR, DMBIS);
3289	cflag = t->c_cflag;
3290#ifdef PC98
3291	if (!IS_8251(com->pc98_if_type)) {
3292#endif
3293	switch (cflag & CSIZE) {
3294	case CS5:
3295		cfcr = CFCR_5BITS;
3296		break;
3297	case CS6:
3298		cfcr = CFCR_6BITS;
3299		break;
3300	case CS7:
3301		cfcr = CFCR_7BITS;
3302		break;
3303	default:
3304		cfcr = CFCR_8BITS;
3305		break;
3306	}
3307	if (cflag & PARENB) {
3308		cfcr |= CFCR_PENAB;
3309		if (!(cflag & PARODD))
3310			cfcr |= CFCR_PEVEN;
3311	}
3312	if (cflag & CSTOPB)
3313		cfcr |= CFCR_STOPB;
3314
3315	if (com->hasfifo && divisor != 0) {
3316		/*
3317		 * Use a fifo trigger level low enough so that the input
3318		 * latency from the fifo is less than about 16 msec and
3319		 * the total latency is less than about 30 msec.  These
3320		 * latencies are reasonable for humans.  Serial comms
3321		 * protocols shouldn't expect anything better since modem
3322		 * latencies are larger.
3323		 *
3324		 * We have to set the FIFO trigger point such that we
3325		 * don't overflow it accidently if a serial interrupt
3326		 * is delayed.  At high speeds, FIFO_RX_HIGH does not
3327		 * leave enough slots free.
3328		 */
3329		com->fifo_image = com->unit == siotsunit ? 0
3330				  : t->c_ospeed <= 4800
3331				  ? FIFO_ENABLE : FIFO_ENABLE | FIFO_RX_MEDH;
3332#ifdef COM_ESP
3333		/*
3334		 * The Hayes ESP card needs the fifo DMA mode bit set
3335		 * in compatibility mode.  If not, it will interrupt
3336		 * for each character received.
3337		 */
3338		if (com->esp)
3339			com->fifo_image |= FIFO_DMA_MODE;
3340#endif
3341		sio_setreg(com, com_fifo, com->fifo_image);
3342	}
3343#ifdef PC98
3344	}
3345#endif
3346
3347	/*
3348	 * This returns with interrupts disabled so that we can complete
3349	 * the speed change atomically.  Keeping interrupts disabled is
3350	 * especially important while com_data is hidden.
3351	 */
3352	(void) siosetwater(com, t->c_ispeed);
3353
3354#ifdef PC98
3355	if (IS_8251(com->pc98_if_type))
3356		com_cflag_and_speed_set(com, cflag, t->c_ospeed);
3357	else {
3358#endif
3359	if (divisor != 0) {
3360		sio_setreg(com, com_cfcr, cfcr | CFCR_DLAB);
3361		/*
3362		 * Only set the divisor registers if they would change,
3363		 * since on some 16550 incompatibles (UMC8669F), setting
3364		 * them while input is arriving them loses sync until
3365		 * data stops arriving.
3366		 */
3367		dlbl = divisor & 0xFF;
3368		if (sio_getreg(com, com_dlbl) != dlbl)
3369			sio_setreg(com, com_dlbl, dlbl);
3370		dlbh = divisor >> 8;
3371		if (sio_getreg(com, com_dlbh) != dlbh)
3372			sio_setreg(com, com_dlbh, dlbh);
3373	}
3374
3375	sio_setreg(com, com_cfcr, com->cfcr_image = cfcr);
3376#ifdef PC98
3377	}
3378#endif
3379
3380	if (!(tp->t_state & TS_TTSTOP))
3381		com->state |= CS_TTGO;
3382
3383	if (cflag & CRTS_IFLOW) {
3384#ifndef PC98
3385		if (com->st16650a) {
3386			sio_setreg(com, com_cfcr, 0xbf);
3387			sio_setreg(com, com_fifo,
3388				   sio_getreg(com, com_fifo) | 0x40);
3389		}
3390#endif
3391		com->state |= CS_RTS_IFLOW;
3392		/*
3393		 * If CS_RTS_IFLOW just changed from off to on, the change
3394		 * needs to be propagated to MCR_RTS.  This isn't urgent,
3395		 * so do it later by calling comstart() instead of repeating
3396		 * a lot of code from comstart() here.
3397		 */
3398	} else if (com->state & CS_RTS_IFLOW) {
3399		com->state &= ~CS_RTS_IFLOW;
3400		/*
3401		 * CS_RTS_IFLOW just changed from on to off.  Force MCR_RTS
3402		 * on here, since comstart() won't do it later.
3403		 */
3404#ifdef PC98
3405		if (IS_8251(com->pc98_if_type))
3406			com_tiocm_bis(com, TIOCM_RTS);
3407		else
3408			outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
3409#else
3410		outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
3411		if (com->st16650a) {
3412			sio_setreg(com, com_cfcr, 0xbf);
3413			sio_setreg(com, com_fifo,
3414				   sio_getreg(com, com_fifo) & ~0x40);
3415		}
3416#endif
3417	}
3418
3419
3420	/*
3421	 * Set up state to handle output flow control.
3422	 * XXX - worth handling MDMBUF (DCD) flow control at the lowest level?
3423	 * Now has 10+ msec latency, while CTS flow has 50- usec latency.
3424	 */
3425	com->state |= CS_ODEVREADY;
3426	com->state &= ~CS_CTS_OFLOW;
3427#ifdef PC98
3428	if (com->pc98_if_type == COM_IF_RSA98III) {
3429		param = inb(com->rsabase + rsa_msr);
3430		outb(com->rsabase + rsa_msr, param & 0x14);
3431	}
3432#endif
3433	if (cflag & CCTS_OFLOW) {
3434		com->state |= CS_CTS_OFLOW;
3435#ifdef PC98
3436		if (IS_8251(com->pc98_if_type)) {
3437			if (!(pc98_get_modem_status(com) & TIOCM_CTS))
3438				com->state &= ~CS_ODEVREADY;
3439		} else {
3440			if (com->pc98_if_type == COM_IF_RSA98III) {
3441				/* Set automatic flow control mode */
3442				outb(com->rsabase + rsa_msr, param | 0x08);
3443			} else
3444#endif
3445		if (!(com->last_modem_status & MSR_CTS))
3446			com->state &= ~CS_ODEVREADY;
3447#ifdef PC98
3448		}
3449#else
3450		if (com->st16650a) {
3451			sio_setreg(com, com_cfcr, 0xbf);
3452			sio_setreg(com, com_fifo,
3453				   sio_getreg(com, com_fifo) | 0x80);
3454		}
3455	} else {
3456		if (com->st16650a) {
3457			sio_setreg(com, com_cfcr, 0xbf);
3458			sio_setreg(com, com_fifo,
3459				   sio_getreg(com, com_fifo) & ~0x80);
3460		}
3461#endif
3462	}
3463
3464#ifdef PC98
3465	if (!IS_8251(com->pc98_if_type))
3466#endif
3467	sio_setreg(com, com_cfcr, com->cfcr_image);
3468
3469	/* XXX shouldn't call functions while intrs are disabled. */
3470	disc_optim(tp, t, com);
3471	/*
3472	 * Recover from fiddling with CS_TTGO.  We used to call siointr1()
3473	 * unconditionally, but that defeated the careful discarding of
3474	 * stale input in sioopen().
3475	 */
3476	if (com->state >= (CS_BUSY | CS_TTGO))
3477		siointr1(com);
3478
3479	mtx_unlock_spin(&sio_lock);
3480	splx(s);
3481	comstart(tp);
3482	if (com->ibufold != NULL) {
3483		free(com->ibufold, M_DEVBUF);
3484		com->ibufold = NULL;
3485	}
3486	return (0);
3487}
3488
3489/*
3490 * This function must be called with the sio_lock mutex released and will
3491 * return with it obtained.
3492 */
3493static int
3494siosetwater(com, speed)
3495	struct com_s	*com;
3496	speed_t		speed;
3497{
3498	int		cp4ticks;
3499	u_char		*ibuf;
3500	int		ibufsize;
3501	struct tty	*tp;
3502
3503	/*
3504	 * Make the buffer size large enough to handle a softtty interrupt
3505	 * latency of about 2 ticks without loss of throughput or data
3506	 * (about 3 ticks if input flow control is not used or not honoured,
3507	 * but a bit less for CS5-CS7 modes).
3508	 */
3509	cp4ticks = speed / 10 / hz * 4;
3510	for (ibufsize = 128; ibufsize < cp4ticks;)
3511		ibufsize <<= 1;
3512#ifdef PC98
3513	if (com->pc98_if_type == COM_IF_RSA98III)
3514		ibufsize = 2048;
3515#endif
3516	if (ibufsize == com->ibufsize) {
3517		mtx_lock_spin(&sio_lock);
3518		return (0);
3519	}
3520
3521	/*
3522	 * Allocate input buffer.  The extra factor of 2 in the size is
3523	 * to allow for an error byte for each input byte.
3524	 */
3525	ibuf = malloc(2 * ibufsize, M_DEVBUF, M_NOWAIT);
3526	if (ibuf == NULL) {
3527		mtx_lock_spin(&sio_lock);
3528		return (ENOMEM);
3529	}
3530
3531	/* Initialize non-critical variables. */
3532	com->ibufold = com->ibuf;
3533	com->ibufsize = ibufsize;
3534	tp = com->tp;
3535	if (tp != NULL) {
3536		tp->t_ififosize = 2 * ibufsize;
3537		tp->t_ispeedwat = (speed_t)-1;
3538		tp->t_ospeedwat = (speed_t)-1;
3539	}
3540
3541	/*
3542	 * Read current input buffer, if any.  Continue with interrupts
3543	 * disabled.
3544	 */
3545	mtx_lock_spin(&sio_lock);
3546	if (com->iptr != com->ibuf)
3547		sioinput(com);
3548
3549	/*-
3550	 * Initialize critical variables, including input buffer watermarks.
3551	 * The external device is asked to stop sending when the buffer
3552	 * exactly reaches high water, or when the high level requests it.
3553	 * The high level is notified immediately (rather than at a later
3554	 * clock tick) when this watermark is reached.
3555	 * The buffer size is chosen so the watermark should almost never
3556	 * be reached.
3557	 * The low watermark is invisibly 0 since the buffer is always
3558	 * emptied all at once.
3559	 */
3560	com->iptr = com->ibuf = ibuf;
3561	com->ibufend = ibuf + ibufsize;
3562	com->ierroff = ibufsize;
3563	com->ihighwater = ibuf + 3 * ibufsize / 4;
3564	return (0);
3565}
3566
3567static void
3568comstart(tp)
3569	struct tty	*tp;
3570{
3571	struct com_s	*com;
3572	int		s;
3573	int		unit;
3574
3575	unit = DEV_TO_UNIT(tp->t_dev);
3576	com = com_addr(unit);
3577	if (com == NULL)
3578		return;
3579	s = spltty();
3580	mtx_lock_spin(&sio_lock);
3581	if (tp->t_state & TS_TTSTOP)
3582		com->state &= ~CS_TTGO;
3583	else
3584		com->state |= CS_TTGO;
3585	if (tp->t_state & TS_TBLOCK) {
3586#ifdef PC98
3587		if (IS_8251(com->pc98_if_type)) {
3588		    if ((com_tiocm_get(com) & TIOCM_RTS) &&
3589			(com->state & CS_RTS_IFLOW))
3590			com_tiocm_bic(com, TIOCM_RTS);
3591		} else {
3592		    if ((com->mcr_image & MCR_RTS) &&
3593			(com->state & CS_RTS_IFLOW))
3594			outb(com->modem_ctl_port, com->mcr_image &= ~MCR_RTS);
3595		}
3596#else
3597		if (com->mcr_image & MCR_RTS && com->state & CS_RTS_IFLOW)
3598			outb(com->modem_ctl_port, com->mcr_image &= ~MCR_RTS);
3599#endif
3600	} else {
3601#ifdef PC98
3602		if (IS_8251(com->pc98_if_type)) {
3603		    if (!(com_tiocm_get(com) & TIOCM_RTS) &&
3604			com->iptr < com->ihighwater &&
3605			com->state & CS_RTS_IFLOW)
3606			com_tiocm_bis(com, TIOCM_RTS);
3607		} else {
3608		    if (!(com->mcr_image & MCR_RTS) &&
3609			com->iptr < com->ihighwater &&
3610			com->state & CS_RTS_IFLOW)
3611			outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
3612		}
3613#else
3614		if (!(com->mcr_image & MCR_RTS) && com->iptr < com->ihighwater
3615		    && com->state & CS_RTS_IFLOW)
3616			outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
3617#endif
3618	}
3619	mtx_unlock_spin(&sio_lock);
3620	if (tp->t_state & (TS_TIMEOUT | TS_TTSTOP)) {
3621		ttwwakeup(tp);
3622		splx(s);
3623		return;
3624	}
3625	if (tp->t_outq.c_cc != 0) {
3626		struct lbq	*qp;
3627		struct lbq	*next;
3628
3629		if (!com->obufs[0].l_queued) {
3630			com->obufs[0].l_tail
3631			    = com->obuf1 + q_to_b(&tp->t_outq, com->obuf1,
3632#ifdef PC98
3633						  com->obufsize);
3634#else
3635						  sizeof com->obuf1);
3636#endif
3637			com->obufs[0].l_next = NULL;
3638			com->obufs[0].l_queued = TRUE;
3639			mtx_lock_spin(&sio_lock);
3640			if (com->state & CS_BUSY) {
3641				qp = com->obufq.l_next;
3642				while ((next = qp->l_next) != NULL)
3643					qp = next;
3644				qp->l_next = &com->obufs[0];
3645			} else {
3646				com->obufq.l_head = com->obufs[0].l_head;
3647				com->obufq.l_tail = com->obufs[0].l_tail;
3648				com->obufq.l_next = &com->obufs[0];
3649				com->state |= CS_BUSY;
3650			}
3651			mtx_unlock_spin(&sio_lock);
3652		}
3653		if (tp->t_outq.c_cc != 0 && !com->obufs[1].l_queued) {
3654			com->obufs[1].l_tail
3655			    = com->obuf2 + q_to_b(&tp->t_outq, com->obuf2,
3656#ifdef PC98
3657						  com->obufsize);
3658#else
3659						  sizeof com->obuf2);
3660#endif
3661			com->obufs[1].l_next = NULL;
3662			com->obufs[1].l_queued = TRUE;
3663			mtx_lock_spin(&sio_lock);
3664			if (com->state & CS_BUSY) {
3665				qp = com->obufq.l_next;
3666				while ((next = qp->l_next) != NULL)
3667					qp = next;
3668				qp->l_next = &com->obufs[1];
3669			} else {
3670				com->obufq.l_head = com->obufs[1].l_head;
3671				com->obufq.l_tail = com->obufs[1].l_tail;
3672				com->obufq.l_next = &com->obufs[1];
3673				com->state |= CS_BUSY;
3674			}
3675			mtx_unlock_spin(&sio_lock);
3676		}
3677		tp->t_state |= TS_BUSY;
3678	}
3679	mtx_lock_spin(&sio_lock);
3680	if (com->state >= (CS_BUSY | CS_TTGO))
3681		siointr1(com);	/* fake interrupt to start output */
3682	mtx_unlock_spin(&sio_lock);
3683	ttwwakeup(tp);
3684	splx(s);
3685}
3686
3687static void
3688comstop(tp, rw)
3689	struct tty	*tp;
3690	int		rw;
3691{
3692	struct com_s	*com;
3693#ifdef PC98
3694	int		rsa98_tmp  = 0;
3695#endif
3696
3697	com = com_addr(DEV_TO_UNIT(tp->t_dev));
3698	if (com == NULL || com->gone)
3699		return;
3700	mtx_lock_spin(&sio_lock);
3701	if (rw & FWRITE) {
3702#ifdef PC98
3703		if (!IS_8251(com->pc98_if_type)) {
3704#endif
3705		if (com->hasfifo)
3706#ifdef COM_ESP
3707		    /* XXX avoid h/w bug. */
3708		    if (!com->esp)
3709#endif
3710			sio_setreg(com, com_fifo,
3711				   FIFO_XMT_RST | com->fifo_image);
3712#ifdef PC98
3713		if (com->pc98_if_type == COM_IF_RSA98III)
3714		    for (rsa98_tmp = 0; rsa98_tmp < 2048; rsa98_tmp++)
3715			sio_setreg(com, com_fifo,
3716				   FIFO_XMT_RST | com->fifo_image);
3717		}
3718#endif
3719		com->obufs[0].l_queued = FALSE;
3720		com->obufs[1].l_queued = FALSE;
3721		if (com->state & CS_ODONE)
3722			com_events -= LOTS_OF_EVENTS;
3723		com->state &= ~(CS_ODONE | CS_BUSY);
3724		com->tp->t_state &= ~TS_BUSY;
3725	}
3726	if (rw & FREAD) {
3727#ifdef PC98
3728		if (!IS_8251(com->pc98_if_type)) {
3729		    if (com->pc98_if_type == COM_IF_RSA98III)
3730			for (rsa98_tmp = 0; rsa98_tmp < 2048; rsa98_tmp++)
3731			    sio_getreg(com, com_data);
3732#endif
3733		if (com->hasfifo)
3734#ifdef COM_ESP
3735		    /* XXX avoid h/w bug. */
3736		    if (!com->esp)
3737#endif
3738			sio_setreg(com, com_fifo,
3739				   FIFO_RCV_RST | com->fifo_image);
3740#ifdef PC98
3741		}
3742#endif
3743		com_events -= (com->iptr - com->ibuf);
3744		com->iptr = com->ibuf;
3745	}
3746	mtx_unlock_spin(&sio_lock);
3747	comstart(tp);
3748}
3749
3750static int
3751commctl(com, bits, how)
3752	struct com_s	*com;
3753	int		bits;
3754	int		how;
3755{
3756	int	mcr;
3757	int	msr;
3758
3759	if (how == DMGET) {
3760		bits = TIOCM_LE;	/* XXX - always enabled while open */
3761		mcr = com->mcr_image;
3762		if (mcr & MCR_DTR)
3763			bits |= TIOCM_DTR;
3764		if (mcr & MCR_RTS)
3765			bits |= TIOCM_RTS;
3766		msr = com->prev_modem_status;
3767		if (msr & MSR_CTS)
3768			bits |= TIOCM_CTS;
3769		if (msr & MSR_DCD)
3770			bits |= TIOCM_CD;
3771		if (msr & MSR_DSR)
3772			bits |= TIOCM_DSR;
3773		/*
3774		 * XXX - MSR_RI is naturally volatile, and we make MSR_TERI
3775		 * more volatile by reading the modem status a lot.  Perhaps
3776		 * we should latch both bits until the status is read here.
3777		 */
3778		if (msr & (MSR_RI | MSR_TERI))
3779			bits |= TIOCM_RI;
3780		return (bits);
3781	}
3782	mcr = 0;
3783	if (bits & TIOCM_DTR)
3784		mcr |= MCR_DTR;
3785	if (bits & TIOCM_RTS)
3786		mcr |= MCR_RTS;
3787	if (com->gone)
3788		return(0);
3789	mtx_lock_spin(&sio_lock);
3790	switch (how) {
3791	case DMSET:
3792		outb(com->modem_ctl_port,
3793		     com->mcr_image = mcr | (com->mcr_image & MCR_IENABLE));
3794		break;
3795	case DMBIS:
3796		outb(com->modem_ctl_port, com->mcr_image |= mcr);
3797		break;
3798	case DMBIC:
3799		outb(com->modem_ctl_port, com->mcr_image &= ~mcr);
3800		break;
3801	}
3802	mtx_unlock_spin(&sio_lock);
3803	return (0);
3804}
3805
3806static void
3807siosettimeout()
3808{
3809	struct com_s	*com;
3810	bool_t		someopen;
3811	int		unit;
3812
3813	/*
3814	 * Set our timeout period to 1 second if no polled devices are open.
3815	 * Otherwise set it to max(1/200, 1/hz).
3816	 * Enable timeouts iff some device is open.
3817	 */
3818	untimeout(comwakeup, (void *)NULL, sio_timeout_handle);
3819	sio_timeout = hz;
3820	someopen = FALSE;
3821	for (unit = 0; unit < sio_numunits; ++unit) {
3822		com = com_addr(unit);
3823		if (com != NULL && com->tp != NULL
3824		    && com->tp->t_state & TS_ISOPEN && !com->gone) {
3825			someopen = TRUE;
3826			if (com->poll || com->poll_output) {
3827				sio_timeout = hz > 200 ? hz / 200 : 1;
3828				break;
3829			}
3830		}
3831	}
3832	if (someopen) {
3833		sio_timeouts_until_log = hz / sio_timeout;
3834		sio_timeout_handle = timeout(comwakeup, (void *)NULL,
3835					     sio_timeout);
3836	} else {
3837		/* Flush error messages, if any. */
3838		sio_timeouts_until_log = 1;
3839		comwakeup((void *)NULL);
3840		untimeout(comwakeup, (void *)NULL, sio_timeout_handle);
3841	}
3842}
3843
3844static void
3845comwakeup(chan)
3846	void	*chan;
3847{
3848	struct com_s	*com;
3849	int		unit;
3850
3851	sio_timeout_handle = timeout(comwakeup, (void *)NULL, sio_timeout);
3852
3853	/*
3854	 * Recover from lost output interrupts.
3855	 * Poll any lines that don't use interrupts.
3856	 */
3857	for (unit = 0; unit < sio_numunits; ++unit) {
3858		com = com_addr(unit);
3859		if (com != NULL && !com->gone
3860		    && (com->state >= (CS_BUSY | CS_TTGO) || com->poll)) {
3861			mtx_lock_spin(&sio_lock);
3862			siointr1(com);
3863			mtx_unlock_spin(&sio_lock);
3864		}
3865	}
3866
3867	/*
3868	 * Check for and log errors, but not too often.
3869	 */
3870	if (--sio_timeouts_until_log > 0)
3871		return;
3872	sio_timeouts_until_log = hz / sio_timeout;
3873	for (unit = 0; unit < sio_numunits; ++unit) {
3874		int	errnum;
3875
3876		com = com_addr(unit);
3877		if (com == NULL)
3878			continue;
3879		if (com->gone)
3880			continue;
3881		for (errnum = 0; errnum < CE_NTYPES; ++errnum) {
3882			u_int	delta;
3883			u_long	total;
3884
3885			mtx_lock_spin(&sio_lock);
3886			delta = com->delta_error_counts[errnum];
3887			com->delta_error_counts[errnum] = 0;
3888			mtx_unlock_spin(&sio_lock);
3889			if (delta == 0)
3890				continue;
3891			total = com->error_counts[errnum] += delta;
3892			log(LOG_ERR, "sio%d: %u more %s%s (total %lu)\n",
3893			    unit, delta, error_desc[errnum],
3894			    delta == 1 ? "" : "s", total);
3895		}
3896	}
3897}
3898
3899#ifdef PC98
3900/* commint is called when modem control line changes */
3901static void
3902commint(dev_t dev)
3903{
3904	register struct tty *tp;
3905	int	stat,delta;
3906	struct com_s *com;
3907	int	mynor,unit;
3908
3909	mynor = minor(dev);
3910	unit = MINOR_TO_UNIT(mynor);
3911	com = com_addr(unit);
3912	tp = com->tp;
3913
3914	stat = com_tiocm_get(com);
3915	delta = com_tiocm_get_delta(com);
3916
3917	if (com->state & CS_CTS_OFLOW) {
3918		if (stat & TIOCM_CTS)
3919			com->state |= CS_ODEVREADY;
3920		else
3921			com->state &= ~CS_ODEVREADY;
3922	}
3923	if ((delta & TIOCM_CAR) && (mynor & CALLOUT_MASK) == 0) {
3924	    if (stat & TIOCM_CAR )
3925		(void)(*linesw[tp->t_line].l_modem)(tp, 1);
3926	    else if ((*linesw[tp->t_line].l_modem)(tp, 0) == 0) {
3927		/* negate DTR, RTS */
3928		com_tiocm_bic(com, (tp->t_cflag & HUPCL) ?
3929				TIOCM_DTR|TIOCM_RTS|TIOCM_LE : TIOCM_LE );
3930		/* disable IENABLE */
3931		com_int_TxRx_disable( com );
3932	    }
3933	}
3934}
3935#endif
3936
3937static void
3938disc_optim(tp, t, com)
3939	struct tty	*tp;
3940	struct termios	*t;
3941	struct com_s	*com;
3942{
3943	if (!(t->c_iflag & (ICRNL | IGNCR | IMAXBEL | INLCR | ISTRIP | IXON))
3944	    && (!(t->c_iflag & BRKINT) || (t->c_iflag & IGNBRK))
3945	    && (!(t->c_iflag & PARMRK)
3946		|| (t->c_iflag & (IGNPAR | IGNBRK)) == (IGNPAR | IGNBRK))
3947	    && !(t->c_lflag & (ECHO | ICANON | IEXTEN | ISIG | PENDIN))
3948	    && linesw[tp->t_line].l_rint == ttyinput)
3949		tp->t_state |= TS_CAN_BYPASS_L_RINT;
3950	else
3951		tp->t_state &= ~TS_CAN_BYPASS_L_RINT;
3952	com->hotchar = linesw[tp->t_line].l_hotchar;
3953}
3954
3955/*
3956 * Following are all routines needed for SIO to act as console
3957 */
3958struct siocnstate {
3959	u_char	dlbl;
3960	u_char	dlbh;
3961	u_char	ier;
3962	u_char	cfcr;
3963	u_char	mcr;
3964};
3965
3966#ifndef __alpha__
3967static speed_t siocngetspeed(Port_t, u_long rclk);
3968#endif
3969static void siocnclose(struct siocnstate *sp, Port_t iobase);
3970static void siocnopen(struct siocnstate *sp, Port_t iobase, int speed);
3971static void siocntxwait(Port_t iobase);
3972
3973#ifdef __alpha__
3974int siocnattach(int port, int speed);
3975int siogdbattach(int port, int speed);
3976int siogdbgetc(void);
3977void siogdbputc(int c);
3978#else
3979static cn_probe_t siocnprobe;
3980static cn_init_t siocninit;
3981static cn_term_t siocnterm;
3982#endif
3983static cn_checkc_t siocncheckc;
3984static cn_getc_t siocngetc;
3985static cn_putc_t siocnputc;
3986
3987#ifndef __alpha__
3988CONS_DRIVER(sio, siocnprobe, siocninit, siocnterm, siocngetc, siocncheckc,
3989	    siocnputc, NULL);
3990#endif
3991
3992#if DDB > 0
3993static struct consdev gdbconsdev;
3994#endif
3995
3996static void
3997siocntxwait(iobase)
3998	Port_t	iobase;
3999{
4000	int	timo;
4001
4002	/*
4003	 * Wait for any pending transmission to finish.  Required to avoid
4004	 * the UART lockup bug when the speed is changed, and for normal
4005	 * transmits.
4006	 */
4007	timo = 100000;
4008	while ((inb(iobase + com_lsr) & (LSR_TSRE | LSR_TXRDY))
4009	       != (LSR_TSRE | LSR_TXRDY) && --timo != 0)
4010		;
4011}
4012
4013#ifndef __alpha__
4014
4015/*
4016 * Read the serial port specified and try to figure out what speed
4017 * it's currently running at.  We're assuming the serial port has
4018 * been initialized and is basicly idle.  This routine is only intended
4019 * to be run at system startup.
4020 *
4021 * If the value read from the serial port doesn't make sense, return 0.
4022 */
4023
4024static speed_t
4025siocngetspeed(iobase, rclk)
4026	Port_t	iobase;
4027	u_long	rclk;
4028{
4029	u_int	divisor;
4030	u_char	dlbh;
4031	u_char	dlbl;
4032	u_char  cfcr;
4033
4034	cfcr = inb(iobase + com_cfcr);
4035	outb(iobase + com_cfcr, CFCR_DLAB | cfcr);
4036
4037	dlbl = inb(iobase + com_dlbl);
4038	dlbh = inb(iobase + com_dlbh);
4039
4040	outb(iobase + com_cfcr, cfcr);
4041
4042	divisor = dlbh << 8 | dlbl;
4043
4044	/* XXX there should be more sanity checking. */
4045	if (divisor == 0)
4046		return (CONSPEED);
4047	return (rclk / (16UL * divisor));
4048}
4049
4050#endif
4051
4052static void
4053siocnopen(sp, iobase, speed)
4054	struct siocnstate	*sp;
4055	Port_t			iobase;
4056	int			speed;
4057{
4058	u_int	divisor;
4059	u_char	dlbh;
4060	u_char	dlbl;
4061
4062	/*
4063	 * Save all the device control registers except the fifo register
4064	 * and set our default ones (cs8 -parenb speed=comdefaultrate).
4065	 * We can't save the fifo register since it is read-only.
4066	 */
4067	sp->ier = inb(iobase + com_ier);
4068	outb(iobase + com_ier, 0);	/* spltty() doesn't stop siointr() */
4069	siocntxwait(iobase);
4070	sp->cfcr = inb(iobase + com_cfcr);
4071	outb(iobase + com_cfcr, CFCR_DLAB | CFCR_8BITS);
4072	sp->dlbl = inb(iobase + com_dlbl);
4073	sp->dlbh = inb(iobase + com_dlbh);
4074	/*
4075	 * Only set the divisor registers if they would change, since on
4076	 * some 16550 incompatibles (Startech), setting them clears the
4077	 * data input register.  This also reduces the effects of the
4078	 * UMC8669F bug.
4079	 */
4080	divisor = siodivisor(comdefaultrclk, speed);
4081	dlbl = divisor & 0xFF;
4082	if (sp->dlbl != dlbl)
4083		outb(iobase + com_dlbl, dlbl);
4084	dlbh = divisor >> 8;
4085	if (sp->dlbh != dlbh)
4086		outb(iobase + com_dlbh, dlbh);
4087	outb(iobase + com_cfcr, CFCR_8BITS);
4088	sp->mcr = inb(iobase + com_mcr);
4089	/*
4090	 * We don't want interrupts, but must be careful not to "disable"
4091	 * them by clearing the MCR_IENABLE bit, since that might cause
4092	 * an interrupt by floating the IRQ line.
4093	 */
4094	outb(iobase + com_mcr, (sp->mcr & MCR_IENABLE) | MCR_DTR | MCR_RTS);
4095}
4096
4097static void
4098siocnclose(sp, iobase)
4099	struct siocnstate	*sp;
4100	Port_t			iobase;
4101{
4102	/*
4103	 * Restore the device control registers.
4104	 */
4105	siocntxwait(iobase);
4106	outb(iobase + com_cfcr, CFCR_DLAB | CFCR_8BITS);
4107	if (sp->dlbl != inb(iobase + com_dlbl))
4108		outb(iobase + com_dlbl, sp->dlbl);
4109	if (sp->dlbh != inb(iobase + com_dlbh))
4110		outb(iobase + com_dlbh, sp->dlbh);
4111	outb(iobase + com_cfcr, sp->cfcr);
4112	/*
4113	 * XXX damp oscillations of MCR_DTR and MCR_RTS by not restoring them.
4114	 */
4115	outb(iobase + com_mcr, sp->mcr | MCR_DTR | MCR_RTS);
4116	outb(iobase + com_ier, sp->ier);
4117}
4118
4119#ifndef __alpha__
4120
4121static void
4122siocnprobe(cp)
4123	struct consdev	*cp;
4124{
4125	speed_t			boot_speed;
4126	u_char			cfcr;
4127	u_int			divisor;
4128	int			s, unit;
4129	struct siocnstate	sp;
4130
4131	/*
4132	 * Find our first enabled console, if any.  If it is a high-level
4133	 * console device, then initialize it and return successfully.
4134	 * If it is a low-level console device, then initialize it and
4135	 * return unsuccessfully.  It must be initialized in both cases
4136	 * for early use by console drivers and debuggers.  Initializing
4137	 * the hardware is not necessary in all cases, since the i/o
4138	 * routines initialize it on the fly, but it is necessary if
4139	 * input might arrive while the hardware is switched back to an
4140	 * uninitialized state.  We can't handle multiple console devices
4141	 * yet because our low-level routines don't take a device arg.
4142	 * We trust the user to set the console flags properly so that we
4143	 * don't need to probe.
4144	 */
4145	cp->cn_pri = CN_DEAD;
4146
4147	for (unit = 0; unit < 16; unit++) { /* XXX need to know how many */
4148		int flags;
4149		if (resource_disabled("sio", unit))
4150			continue;
4151		if (resource_int_value("sio", unit, "flags", &flags))
4152			continue;
4153		if (COM_CONSOLE(flags) || COM_DEBUGGER(flags)) {
4154			int port;
4155			Port_t iobase;
4156
4157			if (resource_int_value("sio", unit, "port", &port))
4158				continue;
4159			iobase = port;
4160			s = spltty();
4161			if (boothowto & RB_SERIAL) {
4162				boot_speed =
4163				    siocngetspeed(iobase, comdefaultrclk);
4164				if (boot_speed)
4165					comdefaultrate = boot_speed;
4166			}
4167
4168			/*
4169			 * Initialize the divisor latch.  We can't rely on
4170			 * siocnopen() to do this the first time, since it
4171			 * avoids writing to the latch if the latch appears
4172			 * to have the correct value.  Also, if we didn't
4173			 * just read the speed from the hardware, then we
4174			 * need to set the speed in hardware so that
4175			 * switching it later is null.
4176			 */
4177			cfcr = inb(iobase + com_cfcr);
4178			outb(iobase + com_cfcr, CFCR_DLAB | cfcr);
4179			divisor = siodivisor(comdefaultrclk, comdefaultrate);
4180			outb(iobase + com_dlbl, divisor & 0xff);
4181			outb(iobase + com_dlbh, divisor >> 8);
4182			outb(iobase + com_cfcr, cfcr);
4183
4184			siocnopen(&sp, iobase, comdefaultrate);
4185
4186			splx(s);
4187			if (COM_CONSOLE(flags) && !COM_LLCONSOLE(flags)) {
4188				cp->cn_dev = makedev(CDEV_MAJOR, unit);
4189				cp->cn_pri = COM_FORCECONSOLE(flags)
4190					     || boothowto & RB_SERIAL
4191					     ? CN_REMOTE : CN_NORMAL;
4192				siocniobase = iobase;
4193				siocnunit = unit;
4194			}
4195			if (COM_DEBUGGER(flags)) {
4196				printf("sio%d: gdb debugging port\n", unit);
4197				siogdbiobase = iobase;
4198				siogdbunit = unit;
4199#if DDB > 0
4200				gdbconsdev.cn_dev = makedev(CDEV_MAJOR, unit);
4201				gdb_arg = &gdbconsdev;
4202				gdb_getc = siocngetc;
4203				gdb_putc = siocnputc;
4204#endif
4205			}
4206		}
4207	}
4208#ifdef	__i386__
4209#if DDB > 0
4210	/*
4211	 * XXX Ugly Compatability.
4212	 * If no gdb port has been specified, set it to be the console
4213	 * as some configuration files don't specify the gdb port.
4214	 */
4215	if (gdb_arg == NULL && (boothowto & RB_GDB)) {
4216		printf("Warning: no GDB port specified. Defaulting to sio%d.\n",
4217			siocnunit);
4218		printf("Set flag 0x80 on desired GDB port in your\n");
4219		printf("configuration file (currently sio only).\n");
4220		siogdbiobase = siocniobase;
4221		siogdbunit = siocnunit;
4222		gdbconsdev.cn_dev = makedev(CDEV_MAJOR, siocnunit);
4223		gdb_arg = &gdbconsdev;
4224		gdb_getc = siocngetc;
4225		gdb_putc = siocnputc;
4226	}
4227#endif
4228#endif
4229}
4230
4231static void
4232siocninit(cp)
4233	struct consdev	*cp;
4234{
4235	comconsole = DEV_TO_UNIT(cp->cn_dev);
4236}
4237
4238static void
4239siocnterm(cp)
4240	struct consdev	*cp;
4241{
4242	comconsole = -1;
4243}
4244
4245#endif
4246
4247#ifdef __alpha__
4248
4249CONS_DRIVER(sio, NULL, NULL, NULL, siocngetc, siocncheckc, siocnputc, NULL);
4250
4251int
4252siocnattach(port, speed)
4253	int port;
4254	int speed;
4255{
4256	int			s;
4257	u_char			cfcr;
4258	u_int			divisor;
4259	struct siocnstate	sp;
4260	int			unit = 0;	/* XXX random value! */
4261
4262	siocniobase = port;
4263	siocnunit = unit;
4264	comdefaultrate = speed;
4265	sio_consdev.cn_pri = CN_NORMAL;
4266	sio_consdev.cn_dev = makedev(CDEV_MAJOR, unit);
4267
4268	s = spltty();
4269
4270	/*
4271	 * Initialize the divisor latch.  We can't rely on
4272	 * siocnopen() to do this the first time, since it
4273	 * avoids writing to the latch if the latch appears
4274	 * to have the correct value.  Also, if we didn't
4275	 * just read the speed from the hardware, then we
4276	 * need to set the speed in hardware so that
4277	 * switching it later is null.
4278	 */
4279	cfcr = inb(siocniobase + com_cfcr);
4280	outb(siocniobase + com_cfcr, CFCR_DLAB | cfcr);
4281	divisor = siodivisor(comdefaultrclk, comdefaultrate);
4282	outb(siocniobase + com_dlbl, divisor & 0xff);
4283	outb(siocniobase + com_dlbh, divisor >> 8);
4284	outb(siocniobase + com_cfcr, cfcr);
4285
4286	siocnopen(&sp, siocniobase, comdefaultrate);
4287	splx(s);
4288
4289	cnadd(&sio_consdev);
4290	return (0);
4291}
4292
4293int
4294siogdbattach(port, speed)
4295	int port;
4296	int speed;
4297{
4298	int			s;
4299	u_char			cfcr;
4300	u_int			divisor;
4301	struct siocnstate	sp;
4302	int			unit = 1;	/* XXX random value! */
4303
4304	siogdbiobase = port;
4305	gdbdefaultrate = speed;
4306
4307	printf("sio%d: gdb debugging port\n", unit);
4308	siogdbunit = unit;
4309#if DDB > 0
4310	gdbconsdev.cn_dev = makedev(CDEV_MAJOR, unit);
4311	gdb_arg = &gdbconsdev;
4312	gdb_getc = siocngetc;
4313	gdb_putc = siocnputc;
4314#endif
4315
4316	s = spltty();
4317
4318	/*
4319	 * Initialize the divisor latch.  We can't rely on
4320	 * siocnopen() to do this the first time, since it
4321	 * avoids writing to the latch if the latch appears
4322	 * to have the correct value.  Also, if we didn't
4323	 * just read the speed from the hardware, then we
4324	 * need to set the speed in hardware so that
4325	 * switching it later is null.
4326	 */
4327	cfcr = inb(siogdbiobase + com_cfcr);
4328	outb(siogdbiobase + com_cfcr, CFCR_DLAB | cfcr);
4329	divisor = siodivisor(comdefaultrclk, gdbdefaultrate);
4330	outb(siogdbiobase + com_dlbl, divisor & 0xff);
4331	outb(siogdbiobase + com_dlbh, divisor >> 8);
4332	outb(siogdbiobase + com_cfcr, cfcr);
4333
4334	siocnopen(&sp, siogdbiobase, gdbdefaultrate);
4335	splx(s);
4336
4337	return (0);
4338}
4339
4340#endif
4341
4342static int
4343siocncheckc(struct consdev *cd)
4344{
4345	int	c;
4346	dev_t	dev;
4347	Port_t	iobase;
4348	int	s;
4349	struct siocnstate	sp;
4350	speed_t	speed;
4351
4352	dev = cd->cn_dev;
4353	if (minor(dev) == siocnunit) {
4354		iobase = siocniobase;
4355		speed = comdefaultrate;
4356	} else {
4357		iobase = siogdbiobase;
4358		speed = gdbdefaultrate;
4359	}
4360	s = spltty();
4361	siocnopen(&sp, iobase, speed);
4362	if (inb(iobase + com_lsr) & LSR_RXRDY)
4363		c = inb(iobase + com_data);
4364	else
4365		c = -1;
4366	siocnclose(&sp, iobase);
4367	splx(s);
4368	return (c);
4369}
4370
4371
4372static int
4373siocngetc(struct consdev *cd)
4374{
4375	int	c;
4376	dev_t	dev;
4377	Port_t	iobase;
4378	int	s;
4379	struct siocnstate	sp;
4380	speed_t	speed;
4381
4382	dev = cd->cn_dev;
4383	if (minor(dev) == siocnunit) {
4384		iobase = siocniobase;
4385		speed = comdefaultrate;
4386	} else {
4387		iobase = siogdbiobase;
4388		speed = gdbdefaultrate;
4389	}
4390	s = spltty();
4391	siocnopen(&sp, iobase, speed);
4392	while (!(inb(iobase + com_lsr) & LSR_RXRDY))
4393		;
4394	c = inb(iobase + com_data);
4395	siocnclose(&sp, iobase);
4396	splx(s);
4397	return (c);
4398}
4399
4400static void
4401siocnputc(struct consdev *cd, int c)
4402{
4403	int	need_unlock;
4404	int	s;
4405	dev_t 	dev;
4406	struct siocnstate	sp;
4407	Port_t	iobase;
4408	speed_t	speed;
4409
4410	dev = cd->cn_dev;
4411	if (minor(dev) == siocnunit) {
4412		iobase = siocniobase;
4413		speed = comdefaultrate;
4414	} else {
4415		iobase = siogdbiobase;
4416		speed = gdbdefaultrate;
4417	}
4418	s = spltty();
4419	need_unlock = 0;
4420	if (sio_inited == 2 && !mtx_owned(&sio_lock)) {
4421		mtx_lock_spin(&sio_lock);
4422		need_unlock = 1;
4423	}
4424	siocnopen(&sp, iobase, speed);
4425	siocntxwait(iobase);
4426	outb(iobase + com_data, c);
4427	siocnclose(&sp, iobase);
4428	if (need_unlock)
4429		mtx_unlock_spin(&sio_lock);
4430	splx(s);
4431}
4432
4433#ifdef __alpha__
4434int
4435siogdbgetc()
4436{
4437	int	c;
4438	Port_t	iobase;
4439	speed_t	speed;
4440	int	s;
4441	struct siocnstate	sp;
4442
4443	if (siogdbunit == siocnunit) {
4444		iobase = siocniobase;
4445		speed = comdefaultrate;
4446	} else {
4447		iobase = siogdbiobase;
4448		speed = gdbdefaultrate;
4449	}
4450
4451	s = spltty();
4452	siocnopen(&sp, iobase, speed);
4453	while (!(inb(iobase + com_lsr) & LSR_RXRDY))
4454		;
4455	c = inb(iobase + com_data);
4456	siocnclose(&sp, iobase);
4457	splx(s);
4458	return (c);
4459}
4460
4461void
4462siogdbputc(c)
4463	int	c;
4464{
4465	Port_t	iobase;
4466	speed_t	speed;
4467	int	s;
4468	struct siocnstate	sp;
4469
4470	if (siogdbunit == siocnunit) {
4471		iobase = siocniobase;
4472		speed = comdefaultrate;
4473	} else {
4474		iobase = siogdbiobase;
4475		speed = gdbdefaultrate;
4476	}
4477
4478	s = spltty();
4479	siocnopen(&sp, iobase, speed);
4480	siocntxwait(siogdbiobase);
4481	outb(siogdbiobase + com_data, c);
4482	siocnclose(&sp, siogdbiobase);
4483	splx(s);
4484}
4485#endif
4486
4487#ifdef PC98
4488/*
4489 *  pc98 local function
4490 */
4491
4492static void
4493com_tiocm_set(struct com_s *com, int msr)
4494{
4495	int	s;
4496	int	tmp = 0;
4497	int	mask = CMD8251_TxEN|CMD8251_RxEN|CMD8251_DTR|CMD8251_RTS;
4498
4499	s=spltty();
4500	com->pc98_prev_modem_status = ( msr & (TIOCM_LE|TIOCM_DTR|TIOCM_RTS) )
4501	   | ( com->pc98_prev_modem_status & ~(TIOCM_LE|TIOCM_DTR|TIOCM_RTS) );
4502	tmp |= (CMD8251_TxEN|CMD8251_RxEN);
4503	if ( msr & TIOCM_DTR ) tmp |= CMD8251_DTR;
4504	if ( msr & TIOCM_RTS ) tmp |= CMD8251_RTS;
4505	pc98_i8251_clear_or_cmd( com, mask, tmp );
4506	splx(s);
4507}
4508
4509static void
4510com_tiocm_bis(struct com_s *com, int msr)
4511{
4512	int	s;
4513	int	tmp = 0;
4514
4515	s=spltty();
4516	com->pc98_prev_modem_status |= ( msr & (TIOCM_LE|TIOCM_DTR|TIOCM_RTS) );
4517	tmp |= CMD8251_TxEN|CMD8251_RxEN;
4518	if ( msr & TIOCM_DTR ) tmp |= CMD8251_DTR;
4519	if ( msr & TIOCM_RTS ) tmp |= CMD8251_RTS;
4520
4521	pc98_i8251_or_cmd( com, tmp );
4522	splx(s);
4523}
4524
4525static void
4526com_tiocm_bic(struct com_s *com, int msr)
4527{
4528	int	s;
4529	int	tmp = msr;
4530
4531	s=spltty();
4532	com->pc98_prev_modem_status &= ~( msr & (TIOCM_LE|TIOCM_DTR|TIOCM_RTS) );
4533	if ( msr & TIOCM_DTR ) tmp |= CMD8251_DTR;
4534	if ( msr & TIOCM_RTS ) tmp |= CMD8251_RTS;
4535
4536	pc98_i8251_clear_cmd( com, tmp );
4537	splx(s);
4538}
4539
4540static int
4541com_tiocm_get(struct com_s *com)
4542{
4543	return( com->pc98_prev_modem_status );
4544}
4545
4546static int
4547com_tiocm_get_delta(struct com_s *com)
4548{
4549	int	tmp;
4550
4551	tmp = com->pc98_modem_delta;
4552	com->pc98_modem_delta = 0;
4553	return( tmp );
4554}
4555
4556/* convert to TIOCM_?? ( ioctl.h ) */
4557static int
4558pc98_get_modem_status(struct com_s *com)
4559{
4560	register int	msr;
4561
4562	msr = com->pc98_prev_modem_status
4563			& ~(TIOCM_CAR|TIOCM_RI|TIOCM_DSR|TIOCM_CTS);
4564	if (com->pc98_8251fifo_enable) {
4565		int	stat2;
4566
4567		stat2 = inb(I8251F_msr);
4568		if ( stat2 & CICSCDF_CD ) msr |= TIOCM_CAR;
4569		if ( stat2 & CICSCDF_CI ) msr |= TIOCM_RI;
4570		if ( stat2 & CICSCDF_DR ) msr |= TIOCM_DSR;
4571		if ( stat2 & CICSCDF_CS ) msr |= TIOCM_CTS;
4572#if COM_CARRIER_DETECT_EMULATE
4573		if ( msr & (TIOCM_DSR|TIOCM_CTS) ) {
4574			msr |= TIOCM_CAR;
4575		}
4576#endif
4577	} else {
4578		int	stat, stat2;
4579
4580		stat  = inb(com->sts_port);
4581		stat2 = inb(com->in_modem_port);
4582		if ( !(stat2 & CICSCD_CD) ) msr |= TIOCM_CAR;
4583		if ( !(stat2 & CICSCD_CI) ) msr |= TIOCM_RI;
4584		if (   stat & STS8251_DSR ) msr |= TIOCM_DSR;
4585		if ( !(stat2 & CICSCD_CS) ) msr |= TIOCM_CTS;
4586#if COM_CARRIER_DETECT_EMULATE
4587		if ( msr & (TIOCM_DSR|TIOCM_CTS) ) {
4588			msr |= TIOCM_CAR;
4589		}
4590#endif
4591	}
4592	return(msr);
4593}
4594
4595static void
4596pc98_check_msr(void* chan)
4597{
4598	int	msr, delta;
4599	int	s;
4600	register struct tty *tp;
4601	struct	com_s *com;
4602	int	mynor;
4603	int	unit;
4604	dev_t	dev;
4605
4606	dev=(dev_t)chan;
4607	mynor = minor(dev);
4608	unit = MINOR_TO_UNIT(mynor);
4609	com = com_addr(unit);
4610	tp = com->tp;
4611
4612	s = spltty();
4613	msr = pc98_get_modem_status(com);
4614	/* make change flag */
4615	delta = msr ^ com->pc98_prev_modem_status;
4616	if ( delta & TIOCM_CAR ) {
4617	    if ( com->modem_car_chg_timer ) {
4618		if ( -- com->modem_car_chg_timer )
4619		    msr ^= TIOCM_CAR;
4620	    } else {
4621		if ((com->modem_car_chg_timer = (msr & TIOCM_CAR) ?
4622		     DCD_ON_RECOGNITION : DCD_OFF_TOLERANCE) != 0)
4623		    msr ^= TIOCM_CAR;
4624	    }
4625	} else
4626	    com->modem_car_chg_timer = 0;
4627	delta = ( msr ^ com->pc98_prev_modem_status ) &
4628			(TIOCM_CAR|TIOCM_RI|TIOCM_DSR|TIOCM_CTS);
4629	com->pc98_prev_modem_status = msr;
4630	delta = ( com->pc98_modem_delta |= delta );
4631	splx(s);
4632	if ( com->modem_checking || (tp->t_state & (TS_ISOPEN)) ) {
4633		if ( delta ) {
4634			commint(dev);
4635		}
4636		timeout(pc98_check_msr, (caddr_t)dev,
4637					PC98_CHECK_MODEM_INTERVAL);
4638	} else {
4639		com->modem_checking = 0;
4640	}
4641}
4642
4643static void
4644pc98_msrint_start(dev_t dev)
4645{
4646	struct	com_s *com;
4647	int	mynor;
4648	int	unit;
4649	int	s = spltty();
4650
4651	mynor = minor(dev);
4652	unit = MINOR_TO_UNIT(mynor);
4653	com = com_addr(unit);
4654	/* modem control line check routine envoke interval is 1/10 sec */
4655	if ( com->modem_checking == 0 ) {
4656		com->pc98_prev_modem_status = pc98_get_modem_status(com);
4657		com->pc98_modem_delta = 0;
4658		timeout(pc98_check_msr, (caddr_t)dev,
4659					PC98_CHECK_MODEM_INTERVAL);
4660		com->modem_checking = 1;
4661	}
4662	splx(s);
4663}
4664
4665static void
4666pc98_disable_i8251_interrupt(struct com_s *com, int mod)
4667{
4668	/* disable interrupt */
4669	register int	tmp;
4670
4671	mod |= ~(IEN_Tx|IEN_TxEMP|IEN_Rx);
4672	COM_INT_DISABLE
4673	tmp = inb( com->intr_ctrl_port ) & ~(IEN_Tx|IEN_TxEMP|IEN_Rx);
4674	outb( com->intr_ctrl_port, (com->intr_enable&=~mod) | tmp );
4675	COM_INT_ENABLE
4676}
4677
4678static void
4679pc98_enable_i8251_interrupt(struct com_s *com, int mod)
4680{
4681	register int	tmp;
4682
4683	COM_INT_DISABLE
4684	tmp = inb( com->intr_ctrl_port ) & ~(IEN_Tx|IEN_TxEMP|IEN_Rx);
4685	outb( com->intr_ctrl_port, (com->intr_enable|=mod) | tmp );
4686	COM_INT_ENABLE
4687}
4688
4689static int
4690pc98_check_i8251_interrupt(struct com_s *com)
4691{
4692	return ( com->intr_enable & 0x07 );
4693}
4694
4695static void
4696pc98_i8251_clear_cmd(struct com_s *com, int x)
4697{
4698	int	tmp;
4699
4700	COM_INT_DISABLE
4701	tmp = com->pc98_prev_siocmd & ~(x);
4702	if (com->pc98_8251fifo_enable)
4703	    outb(I8251F_fcr, 0);
4704	outb(com->cmd_port, tmp);
4705	com->pc98_prev_siocmd = tmp & ~(CMD8251_ER|CMD8251_RESET|CMD8251_EH);
4706	if (com->pc98_8251fifo_enable)
4707	    outb(I8251F_fcr, CTRL8251F_ENABLE);
4708	COM_INT_ENABLE
4709}
4710
4711static void
4712pc98_i8251_or_cmd(struct com_s *com, int x)
4713{
4714	int	tmp;
4715
4716	COM_INT_DISABLE
4717	if (com->pc98_8251fifo_enable)
4718	    outb(I8251F_fcr, 0);
4719	tmp = com->pc98_prev_siocmd | (x);
4720	outb(com->cmd_port, tmp);
4721	com->pc98_prev_siocmd = tmp & ~(CMD8251_ER|CMD8251_RESET|CMD8251_EH);
4722	if (com->pc98_8251fifo_enable)
4723	    outb(I8251F_fcr, CTRL8251F_ENABLE);
4724	COM_INT_ENABLE
4725}
4726
4727static void
4728pc98_i8251_set_cmd(struct com_s *com, int x)
4729{
4730	int	tmp;
4731
4732	COM_INT_DISABLE
4733	if (com->pc98_8251fifo_enable)
4734	    outb(I8251F_fcr, 0);
4735	tmp = (x);
4736	outb(com->cmd_port, tmp);
4737	com->pc98_prev_siocmd = tmp & ~(CMD8251_ER|CMD8251_RESET|CMD8251_EH);
4738	if (com->pc98_8251fifo_enable)
4739	    outb(I8251F_fcr, CTRL8251F_ENABLE);
4740	COM_INT_ENABLE
4741}
4742
4743static void
4744pc98_i8251_clear_or_cmd(struct com_s *com, int clr, int x)
4745{
4746	int	tmp;
4747	COM_INT_DISABLE
4748	if (com->pc98_8251fifo_enable)
4749	    outb(I8251F_fcr, 0);
4750	tmp = com->pc98_prev_siocmd & ~(clr);
4751	tmp |= (x);
4752	outb(com->cmd_port, tmp);
4753	com->pc98_prev_siocmd = tmp & ~(CMD8251_ER|CMD8251_RESET|CMD8251_EH);
4754	if (com->pc98_8251fifo_enable)
4755	    outb(I8251F_fcr, CTRL8251F_ENABLE);
4756	COM_INT_ENABLE
4757}
4758
4759static int
4760pc98_i8251_get_cmd(struct com_s *com)
4761{
4762	return com->pc98_prev_siocmd;
4763}
4764
4765static int
4766pc98_i8251_get_mod(struct com_s *com)
4767{
4768	return com->pc98_prev_siomod;
4769}
4770
4771static void
4772pc98_i8251_reset(struct com_s *com, int mode, int command)
4773{
4774	if (com->pc98_8251fifo_enable)
4775	    outb(I8251F_fcr, 0);
4776	outb(com->cmd_port, 0);	/* dummy */
4777	DELAY(2);
4778	outb(com->cmd_port, 0);	/* dummy */
4779	DELAY(2);
4780	outb(com->cmd_port, 0);	/* dummy */
4781	DELAY(2);
4782	outb(com->cmd_port, CMD8251_RESET);	/* internal reset */
4783	DELAY(2);
4784	outb(com->cmd_port, mode );	/* mode register */
4785	com->pc98_prev_siomod = mode;
4786	DELAY(2);
4787	pc98_i8251_set_cmd( com, (command|CMD8251_ER) );
4788	DELAY(10);
4789	if (com->pc98_8251fifo_enable)
4790	    outb(I8251F_fcr, CTRL8251F_ENABLE |
4791		 CTRL8251F_XMT_RST | CTRL8251F_RCV_RST);
4792}
4793
4794static void
4795pc98_check_sysclock(void)
4796{
4797	/* get system clock from port */
4798	if ( pc98_machine_type & M_8M ) {
4799	/* 8 MHz system & H98 */
4800		sysclock = 8;
4801	} else {
4802	/* 5 MHz system */
4803		sysclock = 5;
4804	}
4805}
4806
4807static void
4808com_cflag_and_speed_set( struct com_s *com, int cflag, int speed)
4809{
4810	int	cfcr=0;
4811	int	previnterrupt;
4812	u_int	count;
4813
4814	if (pc98_ttspeedtab(com, speed, &count) != 0)
4815		return;
4816
4817	previnterrupt = pc98_check_i8251_interrupt(com);
4818	pc98_disable_i8251_interrupt( com, IEN_Tx|IEN_TxEMP|IEN_Rx );
4819
4820	switch ( cflag&CSIZE ) {
4821	  case CS5:
4822		cfcr = MOD8251_5BITS; break;
4823	  case CS6:
4824		cfcr = MOD8251_6BITS; break;
4825	  case CS7:
4826		cfcr = MOD8251_7BITS; break;
4827	  case CS8:
4828		cfcr = MOD8251_8BITS; break;
4829	}
4830	if ( cflag&PARENB ) {
4831	    if ( cflag&PARODD )
4832		cfcr |= MOD8251_PODD;
4833	    else
4834		cfcr |= MOD8251_PEVEN;
4835	} else
4836		cfcr |= MOD8251_PDISAB;
4837
4838	if ( cflag&CSTOPB )
4839		cfcr |= MOD8251_STOP2;
4840	else
4841		cfcr |= MOD8251_STOP1;
4842
4843	if ( count & 0x10000 )
4844		cfcr |= MOD8251_CLKX1;
4845	else
4846		cfcr |= MOD8251_CLKX16;
4847
4848	if (epson_machine_id != 0x20) {	/* XXX */
4849		int	tmp;
4850		while (!((tmp = inb(com->sts_port)) & STS8251_TxEMP))
4851			;
4852	}
4853	/* set baud rate from ospeed */
4854	pc98_set_baud_rate( com, count );
4855
4856	if ( cfcr != pc98_i8251_get_mod(com) )
4857		pc98_i8251_reset(com, cfcr, pc98_i8251_get_cmd(com) );
4858
4859	pc98_enable_i8251_interrupt( com, previnterrupt );
4860}
4861
4862static int
4863pc98_ttspeedtab(struct com_s *com, int speed, u_int *divisor)
4864{
4865	int	if_type, effect_sp, count = -1, mod;
4866
4867	if_type = com->pc98_if_type & 0x0f;
4868
4869	switch (com->pc98_if_type) {
4870	case COM_IF_INTERNAL:
4871	    if (PC98SIO_baud_rate_port(if_type) != -1) {
4872		count = ttspeedtab(speed, if_8251_type[if_type].speedtab);
4873		if (count > 0) {
4874		    count |= COM1_EXT_CLOCK;
4875		    break;
4876		}
4877	    }
4878
4879	    /* for *1CLK asynchronous! mode, TEFUTEFU */
4880	    mod = (sysclock == 5) ? 2457600 : 1996800;
4881	    effect_sp = ttspeedtab( speed, pc98speedtab );
4882	    if ( effect_sp < 0 )	/* XXX */
4883		effect_sp = ttspeedtab( (speed - 1), pc98speedtab );
4884	    if ( effect_sp <= 0 )
4885		return effect_sp;
4886	    if ( effect_sp == speed )
4887		mod /= 16;
4888	    if ( mod % effect_sp )
4889		return(-1);
4890	    count = mod / effect_sp;
4891	    if ( count > 65535 )
4892		return(-1);
4893	    if ( effect_sp != speed )
4894		count |= 0x10000;
4895	    break;
4896	case COM_IF_PC9861K_1:
4897	case COM_IF_PC9861K_2:
4898	    count = 1;
4899	    break;
4900	case COM_IF_IND_SS_1:
4901	case COM_IF_IND_SS_2:
4902	case COM_IF_PIO9032B_1:
4903	case COM_IF_PIO9032B_2:
4904	    count = ttspeedtab( speed, if_8251_type[if_type].speedtab );
4905	    break;
4906	case COM_IF_B98_01_1:
4907	case COM_IF_B98_01_2:
4908	    count = ttspeedtab( speed, if_8251_type[if_type].speedtab );
4909#ifdef B98_01_OLD
4910	    if (count == 0 || count == 1) {
4911		count += 4;
4912		count |= 0x20000;  /* x1 mode for 76800 and 153600 */
4913	    }
4914#endif
4915	    break;
4916	}
4917
4918	if (count < 0)
4919		return count;
4920
4921	*divisor = (u_int) count;
4922	return 0;
4923}
4924
4925static void
4926pc98_set_baud_rate( struct com_s *com, u_int count )
4927{
4928	int	if_type, io, s;
4929
4930	if_type = com->pc98_if_type & 0x0f;
4931	io = rman_get_start(com->ioportres) & 0xff00;
4932
4933	switch (com->pc98_if_type) {
4934	case COM_IF_INTERNAL:
4935	    if (PC98SIO_baud_rate_port(if_type) != -1) {
4936		if (count & COM1_EXT_CLOCK) {
4937		    outb((Port_t)PC98SIO_baud_rate_port(if_type), count & 0xff);
4938		    break;
4939		} else {
4940		    outb((Port_t)PC98SIO_baud_rate_port(if_type), 0x09);
4941		}
4942	    }
4943
4944	    if (count == 0)
4945		return;
4946
4947	    /* set i8253 */
4948	    s = splclock();
4949	    if (count != 3)
4950		outb( 0x77, 0xb6 );
4951	    else
4952		outb( 0x77, 0xb4 );
4953	    outb( 0x5f, 0);
4954	    outb( 0x75, count & 0xff );
4955	    outb( 0x5f, 0);
4956	    outb( 0x75, (count >> 8) & 0xff );
4957	    splx(s);
4958	    break;
4959	case COM_IF_IND_SS_1:
4960	case COM_IF_IND_SS_2:
4961	    outb(io | PC98SIO_intr_ctrl_port(if_type), 0);
4962	    outb(io | PC98SIO_baud_rate_port(if_type), 0);
4963	    outb(io | PC98SIO_baud_rate_port(if_type), 0xc0);
4964	    outb(io | PC98SIO_baud_rate_port(if_type), (count >> 8) | 0x80);
4965	    outb(io | PC98SIO_baud_rate_port(if_type), count & 0xff);
4966	    break;
4967	case COM_IF_PIO9032B_1:
4968	case COM_IF_PIO9032B_2:
4969	    outb(io | PC98SIO_baud_rate_port(if_type), count);
4970	    break;
4971	case COM_IF_B98_01_1:
4972	case COM_IF_B98_01_2:
4973	    outb(io | PC98SIO_baud_rate_port(if_type), count & 0x0f);
4974#ifdef B98_01_OLD
4975	    /*
4976	     * Some old B98_01 board should be controlled
4977	     * in different way, but this hasn't been tested yet.
4978	     */
4979	    outb(io | PC98SIO_func_port(if_type),
4980		 (count & 0x20000) ? 0xf0 : 0xf2);
4981#endif
4982	    break;
4983	}
4984}
4985static int
4986pc98_check_if_type(device_t dev, struct siodev *iod)
4987{
4988	int	irr, io, if_type, tmp;
4989	static  short	irq_tab[2][8] = {
4990		{  3,  5,  6,  9, 10, 12, 13, -1},
4991		{  3, 10, 12, 13,  5,  6,  9, -1}
4992	};
4993
4994	if_type = iod->if_type & 0x0f;
4995	iod->irq = 0;
4996	io = isa_get_port(dev) & 0xff00;
4997
4998	if (IS_8251(iod->if_type)) {
4999	    if (PC98SIO_func_port(if_type) != -1) {
5000		outb(io | PC98SIO_func_port(if_type), 0xf2);
5001		tmp = ttspeedtab(9600, if_8251_type[if_type].speedtab);
5002		if (tmp != -1 && PC98SIO_baud_rate_port(if_type) != -1)
5003		    outb(io | PC98SIO_baud_rate_port(if_type), tmp);
5004	    }
5005
5006	    iod->cmd  = io | PC98SIO_cmd_port(if_type);
5007	    iod->sts  = io | PC98SIO_sts_port(if_type);
5008	    iod->mod  = io | PC98SIO_in_modem_port(if_type);
5009	    iod->ctrl = io | PC98SIO_intr_ctrl_port(if_type);
5010
5011	    if (iod->if_type == COM_IF_INTERNAL) {
5012		iod->irq = 4;
5013
5014		if (pc98_check_8251vfast()) {
5015			PC98SIO_baud_rate_port(if_type) = I8251F_div;
5016			if_8251_type[if_type].speedtab = pc98fast_speedtab;
5017		}
5018	    } else {
5019		tmp = inb( iod->mod ) & if_8251_type[if_type].irr_mask;
5020		if ((isa_get_port(dev) & 0xff) == IO_COM2)
5021		    iod->irq = irq_tab[0][tmp];
5022		else
5023		    iod->irq = irq_tab[1][tmp];
5024	    }
5025	} else {
5026	    irr = if_16550a_type[if_type].irr_read;
5027#ifdef COM_MULTIPORT
5028	    if (!COM_ISMULTIPORT(device_get_flags(dev)) ||
5029		    device_get_unit(dev) == COM_MPMASTER(device_get_flags(dev)))
5030#endif
5031	    if (irr != -1) {
5032		tmp = inb(io | irr);
5033		if (isa_get_port(dev) & 0x01)	/* XXX depend on RSB-384 */
5034		    iod->irq = irq_tab[1][tmp >> 3];
5035		else
5036		    iod->irq = irq_tab[0][tmp & 0x07];
5037	    }
5038	}
5039	if ( iod->irq == -1 ) return -1;
5040
5041	return 0;
5042}
5043static void
5044pc98_set_ioport(struct com_s *com)
5045{
5046	int	if_type = com->pc98_if_type & 0x0f;
5047	Port_t	io = rman_get_start(com->ioportres) & 0xff00;
5048
5049	pc98_check_sysclock();
5050	com->data_port		= io | PC98SIO_data_port(if_type);
5051	com->cmd_port		= io | PC98SIO_cmd_port(if_type);
5052	com->sts_port		= io | PC98SIO_sts_port(if_type);
5053	com->in_modem_port	= io | PC98SIO_in_modem_port(if_type);
5054	com->intr_ctrl_port	= io | PC98SIO_intr_ctrl_port(if_type);
5055}
5056static int
5057pc98_check_8251vfast(void)
5058{
5059    int	i;
5060
5061    outb(I8251F_div, 0x8c);
5062    DELAY(10);
5063    for (i = 0; i < 100; i++) {
5064	if ((inb(I8251F_div) & 0x80) != 0) {
5065	    i = 0;
5066	    break;
5067	}
5068	DELAY(1);
5069    }
5070    outb(I8251F_div, 0);
5071    DELAY(10);
5072    for (; i < 100; i++) {
5073	if ((inb(I8251F_div) & 0x80) == 0)
5074	    return 1;
5075	DELAY(1);
5076    }
5077
5078    return 0;
5079}
5080static int
5081pc98_check_8251fifo(void)
5082{
5083    u_char	tmp1, tmp2;
5084
5085    tmp1 = inb(I8251F_iir);
5086    DELAY(10);
5087    tmp2 = inb(I8251F_iir);
5088    if (((tmp1 ^ tmp2) & 0x40) != 0 && ((tmp1 | tmp2) & 0x20) == 0)
5089	return 1;
5090
5091    return 0;
5092}
5093#endif /* PC98 defined */
5094