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