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