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