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