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