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