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