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