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