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