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