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