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