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