sio.c revision 95523
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/dev/sio/sio.c 95523 2002-04-26 20:24:28Z phk $
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#include <sys/param.h>
53#include <sys/systm.h>
54#include <sys/bus.h>
55#include <sys/conf.h>
56#include <sys/dkstat.h>
57#include <sys/fcntl.h>
58#include <sys/interrupt.h>
59#include <sys/kernel.h>
60#include <sys/lock.h>
61#include <sys/malloc.h>
62#include <sys/module.h>
63#include <sys/mutex.h>
64#include <sys/proc.h>
65#include <sys/reboot.h>
66#include <sys/sysctl.h>
67#include <sys/syslog.h>
68#include <sys/tty.h>
69#include <machine/bus_pio.h>
70#include <machine/bus.h>
71#include <sys/rman.h>
72#include <sys/timepps.h>
73#include <sys/uio.h>
74
75#include <isa/isavar.h>
76
77#include <machine/limits.h>
78#include <machine/resource.h>
79
80#include <dev/sio/sioreg.h>
81#include <dev/sio/siovar.h>
82
83#ifdef COM_ESP
84#include <dev/ic/esp.h>
85#endif
86#include <dev/ic/ns16550.h>
87
88#define	LOTS_OF_EVENTS	64	/* helps separate urgent events from input */
89
90#define	CALLOUT_MASK		0x80
91#define	CONTROL_MASK		0x60
92#define	CONTROL_INIT_STATE	0x20
93#define	CONTROL_LOCK_STATE	0x40
94#define	DEV_TO_UNIT(dev)	(MINOR_TO_UNIT(minor(dev)))
95#define	MINOR_TO_UNIT(mynor)	((((mynor) & ~0xffffU) >> (8 + 3)) \
96				 | ((mynor) & 0x1f))
97#define	UNIT_TO_MINOR(unit)	((((unit) & ~0x1fU) << (8 + 3)) \
98				 | ((unit) & 0x1f))
99
100#ifdef COM_MULTIPORT
101/* checks in flags for multiport and which is multiport "master chip"
102 * for a given card
103 */
104#define	COM_ISMULTIPORT(flags)	((flags) & 0x01)
105#define	COM_MPMASTER(flags)	(((flags) >> 8) & 0x0ff)
106#define	COM_NOTAST4(flags)	((flags) & 0x04)
107#endif /* COM_MULTIPORT */
108
109#define	COM_CONSOLE(flags)	((flags) & 0x10)
110#define	COM_FORCECONSOLE(flags)	((flags) & 0x20)
111#define	COM_LLCONSOLE(flags)	((flags) & 0x40)
112#define	COM_DEBUGGER(flags)	((flags) & 0x80)
113#define	COM_LOSESOUTINTS(flags)	((flags) & 0x08)
114#define	COM_NOFIFO(flags)		((flags) & 0x02)
115#define COM_ST16650A(flags)	((flags) & 0x20000)
116#define COM_C_NOPROBE		(0x40000)
117#define COM_NOPROBE(flags)	((flags) & COM_C_NOPROBE)
118#define COM_C_IIR_TXRDYBUG	(0x80000)
119#define COM_IIR_TXRDYBUG(flags)	((flags) & COM_C_IIR_TXRDYBUG)
120#define	COM_FIFOSIZE(flags)	(((flags) & 0xff000000) >> 24)
121
122#define	com_scr		7	/* scratch register for 16450-16550 (R/W) */
123
124#define	sio_getreg(com, off) \
125	(bus_space_read_1((com)->bst, (com)->bsh, (off)))
126#define	sio_setreg(com, off, value) \
127	(bus_space_write_1((com)->bst, (com)->bsh, (off), (value)))
128
129/*
130 * com state bits.
131 * (CS_BUSY | CS_TTGO) and (CS_BUSY | CS_TTGO | CS_ODEVREADY) must be higher
132 * than the other bits so that they can be tested as a group without masking
133 * off the low bits.
134 *
135 * The following com and tty flags correspond closely:
136 *	CS_BUSY		= TS_BUSY (maintained by comstart(), siopoll() and
137 *				   comstop())
138 *	CS_TTGO		= ~TS_TTSTOP (maintained by comparam() and comstart())
139 *	CS_CTS_OFLOW	= CCTS_OFLOW (maintained by comparam())
140 *	CS_RTS_IFLOW	= CRTS_IFLOW (maintained by comparam())
141 * TS_FLUSH is not used.
142 * XXX I think TIOCSETA doesn't clear TS_TTSTOP when it clears IXON.
143 * XXX CS_*FLOW should be CF_*FLOW in com->flags (control flags not state).
144 */
145#define	CS_BUSY		0x80	/* output in progress */
146#define	CS_TTGO		0x40	/* output not stopped by XOFF */
147#define	CS_ODEVREADY	0x20	/* external device h/w ready (CTS) */
148#define	CS_CHECKMSR	1	/* check of MSR scheduled */
149#define	CS_CTS_OFLOW	2	/* use CTS output flow control */
150#define	CS_DTR_OFF	0x10	/* DTR held off */
151#define	CS_ODONE	4	/* output completed */
152#define	CS_RTS_IFLOW	8	/* use RTS input flow control */
153#define	CSE_BUSYCHECK	1	/* siobusycheck() scheduled */
154
155static	char const * const	error_desc[] = {
156#define	CE_OVERRUN			0
157	"silo overflow",
158#define	CE_INTERRUPT_BUF_OVERFLOW	1
159	"interrupt-level buffer overflow",
160#define	CE_TTY_BUF_OVERFLOW		2
161	"tty-level buffer overflow",
162};
163
164#define	CE_NTYPES			3
165#define	CE_RECORD(com, errnum)		(++(com)->delta_error_counts[errnum])
166
167/* types.  XXX - should be elsewhere */
168typedef u_int	Port_t;		/* hardware port */
169typedef u_char	bool_t;		/* boolean */
170
171/* queue of linear buffers */
172struct lbq {
173	u_char	*l_head;	/* next char to process */
174	u_char	*l_tail;	/* one past the last char to process */
175	struct lbq *l_next;	/* next in queue */
176	bool_t	l_queued;	/* nonzero if queued */
177};
178
179/* com device structure */
180struct com_s {
181	u_int	flags;		/* Copy isa device flags */
182	u_char	state;		/* miscellaneous flag bits */
183	bool_t  active_out;	/* nonzero if the callout device is open */
184	u_char	cfcr_image;	/* copy of value written to CFCR */
185#ifdef COM_ESP
186	bool_t	esp;		/* is this unit a hayes esp board? */
187#endif
188	u_char	extra_state;	/* more flag bits, separate for order trick */
189	u_char	fifo_image;	/* copy of value written to FIFO */
190	bool_t	hasfifo;	/* nonzero for 16550 UARTs */
191	bool_t	st16650a;	/* Is a Startech 16650A or RTS/CTS compat */
192	bool_t	loses_outints;	/* nonzero if device loses output interrupts */
193	u_char	mcr_image;	/* copy of value written to MCR */
194#ifdef COM_MULTIPORT
195	bool_t	multiport;	/* is this unit part of a multiport device? */
196#endif /* COM_MULTIPORT */
197	bool_t	no_irq;		/* nonzero if irq is not attached */
198	bool_t  gone;		/* hardware disappeared */
199	bool_t	poll;		/* nonzero if polling is required */
200	bool_t	poll_output;	/* nonzero if polling for output is required */
201	int	unit;		/* unit	number */
202	int	dtr_wait;	/* time to hold DTR down on close (* 1/hz) */
203	u_int	tx_fifo_size;
204	u_int	wopeners;	/* # processes waiting for DCD in open() */
205
206	/*
207	 * The high level of the driver never reads status registers directly
208	 * because there would be too many side effects to handle conveniently.
209	 * Instead, it reads copies of the registers stored here by the
210	 * interrupt handler.
211	 */
212	u_char	last_modem_status;	/* last MSR read by intr handler */
213	u_char	prev_modem_status;	/* last MSR handled by high level */
214
215	u_char	hotchar;	/* ldisc-specific char to be handled ASAP */
216	u_char	*ibuf;		/* start of input buffer */
217	u_char	*ibufend;	/* end of input buffer */
218	u_char	*ibufold;	/* old input buffer, to be freed */
219	u_char	*ihighwater;	/* threshold in input buffer */
220	u_char	*iptr;		/* next free spot in input buffer */
221	int	ibufsize;	/* size of ibuf (not include error bytes) */
222	int	ierroff;	/* offset of error bytes in ibuf */
223
224	struct lbq	obufq;	/* head of queue of output buffers */
225	struct lbq	obufs[2];	/* output buffers */
226
227	bus_space_tag_t		bst;
228	bus_space_handle_t	bsh;
229
230	Port_t	data_port;	/* i/o ports */
231#ifdef COM_ESP
232	Port_t	esp_port;
233#endif
234	Port_t	int_id_port;
235	Port_t	modem_ctl_port;
236	Port_t	line_status_port;
237	Port_t	modem_status_port;
238	Port_t	intr_ctl_port;	/* Ports of IIR register */
239
240	struct tty	*tp;	/* cross reference */
241
242	/* Initial state. */
243	struct termios	it_in;	/* should be in struct tty */
244	struct termios	it_out;
245
246	/* Lock state. */
247	struct termios	lt_in;	/* should be in struct tty */
248	struct termios	lt_out;
249
250	bool_t	do_timestamp;
251	bool_t	do_dcd_timestamp;
252	struct timeval	timestamp;
253	struct timeval	dcd_timestamp;
254	struct	pps_state pps;
255
256	u_long	bytes_in;	/* statistics */
257	u_long	bytes_out;
258	u_int	delta_error_counts[CE_NTYPES];
259	u_long	error_counts[CE_NTYPES];
260
261	u_long	rclk;
262
263	struct resource *irqres;
264	struct resource *ioportres;
265	void *cookie;
266	dev_t devs[6];
267
268	/*
269	 * Data area for output buffers.  Someday we should build the output
270	 * buffer queue without copying data.
271	 */
272	u_char	obuf1[256];
273	u_char	obuf2[256];
274};
275
276#ifdef COM_ESP
277static	int	espattach(struct com_s *com, Port_t esp_port);
278#endif
279
280static	timeout_t siobusycheck;
281static	u_int	siodivisor(u_long rclk, speed_t speed);
282static	timeout_t siodtrwakeup;
283static	void	comhardclose(struct com_s *com);
284static	void	sioinput(struct com_s *com);
285static	void	siointr1(struct com_s *com);
286static	void	siointr(void *arg);
287static	int	commctl(struct com_s *com, int bits, int how);
288static	int	comparam(struct tty *tp, struct termios *t);
289static	void	siopoll(void *);
290static	void	siosettimeout(void);
291static	int	siosetwater(struct com_s *com, speed_t speed);
292static	void	comstart(struct tty *tp);
293static	void	comstop(struct tty *tp, int rw);
294static	timeout_t comwakeup;
295static	void	disc_optim(struct tty *tp, struct termios *t,
296		    struct com_s *com);
297
298char		sio_driver_name[] = "sio";
299static struct	mtx sio_lock;
300static int	sio_inited;
301
302/* table and macro for fast conversion from a unit number to its com struct */
303devclass_t	sio_devclass;
304#define	com_addr(unit)	((struct com_s *) \
305			 devclass_get_softc(sio_devclass, unit)) /* XXX */
306
307static	d_open_t	sioopen;
308static	d_close_t	sioclose;
309static	d_read_t	sioread;
310static	d_write_t	siowrite;
311static	d_ioctl_t	sioioctl;
312
313#define	CDEV_MAJOR	28
314static struct cdevsw sio_cdevsw = {
315	/* open */	sioopen,
316	/* close */	sioclose,
317	/* read */	sioread,
318	/* write */	siowrite,
319	/* ioctl */	sioioctl,
320	/* poll */	ttypoll,
321	/* mmap */	nommap,
322	/* strategy */	nostrategy,
323	/* name */	sio_driver_name,
324	/* maj */	CDEV_MAJOR,
325	/* dump */	nodump,
326	/* psize */	nopsize,
327	/* flags */	D_TTY | D_KQFILTER,
328	/* kqfilter */	ttykqfilter,
329};
330
331int	comconsole = -1;
332static	volatile speed_t	comdefaultrate = CONSPEED;
333static	u_long			comdefaultrclk = DEFAULT_RCLK;
334SYSCTL_ULONG(_machdep, OID_AUTO, conrclk, CTLFLAG_RW, &comdefaultrclk, 0, "");
335#ifdef __alpha__
336static	volatile speed_t	gdbdefaultrate = CONSPEED;
337#endif
338static	u_int	com_events;	/* input chars + weighted output completions */
339static	Port_t	siocniobase;
340#ifndef __alpha__
341static	int	siocnunit;
342#endif
343static	Port_t	siogdbiobase;
344static	int	siogdbunit = -1;
345static	void	*sio_slow_ih;
346static	void	*sio_fast_ih;
347static	int	sio_timeout;
348static	int	sio_timeouts_until_log;
349static	struct	callout_handle sio_timeout_handle
350    = CALLOUT_HANDLE_INITIALIZER(&sio_timeout_handle);
351static	int	sio_numunits;
352
353#ifdef COM_ESP
354/* XXX configure this properly. */
355/* XXX quite broken for new-bus. */
356static	Port_t	likely_com_ports[] = { 0x3f8, 0x2f8, 0x3e8, 0x2e8, };
357static	Port_t	likely_esp_ports[] = { 0x140, 0x180, 0x280, 0 };
358#endif
359
360/*
361 * handle sysctl read/write requests for console speed
362 *
363 * In addition to setting comdefaultrate for I/O through /dev/console,
364 * also set the initial and lock values for the /dev/ttyXX device
365 * if there is one associated with the console.  Finally, if the /dev/tty
366 * device has already been open, change the speed on the open running port
367 * itself.
368 */
369
370static int
371sysctl_machdep_comdefaultrate(SYSCTL_HANDLER_ARGS)
372{
373	int error, s;
374	speed_t newspeed;
375	struct com_s *com;
376	struct tty *tp;
377
378	newspeed = comdefaultrate;
379
380	error = sysctl_handle_opaque(oidp, &newspeed, sizeof newspeed, req);
381	if (error || !req->newptr)
382		return (error);
383
384	comdefaultrate = newspeed;
385
386	if (comconsole < 0)		/* serial console not selected? */
387		return (0);
388
389	com = com_addr(comconsole);
390	if (com == NULL)
391		return (ENXIO);
392
393	/*
394	 * set the initial and lock rates for /dev/ttydXX and /dev/cuaXX
395	 * (note, the lock rates really are boolean -- if non-zero, disallow
396	 *  speed changes)
397	 */
398	com->it_in.c_ispeed  = com->it_in.c_ospeed =
399	com->lt_in.c_ispeed  = com->lt_in.c_ospeed =
400	com->it_out.c_ispeed = com->it_out.c_ospeed =
401	com->lt_out.c_ispeed = com->lt_out.c_ospeed = comdefaultrate;
402
403	/*
404	 * if we're open, change the running rate too
405	 */
406	tp = com->tp;
407	if (tp && (tp->t_state & TS_ISOPEN)) {
408		tp->t_termios.c_ispeed =
409		tp->t_termios.c_ospeed = comdefaultrate;
410		s = spltty();
411		error = comparam(tp, &tp->t_termios);
412		splx(s);
413	}
414	return error;
415}
416
417SYSCTL_PROC(_machdep, OID_AUTO, conspeed, CTLTYPE_INT | CTLFLAG_RW,
418	    0, 0, sysctl_machdep_comdefaultrate, "I", "");
419/* TUNABLE_INT("machdep.conspeed", &comdefaultrate); */
420
421#define SET_FLAG(dev, bit) device_set_flags(dev, device_get_flags(dev) | (bit))
422#define CLR_FLAG(dev, bit) device_set_flags(dev, device_get_flags(dev) & ~(bit))
423
424/*
425 *	Unload the driver and clear the table.
426 *	XXX this is mostly wrong.
427 *	XXX TODO:
428 *	This is usually called when the card is ejected, but
429 *	can be caused by a modunload of a controller driver.
430 *	The idea is to reset the driver's view of the device
431 *	and ensure that any driver entry points such as
432 *	read and write do not hang.
433 */
434int
435siodetach(dev)
436	device_t	dev;
437{
438	struct com_s	*com;
439	int i;
440
441	com = (struct com_s *) device_get_softc(dev);
442	if (com == NULL) {
443		device_printf(dev, "NULL com in siounload\n");
444		return (0);
445	}
446	com->gone = 1;
447	for (i = 0 ; i < 6; i++)
448		destroy_dev(com->devs[i]);
449	if (com->irqres) {
450		bus_teardown_intr(dev, com->irqres, com->cookie);
451		bus_release_resource(dev, SYS_RES_IRQ, 0, com->irqres);
452	}
453	if (com->ioportres)
454		bus_release_resource(dev, SYS_RES_IOPORT, 0, com->ioportres);
455	if (com->tp && (com->tp->t_state & TS_ISOPEN)) {
456		device_printf(dev, "still open, forcing close\n");
457		(*linesw[com->tp->t_line].l_close)(com->tp, 0);
458		com->tp->t_gen++;
459		ttyclose(com->tp);
460		ttwakeup(com->tp);
461		ttwwakeup(com->tp);
462	} else {
463		if (com->ibuf != NULL)
464			free(com->ibuf, M_DEVBUF);
465		device_set_softc(dev, NULL);
466		free(com, M_DEVBUF);
467	}
468	return (0);
469}
470
471int
472sioprobe(dev, xrid, rclk, noprobe)
473	device_t	dev;
474	int		xrid;
475	u_long		rclk;
476	int		noprobe;
477{
478#if 0
479	static bool_t	already_init;
480	device_t	xdev;
481#endif
482	struct com_s	*com;
483	u_int		divisor;
484	bool_t		failures[10];
485	int		fn;
486	device_t	idev;
487	Port_t		iobase;
488	intrmask_t	irqmap[4];
489	intrmask_t	irqs;
490	u_char		mcr_image;
491	int		result;
492	u_long		xirq;
493	u_int		flags = device_get_flags(dev);
494	int		rid;
495	struct resource *port;
496
497	rid = xrid;
498	port = bus_alloc_resource(dev, SYS_RES_IOPORT, &rid,
499				  0, ~0, IO_COMSIZE, RF_ACTIVE);
500	if (!port)
501		return (ENXIO);
502
503	com = malloc(sizeof(*com), M_DEVBUF, M_NOWAIT | M_ZERO);
504	if (com == NULL)
505		return (ENOMEM);
506	device_set_softc(dev, com);
507	com->bst = rman_get_bustag(port);
508	com->bsh = rman_get_bushandle(port);
509	if (rclk == 0)
510		rclk = DEFAULT_RCLK;
511	com->rclk = rclk;
512
513	while (sio_inited != 2)
514		if (atomic_cmpset_int(&sio_inited, 0, 1)) {
515			mtx_init(&sio_lock, sio_driver_name, NULL,
516			    (comconsole != -1) ?
517			    MTX_SPIN | MTX_QUIET : MTX_SPIN);
518			atomic_store_rel_int(&sio_inited, 2);
519		}
520
521#if 0
522	/*
523	 * XXX this is broken - when we are first called, there are no
524	 * previously configured IO ports.  We could hard code
525	 * 0x3f8, 0x2f8, 0x3e8, 0x2e8 etc but that's probably worse.
526	 * This code has been doing nothing since the conversion since
527	 * "count" is zero the first time around.
528	 */
529	if (!already_init) {
530		/*
531		 * Turn off MCR_IENABLE for all likely serial ports.  An unused
532		 * port with its MCR_IENABLE gate open will inhibit interrupts
533		 * from any used port that shares the interrupt vector.
534		 * XXX the gate enable is elsewhere for some multiports.
535		 */
536		device_t *devs;
537		int count, i, xioport;
538
539		devclass_get_devices(sio_devclass, &devs, &count);
540		for (i = 0; i < count; i++) {
541			xdev = devs[i];
542			if (device_is_enabled(xdev) &&
543			    bus_get_resource(xdev, SYS_RES_IOPORT, 0, &xioport,
544					     NULL) == 0)
545				outb(xioport + com_mcr, 0);
546		}
547		free(devs, M_TEMP);
548		already_init = TRUE;
549	}
550#endif
551
552	if (COM_LLCONSOLE(flags)) {
553		printf("sio%d: reserved for low-level i/o\n",
554		       device_get_unit(dev));
555		bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
556		device_set_softc(dev, NULL);
557		free(com, M_DEVBUF);
558		return (ENXIO);
559	}
560
561	/*
562	 * If the device is on a multiport card and has an AST/4
563	 * compatible interrupt control register, initialize this
564	 * register and prepare to leave MCR_IENABLE clear in the mcr.
565	 * Otherwise, prepare to set MCR_IENABLE in the mcr.
566	 * Point idev to the device struct giving the correct id_irq.
567	 * This is the struct for the master device if there is one.
568	 */
569	idev = dev;
570	mcr_image = MCR_IENABLE;
571#ifdef COM_MULTIPORT
572	if (COM_ISMULTIPORT(flags)) {
573		Port_t xiobase;
574		u_long io;
575
576		idev = devclass_get_device(sio_devclass, COM_MPMASTER(flags));
577		if (idev == NULL) {
578			printf("sio%d: master device %d not configured\n",
579			       device_get_unit(dev), COM_MPMASTER(flags));
580			idev = dev;
581		}
582		if (!COM_NOTAST4(flags)) {
583			if (bus_get_resource(idev, SYS_RES_IOPORT, 0, &io,
584					     NULL) == 0) {
585				xiobase = io;
586				if (bus_get_resource(idev, SYS_RES_IRQ, 0,
587				    NULL, NULL) == 0)
588					outb(xiobase + com_scr, 0x80);
589				else
590					outb(xiobase + com_scr, 0);
591			}
592			mcr_image = 0;
593		}
594	}
595#endif /* COM_MULTIPORT */
596	if (bus_get_resource(idev, SYS_RES_IRQ, 0, NULL, NULL) != 0)
597		mcr_image = 0;
598
599	bzero(failures, sizeof failures);
600	iobase = rman_get_start(port);
601
602	/*
603	 * We don't want to get actual interrupts, just masked ones.
604	 * Interrupts from this line should already be masked in the ICU,
605	 * but mask them in the processor as well in case there are some
606	 * (misconfigured) shared interrupts.
607	 */
608	mtx_lock_spin(&sio_lock);
609/* EXTRA DELAY? */
610
611	/*
612	 * Initialize the speed and the word size and wait long enough to
613	 * drain the maximum of 16 bytes of junk in device output queues.
614	 * The speed is undefined after a master reset and must be set
615	 * before relying on anything related to output.  There may be
616	 * junk after a (very fast) soft reboot and (apparently) after
617	 * master reset.
618	 * XXX what about the UART bug avoided by waiting in comparam()?
619	 * We don't want to to wait long enough to drain at 2 bps.
620	 */
621	if (iobase == siocniobase)
622		DELAY((16 + 1) * 1000000 / (comdefaultrate / 10));
623	else {
624		sio_setreg(com, com_cfcr, CFCR_DLAB | CFCR_8BITS);
625		divisor = siodivisor(rclk, SIO_TEST_SPEED);
626		sio_setreg(com, com_dlbl, divisor & 0xff);
627		sio_setreg(com, com_dlbh, divisor >> 8);
628		sio_setreg(com, com_cfcr, CFCR_8BITS);
629		DELAY((16 + 1) * 1000000 / (SIO_TEST_SPEED / 10));
630	}
631
632	/*
633	 * Enable the interrupt gate and disable device interupts.  This
634	 * should leave the device driving the interrupt line low and
635	 * guarantee an edge trigger if an interrupt can be generated.
636	 */
637/* EXTRA DELAY? */
638	sio_setreg(com, com_mcr, mcr_image);
639	sio_setreg(com, com_ier, 0);
640	DELAY(1000);		/* XXX */
641	irqmap[0] = isa_irq_pending();
642
643	/*
644	 * Attempt to set loopback mode so that we can send a null byte
645	 * without annoying any external device.
646	 */
647/* EXTRA DELAY? */
648	sio_setreg(com, com_mcr, mcr_image | MCR_LOOPBACK);
649
650	/*
651	 * Attempt to generate an output interrupt.  On 8250's, setting
652	 * IER_ETXRDY generates an interrupt independent of the current
653	 * setting and independent of whether the THR is empty.  On 16450's,
654	 * setting IER_ETXRDY generates an interrupt independent of the
655	 * current setting.  On 16550A's, setting IER_ETXRDY only
656	 * generates an interrupt when IER_ETXRDY is not already set.
657	 */
658	sio_setreg(com, com_ier, IER_ETXRDY);
659
660	/*
661	 * On some 16x50 incompatibles, setting IER_ETXRDY doesn't generate
662	 * an interrupt.  They'd better generate one for actually doing
663	 * output.  Loopback may be broken on the same incompatibles but
664	 * it's unlikely to do more than allow the null byte out.
665	 */
666	sio_setreg(com, com_data, 0);
667	DELAY((1 + 2) * 1000000 / (SIO_TEST_SPEED / 10));
668
669	/*
670	 * Turn off loopback mode so that the interrupt gate works again
671	 * (MCR_IENABLE was hidden).  This should leave the device driving
672	 * an interrupt line high.  It doesn't matter if the interrupt
673	 * line oscillates while we are not looking at it, since interrupts
674	 * are disabled.
675	 */
676/* EXTRA DELAY? */
677	sio_setreg(com, com_mcr, mcr_image);
678
679	/*
680	 * It seems my Xircom CBEM56G Cardbus modem wants to be reset
681	 * to 8 bits *again*, or else probe test 0 will fail.
682	 * gwk@sgi.com, 4/19/2001
683	 */
684	sio_setreg(com, com_cfcr, CFCR_8BITS);
685
686	/*
687	 * Some pcmcia cards have the "TXRDY bug", so we check everyone
688	 * for IIR_TXRDY implementation ( Palido 321s, DC-1S... )
689	 */
690	if (noprobe) {
691		/* Reading IIR register twice */
692		for (fn = 0; fn < 2; fn ++) {
693			DELAY(10000);
694			failures[6] = sio_getreg(com, com_iir);
695		}
696		/* Check IIR_TXRDY clear ? */
697		result = 0;
698		if (failures[6] & IIR_TXRDY) {
699			/* No, Double check with clearing IER */
700			sio_setreg(com, com_ier, 0);
701			if (sio_getreg(com, com_iir) & IIR_NOPEND) {
702				/* Ok. We discovered TXRDY bug! */
703				SET_FLAG(dev, COM_C_IIR_TXRDYBUG);
704			} else {
705				/* Unknown, Just omit this chip.. XXX */
706				result = ENXIO;
707				sio_setreg(com, com_mcr, 0);
708			}
709		} else {
710			/* OK. this is well-known guys */
711			CLR_FLAG(dev, COM_C_IIR_TXRDYBUG);
712		}
713		sio_setreg(com, com_ier, 0);
714		sio_setreg(com, com_cfcr, CFCR_8BITS);
715		mtx_unlock_spin(&sio_lock);
716		bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
717		if (iobase == siocniobase)
718			result = 0;
719		if (result != 0) {
720			device_set_softc(dev, NULL);
721			free(com, M_DEVBUF);
722		}
723		return (result);
724	}
725
726	/*
727	 * Check that
728	 *	o the CFCR, IER and MCR in UART hold the values written to them
729	 *	  (the values happen to be all distinct - this is good for
730	 *	  avoiding false positive tests from bus echoes).
731	 *	o an output interrupt is generated and its vector is correct.
732	 *	o the interrupt goes away when the IIR in the UART is read.
733	 */
734/* EXTRA DELAY? */
735	failures[0] = sio_getreg(com, com_cfcr) - CFCR_8BITS;
736	failures[1] = sio_getreg(com, com_ier) - IER_ETXRDY;
737	failures[2] = sio_getreg(com, com_mcr) - mcr_image;
738	DELAY(10000);		/* Some internal modems need this time */
739	irqmap[1] = isa_irq_pending();
740	failures[4] = (sio_getreg(com, com_iir) & IIR_IMASK) - IIR_TXRDY;
741	DELAY(1000);		/* XXX */
742	irqmap[2] = isa_irq_pending();
743	failures[6] = (sio_getreg(com, com_iir) & IIR_IMASK) - IIR_NOPEND;
744
745	/*
746	 * Turn off all device interrupts and check that they go off properly.
747	 * Leave MCR_IENABLE alone.  For ports without a master port, it gates
748	 * the OUT2 output of the UART to
749	 * the ICU input.  Closing the gate would give a floating ICU input
750	 * (unless there is another device driving it) and spurious interrupts.
751	 * (On the system that this was first tested on, the input floats high
752	 * and gives a (masked) interrupt as soon as the gate is closed.)
753	 */
754	sio_setreg(com, com_ier, 0);
755	sio_setreg(com, com_cfcr, CFCR_8BITS);	/* dummy to avoid bus echo */
756	failures[7] = sio_getreg(com, com_ier);
757	DELAY(1000);		/* XXX */
758	irqmap[3] = isa_irq_pending();
759	failures[9] = (sio_getreg(com, com_iir) & IIR_IMASK) - IIR_NOPEND;
760
761	mtx_unlock_spin(&sio_lock);
762
763	irqs = irqmap[1] & ~irqmap[0];
764	if (bus_get_resource(idev, SYS_RES_IRQ, 0, &xirq, NULL) == 0 &&
765	    ((1 << xirq) & irqs) == 0) {
766		printf(
767		"sio%d: configured irq %ld not in bitmap of probed irqs %#x\n",
768		    device_get_unit(dev), xirq, irqs);
769		printf(
770		"sio%d: port may not be enabled\n",
771		    device_get_unit(dev));
772	}
773	if (bootverbose)
774		printf("sio%d: irq maps: %#x %#x %#x %#x\n",
775		    device_get_unit(dev),
776		    irqmap[0], irqmap[1], irqmap[2], irqmap[3]);
777
778	result = 0;
779	for (fn = 0; fn < sizeof failures; ++fn)
780		if (failures[fn]) {
781			sio_setreg(com, com_mcr, 0);
782			result = ENXIO;
783			if (bootverbose) {
784				printf("sio%d: probe failed test(s):",
785				    device_get_unit(dev));
786				for (fn = 0; fn < sizeof failures; ++fn)
787					if (failures[fn])
788						printf(" %d", fn);
789				printf("\n");
790			}
791			break;
792		}
793	bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
794	if (iobase == siocniobase)
795		result = 0;
796	if (result != 0) {
797		device_set_softc(dev, NULL);
798		free(com, M_DEVBUF);
799	}
800	return (result);
801}
802
803#ifdef COM_ESP
804static int
805espattach(com, esp_port)
806	struct com_s		*com;
807	Port_t			esp_port;
808{
809	u_char	dips;
810	u_char	val;
811
812	/*
813	 * Check the ESP-specific I/O port to see if we're an ESP
814	 * card.  If not, return failure immediately.
815	 */
816	if ((inb(esp_port) & 0xf3) == 0) {
817		printf(" port 0x%x is not an ESP board?\n", esp_port);
818		return (0);
819	}
820
821	/*
822	 * We've got something that claims to be a Hayes ESP card.
823	 * Let's hope so.
824	 */
825
826	/* Get the dip-switch configuration */
827	outb(esp_port + ESP_CMD1, ESP_GETDIPS);
828	dips = inb(esp_port + ESP_STATUS1);
829
830	/*
831	 * Bits 0,1 of dips say which COM port we are.
832	 */
833	if (rman_get_start(com->ioportres) == likely_com_ports[dips & 0x03])
834		printf(" : ESP");
835	else {
836		printf(" esp_port has com %d\n", dips & 0x03);
837		return (0);
838	}
839
840	/*
841	 * Check for ESP version 2.0 or later:  bits 4,5,6 = 010.
842	 */
843	outb(esp_port + ESP_CMD1, ESP_GETTEST);
844	val = inb(esp_port + ESP_STATUS1);	/* clear reg 1 */
845	val = inb(esp_port + ESP_STATUS2);
846	if ((val & 0x70) < 0x20) {
847		printf("-old (%o)", val & 0x70);
848		return (0);
849	}
850
851	/*
852	 * Check for ability to emulate 16550:  bit 7 == 1
853	 */
854	if ((dips & 0x80) == 0) {
855		printf(" slave");
856		return (0);
857	}
858
859	/*
860	 * Okay, we seem to be a Hayes ESP card.  Whee.
861	 */
862	com->esp = TRUE;
863	com->esp_port = esp_port;
864	return (1);
865}
866#endif /* COM_ESP */
867
868int
869sioattach(dev, xrid, rclk)
870	device_t	dev;
871	int		xrid;
872	u_long		rclk;
873{
874	struct com_s	*com;
875#ifdef COM_ESP
876	Port_t		*espp;
877#endif
878	Port_t		iobase;
879	int		minorbase;
880	int		unit;
881	u_int		flags;
882	int		rid;
883	struct resource *port;
884	int		ret;
885
886	rid = xrid;
887	port = bus_alloc_resource(dev, SYS_RES_IOPORT, &rid,
888				  0, ~0, IO_COMSIZE, RF_ACTIVE);
889	if (!port)
890		return (ENXIO);
891
892	iobase = rman_get_start(port);
893	unit = device_get_unit(dev);
894	com = device_get_softc(dev);
895	flags = device_get_flags(dev);
896
897	if (unit >= sio_numunits)
898		sio_numunits = unit + 1;
899	/*
900	 * sioprobe() has initialized the device registers as follows:
901	 *	o cfcr = CFCR_8BITS.
902	 *	  It is most important that CFCR_DLAB is off, so that the
903	 *	  data port is not hidden when we enable interrupts.
904	 *	o ier = 0.
905	 *	  Interrupts are only enabled when the line is open.
906	 *	o mcr = MCR_IENABLE, or 0 if the port has AST/4 compatible
907	 *	  interrupt control register or the config specifies no irq.
908	 *	  Keeping MCR_DTR and MCR_RTS off might stop the external
909	 *	  device from sending before we are ready.
910	 */
911	bzero(com, sizeof *com);
912	com->unit = unit;
913	com->ioportres = port;
914	com->bst = rman_get_bustag(port);
915	com->bsh = rman_get_bushandle(port);
916	com->cfcr_image = CFCR_8BITS;
917	com->dtr_wait = 3 * hz;
918	com->loses_outints = COM_LOSESOUTINTS(flags) != 0;
919	com->no_irq = bus_get_resource(dev, SYS_RES_IRQ, 0, NULL, NULL) != 0;
920	com->tx_fifo_size = 1;
921	com->obufs[0].l_head = com->obuf1;
922	com->obufs[1].l_head = com->obuf2;
923
924	com->data_port = iobase + com_data;
925	com->int_id_port = iobase + com_iir;
926	com->modem_ctl_port = iobase + com_mcr;
927	com->mcr_image = inb(com->modem_ctl_port);
928	com->line_status_port = iobase + com_lsr;
929	com->modem_status_port = iobase + com_msr;
930	com->intr_ctl_port = iobase + com_ier;
931
932	if (rclk == 0)
933		rclk = DEFAULT_RCLK;
934	com->rclk = rclk;
935
936	/*
937	 * We don't use all the flags from <sys/ttydefaults.h> since they
938	 * are only relevant for logins.  It's important to have echo off
939	 * initially so that the line doesn't start blathering before the
940	 * echo flag can be turned off.
941	 */
942	com->it_in.c_iflag = 0;
943	com->it_in.c_oflag = 0;
944	com->it_in.c_cflag = TTYDEF_CFLAG;
945	com->it_in.c_lflag = 0;
946	if (unit == comconsole) {
947		com->it_in.c_iflag = TTYDEF_IFLAG;
948		com->it_in.c_oflag = TTYDEF_OFLAG;
949		com->it_in.c_cflag = TTYDEF_CFLAG | CLOCAL;
950		com->it_in.c_lflag = TTYDEF_LFLAG;
951		com->lt_out.c_cflag = com->lt_in.c_cflag = CLOCAL;
952		com->lt_out.c_ispeed = com->lt_out.c_ospeed =
953		com->lt_in.c_ispeed = com->lt_in.c_ospeed =
954		com->it_in.c_ispeed = com->it_in.c_ospeed = comdefaultrate;
955	} else
956		com->it_in.c_ispeed = com->it_in.c_ospeed = TTYDEF_SPEED;
957	if (siosetwater(com, com->it_in.c_ispeed) != 0) {
958		mtx_unlock_spin(&sio_lock);
959		/*
960		 * Leave i/o resources allocated if this is a `cn'-level
961		 * console, so that other devices can't snarf them.
962		 */
963		if (iobase != siocniobase)
964			bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
965		return (ENOMEM);
966	}
967	mtx_unlock_spin(&sio_lock);
968	termioschars(&com->it_in);
969	com->it_out = com->it_in;
970
971	/* attempt to determine UART type */
972	printf("sio%d: type", unit);
973
974
975#ifdef COM_MULTIPORT
976	if (!COM_ISMULTIPORT(flags) && !COM_IIR_TXRDYBUG(flags))
977#else
978	if (!COM_IIR_TXRDYBUG(flags))
979#endif
980	{
981		u_char	scr;
982		u_char	scr1;
983		u_char	scr2;
984
985		scr = sio_getreg(com, com_scr);
986		sio_setreg(com, com_scr, 0xa5);
987		scr1 = sio_getreg(com, com_scr);
988		sio_setreg(com, com_scr, 0x5a);
989		scr2 = sio_getreg(com, com_scr);
990		sio_setreg(com, com_scr, scr);
991		if (scr1 != 0xa5 || scr2 != 0x5a) {
992			printf(" 8250 or not responding");
993			goto determined_type;
994		}
995	}
996	sio_setreg(com, com_fifo, FIFO_ENABLE | FIFO_RX_HIGH);
997	DELAY(100);
998	com->st16650a = 0;
999	switch (inb(com->int_id_port) & IIR_FIFO_MASK) {
1000	case FIFO_RX_LOW:
1001		printf(" 16450");
1002		break;
1003	case FIFO_RX_MEDL:
1004		printf(" 16450?");
1005		break;
1006	case FIFO_RX_MEDH:
1007		printf(" 16550?");
1008		break;
1009	case FIFO_RX_HIGH:
1010		if (COM_NOFIFO(flags)) {
1011			printf(" 16550A fifo disabled");
1012		} else {
1013			com->hasfifo = TRUE;
1014			if (COM_ST16650A(flags)) {
1015				com->st16650a = 1;
1016				com->tx_fifo_size = 32;
1017				printf(" ST16650A");
1018			} else {
1019				com->tx_fifo_size = COM_FIFOSIZE(flags);
1020				printf(" 16550A");
1021			}
1022		}
1023#ifdef COM_ESP
1024		for (espp = likely_esp_ports; *espp != 0; espp++)
1025			if (espattach(com, *espp)) {
1026				com->tx_fifo_size = 1024;
1027				break;
1028			}
1029#endif
1030		if (!com->st16650a) {
1031			if (!com->tx_fifo_size)
1032				com->tx_fifo_size = 16;
1033			else
1034				printf(" lookalike with %d bytes FIFO",
1035				    com->tx_fifo_size);
1036		}
1037
1038		break;
1039	}
1040
1041#ifdef COM_ESP
1042	if (com->esp) {
1043		/*
1044		 * Set 16550 compatibility mode.
1045		 * We don't use the ESP_MODE_SCALE bit to increase the
1046		 * fifo trigger levels because we can't handle large
1047		 * bursts of input.
1048		 * XXX flow control should be set in comparam(), not here.
1049		 */
1050		outb(com->esp_port + ESP_CMD1, ESP_SETMODE);
1051		outb(com->esp_port + ESP_CMD2, ESP_MODE_RTS | ESP_MODE_FIFO);
1052
1053		/* Set RTS/CTS flow control. */
1054		outb(com->esp_port + ESP_CMD1, ESP_SETFLOWTYPE);
1055		outb(com->esp_port + ESP_CMD2, ESP_FLOW_RTS);
1056		outb(com->esp_port + ESP_CMD2, ESP_FLOW_CTS);
1057
1058		/* Set flow-control levels. */
1059		outb(com->esp_port + ESP_CMD1, ESP_SETRXFLOW);
1060		outb(com->esp_port + ESP_CMD2, HIBYTE(768));
1061		outb(com->esp_port + ESP_CMD2, LOBYTE(768));
1062		outb(com->esp_port + ESP_CMD2, HIBYTE(512));
1063		outb(com->esp_port + ESP_CMD2, LOBYTE(512));
1064	}
1065#endif /* COM_ESP */
1066	sio_setreg(com, com_fifo, 0);
1067determined_type: ;
1068
1069#ifdef COM_MULTIPORT
1070	if (COM_ISMULTIPORT(flags)) {
1071		device_t masterdev;
1072
1073		com->multiport = TRUE;
1074		printf(" (multiport");
1075		if (unit == COM_MPMASTER(flags))
1076			printf(" master");
1077		printf(")");
1078		masterdev = devclass_get_device(sio_devclass,
1079		    COM_MPMASTER(flags));
1080		com->no_irq = (masterdev == NULL || bus_get_resource(masterdev,
1081		    SYS_RES_IRQ, 0, NULL, NULL) != 0);
1082	 }
1083#endif /* COM_MULTIPORT */
1084	if (unit == comconsole)
1085		printf(", console");
1086	if (COM_IIR_TXRDYBUG(flags))
1087		printf(" with a bogus IIR_TXRDY register");
1088	printf("\n");
1089
1090	if (sio_fast_ih == NULL) {
1091		swi_add(&tty_ithd, "tty:sio", siopoll, NULL, SWI_TTY, 0,
1092		    &sio_fast_ih);
1093		swi_add(&clk_ithd, "tty:sio", siopoll, NULL, SWI_TTY, 0,
1094		    &sio_slow_ih);
1095	}
1096	minorbase = UNIT_TO_MINOR(unit);
1097	com->devs[0] = make_dev(&sio_cdevsw, minorbase,
1098	    UID_ROOT, GID_WHEEL, 0600, "ttyd%r", unit);
1099	com->devs[1] = make_dev(&sio_cdevsw, minorbase | CONTROL_INIT_STATE,
1100	    UID_ROOT, GID_WHEEL, 0600, "ttyid%r", unit);
1101	com->devs[2] = make_dev(&sio_cdevsw, minorbase | CONTROL_LOCK_STATE,
1102	    UID_ROOT, GID_WHEEL, 0600, "ttyld%r", unit);
1103	com->devs[3] = make_dev(&sio_cdevsw, minorbase | CALLOUT_MASK,
1104	    UID_UUCP, GID_DIALER, 0660, "cuaa%r", unit);
1105	com->devs[4] = make_dev(&sio_cdevsw,
1106	    minorbase | CALLOUT_MASK | CONTROL_INIT_STATE,
1107	    UID_UUCP, GID_DIALER, 0660, "cuaia%r", unit);
1108	com->devs[5] = make_dev(&sio_cdevsw,
1109	    minorbase | CALLOUT_MASK | CONTROL_LOCK_STATE,
1110	    UID_UUCP, GID_DIALER, 0660, "cuala%r", unit);
1111	com->flags = flags;
1112	com->pps.ppscap = PPS_CAPTUREASSERT | PPS_CAPTURECLEAR;
1113	pps_init(&com->pps);
1114
1115	rid = 0;
1116	com->irqres = bus_alloc_resource(dev, SYS_RES_IRQ, &rid, 0ul, ~0ul, 1,
1117	    RF_ACTIVE);
1118	if (com->irqres) {
1119		ret = BUS_SETUP_INTR(device_get_parent(dev), dev, com->irqres,
1120				     INTR_TYPE_TTY | INTR_FAST,
1121				     siointr, com, &com->cookie);
1122		if (ret) {
1123			ret = BUS_SETUP_INTR(device_get_parent(dev), dev,
1124					     com->irqres, INTR_TYPE_TTY,
1125					     siointr, com, &com->cookie);
1126			if (ret == 0)
1127				device_printf(dev, "unable to activate interrupt in fast mode - using normal mode\n");
1128		}
1129		if (ret)
1130			device_printf(dev, "could not activate interrupt\n");
1131#if defined(DDB) && (defined(BREAK_TO_DEBUGGER) || \
1132    defined(ALT_BREAK_TO_DEBUGGER))
1133		/*
1134		 * Enable interrupts for early break-to-debugger support
1135		 * on the console.
1136		 */
1137		if (ret == 0 && unit == comconsole)
1138			outb(siocniobase + com_ier, IER_ERXRDY | IER_ERLS |
1139			    IER_EMSC);
1140#endif
1141	}
1142
1143	return (0);
1144}
1145
1146static int
1147sioopen(dev, flag, mode, td)
1148	dev_t		dev;
1149	int		flag;
1150	int		mode;
1151	struct thread	*td;
1152{
1153	struct com_s	*com;
1154	int		error;
1155	int		mynor;
1156	int		s;
1157	struct tty	*tp;
1158	int		unit;
1159
1160	mynor = minor(dev);
1161	unit = MINOR_TO_UNIT(mynor);
1162	com = com_addr(unit);
1163	if (com == NULL)
1164		return (ENXIO);
1165	if (com->gone)
1166		return (ENXIO);
1167	if (mynor & CONTROL_MASK)
1168		return (0);
1169	tp = dev->si_tty = com->tp = ttymalloc(com->tp);
1170	s = spltty();
1171	/*
1172	 * We jump to this label after all non-interrupted sleeps to pick
1173	 * up any changes of the device state.
1174	 */
1175open_top:
1176	while (com->state & CS_DTR_OFF) {
1177		error = tsleep(&com->dtr_wait, TTIPRI | PCATCH, "siodtr", 0);
1178		if (com_addr(unit) == NULL)
1179			return (ENXIO);
1180		if (error != 0 || com->gone)
1181			goto out;
1182	}
1183	if (tp->t_state & TS_ISOPEN) {
1184		/*
1185		 * The device is open, so everything has been initialized.
1186		 * Handle conflicts.
1187		 */
1188		if (mynor & CALLOUT_MASK) {
1189			if (!com->active_out) {
1190				error = EBUSY;
1191				goto out;
1192			}
1193		} else {
1194			if (com->active_out) {
1195				if (flag & O_NONBLOCK) {
1196					error = EBUSY;
1197					goto out;
1198				}
1199				error =	tsleep(&com->active_out,
1200					       TTIPRI | PCATCH, "siobi", 0);
1201				if (com_addr(unit) == NULL)
1202					return (ENXIO);
1203				if (error != 0 || com->gone)
1204					goto out;
1205				goto open_top;
1206			}
1207		}
1208		if (tp->t_state & TS_XCLUDE &&
1209		    suser(td)) {
1210			error = EBUSY;
1211			goto out;
1212		}
1213	} else {
1214		/*
1215		 * The device isn't open, so there are no conflicts.
1216		 * Initialize it.  Initialization is done twice in many
1217		 * cases: to preempt sleeping callin opens if we are
1218		 * callout, and to complete a callin open after DCD rises.
1219		 */
1220		tp->t_oproc = comstart;
1221		tp->t_param = comparam;
1222		tp->t_stop = comstop;
1223		tp->t_dev = dev;
1224		tp->t_termios = mynor & CALLOUT_MASK
1225				? com->it_out : com->it_in;
1226		(void)commctl(com, TIOCM_DTR | TIOCM_RTS, DMSET);
1227		com->poll = com->no_irq;
1228		com->poll_output = com->loses_outints;
1229		++com->wopeners;
1230		error = comparam(tp, &tp->t_termios);
1231		--com->wopeners;
1232		if (error != 0)
1233			goto out;
1234		/*
1235		 * XXX we should goto open_top if comparam() slept.
1236		 */
1237		if (com->hasfifo) {
1238			/*
1239			 * (Re)enable and drain fifos.
1240			 *
1241			 * Certain SMC chips cause problems if the fifos
1242			 * are enabled while input is ready.  Turn off the
1243			 * fifo if necessary to clear the input.  We test
1244			 * the input ready bit after enabling the fifos
1245			 * since we've already enabled them in comparam()
1246			 * and to handle races between enabling and fresh
1247			 * input.
1248			 */
1249			while (TRUE) {
1250				sio_setreg(com, com_fifo,
1251					   FIFO_RCV_RST | FIFO_XMT_RST
1252					   | com->fifo_image);
1253				/*
1254				 * XXX the delays are for superstitious
1255				 * historical reasons.  It must be less than
1256				 * the character time at the maximum
1257				 * supported speed (87 usec at 115200 bps
1258				 * 8N1).  Otherwise we might loop endlessly
1259				 * if data is streaming in.  We used to use
1260				 * delays of 100.  That usually worked
1261				 * because DELAY(100) used to usually delay
1262				 * for about 85 usec instead of 100.
1263				 */
1264				DELAY(50);
1265				if (!(inb(com->line_status_port) & LSR_RXRDY))
1266					break;
1267				sio_setreg(com, com_fifo, 0);
1268				DELAY(50);
1269				(void) inb(com->data_port);
1270			}
1271		}
1272
1273		mtx_lock_spin(&sio_lock);
1274		(void) inb(com->line_status_port);
1275		(void) inb(com->data_port);
1276		com->prev_modem_status = com->last_modem_status
1277		    = inb(com->modem_status_port);
1278		if (COM_IIR_TXRDYBUG(com->flags)) {
1279			outb(com->intr_ctl_port, IER_ERXRDY | IER_ERLS
1280						| IER_EMSC);
1281		} else {
1282			outb(com->intr_ctl_port, IER_ERXRDY | IER_ETXRDY
1283						| IER_ERLS | IER_EMSC);
1284		}
1285		mtx_unlock_spin(&sio_lock);
1286		/*
1287		 * Handle initial DCD.  Callout devices get a fake initial
1288		 * DCD (trapdoor DCD).  If we are callout, then any sleeping
1289		 * callin opens get woken up and resume sleeping on "siobi"
1290		 * instead of "siodcd".
1291		 */
1292		/*
1293		 * XXX `mynor & CALLOUT_MASK' should be
1294		 * `tp->t_cflag & (SOFT_CARRIER | TRAPDOOR_CARRIER) where
1295		 * TRAPDOOR_CARRIER is the default initial state for callout
1296		 * devices and SOFT_CARRIER is like CLOCAL except it hides
1297		 * the true carrier.
1298		 */
1299		if (com->prev_modem_status & MSR_DCD || mynor & CALLOUT_MASK)
1300			(*linesw[tp->t_line].l_modem)(tp, 1);
1301	}
1302	/*
1303	 * Wait for DCD if necessary.
1304	 */
1305	if (!(tp->t_state & TS_CARR_ON) && !(mynor & CALLOUT_MASK)
1306	    && !(tp->t_cflag & CLOCAL) && !(flag & O_NONBLOCK)) {
1307		++com->wopeners;
1308		error = tsleep(TSA_CARR_ON(tp), TTIPRI | PCATCH, "siodcd", 0);
1309		if (com_addr(unit) == NULL)
1310			return (ENXIO);
1311		--com->wopeners;
1312		if (error != 0 || com->gone)
1313			goto out;
1314		goto open_top;
1315	}
1316	error =	(*linesw[tp->t_line].l_open)(dev, tp);
1317	disc_optim(tp, &tp->t_termios, com);
1318	if (tp->t_state & TS_ISOPEN && mynor & CALLOUT_MASK)
1319		com->active_out = TRUE;
1320	siosettimeout();
1321out:
1322	splx(s);
1323	if (!(tp->t_state & TS_ISOPEN) && com->wopeners == 0)
1324		comhardclose(com);
1325	return (error);
1326}
1327
1328static int
1329sioclose(dev, flag, mode, td)
1330	dev_t		dev;
1331	int		flag;
1332	int		mode;
1333	struct thread	*td;
1334{
1335	struct com_s	*com;
1336	int		mynor;
1337	int		s;
1338	struct tty	*tp;
1339
1340	mynor = minor(dev);
1341	if (mynor & CONTROL_MASK)
1342		return (0);
1343	com = com_addr(MINOR_TO_UNIT(mynor));
1344	if (com == NULL)
1345		return (ENODEV);
1346	tp = com->tp;
1347	s = spltty();
1348	(*linesw[tp->t_line].l_close)(tp, flag);
1349	disc_optim(tp, &tp->t_termios, com);
1350	comstop(tp, FREAD | FWRITE);
1351	comhardclose(com);
1352	ttyclose(tp);
1353	siosettimeout();
1354	splx(s);
1355	if (com->gone) {
1356		printf("sio%d: gone\n", com->unit);
1357		s = spltty();
1358		if (com->ibuf != NULL)
1359			free(com->ibuf, M_DEVBUF);
1360		bzero(tp, sizeof *tp);
1361		splx(s);
1362	}
1363	return (0);
1364}
1365
1366static void
1367comhardclose(com)
1368	struct com_s	*com;
1369{
1370	int		s;
1371	struct tty	*tp;
1372	int		unit;
1373
1374	unit = com->unit;
1375	s = spltty();
1376	com->poll = FALSE;
1377	com->poll_output = FALSE;
1378	com->do_timestamp = FALSE;
1379	com->do_dcd_timestamp = FALSE;
1380	com->pps.ppsparam.mode = 0;
1381	sio_setreg(com, com_cfcr, com->cfcr_image &= ~CFCR_SBREAK);
1382	tp = com->tp;
1383
1384#if defined(DDB) && (defined(BREAK_TO_DEBUGGER) || \
1385    defined(ALT_BREAK_TO_DEBUGGER))
1386	/*
1387	 * Leave interrupts enabled and don't clear DTR if this is the
1388	 * console. This allows us to detect break-to-debugger events
1389	 * while the console device is closed.
1390	 */
1391	if (com->unit != comconsole)
1392#endif
1393	{
1394		sio_setreg(com, com_ier, 0);
1395		if (tp->t_cflag & HUPCL
1396		    /*
1397		     * XXX we will miss any carrier drop between here and the
1398		     * next open.  Perhaps we should watch DCD even when the
1399		     * port is closed; it is not sufficient to check it at
1400		     * the next open because it might go up and down while
1401		     * we're not watching.
1402		     */
1403		    || (!com->active_out
1404		        && !(com->prev_modem_status & MSR_DCD)
1405		        && !(com->it_in.c_cflag & CLOCAL))
1406		    || !(tp->t_state & TS_ISOPEN)) {
1407			(void)commctl(com, TIOCM_DTR, DMBIC);
1408			if (com->dtr_wait != 0 && !(com->state & CS_DTR_OFF)) {
1409				timeout(siodtrwakeup, com, com->dtr_wait);
1410				com->state |= CS_DTR_OFF;
1411			}
1412		}
1413	}
1414	if (com->hasfifo) {
1415		/*
1416		 * Disable fifos so that they are off after controlled
1417		 * reboots.  Some BIOSes fail to detect 16550s when the
1418		 * fifos are enabled.
1419		 */
1420		sio_setreg(com, com_fifo, 0);
1421	}
1422	com->active_out = FALSE;
1423	wakeup(&com->active_out);
1424	wakeup(TSA_CARR_ON(tp));	/* restart any wopeners */
1425	splx(s);
1426}
1427
1428static int
1429sioread(dev, uio, flag)
1430	dev_t		dev;
1431	struct uio	*uio;
1432	int		flag;
1433{
1434	int		mynor;
1435	struct com_s	*com;
1436
1437	mynor = minor(dev);
1438	if (mynor & CONTROL_MASK)
1439		return (ENODEV);
1440	com = com_addr(MINOR_TO_UNIT(mynor));
1441	if (com == NULL || com->gone)
1442		return (ENODEV);
1443	return ((*linesw[com->tp->t_line].l_read)(com->tp, uio, flag));
1444}
1445
1446static int
1447siowrite(dev, uio, flag)
1448	dev_t		dev;
1449	struct uio	*uio;
1450	int		flag;
1451{
1452	int		mynor;
1453	struct com_s	*com;
1454	int		unit;
1455
1456	mynor = minor(dev);
1457	if (mynor & CONTROL_MASK)
1458		return (ENODEV);
1459
1460	unit = MINOR_TO_UNIT(mynor);
1461	com = com_addr(unit);
1462	if (com == NULL || com->gone)
1463		return (ENODEV);
1464	/*
1465	 * (XXX) We disallow virtual consoles if the physical console is
1466	 * a serial port.  This is in case there is a display attached that
1467	 * is not the console.  In that situation we don't need/want the X
1468	 * server taking over the console.
1469	 */
1470	if (constty != NULL && unit == comconsole)
1471		constty = NULL;
1472	return ((*linesw[com->tp->t_line].l_write)(com->tp, uio, flag));
1473}
1474
1475static void
1476siobusycheck(chan)
1477	void	*chan;
1478{
1479	struct com_s	*com;
1480	int		s;
1481
1482	com = (struct com_s *)chan;
1483
1484	/*
1485	 * Clear TS_BUSY if low-level output is complete.
1486	 * spl locking is sufficient because siointr1() does not set CS_BUSY.
1487	 * If siointr1() clears CS_BUSY after we look at it, then we'll get
1488	 * called again.  Reading the line status port outside of siointr1()
1489	 * is safe because CS_BUSY is clear so there are no output interrupts
1490	 * to lose.
1491	 */
1492	s = spltty();
1493	if (com->state & CS_BUSY)
1494		com->extra_state &= ~CSE_BUSYCHECK;	/* False alarm. */
1495	else if ((inb(com->line_status_port) & (LSR_TSRE | LSR_TXRDY))
1496	    == (LSR_TSRE | LSR_TXRDY)) {
1497		com->tp->t_state &= ~TS_BUSY;
1498		ttwwakeup(com->tp);
1499		com->extra_state &= ~CSE_BUSYCHECK;
1500	} else
1501		timeout(siobusycheck, com, hz / 100);
1502	splx(s);
1503}
1504
1505static u_int
1506siodivisor(rclk, speed)
1507	u_long	rclk;
1508	speed_t	speed;
1509{
1510	long	actual_speed;
1511	u_int	divisor;
1512	int	error;
1513
1514	if (speed == 0 || speed > (ULONG_MAX - 1) / 8)
1515		return (0);
1516	divisor = (rclk / (8UL * speed) + 1) / 2;
1517	if (divisor == 0 || divisor >= 65536)
1518		return (0);
1519	actual_speed = rclk / (16UL * divisor);
1520
1521	/* 10 times error in percent: */
1522	error = ((actual_speed - (long)speed) * 2000 / (long)speed + 1) / 2;
1523
1524	/* 3.0% maximum error tolerance: */
1525	if (error < -30 || error > 30)
1526		return (0);
1527
1528	return (divisor);
1529}
1530
1531static void
1532siodtrwakeup(chan)
1533	void	*chan;
1534{
1535	struct com_s	*com;
1536
1537	com = (struct com_s *)chan;
1538	com->state &= ~CS_DTR_OFF;
1539	wakeup(&com->dtr_wait);
1540}
1541
1542/*
1543 * Call this function with the sio_lock mutex held.  It will return with the
1544 * lock still held.
1545 */
1546static void
1547sioinput(com)
1548	struct com_s	*com;
1549{
1550	u_char		*buf;
1551	int		incc;
1552	u_char		line_status;
1553	int		recv_data;
1554	struct tty	*tp;
1555
1556	buf = com->ibuf;
1557	tp = com->tp;
1558	if (!(tp->t_state & TS_ISOPEN) || !(tp->t_cflag & CREAD)) {
1559		com_events -= (com->iptr - com->ibuf);
1560		com->iptr = com->ibuf;
1561		return;
1562	}
1563	if (tp->t_state & TS_CAN_BYPASS_L_RINT) {
1564		/*
1565		 * Avoid the grotesquely inefficient lineswitch routine
1566		 * (ttyinput) in "raw" mode.  It usually takes about 450
1567		 * instructions (that's without canonical processing or echo!).
1568		 * slinput is reasonably fast (usually 40 instructions plus
1569		 * call overhead).
1570		 */
1571		do {
1572			/*
1573			 * This may look odd, but it is using save-and-enable
1574			 * semantics instead of the save-and-disable semantics
1575			 * that are used everywhere else.
1576			 */
1577			mtx_unlock_spin(&sio_lock);
1578			incc = com->iptr - buf;
1579			if (tp->t_rawq.c_cc + incc > tp->t_ihiwat
1580			    && (com->state & CS_RTS_IFLOW
1581				|| tp->t_iflag & IXOFF)
1582			    && !(tp->t_state & TS_TBLOCK))
1583				ttyblock(tp);
1584			com->delta_error_counts[CE_TTY_BUF_OVERFLOW]
1585				+= b_to_q((char *)buf, incc, &tp->t_rawq);
1586			buf += incc;
1587			tk_nin += incc;
1588			tk_rawcc += incc;
1589			tp->t_rawcc += incc;
1590			ttwakeup(tp);
1591			if (tp->t_state & TS_TTSTOP
1592			    && (tp->t_iflag & IXANY
1593				|| tp->t_cc[VSTART] == tp->t_cc[VSTOP])) {
1594				tp->t_state &= ~TS_TTSTOP;
1595				tp->t_lflag &= ~FLUSHO;
1596				comstart(tp);
1597			}
1598			mtx_lock_spin(&sio_lock);
1599		} while (buf < com->iptr);
1600	} else {
1601		do {
1602			/*
1603			 * This may look odd, but it is using save-and-enable
1604			 * semantics instead of the save-and-disable semantics
1605			 * that are used everywhere else.
1606			 */
1607			mtx_unlock_spin(&sio_lock);
1608			line_status = buf[com->ierroff];
1609			recv_data = *buf++;
1610			if (line_status
1611			    & (LSR_BI | LSR_FE | LSR_OE | LSR_PE)) {
1612				if (line_status & LSR_BI)
1613					recv_data |= TTY_BI;
1614				if (line_status & LSR_FE)
1615					recv_data |= TTY_FE;
1616				if (line_status & LSR_OE)
1617					recv_data |= TTY_OE;
1618				if (line_status & LSR_PE)
1619					recv_data |= TTY_PE;
1620			}
1621			(*linesw[tp->t_line].l_rint)(recv_data, tp);
1622			mtx_lock_spin(&sio_lock);
1623		} while (buf < com->iptr);
1624	}
1625	com_events -= (com->iptr - com->ibuf);
1626	com->iptr = com->ibuf;
1627
1628	/*
1629	 * There is now room for another low-level buffer full of input,
1630	 * so enable RTS if it is now disabled and there is room in the
1631	 * high-level buffer.
1632	 */
1633	if ((com->state & CS_RTS_IFLOW) && !(com->mcr_image & MCR_RTS) &&
1634	    !(tp->t_state & TS_TBLOCK))
1635		outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
1636}
1637
1638void
1639siointr(arg)
1640	void		*arg;
1641{
1642	struct com_s	*com;
1643
1644#ifndef COM_MULTIPORT
1645	com = (struct com_s *)arg;
1646
1647	mtx_lock_spin(&sio_lock);
1648	siointr1(com);
1649	mtx_unlock_spin(&sio_lock);
1650#else /* COM_MULTIPORT */
1651	bool_t		possibly_more_intrs;
1652	int		unit;
1653
1654	/*
1655	 * Loop until there is no activity on any port.  This is necessary
1656	 * to get an interrupt edge more than to avoid another interrupt.
1657	 * If the IRQ signal is just an OR of the IRQ signals from several
1658	 * devices, then the edge from one may be lost because another is
1659	 * on.
1660	 */
1661	mtx_lock_spin(&sio_lock);
1662	do {
1663		possibly_more_intrs = FALSE;
1664		for (unit = 0; unit < sio_numunits; ++unit) {
1665			com = com_addr(unit);
1666			/*
1667			 * XXX COM_LOCK();
1668			 * would it work here, or be counter-productive?
1669			 */
1670			if (com != NULL
1671			    && !com->gone
1672			    && (inb(com->int_id_port) & IIR_IMASK)
1673			       != IIR_NOPEND) {
1674				siointr1(com);
1675				possibly_more_intrs = TRUE;
1676			}
1677			/* XXX COM_UNLOCK(); */
1678		}
1679	} while (possibly_more_intrs);
1680	mtx_unlock_spin(&sio_lock);
1681#endif /* COM_MULTIPORT */
1682}
1683
1684static struct timespec siots[8192];
1685static int siotso;
1686static int volatile siotsunit = -1;
1687
1688static int
1689sysctl_siots(SYSCTL_HANDLER_ARGS)
1690{
1691	char buf[128];
1692	long long delta;
1693	size_t len;
1694	int error, i;
1695
1696	for (i = 1; i < siotso; i++) {
1697		delta = (long long)(siots[i].tv_sec - siots[i - 1].tv_sec) *
1698		    1000000000 +
1699		    (siots[i].tv_nsec - siots[i - 1].tv_nsec);
1700		len = sprintf(buf, "%lld\n", delta);
1701		if (delta >= 110000)
1702			len += sprintf(buf + len - 1, ": *** %ld.%09ld\n",
1703			    (long)siots[i].tv_sec, siots[i].tv_nsec);
1704		if (i == siotso - 1)
1705			buf[len - 1] = '\0';
1706		error = SYSCTL_OUT(req, buf, len);
1707		if (error != 0)
1708			return (error);
1709		uio_yield();
1710	}
1711	return (0);
1712}
1713
1714SYSCTL_PROC(_machdep, OID_AUTO, siots, CTLTYPE_STRING | CTLFLAG_RD,
1715    0, 0, sysctl_siots, "A", "sio timestamps");
1716
1717static void
1718siointr1(com)
1719	struct com_s	*com;
1720{
1721	u_char	line_status;
1722	u_char	modem_status;
1723	u_char	*ioptr;
1724	u_char	recv_data;
1725	u_char	int_ctl;
1726	u_char	int_ctl_new;
1727
1728	int_ctl = inb(com->intr_ctl_port);
1729	int_ctl_new = int_ctl;
1730
1731	while (!com->gone) {
1732		if (com->pps.ppsparam.mode & PPS_CAPTUREBOTH) {
1733			modem_status = inb(com->modem_status_port);
1734		        if ((modem_status ^ com->last_modem_status) & MSR_DCD) {
1735				pps_capture(&com->pps);
1736				pps_event(&com->pps, (modem_status & MSR_DCD) ?
1737				    PPS_CAPTUREASSERT : PPS_CAPTURECLEAR);
1738			}
1739		}
1740		line_status = inb(com->line_status_port);
1741
1742		/* input event? (check first to help avoid overruns) */
1743		while (line_status & LSR_RCV_MASK) {
1744			/* break/unnattached error bits or real input? */
1745			if (!(line_status & LSR_RXRDY))
1746				recv_data = 0;
1747			else
1748				recv_data = inb(com->data_port);
1749#if defined(DDB) && defined(ALT_BREAK_TO_DEBUGGER)
1750			/*
1751			 * Solaris implements a new BREAK which is initiated
1752			 * by a character sequence CR ~ ^b which is similar
1753			 * to a familiar pattern used on Sun servers by the
1754			 * Remote Console.
1755			 */
1756#define	KEY_CRTLB	2	/* ^B */
1757#define	KEY_CR		13	/* CR '\r' */
1758#define	KEY_TILDE	126	/* ~ */
1759
1760			if (com->unit == comconsole) {
1761				static int brk_state1 = 0, brk_state2 = 0;
1762				if (recv_data == KEY_CR) {
1763					brk_state1 = recv_data;
1764					brk_state2 = 0;
1765				} else if (brk_state1 == KEY_CR
1766					   && (recv_data == KEY_TILDE
1767					       || recv_data == KEY_CRTLB)) {
1768					if (recv_data == KEY_TILDE)
1769						brk_state2 = recv_data;
1770					else if (brk_state2 == KEY_TILDE
1771						 && recv_data == KEY_CRTLB) {
1772							breakpoint();
1773							brk_state1 = 0;
1774							brk_state2 = 0;
1775							goto cont;
1776					} else
1777						brk_state2 = 0;
1778				} else
1779					brk_state1 = 0;
1780			}
1781#endif
1782			if (line_status & (LSR_BI | LSR_FE | LSR_PE)) {
1783				/*
1784				 * Don't store BI if IGNBRK or FE/PE if IGNPAR.
1785				 * Otherwise, push the work to a higher level
1786				 * (to handle PARMRK) if we're bypassing.
1787				 * Otherwise, convert BI/FE and PE+INPCK to 0.
1788				 *
1789				 * This makes bypassing work right in the
1790				 * usual "raw" case (IGNBRK set, and IGNPAR
1791				 * and INPCK clear).
1792				 *
1793				 * Note: BI together with FE/PE means just BI.
1794				 */
1795				if (line_status & LSR_BI) {
1796#if defined(DDB) && defined(BREAK_TO_DEBUGGER)
1797					if (com->unit == comconsole) {
1798						breakpoint();
1799						goto cont;
1800					}
1801#endif
1802					if (com->tp == NULL
1803					    || com->tp->t_iflag & IGNBRK)
1804						goto cont;
1805				} else {
1806					if (com->tp == NULL
1807					    || com->tp->t_iflag & IGNPAR)
1808						goto cont;
1809				}
1810				if (com->tp->t_state & TS_CAN_BYPASS_L_RINT
1811				    && (line_status & (LSR_BI | LSR_FE)
1812					|| com->tp->t_iflag & INPCK))
1813					recv_data = 0;
1814			}
1815			++com->bytes_in;
1816			if (com->hotchar != 0 && recv_data == com->hotchar)
1817				swi_sched(sio_fast_ih, 0);
1818			ioptr = com->iptr;
1819			if (ioptr >= com->ibufend)
1820				CE_RECORD(com, CE_INTERRUPT_BUF_OVERFLOW);
1821			else {
1822				if (com->do_timestamp)
1823					microtime(&com->timestamp);
1824				++com_events;
1825				swi_sched(sio_slow_ih, SWI_DELAY);
1826#if 0 /* for testing input latency vs efficiency */
1827if (com->iptr - com->ibuf == 8)
1828	swi_sched(sio_fast_ih, 0);
1829#endif
1830				ioptr[0] = recv_data;
1831				ioptr[com->ierroff] = line_status;
1832				com->iptr = ++ioptr;
1833				if (ioptr == com->ihighwater
1834				    && com->state & CS_RTS_IFLOW)
1835					outb(com->modem_ctl_port,
1836					     com->mcr_image &= ~MCR_RTS);
1837				if (line_status & LSR_OE)
1838					CE_RECORD(com, CE_OVERRUN);
1839			}
1840cont:
1841			/*
1842			 * "& 0x7F" is to avoid the gcc-1.40 generating a slow
1843			 * jump from the top of the loop to here
1844			 */
1845			line_status = inb(com->line_status_port) & 0x7F;
1846		}
1847
1848		/* modem status change? (always check before doing output) */
1849		modem_status = inb(com->modem_status_port);
1850		if (modem_status != com->last_modem_status) {
1851			if (com->do_dcd_timestamp
1852			    && !(com->last_modem_status & MSR_DCD)
1853			    && modem_status & MSR_DCD)
1854				microtime(&com->dcd_timestamp);
1855
1856			/*
1857			 * Schedule high level to handle DCD changes.  Note
1858			 * that we don't use the delta bits anywhere.  Some
1859			 * UARTs mess them up, and it's easy to remember the
1860			 * previous bits and calculate the delta.
1861			 */
1862			com->last_modem_status = modem_status;
1863			if (!(com->state & CS_CHECKMSR)) {
1864				com_events += LOTS_OF_EVENTS;
1865				com->state |= CS_CHECKMSR;
1866				swi_sched(sio_fast_ih, 0);
1867			}
1868
1869			/* handle CTS change immediately for crisp flow ctl */
1870			if (com->state & CS_CTS_OFLOW) {
1871				if (modem_status & MSR_CTS)
1872					com->state |= CS_ODEVREADY;
1873				else
1874					com->state &= ~CS_ODEVREADY;
1875			}
1876		}
1877
1878		/* output queued and everything ready? */
1879		if (line_status & LSR_TXRDY
1880		    && com->state >= (CS_BUSY | CS_TTGO | CS_ODEVREADY)) {
1881			ioptr = com->obufq.l_head;
1882			if (com->tx_fifo_size > 1 && com->unit != siotsunit) {
1883				u_int	ocount;
1884
1885				ocount = com->obufq.l_tail - ioptr;
1886				if (ocount > com->tx_fifo_size)
1887					ocount = com->tx_fifo_size;
1888				com->bytes_out += ocount;
1889				do
1890					outb(com->data_port, *ioptr++);
1891				while (--ocount != 0);
1892			} else {
1893				outb(com->data_port, *ioptr++);
1894				++com->bytes_out;
1895				if (com->unit == siotsunit) {
1896					nanouptime(&siots[siotso]);
1897					siotso = (siotso + 1) %
1898					    (sizeof siots / sizeof siots[0]);
1899				}
1900			}
1901			com->obufq.l_head = ioptr;
1902			if (COM_IIR_TXRDYBUG(com->flags)) {
1903				int_ctl_new = int_ctl | IER_ETXRDY;
1904			}
1905			if (ioptr >= com->obufq.l_tail) {
1906				struct lbq	*qp;
1907
1908				qp = com->obufq.l_next;
1909				qp->l_queued = FALSE;
1910				qp = qp->l_next;
1911				if (qp != NULL) {
1912					com->obufq.l_head = qp->l_head;
1913					com->obufq.l_tail = qp->l_tail;
1914					com->obufq.l_next = qp;
1915				} else {
1916					/* output just completed */
1917					if (COM_IIR_TXRDYBUG(com->flags)) {
1918						int_ctl_new = int_ctl & ~IER_ETXRDY;
1919					}
1920					com->state &= ~CS_BUSY;
1921				}
1922				if (!(com->state & CS_ODONE)) {
1923					com_events += LOTS_OF_EVENTS;
1924					com->state |= CS_ODONE;
1925					/* handle at high level ASAP */
1926					swi_sched(sio_fast_ih, 0);
1927				}
1928			}
1929			if (COM_IIR_TXRDYBUG(com->flags) && (int_ctl != int_ctl_new)) {
1930				outb(com->intr_ctl_port, int_ctl_new);
1931			}
1932		}
1933
1934		/* finished? */
1935#ifndef COM_MULTIPORT
1936		if ((inb(com->int_id_port) & IIR_IMASK) == IIR_NOPEND)
1937#endif /* COM_MULTIPORT */
1938			return;
1939	}
1940}
1941
1942static int
1943sioioctl(dev, cmd, data, flag, td)
1944	dev_t		dev;
1945	u_long		cmd;
1946	caddr_t		data;
1947	int		flag;
1948	struct thread	*td;
1949{
1950	struct com_s	*com;
1951	int		error;
1952	int		mynor;
1953	int		s;
1954	struct tty	*tp;
1955#if defined(COMPAT_43) || defined(COMPAT_SUNOS)
1956	u_long		oldcmd;
1957	struct termios	term;
1958#endif
1959
1960	mynor = minor(dev);
1961	com = com_addr(MINOR_TO_UNIT(mynor));
1962	if (com == NULL || com->gone)
1963		return (ENODEV);
1964	if (mynor & CONTROL_MASK) {
1965		struct termios	*ct;
1966
1967		switch (mynor & CONTROL_MASK) {
1968		case CONTROL_INIT_STATE:
1969			ct = mynor & CALLOUT_MASK ? &com->it_out : &com->it_in;
1970			break;
1971		case CONTROL_LOCK_STATE:
1972			ct = mynor & CALLOUT_MASK ? &com->lt_out : &com->lt_in;
1973			break;
1974		default:
1975			return (ENODEV);	/* /dev/nodev */
1976		}
1977		switch (cmd) {
1978		case TIOCSETA:
1979			error = suser(td);
1980			if (error != 0)
1981				return (error);
1982			*ct = *(struct termios *)data;
1983			return (0);
1984		case TIOCGETA:
1985			*(struct termios *)data = *ct;
1986			return (0);
1987		case TIOCGETD:
1988			*(int *)data = TTYDISC;
1989			return (0);
1990		case TIOCGWINSZ:
1991			bzero(data, sizeof(struct winsize));
1992			return (0);
1993		default:
1994			return (ENOTTY);
1995		}
1996	}
1997	tp = com->tp;
1998#if defined(COMPAT_43) || defined(COMPAT_SUNOS)
1999	term = tp->t_termios;
2000	oldcmd = cmd;
2001	error = ttsetcompat(tp, &cmd, data, &term);
2002	if (error != 0)
2003		return (error);
2004	if (cmd != oldcmd)
2005		data = (caddr_t)&term;
2006#endif
2007	if (cmd == TIOCSETA || cmd == TIOCSETAW || cmd == TIOCSETAF) {
2008		int	cc;
2009		struct termios *dt = (struct termios *)data;
2010		struct termios *lt = mynor & CALLOUT_MASK
2011				     ? &com->lt_out : &com->lt_in;
2012
2013		dt->c_iflag = (tp->t_iflag & lt->c_iflag)
2014			      | (dt->c_iflag & ~lt->c_iflag);
2015		dt->c_oflag = (tp->t_oflag & lt->c_oflag)
2016			      | (dt->c_oflag & ~lt->c_oflag);
2017		dt->c_cflag = (tp->t_cflag & lt->c_cflag)
2018			      | (dt->c_cflag & ~lt->c_cflag);
2019		dt->c_lflag = (tp->t_lflag & lt->c_lflag)
2020			      | (dt->c_lflag & ~lt->c_lflag);
2021		for (cc = 0; cc < NCCS; ++cc)
2022			if (lt->c_cc[cc] != 0)
2023				dt->c_cc[cc] = tp->t_cc[cc];
2024		if (lt->c_ispeed != 0)
2025			dt->c_ispeed = tp->t_ispeed;
2026		if (lt->c_ospeed != 0)
2027			dt->c_ospeed = tp->t_ospeed;
2028	}
2029	error = (*linesw[tp->t_line].l_ioctl)(tp, cmd, data, flag, td);
2030	if (error != ENOIOCTL)
2031		return (error);
2032	s = spltty();
2033	error = ttioctl(tp, cmd, data, flag);
2034	disc_optim(tp, &tp->t_termios, com);
2035	if (error != ENOIOCTL) {
2036		splx(s);
2037		return (error);
2038	}
2039	switch (cmd) {
2040	case TIOCSBRK:
2041		sio_setreg(com, com_cfcr, com->cfcr_image |= CFCR_SBREAK);
2042		break;
2043	case TIOCCBRK:
2044		sio_setreg(com, com_cfcr, com->cfcr_image &= ~CFCR_SBREAK);
2045		break;
2046	case TIOCSDTR:
2047		(void)commctl(com, TIOCM_DTR, DMBIS);
2048		break;
2049	case TIOCCDTR:
2050		(void)commctl(com, TIOCM_DTR, DMBIC);
2051		break;
2052	/*
2053	 * XXX should disallow changing MCR_RTS if CS_RTS_IFLOW is set.  The
2054	 * changes get undone on the next call to comparam().
2055	 */
2056	case TIOCMSET:
2057		(void)commctl(com, *(int *)data, DMSET);
2058		break;
2059	case TIOCMBIS:
2060		(void)commctl(com, *(int *)data, DMBIS);
2061		break;
2062	case TIOCMBIC:
2063		(void)commctl(com, *(int *)data, DMBIC);
2064		break;
2065	case TIOCMGET:
2066		*(int *)data = commctl(com, 0, DMGET);
2067		break;
2068	case TIOCMSDTRWAIT:
2069		/* must be root since the wait applies to following logins */
2070		error = suser(td);
2071		if (error != 0) {
2072			splx(s);
2073			return (error);
2074		}
2075		com->dtr_wait = *(int *)data * hz / 100;
2076		break;
2077	case TIOCMGDTRWAIT:
2078		*(int *)data = com->dtr_wait * 100 / hz;
2079		break;
2080	case TIOCTIMESTAMP:
2081		com->do_timestamp = TRUE;
2082		*(struct timeval *)data = com->timestamp;
2083		break;
2084	case TIOCDCDTIMESTAMP:
2085		com->do_dcd_timestamp = TRUE;
2086		*(struct timeval *)data = com->dcd_timestamp;
2087		break;
2088	default:
2089		splx(s);
2090		error = pps_ioctl(cmd, data, &com->pps);
2091		if (error == ENODEV)
2092			error = ENOTTY;
2093		return (error);
2094	}
2095	splx(s);
2096	return (0);
2097}
2098
2099/* software interrupt handler for SWI_TTY */
2100static void
2101siopoll(void *dummy)
2102{
2103	int		unit;
2104
2105	if (com_events == 0)
2106		return;
2107repeat:
2108	for (unit = 0; unit < sio_numunits; ++unit) {
2109		struct com_s	*com;
2110		int		incc;
2111		struct tty	*tp;
2112
2113		com = com_addr(unit);
2114		if (com == NULL)
2115			continue;
2116		tp = com->tp;
2117		if (tp == NULL || com->gone) {
2118			/*
2119			 * Discard any events related to never-opened or
2120			 * going-away devices.
2121			 */
2122			mtx_lock_spin(&sio_lock);
2123			incc = com->iptr - com->ibuf;
2124			com->iptr = com->ibuf;
2125			if (com->state & CS_CHECKMSR) {
2126				incc += LOTS_OF_EVENTS;
2127				com->state &= ~CS_CHECKMSR;
2128			}
2129			com_events -= incc;
2130			mtx_unlock_spin(&sio_lock);
2131			continue;
2132		}
2133		if (com->iptr != com->ibuf) {
2134			mtx_lock_spin(&sio_lock);
2135			sioinput(com);
2136			mtx_unlock_spin(&sio_lock);
2137		}
2138		if (com->state & CS_CHECKMSR) {
2139			u_char	delta_modem_status;
2140
2141			mtx_lock_spin(&sio_lock);
2142			delta_modem_status = com->last_modem_status
2143					     ^ com->prev_modem_status;
2144			com->prev_modem_status = com->last_modem_status;
2145			com_events -= LOTS_OF_EVENTS;
2146			com->state &= ~CS_CHECKMSR;
2147			mtx_unlock_spin(&sio_lock);
2148			if (delta_modem_status & MSR_DCD)
2149				(*linesw[tp->t_line].l_modem)
2150					(tp, com->prev_modem_status & MSR_DCD);
2151		}
2152		if (com->state & CS_ODONE) {
2153			mtx_lock_spin(&sio_lock);
2154			com_events -= LOTS_OF_EVENTS;
2155			com->state &= ~CS_ODONE;
2156			mtx_unlock_spin(&sio_lock);
2157			if (!(com->state & CS_BUSY)
2158			    && !(com->extra_state & CSE_BUSYCHECK)) {
2159				timeout(siobusycheck, com, hz / 100);
2160				com->extra_state |= CSE_BUSYCHECK;
2161			}
2162			(*linesw[tp->t_line].l_start)(tp);
2163		}
2164		if (com_events == 0)
2165			break;
2166	}
2167	if (com_events >= LOTS_OF_EVENTS)
2168		goto repeat;
2169}
2170
2171static int
2172comparam(tp, t)
2173	struct tty	*tp;
2174	struct termios	*t;
2175{
2176	u_int		cfcr;
2177	int		cflag;
2178	struct com_s	*com;
2179	u_int		divisor;
2180	u_char		dlbh;
2181	u_char		dlbl;
2182	int		s;
2183	int		unit;
2184
2185	unit = DEV_TO_UNIT(tp->t_dev);
2186	com = com_addr(unit);
2187	if (com == NULL)
2188		return (ENODEV);
2189
2190	/* do historical conversions */
2191	if (t->c_ispeed == 0)
2192		t->c_ispeed = t->c_ospeed;
2193
2194	/* check requested parameters */
2195	if (t->c_ospeed == 0)
2196		divisor = 0;
2197	else {
2198		if (t->c_ispeed != t->c_ospeed)
2199			return (EINVAL);
2200		divisor = siodivisor(com->rclk, t->c_ispeed);
2201		if (divisor == 0)
2202			return (EINVAL);
2203	}
2204
2205	/* parameters are OK, convert them to the com struct and the device */
2206	s = spltty();
2207	if (divisor == 0)
2208		(void)commctl(com, TIOCM_DTR, DMBIC);	/* hang up line */
2209	else
2210		(void)commctl(com, TIOCM_DTR, DMBIS);
2211	cflag = t->c_cflag;
2212	switch (cflag & CSIZE) {
2213	case CS5:
2214		cfcr = CFCR_5BITS;
2215		break;
2216	case CS6:
2217		cfcr = CFCR_6BITS;
2218		break;
2219	case CS7:
2220		cfcr = CFCR_7BITS;
2221		break;
2222	default:
2223		cfcr = CFCR_8BITS;
2224		break;
2225	}
2226	if (cflag & PARENB) {
2227		cfcr |= CFCR_PENAB;
2228		if (!(cflag & PARODD))
2229			cfcr |= CFCR_PEVEN;
2230	}
2231	if (cflag & CSTOPB)
2232		cfcr |= CFCR_STOPB;
2233
2234	if (com->hasfifo && divisor != 0) {
2235		/*
2236		 * Use a fifo trigger level low enough so that the input
2237		 * latency from the fifo is less than about 16 msec and
2238		 * the total latency is less than about 30 msec.  These
2239		 * latencies are reasonable for humans.  Serial comms
2240		 * protocols shouldn't expect anything better since modem
2241		 * latencies are larger.
2242		 *
2243		 * The fifo trigger level cannot be set at RX_HIGH for high
2244		 * speed connections without further work on reducing
2245		 * interrupt disablement times in other parts of the system,
2246		 * without producing silo overflow errors.
2247		 */
2248		com->fifo_image = com->unit == siotsunit ? 0
2249				  : t->c_ospeed <= 4800
2250				  ? FIFO_ENABLE : FIFO_ENABLE | FIFO_RX_MEDH;
2251#ifdef COM_ESP
2252		/*
2253		 * The Hayes ESP card needs the fifo DMA mode bit set
2254		 * in compatibility mode.  If not, it will interrupt
2255		 * for each character received.
2256		 */
2257		if (com->esp)
2258			com->fifo_image |= FIFO_DMA_MODE;
2259#endif
2260		sio_setreg(com, com_fifo, com->fifo_image);
2261	}
2262
2263	/*
2264	 * This returns with interrupts disabled so that we can complete
2265	 * the speed change atomically.  Keeping interrupts disabled is
2266	 * especially important while com_data is hidden.
2267	 */
2268	(void) siosetwater(com, t->c_ispeed);
2269
2270	if (divisor != 0) {
2271		sio_setreg(com, com_cfcr, cfcr | CFCR_DLAB);
2272		/*
2273		 * Only set the divisor registers if they would change,
2274		 * since on some 16550 incompatibles (UMC8669F), setting
2275		 * them while input is arriving them loses sync until
2276		 * data stops arriving.
2277		 */
2278		dlbl = divisor & 0xFF;
2279		if (sio_getreg(com, com_dlbl) != dlbl)
2280			sio_setreg(com, com_dlbl, dlbl);
2281		dlbh = divisor >> 8;
2282		if (sio_getreg(com, com_dlbh) != dlbh)
2283			sio_setreg(com, com_dlbh, dlbh);
2284	}
2285
2286	sio_setreg(com, com_cfcr, com->cfcr_image = cfcr);
2287
2288	if (!(tp->t_state & TS_TTSTOP))
2289		com->state |= CS_TTGO;
2290
2291	if (cflag & CRTS_IFLOW) {
2292		if (com->st16650a) {
2293			sio_setreg(com, com_cfcr, 0xbf);
2294			sio_setreg(com, com_fifo,
2295				   sio_getreg(com, com_fifo) | 0x40);
2296		}
2297		com->state |= CS_RTS_IFLOW;
2298		/*
2299		 * If CS_RTS_IFLOW just changed from off to on, the change
2300		 * needs to be propagated to MCR_RTS.  This isn't urgent,
2301		 * so do it later by calling comstart() instead of repeating
2302		 * a lot of code from comstart() here.
2303		 */
2304	} else if (com->state & CS_RTS_IFLOW) {
2305		com->state &= ~CS_RTS_IFLOW;
2306		/*
2307		 * CS_RTS_IFLOW just changed from on to off.  Force MCR_RTS
2308		 * on here, since comstart() won't do it later.
2309		 */
2310		outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
2311		if (com->st16650a) {
2312			sio_setreg(com, com_cfcr, 0xbf);
2313			sio_setreg(com, com_fifo,
2314				   sio_getreg(com, com_fifo) & ~0x40);
2315		}
2316	}
2317
2318
2319	/*
2320	 * Set up state to handle output flow control.
2321	 * XXX - worth handling MDMBUF (DCD) flow control at the lowest level?
2322	 * Now has 10+ msec latency, while CTS flow has 50- usec latency.
2323	 */
2324	com->state |= CS_ODEVREADY;
2325	com->state &= ~CS_CTS_OFLOW;
2326	if (cflag & CCTS_OFLOW) {
2327		com->state |= CS_CTS_OFLOW;
2328		if (!(com->last_modem_status & MSR_CTS))
2329			com->state &= ~CS_ODEVREADY;
2330		if (com->st16650a) {
2331			sio_setreg(com, com_cfcr, 0xbf);
2332			sio_setreg(com, com_fifo,
2333				   sio_getreg(com, com_fifo) | 0x80);
2334		}
2335	} else {
2336		if (com->st16650a) {
2337			sio_setreg(com, com_cfcr, 0xbf);
2338			sio_setreg(com, com_fifo,
2339				   sio_getreg(com, com_fifo) & ~0x80);
2340		}
2341	}
2342
2343	sio_setreg(com, com_cfcr, com->cfcr_image);
2344
2345	/* XXX shouldn't call functions while intrs are disabled. */
2346	disc_optim(tp, t, com);
2347	/*
2348	 * Recover from fiddling with CS_TTGO.  We used to call siointr1()
2349	 * unconditionally, but that defeated the careful discarding of
2350	 * stale input in sioopen().
2351	 */
2352	if (com->state >= (CS_BUSY | CS_TTGO))
2353		siointr1(com);
2354
2355	mtx_unlock_spin(&sio_lock);
2356	splx(s);
2357	comstart(tp);
2358	if (com->ibufold != NULL) {
2359		free(com->ibufold, M_DEVBUF);
2360		com->ibufold = NULL;
2361	}
2362	return (0);
2363}
2364
2365/*
2366 * This function must be called with the sio_lock mutex released and will
2367 * return with it obtained.
2368 */
2369static int
2370siosetwater(com, speed)
2371	struct com_s	*com;
2372	speed_t		speed;
2373{
2374	int		cp4ticks;
2375	u_char		*ibuf;
2376	int		ibufsize;
2377	struct tty	*tp;
2378
2379	/*
2380	 * Make the buffer size large enough to handle a softtty interrupt
2381	 * latency of about 2 ticks without loss of throughput or data
2382	 * (about 3 ticks if input flow control is not used or not honoured,
2383	 * but a bit less for CS5-CS7 modes).
2384	 */
2385	cp4ticks = speed / 10 / hz * 4;
2386	for (ibufsize = 128; ibufsize < cp4ticks;)
2387		ibufsize <<= 1;
2388	if (ibufsize == com->ibufsize) {
2389		mtx_lock_spin(&sio_lock);
2390		return (0);
2391	}
2392
2393	/*
2394	 * Allocate input buffer.  The extra factor of 2 in the size is
2395	 * to allow for an error byte for each input byte.
2396	 */
2397	ibuf = malloc(2 * ibufsize, M_DEVBUF, M_NOWAIT);
2398	if (ibuf == NULL) {
2399		mtx_lock_spin(&sio_lock);
2400		return (ENOMEM);
2401	}
2402
2403	/* Initialize non-critical variables. */
2404	com->ibufold = com->ibuf;
2405	com->ibufsize = ibufsize;
2406	tp = com->tp;
2407	if (tp != NULL) {
2408		tp->t_ififosize = 2 * ibufsize;
2409		tp->t_ispeedwat = (speed_t)-1;
2410		tp->t_ospeedwat = (speed_t)-1;
2411	}
2412
2413	/*
2414	 * Read current input buffer, if any.  Continue with interrupts
2415	 * disabled.
2416	 */
2417	mtx_lock_spin(&sio_lock);
2418	if (com->iptr != com->ibuf)
2419		sioinput(com);
2420
2421	/*-
2422	 * Initialize critical variables, including input buffer watermarks.
2423	 * The external device is asked to stop sending when the buffer
2424	 * exactly reaches high water, or when the high level requests it.
2425	 * The high level is notified immediately (rather than at a later
2426	 * clock tick) when this watermark is reached.
2427	 * The buffer size is chosen so the watermark should almost never
2428	 * be reached.
2429	 * The low watermark is invisibly 0 since the buffer is always
2430	 * emptied all at once.
2431	 */
2432	com->iptr = com->ibuf = ibuf;
2433	com->ibufend = ibuf + ibufsize;
2434	com->ierroff = ibufsize;
2435	com->ihighwater = ibuf + 3 * ibufsize / 4;
2436	return (0);
2437}
2438
2439static void
2440comstart(tp)
2441	struct tty	*tp;
2442{
2443	struct com_s	*com;
2444	int		s;
2445	int		unit;
2446
2447	unit = DEV_TO_UNIT(tp->t_dev);
2448	com = com_addr(unit);
2449	if (com == NULL)
2450		return;
2451	s = spltty();
2452	mtx_lock_spin(&sio_lock);
2453	if (tp->t_state & TS_TTSTOP)
2454		com->state &= ~CS_TTGO;
2455	else
2456		com->state |= CS_TTGO;
2457	if (tp->t_state & TS_TBLOCK) {
2458		if (com->mcr_image & MCR_RTS && com->state & CS_RTS_IFLOW)
2459			outb(com->modem_ctl_port, com->mcr_image &= ~MCR_RTS);
2460	} else {
2461		if (!(com->mcr_image & MCR_RTS) && com->iptr < com->ihighwater
2462		    && com->state & CS_RTS_IFLOW)
2463			outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
2464	}
2465	mtx_unlock_spin(&sio_lock);
2466	if (tp->t_state & (TS_TIMEOUT | TS_TTSTOP)) {
2467		ttwwakeup(tp);
2468		splx(s);
2469		return;
2470	}
2471	if (tp->t_outq.c_cc != 0) {
2472		struct lbq	*qp;
2473		struct lbq	*next;
2474
2475		if (!com->obufs[0].l_queued) {
2476			com->obufs[0].l_tail
2477			    = com->obuf1 + q_to_b(&tp->t_outq, com->obuf1,
2478						  sizeof com->obuf1);
2479			com->obufs[0].l_next = NULL;
2480			com->obufs[0].l_queued = TRUE;
2481			mtx_lock_spin(&sio_lock);
2482			if (com->state & CS_BUSY) {
2483				qp = com->obufq.l_next;
2484				while ((next = qp->l_next) != NULL)
2485					qp = next;
2486				qp->l_next = &com->obufs[0];
2487			} else {
2488				com->obufq.l_head = com->obufs[0].l_head;
2489				com->obufq.l_tail = com->obufs[0].l_tail;
2490				com->obufq.l_next = &com->obufs[0];
2491				com->state |= CS_BUSY;
2492			}
2493			mtx_unlock_spin(&sio_lock);
2494		}
2495		if (tp->t_outq.c_cc != 0 && !com->obufs[1].l_queued) {
2496			com->obufs[1].l_tail
2497			    = com->obuf2 + q_to_b(&tp->t_outq, com->obuf2,
2498						  sizeof com->obuf2);
2499			com->obufs[1].l_next = NULL;
2500			com->obufs[1].l_queued = TRUE;
2501			mtx_lock_spin(&sio_lock);
2502			if (com->state & CS_BUSY) {
2503				qp = com->obufq.l_next;
2504				while ((next = qp->l_next) != NULL)
2505					qp = next;
2506				qp->l_next = &com->obufs[1];
2507			} else {
2508				com->obufq.l_head = com->obufs[1].l_head;
2509				com->obufq.l_tail = com->obufs[1].l_tail;
2510				com->obufq.l_next = &com->obufs[1];
2511				com->state |= CS_BUSY;
2512			}
2513			mtx_unlock_spin(&sio_lock);
2514		}
2515		tp->t_state |= TS_BUSY;
2516	}
2517	mtx_lock_spin(&sio_lock);
2518	if (com->state >= (CS_BUSY | CS_TTGO))
2519		siointr1(com);	/* fake interrupt to start output */
2520	mtx_unlock_spin(&sio_lock);
2521	ttwwakeup(tp);
2522	splx(s);
2523}
2524
2525static void
2526comstop(tp, rw)
2527	struct tty	*tp;
2528	int		rw;
2529{
2530	struct com_s	*com;
2531
2532	com = com_addr(DEV_TO_UNIT(tp->t_dev));
2533	if (com == NULL || com->gone)
2534		return;
2535	mtx_lock_spin(&sio_lock);
2536	if (rw & FWRITE) {
2537		if (com->hasfifo)
2538#ifdef COM_ESP
2539		    /* XXX avoid h/w bug. */
2540		    if (!com->esp)
2541#endif
2542			sio_setreg(com, com_fifo,
2543				   FIFO_XMT_RST | com->fifo_image);
2544		com->obufs[0].l_queued = FALSE;
2545		com->obufs[1].l_queued = FALSE;
2546		if (com->state & CS_ODONE)
2547			com_events -= LOTS_OF_EVENTS;
2548		com->state &= ~(CS_ODONE | CS_BUSY);
2549		com->tp->t_state &= ~TS_BUSY;
2550	}
2551	if (rw & FREAD) {
2552		if (com->hasfifo)
2553#ifdef COM_ESP
2554		    /* XXX avoid h/w bug. */
2555		    if (!com->esp)
2556#endif
2557			sio_setreg(com, com_fifo,
2558				   FIFO_RCV_RST | com->fifo_image);
2559		com_events -= (com->iptr - com->ibuf);
2560		com->iptr = com->ibuf;
2561	}
2562	mtx_unlock_spin(&sio_lock);
2563	comstart(tp);
2564}
2565
2566static int
2567commctl(com, bits, how)
2568	struct com_s	*com;
2569	int		bits;
2570	int		how;
2571{
2572	int	mcr;
2573	int	msr;
2574
2575	if (how == DMGET) {
2576		bits = TIOCM_LE;	/* XXX - always enabled while open */
2577		mcr = com->mcr_image;
2578		if (mcr & MCR_DTR)
2579			bits |= TIOCM_DTR;
2580		if (mcr & MCR_RTS)
2581			bits |= TIOCM_RTS;
2582		msr = com->prev_modem_status;
2583		if (msr & MSR_CTS)
2584			bits |= TIOCM_CTS;
2585		if (msr & MSR_DCD)
2586			bits |= TIOCM_CD;
2587		if (msr & MSR_DSR)
2588			bits |= TIOCM_DSR;
2589		/*
2590		 * XXX - MSR_RI is naturally volatile, and we make MSR_TERI
2591		 * more volatile by reading the modem status a lot.  Perhaps
2592		 * we should latch both bits until the status is read here.
2593		 */
2594		if (msr & (MSR_RI | MSR_TERI))
2595			bits |= TIOCM_RI;
2596		return (bits);
2597	}
2598	mcr = 0;
2599	if (bits & TIOCM_DTR)
2600		mcr |= MCR_DTR;
2601	if (bits & TIOCM_RTS)
2602		mcr |= MCR_RTS;
2603	if (com->gone)
2604		return(0);
2605	mtx_lock_spin(&sio_lock);
2606	switch (how) {
2607	case DMSET:
2608		outb(com->modem_ctl_port,
2609		     com->mcr_image = mcr | (com->mcr_image & MCR_IENABLE));
2610		break;
2611	case DMBIS:
2612		outb(com->modem_ctl_port, com->mcr_image |= mcr);
2613		break;
2614	case DMBIC:
2615		outb(com->modem_ctl_port, com->mcr_image &= ~mcr);
2616		break;
2617	}
2618	mtx_unlock_spin(&sio_lock);
2619	return (0);
2620}
2621
2622static void
2623siosettimeout()
2624{
2625	struct com_s	*com;
2626	bool_t		someopen;
2627	int		unit;
2628
2629	/*
2630	 * Set our timeout period to 1 second if no polled devices are open.
2631	 * Otherwise set it to max(1/200, 1/hz).
2632	 * Enable timeouts iff some device is open.
2633	 */
2634	untimeout(comwakeup, (void *)NULL, sio_timeout_handle);
2635	sio_timeout = hz;
2636	someopen = FALSE;
2637	for (unit = 0; unit < sio_numunits; ++unit) {
2638		com = com_addr(unit);
2639		if (com != NULL && com->tp != NULL
2640		    && com->tp->t_state & TS_ISOPEN && !com->gone) {
2641			someopen = TRUE;
2642			if (com->poll || com->poll_output) {
2643				sio_timeout = hz > 200 ? hz / 200 : 1;
2644				break;
2645			}
2646		}
2647	}
2648	if (someopen) {
2649		sio_timeouts_until_log = hz / sio_timeout;
2650		sio_timeout_handle = timeout(comwakeup, (void *)NULL,
2651					     sio_timeout);
2652	} else {
2653		/* Flush error messages, if any. */
2654		sio_timeouts_until_log = 1;
2655		comwakeup((void *)NULL);
2656		untimeout(comwakeup, (void *)NULL, sio_timeout_handle);
2657	}
2658}
2659
2660static void
2661comwakeup(chan)
2662	void	*chan;
2663{
2664	struct com_s	*com;
2665	int		unit;
2666
2667	sio_timeout_handle = timeout(comwakeup, (void *)NULL, sio_timeout);
2668
2669	/*
2670	 * Recover from lost output interrupts.
2671	 * Poll any lines that don't use interrupts.
2672	 */
2673	for (unit = 0; unit < sio_numunits; ++unit) {
2674		com = com_addr(unit);
2675		if (com != NULL && !com->gone
2676		    && (com->state >= (CS_BUSY | CS_TTGO) || com->poll)) {
2677			mtx_lock_spin(&sio_lock);
2678			siointr1(com);
2679			mtx_unlock_spin(&sio_lock);
2680		}
2681	}
2682
2683	/*
2684	 * Check for and log errors, but not too often.
2685	 */
2686	if (--sio_timeouts_until_log > 0)
2687		return;
2688	sio_timeouts_until_log = hz / sio_timeout;
2689	for (unit = 0; unit < sio_numunits; ++unit) {
2690		int	errnum;
2691
2692		com = com_addr(unit);
2693		if (com == NULL)
2694			continue;
2695		if (com->gone)
2696			continue;
2697		for (errnum = 0; errnum < CE_NTYPES; ++errnum) {
2698			u_int	delta;
2699			u_long	total;
2700
2701			mtx_lock_spin(&sio_lock);
2702			delta = com->delta_error_counts[errnum];
2703			com->delta_error_counts[errnum] = 0;
2704			mtx_unlock_spin(&sio_lock);
2705			if (delta == 0)
2706				continue;
2707			total = com->error_counts[errnum] += delta;
2708			log(LOG_ERR, "sio%d: %u more %s%s (total %lu)\n",
2709			    unit, delta, error_desc[errnum],
2710			    delta == 1 ? "" : "s", total);
2711		}
2712	}
2713}
2714
2715static void
2716disc_optim(tp, t, com)
2717	struct tty	*tp;
2718	struct termios	*t;
2719	struct com_s	*com;
2720{
2721	if (!(t->c_iflag & (ICRNL | IGNCR | IMAXBEL | INLCR | ISTRIP | IXON))
2722	    && (!(t->c_iflag & BRKINT) || (t->c_iflag & IGNBRK))
2723	    && (!(t->c_iflag & PARMRK)
2724		|| (t->c_iflag & (IGNPAR | IGNBRK)) == (IGNPAR | IGNBRK))
2725	    && !(t->c_lflag & (ECHO | ICANON | IEXTEN | ISIG | PENDIN))
2726	    && linesw[tp->t_line].l_rint == ttyinput)
2727		tp->t_state |= TS_CAN_BYPASS_L_RINT;
2728	else
2729		tp->t_state &= ~TS_CAN_BYPASS_L_RINT;
2730	com->hotchar = linesw[tp->t_line].l_hotchar;
2731}
2732
2733/*
2734 * Following are all routines needed for SIO to act as console
2735 */
2736#include <sys/cons.h>
2737
2738struct siocnstate {
2739	u_char	dlbl;
2740	u_char	dlbh;
2741	u_char	ier;
2742	u_char	cfcr;
2743	u_char	mcr;
2744};
2745
2746#ifndef __alpha__
2747static speed_t siocngetspeed(Port_t, u_long rclk);
2748#endif
2749static void siocnclose(struct siocnstate *sp, Port_t iobase);
2750static void siocnopen(struct siocnstate *sp, Port_t iobase, int speed);
2751static void siocntxwait(Port_t iobase);
2752
2753#ifdef __alpha__
2754int siocnattach(int port, int speed);
2755int siogdbattach(int port, int speed);
2756int siogdbgetc(void);
2757void siogdbputc(int c);
2758#else
2759static cn_probe_t siocnprobe;
2760static cn_init_t siocninit;
2761static cn_term_t siocnterm;
2762#endif
2763static cn_checkc_t siocncheckc;
2764static cn_getc_t siocngetc;
2765static cn_putc_t siocnputc;
2766
2767#ifndef __alpha__
2768CONS_DRIVER(sio, siocnprobe, siocninit, siocnterm, siocngetc, siocncheckc,
2769	    siocnputc, NULL);
2770#endif
2771
2772/* To get the GDB related variables */
2773#if DDB > 0
2774#include <ddb/ddb.h>
2775#endif
2776
2777static void
2778siocntxwait(iobase)
2779	Port_t	iobase;
2780{
2781	int	timo;
2782
2783	/*
2784	 * Wait for any pending transmission to finish.  Required to avoid
2785	 * the UART lockup bug when the speed is changed, and for normal
2786	 * transmits.
2787	 */
2788	timo = 100000;
2789	while ((inb(iobase + com_lsr) & (LSR_TSRE | LSR_TXRDY))
2790	       != (LSR_TSRE | LSR_TXRDY) && --timo != 0)
2791		;
2792}
2793
2794#ifndef __alpha__
2795
2796/*
2797 * Read the serial port specified and try to figure out what speed
2798 * it's currently running at.  We're assuming the serial port has
2799 * been initialized and is basicly idle.  This routine is only intended
2800 * to be run at system startup.
2801 *
2802 * If the value read from the serial port doesn't make sense, return 0.
2803 */
2804
2805static speed_t
2806siocngetspeed(iobase, rclk)
2807	Port_t	iobase;
2808	u_long	rclk;
2809{
2810	u_int	divisor;
2811	u_char	dlbh;
2812	u_char	dlbl;
2813	u_char  cfcr;
2814
2815	cfcr = inb(iobase + com_cfcr);
2816	outb(iobase + com_cfcr, CFCR_DLAB | cfcr);
2817
2818	dlbl = inb(iobase + com_dlbl);
2819	dlbh = inb(iobase + com_dlbh);
2820
2821	outb(iobase + com_cfcr, cfcr);
2822
2823	divisor = dlbh << 8 | dlbl;
2824
2825	/* XXX there should be more sanity checking. */
2826	if (divisor == 0)
2827		return (CONSPEED);
2828	return (rclk / (16UL * divisor));
2829}
2830
2831#endif
2832
2833static void
2834siocnopen(sp, iobase, speed)
2835	struct siocnstate	*sp;
2836	Port_t			iobase;
2837	int			speed;
2838{
2839	u_int	divisor;
2840	u_char	dlbh;
2841	u_char	dlbl;
2842
2843	/*
2844	 * Save all the device control registers except the fifo register
2845	 * and set our default ones (cs8 -parenb speed=comdefaultrate).
2846	 * We can't save the fifo register since it is read-only.
2847	 */
2848	sp->ier = inb(iobase + com_ier);
2849	outb(iobase + com_ier, 0);	/* spltty() doesn't stop siointr() */
2850	siocntxwait(iobase);
2851	sp->cfcr = inb(iobase + com_cfcr);
2852	outb(iobase + com_cfcr, CFCR_DLAB | CFCR_8BITS);
2853	sp->dlbl = inb(iobase + com_dlbl);
2854	sp->dlbh = inb(iobase + com_dlbh);
2855	/*
2856	 * Only set the divisor registers if they would change, since on
2857	 * some 16550 incompatibles (Startech), setting them clears the
2858	 * data input register.  This also reduces the effects of the
2859	 * UMC8669F bug.
2860	 */
2861	divisor = siodivisor(comdefaultrclk, speed);
2862	dlbl = divisor & 0xFF;
2863	if (sp->dlbl != dlbl)
2864		outb(iobase + com_dlbl, dlbl);
2865	dlbh = divisor >> 8;
2866	if (sp->dlbh != dlbh)
2867		outb(iobase + com_dlbh, dlbh);
2868	outb(iobase + com_cfcr, CFCR_8BITS);
2869	sp->mcr = inb(iobase + com_mcr);
2870	/*
2871	 * We don't want interrupts, but must be careful not to "disable"
2872	 * them by clearing the MCR_IENABLE bit, since that might cause
2873	 * an interrupt by floating the IRQ line.
2874	 */
2875	outb(iobase + com_mcr, (sp->mcr & MCR_IENABLE) | MCR_DTR | MCR_RTS);
2876}
2877
2878static void
2879siocnclose(sp, iobase)
2880	struct siocnstate	*sp;
2881	Port_t			iobase;
2882{
2883	/*
2884	 * Restore the device control registers.
2885	 */
2886	siocntxwait(iobase);
2887	outb(iobase + com_cfcr, CFCR_DLAB | CFCR_8BITS);
2888	if (sp->dlbl != inb(iobase + com_dlbl))
2889		outb(iobase + com_dlbl, sp->dlbl);
2890	if (sp->dlbh != inb(iobase + com_dlbh))
2891		outb(iobase + com_dlbh, sp->dlbh);
2892	outb(iobase + com_cfcr, sp->cfcr);
2893	/*
2894	 * XXX damp oscillations of MCR_DTR and MCR_RTS by not restoring them.
2895	 */
2896	outb(iobase + com_mcr, sp->mcr | MCR_DTR | MCR_RTS);
2897	outb(iobase + com_ier, sp->ier);
2898}
2899
2900#ifndef __alpha__
2901
2902static void
2903siocnprobe(cp)
2904	struct consdev	*cp;
2905{
2906	speed_t			boot_speed;
2907	u_char			cfcr;
2908	u_int			divisor;
2909	int			s, unit;
2910	struct siocnstate	sp;
2911
2912	/*
2913	 * Find our first enabled console, if any.  If it is a high-level
2914	 * console device, then initialize it and return successfully.
2915	 * If it is a low-level console device, then initialize it and
2916	 * return unsuccessfully.  It must be initialized in both cases
2917	 * for early use by console drivers and debuggers.  Initializing
2918	 * the hardware is not necessary in all cases, since the i/o
2919	 * routines initialize it on the fly, but it is necessary if
2920	 * input might arrive while the hardware is switched back to an
2921	 * uninitialized state.  We can't handle multiple console devices
2922	 * yet because our low-level routines don't take a device arg.
2923	 * We trust the user to set the console flags properly so that we
2924	 * don't need to probe.
2925	 */
2926	cp->cn_pri = CN_DEAD;
2927
2928	for (unit = 0; unit < 16; unit++) { /* XXX need to know how many */
2929		int flags;
2930		int disabled;
2931		if (resource_int_value("sio", unit, "disabled", &disabled) == 0) {
2932			if (disabled)
2933				continue;
2934		}
2935		if (resource_int_value("sio", unit, "flags", &flags))
2936			continue;
2937		if (COM_CONSOLE(flags) || COM_DEBUGGER(flags)) {
2938			int port;
2939			Port_t iobase;
2940
2941			if (resource_int_value("sio", unit, "port", &port))
2942				continue;
2943			iobase = port;
2944			s = spltty();
2945			if (boothowto & RB_SERIAL) {
2946				boot_speed =
2947				    siocngetspeed(iobase, comdefaultrclk);
2948				if (boot_speed)
2949					comdefaultrate = boot_speed;
2950			}
2951
2952			/*
2953			 * Initialize the divisor latch.  We can't rely on
2954			 * siocnopen() to do this the first time, since it
2955			 * avoids writing to the latch if the latch appears
2956			 * to have the correct value.  Also, if we didn't
2957			 * just read the speed from the hardware, then we
2958			 * need to set the speed in hardware so that
2959			 * switching it later is null.
2960			 */
2961			cfcr = inb(iobase + com_cfcr);
2962			outb(iobase + com_cfcr, CFCR_DLAB | cfcr);
2963			divisor = siodivisor(comdefaultrclk, comdefaultrate);
2964			outb(iobase + com_dlbl, divisor & 0xff);
2965			outb(iobase + com_dlbh, divisor >> 8);
2966			outb(iobase + com_cfcr, cfcr);
2967
2968			siocnopen(&sp, iobase, comdefaultrate);
2969
2970			splx(s);
2971			if (COM_CONSOLE(flags) && !COM_LLCONSOLE(flags)) {
2972				cp->cn_dev = makedev(CDEV_MAJOR, unit);
2973				cp->cn_pri = COM_FORCECONSOLE(flags)
2974					     || boothowto & RB_SERIAL
2975					     ? CN_REMOTE : CN_NORMAL;
2976				siocniobase = iobase;
2977				siocnunit = unit;
2978			}
2979			if (COM_DEBUGGER(flags)) {
2980				printf("sio%d: gdb debugging port\n", unit);
2981				siogdbiobase = iobase;
2982				siogdbunit = unit;
2983#if DDB > 0
2984				gdbdev = makedev(CDEV_MAJOR, unit);
2985				gdb_getc = siocngetc;
2986				gdb_putc = siocnputc;
2987#endif
2988			}
2989		}
2990	}
2991#ifdef	__i386__
2992#if DDB > 0
2993	/*
2994	 * XXX Ugly Compatability.
2995	 * If no gdb port has been specified, set it to be the console
2996	 * as some configuration files don't specify the gdb port.
2997	 */
2998	if (gdbdev == NODEV && (boothowto & RB_GDB)) {
2999		printf("Warning: no GDB port specified. Defaulting to sio%d.\n",
3000			siocnunit);
3001		printf("Set flag 0x80 on desired GDB port in your\n");
3002		printf("configuration file (currently sio only).\n");
3003		siogdbiobase = siocniobase;
3004		siogdbunit = siocnunit;
3005		gdbdev = makedev(CDEV_MAJOR, siocnunit);
3006		gdb_getc = siocngetc;
3007		gdb_putc = siocnputc;
3008	}
3009#endif
3010#endif
3011}
3012
3013static void
3014siocninit(cp)
3015	struct consdev	*cp;
3016{
3017	comconsole = DEV_TO_UNIT(cp->cn_dev);
3018}
3019
3020static void
3021siocnterm(cp)
3022	struct consdev	*cp;
3023{
3024	comconsole = -1;
3025}
3026
3027#endif
3028
3029#ifdef __alpha__
3030
3031CONS_DRIVER(sio, NULL, NULL, NULL, siocngetc, siocncheckc, siocnputc, NULL);
3032
3033int
3034siocnattach(port, speed)
3035	int port;
3036	int speed;
3037{
3038	int			s;
3039	u_char			cfcr;
3040	u_int			divisor;
3041	struct siocnstate	sp;
3042
3043	siocniobase = port;
3044	comdefaultrate = speed;
3045	sio_consdev.cn_pri = CN_NORMAL;
3046	sio_consdev.cn_dev = makedev(CDEV_MAJOR, 0);
3047
3048	s = spltty();
3049
3050	/*
3051	 * Initialize the divisor latch.  We can't rely on
3052	 * siocnopen() to do this the first time, since it
3053	 * avoids writing to the latch if the latch appears
3054	 * to have the correct value.  Also, if we didn't
3055	 * just read the speed from the hardware, then we
3056	 * need to set the speed in hardware so that
3057	 * switching it later is null.
3058	 */
3059	cfcr = inb(siocniobase + com_cfcr);
3060	outb(siocniobase + com_cfcr, CFCR_DLAB | cfcr);
3061	divisor = siodivisor(comdefaultrclk, comdefaultrate);
3062	outb(siocniobase + com_dlbl, divisor & 0xff);
3063	outb(siocniobase + com_dlbh, divisor >> 8);
3064	outb(siocniobase + com_cfcr, cfcr);
3065
3066	siocnopen(&sp, siocniobase, comdefaultrate);
3067	splx(s);
3068
3069	cnadd(&sio_consdev);
3070	return (0);
3071}
3072
3073int
3074siogdbattach(port, speed)
3075	int port;
3076	int speed;
3077{
3078	int			s;
3079	u_char			cfcr;
3080	u_int			divisor;
3081	struct siocnstate	sp;
3082	int			unit = 1;	/* XXX !!! */
3083
3084	siogdbiobase = port;
3085	gdbdefaultrate = speed;
3086
3087	printf("sio%d: gdb debugging port\n", unit);
3088	siogdbunit = unit;
3089#if DDB > 0
3090	gdbdev = makedev(CDEV_MAJOR, unit);
3091	gdb_getc = siocngetc;
3092	gdb_putc = siocnputc;
3093#endif
3094
3095	s = spltty();
3096
3097	/*
3098	 * Initialize the divisor latch.  We can't rely on
3099	 * siocnopen() to do this the first time, since it
3100	 * avoids writing to the latch if the latch appears
3101	 * to have the correct value.  Also, if we didn't
3102	 * just read the speed from the hardware, then we
3103	 * need to set the speed in hardware so that
3104	 * switching it later is null.
3105	 */
3106	cfcr = inb(siogdbiobase + com_cfcr);
3107	outb(siogdbiobase + com_cfcr, CFCR_DLAB | cfcr);
3108	divisor = siodivisor(comdefaultrclk, gdbdefaultrate);
3109	outb(siogdbiobase + com_dlbl, divisor & 0xff);
3110	outb(siogdbiobase + com_dlbh, divisor >> 8);
3111	outb(siogdbiobase + com_cfcr, cfcr);
3112
3113	siocnopen(&sp, siogdbiobase, gdbdefaultrate);
3114	splx(s);
3115
3116	return (0);
3117}
3118
3119#endif
3120
3121static int
3122siocncheckc(dev)
3123	dev_t	dev;
3124{
3125	int	c;
3126	Port_t	iobase;
3127	int	s;
3128	struct siocnstate	sp;
3129
3130	if (minor(dev) == siogdbunit)
3131		iobase = siogdbiobase;
3132	else
3133		iobase = siocniobase;
3134	s = spltty();
3135	siocnopen(&sp, iobase, comdefaultrate);
3136	if (inb(iobase + com_lsr) & LSR_RXRDY)
3137		c = inb(iobase + com_data);
3138	else
3139		c = -1;
3140	siocnclose(&sp, iobase);
3141	splx(s);
3142	return (c);
3143}
3144
3145
3146int
3147siocngetc(dev)
3148	dev_t	dev;
3149{
3150	int	c;
3151	Port_t	iobase;
3152	int	s;
3153	struct siocnstate	sp;
3154
3155	if (minor(dev) == siogdbunit)
3156		iobase = siogdbiobase;
3157	else
3158		iobase = siocniobase;
3159	s = spltty();
3160	siocnopen(&sp, iobase, comdefaultrate);
3161	while (!(inb(iobase + com_lsr) & LSR_RXRDY))
3162		;
3163	c = inb(iobase + com_data);
3164	siocnclose(&sp, iobase);
3165	splx(s);
3166	return (c);
3167}
3168
3169void
3170siocnputc(dev, c)
3171	dev_t	dev;
3172	int	c;
3173{
3174	int	need_unlock;
3175	int	s;
3176	struct siocnstate	sp;
3177	Port_t	iobase;
3178
3179	if (minor(dev) == siogdbunit)
3180		iobase = siogdbiobase;
3181	else
3182		iobase = siocniobase;
3183	s = spltty();
3184	need_unlock = 0;
3185	if (sio_inited == 2 && !mtx_owned(&sio_lock)) {
3186		mtx_lock_spin(&sio_lock);
3187		need_unlock = 1;
3188	}
3189	siocnopen(&sp, iobase, comdefaultrate);
3190	siocntxwait(iobase);
3191	outb(iobase + com_data, c);
3192	siocnclose(&sp, iobase);
3193	if (need_unlock)
3194		mtx_unlock_spin(&sio_lock);
3195	splx(s);
3196}
3197
3198#ifdef __alpha__
3199int
3200siogdbgetc()
3201{
3202	int	c;
3203	Port_t	iobase;
3204	int	s;
3205	struct siocnstate	sp;
3206
3207	iobase = siogdbiobase;
3208	s = spltty();
3209	siocnopen(&sp, iobase, gdbdefaultrate);
3210	while (!(inb(iobase + com_lsr) & LSR_RXRDY))
3211		;
3212	c = inb(iobase + com_data);
3213	siocnclose(&sp, iobase);
3214	splx(s);
3215	return (c);
3216}
3217
3218void
3219siogdbputc(c)
3220	int	c;
3221{
3222	int	s;
3223	struct siocnstate	sp;
3224
3225	s = spltty();
3226	siocnopen(&sp, siogdbiobase, gdbdefaultrate);
3227	siocntxwait(siogdbiobase);
3228	outb(siogdbiobase + com_data, c);
3229	siocnclose(&sp, siogdbiobase);
3230	splx(s);
3231}
3232#endif
3233