sio.c revision 58377
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 58377 2000-03-20 14:09:06Z phk $
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/timetc.h>
72#include <sys/timepps.h>
73
74#include <isa/isareg.h>
75#include <isa/isavar.h>
76#include <machine/lock.h>
77
78#include <machine/clock.h>
79#include <machine/ipl.h>
80#ifndef SMP
81#include <machine/lock.h>
82#endif
83#include <machine/resource.h>
84
85#include <isa/sioreg.h>
86
87#ifdef COM_ESP
88#include <isa/ic/esp.h>
89#endif
90#include <isa/ic/ns16550.h>
91
92#ifndef __i386__
93#define disable_intr()
94#define enable_intr()
95#endif
96
97#ifdef SMP
98#define disable_intr()	COM_DISABLE_INTR()
99#define enable_intr()	COM_ENABLE_INTR()
100#endif /* SMP */
101
102#define	LOTS_OF_EVENTS	64	/* helps separate urgent events from input */
103
104#define	CALLOUT_MASK		0x80
105#define	CONTROL_MASK		0x60
106#define	CONTROL_INIT_STATE	0x20
107#define	CONTROL_LOCK_STATE	0x40
108#define	DEV_TO_UNIT(dev)	(MINOR_TO_UNIT(minor(dev)))
109#define	MINOR_MAGIC_MASK	(CALLOUT_MASK | CONTROL_MASK)
110#define	MINOR_TO_UNIT(mynor)	((mynor) & ~MINOR_MAGIC_MASK)
111
112#ifdef COM_MULTIPORT
113/* checks in flags for multiport and which is multiport "master chip"
114 * for a given card
115 */
116#define	COM_ISMULTIPORT(flags)	((flags) & 0x01)
117#define	COM_MPMASTER(flags)	(((flags) >> 8) & 0x0ff)
118#define	COM_NOTAST4(flags)	((flags) & 0x04)
119#endif /* COM_MULTIPORT */
120
121#define	COM_CONSOLE(flags)	((flags) & 0x10)
122#define	COM_FORCECONSOLE(flags)	((flags) & 0x20)
123#define	COM_LLCONSOLE(flags)	((flags) & 0x40)
124#define	COM_DEBUGGER(flags)	((flags) & 0x80)
125#define	COM_LOSESOUTINTS(flags)	((flags) & 0x08)
126#define	COM_NOFIFO(flags)		((flags) & 0x02)
127#define COM_ST16650A(flags)	((flags) & 0x20000)
128#define COM_C_NOPROBE		(0x40000)
129#define COM_NOPROBE(flags)	((flags) & COM_C_NOPROBE)
130#define COM_C_IIR_TXRDYBUG	(0x80000)
131#define COM_IIR_TXRDYBUG(flags)	((flags) & COM_C_IIR_TXRDYBUG)
132#define	COM_FIFOSIZE(flags)	(((flags) & 0xff000000) >> 24)
133
134#define	com_scr		7	/* scratch register for 16450-16550 (R/W) */
135
136/*
137 * com state bits.
138 * (CS_BUSY | CS_TTGO) and (CS_BUSY | CS_TTGO | CS_ODEVREADY) must be higher
139 * than the other bits so that they can be tested as a group without masking
140 * off the low bits.
141 *
142 * The following com and tty flags correspond closely:
143 *	CS_BUSY		= TS_BUSY (maintained by comstart(), siopoll() and
144 *				   comstop())
145 *	CS_TTGO		= ~TS_TTSTOP (maintained by comparam() and comstart())
146 *	CS_CTS_OFLOW	= CCTS_OFLOW (maintained by comparam())
147 *	CS_RTS_IFLOW	= CRTS_IFLOW (maintained by comparam())
148 * TS_FLUSH is not used.
149 * XXX I think TIOCSETA doesn't clear TS_TTSTOP when it clears IXON.
150 * XXX CS_*FLOW should be CF_*FLOW in com->flags (control flags not state).
151 */
152#define	CS_BUSY		0x80	/* output in progress */
153#define	CS_TTGO		0x40	/* output not stopped by XOFF */
154#define	CS_ODEVREADY	0x20	/* external device h/w ready (CTS) */
155#define	CS_CHECKMSR	1	/* check of MSR scheduled */
156#define	CS_CTS_OFLOW	2	/* use CTS output flow control */
157#define	CS_DTR_OFF	0x10	/* DTR held off */
158#define	CS_ODONE	4	/* output completed */
159#define	CS_RTS_IFLOW	8	/* use RTS input flow control */
160#define	CSE_BUSYCHECK	1	/* siobusycheck() scheduled */
161
162static	char const * const	error_desc[] = {
163#define	CE_OVERRUN			0
164	"silo overflow",
165#define	CE_INTERRUPT_BUF_OVERFLOW	1
166	"interrupt-level buffer overflow",
167#define	CE_TTY_BUF_OVERFLOW		2
168	"tty-level buffer overflow",
169};
170
171#define	CE_NTYPES			3
172#define	CE_RECORD(com, errnum)		(++(com)->delta_error_counts[errnum])
173
174/* types.  XXX - should be elsewhere */
175typedef u_int	Port_t;		/* hardware port */
176typedef u_char	bool_t;		/* boolean */
177
178/* queue of linear buffers */
179struct lbq {
180	u_char	*l_head;	/* next char to process */
181	u_char	*l_tail;	/* one past the last char to process */
182	struct lbq *l_next;	/* next in queue */
183	bool_t	l_queued;	/* nonzero if queued */
184};
185
186/* com device structure */
187struct com_s {
188	u_int	flags;		/* Copy isa device flags */
189	u_char	state;		/* miscellaneous flag bits */
190	bool_t  active_out;	/* nonzero if the callout device is open */
191	u_char	cfcr_image;	/* copy of value written to CFCR */
192#ifdef COM_ESP
193	bool_t	esp;		/* is this unit a hayes esp board? */
194#endif
195	u_char	extra_state;	/* more flag bits, separate for order trick */
196	u_char	fifo_image;	/* copy of value written to FIFO */
197	bool_t	hasfifo;	/* nonzero for 16550 UARTs */
198	bool_t	st16650a;	/* Is a Startech 16650A or RTS/CTS compat */
199	bool_t	loses_outints;	/* nonzero if device loses output interrupts */
200	u_char	mcr_image;	/* copy of value written to MCR */
201#ifdef COM_MULTIPORT
202	bool_t	multiport;	/* is this unit part of a multiport device? */
203#endif /* COM_MULTIPORT */
204	bool_t	no_irq;		/* nonzero if irq is not attached */
205	bool_t  gone;		/* hardware disappeared */
206	bool_t	poll;		/* nonzero if polling is required */
207	bool_t	poll_output;	/* nonzero if polling for output is required */
208	int	unit;		/* unit	number */
209	int	dtr_wait;	/* time to hold DTR down on close (* 1/hz) */
210	u_int	tx_fifo_size;
211	u_int	wopeners;	/* # processes waiting for DCD in open() */
212
213	/*
214	 * The high level of the driver never reads status registers directly
215	 * because there would be too many side effects to handle conveniently.
216	 * Instead, it reads copies of the registers stored here by the
217	 * interrupt handler.
218	 */
219	u_char	last_modem_status;	/* last MSR read by intr handler */
220	u_char	prev_modem_status;	/* last MSR handled by high level */
221
222	u_char	hotchar;	/* ldisc-specific char to be handled ASAP */
223	u_char	*ibuf;		/* start of input buffer */
224	u_char	*ibufend;	/* end of input buffer */
225	u_char	*ibufold;	/* old input buffer, to be freed */
226	u_char	*ihighwater;	/* threshold in input buffer */
227	u_char	*iptr;		/* next free spot in input buffer */
228	int	ibufsize;	/* size of ibuf (not include error bytes) */
229	int	ierroff;	/* offset of error bytes in ibuf */
230
231	struct lbq	obufq;	/* head of queue of output buffers */
232	struct lbq	obufs[2];	/* output buffers */
233
234	Port_t	data_port;	/* i/o ports */
235#ifdef COM_ESP
236	Port_t	esp_port;
237#endif
238	Port_t	int_id_port;
239	Port_t	iobase;
240	Port_t	modem_ctl_port;
241	Port_t	line_status_port;
242	Port_t	modem_status_port;
243	Port_t	intr_ctl_port;	/* Ports of IIR register */
244
245	struct tty	*tp;	/* cross reference */
246
247	/* Initial state. */
248	struct termios	it_in;	/* should be in struct tty */
249	struct termios	it_out;
250
251	/* Lock state. */
252	struct termios	lt_in;	/* should be in struct tty */
253	struct termios	lt_out;
254
255	bool_t	do_timestamp;
256	bool_t	do_dcd_timestamp;
257	struct timeval	timestamp;
258	struct timeval	dcd_timestamp;
259	struct	pps_state pps;
260
261	u_long	bytes_in;	/* statistics */
262	u_long	bytes_out;
263	u_int	delta_error_counts[CE_NTYPES];
264	u_long	error_counts[CE_NTYPES];
265
266	struct resource *irqres;
267	struct resource *ioportres;
268	void *cookie;
269
270	/*
271	 * Data area for output buffers.  Someday we should build the output
272	 * buffer queue without copying data.
273	 */
274	u_char	obuf1[256];
275	u_char	obuf2[256];
276};
277
278#ifdef COM_ESP
279static	int	espattach	__P((struct com_s *com, Port_t esp_port));
280#endif
281static	int	sioattach	__P((device_t dev));
282static	int	sio_isa_attach	__P((device_t dev));
283
284static	timeout_t siobusycheck;
285static	timeout_t siodtrwakeup;
286static	void	comhardclose	__P((struct com_s *com));
287static	void	sioinput	__P((struct com_s *com));
288static	void	siointr1	__P((struct com_s *com));
289static	void	siointr		__P((void *arg));
290static	int	commctl		__P((struct com_s *com, int bits, int how));
291static	int	comparam	__P((struct tty *tp, struct termios *t));
292static	swihand_t siopoll;
293static	int	sioprobe	__P((device_t dev));
294static	int	sio_isa_probe	__P((device_t dev));
295static	void	siosettimeout	__P((void));
296static	int	siosetwater	__P((struct com_s *com, speed_t speed));
297static	void	comstart	__P((struct tty *tp));
298static	void	comstop		__P((struct tty *tp, int rw));
299static	timeout_t comwakeup;
300static	void	disc_optim	__P((struct tty	*tp, struct termios *t,
301				     struct com_s *com));
302
303#if NCARD > 0
304static	int	sio_pccard_attach __P((device_t dev));
305static	int	sio_pccard_detach __P((device_t dev));
306static	int	sio_pccard_probe __P((device_t dev));
307#endif /* NCARD > 0 */
308
309static char driver_name[] = "sio";
310
311/* table and macro for fast conversion from a unit number to its com struct */
312static	devclass_t	sio_devclass;
313#define	com_addr(unit)	((struct com_s *) \
314			 devclass_get_softc(sio_devclass, unit))
315
316static device_method_t sio_isa_methods[] = {
317	/* Device interface */
318	DEVMETHOD(device_probe,		sio_isa_probe),
319	DEVMETHOD(device_attach,	sio_isa_attach),
320
321	{ 0, 0 }
322};
323
324static driver_t sio_isa_driver = {
325	driver_name,
326	sio_isa_methods,
327	sizeof(struct com_s),
328};
329
330#if NCARD > 0
331static device_method_t sio_pccard_methods[] = {
332	/* Device interface */
333	DEVMETHOD(device_probe,		sio_pccard_probe),
334	DEVMETHOD(device_attach,	sio_pccard_attach),
335	DEVMETHOD(device_detach,	sio_pccard_detach),
336
337	{ 0, 0 }
338};
339
340static driver_t sio_pccard_driver = {
341	driver_name,
342	sio_pccard_methods,
343	sizeof(struct com_s),
344};
345#endif (NCARD > 0)
346
347static	d_open_t	sioopen;
348static	d_close_t	sioclose;
349static	d_read_t	sioread;
350static	d_write_t	siowrite;
351static	d_ioctl_t	sioioctl;
352
353#define	CDEV_MAJOR	28
354static struct cdevsw sio_cdevsw = {
355	/* open */	sioopen,
356	/* close */	sioclose,
357	/* read */	sioread,
358	/* write */	siowrite,
359	/* ioctl */	sioioctl,
360	/* poll */	ttypoll,
361	/* mmap */	nommap,
362	/* strategy */	nostrategy,
363	/* name */	driver_name,
364	/* maj */	CDEV_MAJOR,
365	/* dump */	nodump,
366	/* psize */	nopsize,
367	/* flags */	D_TTY,
368	/* bmaj */	-1
369};
370
371int	comconsole = -1;
372static	volatile speed_t	comdefaultrate = CONSPEED;
373#ifdef __alpha__
374static	volatile speed_t	gdbdefaultrate = CONSPEED;
375#endif
376static	u_int	com_events;	/* input chars + weighted output completions */
377static	Port_t	siocniobase;
378static	int	siocnunit;
379static	Port_t	siogdbiobase;
380static	int	siogdbunit = -1;
381static	bool_t	sio_registered;
382static	int	sio_timeout;
383static	int	sio_timeouts_until_log;
384static	struct	callout_handle sio_timeout_handle
385    = CALLOUT_HANDLE_INITIALIZER(&sio_timeout_handle);
386static	int	sio_numunits;
387
388static	struct speedtab comspeedtab[] = {
389	{ 0,		0 },
390	{ 50,		COMBRD(50) },
391	{ 75,		COMBRD(75) },
392	{ 110,		COMBRD(110) },
393	{ 134,		COMBRD(134) },
394	{ 150,		COMBRD(150) },
395	{ 200,		COMBRD(200) },
396	{ 300,		COMBRD(300) },
397	{ 600,		COMBRD(600) },
398	{ 1200,		COMBRD(1200) },
399	{ 1800,		COMBRD(1800) },
400	{ 2400,		COMBRD(2400) },
401	{ 4800,		COMBRD(4800) },
402	{ 9600,		COMBRD(9600) },
403	{ 19200,	COMBRD(19200) },
404	{ 38400,	COMBRD(38400) },
405	{ 57600,	COMBRD(57600) },
406	{ 115200,	COMBRD(115200) },
407	{ -1,		-1 }
408};
409
410#ifdef COM_ESP
411/* XXX configure this properly. */
412static	Port_t	likely_com_ports[] = { 0x3f8, 0x2f8, 0x3e8, 0x2e8, };
413static	Port_t	likely_esp_ports[] = { 0x140, 0x180, 0x280, 0 };
414#endif
415
416/*
417 * handle sysctl read/write requests for console speed
418 *
419 * In addition to setting comdefaultrate for I/O through /dev/console,
420 * also set the initial and lock values for the /dev/ttyXX device
421 * if there is one associated with the console.  Finally, if the /dev/tty
422 * device has already been open, change the speed on the open running port
423 * itself.
424 */
425
426static int
427sysctl_machdep_comdefaultrate SYSCTL_HANDLER_ARGS
428{
429	int error, s;
430	speed_t newspeed;
431	struct com_s *com;
432	struct tty *tp;
433
434	newspeed = comdefaultrate;
435
436	error = sysctl_handle_opaque(oidp, &newspeed, sizeof newspeed, req);
437	if (error || !req->newptr)
438		return (error);
439
440	comdefaultrate = newspeed;
441
442	if (comconsole < 0)		/* serial console not selected? */
443		return (0);
444
445	com = com_addr(comconsole);
446	if (com == NULL)
447		return (ENXIO);
448
449	/*
450	 * set the initial and lock rates for /dev/ttydXX and /dev/cuaXX
451	 * (note, the lock rates really are boolean -- if non-zero, disallow
452	 *  speed changes)
453	 */
454	com->it_in.c_ispeed  = com->it_in.c_ospeed =
455	com->lt_in.c_ispeed  = com->lt_in.c_ospeed =
456	com->it_out.c_ispeed = com->it_out.c_ospeed =
457	com->lt_out.c_ispeed = com->lt_out.c_ospeed = comdefaultrate;
458
459	/*
460	 * if we're open, change the running rate too
461	 */
462	tp = com->tp;
463	if (tp && (tp->t_state & TS_ISOPEN)) {
464		tp->t_termios.c_ispeed =
465		tp->t_termios.c_ospeed = comdefaultrate;
466		s = spltty();
467		error = comparam(tp, &tp->t_termios);
468		splx(s);
469	}
470	return error;
471}
472
473SYSCTL_PROC(_machdep, OID_AUTO, conspeed, CTLTYPE_INT | CTLFLAG_RW,
474	    0, 0, sysctl_machdep_comdefaultrate, "I", "");
475
476#define SET_FLAG(dev, bit) device_set_flags(dev, device_get_flags(dev) | (bit))
477#define CLR_FLAG(dev, bit) device_set_flags(dev, device_get_flags(dev) & ~(bit))
478
479#if NCARD > 0
480static int
481sio_pccard_probe(dev)
482	device_t	dev;
483{
484	/* Do not probe IRQ - pccard doesn't turn on the interrupt line */
485	/* until bus_setup_intr */
486	SET_FLAG(dev, COM_C_NOPROBE);
487
488	return (sioprobe(dev));
489}
490
491static int
492sio_pccard_attach(dev)
493	device_t	dev;
494{
495	return (sioattach(dev));
496}
497
498/*
499 *	sio_detach - unload the driver and clear the table.
500 *	XXX TODO:
501 *	This is usually called when the card is ejected, but
502 *	can be caused by a modunload of a controller driver.
503 *	The idea is to reset the driver's view of the device
504 *	and ensure that any driver entry points such as
505 *	read and write do not hang.
506 */
507static int
508sio_pccard_detach(dev)
509	device_t	dev;
510{
511	struct com_s	*com;
512
513	com = (struct com_s *) device_get_softc(dev);
514	if (com == NULL) {
515		device_printf(dev, "NULL com in siounload\n");
516		return (0);
517	}
518	if (com->iobase == 0) {
519		device_printf(dev, "already unloaded!\n");
520		return (0);
521	}
522	com->gone = 1;
523	if (com->irqres) {
524		bus_teardown_intr(dev, com->irqres, com->cookie);
525		bus_release_resource(dev, SYS_RES_IRQ, 0, com->irqres);
526	}
527	if (com->ioportres)
528		bus_release_resource(dev, SYS_RES_IOPORT, 0, com->ioportres);
529	if (com->tp && (com->tp->t_state & TS_ISOPEN)) {
530		device_printf(dev, "still open, forcing close\n");
531		com->tp->t_gen++;
532		ttyclose(com->tp);
533		ttwakeup(com->tp);
534		ttwwakeup(com->tp);
535	} else {
536		if (com->ibuf != NULL)
537			free(com->ibuf, M_DEVBUF);
538	}
539	device_printf(dev, "unloaded\n");
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	if (com == NULL)
1429		return (ENODEV);
1430	tp = com->tp;
1431	s = spltty();
1432	(*linesw[tp->t_line].l_close)(tp, flag);
1433	disc_optim(tp, &tp->t_termios, com);
1434	comstop(tp, FREAD | FWRITE);
1435	comhardclose(com);
1436	ttyclose(tp);
1437	siosettimeout();
1438	splx(s);
1439	if (com->gone) {
1440		printf("sio%d: gone\n", com->unit);
1441		s = spltty();
1442		if (com->ibuf != NULL)
1443			free(com->ibuf, M_DEVBUF);
1444		bzero(tp, sizeof *tp);
1445		splx(s);
1446	}
1447	return (0);
1448}
1449
1450static void
1451comhardclose(com)
1452	struct com_s	*com;
1453{
1454	Port_t		iobase;
1455	int		s;
1456	struct tty	*tp;
1457	int		unit;
1458
1459	unit = com->unit;
1460	iobase = com->iobase;
1461	s = spltty();
1462	com->poll = FALSE;
1463	com->poll_output = FALSE;
1464	com->do_timestamp = FALSE;
1465	com->do_dcd_timestamp = FALSE;
1466	com->pps.ppsparam.mode = 0;
1467	outb(iobase + com_cfcr, com->cfcr_image &= ~CFCR_SBREAK);
1468	{
1469		outb(iobase + com_ier, 0);
1470		tp = com->tp;
1471		if (tp->t_cflag & HUPCL
1472		    /*
1473		     * XXX we will miss any carrier drop between here and the
1474		     * next open.  Perhaps we should watch DCD even when the
1475		     * port is closed; it is not sufficient to check it at
1476		     * the next open because it might go up and down while
1477		     * we're not watching.
1478		     */
1479		    || (!com->active_out
1480		        && !(com->prev_modem_status & MSR_DCD)
1481		        && !(com->it_in.c_cflag & CLOCAL))
1482		    || !(tp->t_state & TS_ISOPEN)) {
1483			(void)commctl(com, TIOCM_DTR, DMBIC);
1484			if (com->dtr_wait != 0 && !(com->state & CS_DTR_OFF)) {
1485				timeout(siodtrwakeup, com, com->dtr_wait);
1486				com->state |= CS_DTR_OFF;
1487			}
1488		}
1489	}
1490	if (com->hasfifo) {
1491		/*
1492		 * Disable fifos so that they are off after controlled
1493		 * reboots.  Some BIOSes fail to detect 16550s when the
1494		 * fifos are enabled.
1495		 */
1496		outb(iobase + com_fifo, 0);
1497	}
1498	com->active_out = FALSE;
1499	wakeup(&com->active_out);
1500	wakeup(TSA_CARR_ON(tp));	/* restart any wopeners */
1501	splx(s);
1502}
1503
1504static int
1505sioread(dev, uio, flag)
1506	dev_t		dev;
1507	struct uio	*uio;
1508	int		flag;
1509{
1510	int		mynor;
1511	struct com_s	*com;
1512
1513	mynor = minor(dev);
1514	if (mynor & CONTROL_MASK)
1515		return (ENODEV);
1516	com = com_addr(MINOR_TO_UNIT(mynor));
1517	if (com == NULL || com->gone)
1518		return (ENODEV);
1519	return ((*linesw[com->tp->t_line].l_read)(com->tp, uio, flag));
1520}
1521
1522static int
1523siowrite(dev, uio, flag)
1524	dev_t		dev;
1525	struct uio	*uio;
1526	int		flag;
1527{
1528	int		mynor;
1529	struct com_s	*com;
1530	int		unit;
1531
1532	mynor = minor(dev);
1533	if (mynor & CONTROL_MASK)
1534		return (ENODEV);
1535
1536	unit = MINOR_TO_UNIT(mynor);
1537	com = com_addr(unit);
1538	if (com == NULL || com->gone)
1539		return (ENODEV);
1540	/*
1541	 * (XXX) We disallow virtual consoles if the physical console is
1542	 * a serial port.  This is in case there is a display attached that
1543	 * is not the console.  In that situation we don't need/want the X
1544	 * server taking over the console.
1545	 */
1546	if (constty != NULL && unit == comconsole)
1547		constty = NULL;
1548	return ((*linesw[com->tp->t_line].l_write)(com->tp, uio, flag));
1549}
1550
1551static void
1552siobusycheck(chan)
1553	void	*chan;
1554{
1555	struct com_s	*com;
1556	int		s;
1557
1558	com = (struct com_s *)chan;
1559
1560	/*
1561	 * Clear TS_BUSY if low-level output is complete.
1562	 * spl locking is sufficient because siointr1() does not set CS_BUSY.
1563	 * If siointr1() clears CS_BUSY after we look at it, then we'll get
1564	 * called again.  Reading the line status port outside of siointr1()
1565	 * is safe because CS_BUSY is clear so there are no output interrupts
1566	 * to lose.
1567	 */
1568	s = spltty();
1569	if (com->state & CS_BUSY)
1570		com->extra_state &= ~CSE_BUSYCHECK;	/* False alarm. */
1571	else if ((inb(com->line_status_port) & (LSR_TSRE | LSR_TXRDY))
1572	    == (LSR_TSRE | LSR_TXRDY)) {
1573		com->tp->t_state &= ~TS_BUSY;
1574		ttwwakeup(com->tp);
1575		com->extra_state &= ~CSE_BUSYCHECK;
1576	} else
1577		timeout(siobusycheck, com, hz / 100);
1578	splx(s);
1579}
1580
1581static void
1582siodtrwakeup(chan)
1583	void	*chan;
1584{
1585	struct com_s	*com;
1586
1587	com = (struct com_s *)chan;
1588	com->state &= ~CS_DTR_OFF;
1589	wakeup(&com->dtr_wait);
1590}
1591
1592static void
1593sioinput(com)
1594	struct com_s	*com;
1595{
1596	u_char		*buf;
1597	int		incc;
1598	u_char		line_status;
1599	int		recv_data;
1600	struct tty	*tp;
1601
1602	buf = com->ibuf;
1603	tp = com->tp;
1604	if (!(tp->t_state & TS_ISOPEN) || !(tp->t_cflag & CREAD)) {
1605		com_events -= (com->iptr - com->ibuf);
1606		com->iptr = com->ibuf;
1607		return;
1608	}
1609	if (tp->t_state & TS_CAN_BYPASS_L_RINT) {
1610		/*
1611		 * Avoid the grotesquely inefficient lineswitch routine
1612		 * (ttyinput) in "raw" mode.  It usually takes about 450
1613		 * instructions (that's without canonical processing or echo!).
1614		 * slinput is reasonably fast (usually 40 instructions plus
1615		 * call overhead).
1616		 */
1617		do {
1618			enable_intr();
1619			incc = com->iptr - buf;
1620			if (tp->t_rawq.c_cc + incc > tp->t_ihiwat
1621			    && (com->state & CS_RTS_IFLOW
1622				|| tp->t_iflag & IXOFF)
1623			    && !(tp->t_state & TS_TBLOCK))
1624				ttyblock(tp);
1625			com->delta_error_counts[CE_TTY_BUF_OVERFLOW]
1626				+= b_to_q((char *)buf, incc, &tp->t_rawq);
1627			buf += incc;
1628			tk_nin += incc;
1629			tk_rawcc += incc;
1630			tp->t_rawcc += incc;
1631			ttwakeup(tp);
1632			if (tp->t_state & TS_TTSTOP
1633			    && (tp->t_iflag & IXANY
1634				|| tp->t_cc[VSTART] == tp->t_cc[VSTOP])) {
1635				tp->t_state &= ~TS_TTSTOP;
1636				tp->t_lflag &= ~FLUSHO;
1637				comstart(tp);
1638			}
1639			disable_intr();
1640		} while (buf < com->iptr);
1641	} else {
1642		do {
1643			enable_intr();
1644			line_status = buf[com->ierroff];
1645			recv_data = *buf++;
1646			if (line_status
1647			    & (LSR_BI | LSR_FE | LSR_OE | LSR_PE)) {
1648				if (line_status & LSR_BI)
1649					recv_data |= TTY_BI;
1650				if (line_status & LSR_FE)
1651					recv_data |= TTY_FE;
1652				if (line_status & LSR_OE)
1653					recv_data |= TTY_OE;
1654				if (line_status & LSR_PE)
1655					recv_data |= TTY_PE;
1656			}
1657			(*linesw[tp->t_line].l_rint)(recv_data, tp);
1658			disable_intr();
1659		} while (buf < com->iptr);
1660	}
1661	com_events -= (com->iptr - com->ibuf);
1662	com->iptr = com->ibuf;
1663
1664	/*
1665	 * There is now room for another low-level buffer full of input,
1666	 * so enable RTS if it is now disabled and there is room in the
1667	 * high-level buffer.
1668	 */
1669	if ((com->state & CS_RTS_IFLOW) && !(com->mcr_image & MCR_RTS) &&
1670	    !(tp->t_state & TS_TBLOCK))
1671		outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
1672}
1673
1674void
1675siointr(arg)
1676	void		*arg;
1677{
1678#ifndef COM_MULTIPORT
1679	COM_LOCK();
1680	siointr1((struct com_s *) arg);
1681	COM_UNLOCK();
1682#else /* COM_MULTIPORT */
1683	bool_t		possibly_more_intrs;
1684	int		unit;
1685	struct com_s	*com;
1686
1687	/*
1688	 * Loop until there is no activity on any port.  This is necessary
1689	 * to get an interrupt edge more than to avoid another interrupt.
1690	 * If the IRQ signal is just an OR of the IRQ signals from several
1691	 * devices, then the edge from one may be lost because another is
1692	 * on.
1693	 */
1694	COM_LOCK();
1695	do {
1696		possibly_more_intrs = FALSE;
1697		for (unit = 0; unit < sio_numunits; ++unit) {
1698			com = com_addr(unit);
1699			/*
1700			 * XXX COM_LOCK();
1701			 * would it work here, or be counter-productive?
1702			 */
1703			if (com != NULL
1704			    && !com->gone
1705			    && (inb(com->int_id_port) & IIR_IMASK)
1706			       != IIR_NOPEND) {
1707				siointr1(com);
1708				possibly_more_intrs = TRUE;
1709			}
1710			/* XXX COM_UNLOCK(); */
1711		}
1712	} while (possibly_more_intrs);
1713	COM_UNLOCK();
1714#endif /* COM_MULTIPORT */
1715}
1716
1717static void
1718siointr1(com)
1719	struct com_s	*com;
1720{
1721	u_char	line_status;
1722	u_char	modem_status;
1723	u_char	*ioptr;
1724	u_char	recv_data;
1725	u_char	int_ctl;
1726	u_char	int_ctl_new;
1727	struct	timecounter *tc;
1728	u_int	count;
1729
1730	int_ctl = inb(com->intr_ctl_port);
1731	int_ctl_new = int_ctl;
1732
1733	while (!com->gone) {
1734		if (com->pps.ppsparam.mode & PPS_CAPTUREBOTH) {
1735			modem_status = inb(com->modem_status_port);
1736		        if ((modem_status ^ com->last_modem_status) & MSR_DCD) {
1737				tc = timecounter;
1738				count = tc->tc_get_timecount(tc);
1739				pps_event(&com->pps, tc, count,
1740				    (modem_status & MSR_DCD) ?
1741				    PPS_CAPTUREASSERT : PPS_CAPTURECLEAR);
1742			}
1743		}
1744		line_status = inb(com->line_status_port);
1745
1746		/* input event? (check first to help avoid overruns) */
1747		while (line_status & LSR_RCV_MASK) {
1748			/* break/unnattached error bits or real input? */
1749			if (!(line_status & LSR_RXRDY))
1750				recv_data = 0;
1751			else
1752				recv_data = inb(com->data_port);
1753			if (line_status & (LSR_BI | LSR_FE | LSR_PE)) {
1754				/*
1755				 * Don't store BI if IGNBRK or FE/PE if IGNPAR.
1756				 * Otherwise, push the work to a higher level
1757				 * (to handle PARMRK) if we're bypassing.
1758				 * Otherwise, convert BI/FE and PE+INPCK to 0.
1759				 *
1760				 * This makes bypassing work right in the
1761				 * usual "raw" case (IGNBRK set, and IGNPAR
1762				 * and INPCK clear).
1763				 *
1764				 * Note: BI together with FE/PE means just BI.
1765				 */
1766				if (line_status & LSR_BI) {
1767#if defined(DDB) && defined(BREAK_TO_DEBUGGER)
1768					if (com->unit == comconsole) {
1769						breakpoint();
1770						goto cont;
1771					}
1772#endif
1773					if (com->tp == NULL
1774					    || com->tp->t_iflag & IGNBRK)
1775						goto cont;
1776				} else {
1777					if (com->tp == NULL
1778					    || com->tp->t_iflag & IGNPAR)
1779						goto cont;
1780				}
1781				if (com->tp->t_state & TS_CAN_BYPASS_L_RINT
1782				    && (line_status & (LSR_BI | LSR_FE)
1783					|| com->tp->t_iflag & INPCK))
1784					recv_data = 0;
1785			}
1786			++com->bytes_in;
1787			if (com->hotchar != 0 && recv_data == com->hotchar)
1788				setsofttty();
1789			ioptr = com->iptr;
1790			if (ioptr >= com->ibufend)
1791				CE_RECORD(com, CE_INTERRUPT_BUF_OVERFLOW);
1792			else {
1793				if (com->do_timestamp)
1794					microtime(&com->timestamp);
1795				++com_events;
1796				schedsofttty();
1797#if 0 /* for testing input latency vs efficiency */
1798if (com->iptr - com->ibuf == 8)
1799	setsofttty();
1800#endif
1801				ioptr[0] = recv_data;
1802				ioptr[com->ierroff] = line_status;
1803				com->iptr = ++ioptr;
1804				if (ioptr == com->ihighwater
1805				    && com->state & CS_RTS_IFLOW)
1806					outb(com->modem_ctl_port,
1807					     com->mcr_image &= ~MCR_RTS);
1808				if (line_status & LSR_OE)
1809					CE_RECORD(com, CE_OVERRUN);
1810			}
1811cont:
1812			/*
1813			 * "& 0x7F" is to avoid the gcc-1.40 generating a slow
1814			 * jump from the top of the loop to here
1815			 */
1816			line_status = inb(com->line_status_port) & 0x7F;
1817		}
1818
1819		/* modem status change? (always check before doing output) */
1820		modem_status = inb(com->modem_status_port);
1821		if (modem_status != com->last_modem_status) {
1822			if (com->do_dcd_timestamp
1823			    && !(com->last_modem_status & MSR_DCD)
1824			    && modem_status & MSR_DCD)
1825				microtime(&com->dcd_timestamp);
1826
1827			/*
1828			 * Schedule high level to handle DCD changes.  Note
1829			 * that we don't use the delta bits anywhere.  Some
1830			 * UARTs mess them up, and it's easy to remember the
1831			 * previous bits and calculate the delta.
1832			 */
1833			com->last_modem_status = modem_status;
1834			if (!(com->state & CS_CHECKMSR)) {
1835				com_events += LOTS_OF_EVENTS;
1836				com->state |= CS_CHECKMSR;
1837				setsofttty();
1838			}
1839
1840			/* handle CTS change immediately for crisp flow ctl */
1841			if (com->state & CS_CTS_OFLOW) {
1842				if (modem_status & MSR_CTS)
1843					com->state |= CS_ODEVREADY;
1844				else
1845					com->state &= ~CS_ODEVREADY;
1846			}
1847		}
1848
1849		/* output queued and everything ready? */
1850		if (line_status & LSR_TXRDY
1851		    && com->state >= (CS_BUSY | CS_TTGO | CS_ODEVREADY)) {
1852			ioptr = com->obufq.l_head;
1853			if (com->tx_fifo_size > 1) {
1854				u_int	ocount;
1855
1856				ocount = com->obufq.l_tail - ioptr;
1857				if (ocount > com->tx_fifo_size)
1858					ocount = com->tx_fifo_size;
1859				com->bytes_out += ocount;
1860				do
1861					outb(com->data_port, *ioptr++);
1862				while (--ocount != 0);
1863			} else {
1864				outb(com->data_port, *ioptr++);
1865				++com->bytes_out;
1866			}
1867			com->obufq.l_head = ioptr;
1868			if (COM_IIR_TXRDYBUG(com->flags)) {
1869				int_ctl_new = int_ctl | IER_ETXRDY;
1870			}
1871			if (ioptr >= com->obufq.l_tail) {
1872				struct lbq	*qp;
1873
1874				qp = com->obufq.l_next;
1875				qp->l_queued = FALSE;
1876				qp = qp->l_next;
1877				if (qp != NULL) {
1878					com->obufq.l_head = qp->l_head;
1879					com->obufq.l_tail = qp->l_tail;
1880					com->obufq.l_next = qp;
1881				} else {
1882					/* output just completed */
1883					if (COM_IIR_TXRDYBUG(com->flags)) {
1884						int_ctl_new = int_ctl & ~IER_ETXRDY;
1885					}
1886					com->state &= ~CS_BUSY;
1887				}
1888				if (!(com->state & CS_ODONE)) {
1889					com_events += LOTS_OF_EVENTS;
1890					com->state |= CS_ODONE;
1891					setsofttty();	/* handle at high level ASAP */
1892				}
1893			}
1894			if (COM_IIR_TXRDYBUG(com->flags) && (int_ctl != int_ctl_new)) {
1895				outb(com->intr_ctl_port, int_ctl_new);
1896			}
1897		}
1898
1899		/* finished? */
1900#ifndef COM_MULTIPORT
1901		if ((inb(com->int_id_port) & IIR_IMASK) == IIR_NOPEND)
1902#endif /* COM_MULTIPORT */
1903			return;
1904	}
1905}
1906
1907static int
1908sioioctl(dev, cmd, data, flag, p)
1909	dev_t		dev;
1910	u_long		cmd;
1911	caddr_t		data;
1912	int		flag;
1913	struct proc	*p;
1914{
1915	struct com_s	*com;
1916	int		error;
1917	Port_t		iobase;
1918	int		mynor;
1919	int		s;
1920	struct tty	*tp;
1921#if defined(COMPAT_43) || defined(COMPAT_SUNOS)
1922	u_long		oldcmd;
1923	struct termios	term;
1924#endif
1925
1926	mynor = minor(dev);
1927	com = com_addr(MINOR_TO_UNIT(mynor));
1928	if (com == NULL || com->gone)
1929		return (ENODEV);
1930	iobase = com->iobase;
1931	if (mynor & CONTROL_MASK) {
1932		struct termios	*ct;
1933
1934		switch (mynor & CONTROL_MASK) {
1935		case CONTROL_INIT_STATE:
1936			ct = mynor & CALLOUT_MASK ? &com->it_out : &com->it_in;
1937			break;
1938		case CONTROL_LOCK_STATE:
1939			ct = mynor & CALLOUT_MASK ? &com->lt_out : &com->lt_in;
1940			break;
1941		default:
1942			return (ENODEV);	/* /dev/nodev */
1943		}
1944		switch (cmd) {
1945		case TIOCSETA:
1946			error = suser(p);
1947			if (error != 0)
1948				return (error);
1949			*ct = *(struct termios *)data;
1950			return (0);
1951		case TIOCGETA:
1952			*(struct termios *)data = *ct;
1953			return (0);
1954		case TIOCGETD:
1955			*(int *)data = TTYDISC;
1956			return (0);
1957		case TIOCGWINSZ:
1958			bzero(data, sizeof(struct winsize));
1959			return (0);
1960		default:
1961			return (ENOTTY);
1962		}
1963	}
1964	tp = com->tp;
1965#if defined(COMPAT_43) || defined(COMPAT_SUNOS)
1966	term = tp->t_termios;
1967	oldcmd = cmd;
1968	error = ttsetcompat(tp, &cmd, data, &term);
1969	if (error != 0)
1970		return (error);
1971	if (cmd != oldcmd)
1972		data = (caddr_t)&term;
1973#endif
1974	if (cmd == TIOCSETA || cmd == TIOCSETAW || cmd == TIOCSETAF) {
1975		int	cc;
1976		struct termios *dt = (struct termios *)data;
1977		struct termios *lt = mynor & CALLOUT_MASK
1978				     ? &com->lt_out : &com->lt_in;
1979
1980		dt->c_iflag = (tp->t_iflag & lt->c_iflag)
1981			      | (dt->c_iflag & ~lt->c_iflag);
1982		dt->c_oflag = (tp->t_oflag & lt->c_oflag)
1983			      | (dt->c_oflag & ~lt->c_oflag);
1984		dt->c_cflag = (tp->t_cflag & lt->c_cflag)
1985			      | (dt->c_cflag & ~lt->c_cflag);
1986		dt->c_lflag = (tp->t_lflag & lt->c_lflag)
1987			      | (dt->c_lflag & ~lt->c_lflag);
1988		for (cc = 0; cc < NCCS; ++cc)
1989			if (lt->c_cc[cc] != 0)
1990				dt->c_cc[cc] = tp->t_cc[cc];
1991		if (lt->c_ispeed != 0)
1992			dt->c_ispeed = tp->t_ispeed;
1993		if (lt->c_ospeed != 0)
1994			dt->c_ospeed = tp->t_ospeed;
1995	}
1996	error = (*linesw[tp->t_line].l_ioctl)(tp, cmd, data, flag, p);
1997	if (error != ENOIOCTL)
1998		return (error);
1999	s = spltty();
2000	error = ttioctl(tp, cmd, data, flag);
2001	disc_optim(tp, &tp->t_termios, com);
2002	if (error != ENOIOCTL) {
2003		splx(s);
2004		return (error);
2005	}
2006	switch (cmd) {
2007	case TIOCSBRK:
2008		outb(iobase + com_cfcr, com->cfcr_image |= CFCR_SBREAK);
2009		break;
2010	case TIOCCBRK:
2011		outb(iobase + com_cfcr, com->cfcr_image &= ~CFCR_SBREAK);
2012		break;
2013	case TIOCSDTR:
2014		(void)commctl(com, TIOCM_DTR, DMBIS);
2015		break;
2016	case TIOCCDTR:
2017		(void)commctl(com, TIOCM_DTR, DMBIC);
2018		break;
2019	/*
2020	 * XXX should disallow changing MCR_RTS if CS_RTS_IFLOW is set.  The
2021	 * changes get undone on the next call to comparam().
2022	 */
2023	case TIOCMSET:
2024		(void)commctl(com, *(int *)data, DMSET);
2025		break;
2026	case TIOCMBIS:
2027		(void)commctl(com, *(int *)data, DMBIS);
2028		break;
2029	case TIOCMBIC:
2030		(void)commctl(com, *(int *)data, DMBIC);
2031		break;
2032	case TIOCMGET:
2033		*(int *)data = commctl(com, 0, DMGET);
2034		break;
2035	case TIOCMSDTRWAIT:
2036		/* must be root since the wait applies to following logins */
2037		error = suser(p);
2038		if (error != 0) {
2039			splx(s);
2040			return (error);
2041		}
2042		com->dtr_wait = *(int *)data * hz / 100;
2043		break;
2044	case TIOCMGDTRWAIT:
2045		*(int *)data = com->dtr_wait * 100 / hz;
2046		break;
2047	case TIOCTIMESTAMP:
2048		com->do_timestamp = TRUE;
2049		*(struct timeval *)data = com->timestamp;
2050		break;
2051	case TIOCDCDTIMESTAMP:
2052		com->do_dcd_timestamp = TRUE;
2053		*(struct timeval *)data = com->dcd_timestamp;
2054		break;
2055	default:
2056		splx(s);
2057		error = pps_ioctl(cmd, data, &com->pps);
2058		if (error == ENODEV)
2059			error = ENOTTY;
2060		return (error);
2061	}
2062	splx(s);
2063	return (0);
2064}
2065
2066static void
2067siopoll()
2068{
2069	int		unit;
2070
2071	if (com_events == 0)
2072		return;
2073repeat:
2074	for (unit = 0; unit < sio_numunits; ++unit) {
2075		struct com_s	*com;
2076		int		incc;
2077		struct tty	*tp;
2078
2079		com = com_addr(unit);
2080		if (com == NULL)
2081			continue;
2082		tp = com->tp;
2083		if (tp == NULL || com->gone) {
2084			/*
2085			 * Discard any events related to never-opened or
2086			 * going-away devices.
2087			 */
2088			disable_intr();
2089			incc = com->iptr - com->ibuf;
2090			com->iptr = com->ibuf;
2091			if (com->state & CS_CHECKMSR) {
2092				incc += LOTS_OF_EVENTS;
2093				com->state &= ~CS_CHECKMSR;
2094			}
2095			com_events -= incc;
2096			enable_intr();
2097			continue;
2098		}
2099		if (com->iptr != com->ibuf) {
2100			disable_intr();
2101			sioinput(com);
2102			enable_intr();
2103		}
2104		if (com->state & CS_CHECKMSR) {
2105			u_char	delta_modem_status;
2106
2107			disable_intr();
2108			delta_modem_status = com->last_modem_status
2109					     ^ com->prev_modem_status;
2110			com->prev_modem_status = com->last_modem_status;
2111			com_events -= LOTS_OF_EVENTS;
2112			com->state &= ~CS_CHECKMSR;
2113			enable_intr();
2114			if (delta_modem_status & MSR_DCD)
2115				(*linesw[tp->t_line].l_modem)
2116					(tp, com->prev_modem_status & MSR_DCD);
2117		}
2118		if (com->state & CS_ODONE) {
2119			disable_intr();
2120			com_events -= LOTS_OF_EVENTS;
2121			com->state &= ~CS_ODONE;
2122			enable_intr();
2123			if (!(com->state & CS_BUSY)
2124			    && !(com->extra_state & CSE_BUSYCHECK)) {
2125				timeout(siobusycheck, com, hz / 100);
2126				com->extra_state |= CSE_BUSYCHECK;
2127			}
2128			(*linesw[tp->t_line].l_start)(tp);
2129		}
2130		if (com_events == 0)
2131			break;
2132	}
2133	if (com_events >= LOTS_OF_EVENTS)
2134		goto repeat;
2135}
2136
2137static int
2138comparam(tp, t)
2139	struct tty	*tp;
2140	struct termios	*t;
2141{
2142	u_int		cfcr;
2143	int		cflag;
2144	struct com_s	*com;
2145	int		divisor;
2146	u_char		dlbh;
2147	u_char		dlbl;
2148	Port_t		iobase;
2149	int		s;
2150	int		unit;
2151
2152	/* do historical conversions */
2153	if (t->c_ispeed == 0)
2154		t->c_ispeed = t->c_ospeed;
2155
2156	/* check requested parameters */
2157	divisor = ttspeedtab(t->c_ospeed, comspeedtab);
2158	if (divisor < 0 || (divisor > 0 && t->c_ispeed != t->c_ospeed))
2159		return (EINVAL);
2160
2161	/* parameters are OK, convert them to the com struct and the device */
2162	unit = DEV_TO_UNIT(tp->t_dev);
2163	com = com_addr(unit);
2164	if (com == NULL)
2165		return (ENODEV);
2166	iobase = com->iobase;
2167	s = spltty();
2168	if (divisor == 0)
2169		(void)commctl(com, TIOCM_DTR, DMBIC);	/* hang up line */
2170	else
2171		(void)commctl(com, TIOCM_DTR, DMBIS);
2172	cflag = t->c_cflag;
2173	switch (cflag & CSIZE) {
2174	case CS5:
2175		cfcr = CFCR_5BITS;
2176		break;
2177	case CS6:
2178		cfcr = CFCR_6BITS;
2179		break;
2180	case CS7:
2181		cfcr = CFCR_7BITS;
2182		break;
2183	default:
2184		cfcr = CFCR_8BITS;
2185		break;
2186	}
2187	if (cflag & PARENB) {
2188		cfcr |= CFCR_PENAB;
2189		if (!(cflag & PARODD))
2190			cfcr |= CFCR_PEVEN;
2191	}
2192	if (cflag & CSTOPB)
2193		cfcr |= CFCR_STOPB;
2194
2195	if (com->hasfifo && divisor != 0) {
2196		/*
2197		 * Use a fifo trigger level low enough so that the input
2198		 * latency from the fifo is less than about 16 msec and
2199		 * the total latency is less than about 30 msec.  These
2200		 * latencies are reasonable for humans.  Serial comms
2201		 * protocols shouldn't expect anything better since modem
2202		 * latencies are larger.
2203		 */
2204		com->fifo_image = t->c_ospeed <= 4800
2205				  ? FIFO_ENABLE : FIFO_ENABLE | FIFO_RX_HIGH;
2206#ifdef COM_ESP
2207		/*
2208		 * The Hayes ESP card needs the fifo DMA mode bit set
2209		 * in compatibility mode.  If not, it will interrupt
2210		 * for each character received.
2211		 */
2212		if (com->esp)
2213			com->fifo_image |= FIFO_DMA_MODE;
2214#endif
2215		outb(iobase + com_fifo, com->fifo_image);
2216	}
2217
2218	/*
2219	 * This returns with interrupts disabled so that we can complete
2220	 * the speed change atomically.  Keeping interrupts disabled is
2221	 * especially important while com_data is hidden.
2222	 */
2223	(void) siosetwater(com, t->c_ispeed);
2224
2225	if (divisor != 0) {
2226		outb(iobase + com_cfcr, cfcr | CFCR_DLAB);
2227		/*
2228		 * Only set the divisor registers if they would change,
2229		 * since on some 16550 incompatibles (UMC8669F), setting
2230		 * them while input is arriving them loses sync until
2231		 * data stops arriving.
2232		 */
2233		dlbl = divisor & 0xFF;
2234		if (inb(iobase + com_dlbl) != dlbl)
2235			outb(iobase + com_dlbl, dlbl);
2236		dlbh = (u_int) divisor >> 8;
2237		if (inb(iobase + com_dlbh) != dlbh)
2238			outb(iobase + com_dlbh, dlbh);
2239	}
2240
2241
2242	outb(iobase + com_cfcr, com->cfcr_image = cfcr);
2243
2244	if (!(tp->t_state & TS_TTSTOP))
2245		com->state |= CS_TTGO;
2246
2247	if (cflag & CRTS_IFLOW) {
2248		if (com->st16650a) {
2249			outb(iobase + com_cfcr, 0xbf);
2250			outb(iobase + com_fifo, inb(iobase + com_fifo) | 0x40);
2251		}
2252		com->state |= CS_RTS_IFLOW;
2253		/*
2254		 * If CS_RTS_IFLOW just changed from off to on, the change
2255		 * needs to be propagated to MCR_RTS.  This isn't urgent,
2256		 * so do it later by calling comstart() instead of repeating
2257		 * a lot of code from comstart() here.
2258		 */
2259	} else if (com->state & CS_RTS_IFLOW) {
2260		com->state &= ~CS_RTS_IFLOW;
2261		/*
2262		 * CS_RTS_IFLOW just changed from on to off.  Force MCR_RTS
2263		 * on here, since comstart() won't do it later.
2264		 */
2265		outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
2266		if (com->st16650a) {
2267			outb(iobase + com_cfcr, 0xbf);
2268			outb(iobase + com_fifo, inb(iobase + com_fifo) & ~0x40);
2269		}
2270	}
2271
2272
2273	/*
2274	 * Set up state to handle output flow control.
2275	 * XXX - worth handling MDMBUF (DCD) flow control at the lowest level?
2276	 * Now has 10+ msec latency, while CTS flow has 50- usec latency.
2277	 */
2278	com->state |= CS_ODEVREADY;
2279	com->state &= ~CS_CTS_OFLOW;
2280	if (cflag & CCTS_OFLOW) {
2281		com->state |= CS_CTS_OFLOW;
2282		if (!(com->last_modem_status & MSR_CTS))
2283			com->state &= ~CS_ODEVREADY;
2284		if (com->st16650a) {
2285			outb(iobase + com_cfcr, 0xbf);
2286			outb(iobase + com_fifo, inb(iobase + com_fifo) | 0x80);
2287		}
2288	} else {
2289		if (com->st16650a) {
2290			outb(iobase + com_cfcr, 0xbf);
2291			outb(iobase + com_fifo, inb(iobase + com_fifo) & ~0x80);
2292		}
2293	}
2294
2295
2296	outb(iobase + com_cfcr, com->cfcr_image);
2297
2298
2299	/* XXX shouldn't call functions while intrs are disabled. */
2300	disc_optim(tp, t, com);
2301	/*
2302	 * Recover from fiddling with CS_TTGO.  We used to call siointr1()
2303	 * unconditionally, but that defeated the careful discarding of
2304	 * stale input in sioopen().
2305	 */
2306	if (com->state >= (CS_BUSY | CS_TTGO))
2307		siointr1(com);
2308
2309	enable_intr();
2310	splx(s);
2311	comstart(tp);
2312	if (com->ibufold != NULL) {
2313		free(com->ibufold, M_DEVBUF);
2314		com->ibufold = NULL;
2315	}
2316	return (0);
2317}
2318
2319static int
2320siosetwater(com, speed)
2321	struct com_s	*com;
2322	speed_t		speed;
2323{
2324	int		cp4ticks;
2325	u_char		*ibuf;
2326	int		ibufsize;
2327	struct tty	*tp;
2328
2329	/*
2330	 * Make the buffer size large enough to handle a softtty interrupt
2331	 * latency of about 2 ticks without loss of throughput or data
2332	 * (about 3 ticks if input flow control is not used or not honoured,
2333	 * but a bit less for CS5-CS7 modes).
2334	 */
2335	cp4ticks = speed / 10 / hz * 4;
2336	for (ibufsize = 128; ibufsize < cp4ticks;)
2337		ibufsize <<= 1;
2338	if (ibufsize == com->ibufsize) {
2339		disable_intr();
2340		return (0);
2341	}
2342
2343	/*
2344	 * Allocate input buffer.  The extra factor of 2 in the size is
2345	 * to allow for an error byte for each input byte.
2346	 */
2347	ibuf = malloc(2 * ibufsize, M_DEVBUF, M_NOWAIT);
2348	if (ibuf == NULL) {
2349		disable_intr();
2350		return (ENOMEM);
2351	}
2352
2353	/* Initialize non-critical variables. */
2354	com->ibufold = com->ibuf;
2355	com->ibufsize = ibufsize;
2356	tp = com->tp;
2357	if (tp != NULL) {
2358		tp->t_ififosize = 2 * ibufsize;
2359		tp->t_ispeedwat = (speed_t)-1;
2360		tp->t_ospeedwat = (speed_t)-1;
2361	}
2362
2363	/*
2364	 * Read current input buffer, if any.  Continue with interrupts
2365	 * disabled.
2366	 */
2367	disable_intr();
2368	if (com->iptr != com->ibuf)
2369		sioinput(com);
2370
2371	/*-
2372	 * Initialize critical variables, including input buffer watermarks.
2373	 * The external device is asked to stop sending when the buffer
2374	 * exactly reaches high water, or when the high level requests it.
2375	 * The high level is notified immediately (rather than at a later
2376	 * clock tick) when this watermark is reached.
2377	 * The buffer size is chosen so the watermark should almost never
2378	 * be reached.
2379	 * The low watermark is invisibly 0 since the buffer is always
2380	 * emptied all at once.
2381	 */
2382	com->iptr = com->ibuf = ibuf;
2383	com->ibufend = ibuf + ibufsize;
2384	com->ierroff = ibufsize;
2385	com->ihighwater = ibuf + 3 * ibufsize / 4;
2386	return (0);
2387}
2388
2389static void
2390comstart(tp)
2391	struct tty	*tp;
2392{
2393	struct com_s	*com;
2394	int		s;
2395	int		unit;
2396
2397	unit = DEV_TO_UNIT(tp->t_dev);
2398	com = com_addr(unit);
2399	if (com == NULL)
2400		return;
2401	s = spltty();
2402	disable_intr();
2403	if (tp->t_state & TS_TTSTOP)
2404		com->state &= ~CS_TTGO;
2405	else
2406		com->state |= CS_TTGO;
2407	if (tp->t_state & TS_TBLOCK) {
2408		if (com->mcr_image & MCR_RTS && com->state & CS_RTS_IFLOW)
2409			outb(com->modem_ctl_port, com->mcr_image &= ~MCR_RTS);
2410	} else {
2411		if (!(com->mcr_image & MCR_RTS) && com->iptr < com->ihighwater
2412		    && com->state & CS_RTS_IFLOW)
2413			outb(com->modem_ctl_port, com->mcr_image |= MCR_RTS);
2414	}
2415	enable_intr();
2416	if (tp->t_state & (TS_TIMEOUT | TS_TTSTOP)) {
2417		ttwwakeup(tp);
2418		splx(s);
2419		return;
2420	}
2421	if (tp->t_outq.c_cc != 0) {
2422		struct lbq	*qp;
2423		struct lbq	*next;
2424
2425		if (!com->obufs[0].l_queued) {
2426			com->obufs[0].l_tail
2427			    = com->obuf1 + q_to_b(&tp->t_outq, com->obuf1,
2428						  sizeof com->obuf1);
2429			com->obufs[0].l_next = NULL;
2430			com->obufs[0].l_queued = TRUE;
2431			disable_intr();
2432			if (com->state & CS_BUSY) {
2433				qp = com->obufq.l_next;
2434				while ((next = qp->l_next) != NULL)
2435					qp = next;
2436				qp->l_next = &com->obufs[0];
2437			} else {
2438				com->obufq.l_head = com->obufs[0].l_head;
2439				com->obufq.l_tail = com->obufs[0].l_tail;
2440				com->obufq.l_next = &com->obufs[0];
2441				com->state |= CS_BUSY;
2442			}
2443			enable_intr();
2444		}
2445		if (tp->t_outq.c_cc != 0 && !com->obufs[1].l_queued) {
2446			com->obufs[1].l_tail
2447			    = com->obuf2 + q_to_b(&tp->t_outq, com->obuf2,
2448						  sizeof com->obuf2);
2449			com->obufs[1].l_next = NULL;
2450			com->obufs[1].l_queued = TRUE;
2451			disable_intr();
2452			if (com->state & CS_BUSY) {
2453				qp = com->obufq.l_next;
2454				while ((next = qp->l_next) != NULL)
2455					qp = next;
2456				qp->l_next = &com->obufs[1];
2457			} else {
2458				com->obufq.l_head = com->obufs[1].l_head;
2459				com->obufq.l_tail = com->obufs[1].l_tail;
2460				com->obufq.l_next = &com->obufs[1];
2461				com->state |= CS_BUSY;
2462			}
2463			enable_intr();
2464		}
2465		tp->t_state |= TS_BUSY;
2466	}
2467	disable_intr();
2468	if (com->state >= (CS_BUSY | CS_TTGO))
2469		siointr1(com);	/* fake interrupt to start output */
2470	enable_intr();
2471	ttwwakeup(tp);
2472	splx(s);
2473}
2474
2475static void
2476comstop(tp, rw)
2477	struct tty	*tp;
2478	int		rw;
2479{
2480	struct com_s	*com;
2481
2482	com = com_addr(DEV_TO_UNIT(tp->t_dev));
2483	if (com == NULL || com->gone)
2484		return;
2485	disable_intr();
2486	if (rw & FWRITE) {
2487		if (com->hasfifo)
2488#ifdef COM_ESP
2489		    /* XXX avoid h/w bug. */
2490		    if (!com->esp)
2491#endif
2492			outb(com->iobase + com_fifo,
2493			     FIFO_XMT_RST | com->fifo_image);
2494		com->obufs[0].l_queued = FALSE;
2495		com->obufs[1].l_queued = FALSE;
2496		if (com->state & CS_ODONE)
2497			com_events -= LOTS_OF_EVENTS;
2498		com->state &= ~(CS_ODONE | CS_BUSY);
2499		com->tp->t_state &= ~TS_BUSY;
2500	}
2501	if (rw & FREAD) {
2502		if (com->hasfifo)
2503#ifdef COM_ESP
2504		    /* XXX avoid h/w bug. */
2505		    if (!com->esp)
2506#endif
2507			outb(com->iobase + com_fifo,
2508			     FIFO_RCV_RST | com->fifo_image);
2509		com_events -= (com->iptr - com->ibuf);
2510		com->iptr = com->ibuf;
2511	}
2512	enable_intr();
2513	comstart(tp);
2514}
2515
2516static int
2517commctl(com, bits, how)
2518	struct com_s	*com;
2519	int		bits;
2520	int		how;
2521{
2522	int	mcr;
2523	int	msr;
2524
2525	if (how == DMGET) {
2526		bits = TIOCM_LE;	/* XXX - always enabled while open */
2527		mcr = com->mcr_image;
2528		if (mcr & MCR_DTR)
2529			bits |= TIOCM_DTR;
2530		if (mcr & MCR_RTS)
2531			bits |= TIOCM_RTS;
2532		msr = com->prev_modem_status;
2533		if (msr & MSR_CTS)
2534			bits |= TIOCM_CTS;
2535		if (msr & MSR_DCD)
2536			bits |= TIOCM_CD;
2537		if (msr & MSR_DSR)
2538			bits |= TIOCM_DSR;
2539		/*
2540		 * XXX - MSR_RI is naturally volatile, and we make MSR_TERI
2541		 * more volatile by reading the modem status a lot.  Perhaps
2542		 * we should latch both bits until the status is read here.
2543		 */
2544		if (msr & (MSR_RI | MSR_TERI))
2545			bits |= TIOCM_RI;
2546		return (bits);
2547	}
2548	mcr = 0;
2549	if (bits & TIOCM_DTR)
2550		mcr |= MCR_DTR;
2551	if (bits & TIOCM_RTS)
2552		mcr |= MCR_RTS;
2553	if (com->gone)
2554		return(0);
2555	disable_intr();
2556	switch (how) {
2557	case DMSET:
2558		outb(com->modem_ctl_port,
2559		     com->mcr_image = mcr | (com->mcr_image & MCR_IENABLE));
2560		break;
2561	case DMBIS:
2562		outb(com->modem_ctl_port, com->mcr_image |= mcr);
2563		break;
2564	case DMBIC:
2565		outb(com->modem_ctl_port, com->mcr_image &= ~mcr);
2566		break;
2567	}
2568	enable_intr();
2569	return (0);
2570}
2571
2572static void
2573siosettimeout()
2574{
2575	struct com_s	*com;
2576	bool_t		someopen;
2577	int		unit;
2578
2579	/*
2580	 * Set our timeout period to 1 second if no polled devices are open.
2581	 * Otherwise set it to max(1/200, 1/hz).
2582	 * Enable timeouts iff some device is open.
2583	 */
2584	untimeout(comwakeup, (void *)NULL, sio_timeout_handle);
2585	sio_timeout = hz;
2586	someopen = FALSE;
2587	for (unit = 0; unit < sio_numunits; ++unit) {
2588		com = com_addr(unit);
2589		if (com != NULL && com->tp != NULL
2590		    && com->tp->t_state & TS_ISOPEN && !com->gone) {
2591			someopen = TRUE;
2592			if (com->poll || com->poll_output) {
2593				sio_timeout = hz > 200 ? hz / 200 : 1;
2594				break;
2595			}
2596		}
2597	}
2598	if (someopen) {
2599		sio_timeouts_until_log = hz / sio_timeout;
2600		sio_timeout_handle = timeout(comwakeup, (void *)NULL,
2601					     sio_timeout);
2602	} else {
2603		/* Flush error messages, if any. */
2604		sio_timeouts_until_log = 1;
2605		comwakeup((void *)NULL);
2606		untimeout(comwakeup, (void *)NULL, sio_timeout_handle);
2607	}
2608}
2609
2610static void
2611comwakeup(chan)
2612	void	*chan;
2613{
2614	struct com_s	*com;
2615	int		unit;
2616
2617	sio_timeout_handle = timeout(comwakeup, (void *)NULL, sio_timeout);
2618
2619	/*
2620	 * Recover from lost output interrupts.
2621	 * Poll any lines that don't use interrupts.
2622	 */
2623	for (unit = 0; unit < sio_numunits; ++unit) {
2624		com = com_addr(unit);
2625		if (com != NULL && !com->gone
2626		    && (com->state >= (CS_BUSY | CS_TTGO) || com->poll)) {
2627			disable_intr();
2628			siointr1(com);
2629			enable_intr();
2630		}
2631	}
2632
2633	/*
2634	 * Check for and log errors, but not too often.
2635	 */
2636	if (--sio_timeouts_until_log > 0)
2637		return;
2638	sio_timeouts_until_log = hz / sio_timeout;
2639	for (unit = 0; unit < sio_numunits; ++unit) {
2640		int	errnum;
2641
2642		com = com_addr(unit);
2643		if (com == NULL)
2644			continue;
2645		if (com->gone)
2646			continue;
2647		for (errnum = 0; errnum < CE_NTYPES; ++errnum) {
2648			u_int	delta;
2649			u_long	total;
2650
2651			disable_intr();
2652			delta = com->delta_error_counts[errnum];
2653			com->delta_error_counts[errnum] = 0;
2654			enable_intr();
2655			if (delta == 0)
2656				continue;
2657			total = com->error_counts[errnum] += delta;
2658			log(LOG_ERR, "sio%d: %u more %s%s (total %lu)\n",
2659			    unit, delta, error_desc[errnum],
2660			    delta == 1 ? "" : "s", total);
2661		}
2662	}
2663}
2664
2665static void
2666disc_optim(tp, t, com)
2667	struct tty	*tp;
2668	struct termios	*t;
2669	struct com_s	*com;
2670{
2671	if (!(t->c_iflag & (ICRNL | IGNCR | IMAXBEL | INLCR | ISTRIP | IXON))
2672	    && (!(t->c_iflag & BRKINT) || (t->c_iflag & IGNBRK))
2673	    && (!(t->c_iflag & PARMRK)
2674		|| (t->c_iflag & (IGNPAR | IGNBRK)) == (IGNPAR | IGNBRK))
2675	    && !(t->c_lflag & (ECHO | ICANON | IEXTEN | ISIG | PENDIN))
2676	    && linesw[tp->t_line].l_rint == ttyinput)
2677		tp->t_state |= TS_CAN_BYPASS_L_RINT;
2678	else
2679		tp->t_state &= ~TS_CAN_BYPASS_L_RINT;
2680	com->hotchar = linesw[tp->t_line].l_hotchar;
2681}
2682
2683/*
2684 * Following are all routines needed for SIO to act as console
2685 */
2686#include <sys/cons.h>
2687
2688struct siocnstate {
2689	u_char	dlbl;
2690	u_char	dlbh;
2691	u_char	ier;
2692	u_char	cfcr;
2693	u_char	mcr;
2694};
2695
2696static speed_t siocngetspeed __P((Port_t, struct speedtab *));
2697static void siocnclose	__P((struct siocnstate *sp, Port_t iobase));
2698static void siocnopen	__P((struct siocnstate *sp, Port_t iobase, int speed));
2699static void siocntxwait	__P((Port_t iobase));
2700
2701static cn_probe_t siocnprobe;
2702static cn_init_t siocninit;
2703static cn_checkc_t siocncheckc;
2704static cn_getc_t siocngetc;
2705static cn_putc_t siocnputc;
2706
2707#ifdef __i386__
2708CONS_DRIVER(sio, siocnprobe, siocninit, NULL, siocngetc, siocncheckc,
2709	    siocnputc, NULL);
2710#endif
2711
2712/* To get the GDB related variables */
2713#if DDB > 0
2714#include <ddb/ddb.h>
2715#endif
2716
2717static void
2718siocntxwait(iobase)
2719	Port_t	iobase;
2720{
2721	int	timo;
2722
2723	/*
2724	 * Wait for any pending transmission to finish.  Required to avoid
2725	 * the UART lockup bug when the speed is changed, and for normal
2726	 * transmits.
2727	 */
2728	timo = 100000;
2729	while ((inb(iobase + com_lsr) & (LSR_TSRE | LSR_TXRDY))
2730	       != (LSR_TSRE | LSR_TXRDY) && --timo != 0)
2731		;
2732}
2733
2734/*
2735 * Read the serial port specified and try to figure out what speed
2736 * it's currently running at.  We're assuming the serial port has
2737 * been initialized and is basicly idle.  This routine is only intended
2738 * to be run at system startup.
2739 *
2740 * If the value read from the serial port doesn't make sense, return 0.
2741 */
2742
2743static speed_t
2744siocngetspeed(iobase, table)
2745	Port_t iobase;
2746	struct speedtab *table;
2747{
2748	int	code;
2749	u_char	dlbh;
2750	u_char	dlbl;
2751	u_char  cfcr;
2752
2753	cfcr = inb(iobase + com_cfcr);
2754	outb(iobase + com_cfcr, CFCR_DLAB | cfcr);
2755
2756	dlbl = inb(iobase + com_dlbl);
2757	dlbh = inb(iobase + com_dlbh);
2758
2759	outb(iobase + com_cfcr, cfcr);
2760
2761	code = dlbh << 8 | dlbl;
2762
2763	for (; table->sp_speed != -1; table++)
2764		if (table->sp_code == code)
2765			return (table->sp_speed);
2766
2767	return 0;	/* didn't match anything sane */
2768}
2769
2770static void
2771siocnopen(sp, iobase, speed)
2772	struct siocnstate	*sp;
2773	Port_t			iobase;
2774	int			speed;
2775{
2776	int	divisor;
2777	u_char	dlbh;
2778	u_char	dlbl;
2779
2780	/*
2781	 * Save all the device control registers except the fifo register
2782	 * and set our default ones (cs8 -parenb speed=comdefaultrate).
2783	 * We can't save the fifo register since it is read-only.
2784	 */
2785	sp->ier = inb(iobase + com_ier);
2786	outb(iobase + com_ier, 0);	/* spltty() doesn't stop siointr() */
2787	siocntxwait(iobase);
2788	sp->cfcr = inb(iobase + com_cfcr);
2789	outb(iobase + com_cfcr, CFCR_DLAB | CFCR_8BITS);
2790	sp->dlbl = inb(iobase + com_dlbl);
2791	sp->dlbh = inb(iobase + com_dlbh);
2792	/*
2793	 * Only set the divisor registers if they would change, since on
2794	 * some 16550 incompatibles (Startech), setting them clears the
2795	 * data input register.  This also reduces the effects of the
2796	 * UMC8669F bug.
2797	 */
2798	divisor = ttspeedtab(speed, comspeedtab);
2799	dlbl = divisor & 0xFF;
2800	if (sp->dlbl != dlbl)
2801		outb(iobase + com_dlbl, dlbl);
2802	dlbh = (u_int) divisor >> 8;
2803	if (sp->dlbh != dlbh)
2804		outb(iobase + com_dlbh, dlbh);
2805	outb(iobase + com_cfcr, CFCR_8BITS);
2806	sp->mcr = inb(iobase + com_mcr);
2807	/*
2808	 * We don't want interrupts, but must be careful not to "disable"
2809	 * them by clearing the MCR_IENABLE bit, since that might cause
2810	 * an interrupt by floating the IRQ line.
2811	 */
2812	outb(iobase + com_mcr, (sp->mcr & MCR_IENABLE) | MCR_DTR | MCR_RTS);
2813}
2814
2815static void
2816siocnclose(sp, iobase)
2817	struct siocnstate	*sp;
2818	Port_t			iobase;
2819{
2820	/*
2821	 * Restore the device control registers.
2822	 */
2823	siocntxwait(iobase);
2824	outb(iobase + com_cfcr, CFCR_DLAB | CFCR_8BITS);
2825	if (sp->dlbl != inb(iobase + com_dlbl))
2826		outb(iobase + com_dlbl, sp->dlbl);
2827	if (sp->dlbh != inb(iobase + com_dlbh))
2828		outb(iobase + com_dlbh, sp->dlbh);
2829	outb(iobase + com_cfcr, sp->cfcr);
2830	/*
2831	 * XXX damp oscillations of MCR_DTR and MCR_RTS by not restoring them.
2832	 */
2833	outb(iobase + com_mcr, sp->mcr | MCR_DTR | MCR_RTS);
2834	outb(iobase + com_ier, sp->ier);
2835}
2836
2837static void
2838siocnprobe(cp)
2839	struct consdev	*cp;
2840{
2841	speed_t			boot_speed;
2842	u_char			cfcr;
2843	int			s, unit;
2844	struct siocnstate	sp;
2845
2846	/*
2847	 * Find our first enabled console, if any.  If it is a high-level
2848	 * console device, then initialize it and return successfully.
2849	 * If it is a low-level console device, then initialize it and
2850	 * return unsuccessfully.  It must be initialized in both cases
2851	 * for early use by console drivers and debuggers.  Initializing
2852	 * the hardware is not necessary in all cases, since the i/o
2853	 * routines initialize it on the fly, but it is necessary if
2854	 * input might arrive while the hardware is switched back to an
2855	 * uninitialized state.  We can't handle multiple console devices
2856	 * yet because our low-level routines don't take a device arg.
2857	 * We trust the user to set the console flags properly so that we
2858	 * don't need to probe.
2859	 */
2860	cp->cn_pri = CN_DEAD;
2861
2862	for (unit = 0; unit < 16; unit++) { /* XXX need to know how many */
2863		int flags;
2864		int disabled;
2865		if (resource_int_value("sio", unit, "disabled", &disabled) == 0) {
2866			if (disabled)
2867				continue;
2868		}
2869		if (resource_int_value("sio", unit, "flags", &flags))
2870			continue;
2871		if (COM_CONSOLE(flags) || COM_DEBUGGER(flags)) {
2872			int port;
2873			Port_t iobase;
2874
2875			if (resource_int_value("sio", unit, "port", &port))
2876				continue;
2877			iobase = port;
2878			s = spltty();
2879			if (boothowto & RB_SERIAL) {
2880				boot_speed = siocngetspeed(iobase, comspeedtab);
2881				if (boot_speed)
2882					comdefaultrate = boot_speed;
2883			}
2884
2885			/*
2886			 * Initialize the divisor latch.  We can't rely on
2887			 * siocnopen() to do this the first time, since it
2888			 * avoids writing to the latch if the latch appears
2889			 * to have the correct value.  Also, if we didn't
2890			 * just read the speed from the hardware, then we
2891			 * need to set the speed in hardware so that
2892			 * switching it later is null.
2893			 */
2894			cfcr = inb(iobase + com_cfcr);
2895			outb(iobase + com_cfcr, CFCR_DLAB | cfcr);
2896			outb(iobase + com_dlbl,
2897			     COMBRD(comdefaultrate) & 0xff);
2898			outb(iobase + com_dlbh,
2899			     (u_int) COMBRD(comdefaultrate) >> 8);
2900			outb(iobase + com_cfcr, cfcr);
2901
2902			siocnopen(&sp, iobase, comdefaultrate);
2903
2904			splx(s);
2905			if (COM_CONSOLE(flags) && !COM_LLCONSOLE(flags)) {
2906				cp->cn_dev = makedev(CDEV_MAJOR, unit);
2907				cp->cn_pri = COM_FORCECONSOLE(flags)
2908					     || boothowto & RB_SERIAL
2909					     ? CN_REMOTE : CN_NORMAL;
2910				siocniobase = iobase;
2911				siocnunit = unit;
2912			}
2913			if (COM_DEBUGGER(flags)) {
2914				printf("sio%d: gdb debugging port\n", unit);
2915				siogdbiobase = iobase;
2916				siogdbunit = unit;
2917#if DDB > 0
2918				gdbdev = makedev(CDEV_MAJOR, unit);
2919				gdb_getc = siocngetc;
2920				gdb_putc = siocnputc;
2921#endif
2922			}
2923		}
2924	}
2925#ifdef	__i386__
2926#if DDB > 0
2927	/*
2928	 * XXX Ugly Compatability.
2929	 * If no gdb port has been specified, set it to be the console
2930	 * as some configuration files don't specify the gdb port.
2931	 */
2932	if (gdbdev == NODEV && (boothowto & RB_GDB)) {
2933		printf("Warning: no GDB port specified. Defaulting to sio%d.\n",
2934			siocnunit);
2935		printf("Set flag 0x80 on desired GDB port in your\n");
2936		printf("configuration file (currently sio only).\n");
2937		siogdbiobase = siocniobase;
2938		siogdbunit = siocnunit;
2939		gdbdev = makedev(CDEV_MAJOR, siocnunit);
2940		gdb_getc = siocngetc;
2941		gdb_putc = siocnputc;
2942	}
2943#endif
2944#endif
2945}
2946
2947#ifdef __alpha__
2948
2949CONS_DRIVER(sio, NULL, NULL, NULL, siocngetc, siocncheckc, siocnputc, NULL);
2950
2951int
2952siocnattach(port, speed)
2953	int port;
2954	int speed;
2955{
2956	int			s;
2957	u_char			cfcr;
2958	struct siocnstate	sp;
2959
2960	siocniobase = port;
2961	comdefaultrate = speed;
2962	sio_consdev.cn_pri = CN_NORMAL;
2963	sio_consdev.cn_dev = makedev(CDEV_MAJOR, 0);
2964
2965	s = spltty();
2966
2967	/*
2968	 * Initialize the divisor latch.  We can't rely on
2969	 * siocnopen() to do this the first time, since it
2970	 * avoids writing to the latch if the latch appears
2971	 * to have the correct value.  Also, if we didn't
2972	 * just read the speed from the hardware, then we
2973	 * need to set the speed in hardware so that
2974	 * switching it later is null.
2975	 */
2976	cfcr = inb(siocniobase + com_cfcr);
2977	outb(siocniobase + com_cfcr, CFCR_DLAB | cfcr);
2978	outb(siocniobase + com_dlbl,
2979	     COMBRD(comdefaultrate) & 0xff);
2980	outb(siocniobase + com_dlbh,
2981	     (u_int) COMBRD(comdefaultrate) >> 8);
2982	outb(siocniobase + com_cfcr, cfcr);
2983
2984	siocnopen(&sp, siocniobase, comdefaultrate);
2985	splx(s);
2986
2987	cn_tab = &sio_consdev;
2988	return 0;
2989}
2990
2991int
2992siogdbattach(port, speed)
2993	int port;
2994	int speed;
2995{
2996	int			s;
2997	u_char			cfcr;
2998	struct siocnstate	sp;
2999
3000	siogdbiobase = port;
3001	gdbdefaultrate = speed;
3002
3003	s = spltty();
3004
3005	/*
3006	 * Initialize the divisor latch.  We can't rely on
3007	 * siocnopen() to do this the first time, since it
3008	 * avoids writing to the latch if the latch appears
3009	 * to have the correct value.  Also, if we didn't
3010	 * just read the speed from the hardware, then we
3011	 * need to set the speed in hardware so that
3012	 * switching it later is null.
3013	 */
3014	cfcr = inb(siogdbiobase + com_cfcr);
3015	outb(siogdbiobase + com_cfcr, CFCR_DLAB | cfcr);
3016	outb(siogdbiobase + com_dlbl,
3017	     COMBRD(gdbdefaultrate) & 0xff);
3018	outb(siogdbiobase + com_dlbh,
3019	     (u_int) COMBRD(gdbdefaultrate) >> 8);
3020	outb(siogdbiobase + com_cfcr, cfcr);
3021
3022	siocnopen(&sp, siogdbiobase, gdbdefaultrate);
3023	splx(s);
3024
3025	return 0;
3026}
3027
3028#endif
3029
3030static void
3031siocninit(cp)
3032	struct consdev	*cp;
3033{
3034	comconsole = DEV_TO_UNIT(cp->cn_dev);
3035}
3036
3037static int
3038siocncheckc(dev)
3039	dev_t	dev;
3040{
3041	int	c;
3042	Port_t	iobase;
3043	int	s;
3044	struct siocnstate	sp;
3045
3046	if (minor(dev) == siogdbunit)
3047		iobase = siogdbiobase;
3048	else
3049		iobase = siocniobase;
3050	s = spltty();
3051	siocnopen(&sp, iobase, comdefaultrate);
3052	if (inb(iobase + com_lsr) & LSR_RXRDY)
3053		c = inb(iobase + com_data);
3054	else
3055		c = -1;
3056	siocnclose(&sp, iobase);
3057	splx(s);
3058	return (c);
3059}
3060
3061
3062int
3063siocngetc(dev)
3064	dev_t	dev;
3065{
3066	int	c;
3067	Port_t	iobase;
3068	int	s;
3069	struct siocnstate	sp;
3070
3071	if (minor(dev) == siogdbunit)
3072		iobase = siogdbiobase;
3073	else
3074		iobase = siocniobase;
3075	s = spltty();
3076	siocnopen(&sp, iobase, comdefaultrate);
3077	while (!(inb(iobase + com_lsr) & LSR_RXRDY))
3078		;
3079	c = inb(iobase + com_data);
3080	siocnclose(&sp, iobase);
3081	splx(s);
3082	return (c);
3083}
3084
3085void
3086siocnputc(dev, c)
3087	dev_t	dev;
3088	int	c;
3089{
3090	int	s;
3091	struct siocnstate	sp;
3092	Port_t	iobase;
3093
3094	if (minor(dev) == siogdbunit)
3095		iobase = siogdbiobase;
3096	else
3097		iobase = siocniobase;
3098	s = spltty();
3099	siocnopen(&sp, iobase, comdefaultrate);
3100	siocntxwait(iobase);
3101	outb(iobase + com_data, c);
3102	siocnclose(&sp, iobase);
3103	splx(s);
3104}
3105
3106#ifdef __alpha__
3107int
3108siogdbgetc()
3109{
3110	int	c;
3111	Port_t	iobase;
3112	int	s;
3113	struct siocnstate	sp;
3114
3115	iobase = siogdbiobase;
3116	s = spltty();
3117	siocnopen(&sp, iobase, gdbdefaultrate);
3118	while (!(inb(iobase + com_lsr) & LSR_RXRDY))
3119		;
3120	c = inb(iobase + com_data);
3121	siocnclose(&sp, iobase);
3122	splx(s);
3123	return (c);
3124}
3125
3126void
3127siogdbputc(c)
3128	int	c;
3129{
3130	int	s;
3131	struct siocnstate	sp;
3132
3133	s = spltty();
3134	siocnopen(&sp, siogdbiobase, gdbdefaultrate);
3135	siocntxwait(siogdbiobase);
3136	outb(siogdbiobase + com_data, c);
3137	siocnclose(&sp, siogdbiobase);
3138	splx(s);
3139}
3140#endif
3141
3142DRIVER_MODULE(sio, isa, sio_isa_driver, sio_devclass, 0, 0);
3143#if NCARD > 0
3144DRIVER_MODULE(sio, pccard, sio_pccard_driver, sio_devclass, 0, 0);
3145#endif
3146