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