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