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