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