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