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