sio.c revision 65568
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 65568 2000-09-07 13:34:45Z 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#ifdef PC98
1725	u_char		*obuf;
1726	u_long		obufsize;
1727	int		if_type = GET_IFTYPE(device_get_flags(dev));
1728#endif
1729
1730	rid = xrid;
1731#ifdef PC98
1732	if (IS_8251(if_type)) {
1733		port = bus_alloc_resource(dev, SYS_RES_IOPORT, &rid,
1734					  0, ~0, 1, RF_ACTIVE);
1735	} else if (if_type == COM_IF_RSA98III ||
1736		   isa_get_vendorid(dev)) {
1737		port = bus_alloc_resource(dev, SYS_RES_IOPORT, &rid, 0, ~0,
1738			if_16550a_type[if_type & 0x0f].iatsz, RF_ACTIVE);
1739	} else {
1740		port = isa_alloc_resourcev(dev, SYS_RES_IOPORT, &rid,
1741			if_16550a_type[if_type & 0x0f].iat,
1742			if_16550a_type[if_type & 0x0f].iatsz, RF_ACTIVE);
1743	}
1744#else
1745	port = bus_alloc_resource(dev, SYS_RES_IOPORT, &rid,
1746				  0, ~0, IO_COMSIZE, RF_ACTIVE);
1747#endif
1748	if (!port)
1749		return (ENXIO);
1750#ifdef PC98
1751	if (!IS_8251(if_type)) {
1752		if (isa_load_resourcev(port,
1753			if_16550a_type[if_type & 0x0f].iat,
1754			if_16550a_type[if_type & 0x0f].iatsz) != 0) {
1755		    bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
1756		    return ENXIO;
1757		}
1758	}
1759#endif
1760
1761	iobase = rman_get_start(port);
1762	unit = device_get_unit(dev);
1763	com = device_get_softc(dev);
1764	flags = device_get_flags(dev);
1765
1766	if (unit >= sio_numunits)
1767		sio_numunits = unit + 1;
1768
1769#ifdef PC98
1770	obufsize = 256;
1771	if (if_type == COM_IF_RSA98III)
1772		obufsize = 2048;
1773	if ((obuf = malloc(obufsize * 2, M_DEVBUF, M_NOWAIT)) == NULL) {
1774		bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
1775		return ENXIO;
1776	}
1777	bzero(obuf, obufsize * 2);
1778#endif
1779
1780	/*
1781	 * sioprobe() has initialized the device registers as follows:
1782	 *	o cfcr = CFCR_8BITS.
1783	 *	  It is most important that CFCR_DLAB is off, so that the
1784	 *	  data port is not hidden when we enable interrupts.
1785	 *	o ier = 0.
1786	 *	  Interrupts are only enabled when the line is open.
1787	 *	o mcr = MCR_IENABLE, or 0 if the port has AST/4 compatible
1788	 *	  interrupt control register or the config specifies no irq.
1789	 *	  Keeping MCR_DTR and MCR_RTS off might stop the external
1790	 *	  device from sending before we are ready.
1791	 */
1792	bzero(com, sizeof *com);
1793	com->unit = unit;
1794	com->ioportres = port;
1795	com->bst = rman_get_bustag(port);
1796	com->bsh = rman_get_bushandle(port);
1797	com->cfcr_image = CFCR_8BITS;
1798	com->dtr_wait = 3 * hz;
1799	com->loses_outints = COM_LOSESOUTINTS(flags) != 0;
1800	com->no_irq = bus_get_resource(dev, SYS_RES_IRQ, 0, NULL, NULL) != 0;
1801	com->tx_fifo_size = 1;
1802#ifdef PC98
1803	com->obufsize = obufsize;
1804	com->obuf1 = obuf;
1805	com->obuf2 = obuf + obufsize;
1806#endif
1807	com->obufs[0].l_head = com->obuf1;
1808	com->obufs[1].l_head = com->obuf2;
1809
1810#ifdef PC98
1811	com->pc98_if_type = if_type;
1812
1813	if (IS_8251(if_type)) {
1814	    pc98_set_ioport(com);
1815
1816	    if (if_type == COM_IF_INTERNAL && pc98_check_8251fifo()) {
1817		com->pc98_8251fifo = 1;
1818		com->pc98_8251fifo_enable = 0;
1819	    }
1820	} else {
1821	    bus_addr_t	*iat = if_16550a_type[if_type & 0x0f].iat;
1822
1823	    com->data_port = iobase + iat[com_data];
1824	    com->int_id_port = iobase + iat[com_iir];
1825	    com->modem_ctl_port = iobase + iat[com_mcr];
1826	    com->mcr_image = inb(com->modem_ctl_port);
1827	    com->line_status_port = iobase + iat[com_lsr];
1828	    com->modem_status_port = iobase + iat[com_msr];
1829	    com->intr_ctl_port = iobase + iat[com_ier];
1830	}
1831#else /* not PC98 */
1832	com->data_port = iobase + com_data;
1833	com->int_id_port = iobase + com_iir;
1834	com->modem_ctl_port = iobase + com_mcr;
1835	com->mcr_image = inb(com->modem_ctl_port);
1836	com->line_status_port = iobase + com_lsr;
1837	com->modem_status_port = iobase + com_msr;
1838	com->intr_ctl_port = iobase + com_ier;
1839#endif
1840
1841	/*
1842	 * We don't use all the flags from <sys/ttydefaults.h> since they
1843	 * are only relevant for logins.  It's important to have echo off
1844	 * initially so that the line doesn't start blathering before the
1845	 * echo flag can be turned off.
1846	 */
1847	com->it_in.c_iflag = 0;
1848	com->it_in.c_oflag = 0;
1849	com->it_in.c_cflag = TTYDEF_CFLAG;
1850	com->it_in.c_lflag = 0;
1851	if (unit == comconsole) {
1852#ifdef PC98
1853		if (IS_8251(com->pc98_if_type))
1854			DELAY(100000);
1855#endif
1856		com->it_in.c_iflag = TTYDEF_IFLAG;
1857		com->it_in.c_oflag = TTYDEF_OFLAG;
1858		com->it_in.c_cflag = TTYDEF_CFLAG | CLOCAL;
1859		com->it_in.c_lflag = TTYDEF_LFLAG;
1860		com->lt_out.c_cflag = com->lt_in.c_cflag = CLOCAL;
1861		com->lt_out.c_ispeed = com->lt_out.c_ospeed =
1862		com->lt_in.c_ispeed = com->lt_in.c_ospeed =
1863		com->it_in.c_ispeed = com->it_in.c_ospeed = comdefaultrate;
1864	} else
1865		com->it_in.c_ispeed = com->it_in.c_ospeed = TTYDEF_SPEED;
1866	if (siosetwater(com, com->it_in.c_ispeed) != 0) {
1867		/*
1868		 * Leave i/o resources allocated if this is a `cn'-level
1869		 * console, so that other devices can't snarf them.
1870		 */
1871		if (iobase != siocniobase)
1872			bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
1873		return (ENOMEM);
1874	}
1875	termioschars(&com->it_in);
1876	com->it_out = com->it_in;
1877
1878	/* attempt to determine UART type */
1879	printf("sio%d: type", unit);
1880
1881
1882#ifndef PC98
1883#ifdef COM_MULTIPORT
1884	if (!COM_ISMULTIPORT(flags) && !COM_IIR_TXRDYBUG(flags))
1885#else
1886	if (!COM_IIR_TXRDYBUG(flags))
1887#endif
1888	{
1889		u_char	scr;
1890		u_char	scr1;
1891		u_char	scr2;
1892
1893		scr = sio_getreg(com, com_scr);
1894		sio_setreg(com, com_scr, 0xa5);
1895		scr1 = sio_getreg(com, com_scr);
1896		sio_setreg(com, com_scr, 0x5a);
1897		scr2 = sio_getreg(com, com_scr);
1898		sio_setreg(com, com_scr, scr);
1899		if (scr1 != 0xa5 || scr2 != 0x5a) {
1900			printf(" 8250");
1901			goto determined_type;
1902		}
1903	}
1904#endif /* !PC98 */
1905#ifdef PC98
1906	if (IS_8251(com->pc98_if_type)) {
1907	    if (com->pc98_8251fifo && !COM_NOFIFO(flags))
1908		com->tx_fifo_size = 16;
1909	    com_int_TxRx_disable( com );
1910	    com_cflag_and_speed_set( com, com->it_in.c_cflag, comdefaultrate );
1911	    com_tiocm_bic( com, TIOCM_DTR|TIOCM_RTS|TIOCM_LE );
1912	    com_send_break_off( com );
1913
1914	    if (com->pc98_if_type == COM_IF_INTERNAL) {
1915		printf(" (internal%s%s)",
1916		       com->pc98_8251fifo ? " fifo" : "",
1917		       PC98SIO_baud_rate_port(com->pc98_if_type) != -1 ?
1918		       " v-fast" : "");
1919	    } else {
1920		printf(" 8251%s", if_8251_type[com->pc98_if_type & 0x0f].name);
1921	    }
1922	} else {
1923#endif /* PC98 */
1924	sio_setreg(com, com_fifo, FIFO_ENABLE | FIFO_RX_HIGH);
1925	DELAY(100);
1926	com->st16650a = 0;
1927	switch (inb(com->int_id_port) & IIR_FIFO_MASK) {
1928	case FIFO_RX_LOW:
1929		printf(" 16450");
1930		break;
1931	case FIFO_RX_MEDL:
1932		printf(" 16450?");
1933		break;
1934	case FIFO_RX_MEDH:
1935		printf(" 16550?");
1936		break;
1937	case FIFO_RX_HIGH:
1938		if (COM_NOFIFO(flags)) {
1939			printf(" 16550A fifo disabled");
1940		} else {
1941			com->hasfifo = TRUE;
1942#ifdef PC98
1943			com->tx_fifo_size = 0;	/* XXX flag conflicts. */
1944			printf(" 16550A");
1945#else
1946			if (COM_ST16650A(flags)) {
1947				com->st16650a = 1;
1948				com->tx_fifo_size = 32;
1949				printf(" ST16650A");
1950			} else {
1951				com->tx_fifo_size = COM_FIFOSIZE(flags);
1952				printf(" 16550A");
1953			}
1954#endif
1955		}
1956#ifdef PC98
1957		if (com->pc98_if_type == COM_IF_RSA98III) {
1958			com->tx_fifo_size = 2048;
1959			com->rsabase = iobase;
1960			outb(com->rsabase + rsa_ier, 0x00);
1961			outb(com->rsabase + rsa_frr, 0x00);
1962		}
1963#endif
1964
1965#ifdef COM_ESP
1966#ifdef PC98
1967		if (com->pc98_if_type == COM_IF_ESP98)
1968#endif
1969		for (espp = likely_esp_ports; *espp != 0; espp++)
1970			if (espattach(com, *espp)) {
1971				com->tx_fifo_size = 1024;
1972				break;
1973			}
1974#endif
1975		if (!com->st16650a) {
1976			if (!com->tx_fifo_size)
1977				com->tx_fifo_size = 16;
1978			else
1979				printf(" lookalike with %d bytes FIFO",
1980				    com->tx_fifo_size);
1981		}
1982
1983		break;
1984	}
1985
1986#ifdef PC98
1987	if (com->pc98_if_type == COM_IF_RSB3000) {
1988	    /* Set RSB-2000/3000 Extended Buffer mode. */
1989	    u_char lcr;
1990	    lcr = sio_getreg(com, com_cfcr);
1991	    sio_setreg(com, com_cfcr, lcr | CFCR_DLAB);
1992	    sio_setreg(com, com_emr, EMR_EXBUFF | EMR_EFMODE);
1993	    sio_setreg(com, com_cfcr, lcr);
1994	}
1995#endif
1996
1997#ifdef COM_ESP
1998	if (com->esp) {
1999		/*
2000		 * Set 16550 compatibility mode.
2001		 * We don't use the ESP_MODE_SCALE bit to increase the
2002		 * fifo trigger levels because we can't handle large
2003		 * bursts of input.
2004		 * XXX flow control should be set in comparam(), not here.
2005		 */
2006#ifdef PC98
2007		outb(com->esp_port + ESP98_CMD1, ESP_SETMODE);
2008		outb(com->esp_port + ESP98_CMD2, ESP_MODE_RTS | ESP_MODE_FIFO);
2009#else
2010		outb(com->esp_port + ESP_CMD1, ESP_SETMODE);
2011		outb(com->esp_port + ESP_CMD2, ESP_MODE_RTS | ESP_MODE_FIFO);
2012#endif
2013
2014		/* Set RTS/CTS flow control. */
2015#ifdef PC98
2016		outb(com->esp_port + ESP98_CMD1, ESP_SETFLOWTYPE);
2017		outb(com->esp_port + ESP98_CMD2, ESP_FLOW_RTS);
2018		outb(com->esp_port + ESP98_CMD2, ESP_FLOW_CTS);
2019#else
2020		outb(com->esp_port + ESP_CMD1, ESP_SETFLOWTYPE);
2021		outb(com->esp_port + ESP_CMD2, ESP_FLOW_RTS);
2022		outb(com->esp_port + ESP_CMD2, ESP_FLOW_CTS);
2023#endif
2024
2025		/* Set flow-control levels. */
2026#ifdef PC98
2027		outb(com->esp_port + ESP98_CMD1, ESP_SETRXFLOW);
2028		outb(com->esp_port + ESP98_CMD2, HIBYTE(768));
2029		outb(com->esp_port + ESP98_CMD2, LOBYTE(768));
2030		outb(com->esp_port + ESP98_CMD2, HIBYTE(512));
2031		outb(com->esp_port + ESP98_CMD2, LOBYTE(512));
2032#else
2033		outb(com->esp_port + ESP_CMD1, ESP_SETRXFLOW);
2034		outb(com->esp_port + ESP_CMD2, HIBYTE(768));
2035		outb(com->esp_port + ESP_CMD2, LOBYTE(768));
2036		outb(com->esp_port + ESP_CMD2, HIBYTE(512));
2037		outb(com->esp_port + ESP_CMD2, LOBYTE(512));
2038#endif
2039
2040#ifdef PC98
2041                /* Set UART clock prescaler. */
2042                outb(com->esp_port + ESP98_CMD1, ESP_SETCLOCK);
2043                outb(com->esp_port + ESP98_CMD2, 2);	/* 4 times */
2044#endif
2045	}
2046#endif /* COM_ESP */
2047	sio_setreg(com, com_fifo, 0);
2048#ifdef PC98
2049	printf("%s", if_16550a_type[com->pc98_if_type & 0x0f].name);
2050#else
2051determined_type: ;
2052#endif
2053
2054#ifdef COM_MULTIPORT
2055	if (COM_ISMULTIPORT(flags)) {
2056		device_t masterdev;
2057
2058		com->multiport = TRUE;
2059		printf(" (multiport");
2060		if (unit == COM_MPMASTER(flags))
2061			printf(" master");
2062		printf(")");
2063		masterdev = devclass_get_device(sio_devclass,
2064		    COM_MPMASTER(flags));
2065		com->no_irq = (masterdev == NULL || bus_get_resource(masterdev,
2066		    SYS_RES_IRQ, 0, NULL, NULL) != 0);
2067	 }
2068#endif /* COM_MULTIPORT */
2069#ifdef PC98
2070	}
2071#endif
2072	if (unit == comconsole)
2073		printf(", console");
2074	if (COM_IIR_TXRDYBUG(flags))
2075		printf(" with a bogus IIR_TXRDY register");
2076	printf("\n");
2077
2078	if (!sio_registered) {
2079		register_swi(SWI_TTY, siopoll);
2080		sio_registered = TRUE;
2081	}
2082	make_dev(&sio_cdevsw, unit,
2083	    UID_ROOT, GID_WHEEL, 0600, "ttyd%r", unit);
2084	make_dev(&sio_cdevsw, unit | CONTROL_INIT_STATE,
2085	    UID_ROOT, GID_WHEEL, 0600, "ttyid%r", unit);
2086	make_dev(&sio_cdevsw, unit | CONTROL_LOCK_STATE,
2087	    UID_ROOT, GID_WHEEL, 0600, "ttyld%r", unit);
2088	make_dev(&sio_cdevsw, unit | CALLOUT_MASK,
2089	    UID_UUCP, GID_DIALER, 0660, "cuaa%r", unit);
2090	make_dev(&sio_cdevsw, unit | CALLOUT_MASK | CONTROL_INIT_STATE,
2091	    UID_UUCP, GID_DIALER, 0660, "cuaia%r", unit);
2092	make_dev(&sio_cdevsw, unit | CALLOUT_MASK | CONTROL_LOCK_STATE,
2093	    UID_UUCP, GID_DIALER, 0660, "cuala%r", unit);
2094	com->flags = flags;
2095	com->pps.ppscap = PPS_CAPTUREASSERT | PPS_CAPTURECLEAR;
2096	pps_init(&com->pps);
2097
2098	rid = 0;
2099	com->irqres = bus_alloc_resource(dev, SYS_RES_IRQ, &rid, 0ul, ~0ul, 1,
2100	    RF_ACTIVE);
2101	if (com->irqres) {
2102		ret = BUS_SETUP_INTR(device_get_parent(dev), dev, com->irqres,
2103				     INTR_TYPE_TTY | INTR_FAST,
2104				     siointr, com, &com->cookie);
2105		if (ret) {
2106			ret = BUS_SETUP_INTR(device_get_parent(dev), dev,
2107					     com->irqres, INTR_TYPE_TTY,
2108					     siointr, com, &com->cookie);
2109			if (ret == 0)
2110				device_printf(dev, "unable to activate interrupt in fast mode - using normal mode");
2111		}
2112		if (ret)
2113			device_printf(dev, "could not activate interrupt\n");
2114	}
2115
2116	return (0);
2117}
2118
2119static int
2120sioopen(dev, flag, mode, p)
2121	dev_t		dev;
2122	int		flag;
2123	int		mode;
2124	struct proc	*p;
2125{
2126	struct com_s	*com;
2127	int		error;
2128	int		mynor;
2129	int		s;
2130	struct tty	*tp;
2131	int		unit;
2132
2133	mynor = minor(dev);
2134	unit = MINOR_TO_UNIT(mynor);
2135	com = com_addr(unit);
2136	if (com == NULL)
2137		return (ENXIO);
2138	if (com->gone)
2139		return (ENXIO);
2140	if (mynor & CONTROL_MASK)
2141		return (0);
2142	tp = dev->si_tty = com->tp = ttymalloc(com->tp);
2143	s = spltty();
2144	/*
2145	 * We jump to this label after all non-interrupted sleeps to pick
2146	 * up any changes of the device state.
2147	 */
2148open_top:
2149	while (com->state & CS_DTR_OFF) {
2150		error = tsleep(&com->dtr_wait, TTIPRI | PCATCH, "siodtr", 0);
2151		if (com_addr(unit) == NULL)
2152			return (ENXIO);
2153		if (error != 0 || com->gone)
2154			goto out;
2155	}
2156	if (tp->t_state & TS_ISOPEN) {
2157		/*
2158		 * The device is open, so everything has been initialized.
2159		 * Handle conflicts.
2160		 */
2161		if (mynor & CALLOUT_MASK) {
2162			if (!com->active_out) {
2163				error = EBUSY;
2164				goto out;
2165			}
2166		} else {
2167			if (com->active_out) {
2168				if (flag & O_NONBLOCK) {
2169					error = EBUSY;
2170					goto out;
2171				}
2172				error =	tsleep(&com->active_out,
2173					       TTIPRI | PCATCH, "siobi", 0);
2174				if (com_addr(unit) == NULL)
2175					return (ENXIO);
2176				if (error != 0 || com->gone)
2177					goto out;
2178				goto open_top;
2179			}
2180		}
2181		if (tp->t_state & TS_XCLUDE &&
2182		    suser(p)) {
2183			error = EBUSY;
2184			goto out;
2185		}
2186	} else {
2187		int	intrsave;
2188
2189		/*
2190		 * The device isn't open, so there are no conflicts.
2191		 * Initialize it.  Initialization is done twice in many
2192		 * cases: to preempt sleeping callin opens if we are
2193		 * callout, and to complete a callin open after DCD rises.
2194		 */
2195		tp->t_oproc = comstart;
2196		tp->t_param = comparam;
2197		tp->t_stop = comstop;
2198		tp->t_dev = dev;
2199		tp->t_termios = mynor & CALLOUT_MASK
2200				? com->it_out : com->it_in;
2201#ifdef PC98
2202		if (!IS_8251(com->pc98_if_type))
2203#endif
2204		(void)commctl(com, TIOCM_DTR | TIOCM_RTS, DMSET);
2205		com->poll = com->no_irq;
2206		com->poll_output = com->loses_outints;
2207		++com->wopeners;
2208		error = comparam(tp, &tp->t_termios);
2209		--com->wopeners;
2210		if (error != 0)
2211			goto out;
2212#ifdef PC98
2213		if (IS_8251(com->pc98_if_type)) {
2214			com_tiocm_bis(com, TIOCM_DTR|TIOCM_RTS);
2215			pc98_msrint_start(dev);
2216			if (com->pc98_8251fifo) {
2217			    com->pc98_8251fifo_enable = 1;
2218			    outb(I8251F_fcr, CTRL8251F_ENABLE |
2219				 CTRL8251F_XMT_RST | CTRL8251F_RCV_RST);
2220			}
2221		}
2222#endif
2223		/*
2224		 * XXX we should goto open_top if comparam() slept.
2225		 */
2226		if (com->hasfifo) {
2227			/*
2228			 * (Re)enable and drain fifos.
2229			 *
2230			 * Certain SMC chips cause problems if the fifos
2231			 * are enabled while input is ready.  Turn off the
2232			 * fifo if necessary to clear the input.  We test
2233			 * the input ready bit after enabling the fifos
2234			 * since we've already enabled them in comparam()
2235			 * and to handle races between enabling and fresh
2236			 * input.
2237			 */
2238			while (TRUE) {
2239				sio_setreg(com, com_fifo,
2240					   FIFO_RCV_RST | FIFO_XMT_RST
2241					   | com->fifo_image);
2242#ifdef PC98
2243				if (com->pc98_if_type == COM_IF_RSA98III)
2244					outb(com->rsabase + rsa_frr , 0x00);
2245#endif
2246				/*
2247				 * XXX the delays are for superstitious
2248				 * historical reasons.  It must be less than
2249				 * the character time at the maximum
2250				 * supported speed (87 usec at 115200 bps
2251				 * 8N1).  Otherwise we might loop endlessly
2252				 * if data is streaming in.  We used to use
2253				 * delays of 100.  That usually worked
2254				 * because DELAY(100) used to usually delay
2255				 * for about 85 usec instead of 100.
2256				 */
2257				DELAY(50);
2258#ifdef PC98
2259				if (com->pc98_if_type == COM_IF_RSA98III ?
2260				    !(inb(com->rsabase + rsa_srr) & 0x08) :
2261				    !(inb(com->line_status_port) & LSR_RXRDY))
2262					break;
2263#else
2264				if (!(inb(com->line_status_port) & LSR_RXRDY))
2265					break;
2266#endif
2267				sio_setreg(com, com_fifo, 0);
2268				DELAY(50);
2269				(void) inb(com->data_port);
2270			}
2271		}
2272
2273		intrsave = save_intr();
2274		disable_intr();
2275		COM_LOCK();
2276#ifdef PC98
2277		if (IS_8251(com->pc98_if_type)) {
2278		    com_tiocm_bis(com, TIOCM_LE);
2279		    com->pc98_prev_modem_status = pc98_get_modem_status(com);
2280		    com_int_Rx_enable(com);
2281		} else {
2282#endif
2283		(void) inb(com->line_status_port);
2284		(void) inb(com->data_port);
2285		com->prev_modem_status = com->last_modem_status
2286		    = inb(com->modem_status_port);
2287		if (COM_IIR_TXRDYBUG(com->flags)) {
2288			outb(com->intr_ctl_port, IER_ERXRDY | IER_ERLS
2289						| IER_EMSC);
2290		} else {
2291			outb(com->intr_ctl_port, IER_ERXRDY | IER_ETXRDY
2292						| IER_ERLS | IER_EMSC);
2293		}
2294#ifdef PC98
2295		if (com->pc98_if_type == COM_IF_RSA98III) {
2296			outb(com->rsabase + rsa_ier, 0x1d);
2297			outb(com->intr_ctl_port, IER_ERLS | IER_EMSC);
2298		}
2299#endif
2300#ifdef PC98
2301		}
2302#endif
2303		COM_UNLOCK();
2304		restore_intr(intrsave);
2305		/*
2306		 * Handle initial DCD.  Callout devices get a fake initial
2307		 * DCD (trapdoor DCD).  If we are callout, then any sleeping
2308		 * callin opens get woken up and resume sleeping on "siobi"
2309		 * instead of "siodcd".
2310		 */
2311		/*
2312		 * XXX `mynor & CALLOUT_MASK' should be
2313		 * `tp->t_cflag & (SOFT_CARRIER | TRAPDOOR_CARRIER) where
2314		 * TRAPDOOR_CARRIER is the default initial state for callout
2315		 * devices and SOFT_CARRIER is like CLOCAL except it hides
2316		 * the true carrier.
2317		 */
2318#ifdef PC98
2319		if ((IS_8251(com->pc98_if_type) &&
2320			(pc98_get_modem_status(com) & TIOCM_CAR)) ||
2321		    (!IS_8251(com->pc98_if_type) &&
2322			(com->prev_modem_status & MSR_DCD)) ||
2323		    mynor & CALLOUT_MASK)
2324			(*linesw[tp->t_line].l_modem)(tp, 1);
2325#else
2326		if (com->prev_modem_status & MSR_DCD || mynor & CALLOUT_MASK)
2327			(*linesw[tp->t_line].l_modem)(tp, 1);
2328#endif
2329	}
2330	/*
2331	 * Wait for DCD if necessary.
2332	 */
2333	if (!(tp->t_state & TS_CARR_ON) && !(mynor & CALLOUT_MASK)
2334	    && !(tp->t_cflag & CLOCAL) && !(flag & O_NONBLOCK)) {
2335		++com->wopeners;
2336		error = tsleep(TSA_CARR_ON(tp), TTIPRI | PCATCH, "siodcd", 0);
2337		if (com_addr(unit) == NULL)
2338			return (ENXIO);
2339		--com->wopeners;
2340		if (error != 0 || com->gone)
2341			goto out;
2342		goto open_top;
2343	}
2344	error =	(*linesw[tp->t_line].l_open)(dev, tp);
2345	disc_optim(tp, &tp->t_termios, com);
2346	if (tp->t_state & TS_ISOPEN && mynor & CALLOUT_MASK)
2347		com->active_out = TRUE;
2348	siosettimeout();
2349out:
2350	splx(s);
2351	if (!(tp->t_state & TS_ISOPEN) && com->wopeners == 0)
2352		comhardclose(com);
2353	return (error);
2354}
2355
2356static int
2357sioclose(dev, flag, mode, p)
2358	dev_t		dev;
2359	int		flag;
2360	int		mode;
2361	struct proc	*p;
2362{
2363	struct com_s	*com;
2364	int		mynor;
2365	int		s;
2366	struct tty	*tp;
2367
2368	mynor = minor(dev);
2369	if (mynor & CONTROL_MASK)
2370		return (0);
2371	com = com_addr(MINOR_TO_UNIT(mynor));
2372	if (com == NULL)
2373		return (ENODEV);
2374	tp = com->tp;
2375	s = spltty();
2376	(*linesw[tp->t_line].l_close)(tp, flag);
2377#ifdef PC98
2378	com->modem_checking = 0;
2379#endif
2380	disc_optim(tp, &tp->t_termios, com);
2381	comstop(tp, FREAD | FWRITE);
2382	comhardclose(com);
2383	ttyclose(tp);
2384	siosettimeout();
2385	splx(s);
2386	if (com->gone) {
2387		printf("sio%d: gone\n", com->unit);
2388		s = spltty();
2389		if (com->ibuf != NULL)
2390			free(com->ibuf, M_DEVBUF);
2391		bzero(tp, sizeof *tp);
2392		splx(s);
2393	}
2394	return (0);
2395}
2396
2397static void
2398comhardclose(com)
2399	struct com_s	*com;
2400{
2401	int		s;
2402	struct tty	*tp;
2403	int		unit;
2404
2405	unit = com->unit;
2406	s = spltty();
2407	com->poll = FALSE;
2408	com->poll_output = FALSE;
2409	com->do_timestamp = FALSE;
2410	com->do_dcd_timestamp = FALSE;
2411	com->pps.ppsparam.mode = 0;
2412#ifdef PC98
2413	if (IS_8251(com->pc98_if_type))
2414		com_send_break_off(com);
2415	else
2416#endif
2417	sio_setreg(com, com_cfcr, com->cfcr_image &= ~CFCR_SBREAK);
2418	{
2419#ifdef PC98
2420		int tmp;
2421		if (IS_8251(com->pc98_if_type))
2422			com_int_TxRx_disable(com);
2423		else
2424			sio_setreg(com, com_ier, 0);
2425		if (com->pc98_if_type == COM_IF_RSA98III)
2426			outb(com->rsabase + rsa_ier, 0x00);
2427#else
2428		sio_setreg(com, com_ier, 0);
2429#endif
2430		tp = com->tp;
2431#ifdef PC98
2432		if (IS_8251(com->pc98_if_type))
2433			tmp = pc98_get_modem_status(com) & TIOCM_CAR;
2434		else
2435			tmp = com->prev_modem_status & MSR_DCD;
2436#endif
2437		if (tp->t_cflag & HUPCL
2438		    /*
2439		     * XXX we will miss any carrier drop between here and the
2440		     * next open.  Perhaps we should watch DCD even when the
2441		     * port is closed; it is not sufficient to check it at
2442		     * the next open because it might go up and down while
2443		     * we're not watching.
2444		     */
2445		    || (!com->active_out
2446#ifdef PC98
2447			&& !(tmp)
2448#else
2449		        && !(com->prev_modem_status & MSR_DCD)
2450#endif
2451		        && !(com->it_in.c_cflag & CLOCAL))
2452		    || !(tp->t_state & TS_ISOPEN)) {
2453#ifdef PC98
2454			if (IS_8251(com->pc98_if_type))
2455			    com_tiocm_bic(com, TIOCM_DTR|TIOCM_RTS|TIOCM_LE);
2456			else
2457#endif
2458			(void)commctl(com, TIOCM_DTR, DMBIC);
2459			if (com->dtr_wait != 0 && !(com->state & CS_DTR_OFF)) {
2460				timeout(siodtrwakeup, com, com->dtr_wait);
2461				com->state |= CS_DTR_OFF;
2462			}
2463		}
2464#ifdef PC98
2465		else {
2466			if (IS_8251(com->pc98_if_type))
2467				com_tiocm_bic(com, TIOCM_LE);
2468		}
2469#endif
2470	}
2471#ifdef PC98
2472	if (com->pc98_8251fifo)	{
2473	    if (com->pc98_8251fifo_enable)
2474		outb(I8251F_fcr, CTRL8251F_XMT_RST | CTRL8251F_RCV_RST);
2475	    com->pc98_8251fifo_enable = 0;
2476	}
2477#endif
2478	if (com->hasfifo) {
2479		/*
2480		 * Disable fifos so that they are off after controlled
2481		 * reboots.  Some BIOSes fail to detect 16550s when the
2482		 * fifos are enabled.
2483		 */
2484		sio_setreg(com, com_fifo, 0);
2485	}
2486	com->active_out = FALSE;
2487	wakeup(&com->active_out);
2488	wakeup(TSA_CARR_ON(tp));	/* restart any wopeners */
2489	splx(s);
2490}
2491
2492static int
2493sioread(dev, uio, flag)
2494	dev_t		dev;
2495	struct uio	*uio;
2496	int		flag;
2497{
2498	int		mynor;
2499	struct com_s	*com;
2500
2501	mynor = minor(dev);
2502	if (mynor & CONTROL_MASK)
2503		return (ENODEV);
2504	com = com_addr(MINOR_TO_UNIT(mynor));
2505	if (com == NULL || com->gone)
2506		return (ENODEV);
2507	return ((*linesw[com->tp->t_line].l_read)(com->tp, uio, flag));
2508}
2509
2510static int
2511siowrite(dev, uio, flag)
2512	dev_t		dev;
2513	struct uio	*uio;
2514	int		flag;
2515{
2516	int		mynor;
2517	struct com_s	*com;
2518	int		unit;
2519
2520	mynor = minor(dev);
2521	if (mynor & CONTROL_MASK)
2522		return (ENODEV);
2523
2524	unit = MINOR_TO_UNIT(mynor);
2525	com = com_addr(unit);
2526	if (com == NULL || com->gone)
2527		return (ENODEV);
2528	/*
2529	 * (XXX) We disallow virtual consoles if the physical console is
2530	 * a serial port.  This is in case there is a display attached that
2531	 * is not the console.  In that situation we don't need/want the X
2532	 * server taking over the console.
2533	 */
2534	if (constty != NULL && unit == comconsole)
2535		constty = NULL;
2536	return ((*linesw[com->tp->t_line].l_write)(com->tp, uio, flag));
2537}
2538
2539static void
2540siobusycheck(chan)
2541	void	*chan;
2542{
2543	struct com_s	*com;
2544	int		s;
2545
2546	com = (struct com_s *)chan;
2547
2548	/*
2549	 * Clear TS_BUSY if low-level output is complete.
2550	 * spl locking is sufficient because siointr1() does not set CS_BUSY.
2551	 * If siointr1() clears CS_BUSY after we look at it, then we'll get
2552	 * called again.  Reading the line status port outside of siointr1()
2553	 * is safe because CS_BUSY is clear so there are no output interrupts
2554	 * to lose.
2555	 */
2556	s = spltty();
2557	if (com->state & CS_BUSY)
2558		com->extra_state &= ~CSE_BUSYCHECK;	/* False alarm. */
2559#ifdef	PC98
2560	else if ((IS_8251(com->pc98_if_type) &&
2561		  ((com->pc98_8251fifo_enable &&
2562		    (inb(I8251F_lsr) & (STS8251F_TxRDY | STS8251F_TxEMP))
2563		    == (STS8251F_TxRDY | STS8251F_TxEMP)) ||
2564		   (!com->pc98_8251fifo_enable &&
2565		    (inb(com->sts_port) & (STS8251_TxRDY | STS8251_TxEMP))
2566		    == (STS8251_TxRDY | STS8251_TxEMP)))) ||
2567		 ((inb(com->line_status_port) & (LSR_TSRE | LSR_TXRDY))
2568		  == (LSR_TSRE | LSR_TXRDY))) {
2569#else
2570	else if ((inb(com->line_status_port) & (LSR_TSRE | LSR_TXRDY))
2571	    == (LSR_TSRE | LSR_TXRDY)) {
2572#endif
2573		com->tp->t_state &= ~TS_BUSY;
2574		ttwwakeup(com->tp);
2575		com->extra_state &= ~CSE_BUSYCHECK;
2576	} else
2577		timeout(siobusycheck, com, hz / 100);
2578	splx(s);
2579}
2580
2581static void
2582siodtrwakeup(chan)
2583	void	*chan;
2584{
2585	struct com_s	*com;
2586
2587	com = (struct com_s *)chan;
2588	com->state &= ~CS_DTR_OFF;
2589	wakeup(&com->dtr_wait);
2590}
2591
2592/*
2593 * Call this function with COM_LOCK.  It will return with the lock still held.
2594 */
2595static void
2596sioinput(com)
2597	struct com_s	*com;
2598{
2599	u_char		*buf;
2600	int		incc;
2601	u_char		line_status;
2602	int		recv_data;
2603	struct tty	*tp;
2604	int		intrsave;
2605
2606	buf = com->ibuf;
2607	tp = com->tp;
2608	if (!(tp->t_state & TS_ISOPEN) || !(tp->t_cflag & CREAD)) {
2609		com_events -= (com->iptr - com->ibuf);
2610		com->iptr = com->ibuf;
2611		return;
2612	}
2613	if (tp->t_state & TS_CAN_BYPASS_L_RINT) {
2614		/*
2615		 * Avoid the grotesquely inefficient lineswitch routine
2616		 * (ttyinput) in "raw" mode.  It usually takes about 450
2617		 * instructions (that's without canonical processing or echo!).
2618		 * slinput is reasonably fast (usually 40 instructions plus
2619		 * call overhead).
2620		 */
2621		do {
2622			/*
2623			 * This may look odd, but it is using save-and-enable
2624			 * semantics instead of the save-and-disable semantics
2625			 * that are used everywhere else.
2626			 */
2627			intrsave = save_intr();
2628			COM_UNLOCK();
2629			enable_intr();
2630			incc = com->iptr - buf;
2631			if (tp->t_rawq.c_cc + incc > tp->t_ihiwat
2632			    && (com->state & CS_RTS_IFLOW
2633				|| tp->t_iflag & IXOFF)
2634			    && !(tp->t_state & TS_TBLOCK))
2635				ttyblock(tp);
2636			com->delta_error_counts[CE_TTY_BUF_OVERFLOW]
2637				+= b_to_q((char *)buf, incc, &tp->t_rawq);
2638			buf += incc;
2639			tk_nin += incc;
2640			tk_rawcc += incc;
2641			tp->t_rawcc += incc;
2642			ttwakeup(tp);
2643			if (tp->t_state & TS_TTSTOP
2644			    && (tp->t_iflag & IXANY
2645				|| tp->t_cc[VSTART] == tp->t_cc[VSTOP])) {
2646				tp->t_state &= ~TS_TTSTOP;
2647				tp->t_lflag &= ~FLUSHO;
2648				comstart(tp);
2649			}
2650			restore_intr(intrsave);
2651			COM_LOCK();
2652		} while (buf < com->iptr);
2653	} else {
2654		do {
2655			/*
2656			 * This may look odd, but it is using save-and-enable
2657			 * semantics instead of the save-and-disable semantics
2658			 * that are used everywhere else.
2659			 */
2660			intrsave = save_intr();
2661			COM_UNLOCK();
2662			enable_intr();
2663			line_status = buf[com->ierroff];
2664			recv_data = *buf++;
2665			if (line_status
2666			    & (LSR_BI | LSR_FE | LSR_OE | LSR_PE)) {
2667				if (line_status & LSR_BI)
2668					recv_data |= TTY_BI;
2669				if (line_status & LSR_FE)
2670					recv_data |= TTY_FE;
2671				if (line_status & LSR_OE)
2672					recv_data |= TTY_OE;
2673				if (line_status & LSR_PE)
2674					recv_data |= TTY_PE;
2675			}
2676			(*linesw[tp->t_line].l_rint)(recv_data, tp);
2677			restore_intr(intrsave);
2678			COM_LOCK();
2679		} while (buf < com->iptr);
2680	}
2681	com_events -= (com->iptr - com->ibuf);
2682	com->iptr = com->ibuf;
2683
2684	/*
2685	 * There is now room for another low-level buffer full of input,
2686	 * so enable RTS if it is now disabled and there is room in the
2687	 * high-level buffer.
2688	 */
2689#ifdef PC98
2690	if (IS_8251(com->pc98_if_type)) {
2691		if ((com->state & CS_RTS_IFLOW) &&
2692		    !(com_tiocm_get(com) & TIOCM_RTS) &&
2693		    !(tp->t_state & TS_TBLOCK))
2694			com_tiocm_bis(com, TIOCM_RTS);
2695	} else {
2696		if ((com->state & CS_RTS_IFLOW) &&
2697		    !(com->mcr_image & MCR_RTS) &&
2698		    !(tp->t_state & TS_TBLOCK))
2699			outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
2700	}
2701#else
2702	if ((com->state & CS_RTS_IFLOW) && !(com->mcr_image & MCR_RTS) &&
2703	    !(tp->t_state & TS_TBLOCK))
2704		outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
2705#endif
2706}
2707
2708void
2709siointr(arg)
2710	void		*arg;
2711{
2712#ifndef COM_MULTIPORT
2713	COM_LOCK();
2714	siointr1((struct com_s *) arg);
2715	COM_UNLOCK();
2716#else /* COM_MULTIPORT */
2717	bool_t		possibly_more_intrs;
2718	int		unit;
2719	struct com_s	*com;
2720#ifdef PC98
2721	u_char		rsa_buf_status;
2722#endif
2723
2724	/*
2725	 * Loop until there is no activity on any port.  This is necessary
2726	 * to get an interrupt edge more than to avoid another interrupt.
2727	 * If the IRQ signal is just an OR of the IRQ signals from several
2728	 * devices, then the edge from one may be lost because another is
2729	 * on.
2730	 */
2731	COM_LOCK();
2732	do {
2733		possibly_more_intrs = FALSE;
2734		for (unit = 0; unit < sio_numunits; ++unit) {
2735			com = com_addr(unit);
2736			/*
2737			 * XXX COM_LOCK();
2738			 * would it work here, or be counter-productive?
2739			 */
2740#ifdef PC98
2741			if (com != NULL
2742			    && !com->gone
2743			    && IS_8251(com->pc98_if_type)) {
2744				siointr1(com);
2745			} else if (com != NULL
2746			    && !com->gone
2747			    && com->pc98_if_type == COM_IF_RSA98III) {
2748				rsa_buf_status =
2749				    inb(com->rsabase + rsa_srr) & 0xc9;
2750				if ((rsa_buf_status & 0xc8)
2751				    || !(rsa_buf_status & 0x01)) {
2752				    siointr1(com);
2753				    if (rsa_buf_status !=
2754					(inb(com->rsabase + rsa_srr) & 0xc9))
2755					possibly_more_intrs = TRUE;
2756				}
2757			} else
2758#endif
2759			if (com != NULL
2760			    && !com->gone
2761			    && (inb(com->int_id_port) & IIR_IMASK)
2762			       != IIR_NOPEND) {
2763				siointr1(com);
2764				possibly_more_intrs = TRUE;
2765			}
2766			/* XXX COM_UNLOCK(); */
2767		}
2768	} while (possibly_more_intrs);
2769	COM_UNLOCK();
2770#endif /* COM_MULTIPORT */
2771}
2772
2773static void
2774siointr1(com)
2775	struct com_s	*com;
2776{
2777	u_char	line_status;
2778	u_char	modem_status;
2779	u_char	*ioptr;
2780	u_char	recv_data;
2781	u_char	int_ctl;
2782	u_char	int_ctl_new;
2783	struct	timecounter *tc;
2784	u_int	count;
2785
2786#ifdef PC98
2787	u_char	tmp = 0;
2788	u_char	rsa_buf_status = 0;
2789	int	rsa_tx_fifo_size = 0;
2790#endif /* PC98 */
2791
2792	int_ctl = inb(com->intr_ctl_port);
2793	int_ctl_new = int_ctl;
2794
2795	while (!com->gone) {
2796#ifdef PC98
2797status_read:;
2798		if (IS_8251(com->pc98_if_type)) {
2799			if (com->pc98_8251fifo_enable)
2800				tmp = inb(I8251F_lsr);
2801			else
2802				tmp = inb(com->sts_port);
2803more_intr:
2804			line_status = 0;
2805			if (com->pc98_8251fifo_enable) {
2806			    if (tmp & STS8251F_TxRDY) line_status |= LSR_TXRDY;
2807			    if (tmp & STS8251F_RxRDY) line_status |= LSR_RXRDY;
2808			    if (tmp & STS8251F_TxEMP) line_status |= LSR_TSRE;
2809			    if (tmp & STS8251F_PE)    line_status |= LSR_PE;
2810			    if (tmp & STS8251F_OE)    line_status |= LSR_OE;
2811			    if (tmp & STS8251F_BD_SD) line_status |= LSR_BI;
2812			} else {
2813			    if (tmp & STS8251_TxRDY)  line_status |= LSR_TXRDY;
2814			    if (tmp & STS8251_RxRDY)  line_status |= LSR_RXRDY;
2815			    if (tmp & STS8251_TxEMP)  line_status |= LSR_TSRE;
2816			    if (tmp & STS8251_PE)     line_status |= LSR_PE;
2817			    if (tmp & STS8251_OE)     line_status |= LSR_OE;
2818			    if (tmp & STS8251_FE)     line_status |= LSR_FE;
2819			    if (tmp & STS8251_BD_SD)  line_status |= LSR_BI;
2820			}
2821		} else {
2822#endif /* PC98 */
2823		if (com->pps.ppsparam.mode & PPS_CAPTUREBOTH) {
2824			modem_status = inb(com->modem_status_port);
2825		        if ((modem_status ^ com->last_modem_status) & MSR_DCD) {
2826				tc = timecounter;
2827				count = tc->tc_get_timecount(tc);
2828				pps_event(&com->pps, tc, count,
2829				    (modem_status & MSR_DCD) ?
2830				    PPS_CAPTUREASSERT : PPS_CAPTURECLEAR);
2831			}
2832		}
2833		line_status = inb(com->line_status_port);
2834#ifdef PC98
2835		}
2836		if (com->pc98_if_type == COM_IF_RSA98III)
2837			rsa_buf_status = inb(com->rsabase + rsa_srr);
2838#endif /* PC98 */
2839
2840		/* input event? (check first to help avoid overruns) */
2841#ifndef PC98
2842		while (line_status & LSR_RCV_MASK) {
2843#else
2844		while ((line_status & LSR_RCV_MASK)
2845		       || (com->pc98_if_type == COM_IF_RSA98III
2846			   && (rsa_buf_status & 0x08))) {
2847#endif /* PC98 */
2848			/* break/unnattached error bits or real input? */
2849#ifdef PC98
2850			if (IS_8251(com->pc98_if_type)) {
2851				if (com->pc98_8251fifo_enable) {
2852				    recv_data = inb(I8251F_data);
2853				    if (tmp & (STS8251F_PE | STS8251F_OE |
2854					       STS8251F_BD_SD)) {
2855					pc98_i8251_or_cmd(com, CMD8251_ER);
2856					recv_data = 0;
2857				    }
2858				} else {
2859				    recv_data = inb(com->data_port);
2860				    if (tmp & (STS8251_PE | STS8251_OE |
2861					       STS8251_FE | STS8251_BD_SD)) {
2862					pc98_i8251_or_cmd(com, CMD8251_ER);
2863					recv_data = 0;
2864				    }
2865				}
2866			} else if (com->pc98_if_type == COM_IF_RSA98III) {
2867				if (!(rsa_buf_status & 0x08))
2868					recv_data = 0;
2869				else
2870					recv_data = inb(com->data_port);
2871			} else
2872#endif
2873			if (!(line_status & LSR_RXRDY))
2874				recv_data = 0;
2875			else
2876				recv_data = inb(com->data_port);
2877			if (line_status & (LSR_BI | LSR_FE | LSR_PE)) {
2878				/*
2879				 * Don't store BI if IGNBRK or FE/PE if IGNPAR.
2880				 * Otherwise, push the work to a higher level
2881				 * (to handle PARMRK) if we're bypassing.
2882				 * Otherwise, convert BI/FE and PE+INPCK to 0.
2883				 *
2884				 * This makes bypassing work right in the
2885				 * usual "raw" case (IGNBRK set, and IGNPAR
2886				 * and INPCK clear).
2887				 *
2888				 * Note: BI together with FE/PE means just BI.
2889				 */
2890				if (line_status & LSR_BI) {
2891#if defined(DDB) && defined(BREAK_TO_DEBUGGER)
2892					if (com->unit == comconsole) {
2893						breakpoint();
2894						goto cont;
2895					}
2896#endif
2897					if (com->tp == NULL
2898					    || com->tp->t_iflag & IGNBRK)
2899						goto cont;
2900				} else {
2901					if (com->tp == NULL
2902					    || com->tp->t_iflag & IGNPAR)
2903						goto cont;
2904				}
2905				if (com->tp->t_state & TS_CAN_BYPASS_L_RINT
2906				    && (line_status & (LSR_BI | LSR_FE)
2907					|| com->tp->t_iflag & INPCK))
2908					recv_data = 0;
2909			}
2910			++com->bytes_in;
2911			if (com->hotchar != 0 && recv_data == com->hotchar)
2912				setsofttty();
2913			ioptr = com->iptr;
2914			if (ioptr >= com->ibufend)
2915				CE_RECORD(com, CE_INTERRUPT_BUF_OVERFLOW);
2916			else {
2917				if (com->do_timestamp)
2918					microtime(&com->timestamp);
2919				++com_events;
2920/* XXX - needs to go away when alpha gets ithreads */
2921#ifdef __alpha__
2922				schedsofttty();
2923#endif
2924#if 0 /* for testing input latency vs efficiency */
2925if (com->iptr - com->ibuf == 8)
2926	setsofttty();
2927#endif
2928				ioptr[0] = recv_data;
2929				ioptr[com->ierroff] = line_status;
2930				com->iptr = ++ioptr;
2931				if (ioptr == com->ihighwater
2932				    && com->state & CS_RTS_IFLOW)
2933#ifdef PC98
2934					IS_8251(com->pc98_if_type) ?
2935						com_tiocm_bic(com, TIOCM_RTS) :
2936#endif
2937					outb(com->modem_ctl_port,
2938					     com->mcr_image &= ~MCR_RTS);
2939				if (line_status & LSR_OE)
2940					CE_RECORD(com, CE_OVERRUN);
2941			}
2942cont:
2943			/*
2944			 * "& 0x7F" is to avoid the gcc-1.40 generating a slow
2945			 * jump from the top of the loop to here
2946			 */
2947#ifdef PC98
2948			if (IS_8251(com->pc98_if_type))
2949				goto status_read;
2950			else
2951#endif
2952			line_status = inb(com->line_status_port) & 0x7F;
2953#ifdef PC98
2954			if (com->pc98_if_type == COM_IF_RSA98III)
2955				rsa_buf_status = inb(com->rsabase + rsa_srr);
2956#endif /* PC98 */
2957		}
2958
2959		/* modem status change? (always check before doing output) */
2960#ifdef PC98
2961		if (!IS_8251(com->pc98_if_type)) {
2962#endif
2963		modem_status = inb(com->modem_status_port);
2964		if (modem_status != com->last_modem_status) {
2965			if (com->do_dcd_timestamp
2966			    && !(com->last_modem_status & MSR_DCD)
2967			    && modem_status & MSR_DCD)
2968				microtime(&com->dcd_timestamp);
2969
2970			/*
2971			 * Schedule high level to handle DCD changes.  Note
2972			 * that we don't use the delta bits anywhere.  Some
2973			 * UARTs mess them up, and it's easy to remember the
2974			 * previous bits and calculate the delta.
2975			 */
2976			com->last_modem_status = modem_status;
2977			if (!(com->state & CS_CHECKMSR)) {
2978				com_events += LOTS_OF_EVENTS;
2979				com->state |= CS_CHECKMSR;
2980				setsofttty();
2981			}
2982
2983			/* handle CTS change immediately for crisp flow ctl */
2984			if (com->state & CS_CTS_OFLOW) {
2985				if (modem_status & MSR_CTS)
2986					com->state |= CS_ODEVREADY;
2987				else
2988					com->state &= ~CS_ODEVREADY;
2989			}
2990		}
2991#ifdef PC98
2992		}
2993#endif
2994
2995		/* output queued and everything ready? */
2996#ifndef PC98
2997		if (line_status & LSR_TXRDY
2998		    && com->state >= (CS_BUSY | CS_TTGO | CS_ODEVREADY)) {
2999#else
3000		if (((com->pc98_if_type == COM_IF_RSA98III)
3001		     ? (rsa_buf_status & 0x02)
3002		     : (line_status & LSR_TXRDY))
3003		    && com->state >= (CS_BUSY | CS_TTGO | CS_ODEVREADY)) {
3004#endif
3005#ifdef PC98
3006			Port_t	tmp_data_port;
3007
3008			if (IS_8251(com->pc98_if_type) &&
3009			    com->pc98_8251fifo_enable)
3010				tmp_data_port = I8251F_data;
3011			else
3012				tmp_data_port = com->data_port;
3013#endif
3014
3015			ioptr = com->obufq.l_head;
3016			if (com->tx_fifo_size > 1) {
3017				u_int	ocount;
3018
3019				ocount = com->obufq.l_tail - ioptr;
3020#ifdef PC98
3021				if (com->pc98_if_type == COM_IF_RSA98III) {
3022				  rsa_buf_status = inb(com->rsabase + rsa_srr);
3023				  rsa_tx_fifo_size = 1024;
3024				  if (!(rsa_buf_status & 0x01))
3025				      rsa_tx_fifo_size = 2048;
3026				  if (ocount > rsa_tx_fifo_size)
3027				      ocount = rsa_tx_fifo_size;
3028				} else
3029#endif
3030				if (ocount > com->tx_fifo_size)
3031					ocount = com->tx_fifo_size;
3032				com->bytes_out += ocount;
3033				do
3034#ifdef PC98
3035					outb(tmp_data_port, *ioptr++);
3036#else
3037					outb(com->data_port, *ioptr++);
3038#endif
3039				while (--ocount != 0);
3040			} else {
3041#ifdef PC98
3042				outb(tmp_data_port, *ioptr++);
3043#else
3044				outb(com->data_port, *ioptr++);
3045#endif
3046				++com->bytes_out;
3047			}
3048#ifdef PC98
3049			if (IS_8251(com->pc98_if_type))
3050			    if (!(pc98_check_i8251_interrupt(com) & IEN_TxFLAG))
3051				com_int_Tx_enable(com);
3052#endif
3053			com->obufq.l_head = ioptr;
3054			if (COM_IIR_TXRDYBUG(com->flags)) {
3055				int_ctl_new = int_ctl | IER_ETXRDY;
3056			}
3057			if (ioptr >= com->obufq.l_tail) {
3058				struct lbq	*qp;
3059
3060				qp = com->obufq.l_next;
3061				qp->l_queued = FALSE;
3062				qp = qp->l_next;
3063				if (qp != NULL) {
3064					com->obufq.l_head = qp->l_head;
3065					com->obufq.l_tail = qp->l_tail;
3066					com->obufq.l_next = qp;
3067				} else {
3068					/* output just completed */
3069					if (COM_IIR_TXRDYBUG(com->flags)) {
3070						int_ctl_new = int_ctl & ~IER_ETXRDY;
3071					}
3072					com->state &= ~CS_BUSY;
3073#if defined(PC98)
3074					if (IS_8251(com->pc98_if_type) &&
3075					    pc98_check_i8251_interrupt(com) & IEN_TxFLAG)
3076						com_int_Tx_disable(com);
3077#endif
3078				}
3079				if (!(com->state & CS_ODONE)) {
3080					com_events += LOTS_OF_EVENTS;
3081					com->state |= CS_ODONE;
3082					setsofttty();	/* handle at high level ASAP */
3083				}
3084			}
3085			if (COM_IIR_TXRDYBUG(com->flags) && (int_ctl != int_ctl_new)) {
3086#ifdef PC98
3087				if (com->pc98_if_type == COM_IF_RSA98III) {
3088				    int_ctl_new &= ~(IER_ETXRDY | IER_ERXRDY);
3089				    outb(com->intr_ctl_port, int_ctl_new);
3090				    outb(com->rsabase + rsa_ier, 0x1d);
3091				} else
3092#endif
3093				outb(com->intr_ctl_port, int_ctl_new);
3094			}
3095		}
3096#ifdef PC98
3097		else if (line_status & LSR_TXRDY) {
3098		    if (IS_8251(com->pc98_if_type))
3099			if (pc98_check_i8251_interrupt(com) & IEN_TxFLAG)
3100			    com_int_Tx_disable(com);
3101		}
3102		if (IS_8251(com->pc98_if_type)) {
3103		    if (com->pc98_8251fifo_enable) {
3104			if ((tmp = inb(I8251F_lsr)) & STS8251F_RxRDY)
3105			    goto more_intr;
3106		    } else {
3107			if ((tmp = inb(com->sts_port)) & STS8251_RxRDY)
3108			    goto more_intr;
3109		    }
3110		}
3111#endif
3112
3113		/* finished? */
3114#ifndef COM_MULTIPORT
3115#ifdef PC98
3116		if (IS_8251(com->pc98_if_type))
3117			return;
3118#endif
3119		if ((inb(com->int_id_port) & IIR_IMASK) == IIR_NOPEND)
3120#endif /* COM_MULTIPORT */
3121			return;
3122	}
3123}
3124
3125static int
3126sioioctl(dev, cmd, data, flag, p)
3127	dev_t		dev;
3128	u_long		cmd;
3129	caddr_t		data;
3130	int		flag;
3131	struct proc	*p;
3132{
3133	struct com_s	*com;
3134	int		error;
3135	int		mynor;
3136	int		s;
3137	struct tty	*tp;
3138#if defined(COMPAT_43) || defined(COMPAT_SUNOS)
3139	u_long		oldcmd;
3140	struct termios	term;
3141#endif
3142
3143	mynor = minor(dev);
3144	com = com_addr(MINOR_TO_UNIT(mynor));
3145	if (com == NULL || com->gone)
3146		return (ENODEV);
3147	if (mynor & CONTROL_MASK) {
3148		struct termios	*ct;
3149
3150		switch (mynor & CONTROL_MASK) {
3151		case CONTROL_INIT_STATE:
3152			ct = mynor & CALLOUT_MASK ? &com->it_out : &com->it_in;
3153			break;
3154		case CONTROL_LOCK_STATE:
3155			ct = mynor & CALLOUT_MASK ? &com->lt_out : &com->lt_in;
3156			break;
3157		default:
3158			return (ENODEV);	/* /dev/nodev */
3159		}
3160		switch (cmd) {
3161		case TIOCSETA:
3162			error = suser(p);
3163			if (error != 0)
3164				return (error);
3165			*ct = *(struct termios *)data;
3166			return (0);
3167		case TIOCGETA:
3168			*(struct termios *)data = *ct;
3169			return (0);
3170		case TIOCGETD:
3171			*(int *)data = TTYDISC;
3172			return (0);
3173		case TIOCGWINSZ:
3174			bzero(data, sizeof(struct winsize));
3175			return (0);
3176		default:
3177			return (ENOTTY);
3178		}
3179	}
3180	tp = com->tp;
3181#if defined(COMPAT_43) || defined(COMPAT_SUNOS)
3182	term = tp->t_termios;
3183	oldcmd = cmd;
3184	error = ttsetcompat(tp, &cmd, data, &term);
3185	if (error != 0)
3186		return (error);
3187	if (cmd != oldcmd)
3188		data = (caddr_t)&term;
3189#endif
3190	if (cmd == TIOCSETA || cmd == TIOCSETAW || cmd == TIOCSETAF) {
3191		int	cc;
3192		struct termios *dt = (struct termios *)data;
3193		struct termios *lt = mynor & CALLOUT_MASK
3194				     ? &com->lt_out : &com->lt_in;
3195
3196		dt->c_iflag = (tp->t_iflag & lt->c_iflag)
3197			      | (dt->c_iflag & ~lt->c_iflag);
3198		dt->c_oflag = (tp->t_oflag & lt->c_oflag)
3199			      | (dt->c_oflag & ~lt->c_oflag);
3200		dt->c_cflag = (tp->t_cflag & lt->c_cflag)
3201			      | (dt->c_cflag & ~lt->c_cflag);
3202		dt->c_lflag = (tp->t_lflag & lt->c_lflag)
3203			      | (dt->c_lflag & ~lt->c_lflag);
3204		for (cc = 0; cc < NCCS; ++cc)
3205			if (lt->c_cc[cc] != 0)
3206				dt->c_cc[cc] = tp->t_cc[cc];
3207		if (lt->c_ispeed != 0)
3208			dt->c_ispeed = tp->t_ispeed;
3209		if (lt->c_ospeed != 0)
3210			dt->c_ospeed = tp->t_ospeed;
3211	}
3212	error = (*linesw[tp->t_line].l_ioctl)(tp, cmd, data, flag, p);
3213	if (error != ENOIOCTL)
3214		return (error);
3215	s = spltty();
3216	error = ttioctl(tp, cmd, data, flag);
3217	disc_optim(tp, &tp->t_termios, com);
3218	if (error != ENOIOCTL) {
3219		splx(s);
3220		return (error);
3221	}
3222#ifdef PC98
3223	if (IS_8251(com->pc98_if_type)) {
3224	    switch (cmd) {
3225	    case TIOCSBRK:
3226		com_send_break_on(com);
3227		break;
3228	    case TIOCCBRK:
3229		com_send_break_off(com);
3230		break;
3231	    case TIOCSDTR:
3232		com_tiocm_bis(com, TIOCM_DTR | TIOCM_RTS);
3233		break;
3234	    case TIOCCDTR:
3235		com_tiocm_bic(com, TIOCM_DTR);
3236		break;
3237	/*
3238	 * XXX should disallow changing MCR_RTS if CS_RTS_IFLOW is set.  The
3239	 * changes get undone on the next call to comparam().
3240	 */
3241	    case TIOCMSET:
3242		com_tiocm_set(com, *(int *)data);
3243		break;
3244	    case TIOCMBIS:
3245		com_tiocm_bis(com, *(int *)data);
3246		break;
3247	    case TIOCMBIC:
3248		com_tiocm_bic(com, *(int *)data);
3249		break;
3250	    case TIOCMGET:
3251		*(int *)data = com_tiocm_get(com);
3252		break;
3253	    case TIOCMSDTRWAIT:
3254		/* must be root since the wait applies to following logins */
3255		error = suser(p);
3256		if (error != 0) {
3257			splx(s);
3258			return (error);
3259		}
3260		com->dtr_wait = *(int *)data * hz / 100;
3261		break;
3262	    case TIOCMGDTRWAIT:
3263		*(int *)data = com->dtr_wait * 100 / hz;
3264		break;
3265	    case TIOCTIMESTAMP:
3266		com->do_timestamp = TRUE;
3267		*(struct timeval *)data = com->timestamp;
3268		break;
3269	    case TIOCDCDTIMESTAMP:
3270		com->do_dcd_timestamp = TRUE;
3271		*(struct timeval *)data = com->dcd_timestamp;
3272		break;
3273	    default:
3274		splx(s);
3275		error = pps_ioctl(cmd, data, &com->pps);
3276		if (error == ENODEV)
3277			error = ENOTTY;
3278		return (error);
3279	    }
3280	} else {
3281#endif
3282	switch (cmd) {
3283	case TIOCSBRK:
3284		sio_setreg(com, com_cfcr, com->cfcr_image |= CFCR_SBREAK);
3285		break;
3286	case TIOCCBRK:
3287		sio_setreg(com, com_cfcr, com->cfcr_image &= ~CFCR_SBREAK);
3288		break;
3289	case TIOCSDTR:
3290		(void)commctl(com, TIOCM_DTR, DMBIS);
3291		break;
3292	case TIOCCDTR:
3293		(void)commctl(com, TIOCM_DTR, DMBIC);
3294		break;
3295	/*
3296	 * XXX should disallow changing MCR_RTS if CS_RTS_IFLOW is set.  The
3297	 * changes get undone on the next call to comparam().
3298	 */
3299	case TIOCMSET:
3300		(void)commctl(com, *(int *)data, DMSET);
3301		break;
3302	case TIOCMBIS:
3303		(void)commctl(com, *(int *)data, DMBIS);
3304		break;
3305	case TIOCMBIC:
3306		(void)commctl(com, *(int *)data, DMBIC);
3307		break;
3308	case TIOCMGET:
3309		*(int *)data = commctl(com, 0, DMGET);
3310		break;
3311	case TIOCMSDTRWAIT:
3312		/* must be root since the wait applies to following logins */
3313		error = suser(p);
3314		if (error != 0) {
3315			splx(s);
3316			return (error);
3317		}
3318		com->dtr_wait = *(int *)data * hz / 100;
3319		break;
3320	case TIOCMGDTRWAIT:
3321		*(int *)data = com->dtr_wait * 100 / hz;
3322		break;
3323	case TIOCTIMESTAMP:
3324		com->do_timestamp = TRUE;
3325		*(struct timeval *)data = com->timestamp;
3326		break;
3327	case TIOCDCDTIMESTAMP:
3328		com->do_dcd_timestamp = TRUE;
3329		*(struct timeval *)data = com->dcd_timestamp;
3330		break;
3331	default:
3332		splx(s);
3333		error = pps_ioctl(cmd, data, &com->pps);
3334		if (error == ENODEV)
3335			error = ENOTTY;
3336		return (error);
3337	}
3338#ifdef PC98
3339	}
3340#endif
3341	splx(s);
3342	return (0);
3343}
3344
3345/* software interrupt handler for SWI_TTY */
3346static void
3347siopoll()
3348{
3349	int		unit;
3350	int		intrsave;
3351
3352	if (com_events == 0)
3353		return;
3354repeat:
3355	for (unit = 0; unit < sio_numunits; ++unit) {
3356		struct com_s	*com;
3357		int		incc;
3358		struct tty	*tp;
3359
3360		com = com_addr(unit);
3361		if (com == NULL)
3362			continue;
3363		tp = com->tp;
3364		if (tp == NULL || com->gone) {
3365			/*
3366			 * Discard any events related to never-opened or
3367			 * going-away devices.
3368			 */
3369			intrsave = save_intr();
3370			disable_intr();
3371			COM_LOCK();
3372			incc = com->iptr - com->ibuf;
3373			com->iptr = com->ibuf;
3374			if (com->state & CS_CHECKMSR) {
3375				incc += LOTS_OF_EVENTS;
3376				com->state &= ~CS_CHECKMSR;
3377			}
3378			com_events -= incc;
3379			COM_UNLOCK();
3380			restore_intr(intrsave);
3381			continue;
3382		}
3383		if (com->iptr != com->ibuf) {
3384			intrsave = save_intr();
3385			disable_intr();
3386			COM_LOCK();
3387			sioinput(com);
3388			COM_UNLOCK();
3389			restore_intr(intrsave);
3390		}
3391		if (com->state & CS_CHECKMSR) {
3392			u_char	delta_modem_status;
3393
3394#ifdef PC98
3395			if (!IS_8251(com->pc98_if_type)) {
3396#endif
3397			intrsave = save_intr();
3398			disable_intr();
3399			COM_LOCK();
3400			delta_modem_status = com->last_modem_status
3401					     ^ com->prev_modem_status;
3402			com->prev_modem_status = com->last_modem_status;
3403			com_events -= LOTS_OF_EVENTS;
3404			com->state &= ~CS_CHECKMSR;
3405			COM_UNLOCK();
3406			restore_intr(intrsave);
3407			if (delta_modem_status & MSR_DCD)
3408				(*linesw[tp->t_line].l_modem)
3409					(tp, com->prev_modem_status & MSR_DCD);
3410#ifdef PC98
3411			}
3412#endif
3413		}
3414		if (com->state & CS_ODONE) {
3415			intrsave = save_intr();
3416			disable_intr();
3417			COM_LOCK();
3418			com_events -= LOTS_OF_EVENTS;
3419			com->state &= ~CS_ODONE;
3420			COM_UNLOCK();
3421			restore_intr(intrsave);
3422			if (!(com->state & CS_BUSY)
3423			    && !(com->extra_state & CSE_BUSYCHECK)) {
3424				timeout(siobusycheck, com, hz / 100);
3425				com->extra_state |= CSE_BUSYCHECK;
3426			}
3427			(*linesw[tp->t_line].l_start)(tp);
3428		}
3429		if (com_events == 0)
3430			break;
3431	}
3432	if (com_events >= LOTS_OF_EVENTS)
3433		goto repeat;
3434}
3435
3436static int
3437comparam(tp, t)
3438	struct tty	*tp;
3439	struct termios	*t;
3440{
3441	u_int		cfcr;
3442	int		cflag;
3443	struct com_s	*com;
3444	int		divisor;
3445	u_char		dlbh;
3446	u_char		dlbl;
3447	int		s;
3448	int		unit;
3449	int		intrsave;
3450#ifdef PC98
3451	u_char		param = 0;
3452#endif
3453
3454#ifdef PC98
3455	unit = DEV_TO_UNIT(tp->t_dev);
3456	com = com_addr(unit);
3457
3458	cfcr = 0;
3459	if (IS_8251(com->pc98_if_type)) {
3460	    divisor = pc98_ttspeedtab(com, t->c_ospeed);
3461	} else {
3462	    /* do historical conversions */
3463	    if (t->c_ispeed == 0)
3464		t->c_ispeed = t->c_ospeed;
3465
3466	    /* check requested parameters */
3467	    divisor = ttspeedtab(t->c_ospeed,
3468			if_16550a_type[com->pc98_if_type & 0x0f].speedtab);
3469	}
3470#else
3471	/* do historical conversions */
3472	if (t->c_ispeed == 0)
3473		t->c_ispeed = t->c_ospeed;
3474
3475	/* check requested parameters */
3476	divisor = ttspeedtab(t->c_ospeed, comspeedtab);
3477#endif
3478	if (divisor < 0 || (divisor > 0 && t->c_ispeed != t->c_ospeed))
3479		return (EINVAL);
3480
3481#ifndef PC98
3482	/* parameters are OK, convert them to the com struct and the device */
3483	unit = DEV_TO_UNIT(tp->t_dev);
3484	com = com_addr(unit);
3485	if (com == NULL)
3486		return (ENODEV);
3487#endif
3488	s = spltty();
3489#ifdef PC98
3490	if (IS_8251(com->pc98_if_type)) {
3491		if (divisor == 0)
3492			com_tiocm_bic(com, TIOCM_DTR|TIOCM_RTS|TIOCM_LE);
3493		else
3494			com_tiocm_bis(com, TIOCM_DTR|TIOCM_RTS|TIOCM_LE);
3495	} else
3496#endif
3497	if (divisor == 0)
3498		(void)commctl(com, TIOCM_DTR, DMBIC);	/* hang up line */
3499	else
3500		(void)commctl(com, TIOCM_DTR, DMBIS);
3501	cflag = t->c_cflag;
3502#ifdef PC98
3503	if (!IS_8251(com->pc98_if_type)) {
3504#endif
3505	switch (cflag & CSIZE) {
3506	case CS5:
3507		cfcr = CFCR_5BITS;
3508		break;
3509	case CS6:
3510		cfcr = CFCR_6BITS;
3511		break;
3512	case CS7:
3513		cfcr = CFCR_7BITS;
3514		break;
3515	default:
3516		cfcr = CFCR_8BITS;
3517		break;
3518	}
3519	if (cflag & PARENB) {
3520		cfcr |= CFCR_PENAB;
3521		if (!(cflag & PARODD))
3522			cfcr |= CFCR_PEVEN;
3523	}
3524	if (cflag & CSTOPB)
3525		cfcr |= CFCR_STOPB;
3526
3527	if (com->hasfifo && divisor != 0) {
3528		/*
3529		 * Use a fifo trigger level low enough so that the input
3530		 * latency from the fifo is less than about 16 msec and
3531		 * the total latency is less than about 30 msec.  These
3532		 * latencies are reasonable for humans.  Serial comms
3533		 * protocols shouldn't expect anything better since modem
3534		 * latencies are larger.
3535		 */
3536		com->fifo_image = t->c_ospeed <= 4800
3537				  ? FIFO_ENABLE : FIFO_ENABLE | FIFO_RX_HIGH;
3538#ifdef COM_ESP
3539		/*
3540		 * The Hayes ESP card needs the fifo DMA mode bit set
3541		 * in compatibility mode.  If not, it will interrupt
3542		 * for each character received.
3543		 */
3544		if (com->esp)
3545			com->fifo_image |= FIFO_DMA_MODE;
3546#endif
3547		sio_setreg(com, com_fifo, com->fifo_image);
3548	}
3549#ifdef PC98
3550	}
3551#endif
3552
3553	intrsave = save_intr();
3554	disable_intr();
3555	COM_LOCK();
3556
3557	(void) siosetwater(com, t->c_ispeed);
3558
3559#ifdef PC98
3560	if (IS_8251(com->pc98_if_type))
3561		com_cflag_and_speed_set(com, cflag, t->c_ospeed);
3562	else {
3563#endif
3564	if (divisor != 0) {
3565		sio_setreg(com, com_cfcr, cfcr | CFCR_DLAB);
3566		/*
3567		 * Only set the divisor registers if they would change,
3568		 * since on some 16550 incompatibles (UMC8669F), setting
3569		 * them while input is arriving them loses sync until
3570		 * data stops arriving.
3571		 */
3572		dlbl = divisor & 0xFF;
3573		if (sio_getreg(com, com_dlbl) != dlbl)
3574			sio_setreg(com, com_dlbl, dlbl);
3575		dlbh = (u_int) divisor >> 8;
3576		if (sio_getreg(com, com_dlbh) != dlbh)
3577			sio_setreg(com, com_dlbh, dlbh);
3578	}
3579
3580	sio_setreg(com, com_cfcr, com->cfcr_image = cfcr);
3581#ifdef PC98
3582	}
3583#endif
3584
3585	if (!(tp->t_state & TS_TTSTOP))
3586		com->state |= CS_TTGO;
3587
3588	if (cflag & CRTS_IFLOW) {
3589#ifndef PC98
3590		if (com->st16650a) {
3591			sio_setreg(com, com_cfcr, 0xbf);
3592			sio_setreg(com, com_fifo,
3593				   sio_getreg(com, com_fifo) | 0x40);
3594		}
3595#endif
3596		com->state |= CS_RTS_IFLOW;
3597		/*
3598		 * If CS_RTS_IFLOW just changed from off to on, the change
3599		 * needs to be propagated to MCR_RTS.  This isn't urgent,
3600		 * so do it later by calling comstart() instead of repeating
3601		 * a lot of code from comstart() here.
3602		 */
3603	} else if (com->state & CS_RTS_IFLOW) {
3604		com->state &= ~CS_RTS_IFLOW;
3605		/*
3606		 * CS_RTS_IFLOW just changed from on to off.  Force MCR_RTS
3607		 * on here, since comstart() won't do it later.
3608		 */
3609#ifdef PC98
3610		if (IS_8251(com->pc98_if_type))
3611			com_tiocm_bis(com, TIOCM_RTS);
3612		else
3613			outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
3614#else
3615		outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
3616		if (com->st16650a) {
3617			sio_setreg(com, com_cfcr, 0xbf);
3618			sio_setreg(com, com_fifo,
3619				   sio_getreg(com, com_fifo) & ~0x40);
3620		}
3621#endif
3622	}
3623
3624
3625	/*
3626	 * Set up state to handle output flow control.
3627	 * XXX - worth handling MDMBUF (DCD) flow control at the lowest level?
3628	 * Now has 10+ msec latency, while CTS flow has 50- usec latency.
3629	 */
3630	com->state |= CS_ODEVREADY;
3631	com->state &= ~CS_CTS_OFLOW;
3632#ifdef PC98
3633	if (com->pc98_if_type == COM_IF_RSA98III) {
3634		param = inb(com->rsabase + rsa_msr);
3635		outb(com->rsabase + rsa_msr, param & 0x14);
3636	}
3637#endif
3638	if (cflag & CCTS_OFLOW) {
3639		com->state |= CS_CTS_OFLOW;
3640#ifdef PC98
3641		if (IS_8251(com->pc98_if_type)) {
3642			if (!(pc98_get_modem_status(com) & TIOCM_CTS))
3643				com->state &= ~CS_ODEVREADY;
3644		} else {
3645			if (com->pc98_if_type == COM_IF_RSA98III) {
3646				/* Set automatic flow control mode */
3647				outb(com->rsabase + rsa_msr, param | 0x08);
3648			} else
3649#endif
3650		if (!(com->last_modem_status & MSR_CTS))
3651			com->state &= ~CS_ODEVREADY;
3652#ifdef PC98
3653		}
3654#else
3655		if (com->st16650a) {
3656			sio_setreg(com, com_cfcr, 0xbf);
3657			sio_setreg(com, com_fifo,
3658				   sio_getreg(com, com_fifo) | 0x80);
3659		}
3660	} else {
3661		if (com->st16650a) {
3662			sio_setreg(com, com_cfcr, 0xbf);
3663			sio_setreg(com, com_fifo,
3664				   sio_getreg(com, com_fifo) & ~0x80);
3665		}
3666#endif
3667	}
3668
3669#ifdef PC98
3670	if (!IS_8251(com->pc98_if_type))
3671#endif
3672	sio_setreg(com, com_cfcr, com->cfcr_image);
3673
3674	/* XXX shouldn't call functions while intrs are disabled. */
3675	disc_optim(tp, t, com);
3676	/*
3677	 * Recover from fiddling with CS_TTGO.  We used to call siointr1()
3678	 * unconditionally, but that defeated the careful discarding of
3679	 * stale input in sioopen().
3680	 */
3681	if (com->state >= (CS_BUSY | CS_TTGO))
3682		siointr1(com);
3683
3684	COM_UNLOCK();
3685	restore_intr(intrsave);
3686	splx(s);
3687	comstart(tp);
3688	if (com->ibufold != NULL) {
3689		free(com->ibufold, M_DEVBUF);
3690		com->ibufold = NULL;
3691	}
3692	return (0);
3693}
3694
3695static int
3696siosetwater(com, speed)
3697	struct com_s	*com;
3698	speed_t		speed;
3699{
3700	int		cp4ticks;
3701	u_char		*ibuf;
3702	int		ibufsize;
3703	struct tty	*tp;
3704	int		intrsave;
3705
3706	/*
3707	 * Make the buffer size large enough to handle a softtty interrupt
3708	 * latency of about 2 ticks without loss of throughput or data
3709	 * (about 3 ticks if input flow control is not used or not honoured,
3710	 * but a bit less for CS5-CS7 modes).
3711	 */
3712	cp4ticks = speed / 10 / hz * 4;
3713	for (ibufsize = 128; ibufsize < cp4ticks;)
3714		ibufsize <<= 1;
3715#ifdef PC98
3716	if (com->pc98_if_type == COM_IF_RSA98III)
3717		ibufsize = 2048;
3718#endif
3719	if (ibufsize == com->ibufsize)
3720		return (0);
3721
3722	/*
3723	 * Allocate input buffer.  The extra factor of 2 in the size is
3724	 * to allow for an error byte for each input byte.
3725	 */
3726	ibuf = malloc(2 * ibufsize, M_DEVBUF, M_NOWAIT);
3727	if (ibuf == NULL)
3728		return (ENOMEM);
3729
3730	/* Initialize non-critical variables. */
3731	com->ibufold = com->ibuf;
3732	com->ibufsize = ibufsize;
3733	tp = com->tp;
3734	if (tp != NULL) {
3735		tp->t_ififosize = 2 * ibufsize;
3736		tp->t_ispeedwat = (speed_t)-1;
3737		tp->t_ospeedwat = (speed_t)-1;
3738	}
3739
3740	/*
3741	 * Read current input buffer, if any.  Continue with interrupts
3742	 * disabled.
3743	 */
3744	intrsave = save_intr();
3745	disable_intr();
3746	COM_LOCK();
3747	if (com->iptr != com->ibuf)
3748		sioinput(com);
3749
3750	/*-
3751	 * Initialize critical variables, including input buffer watermarks.
3752	 * The external device is asked to stop sending when the buffer
3753	 * exactly reaches high water, or when the high level requests it.
3754	 * The high level is notified immediately (rather than at a later
3755	 * clock tick) when this watermark is reached.
3756	 * The buffer size is chosen so the watermark should almost never
3757	 * be reached.
3758	 * The low watermark is invisibly 0 since the buffer is always
3759	 * emptied all at once.
3760	 */
3761	com->iptr = com->ibuf = ibuf;
3762	com->ibufend = ibuf + ibufsize;
3763	com->ierroff = ibufsize;
3764	com->ihighwater = ibuf + 3 * ibufsize / 4;
3765	COM_UNLOCK();
3766	restore_intr(intrsave);
3767	return (0);
3768}
3769
3770static void
3771comstart(tp)
3772	struct tty	*tp;
3773{
3774	struct com_s	*com;
3775	int		s;
3776	int		unit;
3777	int		intrsave;
3778
3779	unit = DEV_TO_UNIT(tp->t_dev);
3780	com = com_addr(unit);
3781	if (com == NULL)
3782		return;
3783	s = spltty();
3784	intrsave = save_intr();
3785	disable_intr();
3786	COM_LOCK();
3787	if (tp->t_state & TS_TTSTOP)
3788		com->state &= ~CS_TTGO;
3789	else
3790		com->state |= CS_TTGO;
3791	if (tp->t_state & TS_TBLOCK) {
3792#ifdef PC98
3793		if (IS_8251(com->pc98_if_type)) {
3794		    if ((com_tiocm_get(com) & TIOCM_RTS) &&
3795			(com->state & CS_RTS_IFLOW))
3796			com_tiocm_bic(com, TIOCM_RTS);
3797		} else {
3798		    if ((com->mcr_image & MCR_RTS) &&
3799			(com->state & CS_RTS_IFLOW))
3800			outb(com->modem_ctl_port, com->mcr_image &= ~MCR_RTS);
3801		}
3802#else
3803		if (com->mcr_image & MCR_RTS && com->state & CS_RTS_IFLOW)
3804			outb(com->modem_ctl_port, com->mcr_image &= ~MCR_RTS);
3805#endif
3806	} else {
3807#ifdef PC98
3808		if (IS_8251(com->pc98_if_type)) {
3809		    if (!(com_tiocm_get(com) & TIOCM_RTS) &&
3810			com->iptr < com->ihighwater &&
3811			com->state & CS_RTS_IFLOW)
3812			com_tiocm_bis(com, TIOCM_RTS);
3813		} else {
3814		    if (!(com->mcr_image & MCR_RTS) &&
3815			com->iptr < com->ihighwater &&
3816			com->state & CS_RTS_IFLOW)
3817			outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
3818		}
3819#else
3820		if (!(com->mcr_image & MCR_RTS) && com->iptr < com->ihighwater
3821		    && com->state & CS_RTS_IFLOW)
3822			outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
3823#endif
3824	}
3825	COM_UNLOCK();
3826	restore_intr(intrsave);
3827	if (tp->t_state & (TS_TIMEOUT | TS_TTSTOP)) {
3828		ttwwakeup(tp);
3829		splx(s);
3830		return;
3831	}
3832	if (tp->t_outq.c_cc != 0) {
3833		struct lbq	*qp;
3834		struct lbq	*next;
3835
3836		if (!com->obufs[0].l_queued) {
3837			com->obufs[0].l_tail
3838			    = com->obuf1 + q_to_b(&tp->t_outq, com->obuf1,
3839#ifdef PC98
3840						  com->obufsize);
3841#else
3842						  sizeof com->obuf1);
3843#endif
3844			com->obufs[0].l_next = NULL;
3845			com->obufs[0].l_queued = TRUE;
3846			intrsave = save_intr();
3847			disable_intr();
3848			COM_LOCK();
3849			if (com->state & CS_BUSY) {
3850				qp = com->obufq.l_next;
3851				while ((next = qp->l_next) != NULL)
3852					qp = next;
3853				qp->l_next = &com->obufs[0];
3854			} else {
3855				com->obufq.l_head = com->obufs[0].l_head;
3856				com->obufq.l_tail = com->obufs[0].l_tail;
3857				com->obufq.l_next = &com->obufs[0];
3858				com->state |= CS_BUSY;
3859			}
3860			COM_UNLOCK();
3861			restore_intr(intrsave);
3862		}
3863		if (tp->t_outq.c_cc != 0 && !com->obufs[1].l_queued) {
3864			com->obufs[1].l_tail
3865			    = com->obuf2 + q_to_b(&tp->t_outq, com->obuf2,
3866#ifdef PC98
3867						  com->obufsize);
3868#else
3869						  sizeof com->obuf2);
3870#endif
3871			com->obufs[1].l_next = NULL;
3872			com->obufs[1].l_queued = TRUE;
3873			intrsave = save_intr();
3874			disable_intr();
3875			COM_LOCK();
3876			if (com->state & CS_BUSY) {
3877				qp = com->obufq.l_next;
3878				while ((next = qp->l_next) != NULL)
3879					qp = next;
3880				qp->l_next = &com->obufs[1];
3881			} else {
3882				com->obufq.l_head = com->obufs[1].l_head;
3883				com->obufq.l_tail = com->obufs[1].l_tail;
3884				com->obufq.l_next = &com->obufs[1];
3885				com->state |= CS_BUSY;
3886			}
3887			COM_UNLOCK();
3888			restore_intr(intrsave);
3889		}
3890		tp->t_state |= TS_BUSY;
3891	}
3892	intrsave = save_intr();
3893	disable_intr();
3894	COM_LOCK();
3895	if (com->state >= (CS_BUSY | CS_TTGO))
3896		siointr1(com);	/* fake interrupt to start output */
3897	COM_UNLOCK();
3898	restore_intr(intrsave);
3899	ttwwakeup(tp);
3900	splx(s);
3901}
3902
3903static void
3904comstop(tp, rw)
3905	struct tty	*tp;
3906	int		rw;
3907{
3908	struct com_s	*com;
3909	int		intrsave;
3910#ifdef PC98
3911	int		rsa98_tmp  = 0;
3912#endif
3913
3914	com = com_addr(DEV_TO_UNIT(tp->t_dev));
3915	if (com == NULL || com->gone)
3916		return;
3917	intrsave = save_intr();
3918	disable_intr();
3919	COM_LOCK();
3920	if (rw & FWRITE) {
3921#ifdef PC98
3922		if (!IS_8251(com->pc98_if_type)) {
3923#endif
3924		if (com->hasfifo)
3925#ifdef COM_ESP
3926		    /* XXX avoid h/w bug. */
3927		    if (!com->esp)
3928#endif
3929			sio_setreg(com, com_fifo,
3930				   FIFO_XMT_RST | com->fifo_image);
3931#ifdef PC98
3932		if (com->pc98_if_type == COM_IF_RSA98III)
3933		    for (rsa98_tmp = 0; rsa98_tmp < 2048; rsa98_tmp++)
3934			sio_setreg(com, com_fifo,
3935				   FIFO_XMT_RST | com->fifo_image);
3936		}
3937#endif
3938		com->obufs[0].l_queued = FALSE;
3939		com->obufs[1].l_queued = FALSE;
3940		if (com->state & CS_ODONE)
3941			com_events -= LOTS_OF_EVENTS;
3942		com->state &= ~(CS_ODONE | CS_BUSY);
3943		com->tp->t_state &= ~TS_BUSY;
3944	}
3945	if (rw & FREAD) {
3946#ifdef PC98
3947		if (!IS_8251(com->pc98_if_type)) {
3948		    if (com->pc98_if_type == COM_IF_RSA98III)
3949			for (rsa98_tmp = 0; rsa98_tmp < 2048; rsa98_tmp++)
3950			    sio_getreg(com, com_data);
3951#endif
3952		if (com->hasfifo)
3953#ifdef COM_ESP
3954		    /* XXX avoid h/w bug. */
3955		    if (!com->esp)
3956#endif
3957			sio_setreg(com, com_fifo,
3958				   FIFO_RCV_RST | com->fifo_image);
3959#ifdef PC98
3960		}
3961#endif
3962		com_events -= (com->iptr - com->ibuf);
3963		com->iptr = com->ibuf;
3964	}
3965	COM_UNLOCK();
3966	restore_intr(intrsave);
3967	comstart(tp);
3968}
3969
3970static int
3971commctl(com, bits, how)
3972	struct com_s	*com;
3973	int		bits;
3974	int		how;
3975{
3976	int	mcr;
3977	int	msr;
3978	int	intrsave;
3979
3980	if (how == DMGET) {
3981		bits = TIOCM_LE;	/* XXX - always enabled while open */
3982		mcr = com->mcr_image;
3983		if (mcr & MCR_DTR)
3984			bits |= TIOCM_DTR;
3985		if (mcr & MCR_RTS)
3986			bits |= TIOCM_RTS;
3987		msr = com->prev_modem_status;
3988		if (msr & MSR_CTS)
3989			bits |= TIOCM_CTS;
3990		if (msr & MSR_DCD)
3991			bits |= TIOCM_CD;
3992		if (msr & MSR_DSR)
3993			bits |= TIOCM_DSR;
3994		/*
3995		 * XXX - MSR_RI is naturally volatile, and we make MSR_TERI
3996		 * more volatile by reading the modem status a lot.  Perhaps
3997		 * we should latch both bits until the status is read here.
3998		 */
3999		if (msr & (MSR_RI | MSR_TERI))
4000			bits |= TIOCM_RI;
4001		return (bits);
4002	}
4003	mcr = 0;
4004	if (bits & TIOCM_DTR)
4005		mcr |= MCR_DTR;
4006	if (bits & TIOCM_RTS)
4007		mcr |= MCR_RTS;
4008	if (com->gone)
4009		return(0);
4010	intrsave = save_intr();
4011	disable_intr();
4012	COM_LOCK();
4013	switch (how) {
4014	case DMSET:
4015		outb(com->modem_ctl_port,
4016		     com->mcr_image = mcr | (com->mcr_image & MCR_IENABLE));
4017		break;
4018	case DMBIS:
4019		outb(com->modem_ctl_port, com->mcr_image |= mcr);
4020		break;
4021	case DMBIC:
4022		outb(com->modem_ctl_port, com->mcr_image &= ~mcr);
4023		break;
4024	}
4025	COM_UNLOCK();
4026	restore_intr(intrsave);
4027	return (0);
4028}
4029
4030static void
4031siosettimeout()
4032{
4033	struct com_s	*com;
4034	bool_t		someopen;
4035	int		unit;
4036
4037	/*
4038	 * Set our timeout period to 1 second if no polled devices are open.
4039	 * Otherwise set it to max(1/200, 1/hz).
4040	 * Enable timeouts iff some device is open.
4041	 */
4042	untimeout(comwakeup, (void *)NULL, sio_timeout_handle);
4043	sio_timeout = hz;
4044	someopen = FALSE;
4045	for (unit = 0; unit < sio_numunits; ++unit) {
4046		com = com_addr(unit);
4047		if (com != NULL && com->tp != NULL
4048		    && com->tp->t_state & TS_ISOPEN && !com->gone) {
4049			someopen = TRUE;
4050			if (com->poll || com->poll_output) {
4051				sio_timeout = hz > 200 ? hz / 200 : 1;
4052				break;
4053			}
4054		}
4055	}
4056	if (someopen) {
4057		sio_timeouts_until_log = hz / sio_timeout;
4058		sio_timeout_handle = timeout(comwakeup, (void *)NULL,
4059					     sio_timeout);
4060	} else {
4061		/* Flush error messages, if any. */
4062		sio_timeouts_until_log = 1;
4063		comwakeup((void *)NULL);
4064		untimeout(comwakeup, (void *)NULL, sio_timeout_handle);
4065	}
4066}
4067
4068static void
4069comwakeup(chan)
4070	void	*chan;
4071{
4072	struct com_s	*com;
4073	int		unit;
4074	int		intrsave;
4075
4076	sio_timeout_handle = timeout(comwakeup, (void *)NULL, sio_timeout);
4077
4078	/*
4079	 * Recover from lost output interrupts.
4080	 * Poll any lines that don't use interrupts.
4081	 */
4082	for (unit = 0; unit < sio_numunits; ++unit) {
4083		com = com_addr(unit);
4084		if (com != NULL && !com->gone
4085		    && (com->state >= (CS_BUSY | CS_TTGO) || com->poll)) {
4086			intrsave = save_intr();
4087			disable_intr();
4088			COM_LOCK();
4089			siointr1(com);
4090			COM_UNLOCK();
4091			restore_intr(intrsave);
4092		}
4093	}
4094
4095	/*
4096	 * Check for and log errors, but not too often.
4097	 */
4098	if (--sio_timeouts_until_log > 0)
4099		return;
4100	sio_timeouts_until_log = hz / sio_timeout;
4101	for (unit = 0; unit < sio_numunits; ++unit) {
4102		int	errnum;
4103
4104		com = com_addr(unit);
4105		if (com == NULL)
4106			continue;
4107		if (com->gone)
4108			continue;
4109		for (errnum = 0; errnum < CE_NTYPES; ++errnum) {
4110			u_int	delta;
4111			u_long	total;
4112
4113			intrsave = save_intr();
4114			disable_intr();
4115			COM_LOCK();
4116			delta = com->delta_error_counts[errnum];
4117			com->delta_error_counts[errnum] = 0;
4118			COM_UNLOCK();
4119			restore_intr(intrsave);
4120			if (delta == 0)
4121				continue;
4122			total = com->error_counts[errnum] += delta;
4123			log(LOG_ERR, "sio%d: %u more %s%s (total %lu)\n",
4124			    unit, delta, error_desc[errnum],
4125			    delta == 1 ? "" : "s", total);
4126		}
4127	}
4128}
4129
4130#ifdef PC98
4131/* commint is called when modem control line changes */
4132static void
4133commint(dev_t dev)
4134{
4135	register struct tty *tp;
4136	int	stat,delta;
4137	struct com_s *com;
4138	int	mynor,unit;
4139
4140	mynor = minor(dev);
4141	unit = MINOR_TO_UNIT(mynor);
4142	com = com_addr(unit);
4143	tp = com->tp;
4144
4145	stat = com_tiocm_get(com);
4146	delta = com_tiocm_get_delta(com);
4147
4148	if (com->state & CS_CTS_OFLOW) {
4149		if (stat & TIOCM_CTS)
4150			com->state |= CS_ODEVREADY;
4151		else
4152			com->state &= ~CS_ODEVREADY;
4153	}
4154	if ((delta & TIOCM_CAR) && (mynor & CALLOUT_MASK) == 0) {
4155	    if (stat & TIOCM_CAR )
4156		(void)(*linesw[tp->t_line].l_modem)(tp, 1);
4157	    else if ((*linesw[tp->t_line].l_modem)(tp, 0) == 0) {
4158		/* negate DTR, RTS */
4159		com_tiocm_bic(com, (tp->t_cflag & HUPCL) ?
4160				TIOCM_DTR|TIOCM_RTS|TIOCM_LE : TIOCM_LE );
4161		/* disable IENABLE */
4162		com_int_TxRx_disable( com );
4163	    }
4164	}
4165}
4166#endif
4167
4168static void
4169disc_optim(tp, t, com)
4170	struct tty	*tp;
4171	struct termios	*t;
4172	struct com_s	*com;
4173{
4174	if (!(t->c_iflag & (ICRNL | IGNCR | IMAXBEL | INLCR | ISTRIP | IXON))
4175	    && (!(t->c_iflag & BRKINT) || (t->c_iflag & IGNBRK))
4176	    && (!(t->c_iflag & PARMRK)
4177		|| (t->c_iflag & (IGNPAR | IGNBRK)) == (IGNPAR | IGNBRK))
4178	    && !(t->c_lflag & (ECHO | ICANON | IEXTEN | ISIG | PENDIN))
4179	    && linesw[tp->t_line].l_rint == ttyinput)
4180		tp->t_state |= TS_CAN_BYPASS_L_RINT;
4181	else
4182		tp->t_state &= ~TS_CAN_BYPASS_L_RINT;
4183	com->hotchar = linesw[tp->t_line].l_hotchar;
4184}
4185
4186/*
4187 * Following are all routines needed for SIO to act as console
4188 */
4189#include <sys/cons.h>
4190
4191struct siocnstate {
4192	u_char	dlbl;
4193	u_char	dlbh;
4194	u_char	ier;
4195	u_char	cfcr;
4196	u_char	mcr;
4197};
4198
4199static speed_t siocngetspeed __P((Port_t, struct speedtab *));
4200static void siocnclose	__P((struct siocnstate *sp, Port_t iobase));
4201static void siocnopen	__P((struct siocnstate *sp, Port_t iobase, int speed));
4202static void siocntxwait	__P((Port_t iobase));
4203
4204static cn_probe_t siocnprobe;
4205static cn_init_t siocninit;
4206static cn_checkc_t siocncheckc;
4207static cn_getc_t siocngetc;
4208static cn_putc_t siocnputc;
4209
4210#ifdef __i386__
4211CONS_DRIVER(sio, siocnprobe, siocninit, NULL, siocngetc, siocncheckc,
4212	    siocnputc, NULL);
4213#endif
4214
4215/* To get the GDB related variables */
4216#if DDB > 0
4217#include <ddb/ddb.h>
4218#endif
4219
4220static void
4221siocntxwait(iobase)
4222	Port_t	iobase;
4223{
4224	int	timo;
4225
4226	/*
4227	 * Wait for any pending transmission to finish.  Required to avoid
4228	 * the UART lockup bug when the speed is changed, and for normal
4229	 * transmits.
4230	 */
4231	timo = 100000;
4232	while ((inb(iobase + com_lsr) & (LSR_TSRE | LSR_TXRDY))
4233	       != (LSR_TSRE | LSR_TXRDY) && --timo != 0)
4234		;
4235}
4236
4237/*
4238 * Read the serial port specified and try to figure out what speed
4239 * it's currently running at.  We're assuming the serial port has
4240 * been initialized and is basicly idle.  This routine is only intended
4241 * to be run at system startup.
4242 *
4243 * If the value read from the serial port doesn't make sense, return 0.
4244 */
4245
4246static speed_t
4247siocngetspeed(iobase, table)
4248	Port_t iobase;
4249	struct speedtab *table;
4250{
4251	int	code;
4252	u_char	dlbh;
4253	u_char	dlbl;
4254	u_char  cfcr;
4255
4256	cfcr = inb(iobase + com_cfcr);
4257	outb(iobase + com_cfcr, CFCR_DLAB | cfcr);
4258
4259	dlbl = inb(iobase + com_dlbl);
4260	dlbh = inb(iobase + com_dlbh);
4261
4262	outb(iobase + com_cfcr, cfcr);
4263
4264	code = dlbh << 8 | dlbl;
4265
4266	for (; table->sp_speed != -1; table++)
4267		if (table->sp_code == code)
4268			return (table->sp_speed);
4269
4270	return (0);	/* didn't match anything sane */
4271}
4272
4273static void
4274siocnopen(sp, iobase, speed)
4275	struct siocnstate	*sp;
4276	Port_t			iobase;
4277	int			speed;
4278{
4279	int	divisor;
4280	u_char	dlbh;
4281	u_char	dlbl;
4282
4283	/*
4284	 * Save all the device control registers except the fifo register
4285	 * and set our default ones (cs8 -parenb speed=comdefaultrate).
4286	 * We can't save the fifo register since it is read-only.
4287	 */
4288	sp->ier = inb(iobase + com_ier);
4289	outb(iobase + com_ier, 0);	/* spltty() doesn't stop siointr() */
4290	siocntxwait(iobase);
4291	sp->cfcr = inb(iobase + com_cfcr);
4292	outb(iobase + com_cfcr, CFCR_DLAB | CFCR_8BITS);
4293	sp->dlbl = inb(iobase + com_dlbl);
4294	sp->dlbh = inb(iobase + com_dlbh);
4295	/*
4296	 * Only set the divisor registers if they would change, since on
4297	 * some 16550 incompatibles (Startech), setting them clears the
4298	 * data input register.  This also reduces the effects of the
4299	 * UMC8669F bug.
4300	 */
4301	divisor = ttspeedtab(speed, comspeedtab);
4302	dlbl = divisor & 0xFF;
4303	if (sp->dlbl != dlbl)
4304		outb(iobase + com_dlbl, dlbl);
4305	dlbh = (u_int) divisor >> 8;
4306	if (sp->dlbh != dlbh)
4307		outb(iobase + com_dlbh, dlbh);
4308	outb(iobase + com_cfcr, CFCR_8BITS);
4309	sp->mcr = inb(iobase + com_mcr);
4310	/*
4311	 * We don't want interrupts, but must be careful not to "disable"
4312	 * them by clearing the MCR_IENABLE bit, since that might cause
4313	 * an interrupt by floating the IRQ line.
4314	 */
4315	outb(iobase + com_mcr, (sp->mcr & MCR_IENABLE) | MCR_DTR | MCR_RTS);
4316}
4317
4318static void
4319siocnclose(sp, iobase)
4320	struct siocnstate	*sp;
4321	Port_t			iobase;
4322{
4323	/*
4324	 * Restore the device control registers.
4325	 */
4326	siocntxwait(iobase);
4327	outb(iobase + com_cfcr, CFCR_DLAB | CFCR_8BITS);
4328	if (sp->dlbl != inb(iobase + com_dlbl))
4329		outb(iobase + com_dlbl, sp->dlbl);
4330	if (sp->dlbh != inb(iobase + com_dlbh))
4331		outb(iobase + com_dlbh, sp->dlbh);
4332	outb(iobase + com_cfcr, sp->cfcr);
4333	/*
4334	 * XXX damp oscillations of MCR_DTR and MCR_RTS by not restoring them.
4335	 */
4336	outb(iobase + com_mcr, sp->mcr | MCR_DTR | MCR_RTS);
4337	outb(iobase + com_ier, sp->ier);
4338}
4339
4340static void
4341siocnprobe(cp)
4342	struct consdev	*cp;
4343{
4344	speed_t			boot_speed;
4345	u_char			cfcr;
4346	int			s, unit;
4347	struct siocnstate	sp;
4348
4349	/*
4350	 * Find our first enabled console, if any.  If it is a high-level
4351	 * console device, then initialize it and return successfully.
4352	 * If it is a low-level console device, then initialize it and
4353	 * return unsuccessfully.  It must be initialized in both cases
4354	 * for early use by console drivers and debuggers.  Initializing
4355	 * the hardware is not necessary in all cases, since the i/o
4356	 * routines initialize it on the fly, but it is necessary if
4357	 * input might arrive while the hardware is switched back to an
4358	 * uninitialized state.  We can't handle multiple console devices
4359	 * yet because our low-level routines don't take a device arg.
4360	 * We trust the user to set the console flags properly so that we
4361	 * don't need to probe.
4362	 */
4363	cp->cn_pri = CN_DEAD;
4364
4365	for (unit = 0; unit < 16; unit++) { /* XXX need to know how many */
4366		int flags;
4367		int disabled;
4368		if (resource_int_value("sio", unit, "disabled", &disabled) == 0) {
4369			if (disabled)
4370				continue;
4371		}
4372		if (resource_int_value("sio", unit, "flags", &flags))
4373			continue;
4374		if (COM_CONSOLE(flags) || COM_DEBUGGER(flags)) {
4375			int port;
4376			Port_t iobase;
4377
4378			if (resource_int_value("sio", unit, "port", &port))
4379				continue;
4380			iobase = port;
4381			s = spltty();
4382			if (boothowto & RB_SERIAL) {
4383				boot_speed = siocngetspeed(iobase, comspeedtab);
4384				if (boot_speed)
4385					comdefaultrate = boot_speed;
4386			}
4387
4388			/*
4389			 * Initialize the divisor latch.  We can't rely on
4390			 * siocnopen() to do this the first time, since it
4391			 * avoids writing to the latch if the latch appears
4392			 * to have the correct value.  Also, if we didn't
4393			 * just read the speed from the hardware, then we
4394			 * need to set the speed in hardware so that
4395			 * switching it later is null.
4396			 */
4397			cfcr = inb(iobase + com_cfcr);
4398			outb(iobase + com_cfcr, CFCR_DLAB | cfcr);
4399			outb(iobase + com_dlbl,
4400			     COMBRD(comdefaultrate) & 0xff);
4401			outb(iobase + com_dlbh,
4402			     (u_int) COMBRD(comdefaultrate) >> 8);
4403			outb(iobase + com_cfcr, cfcr);
4404
4405			siocnopen(&sp, iobase, comdefaultrate);
4406
4407			splx(s);
4408			if (COM_CONSOLE(flags) && !COM_LLCONSOLE(flags)) {
4409				cp->cn_dev = makedev(CDEV_MAJOR, unit);
4410				cp->cn_pri = COM_FORCECONSOLE(flags)
4411					     || boothowto & RB_SERIAL
4412					     ? CN_REMOTE : CN_NORMAL;
4413				siocniobase = iobase;
4414				siocnunit = unit;
4415			}
4416			if (COM_DEBUGGER(flags)) {
4417				printf("sio%d: gdb debugging port\n", unit);
4418				siogdbiobase = iobase;
4419				siogdbunit = unit;
4420#if DDB > 0
4421				gdbdev = makedev(CDEV_MAJOR, unit);
4422				gdb_getc = siocngetc;
4423				gdb_putc = siocnputc;
4424#endif
4425			}
4426		}
4427	}
4428#ifdef	__i386__
4429#if DDB > 0
4430	/*
4431	 * XXX Ugly Compatability.
4432	 * If no gdb port has been specified, set it to be the console
4433	 * as some configuration files don't specify the gdb port.
4434	 */
4435	if (gdbdev == NODEV && (boothowto & RB_GDB)) {
4436		printf("Warning: no GDB port specified. Defaulting to sio%d.\n",
4437			siocnunit);
4438		printf("Set flag 0x80 on desired GDB port in your\n");
4439		printf("configuration file (currently sio only).\n");
4440		siogdbiobase = siocniobase;
4441		siogdbunit = siocnunit;
4442		gdbdev = makedev(CDEV_MAJOR, siocnunit);
4443		gdb_getc = siocngetc;
4444		gdb_putc = siocnputc;
4445	}
4446#endif
4447#endif
4448}
4449
4450#ifdef __alpha__
4451
4452CONS_DRIVER(sio, NULL, NULL, NULL, siocngetc, siocncheckc, siocnputc, NULL);
4453
4454int
4455siocnattach(port, speed)
4456	int port;
4457	int speed;
4458{
4459	int			s;
4460	u_char			cfcr;
4461	struct siocnstate	sp;
4462
4463	siocniobase = port;
4464	comdefaultrate = speed;
4465	sio_consdev.cn_pri = CN_NORMAL;
4466	sio_consdev.cn_dev = makedev(CDEV_MAJOR, 0);
4467
4468	s = spltty();
4469
4470	/*
4471	 * Initialize the divisor latch.  We can't rely on
4472	 * siocnopen() to do this the first time, since it
4473	 * avoids writing to the latch if the latch appears
4474	 * to have the correct value.  Also, if we didn't
4475	 * just read the speed from the hardware, then we
4476	 * need to set the speed in hardware so that
4477	 * switching it later is null.
4478	 */
4479	cfcr = inb(siocniobase + com_cfcr);
4480	outb(siocniobase + com_cfcr, CFCR_DLAB | cfcr);
4481	outb(siocniobase + com_dlbl,
4482	     COMBRD(comdefaultrate) & 0xff);
4483	outb(siocniobase + com_dlbh,
4484	     (u_int) COMBRD(comdefaultrate) >> 8);
4485	outb(siocniobase + com_cfcr, cfcr);
4486
4487	siocnopen(&sp, siocniobase, comdefaultrate);
4488	splx(s);
4489
4490	cn_tab = &sio_consdev;
4491	return (0);
4492}
4493
4494int
4495siogdbattach(port, speed)
4496	int port;
4497	int speed;
4498{
4499	int			s;
4500	u_char			cfcr;
4501	struct siocnstate	sp;
4502
4503	siogdbiobase = port;
4504	gdbdefaultrate = speed;
4505
4506	s = spltty();
4507
4508	/*
4509	 * Initialize the divisor latch.  We can't rely on
4510	 * siocnopen() to do this the first time, since it
4511	 * avoids writing to the latch if the latch appears
4512	 * to have the correct value.  Also, if we didn't
4513	 * just read the speed from the hardware, then we
4514	 * need to set the speed in hardware so that
4515	 * switching it later is null.
4516	 */
4517	cfcr = inb(siogdbiobase + com_cfcr);
4518	outb(siogdbiobase + com_cfcr, CFCR_DLAB | cfcr);
4519	outb(siogdbiobase + com_dlbl,
4520	     COMBRD(gdbdefaultrate) & 0xff);
4521	outb(siogdbiobase + com_dlbh,
4522	     (u_int) COMBRD(gdbdefaultrate) >> 8);
4523	outb(siogdbiobase + com_cfcr, cfcr);
4524
4525	siocnopen(&sp, siogdbiobase, gdbdefaultrate);
4526	splx(s);
4527
4528	return (0);
4529}
4530
4531#endif
4532
4533static void
4534siocninit(cp)
4535	struct consdev	*cp;
4536{
4537	comconsole = DEV_TO_UNIT(cp->cn_dev);
4538}
4539
4540static int
4541siocncheckc(dev)
4542	dev_t	dev;
4543{
4544	int	c;
4545	Port_t	iobase;
4546	int	s;
4547	struct siocnstate	sp;
4548
4549	if (minor(dev) == siogdbunit)
4550		iobase = siogdbiobase;
4551	else
4552		iobase = siocniobase;
4553	s = spltty();
4554	siocnopen(&sp, iobase, comdefaultrate);
4555	if (inb(iobase + com_lsr) & LSR_RXRDY)
4556		c = inb(iobase + com_data);
4557	else
4558		c = -1;
4559	siocnclose(&sp, iobase);
4560	splx(s);
4561	return (c);
4562}
4563
4564
4565int
4566siocngetc(dev)
4567	dev_t	dev;
4568{
4569	int	c;
4570	Port_t	iobase;
4571	int	s;
4572	struct siocnstate	sp;
4573
4574	if (minor(dev) == siogdbunit)
4575		iobase = siogdbiobase;
4576	else
4577		iobase = siocniobase;
4578	s = spltty();
4579	siocnopen(&sp, iobase, comdefaultrate);
4580	while (!(inb(iobase + com_lsr) & LSR_RXRDY))
4581		;
4582	c = inb(iobase + com_data);
4583	siocnclose(&sp, iobase);
4584	splx(s);
4585	return (c);
4586}
4587
4588void
4589siocnputc(dev, c)
4590	dev_t	dev;
4591	int	c;
4592{
4593	int	s;
4594	struct siocnstate	sp;
4595	Port_t	iobase;
4596
4597	if (minor(dev) == siogdbunit)
4598		iobase = siogdbiobase;
4599	else
4600		iobase = siocniobase;
4601	s = spltty();
4602	siocnopen(&sp, iobase, comdefaultrate);
4603	siocntxwait(iobase);
4604	outb(iobase + com_data, c);
4605	siocnclose(&sp, iobase);
4606	splx(s);
4607}
4608
4609#ifdef __alpha__
4610int
4611siogdbgetc()
4612{
4613	int	c;
4614	Port_t	iobase;
4615	int	s;
4616	struct siocnstate	sp;
4617
4618	iobase = siogdbiobase;
4619	s = spltty();
4620	siocnopen(&sp, iobase, gdbdefaultrate);
4621	while (!(inb(iobase + com_lsr) & LSR_RXRDY))
4622		;
4623	c = inb(iobase + com_data);
4624	siocnclose(&sp, iobase);
4625	splx(s);
4626	return (c);
4627}
4628
4629void
4630siogdbputc(c)
4631	int	c;
4632{
4633	int	s;
4634	struct siocnstate	sp;
4635
4636	s = spltty();
4637	siocnopen(&sp, siogdbiobase, gdbdefaultrate);
4638	siocntxwait(siogdbiobase);
4639	outb(siogdbiobase + com_data, c);
4640	siocnclose(&sp, siogdbiobase);
4641	splx(s);
4642}
4643#endif
4644
4645DRIVER_MODULE(sio, isa, sio_isa_driver, sio_devclass, 0, 0);
4646#if NCARD > 0
4647DRIVER_MODULE(sio, pccard, sio_pccard_driver, sio_devclass, 0, 0);
4648#endif
4649#if NPCI > 0
4650DRIVER_MODULE(sio, pci, sio_pci_driver, sio_devclass, 0, 0);
4651#endif
4652
4653#ifdef PC98
4654/*
4655 *  pc98 local function
4656 */
4657
4658static void
4659com_tiocm_set(struct com_s *com, int msr)
4660{
4661	int	s;
4662	int	tmp = 0;
4663	int	mask = CMD8251_TxEN|CMD8251_RxEN|CMD8251_DTR|CMD8251_RTS;
4664
4665	s=spltty();
4666	com->pc98_prev_modem_status = ( msr & (TIOCM_LE|TIOCM_DTR|TIOCM_RTS) )
4667	   | ( com->pc98_prev_modem_status & ~(TIOCM_LE|TIOCM_DTR|TIOCM_RTS) );
4668	tmp |= (CMD8251_TxEN|CMD8251_RxEN);
4669	if ( msr & TIOCM_DTR ) tmp |= CMD8251_DTR;
4670	if ( msr & TIOCM_RTS ) tmp |= CMD8251_RTS;
4671	pc98_i8251_clear_or_cmd( com, mask, tmp );
4672	splx(s);
4673}
4674
4675static void
4676com_tiocm_bis(struct com_s *com, int msr)
4677{
4678	int	s;
4679	int	tmp = 0;
4680
4681	s=spltty();
4682	com->pc98_prev_modem_status |= ( msr & (TIOCM_LE|TIOCM_DTR|TIOCM_RTS) );
4683	tmp |= CMD8251_TxEN|CMD8251_RxEN;
4684	if ( msr & TIOCM_DTR ) tmp |= CMD8251_DTR;
4685	if ( msr & TIOCM_RTS ) tmp |= CMD8251_RTS;
4686
4687	pc98_i8251_or_cmd( com, tmp );
4688	splx(s);
4689}
4690
4691static void
4692com_tiocm_bic(struct com_s *com, int msr)
4693{
4694	int	s;
4695	int	tmp = msr;
4696
4697	s=spltty();
4698	com->pc98_prev_modem_status &= ~( msr & (TIOCM_LE|TIOCM_DTR|TIOCM_RTS) );
4699	if ( msr & TIOCM_DTR ) tmp |= CMD8251_DTR;
4700	if ( msr & TIOCM_RTS ) tmp |= CMD8251_RTS;
4701
4702	pc98_i8251_clear_cmd( com, tmp );
4703	splx(s);
4704}
4705
4706static int
4707com_tiocm_get(struct com_s *com)
4708{
4709	return( com->pc98_prev_modem_status );
4710}
4711
4712static int
4713com_tiocm_get_delta(struct com_s *com)
4714{
4715	int	tmp;
4716
4717	tmp = com->pc98_modem_delta;
4718	com->pc98_modem_delta = 0;
4719	return( tmp );
4720}
4721
4722/* convert to TIOCM_?? ( ioctl.h ) */
4723static int
4724pc98_get_modem_status(struct com_s *com)
4725{
4726	register int	msr;
4727
4728	msr = com->pc98_prev_modem_status
4729			& ~(TIOCM_CAR|TIOCM_RI|TIOCM_DSR|TIOCM_CTS);
4730	if (com->pc98_8251fifo_enable) {
4731		int	stat2;
4732
4733		stat2 = inb(I8251F_msr);
4734		if ( stat2 & CICSCDF_CD ) msr |= TIOCM_CAR;
4735		if ( stat2 & CICSCDF_CI ) msr |= TIOCM_RI;
4736		if ( stat2 & CICSCDF_DR ) msr |= TIOCM_DSR;
4737		if ( stat2 & CICSCDF_CS ) msr |= TIOCM_CTS;
4738#if COM_CARRIER_DETECT_EMULATE
4739		if ( msr & (TIOCM_DSR|TIOCM_CTS) ) {
4740			msr |= TIOCM_CAR;
4741		}
4742#endif
4743	} else {
4744		int	stat, stat2;
4745
4746		stat  = inb(com->sts_port);
4747		stat2 = inb(com->in_modem_port);
4748		if ( !(stat2 & CICSCD_CD) ) msr |= TIOCM_CAR;
4749		if ( !(stat2 & CICSCD_CI) ) msr |= TIOCM_RI;
4750		if (   stat & STS8251_DSR ) msr |= TIOCM_DSR;
4751		if ( !(stat2 & CICSCD_CS) ) msr |= TIOCM_CTS;
4752#if COM_CARRIER_DETECT_EMULATE
4753		if ( msr & (TIOCM_DSR|TIOCM_CTS) ) {
4754			msr |= TIOCM_CAR;
4755		}
4756#endif
4757	}
4758	return(msr);
4759}
4760
4761static void
4762pc98_check_msr(void* chan)
4763{
4764	int	msr, delta;
4765	int	s;
4766	register struct tty *tp;
4767	struct	com_s *com;
4768	int	mynor;
4769	int	unit;
4770	dev_t	dev;
4771
4772	dev=(dev_t)chan;
4773	mynor = minor(dev);
4774	unit = MINOR_TO_UNIT(mynor);
4775	com = com_addr(unit);
4776	tp = com->tp;
4777
4778	s = spltty();
4779	msr = pc98_get_modem_status(com);
4780	/* make change flag */
4781	delta = msr ^ com->pc98_prev_modem_status;
4782	if ( delta & TIOCM_CAR ) {
4783	    if ( com->modem_car_chg_timer ) {
4784		if ( -- com->modem_car_chg_timer )
4785		    msr ^= TIOCM_CAR;
4786	    } else {
4787		if ((com->modem_car_chg_timer = (msr & TIOCM_CAR) ?
4788		     DCD_ON_RECOGNITION : DCD_OFF_TOLERANCE) != 0)
4789		    msr ^= TIOCM_CAR;
4790	    }
4791	} else
4792	    com->modem_car_chg_timer = 0;
4793	delta = ( msr ^ com->pc98_prev_modem_status ) &
4794			(TIOCM_CAR|TIOCM_RI|TIOCM_DSR|TIOCM_CTS);
4795	com->pc98_prev_modem_status = msr;
4796	delta = ( com->pc98_modem_delta |= delta );
4797	splx(s);
4798	if ( com->modem_checking || (tp->t_state & (TS_ISOPEN)) ) {
4799		if ( delta ) {
4800			commint(dev);
4801		}
4802		timeout(pc98_check_msr, (caddr_t)dev,
4803					PC98_CHECK_MODEM_INTERVAL);
4804	} else {
4805		com->modem_checking = 0;
4806	}
4807}
4808
4809static void
4810pc98_msrint_start(dev_t dev)
4811{
4812	struct	com_s *com;
4813	int	mynor;
4814	int	unit;
4815	int	s = spltty();
4816
4817	mynor = minor(dev);
4818	unit = MINOR_TO_UNIT(mynor);
4819	com = com_addr(unit);
4820	/* modem control line check routine envoke interval is 1/10 sec */
4821	if ( com->modem_checking == 0 ) {
4822		com->pc98_prev_modem_status = pc98_get_modem_status(com);
4823		com->pc98_modem_delta = 0;
4824		timeout(pc98_check_msr, (caddr_t)dev,
4825					PC98_CHECK_MODEM_INTERVAL);
4826		com->modem_checking = 1;
4827	}
4828	splx(s);
4829}
4830
4831static void
4832pc98_disable_i8251_interrupt(struct com_s *com, int mod)
4833{
4834	/* disable interrupt */
4835	register int	tmp;
4836
4837	mod |= ~(IEN_Tx|IEN_TxEMP|IEN_Rx);
4838	COM_INT_DISABLE
4839	tmp = inb( com->intr_ctrl_port ) & ~(IEN_Tx|IEN_TxEMP|IEN_Rx);
4840	outb( com->intr_ctrl_port, (com->intr_enable&=~mod) | tmp );
4841	COM_INT_ENABLE
4842}
4843
4844static void
4845pc98_enable_i8251_interrupt(struct com_s *com, int mod)
4846{
4847	register int	tmp;
4848
4849	COM_INT_DISABLE
4850	tmp = inb( com->intr_ctrl_port ) & ~(IEN_Tx|IEN_TxEMP|IEN_Rx);
4851	outb( com->intr_ctrl_port, (com->intr_enable|=mod) | tmp );
4852	COM_INT_ENABLE
4853}
4854
4855static int
4856pc98_check_i8251_interrupt(struct com_s *com)
4857{
4858	return ( com->intr_enable & 0x07 );
4859}
4860
4861static void
4862pc98_i8251_clear_cmd(struct com_s *com, int x)
4863{
4864	int	tmp;
4865
4866	COM_INT_DISABLE
4867	tmp = com->pc98_prev_siocmd & ~(x);
4868	if (com->pc98_8251fifo_enable)
4869	    outb(I8251F_fcr, 0);
4870	outb(com->cmd_port, tmp);
4871	com->pc98_prev_siocmd = tmp & ~(CMD8251_ER|CMD8251_RESET|CMD8251_EH);
4872	if (com->pc98_8251fifo_enable)
4873	    outb(I8251F_fcr, CTRL8251F_ENABLE);
4874	COM_INT_ENABLE
4875}
4876
4877static void
4878pc98_i8251_or_cmd(struct com_s *com, int x)
4879{
4880	int	tmp;
4881
4882	COM_INT_DISABLE
4883	if (com->pc98_8251fifo_enable)
4884	    outb(I8251F_fcr, 0);
4885	tmp = com->pc98_prev_siocmd | (x);
4886	outb(com->cmd_port, tmp);
4887	com->pc98_prev_siocmd = tmp & ~(CMD8251_ER|CMD8251_RESET|CMD8251_EH);
4888	if (com->pc98_8251fifo_enable)
4889	    outb(I8251F_fcr, CTRL8251F_ENABLE);
4890	COM_INT_ENABLE
4891}
4892
4893static void
4894pc98_i8251_set_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 = (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_clear_or_cmd(struct com_s *com, int clr, int x)
4911{
4912	int	tmp;
4913	COM_INT_DISABLE
4914	if (com->pc98_8251fifo_enable)
4915	    outb(I8251F_fcr, 0);
4916	tmp = com->pc98_prev_siocmd & ~(clr);
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 int
4926pc98_i8251_get_cmd(struct com_s *com)
4927{
4928	return com->pc98_prev_siocmd;
4929}
4930
4931static int
4932pc98_i8251_get_mod(struct com_s *com)
4933{
4934	return com->pc98_prev_siomod;
4935}
4936
4937static void
4938pc98_i8251_reset(struct com_s *com, int mode, int command)
4939{
4940	if (com->pc98_8251fifo_enable)
4941	    outb(I8251F_fcr, 0);
4942	outb(com->cmd_port, 0);	/* dummy */
4943	DELAY(2);
4944	outb(com->cmd_port, 0);	/* dummy */
4945	DELAY(2);
4946	outb(com->cmd_port, 0);	/* dummy */
4947	DELAY(2);
4948	outb(com->cmd_port, CMD8251_RESET);	/* internal reset */
4949	DELAY(2);
4950	outb(com->cmd_port, mode );	/* mode register */
4951	com->pc98_prev_siomod = mode;
4952	DELAY(2);
4953	pc98_i8251_set_cmd( com, (command|CMD8251_ER) );
4954	DELAY(10);
4955	if (com->pc98_8251fifo_enable)
4956	    outb(I8251F_fcr, CTRL8251F_ENABLE |
4957		 CTRL8251F_XMT_RST | CTRL8251F_RCV_RST);
4958}
4959
4960static void
4961pc98_check_sysclock(void)
4962{
4963	/* get system clock from port */
4964	if ( pc98_machine_type & M_8M ) {
4965	/* 8 MHz system & H98 */
4966		sysclock = 8;
4967	} else {
4968	/* 5 MHz system */
4969		sysclock = 5;
4970	}
4971}
4972
4973static void
4974com_cflag_and_speed_set( struct com_s *com, int cflag, int speed)
4975{
4976	int	cfcr=0, count;
4977	int	previnterrupt;
4978
4979	count = pc98_ttspeedtab( com, speed );
4980	if ( count < 0 ) return;
4981
4982	previnterrupt = pc98_check_i8251_interrupt(com);
4983	pc98_disable_i8251_interrupt( com, IEN_Tx|IEN_TxEMP|IEN_Rx );
4984
4985	switch ( cflag&CSIZE ) {
4986	  case CS5:
4987		cfcr = MOD8251_5BITS; break;
4988	  case CS6:
4989		cfcr = MOD8251_6BITS; break;
4990	  case CS7:
4991		cfcr = MOD8251_7BITS; break;
4992	  case CS8:
4993		cfcr = MOD8251_8BITS; break;
4994	}
4995	if ( cflag&PARENB ) {
4996	    if ( cflag&PARODD )
4997		cfcr |= MOD8251_PODD;
4998	    else
4999		cfcr |= MOD8251_PEVEN;
5000	} else
5001		cfcr |= MOD8251_PDISAB;
5002
5003	if ( cflag&CSTOPB )
5004		cfcr |= MOD8251_STOP2;
5005	else
5006		cfcr |= MOD8251_STOP1;
5007
5008	if ( count & 0x10000 )
5009		cfcr |= MOD8251_CLKX1;
5010	else
5011		cfcr |= MOD8251_CLKX16;
5012
5013	if (epson_machine_id != 0x20) {	/* XXX */
5014		int	tmp;
5015		while (!((tmp = inb(com->sts_port)) & STS8251_TxEMP))
5016			;
5017	}
5018	/* set baud rate from ospeed */
5019	pc98_set_baud_rate( com, count );
5020
5021	if ( cfcr != pc98_i8251_get_mod(com) )
5022		pc98_i8251_reset(com, cfcr, pc98_i8251_get_cmd(com) );
5023
5024	pc98_enable_i8251_interrupt( com, previnterrupt );
5025}
5026
5027static int
5028pc98_ttspeedtab(struct com_s *com, int speed)
5029{
5030	int	if_type, effect_sp, count = -1, mod;
5031
5032	if_type = com->pc98_if_type & 0x0f;
5033
5034	switch (com->pc98_if_type) {
5035	case COM_IF_INTERNAL:
5036	    if (PC98SIO_baud_rate_port(if_type) != -1) {
5037		count = ttspeedtab(speed, if_8251_type[if_type].speedtab);
5038		if (count > 0) {
5039		    count |= COM1_EXT_CLOCK;
5040		    break;
5041		}
5042	    }
5043
5044	    /* for *1CLK asynchronous! mode, TEFUTEFU */
5045	    mod = (sysclock == 5) ? 2457600 : 1996800;
5046	    effect_sp = ttspeedtab( speed, pc98speedtab );
5047	    if ( effect_sp < 0 )	/* XXX */
5048		effect_sp = ttspeedtab( (speed - 1), pc98speedtab );
5049	    if ( effect_sp <= 0 )
5050		return effect_sp;
5051	    if ( effect_sp == speed )
5052		mod /= 16;
5053	    if ( mod % effect_sp )
5054		return(-1);
5055	    count = mod / effect_sp;
5056	    if ( count > 65535 )
5057		return(-1);
5058	    if ( effect_sp != speed )
5059		count |= 0x10000;
5060	    break;
5061	case COM_IF_PC9861K_1:
5062	case COM_IF_PC9861K_2:
5063	    count = 1;
5064	    break;
5065	case COM_IF_IND_SS_1:
5066	case COM_IF_IND_SS_2:
5067	case COM_IF_PIO9032B_1:
5068	case COM_IF_PIO9032B_2:
5069	    if ( speed == 0 ) return 0;
5070	    count = ttspeedtab( speed, if_8251_type[if_type].speedtab );
5071	    break;
5072	case COM_IF_B98_01_1:
5073	case COM_IF_B98_01_2:
5074	    if ( speed == 0 ) return 0;
5075	    count = ttspeedtab( speed, if_8251_type[if_type].speedtab );
5076#ifdef B98_01_OLD
5077	    if (count == 0 || count == 1) {
5078		count += 4;
5079		count |= 0x20000;  /* x1 mode for 76800 and 153600 */
5080	    }
5081#endif
5082	    break;
5083	}
5084
5085	return count;
5086}
5087
5088static void
5089pc98_set_baud_rate( struct com_s *com, int count )
5090{
5091	int	if_type, io, s;
5092
5093	if_type = com->pc98_if_type & 0x0f;
5094	io = rman_get_start(com->ioportres) & 0xff00;
5095
5096	switch (com->pc98_if_type) {
5097	case COM_IF_INTERNAL:
5098	    if (PC98SIO_baud_rate_port(if_type) != -1) {
5099		if (count & COM1_EXT_CLOCK) {
5100		    outb((Port_t)PC98SIO_baud_rate_port(if_type), count & 0xff);
5101		    break;
5102		} else {
5103		    outb((Port_t)PC98SIO_baud_rate_port(if_type), 0x09);
5104		}
5105	    }
5106
5107	    if ( count < 0 ) {
5108		printf( "[ Illegal count : %d ]", count );
5109		return;
5110	    } else if ( count == 0 )
5111		return;
5112	    /* set i8253 */
5113	    s = splclock();
5114	    if (count != 3)
5115		outb( 0x77, 0xb6 );
5116	    else
5117		outb( 0x77, 0xb4 );
5118	    outb( 0x5f, 0);
5119	    outb( 0x75, count & 0xff );
5120	    outb( 0x5f, 0);
5121	    outb( 0x75, (count >> 8) & 0xff );
5122	    splx(s);
5123	    break;
5124	case COM_IF_IND_SS_1:
5125	case COM_IF_IND_SS_2:
5126	    outb(io | PC98SIO_intr_ctrl_port(if_type), 0);
5127	    outb(io | PC98SIO_baud_rate_port(if_type), 0);
5128	    outb(io | PC98SIO_baud_rate_port(if_type), 0xc0);
5129	    outb(io | PC98SIO_baud_rate_port(if_type), (count >> 8) | 0x80);
5130	    outb(io | PC98SIO_baud_rate_port(if_type), count & 0xff);
5131	    break;
5132	case COM_IF_PIO9032B_1:
5133	case COM_IF_PIO9032B_2:
5134	    outb(io | PC98SIO_baud_rate_port(if_type), count);
5135	    break;
5136	case COM_IF_B98_01_1:
5137	case COM_IF_B98_01_2:
5138	    outb(io | PC98SIO_baud_rate_port(if_type), count & 0x0f);
5139#ifdef B98_01_OLD
5140	    /*
5141	     * Some old B98_01 board should be controlled
5142	     * in different way, but this hasn't been tested yet.
5143	     */
5144	    outb(io | PC98SIO_func_port(if_type),
5145		 (count & 0x20000) ? 0xf0 : 0xf2);
5146#endif
5147	    break;
5148	}
5149}
5150static int
5151pc98_check_if_type(device_t dev, struct siodev *iod)
5152{
5153	int	irr, io, if_type, tmp;
5154	static  short	irq_tab[2][8] = {
5155		{  3,  5,  6,  9, 10, 12, 13, -1},
5156		{  3, 10, 12, 13,  5,  6,  9, -1}
5157	};
5158
5159	if_type = iod->if_type & 0x0f;
5160	iod->irq = 0;
5161	io = isa_get_port(dev) & 0xff00;
5162
5163	if (IS_8251(iod->if_type)) {
5164	    if (PC98SIO_func_port(if_type) != -1) {
5165		outb(io | PC98SIO_func_port(if_type), 0xf2);
5166		tmp = ttspeedtab(9600, if_8251_type[if_type].speedtab);
5167		if (tmp != -1 && PC98SIO_baud_rate_port(if_type) != -1)
5168		    outb(io | PC98SIO_baud_rate_port(if_type), tmp);
5169	    }
5170
5171	    iod->cmd  = io | PC98SIO_cmd_port(if_type);
5172	    iod->sts  = io | PC98SIO_sts_port(if_type);
5173	    iod->mod  = io | PC98SIO_in_modem_port(if_type);
5174	    iod->ctrl = io | PC98SIO_intr_ctrl_port(if_type);
5175
5176	    if (iod->if_type == COM_IF_INTERNAL) {
5177		iod->irq = 4;
5178
5179		if (pc98_check_8251vfast()) {
5180			PC98SIO_baud_rate_port(if_type) = I8251F_div;
5181			if_8251_type[if_type].speedtab = pc98fast_speedtab;
5182		}
5183	    } else {
5184		tmp = inb( iod->mod ) & if_8251_type[if_type].irr_mask;
5185		if ((isa_get_port(dev) & 0xff) == IO_COM2)
5186		    iod->irq = irq_tab[0][tmp];
5187		else
5188		    iod->irq = irq_tab[1][tmp];
5189	    }
5190	} else {
5191	    irr = if_16550a_type[if_type].irr_read;
5192#ifdef COM_MULTIPORT
5193	    if (!COM_ISMULTIPORT(device_get_flags(dev)) ||
5194		    device_get_unit(dev) == COM_MPMASTER(device_get_flags(dev)))
5195#endif
5196	    if (irr != -1) {
5197		tmp = inb(io | irr);
5198		if (isa_get_port(dev) & 0x01)	/* XXX depend on RSB-384 */
5199		    iod->irq = irq_tab[1][tmp >> 3];
5200		else
5201		    iod->irq = irq_tab[0][tmp & 0x07];
5202	    }
5203	}
5204	if ( iod->irq == -1 ) return -1;
5205
5206	return 0;
5207}
5208static void
5209pc98_set_ioport(struct com_s *com)
5210{
5211	int	if_type = com->pc98_if_type & 0x0f;
5212	Port_t	io = rman_get_start(com->ioportres) & 0xff00;
5213
5214	pc98_check_sysclock();
5215	com->data_port		= io | PC98SIO_data_port(if_type);
5216	com->cmd_port		= io | PC98SIO_cmd_port(if_type);
5217	com->sts_port		= io | PC98SIO_sts_port(if_type);
5218	com->in_modem_port	= io | PC98SIO_in_modem_port(if_type);
5219	com->intr_ctrl_port	= io | PC98SIO_intr_ctrl_port(if_type);
5220}
5221static int
5222pc98_check_8251vfast(void)
5223{
5224    int	i;
5225
5226    outb(I8251F_div, 0x8c);
5227    DELAY(10);
5228    for (i = 0; i < 100; i++) {
5229	if ((inb(I8251F_div) & 0x80) != 0) {
5230	    i = 0;
5231	    break;
5232	}
5233	DELAY(1);
5234    }
5235    outb(I8251F_div, 0);
5236    DELAY(10);
5237    for (; i < 100; i++) {
5238	if ((inb(I8251F_div) & 0x80) == 0)
5239	    return 1;
5240	DELAY(1);
5241    }
5242
5243    return 0;
5244}
5245static int
5246pc98_check_8251fifo(void)
5247{
5248    u_char	tmp1, tmp2;
5249
5250    tmp1 = inb(I8251F_iir);
5251    DELAY(10);
5252    tmp2 = inb(I8251F_iir);
5253    if (((tmp1 ^ tmp2) & 0x40) != 0 && ((tmp1 | tmp2) & 0x20) == 0)
5254	return 1;
5255
5256    return 0;
5257}
5258#endif /* PC98 defined */
5259