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