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