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