sio.c revision 72200
1135911Sphk/*-
2135911Sphk * Copyright (c) 1991 The Regents of the University of California.
3135911Sphk * All rights reserved.
4135911Sphk *
5135911Sphk * Redistribution and use in source and binary forms, with or without
6135911Sphk * modification, are permitted provided that the following conditions
7135911Sphk * are met:
8135911Sphk * 1. Redistributions of source code must retain the above copyright
9135911Sphk *    notice, this list of conditions and the following disclaimer.
10135911Sphk * 2. Redistributions in binary form must reproduce the above copyright
11135911Sphk *    notice, this list of conditions and the following disclaimer in the
12135911Sphk *    documentation and/or other materials provided with the distribution.
13135911Sphk * 3. All advertising materials mentioning features or use of this software
14136257Sphk *    must display the following acknowledgement:
15135911Sphk *	This product includes software developed by the University of
16135911Sphk *	California, Berkeley and its contributors.
17136257Sphk * 4. Neither the name of the University nor the names of its contributors
18135911Sphk *    may be used to endorse or promote products derived from this software
19135911Sphk *    without specific prior written permission.
20135911Sphk *
21135911Sphk * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
22135911Sphk * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
23135911Sphk * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
24135911Sphk * ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
25135911Sphk * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
26135911Sphk * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
27135911Sphk * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
28135911Sphk * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
29135911Sphk * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
30135911Sphk * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
31135911Sphk * SUCH DAMAGE.
32135911Sphk *
33135911Sphk * $FreeBSD: head/sys/dev/sio/sio.c 72200 2001-02-09 06:11:45Z bmilekic $
34135911Sphk *	from: @(#)com.c	7.5 (Berkeley) 5/16/91
35135911Sphk *	from: i386/isa sio.c,v 1.234
36135911Sphk */
37135911Sphk
38135911Sphk#include "opt_comconsole.h"
39135911Sphk#include "opt_compat.h"
40135911Sphk#include "opt_ddb.h"
41135911Sphk#include "opt_sio.h"
42135911Sphk#include "card.h"
43135911Sphk#include "pci.h"
44135911Sphk
45135911Sphk/*
46135911Sphk * Serial driver, based on 386BSD-0.1 com driver.
47135911Sphk * Mostly rewritten to use pseudo-DMA.
48135911Sphk * Works for National Semiconductor NS8250-NS16550AF UARTs.
49135911Sphk * COM driver, based on HP dca driver.
50135911Sphk *
51135911Sphk * Changes for PC-Card integration:
52135911Sphk *	- Added PC-Card driver table and handlers
53135911Sphk */
54135911Sphk#include <sys/param.h>
55135911Sphk#include <sys/bus.h>
56135911Sphk#include <sys/systm.h>
57135911Sphk#include <sys/reboot.h>
58135911Sphk#include <sys/malloc.h>
59136257Sphk#include <sys/tty.h>
60135911Sphk#include <sys/proc.h>
61135911Sphk#include <sys/module.h>
62135911Sphk#include <sys/conf.h>
63135911Sphk#include <sys/dkstat.h>
64135911Sphk#include <sys/fcntl.h>
65135911Sphk#include <sys/interrupt.h>
66135911Sphk#include <sys/ipl.h>
67135911Sphk#include <sys/kernel.h>
68135911Sphk#include <sys/syslog.h>
69135911Sphk#include <sys/sysctl.h>
70135911Sphk#include <sys/bus.h>
71135911Sphk#include <machine/bus_pio.h>
72135911Sphk#include <machine/bus.h>
73135911Sphk#include <sys/rman.h>
74135911Sphk#include <sys/timetc.h>
75135911Sphk#include <sys/timepps.h>
76135911Sphk
77135911Sphk#include <isa/isareg.h>
78135911Sphk#include <isa/isavar.h>
79135911Sphk#if NPCI > 0
80135911Sphk#include <pci/pcireg.h>
81135911Sphk#include <pci/pcivar.h>
82135911Sphk#endif
83135911Sphk#include <machine/lock.h>
84135911Sphk
85135911Sphk#include <machine/clock.h>
86135911Sphk#ifndef SMP
87135911Sphk#include <machine/lock.h>
88135911Sphk#endif
89135911Sphk#include <machine/resource.h>
90136257Sphk
91135911Sphk#include <isa/sioreg.h>
92135911Sphk
93135911Sphk#ifdef COM_ESP
94135911Sphk#include <isa/ic/esp.h>
95135911Sphk#endif
96135911Sphk#include <isa/ic/ns16550.h>
97135911Sphk
98135911Sphk#define	LOTS_OF_EVENTS	64	/* helps separate urgent events from input */
99135911Sphk
100135911Sphk#define	CALLOUT_MASK		0x80
101135911Sphk#define	CONTROL_MASK		0x60
102135911Sphk#define	CONTROL_INIT_STATE	0x20
103135911Sphk#define	CONTROL_LOCK_STATE	0x40
104136257Sphk#define	DEV_TO_UNIT(dev)	(MINOR_TO_UNIT(minor(dev)))
105136257Sphk#define	MINOR_MAGIC_MASK	(CALLOUT_MASK | CONTROL_MASK)
106136815Sdes#define	MINOR_TO_UNIT(mynor)	((mynor) & ~MINOR_MAGIC_MASK)
107136257Sphk
108136815Sdes#ifdef COM_MULTIPORT
109136257Sphk/* checks in flags for multiport and which is multiport "master chip"
110136257Sphk * for a given card
111136257Sphk */
112136257Sphk#define	COM_ISMULTIPORT(flags)	((flags) & 0x01)
113136257Sphk#define	COM_MPMASTER(flags)	(((flags) >> 8) & 0x0ff)
114136257Sphk#define	COM_NOTAST4(flags)	((flags) & 0x04)
115136257Sphk#endif /* COM_MULTIPORT */
116135911Sphk
117135911Sphk#define	COM_CONSOLE(flags)	((flags) & 0x10)
118135911Sphk#define	COM_FORCECONSOLE(flags)	((flags) & 0x20)
119135911Sphk#define	COM_LLCONSOLE(flags)	((flags) & 0x40)
120135911Sphk#define	COM_DEBUGGER(flags)	((flags) & 0x80)
121135911Sphk#define	COM_LOSESOUTINTS(flags)	((flags) & 0x08)
122135911Sphk#define	COM_NOFIFO(flags)		((flags) & 0x02)
123135911Sphk#define COM_ST16650A(flags)	((flags) & 0x20000)
124135911Sphk#define COM_C_NOPROBE		(0x40000)
125135911Sphk#define COM_NOPROBE(flags)	((flags) & COM_C_NOPROBE)
126135911Sphk#define COM_C_IIR_TXRDYBUG	(0x80000)
127135911Sphk#define COM_IIR_TXRDYBUG(flags)	((flags) & COM_C_IIR_TXRDYBUG)
128136815Sdes#define	COM_FIFOSIZE(flags)	(((flags) & 0xff000000) >> 24)
129136815Sdes
130135911Sphk#define	com_scr		7	/* scratch register for 16450-16550 (R/W) */
131135911Sphk
132135911Sphk#define	sio_getreg(com, off) \
133135911Sphk	(bus_space_read_1((com)->bst, (com)->bsh, (off)))
134136815Sdes#define	sio_setreg(com, off, value) \
135135911Sphk	(bus_space_write_1((com)->bst, (com)->bsh, (off), (value)))
136135911Sphk
137135911Sphk/*
138135911Sphk * com state bits.
139135911Sphk * (CS_BUSY | CS_TTGO) and (CS_BUSY | CS_TTGO | CS_ODEVREADY) must be higher
140135911Sphk * than the other bits so that they can be tested as a group without masking
141135911Sphk * off the low bits.
142135911Sphk *
143135911Sphk * The following com and tty flags correspond closely:
144135911Sphk *	CS_BUSY		= TS_BUSY (maintained by comstart(), siopoll() and
145 *				   comstop())
146 *	CS_TTGO		= ~TS_TTSTOP (maintained by comparam() and comstart())
147 *	CS_CTS_OFLOW	= CCTS_OFLOW (maintained by comparam())
148 *	CS_RTS_IFLOW	= CRTS_IFLOW (maintained by comparam())
149 * TS_FLUSH is not used.
150 * XXX I think TIOCSETA doesn't clear TS_TTSTOP when it clears IXON.
151 * XXX CS_*FLOW should be CF_*FLOW in com->flags (control flags not state).
152 */
153#define	CS_BUSY		0x80	/* output in progress */
154#define	CS_TTGO		0x40	/* output not stopped by XOFF */
155#define	CS_ODEVREADY	0x20	/* external device h/w ready (CTS) */
156#define	CS_CHECKMSR	1	/* check of MSR scheduled */
157#define	CS_CTS_OFLOW	2	/* use CTS output flow control */
158#define	CS_DTR_OFF	0x10	/* DTR held off */
159#define	CS_ODONE	4	/* output completed */
160#define	CS_RTS_IFLOW	8	/* use RTS input flow control */
161#define	CSE_BUSYCHECK	1	/* siobusycheck() scheduled */
162
163static	char const * const	error_desc[] = {
164#define	CE_OVERRUN			0
165	"silo overflow",
166#define	CE_INTERRUPT_BUF_OVERFLOW	1
167	"interrupt-level buffer overflow",
168#define	CE_TTY_BUF_OVERFLOW		2
169	"tty-level buffer overflow",
170};
171
172#define	CE_NTYPES			3
173#define	CE_RECORD(com, errnum)		(++(com)->delta_error_counts[errnum])
174
175/* types.  XXX - should be elsewhere */
176typedef u_int	Port_t;		/* hardware port */
177typedef u_char	bool_t;		/* boolean */
178
179/* queue of linear buffers */
180struct lbq {
181	u_char	*l_head;	/* next char to process */
182	u_char	*l_tail;	/* one past the last char to process */
183	struct lbq *l_next;	/* next in queue */
184	bool_t	l_queued;	/* nonzero if queued */
185};
186
187/* com device structure */
188struct com_s {
189	u_int	flags;		/* Copy isa device flags */
190	u_char	state;		/* miscellaneous flag bits */
191	bool_t  active_out;	/* nonzero if the callout device is open */
192	u_char	cfcr_image;	/* copy of value written to CFCR */
193#ifdef COM_ESP
194	bool_t	esp;		/* is this unit a hayes esp board? */
195#endif
196	u_char	extra_state;	/* more flag bits, separate for order trick */
197	u_char	fifo_image;	/* copy of value written to FIFO */
198	bool_t	hasfifo;	/* nonzero for 16550 UARTs */
199	bool_t	st16650a;	/* Is a Startech 16650A or RTS/CTS compat */
200	bool_t	loses_outints;	/* nonzero if device loses output interrupts */
201	u_char	mcr_image;	/* copy of value written to MCR */
202#ifdef COM_MULTIPORT
203	bool_t	multiport;	/* is this unit part of a multiport device? */
204#endif /* COM_MULTIPORT */
205	bool_t	no_irq;		/* nonzero if irq is not attached */
206	bool_t  gone;		/* hardware disappeared */
207	bool_t	poll;		/* nonzero if polling is required */
208	bool_t	poll_output;	/* nonzero if polling for output is required */
209	int	unit;		/* unit	number */
210	int	dtr_wait;	/* time to hold DTR down on close (* 1/hz) */
211	u_int	tx_fifo_size;
212	u_int	wopeners;	/* # processes waiting for DCD in open() */
213
214	/*
215	 * The high level of the driver never reads status registers directly
216	 * because there would be too many side effects to handle conveniently.
217	 * Instead, it reads copies of the registers stored here by the
218	 * interrupt handler.
219	 */
220	u_char	last_modem_status;	/* last MSR read by intr handler */
221	u_char	prev_modem_status;	/* last MSR handled by high level */
222
223	u_char	hotchar;	/* ldisc-specific char to be handled ASAP */
224	u_char	*ibuf;		/* start of input buffer */
225	u_char	*ibufend;	/* end of input buffer */
226	u_char	*ibufold;	/* old input buffer, to be freed */
227	u_char	*ihighwater;	/* threshold in input buffer */
228	u_char	*iptr;		/* next free spot in input buffer */
229	int	ibufsize;	/* size of ibuf (not include error bytes) */
230	int	ierroff;	/* offset of error bytes in ibuf */
231
232	struct lbq	obufq;	/* head of queue of output buffers */
233	struct lbq	obufs[2];	/* output buffers */
234
235	bus_space_tag_t		bst;
236	bus_space_handle_t	bsh;
237
238	Port_t	data_port;	/* i/o ports */
239#ifdef COM_ESP
240	Port_t	esp_port;
241#endif
242	Port_t	int_id_port;
243	Port_t	modem_ctl_port;
244	Port_t	line_status_port;
245	Port_t	modem_status_port;
246	Port_t	intr_ctl_port;	/* Ports of IIR register */
247
248	struct tty	*tp;	/* cross reference */
249
250	/* Initial state. */
251	struct termios	it_in;	/* should be in struct tty */
252	struct termios	it_out;
253
254	/* Lock state. */
255	struct termios	lt_in;	/* should be in struct tty */
256	struct termios	lt_out;
257
258	bool_t	do_timestamp;
259	bool_t	do_dcd_timestamp;
260	struct timeval	timestamp;
261	struct timeval	dcd_timestamp;
262	struct	pps_state pps;
263
264	u_long	bytes_in;	/* statistics */
265	u_long	bytes_out;
266	u_int	delta_error_counts[CE_NTYPES];
267	u_long	error_counts[CE_NTYPES];
268
269	struct resource *irqres;
270	struct resource *ioportres;
271	void *cookie;
272	dev_t devs[6];
273
274	/*
275	 * Data area for output buffers.  Someday we should build the output
276	 * buffer queue without copying data.
277	 */
278	u_char	obuf1[256];
279	u_char	obuf2[256];
280};
281
282#ifdef COM_ESP
283static	int	espattach	__P((struct com_s *com, Port_t esp_port));
284#endif
285static	int	sioattach	__P((device_t dev, int rid));
286static	int	sio_isa_attach	__P((device_t dev));
287
288static	timeout_t siobusycheck;
289static	timeout_t siodtrwakeup;
290static	void	comhardclose	__P((struct com_s *com));
291static	void	sioinput	__P((struct com_s *com));
292static	void	siointr1	__P((struct com_s *com));
293static	void	siointr		__P((void *arg));
294static	int	commctl		__P((struct com_s *com, int bits, int how));
295static	int	comparam	__P((struct tty *tp, struct termios *t));
296static	void	siopoll		__P((void *));
297static	int	sioprobe	__P((device_t dev, int xrid));
298static	int	sio_isa_probe	__P((device_t dev));
299static	void	siosettimeout	__P((void));
300static	int	siosetwater	__P((struct com_s *com, speed_t speed));
301static	void	comstart	__P((struct tty *tp));
302static	void	comstop		__P((struct tty *tp, int rw));
303static	timeout_t comwakeup;
304static	void	disc_optim	__P((struct tty	*tp, struct termios *t,
305				     struct com_s *com));
306
307#if NCARD > 0
308static	int	sio_pccard_attach __P((device_t dev));
309static	int	sio_pccard_detach __P((device_t dev));
310static	int	sio_pccard_probe __P((device_t dev));
311#endif /* NCARD > 0 */
312
313#if NPCI > 0
314static	int	sio_pci_attach __P((device_t dev));
315static	void	sio_pci_kludge_unit __P((device_t dev));
316static	int	sio_pci_probe __P((device_t dev));
317#endif /* NPCI > 0 */
318
319static char	driver_name[] = "sio";
320static struct	mtx sio_lock;
321static int	sio_inited;
322
323/* table and macro for fast conversion from a unit number to its com struct */
324static	devclass_t	sio_devclass;
325#define	com_addr(unit)	((struct com_s *) \
326			 devclass_get_softc(sio_devclass, unit))
327
328static device_method_t sio_isa_methods[] = {
329	/* Device interface */
330	DEVMETHOD(device_probe,		sio_isa_probe),
331	DEVMETHOD(device_attach,	sio_isa_attach),
332
333	{ 0, 0 }
334};
335
336static driver_t sio_isa_driver = {
337	driver_name,
338	sio_isa_methods,
339	sizeof(struct com_s),
340};
341
342#if NCARD > 0
343static device_method_t sio_pccard_methods[] = {
344	/* Device interface */
345	DEVMETHOD(device_probe,		sio_pccard_probe),
346	DEVMETHOD(device_attach,	sio_pccard_attach),
347	DEVMETHOD(device_detach,	sio_pccard_detach),
348
349	{ 0, 0 }
350};
351
352static driver_t sio_pccard_driver = {
353	driver_name,
354	sio_pccard_methods,
355	sizeof(struct com_s),
356};
357#endif /* NCARD > 0 */
358
359#if NPCI > 0
360static device_method_t sio_pci_methods[] = {
361	/* Device interface */
362	DEVMETHOD(device_probe,		sio_pci_probe),
363	DEVMETHOD(device_attach,	sio_pci_attach),
364
365	{ 0, 0 }
366};
367
368static driver_t sio_pci_driver = {
369	driver_name,
370	sio_pci_methods,
371	sizeof(struct com_s),
372};
373#endif /* NPCI > 0 */
374
375static	d_open_t	sioopen;
376static	d_close_t	sioclose;
377static	d_read_t	sioread;
378static	d_write_t	siowrite;
379static	d_ioctl_t	sioioctl;
380
381#define	CDEV_MAJOR	28
382static struct cdevsw sio_cdevsw = {
383	/* open */	sioopen,
384	/* close */	sioclose,
385	/* read */	sioread,
386	/* write */	siowrite,
387	/* ioctl */	sioioctl,
388	/* poll */	ttypoll,
389	/* mmap */	nommap,
390	/* strategy */	nostrategy,
391	/* name */	driver_name,
392	/* maj */	CDEV_MAJOR,
393	/* dump */	nodump,
394	/* psize */	nopsize,
395	/* flags */	D_TTY,
396	/* bmaj */	-1
397};
398
399int	comconsole = -1;
400static	volatile speed_t	comdefaultrate = CONSPEED;
401#ifdef __alpha__
402static	volatile speed_t	gdbdefaultrate = CONSPEED;
403#endif
404static	u_int	com_events;	/* input chars + weighted output completions */
405static	Port_t	siocniobase;
406#ifndef __alpha__
407static	int	siocnunit;
408#endif
409static	Port_t	siogdbiobase;
410static	int	siogdbunit = -1;
411static	struct intrhand *sio_slow_ih;
412static	struct intrhand *sio_fast_ih;
413static	int	sio_timeout;
414static	int	sio_timeouts_until_log;
415static	struct	callout_handle sio_timeout_handle
416    = CALLOUT_HANDLE_INITIALIZER(&sio_timeout_handle);
417static	int	sio_numunits;
418
419static	struct speedtab comspeedtab[] = {
420	{ 0,		0 },
421	{ 50,		COMBRD(50) },
422	{ 75,		COMBRD(75) },
423	{ 110,		COMBRD(110) },
424	{ 134,		COMBRD(134) },
425	{ 150,		COMBRD(150) },
426	{ 200,		COMBRD(200) },
427	{ 300,		COMBRD(300) },
428	{ 600,		COMBRD(600) },
429	{ 1200,		COMBRD(1200) },
430	{ 1800,		COMBRD(1800) },
431	{ 2400,		COMBRD(2400) },
432	{ 4800,		COMBRD(4800) },
433	{ 9600,		COMBRD(9600) },
434	{ 19200,	COMBRD(19200) },
435	{ 38400,	COMBRD(38400) },
436	{ 57600,	COMBRD(57600) },
437	{ 115200,	COMBRD(115200) },
438	{ -1,		-1 }
439};
440
441#ifdef COM_ESP
442/* XXX configure this properly. */
443static	Port_t	likely_com_ports[] = { 0x3f8, 0x2f8, 0x3e8, 0x2e8, };
444static	Port_t	likely_esp_ports[] = { 0x140, 0x180, 0x280, 0 };
445#endif
446
447/*
448 * handle sysctl read/write requests for console speed
449 *
450 * In addition to setting comdefaultrate for I/O through /dev/console,
451 * also set the initial and lock values for the /dev/ttyXX device
452 * if there is one associated with the console.  Finally, if the /dev/tty
453 * device has already been open, change the speed on the open running port
454 * itself.
455 */
456
457static int
458sysctl_machdep_comdefaultrate(SYSCTL_HANDLER_ARGS)
459{
460	int error, s;
461	speed_t newspeed;
462	struct com_s *com;
463	struct tty *tp;
464
465	newspeed = comdefaultrate;
466
467	error = sysctl_handle_opaque(oidp, &newspeed, sizeof newspeed, req);
468	if (error || !req->newptr)
469		return (error);
470
471	comdefaultrate = newspeed;
472
473	if (comconsole < 0)		/* serial console not selected? */
474		return (0);
475
476	com = com_addr(comconsole);
477	if (com == NULL)
478		return (ENXIO);
479
480	/*
481	 * set the initial and lock rates for /dev/ttydXX and /dev/cuaXX
482	 * (note, the lock rates really are boolean -- if non-zero, disallow
483	 *  speed changes)
484	 */
485	com->it_in.c_ispeed  = com->it_in.c_ospeed =
486	com->lt_in.c_ispeed  = com->lt_in.c_ospeed =
487	com->it_out.c_ispeed = com->it_out.c_ospeed =
488	com->lt_out.c_ispeed = com->lt_out.c_ospeed = comdefaultrate;
489
490	/*
491	 * if we're open, change the running rate too
492	 */
493	tp = com->tp;
494	if (tp && (tp->t_state & TS_ISOPEN)) {
495		tp->t_termios.c_ispeed =
496		tp->t_termios.c_ospeed = comdefaultrate;
497		s = spltty();
498		error = comparam(tp, &tp->t_termios);
499		splx(s);
500	}
501	return error;
502}
503
504SYSCTL_PROC(_machdep, OID_AUTO, conspeed, CTLTYPE_INT | CTLFLAG_RW,
505	    0, 0, sysctl_machdep_comdefaultrate, "I", "");
506
507#define SET_FLAG(dev, bit) device_set_flags(dev, device_get_flags(dev) | (bit))
508#define CLR_FLAG(dev, bit) device_set_flags(dev, device_get_flags(dev) & ~(bit))
509
510#if NCARD > 0
511static int
512sio_pccard_probe(dev)
513	device_t	dev;
514{
515	/* Do not probe IRQ - pccard doesn't turn on the interrupt line */
516	/* until bus_setup_intr */
517	SET_FLAG(dev, COM_C_NOPROBE);
518
519	return (sioprobe(dev, 0));
520}
521
522static int
523sio_pccard_attach(dev)
524	device_t	dev;
525{
526	return (sioattach(dev, 0));
527}
528
529/*
530 *	sio_detach - unload the driver and clear the table.
531 *	XXX TODO:
532 *	This is usually called when the card is ejected, but
533 *	can be caused by a modunload of a controller driver.
534 *	The idea is to reset the driver's view of the device
535 *	and ensure that any driver entry points such as
536 *	read and write do not hang.
537 */
538static int
539sio_pccard_detach(dev)
540	device_t	dev;
541{
542	struct com_s	*com;
543	int i;
544
545	com = (struct com_s *) device_get_softc(dev);
546	if (com == NULL) {
547		device_printf(dev, "NULL com in siounload\n");
548		return (0);
549	}
550	com->gone = 1;
551	for (i = 0 ; i < 6; i++)
552		destroy_dev(com->devs[i]);
553	if (com->irqres) {
554		bus_teardown_intr(dev, com->irqres, com->cookie);
555		bus_release_resource(dev, SYS_RES_IRQ, 0, com->irqres);
556	}
557	if (com->ioportres)
558		bus_release_resource(dev, SYS_RES_IOPORT, 0, com->ioportres);
559	if (com->tp && (com->tp->t_state & TS_ISOPEN)) {
560		device_printf(dev, "still open, forcing close\n");
561		com->tp->t_gen++;
562		ttyclose(com->tp);
563		ttwakeup(com->tp);
564		ttwwakeup(com->tp);
565	} else {
566		if (com->ibuf != NULL)
567			free(com->ibuf, M_DEVBUF);
568	}
569	device_printf(dev, "unloaded\n");
570	return (0);
571}
572#endif /* NCARD > 0 */
573
574#if NPCI > 0
575struct pci_ids {
576	u_int32_t	type;
577	const char	*desc;
578	int		rid;
579};
580
581static struct pci_ids pci_ids[] = {
582	{ 0x100812b9, "3COM PCI FaxModem", 0x10 },
583	{ 0x048011c1, "ActionTec 56k FAX PCI Modem", 0x14 },
584	{ 0x00000000, NULL, 0 }
585};
586
587static int
588sio_pci_attach(dev)
589	device_t	dev;
590{
591	u_int32_t	type;
592	struct pci_ids	*id;
593
594	type = pci_get_devid(dev);
595	id = pci_ids;
596	while (id->type && id->type != type)
597		id++;
598	if (id->desc == NULL)
599		return (ENXIO);
600	sio_pci_kludge_unit(dev);
601	return (sioattach(dev, id->rid));
602}
603
604/*
605 * Don't cut and paste this to other drivers.  It is a horrible kludge
606 * which will fail to work and also be unnecessary in future versions.
607 */
608static void
609sio_pci_kludge_unit(dev)
610	device_t dev;
611{
612	devclass_t	dc;
613	int		err;
614	int		start;
615	int		unit;
616
617	unit = 0;
618	start = 0;
619	while (resource_int_value("sio", unit, "port", &start) == 0 &&
620	    start > 0)
621		unit++;
622	if (device_get_unit(dev) < unit) {
623		dc = device_get_devclass(dev);
624		while (devclass_get_device(dc, unit))
625			unit++;
626		device_printf(dev, "moving to sio%d\n", unit);
627		err = device_set_unit(dev, unit);	/* EVIL DO NOT COPY */
628		if (err)
629			device_printf(dev, "error moving device %d\n", err);
630	}
631}
632
633static int
634sio_pci_probe(dev)
635	device_t	dev;
636{
637	u_int32_t	type;
638	struct pci_ids	*id;
639
640	type = pci_get_devid(dev);
641	id = pci_ids;
642	while (id->type && id->type != type)
643		id++;
644	if (id->desc == NULL)
645		return (ENXIO);
646	device_set_desc(dev, id->desc);
647	return (sioprobe(dev, id->rid));
648}
649#endif /* NPCI > 0 */
650
651static struct isa_pnp_id sio_ids[] = {
652	{0x0005d041, "Standard PC COM port"},	/* PNP0500 */
653	{0x0105d041, "16550A-compatible COM port"},	/* PNP0501 */
654	{0x0205d041, "Multiport serial device (non-intelligent 16550)"}, /* PNP0502 */
655	{0x1005d041, "Generic IRDA-compatible device"},	/* PNP0510 */
656	{0x1105d041, "Generic IRDA-compatible device"},	/* PNP0511 */
657	/* Devices that do not have a compatid */
658	{0x12206804, NULL},     /* ACH2012 - 5634BTS 56K Video Ready Modem */
659	{0x7602a904, NULL},	/* AEI0276 - 56K v.90 Fax Modem (LKT) */
660	{0x00007905, NULL},	/* AKY0000 - 56K Plug&Play Modem */
661	{0x01405407, NULL},	/* AZT4001 - AZT3000 PnP SOUND DEVICE, MODEM */
662	{0x56039008, NULL},	/* BDP0356 - Best Data 56x2 */
663	{0x36339008, NULL},	/* BDP3336 - Best Data Prods. 336F */
664	{0x0014490a, NULL},	/* BRI1400 - Boca 33.6 PnP */
665	{0x0015490a, NULL},	/* BRI1500 - Internal Fax Data */
666	{0x0034490a, NULL},	/* BRI3400 - Internal ACF Modem */
667	{0x0094490a, NULL},	/* BRI9400 - Boca K56Flex PnP */
668	{0x00b4490a, NULL},	/* BRIB400 - Boca 56k PnP */
669	{0x0030320d, NULL},	/* CIR3000 - Cirrus Logic V43 */
670	{0x0100440e, NULL},	/* CRD0001 - Cardinal MVP288IV ? */
671	{0x36033610, NULL},     /* DAV0336 - DAVICOM 336PNP MODEM */
672	{0x0000aa1a, NULL},	/* FUJ0000 - FUJITSU Modem 33600 PNP/I2 */
673	{0x1200c31e, NULL},	/* GVC0012 - VF1128HV-R9 (win modem?) */
674	{0x0303c31e, NULL},	/* GVC0303 - MaxTech 33.6 PnP D/F/V */
675	{0x0505c31e, NULL},	/* GVC0505 - GVC 56k Faxmodem */
676	{0x0050c31e, NULL},	/* GVC5000 - some GVC modem */
677	{0x3800f91e, NULL},	/* GWY0038 - Telepath with v.90 */
678	{0x9062f91e, NULL},	/* GWY6290 - Telepath with x2 Technology */
679	{0x21002534, NULL},	/* MAE0021 - Jetstream Int V.90 56k Voice Series 2*/
680	{0x0000f435, NULL},	/* MOT0000 - Motorola ModemSURFR 33.6 Intern */
681	{0x5015f435, NULL},	/* MOT1550 - Motorola ModemSURFR 56K Modem */
682	{0xf015f435, NULL},	/* MOT15F0 - Motorola VoiceSURFR 56K Modem */
683	{0x6045f435, NULL},	/* MOT4560 - Motorola ? */
684	{0x61e7a338, NULL},	/* NECE761 - 33.6Modem */
685 	{0x08804f3f, NULL},	/* OZO8008 - Zoom  (33.6k Modem) */
686	{0x0f804f3f, NULL},	/* OZO800f - Zoom 2812 (56k Modem) */
687	{0x39804f3f, NULL},	/* OZO8039 - Zoom 56k flex */
688	{0x3024a341, NULL},	/* PMC2430 - Pace 56 Voice Internal Modem */
689	{0x1000eb49, NULL},	/* ROK0010 - Rockwell ? */
690	{0x5002734a, NULL},	/* RSS0250 - 5614Jx3(G) Internal Modem */
691	{0x6202734a, NULL},	/* RSS0262 - 5614Jx3[G] V90+K56Flex Modem */
692	{0xc100ad4d, NULL},	/* SMM00C1 - Leopard 56k PnP */
693	{0x9012b04e, NULL},	/* SUP1290 - Supra ? */
694	{0x1013b04e, NULL},	/* SUP1310 - SupraExpress 336i PnP */
695	{0x8013b04e, NULL},	/* SUP1380 - SupraExpress 288i PnP Voice */
696	{0x8113b04e, NULL},	/* SUP1381 - SupraExpress 336i PnP Voice */
697	{0x5016b04e, NULL},	/* SUP1650 - Supra 336i Sp Intl */
698	{0x7016b04e, NULL},	/* SUP1670 - Supra 336i V+ Intl */
699	{0x7420b04e, NULL},	/* SUP2070 - Supra ? */
700	{0x8020b04e, NULL},	/* SUP2080 - Supra ? */
701	{0x8420b04e, NULL},	/* SUP2084 - SupraExpress 56i PnP */
702	{0x7121b04e, NULL},	/* SUP2171 - SupraExpress 56i Sp? */
703	{0x8024b04e, NULL},	/* SUP2480 - Supra ? */
704	{0x01007256, NULL},	/* USR0001 - U.S. Robotics Inc., Sportster W */
705	{0x02007256, NULL},	/* USR0002 - U.S. Robotics Inc. Sportster 33. */
706	{0x04007256, NULL},	/* USR0004 - USR Sportster 14.4k */
707	{0x06007256, NULL},	/* USR0006 - USR Sportster 33.6k */
708	{0x11007256, NULL},	/* USR0011 - USR ? */
709	{0x01017256, NULL},	/* USR0101 - USR ? */
710	{0x30207256, NULL},	/* USR2030 - U.S.Robotics Inc. Sportster 560 */
711	{0x50207256, NULL},	/* USR2050 - U.S.Robotics Inc. Sportster 33. */
712	{0x70207256, NULL},	/* USR2070 - U.S.Robotics Inc. Sportster 560 */
713	{0x30307256, NULL},	/* USR3030 - U.S. Robotics 56K FAX INT */
714	{0x31307256, NULL},	/* USR3031 - U.S. Robotics 56K FAX INT */
715	{0x50307256, NULL},	/* USR3050 - U.S. Robotics 56K FAX INT */
716	{0x70307256, NULL},	/* USR3070 - U.S. Robotics 56K Voice INT */
717	{0x90307256, NULL},	/* USR3090 - USR ? */
718	{0x70917256, NULL},	/* USR9170 - U.S. Robotics 56K FAX INT */
719	{0x90917256, NULL},	/* USR9190 - USR 56k Voice INT */
720	{0x0300695c, NULL},	/* WCI0003 - Fax/Voice/Modem/Speakphone/Asvd */
721	{0x01a0896a, NULL},	/* ZTIA001 - Zoom Internal V90 Faxmodem */
722	{0x61f7896a, NULL},	/* ZTIF761 - Zoom ComStar 33.6 */
723	{0}
724};
725
726
727
728static int
729sio_isa_probe(dev)
730	device_t	dev;
731{
732	/* Check isapnp ids */
733	if (ISA_PNP_PROBE(device_get_parent(dev), dev, sio_ids) == ENXIO)
734		return (ENXIO);
735	return (sioprobe(dev, 0));
736}
737
738static int
739sioprobe(dev, xrid)
740	device_t	dev;
741	int		xrid;
742{
743#if 0
744	static bool_t	already_init;
745	device_t	xdev;
746#endif
747	struct com_s	*com;
748	bool_t		failures[10];
749	int		fn;
750	device_t	idev;
751	Port_t		iobase;
752	intrmask_t	irqmap[4];
753	intrmask_t	irqs;
754	u_char		mcr_image;
755	int		result;
756	u_long		xirq;
757	u_int		flags = device_get_flags(dev);
758	int		rid;
759	struct resource *port;
760
761	rid = xrid;
762	port = bus_alloc_resource(dev, SYS_RES_IOPORT, &rid,
763				  0, ~0, IO_COMSIZE, RF_ACTIVE);
764	if (!port)
765		return (ENXIO);
766
767	com = device_get_softc(dev);
768	com->bst = rman_get_bustag(port);
769	com->bsh = rman_get_bushandle(port);
770
771	if (atomic_cmpset_int(&sio_inited, 0, 1))
772		mtx_init(&sio_lock, "sio", MTX_SPIN);
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	mtx_lock_spin(&sio_lock);
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		mtx_unlock_spin(&sio_lock);
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	mtx_unlock_spin(&sio_lock);
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		mtx_unlock_spin(&sio_lock);
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	mtx_unlock_spin(&sio_lock);
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_fast_ih == NULL) {
1317		sio_fast_ih = sinthand_add("tty:sio", &tty_ithd, siopoll,
1318		    NULL, SWI_TTY, 0);
1319		sio_slow_ih = sinthand_add("tty:sio", &clk_ithd, siopoll,
1320		    NULL, SWI_TTY, 0);
1321	}
1322	com->devs[0] = make_dev(&sio_cdevsw, unit,
1323	    UID_ROOT, GID_WHEEL, 0600, "ttyd%r", unit);
1324	com->devs[1] = make_dev(&sio_cdevsw, unit | CONTROL_INIT_STATE,
1325	    UID_ROOT, GID_WHEEL, 0600, "ttyid%r", unit);
1326	com->devs[2] = make_dev(&sio_cdevsw, unit | CONTROL_LOCK_STATE,
1327	    UID_ROOT, GID_WHEEL, 0600, "ttyld%r", unit);
1328	com->devs[3] = make_dev(&sio_cdevsw, unit | CALLOUT_MASK,
1329	    UID_UUCP, GID_DIALER, 0660, "cuaa%r", unit);
1330	com->devs[4] = make_dev(&sio_cdevsw,
1331	    unit | CALLOUT_MASK | CONTROL_INIT_STATE,
1332	    UID_UUCP, GID_DIALER, 0660, "cuaia%r", unit);
1333	com->devs[5] = make_dev(&sio_cdevsw,
1334	    unit | CALLOUT_MASK | CONTROL_LOCK_STATE,
1335	    UID_UUCP, GID_DIALER, 0660, "cuala%r", unit);
1336	com->flags = flags;
1337	com->pps.ppscap = PPS_CAPTUREASSERT | PPS_CAPTURECLEAR;
1338	pps_init(&com->pps);
1339
1340	rid = 0;
1341	com->irqres = bus_alloc_resource(dev, SYS_RES_IRQ, &rid, 0ul, ~0ul, 1,
1342	    RF_ACTIVE);
1343	if (com->irqres) {
1344		ret = BUS_SETUP_INTR(device_get_parent(dev), dev, com->irqres,
1345				     INTR_TYPE_TTY | INTR_FAST,
1346				     siointr, com, &com->cookie);
1347		if (ret) {
1348			ret = BUS_SETUP_INTR(device_get_parent(dev), dev,
1349					     com->irqres, INTR_TYPE_TTY,
1350					     siointr, com, &com->cookie);
1351			if (ret == 0)
1352				device_printf(dev, "unable to activate interrupt in fast mode - using normal mode");
1353		}
1354		if (ret)
1355			device_printf(dev, "could not activate interrupt\n");
1356	}
1357
1358	return (0);
1359}
1360
1361static int
1362sioopen(dev, flag, mode, p)
1363	dev_t		dev;
1364	int		flag;
1365	int		mode;
1366	struct proc	*p;
1367{
1368	struct com_s	*com;
1369	int		error;
1370	int		mynor;
1371	int		s;
1372	struct tty	*tp;
1373	int		unit;
1374
1375	mynor = minor(dev);
1376	unit = MINOR_TO_UNIT(mynor);
1377	com = com_addr(unit);
1378	if (com == NULL)
1379		return (ENXIO);
1380	if (com->gone)
1381		return (ENXIO);
1382	if (mynor & CONTROL_MASK)
1383		return (0);
1384	tp = dev->si_tty = com->tp = ttymalloc(com->tp);
1385	s = spltty();
1386	/*
1387	 * We jump to this label after all non-interrupted sleeps to pick
1388	 * up any changes of the device state.
1389	 */
1390open_top:
1391	while (com->state & CS_DTR_OFF) {
1392		error = tsleep(&com->dtr_wait, TTIPRI | PCATCH, "siodtr", 0);
1393		if (com_addr(unit) == NULL)
1394			return (ENXIO);
1395		if (error != 0 || com->gone)
1396			goto out;
1397	}
1398	if (tp->t_state & TS_ISOPEN) {
1399		/*
1400		 * The device is open, so everything has been initialized.
1401		 * Handle conflicts.
1402		 */
1403		if (mynor & CALLOUT_MASK) {
1404			if (!com->active_out) {
1405				error = EBUSY;
1406				goto out;
1407			}
1408		} else {
1409			if (com->active_out) {
1410				if (flag & O_NONBLOCK) {
1411					error = EBUSY;
1412					goto out;
1413				}
1414				error =	tsleep(&com->active_out,
1415					       TTIPRI | PCATCH, "siobi", 0);
1416				if (com_addr(unit) == NULL)
1417					return (ENXIO);
1418				if (error != 0 || com->gone)
1419					goto out;
1420				goto open_top;
1421			}
1422		}
1423		if (tp->t_state & TS_XCLUDE &&
1424		    suser(p)) {
1425			error = EBUSY;
1426			goto out;
1427		}
1428	} else {
1429		/*
1430		 * The device isn't open, so there are no conflicts.
1431		 * Initialize it.  Initialization is done twice in many
1432		 * cases: to preempt sleeping callin opens if we are
1433		 * callout, and to complete a callin open after DCD rises.
1434		 */
1435		tp->t_oproc = comstart;
1436		tp->t_param = comparam;
1437		tp->t_stop = comstop;
1438		tp->t_dev = dev;
1439		tp->t_termios = mynor & CALLOUT_MASK
1440				? com->it_out : com->it_in;
1441		(void)commctl(com, TIOCM_DTR | TIOCM_RTS, DMSET);
1442		com->poll = com->no_irq;
1443		com->poll_output = com->loses_outints;
1444		++com->wopeners;
1445		error = comparam(tp, &tp->t_termios);
1446		--com->wopeners;
1447		if (error != 0)
1448			goto out;
1449		/*
1450		 * XXX we should goto open_top if comparam() slept.
1451		 */
1452		if (com->hasfifo) {
1453			/*
1454			 * (Re)enable and drain fifos.
1455			 *
1456			 * Certain SMC chips cause problems if the fifos
1457			 * are enabled while input is ready.  Turn off the
1458			 * fifo if necessary to clear the input.  We test
1459			 * the input ready bit after enabling the fifos
1460			 * since we've already enabled them in comparam()
1461			 * and to handle races between enabling and fresh
1462			 * input.
1463			 */
1464			while (TRUE) {
1465				sio_setreg(com, com_fifo,
1466					   FIFO_RCV_RST | FIFO_XMT_RST
1467					   | com->fifo_image);
1468				/*
1469				 * XXX the delays are for superstitious
1470				 * historical reasons.  It must be less than
1471				 * the character time at the maximum
1472				 * supported speed (87 usec at 115200 bps
1473				 * 8N1).  Otherwise we might loop endlessly
1474				 * if data is streaming in.  We used to use
1475				 * delays of 100.  That usually worked
1476				 * because DELAY(100) used to usually delay
1477				 * for about 85 usec instead of 100.
1478				 */
1479				DELAY(50);
1480				if (!(inb(com->line_status_port) & LSR_RXRDY))
1481					break;
1482				sio_setreg(com, com_fifo, 0);
1483				DELAY(50);
1484				(void) inb(com->data_port);
1485			}
1486		}
1487
1488		mtx_lock_spin(&sio_lock);
1489		(void) inb(com->line_status_port);
1490		(void) inb(com->data_port);
1491		com->prev_modem_status = com->last_modem_status
1492		    = inb(com->modem_status_port);
1493		if (COM_IIR_TXRDYBUG(com->flags)) {
1494			outb(com->intr_ctl_port, IER_ERXRDY | IER_ERLS
1495						| IER_EMSC);
1496		} else {
1497			outb(com->intr_ctl_port, IER_ERXRDY | IER_ETXRDY
1498						| IER_ERLS | IER_EMSC);
1499		}
1500		mtx_unlock_spin(&sio_lock);
1501		/*
1502		 * Handle initial DCD.  Callout devices get a fake initial
1503		 * DCD (trapdoor DCD).  If we are callout, then any sleeping
1504		 * callin opens get woken up and resume sleeping on "siobi"
1505		 * instead of "siodcd".
1506		 */
1507		/*
1508		 * XXX `mynor & CALLOUT_MASK' should be
1509		 * `tp->t_cflag & (SOFT_CARRIER | TRAPDOOR_CARRIER) where
1510		 * TRAPDOOR_CARRIER is the default initial state for callout
1511		 * devices and SOFT_CARRIER is like CLOCAL except it hides
1512		 * the true carrier.
1513		 */
1514		if (com->prev_modem_status & MSR_DCD || mynor & CALLOUT_MASK)
1515			(*linesw[tp->t_line].l_modem)(tp, 1);
1516	}
1517	/*
1518	 * Wait for DCD if necessary.
1519	 */
1520	if (!(tp->t_state & TS_CARR_ON) && !(mynor & CALLOUT_MASK)
1521	    && !(tp->t_cflag & CLOCAL) && !(flag & O_NONBLOCK)) {
1522		++com->wopeners;
1523		error = tsleep(TSA_CARR_ON(tp), TTIPRI | PCATCH, "siodcd", 0);
1524		if (com_addr(unit) == NULL)
1525			return (ENXIO);
1526		--com->wopeners;
1527		if (error != 0 || com->gone)
1528			goto out;
1529		goto open_top;
1530	}
1531	error =	(*linesw[tp->t_line].l_open)(dev, tp);
1532	disc_optim(tp, &tp->t_termios, com);
1533	if (tp->t_state & TS_ISOPEN && mynor & CALLOUT_MASK)
1534		com->active_out = TRUE;
1535	siosettimeout();
1536out:
1537	splx(s);
1538	if (!(tp->t_state & TS_ISOPEN) && com->wopeners == 0)
1539		comhardclose(com);
1540	return (error);
1541}
1542
1543static int
1544sioclose(dev, flag, mode, p)
1545	dev_t		dev;
1546	int		flag;
1547	int		mode;
1548	struct proc	*p;
1549{
1550	struct com_s	*com;
1551	int		mynor;
1552	int		s;
1553	struct tty	*tp;
1554
1555	mynor = minor(dev);
1556	if (mynor & CONTROL_MASK)
1557		return (0);
1558	com = com_addr(MINOR_TO_UNIT(mynor));
1559	if (com == NULL)
1560		return (ENODEV);
1561	tp = com->tp;
1562	s = spltty();
1563	(*linesw[tp->t_line].l_close)(tp, flag);
1564	disc_optim(tp, &tp->t_termios, com);
1565	comstop(tp, FREAD | FWRITE);
1566	comhardclose(com);
1567	ttyclose(tp);
1568	siosettimeout();
1569	splx(s);
1570	if (com->gone) {
1571		printf("sio%d: gone\n", com->unit);
1572		s = spltty();
1573		if (com->ibuf != NULL)
1574			free(com->ibuf, M_DEVBUF);
1575		bzero(tp, sizeof *tp);
1576		splx(s);
1577	}
1578	return (0);
1579}
1580
1581static void
1582comhardclose(com)
1583	struct com_s	*com;
1584{
1585	int		s;
1586	struct tty	*tp;
1587	int		unit;
1588
1589	unit = com->unit;
1590	s = spltty();
1591	com->poll = FALSE;
1592	com->poll_output = FALSE;
1593	com->do_timestamp = FALSE;
1594	com->do_dcd_timestamp = FALSE;
1595	com->pps.ppsparam.mode = 0;
1596	sio_setreg(com, com_cfcr, com->cfcr_image &= ~CFCR_SBREAK);
1597	{
1598		sio_setreg(com, com_ier, 0);
1599		tp = com->tp;
1600		if (tp->t_cflag & HUPCL
1601		    /*
1602		     * XXX we will miss any carrier drop between here and the
1603		     * next open.  Perhaps we should watch DCD even when the
1604		     * port is closed; it is not sufficient to check it at
1605		     * the next open because it might go up and down while
1606		     * we're not watching.
1607		     */
1608		    || (!com->active_out
1609		        && !(com->prev_modem_status & MSR_DCD)
1610		        && !(com->it_in.c_cflag & CLOCAL))
1611		    || !(tp->t_state & TS_ISOPEN)) {
1612			(void)commctl(com, TIOCM_DTR, DMBIC);
1613			if (com->dtr_wait != 0 && !(com->state & CS_DTR_OFF)) {
1614				timeout(siodtrwakeup, com, com->dtr_wait);
1615				com->state |= CS_DTR_OFF;
1616			}
1617		}
1618	}
1619	if (com->hasfifo) {
1620		/*
1621		 * Disable fifos so that they are off after controlled
1622		 * reboots.  Some BIOSes fail to detect 16550s when the
1623		 * fifos are enabled.
1624		 */
1625		sio_setreg(com, com_fifo, 0);
1626	}
1627	com->active_out = FALSE;
1628	wakeup(&com->active_out);
1629	wakeup(TSA_CARR_ON(tp));	/* restart any wopeners */
1630	splx(s);
1631}
1632
1633static int
1634sioread(dev, uio, flag)
1635	dev_t		dev;
1636	struct uio	*uio;
1637	int		flag;
1638{
1639	int		mynor;
1640	struct com_s	*com;
1641
1642	mynor = minor(dev);
1643	if (mynor & CONTROL_MASK)
1644		return (ENODEV);
1645	com = com_addr(MINOR_TO_UNIT(mynor));
1646	if (com == NULL || com->gone)
1647		return (ENODEV);
1648	return ((*linesw[com->tp->t_line].l_read)(com->tp, uio, flag));
1649}
1650
1651static int
1652siowrite(dev, uio, flag)
1653	dev_t		dev;
1654	struct uio	*uio;
1655	int		flag;
1656{
1657	int		mynor;
1658	struct com_s	*com;
1659	int		unit;
1660
1661	mynor = minor(dev);
1662	if (mynor & CONTROL_MASK)
1663		return (ENODEV);
1664
1665	unit = MINOR_TO_UNIT(mynor);
1666	com = com_addr(unit);
1667	if (com == NULL || com->gone)
1668		return (ENODEV);
1669	/*
1670	 * (XXX) We disallow virtual consoles if the physical console is
1671	 * a serial port.  This is in case there is a display attached that
1672	 * is not the console.  In that situation we don't need/want the X
1673	 * server taking over the console.
1674	 */
1675	if (constty != NULL && unit == comconsole)
1676		constty = NULL;
1677	return ((*linesw[com->tp->t_line].l_write)(com->tp, uio, flag));
1678}
1679
1680static void
1681siobusycheck(chan)
1682	void	*chan;
1683{
1684	struct com_s	*com;
1685	int		s;
1686
1687	com = (struct com_s *)chan;
1688
1689	/*
1690	 * Clear TS_BUSY if low-level output is complete.
1691	 * spl locking is sufficient because siointr1() does not set CS_BUSY.
1692	 * If siointr1() clears CS_BUSY after we look at it, then we'll get
1693	 * called again.  Reading the line status port outside of siointr1()
1694	 * is safe because CS_BUSY is clear so there are no output interrupts
1695	 * to lose.
1696	 */
1697	s = spltty();
1698	if (com->state & CS_BUSY)
1699		com->extra_state &= ~CSE_BUSYCHECK;	/* False alarm. */
1700	else if ((inb(com->line_status_port) & (LSR_TSRE | LSR_TXRDY))
1701	    == (LSR_TSRE | LSR_TXRDY)) {
1702		com->tp->t_state &= ~TS_BUSY;
1703		ttwwakeup(com->tp);
1704		com->extra_state &= ~CSE_BUSYCHECK;
1705	} else
1706		timeout(siobusycheck, com, hz / 100);
1707	splx(s);
1708}
1709
1710static void
1711siodtrwakeup(chan)
1712	void	*chan;
1713{
1714	struct com_s	*com;
1715
1716	com = (struct com_s *)chan;
1717	com->state &= ~CS_DTR_OFF;
1718	wakeup(&com->dtr_wait);
1719}
1720
1721/*
1722 * Call this function with the sio_lock mutex held.  It will return with the
1723 * lock still held.
1724 */
1725static void
1726sioinput(com)
1727	struct com_s	*com;
1728{
1729	u_char		*buf;
1730	int		incc;
1731	u_char		line_status;
1732	int		recv_data;
1733	struct tty	*tp;
1734
1735	buf = com->ibuf;
1736	tp = com->tp;
1737	if (!(tp->t_state & TS_ISOPEN) || !(tp->t_cflag & CREAD)) {
1738		com_events -= (com->iptr - com->ibuf);
1739		com->iptr = com->ibuf;
1740		return;
1741	}
1742	if (tp->t_state & TS_CAN_BYPASS_L_RINT) {
1743		/*
1744		 * Avoid the grotesquely inefficient lineswitch routine
1745		 * (ttyinput) in "raw" mode.  It usually takes about 450
1746		 * instructions (that's without canonical processing or echo!).
1747		 * slinput is reasonably fast (usually 40 instructions plus
1748		 * call overhead).
1749		 */
1750		do {
1751			/*
1752			 * This may look odd, but it is using save-and-enable
1753			 * semantics instead of the save-and-disable semantics
1754			 * that are used everywhere else.
1755			 */
1756			mtx_unlock_spin(&sio_lock);
1757			incc = com->iptr - buf;
1758			if (tp->t_rawq.c_cc + incc > tp->t_ihiwat
1759			    && (com->state & CS_RTS_IFLOW
1760				|| tp->t_iflag & IXOFF)
1761			    && !(tp->t_state & TS_TBLOCK))
1762				ttyblock(tp);
1763			com->delta_error_counts[CE_TTY_BUF_OVERFLOW]
1764				+= b_to_q((char *)buf, incc, &tp->t_rawq);
1765			buf += incc;
1766			tk_nin += incc;
1767			tk_rawcc += incc;
1768			tp->t_rawcc += incc;
1769			ttwakeup(tp);
1770			if (tp->t_state & TS_TTSTOP
1771			    && (tp->t_iflag & IXANY
1772				|| tp->t_cc[VSTART] == tp->t_cc[VSTOP])) {
1773				tp->t_state &= ~TS_TTSTOP;
1774				tp->t_lflag &= ~FLUSHO;
1775				comstart(tp);
1776			}
1777			mtx_lock_spin(&sio_lock);
1778		} while (buf < com->iptr);
1779	} else {
1780		do {
1781			/*
1782			 * This may look odd, but it is using save-and-enable
1783			 * semantics instead of the save-and-disable semantics
1784			 * that are used everywhere else.
1785			 */
1786			mtx_unlock_spin(&sio_lock);
1787			line_status = buf[com->ierroff];
1788			recv_data = *buf++;
1789			if (line_status
1790			    & (LSR_BI | LSR_FE | LSR_OE | LSR_PE)) {
1791				if (line_status & LSR_BI)
1792					recv_data |= TTY_BI;
1793				if (line_status & LSR_FE)
1794					recv_data |= TTY_FE;
1795				if (line_status & LSR_OE)
1796					recv_data |= TTY_OE;
1797				if (line_status & LSR_PE)
1798					recv_data |= TTY_PE;
1799			}
1800			(*linesw[tp->t_line].l_rint)(recv_data, tp);
1801			mtx_lock_spin(&sio_lock);
1802		} while (buf < com->iptr);
1803	}
1804	com_events -= (com->iptr - com->ibuf);
1805	com->iptr = com->ibuf;
1806
1807	/*
1808	 * There is now room for another low-level buffer full of input,
1809	 * so enable RTS if it is now disabled and there is room in the
1810	 * high-level buffer.
1811	 */
1812	if ((com->state & CS_RTS_IFLOW) && !(com->mcr_image & MCR_RTS) &&
1813	    !(tp->t_state & TS_TBLOCK))
1814		outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
1815}
1816
1817void
1818siointr(arg)
1819	void		*arg;
1820{
1821	struct com_s	*com;
1822
1823#ifndef COM_MULTIPORT
1824	com = (struct com_s *)arg;
1825
1826	mtx_lock_spin(&sio_lock);
1827	siointr1(com);
1828	mtx_unlock_spin(&sio_lock);
1829#else /* COM_MULTIPORT */
1830	bool_t		possibly_more_intrs;
1831	int		unit;
1832
1833	/*
1834	 * Loop until there is no activity on any port.  This is necessary
1835	 * to get an interrupt edge more than to avoid another interrupt.
1836	 * If the IRQ signal is just an OR of the IRQ signals from several
1837	 * devices, then the edge from one may be lost because another is
1838	 * on.
1839	 */
1840	mtx_lock_spin(&sio_lock);
1841	do {
1842		possibly_more_intrs = FALSE;
1843		for (unit = 0; unit < sio_numunits; ++unit) {
1844			com = com_addr(unit);
1845			/*
1846			 * XXX COM_LOCK();
1847			 * would it work here, or be counter-productive?
1848			 */
1849			if (com != NULL
1850			    && !com->gone
1851			    && (inb(com->int_id_port) & IIR_IMASK)
1852			       != IIR_NOPEND) {
1853				siointr1(com);
1854				possibly_more_intrs = TRUE;
1855			}
1856			/* XXX COM_UNLOCK(); */
1857		}
1858	} while (possibly_more_intrs);
1859	mtx_unlock_spin(&sio_lock);
1860#endif /* COM_MULTIPORT */
1861}
1862
1863static void
1864siointr1(com)
1865	struct com_s	*com;
1866{
1867	u_char	line_status;
1868	u_char	modem_status;
1869	u_char	*ioptr;
1870	u_char	recv_data;
1871	u_char	int_ctl;
1872	u_char	int_ctl_new;
1873	struct	timecounter *tc;
1874	u_int	count;
1875
1876	int_ctl = inb(com->intr_ctl_port);
1877	int_ctl_new = int_ctl;
1878
1879	while (!com->gone) {
1880		if (com->pps.ppsparam.mode & PPS_CAPTUREBOTH) {
1881			modem_status = inb(com->modem_status_port);
1882		        if ((modem_status ^ com->last_modem_status) & MSR_DCD) {
1883				tc = timecounter;
1884				count = tc->tc_get_timecount(tc);
1885				pps_event(&com->pps, tc, count,
1886				    (modem_status & MSR_DCD) ?
1887				    PPS_CAPTUREASSERT : PPS_CAPTURECLEAR);
1888			}
1889		}
1890		line_status = inb(com->line_status_port);
1891
1892		/* input event? (check first to help avoid overruns) */
1893		while (line_status & LSR_RCV_MASK) {
1894			/* break/unnattached error bits or real input? */
1895			if (!(line_status & LSR_RXRDY))
1896				recv_data = 0;
1897			else
1898				recv_data = inb(com->data_port);
1899#if defined(DDB) && defined(ALT_BREAK_TO_DEBUGGER)
1900			/*
1901			 * Solaris implements a new BREAK which is initiated
1902			 * by a character sequence CR ~ ^b which is similar
1903			 * to a familiar pattern used on Sun servers by the
1904			 * Remote Console.
1905			 */
1906#define	KEY_CRTLB	2	/* ^B */
1907#define	KEY_CR		13	/* CR '\r' */
1908#define	KEY_TILDE	126	/* ~ */
1909
1910			if (com->unit == comconsole) {
1911				static int brk_state1 = 0, brk_state2 = 0;
1912				if (recv_data == KEY_CR) {
1913					brk_state1 = recv_data;
1914					brk_state2 = 0;
1915				} else if (brk_state1 == KEY_CR
1916					   && (recv_data == KEY_TILDE
1917					       || recv_data == KEY_CRTLB)) {
1918					if (recv_data == KEY_TILDE)
1919						brk_state2 = recv_data;
1920					else if (brk_state2 == KEY_TILDE
1921						 && recv_data == KEY_CRTLB) {
1922							breakpoint();
1923							brk_state1 = 0;
1924							brk_state2 = 0;
1925							goto cont;
1926					} else
1927						brk_state2 = 0;
1928				} else
1929					brk_state1 = 0;
1930			}
1931#endif
1932			if (line_status & (LSR_BI | LSR_FE | LSR_PE)) {
1933				/*
1934				 * Don't store BI if IGNBRK or FE/PE if IGNPAR.
1935				 * Otherwise, push the work to a higher level
1936				 * (to handle PARMRK) if we're bypassing.
1937				 * Otherwise, convert BI/FE and PE+INPCK to 0.
1938				 *
1939				 * This makes bypassing work right in the
1940				 * usual "raw" case (IGNBRK set, and IGNPAR
1941				 * and INPCK clear).
1942				 *
1943				 * Note: BI together with FE/PE means just BI.
1944				 */
1945				if (line_status & LSR_BI) {
1946#if defined(DDB) && defined(BREAK_TO_DEBUGGER)
1947					if (com->unit == comconsole) {
1948						breakpoint();
1949						goto cont;
1950					}
1951#endif
1952					if (com->tp == NULL
1953					    || com->tp->t_iflag & IGNBRK)
1954						goto cont;
1955				} else {
1956					if (com->tp == NULL
1957					    || com->tp->t_iflag & IGNPAR)
1958						goto cont;
1959				}
1960				if (com->tp->t_state & TS_CAN_BYPASS_L_RINT
1961				    && (line_status & (LSR_BI | LSR_FE)
1962					|| com->tp->t_iflag & INPCK))
1963					recv_data = 0;
1964			}
1965			++com->bytes_in;
1966			if (com->hotchar != 0 && recv_data == com->hotchar)
1967				sched_swi(sio_fast_ih, SWI_NOSWITCH);
1968			ioptr = com->iptr;
1969			if (ioptr >= com->ibufend)
1970				CE_RECORD(com, CE_INTERRUPT_BUF_OVERFLOW);
1971			else {
1972				if (com->do_timestamp)
1973					microtime(&com->timestamp);
1974				++com_events;
1975				sched_swi(sio_slow_ih, SWI_DELAY);
1976#if 0 /* for testing input latency vs efficiency */
1977if (com->iptr - com->ibuf == 8)
1978	sched_swi(sio_fast_ih, SWI_NOSWITCH);
1979#endif
1980				ioptr[0] = recv_data;
1981				ioptr[com->ierroff] = line_status;
1982				com->iptr = ++ioptr;
1983				if (ioptr == com->ihighwater
1984				    && com->state & CS_RTS_IFLOW)
1985					outb(com->modem_ctl_port,
1986					     com->mcr_image &= ~MCR_RTS);
1987				if (line_status & LSR_OE)
1988					CE_RECORD(com, CE_OVERRUN);
1989			}
1990cont:
1991			/*
1992			 * "& 0x7F" is to avoid the gcc-1.40 generating a slow
1993			 * jump from the top of the loop to here
1994			 */
1995			line_status = inb(com->line_status_port) & 0x7F;
1996		}
1997
1998		/* modem status change? (always check before doing output) */
1999		modem_status = inb(com->modem_status_port);
2000		if (modem_status != com->last_modem_status) {
2001			if (com->do_dcd_timestamp
2002			    && !(com->last_modem_status & MSR_DCD)
2003			    && modem_status & MSR_DCD)
2004				microtime(&com->dcd_timestamp);
2005
2006			/*
2007			 * Schedule high level to handle DCD changes.  Note
2008			 * that we don't use the delta bits anywhere.  Some
2009			 * UARTs mess them up, and it's easy to remember the
2010			 * previous bits and calculate the delta.
2011			 */
2012			com->last_modem_status = modem_status;
2013			if (!(com->state & CS_CHECKMSR)) {
2014				com_events += LOTS_OF_EVENTS;
2015				com->state |= CS_CHECKMSR;
2016				sched_swi(sio_fast_ih, SWI_NOSWITCH);
2017			}
2018
2019			/* handle CTS change immediately for crisp flow ctl */
2020			if (com->state & CS_CTS_OFLOW) {
2021				if (modem_status & MSR_CTS)
2022					com->state |= CS_ODEVREADY;
2023				else
2024					com->state &= ~CS_ODEVREADY;
2025			}
2026		}
2027
2028		/* output queued and everything ready? */
2029		if (line_status & LSR_TXRDY
2030		    && com->state >= (CS_BUSY | CS_TTGO | CS_ODEVREADY)) {
2031			ioptr = com->obufq.l_head;
2032			if (com->tx_fifo_size > 1) {
2033				u_int	ocount;
2034
2035				ocount = com->obufq.l_tail - ioptr;
2036				if (ocount > com->tx_fifo_size)
2037					ocount = com->tx_fifo_size;
2038				com->bytes_out += ocount;
2039				do
2040					outb(com->data_port, *ioptr++);
2041				while (--ocount != 0);
2042			} else {
2043				outb(com->data_port, *ioptr++);
2044				++com->bytes_out;
2045			}
2046			com->obufq.l_head = ioptr;
2047			if (COM_IIR_TXRDYBUG(com->flags)) {
2048				int_ctl_new = int_ctl | IER_ETXRDY;
2049			}
2050			if (ioptr >= com->obufq.l_tail) {
2051				struct lbq	*qp;
2052
2053				qp = com->obufq.l_next;
2054				qp->l_queued = FALSE;
2055				qp = qp->l_next;
2056				if (qp != NULL) {
2057					com->obufq.l_head = qp->l_head;
2058					com->obufq.l_tail = qp->l_tail;
2059					com->obufq.l_next = qp;
2060				} else {
2061					/* output just completed */
2062					if (COM_IIR_TXRDYBUG(com->flags)) {
2063						int_ctl_new = int_ctl & ~IER_ETXRDY;
2064					}
2065					com->state &= ~CS_BUSY;
2066				}
2067				if (!(com->state & CS_ODONE)) {
2068					com_events += LOTS_OF_EVENTS;
2069					com->state |= CS_ODONE;
2070					/* handle at high level ASAP */
2071					sched_swi(sio_fast_ih, SWI_NOSWITCH);
2072				}
2073			}
2074			if (COM_IIR_TXRDYBUG(com->flags) && (int_ctl != int_ctl_new)) {
2075				outb(com->intr_ctl_port, int_ctl_new);
2076			}
2077		}
2078
2079		/* finished? */
2080#ifndef COM_MULTIPORT
2081		if ((inb(com->int_id_port) & IIR_IMASK) == IIR_NOPEND)
2082#endif /* COM_MULTIPORT */
2083			return;
2084	}
2085}
2086
2087static int
2088sioioctl(dev, cmd, data, flag, p)
2089	dev_t		dev;
2090	u_long		cmd;
2091	caddr_t		data;
2092	int		flag;
2093	struct proc	*p;
2094{
2095	struct com_s	*com;
2096	int		error;
2097	int		mynor;
2098	int		s;
2099	struct tty	*tp;
2100#if defined(COMPAT_43) || defined(COMPAT_SUNOS)
2101	u_long		oldcmd;
2102	struct termios	term;
2103#endif
2104
2105	mynor = minor(dev);
2106	com = com_addr(MINOR_TO_UNIT(mynor));
2107	if (com == NULL || com->gone)
2108		return (ENODEV);
2109	if (mynor & CONTROL_MASK) {
2110		struct termios	*ct;
2111
2112		switch (mynor & CONTROL_MASK) {
2113		case CONTROL_INIT_STATE:
2114			ct = mynor & CALLOUT_MASK ? &com->it_out : &com->it_in;
2115			break;
2116		case CONTROL_LOCK_STATE:
2117			ct = mynor & CALLOUT_MASK ? &com->lt_out : &com->lt_in;
2118			break;
2119		default:
2120			return (ENODEV);	/* /dev/nodev */
2121		}
2122		switch (cmd) {
2123		case TIOCSETA:
2124			error = suser(p);
2125			if (error != 0)
2126				return (error);
2127			*ct = *(struct termios *)data;
2128			return (0);
2129		case TIOCGETA:
2130			*(struct termios *)data = *ct;
2131			return (0);
2132		case TIOCGETD:
2133			*(int *)data = TTYDISC;
2134			return (0);
2135		case TIOCGWINSZ:
2136			bzero(data, sizeof(struct winsize));
2137			return (0);
2138		default:
2139			return (ENOTTY);
2140		}
2141	}
2142	tp = com->tp;
2143#if defined(COMPAT_43) || defined(COMPAT_SUNOS)
2144	term = tp->t_termios;
2145	oldcmd = cmd;
2146	error = ttsetcompat(tp, &cmd, data, &term);
2147	if (error != 0)
2148		return (error);
2149	if (cmd != oldcmd)
2150		data = (caddr_t)&term;
2151#endif
2152	if (cmd == TIOCSETA || cmd == TIOCSETAW || cmd == TIOCSETAF) {
2153		int	cc;
2154		struct termios *dt = (struct termios *)data;
2155		struct termios *lt = mynor & CALLOUT_MASK
2156				     ? &com->lt_out : &com->lt_in;
2157
2158		dt->c_iflag = (tp->t_iflag & lt->c_iflag)
2159			      | (dt->c_iflag & ~lt->c_iflag);
2160		dt->c_oflag = (tp->t_oflag & lt->c_oflag)
2161			      | (dt->c_oflag & ~lt->c_oflag);
2162		dt->c_cflag = (tp->t_cflag & lt->c_cflag)
2163			      | (dt->c_cflag & ~lt->c_cflag);
2164		dt->c_lflag = (tp->t_lflag & lt->c_lflag)
2165			      | (dt->c_lflag & ~lt->c_lflag);
2166		for (cc = 0; cc < NCCS; ++cc)
2167			if (lt->c_cc[cc] != 0)
2168				dt->c_cc[cc] = tp->t_cc[cc];
2169		if (lt->c_ispeed != 0)
2170			dt->c_ispeed = tp->t_ispeed;
2171		if (lt->c_ospeed != 0)
2172			dt->c_ospeed = tp->t_ospeed;
2173	}
2174	error = (*linesw[tp->t_line].l_ioctl)(tp, cmd, data, flag, p);
2175	if (error != ENOIOCTL)
2176		return (error);
2177	s = spltty();
2178	error = ttioctl(tp, cmd, data, flag);
2179	disc_optim(tp, &tp->t_termios, com);
2180	if (error != ENOIOCTL) {
2181		splx(s);
2182		return (error);
2183	}
2184	switch (cmd) {
2185	case TIOCSBRK:
2186		sio_setreg(com, com_cfcr, com->cfcr_image |= CFCR_SBREAK);
2187		break;
2188	case TIOCCBRK:
2189		sio_setreg(com, com_cfcr, com->cfcr_image &= ~CFCR_SBREAK);
2190		break;
2191	case TIOCSDTR:
2192		(void)commctl(com, TIOCM_DTR, DMBIS);
2193		break;
2194	case TIOCCDTR:
2195		(void)commctl(com, TIOCM_DTR, DMBIC);
2196		break;
2197	/*
2198	 * XXX should disallow changing MCR_RTS if CS_RTS_IFLOW is set.  The
2199	 * changes get undone on the next call to comparam().
2200	 */
2201	case TIOCMSET:
2202		(void)commctl(com, *(int *)data, DMSET);
2203		break;
2204	case TIOCMBIS:
2205		(void)commctl(com, *(int *)data, DMBIS);
2206		break;
2207	case TIOCMBIC:
2208		(void)commctl(com, *(int *)data, DMBIC);
2209		break;
2210	case TIOCMGET:
2211		*(int *)data = commctl(com, 0, DMGET);
2212		break;
2213	case TIOCMSDTRWAIT:
2214		/* must be root since the wait applies to following logins */
2215		error = suser(p);
2216		if (error != 0) {
2217			splx(s);
2218			return (error);
2219		}
2220		com->dtr_wait = *(int *)data * hz / 100;
2221		break;
2222	case TIOCMGDTRWAIT:
2223		*(int *)data = com->dtr_wait * 100 / hz;
2224		break;
2225	case TIOCTIMESTAMP:
2226		com->do_timestamp = TRUE;
2227		*(struct timeval *)data = com->timestamp;
2228		break;
2229	case TIOCDCDTIMESTAMP:
2230		com->do_dcd_timestamp = TRUE;
2231		*(struct timeval *)data = com->dcd_timestamp;
2232		break;
2233	default:
2234		splx(s);
2235		error = pps_ioctl(cmd, data, &com->pps);
2236		if (error == ENODEV)
2237			error = ENOTTY;
2238		return (error);
2239	}
2240	splx(s);
2241	return (0);
2242}
2243
2244/* software interrupt handler for SWI_TTY */
2245static void
2246siopoll(void *dummy)
2247{
2248	int		unit;
2249
2250	if (com_events == 0)
2251		return;
2252repeat:
2253	for (unit = 0; unit < sio_numunits; ++unit) {
2254		struct com_s	*com;
2255		int		incc;
2256		struct tty	*tp;
2257
2258		com = com_addr(unit);
2259		if (com == NULL)
2260			continue;
2261		tp = com->tp;
2262		if (tp == NULL || com->gone) {
2263			/*
2264			 * Discard any events related to never-opened or
2265			 * going-away devices.
2266			 */
2267			mtx_lock_spin(&sio_lock);
2268			incc = com->iptr - com->ibuf;
2269			com->iptr = com->ibuf;
2270			if (com->state & CS_CHECKMSR) {
2271				incc += LOTS_OF_EVENTS;
2272				com->state &= ~CS_CHECKMSR;
2273			}
2274			com_events -= incc;
2275			mtx_unlock_spin(&sio_lock);
2276			continue;
2277		}
2278		if (com->iptr != com->ibuf) {
2279			mtx_lock_spin(&sio_lock);
2280			sioinput(com);
2281			mtx_unlock_spin(&sio_lock);
2282		}
2283		if (com->state & CS_CHECKMSR) {
2284			u_char	delta_modem_status;
2285
2286			mtx_lock_spin(&sio_lock);
2287			delta_modem_status = com->last_modem_status
2288					     ^ com->prev_modem_status;
2289			com->prev_modem_status = com->last_modem_status;
2290			com_events -= LOTS_OF_EVENTS;
2291			com->state &= ~CS_CHECKMSR;
2292			mtx_unlock_spin(&sio_lock);
2293			if (delta_modem_status & MSR_DCD)
2294				(*linesw[tp->t_line].l_modem)
2295					(tp, com->prev_modem_status & MSR_DCD);
2296		}
2297		if (com->state & CS_ODONE) {
2298			mtx_lock_spin(&sio_lock);
2299			com_events -= LOTS_OF_EVENTS;
2300			com->state &= ~CS_ODONE;
2301			mtx_unlock_spin(&sio_lock);
2302			if (!(com->state & CS_BUSY)
2303			    && !(com->extra_state & CSE_BUSYCHECK)) {
2304				timeout(siobusycheck, com, hz / 100);
2305				com->extra_state |= CSE_BUSYCHECK;
2306			}
2307			(*linesw[tp->t_line].l_start)(tp);
2308		}
2309		if (com_events == 0)
2310			break;
2311	}
2312	if (com_events >= LOTS_OF_EVENTS)
2313		goto repeat;
2314}
2315
2316static int
2317comparam(tp, t)
2318	struct tty	*tp;
2319	struct termios	*t;
2320{
2321	u_int		cfcr;
2322	int		cflag;
2323	struct com_s	*com;
2324	int		divisor;
2325	u_char		dlbh;
2326	u_char		dlbl;
2327	int		s;
2328	int		unit;
2329
2330	/* do historical conversions */
2331	if (t->c_ispeed == 0)
2332		t->c_ispeed = t->c_ospeed;
2333
2334	/* check requested parameters */
2335	divisor = ttspeedtab(t->c_ospeed, comspeedtab);
2336	if (divisor < 0 || (divisor > 0 && t->c_ispeed != t->c_ospeed))
2337		return (EINVAL);
2338
2339	/* parameters are OK, convert them to the com struct and the device */
2340	unit = DEV_TO_UNIT(tp->t_dev);
2341	com = com_addr(unit);
2342	if (com == NULL)
2343		return (ENODEV);
2344	s = spltty();
2345	if (divisor == 0)
2346		(void)commctl(com, TIOCM_DTR, DMBIC);	/* hang up line */
2347	else
2348		(void)commctl(com, TIOCM_DTR, DMBIS);
2349	cflag = t->c_cflag;
2350	switch (cflag & CSIZE) {
2351	case CS5:
2352		cfcr = CFCR_5BITS;
2353		break;
2354	case CS6:
2355		cfcr = CFCR_6BITS;
2356		break;
2357	case CS7:
2358		cfcr = CFCR_7BITS;
2359		break;
2360	default:
2361		cfcr = CFCR_8BITS;
2362		break;
2363	}
2364	if (cflag & PARENB) {
2365		cfcr |= CFCR_PENAB;
2366		if (!(cflag & PARODD))
2367			cfcr |= CFCR_PEVEN;
2368	}
2369	if (cflag & CSTOPB)
2370		cfcr |= CFCR_STOPB;
2371
2372	if (com->hasfifo && divisor != 0) {
2373		/*
2374		 * Use a fifo trigger level low enough so that the input
2375		 * latency from the fifo is less than about 16 msec and
2376		 * the total latency is less than about 30 msec.  These
2377		 * latencies are reasonable for humans.  Serial comms
2378		 * protocols shouldn't expect anything better since modem
2379		 * latencies are larger.
2380		 */
2381		com->fifo_image = t->c_ospeed <= 4800
2382				  ? FIFO_ENABLE : FIFO_ENABLE | FIFO_RX_HIGH;
2383#ifdef COM_ESP
2384		/*
2385		 * The Hayes ESP card needs the fifo DMA mode bit set
2386		 * in compatibility mode.  If not, it will interrupt
2387		 * for each character received.
2388		 */
2389		if (com->esp)
2390			com->fifo_image |= FIFO_DMA_MODE;
2391#endif
2392		sio_setreg(com, com_fifo, com->fifo_image);
2393	}
2394
2395	/*
2396	 * This returns with interrupts disabled so that we can complete
2397	 * the speed change atomically.  Keeping interrupts disabled is
2398	 * especially important while com_data is hidden.
2399	 */
2400	(void) siosetwater(com, t->c_ispeed);
2401
2402	if (divisor != 0) {
2403		sio_setreg(com, com_cfcr, cfcr | CFCR_DLAB);
2404		/*
2405		 * Only set the divisor registers if they would change,
2406		 * since on some 16550 incompatibles (UMC8669F), setting
2407		 * them while input is arriving them loses sync until
2408		 * data stops arriving.
2409		 */
2410		dlbl = divisor & 0xFF;
2411		if (sio_getreg(com, com_dlbl) != dlbl)
2412			sio_setreg(com, com_dlbl, dlbl);
2413		dlbh = (u_int) divisor >> 8;
2414		if (sio_getreg(com, com_dlbh) != dlbh)
2415			sio_setreg(com, com_dlbh, dlbh);
2416	}
2417
2418	sio_setreg(com, com_cfcr, com->cfcr_image = cfcr);
2419
2420	if (!(tp->t_state & TS_TTSTOP))
2421		com->state |= CS_TTGO;
2422
2423	if (cflag & CRTS_IFLOW) {
2424		if (com->st16650a) {
2425			sio_setreg(com, com_cfcr, 0xbf);
2426			sio_setreg(com, com_fifo,
2427				   sio_getreg(com, com_fifo) | 0x40);
2428		}
2429		com->state |= CS_RTS_IFLOW;
2430		/*
2431		 * If CS_RTS_IFLOW just changed from off to on, the change
2432		 * needs to be propagated to MCR_RTS.  This isn't urgent,
2433		 * so do it later by calling comstart() instead of repeating
2434		 * a lot of code from comstart() here.
2435		 */
2436	} else if (com->state & CS_RTS_IFLOW) {
2437		com->state &= ~CS_RTS_IFLOW;
2438		/*
2439		 * CS_RTS_IFLOW just changed from on to off.  Force MCR_RTS
2440		 * on here, since comstart() won't do it later.
2441		 */
2442		outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
2443		if (com->st16650a) {
2444			sio_setreg(com, com_cfcr, 0xbf);
2445			sio_setreg(com, com_fifo,
2446				   sio_getreg(com, com_fifo) & ~0x40);
2447		}
2448	}
2449
2450
2451	/*
2452	 * Set up state to handle output flow control.
2453	 * XXX - worth handling MDMBUF (DCD) flow control at the lowest level?
2454	 * Now has 10+ msec latency, while CTS flow has 50- usec latency.
2455	 */
2456	com->state |= CS_ODEVREADY;
2457	com->state &= ~CS_CTS_OFLOW;
2458	if (cflag & CCTS_OFLOW) {
2459		com->state |= CS_CTS_OFLOW;
2460		if (!(com->last_modem_status & MSR_CTS))
2461			com->state &= ~CS_ODEVREADY;
2462		if (com->st16650a) {
2463			sio_setreg(com, com_cfcr, 0xbf);
2464			sio_setreg(com, com_fifo,
2465				   sio_getreg(com, com_fifo) | 0x80);
2466		}
2467	} else {
2468		if (com->st16650a) {
2469			sio_setreg(com, com_cfcr, 0xbf);
2470			sio_setreg(com, com_fifo,
2471				   sio_getreg(com, com_fifo) & ~0x80);
2472		}
2473	}
2474
2475	sio_setreg(com, com_cfcr, com->cfcr_image);
2476
2477	/* XXX shouldn't call functions while intrs are disabled. */
2478	disc_optim(tp, t, com);
2479	/*
2480	 * Recover from fiddling with CS_TTGO.  We used to call siointr1()
2481	 * unconditionally, but that defeated the careful discarding of
2482	 * stale input in sioopen().
2483	 */
2484	if (com->state >= (CS_BUSY | CS_TTGO))
2485		siointr1(com);
2486
2487	mtx_unlock_spin(&sio_lock);
2488	splx(s);
2489	comstart(tp);
2490	if (com->ibufold != NULL) {
2491		free(com->ibufold, M_DEVBUF);
2492		com->ibufold = NULL;
2493	}
2494	return (0);
2495}
2496
2497/*
2498 * This function must be called with the sio_lock mutex released and will
2499 * return with it obtained.
2500 */
2501static int
2502siosetwater(com, speed)
2503	struct com_s	*com;
2504	speed_t		speed;
2505{
2506	int		cp4ticks;
2507	u_char		*ibuf;
2508	int		ibufsize;
2509	struct tty	*tp;
2510
2511	/*
2512	 * Make the buffer size large enough to handle a softtty interrupt
2513	 * latency of about 2 ticks without loss of throughput or data
2514	 * (about 3 ticks if input flow control is not used or not honoured,
2515	 * but a bit less for CS5-CS7 modes).
2516	 */
2517	cp4ticks = speed / 10 / hz * 4;
2518	for (ibufsize = 128; ibufsize < cp4ticks;)
2519		ibufsize <<= 1;
2520	if (ibufsize == com->ibufsize) {
2521		mtx_lock_spin(&sio_lock);
2522		return (0);
2523	}
2524
2525	/*
2526	 * Allocate input buffer.  The extra factor of 2 in the size is
2527	 * to allow for an error byte for each input byte.
2528	 */
2529	ibuf = malloc(2 * ibufsize, M_DEVBUF, M_NOWAIT);
2530	if (ibuf == NULL) {
2531		mtx_lock_spin(&sio_lock);
2532		return (ENOMEM);
2533	}
2534
2535	/* Initialize non-critical variables. */
2536	com->ibufold = com->ibuf;
2537	com->ibufsize = ibufsize;
2538	tp = com->tp;
2539	if (tp != NULL) {
2540		tp->t_ififosize = 2 * ibufsize;
2541		tp->t_ispeedwat = (speed_t)-1;
2542		tp->t_ospeedwat = (speed_t)-1;
2543	}
2544
2545	/*
2546	 * Read current input buffer, if any.  Continue with interrupts
2547	 * disabled.
2548	 */
2549	mtx_lock_spin(&sio_lock);
2550	if (com->iptr != com->ibuf)
2551		sioinput(com);
2552
2553	/*-
2554	 * Initialize critical variables, including input buffer watermarks.
2555	 * The external device is asked to stop sending when the buffer
2556	 * exactly reaches high water, or when the high level requests it.
2557	 * The high level is notified immediately (rather than at a later
2558	 * clock tick) when this watermark is reached.
2559	 * The buffer size is chosen so the watermark should almost never
2560	 * be reached.
2561	 * The low watermark is invisibly 0 since the buffer is always
2562	 * emptied all at once.
2563	 */
2564	com->iptr = com->ibuf = ibuf;
2565	com->ibufend = ibuf + ibufsize;
2566	com->ierroff = ibufsize;
2567	com->ihighwater = ibuf + 3 * ibufsize / 4;
2568	return (0);
2569}
2570
2571static void
2572comstart(tp)
2573	struct tty	*tp;
2574{
2575	struct com_s	*com;
2576	int		s;
2577	int		unit;
2578
2579	unit = DEV_TO_UNIT(tp->t_dev);
2580	com = com_addr(unit);
2581	if (com == NULL)
2582		return;
2583	s = spltty();
2584	mtx_lock_spin(&sio_lock);
2585	if (tp->t_state & TS_TTSTOP)
2586		com->state &= ~CS_TTGO;
2587	else
2588		com->state |= CS_TTGO;
2589	if (tp->t_state & TS_TBLOCK) {
2590		if (com->mcr_image & MCR_RTS && com->state & CS_RTS_IFLOW)
2591			outb(com->modem_ctl_port, com->mcr_image &= ~MCR_RTS);
2592	} else {
2593		if (!(com->mcr_image & MCR_RTS) && com->iptr < com->ihighwater
2594		    && com->state & CS_RTS_IFLOW)
2595			outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
2596	}
2597	mtx_unlock_spin(&sio_lock);
2598	if (tp->t_state & (TS_TIMEOUT | TS_TTSTOP)) {
2599		ttwwakeup(tp);
2600		splx(s);
2601		return;
2602	}
2603	if (tp->t_outq.c_cc != 0) {
2604		struct lbq	*qp;
2605		struct lbq	*next;
2606
2607		if (!com->obufs[0].l_queued) {
2608			com->obufs[0].l_tail
2609			    = com->obuf1 + q_to_b(&tp->t_outq, com->obuf1,
2610						  sizeof com->obuf1);
2611			com->obufs[0].l_next = NULL;
2612			com->obufs[0].l_queued = TRUE;
2613			mtx_lock_spin(&sio_lock);
2614			if (com->state & CS_BUSY) {
2615				qp = com->obufq.l_next;
2616				while ((next = qp->l_next) != NULL)
2617					qp = next;
2618				qp->l_next = &com->obufs[0];
2619			} else {
2620				com->obufq.l_head = com->obufs[0].l_head;
2621				com->obufq.l_tail = com->obufs[0].l_tail;
2622				com->obufq.l_next = &com->obufs[0];
2623				com->state |= CS_BUSY;
2624			}
2625			mtx_unlock_spin(&sio_lock);
2626		}
2627		if (tp->t_outq.c_cc != 0 && !com->obufs[1].l_queued) {
2628			com->obufs[1].l_tail
2629			    = com->obuf2 + q_to_b(&tp->t_outq, com->obuf2,
2630						  sizeof com->obuf2);
2631			com->obufs[1].l_next = NULL;
2632			com->obufs[1].l_queued = TRUE;
2633			mtx_lock_spin(&sio_lock);
2634			if (com->state & CS_BUSY) {
2635				qp = com->obufq.l_next;
2636				while ((next = qp->l_next) != NULL)
2637					qp = next;
2638				qp->l_next = &com->obufs[1];
2639			} else {
2640				com->obufq.l_head = com->obufs[1].l_head;
2641				com->obufq.l_tail = com->obufs[1].l_tail;
2642				com->obufq.l_next = &com->obufs[1];
2643				com->state |= CS_BUSY;
2644			}
2645			mtx_unlock_spin(&sio_lock);
2646		}
2647		tp->t_state |= TS_BUSY;
2648	}
2649	mtx_lock_spin(&sio_lock);
2650	if (com->state >= (CS_BUSY | CS_TTGO))
2651		siointr1(com);	/* fake interrupt to start output */
2652	mtx_unlock_spin(&sio_lock);
2653	ttwwakeup(tp);
2654	splx(s);
2655}
2656
2657static void
2658comstop(tp, rw)
2659	struct tty	*tp;
2660	int		rw;
2661{
2662	struct com_s	*com;
2663
2664	com = com_addr(DEV_TO_UNIT(tp->t_dev));
2665	if (com == NULL || com->gone)
2666		return;
2667	mtx_lock_spin(&sio_lock);
2668	if (rw & FWRITE) {
2669		if (com->hasfifo)
2670#ifdef COM_ESP
2671		    /* XXX avoid h/w bug. */
2672		    if (!com->esp)
2673#endif
2674			sio_setreg(com, com_fifo,
2675				   FIFO_XMT_RST | com->fifo_image);
2676		com->obufs[0].l_queued = FALSE;
2677		com->obufs[1].l_queued = FALSE;
2678		if (com->state & CS_ODONE)
2679			com_events -= LOTS_OF_EVENTS;
2680		com->state &= ~(CS_ODONE | CS_BUSY);
2681		com->tp->t_state &= ~TS_BUSY;
2682	}
2683	if (rw & FREAD) {
2684		if (com->hasfifo)
2685#ifdef COM_ESP
2686		    /* XXX avoid h/w bug. */
2687		    if (!com->esp)
2688#endif
2689			sio_setreg(com, com_fifo,
2690				   FIFO_RCV_RST | com->fifo_image);
2691		com_events -= (com->iptr - com->ibuf);
2692		com->iptr = com->ibuf;
2693	}
2694	mtx_unlock_spin(&sio_lock);
2695	comstart(tp);
2696}
2697
2698static int
2699commctl(com, bits, how)
2700	struct com_s	*com;
2701	int		bits;
2702	int		how;
2703{
2704	int	mcr;
2705	int	msr;
2706
2707	if (how == DMGET) {
2708		bits = TIOCM_LE;	/* XXX - always enabled while open */
2709		mcr = com->mcr_image;
2710		if (mcr & MCR_DTR)
2711			bits |= TIOCM_DTR;
2712		if (mcr & MCR_RTS)
2713			bits |= TIOCM_RTS;
2714		msr = com->prev_modem_status;
2715		if (msr & MSR_CTS)
2716			bits |= TIOCM_CTS;
2717		if (msr & MSR_DCD)
2718			bits |= TIOCM_CD;
2719		if (msr & MSR_DSR)
2720			bits |= TIOCM_DSR;
2721		/*
2722		 * XXX - MSR_RI is naturally volatile, and we make MSR_TERI
2723		 * more volatile by reading the modem status a lot.  Perhaps
2724		 * we should latch both bits until the status is read here.
2725		 */
2726		if (msr & (MSR_RI | MSR_TERI))
2727			bits |= TIOCM_RI;
2728		return (bits);
2729	}
2730	mcr = 0;
2731	if (bits & TIOCM_DTR)
2732		mcr |= MCR_DTR;
2733	if (bits & TIOCM_RTS)
2734		mcr |= MCR_RTS;
2735	if (com->gone)
2736		return(0);
2737	mtx_lock_spin(&sio_lock);
2738	switch (how) {
2739	case DMSET:
2740		outb(com->modem_ctl_port,
2741		     com->mcr_image = mcr | (com->mcr_image & MCR_IENABLE));
2742		break;
2743	case DMBIS:
2744		outb(com->modem_ctl_port, com->mcr_image |= mcr);
2745		break;
2746	case DMBIC:
2747		outb(com->modem_ctl_port, com->mcr_image &= ~mcr);
2748		break;
2749	}
2750	mtx_unlock_spin(&sio_lock);
2751	return (0);
2752}
2753
2754static void
2755siosettimeout()
2756{
2757	struct com_s	*com;
2758	bool_t		someopen;
2759	int		unit;
2760
2761	/*
2762	 * Set our timeout period to 1 second if no polled devices are open.
2763	 * Otherwise set it to max(1/200, 1/hz).
2764	 * Enable timeouts iff some device is open.
2765	 */
2766	untimeout(comwakeup, (void *)NULL, sio_timeout_handle);
2767	sio_timeout = hz;
2768	someopen = FALSE;
2769	for (unit = 0; unit < sio_numunits; ++unit) {
2770		com = com_addr(unit);
2771		if (com != NULL && com->tp != NULL
2772		    && com->tp->t_state & TS_ISOPEN && !com->gone) {
2773			someopen = TRUE;
2774			if (com->poll || com->poll_output) {
2775				sio_timeout = hz > 200 ? hz / 200 : 1;
2776				break;
2777			}
2778		}
2779	}
2780	if (someopen) {
2781		sio_timeouts_until_log = hz / sio_timeout;
2782		sio_timeout_handle = timeout(comwakeup, (void *)NULL,
2783					     sio_timeout);
2784	} else {
2785		/* Flush error messages, if any. */
2786		sio_timeouts_until_log = 1;
2787		comwakeup((void *)NULL);
2788		untimeout(comwakeup, (void *)NULL, sio_timeout_handle);
2789	}
2790}
2791
2792static void
2793comwakeup(chan)
2794	void	*chan;
2795{
2796	struct com_s	*com;
2797	int		unit;
2798
2799	sio_timeout_handle = timeout(comwakeup, (void *)NULL, sio_timeout);
2800
2801	/*
2802	 * Recover from lost output interrupts.
2803	 * Poll any lines that don't use interrupts.
2804	 */
2805	for (unit = 0; unit < sio_numunits; ++unit) {
2806		com = com_addr(unit);
2807		if (com != NULL && !com->gone
2808		    && (com->state >= (CS_BUSY | CS_TTGO) || com->poll)) {
2809			mtx_lock_spin(&sio_lock);
2810			siointr1(com);
2811			mtx_unlock_spin(&sio_lock);
2812		}
2813	}
2814
2815	/*
2816	 * Check for and log errors, but not too often.
2817	 */
2818	if (--sio_timeouts_until_log > 0)
2819		return;
2820	sio_timeouts_until_log = hz / sio_timeout;
2821	for (unit = 0; unit < sio_numunits; ++unit) {
2822		int	errnum;
2823
2824		com = com_addr(unit);
2825		if (com == NULL)
2826			continue;
2827		if (com->gone)
2828			continue;
2829		for (errnum = 0; errnum < CE_NTYPES; ++errnum) {
2830			u_int	delta;
2831			u_long	total;
2832
2833			mtx_lock_spin(&sio_lock);
2834			delta = com->delta_error_counts[errnum];
2835			com->delta_error_counts[errnum] = 0;
2836			mtx_unlock_spin(&sio_lock);
2837			if (delta == 0)
2838				continue;
2839			total = com->error_counts[errnum] += delta;
2840			log(LOG_ERR, "sio%d: %u more %s%s (total %lu)\n",
2841			    unit, delta, error_desc[errnum],
2842			    delta == 1 ? "" : "s", total);
2843		}
2844	}
2845}
2846
2847static void
2848disc_optim(tp, t, com)
2849	struct tty	*tp;
2850	struct termios	*t;
2851	struct com_s	*com;
2852{
2853	if (!(t->c_iflag & (ICRNL | IGNCR | IMAXBEL | INLCR | ISTRIP | IXON))
2854	    && (!(t->c_iflag & BRKINT) || (t->c_iflag & IGNBRK))
2855	    && (!(t->c_iflag & PARMRK)
2856		|| (t->c_iflag & (IGNPAR | IGNBRK)) == (IGNPAR | IGNBRK))
2857	    && !(t->c_lflag & (ECHO | ICANON | IEXTEN | ISIG | PENDIN))
2858	    && linesw[tp->t_line].l_rint == ttyinput)
2859		tp->t_state |= TS_CAN_BYPASS_L_RINT;
2860	else
2861		tp->t_state &= ~TS_CAN_BYPASS_L_RINT;
2862	com->hotchar = linesw[tp->t_line].l_hotchar;
2863}
2864
2865/*
2866 * Following are all routines needed for SIO to act as console
2867 */
2868#include <sys/cons.h>
2869
2870struct siocnstate {
2871	u_char	dlbl;
2872	u_char	dlbh;
2873	u_char	ier;
2874	u_char	cfcr;
2875	u_char	mcr;
2876};
2877
2878#ifndef __alpha__
2879static speed_t siocngetspeed __P((Port_t, struct speedtab *));
2880#endif
2881static void siocnclose	__P((struct siocnstate *sp, Port_t iobase));
2882static void siocnopen	__P((struct siocnstate *sp, Port_t iobase, int speed));
2883static void siocntxwait	__P((Port_t iobase));
2884
2885#ifdef __alpha__
2886int siocnattach __P((int port, int speed));
2887int siogdbattach __P((int port, int speed));
2888int siogdbgetc __P((void));
2889void siogdbputc __P((int c));
2890#else
2891static cn_probe_t siocnprobe;
2892static cn_init_t siocninit;
2893#endif
2894static cn_checkc_t siocncheckc;
2895static cn_getc_t siocngetc;
2896static cn_putc_t siocnputc;
2897
2898#ifdef __i386__
2899CONS_DRIVER(sio, siocnprobe, siocninit, NULL, siocngetc, siocncheckc,
2900	    siocnputc, NULL);
2901#endif
2902
2903/* To get the GDB related variables */
2904#if DDB > 0
2905#include <ddb/ddb.h>
2906#endif
2907
2908static void
2909siocntxwait(iobase)
2910	Port_t	iobase;
2911{
2912	int	timo;
2913
2914	/*
2915	 * Wait for any pending transmission to finish.  Required to avoid
2916	 * the UART lockup bug when the speed is changed, and for normal
2917	 * transmits.
2918	 */
2919	timo = 100000;
2920	while ((inb(iobase + com_lsr) & (LSR_TSRE | LSR_TXRDY))
2921	       != (LSR_TSRE | LSR_TXRDY) && --timo != 0)
2922		;
2923}
2924
2925#ifndef __alpha__
2926
2927/*
2928 * Read the serial port specified and try to figure out what speed
2929 * it's currently running at.  We're assuming the serial port has
2930 * been initialized and is basicly idle.  This routine is only intended
2931 * to be run at system startup.
2932 *
2933 * If the value read from the serial port doesn't make sense, return 0.
2934 */
2935
2936static speed_t
2937siocngetspeed(iobase, table)
2938	Port_t iobase;
2939	struct speedtab *table;
2940{
2941	int	code;
2942	u_char	dlbh;
2943	u_char	dlbl;
2944	u_char  cfcr;
2945
2946	cfcr = inb(iobase + com_cfcr);
2947	outb(iobase + com_cfcr, CFCR_DLAB | cfcr);
2948
2949	dlbl = inb(iobase + com_dlbl);
2950	dlbh = inb(iobase + com_dlbh);
2951
2952	outb(iobase + com_cfcr, cfcr);
2953
2954	code = dlbh << 8 | dlbl;
2955
2956	for (; table->sp_speed != -1; table++)
2957		if (table->sp_code == code)
2958			return (table->sp_speed);
2959
2960	return (0);	/* didn't match anything sane */
2961}
2962
2963#endif
2964
2965static void
2966siocnopen(sp, iobase, speed)
2967	struct siocnstate	*sp;
2968	Port_t			iobase;
2969	int			speed;
2970{
2971	int	divisor;
2972	u_char	dlbh;
2973	u_char	dlbl;
2974
2975	/*
2976	 * Save all the device control registers except the fifo register
2977	 * and set our default ones (cs8 -parenb speed=comdefaultrate).
2978	 * We can't save the fifo register since it is read-only.
2979	 */
2980	sp->ier = inb(iobase + com_ier);
2981	outb(iobase + com_ier, 0);	/* spltty() doesn't stop siointr() */
2982	siocntxwait(iobase);
2983	sp->cfcr = inb(iobase + com_cfcr);
2984	outb(iobase + com_cfcr, CFCR_DLAB | CFCR_8BITS);
2985	sp->dlbl = inb(iobase + com_dlbl);
2986	sp->dlbh = inb(iobase + com_dlbh);
2987	/*
2988	 * Only set the divisor registers if they would change, since on
2989	 * some 16550 incompatibles (Startech), setting them clears the
2990	 * data input register.  This also reduces the effects of the
2991	 * UMC8669F bug.
2992	 */
2993	divisor = ttspeedtab(speed, comspeedtab);
2994	dlbl = divisor & 0xFF;
2995	if (sp->dlbl != dlbl)
2996		outb(iobase + com_dlbl, dlbl);
2997	dlbh = (u_int) divisor >> 8;
2998	if (sp->dlbh != dlbh)
2999		outb(iobase + com_dlbh, dlbh);
3000	outb(iobase + com_cfcr, CFCR_8BITS);
3001	sp->mcr = inb(iobase + com_mcr);
3002	/*
3003	 * We don't want interrupts, but must be careful not to "disable"
3004	 * them by clearing the MCR_IENABLE bit, since that might cause
3005	 * an interrupt by floating the IRQ line.
3006	 */
3007	outb(iobase + com_mcr, (sp->mcr & MCR_IENABLE) | MCR_DTR | MCR_RTS);
3008}
3009
3010static void
3011siocnclose(sp, iobase)
3012	struct siocnstate	*sp;
3013	Port_t			iobase;
3014{
3015	/*
3016	 * Restore the device control registers.
3017	 */
3018	siocntxwait(iobase);
3019	outb(iobase + com_cfcr, CFCR_DLAB | CFCR_8BITS);
3020	if (sp->dlbl != inb(iobase + com_dlbl))
3021		outb(iobase + com_dlbl, sp->dlbl);
3022	if (sp->dlbh != inb(iobase + com_dlbh))
3023		outb(iobase + com_dlbh, sp->dlbh);
3024	outb(iobase + com_cfcr, sp->cfcr);
3025	/*
3026	 * XXX damp oscillations of MCR_DTR and MCR_RTS by not restoring them.
3027	 */
3028	outb(iobase + com_mcr, sp->mcr | MCR_DTR | MCR_RTS);
3029	outb(iobase + com_ier, sp->ier);
3030}
3031
3032#ifndef __alpha__
3033
3034static void
3035siocnprobe(cp)
3036	struct consdev	*cp;
3037{
3038	speed_t			boot_speed;
3039	u_char			cfcr;
3040	int			s, unit;
3041	struct siocnstate	sp;
3042
3043	/*
3044	 * Find our first enabled console, if any.  If it is a high-level
3045	 * console device, then initialize it and return successfully.
3046	 * If it is a low-level console device, then initialize it and
3047	 * return unsuccessfully.  It must be initialized in both cases
3048	 * for early use by console drivers and debuggers.  Initializing
3049	 * the hardware is not necessary in all cases, since the i/o
3050	 * routines initialize it on the fly, but it is necessary if
3051	 * input might arrive while the hardware is switched back to an
3052	 * uninitialized state.  We can't handle multiple console devices
3053	 * yet because our low-level routines don't take a device arg.
3054	 * We trust the user to set the console flags properly so that we
3055	 * don't need to probe.
3056	 */
3057	cp->cn_pri = CN_DEAD;
3058
3059	for (unit = 0; unit < 16; unit++) { /* XXX need to know how many */
3060		int flags;
3061		int disabled;
3062		if (resource_int_value("sio", unit, "disabled", &disabled) == 0) {
3063			if (disabled)
3064				continue;
3065		}
3066		if (resource_int_value("sio", unit, "flags", &flags))
3067			continue;
3068		if (COM_CONSOLE(flags) || COM_DEBUGGER(flags)) {
3069			int port;
3070			Port_t iobase;
3071
3072			if (resource_int_value("sio", unit, "port", &port))
3073				continue;
3074			iobase = port;
3075			s = spltty();
3076			if (boothowto & RB_SERIAL) {
3077				boot_speed = siocngetspeed(iobase, comspeedtab);
3078				if (boot_speed)
3079					comdefaultrate = boot_speed;
3080			}
3081
3082			/*
3083			 * Initialize the divisor latch.  We can't rely on
3084			 * siocnopen() to do this the first time, since it
3085			 * avoids writing to the latch if the latch appears
3086			 * to have the correct value.  Also, if we didn't
3087			 * just read the speed from the hardware, then we
3088			 * need to set the speed in hardware so that
3089			 * switching it later is null.
3090			 */
3091			cfcr = inb(iobase + com_cfcr);
3092			outb(iobase + com_cfcr, CFCR_DLAB | cfcr);
3093			outb(iobase + com_dlbl,
3094			     COMBRD(comdefaultrate) & 0xff);
3095			outb(iobase + com_dlbh,
3096			     (u_int) COMBRD(comdefaultrate) >> 8);
3097			outb(iobase + com_cfcr, cfcr);
3098
3099			siocnopen(&sp, iobase, comdefaultrate);
3100
3101			splx(s);
3102			if (COM_CONSOLE(flags) && !COM_LLCONSOLE(flags)) {
3103				cp->cn_dev = makedev(CDEV_MAJOR, unit);
3104				cp->cn_pri = COM_FORCECONSOLE(flags)
3105					     || boothowto & RB_SERIAL
3106					     ? CN_REMOTE : CN_NORMAL;
3107				siocniobase = iobase;
3108				siocnunit = unit;
3109			}
3110			if (COM_DEBUGGER(flags)) {
3111				printf("sio%d: gdb debugging port\n", unit);
3112				siogdbiobase = iobase;
3113				siogdbunit = unit;
3114#if DDB > 0
3115				gdbdev = makedev(CDEV_MAJOR, unit);
3116				gdb_getc = siocngetc;
3117				gdb_putc = siocnputc;
3118#endif
3119			}
3120		}
3121	}
3122#ifdef	__i386__
3123#if DDB > 0
3124	/*
3125	 * XXX Ugly Compatability.
3126	 * If no gdb port has been specified, set it to be the console
3127	 * as some configuration files don't specify the gdb port.
3128	 */
3129	if (gdbdev == NODEV && (boothowto & RB_GDB)) {
3130		printf("Warning: no GDB port specified. Defaulting to sio%d.\n",
3131			siocnunit);
3132		printf("Set flag 0x80 on desired GDB port in your\n");
3133		printf("configuration file (currently sio only).\n");
3134		siogdbiobase = siocniobase;
3135		siogdbunit = siocnunit;
3136		gdbdev = makedev(CDEV_MAJOR, siocnunit);
3137		gdb_getc = siocngetc;
3138		gdb_putc = siocnputc;
3139	}
3140#endif
3141#endif
3142}
3143
3144static void
3145siocninit(cp)
3146	struct consdev	*cp;
3147{
3148	comconsole = DEV_TO_UNIT(cp->cn_dev);
3149}
3150
3151#endif
3152
3153#ifdef __alpha__
3154
3155CONS_DRIVER(sio, NULL, NULL, NULL, siocngetc, siocncheckc, siocnputc, NULL);
3156
3157int
3158siocnattach(port, speed)
3159	int port;
3160	int speed;
3161{
3162	int			s;
3163	u_char			cfcr;
3164	struct siocnstate	sp;
3165
3166	siocniobase = port;
3167	comdefaultrate = speed;
3168	sio_consdev.cn_pri = CN_NORMAL;
3169	sio_consdev.cn_dev = makedev(CDEV_MAJOR, 0);
3170
3171	s = spltty();
3172
3173	/*
3174	 * Initialize the divisor latch.  We can't rely on
3175	 * siocnopen() to do this the first time, since it
3176	 * avoids writing to the latch if the latch appears
3177	 * to have the correct value.  Also, if we didn't
3178	 * just read the speed from the hardware, then we
3179	 * need to set the speed in hardware so that
3180	 * switching it later is null.
3181	 */
3182	cfcr = inb(siocniobase + com_cfcr);
3183	outb(siocniobase + com_cfcr, CFCR_DLAB | cfcr);
3184	outb(siocniobase + com_dlbl,
3185	     COMBRD(comdefaultrate) & 0xff);
3186	outb(siocniobase + com_dlbh,
3187	     (u_int) COMBRD(comdefaultrate) >> 8);
3188	outb(siocniobase + com_cfcr, cfcr);
3189
3190	siocnopen(&sp, siocniobase, comdefaultrate);
3191	splx(s);
3192
3193	cn_tab = &sio_consdev;
3194	return (0);
3195}
3196
3197int
3198siogdbattach(port, speed)
3199	int port;
3200	int speed;
3201{
3202	int			s;
3203	u_char			cfcr;
3204	struct siocnstate	sp;
3205	int			unit = 1;	/* XXX !!! */
3206
3207	siogdbiobase = port;
3208	gdbdefaultrate = speed;
3209
3210	printf("sio%d: gdb debugging port\n", unit);
3211	siogdbunit = unit;
3212#if DDB > 0
3213	gdbdev = makedev(CDEV_MAJOR, unit);
3214	gdb_getc = siocngetc;
3215	gdb_putc = siocnputc;
3216#endif
3217
3218	s = spltty();
3219
3220	/*
3221	 * Initialize the divisor latch.  We can't rely on
3222	 * siocnopen() to do this the first time, since it
3223	 * avoids writing to the latch if the latch appears
3224	 * to have the correct value.  Also, if we didn't
3225	 * just read the speed from the hardware, then we
3226	 * need to set the speed in hardware so that
3227	 * switching it later is null.
3228	 */
3229	cfcr = inb(siogdbiobase + com_cfcr);
3230	outb(siogdbiobase + com_cfcr, CFCR_DLAB | cfcr);
3231	outb(siogdbiobase + com_dlbl,
3232	     COMBRD(gdbdefaultrate) & 0xff);
3233	outb(siogdbiobase + com_dlbh,
3234	     (u_int) COMBRD(gdbdefaultrate) >> 8);
3235	outb(siogdbiobase + com_cfcr, cfcr);
3236
3237	siocnopen(&sp, siogdbiobase, gdbdefaultrate);
3238	splx(s);
3239
3240	return (0);
3241}
3242
3243#endif
3244
3245static int
3246siocncheckc(dev)
3247	dev_t	dev;
3248{
3249	int	c;
3250	Port_t	iobase;
3251	int	s;
3252	struct siocnstate	sp;
3253
3254	if (minor(dev) == siogdbunit)
3255		iobase = siogdbiobase;
3256	else
3257		iobase = siocniobase;
3258	s = spltty();
3259	siocnopen(&sp, iobase, comdefaultrate);
3260	if (inb(iobase + com_lsr) & LSR_RXRDY)
3261		c = inb(iobase + com_data);
3262	else
3263		c = -1;
3264	siocnclose(&sp, iobase);
3265	splx(s);
3266	return (c);
3267}
3268
3269
3270int
3271siocngetc(dev)
3272	dev_t	dev;
3273{
3274	int	c;
3275	Port_t	iobase;
3276	int	s;
3277	struct siocnstate	sp;
3278
3279	if (minor(dev) == siogdbunit)
3280		iobase = siogdbiobase;
3281	else
3282		iobase = siocniobase;
3283	s = spltty();
3284	siocnopen(&sp, iobase, comdefaultrate);
3285	while (!(inb(iobase + com_lsr) & LSR_RXRDY))
3286		;
3287	c = inb(iobase + com_data);
3288	siocnclose(&sp, iobase);
3289	splx(s);
3290	return (c);
3291}
3292
3293void
3294siocnputc(dev, c)
3295	dev_t	dev;
3296	int	c;
3297{
3298	int	s;
3299	struct siocnstate	sp;
3300	Port_t	iobase;
3301
3302	if (minor(dev) == siogdbunit)
3303		iobase = siogdbiobase;
3304	else
3305		iobase = siocniobase;
3306	s = spltty();
3307	siocnopen(&sp, iobase, comdefaultrate);
3308	siocntxwait(iobase);
3309	outb(iobase + com_data, c);
3310	siocnclose(&sp, iobase);
3311	splx(s);
3312}
3313
3314#ifdef __alpha__
3315int
3316siogdbgetc()
3317{
3318	int	c;
3319	Port_t	iobase;
3320	int	s;
3321	struct siocnstate	sp;
3322
3323	iobase = siogdbiobase;
3324	s = spltty();
3325	siocnopen(&sp, iobase, gdbdefaultrate);
3326	while (!(inb(iobase + com_lsr) & LSR_RXRDY))
3327		;
3328	c = inb(iobase + com_data);
3329	siocnclose(&sp, iobase);
3330	splx(s);
3331	return (c);
3332}
3333
3334void
3335siogdbputc(c)
3336	int	c;
3337{
3338	int	s;
3339	struct siocnstate	sp;
3340
3341	s = spltty();
3342	siocnopen(&sp, siogdbiobase, gdbdefaultrate);
3343	siocntxwait(siogdbiobase);
3344	outb(siogdbiobase + com_data, c);
3345	siocnclose(&sp, siogdbiobase);
3346	splx(s);
3347}
3348#endif
3349
3350DRIVER_MODULE(sio, isa, sio_isa_driver, sio_devclass, 0, 0);
3351#if NCARD > 0
3352DRIVER_MODULE(sio, pccard, sio_pccard_driver, sio_devclass, 0, 0);
3353#endif
3354#if NPCI > 0
3355DRIVER_MODULE(sio, pci, sio_pci_driver, sio_devclass, 0, 0);
3356#endif
3357