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