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