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