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