sio.c revision 129939
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 129939 2004-06-01 11:57:15Z 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	comhardclose(com);
2109	ttyclose(tp);
2110	siosettimeout();
2111	splx(s);
2112	if (com->gone) {
2113		printf("sio%d: gone\n", com->unit);
2114		s = spltty();
2115		if (com->ibuf != NULL)
2116			free(com->ibuf, M_DEVBUF);
2117		bzero(tp, sizeof *tp);
2118		splx(s);
2119	}
2120	return (0);
2121}
2122
2123static void
2124comhardclose(com)
2125	struct com_s	*com;
2126{
2127	int		s;
2128	struct tty	*tp;
2129
2130	s = spltty();
2131	com->poll = FALSE;
2132	com->poll_output = FALSE;
2133	com->do_timestamp = FALSE;
2134	com->do_dcd_timestamp = FALSE;
2135	com->pps.ppsparam.mode = 0;
2136#ifdef PC98
2137	if (IS_8251(com->pc98_if_type))
2138		com_send_break_off(com);
2139	else
2140#endif
2141	sio_setreg(com, com_cfcr, com->cfcr_image &= ~CFCR_SBREAK);
2142	tp = com->tp;
2143
2144#if defined(DDB) && (defined(BREAK_TO_DEBUGGER) || \
2145    defined(ALT_BREAK_TO_DEBUGGER))
2146	/*
2147	 * Leave interrupts enabled and don't clear DTR if this is the
2148	 * console. This allows us to detect break-to-debugger events
2149	 * while the console device is closed.
2150	 */
2151	if (com->unit != comconsole)
2152#endif
2153	{
2154#ifdef PC98
2155		int	tmp;
2156		if (IS_8251(com->pc98_if_type))
2157			com_int_TxRx_disable(com);
2158		else
2159			sio_setreg(com, com_ier, 0);
2160		if (com->pc98_if_type == COM_IF_RSA98III)
2161			outb(com->rsabase + rsa_ier, 0x00);
2162		if (IS_8251(com->pc98_if_type))
2163			tmp = pc98_get_modem_status(com) & TIOCM_CAR;
2164		else
2165			tmp = com->prev_modem_status & MSR_DCD;
2166#else
2167		sio_setreg(com, com_ier, 0);
2168#endif
2169		if (tp->t_cflag & HUPCL
2170		    /*
2171		     * XXX we will miss any carrier drop between here and the
2172		     * next open.  Perhaps we should watch DCD even when the
2173		     * port is closed; it is not sufficient to check it at
2174		     * the next open because it might go up and down while
2175		     * we're not watching.
2176		     */
2177		    || (!com->active_out
2178#ifdef PC98
2179			&& !(tmp)
2180#else
2181		        && !(com->prev_modem_status & MSR_DCD)
2182#endif
2183		        && !(com->it_in.c_cflag & CLOCAL))
2184		    || !(tp->t_state & TS_ISOPEN)) {
2185#ifdef PC98
2186			if (IS_8251(com->pc98_if_type))
2187			    com_tiocm_bic(com, TIOCM_DTR|TIOCM_RTS|TIOCM_LE);
2188			else
2189#endif
2190			(void)commctl(com, TIOCM_DTR, DMBIC);
2191			if (com->dtr_wait != 0 && !(com->state & CS_DTR_OFF)) {
2192				timeout(siodtrwakeup, com, com->dtr_wait);
2193				com->state |= CS_DTR_OFF;
2194			}
2195		}
2196#ifdef PC98
2197		else {
2198			if (IS_8251(com->pc98_if_type))
2199				com_tiocm_bic(com, TIOCM_LE);
2200		}
2201#endif
2202	}
2203#ifdef PC98
2204	if (com->pc98_8251fifo)	{
2205	    if (com->pc98_8251fifo_enable)
2206		outb(I8251F_fcr, CTRL8251F_XMT_RST | CTRL8251F_RCV_RST);
2207	    com->pc98_8251fifo_enable = 0;
2208	}
2209#endif
2210	if (com->hasfifo) {
2211		/*
2212		 * Disable fifos so that they are off after controlled
2213		 * reboots.  Some BIOSes fail to detect 16550s when the
2214		 * fifos are enabled.
2215		 */
2216		sio_setreg(com, com_fifo, 0);
2217	}
2218	com->active_out = FALSE;
2219	wakeup(&com->active_out);
2220	wakeup(TSA_CARR_ON(tp));	/* restart any wopeners */
2221	splx(s);
2222}
2223
2224static int
2225sioread(dev, uio, flag)
2226	dev_t		dev;
2227	struct uio	*uio;
2228	int		flag;
2229{
2230	int		mynor;
2231	struct com_s	*com;
2232
2233	mynor = minor(dev);
2234	if (mynor & CONTROL_MASK)
2235		return (ENODEV);
2236	com = com_addr(MINOR_TO_UNIT(mynor));
2237	if (com == NULL || com->gone)
2238		return (ENODEV);
2239	return ((*linesw[com->tp->t_line].l_read)(com->tp, uio, flag));
2240}
2241
2242static int
2243siowrite(dev, uio, flag)
2244	dev_t		dev;
2245	struct uio	*uio;
2246	int		flag;
2247{
2248	int		mynor;
2249	struct com_s	*com;
2250	int		unit;
2251
2252	mynor = minor(dev);
2253	if (mynor & CONTROL_MASK)
2254		return (ENODEV);
2255
2256	unit = MINOR_TO_UNIT(mynor);
2257	com = com_addr(unit);
2258	if (com == NULL || com->gone)
2259		return (ENODEV);
2260	/*
2261	 * (XXX) We disallow virtual consoles if the physical console is
2262	 * a serial port.  This is in case there is a display attached that
2263	 * is not the console.  In that situation we don't need/want the X
2264	 * server taking over the console.
2265	 */
2266	if (constty != NULL && unit == comconsole)
2267		constty = NULL;
2268	return ((*linesw[com->tp->t_line].l_write)(com->tp, uio, flag));
2269}
2270
2271static void
2272siobusycheck(chan)
2273	void	*chan;
2274{
2275	struct com_s	*com;
2276	int		s;
2277
2278	com = (struct com_s *)chan;
2279
2280	/*
2281	 * Clear TS_BUSY if low-level output is complete.
2282	 * spl locking is sufficient because siointr1() does not set CS_BUSY.
2283	 * If siointr1() clears CS_BUSY after we look at it, then we'll get
2284	 * called again.  Reading the line status port outside of siointr1()
2285	 * is safe because CS_BUSY is clear so there are no output interrupts
2286	 * to lose.
2287	 */
2288	s = spltty();
2289	if (com->state & CS_BUSY)
2290		com->extra_state &= ~CSE_BUSYCHECK;	/* False alarm. */
2291#ifdef	PC98
2292	else if ((IS_8251(com->pc98_if_type) &&
2293		  ((com->pc98_8251fifo_enable &&
2294		    (inb(I8251F_lsr) & (STS8251F_TxRDY | STS8251F_TxEMP))
2295		    == (STS8251F_TxRDY | STS8251F_TxEMP)) ||
2296		   (!com->pc98_8251fifo_enable &&
2297		    (inb(com->sts_port) & (STS8251_TxRDY | STS8251_TxEMP))
2298		    == (STS8251_TxRDY | STS8251_TxEMP)))) ||
2299		 ((inb(com->line_status_port) & (LSR_TSRE | LSR_TXRDY))
2300		  == (LSR_TSRE | LSR_TXRDY))) {
2301#else
2302	else if ((inb(com->line_status_port) & (LSR_TSRE | LSR_TXRDY))
2303	    == (LSR_TSRE | LSR_TXRDY)) {
2304#endif
2305		com->tp->t_state &= ~TS_BUSY;
2306		ttwwakeup(com->tp);
2307		com->extra_state &= ~CSE_BUSYCHECK;
2308	} else
2309		timeout(siobusycheck, com, hz / 100);
2310	splx(s);
2311}
2312
2313static u_int
2314siodivisor(rclk, speed)
2315	u_long	rclk;
2316	speed_t	speed;
2317{
2318	long	actual_speed;
2319	u_int	divisor;
2320	int	error;
2321
2322	if (speed == 0)
2323		return (0);
2324#if UINT_MAX > (ULONG_MAX - 1) / 8
2325	if (speed > (ULONG_MAX - 1) / 8)
2326		return (0);
2327#endif
2328	divisor = (rclk / (8UL * speed) + 1) / 2;
2329	if (divisor == 0 || divisor >= 65536)
2330		return (0);
2331	actual_speed = rclk / (16UL * divisor);
2332
2333	/* 10 times error in percent: */
2334	error = ((actual_speed - (long)speed) * 2000 / (long)speed + 1) / 2;
2335
2336	/* 3.0% maximum error tolerance: */
2337	if (error < -30 || error > 30)
2338		return (0);
2339
2340	return (divisor);
2341}
2342
2343static void
2344siodtrwakeup(chan)
2345	void	*chan;
2346{
2347	struct com_s	*com;
2348
2349	com = (struct com_s *)chan;
2350	com->state &= ~CS_DTR_OFF;
2351	wakeup(&com->dtr_wait);
2352}
2353
2354/*
2355 * Call this function with the sio_lock mutex held.  It will return with the
2356 * lock still held.
2357 */
2358static void
2359sioinput(com)
2360	struct com_s	*com;
2361{
2362	u_char		*buf;
2363	int		incc;
2364	u_char		line_status;
2365	int		recv_data;
2366	struct tty	*tp;
2367
2368	buf = com->ibuf;
2369	tp = com->tp;
2370	if (!(tp->t_state & TS_ISOPEN) || !(tp->t_cflag & CREAD)) {
2371		com_events -= (com->iptr - com->ibuf);
2372		com->iptr = com->ibuf;
2373		return;
2374	}
2375	if (tp->t_state & TS_CAN_BYPASS_L_RINT) {
2376		/*
2377		 * Avoid the grotesquely inefficient lineswitch routine
2378		 * (ttyinput) in "raw" mode.  It usually takes about 450
2379		 * instructions (that's without canonical processing or echo!).
2380		 * slinput is reasonably fast (usually 40 instructions plus
2381		 * call overhead).
2382		 */
2383		do {
2384			/*
2385			 * This may look odd, but it is using save-and-enable
2386			 * semantics instead of the save-and-disable semantics
2387			 * that are used everywhere else.
2388			 */
2389			mtx_unlock_spin(&sio_lock);
2390			incc = com->iptr - buf;
2391			if (tp->t_rawq.c_cc + incc > tp->t_ihiwat
2392			    && (com->state & CS_RTS_IFLOW
2393				|| tp->t_iflag & IXOFF)
2394			    && !(tp->t_state & TS_TBLOCK))
2395				ttyblock(tp);
2396			com->delta_error_counts[CE_TTY_BUF_OVERFLOW]
2397				+= b_to_q((char *)buf, incc, &tp->t_rawq);
2398			buf += incc;
2399			tk_nin += incc;
2400			tk_rawcc += incc;
2401			tp->t_rawcc += incc;
2402			ttwakeup(tp);
2403			if (tp->t_state & TS_TTSTOP
2404			    && (tp->t_iflag & IXANY
2405				|| tp->t_cc[VSTART] == tp->t_cc[VSTOP])) {
2406				tp->t_state &= ~TS_TTSTOP;
2407				tp->t_lflag &= ~FLUSHO;
2408				comstart(tp);
2409			}
2410			mtx_lock_spin(&sio_lock);
2411		} while (buf < com->iptr);
2412	} else {
2413		do {
2414			/*
2415			 * This may look odd, but it is using save-and-enable
2416			 * semantics instead of the save-and-disable semantics
2417			 * that are used everywhere else.
2418			 */
2419			mtx_unlock_spin(&sio_lock);
2420			line_status = buf[com->ierroff];
2421			recv_data = *buf++;
2422			if (line_status
2423			    & (LSR_BI | LSR_FE | LSR_OE | LSR_PE)) {
2424				if (line_status & LSR_BI)
2425					recv_data |= TTY_BI;
2426				if (line_status & LSR_FE)
2427					recv_data |= TTY_FE;
2428				if (line_status & LSR_OE)
2429					recv_data |= TTY_OE;
2430				if (line_status & LSR_PE)
2431					recv_data |= TTY_PE;
2432			}
2433			(*linesw[tp->t_line].l_rint)(recv_data, tp);
2434			mtx_lock_spin(&sio_lock);
2435		} while (buf < com->iptr);
2436	}
2437	com_events -= (com->iptr - com->ibuf);
2438	com->iptr = com->ibuf;
2439
2440	/*
2441	 * There is now room for another low-level buffer full of input,
2442	 * so enable RTS if it is now disabled and there is room in the
2443	 * high-level buffer.
2444	 */
2445#ifdef PC98
2446	if (IS_8251(com->pc98_if_type)) {
2447		if ((com->state & CS_RTS_IFLOW) &&
2448		    !(com_tiocm_get(com) & TIOCM_RTS) &&
2449		    !(tp->t_state & TS_TBLOCK))
2450			com_tiocm_bis(com, TIOCM_RTS);
2451	} else {
2452		if ((com->state & CS_RTS_IFLOW) &&
2453		    !(com->mcr_image & MCR_RTS) &&
2454		    !(tp->t_state & TS_TBLOCK))
2455			outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
2456	}
2457#else
2458	if ((com->state & CS_RTS_IFLOW) && !(com->mcr_image & MCR_RTS) &&
2459	    !(tp->t_state & TS_TBLOCK))
2460		outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
2461#endif
2462}
2463
2464static void
2465siointr(arg)
2466	void		*arg;
2467{
2468	struct com_s	*com;
2469#if defined(PC98) && defined(COM_MULTIPORT)
2470	u_char		rsa_buf_status;
2471#endif
2472
2473#ifndef COM_MULTIPORT
2474	com = (struct com_s *)arg;
2475
2476	mtx_lock_spin(&sio_lock);
2477	siointr1(com);
2478	mtx_unlock_spin(&sio_lock);
2479#else /* COM_MULTIPORT */
2480	bool_t		possibly_more_intrs;
2481	int		unit;
2482
2483	/*
2484	 * Loop until there is no activity on any port.  This is necessary
2485	 * to get an interrupt edge more than to avoid another interrupt.
2486	 * If the IRQ signal is just an OR of the IRQ signals from several
2487	 * devices, then the edge from one may be lost because another is
2488	 * on.
2489	 */
2490	mtx_lock_spin(&sio_lock);
2491	do {
2492		possibly_more_intrs = FALSE;
2493		for (unit = 0; unit < sio_numunits; ++unit) {
2494			com = com_addr(unit);
2495			/*
2496			 * XXX COM_LOCK();
2497			 * would it work here, or be counter-productive?
2498			 */
2499#ifdef PC98
2500			if (com != NULL
2501			    && !com->gone
2502			    && IS_8251(com->pc98_if_type)) {
2503				siointr1(com);
2504			} else if (com != NULL
2505			    && !com->gone
2506			    && com->pc98_if_type == COM_IF_RSA98III) {
2507				rsa_buf_status =
2508				    inb(com->rsabase + rsa_srr) & 0xc9;
2509				if ((rsa_buf_status & 0xc8)
2510				    || !(rsa_buf_status & 0x01)) {
2511				    siointr1(com);
2512				    if (rsa_buf_status !=
2513					(inb(com->rsabase + rsa_srr) & 0xc9))
2514					possibly_more_intrs = TRUE;
2515				}
2516			} else
2517#endif
2518			if (com != NULL
2519			    && !com->gone
2520			    && (inb(com->int_id_port) & IIR_IMASK)
2521			       != IIR_NOPEND) {
2522				siointr1(com);
2523				possibly_more_intrs = TRUE;
2524			}
2525			/* XXX COM_UNLOCK(); */
2526		}
2527	} while (possibly_more_intrs);
2528	mtx_unlock_spin(&sio_lock);
2529#endif /* COM_MULTIPORT */
2530}
2531
2532static struct timespec siots[8];
2533static int siotso;
2534static int volatile siotsunit = -1;
2535
2536static int
2537sysctl_siots(SYSCTL_HANDLER_ARGS)
2538{
2539	char buf[128];
2540	long long delta;
2541	size_t len;
2542	int error, i, tso;
2543
2544	for (i = 1, tso = siotso; i < tso; i++) {
2545		delta = (long long)(siots[i].tv_sec - siots[i - 1].tv_sec) *
2546		    1000000000 +
2547		    (siots[i].tv_nsec - siots[i - 1].tv_nsec);
2548		len = sprintf(buf, "%lld\n", delta);
2549		if (delta >= 110000)
2550			len += sprintf(buf + len - 1, ": *** %ld.%09ld\n",
2551			    (long)siots[i].tv_sec, siots[i].tv_nsec) - 1;
2552		if (i == tso - 1)
2553			buf[len - 1] = '\0';
2554		error = SYSCTL_OUT(req, buf, len);
2555		if (error != 0)
2556			return (error);
2557		uio_yield();
2558	}
2559	return (0);
2560}
2561
2562SYSCTL_PROC(_machdep, OID_AUTO, siots, CTLTYPE_STRING | CTLFLAG_RD,
2563    0, 0, sysctl_siots, "A", "sio timestamps");
2564
2565static void
2566siointr1(com)
2567	struct com_s	*com;
2568{
2569	u_char	int_ctl;
2570	u_char	int_ctl_new;
2571	u_char	line_status;
2572	u_char	modem_status;
2573	u_char	*ioptr;
2574	u_char	recv_data;
2575
2576#ifdef PC98
2577	u_char	tmp = 0;
2578	u_char	rsa_buf_status = 0;
2579	int	rsa_tx_fifo_size = 0;
2580#endif /* PC98 */
2581
2582	if (COM_IIR_TXRDYBUG(com->flags)) {
2583		int_ctl = inb(com->int_ctl_port);
2584		int_ctl_new = int_ctl;
2585	} else {
2586		int_ctl = 0;
2587		int_ctl_new = 0;
2588	}
2589
2590	while (!com->gone) {
2591#ifdef PC98
2592status_read:;
2593		if (IS_8251(com->pc98_if_type)) {
2594			if (com->pc98_8251fifo_enable)
2595				tmp = inb(I8251F_lsr);
2596			else
2597				tmp = inb(com->sts_port);
2598more_intr:
2599			line_status = 0;
2600			if (com->pc98_8251fifo_enable) {
2601			    if (tmp & STS8251F_TxRDY) line_status |= LSR_TXRDY;
2602			    if (tmp & STS8251F_RxRDY) line_status |= LSR_RXRDY;
2603			    if (tmp & STS8251F_TxEMP) line_status |= LSR_TSRE;
2604			    if (tmp & STS8251F_PE)    line_status |= LSR_PE;
2605			    if (tmp & STS8251F_OE)    line_status |= LSR_OE;
2606			    if (tmp & STS8251F_BD_SD) line_status |= LSR_BI;
2607			} else {
2608			    if (tmp & STS8251_TxRDY)  line_status |= LSR_TXRDY;
2609			    if (tmp & STS8251_RxRDY)  line_status |= LSR_RXRDY;
2610			    if (tmp & STS8251_TxEMP)  line_status |= LSR_TSRE;
2611			    if (tmp & STS8251_PE)     line_status |= LSR_PE;
2612			    if (tmp & STS8251_OE)     line_status |= LSR_OE;
2613			    if (tmp & STS8251_FE)     line_status |= LSR_FE;
2614			    if (tmp & STS8251_BD_SD)  line_status |= LSR_BI;
2615			}
2616		} else {
2617#endif /* PC98 */
2618		if (com->pps.ppsparam.mode & PPS_CAPTUREBOTH) {
2619			modem_status = inb(com->modem_status_port);
2620		        if ((modem_status ^ com->last_modem_status) &
2621			    com->pps_bit) {
2622				pps_capture(&com->pps);
2623				pps_event(&com->pps,
2624				    (modem_status & com->pps_bit) ?
2625				    PPS_CAPTUREASSERT : PPS_CAPTURECLEAR);
2626			}
2627		}
2628		line_status = inb(com->line_status_port);
2629#ifdef PC98
2630		}
2631		if (com->pc98_if_type == COM_IF_RSA98III)
2632			rsa_buf_status = inb(com->rsabase + rsa_srr);
2633#endif /* PC98 */
2634
2635		/* input event? (check first to help avoid overruns) */
2636#ifndef PC98
2637		while (line_status & LSR_RCV_MASK) {
2638#else
2639		while ((line_status & LSR_RCV_MASK)
2640		       || (com->pc98_if_type == COM_IF_RSA98III
2641			   && (rsa_buf_status & 0x08))) {
2642#endif /* PC98 */
2643			/* break/unnattached error bits or real input? */
2644#ifdef PC98
2645			if (IS_8251(com->pc98_if_type)) {
2646				if (com->pc98_8251fifo_enable) {
2647				    recv_data = inb(I8251F_data);
2648				    if (tmp & (STS8251F_PE | STS8251F_OE |
2649					       STS8251F_BD_SD)) {
2650					pc98_i8251_or_cmd(com, CMD8251_ER);
2651					recv_data = 0;
2652				    }
2653				} else {
2654				    recv_data = inb(com->data_port);
2655				    if (tmp & (STS8251_PE | STS8251_OE |
2656					       STS8251_FE | STS8251_BD_SD)) {
2657					pc98_i8251_or_cmd(com, CMD8251_ER);
2658					recv_data = 0;
2659				    }
2660				}
2661			} else if (com->pc98_if_type == COM_IF_RSA98III) {
2662				if (!(rsa_buf_status & 0x08))
2663					recv_data = 0;
2664				else
2665					recv_data = inb(com->data_port);
2666			} else
2667#endif
2668			if (!(line_status & LSR_RXRDY))
2669				recv_data = 0;
2670			else
2671				recv_data = inb(com->data_port);
2672#ifdef DDB
2673#ifdef ALT_BREAK_TO_DEBUGGER
2674			if (com->unit == comconsole &&
2675			    db_alt_break(recv_data, &com->alt_brk_state) != 0)
2676				breakpoint();
2677#endif /* ALT_BREAK_TO_DEBUGGER */
2678#endif /* DDB */
2679			if (line_status & (LSR_BI | LSR_FE | LSR_PE)) {
2680				/*
2681				 * Don't store BI if IGNBRK or FE/PE if IGNPAR.
2682				 * Otherwise, push the work to a higher level
2683				 * (to handle PARMRK) if we're bypassing.
2684				 * Otherwise, convert BI/FE and PE+INPCK to 0.
2685				 *
2686				 * This makes bypassing work right in the
2687				 * usual "raw" case (IGNBRK set, and IGNPAR
2688				 * and INPCK clear).
2689				 *
2690				 * Note: BI together with FE/PE means just BI.
2691				 */
2692				if (line_status & LSR_BI) {
2693#if defined(DDB) && defined(BREAK_TO_DEBUGGER)
2694					if (com->unit == comconsole) {
2695						breakpoint();
2696						goto cont;
2697					}
2698#endif
2699					if (com->tp == NULL
2700					    || com->tp->t_iflag & IGNBRK)
2701						goto cont;
2702				} else {
2703					if (com->tp == NULL
2704					    || com->tp->t_iflag & IGNPAR)
2705						goto cont;
2706				}
2707				if (com->tp->t_state & TS_CAN_BYPASS_L_RINT
2708				    && (line_status & (LSR_BI | LSR_FE)
2709					|| com->tp->t_iflag & INPCK))
2710					recv_data = 0;
2711			}
2712			++com->bytes_in;
2713			if (com->hotchar != 0 && recv_data == com->hotchar)
2714				swi_sched(sio_fast_ih, 0);
2715			ioptr = com->iptr;
2716			if (ioptr >= com->ibufend)
2717				CE_RECORD(com, CE_INTERRUPT_BUF_OVERFLOW);
2718			else {
2719				if (com->do_timestamp)
2720					microtime(&com->timestamp);
2721				++com_events;
2722				swi_sched(sio_slow_ih, SWI_DELAY);
2723#if 0 /* for testing input latency vs efficiency */
2724if (com->iptr - com->ibuf == 8)
2725	swi_sched(sio_fast_ih, 0);
2726#endif
2727				ioptr[0] = recv_data;
2728				ioptr[com->ierroff] = line_status;
2729				com->iptr = ++ioptr;
2730				if (ioptr == com->ihighwater
2731				    && com->state & CS_RTS_IFLOW)
2732#ifdef PC98
2733					IS_8251(com->pc98_if_type) ?
2734						com_tiocm_bic(com, TIOCM_RTS) :
2735#endif
2736					outb(com->modem_ctl_port,
2737					     com->mcr_image &= ~MCR_RTS);
2738				if (line_status & LSR_OE)
2739					CE_RECORD(com, CE_OVERRUN);
2740			}
2741cont:
2742			if (line_status & LSR_TXRDY
2743			    && com->state >= (CS_BUSY | CS_TTGO | CS_ODEVREADY))
2744				goto txrdy;
2745
2746			/*
2747			 * "& 0x7F" is to avoid the gcc-1.40 generating a slow
2748			 * jump from the top of the loop to here
2749			 */
2750#ifdef PC98
2751			if (IS_8251(com->pc98_if_type))
2752				goto status_read;
2753			else
2754#endif
2755			line_status = inb(com->line_status_port) & 0x7F;
2756#ifdef PC98
2757			if (com->pc98_if_type == COM_IF_RSA98III)
2758				rsa_buf_status = inb(com->rsabase + rsa_srr);
2759#endif /* PC98 */
2760		}
2761
2762		/* modem status change? (always check before doing output) */
2763#ifdef PC98
2764		if (!IS_8251(com->pc98_if_type)) {
2765#endif
2766		modem_status = inb(com->modem_status_port);
2767		if (modem_status != com->last_modem_status) {
2768			if (com->do_dcd_timestamp
2769			    && !(com->last_modem_status & MSR_DCD)
2770			    && modem_status & MSR_DCD)
2771				microtime(&com->dcd_timestamp);
2772
2773			/*
2774			 * Schedule high level to handle DCD changes.  Note
2775			 * that we don't use the delta bits anywhere.  Some
2776			 * UARTs mess them up, and it's easy to remember the
2777			 * previous bits and calculate the delta.
2778			 */
2779			com->last_modem_status = modem_status;
2780			if (!(com->state & CS_CHECKMSR)) {
2781				com_events += LOTS_OF_EVENTS;
2782				com->state |= CS_CHECKMSR;
2783				swi_sched(sio_fast_ih, 0);
2784			}
2785
2786			/* handle CTS change immediately for crisp flow ctl */
2787			if (com->state & CS_CTS_OFLOW) {
2788				if (modem_status & MSR_CTS)
2789					com->state |= CS_ODEVREADY;
2790				else
2791					com->state &= ~CS_ODEVREADY;
2792			}
2793		}
2794#ifdef PC98
2795		}
2796#endif
2797
2798txrdy:
2799		/* output queued and everything ready? */
2800#ifndef PC98
2801		if (line_status & LSR_TXRDY
2802		    && com->state >= (CS_BUSY | CS_TTGO | CS_ODEVREADY)) {
2803#else
2804		if (((com->pc98_if_type == COM_IF_RSA98III)
2805		     ? (rsa_buf_status & 0x02)
2806		     : (line_status & LSR_TXRDY))
2807		    && com->state >= (CS_BUSY | CS_TTGO | CS_ODEVREADY)) {
2808#endif
2809#ifdef PC98
2810			Port_t	tmp_data_port;
2811
2812			if (IS_8251(com->pc98_if_type) &&
2813			    com->pc98_8251fifo_enable)
2814				tmp_data_port = I8251F_data;
2815			else
2816				tmp_data_port = com->data_port;
2817#endif
2818
2819			ioptr = com->obufq.l_head;
2820			if (com->tx_fifo_size > 1 && com->unit != siotsunit) {
2821				u_int	ocount;
2822
2823				ocount = com->obufq.l_tail - ioptr;
2824#ifdef PC98
2825				if (com->pc98_if_type == COM_IF_RSA98III) {
2826				  rsa_buf_status = inb(com->rsabase + rsa_srr);
2827				  rsa_tx_fifo_size = 1024;
2828				  if (!(rsa_buf_status & 0x01))
2829				      rsa_tx_fifo_size = 2048;
2830				  if (ocount > rsa_tx_fifo_size)
2831				      ocount = rsa_tx_fifo_size;
2832				} else
2833#endif
2834				if (ocount > com->tx_fifo_size)
2835					ocount = com->tx_fifo_size;
2836				com->bytes_out += ocount;
2837				do
2838#ifdef PC98
2839					outb(tmp_data_port, *ioptr++);
2840#else
2841					outb(com->data_port, *ioptr++);
2842#endif
2843				while (--ocount != 0);
2844			} else {
2845#ifdef PC98
2846				outb(tmp_data_port, *ioptr++);
2847#else
2848				outb(com->data_port, *ioptr++);
2849#endif
2850				++com->bytes_out;
2851				if (com->unit == siotsunit
2852				    && siotso < sizeof siots / sizeof siots[0])
2853					nanouptime(&siots[siotso++]);
2854			}
2855#ifdef PC98
2856			if (IS_8251(com->pc98_if_type))
2857			    if (!(pc98_check_i8251_interrupt(com) & IEN_TxFLAG))
2858				com_int_Tx_enable(com);
2859#endif
2860			com->obufq.l_head = ioptr;
2861			if (COM_IIR_TXRDYBUG(com->flags))
2862				int_ctl_new = int_ctl | IER_ETXRDY;
2863			if (ioptr >= com->obufq.l_tail) {
2864				struct lbq	*qp;
2865
2866				qp = com->obufq.l_next;
2867				qp->l_queued = FALSE;
2868				qp = qp->l_next;
2869				if (qp != NULL) {
2870					com->obufq.l_head = qp->l_head;
2871					com->obufq.l_tail = qp->l_tail;
2872					com->obufq.l_next = qp;
2873				} else {
2874					/* output just completed */
2875					if (COM_IIR_TXRDYBUG(com->flags))
2876						int_ctl_new = int_ctl
2877							      & ~IER_ETXRDY;
2878					com->state &= ~CS_BUSY;
2879#if defined(PC98)
2880					if (IS_8251(com->pc98_if_type) &&
2881					    pc98_check_i8251_interrupt(com) & IEN_TxFLAG)
2882						com_int_Tx_disable(com);
2883#endif
2884				}
2885				if (!(com->state & CS_ODONE)) {
2886					com_events += LOTS_OF_EVENTS;
2887					com->state |= CS_ODONE;
2888					/* handle at high level ASAP */
2889					swi_sched(sio_fast_ih, 0);
2890				}
2891			}
2892#ifdef PC98
2893			if (COM_IIR_TXRDYBUG(com->flags)
2894			    && int_ctl != int_ctl_new) {
2895				if (com->pc98_if_type == COM_IF_RSA98III) {
2896				    int_ctl_new &= ~(IER_ETXRDY | IER_ERXRDY);
2897				    outb(com->int_ctl_port, int_ctl_new);
2898				    outb(com->rsabase + rsa_ier, 0x1d);
2899				} else
2900				    outb(com->int_ctl_port, int_ctl_new);
2901			}
2902#else
2903			if (COM_IIR_TXRDYBUG(com->flags)
2904			    && int_ctl != int_ctl_new)
2905				outb(com->int_ctl_port, int_ctl_new);
2906#endif
2907		}
2908#ifdef PC98
2909		else if (line_status & LSR_TXRDY) {
2910		    if (IS_8251(com->pc98_if_type))
2911			if (pc98_check_i8251_interrupt(com) & IEN_TxFLAG)
2912			    com_int_Tx_disable(com);
2913		}
2914		if (IS_8251(com->pc98_if_type)) {
2915		    if (com->pc98_8251fifo_enable) {
2916			if ((tmp = inb(I8251F_lsr)) & STS8251F_RxRDY)
2917			    goto more_intr;
2918		    } else {
2919			if ((tmp = inb(com->sts_port)) & STS8251_RxRDY)
2920			    goto more_intr;
2921		    }
2922		}
2923#endif
2924
2925		/* finished? */
2926#ifndef COM_MULTIPORT
2927#ifdef PC98
2928		if (IS_8251(com->pc98_if_type))
2929			return;
2930#endif
2931		if ((inb(com->int_id_port) & IIR_IMASK) == IIR_NOPEND)
2932#endif /* COM_MULTIPORT */
2933			return;
2934	}
2935}
2936
2937static int
2938sioioctl(dev, cmd, data, flag, td)
2939	dev_t		dev;
2940	u_long		cmd;
2941	caddr_t		data;
2942	int		flag;
2943	struct thread	*td;
2944{
2945	struct com_s	*com;
2946	int		error;
2947	int		mynor;
2948	int		s;
2949	struct tty	*tp;
2950#if defined(COMPAT_43) || defined(COMPAT_SUNOS)
2951	u_long		oldcmd;
2952	struct termios	term;
2953#endif
2954
2955	mynor = minor(dev);
2956	com = com_addr(MINOR_TO_UNIT(mynor));
2957	if (com == NULL || com->gone)
2958		return (ENODEV);
2959	if (mynor & CONTROL_MASK) {
2960		struct termios	*ct;
2961
2962		switch (mynor & CONTROL_MASK) {
2963		case CONTROL_INIT_STATE:
2964			ct = mynor & CALLOUT_MASK ? &com->it_out : &com->it_in;
2965			break;
2966		case CONTROL_LOCK_STATE:
2967			ct = mynor & CALLOUT_MASK ? &com->lt_out : &com->lt_in;
2968			break;
2969		default:
2970			return (ENODEV);	/* /dev/nodev */
2971		}
2972		switch (cmd) {
2973		case TIOCSETA:
2974			error = suser(td);
2975			if (error != 0)
2976				return (error);
2977			*ct = *(struct termios *)data;
2978			return (0);
2979		case TIOCGETA:
2980			*(struct termios *)data = *ct;
2981			return (0);
2982		case TIOCGETD:
2983			*(int *)data = TTYDISC;
2984			return (0);
2985		case TIOCGWINSZ:
2986			bzero(data, sizeof(struct winsize));
2987			return (0);
2988		default:
2989			return (ENOTTY);
2990		}
2991	}
2992	tp = com->tp;
2993#if defined(COMPAT_43) || defined(COMPAT_SUNOS)
2994	term = tp->t_termios;
2995	oldcmd = cmd;
2996	error = ttsetcompat(tp, &cmd, data, &term);
2997	if (error != 0)
2998		return (error);
2999	if (cmd != oldcmd)
3000		data = (caddr_t)&term;
3001#endif
3002	if (cmd == TIOCSETA || cmd == TIOCSETAW || cmd == TIOCSETAF) {
3003		int	cc;
3004		struct termios *dt = (struct termios *)data;
3005		struct termios *lt = mynor & CALLOUT_MASK
3006				     ? &com->lt_out : &com->lt_in;
3007
3008		dt->c_iflag = (tp->t_iflag & lt->c_iflag)
3009			      | (dt->c_iflag & ~lt->c_iflag);
3010		dt->c_oflag = (tp->t_oflag & lt->c_oflag)
3011			      | (dt->c_oflag & ~lt->c_oflag);
3012		dt->c_cflag = (tp->t_cflag & lt->c_cflag)
3013			      | (dt->c_cflag & ~lt->c_cflag);
3014		dt->c_lflag = (tp->t_lflag & lt->c_lflag)
3015			      | (dt->c_lflag & ~lt->c_lflag);
3016		for (cc = 0; cc < NCCS; ++cc)
3017			if (lt->c_cc[cc] != 0)
3018				dt->c_cc[cc] = tp->t_cc[cc];
3019		if (lt->c_ispeed != 0)
3020			dt->c_ispeed = tp->t_ispeed;
3021		if (lt->c_ospeed != 0)
3022			dt->c_ospeed = tp->t_ospeed;
3023	}
3024	error = (*linesw[tp->t_line].l_ioctl)(tp, cmd, data, flag, td);
3025	if (error != ENOIOCTL)
3026		return (error);
3027	s = spltty();
3028	error = ttioctl(tp, cmd, data, flag);
3029	disc_optim(tp, &tp->t_termios, com);
3030	if (error != ENOIOCTL) {
3031		splx(s);
3032		return (error);
3033	}
3034#ifdef PC98
3035	if (IS_8251(com->pc98_if_type)) {
3036	    switch (cmd) {
3037	    case TIOCSBRK:
3038		com_send_break_on(com);
3039		break;
3040	    case TIOCCBRK:
3041		com_send_break_off(com);
3042		break;
3043	    case TIOCSDTR:
3044		com_tiocm_bis(com, TIOCM_DTR | TIOCM_RTS);
3045		break;
3046	    case TIOCCDTR:
3047		com_tiocm_bic(com, TIOCM_DTR);
3048		break;
3049	/*
3050	 * XXX should disallow changing MCR_RTS if CS_RTS_IFLOW is set.  The
3051	 * changes get undone on the next call to comparam().
3052	 */
3053	    case TIOCMSET:
3054		com_tiocm_set(com, *(int *)data);
3055		break;
3056	    case TIOCMBIS:
3057		com_tiocm_bis(com, *(int *)data);
3058		break;
3059	    case TIOCMBIC:
3060		com_tiocm_bic(com, *(int *)data);
3061		break;
3062	    case TIOCMGET:
3063		*(int *)data = com_tiocm_get(com);
3064		break;
3065	    case TIOCMSDTRWAIT:
3066		/* must be root since the wait applies to following logins */
3067		error = suser(td);
3068		if (error != 0) {
3069			splx(s);
3070			return (error);
3071		}
3072		com->dtr_wait = *(int *)data * hz / 100;
3073		break;
3074	    case TIOCMGDTRWAIT:
3075		*(int *)data = com->dtr_wait * 100 / hz;
3076		break;
3077	    case TIOCTIMESTAMP:
3078		com->do_timestamp = TRUE;
3079		*(struct timeval *)data = com->timestamp;
3080		break;
3081	    case TIOCDCDTIMESTAMP:
3082		com->do_dcd_timestamp = TRUE;
3083		*(struct timeval *)data = com->dcd_timestamp;
3084		break;
3085	    default:
3086		splx(s);
3087		error = pps_ioctl(cmd, data, &com->pps);
3088		if (error == ENODEV)
3089			error = ENOTTY;
3090		return (error);
3091	    }
3092	} else {
3093#endif
3094	switch (cmd) {
3095	case TIOCSBRK:
3096		sio_setreg(com, com_cfcr, com->cfcr_image |= CFCR_SBREAK);
3097		break;
3098	case TIOCCBRK:
3099		sio_setreg(com, com_cfcr, com->cfcr_image &= ~CFCR_SBREAK);
3100		break;
3101	case TIOCSDTR:
3102		(void)commctl(com, TIOCM_DTR, DMBIS);
3103		break;
3104	case TIOCCDTR:
3105		(void)commctl(com, TIOCM_DTR, DMBIC);
3106		break;
3107	/*
3108	 * XXX should disallow changing MCR_RTS if CS_RTS_IFLOW is set.  The
3109	 * changes get undone on the next call to comparam().
3110	 */
3111	case TIOCMSET:
3112		(void)commctl(com, *(int *)data, DMSET);
3113		break;
3114	case TIOCMBIS:
3115		(void)commctl(com, *(int *)data, DMBIS);
3116		break;
3117	case TIOCMBIC:
3118		(void)commctl(com, *(int *)data, DMBIC);
3119		break;
3120	case TIOCMGET:
3121		*(int *)data = commctl(com, 0, DMGET);
3122		break;
3123	case TIOCMSDTRWAIT:
3124		/* must be root since the wait applies to following logins */
3125		error = suser(td);
3126		if (error != 0) {
3127			splx(s);
3128			return (error);
3129		}
3130		com->dtr_wait = *(int *)data * hz / 100;
3131		break;
3132	case TIOCMGDTRWAIT:
3133		*(int *)data = com->dtr_wait * 100 / hz;
3134		break;
3135	case TIOCTIMESTAMP:
3136		com->do_timestamp = TRUE;
3137		*(struct timeval *)data = com->timestamp;
3138		break;
3139	case TIOCDCDTIMESTAMP:
3140		com->do_dcd_timestamp = TRUE;
3141		*(struct timeval *)data = com->dcd_timestamp;
3142		break;
3143	default:
3144		splx(s);
3145		error = pps_ioctl(cmd, data, &com->pps);
3146		if (error == ENODEV)
3147			error = ENOTTY;
3148		return (error);
3149	}
3150#ifdef PC98
3151	}
3152#endif
3153	splx(s);
3154	return (0);
3155}
3156
3157/* software interrupt handler for SWI_TTY */
3158static void
3159siopoll(void *dummy)
3160{
3161	int		unit;
3162
3163	if (com_events == 0)
3164		return;
3165repeat:
3166	for (unit = 0; unit < sio_numunits; ++unit) {
3167		struct com_s	*com;
3168		int		incc;
3169		struct tty	*tp;
3170
3171		com = com_addr(unit);
3172		if (com == NULL)
3173			continue;
3174		tp = com->tp;
3175		if (tp == NULL || com->gone) {
3176			/*
3177			 * Discard any events related to never-opened or
3178			 * going-away devices.
3179			 */
3180			mtx_lock_spin(&sio_lock);
3181			incc = com->iptr - com->ibuf;
3182			com->iptr = com->ibuf;
3183			if (com->state & CS_CHECKMSR) {
3184				incc += LOTS_OF_EVENTS;
3185				com->state &= ~CS_CHECKMSR;
3186			}
3187			com_events -= incc;
3188			mtx_unlock_spin(&sio_lock);
3189			continue;
3190		}
3191		if (com->iptr != com->ibuf) {
3192			mtx_lock_spin(&sio_lock);
3193			sioinput(com);
3194			mtx_unlock_spin(&sio_lock);
3195		}
3196		if (com->state & CS_CHECKMSR) {
3197			u_char	delta_modem_status;
3198
3199#ifdef PC98
3200			if (!IS_8251(com->pc98_if_type)) {
3201#endif
3202			mtx_lock_spin(&sio_lock);
3203			delta_modem_status = com->last_modem_status
3204					     ^ com->prev_modem_status;
3205			com->prev_modem_status = com->last_modem_status;
3206			com_events -= LOTS_OF_EVENTS;
3207			com->state &= ~CS_CHECKMSR;
3208			mtx_unlock_spin(&sio_lock);
3209			if (delta_modem_status & MSR_DCD)
3210				(*linesw[tp->t_line].l_modem)
3211					(tp, com->prev_modem_status & MSR_DCD);
3212#ifdef PC98
3213			}
3214#endif
3215		}
3216		if (com->state & CS_ODONE) {
3217			mtx_lock_spin(&sio_lock);
3218			com_events -= LOTS_OF_EVENTS;
3219			com->state &= ~CS_ODONE;
3220			mtx_unlock_spin(&sio_lock);
3221			if (!(com->state & CS_BUSY)
3222			    && !(com->extra_state & CSE_BUSYCHECK)) {
3223				timeout(siobusycheck, com, hz / 100);
3224				com->extra_state |= CSE_BUSYCHECK;
3225			}
3226			(*linesw[tp->t_line].l_start)(tp);
3227		}
3228		if (com_events == 0)
3229			break;
3230	}
3231	if (com_events >= LOTS_OF_EVENTS)
3232		goto repeat;
3233}
3234
3235static int
3236comparam(tp, t)
3237	struct tty	*tp;
3238	struct termios	*t;
3239{
3240	u_int		cfcr;
3241	int		cflag;
3242	struct com_s	*com;
3243	u_int		divisor;
3244	u_char		dlbh;
3245	u_char		dlbl;
3246	u_char		efr_flowbits;
3247	int		s;
3248	int		unit;
3249#ifdef PC98
3250	u_char		param = 0;
3251#endif
3252
3253	unit = DEV_TO_UNIT(tp->t_dev);
3254	com = com_addr(unit);
3255	if (com == NULL)
3256		return (ENODEV);
3257
3258#ifdef PC98
3259	cfcr = 0;
3260
3261	if (IS_8251(com->pc98_if_type)) {
3262		if (pc98_ttspeedtab(com, t->c_ospeed, &divisor) != 0)
3263			return (EINVAL);
3264	} else {
3265#endif
3266	/* check requested parameters */
3267	if (t->c_ispeed != (t->c_ospeed != 0 ? t->c_ospeed : tp->t_ospeed))
3268		return (EINVAL);
3269	divisor = siodivisor(com->rclk, t->c_ispeed);
3270	if (divisor == 0)
3271		return (EINVAL);
3272#ifdef PC98
3273	}
3274#endif
3275
3276	/* parameters are OK, convert them to the com struct and the device */
3277	s = spltty();
3278#ifdef PC98
3279	if (IS_8251(com->pc98_if_type)) {
3280		if (t->c_ospeed == 0)
3281			com_tiocm_bic(com, TIOCM_DTR|TIOCM_RTS|TIOCM_LE);
3282		else
3283			com_tiocm_bis(com, TIOCM_DTR|TIOCM_RTS|TIOCM_LE);
3284	} else
3285#endif
3286	if (t->c_ospeed == 0)
3287		(void)commctl(com, TIOCM_DTR, DMBIC);	/* hang up line */
3288	else
3289		(void)commctl(com, TIOCM_DTR, DMBIS);
3290	cflag = t->c_cflag;
3291#ifdef PC98
3292	if (!IS_8251(com->pc98_if_type)) {
3293#endif
3294	switch (cflag & CSIZE) {
3295	case CS5:
3296		cfcr = CFCR_5BITS;
3297		break;
3298	case CS6:
3299		cfcr = CFCR_6BITS;
3300		break;
3301	case CS7:
3302		cfcr = CFCR_7BITS;
3303		break;
3304	default:
3305		cfcr = CFCR_8BITS;
3306		break;
3307	}
3308	if (cflag & PARENB) {
3309		cfcr |= CFCR_PENAB;
3310		if (!(cflag & PARODD))
3311			cfcr |= CFCR_PEVEN;
3312	}
3313	if (cflag & CSTOPB)
3314		cfcr |= CFCR_STOPB;
3315
3316	if (com->hasfifo) {
3317		/*
3318		 * Use a fifo trigger level low enough so that the input
3319		 * latency from the fifo is less than about 16 msec and
3320		 * the total latency is less than about 30 msec.  These
3321		 * latencies are reasonable for humans.  Serial comms
3322		 * protocols shouldn't expect anything better since modem
3323		 * latencies are larger.
3324		 *
3325		 * The fifo trigger level cannot be set at RX_HIGH for high
3326		 * speed connections without further work on reducing
3327		 * interrupt disablement times in other parts of the system,
3328		 * without producing silo overflow errors.
3329		 */
3330		com->fifo_image = com->unit == siotsunit ? 0
3331				  : t->c_ispeed <= 4800
3332				  ? FIFO_ENABLE : FIFO_ENABLE | FIFO_RX_MEDH;
3333#ifdef COM_ESP
3334		/*
3335		 * The Hayes ESP card needs the fifo DMA mode bit set
3336		 * in compatibility mode.  If not, it will interrupt
3337		 * for each character received.
3338		 */
3339		if (com->esp)
3340			com->fifo_image |= FIFO_DMA_MODE;
3341#endif
3342		sio_setreg(com, com_fifo, com->fifo_image);
3343	}
3344#ifdef PC98
3345	}
3346#endif
3347
3348	/*
3349	 * This returns with interrupts disabled so that we can complete
3350	 * the speed change atomically.  Keeping interrupts disabled is
3351	 * especially important while com_data is hidden.
3352	 */
3353	(void) siosetwater(com, t->c_ispeed);
3354
3355#ifdef PC98
3356	if (IS_8251(com->pc98_if_type))
3357		com_cflag_and_speed_set(com, cflag, t->c_ospeed);
3358	else {
3359#endif
3360	sio_setreg(com, com_cfcr, cfcr | CFCR_DLAB);
3361	/*
3362	 * Only set the divisor registers if they would change, since on
3363	 * some 16550 incompatibles (UMC8669F), setting them while input
3364	 * is arriving loses sync until data stops arriving.
3365	 */
3366	dlbl = divisor & 0xFF;
3367	if (sio_getreg(com, com_dlbl) != dlbl)
3368		sio_setreg(com, com_dlbl, dlbl);
3369	dlbh = divisor >> 8;
3370	if (sio_getreg(com, com_dlbh) != dlbh)
3371		sio_setreg(com, com_dlbh, dlbh);
3372#ifdef PC98
3373	}
3374#endif
3375
3376	efr_flowbits = 0;
3377
3378	if (cflag & CRTS_IFLOW) {
3379		com->state |= CS_RTS_IFLOW;
3380		efr_flowbits |= EFR_AUTORTS;
3381		/*
3382		 * If CS_RTS_IFLOW just changed from off to on, the change
3383		 * needs to be propagated to MCR_RTS.  This isn't urgent,
3384		 * so do it later by calling comstart() instead of repeating
3385		 * a lot of code from comstart() here.
3386		 */
3387	} else if (com->state & CS_RTS_IFLOW) {
3388		com->state &= ~CS_RTS_IFLOW;
3389		/*
3390		 * CS_RTS_IFLOW just changed from on to off.  Force MCR_RTS
3391		 * on here, since comstart() won't do it later.
3392		 */
3393#ifdef PC98
3394		if (IS_8251(com->pc98_if_type))
3395			com_tiocm_bis(com, TIOCM_RTS);
3396		else
3397			outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
3398#else
3399		outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
3400#endif
3401	}
3402
3403	/*
3404	 * Set up state to handle output flow control.
3405	 * XXX - worth handling MDMBUF (DCD) flow control at the lowest level?
3406	 * Now has 10+ msec latency, while CTS flow has 50- usec latency.
3407	 */
3408	com->state |= CS_ODEVREADY;
3409	com->state &= ~CS_CTS_OFLOW;
3410#ifdef PC98
3411	if (com->pc98_if_type == COM_IF_RSA98III) {
3412		param = inb(com->rsabase + rsa_msr);
3413		outb(com->rsabase + rsa_msr, param & 0x14);
3414	}
3415#endif
3416	if (cflag & CCTS_OFLOW) {
3417		com->state |= CS_CTS_OFLOW;
3418		efr_flowbits |= EFR_AUTOCTS;
3419#ifdef PC98
3420		if (IS_8251(com->pc98_if_type)) {
3421			if (!(pc98_get_modem_status(com) & TIOCM_CTS))
3422				com->state &= ~CS_ODEVREADY;
3423		} else if (com->pc98_if_type == COM_IF_RSA98III) {
3424			/* Set automatic flow control mode */
3425			outb(com->rsabase + rsa_msr, param | 0x08);
3426		} else
3427#endif
3428		if (!(com->last_modem_status & MSR_CTS))
3429			com->state &= ~CS_ODEVREADY;
3430	}
3431
3432#ifdef PC98
3433	if (!IS_8251(com->pc98_if_type))
3434		sio_setreg(com, com_cfcr, com->cfcr_image = cfcr);
3435#else
3436	if (com->st16650a) {
3437		sio_setreg(com, com_lcr, LCR_EFR_ENABLE);
3438		sio_setreg(com, com_efr,
3439			   (sio_getreg(com, com_efr)
3440			    & ~(EFR_AUTOCTS | EFR_AUTORTS)) | efr_flowbits);
3441	}
3442	sio_setreg(com, com_cfcr, com->cfcr_image = cfcr);
3443#endif
3444
3445	/* XXX shouldn't call functions while intrs are disabled. */
3446	disc_optim(tp, t, com);
3447
3448	mtx_unlock_spin(&sio_lock);
3449	splx(s);
3450	comstart(tp);
3451	if (com->ibufold != NULL) {
3452		free(com->ibufold, M_DEVBUF);
3453		com->ibufold = NULL;
3454	}
3455	return (0);
3456}
3457
3458/*
3459 * This function must be called with the sio_lock mutex released and will
3460 * return with it obtained.
3461 */
3462static int
3463siosetwater(com, speed)
3464	struct com_s	*com;
3465	speed_t		speed;
3466{
3467	int		cp4ticks;
3468	u_char		*ibuf;
3469	int		ibufsize;
3470	struct tty	*tp;
3471
3472	/*
3473	 * Make the buffer size large enough to handle a softtty interrupt
3474	 * latency of about 2 ticks without loss of throughput or data
3475	 * (about 3 ticks if input flow control is not used or not honoured,
3476	 * but a bit less for CS5-CS7 modes).
3477	 */
3478	cp4ticks = speed / 10 / hz * 4;
3479	for (ibufsize = 128; ibufsize < cp4ticks;)
3480		ibufsize <<= 1;
3481#ifdef PC98
3482	if (com->pc98_if_type == COM_IF_RSA98III)
3483		ibufsize = 2048;
3484#endif
3485	if (ibufsize == com->ibufsize) {
3486		mtx_lock_spin(&sio_lock);
3487		return (0);
3488	}
3489
3490	/*
3491	 * Allocate input buffer.  The extra factor of 2 in the size is
3492	 * to allow for an error byte for each input byte.
3493	 */
3494	ibuf = malloc(2 * ibufsize, M_DEVBUF, M_NOWAIT);
3495	if (ibuf == NULL) {
3496		mtx_lock_spin(&sio_lock);
3497		return (ENOMEM);
3498	}
3499
3500	/* Initialize non-critical variables. */
3501	com->ibufold = com->ibuf;
3502	com->ibufsize = ibufsize;
3503	tp = com->tp;
3504	if (tp != NULL) {
3505		tp->t_ififosize = 2 * ibufsize;
3506		tp->t_ispeedwat = (speed_t)-1;
3507		tp->t_ospeedwat = (speed_t)-1;
3508	}
3509
3510	/*
3511	 * Read current input buffer, if any.  Continue with interrupts
3512	 * disabled.
3513	 */
3514	mtx_lock_spin(&sio_lock);
3515	if (com->iptr != com->ibuf)
3516		sioinput(com);
3517
3518	/*-
3519	 * Initialize critical variables, including input buffer watermarks.
3520	 * The external device is asked to stop sending when the buffer
3521	 * exactly reaches high water, or when the high level requests it.
3522	 * The high level is notified immediately (rather than at a later
3523	 * clock tick) when this watermark is reached.
3524	 * The buffer size is chosen so the watermark should almost never
3525	 * be reached.
3526	 * The low watermark is invisibly 0 since the buffer is always
3527	 * emptied all at once.
3528	 */
3529	com->iptr = com->ibuf = ibuf;
3530	com->ibufend = ibuf + ibufsize;
3531	com->ierroff = ibufsize;
3532	com->ihighwater = ibuf + 3 * ibufsize / 4;
3533	return (0);
3534}
3535
3536static void
3537comstart(tp)
3538	struct tty	*tp;
3539{
3540	struct com_s	*com;
3541	int		s;
3542	int		unit;
3543
3544	unit = DEV_TO_UNIT(tp->t_dev);
3545	com = com_addr(unit);
3546	if (com == NULL)
3547		return;
3548	s = spltty();
3549	mtx_lock_spin(&sio_lock);
3550	if (tp->t_state & TS_TTSTOP)
3551		com->state &= ~CS_TTGO;
3552	else
3553		com->state |= CS_TTGO;
3554	if (tp->t_state & TS_TBLOCK) {
3555#ifdef PC98
3556		if (IS_8251(com->pc98_if_type)) {
3557		    if ((com_tiocm_get(com) & TIOCM_RTS) &&
3558			(com->state & CS_RTS_IFLOW))
3559			com_tiocm_bic(com, TIOCM_RTS);
3560		} else {
3561		    if ((com->mcr_image & MCR_RTS) &&
3562			(com->state & CS_RTS_IFLOW))
3563			outb(com->modem_ctl_port, com->mcr_image &= ~MCR_RTS);
3564		}
3565#else
3566		if (com->mcr_image & MCR_RTS && com->state & CS_RTS_IFLOW)
3567			outb(com->modem_ctl_port, com->mcr_image &= ~MCR_RTS);
3568#endif
3569	} else {
3570#ifdef PC98
3571		if (IS_8251(com->pc98_if_type)) {
3572		    if (!(com_tiocm_get(com) & TIOCM_RTS) &&
3573			com->iptr < com->ihighwater &&
3574			com->state & CS_RTS_IFLOW)
3575			com_tiocm_bis(com, TIOCM_RTS);
3576		} else {
3577		    if (!(com->mcr_image & MCR_RTS) &&
3578			com->iptr < com->ihighwater &&
3579			com->state & CS_RTS_IFLOW)
3580			outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
3581		}
3582#else
3583		if (!(com->mcr_image & MCR_RTS) && com->iptr < com->ihighwater
3584		    && com->state & CS_RTS_IFLOW)
3585			outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
3586#endif
3587	}
3588	mtx_unlock_spin(&sio_lock);
3589	if (tp->t_state & (TS_TIMEOUT | TS_TTSTOP)) {
3590		ttwwakeup(tp);
3591		splx(s);
3592		return;
3593	}
3594	if (tp->t_outq.c_cc != 0) {
3595		struct lbq	*qp;
3596		struct lbq	*next;
3597
3598		if (!com->obufs[0].l_queued) {
3599			com->obufs[0].l_tail
3600			    = com->obuf1 + q_to_b(&tp->t_outq, com->obuf1,
3601#ifdef PC98
3602						  com->obufsize);
3603#else
3604						  sizeof com->obuf1);
3605#endif
3606			com->obufs[0].l_next = NULL;
3607			com->obufs[0].l_queued = TRUE;
3608			mtx_lock_spin(&sio_lock);
3609			if (com->state & CS_BUSY) {
3610				qp = com->obufq.l_next;
3611				while ((next = qp->l_next) != NULL)
3612					qp = next;
3613				qp->l_next = &com->obufs[0];
3614			} else {
3615				com->obufq.l_head = com->obufs[0].l_head;
3616				com->obufq.l_tail = com->obufs[0].l_tail;
3617				com->obufq.l_next = &com->obufs[0];
3618				com->state |= CS_BUSY;
3619			}
3620			mtx_unlock_spin(&sio_lock);
3621		}
3622		if (tp->t_outq.c_cc != 0 && !com->obufs[1].l_queued) {
3623			com->obufs[1].l_tail
3624			    = com->obuf2 + q_to_b(&tp->t_outq, com->obuf2,
3625#ifdef PC98
3626						  com->obufsize);
3627#else
3628						  sizeof com->obuf2);
3629#endif
3630			com->obufs[1].l_next = NULL;
3631			com->obufs[1].l_queued = TRUE;
3632			mtx_lock_spin(&sio_lock);
3633			if (com->state & CS_BUSY) {
3634				qp = com->obufq.l_next;
3635				while ((next = qp->l_next) != NULL)
3636					qp = next;
3637				qp->l_next = &com->obufs[1];
3638			} else {
3639				com->obufq.l_head = com->obufs[1].l_head;
3640				com->obufq.l_tail = com->obufs[1].l_tail;
3641				com->obufq.l_next = &com->obufs[1];
3642				com->state |= CS_BUSY;
3643			}
3644			mtx_unlock_spin(&sio_lock);
3645		}
3646		tp->t_state |= TS_BUSY;
3647	}
3648	mtx_lock_spin(&sio_lock);
3649	if (com->state >= (CS_BUSY | CS_TTGO))
3650		siointr1(com);	/* fake interrupt to start output */
3651	mtx_unlock_spin(&sio_lock);
3652	ttwwakeup(tp);
3653	splx(s);
3654}
3655
3656static void
3657comstop(tp, rw)
3658	struct tty	*tp;
3659	int		rw;
3660{
3661	struct com_s	*com;
3662#ifdef PC98
3663	int		rsa98_tmp  = 0;
3664#endif
3665
3666	com = com_addr(DEV_TO_UNIT(tp->t_dev));
3667	if (com == NULL || com->gone)
3668		return;
3669	mtx_lock_spin(&sio_lock);
3670	if (rw & FWRITE) {
3671#ifdef PC98
3672		if (!IS_8251(com->pc98_if_type)) {
3673#endif
3674		if (com->hasfifo)
3675#ifdef COM_ESP
3676		    /* XXX avoid h/w bug. */
3677		    if (!com->esp)
3678#endif
3679			sio_setreg(com, com_fifo,
3680				   FIFO_XMT_RST | com->fifo_image);
3681#ifdef PC98
3682		if (com->pc98_if_type == COM_IF_RSA98III)
3683		    for (rsa98_tmp = 0; rsa98_tmp < 2048; rsa98_tmp++)
3684			sio_setreg(com, com_fifo,
3685				   FIFO_XMT_RST | com->fifo_image);
3686		}
3687#endif
3688		com->obufs[0].l_queued = FALSE;
3689		com->obufs[1].l_queued = FALSE;
3690		if (com->state & CS_ODONE)
3691			com_events -= LOTS_OF_EVENTS;
3692		com->state &= ~(CS_ODONE | CS_BUSY);
3693		com->tp->t_state &= ~TS_BUSY;
3694	}
3695	if (rw & FREAD) {
3696#ifdef PC98
3697		if (!IS_8251(com->pc98_if_type)) {
3698		    if (com->pc98_if_type == COM_IF_RSA98III)
3699			for (rsa98_tmp = 0; rsa98_tmp < 2048; rsa98_tmp++)
3700			    sio_getreg(com, com_data);
3701#endif
3702		if (com->hasfifo)
3703#ifdef COM_ESP
3704		    /* XXX avoid h/w bug. */
3705		    if (!com->esp)
3706#endif
3707			sio_setreg(com, com_fifo,
3708				   FIFO_RCV_RST | com->fifo_image);
3709#ifdef PC98
3710		}
3711#endif
3712		com_events -= (com->iptr - com->ibuf);
3713		com->iptr = com->ibuf;
3714	}
3715	mtx_unlock_spin(&sio_lock);
3716	comstart(tp);
3717}
3718
3719static int
3720commctl(com, bits, how)
3721	struct com_s	*com;
3722	int		bits;
3723	int		how;
3724{
3725	int	mcr;
3726	int	msr;
3727
3728	if (how == DMGET) {
3729		bits = TIOCM_LE;	/* XXX - always enabled while open */
3730		mcr = com->mcr_image;
3731		if (mcr & MCR_DTR)
3732			bits |= TIOCM_DTR;
3733		if (mcr & MCR_RTS)
3734			bits |= TIOCM_RTS;
3735		msr = com->prev_modem_status;
3736		if (msr & MSR_CTS)
3737			bits |= TIOCM_CTS;
3738		if (msr & MSR_DCD)
3739			bits |= TIOCM_CD;
3740		if (msr & MSR_DSR)
3741			bits |= TIOCM_DSR;
3742		/*
3743		 * XXX - MSR_RI is naturally volatile, and we make MSR_TERI
3744		 * more volatile by reading the modem status a lot.  Perhaps
3745		 * we should latch both bits until the status is read here.
3746		 */
3747		if (msr & (MSR_RI | MSR_TERI))
3748			bits |= TIOCM_RI;
3749		return (bits);
3750	}
3751	mcr = 0;
3752	if (bits & TIOCM_DTR)
3753		mcr |= MCR_DTR;
3754	if (bits & TIOCM_RTS)
3755		mcr |= MCR_RTS;
3756	if (com->gone)
3757		return(0);
3758	mtx_lock_spin(&sio_lock);
3759	switch (how) {
3760	case DMSET:
3761		outb(com->modem_ctl_port,
3762		     com->mcr_image = mcr | (com->mcr_image & MCR_IENABLE));
3763		break;
3764	case DMBIS:
3765		outb(com->modem_ctl_port, com->mcr_image |= mcr);
3766		break;
3767	case DMBIC:
3768		outb(com->modem_ctl_port, com->mcr_image &= ~mcr);
3769		break;
3770	}
3771	mtx_unlock_spin(&sio_lock);
3772	return (0);
3773}
3774
3775static void
3776siosettimeout()
3777{
3778	struct com_s	*com;
3779	bool_t		someopen;
3780	int		unit;
3781
3782	/*
3783	 * Set our timeout period to 1 second if no polled devices are open.
3784	 * Otherwise set it to max(1/200, 1/hz).
3785	 * Enable timeouts iff some device is open.
3786	 */
3787	untimeout(comwakeup, (void *)NULL, sio_timeout_handle);
3788	sio_timeout = hz;
3789	someopen = FALSE;
3790	for (unit = 0; unit < sio_numunits; ++unit) {
3791		com = com_addr(unit);
3792		if (com != NULL && com->tp != NULL
3793		    && com->tp->t_state & TS_ISOPEN && !com->gone) {
3794			someopen = TRUE;
3795			if (com->poll || com->poll_output) {
3796				sio_timeout = hz > 200 ? hz / 200 : 1;
3797				break;
3798			}
3799		}
3800	}
3801	if (someopen) {
3802		sio_timeouts_until_log = hz / sio_timeout;
3803		sio_timeout_handle = timeout(comwakeup, (void *)NULL,
3804					     sio_timeout);
3805	} else {
3806		/* Flush error messages, if any. */
3807		sio_timeouts_until_log = 1;
3808		comwakeup((void *)NULL);
3809		untimeout(comwakeup, (void *)NULL, sio_timeout_handle);
3810	}
3811}
3812
3813static void
3814comwakeup(chan)
3815	void	*chan;
3816{
3817	struct com_s	*com;
3818	int		unit;
3819
3820	sio_timeout_handle = timeout(comwakeup, (void *)NULL, sio_timeout);
3821
3822	/*
3823	 * Recover from lost output interrupts.
3824	 * Poll any lines that don't use interrupts.
3825	 */
3826	for (unit = 0; unit < sio_numunits; ++unit) {
3827		com = com_addr(unit);
3828		if (com != NULL && !com->gone
3829		    && (com->state >= (CS_BUSY | CS_TTGO) || com->poll)) {
3830			mtx_lock_spin(&sio_lock);
3831			siointr1(com);
3832			mtx_unlock_spin(&sio_lock);
3833		}
3834	}
3835
3836	/*
3837	 * Check for and log errors, but not too often.
3838	 */
3839	if (--sio_timeouts_until_log > 0)
3840		return;
3841	sio_timeouts_until_log = hz / sio_timeout;
3842	for (unit = 0; unit < sio_numunits; ++unit) {
3843		int	errnum;
3844
3845		com = com_addr(unit);
3846		if (com == NULL)
3847			continue;
3848		if (com->gone)
3849			continue;
3850		for (errnum = 0; errnum < CE_NTYPES; ++errnum) {
3851			u_int	delta;
3852			u_long	total;
3853
3854			mtx_lock_spin(&sio_lock);
3855			delta = com->delta_error_counts[errnum];
3856			com->delta_error_counts[errnum] = 0;
3857			mtx_unlock_spin(&sio_lock);
3858			if (delta == 0)
3859				continue;
3860			total = com->error_counts[errnum] += delta;
3861			log(LOG_ERR, "sio%d: %u more %s%s (total %lu)\n",
3862			    unit, delta, error_desc[errnum],
3863			    delta == 1 ? "" : "s", total);
3864		}
3865	}
3866}
3867
3868#ifdef PC98
3869/* commint is called when modem control line changes */
3870static void
3871commint(dev_t dev)
3872{
3873	register struct tty *tp;
3874	int	stat,delta;
3875	struct com_s *com;
3876	int	mynor,unit;
3877
3878	mynor = minor(dev);
3879	unit = MINOR_TO_UNIT(mynor);
3880	com = com_addr(unit);
3881	tp = com->tp;
3882
3883	stat = com_tiocm_get(com);
3884	delta = com_tiocm_get_delta(com);
3885
3886	if (com->state & CS_CTS_OFLOW) {
3887		if (stat & TIOCM_CTS)
3888			com->state |= CS_ODEVREADY;
3889		else
3890			com->state &= ~CS_ODEVREADY;
3891	}
3892	if ((delta & TIOCM_CAR) && (mynor & CALLOUT_MASK) == 0) {
3893	    if (stat & TIOCM_CAR )
3894		(void)(*linesw[tp->t_line].l_modem)(tp, 1);
3895	    else if ((*linesw[tp->t_line].l_modem)(tp, 0) == 0) {
3896		/* negate DTR, RTS */
3897		com_tiocm_bic(com, (tp->t_cflag & HUPCL) ?
3898				TIOCM_DTR|TIOCM_RTS|TIOCM_LE : TIOCM_LE );
3899		/* disable IENABLE */
3900		com_int_TxRx_disable( com );
3901	    }
3902	}
3903}
3904#endif
3905
3906static void
3907disc_optim(tp, t, com)
3908	struct tty	*tp;
3909	struct termios	*t;
3910	struct com_s	*com;
3911{
3912	if (!(t->c_iflag & (ICRNL | IGNCR | IMAXBEL | INLCR | ISTRIP | IXON))
3913	    && (!(t->c_iflag & BRKINT) || (t->c_iflag & IGNBRK))
3914	    && (!(t->c_iflag & PARMRK)
3915		|| (t->c_iflag & (IGNPAR | IGNBRK)) == (IGNPAR | IGNBRK))
3916	    && !(t->c_lflag & (ECHO | ICANON | IEXTEN | ISIG | PENDIN))
3917	    && linesw[tp->t_line].l_rint == ttyinput)
3918		tp->t_state |= TS_CAN_BYPASS_L_RINT;
3919	else
3920		tp->t_state &= ~TS_CAN_BYPASS_L_RINT;
3921	com->hotchar = linesw[tp->t_line].l_hotchar;
3922}
3923
3924/*
3925 * Following are all routines needed for SIO to act as console
3926 */
3927struct siocnstate {
3928	u_char	dlbl;
3929	u_char	dlbh;
3930	u_char	ier;
3931	u_char	cfcr;
3932	u_char	mcr;
3933};
3934
3935/*
3936 * This is a function in order to not replicate "ttyd%d" more
3937 * places than absolutely necessary.
3938 */
3939static void
3940siocnset(struct consdev *cd, int unit)
3941{
3942
3943	cd->cn_unit = unit;
3944	sprintf(cd->cn_name, "ttyd%d", unit);
3945}
3946
3947#ifndef __alpha__
3948static speed_t siocngetspeed(Port_t, u_long rclk);
3949#endif
3950static void siocnclose(struct siocnstate *sp, Port_t iobase);
3951static void siocnopen(struct siocnstate *sp, Port_t iobase, int speed);
3952static void siocntxwait(Port_t iobase);
3953
3954#ifdef __alpha__
3955int siocnattach(int port, int speed);
3956int siogdbattach(int port, int speed);
3957int siogdbgetc(void);
3958void siogdbputc(int c);
3959#else
3960static cn_probe_t siocnprobe;
3961static cn_init_t siocninit;
3962static cn_term_t siocnterm;
3963#endif
3964static cn_checkc_t siocncheckc;
3965static cn_getc_t siocngetc;
3966static cn_putc_t siocnputc;
3967
3968#ifndef __alpha__
3969CONS_DRIVER(sio, siocnprobe, siocninit, siocnterm, siocngetc, siocncheckc,
3970	    siocnputc, NULL);
3971#endif
3972
3973#if DDB > 0
3974static struct consdev gdbconsdev;
3975#endif
3976
3977static void
3978siocntxwait(iobase)
3979	Port_t	iobase;
3980{
3981	int	timo;
3982
3983	/*
3984	 * Wait for any pending transmission to finish.  Required to avoid
3985	 * the UART lockup bug when the speed is changed, and for normal
3986	 * transmits.
3987	 */
3988	timo = 100000;
3989	while ((inb(iobase + com_lsr) & (LSR_TSRE | LSR_TXRDY))
3990	       != (LSR_TSRE | LSR_TXRDY) && --timo != 0)
3991		;
3992}
3993
3994#ifndef __alpha__
3995
3996/*
3997 * Read the serial port specified and try to figure out what speed
3998 * it's currently running at.  We're assuming the serial port has
3999 * been initialized and is basicly idle.  This routine is only intended
4000 * to be run at system startup.
4001 *
4002 * If the value read from the serial port doesn't make sense, return 0.
4003 */
4004
4005static speed_t
4006siocngetspeed(iobase, rclk)
4007	Port_t	iobase;
4008	u_long	rclk;
4009{
4010	u_int	divisor;
4011	u_char	dlbh;
4012	u_char	dlbl;
4013	u_char  cfcr;
4014
4015	cfcr = inb(iobase + com_cfcr);
4016	outb(iobase + com_cfcr, CFCR_DLAB | cfcr);
4017
4018	dlbl = inb(iobase + com_dlbl);
4019	dlbh = inb(iobase + com_dlbh);
4020
4021	outb(iobase + com_cfcr, cfcr);
4022
4023	divisor = dlbh << 8 | dlbl;
4024
4025	/* XXX there should be more sanity checking. */
4026	if (divisor == 0)
4027		return (CONSPEED);
4028	return (rclk / (16UL * divisor));
4029}
4030
4031#endif
4032
4033static void
4034siocnopen(sp, iobase, speed)
4035	struct siocnstate	*sp;
4036	Port_t			iobase;
4037	int			speed;
4038{
4039	u_int	divisor;
4040	u_char	dlbh;
4041	u_char	dlbl;
4042
4043	/*
4044	 * Save all the device control registers except the fifo register
4045	 * and set our default ones (cs8 -parenb speed=comdefaultrate).
4046	 * We can't save the fifo register since it is read-only.
4047	 */
4048	sp->ier = inb(iobase + com_ier);
4049	outb(iobase + com_ier, 0);	/* spltty() doesn't stop siointr() */
4050	siocntxwait(iobase);
4051	sp->cfcr = inb(iobase + com_cfcr);
4052	outb(iobase + com_cfcr, CFCR_DLAB | CFCR_8BITS);
4053	sp->dlbl = inb(iobase + com_dlbl);
4054	sp->dlbh = inb(iobase + com_dlbh);
4055	/*
4056	 * Only set the divisor registers if they would change, since on
4057	 * some 16550 incompatibles (Startech), setting them clears the
4058	 * data input register.  This also reduces the effects of the
4059	 * UMC8669F bug.
4060	 */
4061	divisor = siodivisor(comdefaultrclk, speed);
4062	dlbl = divisor & 0xFF;
4063	if (sp->dlbl != dlbl)
4064		outb(iobase + com_dlbl, dlbl);
4065	dlbh = divisor >> 8;
4066	if (sp->dlbh != dlbh)
4067		outb(iobase + com_dlbh, dlbh);
4068	outb(iobase + com_cfcr, CFCR_8BITS);
4069	sp->mcr = inb(iobase + com_mcr);
4070	/*
4071	 * We don't want interrupts, but must be careful not to "disable"
4072	 * them by clearing the MCR_IENABLE bit, since that might cause
4073	 * an interrupt by floating the IRQ line.
4074	 */
4075	outb(iobase + com_mcr, (sp->mcr & MCR_IENABLE) | MCR_DTR | MCR_RTS);
4076}
4077
4078static void
4079siocnclose(sp, iobase)
4080	struct siocnstate	*sp;
4081	Port_t			iobase;
4082{
4083	/*
4084	 * Restore the device control registers.
4085	 */
4086	siocntxwait(iobase);
4087	outb(iobase + com_cfcr, CFCR_DLAB | CFCR_8BITS);
4088	if (sp->dlbl != inb(iobase + com_dlbl))
4089		outb(iobase + com_dlbl, sp->dlbl);
4090	if (sp->dlbh != inb(iobase + com_dlbh))
4091		outb(iobase + com_dlbh, sp->dlbh);
4092	outb(iobase + com_cfcr, sp->cfcr);
4093	/*
4094	 * XXX damp oscillations of MCR_DTR and MCR_RTS by not restoring them.
4095	 */
4096	outb(iobase + com_mcr, sp->mcr | MCR_DTR | MCR_RTS);
4097	outb(iobase + com_ier, sp->ier);
4098}
4099
4100#ifndef __alpha__
4101
4102static void
4103siocnprobe(cp)
4104	struct consdev	*cp;
4105{
4106	speed_t			boot_speed;
4107	u_char			cfcr;
4108	u_int			divisor;
4109	int			s, unit;
4110	struct siocnstate	sp;
4111
4112	/*
4113	 * Find our first enabled console, if any.  If it is a high-level
4114	 * console device, then initialize it and return successfully.
4115	 * If it is a low-level console device, then initialize it and
4116	 * return unsuccessfully.  It must be initialized in both cases
4117	 * for early use by console drivers and debuggers.  Initializing
4118	 * the hardware is not necessary in all cases, since the i/o
4119	 * routines initialize it on the fly, but it is necessary if
4120	 * input might arrive while the hardware is switched back to an
4121	 * uninitialized state.  We can't handle multiple console devices
4122	 * yet because our low-level routines don't take a device arg.
4123	 * We trust the user to set the console flags properly so that we
4124	 * don't need to probe.
4125	 */
4126	cp->cn_pri = CN_DEAD;
4127
4128	for (unit = 0; unit < 16; unit++) { /* XXX need to know how many */
4129		int flags;
4130
4131		if (resource_disabled("sio", unit))
4132			continue;
4133		if (resource_int_value("sio", unit, "flags", &flags))
4134			continue;
4135		if (COM_CONSOLE(flags) || COM_DEBUGGER(flags)) {
4136			int port;
4137			Port_t iobase;
4138
4139			if (resource_int_value("sio", unit, "port", &port))
4140				continue;
4141			iobase = port;
4142			s = spltty();
4143			if (boothowto & RB_SERIAL) {
4144				boot_speed =
4145				    siocngetspeed(iobase, comdefaultrclk);
4146				if (boot_speed)
4147					comdefaultrate = boot_speed;
4148			}
4149
4150			/*
4151			 * Initialize the divisor latch.  We can't rely on
4152			 * siocnopen() to do this the first time, since it
4153			 * avoids writing to the latch if the latch appears
4154			 * to have the correct value.  Also, if we didn't
4155			 * just read the speed from the hardware, then we
4156			 * need to set the speed in hardware so that
4157			 * switching it later is null.
4158			 */
4159			cfcr = inb(iobase + com_cfcr);
4160			outb(iobase + com_cfcr, CFCR_DLAB | cfcr);
4161			divisor = siodivisor(comdefaultrclk, comdefaultrate);
4162			outb(iobase + com_dlbl, divisor & 0xff);
4163			outb(iobase + com_dlbh, divisor >> 8);
4164			outb(iobase + com_cfcr, cfcr);
4165
4166			siocnopen(&sp, iobase, comdefaultrate);
4167
4168			splx(s);
4169			if (COM_CONSOLE(flags) && !COM_LLCONSOLE(flags)) {
4170				siocnset(cp, unit);
4171				cp->cn_pri = COM_FORCECONSOLE(flags)
4172					     || boothowto & RB_SERIAL
4173					     ? CN_REMOTE : CN_NORMAL;
4174				siocniobase = iobase;
4175				siocnunit = unit;
4176			}
4177			if (COM_DEBUGGER(flags)) {
4178				printf("sio%d: gdb debugging port\n", unit);
4179				siogdbiobase = iobase;
4180				siogdbunit = unit;
4181#if DDB > 0
4182				siocnset(&gdbconsdev, unit);
4183				gdb_arg = &gdbconsdev;
4184				gdb_getc = siocngetc;
4185				gdb_putc = siocnputc;
4186#endif
4187			}
4188		}
4189	}
4190#ifdef	__i386__
4191#if DDB > 0
4192	/*
4193	 * XXX Ugly Compatability.
4194	 * If no gdb port has been specified, set it to be the console
4195	 * as some configuration files don't specify the gdb port.
4196	 */
4197	if (gdb_arg == NULL && (boothowto & RB_GDB)) {
4198		printf("Warning: no GDB port specified. Defaulting to sio%d.\n",
4199			siocnunit);
4200		printf("Set flag 0x80 on desired GDB port in your\n");
4201		printf("configuration file (currently sio only).\n");
4202		siogdbiobase = siocniobase;
4203		siogdbunit = siocnunit;
4204		siocnset(&gdbconsdev, siocnunit);
4205		gdb_arg = &gdbconsdev;
4206		gdb_getc = siocngetc;
4207		gdb_putc = siocnputc;
4208	}
4209#endif
4210#endif
4211}
4212
4213static void
4214siocninit(cp)
4215	struct consdev	*cp;
4216{
4217	comconsole = cp->cn_unit;
4218}
4219
4220static void
4221siocnterm(cp)
4222	struct consdev	*cp;
4223{
4224	comconsole = -1;
4225}
4226
4227#endif
4228
4229#ifdef __alpha__
4230
4231CONS_DRIVER(sio, NULL, NULL, NULL, siocngetc, siocncheckc, siocnputc, NULL);
4232
4233int
4234siocnattach(port, speed)
4235	int port;
4236	int speed;
4237{
4238	int			s;
4239	u_char			cfcr;
4240	u_int			divisor;
4241	struct siocnstate	sp;
4242	int			unit = 0;	/* XXX random value! */
4243
4244	siocniobase = port;
4245	siocnunit = unit;
4246	comdefaultrate = speed;
4247	sio_consdev.cn_pri = CN_NORMAL;
4248	siocnset(&sio_consdev, unit);
4249
4250	s = spltty();
4251
4252	/*
4253	 * Initialize the divisor latch.  We can't rely on
4254	 * siocnopen() to do this the first time, since it
4255	 * avoids writing to the latch if the latch appears
4256	 * to have the correct value.  Also, if we didn't
4257	 * just read the speed from the hardware, then we
4258	 * need to set the speed in hardware so that
4259	 * switching it later is null.
4260	 */
4261	cfcr = inb(siocniobase + com_cfcr);
4262	outb(siocniobase + com_cfcr, CFCR_DLAB | cfcr);
4263	divisor = siodivisor(comdefaultrclk, comdefaultrate);
4264	outb(siocniobase + com_dlbl, divisor & 0xff);
4265	outb(siocniobase + com_dlbh, divisor >> 8);
4266	outb(siocniobase + com_cfcr, cfcr);
4267
4268	siocnopen(&sp, siocniobase, comdefaultrate);
4269	splx(s);
4270
4271	cnadd(&sio_consdev);
4272	return (0);
4273}
4274
4275int
4276siogdbattach(port, speed)
4277	int port;
4278	int speed;
4279{
4280	int			s;
4281	u_char			cfcr;
4282	u_int			divisor;
4283	struct siocnstate	sp;
4284	int			unit = 1;	/* XXX random value! */
4285
4286	siogdbiobase = port;
4287	gdbdefaultrate = speed;
4288
4289	printf("sio%d: gdb debugging port\n", unit);
4290	siogdbunit = unit;
4291#if DDB > 0
4292	siocnset(&gdbconsdev, unit);
4293	gdb_arg = &gdbconsdev;
4294	gdb_getc = siocngetc;
4295	gdb_putc = siocnputc;
4296#endif
4297
4298	s = spltty();
4299
4300	/*
4301	 * Initialize the divisor latch.  We can't rely on
4302	 * siocnopen() to do this the first time, since it
4303	 * avoids writing to the latch if the latch appears
4304	 * to have the correct value.  Also, if we didn't
4305	 * just read the speed from the hardware, then we
4306	 * need to set the speed in hardware so that
4307	 * switching it later is null.
4308	 */
4309	cfcr = inb(siogdbiobase + com_cfcr);
4310	outb(siogdbiobase + com_cfcr, CFCR_DLAB | cfcr);
4311	divisor = siodivisor(comdefaultrclk, gdbdefaultrate);
4312	outb(siogdbiobase + com_dlbl, divisor & 0xff);
4313	outb(siogdbiobase + com_dlbh, divisor >> 8);
4314	outb(siogdbiobase + com_cfcr, cfcr);
4315
4316	siocnopen(&sp, siogdbiobase, gdbdefaultrate);
4317	splx(s);
4318
4319	return (0);
4320}
4321
4322#endif
4323
4324static int
4325siocncheckc(struct consdev *cd)
4326{
4327	int	c;
4328	Port_t	iobase;
4329	int	s;
4330	struct siocnstate	sp;
4331	speed_t	speed;
4332
4333	if (cd->cn_unit == siocnunit) {
4334		iobase = siocniobase;
4335		speed = comdefaultrate;
4336	} else {
4337		iobase = siogdbiobase;
4338		speed = gdbdefaultrate;
4339	}
4340	s = spltty();
4341	siocnopen(&sp, iobase, speed);
4342	if (inb(iobase + com_lsr) & LSR_RXRDY)
4343		c = inb(iobase + com_data);
4344	else
4345		c = -1;
4346	siocnclose(&sp, iobase);
4347	splx(s);
4348	return (c);
4349}
4350
4351static int
4352siocngetc(struct consdev *cd)
4353{
4354	int	c;
4355	Port_t	iobase;
4356	int	s;
4357	struct siocnstate	sp;
4358	speed_t	speed;
4359
4360	if (cd->cn_unit == siocnunit) {
4361		iobase = siocniobase;
4362		speed = comdefaultrate;
4363	} else {
4364		iobase = siogdbiobase;
4365		speed = gdbdefaultrate;
4366	}
4367	s = spltty();
4368	siocnopen(&sp, iobase, speed);
4369	while (!(inb(iobase + com_lsr) & LSR_RXRDY))
4370		;
4371	c = inb(iobase + com_data);
4372	siocnclose(&sp, iobase);
4373	splx(s);
4374	return (c);
4375}
4376
4377static void
4378siocnputc(struct consdev *cd, int c)
4379{
4380	int	need_unlock;
4381	int	s;
4382	struct siocnstate	sp;
4383	Port_t	iobase;
4384	speed_t	speed;
4385
4386	if (cd->cn_unit == siocnunit) {
4387		iobase = siocniobase;
4388		speed = comdefaultrate;
4389	} else {
4390		iobase = siogdbiobase;
4391		speed = gdbdefaultrate;
4392	}
4393	s = spltty();
4394	need_unlock = 0;
4395	if (sio_inited == 2 && !mtx_owned(&sio_lock)) {
4396		mtx_lock_spin(&sio_lock);
4397		need_unlock = 1;
4398	}
4399	siocnopen(&sp, iobase, speed);
4400	siocntxwait(iobase);
4401	outb(iobase + com_data, c);
4402	siocnclose(&sp, iobase);
4403	if (need_unlock)
4404		mtx_unlock_spin(&sio_lock);
4405	splx(s);
4406}
4407
4408#ifdef __alpha__
4409int
4410siogdbgetc()
4411{
4412	int	c;
4413	Port_t	iobase;
4414	speed_t	speed;
4415	int	s;
4416	struct siocnstate	sp;
4417
4418	if (siogdbunit == siocnunit) {
4419		iobase = siocniobase;
4420		speed = comdefaultrate;
4421	} else {
4422		iobase = siogdbiobase;
4423		speed = gdbdefaultrate;
4424	}
4425
4426	s = spltty();
4427	siocnopen(&sp, iobase, speed);
4428	while (!(inb(iobase + com_lsr) & LSR_RXRDY))
4429		;
4430	c = inb(iobase + com_data);
4431	siocnclose(&sp, iobase);
4432	splx(s);
4433	return (c);
4434}
4435
4436void
4437siogdbputc(c)
4438	int	c;
4439{
4440	Port_t	iobase;
4441	speed_t	speed;
4442	int	s;
4443	struct siocnstate	sp;
4444
4445	if (siogdbunit == siocnunit) {
4446		iobase = siocniobase;
4447		speed = comdefaultrate;
4448	} else {
4449		iobase = siogdbiobase;
4450		speed = gdbdefaultrate;
4451	}
4452
4453	s = spltty();
4454	siocnopen(&sp, iobase, speed);
4455	siocntxwait(siogdbiobase);
4456	outb(siogdbiobase + com_data, c);
4457	siocnclose(&sp, siogdbiobase);
4458	splx(s);
4459}
4460#endif
4461
4462#ifdef PC98
4463/*
4464 *  pc98 local function
4465 */
4466
4467static void
4468com_tiocm_set(struct com_s *com, int msr)
4469{
4470	int	s;
4471	int	tmp = 0;
4472	int	mask = CMD8251_TxEN|CMD8251_RxEN|CMD8251_DTR|CMD8251_RTS;
4473
4474	s=spltty();
4475	com->pc98_prev_modem_status = ( msr & (TIOCM_LE|TIOCM_DTR|TIOCM_RTS) )
4476	   | ( com->pc98_prev_modem_status & ~(TIOCM_LE|TIOCM_DTR|TIOCM_RTS) );
4477	tmp |= (CMD8251_TxEN|CMD8251_RxEN);
4478	if ( msr & TIOCM_DTR ) tmp |= CMD8251_DTR;
4479	if ( msr & TIOCM_RTS ) tmp |= CMD8251_RTS;
4480	pc98_i8251_clear_or_cmd( com, mask, tmp );
4481	splx(s);
4482}
4483
4484static void
4485com_tiocm_bis(struct com_s *com, int msr)
4486{
4487	int	s;
4488	int	tmp = 0;
4489
4490	s=spltty();
4491	com->pc98_prev_modem_status |= ( msr & (TIOCM_LE|TIOCM_DTR|TIOCM_RTS) );
4492	tmp |= CMD8251_TxEN|CMD8251_RxEN;
4493	if ( msr & TIOCM_DTR ) tmp |= CMD8251_DTR;
4494	if ( msr & TIOCM_RTS ) tmp |= CMD8251_RTS;
4495
4496	pc98_i8251_or_cmd( com, tmp );
4497	splx(s);
4498}
4499
4500static void
4501com_tiocm_bic(struct com_s *com, int msr)
4502{
4503	int	s;
4504	int	tmp = msr;
4505
4506	s=spltty();
4507	com->pc98_prev_modem_status &= ~( msr & (TIOCM_LE|TIOCM_DTR|TIOCM_RTS) );
4508	if ( msr & TIOCM_DTR ) tmp |= CMD8251_DTR;
4509	if ( msr & TIOCM_RTS ) tmp |= CMD8251_RTS;
4510
4511	pc98_i8251_clear_cmd( com, tmp );
4512	splx(s);
4513}
4514
4515static int
4516com_tiocm_get(struct com_s *com)
4517{
4518	return( com->pc98_prev_modem_status );
4519}
4520
4521static int
4522com_tiocm_get_delta(struct com_s *com)
4523{
4524	int	tmp;
4525
4526	tmp = com->pc98_modem_delta;
4527	com->pc98_modem_delta = 0;
4528	return( tmp );
4529}
4530
4531/* convert to TIOCM_?? ( ioctl.h ) */
4532static int
4533pc98_get_modem_status(struct com_s *com)
4534{
4535	register int	msr;
4536
4537	msr = com->pc98_prev_modem_status
4538			& ~(TIOCM_CAR|TIOCM_RI|TIOCM_DSR|TIOCM_CTS);
4539	if (com->pc98_8251fifo_enable) {
4540		int	stat2;
4541
4542		stat2 = inb(I8251F_msr);
4543		if ( stat2 & CICSCDF_CD ) msr |= TIOCM_CAR;
4544		if ( stat2 & CICSCDF_CI ) msr |= TIOCM_RI;
4545		if ( stat2 & CICSCDF_DR ) msr |= TIOCM_DSR;
4546		if ( stat2 & CICSCDF_CS ) msr |= TIOCM_CTS;
4547#if COM_CARRIER_DETECT_EMULATE
4548		if ( msr & (TIOCM_DSR|TIOCM_CTS) ) {
4549			msr |= TIOCM_CAR;
4550		}
4551#endif
4552	} else {
4553		int	stat, stat2;
4554
4555		stat  = inb(com->sts_port);
4556		stat2 = inb(com->in_modem_port);
4557		if ( !(stat2 & CICSCD_CD) ) msr |= TIOCM_CAR;
4558		if ( !(stat2 & CICSCD_CI) ) msr |= TIOCM_RI;
4559		if (   stat & STS8251_DSR ) msr |= TIOCM_DSR;
4560		if ( !(stat2 & CICSCD_CS) ) msr |= TIOCM_CTS;
4561#if COM_CARRIER_DETECT_EMULATE
4562		if ( msr & (TIOCM_DSR|TIOCM_CTS) ) {
4563			msr |= TIOCM_CAR;
4564		}
4565#endif
4566	}
4567	return(msr);
4568}
4569
4570static void
4571pc98_check_msr(void* chan)
4572{
4573	int	msr, delta;
4574	int	s;
4575	register struct tty *tp;
4576	struct	com_s *com;
4577	int	mynor;
4578	int	unit;
4579	dev_t	dev;
4580
4581	dev=(dev_t)chan;
4582	mynor = minor(dev);
4583	unit = MINOR_TO_UNIT(mynor);
4584	com = com_addr(unit);
4585	tp = com->tp;
4586
4587	s = spltty();
4588	msr = pc98_get_modem_status(com);
4589	/* make change flag */
4590	delta = msr ^ com->pc98_prev_modem_status;
4591	if ( delta & TIOCM_CAR ) {
4592	    if ( com->modem_car_chg_timer ) {
4593		if ( -- com->modem_car_chg_timer )
4594		    msr ^= TIOCM_CAR;
4595	    } else {
4596		if ((com->modem_car_chg_timer = (msr & TIOCM_CAR) ?
4597		     DCD_ON_RECOGNITION : DCD_OFF_TOLERANCE) != 0)
4598		    msr ^= TIOCM_CAR;
4599	    }
4600	} else
4601	    com->modem_car_chg_timer = 0;
4602	delta = ( msr ^ com->pc98_prev_modem_status ) &
4603			(TIOCM_CAR|TIOCM_RI|TIOCM_DSR|TIOCM_CTS);
4604	com->pc98_prev_modem_status = msr;
4605	delta = ( com->pc98_modem_delta |= delta );
4606	splx(s);
4607	if ( com->modem_checking || (tp->t_state & (TS_ISOPEN)) ) {
4608		if ( delta ) {
4609			commint(dev);
4610		}
4611		timeout(pc98_check_msr, (caddr_t)dev,
4612					PC98_CHECK_MODEM_INTERVAL);
4613	} else {
4614		com->modem_checking = 0;
4615	}
4616}
4617
4618static void
4619pc98_msrint_start(dev_t dev)
4620{
4621	struct	com_s *com;
4622	int	mynor;
4623	int	unit;
4624	int	s = spltty();
4625
4626	mynor = minor(dev);
4627	unit = MINOR_TO_UNIT(mynor);
4628	com = com_addr(unit);
4629	/* modem control line check routine envoke interval is 1/10 sec */
4630	if ( com->modem_checking == 0 ) {
4631		com->pc98_prev_modem_status = pc98_get_modem_status(com);
4632		com->pc98_modem_delta = 0;
4633		timeout(pc98_check_msr, (caddr_t)dev,
4634					PC98_CHECK_MODEM_INTERVAL);
4635		com->modem_checking = 1;
4636	}
4637	splx(s);
4638}
4639
4640static void
4641pc98_disable_i8251_interrupt(struct com_s *com, int mod)
4642{
4643	/* disable interrupt */
4644	register int	tmp;
4645
4646	mod |= ~(IEN_Tx|IEN_TxEMP|IEN_Rx);
4647	COM_INT_DISABLE
4648	tmp = inb( com->intr_ctrl_port ) & ~(IEN_Tx|IEN_TxEMP|IEN_Rx);
4649	outb( com->intr_ctrl_port, (com->intr_enable&=~mod) | tmp );
4650	COM_INT_ENABLE
4651}
4652
4653static void
4654pc98_enable_i8251_interrupt(struct com_s *com, int mod)
4655{
4656	register int	tmp;
4657
4658	COM_INT_DISABLE
4659	tmp = inb( com->intr_ctrl_port ) & ~(IEN_Tx|IEN_TxEMP|IEN_Rx);
4660	outb( com->intr_ctrl_port, (com->intr_enable|=mod) | tmp );
4661	COM_INT_ENABLE
4662}
4663
4664static int
4665pc98_check_i8251_interrupt(struct com_s *com)
4666{
4667	return ( com->intr_enable & 0x07 );
4668}
4669
4670static void
4671pc98_i8251_clear_cmd(struct com_s *com, int x)
4672{
4673	int	tmp;
4674
4675	COM_INT_DISABLE
4676	tmp = com->pc98_prev_siocmd & ~(x);
4677	if (com->pc98_8251fifo_enable)
4678	    outb(I8251F_fcr, 0);
4679	outb(com->cmd_port, tmp);
4680	com->pc98_prev_siocmd = tmp & ~(CMD8251_ER|CMD8251_RESET|CMD8251_EH);
4681	if (com->pc98_8251fifo_enable)
4682	    outb(I8251F_fcr, CTRL8251F_ENABLE);
4683	COM_INT_ENABLE
4684}
4685
4686static void
4687pc98_i8251_or_cmd(struct com_s *com, int x)
4688{
4689	int	tmp;
4690
4691	COM_INT_DISABLE
4692	if (com->pc98_8251fifo_enable)
4693	    outb(I8251F_fcr, 0);
4694	tmp = com->pc98_prev_siocmd | (x);
4695	outb(com->cmd_port, tmp);
4696	com->pc98_prev_siocmd = tmp & ~(CMD8251_ER|CMD8251_RESET|CMD8251_EH);
4697	if (com->pc98_8251fifo_enable)
4698	    outb(I8251F_fcr, CTRL8251F_ENABLE);
4699	COM_INT_ENABLE
4700}
4701
4702static void
4703pc98_i8251_set_cmd(struct com_s *com, int x)
4704{
4705	int	tmp;
4706
4707	COM_INT_DISABLE
4708	if (com->pc98_8251fifo_enable)
4709	    outb(I8251F_fcr, 0);
4710	tmp = (x);
4711	outb(com->cmd_port, tmp);
4712	com->pc98_prev_siocmd = tmp & ~(CMD8251_ER|CMD8251_RESET|CMD8251_EH);
4713	if (com->pc98_8251fifo_enable)
4714	    outb(I8251F_fcr, CTRL8251F_ENABLE);
4715	COM_INT_ENABLE
4716}
4717
4718static void
4719pc98_i8251_clear_or_cmd(struct com_s *com, int clr, int x)
4720{
4721	int	tmp;
4722	COM_INT_DISABLE
4723	if (com->pc98_8251fifo_enable)
4724	    outb(I8251F_fcr, 0);
4725	tmp = com->pc98_prev_siocmd & ~(clr);
4726	tmp |= (x);
4727	outb(com->cmd_port, tmp);
4728	com->pc98_prev_siocmd = tmp & ~(CMD8251_ER|CMD8251_RESET|CMD8251_EH);
4729	if (com->pc98_8251fifo_enable)
4730	    outb(I8251F_fcr, CTRL8251F_ENABLE);
4731	COM_INT_ENABLE
4732}
4733
4734static int
4735pc98_i8251_get_cmd(struct com_s *com)
4736{
4737	return com->pc98_prev_siocmd;
4738}
4739
4740static int
4741pc98_i8251_get_mod(struct com_s *com)
4742{
4743	return com->pc98_prev_siomod;
4744}
4745
4746static void
4747pc98_i8251_reset(struct com_s *com, int mode, int command)
4748{
4749	if (com->pc98_8251fifo_enable)
4750	    outb(I8251F_fcr, 0);
4751	outb(com->cmd_port, 0);	/* dummy */
4752	DELAY(2);
4753	outb(com->cmd_port, 0);	/* dummy */
4754	DELAY(2);
4755	outb(com->cmd_port, 0);	/* dummy */
4756	DELAY(2);
4757	outb(com->cmd_port, CMD8251_RESET);	/* internal reset */
4758	DELAY(2);
4759	outb(com->cmd_port, mode );	/* mode register */
4760	com->pc98_prev_siomod = mode;
4761	DELAY(2);
4762	pc98_i8251_set_cmd( com, (command|CMD8251_ER) );
4763	DELAY(10);
4764	if (com->pc98_8251fifo_enable)
4765	    outb(I8251F_fcr, CTRL8251F_ENABLE |
4766		 CTRL8251F_XMT_RST | CTRL8251F_RCV_RST);
4767}
4768
4769static void
4770pc98_check_sysclock(void)
4771{
4772	/* get system clock from port */
4773	if ( pc98_machine_type & M_8M ) {
4774	/* 8 MHz system & H98 */
4775		sysclock = 8;
4776	} else {
4777	/* 5 MHz system */
4778		sysclock = 5;
4779	}
4780}
4781
4782static void
4783com_cflag_and_speed_set( struct com_s *com, int cflag, int speed)
4784{
4785	int	cfcr=0;
4786	int	previnterrupt;
4787	u_int	count;
4788
4789	if (pc98_ttspeedtab(com, speed, &count) != 0)
4790		return;
4791
4792	previnterrupt = pc98_check_i8251_interrupt(com);
4793	pc98_disable_i8251_interrupt( com, IEN_Tx|IEN_TxEMP|IEN_Rx );
4794
4795	switch ( cflag&CSIZE ) {
4796	  case CS5:
4797		cfcr = MOD8251_5BITS; break;
4798	  case CS6:
4799		cfcr = MOD8251_6BITS; break;
4800	  case CS7:
4801		cfcr = MOD8251_7BITS; break;
4802	  case CS8:
4803		cfcr = MOD8251_8BITS; break;
4804	}
4805	if ( cflag&PARENB ) {
4806	    if ( cflag&PARODD )
4807		cfcr |= MOD8251_PODD;
4808	    else
4809		cfcr |= MOD8251_PEVEN;
4810	} else
4811		cfcr |= MOD8251_PDISAB;
4812
4813	if ( cflag&CSTOPB )
4814		cfcr |= MOD8251_STOP2;
4815	else
4816		cfcr |= MOD8251_STOP1;
4817
4818	if ( count & 0x10000 )
4819		cfcr |= MOD8251_CLKX1;
4820	else
4821		cfcr |= MOD8251_CLKX16;
4822
4823	if (epson_machine_id != 0x20) {	/* XXX */
4824		int	tmp;
4825		while (!((tmp = inb(com->sts_port)) & STS8251_TxEMP))
4826			;
4827	}
4828	/* set baud rate from ospeed */
4829	pc98_set_baud_rate( com, count );
4830
4831	if ( cfcr != pc98_i8251_get_mod(com) )
4832		pc98_i8251_reset(com, cfcr, pc98_i8251_get_cmd(com) );
4833
4834	pc98_enable_i8251_interrupt( com, previnterrupt );
4835}
4836
4837static int
4838pc98_ttspeedtab(struct com_s *com, int speed, u_int *divisor)
4839{
4840	int	if_type, effect_sp, count = -1, mod;
4841
4842	if_type = com->pc98_if_type & 0x0f;
4843
4844	switch (com->pc98_if_type) {
4845	case COM_IF_INTERNAL:
4846	    if (PC98SIO_baud_rate_port(if_type) != -1) {
4847		count = ttspeedtab(speed, if_8251_type[if_type].speedtab);
4848		if (count > 0) {
4849		    count |= COM1_EXT_CLOCK;
4850		    break;
4851		}
4852	    }
4853
4854	    /* for *1CLK asynchronous! mode, TEFUTEFU */
4855	    mod = (sysclock == 5) ? 2457600 : 1996800;
4856	    effect_sp = ttspeedtab( speed, pc98speedtab );
4857	    if ( effect_sp < 0 )	/* XXX */
4858		effect_sp = ttspeedtab( (speed - 1), pc98speedtab );
4859	    if ( effect_sp <= 0 )
4860		return effect_sp;
4861	    if ( effect_sp == speed )
4862		mod /= 16;
4863	    if ( mod % effect_sp )
4864		return(-1);
4865	    count = mod / effect_sp;
4866	    if ( count > 65535 )
4867		return(-1);
4868	    if ( effect_sp != speed )
4869		count |= 0x10000;
4870	    break;
4871	case COM_IF_PC9861K_1:
4872	case COM_IF_PC9861K_2:
4873	    count = 1;
4874	    break;
4875	case COM_IF_IND_SS_1:
4876	case COM_IF_IND_SS_2:
4877	case COM_IF_PIO9032B_1:
4878	case COM_IF_PIO9032B_2:
4879	    count = ttspeedtab( speed, if_8251_type[if_type].speedtab );
4880	    break;
4881	case COM_IF_B98_01_1:
4882	case COM_IF_B98_01_2:
4883	    count = ttspeedtab( speed, if_8251_type[if_type].speedtab );
4884#ifdef B98_01_OLD
4885	    if (count == 0 || count == 1) {
4886		count += 4;
4887		count |= 0x20000;  /* x1 mode for 76800 and 153600 */
4888	    }
4889#endif
4890	    break;
4891	}
4892
4893	if (count < 0)
4894		return count;
4895
4896	*divisor = (u_int) count;
4897	return 0;
4898}
4899
4900static void
4901pc98_set_baud_rate( struct com_s *com, u_int count )
4902{
4903	int	if_type, io, s;
4904
4905	if_type = com->pc98_if_type & 0x0f;
4906	io = rman_get_start(com->ioportres) & 0xff00;
4907
4908	switch (com->pc98_if_type) {
4909	case COM_IF_INTERNAL:
4910	    if (PC98SIO_baud_rate_port(if_type) != -1) {
4911		if (count & COM1_EXT_CLOCK) {
4912		    outb((Port_t)PC98SIO_baud_rate_port(if_type), count & 0xff);
4913		    break;
4914		} else {
4915		    outb((Port_t)PC98SIO_baud_rate_port(if_type), 0x09);
4916		}
4917	    }
4918
4919	    if (count == 0)
4920		return;
4921
4922	    /* set i8253 */
4923	    s = splclock();
4924	    if (count != 3)
4925		outb( 0x77, 0xb6 );
4926	    else
4927		outb( 0x77, 0xb4 );
4928	    outb( 0x5f, 0);
4929	    outb( 0x75, count & 0xff );
4930	    outb( 0x5f, 0);
4931	    outb( 0x75, (count >> 8) & 0xff );
4932	    splx(s);
4933	    break;
4934	case COM_IF_IND_SS_1:
4935	case COM_IF_IND_SS_2:
4936	    outb(io | PC98SIO_intr_ctrl_port(if_type), 0);
4937	    outb(io | PC98SIO_baud_rate_port(if_type), 0);
4938	    outb(io | PC98SIO_baud_rate_port(if_type), 0xc0);
4939	    outb(io | PC98SIO_baud_rate_port(if_type), (count >> 8) | 0x80);
4940	    outb(io | PC98SIO_baud_rate_port(if_type), count & 0xff);
4941	    break;
4942	case COM_IF_PIO9032B_1:
4943	case COM_IF_PIO9032B_2:
4944	    outb(io | PC98SIO_baud_rate_port(if_type), count);
4945	    break;
4946	case COM_IF_B98_01_1:
4947	case COM_IF_B98_01_2:
4948	    outb(io | PC98SIO_baud_rate_port(if_type), count & 0x0f);
4949#ifdef B98_01_OLD
4950	    /*
4951	     * Some old B98_01 board should be controlled
4952	     * in different way, but this hasn't been tested yet.
4953	     */
4954	    outb(io | PC98SIO_func_port(if_type),
4955		 (count & 0x20000) ? 0xf0 : 0xf2);
4956#endif
4957	    break;
4958	}
4959}
4960static int
4961pc98_check_if_type(device_t dev, struct siodev *iod)
4962{
4963	int	irr, io, if_type, tmp;
4964	static  short	irq_tab[2][8] = {
4965		{  3,  5,  6,  9, 10, 12, 13, -1},
4966		{  3, 10, 12, 13,  5,  6,  9, -1}
4967	};
4968
4969	if_type = iod->if_type & 0x0f;
4970	iod->irq = 0;
4971	io = isa_get_port(dev) & 0xff00;
4972
4973	if (IS_8251(iod->if_type)) {
4974	    if (PC98SIO_func_port(if_type) != -1) {
4975		outb(io | PC98SIO_func_port(if_type), 0xf2);
4976		tmp = ttspeedtab(9600, if_8251_type[if_type].speedtab);
4977		if (tmp != -1 && PC98SIO_baud_rate_port(if_type) != -1)
4978		    outb(io | PC98SIO_baud_rate_port(if_type), tmp);
4979	    }
4980
4981	    iod->cmd  = io | PC98SIO_cmd_port(if_type);
4982	    iod->sts  = io | PC98SIO_sts_port(if_type);
4983	    iod->mod  = io | PC98SIO_in_modem_port(if_type);
4984	    iod->ctrl = io | PC98SIO_intr_ctrl_port(if_type);
4985
4986	    if (iod->if_type == COM_IF_INTERNAL) {
4987		iod->irq = 4;
4988
4989		if (pc98_check_8251vfast()) {
4990			PC98SIO_baud_rate_port(if_type) = I8251F_div;
4991			if_8251_type[if_type].speedtab = pc98fast_speedtab;
4992		}
4993	    } else {
4994		tmp = inb( iod->mod ) & if_8251_type[if_type].irr_mask;
4995		if ((isa_get_port(dev) & 0xff) == IO_COM2)
4996		    iod->irq = irq_tab[0][tmp];
4997		else
4998		    iod->irq = irq_tab[1][tmp];
4999	    }
5000	} else {
5001	    irr = if_16550a_type[if_type].irr_read;
5002#ifdef COM_MULTIPORT
5003	    if (!COM_ISMULTIPORT(device_get_flags(dev)) ||
5004		    device_get_unit(dev) == COM_MPMASTER(device_get_flags(dev)))
5005#endif
5006	    if (irr != -1) {
5007		tmp = inb(io | irr);
5008		if (isa_get_port(dev) & 0x01)	/* XXX depend on RSB-384 */
5009		    iod->irq = irq_tab[1][tmp >> 3];
5010		else
5011		    iod->irq = irq_tab[0][tmp & 0x07];
5012	    }
5013	}
5014	if ( iod->irq == -1 ) return -1;
5015
5016	return 0;
5017}
5018static void
5019pc98_set_ioport(struct com_s *com)
5020{
5021	int	if_type = com->pc98_if_type & 0x0f;
5022	Port_t	io = rman_get_start(com->ioportres) & 0xff00;
5023
5024	pc98_check_sysclock();
5025	com->data_port		= io | PC98SIO_data_port(if_type);
5026	com->cmd_port		= io | PC98SIO_cmd_port(if_type);
5027	com->sts_port		= io | PC98SIO_sts_port(if_type);
5028	com->in_modem_port	= io | PC98SIO_in_modem_port(if_type);
5029	com->intr_ctrl_port	= io | PC98SIO_intr_ctrl_port(if_type);
5030}
5031static int
5032pc98_check_8251vfast(void)
5033{
5034    int	i;
5035
5036    outb(I8251F_div, 0x8c);
5037    DELAY(10);
5038    for (i = 0; i < 100; i++) {
5039	if ((inb(I8251F_div) & 0x80) != 0) {
5040	    i = 0;
5041	    break;
5042	}
5043	DELAY(1);
5044    }
5045    outb(I8251F_div, 0);
5046    DELAY(10);
5047    for (; i < 100; i++) {
5048	if ((inb(I8251F_div) & 0x80) == 0)
5049	    return 1;
5050	DELAY(1);
5051    }
5052
5053    return 0;
5054}
5055static int
5056pc98_check_8251fifo(void)
5057{
5058    u_char	tmp1, tmp2;
5059
5060    tmp1 = inb(I8251F_iir);
5061    DELAY(10);
5062    tmp2 = inb(I8251F_iir);
5063    if (((tmp1 ^ tmp2) & 0x40) != 0 && ((tmp1 | tmp2) & 0x20) == 0)
5064	return 1;
5065
5066    return 0;
5067}
5068#endif /* PC98 defined */
5069