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