sio.c revision 57769
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 57769 2000-03-05 14:44:05Z peter $
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	{0x3024a341, NULL},	/* PMC2430 - Pace 56 Voice Internal Modem */
576	{0x1000eb49, NULL},	/* ROK0010 - Rockwell ? */
577	{0x5002734a, NULL},	/* RSS0250 - 5614Jx3(G) Internal Modem */
578	{0xc100ad4d, NULL},	/* SMM00C1 - Leopard 56k PnP */
579	{0x9012b04e, NULL},	/* SUP1290 - Supra ? */
580	{0x1013b04e, NULL},	/* SUP1310 - SupraExpress 336i PnP */
581	{0x8013b04e, NULL},	/* SUP1380 - SupraExpress 288i PnP Voice */
582	{0x8113b04e, NULL},	/* SUP1381 - SupraExpress 336i PnP Voice */
583	{0x5016b04e, NULL},	/* SUP1650 - Supra 336i Sp Intl */
584	{0x7420b04e, NULL},	/* SUP2070 - Supra ? */
585	{0x8020b04e, NULL},	/* SUP2080 - Supra ? */
586	{0x8420b04e, NULL},	/* SUP2084 - SupraExpress 56i PnP */
587	{0x7121b04e, NULL},	/* SUP2171 - SupraExpress 56i Sp? */
588	{0x8024b04e, NULL},	/* SUP2480 - Supra ? */
589	{0x01007256, NULL},	/* USR0001 - U.S. Robotics Inc., Sportster W */
590	{0x02007256, NULL},	/* USR0002 - U.S. Robotics Inc. Sportster 33. */
591	{0x04007256, NULL},	/* USR0004 - USR Sportster 14.4k */
592	{0x06007256, NULL},	/* USR0006 - USR Sportster 33.6k */
593	{0x11007256, NULL},	/* USR0011 - USR ? */
594	{0x01017256, NULL},	/* USR0101 - USR ? */
595	{0x30207256, NULL},	/* USR2030 - U.S.Robotics Inc. Sportster 560 */
596	{0x50207256, NULL},	/* USR2050 - U.S.Robotics Inc. Sportster 33. */
597	{0x70207256, NULL},	/* USR2070 - U.S.Robotics Inc. Sportster 560 */
598	{0x30307256, NULL},	/* USR3030 - U.S. Robotics 56K FAX INT */
599	{0x31307256, NULL},	/* USR3031 - U.S. Robotics 56K FAX INT */
600	{0x70307256, NULL},	/* USR3070 - U.S. Robotics 56K Voice INT */
601	{0x90307256, NULL},	/* USR3090 - USR ? */
602	{0x90917256, NULL},	/* USR9190 - USR 56k Voice INT */
603	{0x0300695c, NULL},	/* WCI0003 - Fax/Voice/Modem/Speakphone/Asvd */
604	{0x61f7896a, NULL},	/* ZTIF761 - Zoom ComStar 33.6 */
605	{0}
606};
607
608
609
610static int
611sio_isa_probe(dev)
612	device_t	dev;
613{
614	/* Check isapnp ids */
615	if (ISA_PNP_PROBE(device_get_parent(dev), dev, sio_ids) == ENXIO)
616		return (ENXIO);
617	return (sioprobe(dev));
618}
619
620static int
621sioprobe(dev)
622	device_t	dev;
623{
624#if 0
625	static bool_t	already_init;
626	device_t	xdev;
627#endif
628	bool_t		failures[10];
629	int		fn;
630	device_t	idev;
631	Port_t		iobase;
632	intrmask_t	irqmap[4];
633	intrmask_t	irqs;
634	u_char		mcr_image;
635	int		result;
636	u_long		xirq;
637	u_int		flags = device_get_flags(dev);
638	int		rid;
639	struct resource *port;
640
641	rid = 0;
642	port = bus_alloc_resource(dev, SYS_RES_IOPORT, &rid,
643				  0, ~0, IO_COMSIZE, RF_ACTIVE);
644	if (!port)
645		return ENXIO;
646
647#if 0
648	/*
649	 * XXX this is broken - when we are first called, there are no
650	 * previously configured IO ports.  We could hard code
651	 * 0x3f8, 0x2f8, 0x3e8, 0x2e8 etc but that's probably worse.
652	 * This code has been doing nothing since the conversion since
653	 * "count" is zero the first time around.
654	 */
655	if (!already_init) {
656		/*
657		 * Turn off MCR_IENABLE for all likely serial ports.  An unused
658		 * port with its MCR_IENABLE gate open will inhibit interrupts
659		 * from any used port that shares the interrupt vector.
660		 * XXX the gate enable is elsewhere for some multiports.
661		 */
662		device_t *devs;
663		int count, i, xioport;
664
665		devclass_get_devices(sio_devclass, &devs, &count);
666		for (i = 0; i < count; i++) {
667			xdev = devs[i];
668			if (device_is_enabled(xdev) &&
669			    bus_get_resource(xdev, SYS_RES_IOPORT, 0, &xioport,
670					     NULL) == 0)
671				outb(xioport + com_mcr, 0);
672		}
673		free(devs, M_TEMP);
674		already_init = TRUE;
675	}
676#endif
677
678	if (COM_LLCONSOLE(flags)) {
679		printf("sio%d: reserved for low-level i/o\n",
680		       device_get_unit(dev));
681		bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
682		return (ENXIO);
683	}
684
685	/*
686	 * If the device is on a multiport card and has an AST/4
687	 * compatible interrupt control register, initialize this
688	 * register and prepare to leave MCR_IENABLE clear in the mcr.
689	 * Otherwise, prepare to set MCR_IENABLE in the mcr.
690	 * Point idev to the device struct giving the correct id_irq.
691	 * This is the struct for the master device if there is one.
692	 */
693	idev = dev;
694	mcr_image = MCR_IENABLE;
695#ifdef COM_MULTIPORT
696	if (COM_ISMULTIPORT(flags)) {
697		Port_t xiobase;
698		u_long io;
699
700		idev = devclass_get_device(sio_devclass, COM_MPMASTER(flags));
701		if (idev == NULL) {
702			printf("sio%d: master device %d not configured\n",
703			       device_get_unit(dev), COM_MPMASTER(flags));
704			idev = dev;
705		}
706		if (!COM_NOTAST4(flags)) {
707			if (bus_get_resource(idev, SYS_RES_IOPORT, 0, &io,
708					     NULL) == 0) {
709				xiobase = io;
710				if (bus_get_resource(idev, SYS_RES_IRQ, 0,
711				    NULL, NULL) == 0)
712					outb(xiobase + com_scr, 0x80);
713				else
714					outb(xiobase + com_scr, 0);
715			}
716			mcr_image = 0;
717		}
718	}
719#endif /* COM_MULTIPORT */
720	if (bus_get_resource(idev, SYS_RES_IRQ, 0, NULL, NULL) != 0)
721		mcr_image = 0;
722
723	bzero(failures, sizeof failures);
724	iobase = rman_get_start(port);
725
726	/*
727	 * We don't want to get actual interrupts, just masked ones.
728	 * Interrupts from this line should already be masked in the ICU,
729	 * but mask them in the processor as well in case there are some
730	 * (misconfigured) shared interrupts.
731	 */
732	disable_intr();
733/* EXTRA DELAY? */
734
735	/*
736	 * Initialize the speed and the word size and wait long enough to
737	 * drain the maximum of 16 bytes of junk in device output queues.
738	 * The speed is undefined after a master reset and must be set
739	 * before relying on anything related to output.  There may be
740	 * junk after a (very fast) soft reboot and (apparently) after
741	 * master reset.
742	 * XXX what about the UART bug avoided by waiting in comparam()?
743	 * We don't want to to wait long enough to drain at 2 bps.
744	 */
745	if (iobase == siocniobase)
746		DELAY((16 + 1) * 1000000 / (comdefaultrate / 10));
747	else {
748		outb(iobase + com_cfcr, CFCR_DLAB | CFCR_8BITS);
749		outb(iobase + com_dlbl, COMBRD(SIO_TEST_SPEED) & 0xff);
750		outb(iobase + com_dlbh, (u_int) COMBRD(SIO_TEST_SPEED) >> 8);
751		outb(iobase + com_cfcr, CFCR_8BITS);
752		DELAY((16 + 1) * 1000000 / (SIO_TEST_SPEED / 10));
753	}
754
755	/*
756	 * Enable the interrupt gate and disable device interupts.  This
757	 * should leave the device driving the interrupt line low and
758	 * guarantee an edge trigger if an interrupt can be generated.
759	 */
760/* EXTRA DELAY? */
761	outb(iobase + com_mcr, mcr_image);
762	outb(iobase + com_ier, 0);
763	DELAY(1000);		/* XXX */
764	irqmap[0] = isa_irq_pending();
765
766	/*
767	 * Attempt to set loopback mode so that we can send a null byte
768	 * without annoying any external device.
769	 */
770/* EXTRA DELAY? */
771	outb(iobase + com_mcr, mcr_image | MCR_LOOPBACK);
772
773	/*
774	 * Attempt to generate an output interrupt.  On 8250's, setting
775	 * IER_ETXRDY generates an interrupt independent of the current
776	 * setting and independent of whether the THR is empty.  On 16450's,
777	 * setting IER_ETXRDY generates an interrupt independent of the
778	 * current setting.  On 16550A's, setting IER_ETXRDY only
779	 * generates an interrupt when IER_ETXRDY is not already set.
780	 */
781	outb(iobase + com_ier, IER_ETXRDY);
782
783	/*
784	 * On some 16x50 incompatibles, setting IER_ETXRDY doesn't generate
785	 * an interrupt.  They'd better generate one for actually doing
786	 * output.  Loopback may be broken on the same incompatibles but
787	 * it's unlikely to do more than allow the null byte out.
788	 */
789	outb(iobase + com_data, 0);
790	DELAY((1 + 2) * 1000000 / (SIO_TEST_SPEED / 10));
791
792	/*
793	 * Turn off loopback mode so that the interrupt gate works again
794	 * (MCR_IENABLE was hidden).  This should leave the device driving
795	 * an interrupt line high.  It doesn't matter if the interrupt
796	 * line oscillates while we are not looking at it, since interrupts
797	 * are disabled.
798	 */
799/* EXTRA DELAY? */
800	outb(iobase + com_mcr, mcr_image);
801
802	/*
803	 * Some pcmcia cards have the "TXRDY bug", so we check everyone
804	 * for IIR_TXRDY implementation ( Palido 321s, DC-1S... )
805	 */
806	if (COM_NOPROBE(flags)) {
807		/* Reading IIR register twice */
808		for (fn = 0; fn < 2; fn ++) {
809			DELAY(10000);
810			failures[6] = inb(iobase + com_iir);
811		}
812		/* Check IIR_TXRDY clear ? */
813		result = 0;
814		if (failures[6] & IIR_TXRDY) {
815			/* Nop, Double check with clearing IER */
816			outb(iobase + com_ier, 0);
817			if (inb(iobase + com_iir) & IIR_NOPEND) {
818				/* Ok. we're familia this gang */
819				SET_FLAG(dev, COM_C_IIR_TXRDYBUG);
820			} else {
821				/* Unknown, Just omit this chip.. XXX */
822				result = ENXIO;
823			}
824		} else {
825			/* OK. this is well-known guys */
826			CLR_FLAG(dev, COM_C_IIR_TXRDYBUG);
827		}
828		outb(iobase + com_cfcr, CFCR_8BITS);
829		enable_intr();
830		bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
831		return (iobase == siocniobase ? 0 : result);
832	}
833
834	/*
835	 * Check that
836	 *	o the CFCR, IER and MCR in UART hold the values written to them
837	 *	  (the values happen to be all distinct - this is good for
838	 *	  avoiding false positive tests from bus echoes).
839	 *	o an output interrupt is generated and its vector is correct.
840	 *	o the interrupt goes away when the IIR in the UART is read.
841	 */
842/* EXTRA DELAY? */
843	failures[0] = inb(iobase + com_cfcr) - CFCR_8BITS;
844	failures[1] = inb(iobase + com_ier) - IER_ETXRDY;
845	failures[2] = inb(iobase + com_mcr) - mcr_image;
846	DELAY(10000);		/* Some internal modems need this time */
847	irqmap[1] = isa_irq_pending();
848	failures[4] = (inb(iobase + com_iir) & IIR_IMASK) - IIR_TXRDY;
849	DELAY(1000);		/* XXX */
850	irqmap[2] = isa_irq_pending();
851	failures[6] = (inb(iobase + com_iir) & IIR_IMASK) - IIR_NOPEND;
852
853	/*
854	 * Turn off all device interrupts and check that they go off properly.
855	 * Leave MCR_IENABLE alone.  For ports without a master port, it gates
856	 * the OUT2 output of the UART to
857	 * the ICU input.  Closing the gate would give a floating ICU input
858	 * (unless there is another device driving it) and spurious interrupts.
859	 * (On the system that this was first tested on, the input floats high
860	 * and gives a (masked) interrupt as soon as the gate is closed.)
861	 */
862	outb(iobase + com_ier, 0);
863	outb(iobase + com_cfcr, CFCR_8BITS);	/* dummy to avoid bus echo */
864	failures[7] = inb(iobase + com_ier);
865	DELAY(1000);		/* XXX */
866	irqmap[3] = isa_irq_pending();
867	failures[9] = (inb(iobase + com_iir) & IIR_IMASK) - IIR_NOPEND;
868
869	enable_intr();
870
871	irqs = irqmap[1] & ~irqmap[0];
872	if (bus_get_resource(idev, SYS_RES_IRQ, 0, &xirq, NULL) == 0 &&
873	    ((1 << xirq) & irqs) == 0)
874		printf(
875		"sio%d: configured irq %ld not in bitmap of probed irqs %#x\n",
876		    device_get_unit(dev), xirq, irqs);
877	if (bootverbose)
878		printf("sio%d: irq maps: %#x %#x %#x %#x\n",
879		    device_get_unit(dev),
880		    irqmap[0], irqmap[1], irqmap[2], irqmap[3]);
881
882	result = 0;
883	for (fn = 0; fn < sizeof failures; ++fn)
884		if (failures[fn]) {
885			outb(iobase + com_mcr, 0);
886			result = ENXIO;
887			if (bootverbose) {
888				printf("sio%d: probe failed test(s):",
889				    device_get_unit(dev));
890				for (fn = 0; fn < sizeof failures; ++fn)
891					if (failures[fn])
892						printf(" %d", fn);
893				printf("\n");
894			}
895			break;
896		}
897	bus_release_resource(dev, SYS_RES_IOPORT, rid, port);
898	return (iobase == siocniobase ? 0 : result);
899}
900
901#ifdef COM_ESP
902static int
903espattach(com, esp_port)
904	struct com_s		*com;
905	Port_t			esp_port;
906{
907	u_char	dips;
908	u_char	val;
909
910	/*
911	 * Check the ESP-specific I/O port to see if we're an ESP
912	 * card.  If not, return failure immediately.
913	 */
914	if ((inb(esp_port) & 0xf3) == 0) {
915		printf(" port 0x%x is not an ESP board?\n", esp_port);
916		return (0);
917	}
918
919	/*
920	 * We've got something that claims to be a Hayes ESP card.
921	 * Let's hope so.
922	 */
923
924	/* Get the dip-switch configuration */
925	outb(esp_port + ESP_CMD1, ESP_GETDIPS);
926	dips = inb(esp_port + ESP_STATUS1);
927
928	/*
929	 * Bits 0,1 of dips say which COM port we are.
930	 */
931	if (com->iobase == likely_com_ports[dips & 0x03])
932		printf(" : ESP");
933	else {
934		printf(" esp_port has com %d\n", dips & 0x03);
935		return (0);
936	}
937
938	/*
939	 * Check for ESP version 2.0 or later:  bits 4,5,6 = 010.
940	 */
941	outb(esp_port + ESP_CMD1, ESP_GETTEST);
942	val = inb(esp_port + ESP_STATUS1);	/* clear reg 1 */
943	val = inb(esp_port + ESP_STATUS2);
944	if ((val & 0x70) < 0x20) {
945		printf("-old (%o)", val & 0x70);
946		return (0);
947	}
948
949	/*
950	 * Check for ability to emulate 16550:  bit 7 == 1
951	 */
952	if ((dips & 0x80) == 0) {
953		printf(" slave");
954		return (0);
955	}
956
957	/*
958	 * Okay, we seem to be a Hayes ESP card.  Whee.
959	 */
960	com->esp = TRUE;
961	com->esp_port = esp_port;
962	return (1);
963}
964#endif /* COM_ESP */
965
966static int
967sio_isa_attach(dev)
968	device_t	dev;
969{
970	return (sioattach(dev));
971}
972
973static int
974sioattach(dev)
975	device_t	dev;
976{
977	struct com_s	*com;
978#ifdef COM_ESP
979	Port_t		*espp;
980#endif
981	Port_t		iobase;
982	int		unit;
983	u_int		flags;
984	int		rid;
985	struct resource *port;
986	int		ret;
987
988	rid = 0;
989	port = bus_alloc_resource(dev, SYS_RES_IOPORT, &rid,
990				  0, ~0, IO_COMSIZE, RF_ACTIVE);
991	if (!port)
992		return ENXIO;
993
994	iobase = rman_get_start(port);
995	unit = device_get_unit(dev);
996	com = device_get_softc(dev);
997	flags = device_get_flags(dev);
998
999	if (unit >= sio_numunits)
1000		sio_numunits = unit + 1;
1001	/*
1002	 * sioprobe() has initialized the device registers as follows:
1003	 *	o cfcr = CFCR_8BITS.
1004	 *	  It is most important that CFCR_DLAB is off, so that the
1005	 *	  data port is not hidden when we enable interrupts.
1006	 *	o ier = 0.
1007	 *	  Interrupts are only enabled when the line is open.
1008	 *	o mcr = MCR_IENABLE, or 0 if the port has AST/4 compatible
1009	 *	  interrupt control register or the config specifies no irq.
1010	 *	  Keeping MCR_DTR and MCR_RTS off might stop the external
1011	 *	  device from sending before we are ready.
1012	 */
1013	bzero(com, sizeof *com);
1014	com->unit = unit;
1015	com->ioportres = port;
1016	com->cfcr_image = CFCR_8BITS;
1017	com->dtr_wait = 3 * hz;
1018	com->loses_outints = COM_LOSESOUTINTS(flags) != 0;
1019	com->no_irq = bus_get_resource(dev, SYS_RES_IRQ, 0, NULL, NULL) != 0;
1020	com->tx_fifo_size = 1;
1021	com->obufs[0].l_head = com->obuf1;
1022	com->obufs[1].l_head = com->obuf2;
1023
1024	com->iobase = iobase;
1025	com->data_port = iobase + com_data;
1026	com->int_id_port = iobase + com_iir;
1027	com->modem_ctl_port = iobase + com_mcr;
1028	com->mcr_image = inb(com->modem_ctl_port);
1029	com->line_status_port = iobase + com_lsr;
1030	com->modem_status_port = iobase + com_msr;
1031	com->intr_ctl_port = iobase + com_ier;
1032
1033	/*
1034	 * We don't use all the flags from <sys/ttydefaults.h> since they
1035	 * are only relevant for logins.  It's important to have echo off
1036	 * initially so that the line doesn't start blathering before the
1037	 * echo flag can be turned off.
1038	 */
1039	com->it_in.c_iflag = 0;
1040	com->it_in.c_oflag = 0;
1041	com->it_in.c_cflag = TTYDEF_CFLAG;
1042	com->it_in.c_lflag = 0;
1043	if (unit == comconsole) {
1044		com->it_in.c_iflag = TTYDEF_IFLAG;
1045		com->it_in.c_oflag = TTYDEF_OFLAG;
1046		com->it_in.c_cflag = TTYDEF_CFLAG | CLOCAL;
1047		com->it_in.c_lflag = TTYDEF_LFLAG;
1048		com->lt_out.c_cflag = com->lt_in.c_cflag = CLOCAL;
1049		com->lt_out.c_ispeed = com->lt_out.c_ospeed =
1050		com->lt_in.c_ispeed = com->lt_in.c_ospeed =
1051		com->it_in.c_ispeed = com->it_in.c_ospeed = comdefaultrate;
1052	} else
1053		com->it_in.c_ispeed = com->it_in.c_ospeed = TTYDEF_SPEED;
1054	if (siosetwater(com, com->it_in.c_ispeed) != 0) {
1055		enable_intr();
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		splx(s);
1444	}
1445	return (0);
1446}
1447
1448static void
1449comhardclose(com)
1450	struct com_s	*com;
1451{
1452	Port_t		iobase;
1453	int		s;
1454	struct tty	*tp;
1455	int		unit;
1456
1457	unit = com->unit;
1458	iobase = com->iobase;
1459	s = spltty();
1460	com->poll = FALSE;
1461	com->poll_output = FALSE;
1462	com->do_timestamp = FALSE;
1463	com->do_dcd_timestamp = FALSE;
1464	com->pps.ppsparam.mode = 0;
1465	outb(iobase + com_cfcr, com->cfcr_image &= ~CFCR_SBREAK);
1466	{
1467		outb(iobase + com_ier, 0);
1468		tp = com->tp;
1469		if (tp->t_cflag & HUPCL
1470		    /*
1471		     * XXX we will miss any carrier drop between here and the
1472		     * next open.  Perhaps we should watch DCD even when the
1473		     * port is closed; it is not sufficient to check it at
1474		     * the next open because it might go up and down while
1475		     * we're not watching.
1476		     */
1477		    || (!com->active_out
1478		        && !(com->prev_modem_status & MSR_DCD)
1479		        && !(com->it_in.c_cflag & CLOCAL))
1480		    || !(tp->t_state & TS_ISOPEN)) {
1481			(void)commctl(com, TIOCM_DTR, DMBIC);
1482			if (com->dtr_wait != 0 && !(com->state & CS_DTR_OFF)) {
1483				timeout(siodtrwakeup, com, com->dtr_wait);
1484				com->state |= CS_DTR_OFF;
1485			}
1486		}
1487	}
1488	if (com->hasfifo) {
1489		/*
1490		 * Disable fifos so that they are off after controlled
1491		 * reboots.  Some BIOSes fail to detect 16550s when the
1492		 * fifos are enabled.
1493		 */
1494		outb(iobase + com_fifo, 0);
1495	}
1496	com->active_out = FALSE;
1497	wakeup(&com->active_out);
1498	wakeup(TSA_CARR_ON(tp));	/* restart any wopeners */
1499	splx(s);
1500}
1501
1502static int
1503sioread(dev, uio, flag)
1504	dev_t		dev;
1505	struct uio	*uio;
1506	int		flag;
1507{
1508	int		mynor;
1509	struct com_s	*com;
1510
1511	mynor = minor(dev);
1512	if (mynor & CONTROL_MASK)
1513		return (ENODEV);
1514	com = com_addr(MINOR_TO_UNIT(mynor));
1515	if (com->gone)
1516		return (ENODEV);
1517	return ((*linesw[com->tp->t_line].l_read)(com->tp, uio, flag));
1518}
1519
1520static int
1521siowrite(dev, uio, flag)
1522	dev_t		dev;
1523	struct uio	*uio;
1524	int		flag;
1525{
1526	int		mynor;
1527	struct com_s	*com;
1528	int		unit;
1529
1530	mynor = minor(dev);
1531	if (mynor & CONTROL_MASK)
1532		return (ENODEV);
1533
1534	unit = MINOR_TO_UNIT(mynor);
1535	com = com_addr(unit);
1536	if (com->gone)
1537		return (ENODEV);
1538	/*
1539	 * (XXX) We disallow virtual consoles if the physical console is
1540	 * a serial port.  This is in case there is a display attached that
1541	 * is not the console.  In that situation we don't need/want the X
1542	 * server taking over the console.
1543	 */
1544	if (constty != NULL && unit == comconsole)
1545		constty = NULL;
1546	return ((*linesw[com->tp->t_line].l_write)(com->tp, uio, flag));
1547}
1548
1549static void
1550siobusycheck(chan)
1551	void	*chan;
1552{
1553	struct com_s	*com;
1554	int		s;
1555
1556	com = (struct com_s *)chan;
1557
1558	/*
1559	 * Clear TS_BUSY if low-level output is complete.
1560	 * spl locking is sufficient because siointr1() does not set CS_BUSY.
1561	 * If siointr1() clears CS_BUSY after we look at it, then we'll get
1562	 * called again.  Reading the line status port outside of siointr1()
1563	 * is safe because CS_BUSY is clear so there are no output interrupts
1564	 * to lose.
1565	 */
1566	s = spltty();
1567	if (com->state & CS_BUSY)
1568		com->extra_state &= ~CSE_BUSYCHECK;	/* False alarm. */
1569	else if ((inb(com->line_status_port) & (LSR_TSRE | LSR_TXRDY))
1570	    == (LSR_TSRE | LSR_TXRDY)) {
1571		com->tp->t_state &= ~TS_BUSY;
1572		ttwwakeup(com->tp);
1573		com->extra_state &= ~CSE_BUSYCHECK;
1574	} else
1575		timeout(siobusycheck, com, hz / 100);
1576	splx(s);
1577}
1578
1579static void
1580siodtrwakeup(chan)
1581	void	*chan;
1582{
1583	struct com_s	*com;
1584
1585	com = (struct com_s *)chan;
1586	com->state &= ~CS_DTR_OFF;
1587	wakeup(&com->dtr_wait);
1588}
1589
1590static void
1591sioinput(com)
1592	struct com_s	*com;
1593{
1594	u_char		*buf;
1595	int		incc;
1596	u_char		line_status;
1597	int		recv_data;
1598	struct tty	*tp;
1599
1600	buf = com->ibuf;
1601	tp = com->tp;
1602	if (!(tp->t_state & TS_ISOPEN) || !(tp->t_cflag & CREAD)) {
1603		com_events -= (com->iptr - com->ibuf);
1604		com->iptr = com->ibuf;
1605		return;
1606	}
1607	if (tp->t_state & TS_CAN_BYPASS_L_RINT) {
1608		/*
1609		 * Avoid the grotesquely inefficient lineswitch routine
1610		 * (ttyinput) in "raw" mode.  It usually takes about 450
1611		 * instructions (that's without canonical processing or echo!).
1612		 * slinput is reasonably fast (usually 40 instructions plus
1613		 * call overhead).
1614		 */
1615		do {
1616			enable_intr();
1617			incc = com->iptr - buf;
1618			if (tp->t_rawq.c_cc + incc > tp->t_ihiwat
1619			    && (com->state & CS_RTS_IFLOW
1620				|| tp->t_iflag & IXOFF)
1621			    && !(tp->t_state & TS_TBLOCK))
1622				ttyblock(tp);
1623			com->delta_error_counts[CE_TTY_BUF_OVERFLOW]
1624				+= b_to_q((char *)buf, incc, &tp->t_rawq);
1625			buf += incc;
1626			tk_nin += incc;
1627			tk_rawcc += incc;
1628			tp->t_rawcc += incc;
1629			ttwakeup(tp);
1630			if (tp->t_state & TS_TTSTOP
1631			    && (tp->t_iflag & IXANY
1632				|| tp->t_cc[VSTART] == tp->t_cc[VSTOP])) {
1633				tp->t_state &= ~TS_TTSTOP;
1634				tp->t_lflag &= ~FLUSHO;
1635				comstart(tp);
1636			}
1637			disable_intr();
1638		} while (buf < com->iptr);
1639	} else {
1640		do {
1641			enable_intr();
1642			line_status = buf[com->ierroff];
1643			recv_data = *buf++;
1644			if (line_status
1645			    & (LSR_BI | LSR_FE | LSR_OE | LSR_PE)) {
1646				if (line_status & LSR_BI)
1647					recv_data |= TTY_BI;
1648				if (line_status & LSR_FE)
1649					recv_data |= TTY_FE;
1650				if (line_status & LSR_OE)
1651					recv_data |= TTY_OE;
1652				if (line_status & LSR_PE)
1653					recv_data |= TTY_PE;
1654			}
1655			(*linesw[tp->t_line].l_rint)(recv_data, tp);
1656			disable_intr();
1657		} while (buf < com->iptr);
1658	}
1659	com_events -= (com->iptr - com->ibuf);
1660	com->iptr = com->ibuf;
1661
1662	/*
1663	 * There is now room for another low-level buffer full of input,
1664	 * so enable RTS if it is now disabled and there is room in the
1665	 * high-level buffer.
1666	 */
1667	if ((com->state & CS_RTS_IFLOW) && !(com->mcr_image & MCR_RTS) &&
1668	    !(tp->t_state & TS_TBLOCK))
1669		outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
1670}
1671
1672void
1673siointr(arg)
1674	void		*arg;
1675{
1676#ifndef COM_MULTIPORT
1677	COM_LOCK();
1678	siointr1((struct com_s *) arg);
1679	COM_UNLOCK();
1680#else /* COM_MULTIPORT */
1681	bool_t		possibly_more_intrs;
1682	int		unit;
1683	struct com_s	*com;
1684
1685	/*
1686	 * Loop until there is no activity on any port.  This is necessary
1687	 * to get an interrupt edge more than to avoid another interrupt.
1688	 * If the IRQ signal is just an OR of the IRQ signals from several
1689	 * devices, then the edge from one may be lost because another is
1690	 * on.
1691	 */
1692	COM_LOCK();
1693	do {
1694		possibly_more_intrs = FALSE;
1695		for (unit = 0; unit < sio_numunits; ++unit) {
1696			com = com_addr(unit);
1697			/*
1698			 * XXX COM_LOCK();
1699			 * would it work here, or be counter-productive?
1700			 */
1701			if (com != NULL
1702			    && !com->gone
1703			    && (inb(com->int_id_port) & IIR_IMASK)
1704			       != IIR_NOPEND) {
1705				siointr1(com);
1706				possibly_more_intrs = TRUE;
1707			}
1708			/* XXX COM_UNLOCK(); */
1709		}
1710	} while (possibly_more_intrs);
1711	COM_UNLOCK();
1712#endif /* COM_MULTIPORT */
1713}
1714
1715static void
1716siointr1(com)
1717	struct com_s	*com;
1718{
1719	u_char	line_status;
1720	u_char	modem_status;
1721	u_char	*ioptr;
1722	u_char	recv_data;
1723	u_char	int_ctl;
1724	u_char	int_ctl_new;
1725	struct	timecounter *tc;
1726	u_int	count;
1727
1728	int_ctl = inb(com->intr_ctl_port);
1729	int_ctl_new = int_ctl;
1730
1731	while (!com->gone) {
1732		if (com->pps.ppsparam.mode & PPS_CAPTUREBOTH) {
1733			modem_status = inb(com->modem_status_port);
1734		        if ((modem_status ^ com->last_modem_status) & MSR_DCD) {
1735				tc = timecounter;
1736				count = tc->tc_get_timecount(tc);
1737				pps_event(&com->pps, tc, count,
1738				    (modem_status & MSR_DCD) ?
1739				    PPS_CAPTUREASSERT : PPS_CAPTURECLEAR);
1740			}
1741		}
1742		line_status = inb(com->line_status_port);
1743
1744		/* input event? (check first to help avoid overruns) */
1745		while (line_status & LSR_RCV_MASK) {
1746			/* break/unnattached error bits or real input? */
1747			if (!(line_status & LSR_RXRDY))
1748				recv_data = 0;
1749			else
1750				recv_data = inb(com->data_port);
1751			if (line_status & (LSR_BI | LSR_FE | LSR_PE)) {
1752				/*
1753				 * Don't store BI if IGNBRK or FE/PE if IGNPAR.
1754				 * Otherwise, push the work to a higher level
1755				 * (to handle PARMRK) if we're bypassing.
1756				 * Otherwise, convert BI/FE and PE+INPCK to 0.
1757				 *
1758				 * This makes bypassing work right in the
1759				 * usual "raw" case (IGNBRK set, and IGNPAR
1760				 * and INPCK clear).
1761				 *
1762				 * Note: BI together with FE/PE means just BI.
1763				 */
1764				if (line_status & LSR_BI) {
1765#if defined(DDB) && defined(BREAK_TO_DEBUGGER)
1766					if (com->unit == comconsole) {
1767						breakpoint();
1768						goto cont;
1769					}
1770#endif
1771					if (com->tp == NULL
1772					    || com->tp->t_iflag & IGNBRK)
1773						goto cont;
1774				} else {
1775					if (com->tp == NULL
1776					    || com->tp->t_iflag & IGNPAR)
1777						goto cont;
1778				}
1779				if (com->tp->t_state & TS_CAN_BYPASS_L_RINT
1780				    && (line_status & (LSR_BI | LSR_FE)
1781					|| com->tp->t_iflag & INPCK))
1782					recv_data = 0;
1783			}
1784			++com->bytes_in;
1785			if (com->hotchar != 0 && recv_data == com->hotchar)
1786				setsofttty();
1787			ioptr = com->iptr;
1788			if (ioptr >= com->ibufend)
1789				CE_RECORD(com, CE_INTERRUPT_BUF_OVERFLOW);
1790			else {
1791				if (com->do_timestamp)
1792					microtime(&com->timestamp);
1793				++com_events;
1794				schedsofttty();
1795#if 0 /* for testing input latency vs efficiency */
1796if (com->iptr - com->ibuf == 8)
1797	setsofttty();
1798#endif
1799				ioptr[0] = recv_data;
1800				ioptr[com->ierroff] = line_status;
1801				com->iptr = ++ioptr;
1802				if (ioptr == com->ihighwater
1803				    && com->state & CS_RTS_IFLOW)
1804					outb(com->modem_ctl_port,
1805					     com->mcr_image &= ~MCR_RTS);
1806				if (line_status & LSR_OE)
1807					CE_RECORD(com, CE_OVERRUN);
1808			}
1809cont:
1810			/*
1811			 * "& 0x7F" is to avoid the gcc-1.40 generating a slow
1812			 * jump from the top of the loop to here
1813			 */
1814			line_status = inb(com->line_status_port) & 0x7F;
1815		}
1816
1817		/* modem status change? (always check before doing output) */
1818		modem_status = inb(com->modem_status_port);
1819		if (modem_status != com->last_modem_status) {
1820			if (com->do_dcd_timestamp
1821			    && !(com->last_modem_status & MSR_DCD)
1822			    && modem_status & MSR_DCD)
1823				microtime(&com->dcd_timestamp);
1824
1825			/*
1826			 * Schedule high level to handle DCD changes.  Note
1827			 * that we don't use the delta bits anywhere.  Some
1828			 * UARTs mess them up, and it's easy to remember the
1829			 * previous bits and calculate the delta.
1830			 */
1831			com->last_modem_status = modem_status;
1832			if (!(com->state & CS_CHECKMSR)) {
1833				com_events += LOTS_OF_EVENTS;
1834				com->state |= CS_CHECKMSR;
1835				setsofttty();
1836			}
1837
1838			/* handle CTS change immediately for crisp flow ctl */
1839			if (com->state & CS_CTS_OFLOW) {
1840				if (modem_status & MSR_CTS)
1841					com->state |= CS_ODEVREADY;
1842				else
1843					com->state &= ~CS_ODEVREADY;
1844			}
1845		}
1846
1847		/* output queued and everything ready? */
1848		if (line_status & LSR_TXRDY
1849		    && com->state >= (CS_BUSY | CS_TTGO | CS_ODEVREADY)) {
1850			ioptr = com->obufq.l_head;
1851			if (com->tx_fifo_size > 1) {
1852				u_int	ocount;
1853
1854				ocount = com->obufq.l_tail - ioptr;
1855				if (ocount > com->tx_fifo_size)
1856					ocount = com->tx_fifo_size;
1857				com->bytes_out += ocount;
1858				do
1859					outb(com->data_port, *ioptr++);
1860				while (--ocount != 0);
1861			} else {
1862				outb(com->data_port, *ioptr++);
1863				++com->bytes_out;
1864			}
1865			com->obufq.l_head = ioptr;
1866			if (COM_IIR_TXRDYBUG(com->flags)) {
1867				int_ctl_new = int_ctl | IER_ETXRDY;
1868			}
1869			if (ioptr >= com->obufq.l_tail) {
1870				struct lbq	*qp;
1871
1872				qp = com->obufq.l_next;
1873				qp->l_queued = FALSE;
1874				qp = qp->l_next;
1875				if (qp != NULL) {
1876					com->obufq.l_head = qp->l_head;
1877					com->obufq.l_tail = qp->l_tail;
1878					com->obufq.l_next = qp;
1879				} else {
1880					/* output just completed */
1881					if (COM_IIR_TXRDYBUG(com->flags)) {
1882						int_ctl_new = int_ctl & ~IER_ETXRDY;
1883					}
1884					com->state &= ~CS_BUSY;
1885				}
1886				if (!(com->state & CS_ODONE)) {
1887					com_events += LOTS_OF_EVENTS;
1888					com->state |= CS_ODONE;
1889					setsofttty();	/* handle at high level ASAP */
1890				}
1891			}
1892			if (COM_IIR_TXRDYBUG(com->flags) && (int_ctl != int_ctl_new)) {
1893				outb(com->intr_ctl_port, int_ctl_new);
1894			}
1895		}
1896
1897		/* finished? */
1898#ifndef COM_MULTIPORT
1899		if ((inb(com->int_id_port) & IIR_IMASK) == IIR_NOPEND)
1900#endif /* COM_MULTIPORT */
1901			return;
1902	}
1903}
1904
1905static int
1906sioioctl(dev, cmd, data, flag, p)
1907	dev_t		dev;
1908	u_long		cmd;
1909	caddr_t		data;
1910	int		flag;
1911	struct proc	*p;
1912{
1913	struct com_s	*com;
1914	int		error;
1915	Port_t		iobase;
1916	int		mynor;
1917	int		s;
1918	struct tty	*tp;
1919#if defined(COMPAT_43) || defined(COMPAT_SUNOS)
1920	u_long		oldcmd;
1921	struct termios	term;
1922#endif
1923
1924	mynor = minor(dev);
1925	com = com_addr(MINOR_TO_UNIT(mynor));
1926	if (com->gone)
1927		return (ENODEV);
1928	iobase = com->iobase;
1929	if (mynor & CONTROL_MASK) {
1930		struct termios	*ct;
1931
1932		switch (mynor & CONTROL_MASK) {
1933		case CONTROL_INIT_STATE:
1934			ct = mynor & CALLOUT_MASK ? &com->it_out : &com->it_in;
1935			break;
1936		case CONTROL_LOCK_STATE:
1937			ct = mynor & CALLOUT_MASK ? &com->lt_out : &com->lt_in;
1938			break;
1939		default:
1940			return (ENODEV);	/* /dev/nodev */
1941		}
1942		switch (cmd) {
1943		case TIOCSETA:
1944			error = suser(p);
1945			if (error != 0)
1946				return (error);
1947			*ct = *(struct termios *)data;
1948			return (0);
1949		case TIOCGETA:
1950			*(struct termios *)data = *ct;
1951			return (0);
1952		case TIOCGETD:
1953			*(int *)data = TTYDISC;
1954			return (0);
1955		case TIOCGWINSZ:
1956			bzero(data, sizeof(struct winsize));
1957			return (0);
1958		default:
1959			return (ENOTTY);
1960		}
1961	}
1962	tp = com->tp;
1963#if defined(COMPAT_43) || defined(COMPAT_SUNOS)
1964	term = tp->t_termios;
1965	oldcmd = cmd;
1966	error = ttsetcompat(tp, &cmd, data, &term);
1967	if (error != 0)
1968		return (error);
1969	if (cmd != oldcmd)
1970		data = (caddr_t)&term;
1971#endif
1972	if (cmd == TIOCSETA || cmd == TIOCSETAW || cmd == TIOCSETAF) {
1973		int	cc;
1974		struct termios *dt = (struct termios *)data;
1975		struct termios *lt = mynor & CALLOUT_MASK
1976				     ? &com->lt_out : &com->lt_in;
1977
1978		dt->c_iflag = (tp->t_iflag & lt->c_iflag)
1979			      | (dt->c_iflag & ~lt->c_iflag);
1980		dt->c_oflag = (tp->t_oflag & lt->c_oflag)
1981			      | (dt->c_oflag & ~lt->c_oflag);
1982		dt->c_cflag = (tp->t_cflag & lt->c_cflag)
1983			      | (dt->c_cflag & ~lt->c_cflag);
1984		dt->c_lflag = (tp->t_lflag & lt->c_lflag)
1985			      | (dt->c_lflag & ~lt->c_lflag);
1986		for (cc = 0; cc < NCCS; ++cc)
1987			if (lt->c_cc[cc] != 0)
1988				dt->c_cc[cc] = tp->t_cc[cc];
1989		if (lt->c_ispeed != 0)
1990			dt->c_ispeed = tp->t_ispeed;
1991		if (lt->c_ospeed != 0)
1992			dt->c_ospeed = tp->t_ospeed;
1993	}
1994	error = (*linesw[tp->t_line].l_ioctl)(tp, cmd, data, flag, p);
1995	if (error != ENOIOCTL)
1996		return (error);
1997	s = spltty();
1998	error = ttioctl(tp, cmd, data, flag);
1999	disc_optim(tp, &tp->t_termios, com);
2000	if (error != ENOIOCTL) {
2001		splx(s);
2002		return (error);
2003	}
2004	switch (cmd) {
2005	case TIOCSBRK:
2006		outb(iobase + com_cfcr, com->cfcr_image |= CFCR_SBREAK);
2007		break;
2008	case TIOCCBRK:
2009		outb(iobase + com_cfcr, com->cfcr_image &= ~CFCR_SBREAK);
2010		break;
2011	case TIOCSDTR:
2012		(void)commctl(com, TIOCM_DTR, DMBIS);
2013		break;
2014	case TIOCCDTR:
2015		(void)commctl(com, TIOCM_DTR, DMBIC);
2016		break;
2017	/*
2018	 * XXX should disallow changing MCR_RTS if CS_RTS_IFLOW is set.  The
2019	 * changes get undone on the next call to comparam().
2020	 */
2021	case TIOCMSET:
2022		(void)commctl(com, *(int *)data, DMSET);
2023		break;
2024	case TIOCMBIS:
2025		(void)commctl(com, *(int *)data, DMBIS);
2026		break;
2027	case TIOCMBIC:
2028		(void)commctl(com, *(int *)data, DMBIC);
2029		break;
2030	case TIOCMGET:
2031		*(int *)data = commctl(com, 0, DMGET);
2032		break;
2033	case TIOCMSDTRWAIT:
2034		/* must be root since the wait applies to following logins */
2035		error = suser(p);
2036		if (error != 0) {
2037			splx(s);
2038			return (error);
2039		}
2040		com->dtr_wait = *(int *)data * hz / 100;
2041		break;
2042	case TIOCMGDTRWAIT:
2043		*(int *)data = com->dtr_wait * 100 / hz;
2044		break;
2045	case TIOCTIMESTAMP:
2046		com->do_timestamp = TRUE;
2047		*(struct timeval *)data = com->timestamp;
2048		break;
2049	case TIOCDCDTIMESTAMP:
2050		com->do_dcd_timestamp = TRUE;
2051		*(struct timeval *)data = com->dcd_timestamp;
2052		break;
2053	default:
2054		splx(s);
2055		error = pps_ioctl(cmd, data, &com->pps);
2056		if (error == ENODEV)
2057			error = ENOTTY;
2058		return (error);
2059	}
2060	splx(s);
2061	return (0);
2062}
2063
2064static void
2065siopoll()
2066{
2067	int		unit;
2068
2069	if (com_events == 0)
2070		return;
2071repeat:
2072	for (unit = 0; unit < sio_numunits; ++unit) {
2073		struct com_s	*com;
2074		int		incc;
2075		struct tty	*tp;
2076
2077		com = com_addr(unit);
2078		if (com == NULL)
2079			continue;
2080		tp = com->tp;
2081		if (tp == NULL || com->gone) {
2082			/*
2083			 * Discard any events related to never-opened or
2084			 * going-away devices.
2085			 */
2086			disable_intr();
2087			incc = com->iptr - com->ibuf;
2088			com->iptr = com->ibuf;
2089			if (com->state & CS_CHECKMSR) {
2090				incc += LOTS_OF_EVENTS;
2091				com->state &= ~CS_CHECKMSR;
2092			}
2093			com_events -= incc;
2094			enable_intr();
2095			continue;
2096		}
2097		if (com->iptr != com->ibuf) {
2098			disable_intr();
2099			sioinput(com);
2100			enable_intr();
2101		}
2102		if (com->state & CS_CHECKMSR) {
2103			u_char	delta_modem_status;
2104
2105			disable_intr();
2106			delta_modem_status = com->last_modem_status
2107					     ^ com->prev_modem_status;
2108			com->prev_modem_status = com->last_modem_status;
2109			com_events -= LOTS_OF_EVENTS;
2110			com->state &= ~CS_CHECKMSR;
2111			enable_intr();
2112			if (delta_modem_status & MSR_DCD)
2113				(*linesw[tp->t_line].l_modem)
2114					(tp, com->prev_modem_status & MSR_DCD);
2115		}
2116		if (com->state & CS_ODONE) {
2117			disable_intr();
2118			com_events -= LOTS_OF_EVENTS;
2119			com->state &= ~CS_ODONE;
2120			enable_intr();
2121			if (!(com->state & CS_BUSY)
2122			    && !(com->extra_state & CSE_BUSYCHECK)) {
2123				timeout(siobusycheck, com, hz / 100);
2124				com->extra_state |= CSE_BUSYCHECK;
2125			}
2126			(*linesw[tp->t_line].l_start)(tp);
2127		}
2128		if (com_events == 0)
2129			break;
2130	}
2131	if (com_events >= LOTS_OF_EVENTS)
2132		goto repeat;
2133}
2134
2135static int
2136comparam(tp, t)
2137	struct tty	*tp;
2138	struct termios	*t;
2139{
2140	u_int		cfcr;
2141	int		cflag;
2142	struct com_s	*com;
2143	int		divisor;
2144	u_char		dlbh;
2145	u_char		dlbl;
2146	Port_t		iobase;
2147	int		s;
2148	int		unit;
2149
2150	/* do historical conversions */
2151	if (t->c_ispeed == 0)
2152		t->c_ispeed = t->c_ospeed;
2153
2154	/* check requested parameters */
2155	divisor = ttspeedtab(t->c_ospeed, comspeedtab);
2156	if (divisor < 0 || (divisor > 0 && t->c_ispeed != t->c_ospeed))
2157		return (EINVAL);
2158
2159	/* parameters are OK, convert them to the com struct and the device */
2160	unit = DEV_TO_UNIT(tp->t_dev);
2161	com = com_addr(unit);
2162	iobase = com->iobase;
2163	s = spltty();
2164	if (divisor == 0)
2165		(void)commctl(com, TIOCM_DTR, DMBIC);	/* hang up line */
2166	else
2167		(void)commctl(com, TIOCM_DTR, DMBIS);
2168	cflag = t->c_cflag;
2169	switch (cflag & CSIZE) {
2170	case CS5:
2171		cfcr = CFCR_5BITS;
2172		break;
2173	case CS6:
2174		cfcr = CFCR_6BITS;
2175		break;
2176	case CS7:
2177		cfcr = CFCR_7BITS;
2178		break;
2179	default:
2180		cfcr = CFCR_8BITS;
2181		break;
2182	}
2183	if (cflag & PARENB) {
2184		cfcr |= CFCR_PENAB;
2185		if (!(cflag & PARODD))
2186			cfcr |= CFCR_PEVEN;
2187	}
2188	if (cflag & CSTOPB)
2189		cfcr |= CFCR_STOPB;
2190
2191	if (com->hasfifo && divisor != 0) {
2192		/*
2193		 * Use a fifo trigger level low enough so that the input
2194		 * latency from the fifo is less than about 16 msec and
2195		 * the total latency is less than about 30 msec.  These
2196		 * latencies are reasonable for humans.  Serial comms
2197		 * protocols shouldn't expect anything better since modem
2198		 * latencies are larger.
2199		 */
2200		com->fifo_image = t->c_ospeed <= 4800
2201				  ? FIFO_ENABLE : FIFO_ENABLE | FIFO_RX_HIGH;
2202#ifdef COM_ESP
2203		/*
2204		 * The Hayes ESP card needs the fifo DMA mode bit set
2205		 * in compatibility mode.  If not, it will interrupt
2206		 * for each character received.
2207		 */
2208		if (com->esp)
2209			com->fifo_image |= FIFO_DMA_MODE;
2210#endif
2211		outb(iobase + com_fifo, com->fifo_image);
2212	}
2213
2214	/*
2215	 * This returns with interrupts disabled so that we can complete
2216	 * the speed change atomically.  Keeping interrupts disabled is
2217	 * especially important while com_data is hidden.
2218	 */
2219	(void) siosetwater(com, t->c_ispeed);
2220
2221	if (divisor != 0) {
2222		outb(iobase + com_cfcr, cfcr | CFCR_DLAB);
2223		/*
2224		 * Only set the divisor registers if they would change,
2225		 * since on some 16550 incompatibles (UMC8669F), setting
2226		 * them while input is arriving them loses sync until
2227		 * data stops arriving.
2228		 */
2229		dlbl = divisor & 0xFF;
2230		if (inb(iobase + com_dlbl) != dlbl)
2231			outb(iobase + com_dlbl, dlbl);
2232		dlbh = (u_int) divisor >> 8;
2233		if (inb(iobase + com_dlbh) != dlbh)
2234			outb(iobase + com_dlbh, dlbh);
2235	}
2236
2237
2238	outb(iobase + com_cfcr, com->cfcr_image = cfcr);
2239
2240	if (!(tp->t_state & TS_TTSTOP))
2241		com->state |= CS_TTGO;
2242
2243	if (cflag & CRTS_IFLOW) {
2244		if (com->st16650a) {
2245			outb(iobase + com_cfcr, 0xbf);
2246			outb(iobase + com_fifo, inb(iobase + com_fifo) | 0x40);
2247		}
2248		com->state |= CS_RTS_IFLOW;
2249		/*
2250		 * If CS_RTS_IFLOW just changed from off to on, the change
2251		 * needs to be propagated to MCR_RTS.  This isn't urgent,
2252		 * so do it later by calling comstart() instead of repeating
2253		 * a lot of code from comstart() here.
2254		 */
2255	} else if (com->state & CS_RTS_IFLOW) {
2256		com->state &= ~CS_RTS_IFLOW;
2257		/*
2258		 * CS_RTS_IFLOW just changed from on to off.  Force MCR_RTS
2259		 * on here, since comstart() won't do it later.
2260		 */
2261		outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
2262		if (com->st16650a) {
2263			outb(iobase + com_cfcr, 0xbf);
2264			outb(iobase + com_fifo, inb(iobase + com_fifo) & ~0x40);
2265		}
2266	}
2267
2268
2269	/*
2270	 * Set up state to handle output flow control.
2271	 * XXX - worth handling MDMBUF (DCD) flow control at the lowest level?
2272	 * Now has 10+ msec latency, while CTS flow has 50- usec latency.
2273	 */
2274	com->state |= CS_ODEVREADY;
2275	com->state &= ~CS_CTS_OFLOW;
2276	if (cflag & CCTS_OFLOW) {
2277		com->state |= CS_CTS_OFLOW;
2278		if (!(com->last_modem_status & MSR_CTS))
2279			com->state &= ~CS_ODEVREADY;
2280		if (com->st16650a) {
2281			outb(iobase + com_cfcr, 0xbf);
2282			outb(iobase + com_fifo, inb(iobase + com_fifo) | 0x80);
2283		}
2284	} else {
2285		if (com->st16650a) {
2286			outb(iobase + com_cfcr, 0xbf);
2287			outb(iobase + com_fifo, inb(iobase + com_fifo) & ~0x80);
2288		}
2289	}
2290
2291
2292	outb(iobase + com_cfcr, com->cfcr_image);
2293
2294
2295	/* XXX shouldn't call functions while intrs are disabled. */
2296	disc_optim(tp, t, com);
2297	/*
2298	 * Recover from fiddling with CS_TTGO.  We used to call siointr1()
2299	 * unconditionally, but that defeated the careful discarding of
2300	 * stale input in sioopen().
2301	 */
2302	if (com->state >= (CS_BUSY | CS_TTGO))
2303		siointr1(com);
2304
2305	enable_intr();
2306	splx(s);
2307	comstart(tp);
2308	if (com->ibufold != NULL) {
2309		free(com->ibufold, M_DEVBUF);
2310		com->ibufold = NULL;
2311	}
2312	return (0);
2313}
2314
2315static int
2316siosetwater(com, speed)
2317	struct com_s	*com;
2318	speed_t		speed;
2319{
2320	int		cp4ticks;
2321	u_char		*ibuf;
2322	int		ibufsize;
2323	struct tty	*tp;
2324
2325	/*
2326	 * Make the buffer size large enough to handle a softtty interrupt
2327	 * latency of about 2 ticks without loss of throughput or data
2328	 * (about 3 ticks if input flow control is not used or not honoured,
2329	 * but a bit less for CS5-CS7 modes).
2330	 */
2331	cp4ticks = speed / 10 / hz * 4;
2332	for (ibufsize = 128; ibufsize < cp4ticks;)
2333		ibufsize <<= 1;
2334	if (ibufsize == com->ibufsize) {
2335		disable_intr();
2336		return (0);
2337	}
2338
2339	/*
2340	 * Allocate input buffer.  The extra factor of 2 in the size is
2341	 * to allow for an error byte for each input byte.
2342	 */
2343	ibuf = malloc(2 * ibufsize, M_DEVBUF, M_NOWAIT);
2344	if (ibuf == NULL) {
2345		disable_intr();
2346		return (ENOMEM);
2347	}
2348
2349	/* Initialize non-critical variables. */
2350	com->ibufold = com->ibuf;
2351	com->ibufsize = ibufsize;
2352	tp = com->tp;
2353	if (tp != NULL) {
2354		tp->t_ififosize = 2 * ibufsize;
2355		tp->t_ispeedwat = (speed_t)-1;
2356		tp->t_ospeedwat = (speed_t)-1;
2357	}
2358
2359	/*
2360	 * Read current input buffer, if any.  Continue with interrupts
2361	 * disabled.
2362	 */
2363	disable_intr();
2364	if (com->iptr != com->ibuf)
2365		sioinput(com);
2366
2367	/*-
2368	 * Initialize critical variables, including input buffer watermarks.
2369	 * The external device is asked to stop sending when the buffer
2370	 * exactly reaches high water, or when the high level requests it.
2371	 * The high level is notified immediately (rather than at a later
2372	 * clock tick) when this watermark is reached.
2373	 * The buffer size is chosen so the watermark should almost never
2374	 * be reached.
2375	 * The low watermark is invisibly 0 since the buffer is always
2376	 * emptied all at once.
2377	 */
2378	com->iptr = com->ibuf = ibuf;
2379	com->ibufend = ibuf + ibufsize;
2380	com->ierroff = ibufsize;
2381	com->ihighwater = ibuf + 3 * ibufsize / 4;
2382	return (0);
2383}
2384
2385static void
2386comstart(tp)
2387	struct tty	*tp;
2388{
2389	struct com_s	*com;
2390	int		s;
2391	int		unit;
2392
2393	unit = DEV_TO_UNIT(tp->t_dev);
2394	com = com_addr(unit);
2395	s = spltty();
2396	disable_intr();
2397	if (tp->t_state & TS_TTSTOP)
2398		com->state &= ~CS_TTGO;
2399	else
2400		com->state |= CS_TTGO;
2401	if (tp->t_state & TS_TBLOCK) {
2402		if (com->mcr_image & MCR_RTS && com->state & CS_RTS_IFLOW)
2403			outb(com->modem_ctl_port, com->mcr_image &= ~MCR_RTS);
2404	} else {
2405		if (!(com->mcr_image & MCR_RTS) && com->iptr < com->ihighwater
2406		    && com->state & CS_RTS_IFLOW)
2407			outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
2408	}
2409	enable_intr();
2410	if (tp->t_state & (TS_TIMEOUT | TS_TTSTOP)) {
2411		ttwwakeup(tp);
2412		splx(s);
2413		return;
2414	}
2415	if (tp->t_outq.c_cc != 0) {
2416		struct lbq	*qp;
2417		struct lbq	*next;
2418
2419		if (!com->obufs[0].l_queued) {
2420			com->obufs[0].l_tail
2421			    = com->obuf1 + q_to_b(&tp->t_outq, com->obuf1,
2422						  sizeof com->obuf1);
2423			com->obufs[0].l_next = NULL;
2424			com->obufs[0].l_queued = TRUE;
2425			disable_intr();
2426			if (com->state & CS_BUSY) {
2427				qp = com->obufq.l_next;
2428				while ((next = qp->l_next) != NULL)
2429					qp = next;
2430				qp->l_next = &com->obufs[0];
2431			} else {
2432				com->obufq.l_head = com->obufs[0].l_head;
2433				com->obufq.l_tail = com->obufs[0].l_tail;
2434				com->obufq.l_next = &com->obufs[0];
2435				com->state |= CS_BUSY;
2436			}
2437			enable_intr();
2438		}
2439		if (tp->t_outq.c_cc != 0 && !com->obufs[1].l_queued) {
2440			com->obufs[1].l_tail
2441			    = com->obuf2 + q_to_b(&tp->t_outq, com->obuf2,
2442						  sizeof com->obuf2);
2443			com->obufs[1].l_next = NULL;
2444			com->obufs[1].l_queued = TRUE;
2445			disable_intr();
2446			if (com->state & CS_BUSY) {
2447				qp = com->obufq.l_next;
2448				while ((next = qp->l_next) != NULL)
2449					qp = next;
2450				qp->l_next = &com->obufs[1];
2451			} else {
2452				com->obufq.l_head = com->obufs[1].l_head;
2453				com->obufq.l_tail = com->obufs[1].l_tail;
2454				com->obufq.l_next = &com->obufs[1];
2455				com->state |= CS_BUSY;
2456			}
2457			enable_intr();
2458		}
2459		tp->t_state |= TS_BUSY;
2460	}
2461	disable_intr();
2462	if (com->state >= (CS_BUSY | CS_TTGO))
2463		siointr1(com);	/* fake interrupt to start output */
2464	enable_intr();
2465	ttwwakeup(tp);
2466	splx(s);
2467}
2468
2469static void
2470comstop(tp, rw)
2471	struct tty	*tp;
2472	int		rw;
2473{
2474	struct com_s	*com;
2475
2476	com = com_addr(DEV_TO_UNIT(tp->t_dev));
2477	if (com->gone)
2478		return;
2479	disable_intr();
2480	if (rw & FWRITE) {
2481		if (com->hasfifo)
2482#ifdef COM_ESP
2483		    /* XXX avoid h/w bug. */
2484		    if (!com->esp)
2485#endif
2486			outb(com->iobase + com_fifo,
2487			     FIFO_XMT_RST | com->fifo_image);
2488		com->obufs[0].l_queued = FALSE;
2489		com->obufs[1].l_queued = FALSE;
2490		if (com->state & CS_ODONE)
2491			com_events -= LOTS_OF_EVENTS;
2492		com->state &= ~(CS_ODONE | CS_BUSY);
2493		com->tp->t_state &= ~TS_BUSY;
2494	}
2495	if (rw & FREAD) {
2496		if (com->hasfifo)
2497#ifdef COM_ESP
2498		    /* XXX avoid h/w bug. */
2499		    if (!com->esp)
2500#endif
2501			outb(com->iobase + com_fifo,
2502			     FIFO_RCV_RST | com->fifo_image);
2503		com_events -= (com->iptr - com->ibuf);
2504		com->iptr = com->ibuf;
2505	}
2506	enable_intr();
2507	comstart(tp);
2508}
2509
2510static int
2511commctl(com, bits, how)
2512	struct com_s	*com;
2513	int		bits;
2514	int		how;
2515{
2516	int	mcr;
2517	int	msr;
2518
2519	if (how == DMGET) {
2520		bits = TIOCM_LE;	/* XXX - always enabled while open */
2521		mcr = com->mcr_image;
2522		if (mcr & MCR_DTR)
2523			bits |= TIOCM_DTR;
2524		if (mcr & MCR_RTS)
2525			bits |= TIOCM_RTS;
2526		msr = com->prev_modem_status;
2527		if (msr & MSR_CTS)
2528			bits |= TIOCM_CTS;
2529		if (msr & MSR_DCD)
2530			bits |= TIOCM_CD;
2531		if (msr & MSR_DSR)
2532			bits |= TIOCM_DSR;
2533		/*
2534		 * XXX - MSR_RI is naturally volatile, and we make MSR_TERI
2535		 * more volatile by reading the modem status a lot.  Perhaps
2536		 * we should latch both bits until the status is read here.
2537		 */
2538		if (msr & (MSR_RI | MSR_TERI))
2539			bits |= TIOCM_RI;
2540		return (bits);
2541	}
2542	mcr = 0;
2543	if (bits & TIOCM_DTR)
2544		mcr |= MCR_DTR;
2545	if (bits & TIOCM_RTS)
2546		mcr |= MCR_RTS;
2547	if (com->gone)
2548		return(0);
2549	disable_intr();
2550	switch (how) {
2551	case DMSET:
2552		outb(com->modem_ctl_port,
2553		     com->mcr_image = mcr | (com->mcr_image & MCR_IENABLE));
2554		break;
2555	case DMBIS:
2556		outb(com->modem_ctl_port, com->mcr_image |= mcr);
2557		break;
2558	case DMBIC:
2559		outb(com->modem_ctl_port, com->mcr_image &= ~mcr);
2560		break;
2561	}
2562	enable_intr();
2563	return (0);
2564}
2565
2566static void
2567siosettimeout()
2568{
2569	struct com_s	*com;
2570	bool_t		someopen;
2571	int		unit;
2572
2573	/*
2574	 * Set our timeout period to 1 second if no polled devices are open.
2575	 * Otherwise set it to max(1/200, 1/hz).
2576	 * Enable timeouts iff some device is open.
2577	 */
2578	untimeout(comwakeup, (void *)NULL, sio_timeout_handle);
2579	sio_timeout = hz;
2580	someopen = FALSE;
2581	for (unit = 0; unit < sio_numunits; ++unit) {
2582		com = com_addr(unit);
2583		if (com != NULL && com->tp != NULL
2584		    && com->tp->t_state & TS_ISOPEN && !com->gone) {
2585			someopen = TRUE;
2586			if (com->poll || com->poll_output) {
2587				sio_timeout = hz > 200 ? hz / 200 : 1;
2588				break;
2589			}
2590		}
2591	}
2592	if (someopen) {
2593		sio_timeouts_until_log = hz / sio_timeout;
2594		sio_timeout_handle = timeout(comwakeup, (void *)NULL,
2595					     sio_timeout);
2596	} else {
2597		/* Flush error messages, if any. */
2598		sio_timeouts_until_log = 1;
2599		comwakeup((void *)NULL);
2600		untimeout(comwakeup, (void *)NULL, sio_timeout_handle);
2601	}
2602}
2603
2604static void
2605comwakeup(chan)
2606	void	*chan;
2607{
2608	struct com_s	*com;
2609	int		unit;
2610
2611	sio_timeout_handle = timeout(comwakeup, (void *)NULL, sio_timeout);
2612
2613	/*
2614	 * Recover from lost output interrupts.
2615	 * Poll any lines that don't use interrupts.
2616	 */
2617	for (unit = 0; unit < sio_numunits; ++unit) {
2618		com = com_addr(unit);
2619		if (com != NULL && !com->gone
2620		    && (com->state >= (CS_BUSY | CS_TTGO) || com->poll)) {
2621			disable_intr();
2622			siointr1(com);
2623			enable_intr();
2624		}
2625	}
2626
2627	/*
2628	 * Check for and log errors, but not too often.
2629	 */
2630	if (--sio_timeouts_until_log > 0)
2631		return;
2632	sio_timeouts_until_log = hz / sio_timeout;
2633	for (unit = 0; unit < sio_numunits; ++unit) {
2634		int	errnum;
2635
2636		com = com_addr(unit);
2637		if (com == NULL)
2638			continue;
2639		if (com->gone)
2640			continue;
2641		for (errnum = 0; errnum < CE_NTYPES; ++errnum) {
2642			u_int	delta;
2643			u_long	total;
2644
2645			disable_intr();
2646			delta = com->delta_error_counts[errnum];
2647			com->delta_error_counts[errnum] = 0;
2648			enable_intr();
2649			if (delta == 0)
2650				continue;
2651			total = com->error_counts[errnum] += delta;
2652			log(LOG_ERR, "sio%d: %u more %s%s (total %lu)\n",
2653			    unit, delta, error_desc[errnum],
2654			    delta == 1 ? "" : "s", total);
2655		}
2656	}
2657}
2658
2659static void
2660disc_optim(tp, t, com)
2661	struct tty	*tp;
2662	struct termios	*t;
2663	struct com_s	*com;
2664{
2665	if (!(t->c_iflag & (ICRNL | IGNCR | IMAXBEL | INLCR | ISTRIP | IXON))
2666	    && (!(t->c_iflag & BRKINT) || (t->c_iflag & IGNBRK))
2667	    && (!(t->c_iflag & PARMRK)
2668		|| (t->c_iflag & (IGNPAR | IGNBRK)) == (IGNPAR | IGNBRK))
2669	    && !(t->c_lflag & (ECHO | ICANON | IEXTEN | ISIG | PENDIN))
2670	    && linesw[tp->t_line].l_rint == ttyinput)
2671		tp->t_state |= TS_CAN_BYPASS_L_RINT;
2672	else
2673		tp->t_state &= ~TS_CAN_BYPASS_L_RINT;
2674	com->hotchar = linesw[tp->t_line].l_hotchar;
2675}
2676
2677/*
2678 * Following are all routines needed for SIO to act as console
2679 */
2680#include <sys/cons.h>
2681
2682struct siocnstate {
2683	u_char	dlbl;
2684	u_char	dlbh;
2685	u_char	ier;
2686	u_char	cfcr;
2687	u_char	mcr;
2688};
2689
2690static speed_t siocngetspeed __P((Port_t, struct speedtab *));
2691static void siocnclose	__P((struct siocnstate *sp, Port_t iobase));
2692static void siocnopen	__P((struct siocnstate *sp, Port_t iobase, int speed));
2693static void siocntxwait	__P((Port_t iobase));
2694
2695static cn_probe_t siocnprobe;
2696static cn_init_t siocninit;
2697static cn_checkc_t siocncheckc;
2698static cn_getc_t siocngetc;
2699static cn_putc_t siocnputc;
2700
2701#ifdef __i386__
2702CONS_DRIVER(sio, siocnprobe, siocninit, NULL, siocngetc, siocncheckc,
2703	    siocnputc, NULL);
2704#endif
2705
2706/* To get the GDB related variables */
2707#if DDB > 0
2708#include <ddb/ddb.h>
2709#endif
2710
2711static void
2712siocntxwait(iobase)
2713	Port_t	iobase;
2714{
2715	int	timo;
2716
2717	/*
2718	 * Wait for any pending transmission to finish.  Required to avoid
2719	 * the UART lockup bug when the speed is changed, and for normal
2720	 * transmits.
2721	 */
2722	timo = 100000;
2723	while ((inb(iobase + com_lsr) & (LSR_TSRE | LSR_TXRDY))
2724	       != (LSR_TSRE | LSR_TXRDY) && --timo != 0)
2725		;
2726}
2727
2728/*
2729 * Read the serial port specified and try to figure out what speed
2730 * it's currently running at.  We're assuming the serial port has
2731 * been initialized and is basicly idle.  This routine is only intended
2732 * to be run at system startup.
2733 *
2734 * If the value read from the serial port doesn't make sense, return 0.
2735 */
2736
2737static speed_t
2738siocngetspeed(iobase, table)
2739	Port_t iobase;
2740	struct speedtab *table;
2741{
2742	int	code;
2743	u_char	dlbh;
2744	u_char	dlbl;
2745	u_char  cfcr;
2746
2747	cfcr = inb(iobase + com_cfcr);
2748	outb(iobase + com_cfcr, CFCR_DLAB | cfcr);
2749
2750	dlbl = inb(iobase + com_dlbl);
2751	dlbh = inb(iobase + com_dlbh);
2752
2753	outb(iobase + com_cfcr, cfcr);
2754
2755	code = dlbh << 8 | dlbl;
2756
2757	for (; table->sp_speed != -1; table++)
2758		if (table->sp_code == code)
2759			return (table->sp_speed);
2760
2761	return 0;	/* didn't match anything sane */
2762}
2763
2764static void
2765siocnopen(sp, iobase, speed)
2766	struct siocnstate	*sp;
2767	Port_t			iobase;
2768	int			speed;
2769{
2770	int	divisor;
2771	u_char	dlbh;
2772	u_char	dlbl;
2773
2774	/*
2775	 * Save all the device control registers except the fifo register
2776	 * and set our default ones (cs8 -parenb speed=comdefaultrate).
2777	 * We can't save the fifo register since it is read-only.
2778	 */
2779	sp->ier = inb(iobase + com_ier);
2780	outb(iobase + com_ier, 0);	/* spltty() doesn't stop siointr() */
2781	siocntxwait(iobase);
2782	sp->cfcr = inb(iobase + com_cfcr);
2783	outb(iobase + com_cfcr, CFCR_DLAB | CFCR_8BITS);
2784	sp->dlbl = inb(iobase + com_dlbl);
2785	sp->dlbh = inb(iobase + com_dlbh);
2786	/*
2787	 * Only set the divisor registers if they would change, since on
2788	 * some 16550 incompatibles (Startech), setting them clears the
2789	 * data input register.  This also reduces the effects of the
2790	 * UMC8669F bug.
2791	 */
2792	divisor = ttspeedtab(speed, comspeedtab);
2793	dlbl = divisor & 0xFF;
2794	if (sp->dlbl != dlbl)
2795		outb(iobase + com_dlbl, dlbl);
2796	dlbh = (u_int) divisor >> 8;
2797	if (sp->dlbh != dlbh)
2798		outb(iobase + com_dlbh, dlbh);
2799	outb(iobase + com_cfcr, CFCR_8BITS);
2800	sp->mcr = inb(iobase + com_mcr);
2801	/*
2802	 * We don't want interrupts, but must be careful not to "disable"
2803	 * them by clearing the MCR_IENABLE bit, since that might cause
2804	 * an interrupt by floating the IRQ line.
2805	 */
2806	outb(iobase + com_mcr, (sp->mcr & MCR_IENABLE) | MCR_DTR | MCR_RTS);
2807}
2808
2809static void
2810siocnclose(sp, iobase)
2811	struct siocnstate	*sp;
2812	Port_t			iobase;
2813{
2814	/*
2815	 * Restore the device control registers.
2816	 */
2817	siocntxwait(iobase);
2818	outb(iobase + com_cfcr, CFCR_DLAB | CFCR_8BITS);
2819	if (sp->dlbl != inb(iobase + com_dlbl))
2820		outb(iobase + com_dlbl, sp->dlbl);
2821	if (sp->dlbh != inb(iobase + com_dlbh))
2822		outb(iobase + com_dlbh, sp->dlbh);
2823	outb(iobase + com_cfcr, sp->cfcr);
2824	/*
2825	 * XXX damp oscillations of MCR_DTR and MCR_RTS by not restoring them.
2826	 */
2827	outb(iobase + com_mcr, sp->mcr | MCR_DTR | MCR_RTS);
2828	outb(iobase + com_ier, sp->ier);
2829}
2830
2831static void
2832siocnprobe(cp)
2833	struct consdev	*cp;
2834{
2835	speed_t			boot_speed;
2836	u_char			cfcr;
2837	int			s, unit;
2838	struct siocnstate	sp;
2839
2840	/*
2841	 * Find our first enabled console, if any.  If it is a high-level
2842	 * console device, then initialize it and return successfully.
2843	 * If it is a low-level console device, then initialize it and
2844	 * return unsuccessfully.  It must be initialized in both cases
2845	 * for early use by console drivers and debuggers.  Initializing
2846	 * the hardware is not necessary in all cases, since the i/o
2847	 * routines initialize it on the fly, but it is necessary if
2848	 * input might arrive while the hardware is switched back to an
2849	 * uninitialized state.  We can't handle multiple console devices
2850	 * yet because our low-level routines don't take a device arg.
2851	 * We trust the user to set the console flags properly so that we
2852	 * don't need to probe.
2853	 */
2854	cp->cn_pri = CN_DEAD;
2855
2856	for (unit = 0; unit < 16; unit++) { /* XXX need to know how many */
2857		int flags;
2858		int disabled;
2859		if (resource_int_value("sio", unit, "disabled", &disabled) == 0) {
2860			if (disabled)
2861				continue;
2862		}
2863		if (resource_int_value("sio", unit, "flags", &flags))
2864			continue;
2865		if (COM_CONSOLE(flags) || COM_DEBUGGER(flags)) {
2866			int port;
2867			Port_t iobase;
2868
2869			if (resource_int_value("sio", unit, "port", &port))
2870				continue;
2871			iobase = port;
2872			s = spltty();
2873			if (boothowto & RB_SERIAL) {
2874				boot_speed = siocngetspeed(iobase, comspeedtab);
2875				if (boot_speed)
2876					comdefaultrate = boot_speed;
2877			}
2878
2879			/*
2880			 * Initialize the divisor latch.  We can't rely on
2881			 * siocnopen() to do this the first time, since it
2882			 * avoids writing to the latch if the latch appears
2883			 * to have the correct value.  Also, if we didn't
2884			 * just read the speed from the hardware, then we
2885			 * need to set the speed in hardware so that
2886			 * switching it later is null.
2887			 */
2888			cfcr = inb(iobase + com_cfcr);
2889			outb(iobase + com_cfcr, CFCR_DLAB | cfcr);
2890			outb(iobase + com_dlbl,
2891			     COMBRD(comdefaultrate) & 0xff);
2892			outb(iobase + com_dlbh,
2893			     (u_int) COMBRD(comdefaultrate) >> 8);
2894			outb(iobase + com_cfcr, cfcr);
2895
2896			siocnopen(&sp, iobase, comdefaultrate);
2897
2898			splx(s);
2899			if (COM_CONSOLE(flags) && !COM_LLCONSOLE(flags)) {
2900				cp->cn_dev = makedev(CDEV_MAJOR, unit);
2901				cp->cn_pri = COM_FORCECONSOLE(flags)
2902					     || boothowto & RB_SERIAL
2903					     ? CN_REMOTE : CN_NORMAL;
2904				siocniobase = iobase;
2905				siocnunit = unit;
2906			}
2907			if (COM_DEBUGGER(flags)) {
2908				printf("sio%d: gdb debugging port\n", unit);
2909				siogdbiobase = iobase;
2910				siogdbunit = unit;
2911#if DDB > 0
2912				gdbdev = makedev(CDEV_MAJOR, unit);
2913				gdb_getc = siocngetc;
2914				gdb_putc = siocnputc;
2915#endif
2916			}
2917		}
2918	}
2919#ifdef	__i386__
2920#if DDB > 0
2921	/*
2922	 * XXX Ugly Compatability.
2923	 * If no gdb port has been specified, set it to be the console
2924	 * as some configuration files don't specify the gdb port.
2925	 */
2926	if (gdbdev == NODEV && (boothowto & RB_GDB)) {
2927		printf("Warning: no GDB port specified. Defaulting to sio%d.\n",
2928			siocnunit);
2929		printf("Set flag 0x80 on desired GDB port in your\n");
2930		printf("configuration file (currently sio only).\n");
2931		siogdbiobase = siocniobase;
2932		siogdbunit = siocnunit;
2933		gdbdev = makedev(CDEV_MAJOR, siocnunit);
2934		gdb_getc = siocngetc;
2935		gdb_putc = siocnputc;
2936	}
2937#endif
2938#endif
2939}
2940
2941#ifdef __alpha__
2942
2943CONS_DRIVER(sio, NULL, NULL, NULL, siocngetc, siocncheckc, siocnputc, NULL);
2944
2945int
2946siocnattach(port, speed)
2947	int port;
2948	int speed;
2949{
2950	int			s;
2951	u_char			cfcr;
2952	struct siocnstate	sp;
2953
2954	siocniobase = port;
2955	comdefaultrate = speed;
2956	sio_consdev.cn_pri = CN_NORMAL;
2957	sio_consdev.cn_dev = makedev(CDEV_MAJOR, 0);
2958
2959	s = spltty();
2960
2961	/*
2962	 * Initialize the divisor latch.  We can't rely on
2963	 * siocnopen() to do this the first time, since it
2964	 * avoids writing to the latch if the latch appears
2965	 * to have the correct value.  Also, if we didn't
2966	 * just read the speed from the hardware, then we
2967	 * need to set the speed in hardware so that
2968	 * switching it later is null.
2969	 */
2970	cfcr = inb(siocniobase + com_cfcr);
2971	outb(siocniobase + com_cfcr, CFCR_DLAB | cfcr);
2972	outb(siocniobase + com_dlbl,
2973	     COMBRD(comdefaultrate) & 0xff);
2974	outb(siocniobase + com_dlbh,
2975	     (u_int) COMBRD(comdefaultrate) >> 8);
2976	outb(siocniobase + com_cfcr, cfcr);
2977
2978	siocnopen(&sp, siocniobase, comdefaultrate);
2979	splx(s);
2980
2981	cn_tab = &sio_consdev;
2982	return 0;
2983}
2984
2985int
2986siogdbattach(port, speed)
2987	int port;
2988	int speed;
2989{
2990	int			s;
2991	u_char			cfcr;
2992	struct siocnstate	sp;
2993
2994	siogdbiobase = port;
2995	gdbdefaultrate = speed;
2996
2997	s = spltty();
2998
2999	/*
3000	 * Initialize the divisor latch.  We can't rely on
3001	 * siocnopen() to do this the first time, since it
3002	 * avoids writing to the latch if the latch appears
3003	 * to have the correct value.  Also, if we didn't
3004	 * just read the speed from the hardware, then we
3005	 * need to set the speed in hardware so that
3006	 * switching it later is null.
3007	 */
3008	cfcr = inb(siogdbiobase + com_cfcr);
3009	outb(siogdbiobase + com_cfcr, CFCR_DLAB | cfcr);
3010	outb(siogdbiobase + com_dlbl,
3011	     COMBRD(gdbdefaultrate) & 0xff);
3012	outb(siogdbiobase + com_dlbh,
3013	     (u_int) COMBRD(gdbdefaultrate) >> 8);
3014	outb(siogdbiobase + com_cfcr, cfcr);
3015
3016	siocnopen(&sp, siogdbiobase, gdbdefaultrate);
3017	splx(s);
3018
3019	return 0;
3020}
3021
3022#endif
3023
3024static void
3025siocninit(cp)
3026	struct consdev	*cp;
3027{
3028	comconsole = DEV_TO_UNIT(cp->cn_dev);
3029}
3030
3031static int
3032siocncheckc(dev)
3033	dev_t	dev;
3034{
3035	int	c;
3036	Port_t	iobase;
3037	int	s;
3038	struct siocnstate	sp;
3039
3040	if (minor(dev) == siogdbunit)
3041		iobase = siogdbiobase;
3042	else
3043		iobase = siocniobase;
3044	s = spltty();
3045	siocnopen(&sp, iobase, comdefaultrate);
3046	if (inb(iobase + com_lsr) & LSR_RXRDY)
3047		c = inb(iobase + com_data);
3048	else
3049		c = -1;
3050	siocnclose(&sp, iobase);
3051	splx(s);
3052	return (c);
3053}
3054
3055
3056int
3057siocngetc(dev)
3058	dev_t	dev;
3059{
3060	int	c;
3061	Port_t	iobase;
3062	int	s;
3063	struct siocnstate	sp;
3064
3065	if (minor(dev) == siogdbunit)
3066		iobase = siogdbiobase;
3067	else
3068		iobase = siocniobase;
3069	s = spltty();
3070	siocnopen(&sp, iobase, comdefaultrate);
3071	while (!(inb(iobase + com_lsr) & LSR_RXRDY))
3072		;
3073	c = inb(iobase + com_data);
3074	siocnclose(&sp, iobase);
3075	splx(s);
3076	return (c);
3077}
3078
3079void
3080siocnputc(dev, c)
3081	dev_t	dev;
3082	int	c;
3083{
3084	int	s;
3085	struct siocnstate	sp;
3086	Port_t	iobase;
3087
3088	if (minor(dev) == siogdbunit)
3089		iobase = siogdbiobase;
3090	else
3091		iobase = siocniobase;
3092	s = spltty();
3093	siocnopen(&sp, iobase, comdefaultrate);
3094	siocntxwait(iobase);
3095	outb(iobase + com_data, c);
3096	siocnclose(&sp, iobase);
3097	splx(s);
3098}
3099
3100#ifdef __alpha__
3101int
3102siogdbgetc()
3103{
3104	int	c;
3105	Port_t	iobase;
3106	int	s;
3107	struct siocnstate	sp;
3108
3109	iobase = siogdbiobase;
3110	s = spltty();
3111	siocnopen(&sp, iobase, gdbdefaultrate);
3112	while (!(inb(iobase + com_lsr) & LSR_RXRDY))
3113		;
3114	c = inb(iobase + com_data);
3115	siocnclose(&sp, iobase);
3116	splx(s);
3117	return (c);
3118}
3119
3120void
3121siogdbputc(c)
3122	int	c;
3123{
3124	int	s;
3125	struct siocnstate	sp;
3126
3127	s = spltty();
3128	siocnopen(&sp, siogdbiobase, gdbdefaultrate);
3129	siocntxwait(siogdbiobase);
3130	outb(siogdbiobase + com_data, c);
3131	siocnclose(&sp, siogdbiobase);
3132	splx(s);
3133}
3134#endif
3135
3136DRIVER_MODULE(sio, isa, sio_isa_driver, sio_devclass, 0, 0);
3137#if NCARD > 0
3138DRIVER_MODULE(sio, pccard, sio_pccard_driver, sio_devclass, 0, 0);
3139#endif
3140