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