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