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