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