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