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