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