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