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