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