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