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