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