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