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